Compare commits

...
104 Commits
Author SHA1 Message Date
seven332 6b5b961986 1.0.18 2017-01-25 13:22:09 +08:00
seven332 6a96035149 Avoid RecyclerView scrolling after detached 2017-01-25 13:19:23 +08:00
seven332 1ce035591a Fix GalleryPageParser 2017-01-25 00:13:55 +08:00
seven332 6cc78802ee 1.0.17 2017-01-24 19:41:23 +08:00
seven332 636c011c23 Rename XXX_G to XXX_E 2017-01-24 19:39:05 +08:00
seven332 92490ca1a6 e-hentai switched to HTTPS 2017-01-24 19:34:24 +08:00
seven332 b6a5d237ac Add EhUrl.getFixedPreviewThumbUrl() 2017-01-24 19:22:58 +08:00
seven332 8be0b5c588 Don't use jack anymore 2016-12-31 19:29:33 +08:00
seven332 fcbe129b6e Fix URL_PREFIX_THUMB_EX 2016-12-30 12:10:59 +08:00
seven332 befbcd6720 Add fix thumb url 2016-12-29 21:50:26 +08:00
seven332 ee5062d4c7 Add round icon 2016-12-19 00:38:26 +08:00
seven332 a4392523d6 1.0.16 2016-12-15 02:06:46 +08:00
seven332 b3371304bf Sync media store after saving image 2016-12-15 02:05:23 +08:00
seven332 38911c2d34 Be compatible with some bad share mechanism
Some apps need file path to share it, but it's not necessary at all.
2016-12-15 01:59:49 +08:00
seven332 6c5ad068d2 Update gradle tools and libraries 2016-12-15 01:30:32 +08:00
seven332 868521f19f Try to get image reload key more than once 2016-12-15 01:13:58 +08:00
seven332 c4cd965306 Add excluding japanese original
Eh site doesn't support it, but just modifying the cookie works fine.
2016-12-03 19:38:49 +08:00
seven332 639adaf7fa Close #201, list local favorites by favorited time 2016-10-29 00:05:18 +08:00
seven332 e174ee0b2c Ensure dao gen called 2016-10-22 00:42:41 +08:00
seven332 04da83f950 Set targetSdkVersion to 25 2016-10-22 00:16:06 +08:00
seven332 84a35e9283 1.0.15 2016-10-18 00:10:10 +08:00
seven332 a907db43be Update libraries 2016-10-18 00:06:09 +08:00
seven332 890be41aa5 Update gradle tool 2016-08-13 18:49:57 +08:00
seven332 f3db305cee Add https in intent-filter 2016-08-13 18:48:57 +08:00
seven332 4626ab1ec4 Update image search url 2016-07-31 19:27:59 +08:00
seven332 a44b070120 1.0.14 2016-07-28 14:28:23 +08:00
seven332 1760fb65e2 Use LinearLayout instead of android.support.v7.widget.ButtonBarLayout 2016-07-28 14:25:01 +08:00
seven332 47d28beddd 1.0.13 2016-07-28 00:17:39 +08:00
seven332 8d39829e54 Update libraries 2016-07-28 00:17:06 +08:00
seven332 2cb8319c91 Check download image size 2016-07-27 23:34:09 +08:00
seven332 27ca88f0c2 Use https for ex and forums 2016-07-27 23:32:31 +08:00
seven332 9aa033c31b Add https support for url parser 2016-07-27 23:27:27 +08:00
seven332 1f1d968766 Make error message different 2016-07-27 23:24:53 +08:00
seven332 3b8ba148dc Save temp share image to internal folder 2016-06-20 23:27:03 +08:00
seven332 5448bdf7bb Use FileProvider to share image
For apps targeting Android N, file:// URIs outside app is not supported any more.
2016-06-18 22:08:29 +08:00
seven332 e7cfd8831e Set targetSdkVersion to 24, upgrade libraries 2016-06-18 21:04:26 +08:00
seven332 148588e53a Show version name in about 2016-06-10 20:37:27 +08:00
seven332 cacfd58330 1.0.12 2016-06-09 21:14:23 +08:00
seven332 97cf075ffb Upgrade libraries 2016-06-09 21:10:21 +08:00
seven332 d93ce846e2 Remove item from decode queue when cancel request 2016-06-08 21:20:53 +08:00
seven332 7e45e379b3 Fix fragment class check 2016-06-08 20:43:21 +08:00
seven332 f3c90d46fd Remove AssertUtils 2016-06-08 20:31:47 +08:00
seven332 c80445e43a Upgrade libraries 2016-06-08 19:33:21 +08:00
seven332 4faa031ae1 Upgrade gradle tool 2016-06-07 17:55:58 +08:00
seven332 17bdb7cb93 Use Queue for decode list 2016-06-07 17:55:10 +08:00
seven332 d17f98f3e4 Upgrade GLGallery to 0.1.2 2016-06-03 01:31:34 +08:00
seven332 52bc260998 Start gallery provider before get start page 2016-06-01 18:58:44 +08:00
seven332 ebaba88cde Add GLGallery library 2016-05-31 00:01:05 +08:00
seven332 94c50b27bf Check existence of views in onAnimationEnd 2016-05-30 00:28:32 +08:00
seven332 b2cf4d1fb0 Check existence of index when clear pToken 2016-05-30 00:25:20 +08:00
seven332 b52f260c9e Avoid restore download null 2016-05-30 00:20:04 +08:00
seven332 b4fc856a51 Fix SpiderInfo read 2016-05-30 00:18:20 +08:00
seven332 e1b07b715f Add GLView library 2016-05-29 15:52:33 +08:00
seven332 1e434c09e6 Use webp image resources 2016-05-28 22:13:53 +08:00
seven332 7fb4ae682a Add compileOptions.incremental 2016-05-25 20:14:38 +08:00
seven332 f2f7821b55 Don't use TransitionDrawable when LoadImageView is not showing 2016-05-25 13:59:00 +08:00
seven332 02b5f6289e Run executeDaoGenerator after copyNotice 2016-05-24 01:30:12 +08:00
seven332 9293e92a99 Upgrade build tool and image library 2016-05-24 00:53:34 +08:00
seven332 ccd98ff36e Block new intent when SolidScene is shown 2016-05-19 16:16:48 +08:00
seven332 6c5cbd9f2f Fix for java6 2016-05-19 15:18:10 +08:00
seven332 4a7edf648b 1.0.11 2016-05-14 13:56:15 +08:00
seven332 cfc9411223 Clean up 2016-05-14 13:23:59 +08:00
seven332 05030e9bb6 Save separated memory information in crash file
app memory, app native memory, app max memory, system total memory
2016-05-14 12:54:38 +08:00
seven332 ab3fc7d842 Avoid create dir when loading thumb in download list 2016-05-14 12:45:02 +08:00
seven332 fb216a960b Lock drawer when suggestion list showing 2016-05-13 13:43:37 +08:00
seven332 c0fbdee61f Copy email address when click donate item 2016-05-13 02:12:10 +08:00
seven332 901c0ae3ec Disable zero rating to gallery 2016-05-12 14:53:46 +08:00
seven332 f727554afd Update libraries 2016-05-12 14:32:09 +08:00
seven332 b0a5666a6d Fix gallery restore
SpiderInfo has changed, but restore code was the old version
2016-05-12 01:22:31 +08:00
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
169 changed files with 2088 additions and 14729 deletions

No files matched your search

