Compare commits

...
35 Commits
Author SHA1 Message Date
seven332 1edf98c9e1 1.0.10 2016-05-11 18:22:28 +08:00
seven332 32ed409a28 Update strings.xml 2016-05-10 17:09:46 +08:00
seven332 cac950fa40 Get ThumbDataContainer file in non-UI thread 2016-05-10 14:05:37 +08:00
seven332 3a03e9aad1 Change fab color
Primary fab is colorPrimary, secondary fab is colorAccent
2016-05-10 13:40:39 +08:00
seven332 971aa86c4e Set SpiderQueen.mMode to local 2016-05-10 02:10:23 +08:00
seven332 bbb5f89a66 Avoid mSpiderInfo null
Use AtomicReference for mSpiderInfo
2016-05-10 02:09:06 +08:00
seven332 f777b694d5 Add memory usage to crash file 2016-05-10 00:56:58 +08:00
seven332 d59fa1756e Use OSUtils 2016-05-10 00:46:00 +08:00
seven332 5ac9ad4d71 Upgrade yorozuya to 0.1.1 2016-05-10 00:40:51 +08:00
seven332 adb3860107 Upgrade libraries 2016-05-09 22:41:54 +08:00
seven332 81876955c6 Upgrade Yorozuya-Thread library to 0.1.1 2016-05-09 21:48:21 +08:00
seven332 b8189d76d6 Decode image partly 2016-05-09 18:47:03 +08:00
seven332 0a472d28b5 Add multi-thread support for image decoding 2016-05-09 00:40:25 +08:00
seven332 9a0ba6f676 Ensure notifyGetImageXXX called after pipe released 2016-05-08 15:52:47 +08:00
seven332 e22010f2b0 Update state at once when force request 2016-05-07 18:49:36 +08:00
seven332 5a2fe3fe19 Update beerbelly to 0.1.3 2016-05-07 18:48:44 +08:00
seven332 c9bbbca311 Set decoder thread priority to default
The priority of a decode thread was THREAD_PRIORITY_BACKGROUND. It may cause a long time waiting before image decoded.
2016-05-07 16:46:01 +08:00
seven332 83d66f9c56 Fix ptoken failed error
When get last page of gallery, the page preview count is not preview count pre page. So old version spider info file may store wrong preview count pre page. Spider info file version is added in the first line.
2016-05-07 15:51:47 +08:00
seven332 1feca40a5c Use System.nanoTime() to calculate frame delay compensation
Use System.nanoTime() instead of SystemClock.elapsedRealtime()
2016-05-07 14:17:10 +08:00
seven332 1bc07a89b8 Prepare for library upgrade 2016-05-07 14:09:03 +08:00
seven332 6c0ad0e329 Upgrade image library to 0.1.6 2016-05-07 14:03:20 +08:00
seven332 21151a5031 Fix FabLayout onClick
mExpanded blocked onClickPrimaryFab and onClickSecondaryFab before. But it should only block onClickSecondaryFab
2016-05-07 14:02:37 +08:00
seven332 74e10178be Fix default rating text 2016-05-05 22:56:43 +08:00
seven332 e289e83983 Update string.xml
Change unfavorited to not favorited
2016-05-05 01:06:33 +08:00
seven332 d07dc49dc7 Add cellular network warning 2016-05-05 01:05:00 +08:00
seven332 981598dc70 Fix some cookies missing in request 2016-05-04 23:50:29 +08:00
seven332 f82c576970 Update pd_big_weird_face 2016-05-04 21:18:24 +08:00
seven332 a0f1e97332 Upgrade image library to 0.1.5 2016-05-04 15:51:00 +08:00
seven332 2dca63b342 Avoid call fab on click listener when not expanded 2016-05-03 21:35:23 +08:00
seven332 9590c758fd 1.0.9 2016-05-03 02:50:51 +08:00
seven332 74bbbabdd4 Add debug print Image count 2016-05-03 02:46:24 +08:00
seven332 363ad7686e Use ImageMovableTextTexture instead of MovableTextTexture
NativeTexture can avoid bad buffer
2016-05-03 02:34:23 +08:00
seven332 ad9f544fe1 Add GLView.onPause and GLView.onResume 2016-05-03 00:52:03 +08:00
seven332 4c3c84f1a6 Clean up 2016-05-02 23:17:29 +08:00
seven332 512fef80db Bump TuXiang library version to 0.1.1 2016-05-02 22:50:36 +08:00
47 changed files with 1047 additions and 417 deletions

No files matched your search