-2
View File
@@ -18,14 +18,12 @@ Windows
> git clone https://github.com/seven332/EhViewer
> cd EhViewer
> gradlew daogenerator:executeDaoGenerator
> gradlew app:assembleDebug
Linux
$ git clone https://github.com/seven332/EhViewer
$ cd EhViewer
$ ./gradlew daogenerator:executeDaoGenerator
$ ./gradlew app:assembleDebug
生成的 apk 文件在 app\build\outputs\apk 目录下
+32 -32
View File
@@ -1,26 +1,19 @@
import com.android.build.gradle.internal.tasks.DefaultAndroidTask
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "24.0.0 rc3"
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.hippo.ehviewer"
minSdkVersion 14
targetSdkVersion 23
versionCode 61
versionName "1.0.8"
targetSdkVersion 25
versionCode 71
versionName "1.0.18"
vectorDrawables.useSupportLibrary = true
resConfigs "zh", "zh-rCN", "zh-rHK", "zh-rTW"
jackOptions {
enabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
lintOptions {
@@ -44,10 +37,12 @@ android {
task copyNotice(type: Copy) {
from '../NOTICE.html'
into './src/main/assets'
finalizedBy ":daogenerator:executeDaoGenerator"
}
tasks.withType(AbstractCompile) {
compileTask -> compileTask.dependsOn copyNotice
// TODO What is jack task?
tasks.withType(DefaultAndroidTask) {
task -> task.dependsOn copyNotice
}
clean {
@@ -56,26 +51,31 @@ clean {
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:design:25.1.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:easyrecyclerview:0.1.0'
compile 'com.github.seven332:drawerLayout:0.1.0'
compile 'com.github.seven332:image:0.1.3'
compile 'com.github.seven332:okhttp:3.2.0-eh'
compile 'com.github.seven332:animator:0.1.0'
compile 'com.github.seven332:beerbelly:0.1.4'
compile 'com.github.seven332:conaco:0.1.5-eh'
compile 'com.github.seven332:drawerlayout:0.1.0'
compile 'com.github.seven332:easyrecyclerview:0.1.1'
compile 'com.github.seven332:glgallery:0.1.2'
compile 'com.github.seven332:glview:0.1.0'
compile 'com.github.seven332:glview-image:0.1.0'
compile 'com.github.seven332:hotspot:0.1.0'
compile 'com.github.seven332:image:0.1.12'
compile 'com.github.seven332:okhttp:3.5.0'
compile 'com.github.seven332:refreshlayout:0.1.0'
compile 'com.github.seven332:ripple:0.1.1'
compile 'com.github.seven332:ripple:0.1.2'
compile 'com.github.seven332:streampipe:0.1.0'
compile 'com.github.seven332:tuxiang:0.1.0'
compile 'com.github.seven332:unifile:0.1.3'
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 'com.github.seven332:tuxiang:0.1.2'
compile 'com.github.seven332:unifile:0.2.0'
compile 'com.github.seven332:yorozuya:0.1.2'
compile 'com.github.seven332:yorozuya-thread:0.1.1'
compile 'com.github.seven332:yorozuya-collect:0.1.4'
compile 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.9.2'
compile 'org.ccil.cowan.tagsoup:tagsoup:1.2.1'
compile 'org.greenrobot:greendao:2.2.0'
compile 'org.jsoup:jsoup:1.9.1'
compile 'org.jsoup:jsoup:1.9.2'
testCompile 'junit:junit:4.12'
}
+13 -1
View File
@@ -28,6 +28,7 @@
<application
android:name="com.hippo.ehviewer.EhApplication"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:allowBackup="true"
@@ -51,6 +52,7 @@
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="http"/>
<data android:scheme="https"/>
<data android:host="exhentai.org"/>
<data android:host="g.e-hentai.org"/>
<data android:host="lofi.e-hentai.org"/>
@@ -130,8 +132,18 @@
<service
android:name="com.hippo.ehviewer.download.DownloadService"
android:icon="@mipmap/ic_launcher"
android:label="@string/download_service_label"/>
<provider
android:name="com.hippo.content.FileProvider"
android:authorities="com.hippo.ehviewer.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths"/>
</provider>
</application>
</manifest>
@@ -37,7 +37,7 @@ import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
public class AppCompatPreferenceActivity extends PreferenceActivity implements AppCompatCallback,
public abstract class AppCompatPreferenceActivity extends PreferenceActivity implements AppCompatCallback,
TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider {
private AppCompatDelegate mDelegate;
@@ -0,0 +1,816 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.content;
import android.content.ClipData;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
import static org.xmlpull.v1.XmlPullParser.START_TAG;
/**
* FileProvider is a special subclass of {@link ContentProvider} that facilitates secure sharing
* of files associated with an app by creating a <code>content://</code> {@link Uri} for a file
* instead of a <code>file:///</code> {@link Uri}.
* <p>
* A content URI allows you to grant read and write access using
* temporary access permissions. When you create an {@link Intent} containing
* a content URI, in order to send the content URI
* to a client app, you can also call {@link Intent#setFlags(int) Intent.setFlags()} to add
* permissions. These permissions are available to the client app for as long as the stack for
* a receiving {@link android.app.Activity} is active. For an {@link Intent} going to a
* {@link android.app.Service}, the permissions are available as long as the
* {@link android.app.Service} is running.
* <p>
* In comparison, to control access to a <code>file:///</code> {@link Uri} you have to modify the
* file system permissions of the underlying file. The permissions you provide become available to
* <em>any</em> app, and remain in effect until you change them. This level of access is
* fundamentally insecure.
* <p>
* The increased level of file access security offered by a content URI
* makes FileProvider a key part of Android's security infrastructure.
* <p>
* This overview of FileProvider includes the following topics:
* </p>
* <ol>
* <li><a href="#ProviderDefinition">Defining a FileProvider</a></li>
* <li><a href="#SpecifyFiles">Specifying Available Files</a></li>
* <li><a href="#GetUri">Retrieving the Content URI for a File</li>
* <li><a href="#Permissions">Granting Temporary Permissions to a URI</a></li>
* <li><a href="#ServeUri">Serving a Content URI to Another App</a></li>
* </ol>
* <h3 id="ProviderDefinition">Defining a FileProvider</h3>
* <p>
* Since the default functionality of FileProvider includes content URI generation for files, you
* don't need to define a subclass in code. Instead, you can include a FileProvider in your app
* by specifying it entirely in XML. To specify the FileProvider component itself, add a
* <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></code>
* element to your app manifest. Set the <code>android:name</code> attribute to
* <code>android.support.v4.content.FileProvider</code>. Set the <code>android:authorities</code>
* attribute to a URI authority based on a domain you control; for example, if you control the
* domain <code>mydomain.com</code> you should use the authority
* <code>com.mydomain.fileprovider</code>. Set the <code>android:exported</code> attribute to
* <code>false</code>; the FileProvider does not need to be public. Set the
* <a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn"
* >android:grantUriPermissions</a> attribute to <code>true</code>, to allow you
* to grant temporary access to files. For example:
* <pre class="prettyprint">
*&lt;manifest&gt;
* ...
* &lt;application&gt;
* ...
* &lt;provider
* android:name="android.support.v4.content.FileProvider"
* android:authorities="com.mydomain.fileprovider"
* android:exported="false"
* android:grantUriPermissions="true"&gt;
* ...
* &lt;/provider&gt;
* ...
* &lt;/application&gt;
*&lt;/manifest&gt;</pre>
* <p>
* If you want to override any of the default behavior of FileProvider methods, extend
* the FileProvider class and use the fully-qualified class name in the <code>android:name</code>
* attribute of the <code>&lt;provider&gt;</code> element.
* <h3 id="SpecifyFiles">Specifying Available Files</h3>
* A FileProvider can only generate a content URI for files in directories that you specify
* beforehand. To specify a directory, specify the its storage area and path in XML, using child
* elements of the <code>&lt;paths&gt;</code> element.
* For example, the following <code>paths</code> element tells FileProvider that you intend to
* request content URIs for the <code>images/</code> subdirectory of your private file area.
* <pre class="prettyprint">
*&lt;paths xmlns:android="http://schemas.android.com/apk/res/android"&gt;
* &lt;files-path name="my_images" path="images/"/&gt;
* ...
*&lt;/paths&gt;
*</pre>
* <p>
* The <code>&lt;paths&gt;</code> element must contain one or more of the following child elements:
* </p>
* <dl>
* <dt>
* <pre class="prettyprint">
*&lt;files-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the <code>files/</code> subdirectory of your app's internal storage
* area. This subdirectory is the same as the value returned by {@link Context#getFilesDir()
* Context.getFilesDir()}.
* </dd>
* <dt>
* <pre>
*&lt;cache-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* <dt>
* <dd>
* Represents files in the cache subdirectory of your app's internal storage area. The root path
* of this subdirectory is the same as the value returned by {@link Context#getCacheDir()
* getCacheDir()}.
* </dd>
* <dt>
* <pre class="prettyprint">
*&lt;external-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the root of the external storage area. The root path of this subdirectory
* is the same as the value returned by
* {@link Environment#getExternalStorageDirectory() Environment.getExternalStorageDirectory()}.
* </dd>
* <dt>
* <pre class="prettyprint">
*&lt;external-files-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the root of your app's external storage area. The root path of this
* subdirectory is the same as the value returned by
* {@code Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)}.
* </dd>
* <dt>
* <pre class="prettyprint">
*&lt;external-cache-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the root of your app's external cache area. The root path of this
* subdirectory is the same as the value returned by
* {@link Context#getExternalCacheDir() Context.getExternalCacheDir()}.
* </dd>
* </dl>
* <p>
* These child elements all use the same attributes:
* </p>
* <dl>
* <dt>
* <code>name="<i>name</i>"</code>
* </dt>
* <dd>
* A URI path segment. To enforce security, this value hides the name of the subdirectory
* you're sharing. The subdirectory name for this value is contained in the
* <code>path</code> attribute.
* </dd>
* <dt>
* <code>path="<i>path</i>"</code>
* </dt>
* <dd>
* The subdirectory you're sharing. While the <code>name</code> attribute is a URI path
* segment, the <code>path</code> value is an actual subdirectory name. Notice that the
* value refers to a <b>subdirectory</b>, not an individual file or files. You can't
* share a single file by its file name, nor can you specify a subset of files using
* wildcards.
* </dd>
* </dl>
* <p>
* You must specify a child element of <code>&lt;paths&gt;</code> for each directory that contains
* files for which you want content URIs. For example, these XML elements specify two directories:
* <pre class="prettyprint">
*&lt;paths xmlns:android="http://schemas.android.com/apk/res/android"&gt;
* &lt;files-path name="my_images" path="images/"/&gt;
* &lt;files-path name="my_docs" path="docs/"/&gt;
*&lt;/paths&gt;
*</pre>
* <p>
* Put the <code>&lt;paths&gt;</code> element and its children in an XML file in your project.
* For example, you can add them to a new file called <code>res/xml/file_paths.xml</code>.
* To link this file to the FileProvider, add a
* <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">&lt;meta-data&gt;</a> element
* as a child of the <code>&lt;provider&gt;</code> element that defines the FileProvider. Set the
* <code>&lt;meta-data&gt;</code> element's "android:name" attribute to
* <code>android.support.FILE_PROVIDER_PATHS</code>. Set the element's "android:resource" attribute
* to <code>&#64;xml/file_paths</code> (notice that you don't specify the <code>.xml</code>
* extension). For example:
* <pre class="prettyprint">
*&lt;provider
* android:name="android.support.v4.content.FileProvider"
* android:authorities="com.mydomain.fileprovider"
* android:exported="false"
* android:grantUriPermissions="true"&gt;
* &lt;meta-data
* android:name="android.support.FILE_PROVIDER_PATHS"
* android:resource="&#64;xml/file_paths" /&gt;
*&lt;/provider&gt;
*</pre>
* <h3 id="GetUri">Generating the Content URI for a File</h3>
* <p>
* To share a file with another app using a content URI, your app has to generate the content URI.
* To generate the content URI, create a new {@link File} for the file, then pass the {@link File}
* to {@link #getUriForFile(Context, String, File) getUriForFile()}. You can send the content URI
* returned by {@link #getUriForFile(Context, String, File) getUriForFile()} to another app in an
* {@link android.content.Intent}. The client app that receives the content URI can open the file
* and access its contents by calling
* {@link android.content.ContentResolver#openFileDescriptor(Uri, String)
* ContentResolver.openFileDescriptor} to get a {@link ParcelFileDescriptor}.
* <p>
* For example, suppose your app is offering files to other apps with a FileProvider that has the
* authority <code>com.mydomain.fileprovider</code>. To get a content URI for the file
* <code>default_image.jpg</code> in the <code>images/</code> subdirectory of your internal storage
* add the following code:
* <pre class="prettyprint">
*File imagePath = new File(Context.getFilesDir(), "images");
*File newFile = new File(imagePath, "default_image.jpg");
*Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);
*</pre>
* As a result of the previous snippet,
* {@link #getUriForFile(Context, String, File) getUriForFile()} returns the content URI
* <code>content://com.mydomain.fileprovider/my_images/default_image.jpg</code>.
* <h3 id="Permissions">Granting Temporary Permissions to a URI</h3>
* To grant an access permission to a content URI returned from
* {@link #getUriForFile(Context, String, File) getUriForFile()}, do one of the following:
* <ul>
* <li>
* Call the method
* {@link Context#grantUriPermission(String, Uri, int)
* Context.grantUriPermission(package, Uri, mode_flags)} for the <code>content://</code>
* {@link Uri}, using the desired mode flags. This grants temporary access permission for the
* content URI to the specified package, according to the value of the
* the <code>mode_flags</code> parameter, which you can set to
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}, {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}
* or both. The permission remains in effect until you revoke it by calling
* {@link Context#revokeUriPermission(Uri, int) revokeUriPermission()} or until the device
* reboots.
* </li>
* <li>
* Put the content URI in an {@link Intent} by calling {@link Intent#setData(Uri) setData()}.
* </li>
* <li>
* Next, call the method {@link Intent#setFlags(int) Intent.setFlags()} with either
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} or
* {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} or both.
* </li>
* <li>
* Finally, send the {@link Intent} to
* another app. Most often, you do this by calling
* {@link android.app.Activity#setResult(int, android.content.Intent) setResult()}.
* <p>
* Permissions granted in an {@link Intent} remain in effect while the stack of the receiving
* {@link android.app.Activity} is active. When the stack finishes, the permissions are
* automatically removed. Permissions granted to one {@link android.app.Activity} in a client
* app are automatically extended to other components of that app.
* </p>
* </li>
* </ul>
* <h3 id="ServeUri">Serving a Content URI to Another App</h3>
* <p>
* There are a variety of ways to serve the content URI for a file to a client app. One common way
* is for the client app to start your app by calling
* {@link android.app.Activity#startActivityForResult(Intent, int, Bundle) startActivityResult()},
* which sends an {@link Intent} to your app to start an {@link android.app.Activity} in your app.
* In response, your app can immediately return a content URI to the client app or present a user
* interface that allows the user to pick a file. In the latter case, once the user picks the file
* your app can return its content URI. In both cases, your app returns the content URI in an
* {@link Intent} sent via {@link android.app.Activity#setResult(int, Intent) setResult()}.
* </p>
* <p>
* You can also put the content URI in a {@link android.content.ClipData} object and then add the
* object to an {@link Intent} you send to a client app. To do this, call
* {@link Intent#setClipData(ClipData) Intent.setClipData()}. When you use this approach, you can
* add multiple {@link android.content.ClipData} objects to the {@link Intent}, each with its own
* content URI. When you call {@link Intent#setFlags(int) Intent.setFlags()} on the {@link Intent}
* to set temporary access permissions, the same permissions are applied to all of the content
* URIs.
* </p>
* <p class="note">
* <strong>Note:</strong> The {@link Intent#setClipData(ClipData) Intent.setClipData()} method is
* only available in platform version 16 (Android 4.1) and later. If you want to maintain
* compatibility with previous versions, you should send one content URI at a time in the
* {@link Intent}. Set the action to {@link Intent#ACTION_SEND} and put the URI in data by calling
* {@link Intent#setData setData()}.
* </p>
* <h3 id="">More Information</h3>
* <p>
* To learn more about FileProvider, see the Android training class
* <a href="{@docRoot}training/secure-file-sharing/index.html">Sharing Files Securely with URIs</a>.
* </p>
*/
public class FileProvider extends ContentProvider {
private static final String[] COLUMNS = {
MediaStore.MediaColumns.DISPLAY_NAME,
MediaStore.MediaColumns.SIZE,
MediaStore.MediaColumns.DATA
};
private static final String
META_DATA_FILE_PROVIDER_PATHS = "android.support.FILE_PROVIDER_PATHS";
private static final String TAG_ROOT_PATH = "root-path";
private static final String TAG_FILES_PATH = "files-path";
private static final String TAG_CACHE_PATH = "cache-path";
private static final String TAG_EXTERNAL = "external-path";
private static final String TAG_EXTERNAL_FILES = "external-files-path";
private static final String TAG_EXTERNAL_CACHE = "external-cache-path";
private static final String ATTR_NAME = "name";
private static final String ATTR_PATH = "path";
private static final File DEVICE_ROOT = new File("/");
// @GuardedBy("sCache")
private static HashMap<String, PathStrategy> sCache = new HashMap<String, PathStrategy>();
private PathStrategy mStrategy;
/**
* The default FileProvider implementation does not need to be initialized. If you want to
* override this method, you must provide your own subclass of FileProvider.
*/
@Override
public boolean onCreate() {
return true;
}
/**
* After the FileProvider is instantiated, this method is called to provide the system with
* information about the provider.
*
* @param context A {@link Context} for the current component.
* @param info A {@link ProviderInfo} for the new provider.
*/
@Override
public void attachInfo(Context context, ProviderInfo info) {
super.attachInfo(context, info);
// Sanity check our security
if (info.exported) {
throw new SecurityException("Provider must not be exported");
}
if (!info.grantUriPermissions) {
throw new SecurityException("Provider must grant uri permissions");
}
mStrategy = getPathStrategy(context, info.authority);
}
/**
* Return a content URI for a given {@link File}. Specific temporary
* permissions for the content URI can be set with
* {@link Context#grantUriPermission(String, Uri, int)}, or added
* to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then
* {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and
* {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a
* <code>content</code> {@link Uri} for file paths defined in their <code>&lt;paths&gt;</code>
* meta-data element. See the Class Overview for more information.
*
* @param context A {@link Context} for the current component.
* @param authority The authority of a {@link FileProvider} defined in a
* {@code <provider>} element in your app's manifest.
* @param file A {@link File} pointing to the filename for which you want a
* <code>content</code> {@link Uri}.
* @return A content URI for the file.
* @throws IllegalArgumentException When the given {@link File} is outside
* the paths supported by the provider.
*/
public static Uri getUriForFile(Context context, String authority, File file) {
final PathStrategy strategy = getPathStrategy(context, authority);
return strategy.getUriForFile(file);
}
/**
* Use a content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file
* managed by the FileProvider.
* FileProvider reports the column names defined in {@link android.provider.MediaStore.MediaColumns}:
* <ul>
* <li>{@link android.provider.MediaStore.MediaColumns#DISPLAY_NAME}</li>
* <li>{@link android.provider.MediaStore.MediaColumns#SIZE}</li>
* <li>{@link android.provider.MediaStore.MediaColumns#DATA}</li>
* </ul>
* For more information, see
* {@link ContentProvider#query(Uri, String[], String, String[], String)
* ContentProvider.query()}.
*
* @param uri A content URI returned by {@link #getUriForFile}.
* @param projection The list of columns to put into the {@link Cursor}. If null all columns are
* included.
* @param selection Selection criteria to apply. If null then all data that matches the content
* URI is returned.
* @param selectionArgs An array of {@link java.lang.String}, containing arguments to bind to
* the <i>selection</i> parameter. The <i>query</i> method scans <i>selection</i> from left to
* right and iterates through <i>selectionArgs</i>, replacing the current "?" character in
* <i>selection</i> with the value at the current position in <i>selectionArgs</i>. The
* values are bound to <i>selection</i> as {@link java.lang.String} values.
* @param sortOrder A {@link java.lang.String} containing the column name(s) on which to sort
* the resulting {@link Cursor}.
* @return A {@link Cursor} containing the results of the query.
*
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
if (projection == null) {
projection = COLUMNS;
}
String[] cols = new String[projection.length];
Object[] values = new Object[projection.length];
int i = 0;
for (String col : projection) {
if (MediaStore.MediaColumns.DISPLAY_NAME.equals(col)) {
cols[i] = MediaStore.MediaColumns.DISPLAY_NAME;
values[i++] = file.getName();
} else if (MediaStore.MediaColumns.SIZE.equals(col)) {
cols[i] = MediaStore.MediaColumns.SIZE;
values[i++] = file.length();
} else if (MediaStore.MediaColumns.DATA.equals(col)) {
cols[i] = MediaStore.MediaColumns.DATA;
values[i++] = file.getPath();
}
}
cols = copyOf(cols, i);
values = copyOf(values, i);
final MatrixCursor cursor = new MatrixCursor(cols, 1);
cursor.addRow(values);
return cursor;
}
/**
* Returns the MIME type of a content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
*
* @param uri A content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @return If the associated file has an extension, the MIME type associated with that
* extension; otherwise <code>application/octet-stream</code>.
*/
@Override
public String getType(Uri uri) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
final int lastDot = file.getName().lastIndexOf('.');
if (lastDot >= 0) {
final String extension = file.getName().substring(lastDot + 1);
final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if (mime != null) {
return mime;
}
}
return "application/octet-stream";
}
/**
* By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must
* subclass FileProvider if you want to provide different functionality.
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException("No external inserts");
}
/**
* By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must
* subclass FileProvider if you want to provide different functionality.
*/
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException("No external updates");
}
/**
* Deletes the file associated with the specified content URI, as
* returned by {@link #getUriForFile(Context, String, File) getUriForFile()}. Notice that this
* method does <b>not</b> throw an {@link java.io.IOException}; you must check its return value.
*
* @param uri A content URI for a file, as returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @param selection Ignored. Set to {@code null}.
* @param selectionArgs Ignored. Set to {@code null}.
* @return 1 if the delete succeeds; otherwise, 0.
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
return file.delete() ? 1 : 0;
}
/**
* By default, FileProvider automatically returns the
* {@link ParcelFileDescriptor} for a file associated with a <code>content://</code>
* {@link Uri}. To get the {@link ParcelFileDescriptor}, call
* {@link android.content.ContentResolver#openFileDescriptor(Uri, String)
* ContentResolver.openFileDescriptor}.
*
* To override this method, you must provide your own subclass of FileProvider.
*
* @param uri A content URI associated with a file, as returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @param mode Access mode for the file. May be "r" for read-only access, "rw" for read and
* write access, or "rwt" for read and write access that truncates any existing file.
* @return A new {@link ParcelFileDescriptor} with which you can access the file.
*/
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
final int fileMode = modeToMode(mode);
return ParcelFileDescriptor.open(file, fileMode);
}
/**
* Return {@link PathStrategy} for given authority, either by parsing or
* returning from cache.
*/
private static PathStrategy getPathStrategy(Context context, String authority) {
PathStrategy strat;
synchronized (sCache) {
strat = sCache.get(authority);
if (strat == null) {
try {
strat = parsePathStrategy(context, authority);
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
} catch (XmlPullParserException e) {
throw new IllegalArgumentException(
"Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
}
sCache.put(authority, strat);
}
}
return strat;
}
/**
* Parse and return {@link PathStrategy} for given authority as defined in
* {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <meta-data>}.
*
* @see #getPathStrategy(Context, String)
*/
private static PathStrategy parsePathStrategy(Context context, String authority)
throws IOException, XmlPullParserException {
final SimplePathStrategy strat = new SimplePathStrategy(authority);
final ProviderInfo info = context.getPackageManager()
.resolveContentProvider(authority, PackageManager.GET_META_DATA);
final XmlResourceParser in = info.loadXmlMetaData(
context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
if (in == null) {
throw new IllegalArgumentException(
"Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
}
int type;
while ((type = in.next()) != END_DOCUMENT) {
if (type == START_TAG) {
final String tag = in.getName();
final String name = in.getAttributeValue(null, ATTR_NAME);
String path = in.getAttributeValue(null, ATTR_PATH);
File target = null;
if (TAG_ROOT_PATH.equals(tag)) {
target = DEVICE_ROOT;
} else if (TAG_FILES_PATH.equals(tag)) {
target = context.getFilesDir();
} else if (TAG_CACHE_PATH.equals(tag)) {
target = context.getCacheDir();
} else if (TAG_EXTERNAL.equals(tag)) {
target = Environment.getExternalStorageDirectory();
} else if (TAG_EXTERNAL_FILES.equals(tag)) {
File[] externalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);
if (externalFilesDirs.length > 0) {
target = externalFilesDirs[0];
}
} else if (TAG_EXTERNAL_CACHE.equals(tag)) {
File[] externalCacheDirs = ContextCompat.getExternalCacheDirs(context);
if (externalCacheDirs.length > 0) {
target = externalCacheDirs[0];
}
}
if (target != null) {
strat.addRoot(name, buildPath(target, path));
}
}
}
return strat;
}
/**
* Strategy for mapping between {@link File} and {@link Uri}.
* <p>
* Strategies must be symmetric so that mapping a {@link File} to a
* {@link Uri} and then back to a {@link File} points at the original
* target.
* <p>
* Strategies must remain consistent across app launches, and not rely on
* dynamic state. This ensures that any generated {@link Uri} can still be
* resolved if your process is killed and later restarted.
*
* @see SimplePathStrategy
*/
interface PathStrategy {
/**
* Return a {@link Uri} that represents the given {@link File}.
*/
public Uri getUriForFile(File file);
/**
* Return a {@link File} that represents the given {@link Uri}.
*/
public File getFileForUri(Uri uri);
}
/**
* Strategy that provides access to files living under a narrow whitelist of
* filesystem roots. It will throw {@link SecurityException} if callers try
* accessing files outside the configured roots.
* <p>
* For example, if configured with
* {@code addRoot("myfiles", context.getFilesDir())}, then
* {@code context.getFileStreamPath("foo.txt")} would map to
* {@code content://myauthority/myfiles/foo.txt}.
*/
static class SimplePathStrategy implements PathStrategy {
private final String mAuthority;
private final HashMap<String, File> mRoots = new HashMap<String, File>();
public SimplePathStrategy(String authority) {
mAuthority = authority;
}
/**
* Add a mapping from a name to a filesystem root. The provider only offers
* access to files that live under configured roots.
*/
public void addRoot(String name, File root) {
if (TextUtils.isEmpty(name)) {
throw new IllegalArgumentException("Name must not be empty");
}
try {
// Resolve to canonical path to keep path checking fast
root = root.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed to resolve canonical path for " + root, e);
}
mRoots.put(name, root);
}
@Override
public Uri getUriForFile(File file) {
String path;
try {
path = file.getCanonicalPath();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
}
// Find the most-specific root path
Map.Entry<String, File> mostSpecific = null;
for (Map.Entry<String, File> root : mRoots.entrySet()) {
final String rootPath = root.getValue().getPath();
if (path.startsWith(rootPath) && (mostSpecific == null
|| rootPath.length() > mostSpecific.getValue().getPath().length())) {
mostSpecific = root;
}
}
if (mostSpecific == null) {
throw new IllegalArgumentException(
"Failed to find configured root that contains " + path);
}
// Start at first char of path under root
final String rootPath = mostSpecific.getValue().getPath();
if (rootPath.endsWith("/")) {
path = path.substring(rootPath.length());
} else {
path = path.substring(rootPath.length() + 1);
}
// Encode the tag and path separately
path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/");
return new Uri.Builder().scheme("content")
.authority(mAuthority).encodedPath(path).build();
}
@Override
public File getFileForUri(Uri uri) {
String path = uri.getEncodedPath();
final int splitIndex = path.indexOf('/', 1);
final String tag = Uri.decode(path.substring(1, splitIndex));
path = Uri.decode(path.substring(splitIndex + 1));
final File root = mRoots.get(tag);
if (root == null) {
throw new IllegalArgumentException("Unable to find configured root for " + uri);
}
File file = new File(root, path);
try {
file = file.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
}
if (!file.getPath().startsWith(root.getPath())) {
throw new SecurityException("Resolved path jumped beyond configured root");
}
return file;
}
}
/**
* Copied from ContentResolver.java
*/
private static int modeToMode(String mode) {
int modeBits;
if ("r".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_ONLY;
} else if ("w".equals(mode) || "wt".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_TRUNCATE;
} else if ("wa".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_APPEND;
} else if ("rw".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_WRITE
| ParcelFileDescriptor.MODE_CREATE;
} else if ("rwt".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_WRITE
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_TRUNCATE;
} else {
throw new IllegalArgumentException("Invalid mode: " + mode);
}
return modeBits;
}
private static File buildPath(File base, String... segments) {
File cur = base;
for (String segment : segments) {
if (segment != null) {
cur = new File(cur, segment);
}
}
return cur;
}
private static String[] copyOf(String[] original, int newLength) {
final String[] result = new String[newLength];
System.arraycopy(original, 0, result, 0, newLength);
return result;
}
private static Object[] copyOf(Object[] original, int newLength) {
final Object[] result = new Object[newLength];
System.arraycopy(original, 0, result, 0, newLength);
return result;
}
}
@@ -21,12 +21,15 @@ import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Debug;
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;
@@ -35,7 +38,8 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
public class Crash {
public final class Crash {
private Crash() {}
@NonNull
private static String avoidNull(String str) {
@@ -65,14 +69,17 @@ public class Crash {
}
// Runtime
String topActivityClazzName = null;
String topSceneClazzName = null;
String topActivityClazzName = "null";
String topSceneClazzName = "null";
try {
Activity topActivity = ((EhApplication) context.getApplicationContext()).getTopActivity();
if (null != topActivity) {
topActivityClazzName = topActivity.getClass().getName();
if (topActivity instanceof StageActivity) {
topSceneClazzName = ((StageActivity) topActivity).getTopSceneClazzName();
Class<?> clazz = ((StageActivity) topActivity).getTopSceneClass();
if (clazz != null) {
topSceneClazzName = clazz.getName();
}
}
}
} catch (Throwable e) {
@@ -107,6 +114,10 @@ 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("\r\n");
fw.write("MEMORY_NATIVE=");fw.write(FileUtils.humanReadableByteCount(Debug.getNativeHeapAllocatedSize(), false));fw.write("\r\n");
fw.write("MEMORY_MAX=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getAppMaxMemory(), false));fw.write("\r\n");
fw.write("MEMORY_TOTAL=");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
@@ -449,7 +449,7 @@ public class EhDB {
public static synchronized List<GalleryInfo> getAllLocalFavorites() {
LocalFavoritesDao dao = sDaoSession.getLocalFavoritesDao();
List<LocalFavoriteInfo> list = dao.queryBuilder().orderAsc(LocalFavoritesDao.Properties.Time).list();
List<LocalFavoriteInfo> list = dao.queryBuilder().orderDesc(LocalFavoritesDao.Properties.Time).list();
List<GalleryInfo> result = new ArrayList<>();
result.addAll(list);
return result;
@@ -458,7 +458,7 @@ public class EhDB {
public static synchronized List<GalleryInfo> searchLocalFavorites(String query) {
query = SqlUtils.sqlEscapeString("%" + query+ "%");
LocalFavoritesDao dao = sDaoSession.getLocalFavoritesDao();
List<LocalFavoriteInfo> list = dao.queryBuilder().orderAsc(LocalFavoritesDao.Properties.Time)
List<LocalFavoriteInfo> list = dao.queryBuilder().orderDesc(LocalFavoritesDao.Properties.Time)
.where(LocalFavoritesDao.Properties.Title.like(query)).list();
List<GalleryInfo> result = new ArrayList<>();
result.addAll(list);
@@ -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;
}
@@ -29,15 +29,15 @@ import android.util.Log;
import com.hippo.ehviewer.client.EhConfig;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.FavListUrlBuilder;
import com.hippo.ehviewer.gallery.gl.GalleryView;
import com.hippo.ehviewer.gallery.gl.ImageView;
import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.glgallery.GalleryView;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.NumberUtils;
import junit.framework.Assert;
import java.io.File;
public class Settings {
@@ -300,6 +300,13 @@ public class Settings {
return getIntFromStr(KEY_THUMB_RESOLUTION, DEFAULT_THUMB_RESOLUTION);
}
private static final String KEY_FIX_THUMB_URL = "fix_thumb_url";
private static final boolean DEFAULT_FIX_THUMB_URL = false;
public static boolean getFixThumbUrl() {
return getBoolean(KEY_FIX_THUMB_URL, DEFAULT_FIX_THUMB_URL);
}
private static final String KEY_SHOW_JPN_TITLE = "show_jpn_title";
private static final boolean DEFAULT_SHOW_JPN_TITLE = false;
@@ -412,6 +419,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
********************/
@@ -427,7 +441,7 @@ public class Settings {
}
private static final String KEY_READING_DIRECTION = "reading_direction";
private static final int DEFAULT_READING_DIRECTION = GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT;
private static final int DEFAULT_READING_DIRECTION = GalleryView.LAYOUT_RIGHT_TO_LEFT;
@GalleryView.LayoutMode
public static int getReadingDirection() {
@@ -439,11 +453,11 @@ public class Settings {
}
private static final String KEY_PAGE_SCALING = "page_scaling";
private static final int DEFAULT_PAGE_SCALING = ImageView.SCALE_FIT;
private static final int DEFAULT_PAGE_SCALING = GalleryView.SCALE_FIT;
@ImageView.Scale
@GalleryView.ScaleMode
public static int getPageScaling() {
return ImageView.sanitizeScaleMode(getIntFromStr(KEY_PAGE_SCALING, DEFAULT_PAGE_SCALING));
return GalleryView.sanitizeScaleMode(getIntFromStr(KEY_PAGE_SCALING, DEFAULT_PAGE_SCALING));
}
public static void putPageScaling(int value) {
@@ -451,11 +465,11 @@ public class Settings {
}
private static final String KEY_START_POSITION = "start_position";
private static final int DEFAULT_START_POSITION = ImageView.START_POSITION_TOP_RIGHT;
private static final int DEFAULT_START_POSITION = GalleryView.START_POSITION_TOP_RIGHT;
@ImageView.StartPosition
@GalleryView.StartPosition
public static int getStartPosition() {
return ImageView.sanitizeStartPosition(getIntFromStr(KEY_START_POSITION, DEFAULT_START_POSITION));
return GalleryView.sanitizeStartPosition(getIntFromStr(KEY_START_POSITION, DEFAULT_START_POSITION));
}
public static void putStartPosition(int value) {
@@ -717,7 +731,7 @@ public class Settings {
}
public static void putFavCat(String[] value) {
AssertUtils.assertEquals(10, value.length);
Assert.assertEquals(10, value.length);
sSettingsPre.edit()
.putString(KEY_FAV_CAT_0, value[0])
.putString(KEY_FAV_CAT_1, value[1])
@@ -299,6 +299,7 @@ public class EhConfig implements Cloneable {
public static final int NAMESPACES_MALE = 0x40;
public static final int NAMESPACES_FEMALE = 0x80;
public static final String JAPANESE_ORIGINAL = "0";
public static final String JAPANESE_TRANSLATED = "1024";
public static final String JAPANESE_REWRITE = "2048";
public static final String ENGLISH_ORIGINAL = "1";
@@ -35,7 +35,7 @@ public class EhCookieStore extends CookieDBStore {
new Cookie.Builder()
.name(EhConfig.KEY_CONTENT_WARNING)
.value(EhConfig.CONTENT_WARNING_NOT_SHOW)
.domain(EhUrl.DOMAIN_G)
.domain(EhUrl.DOMAIN_E)
.path("/")
.expiresAt(Long.MAX_VALUE)
.build();
@@ -83,7 +83,7 @@ public class EhCookieStore extends CookieDBStore {
Object tag = request.tag();
String host = url.host();
boolean checkTips = domainMatch(host, EhUrl.DOMAIN_G);
boolean checkTips = domainMatch(host, EhUrl.DOMAIN_E);
boolean checkUconfig = (domainMatch(host, EhUrl.DOMAIN_E) || domainMatch(host, EhUrl.DOMAIN_EX)) && tag instanceof EhConfig;
if (checkTips || checkUconfig) {
@@ -45,7 +45,8 @@ import com.hippo.ehviewer.client.parser.TorrentParser;
import com.hippo.ehviewer.client.parser.VoteCommentParser;
import com.hippo.ehviewer.client.parser.WhatsHotParser;
import com.hippo.network.StatusCodeException;
import com.hippo.yorozuya.AssertUtils;
import junit.framework.Assert;
import org.json.JSONArray;
import org.json.JSONObject;
@@ -199,6 +200,10 @@ public class EhEngine {
}
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
return result;
}
@@ -447,6 +452,10 @@ public class EhEngine {
fillGalleryListByApi(task, okHttpClient, result.galleryInfoList);
}
for (GalleryInfo info : result.galleryInfoList) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
return result;
}
@@ -501,7 +510,7 @@ public class EhEngine {
public static Void addFavoritesRange(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long[] gidArray, String[] tokenArray, int dstCat) throws Exception {
AssertUtils.assertEqualsEx(gidArray.length, tokenArray.length);
Assert.assertEquals(gidArray.length, tokenArray.length);
for (int i = 0, n = gidArray.length; i < n; i++) {
addFavorites(task, okHttpClient, gidArray[i], tokenArray[i], dstCat, null);
}
@@ -554,6 +563,10 @@ public class EhEngine {
fillGalleryListByApi(task, okHttpClient, result.galleryInfoList);
}
for (GalleryInfo info : result.galleryInfoList) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
return result;
}
@@ -588,7 +601,7 @@ public class EhEngine {
public static List<GalleryInfo> getWhatsHot(@Nullable EhClient.Task task,
OkHttpClient okHttpClient) throws Exception {
String url = EhUrl.HOST_G;
String url = EhUrl.HOST_E;
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -618,6 +631,10 @@ public class EhEngine {
fillGalleryListByApi(task, okHttpClient, list);
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
return list;
}
@@ -801,6 +818,10 @@ public class EhEngine {
}
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
return result;
}
@@ -21,31 +21,40 @@ import android.support.annotation.NonNull;
import com.hippo.ehviewer.Settings;
import com.hippo.network.UrlBuilder;
import java.util.List;
import java.util.ListIterator;
import okhttp3.HttpUrl;
public class EhUrl {
public static final int SITE_G = 0;
public static final int SITE_E = 0;
public static final int SITE_EX = 1;
public static final String DOMAIN_EX = "exhentai.org";
public static final String DOMAIN_E = "e-hentai.org";
public static final String DOMAIN_G = "g.e-hentai.org";
public static final String DOMAIN_LOFI = "lofi.e-hentai.org";
public static final String HOST_E = "http://" + DOMAIN_E + "/";
public static final String HOST_EX = "http://" + DOMAIN_EX + "/";
public static final String HOST_G = "http://" + DOMAIN_G + "/";
public static final String HOST_EX = "https://" + DOMAIN_EX + "/";
public static final String HOST_E = "https://" + DOMAIN_E + "/";
public static final String API_SIGN_IN = "http://forums.e-hentai.org/index.php?act=Login&CODE=01";
public static final String API_SIGN_IN = "https://forums.e-hentai.org/index.php?act=Login&CODE=01";
public static final String API_G = HOST_G + "api.php";
public static final String API_E = HOST_E + "api.php";
public static final String API_EX = HOST_EX + "api.php";
public static final String URL_SIGN_IN = "http://forums.e-hentai.org/index.php?act=Login";
public static final String URL_REGISTER = "http://forums.e-hentai.org/index.php?act=Reg&CODE=00";
public static final String URL_FAVORITES_G = HOST_G + "favorites.php";
public static final String URL_IMAGE_SEARCH_E = "https://upload.e-hentai.org/image_lookup.php";
public static final String URL_IMAGE_SEARCH_EX = "https://exhentai.org/upload/image_lookup.php";
public static final String URL_SIGN_IN = "https://forums.e-hentai.org/index.php?act=Login";
public static final String URL_REGISTER = "https://forums.e-hentai.org/index.php?act=Reg&CODE=00";
public static final String URL_FAVORITES_E = HOST_E + "favorites.php";
public static final String URL_FAVORITES_EX = HOST_EX + "favorites.php";
public static final String URL_FORUMS = "https://forums.e-hentai.org/";
private static final String URL_PREFIX_THUMB_E = "https://ehgt.org/t/";
private static final String URL_PREFIX_THUMB_EX = "https://exhentai.org/t/";
public static String getGalleryDetailUrl(long gid, String token) {
return getGalleryDetailUrl(gid, token, 0, false);
}
@@ -53,8 +62,8 @@ public class EhUrl {
public static String getHost() {
switch (Settings.getGallerySite()) {
default:
case SITE_G:
return HOST_G;
case SITE_E:
return HOST_E;
case SITE_EX:
return HOST_EX;
}
@@ -63,8 +72,8 @@ public class EhUrl {
public static String getFavoritesUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_G:
return URL_FAVORITES_G;
case SITE_E:
return URL_FAVORITES_E;
case SITE_EX:
return URL_FAVORITES_EX;
}
@@ -73,8 +82,8 @@ public class EhUrl {
public static String getApiUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_G:
return API_G;
case SITE_E:
return API_E;
case SITE_EX:
return API_EX;
}
@@ -107,10 +116,50 @@ public class EhUrl {
public static String getImageSearchUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_G:
return "http://ul.e-hentai.org/image_lookup.php";
case SITE_E:
return URL_IMAGE_SEARCH_E;
case SITE_EX:
return "http://ul.exhentai.org/image_lookup.php";
return URL_IMAGE_SEARCH_EX;
}
}
public static String getThumbUrlPrefix() {
switch (Settings.getGallerySite()) {
default:
//case SITE_E:
return URL_PREFIX_THUMB_E;
//case SITE_EX:
// return URL_PREFIX_THUMB_EX;
}
}
public static String getFixedPreviewThumbUrl(String originUrl) {
HttpUrl url = HttpUrl.parse(originUrl);
if (url == null) return originUrl;
List<String> pathSegments = url.pathSegments();
if (pathSegments == null || pathSegments.size() < 3) return originUrl;
ListIterator<String> iterator = pathSegments.listIterator(pathSegments.size());
// The last segments, like
// 317a1a254cd9c3269e71b2aa2671fe8d28c91097-260198-640-480-png_250.jpg
if (!iterator.hasPrevious()) return originUrl;
String lastSegment = iterator.previous();
// The second last segments, like
// 7a
if (!iterator.hasPrevious()) return originUrl;
String secondLastSegment = iterator.previous();
// The third last segments, like
// 31
if (!iterator.hasPrevious()) return originUrl;
String thirdLastSegment = iterator.previous();
// Check path segments
if (lastSegment != null && secondLastSegment != null
&& thirdLastSegment != null
&& lastSegment.startsWith(thirdLastSegment)
&& lastSegment.startsWith(secondLastSegment, thirdLastSegment.length())) {
return getThumbUrlPrefix() + thirdLastSegment + "/" + secondLastSegment + "/" + lastSegment;
} else {
return originUrl;
}
}
}
@@ -22,7 +22,8 @@ import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.JsoupUtils;
import com.hippo.yorozuya.AssertUtils;
import junit.framework.Assert;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
@@ -53,7 +54,7 @@ public class FavoritesParser {
//noinspection ConstantConditions
Elements fps = ido.getElementsByClass("fp");
// Last one is "fp fps"
AssertUtils.assertEqualsEx(11, fps.size());
Assert.assertEquals(11, fps.size());
for (int i = 0; i < 10; i++) {
Element fp = fps.get(i);
@@ -20,6 +20,8 @@ import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryComment;
import com.hippo.ehviewer.client.data.GalleryDetail;
@@ -511,6 +513,9 @@ public class GalleryDetailParser {
String pageUrl = element.attr("href");
element = element.child(0);
String imageUrl = element.attr("src");
if (Settings.getFixThumbUrl()) {
imageUrl = EhUrl.getFixedPreviewThumbUrl(imageUrl);
}
int index = Integer.parseInt(element.attr("alt")) - 1;
largePreviewSet.addItem(index, imageUrl, pageUrl);
}
@@ -529,8 +534,13 @@ public class GalleryDetailParser {
LargePreviewSet largePreviewSet = new LargePreviewSet();
while (m.find()) {
largePreviewSet.addItem(ParserUtils.parseInt(m.group(2)) - 1,
ParserUtils.trim(m.group(3)), ParserUtils.trim(m.group(1)));
int index = ParserUtils.parseInt(m.group(2)) - 1;
String imageUrl = ParserUtils.trim(m.group(3));
String pageUrl = ParserUtils.trim(m.group(1));
if (Settings.getFixThumbUrl()) {
imageUrl = EhUrl.getFixedPreviewThumbUrl(imageUrl);
}
largePreviewSet.addItem(index, imageUrl, pageUrl);
}
if (largePreviewSet.size() == 0) {
@@ -29,8 +29,8 @@ import java.util.regex.Pattern;
*/
public final class GalleryDetailUrlParser {
public static final Pattern URL_PATTERN = Pattern.compile("http://(?:" +
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_G + "|" + EhUrl.DOMAIN_LOFI + ")/g/(\\d+)/(\\w+)");
public static final Pattern URL_PATTERN = Pattern.compile("https?://(?:" +
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_E + "|" + EhUrl.DOMAIN_LOFI + ")/g/(\\d+)/(\\w+)");
@Nullable
public static Result parse(String url) {
@@ -143,18 +143,18 @@ public class GalleryListParser {
// Title (required)
Element it5 = JsoupUtils.getElementByClass(e, "it5");
if (null == it5) {
Log.e(TAG, "Can't parse gallery info title");
Log.e(TAG, "Can't parse gallery info title, step 1");
return null;
}
Elements es = it5.children();
if (null == es || es.size() <= 0) {
Log.e(TAG, "Can't parse gallery info title");
Log.e(TAG, "Can't parse gallery info title, step 2");
return null;
}
Element a = es.get(0);
GalleryDetailUrlParser.Result result = GalleryDetailUrlParser.parse(a.attr("href"));
if (null == result) {
Log.e(TAG, "Can't parse gallery info title");
Log.e(TAG, "Can't parse gallery info title, step 3");
return null;
}
gi.gid = result.gid;
@@ -29,7 +29,7 @@ import java.net.URLDecoder;
public final class GalleryListUrlParser {
private static final String[] VALID_HOSTS = {EhUrl.DOMAIN_EX, EhUrl.DOMAIN_G, EhUrl.DOMAIN_LOFI};
private static final String[] VALID_HOSTS = {EhUrl.DOMAIN_EX, EhUrl.DOMAIN_E, EhUrl.DOMAIN_LOFI};
private static final String PATH_NORMAL = "/";
private static final String PATH_UPLOADER = "/uploader/";
@@ -26,7 +26,7 @@ import java.util.regex.Pattern;
public class GalleryPageParser {
private static final Pattern PATTERN_IMAGE_URL = Pattern.compile("<(?:/iframe|div id=\"i3\")[^>]*><a[^>]+><img[^>]*src=\"(.+?)\"");
private static final Pattern PATTERN_IMAGE_URL = Pattern.compile("<img[^>]*src=\"([^\"]+)\" style");
private static final Pattern PATTERN_SKIP_HATH_KEY = Pattern.compile("onclick=\"return nl\\('([^\\)]+)'\\)");
private static final Pattern PATTERN_ORIGIN_IMAGE_URL = Pattern.compile("<a href=\"([^\"]+)fullimg.php([^\"]+)\">");
@@ -26,8 +26,8 @@ import java.util.regex.Pattern;
*/
public final class GalleryPageUrlParser {
public static final Pattern URL_PATTERN = Pattern.compile("http://(?:" +
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_G + "|" + EhUrl.DOMAIN_LOFI + ")/s/(\\w+)/(\\d+)-(\\d+)");
public static final Pattern URL_PATTERN = Pattern.compile("https?://(?:" +
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_E + "|" + EhUrl.DOMAIN_LOFI + ")/s/(\\w+)/(\\d+)-(\\d+)");
public static Result parse(String url) {
if (url == null) {
@@ -23,7 +23,7 @@ import android.util.Log;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.FileUtils;
@@ -41,7 +41,7 @@ import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class DirGalleryProvider extends GalleryProvider implements Runnable {
public class DirGalleryProvider extends GalleryProvider2 implements Runnable {
private static final String TAG = DirGalleryProvider.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
@@ -22,13 +22,14 @@ import android.support.annotation.Nullable;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.spider.SpiderQueen;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.SimpleHandler;
import java.util.Locale;
public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.OnSpiderListener {
public class EhGalleryProvider extends GalleryProvider2 implements SpiderQueen.OnSpiderListener {
private final Context mContext;
private final GalleryInfo mGalleryInfo;
@@ -1,319 +0,0 @@
/*
* 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.ehviewer.gallery;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import com.hippo.beerbelly.LruCache;
import com.hippo.gl.glrenderer.GLCanvas;
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 {
public static final int STATE_WAIT = -1;
public static final int STATE_ERROR = -2;
// With dot
public static final String[] SUPPORT_IMAGE_EXTENSIONS = {
".jpg", // Joint Photographic Experts Group
".jpeg",
".png", // Portable Network Graphics
".gif", // Graphics Interchange Format
};
private final ConcurrentPool<NotifyTask> mNotifyTaskPool = new ConcurrentPool<>(5);
private volatile GalleryProviderListener mGalleryProviderListener;
private volatile GLRoot mGLRoot;
private final ImageCache mImageCache = new ImageCache();
private boolean mStarted = false;
@UiThread
public void start() {
OSUtils.checkMainLoop();
if (mStarted) {
throw new IllegalStateException("Can't start it twice");
}
mStarted = true;
}
@UiThread
public void stop() {
OSUtils.checkMainLoop();
mImageCache.close();
}
public void setGLRoot(GLRoot glRoot) {
mGLRoot = glRoot;
}
/**
* @return {@link #STATE_WAIT} for wait, 0 for empty
*/
public abstract int size();
public final void request(int index) {
ImageWrapper imageWrapper = mImageCache.get(index);
if (imageWrapper != null) {
notifyPageSucceed(index, imageWrapper);
} else {
onRequest(index);
}
}
public final void forceRequest(int index) {
onForceRequest(index);
}
protected abstract void onRequest(int index);
protected abstract void onForceRequest(int index);
public final void cancelRequest(int index) {
onCancelRequest(index);
}
protected abstract void onCancelRequest(int index);
public abstract String getError();
public int getStartPage() {
return 0;
}
/**
* @return without extension
*/
@NonNull
public abstract String getImageFilename(int index);
public abstract boolean save(int index, @NonNull UniFile file);
/**
* @param filename without extension
*/
@Nullable
public abstract UniFile save(int index, @NonNull UniFile dir, @NonNull String filename);
public void putStartPage(int page) {}
public void setGalleryProviderListener(GalleryProviderListener listener) {
mGalleryProviderListener = listener;
}
public void notifyDataChanged() {
notify(NotifyTask.TYPE_DATA_CHANGED, -1, 0.0f, null, null);
}
public void notifyDataChanged(int index) {
notify(NotifyTask.TYPE_DATA_CHANGED, index, 0.0f, null, null);
}
public void notifyPageWait(int index) {
notify(NotifyTask.TYPE_WAIT, index, 0.0f, null, null);
}
public void notifyPagePercent(int index, float percent) {
notify(NotifyTask.TYPE_PERCENT, index, percent, null, null);
}
public void notifyPageSucceed(int index, Image image) {
ImageWrapper imageWrapper = new ImageWrapper(image);
mImageCache.add(index, imageWrapper);
notifyPageSucceed(index, imageWrapper);
}
public void notifyPageSucceed(int index, ImageWrapper image) {
notify(NotifyTask.TYPE_SUCCEED, index, 0.0f, image, null);
}
public void notifyPageFailed(int index, String error) {
notify(NotifyTask.TYPE_FAILED, index, 0.0f, null, error);
}
private void notify(@NotifyTask.Type int type, int index, float percent, ImageWrapper image, String error) {
GalleryProviderListener listener = mGalleryProviderListener;
if (listener == null) {
return;
}
GLRoot glRoot = mGLRoot;
if (glRoot == null) {
return;
}
NotifyTask task = mNotifyTaskPool.pop();
if (task == null) {
task = new NotifyTask(listener, mNotifyTaskPool);
}
task.setData(type, index, percent, image, error);
glRoot.addOnGLIdleListener(task);
}
private static class NotifyTask implements GLRoot.OnGLIdleListener {
@IntDef({TYPE_DATA_CHANGED, NotifyTask.TYPE_WAIT, TYPE_PERCENT, TYPE_SUCCEED, TYPE_FAILED})
@Retention(RetentionPolicy.SOURCE)
public @interface Type {}
public static final int TYPE_DATA_CHANGED = 0;
public static final int TYPE_WAIT = 1;
public static final int TYPE_PERCENT = 2;
public static final int TYPE_SUCCEED = 3;
public static final int TYPE_FAILED = 4;
private final GalleryProviderListener mGalleryProviderListener;
private final ConcurrentPool<NotifyTask> mPool;
@Type
private int mType;
private int mIndex;
private float mPercent;
private ImageWrapper mImage;
private String mError;
public NotifyTask(GalleryProviderListener galleryProviderListener, ConcurrentPool<NotifyTask> pool) {
mGalleryProviderListener = galleryProviderListener;
mPool = pool;
}
public void setData(@Type int type, int index, float percent, ImageWrapper image, String error) {
mType = type;
mIndex = index;
mPercent = percent;
mImage = image;
mError = error;
}
@Override
public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
switch (mType) {
case TYPE_DATA_CHANGED:
if (mIndex < 0) {
mGalleryProviderListener.onDataChanged();
} else {
mGalleryProviderListener.onDataChanged(mIndex);
}
break;
case TYPE_WAIT:
mGalleryProviderListener.onPageWait(mIndex);
break;
case TYPE_PERCENT:
mGalleryProviderListener.onPagePercent(mIndex, mPercent);
break;
case TYPE_SUCCEED:
mGalleryProviderListener.onPageSucceed(mIndex, mImage);
break;
case TYPE_FAILED:
mGalleryProviderListener.onPageFailed(mIndex, mError);
break;
}
// Clean data
mImage = null;
mError = null;
// Push back
mPool.push(this);
return false;
}
}
private static class ImageCache extends LruCache<Integer, ImageWrapper> {
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));
}
public void add(Integer key, ImageWrapper value) {
if (value.obtain()) {
put(key, value);
}
}
@Override
protected int sizeOf(Integer key, ImageWrapper value) {
return value.getWidth() * value.getHeight() * 4;
}
@Override
protected void entryRemoved(boolean evicted, Integer key, ImageWrapper oldValue, ImageWrapper newValue) {
if (oldValue != null) {
oldValue.release();
}
}
}
}
@@ -0,0 +1,54 @@
/*
* 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.ehviewer.gallery;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.unifile.UniFile;
public abstract class GalleryProvider2 extends GalleryProvider {
// With dot
public static final String[] SUPPORT_IMAGE_EXTENSIONS = {
".jpg", // Joint Photographic Experts Group
".jpeg",
".png", // Portable Network Graphics
".gif", // Graphics Interchange Format
};
public int getStartPage() {
return 0;
}
public void putStartPage(int page) {}
/**
* @return without extension
*/
@NonNull
public abstract String getImageFilename(int index);
public abstract boolean save(int index, @NonNull UniFile file);
/**
* @param filename without extension
*/
@Nullable
public abstract UniFile save(int index, @NonNull UniFile dir, @NonNull String filename);
}
@@ -1,34 +0,0 @@
/*
* 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.ehviewer.gallery;
import com.hippo.image.ImageWrapper;
public interface GalleryProviderListener {
void onDataChanged();
void onPageWait(int index);
void onPagePercent(int index, float percent);
void onPageSucceed(int index, ImageWrapper image);
void onPageFailed(int index, String error);
void onDataChanged(int index);
}
@@ -23,7 +23,7 @@ import android.util.Log;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.StringUtils;
@@ -43,7 +43,7 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
public class ZipGalleryProvider extends GalleryProvider implements Runnable {
public class ZipGalleryProvider extends GalleryProvider2 implements Runnable {
private static final String TAG = ZipGalleryProvider.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
@@ -1,67 +0,0 @@
/*
* 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.ehviewer.gallery.gl;
import android.view.MotionEvent;
public class DownUpDetector {
public interface DownUpListener {
void onDown(MotionEvent e);
void onUp(MotionEvent e);
void onPointerDown(MotionEvent e);
void onPointerUp(MotionEvent e);
}
private boolean mStillDown;
private DownUpListener mListener;
public DownUpDetector(DownUpListener listener) {
mListener = listener;
}
private void setState(boolean down, MotionEvent e) {
if (down == mStillDown) return;
mStillDown = down;
if (down) {
mListener.onDown(e);
} else {
mListener.onUp(e);
}
}
public void onTouchEvent(MotionEvent ev) {
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
setState(true, ev);
break;
case MotionEvent.ACTION_POINTER_DOWN:
mListener.onPointerDown(ev);
break;
case MotionEvent.ACTION_UP:
mListener.onPointerUp(ev);
setState(false, ev);
break;
case MotionEvent.ACTION_CANCEL:
setState(false, ev);
break;
}
}
public boolean isDown() {
return mStillDown;
}
}
@@ -1,138 +0,0 @@
/*
* 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.ehviewer.gallery.gl;
import android.content.Context;
import android.hardware.SensorManager;
import android.view.ViewConfiguration;
import android.view.animation.Interpolator;
import com.hippo.gl.anim.Animation;
public abstract class Fling extends Animation {
private static final float DECELERATION_RATE = (float) (Math.log(0.78) / Math.log(0.9));
private static final float INFLEXION = 0.35f; // Tension lines cross at (INFLEXION, 1)
private static final float START_TENSION = 0.5f;
private static final float END_TENSION = 1.0f;
private static final float P1 = START_TENSION * INFLEXION;
private static final float P2 = 1.0f - END_TENSION * (1.0f - INFLEXION);
private static final float FLING_FRICTION = ViewConfiguration.getScrollFriction();
private static final int NB_SAMPLES = 100;
private static final float[] SPLINE_POSITION = new float[NB_SAMPLES + 1];
private static final float[] SPLINE_TIME = new float[NB_SAMPLES + 1];
private float mPhysicalCoeff;
static {
float x_min = 0.0f;
float y_min = 0.0f;
for (int i = 0; i < NB_SAMPLES; i++) {
final float alpha = (float) i / NB_SAMPLES;
float x_max = 1.0f;
float x, tx, coef;
while (true) {
x = x_min + (x_max - x_min) / 2.0f;
coef = 3.0f * x * (1.0f - x);
tx = coef * ((1.0f - x) * P1 + x * P2) + x * x * x;
if (Math.abs(tx - alpha) < 1E-5) break;
if (tx > alpha) x_max = x;
else x_min = x;
}
SPLINE_POSITION[i] = coef * ((1.0f - x) * START_TENSION + x) + x * x * x;
float y_max = 1.0f;
float y, dy;
while (true) {
y = y_min + (y_max - y_min) / 2.0f;
coef = 3.0f * y * (1.0f - y);
dy = coef * ((1.0f - y) * START_TENSION + y) + y * y * y;
if (Math.abs(dy - alpha) < 1E-5) break;
if (dy > alpha) y_max = y;
else y_min = y;
}
SPLINE_TIME[i] = coef * ((1.0f - y) * P1 + y * P2) + y * y * y;
}
SPLINE_POSITION[NB_SAMPLES] = SPLINE_TIME[NB_SAMPLES] = 1.0f;
}
private static final Interpolator FLING_INTERPOLATOR = new Interpolator() {
@Override
public float getInterpolation(float input) {
final int index = (int) (NB_SAMPLES * input);
float distanceCoef = 1.f;
float velocityCoef = 0.f;
if (index < NB_SAMPLES) {
final float t_inf = (float) index / NB_SAMPLES;
final float t_sup = (float) (index + 1) / NB_SAMPLES;
final float d_inf = SPLINE_POSITION[index];
final float d_sup = SPLINE_POSITION[index + 1];
velocityCoef = (d_sup - d_inf) / (t_sup - t_inf);
distanceCoef = d_inf + (input - t_inf) * velocityCoef;
}
return distanceCoef;
}
};
public Fling(Context context) {
final float ppi = context.getResources().getDisplayMetrics().density * 160.0f;
mPhysicalCoeff = SensorManager.GRAVITY_EARTH // g (m/s^2)
* 39.37f // inch/meter
* ppi
* 0.84f; // look and feel tuning
setInterpolator(FLING_INTERPOLATOR);
}
private double getSplineDeceleration(int velocity) {
return Math.log(INFLEXION * Math.abs(velocity) / (FLING_FRICTION * mPhysicalCoeff));
}
/* Returns the duration, expressed in milliseconds */
protected int getSplineFlingDuration(int velocity) {
final double l = getSplineDeceleration(velocity);
final double decelMinusOne = DECELERATION_RATE - 1.0;
return (int) (1000.0 * Math.exp(l / decelMinusOne));
}
protected double getSplineFlingDistance(int velocity) {
final double l = getSplineDeceleration(velocity);
final double decelMinusOne = DECELERATION_RATE - 1.0;
return FLING_FRICTION * mPhysicalCoeff * Math.exp(DECELERATION_RATE / decelMinusOne * l);
}
/**
* Modifies mDuration to the duration it takes to get from start to newFinal using the
* spline interpolation. The previous duration was needed to get to oldFinal.
**/
protected int adjustDuration(int start, int oldFinal, int newFinal, int duration) {
final int oldDistance = oldFinal - start;
final int newDistance = newFinal - start;
final float x = Math.abs((float) newDistance / oldDistance);
final int index = (int) (NB_SAMPLES * x);
if (index < NB_SAMPLES) {
final float x_inf = (float) index / NB_SAMPLES;
final float x_sup = (float) (index + 1) / NB_SAMPLES;
final float t_inf = SPLINE_TIME[index];
final float t_sup = SPLINE_TIME[index + 1];
final float timeCoef = t_inf + (x - x_inf) / (x_sup - x_inf) * (t_sup - t_inf);
duration *= timeCoef;
}
return duration;
}
}
@@ -1,188 +0,0 @@
/*
* 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.ehviewer.gallery.gl;
import android.content.Context;
import com.hippo.gl.glrenderer.BasicTexture;
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;
import com.hippo.gl.widget.GLLinearLayout;
import com.hippo.gl.widget.GLMovableTextView;
import com.hippo.gl.widget.GLProgressView;
import com.hippo.gl.widget.GLTextureView;
import com.hippo.yorozuya.LayoutUtils;
public class GalleryPageView extends GLFrameLayout {
public static final int INVALID_INDEX = -1;
private static final int INFO_INTERVAL = 24;
public static final float PROGRESS_GONE = -1.0f;
public static final float PROGRESS_INDETERMINATE = -2.0f;
private static final int PAGE_MIN_HEIGHT = 256;
private final ImageView mImage;
private final GLLinearLayout mInfo;
private final GLMovableTextView mPage;
private final GLTextureView mError;
private final GLProgressView mProgress;
private final int mPageMinHeight;
private int mIndex = INVALID_INDEX;
public GalleryPageView(Context context, MovableTextTexture pageTextTexture,
int progressColor, int progressSize) {
// Add image
mImage = new ImageView();
GravityLayoutParams glp = new GravityLayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
addComponent(mImage, glp);
// Add other panel
mInfo = new GLLinearLayout();
mInfo.setOrientation(GLLinearLayout.VERTICAL);
mInfo.setInterval(LayoutUtils.dp2pix(context, INFO_INTERVAL));
glp = new GravityLayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
glp.gravity = Gravity.CENTER;
addComponent(mInfo, glp);
// Add page
mPage = new GLMovableTextView();
mPage.setTextTexture(pageTextTexture);
GLLinearLayout.LayoutParams lp = new GLLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
mInfo.addComponent(mPage, lp);
// Add error
mError = new GLTextureView();
lp = new GLLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
mInfo.addComponent(mError, lp);
// Add progress
mProgress = new GLProgressView();
mProgress.setBgColor(GalleryView.BACKGROUND_COLOR);
mProgress.setColor(progressColor);
mProgress.setMinimumWidth(progressSize);
mProgress.setMinimumHeight(progressSize);
lp = new GLLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
mInfo.addComponent(mProgress, lp);
mPageMinHeight = LayoutUtils.dp2pix(context, PAGE_MIN_HEIGHT);
}
@Override
protected int getSuggestedMinimumHeight() {
// The height of the actual image may be smaller than mPageMinHeight.
// Set min height as 0 when the image is visible.
// For PageLayoutManager, min height is useless.
if (mImage.getVisibility() == VISIBLE) {
return 0;
} else {
return mPageMinHeight;
}
}
int getIndex() {
return mIndex;
}
void setIndex(int index) {
mIndex = index;
}
public void showImage() {
mImage.setVisibility(VISIBLE);
mInfo.setVisibility(GONE);
}
public void showInfo() {
// For image valid rect
mImage.setVisibility(INVISIBLE);
mInfo.setVisibility(VISIBLE);
}
private void unbindImage() {
ImageTexture texture = mImage.getImageTexture();
if (texture != null) {
mImage.setImageTexture(null);
texture.recycle();
}
}
public void setImage(ImageTexture imageTexture) {
unbindImage();
if (imageTexture != null) {
mImage.setImageTexture(imageTexture);
}
}
public void setPage(int page) {
mPage.setText(Integer.toString(page));
}
public void setProgress(float progress) {
if (progress == PROGRESS_GONE) {
mProgress.setVisibility(GONE);
} else if (progress == PROGRESS_INDETERMINATE) {
mProgress.setVisibility(VISIBLE);
mProgress.setIndeterminate(true);
} else {
mProgress.setVisibility(VISIBLE);
mProgress.setIndeterminate(false);
mProgress.setProgress(progress);
}
}
private void unbindError() {
Texture texture = mError.getTexture();
if (texture != null) {
mError.setTexture(null);
if (texture instanceof BasicTexture) {
((BasicTexture) texture).recycle();
}
}
}
public void setError(String error, GalleryView galleryView) {
unbindError();
if (error == null) {
mError.setVisibility(GONE);
} else {
mError.setVisibility(VISIBLE);
galleryView.bindErrorView(mError, error);
}
}
public ImageView getImageView() {
return mImage;
}
public boolean isLoaded() {
return mImage.getVisibility() == VISIBLE;
}
}
@@ -1,993 +0,0 @@
/*
* 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.ehviewer.gallery.gl;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
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.StringTexture;
import com.hippo.gl.glrenderer.Texture;
import com.hippo.gl.util.GalleryUtils;
import com.hippo.gl.view.AnimationTime;
import com.hippo.gl.view.GLRoot;
import com.hippo.gl.view.GLView;
import com.hippo.gl.widget.GLEdgeView;
import com.hippo.gl.widget.GLProgressView;
import com.hippo.gl.widget.GLTextureView;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.Pool;
import com.hippo.yorozuya.ResourcesUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class GalleryView extends GLView implements GestureRecognizer.Listener {
@IntDef({LAYOUT_MODE_LEFT_TO_RIGHT, LAYOUT_MODE_RIGHT_TO_LEFT, LAYOUT_MODE_TOP_TO_BOTTOM})
@Retention(RetentionPolicy.SOURCE)
public @interface LayoutMode {}
public static final int BACKGROUND_COLOR = 0xff212121;
private static final int PROGRESS_SIZE_IN_DP = 48;
public static final int LAYOUT_MODE_LEFT_TO_RIGHT = 0;
public static final int LAYOUT_MODE_RIGHT_TO_LEFT = 1;
public static final int LAYOUT_MODE_TOP_TO_BOTTOM = 2;
private static final float[] LEFT_AREA = {0.0f, 0.0f, 1.0f / 3.0f, 1f};
private static final float[] RIGHT_AREA = {2.0f / 3.0f, 0.0f, 1.0f, 1f};
private static final float[] MENU_AREA = {1.0f / 3.0f, 0.0f, 2.0f / 3.0f, 1.0f / 2.0f};
private static final float[] SLIDER_AREA = {1.0f / 3.0f, 1.0f / 2.0f, 2.0f / 3.0f, 1.0f};
private static final int METHOD_ON_SINGLE_TAP_UP = 0;
private static final int METHOD_ON_SINGLE_TAP_CONFIRMED = 1;
private static final int METHOD_ON_DOUBLE_TAP = 2;
private static final int METHOD_ON_DOUBLE_TAP_CONFIRMED = 3;
private static final int METHOD_ON_LONG_PRESS = 4;
private static final int METHOD_ON_SCROLL = 5;
private static final int METHOD_ON_FLING = 6;
private static final int METHOD_ON_SCALE_BEGIN = 7;
private static final int METHOD_ON_SCALE = 8;
private static final int METHOD_ON_SCALE_END = 9;
private static final int METHOD_ON_DOWN = 10;
private static final int METHOD_ON_UP = 11;
private static final int METHOD_ON_POINTER_DOWN = 12;
private static final int METHOD_ON_POINTER_UP = 13;
private static final int METHOD_SET_LAYOUT_MODE = 14;
private static final int METHOD_SET_CURRENT_PAGE = 15;
private static final int METHOD_PAGE_LEFT = 16;
private static final int METHOD_PAGE_RIGHT = 17;
private static final int METHOD_SET_SCALE_MODE = 18;
private static final int METHOD_SET_START_POSITION = 19;
private static final int METHOD_ON_ATTACH_TO_ROOT = 20;
private final Context mContext;
private MovableTextTexture mPageTextTexture;
private final GestureRecognizer mGestureRecognizer;
private Adapter mAdapter;
private PagerLayoutManager mPagerLayoutManager;
private ScrollLayoutManager mScrollLayoutManager;
@Nullable
private LayoutManager mLayoutManager;
private final Pool<GalleryPageView> mGalleryPageViewPool = new Pool<>(5);
private final GLEdgeView mEdgeView;
private GLProgressView mProgressCache;
private GLTextureView mErrorViewCache;
private final int mProgressColor;
private final int mProgressSize;
private final float mErrorSize;
private final int mErrorColor;
private boolean mEnableRequestFill = true;
private boolean mRequestFill = false;
private boolean mWillFill = false;
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();
private final Rect mMenuArea = new Rect();
private final Rect mSliderArea = new Rect();
private final String mDefaultErrorStr;
private final String mEmptyStr;
@LayoutMode
private int mLayoutMode = LAYOUT_MODE_RIGHT_TO_LEFT;
@ImageView.Scale
private int mScaleMode = ImageView.SCALE_FIT;
@ImageView.StartPosition
private int mStartPosition = ImageView.START_POSITION_TOP_LEFT;
private int mIndex;
private final Listener mListener;
private final List<Integer> mMethodList = new ArrayList<>(5);
private final List<Object[]> mArgsList = new ArrayList<>(5);
private final List<Integer> mMethodListTemp = new ArrayList<>(5);
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,
Listener listener, @LayoutMode int layoutMode, @ImageView.Scale int scaleMode,
@ImageView.StartPosition int startPosition, int startPage) {
mContext = context;
mAdapter = adapter;
mListener = listener;
mEdgeView = new GLEdgeView(context);
mGestureRecognizer = new GestureRecognizer(context, this);
adapter.setGalleryView(this);
mLayoutMode = layoutMode;
mScaleMode = scaleMode;
mStartPosition = startPosition;
mIndex = MathUtils.clamp(startPage, 0, Integer.MAX_VALUE);
mProgressColor = ResourcesUtils.getAttrColor(context, R.attr.colorPrimary);
mProgressSize = LayoutUtils.dp2pix(context, PROGRESS_SIZE_IN_DP);
mErrorSize = context.getResources().getDimension(R.dimen.text_large);
mErrorColor = context.getResources().getColor(R.color.red_500);
mDefaultErrorStr = context.getResources().getString(R.string.error_unknown);
mEmptyStr = context.getResources().getString(R.string.error_empty);
setBackgroundColor(BACKGROUND_COLOR);
}
private void ensurePagerLayoutManager() {
if (mPagerLayoutManager == null) {
mPagerLayoutManager = new PagerLayoutManager(mContext, this, mScaleMode, mStartPosition, 1.0f);
}
}
private void ensureScrollLayoutManager() {
if (mScrollLayoutManager == null) {
mScrollLayoutManager = new ScrollLayoutManager(mContext, this);
}
}
private void attachLayoutManager() {
if (null != mLayoutManager) {
return;
}
switch (mLayoutMode) {
case LAYOUT_MODE_LEFT_TO_RIGHT:
ensurePagerLayoutManager();
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_LEFT_TO_RIGHT);
mPagerLayoutManager.onAttach(mAdapter);
mPagerLayoutManager.setCurrentIndex(mIndex);
mAdapter = null;
mLayoutManager = mPagerLayoutManager;
break;
case LAYOUT_MODE_RIGHT_TO_LEFT:
ensurePagerLayoutManager();
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_RIGHT_TO_LEFT);
mPagerLayoutManager.onAttach(mAdapter);
mPagerLayoutManager.setCurrentIndex(mIndex);
mAdapter = null;
mLayoutManager = mPagerLayoutManager;
break;
case LAYOUT_MODE_TOP_TO_BOTTOM:
ensureScrollLayoutManager();
mScrollLayoutManager.onAttach(mAdapter);
mScrollLayoutManager.setCurrentIndex(mIndex);
mAdapter = null;
mLayoutManager = mScrollLayoutManager;
break;
}
requestFill();
}
private void detachLayoutManager() {
if (null == mLayoutManager) {
return;
}
mIndex = mLayoutManager.getInternalCurrentIndex();
mAdapter = mLayoutManager.onDetach();
mLayoutManager = null;
}
@SuppressWarnings("deprecation")
private void onAttachToRootInternal() {
if (null == mPageTextTexture) {
mPageTextTexture = MovableTextTexture.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'});
}
attachLayoutManager();
}
@Override
public void onAttachToRoot(GLRoot root) {
super.onAttachToRoot(root);
mEdgeView.onAttachToRoot(root);
postMethod(METHOD_ON_ATTACH_TO_ROOT);
}
@Override
public void onDetachFromRoot() {
// When detached, render() will not be called. So do it here
detachLayoutManager();
if (null != mPageTextTexture) {
mPageTextTexture.recycle();
mPageTextTexture = null;
}
super.onDetachFromRoot();
mEdgeView.onDetachFromRoot();
}
@LayoutMode
public static int sanitizeLayoutMode(int layoutMode) {
if (layoutMode != GalleryView.LAYOUT_MODE_LEFT_TO_RIGHT &&
layoutMode != GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT &&
layoutMode != GalleryView.LAYOUT_MODE_TOP_TO_BOTTOM) {
return GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT;
} else {
return layoutMode;
}
}
public int getLayoutMode() {
return mLayoutMode;
}
public int getCurrentIndex() {
return mCurrentIndex.get();
}
@Override
public void requestLayout() {
// Do not need requestLayout, because the size will not change
requestFill();
}
public void requestFill() {
if (mEnableRequestFill) {
mRequestFill = true;
if (!mWillFill) {
invalidate();
}
}
}
@Override
protected boolean dispatchTouchEvent(MotionEvent event) {
// Do not pass event to component, so handle event here
mGestureRecognizer.onTouchEvent(event);
return true;
}
GLEdgeView getEdgeView() {
return mEdgeView;
}
String getDefaultErrorStr() {
return mDefaultErrorStr;
}
String getEmptyStr() {
return mEmptyStr;
}
boolean isFirstScroll() {
boolean firstScroll = mFirstScroll;
mFirstScroll = false;
return firstScroll;
}
// Make sure method run in render thread to ensure thread safe
private void postMethod(int method, Object... args) {
synchronized (this) {
mMethodList.add(method);
mArgsList.add(args);
}
invalidate();
}
public void setLayoutMode(@LayoutMode int layoutMode) {
postMethod(METHOD_SET_LAYOUT_MODE, layoutMode);
}
public void setCurrentPage(int page) {
postMethod(METHOD_SET_CURRENT_PAGE, page);
}
public void pageLeft() {
postMethod(METHOD_PAGE_LEFT);
}
public void pageRight() {
postMethod(METHOD_PAGE_RIGHT);
}
public void setScaleMode(@ImageView.Scale int scaleMode) {
postMethod(METHOD_SET_SCALE_MODE, scaleMode);
}
public void setStartPosition(@ImageView.StartPosition int startPosition) {
postMethod(METHOD_SET_START_POSITION, startPosition);
}
@Override
public boolean onSingleTapUp(float x, float y) {
postMethod(METHOD_ON_SINGLE_TAP_UP, x, y);
return true;
}
@Override
public boolean onSingleTapConfirmed(float x, float y) {
postMethod(METHOD_ON_SINGLE_TAP_CONFIRMED, x, y);
return true;
}
@Override
public boolean onDoubleTap(float x, float y) {
postMethod(METHOD_ON_DOUBLE_TAP, x, y);
return true;
}
@Override
public boolean onDoubleTapConfirmed(float x, float y) {
postMethod(METHOD_ON_DOUBLE_TAP_CONFIRMED, x, y);
return true;
}
@Override
public void onLongPress(float x, float y) {
if (mLayoutManager != null && !mLayoutManager.isTapOrPressEnable()) {
return;
}
postMethod(METHOD_ON_LONG_PRESS, x, y);
}
@Override
public boolean onScroll(float dx, float dy, float totalX, float totalY, float x, float y) {
postMethod(METHOD_ON_SCROLL, dx, dy, totalX, totalY, x, y);
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
postMethod(METHOD_ON_FLING, velocityX, velocityY);
return true;
}
@Override
public boolean onScaleBegin(float focusX, float focusY) {
postMethod(METHOD_ON_SCALE_BEGIN, focusX, focusY);
return true;
}
@Override
public boolean onScale(float focusX, float focusY, float scale) {
postMethod(METHOD_ON_SCALE, focusX, focusY, scale);
return true;
}
@Override
public void onScaleEnd() {
postMethod(METHOD_ON_SCALE_END);
}
@Override
public void onDown(float x, float y) {
postMethod(METHOD_ON_DOWN, x, y);
}
@Override
public void onUp() {
postMethod(METHOD_ON_UP);
}
@Override
public void onPointerDown(float x, float y) {
postMethod(METHOD_ON_POINTER_DOWN, x, y);
}
@Override
public void onPointerUp() {
postMethod(METHOD_ON_POINTER_UP);
}
@Override
protected void onLayout(boolean changeSize, int left, int top, int right, int bottom) {
mEdgeView.layout(left, top, right, bottom);
fill();
if (changeSize) {
int width = right - left;
int height = bottom - top;
mLeftArea.set((int) (LEFT_AREA[0] * width), (int) (LEFT_AREA[1] * height),
(int) (LEFT_AREA[2] * width), (int) (LEFT_AREA[3] * height));
mRightArea.set((int) (RIGHT_AREA[0] * width), (int) (RIGHT_AREA[1] * height),
(int) (RIGHT_AREA[2] * width), (int) (RIGHT_AREA[3] * height));
mMenuArea.set((int) (MENU_AREA[0] * width), (int) (MENU_AREA[1] * height),
(int) (MENU_AREA[2] * width), (int) (MENU_AREA[3] * height));
mSliderArea.set((int) (SLIDER_AREA[0] * width), (int) (SLIDER_AREA[1] * height),
(int) (SLIDER_AREA[2] * width), (int) (SLIDER_AREA[3] * height));
}
}
@RenderThread
public void onDataChanged() {
GalleryUtils.assertInRenderThread();
if (mLayoutManager != null){
mLayoutManager.onDataChanged();
}
}
private void onSingleTapUpInternal(float x, float y) {
}
private void onSingleTapConfirmedInternal(float x, float y) {
if (mLayoutManager == null || !mLayoutManager.isTapOrPressEnable()) {
return;
}
if (mSliderArea.contains((int) x, (int) y)) {
mListener.onTapSliderArea();
} else if (mMenuArea.contains((int) x, (int) y)) {
mListener.onTapMenuArea();
} else if (mLeftArea.contains((int) x, (int) y)) {
mLayoutManager.onPageLeft();
} else if (mRightArea.contains((int) x, (int) y)) {
mLayoutManager.onPageRight();
}
}
private void onDoubleTapInternal(float x, float y) {
}
private void onDoubleTapConfirmedInternal(float x, float y) {
if (mScale) {
return;
}
if (mLayoutManager != null) {
mLayoutManager.onDoubleTapConfirmed(x, y);
}
}
private void onLongPressInternal(float x, float y) {
if (mScale) {
return;
}
if (mLayoutManager == null) {
return;
}
int index = mLayoutManager.getIndexUnder(x, y);
if (index == GalleryPageView.INVALID_INDEX) {
return;
}
mListener.onLongPressPage(index);
}
private void onScrollInternal(float dx, float dy, float totalX, float totalY, float x, float y) {
if (mScale) {
return;
}
mScroll = true;
if (mLayoutManager != null) {
mLayoutManager.onScroll(dx, dy, totalX, totalY, x, y);
}
}
private void onFlingInternal(float velocityX, float velocityY) {
if (mLayoutManager != null) {
mLayoutManager.onFling(velocityX, velocityY);
}
}
private void onScaleBeginInternal(float focusX, float focusY) {
onScaleInternal(focusX, focusY, 1.0f);
}
private void onScaleInternal(float focusX, float focusY, float scale) {
if (mScroll || (mLayoutManager != null && !mLayoutManager.canScale())) {
return;
}
mScale = true;
if (mLayoutManager != null) {
mLayoutManager.onScale(focusX, focusY, scale);
}
}
private void onScaleEndInternal() {
}
private void onDownInternal(float x, float y) {
mTouched = true;
mScale = false;
mScroll = false;
mFirstScroll = true;
if (mLayoutManager != null) {
mLayoutManager.onDown();
}
}
private void onUpInternal() {
mTouched = false;
if (mLayoutManager != null) {
mLayoutManager.onUp();
}
}
private void onPointerDownInternal(float x, float y) {
if (!mScroll && (mLayoutManager != null && mLayoutManager.canScale())) {
mScale = true;
}
}
private void onPointerUpInternal() {
}
private void setLayoutModeInternal(int layoutMode) {
if (mLayoutMode == layoutMode) {
return;
}
mLayoutMode = layoutMode;
if (mLayoutManager == null) {
return;
}
switch (mLayoutMode) {
case LAYOUT_MODE_LEFT_TO_RIGHT:
if (mLayoutManager == mPagerLayoutManager) {
// mPagerLayoutManager already attached, just change mode
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_LEFT_TO_RIGHT);
} else {
ensurePagerLayoutManager();
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_LEFT_TO_RIGHT);
int index = mLayoutManager.getInternalCurrentIndex();
mPagerLayoutManager.onAttach(mLayoutManager.onDetach());
mPagerLayoutManager.setCurrentIndex(index);
mLayoutManager = mPagerLayoutManager;
}
break;
case LAYOUT_MODE_RIGHT_TO_LEFT:
if (mLayoutManager == mPagerLayoutManager) {
// mPagerLayoutManager already attached, just change mode
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_RIGHT_TO_LEFT);
} else {
ensurePagerLayoutManager();
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_RIGHT_TO_LEFT);
int index = mLayoutManager.getInternalCurrentIndex();
mPagerLayoutManager.onAttach(mLayoutManager.onDetach());
mPagerLayoutManager.setCurrentIndex(index);
mLayoutManager = mPagerLayoutManager;
}
break;
case LAYOUT_MODE_TOP_TO_BOTTOM:
ensureScrollLayoutManager();
int index = mLayoutManager.getInternalCurrentIndex();
mScrollLayoutManager.onAttach(mLayoutManager.onDetach());
mScrollLayoutManager.setCurrentIndex(index);
mLayoutManager = mScrollLayoutManager;
break;
}
requestFill();
}
private void setCurrentPageInternal(int page) {
if (mLayoutManager != null) {
mLayoutManager.setCurrentIndex(page);
} else {
mIndex = page;
}
}
private void pageLeftInternal() {
if (mLayoutManager != null) {
mLayoutManager.onPageLeft();
}
}
private void pageRightInternal() {
if (mLayoutManager != null) {
mLayoutManager.onPageRight();
}
}
private void setScaleModeInternal(int scaleMode) {
mScaleMode = scaleMode;
if (mPagerLayoutManager != null) {
mPagerLayoutManager.setScaleMode(scaleMode);
}
}
private void setStartPositionInternal(int startPosition) {
mStartPosition = startPosition;
if (mPagerLayoutManager != null) {
mPagerLayoutManager.setStartPosition(startPosition);
}
}
@RenderThread
void forceFill() {
mRequestFill = true;
fill();
}
@RenderThread
private void fill() {
GalleryUtils.assertInRenderThread();
if (!mRequestFill) {
return;
}
// Disable request layout
mEnableRequestFill = false;
if (mLayoutManager != null) {
mLayoutManager.onFill();
}
mEnableRequestFill = true;
mRequestFill = false;
}
private void dispatchMethod() {
List<Integer> methodListTemp = mMethodListTemp;
List<Object[]> argsListTemp = mArgsListTemp;
synchronized (this) {
if (mMethodList.isEmpty()) {
return;
}
methodListTemp.addAll(mMethodList);
argsListTemp.addAll(mArgsList);
mMethodList.clear();
mArgsList.clear();
}
for (int i = 0, n = methodListTemp.size(); i < n; i++) {
int method = methodListTemp.get(i);
Object[] args = argsListTemp.get(i);
switch (method) {
case METHOD_ON_SINGLE_TAP_UP:
onSingleTapUpInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_SINGLE_TAP_CONFIRMED:
onSingleTapConfirmedInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_DOUBLE_TAP:
onDoubleTapInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_DOUBLE_TAP_CONFIRMED:
onDoubleTapConfirmedInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_LONG_PRESS:
onLongPressInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_SCROLL:
onScrollInternal((Float) args[0], (Float) args[1], (Float) args[2],
(Float) args[3], (Float) args[4], (Float) args[5]);
break;
case METHOD_ON_FLING:
onFlingInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_SCALE_BEGIN:
onScaleBeginInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_SCALE:
onScaleInternal((Float) args[0], (Float) args[1], (Float) args[2]);
break;
case METHOD_ON_SCALE_END:
onScaleEndInternal();
break;
case METHOD_ON_DOWN:
onDownInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_UP:
onUpInternal();
break;
case METHOD_ON_POINTER_DOWN:
onPointerDownInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_POINTER_UP:
onPointerUpInternal();
break;
case METHOD_SET_LAYOUT_MODE:
setLayoutModeInternal((Integer) args[0]);
break;
case METHOD_SET_CURRENT_PAGE:
setCurrentPageInternal((Integer) args[0]);
break;
case METHOD_PAGE_LEFT:
pageLeftInternal();
break;
case METHOD_PAGE_RIGHT:
pageRightInternal();
break;
case METHOD_SET_SCALE_MODE:
setScaleModeInternal((Integer) args[0]);
break;
case METHOD_SET_START_POSITION:
setStartPositionInternal((Integer) args[0]);
break;
case METHOD_ON_ATTACH_TO_ROOT:
onAttachToRootInternal();
break;
}
}
methodListTemp.clear();
argsListTemp.clear();
}
@Override
public void render(GLCanvas canvas) {
mWillFill = true;
int oldCurrentIndex = mCurrentIndex.get();
// Dispatch method
dispatchMethod();
long time = AnimationTime.get();
if (mLayoutManager != null && mLayoutManager.onUpdateAnimation(time)) {
invalidate();
}
fill();
mWillFill = false;
super.render(canvas);
mEdgeView.render(canvas);
int newCurrentIndex;
if (mLayoutManager != null) {
newCurrentIndex = mLayoutManager.getCurrentIndex();
} else {
newCurrentIndex = GalleryPageView.INVALID_INDEX;
}
mCurrentIndex.lazySet(newCurrentIndex);
if (oldCurrentIndex != newCurrentIndex) {
mListener.onUpdateCurrentIndex(newCurrentIndex);
}
}
@RenderThread
public GalleryPageView findPageByIndex(int id) {
if (!mPause && mLayoutManager != null) {
return mLayoutManager.findPageByIndex(id);
} else {
return null;
}
}
GalleryPageView obtainPage() {
GalleryPageView page = mGalleryPageViewPool.pop();
if (page == null) {
page = new GalleryPageView(mContext, mPageTextTexture, mProgressColor, mProgressSize);
}
return page;
}
void releasePage(GalleryPageView page) {
mGalleryPageViewPool.push(page);
}
/**
* Indeterminate GLProgressView
*/
GLProgressView obtainProgress() {
GLProgressView progress;
if (mProgressCache != null) {
progress = mProgressCache;
mProgressCache = null;
} else {
progress = new GLProgressView();
progress.setColor(mProgressColor);
progress.setBgColor(BACKGROUND_COLOR);
progress.setIndeterminate(true);
progress.setMinimumWidth(mProgressSize);
progress.setMinimumHeight(mProgressSize);
}
return progress;
}
/**
* @param progress Indeterminate GLProgressView
*/
void releaseProgress(GLProgressView progress) {
mProgressCache = progress;
}
GLTextureView obtainErrorView() {
GLTextureView errorView;
if (mErrorViewCache != null) {
errorView = mErrorViewCache;
mErrorViewCache = null;
} else {
errorView = new GLTextureView();
}
return errorView;
}
void unbindErrorView(GLTextureView errorView) {
Texture texture = errorView.getTexture();
if (texture != null) {
errorView.setTexture(null);
if (texture instanceof BasicTexture) {
((BasicTexture) texture).recycle();
}
}
}
void bindErrorView(GLTextureView errorView, String error) {
unbindErrorView(errorView);
Texture texture = StringTexture.newInstance(error, mErrorSize, mErrorColor);
errorView.setTexture(texture);
}
void releaseErrorView(GLTextureView errorView) {
unbindErrorView(errorView);
mErrorViewCache = errorView;
}
public static abstract class Adapter {
protected GalleryView mGalleryView;
private void setGalleryView(@NonNull GalleryView galleryView) {
mGalleryView = galleryView;
}
public void bind(GalleryPageView view, int index) {
onBind(view, index);
view.setIndex(index);
}
public void unbind(GalleryPageView view) {
onUnbind(view, view.getIndex());
view.setIndex(GalleryPageView.INVALID_INDEX);
}
public abstract void onBind(GalleryPageView view, int index);
public abstract void onUnbind(GalleryPageView view, int index);
/**
* @return Null for no error
*/
public abstract String getError();
public abstract int size();
}
public static abstract class LayoutManager {
protected GalleryView mGalleryView;
public LayoutManager(@NonNull GalleryView galleryView) {
mGalleryView = galleryView;
}
public abstract void onAttach(Adapter iterator);
public abstract Adapter onDetach();
public abstract void onFill();
public abstract void onDown();
public abstract void onUp();
public abstract void onDoubleTapConfirmed(float x, float y);
public abstract void onLongPress(float x, float y);
public abstract void onScroll(float dx, float dy, float totalX, float totalY, float x, float y);
public abstract void onFling(float velocityX, float velocityY);
public abstract boolean canScale();
public abstract void onScale(float focusX, float focusY, float scale);
public abstract boolean onUpdateAnimation(long time);
public abstract void onDataChanged();
public abstract void onPageLeft();
public abstract void onPageRight();
public abstract boolean isTapOrPressEnable();
public abstract GalleryPageView findPageByIndex(int index);
/**
* @return {@link GalleryPageView#INVALID_INDEX} for error
*/
public abstract int getCurrentIndex();
public abstract void setCurrentIndex(int index);
public abstract int getIndexUnder(float x, float y);
abstract int getInternalCurrentIndex();
protected void placeCenter(GLView view) {
int spec = GLView.MeasureSpec.makeMeasureSpec(GLView.LayoutParams.WRAP_CONTENT,
GLView.LayoutParams.WRAP_CONTENT);
view.measure(spec, spec);
int viewWidth = view.getMeasuredWidth();
int viewHeight = view.getMeasuredHeight();
int viewLeft = mGalleryView.getWidth() / 2 - viewWidth / 2;
int viewTop = mGalleryView.getHeight() / 2 - viewHeight / 2;
view.layout(viewLeft, viewTop, viewLeft + viewWidth, viewTop + viewHeight);
}
}
public interface Listener {
@RenderThread
void onUpdateCurrentIndex(int index);
@RenderThread
void onTapSliderArea();
@RenderThread
void onTapMenuArea();
@RenderThread
void onLongPressPage(int index);
}
}
@@ -1,174 +0,0 @@
/*
* 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.ehviewer.gallery.gl;
import android.content.Context;
import android.os.SystemClock;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
// This class aggregates three gesture detectors: GestureDetector,
// ScaleGestureDetector, and DownUpDetector.
public class GestureRecognizer {
@SuppressWarnings("unused")
private static final String TAG = "GestureRecognizer";
public interface Listener {
boolean onSingleTapUp(float x, float y);
boolean onSingleTapConfirmed(float x, float y);
boolean onDoubleTap(float x, float y);
boolean onDoubleTapConfirmed(float x, float y);
void onLongPress(float x, float y);
boolean onScroll(float dx, float dy, float totalX, float totalY, float x, float y);
/**
* @param velocityX Finger from top to bottom is positive
* @param velocityY Finger from left to right is positive
*/
boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);
boolean onScaleBegin(float focusX, float focusY);
boolean onScale(float focusX, float focusY, float scale);
void onScaleEnd();
void onDown(float x, float y);
void onUp();
void onPointerDown(float x, float y);
void onPointerUp();
}
private final GestureDetectorCompat mGestureDetector;
private final ScaleGestureDetector mScaleDetector;
private final DownUpDetector mDownUpDetector;
private final Listener mListener;
public GestureRecognizer(Context context, Listener listener) {
mListener = listener;
MyGestureListener gestureListener = new MyGestureListener();
mGestureDetector = new GestureDetectorCompat(context, gestureListener,
null /* ignoreMultitouch */);
mGestureDetector.setOnDoubleTapListener(gestureListener);
mScaleDetector = new ScaleGestureDetector(
context, new MyScaleListener());
mDownUpDetector = new DownUpDetector(new MyDownUpListener());
}
public void onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
mGestureDetector.onTouchEvent(event);
mDownUpDetector.onTouchEvent(event);
}
public boolean isDown() {
return mDownUpDetector.isDown();
}
public void cancelScale() {
long now = SystemClock.uptimeMillis();
MotionEvent cancelEvent = MotionEvent.obtain(
now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
mScaleDetector.onTouchEvent(cancelEvent);
cancelEvent.recycle();
}
private class MyGestureListener
extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return mListener.onSingleTapUp(e.getX(), e.getY());
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return mListener.onSingleTapConfirmed(e.getX(), e.getY());
}
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_UP) {
return mListener.onDoubleTapConfirmed(e.getX(), e.getY());
} else {
return true;
}
}
@Override
public boolean onDoubleTap(MotionEvent e) {
return mListener.onDoubleTap(e.getX(), e.getY());
}
@Override
public void onLongPress(MotionEvent e) {
mListener.onLongPress(e.getX(), e.getY());
}
@Override
public boolean onScroll(
MotionEvent e1, MotionEvent e2, float dx, float dy) {
return mListener.onScroll(
dx, dy, e2.getX() - e1.getX(), e2.getY() - e1.getY(), e2.getX(), e2.getY());
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return mListener.onFling(e1, e2, velocityX, velocityY);
}
}
private class MyScaleListener
extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return mListener.onScaleBegin(
detector.getFocusX(), detector.getFocusY());
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
return mListener.onScale(detector.getFocusX(),
detector.getFocusY(), detector.getScaleFactor());
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
mListener.onScaleEnd();
}
}
private class MyDownUpListener implements DownUpDetector.DownUpListener {
@Override
public void onDown(MotionEvent e) {
mListener.onDown(e.getX(), e.getY());
}
@Override
public void onUp(MotionEvent e) {
mListener.onUp();
}
@Override
public void onPointerDown(MotionEvent e) {
mListener.onPointerDown(e.getX(), e.getY());
}
@Override
public void onPointerUp(MotionEvent e) {
mListener.onPointerUp();
}
}
}
@@ -1,618 +0,0 @@
/*
* 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.ehviewer.gallery.gl;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.IntDef;
import com.hippo.gl.anim.AlphaAnimation;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.gl.glrenderer.ImageTexture;
import com.hippo.gl.glrenderer.Texture;
import com.hippo.gl.view.GLView;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.MathUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
public class ImageView extends GLView implements ImageTexture.Callback {
@IntDef({SCALE_ORIGIN, SCALE_FIT_WIDTH, SCALE_FIT_HEIGHT, SCALE_FIT, SCALE_FIXED})
@Retention(RetentionPolicy.SOURCE)
public @interface Scale {}
@IntDef({START_POSITION_TOP_LEFT, START_POSITION_TOP_RIGHT, START_POSITION_BOTTOM_LEFT,
START_POSITION_BOTTOM_RIGHT, START_POSITION_CENTER})
@Retention(RetentionPolicy.SOURCE)
public @interface StartPosition {}
// TODO adjust scale max and min according to image size and screen size
private static final float SCALE_MIN = 1 / 10.0f;
private static final float SCALE_MAX = 10.0f;
public static final int SCALE_ORIGIN = 0;
public static final int SCALE_FIT_WIDTH = 1;
public static final int SCALE_FIT_HEIGHT = 2;
public static final int SCALE_FIT = 3;
public static final int SCALE_FIXED = 4;
public static final int START_POSITION_TOP_LEFT = 0;
public static final int START_POSITION_TOP_RIGHT = 1;
public static final int START_POSITION_BOTTOM_LEFT = 2;
public static final int START_POSITION_BOTTOM_RIGHT = 3;
public static final int START_POSITION_CENTER = 4;
private static final long ALPHA_ANIMATION_DURING = 300L;
private ImageTexture mImageTexture;
private int mTextureWidth;
private int mTextureHeight;
private final RectF mDst = new RectF();
private final RectF mSrcActual = new RectF();
private final RectF mDstActual = new RectF();
private final Rect mValidRect = new Rect();
private int mScaleMode = SCALE_FIT;
private int mStartPosition = START_POSITION_TOP_RIGHT;
private float mScaleValue = 1.0f;
private float mScale = 1.0f;
private boolean mScaleOffsetDirty = true;
private boolean mPositionInRootDirty = true;
private final AlphaAnimation mAlphaAnimation;
public ImageView() {
mAlphaAnimation = new AlphaAnimation(0.0f, 1.0f);
mAlphaAnimation.setDuration(ALPHA_ANIMATION_DURING);
mAlphaAnimation.setInterpolator(AnimationUtils.FAST_SLOW_INTERPOLATOR);
}
@Scale
public static int sanitizeScaleMode(int scaleMode) {
if (scaleMode != SCALE_ORIGIN &&
scaleMode != SCALE_FIT_WIDTH &&
scaleMode != SCALE_FIT_HEIGHT &&
scaleMode != SCALE_FIT &&
scaleMode != SCALE_FIXED) {
return SCALE_FIT;
} else {
return scaleMode;
}
}
@StartPosition
public static int sanitizeStartPosition(int startPosition) {
if (startPosition != START_POSITION_TOP_LEFT &&
startPosition != START_POSITION_TOP_RIGHT &&
startPosition != START_POSITION_BOTTOM_LEFT &&
startPosition != START_POSITION_BOTTOM_RIGHT &&
startPosition != START_POSITION_CENTER) {
return START_POSITION_TOP_RIGHT;
} else {
return startPosition;
}
}
@Override
protected int getSuggestedMinimumWidth() {
return Math.max(super.getSuggestedMinimumWidth(),
mImageTexture == null ? 0 : mTextureWidth);
}
@Override
protected int getSuggestedMinimumHeight() {
return Math.max(super.getSuggestedMinimumHeight(),
mImageTexture == null ? 0 : mTextureHeight);
}
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
if (mImageTexture == null) {
super.onMeasure(widthSpec, heightSpec);
} else {
float ratio = (float) mTextureWidth / mTextureHeight;
int widthSize = MeasureSpec.getSize(widthSpec);
int heightSize = MeasureSpec.getSize(heightSpec);
int widthMode = MeasureSpec.getMode(widthSpec);
int heightMode = MeasureSpec.getMode(heightSpec);
int measureWidth = -1;
int measureHeight = -1;
if (widthMode == MeasureSpec.EXACTLY) {
measureWidth = widthSize;
if (heightMode == MeasureSpec.EXACTLY) {
measureHeight = heightSize;
} else {
measureHeight = (int) (widthSize / ratio);
if (heightMode == MeasureSpec.AT_MOST) {
measureHeight = Math.min(measureHeight, heightSize);
}
}
} else if (heightMode == MeasureSpec.EXACTLY) {
measureHeight = heightSize;
measureWidth = (int) (heightSize * ratio);
if (widthMode == MeasureSpec.AT_MOST) {
measureWidth = Math.min(measureWidth, widthSize);
}
}
if (measureWidth == -1 || measureHeight == -1) {
super.onMeasure(widthSpec, heightSpec);
} else {
setMeasuredSize(measureWidth, measureHeight);
}
}
}
@Override
protected void onSizeChanged(int newW, int newH, int oldW, int oldH) {
mScaleOffsetDirty = true;
mPositionInRootDirty = true;
}
@Override
protected void onPositionInRootChanged(int x, int y, int oldX, int oldY) {
mPositionInRootDirty = true;
if (mImageTexture != null) {
getValidRect(mValidRect);
if (!mValidRect.isEmpty()) {
mImageTexture.start();
} else {
mImageTexture.stop();
}
}
}
public void getScaleDefault(float[] scaleDefault) {
if (mImageTexture == null) {
return;
}
scaleDefault[0] = 1.0f;
scaleDefault[1] = (float) getWidth() / mTextureWidth;
scaleDefault[2] = (float) getHeight() / mTextureHeight;
scaleDefault[3] = Math.max(scaleDefault[1], scaleDefault[2]) * 2;
scaleDefault[0] = MathUtils.clamp(scaleDefault[0], SCALE_MIN, SCALE_MAX);
scaleDefault[1] = MathUtils.clamp(scaleDefault[1], SCALE_MIN, SCALE_MAX);
scaleDefault[2] = MathUtils.clamp(scaleDefault[2], SCALE_MIN, SCALE_MAX);
scaleDefault[3] = MathUtils.clamp(scaleDefault[3], SCALE_MIN, SCALE_MAX);
Arrays.sort(scaleDefault);
}
public void setImageTexture(ImageTexture imageTexture) {
// Remove callback
if (mImageTexture != null) {
mImageTexture.setCallback(null);
}
int oldTextureWidth = mTextureWidth;
int oldTextureHeight = mTextureHeight;
mImageTexture = imageTexture;
if (imageTexture != null) {
imageTexture.setCallback(this);
mTextureWidth = imageTexture.getWidth();
mTextureHeight = imageTexture.getHeight();
// Avoid zero and negative
if (mTextureWidth <= 0) {
mTextureWidth = 1;
}
if (mTextureHeight <= 0) {
mTextureHeight = 1;
}
// Start alpha animation, do not show animation for image has no valid rect
getValidRect(mValidRect);
if (!mValidRect.isEmpty()) {
startAnimation(mAlphaAnimation, true);
}
} else {
mTextureWidth = 1;
mTextureHeight = 1;
}
mScaleOffsetDirty = true;
mPositionInRootDirty = true;
if (oldTextureWidth != mTextureWidth || oldTextureHeight != mTextureHeight) {
requestLayout();
}
}
public ImageTexture getImageTexture() {
return mImageTexture;
}
public boolean isLoaded() {
return mImageTexture != null;
}
public boolean canFlingVertically() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return false;
}
}
return mDst.top < 0.0f || mDst.bottom > getHeight();
}
public boolean canFlingHorizontally() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return false;
}
}
return mDst.left < 0.0f || mDst.right > getWidth();
}
public boolean canFling() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return false;
}
}
return mDst.left < 0.0f || mDst.top < 0.0f || mDst.right > getWidth() || mDst.bottom > getHeight();
}
public int getMaxDx() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return 0;
}
}
return Math.max(0, -(int) mDst.left);
}
public int getMinDx() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return 0;
}
}
return Math.min(0, getWidth() - (int) mDst.right);
}
public int getMaxDy() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return 0;
}
}
return Math.max(0, -(int) mDst.top);
}
public int getMinDy() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return 0;
}
}
return Math.min(0, getHeight() - (int) mDst.bottom);
}
public float getScale() {
return mScale;
}
/**
* If target is shorter then screen, make it in screen center. If target is
* longer then parent, make sure target fill parent over
*/
private void adjustPosition() {
RectF dst = mDst;
int screenWidth = getWidth();
int screenHeight = getHeight();
float targetWidth = dst.width();
float targetHeight = dst.height();
if (targetWidth > screenWidth) {
float fixXOffset = dst.left;
if (fixXOffset > 0) {
dst.left -= fixXOffset;
dst.right -= fixXOffset;
} else if ((fixXOffset = screenWidth - dst.right) > 0) {
dst.left += fixXOffset;
dst.right += fixXOffset;
}
} else {
float left = (screenWidth - targetWidth) / 2;
dst.offsetTo(left, dst.top);
}
if (targetHeight > screenHeight) {
float fixYOffset = dst.top;
if (fixYOffset > 0) {
dst.top -= fixYOffset;
dst.bottom -= fixYOffset;
} else if ((fixYOffset = screenHeight - dst.bottom) > 0) {
dst.top += fixYOffset;
dst.bottom += fixYOffset;
}
} else {
float top = (screenHeight - targetHeight) / 2;
dst.offsetTo(dst.left, top);
}
}
public void setScaleOffset(@Scale int scaleMode, @StartPosition int startPosition, float scaleValue) {
mScaleMode = scaleMode;
mStartPosition = startPosition;
mScaleValue = scaleValue;
int screenWidth = getWidth();
int screenHeight = getHeight();
if (mImageTexture == null || screenWidth == 0 || screenHeight == 0) {
mScaleOffsetDirty = true;
return;
}
int textureWidth = mTextureWidth;
int textureHeight = mTextureHeight;
// Set scale
float targetWidth;
float targetHeight;
switch (scaleMode) {
case SCALE_ORIGIN:
mScale = 1.0f;
targetWidth = textureWidth;
targetHeight = textureHeight;
break;
case SCALE_FIT_WIDTH:
mScale = (float) screenWidth / textureWidth;
targetWidth = screenWidth;
targetHeight = textureHeight * mScale;
break;
case SCALE_FIT_HEIGHT:
mScale = (float) screenHeight / textureHeight;
targetWidth = textureWidth * mScale;
targetHeight = screenHeight;
break;
case SCALE_FIT:
float scaleX = (float) screenWidth / textureWidth;
float scaleY = (float) screenHeight / textureHeight;
if (scaleX < scaleY) {
mScale = scaleX;
targetWidth = screenWidth;
targetHeight = textureHeight * scaleX;
} else {
mScale = scaleY;
targetWidth = textureWidth * scaleY;
targetHeight = screenHeight;
break;
}
break;
case SCALE_FIXED:
default:
mScale = scaleValue;
targetWidth = textureWidth * scaleValue;
targetHeight = textureHeight * scaleValue;
break;
}
// adjust scale, not too big, not too small
if (mScale < SCALE_MIN) {
mScale = SCALE_MIN;
targetWidth = textureWidth * SCALE_MIN;
targetHeight = textureHeight * SCALE_MIN;
} else if (mScale > SCALE_MAX) {
mScale = SCALE_MAX;
targetWidth = textureWidth * SCALE_MAX;
targetHeight = textureHeight * SCALE_MAX;
}
// Set mDst.left and mDst.right
RectF dst = mDst;
switch (startPosition) {
case START_POSITION_TOP_LEFT:
dst.left = 0;
dst.top = 0;
break;
case START_POSITION_TOP_RIGHT:
dst.left = screenWidth - targetWidth;
dst.top = 0;
break;
case START_POSITION_BOTTOM_LEFT:
dst.left = 0;
dst.top = screenHeight - targetHeight;
break;
case START_POSITION_BOTTOM_RIGHT:
dst.left = screenWidth - targetWidth;
dst.top = screenHeight - targetHeight;
break;
case START_POSITION_CENTER:
default:
dst.left = (screenWidth - targetWidth) / 2;
dst.top = (screenHeight - targetHeight) / 2;
break;
}
// Set mDst.right and mDst.bottom
dst.right = dst.left + targetWidth;
dst.bottom = dst.top + targetHeight;
// adjust position
adjustPosition();
mScaleOffsetDirty = false;
mPositionInRootDirty = true;
}
public void scroll(int dx, int dy, int[] remain) {
// Only work after layout
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
}
if (mScaleOffsetDirty) {
remain[0] = dx;
remain[1] = dy;
return;
}
RectF dst = mDst;
int screenWidth = getWidth();
int screenHeight = getHeight();
float targetWidth = dst.width();
float targetHeight = dst.height();
if (targetWidth > screenWidth) {
dst.left -= dx;
dst.right -= dx;
float fixXOffset = dst.left;
if (fixXOffset > 0) {
dst.left -= fixXOffset;
dst.right -= fixXOffset;
remain[0] = -(int) fixXOffset;
} else if ((fixXOffset = screenWidth - dst.right) > 0) {
dst.left += fixXOffset;
dst.right += fixXOffset;
remain[0] = (int) fixXOffset;
} else {
remain[0] = 0;
}
} else {
remain[0] = dx;
}
if (targetHeight > screenHeight) {
dst.top -= dy;
dst.bottom -= dy;
float fixYOffset = dst.top;
if (fixYOffset > 0) {
dst.top -= fixYOffset;
dst.bottom -= fixYOffset;
remain[1] = -(int) fixYOffset;
} else if ((fixYOffset = screenHeight - dst.bottom) > 0) {
dst.top += fixYOffset;
dst.bottom += fixYOffset;
remain[1] = (int) fixYOffset;
} else {
remain[1] = 0;
}
} else {
remain[1] = dy;
}
if (dx != remain[0] || dy != remain[1]) {
mPositionInRootDirty = true;
invalidate();
}
}
public void scale(float focusX, float focusY, float scale) {
// Only work after layout
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
}
if (mScaleOffsetDirty) {
return;
}
if ((mScale == SCALE_MAX && scale >= 1.0f) || (mScale == SCALE_MIN && scale < 1.0f)) {
return;
}
float newScale = mScale * scale;
newScale = MathUtils.clamp(newScale, SCALE_MIN, SCALE_MAX);
mScale = newScale;
RectF dst = mDst;
float left = (focusX - ((focusX - dst.left) * scale));
float top = (focusY - ((focusY - dst.top) * scale));
dst.set(left, top,
(left + (mImageTexture.getWidth() * newScale)),
(top + (mImageTexture.getHeight() * newScale)));
// adjust position
adjustPosition();
mPositionInRootDirty = true;
invalidate();
}
private void applyPositionInRoot() {
int width = mImageTexture.getWidth();
int height = mImageTexture.getHeight();
RectF dst = mDst;
RectF dstActual = mDstActual;
RectF srcActual = mSrcActual;
dstActual.set(dst);
getValidRect(mValidRect);
if (dstActual.intersect(mValidRect.left, mValidRect.top, mValidRect.right, mValidRect.bottom)) {
srcActual.left = MathUtils.lerp(0, width,
MathUtils.delerp(dst.left, dst.right, dstActual.left));
srcActual.right = MathUtils.lerp(0, width,
MathUtils.delerp(dst.left, dst.right, dstActual.right));
srcActual.top = MathUtils.lerp(0, height,
MathUtils.delerp(dst.top, dst.bottom, dstActual.top));
srcActual.bottom = MathUtils.lerp(0, height,
MathUtils.delerp(dst.top, dst.bottom, dstActual.bottom));
} else {
// Can't be seen, set src and dst empty
srcActual.setEmpty();
dstActual.setEmpty();
}
mPositionInRootDirty = false;
}
@Override
public void onRender(GLCanvas canvas) {
Texture texture = mImageTexture;
if (texture == null) {
return;
}
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
}
if (mPositionInRootDirty) {
applyPositionInRoot();
}
if (!mSrcActual.isEmpty()) {
texture.draw(canvas, mSrcActual, mDstActual);
}
}
@Override
public void invalidateImageTexture(ImageTexture who) {
invalidate();
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -31,6 +31,7 @@ import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhEngine;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.download.DownloadManager;
import com.hippo.ehviewer.spider.SpiderInfo;
import com.hippo.ehviewer.spider.SpiderQueen;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.IOUtils;
@@ -88,13 +89,15 @@ public class RestoreDownloadPreference extends TaskPreference {
InputStream is = null;
try {
is = siFile.openInputStream();
// Skip start page
IOUtils.readAsciiLine(is);
long gid = Long.parseLong(IOUtils.readAsciiLine(is));
SpiderInfo spiderInfo = SpiderInfo.read(is);
if (spiderInfo == null) {
return null;
}
long gid = spiderInfo.gid;
if (mManager.containDownloadInfo(gid)) {
return null;
}
String token = IOUtils.readAsciiLine(is);
String token = spiderInfo.token;
RestoreItem restoreItem = new RestoreItem();
restoreItem.gid = gid;
restoreItem.token = token;
@@ -0,0 +1,57 @@
/*
* 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.ehviewer.preference;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.preference.Preference;
import android.util.AttributeSet;
import com.hippo.ehviewer.R;
public class VersionPreference extends Preference {
public VersionPreference(Context context) {
super(context);
init(context);
}
public VersionPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public VersionPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
setTitle(R.string.settings_about_version);
String version;
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
version = context.getString(R.string.error_unknown);
}
setSummary(version);
}
}
@@ -27,7 +27,7 @@ import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhCacheKeyFactory;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.gallery.GalleryProvider;
import com.hippo.ehviewer.gallery.GalleryProvider2;
import com.hippo.io.UniFileInputStreamPipe;
import com.hippo.io.UniFileOutputStreamPipe;
import com.hippo.streampipe.InputStreamPipe;
@@ -169,7 +169,7 @@ public final class SpiderDen {
@Nullable
private static UniFile findImageFile(UniFile dir, int index) {
for (String extension : GalleryProvider.SUPPORT_IMAGE_EXTENSIONS) {
for (String extension : GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS) {
String filename = generateImageFilename(index, extension);
UniFile file = dir.findFile(filename);
if (file != null) {
@@ -193,10 +193,10 @@ public final class SpiderDen {
* @param extension with dot
*/
private String fixExtension(String extension) {
if (Utilities.contain(GalleryProvider.SUPPORT_IMAGE_EXTENSIONS, extension)) {
if (Utilities.contain(GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS, extension)) {
return extension;
} else {
return GalleryProvider.SUPPORT_IMAGE_EXTENSIONS[0];
return GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS[0];
}
}
@@ -275,8 +275,8 @@ public final class SpiderDen {
}
boolean result = false;
for (int i = 0, n = GalleryProvider.SUPPORT_IMAGE_EXTENSIONS.length; i < n; i++) {
String filename = generateImageFilename(index, GalleryProvider.SUPPORT_IMAGE_EXTENSIONS[i]);
for (int i = 0, n = GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS.length; i < n; i++) {
String filename = generateImageFilename(index, GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS[i]);
UniFile file = dir.subFile(filename);
if (file != null) {
result |= file.delete();
@@ -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,16 +35,18 @@ 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;
long gid = -1;
String token = null;
int pages = -1;
int previewPages = -1;
int previewPerPage = -1;
SparseArray<String> pTokenMap = null;
public int startPage = 0;
public long gid = -1;
public String token = null;
public int pages = -1;
public int previewPages = -1;
public int previewPerPage = -1;
public SparseArray<String> pTokenMap = null;
public static SpiderInfo read(@Nullable UniFile file) {
if (file == null) {
@@ -80,6 +83,18 @@ 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;
}
}
@Nullable
@SuppressWarnings("InfiniteLoopStatement")
public static SpiderInfo read(@Nullable InputStream is) {
if (null == is) {
@@ -89,8 +104,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 +127,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,9 +142,9 @@ 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) {
if (pos > 0) {
int index = Integer.parseInt(line.substring(0, pos));
String pToken = line.substring(pos + 1);
if (!TextUtils.isEmpty(pToken)) {
@@ -127,7 +159,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 +170,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));
@@ -45,8 +45,9 @@ import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.GalleryDetailParser;
import com.hippo.ehviewer.client.parser.GalleryPageParser;
import com.hippo.ehviewer.client.parser.GalleryPageUrlParser;
import com.hippo.ehviewer.gallery.GalleryProvider;
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.ehviewer.gallery.GalleryProvider2;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.image.Image;
import com.hippo.streampipe.InputStreamPipe;
import com.hippo.streampipe.OutputStreamPipe;
@@ -70,13 +71,13 @@ import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
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 Stack<Integer> mDecodeRequestStack = new Stack<>();
private final AtomicInteger mDecodingIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
private final Thread[] mDecodeThreadArray = new Thread[DECODE_THREAD_NUM];
private final int[] mDecodeIndexArray = new int[DECODE_THREAD_NUM];
private final Queue<Integer> mDecodeRequestQueue = new LinkedList<>();
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;
@@ -413,7 +422,6 @@ public class SpiderQueen implements Runnable {
}
public String getError() {
// TODO
if (mQueenThread == null) {
return "Error";
} else {
@@ -464,6 +472,9 @@ public class SpiderQueen implements Runnable {
synchronized (mRequestPageQueue) {
mRequestPageQueue.remove(index);
}
synchronized (mDecodeRequestQueue) {
mDecodeRequestQueue.remove(index);
}
}
/**
@@ -482,6 +493,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;
}
@@ -531,10 +544,10 @@ public class SpiderQueen implements Runnable {
result = error;
break;
case STATE_FINISHED:
synchronized (mDecodeRequestStack) {
if (!mDecodeRequestStack.contains(index) && index != mDecodingIndex.get()) {
mDecodeRequestStack.add(index);
mDecodeRequestStack.notify();
synchronized (mDecodeRequestQueue) {
if (!contain(mDecodeIndexArray, index) && !mDecodeRequestQueue.contains(index)) {
mDecodeRequestQueue.add(index);
mDecodeRequestQueue.notify();
}
}
result = null;
@@ -546,6 +559,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 +648,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 +672,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 +693,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 +709,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 +742,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 +750,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 +836,7 @@ public class SpiderQueen implements Runnable {
if (spiderInfo == null) {
return;
}
mSpiderInfo = spiderInfo;
mSpiderInfo.lazySet(spiderInfo);
// Check interrupted
if (Thread.currentThread().isInterrupted()) {
@@ -821,11 +862,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 +909,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 +932,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
@@ -963,14 +1007,27 @@ public class SpiderQueen implements Runnable {
mGid = mGalleryInfo.gid;
}
private GalleryPageParser.Result getImageUrl(long gid, int index, String pToken,
String skipHathKey) throws Exception {
String url = EhUrl.getPageUrl(gid, index, pToken);
if (skipHathKey != null) {
url = url + "?nl=" + skipHathKey;
private String getPageUrl(long gid, int index, String pToken,
String oldPageUrl, String skipHathKey) {
String pageUrl;
if (oldPageUrl != null) {
pageUrl = oldPageUrl;
} else {
pageUrl = EhUrl.getPageUrl(gid, index, pToken);
}
// Add skipHathKey
if (skipHathKey != null) {
if (pageUrl.contains("?")) {
pageUrl += "&nl=" + skipHathKey;
} else {
pageUrl += "?nl=" + skipHathKey;
}
}
return pageUrl;
}
GalleryPageParser.Result result = EhEngine.getGalleryPage(null, mHttpClient, url);
private GalleryPageParser.Result getImageUrl(int index, String pageUrl) throws Exception {
GalleryPageParser.Result result = EhEngine.getGalleryPage(null, mHttpClient, pageUrl);
if (StringUtils.endsWith(result.imageUrl, URL_509_SUFFIX_ARRAY)) {
// Get 509
// Notify listeners
@@ -983,21 +1040,25 @@ public class SpiderQueen implements Runnable {
// false for stop
private boolean downloadImage(long gid, int index, String pToken, boolean force) {
List<String> skipHathKeys = new ArrayList<>(5);
String skipHathKey = null;
String imageUrl;
String error = null;
String pageUrl = null;
boolean interrupt = false;
boolean leakSkipHathKey = false;
// Try twice
for (int i = 0; i < 2; i++) {
if (i > 0 && TextUtils.isEmpty(skipHathKey)) {
// No need to get image url twice without skip hath key
for (int i = 0; i < 5; i++) {
if (leakSkipHathKey) {
break;
}
pageUrl = getPageUrl(gid, index, pToken, pageUrl, skipHathKey);
GalleryPageParser.Result result = null;
try {
result = getImageUrl(gid, index, pToken, skipHathKey);
result = getImageUrl(index, pageUrl);
} catch (Image509Exception e) {
error = GetText.getString(R.string.error_509);
} catch (Exception e) {
@@ -1009,6 +1070,7 @@ public class SpiderQueen implements Runnable {
}
// Check interrupted
if (Thread.currentThread().isInterrupted()) {
error = "Interrupted";
interrupt = true;
break;
}
@@ -1019,11 +1081,22 @@ public class SpiderQueen implements Runnable {
imageUrl = result.imageUrl;
}
skipHathKey = result.skipHathKey;
if (!TextUtils.isEmpty(skipHathKey)) {
if (skipHathKeys.contains(skipHathKey)) {
// Duplicate skip hath key, don't run next turn
leakSkipHathKey = true;
} else {
skipHathKeys.add(skipHathKey);
}
} else {
// No skip hath key, don't run next turn
leakSkipHathKey = true;
}
// If it is force request, skip first image
if (force && i == 0) {
continue;
}
//if (force && i == 0) {
// continue;
//}
if (DEBUG_LOG) {
Log.d(TAG, imageUrl);
@@ -1042,6 +1115,7 @@ public class SpiderQueen implements Runnable {
if (response.code() >= 400) {
// Maybe 404
response.body().close();
error = "Bad code: " + response.code();
continue;
}
ResponseBody responseBody = response.body();
@@ -1050,8 +1124,8 @@ public class SpiderQueen implements Runnable {
String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(
responseBody.contentType().toString());
// Ensure extension
if (!Utilities.contain(GalleryProvider.SUPPORT_IMAGE_EXTENSIONS, extension)) {
extension = GalleryProvider.SUPPORT_IMAGE_EXTENSIONS[0];
if (!Utilities.contain(GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS, extension)) {
extension = GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS[0];
}
// Get out put pipe
@@ -1088,9 +1162,21 @@ public class SpiderQueen implements Runnable {
}
os.flush();
// check download size
if (contentLength >= 0) {
if (receivedSize < contentLength) {
Log.e(TAG, "Can't download all of image data");
error = "Incomplete";
continue;
} else if (receivedSize > contentLength) {
Log.w(TAG, "Received data is more than contentLength");
}
}
// Check interrupted
if (Thread.currentThread().isInterrupted()) {
interrupt = true;
error = "Interrupted";
break;
}
@@ -1125,6 +1211,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 +1265,12 @@ 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);
if (SpiderInfo.TOKEN_FAILED.equals(pToken)) {
mSpiderInfo.pTokenMap.remove(i);
int i = spiderInfo.pTokenMap.indexOfKey(index);
if (i >= 0) {
String pToken = spiderInfo.pTokenMap.valueAt(i);
if (SpiderInfo.TOKEN_FAILED.equals(pToken)) {
spiderInfo.pTokenMap.remove(i);
}
}
}
}
@@ -1186,7 +1279,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);
@@ -1214,7 +1307,7 @@ public class SpiderQueen implements Runnable {
if (pToken == null) {
// Interrupted
// Get token failed
updatePageState(index, STATE_FAILED, null);
updatePageState(index, STATE_FAILED, "Interrupted");
return false;
}
@@ -1260,6 +1353,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 (mDecodeRequestQueue) {
mDecodeIndexArray[mThreadIndex] = GalleryPageView.INVALID_INDEX;
}
}
@Override
public void run() {
if (DEBUG_LOG) {
@@ -1268,30 +1373,30 @@ public class SpiderQueen implements Runnable {
while (!Thread.currentThread().isInterrupted()) {
int index;
synchronized (mDecodeRequestStack) {
if (mDecodeRequestStack.isEmpty()) {
synchronized (mDecodeRequestQueue) {
if (mDecodeRequestQueue.isEmpty()) {
try {
mDecodeRequestStack.wait();
mDecodeRequestQueue.wait();
} catch (InterruptedException e) {
// Interrupted
break;
}
continue;
}
index = mDecodeRequestStack.pop();
mDecodingIndex.lazySet(index);
index = mDecodeRequestQueue.remove();
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 +1404,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 +1442,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);
@@ -24,7 +24,7 @@ import com.google.analytics.tracking.android.EasyTracker;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.Settings;
public class EhActivity extends AppCompatActivity {
public abstract class EhActivity extends AppCompatActivity {
private boolean mTrackStarted;
@@ -24,7 +24,7 @@ import com.hippo.app.AppCompatPreferenceActivity;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.Settings;
public class EhPreferenceActivity extends AppCompatPreferenceActivity {
public abstract class EhPreferenceActivity extends AppCompatPreferenceActivity {
private boolean mTrackStarted;
@@ -61,6 +61,7 @@ public class ExcludedLanguagesActivity extends ToolbarActivity
};
private static final String[] LANGUAGES = {
EhConfig.JAPANESE_ORIGINAL,
EhConfig.JAPANESE_TRANSLATED,
EhConfig.JAPANESE_REWRITE,
EhConfig.ENGLISH_ORIGINAL,
@@ -207,8 +208,8 @@ public class ExcludedLanguagesActivity extends ToolbarActivity
String pattern = LANGUAGES[j];
if (pattern.equals(language)) {
// Get it
int row = (j + 1) / 3;
int column = (j + 1) % 3;
int row = j / 3;
int column = j % 3;
mSelections[row][column] = true;
break;
}
@@ -282,22 +283,19 @@ public class ExcludedLanguagesActivity extends ToolbarActivity
finish();
} else if (v == mOk) {
StringBuilder sb = new StringBuilder();
int i = -1;
int i = 0;
boolean first = true;
for (boolean[] selections : mSelections) {
for (boolean b : selections) {
i++;
if (i == 0) {
continue;
}
if (b) {
if (!first) {
sb.append("x");
} else {
first = false;
}
sb.append(LANGUAGES[i - 1]);
sb.append(LANGUAGES[i]);
}
i++;
}
}
@@ -383,11 +381,6 @@ public class ExcludedLanguagesActivity extends ToolbarActivity
@Override
public void onBindViewHolder(LanguageHolder holder, int position) {
holder.language.setText(LANGUAGE_STR_IDS[position]);
if (position == 0) {
holder.original.setVisibility(View.INVISIBLE);
} else {
holder.original.setVisibility(View.VISIBLE);
}
boolean[] selections = mSelections[position];
holder.original.setChecked(selections[0]);
holder.translated.setChecked(selections[1]);
@@ -20,11 +20,13 @@ import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
@@ -52,31 +54,29 @@ import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.gallery.DirGalleryProvider;
import com.hippo.ehviewer.gallery.EhGalleryProvider;
import com.hippo.ehviewer.gallery.GalleryProvider;
import com.hippo.ehviewer.gallery.GalleryProviderListener;
import com.hippo.ehviewer.gallery.GalleryProvider2;
import com.hippo.ehviewer.gallery.ZipGalleryProvider;
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.ehviewer.gallery.gl.GalleryView;
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.view.GLRootView;
import com.hippo.image.ImageWrapper;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.glgallery.GalleryView;
import com.hippo.glgallery.SimpleAdapter;
import com.hippo.glview.view.GLRootView;
import com.hippo.unifile.UniFile;
import com.hippo.util.SystemUiHelper;
import com.hippo.widget.ColorView;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.ConcurrentPool;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.SimpleAnimatorListener;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.ViewUtils;
import java.io.File;
public class GalleryActivity extends EhActivity
implements GalleryProviderListener, SeekBar.OnSeekBarChangeListener,
public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChangeListener,
GalleryView.Listener {
public static final String ACTION_DIR = "dir";
@@ -103,11 +103,10 @@ public class GalleryActivity extends EhActivity
private GLRootView mGLRootView;
@Nullable
private GalleryView mGalleryView;
@Nullable
private ImageTexture.Uploader mUploader;
private GalleryProvider2 mGalleryProvider;
@Nullable
private GalleryProvider mGalleryProvider;
private GalleryAdapter mGalleryAdapter;
@Nullable
private SystemUiHelper mSystemUiHelper;
@@ -236,6 +235,7 @@ public class GalleryActivity extends EhActivity
}
@Override
@SuppressWarnings({"deprecation", "WrongConstant"})
protected void onCreate(@Nullable Bundle savedInstanceState) {
if (Settings.getReadingFullscreen() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window w = getWindow();
@@ -257,14 +257,9 @@ public class GalleryActivity extends EhActivity
finish();
return;
}
mGalleryProvider.setGalleryProviderListener(this);
mGalleryProvider.start();
setContentView(R.layout.activity_gallery);
mGLRootView = (GLRootView) ViewUtils.$$(this, R.id.gl_root_view);
mGalleryProvider.setGLRoot(mGLRootView);
mUploader = new ImageTexture.Uploader(mGLRootView);
// Get start page
int startPage;
if (savedInstanceState == null) {
startPage = mPage >= 0 ? mPage : mGalleryProvider.getStartPage();
@@ -272,10 +267,37 @@ public class GalleryActivity extends EhActivity
startPage = mCurrentIndex;
}
mGalleryView = new GalleryView(this, new GalleryAdapter(), this,
Settings.getReadingDirection(), Settings.getPageScaling(),
Settings.getStartPosition(), startPage);
setContentView(R.layout.activity_gallery);
mGLRootView = (GLRootView) ViewUtils.$$(this, R.id.gl_root_view);
mGalleryAdapter = new GalleryAdapter(mGLRootView, mGalleryProvider);
Resources resources = getResources();
int primaryColor = ResourcesUtils.getAttrColor(this, R.attr.colorPrimary);
mGalleryView = new GalleryView.Builder(this, mGalleryAdapter)
.setListener(this)
.setLayoutMode(Settings.getReadingDirection())
.setScaleMode(Settings.getPageScaling())
.setStartPosition(Settings.getStartPosition())
.setStartPage(startPage)
.setBackgroundColor(resources.getColor(R.color.gallery_background))
.setEdgeColor(primaryColor & 0xffffff | 0x33000000)
.setPagerInterval(resources.getDimensionPixelOffset(R.dimen.gallery_pager_interval))
.setScrollInterval(resources.getDimensionPixelOffset(R.dimen.gallery_scroll_interval))
.setPageMinHeight(resources.getDimensionPixelOffset(R.dimen.gallery_page_min_height))
.setPageInfoInterval(resources.getDimensionPixelOffset(R.dimen.gallery_page_info_interval))
.setProgressColor(primaryColor)
.setProgressSize(resources.getDimensionPixelOffset(R.dimen.gallery_progress_size))
.setPageTextColor(resources.getColor(R.color.secondary_text_default_dark))
.setPageTextSize(resources.getDimensionPixelOffset(R.dimen.gallery_page_text_size))
.setPageTextTypeface(Typeface.DEFAULT)
.setErrorTextColor(resources.getColor(R.color.red_500))
.setErrorTextSize(resources.getDimensionPixelOffset(R.dimen.gallery_error_text_size))
.setDefaultErrorString(resources.getString(R.string.error_unknown))
.setEmptyString(resources.getString(R.string.error_empty))
.build();
mGLRootView.setContentPane(mGalleryView);
mGalleryProvider.setListener(mGalleryAdapter);
mGalleryProvider.setGLRoot(mGLRootView);
// System UI helper
if (Settings.getReadingFullscreen()) {
@@ -347,12 +369,12 @@ public class GalleryActivity extends EhActivity
super.onDestroy();
mGLRootView = null;
mGalleryView = null;
if (mUploader != null) {
mUploader.clear();
mUploader = null;
if (mGalleryAdapter != null) {
mGalleryAdapter.clearUploader();
mGalleryAdapter = null;
}
if (mGalleryProvider != null) {
mGalleryProvider.setGalleryProviderListener(null);
mGalleryProvider.setListener(null);
mGalleryProvider.stop();
mGalleryProvider = null;
}
@@ -409,14 +431,14 @@ public class GalleryActivity extends EhActivity
// Check volume
if (Settings.getVolumePage()) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
mGalleryView.pageRight();
} else {
mGalleryView.pageLeft();
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
mGalleryView.pageLeft();
} else {
mGalleryView.pageRight();
@@ -429,7 +451,7 @@ public class GalleryActivity extends EhActivity
switch (keyCode) {
case KeyEvent.KEYCODE_PAGE_UP:
case KeyEvent.KEYCODE_DPAD_UP:
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
mGalleryView.pageRight();
} else {
mGalleryView.pageLeft();
@@ -440,7 +462,7 @@ public class GalleryActivity extends EhActivity
return true;
case KeyEvent.KEYCODE_PAGE_DOWN:
case KeyEvent.KEYCODE_DPAD_DOWN:
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
mGalleryView.pageLeft();
} else {
mGalleryView.pageRight();
@@ -513,7 +535,7 @@ public class GalleryActivity extends EhActivity
TextView start;
TextView end;
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
start = mRightText;
end = mLeftText;
mSeekBar.setReverse(true);
@@ -528,96 +550,11 @@ public class GalleryActivity extends EhActivity
mSeekBar.setProgress(mCurrentIndex);
}
@Override
public void onDataChanged() {
if (mGalleryView != null) {
mGalleryView.onDataChanged();
}
if (mGalleryProvider != null) {
int size = mGalleryProvider.size();
NotifyTask task = mNotifyTaskPool.pop();
if (task == null) {
task = new NotifyTask();
}
task.setData(NotifyTask.KEY_SIZE, size);
SimpleHandler.getInstance().post(task);
}
}
@Override
public void onPageWait(int index) {
GalleryPageView page = findPageByIndex(index);
if (page != null) {
page.showInfo();
page.setImage(null);
page.setPage(index + 1);
page.setProgress(GalleryPageView.PROGRESS_INDETERMINATE);
page.setError(null, null);
}
}
@Override
public void onPagePercent(int index, float percent) {
GalleryPageView page = findPageByIndex(index);
if (page != null) {
page.showInfo();
page.setImage(null);
page.setPage(index + 1);
page.setProgress(percent);
page.setError(null, null);
}
}
@Override
public void onPageSucceed(int index, ImageWrapper image) {
GalleryPageView page = findPageByIndex(index);
if (page != null) {
if (image.obtain()) {
ImageTexture imageTexture = new ImageTexture(image);
if (mUploader != null) {
mUploader.addTexture(imageTexture);
}
page.showImage();
page.setImage(imageTexture);
page.setPage(index + 1);
page.setProgress(GalleryPageView.PROGRESS_GONE);
page.setError(null, null);
} else {
// The image is recycled, request again.
// TODO request loop ?
if (mGalleryProvider != null) {
mGalleryProvider.request(index);
}
}
}
}
@Override
public void onPageFailed(int index, String error) {
GalleryPageView page = findPageByIndex(index);
if (page != null && mGalleryView != null) {
page.showInfo();
page.setImage(null);
page.setPage(index + 1);
page.setProgress(GalleryPageView.PROGRESS_GONE);
page.setError(error, mGalleryView);
}
}
@Override
public void onDataChanged(int index) {
GalleryPageView page = findPageByIndex(index);
if (page != null && mGalleryProvider != null) {
mGalleryProvider.request(index);
}
}
@Override
@SuppressLint("SetTextI18n")
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
TextView start;
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
start = mRightText;
} else {
start = mLeftText;
@@ -816,8 +753,8 @@ public class GalleryActivity extends EhActivity
public void onClick(DialogInterface dialog, int which) {
int screenRotation = mScreenRotation.getSelectedItemPosition();
int layoutMode = GalleryView.sanitizeLayoutMode(mReadingDirection.getSelectedItemPosition());
int scaleMode = ImageView.sanitizeScaleMode(mScaleMode.getSelectedItemPosition());
int startPosition = ImageView.sanitizeStartPosition(mStartPosition.getSelectedItemPosition());
int scaleMode = GalleryView.sanitizeScaleMode(mScaleMode.getSelectedItemPosition());
int startPosition = GalleryView.sanitizeStartPosition(mStartPosition.getSelectedItemPosition());
boolean keepScreenOn = mKeepScreenOn.isChecked();
boolean showClock = mShowClock.isChecked();
boolean showProgress = mShowProgress.isChecked();
@@ -892,29 +829,42 @@ public class GalleryActivity extends EhActivity
return;
}
File dir = AppConfig.getExternalTempDir();
File dir = AppConfig.getExternalImageDir();
if (null == dir) {
Toast.makeText(this, R.string.error_cant_create_temp_file, Toast.LENGTH_SHORT).show();
return;
}
UniFile file;
if (null == (file = mGalleryProvider.save(page, UniFile.fromFile(dir), Long.toString(System.currentTimeMillis())))) {
if (null == (file = mGalleryProvider.save(page, UniFile.fromFile(dir), mGalleryProvider.getImageFilename(page)))) {
Toast.makeText(this, R.string.error_cant_save_image, Toast.LENGTH_SHORT).show();
return;
}
String filename = file.getName();
if (filename == null) {
Toast.makeText(this, R.string.error_cant_save_image, Toast.LENGTH_SHORT).show();
return;
}
// TODO Create ContentProvider for some app are not grand storage write permission
Uri uri = file.getUri();
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(uri.toString()));
MimeTypeMap.getFileExtensionFromUrl(filename));
if (TextUtils.isEmpty(mimeType)) {
mimeType = "image/jpeg";
}
Uri uri = new Uri.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority("com.hippo.ehviewer.fileprovider")
.appendPath("image")
.appendPath(filename)
.build();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType(mimeType);
startActivity(Intent.createChooser(intent, getString(R.string.share_image)));
// Sync media store
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, file.getUri()));
}
private void saveImage(int page) {
@@ -934,6 +884,9 @@ public class GalleryActivity extends EhActivity
}
Toast.makeText(this, getString(R.string.image_saved, file.getUri()), Toast.LENGTH_SHORT).show();
// Sync media store
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, file.getUri()));
}
private void showPageDialog(final int page) {
@@ -1039,46 +992,25 @@ public class GalleryActivity extends EhActivity
}
}
private class GalleryAdapter extends GalleryView.Adapter {
private class GalleryAdapter extends SimpleAdapter {
@Override
public String getError() {
if (mGalleryProvider == null) {
return getString(R.string.error_no_provider);
} else if (mGalleryProvider.size() <= GalleryProvider.STATE_ERROR) {
return mGalleryProvider.getError();
}
return null;
public GalleryAdapter(@NonNull GLRootView glRootView, @NonNull GalleryProvider provider) {
super(glRootView, provider);
}
@Override
public int size() {
if (mGalleryProvider == null) {
return GalleryProvider.STATE_ERROR;
} else {
return mGalleryProvider.size();
}
}
public void onDataChanged() {
super.onDataChanged();
@Override
public void onBind(GalleryPageView view, int index) {
if (mGalleryProvider != null && mGalleryView != null) {
mGalleryProvider.request(index);
view.showInfo();
view.setImage(null);
view.setPage(index + 1);
view.setProgress(GalleryPageView.PROGRESS_INDETERMINATE);
view.setError(null, null);
}
}
@Override
public void onUnbind(GalleryPageView view, int index) {
if (mGalleryProvider != null) {
mGalleryProvider.cancelRequest(index);
int size = mGalleryProvider.size();
NotifyTask task = mNotifyTaskPool.pop();
if (task == null) {
task = new NotifyTask();
}
task.setData(NotifyTask.KEY_SIZE, size);
SimpleHandler.getInstance().post(task);
}
view.setImage(null);
view.setError(null, null);
}
}
}
@@ -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;
@@ -32,7 +33,6 @@ import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
@@ -66,10 +66,12 @@ import com.hippo.ehviewer.ui.scene.QuickSearchScene;
import com.hippo.ehviewer.ui.scene.SecurityScene;
import com.hippo.ehviewer.ui.scene.SelectSiteScene;
import com.hippo.ehviewer.ui.scene.SignInScene;
import com.hippo.ehviewer.ui.scene.SolidScene;
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;
@@ -89,24 +91,12 @@ import java.io.OutputStream;
public final class MainActivity extends StageActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
private static final int REQUEST_CODE_SETTINGS = 0;
private static final String KEY_NAV_CHECKED_ITEM = "nav_checked_item";
public static final int CHECK_STEP_SECURITY = 0;
public static final int CHECK_STEP_WARNING = 1;
public static final int CHECK_STEP_ANALYTICS = 2;
public static final int CHECK_STEP_CRASH = 3;
public static final int CHECK_STEP_SIGN_IN = 4;
public static final int CHECK_STEP_SELECT_SITE = 5;
public static final String KEY_TARGET_SCENE = "target_scene";
public static final String KEY_TARGET_ARGS = "target_args";
/*---------------
Whole life cycle
---------------*/
@@ -145,61 +135,6 @@ public final class MainActivity extends StageActivity
registerLaunchMode(ProgressScene.class, SceneFragment.LAUNCH_MODE_STANDARD);
}
public void startSceneForCheckStep(int checkStep, Bundle args) {
switch (checkStep) {
case CHECK_STEP_SECURITY:
if (Settings.getShowWarning()) {
startScene(new Announcer(WarningScene.class).setArgs(args));
break;
}
case CHECK_STEP_WARNING:
if (Settings.getAskAnalytics()) {
startScene(new Announcer(AnalyticsScene.class).setArgs(args));
break;
}
case CHECK_STEP_ANALYTICS:
if (Crash.hasCrashFile()) {
startScene(new Announcer(CrashScene.class).setArgs(args));
break;
}
case CHECK_STEP_CRASH:
if (EhUtils.needSignedIn(this)) {
startScene(new Announcer(SignInScene.class).setArgs(args));
break;
}
case CHECK_STEP_SIGN_IN:
if (Settings.getSelectSite()) {
startScene(new Announcer(SelectSiteScene.class).setArgs(args));
break;
}
case CHECK_STEP_SELECT_SITE:
String targetScene = null;
Bundle targetArgs = null;
if (null != args) {
targetScene = args.getString(KEY_TARGET_SCENE);
targetArgs = args.getBundle(KEY_TARGET_ARGS);
}
Class<?> clazz = null;
if (targetScene != null) {
try {
clazz = Class.forName(targetScene);
} catch (ClassNotFoundException e) {
Log.e(TAG, "Can't find class with name: " + targetScene);
}
}
if (clazz != null) {
startScene(new Announcer(clazz).setArgs(targetArgs));
} else {
Bundle newArgs = new Bundle();
newArgs.putString(GalleryListScene.KEY_ACTION, GalleryListScene.ACTION_HOMEPAGE);
startScene(new Announcer(GalleryListScene.class).setArgs(newArgs));
}
break;
}
}
@Override
public int getContainerViewId() {
return R.id.fragment_container;
@@ -232,33 +167,33 @@ public final class MainActivity extends StageActivity
if (0 == getSceneCount()) {
if (!TextUtils.isEmpty(Settings.getSecurity())) {
Bundle newArgs = new Bundle();
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(SecurityScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(SecurityScene.KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(SecurityScene.class).setArgs(newArgs);
} else if (Settings.getShowWarning()) {
Bundle newArgs = new Bundle();
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(WarningScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(WarningScene.KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(WarningScene.class).setArgs(newArgs);
} else if (Settings.getAskAnalytics()) {
Bundle newArgs = new Bundle();
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(AnalyticsScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(AnalyticsScene.KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(AnalyticsScene.class).setArgs(newArgs);
} else if (Crash.hasCrashFile()) {
Bundle newArgs = new Bundle();
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(CrashScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(CrashScene.KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(CrashScene.class).setArgs(newArgs);
} else if (EhUtils.needSignedIn(this)) {
Bundle newArgs = new Bundle();
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(SignInScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(SignInScene.KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(SignInScene.class).setArgs(newArgs);
} else if (Settings.getSelectSite()) {
Bundle newArgs = new Bundle();
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(SelectSiteScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(SelectSiteScene.KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(SelectSiteScene.class).setArgs(newArgs);
}
}
@@ -339,6 +274,12 @@ public final class MainActivity extends StageActivity
@Override
protected void onUnrecognizedIntent(@Nullable Intent intent) {
Class<?> clazz = getTopSceneClass();
if (clazz != null && SolidScene.class.isAssignableFrom(clazz)) {
// TODO the intent lost
return;
}
if (!handleIntent(intent)) {
boolean handleUrl = false;
if (intent != null && Intent.ACTION_VIEW.equals(intent.getAction())) {
@@ -392,6 +333,9 @@ public final class MainActivity extends StageActivity
onInit();
CommonOperations.checkUpdate(this, false);
checkDownloadLocation();
if (Settings.getCellularNetworkWarning()) {
checkCellularNetwork();
}
} else {
onRestore(savedInstanceState);
}
@@ -410,6 +354,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,
@@ -26,7 +26,7 @@ import android.view.ViewGroup;
import com.hippo.ehviewer.R;
public class ToolbarActivity extends EhActivity {
public abstract class ToolbarActivity extends EhActivity {
@Override
public void setContentView(@LayoutRes int layoutResID) {
@@ -16,10 +16,14 @@
package com.hippo.ehviewer.ui.fragment;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
import com.hippo.ehviewer.Analytics;
import com.hippo.ehviewer.EhApplication;
@@ -75,6 +79,10 @@ public class AboutFragment extends PreferenceFragment
AppHelper.sendEmail(getActivity(), EhApplication.getDeveloperEmail(),
"About EhViewer", null);
} else if (KEY_DONATE.equals(key)) {
ClipboardManager cmb = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setPrimaryClip(ClipData.newPlainText(null, "seven332$163.com".replace('$', '@')));
Toast.makeText(getActivity(), R.string.settings_about_donate_toast, Toast.LENGTH_SHORT).show();
new AlertDialog.Builder(getActivity())
.setTitle(R.string.settings_about_donate)
.setMessage(getString(R.string.settings_about_donate_message).replace('$', '@'))
@@ -32,7 +32,7 @@ import com.hippo.text.Html;
import com.hippo.text.LinkMovementMethod2;
import com.hippo.yorozuya.ViewUtils;
public class AnalyticsScene extends BaseScene implements View.OnClickListener {
public class AnalyticsScene extends SolidScene implements View.OnClickListener {
@Nullable
private View mReject;
@@ -90,7 +90,7 @@ public class AnalyticsScene extends BaseScene implements View.OnClickListener {
// Start new scene and finish it self
MainActivity activity = getActivity2();
if (null != activity) {
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_ANALYTICS, getArguments());
startSceneForCheckStep(CHECK_STEP_ANALYTICS, getArguments());
}
finish();
}
@@ -36,12 +36,13 @@ import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import okhttp3.Cookie;
public class CookieSignInScene extends BaseScene implements EditText.OnEditorActionListener,
public class CookieSignInScene extends SolidScene implements EditText.OnEditorActionListener,
View.OnClickListener {
/*---------------
@@ -70,10 +71,10 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
View view = inflater.inflate(R.layout.scene_cookie_sign_in, container, false);
mIpbMemberIdLayout = (TextInputLayout) ViewUtils.$$(view, R.id.ipb_member_id_layout);
mIpbMemberId = mIpbMemberIdLayout.getEditText();
AssertUtils.assertNotNull(mIpbMemberId);
Assert.assertNotNull(mIpbMemberId);
mIpbPassHashLayout = (TextInputLayout) ViewUtils.$$(view, R.id.ipb_pass_hash_layout);
mIpbPassHash = mIpbPassHashLayout.getEditText();
AssertUtils.assertNotNull(mIpbPassHash);
Assert.assertNotNull(mIpbPassHash);
mOk = ViewUtils.$$(view, R.id.ok);
mIpbPassHash.setOnEditorActionListener(this);
@@ -82,7 +83,7 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
// Try to get old version cookie info
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
SharedPreferences sharedPreferences = context.getSharedPreferences("eh_info", 0);
String ipbMemberId = sharedPreferences.getString("ipb_member_id", null);
String ipbPassHash = sharedPreferences.getString("ipb_pass_hash", null);
@@ -30,7 +30,7 @@ import com.hippo.ripple.Ripple;
import com.hippo.util.AppHelper;
import com.hippo.yorozuya.ViewUtils;
public class CrashScene extends BaseScene implements View.OnClickListener {
public class CrashScene extends SolidScene implements View.OnClickListener {
/*---------------
Whole life cycle
@@ -88,7 +88,7 @@ public class CrashScene extends BaseScene implements View.OnClickListener {
// Start new scene and finish it self
if (null != activity) {
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_CRASH, getArguments());
startSceneForCheckStep(CHECK_STEP_CRASH, getArguments());
}
finish();
}
@@ -53,9 +53,10 @@ import com.hippo.ehviewer.R;
import com.hippo.ehviewer.dao.DownloadLabel;
import com.hippo.util.DrawableManager;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.List;
public class DownloadLabelsScene extends ToolbarScene {
@@ -100,7 +101,7 @@ public class DownloadLabelsScene extends ToolbarScene {
mViewTransition = new ViewTransition(mRecyclerView, tip);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_label);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
tip.setCompoundDrawables(null, drawable, null, null);
@@ -340,7 +341,7 @@ public class DownloadLabelsScene extends ToolbarScene {
public LabelAdapter() {
mInflater = getLayoutInflater2();
AssertUtils.assertNotNull(mInflater);
Assert.assertNotNull(mInflater);
}
@Override
@@ -389,6 +390,11 @@ public class DownloadLabelsScene extends ToolbarScene {
}
}
@Override
public boolean onCheckCanDrop(int draggingPosition, int dropPosition) {
return true;
}
@Override
public int onGetSwipeReactionType(LabelHolder holder, int position, int x, int y) {
if (ViewUtils.isViewUnder(holder.getSwipeableContainerView(), x, y, 0)) {
@@ -88,7 +88,6 @@ import com.hippo.view.ViewTransition;
import com.hippo.widget.FabLayout;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.recyclerview.AutoStaggeredGridLayoutManager;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.ObjectUtils;
@@ -96,6 +95,8 @@ import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.ViewUtils;
import com.hippo.yorozuya.collect.LongList;
import junit.framework.Assert;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -193,7 +194,7 @@ public class DownloadsScene extends ToolbarScene
super.onCreate(savedInstanceState);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
mDownloadManager = EhApplication.getDownloadManager(context);
mDownloadManager.addDownloadInfoListener(this);
@@ -286,7 +287,7 @@ public class DownloadsScene extends ToolbarScene
mViewTransition = new ViewTransition(content, tip);
Context context = getContext2();
AssertUtils.assertNotNull(content);
Assert.assertNotNull(content);
Resources resources = context.getResources();
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_download);
@@ -508,7 +509,7 @@ public class DownloadsScene extends ToolbarScene
View view = inflater.inflate(R.layout.drawer_list, container, false);
final Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.setTitle(R.string.download_labels);
@@ -1123,7 +1124,7 @@ public class DownloadsScene extends ToolbarScene
public DownloadAdapter() {
mInflater = getLayoutInflater2();
AssertUtils.assertNotNull(mInflater);
Assert.assertNotNull(mInflater);
}
@Override
@@ -1145,17 +1146,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,14 +1211,27 @@ public class DownloadsScene extends ToolbarScene
private class ThumbDataContainer implements DataContainer {
@NonNull
private final UniFile mFile;
private final DownloadInfo mInfo;
@Nullable
private UniFile mFile;
/**
* @param file the thumb file
*/
public ThumbDataContainer(@NonNull UniFile file) {
mFile = file;
public ThumbDataContainer(@NonNull DownloadInfo info) {
mInfo = info;
}
private void ensureFile() {
if (mFile == null) {
UniFile dir = SpiderDen.getGalleryDownloadDir(mInfo);
if (dir != null && dir.isDirectory()) {
mFile = dir.createFile(".thumb");
}
}
}
@Override
public boolean isEnabled() {
ensureFile();
return mFile != null;
}
@Override
@@ -1234,6 +1239,11 @@ public class DownloadsScene extends ToolbarScene
@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,12 +1259,19 @@ 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
public void remove() {
mFile.delete();
if (mFile != null) {
mFile.delete();
}
}
}
}
@@ -80,13 +80,14 @@ import com.hippo.util.DrawableManager;
import com.hippo.widget.ContentLayout;
import com.hippo.widget.FabLayout;
import com.hippo.widget.SearchBarMover;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ObjectUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -177,7 +178,7 @@ public class FavoritesScene extends BaseScene implements
super.onCreate(savedInstanceState);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
mClient = EhApplication.getEhClient(context);
mFavCatArray = Settings.getFavCat();
@@ -242,7 +243,7 @@ public class FavoritesScene extends BaseScene implements
mFabLayout = (FabLayout) ViewUtils.$$(view, R.id.fab_layout);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Resources resources = context.getResources();
int paddingTopSB = resources.getDimensionPixelOffset(R.dimen.gallery_padding_top_search_bar);
@@ -499,7 +500,7 @@ public class FavoritesScene extends BaseScene implements
ListView listView = (ListView) view.findViewById(R.id.list_view);
final Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
toolbar.setTitle(R.string.collections);
toolbar.inflateMenu(R.menu.drawer_favorites);
@@ -76,7 +76,6 @@ import com.hippo.widget.FabLayout;
import com.hippo.widget.LinkifyTextView;
import com.hippo.widget.ObservedTextView;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.SimpleAnimatorListener;
@@ -84,6 +83,8 @@ import com.hippo.yorozuya.StringUtils;
import com.hippo.yorozuya.ViewUtils;
import com.hippo.yorozuya.collect.IntList;
import junit.framework.Assert;
import java.util.ArrayList;
import java.util.List;
@@ -190,7 +191,7 @@ public final class GalleryCommentsScene extends ToolbarScene
mFab = (FloatingActionButton) ViewUtils.$$(view, R.id.fab);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Resources resources = context.getResources();
int paddingBottomFab = resources.getDimensionPixelOffset(R.dimen.gallery_padding_bottom_fab);
@@ -454,6 +455,10 @@ public final class GalleryCommentsScene extends ToolbarScene
.setDuration(300L).setListener(new SimpleAnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
if (null == mFab || null == mEditPanel) {
return;
}
mFab.setVisibility(View.INVISIBLE);
mEditPanel.setVisibility(View.VISIBLE);
int halfW = mEditPanel.getWidth() / 2;
@@ -497,6 +502,10 @@ public final class GalleryCommentsScene extends ToolbarScene
animator.addListener(new SimpleAnimatorListener() {
@Override
public void onAnimationEnd(Animator a) {
if (null == mFab || null == mEditPanel) {
return;
}
mEditPanel.setVisibility(View.GONE);
mFab.setVisibility(View.VISIBLE);
int fabStartX = mEditPanel.getLeft() + (mEditPanel.getWidth() / 2) - (mFab.getWidth() / 2);
@@ -609,7 +618,7 @@ public final class GalleryCommentsScene extends ToolbarScene
public CommentAdapter() {
mInflater = getLayoutInflater2();
AssertUtils.assertNotNull(mInflater);
Assert.assertNotNull(mInflater);
}
@Override
@@ -81,6 +81,7 @@ import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.ehviewer.ui.GalleryActivity;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.ehviewer.ui.annotation.WholeLifeCircle;
import com.hippo.ehviewer.widget.GalleryRatingBar;
import com.hippo.reveal.ViewAnimationUtils;
import com.hippo.ripple.Ripple;
import com.hippo.scene.Announcer;
@@ -98,13 +99,13 @@ import com.hippo.widget.AutoWrapLayout;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.ObservedTextView;
import com.hippo.widget.ProgressView;
import com.hippo.widget.ProgressiveRatingBar;
import com.hippo.widget.SimpleGridAutoSpanLayout;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
@@ -400,7 +401,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
long gid = getGid();
if (gid != -1) {
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
mDownloadState = EhApplication.getDownloadManager(context).getDownloadState(gid);
} else {
mDownloadState = DownloadInfo.STATE_INVALID;
@@ -415,7 +416,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mViewTransition = new ViewTransition(mainView, progressView, mTip);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_weird_face);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
@@ -531,7 +532,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
super.onDestroyView();
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
EhApplication.getDownloadManager(context).removeDownloadInfoListener(this);
mTip = null;
@@ -587,7 +588,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
private boolean prepareData() {
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
if (mGalleryDetail != null) {
return true;
@@ -770,7 +771,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
Resources resources = getResources2();
AssertUtils.assertNotNull(resources);
Assert.assertNotNull(resources);
mThumb.load(EhCacheKeyFactory.getThumbKey(gd.gid), gd.thumb);
mTitle.setText(EhUtils.getSuitableTitle(gd));
@@ -913,12 +914,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,18 +938,16 @@ 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) {
Resources resources = getResources2();
AssertUtils.assertNotNull(resources);
Assert.assertNotNull(resources);
return resources.getString(R.string.rating_text, getRatingText(rating, resources), rating, ratingCount);
}
@@ -976,7 +970,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
PopupMenu popup = new PopupMenu(context, mOtherActions, Gravity.TOP);
mPopupMenu = popup;
popup.getMenuInflater().inflate(R.menu.scene_gallery_detail, popup.getMenu());
@@ -1713,17 +1707,17 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
}
private class RateDialogHelper implements ProgressiveRatingBar.OnUserRateListener,
private class RateDialogHelper implements GalleryRatingBar.OnUserRateListener,
DialogInterface.OnClickListener {
@Nullable
private ProgressiveRatingBar mRatingBar;
private GalleryRatingBar mRatingBar;
@Nullable
private TextView mRatingText;
public void setDialog(Dialog dialog, float rating) {
mRatingText = (TextView) ViewUtils.$$(dialog, R.id.rating_text);
mRatingBar = (ProgressiveRatingBar) ViewUtils.$$(dialog, R.id.rating_view);
mRatingBar = (GalleryRatingBar) ViewUtils.$$(dialog, R.id.rating_view);
mRatingText.setText(getRatingText(rating, getResources2()));
mRatingBar.setRating(rating);
mRatingBar.setOnUserRateListener(this);
@@ -37,10 +37,11 @@ import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryDetail;
import com.hippo.ripple.Ripple;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.ArrayList;
public final class GalleryInfoScene extends ToolbarScene implements EasyRecyclerView.OnItemClickListener {
@@ -84,7 +85,7 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
}
Resources resources = getResources2();
AssertUtils.assertNotNull(resources);
Assert.assertNotNull(resources);
mKeys.add(resources.getString(R.string.header_key));
mValues.add(resources.getString(R.string.header_value));
mKeys.add(resources.getString(R.string.key_gid));
@@ -155,7 +156,7 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
View view = inflater.inflate(R.layout.scene_gallery_info, container, false);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
mRecyclerView = (EasyRecyclerView) ViewUtils.$$(view, R.id.recycler_view);
InfoAdapter adapter = new InfoAdapter();
@@ -230,7 +231,7 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
public InfoAdapter() {
mInflater = getLayoutInflater2();
AssertUtils.assertNotNull(mInflater);
Assert.assertNotNull(mInflater);
}
@Override
@@ -88,12 +88,13 @@ import com.hippo.widget.ContentLayout;
import com.hippo.widget.FabLayout;
import com.hippo.widget.SearchBarMover;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.SimpleAnimatorListener;
import com.hippo.yorozuya.StringUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.io.File;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -256,7 +257,7 @@ public final class GalleryListScene extends BaseScene
super.onCreate(savedInstanceState);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
mClient = EhApplication.getEhClient(context);
if (savedInstanceState == null) {
@@ -385,7 +386,7 @@ public final class GalleryListScene extends BaseScene
View view = inflater.inflate(R.layout.scene_gallery_list, container, false);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Resources resources = context.getResources();
mHideActionFabSlop = ViewConfiguration.get(context).getScaledTouchSlop();
@@ -632,7 +633,7 @@ public final class GalleryListScene extends BaseScene
final ListView listView = (ListView) ViewUtils.$$(view, R.id.list_view);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
final List<QuickSearch> list = EhDB.getAllQuickSearch();
final ArrayAdapter<QuickSearch> adapter = new ArrayAdapter<>(context, R.layout.item_simple_list, list);
@@ -1192,6 +1193,14 @@ public final class GalleryListScene extends BaseScene
}
break;
}
if (newState == STATE_NORMAL || newState == STATE_SIMPLE_SEARCH) {
setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.LEFT);
setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.RIGHT);
} else {
setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.LEFT);
setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
}
}
@Override
@@ -53,10 +53,11 @@ import com.hippo.widget.ContentLayout;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.Slider;
import com.hippo.widget.recyclerview.AutoGridLayoutManager;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.ArrayList;
import java.util.Locale;
@@ -90,7 +91,7 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
super.onCreate(savedInstanceState);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
mClient = EhApplication.getEhClient(context);
if (savedInstanceState == null) {
onInit();
@@ -137,7 +138,7 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
mRecyclerView = contentLayout.getRecyclerView();
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Resources resources = context.getResources();
mAdapter = new GalleryPreviewAdapter();
@@ -261,7 +262,7 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
public GalleryPreviewAdapter() {
mInflater = getLayoutInflater2();
AssertUtils.assertNotNull(mInflater);
Assert.assertNotNull(mInflater);
}
@Override
@@ -64,10 +64,11 @@ import com.hippo.util.DrawableManager;
import com.hippo.view.ViewTransition;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.recyclerview.AutoStaggeredGridLayoutManager;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import de.greenrobot.dao.query.LazyList;
public class HistoryScene extends ToolbarScene
@@ -103,7 +104,7 @@ public class HistoryScene extends ToolbarScene
mViewTransition = new ViewTransition(content, tip);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Resources resources = context.getResources();
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_history);
@@ -36,9 +36,10 @@ import com.hippo.scene.SceneFragment;
import com.hippo.util.DrawableManager;
import com.hippo.util.ExceptionUtils;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
/**
* Only show a progress with jobs in background
*/
@@ -169,7 +170,7 @@ public final class ProgressScene extends BaseScene implements View.OnClickListen
mTip = (TextView) ViewUtils.$$(view, R.id.tip);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_weird_face);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
@@ -49,9 +49,10 @@ import com.hippo.ehviewer.R;
import com.hippo.ehviewer.dao.QuickSearch;
import com.hippo.util.DrawableManager;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.List;
public final class QuickSearchScene extends ToolbarScene {
@@ -96,7 +97,7 @@ public final class QuickSearchScene extends ToolbarScene {
mViewTransition = new ViewTransition(mRecyclerView, tip);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_search);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
@@ -197,7 +198,7 @@ public final class QuickSearchScene extends ToolbarScene {
public QuickSearchAdapter() {
mInflater = getLayoutInflater2();
AssertUtils.assertNotNull(mInflater);
Assert.assertNotNull(mInflater);
}
@Override
@@ -248,6 +249,11 @@ public final class QuickSearchScene extends ToolbarScene {
notifyItemMoved(fromPosition, toPosition);
}
@Override
public boolean onCheckCanDrop(int draggingPosition, int dropPosition) {
return true;
}
@Override
public int onGetSwipeReactionType(QuickSearchHolder holder, int position, int x, int y) {
if (ViewUtils.isViewUnder(holder.getSwipeableContainerView(), x, y, 0)) {
@@ -31,13 +31,14 @@ import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.hardware.ShakeDetector;
import com.hippo.widget.lockpattern.LockPatternUtils;
import com.hippo.widget.lockpattern.LockPatternView;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ObjectUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.List;
public class SecurityScene extends BaseScene implements
public class SecurityScene extends SolidScene implements
LockPatternView.OnPatternListener, ShakeDetector.OnShakeListener {
private static final int MAX_RETRY_TIMES = 5;
@@ -63,7 +64,7 @@ public class SecurityScene extends BaseScene implements
super.onCreate(savedInstanceState);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
if (null != mSensorManager) {
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
@@ -152,7 +153,7 @@ public class SecurityScene extends BaseScene implements
String targetPatter = Settings.getSecurity();
if (ObjectUtils.equal(enteredPatter, targetPatter)) {
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_SECURITY, getArguments());
startSceneForCheckStep(CHECK_STEP_SECURITY, getArguments());
finish();
} else {
mPatternView.setDisplayMode(LockPatternView.DisplayMode.Wrong);
@@ -171,7 +172,7 @@ public class SecurityScene extends BaseScene implements
return;
}
Settings.putSecurity("");
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_SECURITY, getArguments());
startSceneForCheckStep(CHECK_STEP_SECURITY, getArguments());
finish();
}
}
@@ -30,7 +30,7 @@ import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.yorozuya.ViewUtils;
public class SelectSiteScene extends BaseScene implements View.OnClickListener {
public class SelectSiteScene extends SolidScene implements View.OnClickListener {
private RadioGroup mRadioGroup;
private View mOk;
@@ -74,14 +74,14 @@ public class SelectSiteScene extends BaseScene implements View.OnClickListener {
switch (id) {
case R.id.site_e:
Settings.putSelectSite(false);
Settings.putGallerySite(EhUrl.SITE_G);
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_SELECT_SITE, getArguments());
Settings.putGallerySite(EhUrl.SITE_E);
startSceneForCheckStep(CHECK_STEP_SELECT_SITE, getArguments());
finish();
break;
case R.id.site_ex:
Settings.putSelectSite(false);
Settings.putGallerySite(EhUrl.SITE_EX);
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_SELECT_SITE, getArguments());
startSceneForCheckStep(CHECK_STEP_SELECT_SITE, getArguments());
finish();
break;
default:
@@ -42,10 +42,11 @@ import com.hippo.ehviewer.client.parser.ProfileParser;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.scene.Announcer;
import com.hippo.scene.SceneFragment;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
public final class SignInScene extends BaseScene implements EditText.OnEditorActionListener,
import junit.framework.Assert;
public final class SignInScene extends SolidScene implements EditText.OnEditorActionListener,
View.OnClickListener {
private static final String KEY_REQUEST_ID = "request_id";
@@ -119,10 +120,10 @@ public final class SignInScene extends BaseScene implements EditText.OnEditorAct
mProgress = ViewUtils.$$(view, R.id.progress);
mUsernameLayout = (TextInputLayout) ViewUtils.$$(loginForm, R.id.username_layout);
mUsername = mUsernameLayout.getEditText();
AssertUtils.assertNotNull(mUsername);
Assert.assertNotNull(mUsername);
mPasswordLayout = (TextInputLayout) ViewUtils.$$(loginForm, R.id.password_layout);
mPassword = mPasswordLayout.getEditText();
AssertUtils.assertNotNull(mPassword);
Assert.assertNotNull(mPassword);
mRegister = ViewUtils.$$(loginForm, R.id.register);
mSignIn = ViewUtils.$$(loginForm, R.id.sign_in);
mSignInViaWebView = (TextView) ViewUtils.$$(loginForm, R.id.sign_in_via_webview);
@@ -142,7 +143,7 @@ public final class SignInScene extends BaseScene implements EditText.OnEditorAct
mSkipSigningIn.setOnClickListener(this);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
EhApplication application = (EhApplication) context.getApplicationContext();
if (application.containGlobalStuff(mRequestId)) {
mSigningIn = true;
@@ -225,8 +226,8 @@ public final class SignInScene extends BaseScene implements EditText.OnEditorAct
} else if (mSignInViaCookies == v) {
startScene(new Announcer(CookieSignInScene.class).setRequestCode(this, REQUEST_CODE_COOKIE));
} else if (mSkipSigningIn == v) {
// Set gallery size SITE_G if skip sign in
Settings.putGallerySite(EhUrl.SITE_G);
// Set gallery size SITE_E if skip sign in
Settings.putGallerySite(EhUrl.SITE_E);
redirectTo();
}
}
@@ -313,7 +314,7 @@ public final class SignInScene extends BaseScene implements EditText.OnEditorAct
Settings.putNeedSignIn(false);
MainActivity activity = getActivity2();
if (null != activity) {
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_SIGN_IN, getArguments());
startSceneForCheckStep(CHECK_STEP_SIGN_IN, getArguments());
}
finish();
}
@@ -0,0 +1,98 @@
/*
* 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.ehviewer.ui.scene;
import android.os.Bundle;
import android.util.Log;
import com.hippo.ehviewer.Crash;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.scene.Announcer;
/**
* Scene for safety, can't be covered
*/
public class SolidScene extends BaseScene {
private static final String TAG = SolidScene.class.getSimpleName();
public static final int CHECK_STEP_SECURITY = 0;
public static final int CHECK_STEP_WARNING = 1;
public static final int CHECK_STEP_ANALYTICS = 2;
public static final int CHECK_STEP_CRASH = 3;
public static final int CHECK_STEP_SIGN_IN = 4;
public static final int CHECK_STEP_SELECT_SITE = 5;
public static final String KEY_TARGET_SCENE = "target_scene";
public static final String KEY_TARGET_ARGS = "target_args";
public void startSceneForCheckStep(int checkStep, Bundle args) {
switch (checkStep) {
case CHECK_STEP_SECURITY:
if (Settings.getShowWarning()) {
startScene(new Announcer(WarningScene.class).setArgs(args));
break;
}
case CHECK_STEP_WARNING:
if (Settings.getAskAnalytics()) {
startScene(new Announcer(AnalyticsScene.class).setArgs(args));
break;
}
case CHECK_STEP_ANALYTICS:
if (Crash.hasCrashFile()) {
startScene(new Announcer(CrashScene.class).setArgs(args));
break;
}
case CHECK_STEP_CRASH:
if (EhUtils.needSignedIn(getContext2())) {
startScene(new Announcer(SignInScene.class).setArgs(args));
break;
}
case CHECK_STEP_SIGN_IN:
if (Settings.getSelectSite()) {
startScene(new Announcer(SelectSiteScene.class).setArgs(args));
break;
}
case CHECK_STEP_SELECT_SITE:
String targetScene = null;
Bundle targetArgs = null;
if (null != args) {
targetScene = args.getString(KEY_TARGET_SCENE);
targetArgs = args.getBundle(KEY_TARGET_ARGS);
}
Class<?> clazz = null;
if (targetScene != null) {
try {
clazz = Class.forName(targetScene);
} catch (ClassNotFoundException e) {
Log.e(TAG, "Can't find class with name: " + targetScene);
}
}
if (clazz != null) {
startScene(new Announcer(clazz).setArgs(targetArgs));
} else {
Bundle newArgs = new Bundle();
newArgs.putString(GalleryListScene.KEY_ACTION, GalleryListScene.ACTION_HOMEPAGE);
startScene(new Announcer(GalleryListScene.class).setArgs(newArgs));
}
break;
}
}
}
@@ -28,7 +28,7 @@ import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.ehviewer.ui.annotation.ViewLifeCircle;
import com.hippo.yorozuya.ViewUtils;
public final class WarningScene extends BaseScene implements View.OnClickListener {
public final class WarningScene extends SolidScene implements View.OnClickListener {
@Nullable
private View mReject;
@@ -75,7 +75,7 @@ public final class WarningScene extends BaseScene implements View.OnClickListene
// Start new scene and finish it self
MainActivity activity = getActivity2();
if (null != activity) {
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_WARNING, getArguments());
startSceneForCheckStep(CHECK_STEP_WARNING, getArguments());
}
finish();
}
@@ -33,7 +33,8 @@ import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.yorozuya.AssertUtils;
import junit.framework.Assert;
import java.util.ArrayList;
import java.util.Collections;
@@ -42,7 +43,7 @@ import java.util.List;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
public class WebViewSignInScene extends BaseScene {
public class WebViewSignInScene extends SolidScene {
/*---------------
View life cycle
@@ -62,7 +63,7 @@ public class WebViewSignInScene extends BaseScene {
public View onCreateView2(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
EhUtils.signOut(context);
@@ -1,11 +1,11 @@
/*
* Copyright (C) 2014 Hippo Seven
* Copyright 2014-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
* 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,
@@ -14,33 +14,44 @@
* limitations under the License.
*/
package com.hippo.widget;
package com.hippo.ehviewer.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.support.v7.widget.AppCompatRatingBar;
import android.util.AttributeSet;
import android.widget.RatingBar;
public class ProgressiveRatingBar extends AppCompatRatingBar {
public class GalleryRatingBar extends AppCompatRatingBar
implements RatingBar.OnRatingBarChangeListener {
private OnUserRateListener mListener;
public ProgressiveRatingBar(Context context) {
public GalleryRatingBar(Context context) {
super(context);
init();
}
public ProgressiveRatingBar(Context context, AttributeSet attrs) {
public GalleryRatingBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ProgressiveRatingBar(Context context, AttributeSet attrs,
public GalleryRatingBar(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setOnRatingBarChangeListener(this);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isPressed() && mListener != null) {
if (mListener != null) {
mListener.onUserRate(getRating());
}
}
@@ -49,6 +60,13 @@ public class ProgressiveRatingBar extends AppCompatRatingBar {
mListener = l;
}
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
if (rating <= 0.0f) {
setRating(0.5f);
}
}
public interface OnUserRateListener {
void onUserRate(float rating);
}
@@ -1,48 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.anim;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.yorozuya.MathUtils;
public class AlphaAnimation extends CanvasAnimation {
private final float mStartAlpha;
private final float mEndAlpha;
private float mCurrentAlpha;
public AlphaAnimation(float from, float to) {
mStartAlpha = from;
mEndAlpha = to;
mCurrentAlpha = from;
}
@Override
public void apply(GLCanvas canvas) {
canvas.multiplyAlpha(mCurrentAlpha);
}
@Override
public int getCanvasSaveFlags() {
return GLCanvas.SAVE_FLAG_ALPHA;
}
@Override
protected void onCalculate(float progress) {
mCurrentAlpha = MathUtils.clamp(mStartAlpha +
(mEndAlpha - mStartAlpha) * progress, 0f, 1f);
}
}
@@ -1,167 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.anim;
import android.os.SystemClock;
import android.view.animation.Interpolator;
import com.hippo.yorozuya.MathUtils;
// Animation calculates a value according to the current input time.
//
// 1. First we need to use setDuration(int) to set the duration of the
// animation. The duration is in milliseconds.
// 2. Then we should call start(). The actual start time is the first value
// passed to calculate(long).
// 3. Each time we want to get an animation value, we call
// calculate(long currentTimeMillis) to ask the Animation to calculate it.
// The parameter passed to calculate(long) should be nonnegative.
// 4. Use get() to get that value.
//
// In step 3, onCalculate(float progress) is called so subclasses can calculate
// the value according to progress (progress is a value in [0,1]).
//
// Before onCalculate(float) is called, There is an optional interpolator which
// can change the progress value. The interpolator can be set by
// setInterpolator(Interpolator). If the interpolator is used, the value passed
// to onCalculate may be (for example, the overshoot effect).
//
// The isActive() method returns true after the animation start() is called and
// before calculate is passed a value which reaches the duration of the
// animation.
//
// The start() method can be called again to restart the Animation.
//
abstract public class Animation {
private static final long ANIMATION_START = -1;
private static final long NO_ANIMATION = -2;
/**
* When the animation reaches the end and <code>repeatCount</code> is INFINITE
* or a positive value, the animation restarts from the beginning.
*/
public static final int RESTART = 1;
/**
* When the animation reaches the end and <code>repeatCount</code> is INFINITE
* or a positive value, the animation reverses direction on every iteration.
*/
public static final int REVERSE = 2;
/**
* This value used used with the {@link #setRepeatCount(int)} property to repeat
* the animation indefinitely.
*/
public static final int INFINITE = -1;
private long mStartTime = NO_ANIMATION;
private long mDuration;
private Interpolator mInterpolator;
private int mRepeatCount;
private int mRepeatMode;
private int mRunnedCount;
private long mLastFrameTime;
public void setInterpolator(Interpolator interpolator) {
mInterpolator = interpolator;
}
public void setDuration(long duration) {
mDuration = duration;
}
public void setRepeatCount(int repeatCount) {
mRepeatCount = repeatCount;
}
public void setRepeatMode(int repeatMode) {
mRepeatMode = repeatMode;
}
public boolean isRunning() {
return mStartTime > 0 || mStartTime == ANIMATION_START;
}
public long getLastFrameTime() {
return mLastFrameTime;
}
public void start() {
if (mStartTime == NO_ANIMATION) {
mStartTime = ANIMATION_START;
mRunnedCount = 0;
mLastFrameTime = 0;
}
}
public void startAt(long time) {
start();
setStartTime(time);
}
public void startNow() {
start();
setStartTime(SystemClock.uptimeMillis());
}
public void setStartTime(long time) {
mStartTime = time;
}
public void cancel() {
mStartTime = NO_ANIMATION;
}
public void reset() {
mStartTime = ANIMATION_START;
mRunnedCount = 0;
mLastFrameTime = 0;
}
// TODO mRepeatMode
public boolean calculate(long currentTimeMillis) {
if (mStartTime == NO_ANIMATION) {
return false;
}
if (mStartTime == ANIMATION_START) {
mStartTime = currentTimeMillis;
}
mLastFrameTime = currentTimeMillis;
long elapse = currentTimeMillis - mStartTime;
float x = MathUtils.clamp(mDuration == 0.0f ? 1.0f : (float) elapse / mDuration, 0.0f, 1.0f); // Avoid NaN
Interpolator i = mInterpolator;
onCalculate(i != null ? i.getInterpolation(x) : x);
// It is ok to call cancel() in onCalculate()
if (mStartTime != NO_ANIMATION && elapse >= mDuration) {
mRunnedCount++;
if (mRunnedCount >= mRepeatCount && mRepeatCount != INFINITE) {
onFinish();
mStartTime = NO_ANIMATION;
} else {
mStartTime += elapse;
}
}
return mStartTime != NO_ANIMATION;
}
abstract protected void onCalculate(float progress);
protected void onFinish() {
}
}
@@ -1,25 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.anim;
import com.hippo.gl.glrenderer.GLCanvas;
public abstract class CanvasAnimation extends Animation {
public abstract int getCanvasSaveFlags();
public abstract void apply(GLCanvas canvas);
}
@@ -1,40 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.anim;
import com.hippo.yorozuya.MathUtils;
public class FloatAnimation extends Animation {
private float mFrom;
private float mTo;
private float mCurrent;
public void setRange(float from, float to) {
mFrom = from;
mTo = to;
}
@Override
protected void onCalculate(float progress) {
mCurrent = MathUtils.lerp(mFrom, mTo, progress);
}
public float get() {
return mCurrent;
}
}
@@ -1,27 +0,0 @@
/*
* 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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE})
public @interface RenderThread {
}
@@ -1,222 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.RectF;
import android.util.Log;
import com.hippo.yorozuya.MathUtils;
import java.util.WeakHashMap;
// BasicTexture is a Texture corresponds to a real GL texture.
// The state of a BasicTexture indicates whether its data is loaded to GL memory.
// If a BasicTexture is loaded into GL memory, it has a GL texture id.
public abstract class BasicTexture implements Texture {
@SuppressWarnings("unused")
private static final String TAG = "BasicTexture";
protected static final int UNSPECIFIED = -1;
protected static final int STATE_UNLOADED = 0;
protected static final int STATE_LOADED = 1;
protected static final int STATE_ERROR = -1;
// Log a warning if a texture is larger along a dimension
private static final int MAX_TEXTURE_SIZE = 4096;
protected int mId = -1;
protected int mState;
protected int mWidth = UNSPECIFIED;
protected int mHeight = UNSPECIFIED;
protected int mTextureWidth;
protected int mTextureHeight;
private boolean mHasBorder;
protected GLCanvas mCanvasRef = null;
private final static WeakHashMap<BasicTexture, Object> sAllTextures
= new WeakHashMap<>();
private static ThreadLocal<Class> sInFinalizer = new ThreadLocal<>();
protected BasicTexture(GLCanvas canvas, int id, int state) {
setAssociatedCanvas(canvas);
mId = id;
mState = state;
synchronized (sAllTextures) {
sAllTextures.put(this, null);
}
}
protected BasicTexture() {
this(null, 0, STATE_UNLOADED);
}
protected void setAssociatedCanvas(GLCanvas canvas) {
mCanvasRef = canvas;
}
/**
* Sets the content size of this texture. In OpenGL, the actual texture
* size must be of power of 2, the size of the content may be smaller.
*/
public void setSize(int width, int height) {
mWidth = width;
mHeight = height;
mTextureWidth = width > 0 ? MathUtils.nextPowerOf2(width) : 0;
mTextureHeight = height > 0 ? MathUtils.nextPowerOf2(height) : 0;
if (mTextureWidth > MAX_TEXTURE_SIZE || mTextureHeight > MAX_TEXTURE_SIZE) {
Log.w(TAG, String.format("texture is too large: %d x %d",
mTextureWidth, mTextureHeight), new Exception());
}
}
public boolean isFlippedVertically() {
return false;
}
public int getId() {
return mId;
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
// Returns the width rounded to the next power of 2.
public int getTextureWidth() {
return mTextureWidth;
}
// Returns the height rounded to the next power of 2.
public int getTextureHeight() {
return mTextureHeight;
}
// Returns true if the texture has one pixel transparent border around the
// actual content. This is used to avoid jigged edges.
//
// The jigged edges appear because we use GL_CLAMP_TO_EDGE for texture wrap
// mode (GL_CLAMP is not available in OpenGL ES), so a pixel partially
// covered by the texture will use the color of the edge texel. If we add
// the transparent border, the color of the edge texel will be mixed with
// appropriate amount of transparent.
//
// Currently our background is black, so we can draw the thumbnails without
// enabling blending.
public boolean hasBorder() {
return mHasBorder;
}
protected void setBorder(boolean hasBorder) {
mHasBorder = hasBorder;
}
@Override
public void draw(GLCanvas canvas, int x, int y) {
canvas.drawTexture(this, x, y, getWidth(), getHeight());
}
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
canvas.drawTexture(this, x, y, w, h);
}
@Override
public void draw(GLCanvas canvas, RectF source, RectF target) {
canvas.drawTexture(this, source, target);
}
// onBind is called before GLCanvas binds this texture.
// It should make sure the data is uploaded to GL memory.
abstract protected boolean onBind(GLCanvas canvas);
// Returns the GL texture target for this texture (e.g. GL_TEXTURE_2D).
abstract protected int getTarget();
public boolean isLoaded() {
return mState == STATE_LOADED;
}
// recycle() is called when the texture will never be used again,
// so it can free all resources.
public void recycle() {
freeResource();
}
// yield() is called when the texture will not be used temporarily,
// so it can free some resources.
// The default implementation unloads the texture from GL memory, so
// the subclass should make sure it can reload the texture to GL memory
// later, or it will have to override this method.
public void yield() {
freeResource();
}
private void freeResource() {
GLCanvas canvas = mCanvasRef;
if (canvas != null && mId != -1) {
canvas.unloadTexture(this);
mId = -1; // Don't free it again.
}
mState = STATE_UNLOADED;
setAssociatedCanvas(null);
}
@Override
protected void finalize() throws Throwable {
try {
sInFinalizer.set(BasicTexture.class);
recycle();
sInFinalizer.set(null);
} finally {
super.finalize();
}
}
// This is for deciding if we can call Bitmap's recycle().
// We cannot call Bitmap's recycle() in finalizer because at that point
// the finalizer of Bitmap may already be called so recycle() will crash.
public static boolean inFinalizer() {
return sInFinalizer.get() != null;
}
public static void yieldAllTextures() {
synchronized (sAllTextures) {
for (BasicTexture t : sAllTextures.keySet()) {
t.yield();
}
}
}
public static void invalidateAllTextures() {
synchronized (sAllTextures) {
for (BasicTexture t : sAllTextures.keySet()) {
t.mState = STATE_UNLOADED;
t.setAssociatedCanvas(null);
}
}
}
}
@@ -1,54 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import com.hippo.yorozuya.AssertUtils;
// BitmapTexture is a texture whose content is specified by a fixed Bitmap.
//
// The texture does not own the Bitmap. The user should make sure the Bitmap
// is valid during the texture's lifetime. When the texture is recycled, it
// does not free the Bitmap.
public class BitmapTexture extends UploadedTexture {
protected Bitmap mContentBitmap;
public BitmapTexture(Bitmap bitmap) {
this(bitmap, false);
}
public BitmapTexture(Bitmap bitmap, boolean hasBorder) {
super(hasBorder);
AssertUtils.assertTrue(bitmap != null && !bitmap.isRecycled());
mContentBitmap = bitmap;
}
@Override
protected void onFreeBitmap(Bitmap bitmap) {
// Do nothing.
}
@Override
protected Bitmap onGetBitmap() {
return mContentBitmap;
}
public Bitmap getBitmap() {
return mContentBitmap;
}
}
@@ -1,51 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
// CanvasTexture is a texture whose content is the drawing on a Canvas.
// The subclasses should override onDraw() to draw on the bitmap.
// By default CanvasTexture is not opaque.
abstract class CanvasTexture extends UploadedTexture {
private final Config mConfig;
public CanvasTexture(int width, int height) {
mConfig = Config.ARGB_8888;
setSize(width, height);
setOpaque(false);
}
@Override
protected Bitmap onGetBitmap() {
Bitmap bitmap = Bitmap.createBitmap(mWidth, mHeight, mConfig);
Canvas canvas = new Canvas(bitmap);
onDraw(canvas, bitmap);
return bitmap;
}
@Override
protected void onFreeBitmap(Bitmap bitmap) {
if (!inFinalizer()) {
bitmap.recycle();
}
}
abstract protected void onDraw(Canvas canvas, Bitmap backing);
}
@@ -1,74 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.RectF;
import com.hippo.yorozuya.ColorUtils;
// ColorTexture is a texture which fills the rectangle with the specified color.
public class ColorTexture implements Texture {
private final int mColor;
private int mWidth = 0;
private int mHeight = 0;
public ColorTexture(int color) {
mColor = color;
}
private boolean isValidSize() {
return mWidth > 0 && mHeight > 0;
}
@Override
public void draw(GLCanvas canvas, int x, int y) {
if (isValidSize()) {
draw(canvas, x, y, mWidth, mHeight);
}
}
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
canvas.fillRect(x, y, w, h, mColor);
}
@Override
public void draw(GLCanvas canvas, RectF source, RectF target) {
canvas.fillRect(target.left, target.top, target.width(), target.height(), mColor);
}
@Override
public boolean isOpaque() {
return ColorUtils.isOpaque(mColor);
}
public void setSize(int width, int height) {
mWidth = width;
mHeight = height;
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
}
@@ -1,60 +0,0 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
// ExtTexture is a texture whose content comes from a external texture.
// Before drawing, setSize() should be called.
public class ExtTexture extends BasicTexture {
private int mTarget;
public ExtTexture(GLCanvas canvas, int target) {
GLId glId = canvas.getGLId();
mId = glId.generateTexture();
mTarget = target;
}
private void uploadToCanvas(GLCanvas canvas) {
canvas.setTextureParameters(this);
setAssociatedCanvas(canvas);
mState = STATE_LOADED;
}
@Override
protected boolean onBind(GLCanvas canvas) {
if (!isLoaded()) {
uploadToCanvas(canvas);
}
return true;
}
@Override
public int getTarget() {
return mTarget;
}
@Override
public boolean isOpaque() {
return true;
}
@Override
public void yield() {
// we cannot free the texture because we have no backup.
}
}
@@ -1,54 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.RectF;
// FadeInTexture is a texture which begins with a color, then gradually animates
// into a given texture.
public class FadeInTexture extends FadeTexture implements Texture {
@SuppressWarnings("unused")
private static final String TAG = "FadeInTexture";
private final int mColor;
private final TiledTexture mTexture;
public FadeInTexture(int color, TiledTexture texture) {
super(texture.getWidth(), texture.getHeight(), texture.isOpaque());
mColor = color;
mTexture = texture;
}
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
if (isAnimating()) {
mTexture.drawMixed(canvas, mColor, getRatio(), x, y, w, h);
} else {
mTexture.draw(canvas, x, y, w, h);
}
}
@Override
public void draw(GLCanvas canvas, RectF source, RectF target) {
if (isAnimating()) {
mTexture.drawMixed(canvas, mColor, getRatio(), source, target);
} else {
mTexture.draw(canvas, source, target);
}
}
}
@@ -1,54 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.RectF;
// FadeOutTexture is a texture which begins with a given texture, then gradually animates
// into fading out totally.
public class FadeOutTexture extends FadeTexture {
@SuppressWarnings("unused")
private static final String TAG = "FadeOutTexture";
private final BasicTexture mTexture;
public FadeOutTexture(BasicTexture texture) {
super(texture.getWidth(), texture.getHeight(), texture.isOpaque());
mTexture = texture;
}
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
if (isAnimating()) {
canvas.save(GLCanvas.SAVE_FLAG_ALPHA);
canvas.setAlpha(getRatio());
mTexture.draw(canvas, x, y, w, h);
canvas.restore();
}
}
@Override
public void draw(GLCanvas canvas, RectF source, RectF target) {
if (isAnimating()) {
canvas.save(GLCanvas.SAVE_FLAG_ALPHA);
canvas.setAlpha(getRatio());
mTexture.draw(canvas, source, target);
canvas.restore();
}
}
}
@@ -1,81 +0,0 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import com.hippo.gl.view.AnimationTime;
import com.hippo.yorozuya.MathUtils;
// FadeTexture is a texture which fades the given texture along the time.
public abstract class FadeTexture implements Texture {
@SuppressWarnings("unused")
private static final String TAG = "FadeTexture";
// The duration of the fading animation in milliseconds
public static final int DURATION = 180;
private final long mStartTime;
private final int mWidth;
private final int mHeight;
private final boolean mIsOpaque;
private boolean mIsAnimating;
public FadeTexture(int width, int height, boolean opaque) {
mWidth = width;
mHeight = height;
mIsOpaque = opaque;
mStartTime = now();
mIsAnimating = true;
}
@Override
public void draw(GLCanvas canvas, int x, int y) {
draw(canvas, x, y, mWidth, mHeight);
}
@Override
public boolean isOpaque() {
return mIsOpaque;
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
public boolean isAnimating() {
if (mIsAnimating) {
if (now() - mStartTime >= DURATION) {
mIsAnimating = false;
}
}
return mIsAnimating;
}
protected float getRatio() {
float r = (float)(now() - mStartTime) / DURATION;
return MathUtils.clamp(1.0f - r, 0.0f, 1.0f);
}
private long now() {
return AnimationTime.get();
}
}
@@ -1,223 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.RectF;
//
// GLCanvas gives a convenient interface to draw using OpenGL.
//
// When a rectangle is specified in this interface, it means the region
// [x, x+width) * [y, y+height)
//
public interface GLCanvas {
GLId getGLId();
// Tells GLCanvas the size of the underlying GL surface. This should be
// called before first drawing and when the size of GL surface is changed.
// This is called by GLRoot and should not be called by the clients
// who only want to draw on the GLCanvas. Both width and height must be
// nonnegative.
void setSize(int width, int height);
// Clear the drawing buffers. This should only be used by GLRoot.
void clearBuffer();
void clearBuffer(float[] argb);
// Sets and gets the current alpha, alpha must be in [0, 1].
void setAlpha(float alpha);
float getAlpha();
// (current alpha) = (current alpha) * alpha
void multiplyAlpha(float alpha);
// Change the current transform matrix.
void translate(float x, float y, float z);
void translate(float x, float y);
void scale(float sx, float sy, float sz);
void rotate(float angle, float x, float y, float z);
void multiplyMatrix(float[] mMatrix, int offset);
// Pushes the configuration state (matrix, and alpha) onto
// a private stack.
void save();
// Same as save(), but only save those specified in saveFlags.
void save(int saveFlags);
int SAVE_FLAG_ALL = 0xFFFFFFFF;
int SAVE_FLAG_ALPHA = 0x01;
int SAVE_FLAG_MATRIX = 0x02;
// Pops from the top of the stack as current configuration state (matrix,
// alpha, and clip). This call balances a previous call to save(), and is
// used to remove all modifications to the configuration state since the
// last save call.
void restore();
// Draws a line using the specified paint from (x1, y1) to (x2, y2).
// (Both end points are included).
void drawLine(float x1, float y1, float x2, float y2, GLPaint paint);
// Draws a rectangle using the specified paint from (x1, y1) to (x2, y2).
// (Both end points are included).
void drawRect(float x1, float y1, float x2, float y2, GLPaint paint);
// Draws a oval using the specified paint for (cx, cy, radiusX, radiusY)
// (Both end points are included).
void drawOval(float cx, float cy, float radiusX, float radiusY,
GLPaint paint);
// Draw a arc inside a rect
void drawArc(float cx, float cy, float radiusX, float radiusY,
float sweepAngle, GLPaint paint);
// Fills the specified rectangle with the specified color.
void fillRect(float x, float y, float width, float height, int color);
// Fills the specified oval with the specified color.
void fillOval(float cx, float cy, float radiusX, float radiusY, int color);
// Fills the specified sector with the specified color.
void fillSector(float cx, float cy, float radiusX, float radiusY, float sweepAngle, int color);
// Draws a texture to the specified rectangle.
void drawTexture(BasicTexture texture, int x, int y, int width, int height);
void drawMesh(BasicTexture tex, int x, int y, int xyBuffer, int uvBuffer, int indexBuffer, int indexCount);
// Draws the source rectangle part of the texture to the target rectangle.
void drawTexture(BasicTexture texture, RectF source, RectF target);
// Draw a texture with a specified texture transform.
void drawTexture(BasicTexture texture, float[] mTextureTransform, int x, int y, int w, int h);
// Draw two textures to the specified rectangle. The actual texture used is
// from * (1 - ratio) + to * ratio
// The two textures must have the same size.
void drawMixed(BasicTexture from, int toColor, float ratio, int x, int y, int w, int h);
// Draw a region of a texture and a specified color to the specified
// rectangle. The actual color used is from * (1 - ratio) + to * ratio.
// The region of the texture is defined by parameter "src". The target
// rectangle is specified by parameter "target".
void drawMixed(BasicTexture from, int toColor, float ratio, RectF src, RectF target);
// Unloads the specified texture from the canvas. The resource allocated
// to draw the texture will be released. The specified texture will return
// to the unloaded state. This function should be called only from
// BasicTexture or its descendant
boolean unloadTexture(BasicTexture texture);
// Delete the specified buffer object, similar to unloadTexture.
void deleteBuffer(int bufferId);
// Delete the textures and buffers in GL side. This function should only be
// called in the GL thread.
void deleteRecycledResources();
// Dump statistics information and clear the counters. For debug only.
void dumpStatisticsAndClear();
void beginRenderTarget(RawTexture texture);
void endRenderTarget();
/**
* Sets texture parameters to use GL_CLAMP_TO_EDGE for both
* GL_TEXTURE_WRAP_S and GL_TEXTURE_WRAP_T. Sets texture parameters to be
* GL_LINEAR for GL_TEXTURE_MIN_FILTER and GL_TEXTURE_MAG_FILTER.
* bindTexture() must be called prior to this.
*
* @param texture The texture to set parameters on.
*/
void setTextureParameters(BasicTexture texture);
/**
* Initializes the texture to a size by calling texImage2D on it.
*
* @param texture The texture to initialize the size.
* @param format The texture format (e.g. GL_RGBA)
* @param type The texture type (e.g. GL_UNSIGNED_BYTE)
*/
void initializeTextureSize(BasicTexture texture, int format, int type);
/**
* Initializes the texture to a size by calling texImage2D on it.
*
* @param texture The texture to initialize the size.
* @param bitmap The bitmap to initialize the bitmap with.
*/
void initializeTexture(BasicTexture texture, Bitmap bitmap);
/**
* Calls glTexSubImage2D to upload a bitmap to the texture.
*
* @param texture The target texture to write to.
* @param xOffset Specifies a texel offset in the x direction within the
* texture array.
* @param yOffset Specifies a texel offset in the y direction within the
* texture array.
* @param format The texture format (e.g. GL_RGBA)
* @param type The texture type (e.g. GL_UNSIGNED_BYTE)
*/
void texSubImage2D(BasicTexture texture, int xOffset, int yOffset, Bitmap bitmap, int format, int type);
/**
* Generates buffers and uploads the buffer data.
*
* @param buffer The buffer to upload
* @return The buffer ID that was generated.
*/
int uploadBuffer(java.nio.FloatBuffer buffer);
/**
* Generates buffers and uploads the element array buffer data.
*
* @param buffer The buffer to upload
* @return The buffer ID that was generated.
*/
int uploadBuffer(java.nio.ByteBuffer buffer);
/**
* After LightCycle makes GL calls, this method is called to restore the GL
* configuration to the one expected by GLCanvas.
*/
void recoverFromLightCycle();
/**
* Gets the bounds given by x, y, width, and height as well as the internal
* matrix state. There is no special handling for non-90-degree rotations.
* It only considers the lower-left and upper-right corners as the bounds.
*
* @param bounds The output bounds to write to.
* @param x The left side of the input rectangle.
* @param y The bottom of the input rectangle.
* @param width The width of the input rectangle.
* @param height The height of the input rectangle.
*/
void getBounds(Rect bounds, int x, int y, int width, int height);
}
File diff suppressed because it is too large. Load diff
@@ -1,42 +0,0 @@
package com.hippo.gl.glrenderer;
import android.opengl.GLES20;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11ExtensionPack;
public class GLES20IdImpl implements GLId {
private final int[] mTempIntArray = new int[1];
@Override
public int generateTexture() {
GLES20.glGenTextures(1, mTempIntArray, 0);
GLES20Canvas.checkError();
return mTempIntArray[0];
}
@Override
public void glGenBuffers(int n, int[] buffers, int offset) {
GLES20.glGenBuffers(n, buffers, offset);
GLES20Canvas.checkError();
}
@Override
public void glDeleteTextures(GL11 gl, int n, int[] textures, int offset) {
GLES20.glDeleteTextures(n, textures, offset);
GLES20Canvas.checkError();
}
@Override
public void glDeleteBuffers(GL11 gl, int n, int[] buffers, int offset) {
GLES20.glDeleteBuffers(n, buffers, offset);
GLES20Canvas.checkError();
}
@Override
public void glDeleteFramebuffers(GL11ExtensionPack gl11ep, int n, int[] buffers, int offset) {
GLES20.glDeleteFramebuffers(n, buffers, offset);
GLES20Canvas.checkError();
}
}
@@ -1,33 +0,0 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11ExtensionPack;
// This mimics corresponding GL functions.
public interface GLId {
int generateTexture();
void glGenBuffers(int n, int[] buffers, int offset);
void glDeleteTextures(GL11 gl, int n, int[] textures, int offset);
void glDeleteBuffers(GL11 gl, int n, int[] buffers, int offset);
void glDeleteFramebuffers(GL11ExtensionPack gl11ep, int n, int[] buffers, int offset);
}
@@ -1,50 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import junit.framework.Assert;
public class GLPaint {
private float mLineWidth = 1f;
private int mColor = 0;
private int mBackgroundColor = 0;
public void setColor(int color) {
mColor = color;
}
public int getColor() {
return mColor;
}
public void setBackgroundColor(int backgroundColor) {
mBackgroundColor = backgroundColor;
}
public int getBackgroundColor() {
return mBackgroundColor;
}
public void setLineWidth(float width) {
Assert.assertTrue(width >= 0);
mLineWidth = width;
}
public float getLineWidth() {
return mLineWidth;
}
}
@@ -1,689 +0,0 @@
/*
* Copyright (C) 2015 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.graphics.drawable.Animatable;
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.PVLock;
import com.hippo.yorozuya.thread.PriorityThreadFactory;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public class ImageTexture implements Texture, Animatable {
@IntDef({TILE_SMALL, TILE_LARGE})
@Retention(RetentionPolicy.SOURCE)
private @interface TileType {}
private static final int TILE_SMALL = 0;
private static final int TILE_LARGE = 1;
private static final int SMALL_CONTENT_SIZE = 254;
private static final int SMALL_BORDER_SIZE = 1;
private static final int SMALL_TILE_SIZE = SMALL_CONTENT_SIZE + 2 * SMALL_BORDER_SIZE;
private static final int LARGE_CONTENT_SIZE = SMALL_CONTENT_SIZE * 2;
private static final int LARGE_BORDER_SIZE = SMALL_BORDER_SIZE * 2;
private static final int LARGE_TILE_SIZE = LARGE_CONTENT_SIZE + 2 * LARGE_BORDER_SIZE;
private static final int INIT_CAPACITY = 8;
// We are targeting at 60fps, so we have 16ms for each frame.
// 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 PVLock sPVLock;
private static Tile sSmallFreeTileHead = null;
private static Tile sLargeFreeTileHead = null;
private static final Object sFreeTileLock = new Object();
private final ImageWrapper mImage;
private int mUploadIndex = 0;
private final Tile[] mTiles; // Can be modified in different threads.
// Should be protected by "synchronized."
private final int mWidth;
private final int mHeight;
private final boolean mOpaque;
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 mNeedRelease = new AtomicBoolean();
private final AtomicBoolean mReleased = new AtomicBoolean();
private final AtomicReference<Thread> mAnimateThread = new AtomicReference<>();
private WeakReference<Callback> mCallback;
static {
sThreadFactory = new PriorityThreadFactory("ImageTexture$AnimateTask", android.os.Process.THREAD_PRIORITY_BACKGROUND);
sPVLock = new PVLock(3);
}
public static class Uploader implements GLRoot.OnGLIdleListener {
private final ArrayDeque<ImageTexture> mTextures =
new ArrayDeque<>(INIT_CAPACITY);
private final GLRoot mGlRoot;
private boolean mIsQueued = false;
public Uploader(GLRoot glRoot) {
mGlRoot = glRoot;
}
public synchronized void clear() {
mTextures.clear();
}
public synchronized void addTexture(ImageTexture t) {
if (t.isReady()) return;
mTextures.addLast(t);
if (mIsQueued) return;
mIsQueued = true;
mGlRoot.addOnGLIdleListener(this);
}
@Override
public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
ArrayDeque<ImageTexture> deque = mTextures;
synchronized (this) {
long now = SystemClock.uptimeMillis();
long dueTime = now + UPLOAD_TILE_LIMIT;
while (now < dueTime && !deque.isEmpty()) {
ImageTexture t = deque.peekFirst();
if (t.uploadNextTile(canvas)) {
deque.removeFirst();
mGlRoot.requestRender();
}
now = SystemClock.uptimeMillis();
}
mIsQueued = !mTextures.isEmpty();
// return true to keep this listener in the queue
return mIsQueued;
}
}
}
private static class Tile extends NativeTexture {
@TileType
private int mTileType;
public int offsetX;
public int offsetY;
public ImageWrapper image;
public Tile nextFreeTile;
public int contentWidth;
public int contentHeight;
public int borderSize;
public void setSize(@TileType int tileType, int width, int height) {
mTileType = tileType;
int tileSize;
if (tileType == TILE_SMALL) {
borderSize = SMALL_BORDER_SIZE;
tileSize = SMALL_TILE_SIZE;
} else if (tileType == TILE_LARGE) {
borderSize = LARGE_BORDER_SIZE;
tileSize = LARGE_TILE_SIZE;
} else {
throw new IllegalStateException("Not support tile type: " + tileType);
}
contentWidth = width;
contentHeight = height;
mWidth = width + 2 * borderSize;
mHeight = height + 2 * borderSize;
mTextureWidth = tileSize;
mTextureHeight = tileSize;
}
@Override
protected void texImage(boolean init) {
if (image != null && !image.isRecycled()) {
image.texImage(init, mTileType, offsetX, offsetY);
}
}
private void invalidate() {
invalidateContent();
image = null;
}
public void free() {
switch (mTileType) {
case TILE_SMALL:
freeSmallTile(this);
break;
case TILE_LARGE:
freeLargeTile(this);
break;
default:
throw new IllegalStateException("Not support tile type: " + mTileType);
}
}
private static void freeSmallTile(Tile tile) {
tile.invalidate();
synchronized (sFreeTileLock) {
tile.nextFreeTile = sSmallFreeTileHead;
sSmallFreeTileHead = tile;
}
}
private static void freeLargeTile(Tile tile) {
tile.invalidate();
synchronized (sFreeTileLock) {
tile.nextFreeTile = sLargeFreeTileHead;
sLargeFreeTileHead = tile;
}
}
}
private static Tile obtainSmallTile() {
synchronized (sFreeTileLock) {
Tile result = sSmallFreeTileHead;
if (result == null) {
return new Tile();
} else {
sSmallFreeTileHead = result.nextFreeTile;
result.nextFreeTile = null;
}
return result;
}
}
private static Tile obtainLargeTile() {
synchronized (sFreeTileLock) {
Tile result = sLargeFreeTileHead;
if (result == null) {
return new Tile();
} else {
sLargeFreeTileHead = result.nextFreeTile;
result.nextFreeTile = null;
}
return result;
}
}
private class AnimateRunnable implements Runnable {
public void doRun() {
long lastTime = SystemClock.elapsedRealtime();
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
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();
}
}
int frameCount = mImage.getFrameCount();
synchronized (mImage) {
// Release image
mImageBusy = false;
}
if (interrupted || mNeedRelease.get() || frameCount <= 1) {
return;
}
while (!Thread.currentThread().isInterrupted()) {
// 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
return;
}
// Obtain image
mImageBusy = true;
}
mImage.advance();
long delay = mImage.getDelay();
long time = SystemClock.elapsedRealtime();
if (-1L != lastDelay) {
delay -= (time - lastTime) - lastDelay;
}
lastTime = time;
lastDelay = delay;
mFrameDirty.lazySet(true);
invalidateSelf();
synchronized (mImage) {
// Release image
mImageBusy = false;
}
if (delay > 0) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
break;
}
}
}
}
@Override
public void run() {
doRun();
while (mNeedRelease.get()) {
// Obtain
synchronized (mImage) {
// Check released
if (mReleased.get()) {
break;
}
// Check image busy
if (mImageBusy) {
// Image is busy, means it is recycling
break;
}
// Obtain image
mImageBusy = true;
}
mImage.release();
mReleased.lazySet(true);
synchronized (mImage) {
// Release image
mImageBusy = false;
}
}
mAnimateThread.lazySet(null);
}
}
public ImageTexture(@NonNull ImageWrapper image) {
mImage = image;
int width = mWidth = image.getWidth();
int height = mHeight = image.getHeight();
boolean opaque = mOpaque = image.isOpaque();
ArrayList<Tile> list = new ArrayList<>();
for (int x = 0; x < width; x += LARGE_CONTENT_SIZE) {
for (int y = 0; y < height; y += LARGE_CONTENT_SIZE) {
int w = Math.min(LARGE_CONTENT_SIZE, width - x);
int h = Math.min(LARGE_CONTENT_SIZE, height - y);
if (w <= SMALL_CONTENT_SIZE) {
Tile tile = obtainSmallTile();
tile.offsetX = x;
tile.offsetY = y;
tile.image = image;
tile.setSize(TILE_SMALL, w, Math.min(SMALL_CONTENT_SIZE, h));
tile.setOpaque(opaque);
list.add(tile);
int nextHeight = h - SMALL_CONTENT_SIZE;
if (nextHeight > 0) {
Tile nextTile = obtainSmallTile();
nextTile.offsetX = x;
nextTile.offsetY = y + SMALL_CONTENT_SIZE;
nextTile.image = image;
nextTile.setSize(TILE_SMALL, w, nextHeight);
nextTile.setOpaque(opaque);
list.add(nextTile);
}
} else if (h <= SMALL_CONTENT_SIZE) {
Tile tile = obtainSmallTile();
tile.offsetX = x;
tile.offsetY = y;
tile.image = image;
tile.setSize(TILE_SMALL, Math.min(SMALL_CONTENT_SIZE, w), h);
tile.setOpaque(opaque);
list.add(tile);
int nextWidth = w - SMALL_CONTENT_SIZE;
if (nextWidth > 0) {
Tile nextTile = obtainSmallTile();
nextTile.offsetX = x + SMALL_CONTENT_SIZE;
nextTile.offsetY = y;
nextTile.image = image;
nextTile.setSize(TILE_SMALL, nextWidth, h);
nextTile.setOpaque(opaque);
list.add(nextTile);
}
} else {
Tile tile = obtainLargeTile();
tile.offsetX = x;
tile.offsetY = y;
tile.image = image;
tile.setSize(TILE_LARGE, w, h);
tile.setOpaque(opaque);
list.add(tile);
}
}
}
mTiles = list.toArray(new Tile[list.size()]);
if (!mImage.isCompleted() || mImage.getFrameCount() > 1) {
Thread thread = sThreadFactory.newThread(new AnimateRunnable());
mAnimateThread.lazySet(thread);
thread.start();
}
}
public final void setCallback(Callback cb) {
mCallback = new WeakReference<>(cb);
}
public Callback getCallback() {
if (mCallback != null) {
return mCallback.get();
}
return null;
}
public void invalidateSelf() {
final Callback callback = getCallback();
if (callback != null) {
callback.invalidateImageTexture(this);
}
}
@Override
public void start() {
if (mReleased.get() || (mImage.isCompleted() && mImage.getFrameCount() <= 1)) {
return;
}
Thread thread = mAnimateThread.get();
if (thread == null) {
thread = sThreadFactory.newThread(new AnimateRunnable());
mAnimateThread.set(thread);
thread.start();
}
}
@Override
public void stop() {
if (!mReleased.get() && (mImage.isCompleted() && mImage.getFrameCount() > 1)) {
Thread thread = mAnimateThread.getAndSet(null);
if (null != thread) {
thread.interrupt();
}
}
}
@Override
public boolean isRunning() {
return mAnimateThread.get() != null;
}
private boolean uploadNextTile(GLCanvas canvas) {
if (mUploadIndex == mTiles.length) return true;
synchronized (mTiles) {
Tile next = mTiles[mUploadIndex++];
// Make sure tile has not already been recycled by the time
// this is called (race condition in onGLIdle)
if (next.image != null) {
boolean hasBeenLoad = next.isLoaded();
next.updateContent(canvas);
// It will take some time for a texture to be drawn for the first
// time. When scrolling, we need to draw several tiles on the screen
// at the same time. It may cause a UI jank even these textures has
// been uploaded.
if (!hasBeenLoad) next.draw(canvas, 0, 0);
}
}
return mUploadIndex == mTiles.length;
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
// We want to draw the "source" on the "target".
// This method is to find the "output" rectangle which is
// the corresponding area of the "src".
// (x,y) target
// (x0,y0) source +---------------+
// +----------+ | |
// | src | | output |
// | +--+ | linear map | +----+ |
// | +--+ | ----------> | | | |
// | | by (scaleX, scaleY) | +----+ |
// +----------+ | |
// Texture +---------------+
// Canvas
private static void mapRect(RectF output,
RectF src, float x0, float y0, float x, float y, float scaleX,
float scaleY) {
output.set(x + (src.left - x0) * scaleX,
y + (src.top - y0) * scaleY,
x + (src.right - x0) * scaleX,
y + (src.bottom - y0) * scaleY);
}
@RenderThread
private void syncFrame() {
if (mFrameDirty.getAndSet(false)) {
// invalid tiles
for (Tile tile : mTiles) {
tile.invalidateContent();
}
}
}
@Override
public void draw(GLCanvas canvas, int x, int y) {
draw(canvas, x, y, mWidth, mHeight);
}
// Draws the texture on to the specified rectangle.
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float scaleX = (float) w / mWidth;
float scaleY = (float) h / mHeight;
syncFrame();
for (Tile t : mTiles) {
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
mapRect(dest, src, 0, 0, x, y, scaleX, scaleY);
src.offset(t.borderSize - t.offsetX, t.borderSize - t.offsetY);
canvas.drawTexture(t, src, dest);
}
}
// Draws a sub region of this texture on to the specified rectangle.
@Override
public void draw(GLCanvas canvas, RectF source, RectF target) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float x0 = source.left;
float y0 = source.top;
float x = target.left;
float y = target.top;
float scaleX = target.width() / source.width();
float scaleY = target.height() / source.height();
syncFrame();
for (Tile t : mTiles) {
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
if (!src.intersect(source)) {
continue;
}
mapRect(dest, src, x0, y0, x, y, scaleX, scaleY);
src.offset(t.borderSize - t.offsetX, t.borderSize - t.offsetY);
canvas.drawTexture(t, src, dest);
}
}
// Draws a mixed color of this texture and a specified color onto the
// a rectangle. The used color is: from * (1 - ratio) + to * ratio.
public void drawMixed(GLCanvas canvas, int color, float ratio,
int x, int y, int width, int height) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float scaleX = (float) width / mWidth;
float scaleY = (float) height / mHeight;
syncFrame();
for (Tile t : mTiles) {
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
mapRect(dest, src, 0, 0, x, y, scaleX, scaleY);
src.offset(t.borderSize - t.offsetX, t.borderSize - t.offsetY);
canvas.drawMixed(t, color, ratio, src, dest);
}
}
public void drawMixed(GLCanvas canvas, int color, float ratio,
RectF source, RectF target) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float x0 = source.left;
float y0 = source.top;
float x = target.left;
float y = target.top;
float scaleX = target.width() / source.width();
float scaleY = target.height() / source.height();
syncFrame();
for (Tile t : mTiles) {
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
if (!src.intersect(source)) {
continue;
}
mapRect(dest, src, x0, y0, x, y, scaleX, scaleY);
src.offset(t.borderSize - t.offsetX, t.borderSize - t.offsetY);
canvas.drawMixed(t, color, ratio, src, dest);
}
}
@Override
public boolean isOpaque() {
return mOpaque;
}
public boolean isReady() {
return mUploadIndex == mTiles.length;
}
public void recycle() {
for (Tile mTile : mTiles) {
mTile.free();
}
boolean releaseNow;
synchronized (mImage) {
if (!mImageBusy) {
releaseNow = true;
mImageBusy = true;
} else {
releaseNow = false;
}
}
if (releaseNow) {
mImage.release();
mReleased.set(true);
synchronized (mImage) {
mImageBusy = false;
}
} else {
mNeedRelease.set(true);
}
Thread thread = mAnimateThread.getAndSet(null);
if (null != thread) {
thread.interrupt();
}
}
public interface Callback {
void invalidateImageTexture(ImageTexture who);
}
}
@@ -1,183 +0,0 @@
package com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import java.util.Arrays;
// TODO support multiline
/**
* Works like movable type.<br>
* <br>
* Only support single line now
*/
public class MovableTextTexture extends SpriteTexture {
private char[] mCharacters;
private float[] mWidths;
private float mHeight;
private float mMaxWidth;
private MovableTextTexture(Bitmap bitmap, int count, int[] rects, char[] characters,
float[] widths, float height, float maxWidth) {
super(bitmap, false, 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
*/
public static MovableTextTexture 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);
// Caculate 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;
}
}
return new MovableTextTexture(bitmap, length, rects, characters, widths, height, maxWidth);
}
}
@@ -1,52 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
// MultiLineTexture is a texture shows the content of a specified String.
//
// To create a MultiLineTexture, use the newInstance() method and specify
// the String, the font size, and the color.
class MultiLineTexture extends CanvasTexture {
private final Layout mLayout;
private MultiLineTexture(Layout layout) {
super(layout.getWidth(), layout.getHeight());
mLayout = layout;
}
public static MultiLineTexture newInstance(
String text, int maxWidth, float textSize, int color,
Layout.Alignment alignment) {
TextPaint paint = StringTexture.getDefaultPaint(textSize, color);
Layout layout = new StaticLayout(text, 0, text.length(), paint,
maxWidth, alignment, 1, 0, true, null, 0);
return new MultiLineTexture(layout);
}
@Override
protected void onDraw(Canvas canvas, Bitmap backing) {
mLayout.draw(canvas);
}
}
@@ -1,101 +0,0 @@
/*
* 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.opengl.GLES20;
import android.util.Log;
import javax.microedition.khronos.opengles.GL11;
public abstract class NativeTexture extends BasicTexture {
private static final String TAG = NativeTexture.class.getSimpleName();
private boolean mContentValid = true;
private boolean mOpaque = true;
public void invalidateContent() {
mContentValid = false;
}
public static void checkError() {
int error = GLES20.glGetError();
if (error != 0) {
Throwable t = new Throwable();
Log.e(TAG, "GL error: " + error, t);
}
}
protected abstract void texImage(boolean init);
private void uploadToCanvas(GLCanvas canvas) {
// Get id
mId = canvas.getGLId().generateTexture();
// Prepare
canvas.setTextureParameters(this);
// Call glTexImage2D
GLES20.glBindTexture(getTarget(), mId);
checkError();
texImage(true);
setAssociatedCanvas(canvas);
mState = STATE_LOADED;
mContentValid = true;
}
public void updateContent(GLCanvas canvas) {
if (!isLoaded()) {
uploadToCanvas(canvas);
} else if (!mContentValid) {
// Call glTexSubImage2D
GLES20.glBindTexture(getTarget(), mId);
checkError();
texImage(false);
mContentValid = true;
}
}
/**
* Whether the content on GPU is valid.
*/
public boolean isContentValid() {
return isLoaded() && mContentValid;
}
@Override
protected boolean onBind(GLCanvas canvas) {
updateContent(canvas);
return isContentValid();
}
@Override
protected int getTarget() {
return GL11.GL_TEXTURE_2D;
}
public void setOpaque(boolean isOpaque) {
mOpaque = isOpaque;
}
@Override
public boolean isOpaque() {
return mOpaque;
}
}
@@ -1,82 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.Rect;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
// See "frameworks/base/include/utils/ResourceTypes.h" for the format of
// NinePatch chunk.
class NinePatchChunk {
public static final int NO_COLOR = 0x00000001;
public static final int TRANSPARENT_COLOR = 0x00000000;
public Rect mPaddings = new Rect();
public int mDivX[];
public int mDivY[];
public int mColor[];
private static void readIntArray(int[] data, ByteBuffer buffer) {
for (int i = 0, n = data.length; i < n; ++i) {
data[i] = buffer.getInt();
}
}
private static void checkDivCount(int length) {
if (length == 0 || (length & 0x01) != 0) {
throw new RuntimeException("invalid nine-patch: " + length);
}
}
public static NinePatchChunk deserialize(byte[] data) {
ByteBuffer byteBuffer =
ByteBuffer.wrap(data).order(ByteOrder.nativeOrder());
byte wasSerialized = byteBuffer.get();
if (wasSerialized == 0) return null;
NinePatchChunk chunk = new NinePatchChunk();
chunk.mDivX = new int[byteBuffer.get()];
chunk.mDivY = new int[byteBuffer.get()];
chunk.mColor = new int[byteBuffer.get()];
checkDivCount(chunk.mDivX.length);
checkDivCount(chunk.mDivY.length);
// skip 8 bytes
byteBuffer.getInt();
byteBuffer.getInt();
chunk.mPaddings.left = byteBuffer.getInt();
chunk.mPaddings.right = byteBuffer.getInt();
chunk.mPaddings.top = byteBuffer.getInt();
chunk.mPaddings.bottom = byteBuffer.getInt();
// skip 4 bytes
byteBuffer.getInt();
readIntArray(chunk.mDivX, byteBuffer);
readIntArray(chunk.mDivY, byteBuffer);
readIntArray(chunk.mColor, byteBuffer);
return chunk;
}
}
@@ -1,424 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import com.hippo.yorozuya.MathUtils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
// NinePatchTexture is a texture backed by a NinePatch resource.
//
// getPaddings() returns paddings specified in the NinePatch.
// getNinePatchChunk() returns the layout data specified in the NinePatch.
//
public class NinePatchTexture extends ResourceTexture {
@SuppressWarnings("unused")
private static final String TAG = "NinePatchTexture";
private NinePatchChunk mChunk;
private SmallCache<NinePatchInstance> mInstanceCache
= new SmallCache<NinePatchInstance>();
public NinePatchTexture(Context context, int resId) {
super(context, resId);
}
@Override
protected Bitmap onGetBitmap() {
if (mBitmap != null) return mBitmap;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeResource(
mContext.getResources(), mResId, options);
mBitmap = bitmap;
setSize(bitmap.getWidth(), bitmap.getHeight());
byte[] chunkData = bitmap.getNinePatchChunk();
mChunk = chunkData == null
? null
: NinePatchChunk.deserialize(bitmap.getNinePatchChunk());
if (mChunk == null) {
throw new RuntimeException("invalid nine-patch image: " + mResId);
}
return bitmap;
}
public Rect getPaddings() {
// get the paddings from nine patch
if (mChunk == null) onGetBitmap();
return mChunk.mPaddings;
}
public NinePatchChunk getNinePatchChunk() {
if (mChunk == null) onGetBitmap();
return mChunk;
}
// This is a simple cache for a small number of things. Linear search
// is used because the cache is small. It also tries to remove less used
// item when the cache is full by moving the often-used items to the front.
private static class SmallCache<V> {
private static final int CACHE_SIZE = 16;
private static final int CACHE_SIZE_START_MOVE = CACHE_SIZE / 2;
private int[] mKey = new int[CACHE_SIZE];
private V[] mValue = (V[]) new Object[CACHE_SIZE];
private int mCount; // number of items in this cache
// Puts a value into the cache. If the cache is full, also returns
// a less used item, otherwise returns null.
public V put(int key, V value) {
if (mCount == CACHE_SIZE) {
V old = mValue[CACHE_SIZE - 1]; // remove the last item
mKey[CACHE_SIZE - 1] = key;
mValue[CACHE_SIZE - 1] = value;
return old;
} else {
mKey[mCount] = key;
mValue[mCount] = value;
mCount++;
return null;
}
}
public V get(int key) {
for (int i = 0; i < mCount; i++) {
if (mKey[i] == key) {
// Move the accessed item one position to the front, so it
// will less likely to be removed when cache is full. Only
// do this if the cache is starting to get full.
if (mCount > CACHE_SIZE_START_MOVE && i > 0) {
int tmpKey = mKey[i];
mKey[i] = mKey[i - 1];
mKey[i - 1] = tmpKey;
V tmpValue = mValue[i];
mValue[i] = mValue[i - 1];
mValue[i - 1] = tmpValue;
}
return mValue[i];
}
}
return null;
}
public void clear() {
for (int i = 0; i < mCount; i++) {
mValue[i] = null; // make sure it's can be garbage-collected.
}
mCount = 0;
}
public int size() {
return mCount;
}
public V valueAt(int i) {
return mValue[i];
}
}
private NinePatchInstance findInstance(GLCanvas canvas, int w, int h) {
int key = w;
key = (key << 16) | h;
NinePatchInstance instance = mInstanceCache.get(key);
if (instance == null) {
instance = new NinePatchInstance(this, w, h);
NinePatchInstance removed = mInstanceCache.put(key, instance);
if (removed != null) {
removed.recycle(canvas);
}
}
return instance;
}
@Override
public void draw(GLCanvas canvas, int x, int y, int w, int h) {
if (!isLoaded()) {
mInstanceCache.clear();
}
if (w != 0 && h != 0) {
findInstance(canvas, w, h).draw(canvas, this, x, y);
}
}
@Override
public void recycle() {
super.recycle();
GLCanvas canvas = mCanvasRef;
if (canvas == null) return;
int n = mInstanceCache.size();
for (int i = 0; i < n; i++) {
NinePatchInstance instance = mInstanceCache.valueAt(i);
instance.recycle(canvas);
}
mInstanceCache.clear();
}
}
// This keeps data for a specialization of NinePatchTexture with the size
// (width, height). We pre-compute the coordinates for efficiency.
class NinePatchInstance {
@SuppressWarnings("unused")
private static final String TAG = "NinePatchInstance";
// We need 16 vertices for a normal nine-patch image (the 4x4 vertices)
private static final int VERTEX_BUFFER_SIZE = 16 * 2;
// We need 22 indices for a normal nine-patch image, plus 2 for each
// transparent region. Current there are at most 1 transparent region.
private static final int INDEX_BUFFER_SIZE = 22 + 2;
private FloatBuffer mXyBuffer;
private FloatBuffer mUvBuffer;
private ByteBuffer mIndexBuffer;
// Names for buffer names: xy, uv, index.
private int mXyBufferName = -1;
private int mUvBufferName;
private int mIndexBufferName;
private int mIdxCount;
public NinePatchInstance(NinePatchTexture tex, int width, int height) {
NinePatchChunk chunk = tex.getNinePatchChunk();
if (width <= 0 || height <= 0) {
throw new RuntimeException("invalid dimension");
}
// The code should be easily extended to handle the general cases by
// allocating more space for buffers. But let's just handle the only
// use case.
if (chunk.mDivX.length != 2 || chunk.mDivY.length != 2) {
throw new RuntimeException("unsupported nine patch");
}
float divX[] = new float[4];
float divY[] = new float[4];
float divU[] = new float[4];
float divV[] = new float[4];
int nx = stretch(divX, divU, chunk.mDivX, tex.getWidth(), width);
int ny = stretch(divY, divV, chunk.mDivY, tex.getHeight(), height);
prepareVertexData(divX, divY, divU, divV, nx, ny, chunk.mColor);
}
/**
* Stretches the texture according to the nine-patch rules. It will
* linearly distribute the strechy parts defined in the nine-patch chunk to
* the target area.
*
* <pre>
* source
* /--------------^---------------\
* u0 u1 u2 u3 u4 u5
* div ---> |fffff|ssssssss|fff|ssssss|ffff| ---> u
* | div0 div1 div2 div3 |
* | | / / / /
* | | / / / /
* | | / / / /
* |fffff|ssss|fff|sss|ffff| ---> x
* x0 x1 x2 x3 x4 x5
* \----------v------------/
* target
*
* f: fixed segment
* s: stretchy segment
* </pre>
*
* @param div the stretch parts defined in nine-patch chunk
* @param source the length of the texture
* @param target the length on the drawing plan
* @param u output, the positions of these dividers in the texture
* coordinate
* @param x output, the corresponding position of these dividers on the
* drawing plan
* @return the number of these dividers.
*/
private static int stretch(
float x[], float u[], int div[], int source, int target) {
int textureSize = MathUtils.nextPowerOf2(source);
float textureBound = (float) source / textureSize;
float stretch = 0;
for (int i = 0, n = div.length; i < n; i += 2) {
stretch += div[i + 1] - div[i];
}
float remaining = target - source + stretch;
float lastX = 0;
float lastU = 0;
x[0] = 0;
u[0] = 0;
for (int i = 0, n = div.length; i < n; i += 2) {
// Make the stretchy segment a little smaller to prevent sampling
// on neighboring fixed segments.
// fixed segment
x[i + 1] = lastX + (div[i] - lastU) + 0.5f;
u[i + 1] = Math.min((div[i] + 0.5f) / textureSize, textureBound);
// stretchy segment
float partU = div[i + 1] - div[i];
float partX = remaining * partU / stretch;
remaining -= partX;
stretch -= partU;
lastX = x[i + 1] + partX;
lastU = div[i + 1];
x[i + 2] = lastX - 0.5f;
u[i + 2] = Math.min((lastU - 0.5f)/ textureSize, textureBound);
}
// the last fixed segment
x[div.length + 1] = target;
u[div.length + 1] = textureBound;
// remove segments with length 0.
int last = 0;
for (int i = 1, n = div.length + 2; i < n; ++i) {
if ((x[i] - x[last]) < 1f) continue;
x[++last] = x[i];
u[last] = u[i];
}
return last + 1;
}
private void prepareVertexData(float x[], float y[], float u[], float v[],
int nx, int ny, int[] color) {
/*
* Given a 3x3 nine-patch image, the vertex order is defined as the
* following graph:
*
* (0) (1) (2) (3)
* | /| /| /|
* | / | / | / |
* (4) (5) (6) (7)
* | \ | \ | \ |
* | \| \| \|
* (8) (9) (A) (B)
* | /| /| /|
* | / | / | / |
* (C) (D) (E) (F)
*
* And we draw the triangle strip in the following index order:
*
* index: 04152637B6A5948C9DAEBF
*/
int pntCount = 0;
float xy[] = new float[VERTEX_BUFFER_SIZE];
float uv[] = new float[VERTEX_BUFFER_SIZE];
for (int j = 0; j < ny; ++j) {
for (int i = 0; i < nx; ++i) {
int xIndex = (pntCount++) << 1;
int yIndex = xIndex + 1;
xy[xIndex] = x[i];
xy[yIndex] = y[j];
uv[xIndex] = u[i];
uv[yIndex] = v[j];
}
}
int idxCount = 1;
boolean isForward = false;
byte index[] = new byte[INDEX_BUFFER_SIZE];
for (int row = 0; row < ny - 1; row++) {
--idxCount;
isForward = !isForward;
int start, end, inc;
if (isForward) {
start = 0;
end = nx;
inc = 1;
} else {
start = nx - 1;
end = -1;
inc = -1;
}
for (int col = start; col != end; col += inc) {
int k = row * nx + col;
if (col != start) {
int colorIdx = row * (nx - 1) + col;
if (isForward) colorIdx--;
if (color[colorIdx] == NinePatchChunk.TRANSPARENT_COLOR) {
index[idxCount] = index[idxCount - 1];
++idxCount;
index[idxCount++] = (byte) k;
}
}
index[idxCount++] = (byte) k;
index[idxCount++] = (byte) (k + nx);
}
}
mIdxCount = idxCount;
int size = (pntCount * 2) * (Float.SIZE / Byte.SIZE);
mXyBuffer = allocateDirectNativeOrderBuffer(size).asFloatBuffer();
mUvBuffer = allocateDirectNativeOrderBuffer(size).asFloatBuffer();
mIndexBuffer = allocateDirectNativeOrderBuffer(mIdxCount);
mXyBuffer.put(xy, 0, pntCount * 2).position(0);
mUvBuffer.put(uv, 0, pntCount * 2).position(0);
mIndexBuffer.put(index, 0, idxCount).position(0);
}
private static ByteBuffer allocateDirectNativeOrderBuffer(int size) {
return ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());
}
private void prepareBuffers(GLCanvas canvas) {
mXyBufferName = canvas.uploadBuffer(mXyBuffer);
mUvBufferName = canvas.uploadBuffer(mUvBuffer);
mIndexBufferName = canvas.uploadBuffer(mIndexBuffer);
// These buffers are never used again.
mXyBuffer = null;
mUvBuffer = null;
mIndexBuffer = null;
}
public void draw(GLCanvas canvas, NinePatchTexture tex, int x, int y) {
if (mXyBufferName == -1) {
prepareBuffers(canvas);
}
canvas.drawMesh(tex, x, y, mXyBufferName, mUvBufferName, mIndexBufferName, mIdxCount);
}
public void recycle(GLCanvas canvas) {
if (mXyBuffer == null) {
canvas.deleteBuffer(mXyBufferName);
canvas.deleteBuffer(mUvBufferName);
canvas.deleteBuffer(mIndexBufferName);
mXyBufferName = -1;
}
}
}
@@ -1,73 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.util.Log;
import javax.microedition.khronos.opengles.GL11;
public class RawTexture extends BasicTexture {
private static final String TAG = "RawTexture";
private final boolean mOpaque;
private boolean mIsFlipped;
public RawTexture(int width, int height, boolean opaque) {
mOpaque = opaque;
setSize(width, height);
}
@Override
public boolean isOpaque() {
return mOpaque;
}
@Override
public boolean isFlippedVertically() {
return mIsFlipped;
}
public void setIsFlippedVertically(boolean isFlipped) {
mIsFlipped = isFlipped;
}
protected void prepare(GLCanvas canvas) {
GLId glId = canvas.getGLId();
mId = glId.generateTexture();
canvas.initializeTextureSize(this, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE);
canvas.setTextureParameters(this);
mState = STATE_LOADED;
setAssociatedCanvas(canvas);
}
@Override
protected boolean onBind(GLCanvas canvas) {
if (isLoaded()) return true;
Log.w(TAG, "lost the content due to context change");
return false;
}
@Override
public void yield() {
// we cannot free the texture because we have no backup.
}
@Override
protected int getTarget() {
return GL11.GL_TEXTURE_2D;
}
}
@@ -1,53 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import junit.framework.Assert;
// ResourceTexture is a texture whose Bitmap is decoded from a resource.
// By default ResourceTexture is not opaque.
public class ResourceTexture extends UploadedTexture {
protected final Context mContext;
protected final int mResId;
public ResourceTexture(Context context, int resId) {
Assert.assertNotNull(context);
mContext = context;
mResId = resId;
setOpaque(false);
}
@Override
protected Bitmap onGetBitmap() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
return BitmapFactory.decodeResource(
mContext.getResources(), mResId, options);
}
@Override
protected void onFreeBitmap(Bitmap bitmap) {
if (!inFinalizer()) {
bitmap.recycle();
}
}
}
@@ -1,73 +0,0 @@
package com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import android.graphics.RectF;
import com.hippo.yorozuya.AssertUtils;
public class SpriteTexture extends TiledTexture {
private int mCount;
private int[] mRects;
private RectF mTempSource = new RectF();
private RectF mTempTarget = new RectF();
public SpriteTexture(Bitmap bitmap, boolean isOpaque, int count, int[] rects) {
super(bitmap, isOpaque);
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);
}
}
@@ -1,87 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.TextUtils;
// StringTexture is a texture shows the content of a specified String.
//
// To create a StringTexture, use the newInstance() method and specify
// the String, the font size, and the color.
public class StringTexture extends CanvasTexture {
private final String mText;
private final TextPaint mPaint;
private final FontMetricsInt mMetrics;
private StringTexture(String text, TextPaint paint,
FontMetricsInt metrics, int width, int height) {
super(width, height);
mText = text;
mPaint = paint;
mMetrics = metrics;
}
public static TextPaint getDefaultPaint(float textSize, int color) {
TextPaint paint = new TextPaint();
paint.setTextSize(textSize);
paint.setAntiAlias(true);
paint.setColor(color);
paint.setShadowLayer(2f, 0f, 0f, Color.BLACK);
return paint;
}
public static StringTexture newInstance(
String text, float textSize, int color) {
return newInstance(text, getDefaultPaint(textSize, color));
}
public static StringTexture newInstance(
String text, float textSize, int color,
float lengthLimit, boolean isBold) {
TextPaint paint = getDefaultPaint(textSize, color);
if (isBold) {
paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
}
if (lengthLimit > 0) {
text = TextUtils.ellipsize(
text, paint, lengthLimit, TextUtils.TruncateAt.END).toString();
}
return newInstance(text, paint);
}
private static StringTexture newInstance(String text, TextPaint paint) {
FontMetricsInt metrics = paint.getFontMetricsInt();
int width = (int) Math.ceil(paint.measureText(text));
int height = metrics.bottom - metrics.top;
// The texture size needs to be at least 1x1.
if (width <= 0) width = 1;
if (height <= 0) height = 1;
return new StringTexture(text, paint, metrics, width, height);
}
@Override
protected void onDraw(Canvas canvas, Bitmap backing) {
canvas.translate(0, -mMetrics.ascent);
canvas.drawText(mText, 0, 0, mPaint);
}
}
@@ -1,47 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.RectF;
// Texture is a rectangular image which can be drawn on GLCanvas.
// The isOpaque() function gives a hint about whether the texture is opaque,
// so the drawing can be done faster.
//
// This is the current texture hierarchy:
//
// Texture
// -- ColorTexture
// -- FadeInTexture
// -- BasicTexture
// -- UploadedTexture
// -- BitmapTexture
// -- Tile
// -- ResourceTexture
// -- NinePatchTexture
// -- CanvasTexture
// -- StringTexture
//
public interface Texture {
int getWidth();
int getHeight();
void draw(GLCanvas canvas, int x, int y);
void draw(GLCanvas canvas, int x, int y, int w, int h);
void draw(GLCanvas canvas, RectF source, RectF target);
boolean isOpaque();
}
@@ -1,104 +0,0 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import com.hippo.gl.view.GLRoot;
import java.util.ArrayDeque;
public class TextureUploader implements GLRoot.OnGLIdleListener {
private static final int INIT_CAPACITY = 64;
private static final int QUOTA_PER_FRAME = 1;
private final ArrayDeque<UploadedTexture> mFgTextures =
new ArrayDeque<UploadedTexture>(INIT_CAPACITY);
private final ArrayDeque<UploadedTexture> mBgTextures =
new ArrayDeque<UploadedTexture>(INIT_CAPACITY);
private final GLRoot mGLRoot;
private volatile boolean mIsQueued = false;
public TextureUploader(GLRoot root) {
mGLRoot = root;
}
public synchronized void clear() {
while (!mFgTextures.isEmpty()) {
mFgTextures.pop().setIsUploading(false);
}
while (!mBgTextures.isEmpty()) {
mBgTextures.pop().setIsUploading(false);
}
}
// caller should hold synchronized on "this"
private void queueSelfIfNeed() {
if (mIsQueued) return;
mIsQueued = true;
mGLRoot.addOnGLIdleListener(this);
}
public synchronized void addBgTexture(UploadedTexture t) {
if (t.isContentValid()) return;
mBgTextures.addLast(t);
t.setIsUploading(true);
queueSelfIfNeed();
}
public synchronized void addFgTexture(UploadedTexture t) {
if (t.isContentValid()) return;
mFgTextures.addLast(t);
t.setIsUploading(true);
queueSelfIfNeed();
}
private int upload(GLCanvas canvas, ArrayDeque<UploadedTexture> deque,
int uploadQuota, boolean isBackground) {
while (uploadQuota > 0) {
UploadedTexture t;
synchronized (this) {
if (deque.isEmpty()) break;
t = deque.removeFirst();
t.setIsUploading(false);
if (t.isContentValid()) continue;
// this has to be protected by the synchronized block
// to prevent the inner bitmap get recycled
t.updateContent(canvas);
}
// It will took some more time for a texture to be drawn for
// the first time.
// Thus, when scrolling, if a new column appears on screen,
// it may cause a UI jank even these textures are uploaded.
if (isBackground) t.draw(canvas, 0, 0);
--uploadQuota;
}
return uploadQuota;
}
@Override
public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
int uploadQuota = QUOTA_PER_FRAME;
uploadQuota = upload(canvas, mFgTextures, uploadQuota, false);
if (uploadQuota < QUOTA_PER_FRAME) mGLRoot.requestRender();
upload(canvas, mBgTextures, uploadQuota, true);
synchronized (this) {
mIsQueued = !mFgTextures.isEmpty() || !mBgTextures.isEmpty();
return mIsQueued;
}
}
}
@@ -1,373 +0,0 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.os.SystemClock;
import com.hippo.gl.view.GLRoot;
import java.util.ArrayDeque;
import java.util.ArrayList;
// This class is similar to BitmapTexture, except the bitmap is
// split into tiles. By doing so, we may increase the time required to
// upload the whole bitmap but we reduce the time of uploading each tile
// so it make the animation more smooth and prevents jank.
public class TiledTexture implements Texture {
private static final int CONTENT_SIZE = 254;
private static final int BORDER_SIZE = 1;
private static final int TILE_SIZE = CONTENT_SIZE + 2 * BORDER_SIZE;
private static final int INIT_CAPACITY = 8;
// We are targeting at 60fps, so we have 16ms for each frame.
// In this 16ms, we use about 4~8 ms to upload tiles.
private static final long UPLOAD_TILE_LIMIT = 4; // ms
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 int mUploadIndex = 0;
private final Tile[] mTiles; // Can be modified in different threads.
// Should be protected by "synchronized."
private final int mWidth;
private final int mHeight;
private final RectF mSrcRect = new RectF();
private final RectF mDestRect = new RectF();
static {
sUploadBitmap = Bitmap.createBitmap(TILE_SIZE, TILE_SIZE, Bitmap.Config.ARGB_8888);
sCanvas = new Canvas(sUploadBitmap);
sBitmapPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
sBitmapPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
sPaint = new Paint();
sPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
sPaint.setColor(Color.TRANSPARENT);
}
public static class Uploader implements GLRoot.OnGLIdleListener {
private final ArrayDeque<TiledTexture> mTextures =
new ArrayDeque<>(INIT_CAPACITY);
private final GLRoot mGlRoot;
private boolean mIsQueued = false;
public Uploader(GLRoot glRoot) {
mGlRoot = glRoot;
}
public synchronized void clear() {
mTextures.clear();
}
public synchronized void addTexture(TiledTexture t) {
if (t.isReady()) return;
mTextures.addLast(t);
if (mIsQueued) return;
mIsQueued = true;
mGlRoot.addOnGLIdleListener(this);
}
@Override
public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
ArrayDeque<TiledTexture> deque = mTextures;
synchronized (this) {
long now = SystemClock.uptimeMillis();
long dueTime = now + UPLOAD_TILE_LIMIT;
while (now < dueTime && !deque.isEmpty()) {
TiledTexture t = deque.peekFirst();
if (t.uploadNextTile(canvas)) {
deque.removeFirst();
mGlRoot.requestRender();
}
now = SystemClock.uptimeMillis();
}
mIsQueued = !mTextures.isEmpty();
// return true to keep this listener in the queue
return mIsQueued;
}
}
}
private static class Tile extends UploadedTexture {
public int offsetX;
public int offsetY;
public Bitmap bitmap;
public Tile nextFreeTile;
public int contentWidth;
public int contentHeight;
@Override
public void setSize(int width, int height) {
contentWidth = width;
contentHeight = height;
mWidth = width + 2 * BORDER_SIZE;
mHeight = height + 2 * BORDER_SIZE;
mTextureWidth = TILE_SIZE;
mTextureHeight = TILE_SIZE;
}
@Override
protected Bitmap onGetBitmap() {
// make a local copy of the reference to the bitmap,
// since it might be null'd in a different thread. b/8694871
Bitmap localBitmapRef = bitmap;
bitmap = null;
if (localBitmapRef != null) {
int x = BORDER_SIZE - offsetX;
int y = BORDER_SIZE - offsetY;
int r = localBitmapRef.getWidth() + x;
int b = localBitmapRef.getHeight() + y;
sCanvas.drawBitmap(localBitmapRef, x, y, sBitmapPaint);
localBitmapRef = null;
// draw borders if need
if (x > 0) sCanvas.drawLine(x - 1, 0, x - 1, TILE_SIZE, sPaint);
if (y > 0) sCanvas.drawLine(0, y - 1, TILE_SIZE, y - 1, sPaint);
if (r < CONTENT_SIZE) sCanvas.drawLine(r, 0, r, TILE_SIZE, sPaint);
if (b < CONTENT_SIZE) sCanvas.drawLine(0, b, TILE_SIZE, b, sPaint);
}
return sUploadBitmap;
}
@Override
protected void onFreeBitmap(Bitmap bitmap) {
// do nothing
}
}
private static void freeTile(Tile tile) {
tile.invalidateContent();
tile.bitmap = null;
synchronized (sFreeTileLock) {
tile.nextFreeTile = sFreeTileHead;
sFreeTileHead = tile;
}
}
private static Tile obtainTile() {
synchronized (sFreeTileLock) {
Tile result = sFreeTileHead;
if (result == null) return new Tile();
sFreeTileHead = result.nextFreeTile;
result.nextFreeTile = null;
return result;
}
}
private boolean uploadNextTile(GLCanvas canvas) {
if (mUploadIndex == mTiles.length) return true;
synchronized (mTiles) {
Tile next = mTiles[mUploadIndex++];
// Make sure tile has not already been recycled by the time
// this is called (race condition in onGLIdle)
if (next.bitmap != null) {
boolean hasBeenLoad = next.isLoaded();
next.updateContent(canvas);
// It will take some time for a texture to be drawn for the first
// time. When scrolling, we need to draw several tiles on the screen
// at the same time. It may cause a UI jank even these textures has
// been uploaded.
if (!hasBeenLoad) next.draw(canvas, 0, 0);
}
}
return mUploadIndex == mTiles.length;
}
public TiledTexture(Bitmap bitmap, boolean isOpaque) {
mWidth = bitmap.getWidth();
mHeight = bitmap.getHeight();
ArrayList<Tile> list = new ArrayList<>();
for (int x = 0, w = mWidth; x < w; x += CONTENT_SIZE) {
for (int y = 0, h = mHeight; y < h; y += CONTENT_SIZE) {
Tile tile = obtainTile();
tile.offsetX = x;
tile.offsetY = y;
tile.bitmap = bitmap;
tile.setSize(
Math.min(CONTENT_SIZE, mWidth - x),
Math.min(CONTENT_SIZE, mHeight - y));
tile.setOpaque(isOpaque);
list.add(tile);
}
}
mTiles = list.toArray(new Tile[list.size()]);
}
public boolean isReady() {
return mUploadIndex == mTiles.length;
}
// Can be called in UI thread.
public void recycle() {
synchronized (mTiles) {
for (int i = 0, n = mTiles.length; i < n; ++i) {
freeTile(mTiles[i]);
}
}
}
// We want to draw the "source" on the "target".
// This method is to find the "output" rectangle which is
// the corresponding area of the "src".
// (x,y) target
// (x0,y0) source +---------------+
// +----------+ | |
// | src | | output |
// | +--+ | linear map | +----+ |
// | +--+ | ----------> | | | |
// | | by (scaleX, scaleY) | +----+ |
// +----------+ | |
// Texture +---------------+
// Canvas
private static void mapRect(RectF output,
RectF src, float x0, float y0, float x, float y, float scaleX,
float scaleY) {
output.set(x + (src.left - x0) * scaleX,
y + (src.top - y0) * scaleY,
x + (src.right - x0) * scaleX,
y + (src.bottom - y0) * scaleY);
}
// Draws a mixed color of this texture and a specified color onto the
// a rectangle. The used color is: from * (1 - ratio) + to * ratio.
public void drawMixed(GLCanvas canvas, int color, float ratio,
int x, int y, int width, int height) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float scaleX = (float) width / mWidth;
float scaleY = (float) height / mHeight;
synchronized (mTiles) {
for (int i = 0, n = mTiles.length; i < n; ++i) {
Tile t = mTiles[i];
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
mapRect(dest, src, 0, 0, x, y, scaleX, scaleY);
src.offset(BORDER_SIZE - t.offsetX, BORDER_SIZE - t.offsetY);
canvas.drawMixed(t, color, ratio, mSrcRect, mDestRect);
}
}
}
public void drawMixed(GLCanvas canvas, int color, float ratio,
RectF source, RectF target) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float x0 = source.left;
float y0 = source.top;
float x = target.left;
float y = target.top;
float scaleX = target.width() / source.width();
float scaleY = target.height() / source.height();
synchronized (mTiles) {
for (int i = 0, n = mTiles.length; i < n; ++i) {
Tile t = mTiles[i];
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
if (!src.intersect(source)) continue;
mapRect(dest, src, x0, y0, x, y, scaleX, scaleY);
src.offset(BORDER_SIZE - t.offsetX, BORDER_SIZE - t.offsetY);
canvas.drawMixed(t, color, ratio, mSrcRect, mDestRect);
}
}
}
// Draws the texture on to the specified rectangle.
@Override
public void draw(GLCanvas canvas, int x, int y, int width, int height) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float scaleX = (float) width / mWidth;
float scaleY = (float) height / mHeight;
synchronized (mTiles) {
for (int i = 0, n = mTiles.length; i < n; ++i) {
Tile t = mTiles[i];
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
mapRect(dest, src, 0, 0, x, y, scaleX, scaleY);
src.offset(BORDER_SIZE - t.offsetX, BORDER_SIZE - t.offsetY);
canvas.drawTexture(t, mSrcRect, mDestRect);
}
}
}
// Draws a sub region of this texture on to the specified rectangle.
@Override
public void draw(GLCanvas canvas, RectF source, RectF target) {
RectF src = mSrcRect;
RectF dest = mDestRect;
float x0 = source.left;
float y0 = source.top;
float x = target.left;
float y = target.top;
float scaleX = target.width() / source.width();
float scaleY = target.height() / source.height();
synchronized (mTiles) {
for (int i = 0, n = mTiles.length; i < n; ++i) {
Tile t = mTiles[i];
src.set(0, 0, t.contentWidth, t.contentHeight);
src.offset(t.offsetX, t.offsetY);
if (!src.intersect(source)) continue;
mapRect(dest, src, x0, y0, x, y, scaleX, scaleY);
src.offset(BORDER_SIZE - t.offsetX, BORDER_SIZE - t.offsetY);
canvas.drawTexture(t, src, dest);
}
}
}
@Override
public int getWidth() {
return mWidth;
}
@Override
public int getHeight() {
return mHeight;
}
@Override
public void draw(GLCanvas canvas, int x, int y) {
draw(canvas, x, y, mWidth, mHeight);
}
@Override
public boolean isOpaque() {
return false;
}
}
@@ -1,296 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gl.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.opengl.GLUtils;
import junit.framework.Assert;
import java.util.HashMap;
import javax.microedition.khronos.opengles.GL11;
// UploadedTextures use a Bitmap for the content of the texture.
//
// Subclasses should implement onGetBitmap() to provide the Bitmap and
// implement onFreeBitmap(mBitmap) which will be called when the Bitmap
// is not needed anymore.
//
// isContentValid() is meaningful only when the isLoaded() returns true.
// It means whether the content needs to be updated.
//
// The user of this class should call recycle() when the texture is not
// needed anymore.
//
// By default an UploadedTexture is opaque (so it can be drawn faster without
// blending). The user or subclass can override it using setOpaque().
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 =
new HashMap<>();
private static BorderKey sBorderKey = new BorderKey();
@SuppressWarnings("unused")
private static final String TAG = "Texture";
private boolean mContentValid = true;
// indicate this textures is being uploaded in background
private boolean mIsUploading = false;
private boolean mOpaque = true;
private boolean mThrottled = false;
private static int sUploadedCount;
private static final int UPLOAD_LIMIT = 100;
protected Bitmap mBitmap;
private int mBorder;
protected UploadedTexture() {
this(false);
}
protected UploadedTexture(boolean hasBorder) {
super(null, 0, STATE_UNLOADED);
if (hasBorder) {
setBorder(true);
mBorder = 1;
}
}
protected void setIsUploading(boolean uploading) {
mIsUploading = uploading;
}
public boolean isUploading() {
return mIsUploading;
}
private static class BorderKey implements Cloneable {
public boolean vertical;
public Config config;
public int length;
@Override
public int hashCode() {
int x = config.hashCode() ^ length;
return vertical ? x : -x;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof BorderKey)) return false;
BorderKey o = (BorderKey) object;
return vertical == o.vertical
&& config == o.config && length == o.length;
}
@Override
public BorderKey clone() {
try {
return (BorderKey) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
}
protected void setThrottled(boolean throttled) {
mThrottled = throttled;
}
private static Bitmap getBorderLine(
boolean vertical, Config config, int length) {
BorderKey key = sBorderKey;
key.vertical = vertical;
key.config = config;
key.length = length;
Bitmap bitmap = sBorderLines.get(key);
if (bitmap == null) {
bitmap = vertical
? Bitmap.createBitmap(1, length, config)
: Bitmap.createBitmap(length, 1, config);
sBorderLines.put(key.clone(), bitmap);
}
return bitmap;
}
private Bitmap getBitmap() {
if (mBitmap == null) {
mBitmap = onGetBitmap();
if (mWidth == UNSPECIFIED) {
int w = mBitmap.getWidth() + mBorder * 2;
int h = mBitmap.getHeight() + mBorder * 2;
setSize(w, h);
}
}
return mBitmap;
}
private void freeBitmap() {
Assert.assertTrue(mBitmap != null);
onFreeBitmap(mBitmap);
mBitmap = null;
}
@Override
public int getWidth() {
if (mWidth == UNSPECIFIED) getBitmap();
return mWidth;
}
@Override
public int getHeight() {
if (mWidth == UNSPECIFIED) getBitmap();
return mHeight;
}
protected abstract Bitmap onGetBitmap();
protected abstract void onFreeBitmap(Bitmap bitmap);
public void invalidateContent() {
if (mBitmap != null) freeBitmap();
mContentValid = false;
mWidth = UNSPECIFIED;
mHeight = UNSPECIFIED;
}
/**
* Whether the content on GPU is valid.
*/
public boolean isContentValid() {
return isLoaded() && mContentValid;
}
/**
* Updates the content on GPU's memory.
* @param canvas
*/
public void updateContent(GLCanvas canvas) {
if (!isLoaded()) {
if (mThrottled && ++sUploadedCount > UPLOAD_LIMIT) {
return;
}
uploadToCanvas(canvas);
} else if (!mContentValid) {
Bitmap bitmap = getBitmap();
int format = GLUtils.getInternalFormat(bitmap);
int type = GLUtils.getType(bitmap);
canvas.texSubImage2D(this, mBorder, mBorder, bitmap, format, type);
freeBitmap();
mContentValid = true;
}
}
public static void resetUploadLimit() {
sUploadedCount = 0;
}
public static boolean uploadLimitReached() {
return sUploadedCount > UPLOAD_LIMIT;
}
private void uploadToCanvas(GLCanvas canvas) {
Bitmap bitmap = getBitmap();
if (bitmap != null) {
try {
int bWidth = bitmap.getWidth();
int bHeight = bitmap.getHeight();
int texWidth = getTextureWidth();
int texHeight = getTextureHeight();
Assert.assertTrue(bWidth <= texWidth && bHeight <= texHeight);
// Upload the bitmap to a new texture.
mId = canvas.getGLId().generateTexture();
canvas.setTextureParameters(this);
if (bWidth == texWidth && bHeight == texHeight) {
canvas.initializeTexture(this, bitmap);
} else {
int format = GLUtils.getInternalFormat(bitmap);
int type = GLUtils.getType(bitmap);
Config config = bitmap.getConfig();
canvas.initializeTextureSize(this, format, type);
canvas.texSubImage2D(this, mBorder, mBorder, bitmap, format, type);
if (mBorder > 0) {
// Left border
Bitmap line = getBorderLine(true, config, texHeight);
canvas.texSubImage2D(this, 0, 0, line, format, type);
// Top border
line = getBorderLine(false, config, texWidth);
canvas.texSubImage2D(this, 0, 0, line, format, type);
}
// Right border
if (mBorder + bWidth < texWidth) {
Bitmap line = getBorderLine(true, config, texHeight);
canvas.texSubImage2D(this, mBorder + bWidth, 0, line, format, type);
}
// Bottom border
if (mBorder + bHeight < texHeight) {
Bitmap line = getBorderLine(false, config, texWidth);
canvas.texSubImage2D(this, 0, mBorder + bHeight, line, format, type);
}
}
} finally {
freeBitmap();
}
// Update texture state.
setAssociatedCanvas(canvas);
mState = STATE_LOADED;
mContentValid = true;
} else {
mState = STATE_ERROR;
throw new RuntimeException("Texture load fail, no bitmap");
}
}
@Override
protected boolean onBind(GLCanvas canvas) {
updateContent(canvas);
return isContentValid();
}
@Override
protected int getTarget() {
return GL11.GL_TEXTURE_2D;
}
public void setOpaque(boolean isOpaque) {
mOpaque = isOpaque;
}
@Override
public boolean isOpaque() {
return mOpaque;
}
@Override
public void recycle() {
super.recycle();
if (mBitmap != null) freeBitmap();
}
}
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more