+11 -9
View File
@@ -8,8 +8,8 @@ android {
applicationId "com.hippo.ehviewer"
minSdkVersion 14
targetSdkVersion 23
versionCode 61
versionName "1.0.8"
versionCode 63
versionName "1.0.10"
vectorDrawables.useSupportLibrary = true
resConfigs "zh", "zh-rCN", "zh-rHK", "zh-rTW"
@@ -59,20 +59,22 @@ dependencies {
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'com.github.amlcurran.showcaseview:library:5.4.3'
compile 'com.github.seven332:beerbelly:0.1.2'
compile 'com.github.seven332:conaco:0.1.3-eh'
compile 'com.github.seven332:animator:0.1.0'
compile 'com.github.seven332:beerbelly:0.1.4'
compile 'com.github.seven332:conaco:0.1.4-eh'
compile 'com.github.seven332:drawerlayout:0.1.0'
compile 'com.github.seven332:easyrecyclerview:0.1.0'
compile 'com.github.seven332:drawerLayout:0.1.0'
compile 'com.github.seven332:image:0.1.3'
compile 'com.github.seven332:hotspot:0.1.0'
compile 'com.github.seven332:image:0.1.7-jpeg-png-gif'
compile 'com.github.seven332:okhttp:3.2.0-eh'
compile 'com.github.seven332:refreshlayout:0.1.0'
compile 'com.github.seven332:ripple:0.1.1'
compile 'com.github.seven332:streampipe:0.1.0'
compile 'com.github.seven332:tuxiang:0.1.0'
compile 'com.github.seven332:tuxiang:0.1.2'
compile 'com.github.seven332:unifile:0.1.3'
compile 'com.github.seven332:yorozuya:0.1.1'
compile 'com.github.seven332:yorozuya-thread:0.1.1'
compile 'com.github.seven332:yorozuya-collect:0.1.2'
compile 'com.github.seven332:yorozuya-thread:0.1.0'
compile 'com.github.seven332:yorozuya:0.1.0'
compile 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.8.7'
compile 'org.ccil.cowan.tagsoup:tagsoup:1.2.1'
compile 'org.greenrobot:greendao:2.2.0'
@@ -26,7 +26,9 @@ import android.support.annotation.NonNull;
import com.hippo.scene.StageActivity;
import com.hippo.util.PackageUtils;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.OSUtils;
import java.io.File;
import java.io.FileInputStream;
@@ -107,6 +109,8 @@ public class Crash {
fw.write("INCREMENTAL=");fw.write(Build.VERSION.INCREMENTAL);fw.write("\r\n");
fw.write("RELEASE=");fw.write(Build.VERSION.RELEASE);fw.write("\r\n");
fw.write("SDK=");fw.write(Integer.toString(Build.VERSION.SDK_INT));fw.write("\r\n");
fw.write("MEMORY=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getAppAllocatedMemory(), false));
fw.write("/");fw.write(FileUtils.humanReadableByteCount(OSUtils.getTotalMemory(), false));fw.write("\r\n");
fw.write("\r\n");
}
@@ -17,7 +17,6 @@
package com.hippo.ehviewer;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.pm.PackageInfo;
@@ -38,6 +37,7 @@ import com.hippo.ehviewer.client.data.GalleryDetail;
import com.hippo.ehviewer.download.DownloadManager;
import com.hippo.ehviewer.spider.SpiderDen;
import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.image.Image;
import com.hippo.image.ImageBitmap;
import com.hippo.network.StatusCodeException;
import com.hippo.okhttp.CookieDB;
@@ -48,6 +48,7 @@ import com.hippo.util.BitmapUtils;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IntIdGenerator;
import com.hippo.yorozuya.OSUtils;
import com.hippo.yorozuya.SimpleHandler;
import java.io.File;
@@ -68,7 +69,9 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
public static final boolean BETA = false;
private static final boolean DEBUG_CONACO = false;
private static final boolean DEBUG_NATIVE_MEMORY = false;
private static final boolean DEBUG_PRINT_NATIVE_MEMORY = false;
private static final boolean DEBUG_PRINT_IMAGE_COUNT = false;
private static final long DEBUG_PRINT_INTERVAL = 3000L;
private Thread.UncaughtExceptionHandler mDefaultHandler;
@@ -135,8 +138,8 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
// Ignore
}
if (DEBUG_NATIVE_MEMORY) {
debugNativeMemory();
if (DEBUG_PRINT_NATIVE_MEMORY || DEBUG_PRINT_IMAGE_COUNT) {
debugPrint();
}
}
@@ -199,13 +202,18 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
}
}
private void debugNativeMemory() {
private void debugPrint() {
new Runnable() {
@Override
public void run() {
Log.i(TAG, "Native memory: " + FileUtils.humanReadableByteCount(
Debug.getNativeHeapAllocatedSize(), false));
SimpleHandler.getInstance().postDelayed(this, 3000);
if (DEBUG_PRINT_NATIVE_MEMORY) {
Log.i(TAG, "Native memory: " + FileUtils.humanReadableByteCount(
Debug.getNativeHeapAllocatedSize(), false));
}
if (DEBUG_PRINT_IMAGE_COUNT) {
Log.i(TAG, "Image count: " + Image.getImageCount());
}
SimpleHandler.getInstance().postDelayed(this, DEBUG_PRINT_INTERVAL);
}
}.run();
}
@@ -272,11 +280,8 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
return application.mImageBitmapHelper;
}
private static int getMemoryCacheMaxSize(Context context) {
final ActivityManager activityManager = (ActivityManager) context.
getSystemService(Context.ACTIVITY_SERVICE);
return Math.min(20 * 1024 * 1024,
Math.round(0.2f * activityManager.getMemoryClass() * 1024 * 1024));
private static int getMemoryCacheMaxSize() {
return Math.min(20 * 1024 * 1024, (int) OSUtils.getAppMaxMemory());
}
@NonNull
@@ -285,7 +290,7 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
if (application.mConaco == null) {
Conaco.Builder<ImageBitmap> builder = new Conaco.Builder<>();
builder.hasMemoryCache = true;
builder.memoryCacheMaxSize = getMemoryCacheMaxSize(context);
builder.memoryCacheMaxSize = getMemoryCacheMaxSize();
builder.hasDiskCache = true;
builder.diskCacheDir = new File(context.getCacheDir(), "thumb");
builder.diskCacheMaxSize = 80 * 1024 * 1024; // 80MB
@@ -20,7 +20,6 @@ import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.conaco.ValueHelper;
import com.hippo.image.Image;
import com.hippo.image.ImageBitmap;
import com.hippo.streampipe.InputStreamPipe;
@@ -35,12 +34,7 @@ public class ImageBitmapHelper implements ValueHelper<ImageBitmap> {
public ImageBitmap decode(@NonNull InputStreamPipe isPipe) {
try {
isPipe.obtain();
Image image = Image.decode(isPipe.open(), false);
if (image != null) {
return new ImageBitmap(image);
} else {
return null;
}
return ImageBitmap.decode(isPipe.open());
} catch (OutOfMemoryError e) {
return null;
} catch (IOException e) {
@@ -53,7 +47,7 @@ public class ImageBitmapHelper implements ValueHelper<ImageBitmap> {
@Override
public int sizeOf(@NonNull String key, @NonNull ImageBitmap value) {
return value.getWidth() * value.getHeight() * 4;
return value.getWidth() * value.getHeight() * 4 /* value.getByteCount() TODO Update Image */;
}
@Override
@@ -69,7 +63,8 @@ public class ImageBitmapHelper implements ValueHelper<ImageBitmap> {
@Override
public boolean useMemoryCache(@NonNull String key, ImageBitmap value) {
if (value != null) {
return value.getWidth() * value.getHeight() <= MAX_CACHE_SIZE;
return value.getWidth() * value.getHeight() <= MAX_CACHE_SIZE
/* value.getByteCount() <= MAX_CACHE_BYTE_COUNT TODO Update Image */;
} else {
return true;
}
@@ -412,6 +412,13 @@ public class Settings {
putString(KEY_HATH_PASSKEY, value);
}
private static final String KEY_CELLULAR_NETWORK_WARNING = "cellular_network_warning";
private static final boolean DEFAULT_CELLULAR_NETWORK_WARNING = false;
public static boolean getCellularNetworkWarning() {
return getBoolean(KEY_CELLULAR_NETWORK_WARNING, DEFAULT_CELLULAR_NETWORK_WARNING);
}
/********************
****** Read
********************/
@@ -23,23 +23,16 @@ import android.support.annotation.UiThread;
import com.hippo.beerbelly.LruCache;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.gl.glrenderer.ImageWrapper;
import com.hippo.gl.view.GLRoot;
import com.hippo.image.Image;
import com.hippo.image.ImageWrapper;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.ConcurrentPool;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.NumberUtils;
import com.hippo.yorozuya.OSUtils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class GalleryProvider {
@@ -259,43 +252,8 @@ public abstract class GalleryProvider {
private static final long MAX_CACHE_SIZE = 128 * 1024 * 1024;
private static final long MIN_CACHE_SIZE = 32 * 1024 * 1024;
private static final String PROCFS_MEMFILE = "/proc/meminfo";
private static final Pattern PROCFS_MEMFILE_FORMAT =
Pattern.compile("^([a-zA-Z]*):[ \t]*([0-9]*)[ \t]kB");
private static final String MEMTOTAL_STRING = "MemTotal";
private static long sMemTotal = -2L;
private static long getTotalMemory() {
if (sMemTotal != -2L) {
return sMemTotal;
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(PROCFS_MEMFILE), 64);
String line;
while ((line = reader.readLine()) != null) {
Matcher matcher = PROCFS_MEMFILE_FORMAT.matcher(line);
if (matcher.find() && MEMTOTAL_STRING.equals(matcher.group(1))) {
long mem = NumberUtils.parseLongSafely(matcher.group(2), -1L);
if (mem != -1L) {
mem *= 1024;
}
sMemTotal = mem;
return mem;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(reader);
}
sMemTotal = -1L;
return -1L;
}
public ImageCache() {
super((int) MathUtils.clamp(getTotalMemory() / 16, MIN_CACHE_SIZE, MAX_CACHE_SIZE));
super((int) MathUtils.clamp(OSUtils.getTotalMemory() / 16, MIN_CACHE_SIZE, MAX_CACHE_SIZE));
}
public void add(Integer key, ImageWrapper value) {
@@ -16,7 +16,7 @@
package com.hippo.ehviewer.gallery;
import com.hippo.image.ImageWrapper;
import com.hippo.gl.glrenderer.ImageWrapper;
public interface GalleryProviderListener {
@@ -19,8 +19,8 @@ package com.hippo.ehviewer.gallery.gl;
import android.content.Context;
import com.hippo.gl.glrenderer.BasicTexture;
import com.hippo.gl.glrenderer.ImageMovableTextTexture;
import com.hippo.gl.glrenderer.ImageTexture;
import com.hippo.gl.glrenderer.MovableTextTexture;
import com.hippo.gl.glrenderer.Texture;
import com.hippo.gl.view.Gravity;
import com.hippo.gl.widget.GLFrameLayout;
@@ -49,7 +49,7 @@ public class GalleryPageView extends GLFrameLayout {
private int mIndex = INVALID_INDEX;
public GalleryPageView(Context context, MovableTextTexture pageTextTexture,
public GalleryPageView(Context context, ImageMovableTextTexture pageTextTexture,
int progressColor, int progressSize) {
// Add image
mImage = new ImageView();
@@ -28,7 +28,7 @@ import com.hippo.ehviewer.R;
import com.hippo.gl.annotation.RenderThread;
import com.hippo.gl.glrenderer.BasicTexture;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.gl.glrenderer.MovableTextTexture;
import com.hippo.gl.glrenderer.ImageMovableTextTexture;
import com.hippo.gl.glrenderer.StringTexture;
import com.hippo.gl.glrenderer.Texture;
import com.hippo.gl.util.GalleryUtils;
@@ -90,7 +90,7 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
private static final int METHOD_ON_ATTACH_TO_ROOT = 20;
private final Context mContext;
private MovableTextTexture mPageTextTexture;
private ImageMovableTextTexture mPageTextTexture;
private final GestureRecognizer mGestureRecognizer;
private Adapter mAdapter;
@@ -116,7 +116,6 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
private boolean mScale = false;
private boolean mScroll = false;
private boolean mFirstScroll = false;
private boolean mTouched = false;
private final Rect mLeftArea = new Rect();
private final Rect mRightArea = new Rect();
@@ -142,7 +141,6 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
private final List<Object[]> mArgsListTemp = new ArrayList<>(5);
private final AtomicInteger mCurrentIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
private boolean mPause;
@SuppressWarnings("deprecation")
public GalleryView(@NonNull Context context, @NonNull Adapter adapter,
@@ -230,7 +228,7 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
@SuppressWarnings("deprecation")
private void onAttachToRootInternal() {
if (null == mPageTextTexture) {
mPageTextTexture = MovableTextTexture.create(Typeface.DEFAULT,
mPageTextTexture = ImageMovableTextTexture.create(Typeface.DEFAULT,
mContext.getResources().getDimensionPixelSize(R.dimen.gallery_page_text),
mContext.getResources().getColor(R.color.secondary_text_dark),
new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'});
@@ -547,7 +545,6 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
}
private void onDownInternal(float x, float y) {
mTouched = true;
mScale = false;
mScroll = false;
mFirstScroll = true;
@@ -557,7 +554,6 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
}
private void onUpInternal() {
mTouched = false;
if (mLayoutManager != null) {
mLayoutManager.onUp();
}
@@ -803,7 +799,7 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
@RenderThread
public GalleryPageView findPageByIndex(int id) {
if (!mPause && mLayoutManager != null) {
if (mLayoutManager != null) {
return mLayoutManager.findPageByIndex(id);
} else {
return null;
@@ -206,6 +206,7 @@ public class ImageView extends GLView implements ImageTexture.Callback {
// Remove callback
if (mImageTexture != null) {
mImageTexture.setCallback(null);
mImageTexture.stop();
}
int oldTextureWidth = mTextureWidth;
@@ -229,6 +230,7 @@ public class ImageView extends GLView implements ImageTexture.Callback {
getValidRect(mValidRect);
if (!mValidRect.isEmpty()) {
startAnimation(mAlphaAnimation, true);
mImageTexture.start();
}
} else {
mTextureWidth = 1;
@@ -24,6 +24,7 @@ import android.util.SparseArray;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.NumberUtils;
import java.io.IOException;
import java.io.InputStream;
@@ -34,6 +35,9 @@ public class SpiderInfo {
private static final String TAG = SpiderInfo.class.getSimpleName();
private static final String VERSION_STR = "VERSION";
private static final int VERSION = 2;
static final String TOKEN_FAILED = "failed";
int startPage = 0;
@@ -44,7 +48,6 @@ public class SpiderInfo {
int previewPerPage = -1;
SparseArray<String> pTokenMap = null;
public static SpiderInfo read(@Nullable UniFile file) {
if (file == null) {
return null;
@@ -80,6 +83,17 @@ public class SpiderInfo {
return startPage >= 0 ? startPage : 0;
}
private static int getVersion(String str) {
if (null == str) {
return -1;
}
if (str.startsWith(VERSION_STR)) {
return NumberUtils.parseIntSafely(str.substring(VERSION_STR.length()), -1);
} else {
return 1;
}
}
@SuppressWarnings("InfiniteLoopStatement")
public static SpiderInfo read(@Nullable InputStream is) {
if (null == is) {
@@ -89,8 +103,20 @@ public class SpiderInfo {
SpiderInfo spiderInfo = null;
try {
spiderInfo = new SpiderInfo();
// Get version
String line = IOUtils.readAsciiLine(is);
int version = getVersion(line);
if (version == VERSION) {
// Read next line
line = IOUtils.readAsciiLine(is);
} else if (version == 1) {
// pass
} else {
// Invalid version
return null;
}
// Start page
spiderInfo.startPage = getStartPage(IOUtils.readAsciiLine(is));
spiderInfo.startPage = getStartPage(line);
// Gid
spiderInfo.gid = Long.parseLong(IOUtils.readAsciiLine(is));
// Token
@@ -100,7 +126,12 @@ public class SpiderInfo {
// Preview pages
spiderInfo.previewPages = Integer.parseInt(IOUtils.readAsciiLine(is));
// Preview pre page
spiderInfo.previewPerPage = Integer.parseInt(IOUtils.readAsciiLine(is));
line = IOUtils.readAsciiLine(is);
if (version == 1) {
// Skip it
} else {
spiderInfo.previewPerPage = Integer.parseInt(line);
}
// Pages
spiderInfo.pages = Integer.parseInt(IOUtils.readAsciiLine(is));
// Check pages
@@ -110,7 +141,7 @@ public class SpiderInfo {
// PToken
spiderInfo.pTokenMap = new SparseArray<>(spiderInfo.pages);
while (true) { // EOFException will raise
String line = IOUtils.readAsciiLine(is);
line = IOUtils.readAsciiLine(is);
int pos = line.indexOf(" ");
if (pos > 0 || pos < line.length() - 1) {
int index = Integer.parseInt(line.substring(0, pos));
@@ -127,7 +158,6 @@ public class SpiderInfo {
}
if (spiderInfo == null || spiderInfo.gid == -1 || spiderInfo.token == null ||
spiderInfo.previewPages == -1 || spiderInfo.previewPerPage == -1 ||
spiderInfo.pages == -1 || spiderInfo.pTokenMap == null) {
return null;
} else {
@@ -139,6 +169,9 @@ public class SpiderInfo {
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(os);
writer.write(VERSION_STR);
writer.write(Integer.toString(VERSION));
writer.write("\n");
writer.write(String.format("%08x", startPage >= 0 ? startPage : 0)); // Avoid negative
writer.write("\n");
writer.write(Long.toString(gid));
@@ -77,6 +77,7 @@ import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.Call;
import okhttp3.OkHttpClient;
@@ -84,11 +85,12 @@ import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class SpiderQueen implements Runnable {
public final class SpiderQueen implements Runnable {
private static final String TAG = SpiderQueen.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
private static final boolean DEBUG_LOG = false;
private static final boolean DEBUG_PTOKEN = true;
@IntDef({MODE_READ, MODE_DOWNLOAD})
@Retention(RetentionPolicy.SOURCE)
@@ -106,6 +108,8 @@ public class SpiderQueen implements Runnable {
public static final int STATE_FINISHED = 2;
public static final int STATE_FAILED = 3;
public static final int DECODE_THREAD_NUM = 1;
public static final String SPIDER_INFO_FILENAME = ".ehviewer";
private static final String[] URL_509_SUFFIX_ARRAY = {
@@ -126,25 +130,22 @@ public class SpiderQueen implements Runnable {
private int mReadReference = 0;
private int mDownloadReference = 0;
@Mode
private int mMode;
// It mQueenThread is null, failed or stopped
@Nullable
private volatile Thread mQueenThread;
private final Object mQueenLock = new Object();
@Nullable
private Thread mDecoderThread;
private final Thread[] mDecodeThreadArray = new Thread[DECODE_THREAD_NUM];
private final int[] mDecodeIndexArray = new int[DECODE_THREAD_NUM];
private final Stack<Integer> mDecodeRequestStack = new Stack<>();
private final AtomicInteger mDecodingIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
private final Object mWorkerLock = new Object();
private ThreadPoolExecutor mWorkerPoolExecutor;
private int mWorkerCount;
private final Object mPTokenLock = new Object();
private volatile SpiderInfo mSpiderInfo;
private final AtomicReference<SpiderInfo> mSpiderInfo = new AtomicReference<>();
private final Queue<Integer> mRequestPTokenQueue = new ConcurrentLinkedQueue<>();
private final Object mPageStateLock = new Object();
@@ -181,6 +182,10 @@ public class SpiderQueen implements Runnable {
mWorkerMaxCount = MathUtils.clamp(Settings.getMultiThreadDownload(), 1, 10);
mPreloadNumber = MathUtils.clamp(Settings.getPreloadImage(), 0, 100);
for (int i = 0; i < DECODE_THREAD_NUM; i++) {
mDecodeIndexArray[i] = GalleryPageView.INVALID_INDEX;
}
mWorkerPoolExecutor = new ThreadPoolExecutor(mWorkerMaxCount, mWorkerMaxCount,
0, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(),
new PriorityThreadFactory(SpiderWorker.class.getSimpleName(), Process.THREAD_PRIORITY_BACKGROUND));
@@ -270,6 +275,9 @@ public class SpiderQueen implements Runnable {
}
private void notifyGetImageFailure(int index, String error) {
if (error == null) {
error = GetText.getString(R.string.error_unknown);
}
synchronized (mSpiderListeners) {
for (OnSpiderListener listener : mSpiderListeners) {
listener.onGetImageFailure(index, error);
@@ -312,18 +320,19 @@ public class SpiderQueen implements Runnable {
}
private void updateMode() {
int mode;
if (mDownloadReference > 0) {
mMode = MODE_DOWNLOAD;
mode = MODE_DOWNLOAD;
} else {
mMode = MODE_READ;
mode = MODE_READ;
}
mSpiderDen.setMode(mMode);
mSpiderDen.setMode(mode);
// Update download page
boolean intoDownloadMode = false;
synchronized (mRequestPageQueue) {
if (mMode == MODE_DOWNLOAD) {
if (mode == MODE_DOWNLOAD) {
if (mDownloadPage < 0) {
mDownloadPage = 0;
intoDownloadMode = true;
@@ -482,6 +491,8 @@ public class SpiderQueen implements Runnable {
// Fix state for force
if (force && (state == STATE_FINISHED || state == STATE_FAILED)) {
// Update state to none at once
updatePageState(index, STATE_NONE);
state = STATE_NONE;
}
@@ -532,7 +543,7 @@ public class SpiderQueen implements Runnable {
break;
case STATE_FINISHED:
synchronized (mDecodeRequestStack) {
if (!mDecodeRequestStack.contains(index) && index != mDecodingIndex.get()) {
if (!contain(mDecodeIndexArray, index) && !mDecodeRequestStack.contains(index)) {
mDecodeRequestStack.add(index);
mDecodeRequestStack.notify();
}
@@ -546,6 +557,15 @@ public class SpiderQueen implements Runnable {
return result;
}
public static boolean contain(int[] array, int value) {
for (int v: array) {
if (v == value) {
return true;
}
}
return false;
}
private void ensureWorkers() {
synchronized (mWorkerLock) {
if (null == mWorkerPoolExecutor) {
@@ -626,21 +646,23 @@ public class SpiderQueen implements Runnable {
}
public int getStartPage() {
mSpiderInfo = readSpiderInfoFromLocal();
if (mSpiderInfo != null) {
return mSpiderInfo.startPage;
SpiderInfo spiderInfo = readSpiderInfoFromLocal();
if (spiderInfo != null) {
mSpiderInfo.lazySet(spiderInfo);
return spiderInfo.startPage;
} else {
return 0;
}
}
public void putStartPage(int page) {
if (mSpiderInfo != null) {
mSpiderInfo.startPage = page;
final SpiderInfo spiderInfo = mSpiderInfo.get();
if (spiderInfo != null) {
spiderInfo.startPage = page;
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
writeSpiderInfoToLocal(mSpiderInfo);
writeSpiderInfoToLocal(spiderInfo);
return null;
}
}.execute();
@@ -648,15 +670,16 @@ public class SpiderQueen implements Runnable {
}
private synchronized SpiderInfo readSpiderInfoFromLocal() {
if (null != mSpiderInfo) {
return mSpiderInfo;
SpiderInfo spiderInfo = mSpiderInfo.get();
if (spiderInfo != null) {
return spiderInfo;
}
// Read from download dir
UniFile downloadDir = mSpiderDen.getDownloadDir();
if (downloadDir != null) {
UniFile file = downloadDir.findFile(SPIDER_INFO_FILENAME);
SpiderInfo spiderInfo = SpiderInfo.read(file);
spiderInfo = SpiderInfo.read(file);
if (spiderInfo != null && spiderInfo.gid == mGalleryInfo.gid &&
spiderInfo.token.equals(mGalleryInfo.token)) {
return spiderInfo;
@@ -668,7 +691,7 @@ public class SpiderQueen implements Runnable {
if (null != pipe) {
try {
pipe.obtain();
SpiderInfo spiderInfo = SpiderInfo.read(pipe.open());
spiderInfo = SpiderInfo.read(pipe.open());
if (spiderInfo != null && spiderInfo.gid == mGalleryInfo.gid &&
spiderInfo.token.equals(mGalleryInfo.token)) {
return spiderInfo;
@@ -684,9 +707,16 @@ public class SpiderQueen implements Runnable {
return null;
}
private void readPreviews(String body, SpiderInfo spiderInfo) throws ParseException {
private void readPreviews(String body, int index, SpiderInfo spiderInfo) throws ParseException {
spiderInfo.pages = GalleryDetailParser.parsePages(body);
spiderInfo.previewPages = GalleryDetailParser.parsePreviewPages(body);
PreviewSet previewSet = GalleryDetailParser.parsePreviewSet(body);
spiderInfo.previewPerPage = previewSet.size();
if ((index >= 0 && index < spiderInfo.pages - 1) || (index == 0 && spiderInfo.pages == 1)) {
spiderInfo.previewPerPage = previewSet.size();
} else {
spiderInfo.previewPerPage = Math.max(spiderInfo.previewPerPage, previewSet.size());
}
for (int i = 0, n = previewSet.size(); i < n; i++) {
GalleryPageUrlParser.Result result = GalleryPageUrlParser.parse(previewSet.getPageUrlAt(i));
if (result != null) {
@@ -710,8 +740,7 @@ public class SpiderQueen implements Runnable {
spiderInfo.pages = GalleryDetailParser.parsePages(body);
spiderInfo.pTokenMap = new SparseArray<>(spiderInfo.pages);
spiderInfo.previewPages = GalleryDetailParser.parsePreviewPages(body);
readPreviews(body, spiderInfo);
readPreviews(body, 0, spiderInfo);
return spiderInfo;
} catch (Exception e) {
return null;
@@ -719,27 +748,37 @@ public class SpiderQueen implements Runnable {
}
private String getPTokenFromInternet(int index, EhConfig config) {
SpiderInfo spiderInfo = mSpiderInfo.get();
if (spiderInfo == null) {
return null;
}
// Check previewIndex
int previewIndex = index / mSpiderInfo.previewPerPage;
int previewIndex;
if (spiderInfo.previewPerPage >= 0) {
previewIndex = index / spiderInfo.previewPerPage;
} else {
previewIndex = 0;
}
try {
String url = EhUrl.getGalleryDetailUrl(
mGalleryInfo.gid, mGalleryInfo.token, previewIndex, false);
if (DEBUG_LOG) {
Log.d(TAG, url);
if (DEBUG_PTOKEN) {
Log.d(TAG, "index " + index + ", previewIndex " + previewIndex +
", previewPerPage " + spiderInfo.previewPerPage+ ", url " + url);
}
Request request = new EhRequestBuilder(url, config).build();
Response response = mHttpClient.newCall(request).execute();
String body = response.body().string();
mSpiderInfo.previewPages = GalleryDetailParser.parsePreviewPages(body);
readPreviews(body, mSpiderInfo);
readPreviews(body, previewIndex, spiderInfo);
// Save to local
writeSpiderInfoToLocal(mSpiderInfo);
writeSpiderInfoToLocal(spiderInfo);
String pToken;
synchronized (mPTokenLock) {
pToken = mSpiderInfo.pTokenMap.get(index);
pToken = spiderInfo.pTokenMap.get(index);
}
return pToken;
} catch (Exception e) {
@@ -795,7 +834,7 @@ public class SpiderQueen implements Runnable {
if (spiderInfo == null) {
return;
}
mSpiderInfo = spiderInfo;
mSpiderInfo.lazySet(spiderInfo);
// Check interrupted
if (Thread.currentThread().isInterrupted()) {
@@ -821,11 +860,13 @@ public class SpiderQueen implements Runnable {
// Ensure worker
tryToEnsureWorkers();
// Start spider decoder
Thread decoderThread = new PriorityThread(new SpiderDecoder(), "SpiderDecoder-" + sIdGenerator.incrementAndGet(),
Process.THREAD_PRIORITY_BACKGROUND);
mDecoderThread = decoderThread;
decoderThread.start();
// Start decoder
for (int i = 0; i < DECODE_THREAD_NUM; i++) {
Thread decoderThread = new PriorityThread(new SpiderDecoder(i),
"SpiderDecoder-" + i, Process.THREAD_PRIORITY_DEFAULT);
mDecodeThreadArray[i] = decoderThread;
decoderThread.start();
}
// handle pToken request
while (!Thread.currentThread().isInterrupted()) {
@@ -866,7 +907,7 @@ public class SpiderQueen implements Runnable {
if (null == pToken) {
// If failed, set the pToken "failed"
synchronized (mPTokenLock) {
mSpiderInfo.pTokenMap.put(index, SpiderInfo.TOKEN_FAILED);
spiderInfo.pTokenMap.put(index, SpiderInfo.TOKEN_FAILED);
}
}
@@ -889,9 +930,10 @@ public class SpiderQueen implements Runnable {
mQueenThread = null;
// Interrupt decoder
Thread decoderThread = mDecoderThread;
if (decoderThread != null) {
decoderThread.interrupt();
for (Thread decoderThread : mDecodeThreadArray) {
if (decoderThread != null) {
decoderThread.interrupt();
}
}
// Interrupt all workers
@@ -1125,6 +1167,11 @@ public class SpiderQueen implements Runnable {
// false for stop
private boolean runInternal() {
SpiderInfo spiderInfo = mSpiderInfo.get();
if (spiderInfo == null) {
return false;
}
int size = mPageStateArray.length;
// Get request index
@@ -1174,10 +1221,10 @@ public class SpiderQueen implements Runnable {
// Clear TOKEN_FAILED for force request
if (force) {
synchronized (mPTokenLock) {
int i = mSpiderInfo.pTokenMap.indexOfKey(index);
String pToken = mSpiderInfo.pTokenMap.valueAt(i);
int i = spiderInfo.pTokenMap.indexOfKey(index);
String pToken = spiderInfo.pTokenMap.valueAt(i);
if (SpiderInfo.TOKEN_FAILED.equals(pToken)) {
mSpiderInfo.pTokenMap.remove(i);
spiderInfo.pTokenMap.remove(i);
}
}
}
@@ -1186,7 +1233,7 @@ public class SpiderQueen implements Runnable {
// Get token
while (!Thread.currentThread().isInterrupted()) {
synchronized (mPTokenLock) {
pToken = mSpiderInfo.pTokenMap.get(index);
pToken = spiderInfo.pTokenMap.get(index);
}
if (pToken == null) {
mRequestPTokenQueue.add(index);
@@ -1260,6 +1307,18 @@ public class SpiderQueen implements Runnable {
private class SpiderDecoder implements Runnable {
private final int mThreadIndex;
public SpiderDecoder(int index) {
mThreadIndex = index;
}
private void resetDecodeIndex() {
synchronized (mDecodeRequestStack) {
mDecodeIndexArray[mThreadIndex] = GalleryPageView.INVALID_INDEX;
}
}
@Override
public void run() {
if (DEBUG_LOG) {
@@ -1279,19 +1338,19 @@ public class SpiderQueen implements Runnable {
continue;
}
index = mDecodeRequestStack.pop();
mDecodingIndex.lazySet(index);
mDecodeIndexArray[mThreadIndex] = index;
}
// Check index valid
if (index < 0 || index >= mPageStateArray.length) {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
resetDecodeIndex();
notifyGetImageFailure(index, GetText.getString(R.string.error_out_of_range));
continue;
}
InputStreamPipe pipe = mSpiderDen.openInputStreamPipe(index);
if (pipe == null) {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
resetDecodeIndex();
// Can't find the file, it might be removed from cache,
// Reset it state and request it
updatePageState(index, STATE_NONE, null);
@@ -1299,24 +1358,36 @@ public class SpiderQueen implements Runnable {
continue;
}
Image image = null;
String error = null;
InputStream is;
pipe.obtain();
try {
pipe.obtain();
// TODO how to keep stream open
Image image = Image.decode(pipe.open(), false);
if (image != null) {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyGetImageSuccess(index, image);
} else {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyGetImageFailure(index, GetText.getString(R.string.error_decoding_failed));
}
is = new AutoCloseInputStream(pipe, pipe.open());
} catch (IOException e) {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyGetImageFailure(index, GetText.getString(R.string.error_reading_failed));
} finally {
// Can't open pipe
error = GetText.getString(R.string.error_reading_failed);
is = null;
pipe.close();
pipe.release();
}
if (is != null) {
image = Image.decode(is, true);
if (image == null) {
error = GetText.getString(R.string.error_decoding_failed);
}
}
// Notify
if (image != null) {
notifyGetImageSuccess(index, image);
} else {
notifyGetImageFailure(index, error);
}
resetDecodeIndex();
}
if (DEBUG_LOG) {
@@ -1325,6 +1396,33 @@ public class SpiderQueen implements Runnable {
}
}
private class AutoCloseInputStream extends InputStream {
private final InputStreamPipe mPipe;
private final InputStream mIs;
public AutoCloseInputStream(InputStreamPipe pipe, InputStream is) {
mPipe = pipe;
mIs = is;
}
@Override
public int read() throws IOException {
return mIs.read();
}
@Override
public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {
return mIs.read(buffer, byteOffset, byteCount);
}
@Override
public void close() throws IOException {
mPipe.close();
mPipe.release();
}
}
public interface OnSpiderListener {
void onGetPages(int pages);
@@ -61,8 +61,8 @@ import com.hippo.ehviewer.gallery.gl.ImageView;
import com.hippo.ehviewer.widget.GalleryGuideView;
import com.hippo.ehviewer.widget.ReversibleSeekBar;
import com.hippo.gl.glrenderer.ImageTexture;
import com.hippo.gl.glrenderer.ImageWrapper;
import com.hippo.gl.view.GLRootView;
import com.hippo.image.ImageWrapper;
import com.hippo.unifile.UniFile;
import com.hippo.util.SystemUiHelper;
import com.hippo.widget.ColorView;
@@ -20,6 +20,7 @@ import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
@@ -70,6 +71,7 @@ import com.hippo.ehviewer.ui.scene.WarningScene;
import com.hippo.ehviewer.ui.scene.WebViewSignInScene;
import com.hippo.ehviewer.widget.EhDrawerLayout;
import com.hippo.io.UniFileInputStreamPipe;
import com.hippo.network.Network;
import com.hippo.scene.Announcer;
import com.hippo.scene.SceneFragment;
import com.hippo.scene.StageActivity;
@@ -392,6 +394,9 @@ public final class MainActivity extends StageActivity
onInit();
CommonOperations.checkUpdate(this, false);
checkDownloadLocation();
if (Settings.getCellularNetworkWarning()) {
checkCellularNetwork();
}
} else {
onRestore(savedInstanceState);
}
@@ -410,6 +415,12 @@ public final class MainActivity extends StageActivity
.show();
}
private void checkCellularNetwork() {
if (Network.getActiveNetworkType(this) == ConnectivityManager.TYPE_MOBILE) {
showTip(R.string.cellular_network_warning, BaseScene.LENGTH_SHORT);
}
}
private void onInit() {
// Check permission
PermissionRequester.request(this, Manifest.permission.WRITE_EXTERNAL_STORAGE,
@@ -1145,17 +1145,8 @@ public class DownloadsScene extends ToolbarScene
return;
}
DownloadInfo info = mList.get(position);
DataContainer container = null;
UniFile dir = SpiderDen.getGalleryDownloadDir(info);
if (dir != null) {
UniFile file = dir.createFile(".thumb");
if (file != null) {
container = new ThumbDataContainer(file);
}
}
holder.thumb.load(EhCacheKeyFactory.getThumbKey(info.gid), info.thumb, container, true);
holder.thumb.load(EhCacheKeyFactory.getThumbKey(info.gid), info.thumb,
new ThumbDataContainer(info), true);
holder.title.setText(EhUtils.getSuitableTitle(info));
holder.uploader.setText(info.uploader);
holder.rating.setRating(info.rating);
@@ -1219,21 +1210,32 @@ public class DownloadsScene extends ToolbarScene
private class ThumbDataContainer implements DataContainer {
@NonNull
private final UniFile mFile;
private final DownloadInfo mInfo;
private UniFile mFile;
/**
* @param file the thumb file
*/
public ThumbDataContainer(@NonNull UniFile file) {
mFile = file;
public ThumbDataContainer(@NonNull DownloadInfo info) {
mInfo = info;
}
@Override
public void onUrlMoved(String requestUrl, String responseUrl) {}
private void ensureFile() {
if (mFile == null) {
UniFile dir = SpiderDen.getGalleryDownloadDir(mInfo);
if (dir != null && dir.ensureDir()) {
mFile = dir.createFile(".thumb");
}
}
}
@Override
public boolean save(InputStream is, long length, String mediaType, ProgressNotifier notify) {
ensureFile();
if (mFile == null) {
return false;
}
OutputStream os = null;
try {
os = mFile.openOutputStream();
@@ -1249,7 +1251,12 @@ public class DownloadsScene extends ToolbarScene
@Override
public InputStreamPipe get() {
return new UniFileInputStreamPipe(mFile);
ensureFile();
if (mFile != null) {
return new UniFileInputStreamPipe(mFile);
} else {
return null;
}
}
@Override
@@ -913,12 +913,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
private static String getRatingText(float rating, Resources resources) {
String undefine = "(´_ゝ`)";
if (-1.0f == rating) {
return undefine;
}
int resId = 0;
int resId;
switch (Math.round(rating * 2)) {
case 0:
resId = R.string.rating0; break;
@@ -942,13 +937,11 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
resId = R.string.rating9; break;
case 10:
resId = R.string.rating10; break;
default:
resId = R.string.rating_none; break;
}
if (resId == 0) {
return undefine;
} else {
return resources.getString(resId);
}
return resources.getString(resId);
}
private String getAllRatingText(float rating, int ratingCount) {
@@ -53,7 +53,7 @@ public abstract class BasicTexture implements Texture {
protected GLCanvas mCanvasRef = null;
private final static WeakHashMap<BasicTexture, Object> sAllTextures
= new WeakHashMap<>();
private static ThreadLocal<Class> sInFinalizer = new ThreadLocal<>();
private static final ThreadLocal<Class> sInFinalizer = new ThreadLocal<>();
protected BasicTexture(GLCanvas canvas, int id, int state) {
setAssociatedCanvas(canvas);
@@ -20,7 +20,7 @@ package com.hippo.gl.glrenderer;
// Before drawing, setSize() should be called.
public class ExtTexture extends BasicTexture {
private int mTarget;
private final int mTarget;
public ExtTexture(GLCanvas canvas, int target) {
GLId glId = canvas.getGLId();
@@ -0,0 +1,209 @@
/*
* Copyright 2016 Hippo Seven
*
* 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 com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.image.Image;
import java.util.Arrays;
public class ImageMovableTextTexture extends ImageSpriteTexture {
private final char[] mCharacters;
private final float[] mWidths;
private final float mHeight;
private final float mMaxWidth;
public ImageMovableTextTexture(@NonNull ImageWrapper image, int count, int[] rects,
char[] characters, float[] widths, float height, float maxWidth) {
super(image, count, rects);
mCharacters = characters;
mWidths = widths;
mHeight = height;
mMaxWidth = maxWidth;
}
public int[] getTextIndexes(String text) {
char[] characters = mCharacters;
int length = text.length();
int[] indexes = new int[length];
for (int i = 0; i < length; i++) {
char ch = text.charAt(i);
indexes[i] = Arrays.binarySearch(characters, ch);
}
return indexes;
}
public float getTextWidth(String text) {
char[] characters = mCharacters;
float[] widths = mWidths;
float width = 0.0f;
for (int i = 0, n = text.length(); i < n; i++) {
char ch = text.charAt(i);
int index = Arrays.binarySearch(characters, ch);
if (index >= 0) {
width += widths[index];
} else {
width += mMaxWidth;
}
}
return width;
}
public float getTextWidth(int[] indexes) {
float[] widths = mWidths;
float width = 0.0f;
int length = indexes.length;
for (int i = 0; i < length; i++) {
int index = indexes[i];
if (index >= 0) {
width += widths[index];
} else {
width += mMaxWidth;
}
}
return width;
}
public float getMaxWidth() {
return mMaxWidth;
}
public float getTextHeight() {
return mHeight;
}
public void drawText(GLCanvas canvas, String text, int x, int y) {
char[] characters = mCharacters;
float[] widths = mWidths;
for (int i = 0, n = text.length(); i < n; i++) {
char ch = text.charAt(i);
int index = Arrays.binarySearch(characters, ch);
if (index >= 0) {
drawSprite(canvas, index, x, y);
x += widths[index];
} else {
x += mMaxWidth;
}
}
}
public void drawText(GLCanvas canvas, int[] indexes, int x, int y) {
float[] widths = mWidths;
for (int i = 0, n = indexes.length; i < n; i++) {
int index = indexes[i];
if (index >= 0) {
drawSprite(canvas, index, x, y);
x += widths[index];
} else {
x += mMaxWidth;
}
}
}
/**
* Create a TextTexture to draw text
*
* @param typeface the typeface
* @param size text size
* @param characters all Characters
* @return the TextTexture
*/
@Nullable
public static ImageMovableTextTexture create(Typeface typeface, int size, int color, char[] characters) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setTextSize(size);
paint.setColor(color);
paint.setTypeface(typeface);
Paint.FontMetricsInt fmi = paint.getFontMetricsInt();
int fixed = fmi.bottom;
int height = fmi.bottom - fmi.top;
int length = characters.length;
float[] widths = new float[length];
paint.getTextWidths(characters, 0, length, widths);
// Calculate bitmap size
float maxWidth = 0.0f;
for (float f : widths) {
maxWidth = Math.max(maxWidth, f);
}
int hCount = (int) Math.ceil(Math.sqrt(height / maxWidth * length));
int vCount = (int) Math.ceil(Math.sqrt(maxWidth / height * length));
if (hCount * (vCount - 1) > length) {
vCount--;
}
if ((hCount - 1) * vCount > length) {
hCount--;
}
Bitmap bitmap = Bitmap.createBitmap((int) Math.ceil(hCount * maxWidth),
(int) Math.ceil(vCount * height), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.translate(0, height - fixed);
// Draw
int[] rects = new int[length * 4];
int x = 0;
int y = 0;
for (int i = 0; i < length; i++) {
int offset = i * 4;
rects[offset + 0] = x;
rects[offset + 1] = y;
rects[offset + 2] = (int) widths[i];
rects[offset + 3] = height;
canvas.drawText(characters, i, 1, x, y, paint);
if (i % hCount == hCount - 1) {
// The end of row
x = 0;
y += height;
} else {
x += maxWidth;
}
}
Image image = Image.create(bitmap);
bitmap.recycle();
if (image == null) {
return null;
}
ImageWrapper imageWrapper = new ImageWrapper(image);
if (imageWrapper.obtain()) {
return new ImageMovableTextTexture(imageWrapper, length, rects, characters, widths, height, maxWidth);
} else {
return null;
}
}
}
@@ -0,0 +1,89 @@
/*
* Copyright 2016 Hippo Seven
*
* 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 com.hippo.gl.glrenderer;
import android.graphics.RectF;
import android.support.annotation.NonNull;
import com.hippo.yorozuya.AssertUtils;
public class ImageSpriteTexture extends ImageTexture {
private final int mCount;
private final int[] mRects;
private final RectF mTempSource = new RectF();
private final RectF mTempTarget = new RectF();
public ImageSpriteTexture(@NonNull ImageWrapper image, int count, int[] rects) {
super(image);
AssertUtils.assertEquals("rects.length must be count * 4", count * 4, rects.length);
mCount = count;
mRects = rects;
}
public int getCount() {
return mCount;
}
public void drawSprite(GLCanvas canvas, int index, int x, int y) {
int[] rects = mRects;
int offset = index * 4;
int sourceX = rects[offset];
int sourceY = rects[offset + 1];
int sourceWidth = rects[offset + 2];
int sourceHeight = rects[offset + 3];
mTempSource.set(sourceX, sourceY, sourceX + sourceWidth, sourceY + sourceHeight);
mTempTarget.set(x, y, x + sourceWidth, y + sourceHeight);
draw(canvas, mTempSource, mTempTarget);
}
public void drawSprite(GLCanvas canvas, int index, int x, int y, int width, int height) {
int[] rects = mRects;
int offset = index * 4;
int sourceX = rects[offset];
int sourceY = rects[offset + 1];
mTempSource.set(sourceX, sourceY, sourceX + rects[offset + 2], sourceY + rects[offset + 3]);
mTempTarget.set(x, y, x + width, y + height);
draw(canvas, mTempSource, mTempTarget);
}
public void drawSpriteMixed(GLCanvas canvas, int index, int color, float ratio, int x, int y) {
int[] rects = mRects;
int offset = index * 4;
int sourceX = rects[offset];
int sourceY = rects[offset + 1];
int sourceWidth = rects[offset + 2];
int sourceHeight = rects[offset + 3];
mTempSource.set(sourceX, sourceY, sourceX + sourceWidth, sourceY + sourceHeight);
mTempTarget.set(x, y, x + sourceWidth, y + sourceHeight);
drawMixed(canvas, color, ratio, mTempSource, mTempTarget);
}
public void drawSpriteMixed(GLCanvas canvas, int index, int color, float ratio,
int x, int y, int width, int height) {
int[] rects = mRects;
int offset = index * 4;
int sourceX = rects[offset];
int sourceY = rects[offset + 1];
mTempSource.set(sourceX, sourceY, sourceX + rects[offset + 2],
sourceY + rects[offset + 3]);
mTempTarget.set(x, y, x + width, y + height);
drawMixed(canvas, color, ratio, mTempSource, mTempTarget);
}
}
@@ -18,13 +18,14 @@ package com.hippo.gl.glrenderer;
import android.graphics.RectF;
import android.graphics.drawable.Animatable;
import android.os.Process;
import android.os.SystemClock;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import com.hippo.gl.annotation.RenderThread;
import com.hippo.gl.view.GLRoot;
import com.hippo.image.ImageWrapper;
import com.hippo.yorozuya.thread.InfiniteThreadExecutor;
import com.hippo.yorozuya.thread.PVLock;
import com.hippo.yorozuya.thread.PriorityThreadFactory;
@@ -33,8 +34,9 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public class ImageTexture implements Texture, Animatable {
@@ -59,7 +61,7 @@ public class ImageTexture implements Texture, Animatable {
// In this 16ms, we use about 4~8 ms to upload tiles.
private static final long UPLOAD_TILE_LIMIT = 4; // ms
private static final PriorityThreadFactory sThreadFactory;
private static final Executor sThreadExecutor;
private static final PVLock sPVLock;
private static Tile sSmallFreeTileHead = null;
@@ -77,17 +79,19 @@ public class ImageTexture implements Texture, Animatable {
private final RectF mSrcRect = new RectF();
private final RectF mDestRect = new RectF();
private final AtomicBoolean mFrameDirty = new AtomicBoolean();
private boolean mImageBusy = false;
private final AtomicBoolean mRunning = new AtomicBoolean();
private final AtomicBoolean mFrameDirty = new AtomicBoolean();
private final AtomicBoolean mNeedRelease = new AtomicBoolean();
private final AtomicBoolean mReleased = new AtomicBoolean();
private final AtomicReference<Thread> mAnimateThread = new AtomicReference<>();
private Runnable mAnimateRunnable = null;
private WeakReference<Callback> mCallback;
static {
sThreadFactory = new PriorityThreadFactory("ImageTexture$AnimateTask", android.os.Process.THREAD_PRIORITY_BACKGROUND);
sThreadExecutor = new InfiniteThreadExecutor(10 * 1000, new LinkedList<>(),
new PriorityThreadFactory("ImageTexture$AnimateTask", Process.THREAD_PRIORITY_BACKGROUND));
sPVLock = new PVLock(3);
}
@@ -173,7 +177,15 @@ public class ImageTexture implements Texture, Animatable {
@Override
protected void texImage(boolean init) {
if (image != null && !image.isRecycled()) {
image.texImage(init, mTileType, offsetX, offsetY);
int w, h;
if (init) {
w = mTextureWidth;
h = mTextureHeight;
} else {
w = mWidth;
h = mHeight;
}
image.texImage(init, offsetX - borderSize, offsetY - borderSize, w, h);
}
}
@@ -241,41 +253,29 @@ public class ImageTexture implements Texture, Animatable {
private class AnimateRunnable implements Runnable {
public void doRun() {
long lastTime = SystemClock.elapsedRealtime();
long lastTime = System.nanoTime();
long lastDelay = -1L;
synchronized (mImage) {
// Check released
if (mReleased.get()) {
return;
}
// Check image busy
if (mImageBusy) {
// Image is busy, means it is recycling
return;
}
if (mNeedRelease.get()) {
// Need release
// Check released, image busy, Need release
if (mReleased.get() || mImageBusy || mNeedRelease.get()) {
mAnimateRunnable = null;
return;
}
// Obtain image
mImageBusy = true;
}
boolean interrupted = Thread.currentThread().isInterrupted();
if (!mImage.isCompleted()) {
if (!interrupted) {
try {
sPVLock.p();
} catch (InterruptedException e) {
interrupted = true;
}
if (!interrupted && !mNeedRelease.get()) {
mImage.complete();
}
sPVLock.v();
try {
sPVLock.p();
} catch (InterruptedException e) {
// Ignore
}
if (!mNeedRelease.get()) {
mImage.complete();
}
sPVLock.v();
}
int frameCount = mImage.getFrameCount();
@@ -283,26 +283,19 @@ public class ImageTexture implements Texture, Animatable {
synchronized (mImage) {
// Release image
mImageBusy = false;
// Check need release, frameCount <= 1
if (mNeedRelease.get() || frameCount <= 1) {
mAnimateRunnable = null;
return;
}
}
if (interrupted || mNeedRelease.get() || frameCount <= 1) {
return;
}
while (!Thread.currentThread().isInterrupted()) {
for (;;) {
// Obtain
synchronized (mImage) {
// Check released
if (mReleased.get()) {
return;
}
// Check image busy
if (mImageBusy) {
// Image is busy, means it is recycling
return;
}
if (mNeedRelease.get()) {
// Need release
// Check released, image busy, Need release, not running
if (mReleased.get() || mImageBusy || mNeedRelease.get() || !mRunning.get()) {
mAnimateRunnable = null;
return;
}
// Obtain image
@@ -311,9 +304,9 @@ public class ImageTexture implements Texture, Animatable {
mImage.advance();
long delay = mImage.getDelay();
long time = SystemClock.elapsedRealtime();
long time = System.nanoTime();
if (-1L != lastDelay) {
delay -= (time - lastTime) - lastDelay;
delay -= (time - lastTime) / 1000000 - lastDelay;
}
lastTime = time;
lastDelay = delay;
@@ -329,7 +322,7 @@ public class ImageTexture implements Texture, Animatable {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
break;
// Ignore
}
}
}
@@ -363,11 +356,12 @@ public class ImageTexture implements Texture, Animatable {
mImageBusy = false;
}
}
mAnimateThread.lazySet(null);
}
}
/**
* Call {@link ImageWrapper#obtain()} first
*/
public ImageTexture(@NonNull ImageWrapper image) {
mImage = image;
int width = mWidth = image.getWidth();
@@ -432,10 +426,10 @@ public class ImageTexture implements Texture, Animatable {
mTiles = list.toArray(new Tile[list.size()]);
if (!mImage.isCompleted() || mImage.getFrameCount() > 1) {
Thread thread = sThreadFactory.newThread(new AnimateRunnable());
mAnimateThread.lazySet(thread);
thread.start();
if (!mImage.isCompleted()) {
Runnable runnable = new AnimateRunnable();
mAnimateRunnable = runnable;
sThreadExecutor.execute(runnable);
}
}
@@ -459,33 +453,31 @@ public class ImageTexture implements Texture, Animatable {
@Override
public void start() {
if (mReleased.get() || (mImage.isCompleted() && mImage.getFrameCount() <= 1)) {
if (mReleased.get() || mNeedRelease.get() || (mImage.isCompleted() && mImage.getFrameCount() <= 1) ||
mRunning.get()) {
return;
}
Thread thread = mAnimateThread.get();
if (thread == null) {
thread = sThreadFactory.newThread(new AnimateRunnable());
mAnimateThread.set(thread);
thread.start();
}
}
mRunning.lazySet(true);
@Override
public void stop() {
if (!mReleased.get() && (mImage.isCompleted() && mImage.getFrameCount() > 1)) {
Thread thread = mAnimateThread.getAndSet(null);
if (null != thread) {
thread.interrupt();
synchronized (mImage) {
if (mAnimateRunnable == null) {
Runnable runnable = new AnimateRunnable();
mAnimateRunnable = runnable;
sThreadExecutor.execute(runnable);
}
}
}
@Override
public boolean isRunning() {
return mAnimateThread.get() != null;
public void stop() {
mRunning.lazySet(false);
}
@Override
public boolean isRunning() {
return mRunning.get();
}
private boolean uploadNextTile(GLCanvas canvas) {
if (mUploadIndex == mTiles.length) return true;
@@ -652,6 +644,8 @@ public class ImageTexture implements Texture, Animatable {
}
public void recycle() {
mRunning.lazySet(false);
for (Tile mTile : mTiles) {
mTile.free();
}
@@ -664,6 +658,7 @@ public class ImageTexture implements Texture, Animatable {
mImageBusy = true;
} else {
releaseNow = false;
mNeedRelease.set(true);
}
}
@@ -673,13 +668,6 @@ public class ImageTexture implements Texture, Animatable {
synchronized (mImage) {
mImageBusy = false;
}
} else {
mNeedRelease.set(true);
}
Thread thread = mAnimateThread.getAndSet(null);
if (null != thread) {
thread.interrupt();
}
}
@@ -0,0 +1,153 @@
/*
* Copyright 2016 Hippo Seven
*
* 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 com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import com.hippo.image.Image;
/**
* A wrapper for {@link Image}. It is useful for multi-usage.
* It handles image recycle automatically.
*/
public class ImageWrapper {
private final Image mImage;
private int mReferences;
/**
* Create ImageWrapper
*
* @param image the image should not be obtained or recycled.
*/
public ImageWrapper(@NonNull Image image) {
mImage = image;
}
/**
* Obtain the image
*
* @return false for the image is recycled and obtain failed
*/
public synchronized boolean obtain() {
if (mImage.isRecycled()) {
return false;
} else {
++mReferences;
return true;
}
}
/**
* Release the image
*/
public synchronized void release() {
--mReferences;
if (mReferences <= 0 && !mImage.isRecycled()) {
mImage.recycle();
}
}
/**
* @see Image#getFormat()
*/
public int getFormat() {
return mImage.getFormat();
}
/**
* @see Image#getFormat()
*/
public int getWidth() {
return mImage.getWidth();
}
/**
* @see Image#getHeight()
*/
public int getHeight() {
return mImage.getHeight();
}
/**
* @see Image#complete()
*/
public boolean complete() {
synchronized (mImage) {
return mImage.complete();
}
}
/**
* @see Image#isCompleted()
*/
public boolean isCompleted() {
return mImage.isCompleted();
}
/**
* @see Image#render(int, int, Bitmap, int, int, int, int, boolean, int)
*/
public void render(int srcX, int srcY, Bitmap dst, int dstX, int dstY,
int width, int height, boolean fillBlank, int defaultColor) {
mImage.render(srcX, srcY, dst, dstX, dstY,
width, height, fillBlank, defaultColor);
}
/**
* @see Image#texImage(boolean, int, int, int, int)
*/
public void texImage(boolean init, int offsetX, int offsetY, int width, int height) {
mImage.texImage(init, offsetX, offsetY, width, height);
}
/**
* @see Image#advance()
*/
public void advance() {
mImage.advance();
}
/**
* @see Image#getDelay()
*/
public int getDelay() {
return mImage.getDelay();
}
/**
* @see Image#getFrameCount()
*/
public int getFrameCount() {
return mImage.getFrameCount();
}
/**
* @see Image#isOpaque()
*/
public boolean isOpaque() {
return mImage.isOpaque();
}
/**
* @see Image#isRecycled()
*/
public boolean isRecycled() {
return mImage.isRecycled();
}
}
@@ -13,12 +13,12 @@ import java.util.Arrays;
* <br>
* Only support single line now
*/
public class MovableTextTexture extends SpriteTexture {
public final class MovableTextTexture extends SpriteTexture {
private char[] mCharacters;
private float[] mWidths;
private float mHeight;
private float mMaxWidth;
private final char[] mCharacters;
private final float[] mWidths;
private final float mHeight;
private final float mMaxWidth;
private MovableTextTexture(Bitmap bitmap, int count, int[] rects, char[] characters,
float[] widths, float height, float maxWidth) {
@@ -137,7 +137,7 @@ public class MovableTextTexture extends SpriteTexture {
float[] widths = new float[length];
paint.getTextWidths(characters, 0, length, widths);
// Caculate bitmap size
// Calculate bitmap size
float maxWidth = 0.0f;
for (float f : widths) {
maxWidth = Math.max(maxWidth, f);
@@ -54,6 +54,7 @@ public abstract class NativeTexture extends BasicTexture {
GLES20.glBindTexture(getTarget(), mId);
checkError();
texImage(true);
checkError();
setAssociatedCanvas(canvas);
mState = STATE_LOADED;
@@ -68,6 +69,7 @@ public abstract class NativeTexture extends BasicTexture {
GLES20.glBindTexture(getTarget(), mId);
checkError();
texImage(false);
checkError();
mContentValid = true;
}
}
@@ -7,11 +7,11 @@ import com.hippo.yorozuya.AssertUtils;
public class SpriteTexture extends TiledTexture {
private int mCount;
private int[] mRects;
private final int mCount;
private final int[] mRects;
private RectF mTempSource = new RectF();
private RectF mTempTarget = new RectF();
private final RectF mTempSource = new RectF();
private final RectF mTempTarget = new RectF();
public SpriteTexture(Bitmap bitmap, boolean isOpaque, int count, int[] rects) {
super(bitmap, isOpaque);
@@ -25,9 +25,9 @@ public class TextureUploader implements GLRoot.OnGLIdleListener {
private static final int QUOTA_PER_FRAME = 1;
private final ArrayDeque<UploadedTexture> mFgTextures =
new ArrayDeque<UploadedTexture>(INIT_CAPACITY);
new ArrayDeque<>(INIT_CAPACITY);
private final ArrayDeque<UploadedTexture> mBgTextures =
new ArrayDeque<UploadedTexture>(INIT_CAPACITY);
new ArrayDeque<>(INIT_CAPACITY);
private final GLRoot mGLRoot;
private volatile boolean mIsQueued = false;
@@ -47,10 +47,10 @@ public class TiledTexture implements Texture {
private static Tile sFreeTileHead = null;
private static final Object sFreeTileLock = new Object();
private static Bitmap sUploadBitmap;
private static Canvas sCanvas;
private static Paint sBitmapPaint;
private static Paint sPaint;
private static final Bitmap sUploadBitmap;
private static final Canvas sCanvas;
private static final Paint sBitmapPaint;
private static final Paint sPaint;
private int mUploadIndex = 0;
@@ -44,9 +44,9 @@ public abstract class UploadedTexture extends BasicTexture {
// To prevent keeping allocation the borders, we store those used borders here.
// Since the length will be power of two, it won't use too much memory.
private static HashMap<BorderKey, Bitmap> sBorderLines =
private static final HashMap<BorderKey, Bitmap> sBorderLines =
new HashMap<>();
private static BorderKey sBorderKey = new BorderKey();
private static final BorderKey sBorderKey = new BorderKey();
@SuppressWarnings("unused")
private static final String TAG = "Texture";
@@ -25,8 +25,8 @@ import android.support.v4.content.ContextCompat;
public class XmlResourceTexture extends UploadedTexture {
private Context mContext;
private int mResId;
private final Context mContext;
private final int mResId;
private int mWidth;
private int mHeight;
@@ -63,7 +63,7 @@ import javax.microedition.khronos.opengles.GL11;
// (2) The public methods of CameraHeadUpDisplay
// (3) The overridden methods in GLRootView.
public class GLRootView extends GLSurfaceView
implements Renderer, GLRoot {
implements GLRoot {
private static final String TAG = "GLRootView";
private static final boolean DEBUG_FPS = false;
@@ -107,22 +107,113 @@ public class GLRootView extends GLSurfaceView
mRenderLock.newCondition();
private boolean mFreeze;
private long mLastDrawFinishTime;
private boolean mInDownState = false;
//private boolean mFirstDraw = true;
private class GLRootRenderer implements Renderer {
/**
* Called when the context is created, possibly after automatic destruction.
*/
@Override
public void onSurfaceCreated(GL10 gl1, EGLConfig config) {
GL11 gl = (GL11) gl1;
if (mGL != null) {
// The GL Object has changed
Log.i(TAG, "GLObject has changed from " + mGL + " to " + gl);
}
mRenderLock.lock();
try {
mGL = gl;
mCanvas = new GLES20Canvas();
BasicTexture.invalidateAllTextures();
} finally {
mRenderLock.unlock();
}
if (DEBUG_FPS) {
setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
} else {
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
}
/**
* Called when the OpenGL surface is recreated without destroying the
* context.
*/
@Override
public void onSurfaceChanged(GL10 gl1, int width, int height) {
Log.i(TAG, "onSurfaceChanged: " + width + "x" + height + ", gl10: " + gl1.toString());
Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY);
GalleryUtils.setRenderThread();
GL11 gl = (GL11) gl1;
AssertUtils.assertTrue(mGL == gl);
mCanvas.setSize(width, height);
}
@Override
public void onDrawFrame(GL10 gl) {
AnimationTime.update();
long t0 = System.nanoTime();
mRenderLock.lock();
while (mFreeze) {
mFreezeCondition.awaitUninterruptibly();
}
try {
onDrawFrameLocked(gl);
} finally {
mRenderLock.unlock();
}
long t = System.nanoTime();
long duration = (t - t0) / 1000000;
if (duration > 8) {
Log.v(TAG, "--- " + duration + " ---");
}
}
@Override
public void onSurfaceDestroyed() {
if (mContentView != null && mContentView.isAttachedToRoot()) {
mContentView.detachFromRoot();
}
}
@Override
public void onPause() {
if (mContentView != null) {
mContentView.pause();
}
}
@Override
public void onResume() {
if (mContentView != null) {
mContentView.resume();
}
}
}
public GLRootView(Context context) {
this(context, null);
}
@SuppressWarnings("deprecation")
public GLRootView(Context context, AttributeSet attrs) {
super(context, attrs);
mFlags |= FLAG_INITIALIZED;
setBackgroundDrawable(null);
setEGLContextClientVersion(2);
setEGLConfigChooser(new BestConfigChooser());
setRenderer(this);
final int eglContextClientVersion = 2;
setEGLContextClientVersion(eglContextClientVersion);
setEGLConfigChooser(new BestConfigChooser(eglContextClientVersion));
setRenderer(new GLRootRenderer());
getHolder().setFormat(PixelFormat.RGB_888);
// Uncomment this to enable gl error check.
@@ -273,56 +364,6 @@ public class GLRootView extends GLSurfaceView
if (changed) requestLayoutContentPane();
}
/**
* Called when the context is created, possibly after automatic destruction.
*/
// This is a GLSurfaceView.Renderer callback
@Override
public void onSurfaceCreated(GL10 gl1, EGLConfig config) {
GL11 gl = (GL11) gl1;
if (mGL != null) {
// The GL Object has changed
Log.i(TAG, "GLObject has changed from " + mGL + " to " + gl);
}
mRenderLock.lock();
try {
mGL = gl;
mCanvas = new GLES20Canvas();
BasicTexture.invalidateAllTextures();
} finally {
mRenderLock.unlock();
}
if (DEBUG_FPS) {
setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
} else {
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
}
/**
* Called when the OpenGL surface is recreated without destroying the
* context.
*/
// This is a GLSurfaceView.Renderer callback
@Override
public void onSurfaceChanged(GL10 gl1, int width, int height) {
Log.i(TAG, "onSurfaceChanged: " + width + "x" + height + ", gl10: " + gl1.toString());
Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY);
GalleryUtils.setRenderThread();
GL11 gl = (GL11) gl1;
AssertUtils.assertTrue(mGL == gl);
mCanvas.setSize(width, height);
}
@Override
public void onSurfaceDestroyed() {
if (mContentView != null && mContentView.isAttachedToRoot()) {
mContentView.detachFromRoot();
}
}
private void outputFps() {
long now = System.nanoTime();
if (mFrameCountingStart == 0) {
@@ -336,47 +377,6 @@ public class GLRootView extends GLSurfaceView
++mFrameCount;
}
@Override
public void onDrawFrame(GL10 gl) {
AnimationTime.update();
long t0 = System.nanoTime();
mRenderLock.lock();
while (mFreeze) {
mFreezeCondition.awaitUninterruptibly();
}
try {
onDrawFrameLocked(gl);
} finally {
mRenderLock.unlock();
}
// We put a black cover View in front of the SurfaceView and hide it
// after the first draw. This prevents the SurfaceView being transparent
// before the first draw.
//if (mFirstDraw) {
// mFirstDraw = false;
// post(new Runnable() {
// @Override
// public void run() {
// View root = getRootView();
// View cover = root.findViewById(R.id.gl_root_cover);
// cover.setVisibility(GONE);
// }
// });
//}
long t = System.nanoTime();
long duration = (t - t0) / 1000000;
if (duration > 34) {
Log.v(TAG, "--- " + duration + " ---");
}
}
private void onDrawFrameLocked(GL10 gl) {
if (DEBUG_FPS) outputFps();
// release the unbound textures and deleted buffers.
@@ -212,7 +212,7 @@ public class GLView implements TouchOwner {
}
// This should only be called on the content pane (the topmost GLView).
public void attachToRoot(GLRoot root) {
void attachToRoot(GLRoot root) {
AssertUtils.assertTrue(mParent == null && mRoot == null);
onAttachToRoot(root);
}
@@ -223,6 +223,16 @@ public class GLView implements TouchOwner {
onDetachFromRoot();
}
// This should only be called on the content pane (the topmost GLView).
void pause() {
onPause();
}
// This should only be called on the content pane (the topmost GLView).
void resume() {
onResume();
}
public boolean isAttachedToRoot() {
return mRoot != null;
}
@@ -1115,6 +1125,18 @@ public class GLView implements TouchOwner {
mRoot = null;
}
public void onPause() {
for (int i = 0, n = getComponentCount(); i < n; ++i) {
getComponent(i).onPause();
}
}
public void onResume() {
for (int i = 0, n = getComponentCount(); i < n; ++i) {
getComponent(i).onResume();
}
}
public void lockRendering() {
if (mRoot != null) {
mRoot.lockRenderThread();
@@ -20,14 +20,14 @@ import android.graphics.Rect;
import android.text.TextUtils;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.gl.glrenderer.MovableTextTexture;
import com.hippo.gl.glrenderer.ImageMovableTextTexture;
import com.hippo.gl.view.GLView;
import com.hippo.gl.view.Gravity;
import com.hippo.yorozuya.collect.CollectionUtils;
public class GLMovableTextView extends GLView {
MovableTextTexture mTextTexture;
ImageMovableTextTexture mTextTexture;
private String mText = "";
private int[] mIndexes = CollectionUtils.EMPTY_INT_ARRAY;
@@ -42,7 +42,7 @@ public class GLMovableTextView extends GLView {
}
}
public void setTextTexture(MovableTextTexture textTexture) {
public void setTextTexture(ImageMovableTextTexture textTexture) {
if (mTextTexture == textTexture) {
return;
}
@@ -0,0 +1,35 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* 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 com.hippo.network;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public final class Network {
private Network() {}
public static int getActiveNetworkType(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
return activeNetwork.getType();
} else {
return -1;
}
}
}
@@ -216,7 +216,6 @@ public class CookieDBStore implements CookieJar {
List<CookieWithID> cookies = map.get(key);
// cookies can not be null
getInternal(url, cookies, result);
break;
}
}
@@ -357,7 +357,7 @@ public class FabLayout extends ViewGroup implements View.OnClickListener {
int position = indexOfChild(v);
if (position == getChildCount() - 1) {
mOnClickFabListener.onClickPrimaryFab(this, (FloatingActionButton) v);
} else if (position >= 0) {
} else if (position >= 0 && mExpanded) {
mOnClickFabListener.onClickSecondaryFab(this, (FloatingActionButton) v, position);
}
}
@@ -117,7 +117,7 @@ public class LoadImageView extends FixedAspectImageView implements Unikery<Image
if (mFailed) {
onFailure();
} else {
} else if (mTaskId == Unikery.INVALID_ID) /* if (!mConaco.isLoading(mTaskId)) TODO Update Conaco */ {
load(mKey, mUrl, mContainer, mUseNetwork);
}
}
@@ -60,7 +60,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="@string/unfavorited"
android:text="@string/not_favorited"
android:drawablePadding="8dp"
android:textColor="@color/primary_text_light"/>
+13 -12
View File
@@ -61,45 +61,46 @@
android:paddingBottom="@dimen/corner_fab_margin">
<android.support.design.widget.FloatingActionButton
style="@style/Widget.Design.FloatingActionButton.Mini"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/v_check_all_dark_x24"
app:backgroundTint="?attr/colorPrimary"/>
app:backgroundTint="?attr/colorAccent"
style="@style/Widget.Design.FloatingActionButton.Mini"/>
<android.support.design.widget.FloatingActionButton
style="@style/Widget.Design.FloatingActionButton.Mini"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/v_play_dark_x24"
app:backgroundTint="?attr/colorPrimary"/>
app:backgroundTint="?attr/colorAccent"
style="@style/Widget.Design.FloatingActionButton.Mini"/>
<android.support.design.widget.FloatingActionButton
style="@style/Widget.Design.FloatingActionButton.Mini"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/v_pause_dark_x24"
app:backgroundTint="?attr/colorPrimary"/>
app:backgroundTint="?attr/colorAccent"
style="@style/Widget.Design.FloatingActionButton.Mini"/>
<android.support.design.widget.FloatingActionButton
style="@style/Widget.Design.FloatingActionButton.Mini"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/v_delete_dark_x24"
app:backgroundTint="?attr/colorPrimary"/>
app:backgroundTint="?attr/colorAccent"
style="@style/Widget.Design.FloatingActionButton.Mini"/>
<android.support.design.widget.FloatingActionButton
style="@style/Widget.Design.FloatingActionButton.Mini"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/v_folder_move_dark_x24"
app:backgroundTint="?attr/colorPrimary"/>
app:backgroundTint="?attr/colorAccent"
style="@style/Widget.Design.FloatingActionButton.Mini"/>
<android.support.design.widget.FloatingActionButton
style="@style/Widget.Design.FloatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/v_close_dark_x24"/>
app:srcCompat="@drawable/v_close_dark_x24"
app:backgroundTint="?attr/colorPrimary"
style="@style/Widget.Design.FloatingActionButton"/>
</com.hippo.widget.FabLayout>
+7 -6
View File
@@ -44,24 +44,25 @@
android:paddingBottom="@dimen/corner_fab_margin">
<android.support.design.widget.FloatingActionButton
style="@style/Widget.Design.FloatingActionButton.Mini"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/v_delete_dark_x24"
app:backgroundTint="?attr/colorPrimary"/>
app:backgroundTint="?attr/colorAccent"
style="@style/Widget.Design.FloatingActionButton.Mini"/>
<android.support.design.widget.FloatingActionButton
style="@style/Widget.Design.FloatingActionButton.Mini"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/v_folder_move_dark_x24"
app:backgroundTint="?attr/colorPrimary"/>
app:backgroundTint="?attr/colorAccent"
style="@style/Widget.Design.FloatingActionButton.Mini"/>
<android.support.design.widget.FloatingActionButton
style="@style/Widget.Design.FloatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/v_close_dark_x24"/>
app:srcCompat="@drawable/v_close_dark_x24"
app:backgroundTint="?attr/colorPrimary"
style="@style/Widget.Design.FloatingActionButton"/>
</com.hippo.widget.FabLayout>
</FrameLayout>
@@ -94,6 +94,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/v_reply_dark_x24"
app:backgroundTint="?attr/colorPrimary"
style="@style/Widget.Design.FloatingActionButton"/>
</com.hippo.widget.FabLayout>
@@ -52,19 +52,20 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/v_go_to_dark_x24"
app:backgroundTint="?attr/colorPrimary"
app:backgroundTint="?attr/colorAccent"
style="@style/Widget.Design.FloatingActionButton.Mini"/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/v_refresh_dark_x24"
app:backgroundTint="?attr/colorPrimary"
app:backgroundTint="?attr/colorAccent"
style="@style/Widget.Design.FloatingActionButton.Mini"/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:backgroundTint="?attr/colorPrimary"
style="@style/Widget.Design.FloatingActionButton"/>
</com.hippo.widget.FabLayout>
+4 -1
View File
@@ -50,6 +50,8 @@
<string name="invalid_download_location">似乎下载路径不可用。请到重新设置下载路径。</string>
<string name="cellular_network_warning">正在使用移动网络</string>
<string name="error_bad_status_code">错误的状态码:%d</string>
<string name="error_timeout">超时</string>
<string name="error_unknown_host">未知主机</string>
@@ -196,7 +198,7 @@
<string name="no_torrents">没有种子</string>
<string name="torrents">种子</string>
<string name="favorited">已收藏</string>
<string name="unfavorited">未收藏</string>
<string name="not_favorited">未收藏</string>
<string name="add_favorites_dialog_title">添加收藏</string>
<string name="remember_favorite_collection">记住收藏夹</string>
<string name="add_to_favorite_success">已添加至收藏</string>
@@ -385,6 +387,7 @@
<string name="settings_eh_show_jpn_title_summary_off">显示默认标题。一般是英文标题</string>
<string name="settings_eh_filter">过滤</string>
<string name="settings_eh_filter_summary">过滤标题,上传者,标签和标签组</string>
<string name="settings_eh_cellular_network_warning">移动网络警告</string>
<string name="settings_read">阅读</string>
<string name="settings_read_screen_rotation">屏幕方向</string>
+4 -1
View File
@@ -50,6 +50,8 @@
<string name="invalid_download_location">似乎下載路徑不可用。請到重新設置下載路徑。</string>
<string name="cellular_network_warning">正在使用移動網絡</string>
<string name="error_bad_status_code">錯誤的狀態碼:%d</string>
<string name="error_timeout">超時</string>
<string name="error_unknown_host">未知主機</string>
@@ -196,7 +198,7 @@
<string name="no_torrents">沒有種子</string>
<string name="torrents">種子</string>
<string name="favorited">已收藏</string>
<string name="unfavorited">未收藏</string>
<string name="not_favorited">未收藏</string>
<string name="add_favorites_dialog_title">添加收藏</string>
<string name="remember_favorite_collection">記住收藏夾</string>
<string name="add_to_favorite_success">已添加至收藏</string>
@@ -385,6 +387,7 @@
<string name="settings_eh_show_jpn_title_summary_off">顯示默認標題。一般是英文標題</string>
<string name="settings_eh_filter">過濾</string>
<string name="settings_eh_filter_summary">過濾標題,上傳者,標籤和標籤組</string>
<string name="settings_eh_cellular_network_warning">移動網絡警告</string>
<string name="settings_read">閲讀</string>
<string name="settings_read_screen_rotation">屏幕方向</string>
+4 -1
View File
@@ -50,6 +50,8 @@
<string name="invalid_download_location">似乎下載路徑不可用。請到重新設定下載路徑。</string>
<string name="cellular_network_warning">正在使用行動網路</string>
<string name="error_bad_status_code">錯誤的狀態碼:%d</string>
<string name="error_timeout">超時</string>
<string name="error_unknown_host">未知主機</string>
@@ -196,7 +198,7 @@
<string name="no_torrents">沒有種子</string>
<string name="torrents">種子</string>
<string name="favorited">已收藏</string>
<string name="unfavorited">未收藏</string>
<string name="not_favorited">未收藏</string>
<string name="add_favorites_dialog_title">新增收藏</string>
<string name="remember_favorite_collection">記住收藏夾</string>
<string name="add_to_favorite_success">已新增至收藏</string>
@@ -385,6 +387,7 @@
<string name="settings_eh_show_jpn_title_summary_off">顯示預設標題。一般是英文標題</string>
<string name="settings_eh_filter">過濾</string>
<string name="settings_eh_filter_summary">過濾標題,上傳者,標籤和標籤組</string>
<string name="settings_eh_cellular_network_warning">行動網路警告</string>
<string name="settings_read">閱讀</string>
<string name="settings_read_screen_rotation">螢幕方向</string>
+1 -1
View File
@@ -65,7 +65,7 @@
<string name="pd_big_search" translatable="false">M20.46,14.65C21.86,16.15,20.31,18.6,18.32,17.87C19.78,17.57,20.79,16.37,20.46,14.65ZM4.32,17.87C6.32,18.6,7.86,16.17,6.46,14.65C6.79,16.38,5.78,17.55,4.32,17.87ZM16.87,4.3C16.6,3.56,15.87,3,15,3C13.7,3,12.7,4.24,13.1,5.58C14.2,5.18,15.44,4.48,16.87,4.31ZM24,16C24,18.76,21.76,21,19,21C14.96,21,14.84,16.88,12,16.88S9.04,21,5,21C2.24,21,0,18.76,0,16C0,13.87,1.53,11.43,3.94,7.18C5.84,3.81,8.69,5.92,10.76,6.58C11.54,6.85,12.41,6.88,13.24,6.58C15.3,5.92,18.14,3.81,20.06,7.18C22.46,11.43,24,13.88,24,16ZM8,16C8,14.35,6.65,13,5,13S2,14.35,2,16S3.35,19,5,19S8,17.65,8,16ZM13,14C13,13.45,12.55,13,12,13S11,13.45,11,14S11.45,15,12,15S13,14.55,13,14ZM22,16C22,14.35,20.65,13,19,13S16,14.35,16,16S17.35,19,19,19S22,17.65,22,16ZM9,3C8.14,3,7.4,3.55,7.13,4.3C8.56,4.48,9.79,5.2,10.9,5.58C11.3,4.24,10.3,3,9,3Z</string>
<string name="pd_big_history" translatable="false">M5.5,2H22V0H5C3.3,0,2,1.3,2,3V21C2,22.7,3.3,24,5,24H22V4H5.5C4.1,4,4.1,2,5.5,2ZM20,6V22H6V6H20M12.5,11.8V14.4L14.9,15.8L15.3,15.2L13.3,14V11.9M13.3,9.3C11.5,9.3,10,10.3,9.2,11.7L8,10.5V13.8H11.3L9.9,12.4C10.5,11.1,11.8,10.3,13.3,10.3C15.4,10.3,17.1,12,17.1,14.1S15.4,17.9,13.3,17.9C11.7,17.9,10.3,16.9,9.8,15.4H8.7C9.3,17.4,11.1,18.9,13.3,18.9C15.9,18.9,18.1,16.8,18.1,14.1C18,11.4,15.9,9.3,13.3,9.3Z</string>
<string name="pd_big_download" translatable="false">M0,19V24H24V19H0ZM16,22H15V21H16V22ZM19,22H18V21H19V22ZM22,22H21V21H22V22M15,11L15,0L9,0L9,11L5,11L12,18L19,11Z</string>
<string name="pd_big_weird_face" translatable="false">M12.9,21.3C11.3,19.4,10.5,18.3,8.6,17.1C7.5,16.4,6.6,15.4,5.9,14.4L6.4,13.9L6.4,13.9C8.9,15.9,11.2,16.2,15.8,16.2C15.8,16.2,17,17.4,18.2,18.8C21.1,22,16.1,25,12.9,21.3ZM10.9,21.9C5.9,21.4,2,17.1,2,12C2,6.5,6.5,2,12,2S22,6.5,22,12C22,14.2,21.3,16.2,20.1,17.8C20.6,18.4,20.9,19.1,21.1,19.8C22.9,17.7,24,15,24,12C24,5.4,18.6,0,12,0S0,5.4,0,12S5.4,24,12,24C12.3,24,12.6,24,12.9,24C12,23.3,11.6,22.8,10.9,21.9M8.5,10.7L7.2,12L6,10.8L7.3,9.5L6,8.2L7.2,7L8.5,8.3L9.8,7L11,8.2L9.7,9.5L11,10.8L9.8,12C9.8,12,8.5,10.7,8.5,10.7M15.5,6C13.6,6,12,7.6,12,9.5S13.6,13,15.5,13S19,11.4,19,9.5S17.4,6,15.5,6ZM15.5,11C14.7,11,14,10.3,14,9.5S14.7,8,15.5,8S17,8.7,17,9.5S16.3,11,15.5,11Z</string>
<string name="pd_big_weird_face" translatable="false">M12.9,21.3C11.3,19.4,10.5,18.3,8.6,17.1C7.5,16.4,6.6,15.4,5.9,14.4L6.4,13.9L6.4,13.9C8.9,15.9,11.2,16.2,15.8,16.2C15.8,16.2,17,17.4,18.2,18.8C21.1,22,16.1,25,12.9,21.3ZM10.9,21.9C5.9,21.4,2,17.1,2,12C2,6.5,6.5,2,12,2S22,6.5,22,12C22,14.2,21.3,16.2,20.1,17.8C20.6,18.4,20.9,19.1,21.1,19.8C22.9,17.7,24,15,24,12C24,5.4,18.6,0,12,0S0,5.4,0,12S5.4,24,12,24C12.3,24,12.6,24,12.9,24C12,23.3,11.6,22.8,10.9,21.9M15.5,10.7L14.2,12L13,10.8L14.3,9.5L13,8.2L14.2,7L15.5,8.3L16.8,7L18,8.2L16.7,9.5L18,10.8L16.8,12L15.5,10.7M8.5,6C6.6,6,5,7.6,5,9.5S6.6,13,8.5,13S12,11.4,12,9.5S10.4,6,8.5,6ZM8.5,11C7.7,11,7,10.3,7,9.5S7.7,8,8.5,8C9.3,8,10,8.7,10,9.5S9.3,11,8.5,11Z</string>
<string name="pd_big_filter" translatable="false">M22.9,2.84C24,0.44,15.08,0,12,0C9.06,0,0,0.43,1.1,2.84C1.6,3.94,10,15.76,10,15.76V21L14,24V15.76S22.4,3.96,22.9,2.84ZM12,1.94C16.25,1.94,20.15,2.51,20.15,3.17S16.25,4.34,12,4.34S3.97,3.8,3.97,3.17S7.76,1.94,12,1.94Z</string>
<string name="pd_slider_bubble" translatable="false">M13,0C20.2,0,26,5.9,26,13.2,26,16.9,24,20.8,18.7,26.1L13,32,7.2,26.2C2,20.8,0,16.9,0,13.3,0,5.9,5.8,0,13,0Z</string>
+5 -1
View File
@@ -66,6 +66,8 @@
<string name="invalid_download_location">It seems download location is not available. Please set it in Settings.</string>
<string name="cellular_network_warning">Connected to cellular networks</string>
<string name="error_status_code_400" translatable="false">Bad Request</string>
<string name="error_status_code_401" translatable="false">Unauthorized</string>
<string name="error_status_code_402" translatable="false">Payment Required</string>
@@ -239,7 +241,7 @@
<string name="no_torrents">No torrents</string>
<string name="torrents">Torrents</string>
<string name="favorited">Favorited</string>
<string name="unfavorited">Unfavorited</string>
<string name="not_favorited">Not favorited</string>
<string name="add_favorites_dialog_title">Add to favorites</string>
<string name="remember_favorite_collection">Remember favorite collection</string>
<string name="add_to_favorite_success">Added to favorites</string>
@@ -261,6 +263,7 @@
<string name="rating2">PAINFUL</string>
<string name="rating1">UNBEARABLE</string>
<string name="rating0">DISASTER</string>
<string name="rating_none" translatable="false">(´_ゝ`)</string>
<!-- Gallery Info -->
<string name="gallery_info">Gallery Info</string>
@@ -427,6 +430,7 @@
<string name="settings_eh_show_jpn_title_summary_off">Show default title. It is usually English title</string>
<string name="settings_eh_filter">Filter</string>
<string name="settings_eh_filter_summary">Filter by title, uploader, tag and tag namespace</string>
<string name="settings_eh_cellular_network_warning">Cellular network warning</string>
<string name="settings_read">Read</string>
<string name="settings_read_screen_rotation">Screen orientation</string>
+5
View File
@@ -97,4 +97,9 @@
android:summary="@string/settings_eh_filter_summary"
app:activity="com.hippo.ehviewer.ui.FilterActivity"/>
<com.hippo.preference.SwitchPreference
android:key="cellular_network_warning"
android:title="@string/settings_eh_cellular_network_warning"
android:defaultValue="false"/>
</PreferenceScreen>