Compare commits

..
Author SHA1 Message Date
seven332 e292d7786c Update libraries 2017-11-13 14:46:25 +08:00
seven332 942938e629 Add CookieRepository 2017-08-13 15:33:32 +08:00
seven332 7785b55c92 Add HttpLoggingInterceptor 2017-08-13 15:32:49 +08:00
seven332 56cb112cef Fix gallery comment max lines 2017-08-12 21:37:32 +08:00
seven332 772a4db5f8 Add GalleryListScene 2017-08-12 21:35:28 +08:00
seven332 96095152e9 Add gallery comments 2017-08-11 16:04:11 +08:00
seven332 48af04e53e Show a tip if no tag 2017-08-11 13:28:22 +08:00
seven332 2c90238b2d Add gallery comments parsing 2017-08-11 13:00:22 +08:00
seven332 abda29dd17 Fix tag parsing 2017-08-10 23:48:15 +08:00
seven332 76cd12fb52 Fix UI for 0.0 rating 2017-08-10 23:43:30 +08:00
seven332 d121001056 Add gallery detail 2017-08-10 16:32:38 +08:00
seven332 835e2db327 Add NoiTask
It's useful for custom view
2017-08-08 00:08:40 +08:00
seven332 db53ee00ba Improve NoiView 2017-08-07 19:06:03 +08:00
seven332 31546e1758 Add EhvStageLayout 2017-08-07 14:09:20 +08:00
seven332 27722e807a Fix cancel checking in NoiView.onDetachedFromWindow() 2017-08-06 18:13:52 +08:00
seven332 11466a1faf Improve Explainer 2017-08-06 16:55:49 +08:00
seven332 5a5826e286 Add NoiView gravity 2017-08-06 14:38:28 +08:00
seven332 b9b58457f7 Fix NoiView.enableFade default value 2017-08-05 23:01:29 +08:00
seven332 cca3b8ce4f Add NoiView fading effect 2017-08-05 22:42:47 +08:00
seven332 f50025ca89 Add noi 2017-08-05 20:25:07 +08:00
seven332 009e627a3a Kotlin is awesome 2017-07-31 13:32:05 +08:00
218 changed files with 16144 additions and 2 deletions

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
*.iml
.gradle
/local.properties
/.idea
.DS_Store
/build
/captures
.externalNativeBuild
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
+1
View File
@@ -0,0 +1 @@
/build
+114
View File
@@ -0,0 +1,114 @@
/*
* Copyright 2017 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.
*/
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion "$target_sdk_version".toInteger()
buildToolsVersion "$build_tools_version"
defaultConfig {
applicationId "com.hippo.ehviewer"
minSdkVersion "$mini_sdk_version"
targetSdkVersion "$target_sdk_version"
versionCode 1
versionName "1.0"
vectorDrawables.useSupportLibrary = true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
debug {
applicationIdSuffix ".debug"
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
// Support libraries
compile "com.android.support:appcompat-v7:$support_library_version"
compile "com.android.support:recyclerview-v7:$support_library_version"
compile "com.android.support:design:$support_library_version"
// RxJava
compile "io.reactivex.rxjava2:rxjava:2.1.2"
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.jakewharton.rxbinding2:rxbinding:2.0.0'
compile 'com.jakewharton.rxrelay2:rxrelay:2.0.0'
// OkHttp
compile 'com.squareup.okhttp3:okhttp:3.8.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.8.1'
// Modified okio
compile 'com.github.seven332.okio:okio:1.13.0'
// UniFile
compile 'com.github.seven332:unifile:1.0.0'
// Jsoup
compile 'org.jsoup:jsoup:1.10.3'
// Stage
compile "com.github.seven332.stage:stage:$stage_library_version"
compile "com.github.seven332.stage:stage-dialog:$stage_library_version"
compile 'com.github.seven332.android-dialog:base:0.1.0'
// ViewState
compile "com.github.seven332.viewstate:viewstate:$view_state_library_version"
kapt "com.github.seven332.viewstate:viewstate-compiler:$view_state_library_version"
// Html
compile 'com.github.seven332:android-html:0.1.1'
// Widgets
compile "com.github.seven332:drawerlayout:$drawer_layout_library_version"
compile "com.github.seven332:refreshlayout:$refresh_layout_library_version"
compile 'com.github.seven332:swipeback:0.1.3'
compile 'com.google.android:flexbox:0.3.0'
compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.7'
// LeakCanary
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
testCompile 'junit:junit:4.12'
testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
testCompile 'org.robolectric:robolectric:3.4'
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
}
configurations.all {
// Use modified okio instead
exclude group: 'com.squareup.okio', module: 'okio'
}
+25
View File
@@ -0,0 +1,25 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in D:\work\Android\android-sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,43 @@
/*
* Copyright 2017 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;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.hippo.ehviewer", appContext.getPackageName());
}
}
+41
View File
@@ -0,0 +1,41 @@
<!--
~ Copyright 2017 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.
-->
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hippo.ehviewer">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:name=".EhvApp"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".activity.EhvActivity"
android:theme="@style/AppTheme.Ehv">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,65 @@
/*
* Copyright 2017 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
import android.app.Application
import com.hippo.ehviewer.client.AutoSwitchClient
import com.hippo.ehviewer.client.AutoSwitchUrl
import com.hippo.ehviewer.network.CookieRepository
import com.hippo.ehviewer.noi.Noi
import com.squareup.leakcanary.LeakCanary
import com.squareup.leakcanary.RefWatcher
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.io.File
import kotlin.properties.Delegates
/*
* Created by Hippo on 2017/7/23.
*/
var REF_WATCHER: RefWatcher by Delegates.notNull<RefWatcher>()
private set
var EHV_APP: EhvApp by Delegates.notNull<EhvApp>()
private set
val EHV_PREFERENCES: EhvPreferences by lazy { EhvPreferences(EHV_APP) }
val OK_HTTP_CLIENT: OkHttpClient by lazy {
OkHttpClient.Builder()
.cache(Cache(File(EHV_APP.cacheDir, "okhttp").apply { mkdirs() }, 50 * 1024 * 1024))
.cookieJar(CookieRepository(EHV_APP))
.addNetworkInterceptor(HttpLoggingInterceptor().also { it.level = HttpLoggingInterceptor.Level.BASIC })
.build()
}
val NOI: Noi by lazy { Noi(EHV_APP, client = OK_HTTP_CLIENT) }
val EH_CLIENT: AutoSwitchClient by lazy { AutoSwitchClient(NOI, EHV_PREFERENCES.ehMode.observable) }
val EH_URL: AutoSwitchUrl by lazy { AutoSwitchUrl(EHV_PREFERENCES.ehMode.observable) }
class EhvApp : Application() {
override fun onCreate() {
EHV_APP = this
super.onCreate()
REF_WATCHER = LeakCanary.install(this)
}
}
@@ -0,0 +1,37 @@
/*
* Copyright 2017 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
import android.content.Context
import com.hippo.ehviewer.client.EH_MODE_E
import com.hippo.ehviewer.preference.Preferences
/*
* Created by Hippo on 2017/7/28.
*/
const val LIST_MODE_DETAIL = 0
const val LIST_MODE_BRIEF = 1
class EhvPreferences(context: Context) : Preferences(context.getSharedPreferences("ehv2", 0)) {
val listMode = IntPreference("list_mode", LIST_MODE_DETAIL)
val detailWidth = IntPreference("detail_width", 300)
val briefWidth = IntPreference("brief_width", 120)
val ehMode = IntPreference("eh_mode", EH_MODE_E)
}
@@ -0,0 +1,55 @@
/*
* Copyright 2017 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.activity
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.Snackbar
import android.view.ViewGroup
import com.hippo.ehviewer.R
import com.hippo.ehviewer.scene.MainScene
import com.hippo.ehviewer.util.find
import com.hippo.stage.Scene
/*
* Created by Hippo on 2017/7/23.
*/
class EhvActivity : StageActivity() {
private lateinit var coordinatorLayout: CoordinatorLayout
private lateinit var stageLayout: ViewGroup
override fun onSetContentView() {
setContentView(R.layout.activity_ehv)
coordinatorLayout = find(R.id.coordinator_layout)
stageLayout = find(R.id.stage_layout)
}
override fun onGetStageLayout(): ViewGroup = stageLayout
override fun onCreateRootScene(): Scene = MainScene()
fun snack(resId: Int) {
Snackbar.make(coordinatorLayout, resId, Snackbar.LENGTH_SHORT).show()
}
fun snack(message: CharSequence?) {
if (message != null && message.isNotBlank()) {
Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_SHORT).show()
}
}
}
@@ -0,0 +1,87 @@
/*
* Copyright 2017 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.activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.ViewGroup
import com.hippo.stage.Director
import com.hippo.stage.Scene
import com.hippo.stage.Stage
/*
* Created by Hippo on 2017/7/23.
*/
abstract class StageActivity : AppCompatActivity() {
companion object {
private const val STAGE_ID = 0
}
private var director: Director? = null
private var stage: Stage? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
onSetContentView()
val director = Director.hire(this, savedInstanceState)
this.director = director
val needRoot = !director.contains(STAGE_ID)
val stage = director.direct(onGetStageLayout(), STAGE_ID)
this.stage = stage
if (needRoot) {
stage.pushScene(onCreateRootScene())
}
}
/**
* Sets content view for this `Activity`.
*
* Please call [setContentView] here.
*
* It's called in [onCreate].
*/
protected abstract fun onSetContentView()
/**
* Returns the container for scenes.
*/
protected abstract fun onGetStageLayout(): ViewGroup
/**
* Returns root scene for this `StageActivity`.
*/
protected abstract fun onCreateRootScene(): Scene
override fun onDestroy() {
super.onDestroy()
director = null
stage = null
}
override fun onBackPressed() {
if (!(director?.handleBack() ?: false)) {
super.onBackPressed()
}
}
}
@@ -0,0 +1,77 @@
/*
* Copyright 2017 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.adapter
import android.support.annotation.CallSuper
import com.hippo.ehviewer.mvp.MvpPaper
import com.hippo.ehviewer.widget.content.ContentDataAdapter
import io.reactivex.Observable
/*
* Created by Hippo on 6/13/2017.
*/
abstract class AlertAdapter<T : Any, VH: AlertHolder>(
lifecycle: Observable<Int>
) : ContentDataAdapter<T, VH>() {
private val holderList = mutableListOf<VH>()
private var isResumed = false
set(value) {
field = value
holderList.forEach { it.isResumed = value }
}
init {
lifecycle.subscribe({
when (it) {
MvpPaper.RESUME -> isResumed = true
MvpPaper.PAUSE -> isResumed = false
MvpPaper.DESTROY -> {
holderList.clear()
}
}
}, { /* Ignore error */ })
}
@CallSuper
override fun onBindViewHolder(holder: VH, position: Int) {
if (isResumed) {
holder.isResumed = true
}
holderList.add(holder)
}
override fun onViewAttachedToWindow(holder: VH) {
super.onViewAttachedToWindow(holder)
holder.isAttached = true
}
override fun onViewDetachedFromWindow(holder: VH) {
super.onViewDetachedFromWindow(holder)
holder.isAttached = false
}
@CallSuper
override fun onViewRecycled(holder: VH) {
super.onViewRecycled(holder)
holderList.remove(holder)
holder.isAttached = false
holder.isResumed = false
}
}
@@ -0,0 +1,65 @@
/*
* Copyright 2017 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.adapter
import android.support.annotation.CallSuper
import android.support.v7.widget.RecyclerView
import android.view.View
/*
* Created by Hippo on 6/13/2017.
*/
abstract class AlertHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private var hasResumed = false
internal var isAttached = false
set(value) {
if (field == value) return
field = value
if (value && isResumed) resume() else pause()
}
internal var isResumed = false
set(value) {
if (field == value) return
field = value
if (value && isAttached) resume() else pause()
}
private fun resume() {
if (!hasResumed) {
hasResumed = true
onResume()
}
}
private fun pause() {
if (hasResumed) {
hasResumed = false
onPause()
}
}
@CallSuper
open fun onResume() {}
@CallSuper
open fun onPause() {}
}
@@ -0,0 +1,80 @@
/*
* Copyright 2017 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.client
import com.hippo.ehviewer.client.data.Comment
import com.hippo.ehviewer.client.data.GalleryInfo
import com.hippo.ehviewer.client.parser.parseGalleryDetail
import com.hippo.ehviewer.client.parser.parseGalleryList
import com.hippo.ehviewer.client.parser.parseLofiGalleryDetail
import com.hippo.ehviewer.client.parser.parseLofiGalleryList
import com.hippo.ehviewer.noi.Noi
import io.reactivex.Observable
import io.reactivex.Single
/*
* Created by Hippo on 2017/7/24.
*/
interface EhClient {
fun galleryList(url: String): Single<Pair<List<GalleryInfo>, Int>>
fun galleryDetail(url: String): Single<Pair<GalleryInfo, List<Comment>>>
}
private class EClient(val noi: Noi) : EhClient {
override fun galleryList(url: String): Single<Pair<List<GalleryInfo>, Int>> =
noi.http(url).asResponse().parse { parseGalleryList(it) }
override fun galleryDetail(url: String): Single<Pair<GalleryInfo, List<Comment>>> =
noi.http(url).asResponse().parse { parseGalleryDetail(it) }
}
private class LofiClient(val noi: Noi) : EhClient {
override fun galleryList(url: String): Single<Pair<List<GalleryInfo>, Int>> =
noi.http(url).asResponse().parse { parseLofiGalleryList(it) }
override fun galleryDetail(url: String): Single<Pair<GalleryInfo, List<Comment>>> =
noi.http(url).asResponse().parse { parseLofiGalleryDetail(it) }
}
private typealias ExClient = EClient
/** Switches client automatically **/
class AutoSwitchClient(noi: Noi, ehModeObservable: Observable<Int>) : EhClient {
val eClient: EhClient by lazy { EClient(noi) }
val lofiClient: EhClient by lazy { LofiClient(noi) }
val exClient: EhClient by lazy { ExClient(noi) }
lateinit var current: EhClient
private set
init {
ehModeObservable.subscribe({ mode ->
when (mode) {
EH_MODE_E -> current = eClient
EH_MODE_LOFI -> current = lofiClient
EH_MODE_EX -> current = exClient
}
}, { /* Ignore error */ })
}
override fun galleryList(url: String) = current.galleryList(url)
override fun galleryDetail(url: String) = current.galleryDetail(url)
}
@@ -0,0 +1,77 @@
/*
* Copyright 2017 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.client
import com.hippo.ehviewer.exception.GeneralException
import com.hippo.ehviewer.exception.ParseException
import com.hippo.ehviewer.exception.ResponseCodeException
import com.hippo.ehviewer.exception.SadPandaException
import io.reactivex.Single
import io.reactivex.functions.Function
import okhttp3.MediaType
import okhttp3.Response
/*
* Created by Hippo on 2017/7/25.
*/
private val SAD_PANDA_MEDIA_TYPE = MediaType.parse("image/gif")
private const val SAD_PANDA_CONTENT_LENGTH = 9615L
private const val PLAIN_NOTICE_MAX_LENGTH = 512
private class EhParser<T>(val parser: (String) -> T) : Function<Response, T> {
override fun apply(response: Response): T {
// Make sure response is closed after applying
response.use { return doApply(it) }
}
private fun doApply(response: Response): T {
val body = response.body()!!
// Check sad panda
if (response.request().url().host() == HOST_EX &&
body.contentLength() == SAD_PANDA_CONTENT_LENGTH &&
body.contentType() == SAD_PANDA_MEDIA_TYPE) {
throw SadPandaException()
}
val string = body.string()
try {
// Check response code
if (!response.isSuccessful) {
throw ResponseCodeException(response.code())
}
return parser(string)
} catch (e: Throwable) {
// Check plain text body
if (!string.contains("<") && string.length <= PLAIN_NOTICE_MAX_LENGTH) {
throw GeneralException(string)
} else {
// Fill body of ParseException
if (e is ParseException) {
e.body = string
}
throw e
}
}
}
}
fun <T> Single<Response>.parse(parser: (String) -> T): Single<T> = map(EhParser(parser))
@@ -0,0 +1,110 @@
/*
* Copyright 2017 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.client
import io.reactivex.Observable
import okhttp3.HttpUrl
/*
* Created by Hippo on 2017/7/25.
*/
const val EH_MODE_E = 0
const val EH_MODE_LOFI = 1
const val EH_MODE_EX = 2
const val HOST_E = "e-hentai.org"
const val HOST_LOFI = "e-hentai.org"
const val HOST_EX = "exhentai.org"
const val URL_E = "https://e-hentai.org/"
const val URL_LOFI = "https://e-hentai.org/lofi/"
const val URL_EX = "https://exhentai.org/"
const val URL_COVER_E = "https://ul.ehgt.org/"
const val URL_COVER_EX = "https://exhentai.org/t/"
/** width == 200 **/
const val COVER_SIZE_200 = "l"
/** width == 250 **/
const val COVER_SIZE_250 = "250"
/** width == 300 **/
const val COVER_SIZE_300 = "300"
private fun appendQuery(url: String, query: Map<String, String>): String {
if (query.isEmpty()) return url
val builder = HttpUrl.parse(url)!!.newBuilder()
for ((name, value) in query) {
builder.addQueryParameter(name, value)
}
return builder.toString()
}
interface EhUrl {
fun galleryListUrl(query: Map<String, String>): String
fun coverUrl(fingerprint: String, type: String): String
fun galleryDetailUrl(gid: Long, token: String): String
}
private abstract class BaseUrl(
val baseUrl: String,
val coverUrl: String
) : EhUrl {
override fun galleryListUrl(query: Map<String, String>): String = appendQuery(baseUrl, query)
override fun coverUrl(fingerprint: String, type: String): String =
coverUrl + fingerprint.substring(0, 2) + "/" + fingerprint.substring(2, 4) + "/" + fingerprint + "_" + type + ".jpg"
override fun galleryDetailUrl(gid: Long, token: String): String = baseUrl + "g/" + gid + "/" + token + "/"
}
private class EUrl : BaseUrl(URL_E, URL_COVER_E)
private class LofiUrl : BaseUrl(URL_LOFI, URL_COVER_E)
private class ExUrl : BaseUrl(URL_EX, URL_COVER_EX)
/** Switches url automatically **/
class AutoSwitchUrl(ehModeObservable: Observable<Int>) : EhUrl {
val eUrl: EhUrl by lazy { EUrl() }
val lofiUrl: EhUrl by lazy { LofiUrl() }
val exUrl: EhUrl by lazy { ExUrl() }
lateinit var current: EhUrl
private set
init {
ehModeObservable.subscribe({ mode ->
when (mode) {
EH_MODE_E -> current = eUrl
EH_MODE_LOFI -> current = lofiUrl
EH_MODE_EX -> current = exUrl
}
}, { /* Ignore error */ })
}
override fun galleryListUrl(query: Map<String, String>): String = current.galleryListUrl(query)
override fun coverUrl(fingerprint: String, type: String): String = current.coverUrl(fingerprint, type)
override fun galleryDetailUrl(gid: Long, token: String): String = current.galleryDetailUrl(gid, token)
}
@@ -0,0 +1,344 @@
/*
* Copyright 2017 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.client
import android.graphics.Color
import com.hippo.ehviewer.R
import java.util.regex.Pattern
/*
* Created by Hippo on 2017/7/25.
*/
///////////////////////////////////////////////////////////////////////////
// Category
///////////////////////////////////////////////////////////////////////////
const val CATEGORY_MISC = 0x1
const val CATEGORY_DOUJINSHI = 0x2
const val CATEGORY_MANGA = 0x4
const val CATEGORY_ARTIST_CG = 0x8
const val CATEGORY_GAME_CG = 0x10
const val CATEGORY_IMAGE_SET = 0x20
const val CATEGORY_COSPLAY = 0x40
const val CATEGORY_ASIAN_PORN = 0x80
const val CATEGORY_NON_H = 0x100
const val CATEGORY_WESTERN = 0x200
/** Indicate no category specify **/
const val CATEGORY_NONE = 0
/** Unknown category **/
const val CATEGORY_UNKNOWN = -1
private val CATEGORY_VALUES = intArrayOf(
CATEGORY_MISC,
CATEGORY_DOUJINSHI,
CATEGORY_MANGA,
CATEGORY_ARTIST_CG,
CATEGORY_GAME_CG,
CATEGORY_IMAGE_SET,
CATEGORY_COSPLAY,
CATEGORY_ASIAN_PORN,
CATEGORY_NON_H,
CATEGORY_WESTERN
)
private val CATEGORY_STRINGS = arrayOf(
arrayOf("misc"),
arrayOf("doujinshi"),
arrayOf("manga"),
arrayOf("artist cg", "artistcg", "artist cg sets"),
arrayOf("game cg", "gamecg", "game cg sets"),
arrayOf("image set", "imageset", "image sets"),
arrayOf("cosplay"),
arrayOf("asian porn", "asianporn", "asian porn"),
arrayOf("non-h"),
arrayOf("western")
)
private val CATEGORY_STRING_UNKNOWN = "unknown"
/**
* Converts category value to category string.
* Returns `null` if invalid.
*/
fun Int.categoryString(): String? {
val index = CATEGORY_VALUES.indexOf(this)
if (index >= 0) {
return CATEGORY_STRINGS[index][0]
} else {
return null
}
}
/**
* Converts category value to category string.
* Returns `unknown` if invalid.
*/
fun Int.categoryStringNonNull(): String = categoryString() ?: CATEGORY_STRING_UNKNOWN
/**
* Convert category string to category value.
* Returns [CATEGORY_UNKNOWN] if invalid.
*/
fun String.categoryValue(): Int {
val lowerCase = this.toLowerCase()
val index = CATEGORY_STRINGS.indexOfFirst { it.contains(lowerCase) }
if (index >= 0) {
return CATEGORY_VALUES[index]
} else {
return CATEGORY_UNKNOWN
}
}
const val COLOR_DOUJINSHI = 0xfff44336.toInt() // red_500
const val COLOR_MANGA = 0xffff9800.toInt() // orange_500
const val COLOR_ARTIST_CG = 0xffffc107.toInt() // amber_500
const val COLOR_GAME_CG = 0xff4caf50.toInt() // green_500
const val COLOR_WESTERN = 0xff8bc34a.toInt() // light_green_500
const val COLOR_NON_H = 0xff2196f3.toInt() // blue_500
const val COLOR_IMAGE_SET = 0xff3f51b5.toInt() // indigo_500
const val COLOR_COSPLAY = 0xff9c27b0.toInt() // purple_500
const val COLOR_ASIAN_PORN = 0xff9575cd.toInt() // deep_purple_300
const val COLOR_MISC = 0xfff06292.toInt() // pink_300
const val COLOR_UNKNOWN = Color.BLACK
/**
* Get the color to represent the category.
* Returns black if can't recognize the category.
*/
fun Int.categoryColor(): Int {
when (this) {
CATEGORY_DOUJINSHI -> return COLOR_DOUJINSHI
CATEGORY_MANGA -> return COLOR_MANGA
CATEGORY_ARTIST_CG -> return COLOR_ARTIST_CG
CATEGORY_GAME_CG -> return COLOR_GAME_CG
CATEGORY_WESTERN -> return COLOR_WESTERN
CATEGORY_NON_H -> return COLOR_NON_H
CATEGORY_IMAGE_SET -> return COLOR_IMAGE_SET
CATEGORY_COSPLAY -> return COLOR_COSPLAY
CATEGORY_ASIAN_PORN -> return COLOR_ASIAN_PORN
CATEGORY_MISC -> return COLOR_MISC
else -> return COLOR_UNKNOWN
}
}
///////////////////////////////////////////////////////////////////////////
// Language
///////////////////////////////////////////////////////////////////////////
/** Japanese **/
const val LANG_JA = 0
/** English **/
const val LANG_EN = 1
/** Chinese **/
const val LANG_ZH = 2
/** Dutch **/
const val LANG_NL = 3
/** French **/
const val LANG_FR = 4
/** German **/
const val LANG_DE = 5
/** Hungarian **/
const val LANG_HU = 6
/** Italian **/
const val LANG_IT = 7
/** Korean **/
const val LANG_KO = 8
/** Polish **/
const val LANG_PL = 9
/** Portuguese **/
const val LANG_PT = 10
/** Russian **/
const val LANG_RU = 11
/** Spanish **/
const val LANG_ES = 12
/** Thai **/
const val LANG_TH = 13
/** Vietnamese **/
const val LANG_VI = 14
/** N/A **/
const val LANG_N_A = 15
/** Other **/
const val LANG_OTHER = 16
/** Unknown **/
val LANG_UNKNOWN = -1
private val LANG_PATTERN_EN = Pattern.compile("[(\\[]eng(?:lish)?[)\\]]|英訳", Pattern.CASE_INSENSITIVE)
private val LANG_PATTERN_ZH = Pattern.compile("[((\\[]ch(?:inese)?[))\\]]|[汉漢]化|中[国國][语語]|中文|中国翻訳", Pattern.CASE_INSENSITIVE)
private val LANG_PATTERN_NL = Pattern.compile("[(\\[]dutch[)\\]]|オランダ語訳", Pattern.CASE_INSENSITIVE)
private val LANG_PATTERN_FR = Pattern.compile("[(\\[]fr(?:ench)?[)\\]]|フランス翻訳", Pattern.CASE_INSENSITIVE)
private val LANG_PATTERN_DE = Pattern.compile("[(\\[]german[)\\]]|ドイツ翻訳", Pattern.CASE_INSENSITIVE)
private val LANG_PATTERN_HU = Pattern.compile("[(\\[]hun(?:garian)?[)\\]]|ハンガリー翻訳", Pattern.CASE_INSENSITIVE)
private val LANG_PATTERN_IT = Pattern.compile("[(\\[]italiano?[)\\]]|イタリア翻訳", Pattern.CASE_INSENSITIVE)
private val LANG_PATTERN_KO = Pattern.compile("[(\\[]korean?[)\\]]|韓国翻訳", Pattern.CASE_INSENSITIVE)
private val LANG_PATTERN_PL = Pattern.compile("[(\\[]polish[)\\]]|ポーランド翻訳", Pattern.CASE_INSENSITIVE)
private val LANG_PATTERN_PT = Pattern.compile("[(\\[]portuguese|ポルトガル翻訳", Pattern.CASE_INSENSITIVE)
private val LANG_PATTERN_RU = Pattern.compile("[(\\[]rus(?:sian)?[)\\]]|ロシア翻訳", Pattern.CASE_INSENSITIVE)
private val LANG_PATTERN_ES = Pattern.compile("[(\\[]spanish[)\\]]|[(\\[]Español[)\\]]|スペイン翻訳", Pattern.CASE_INSENSITIVE)
private val LANG_PATTERN_TH = Pattern.compile("[(\\[]thai(?: ภาษาไทย)?[)\\]]|แปลไทย|タイ翻訳", Pattern.CASE_INSENSITIVE)
private val LANG_PATTERN_VI = Pattern.compile("[(\\[]vietnamese(?: Tiếng Việt)?[)\\]]|ベトナム翻訳", Pattern.CASE_INSENSITIVE)
private val GUESS_LANGS = intArrayOf(
LANG_EN,
LANG_ZH,
LANG_ES,
LANG_KO,
LANG_RU,
LANG_FR,
LANG_PT,
LANG_TH,
LANG_DE,
LANG_IT,
LANG_VI,
LANG_PL,
LANG_HU,
LANG_NL
)
private val GUESS_LANG_PATTERNS = arrayOf(
LANG_PATTERN_EN,
LANG_PATTERN_ZH,
LANG_PATTERN_ES,
LANG_PATTERN_KO,
LANG_PATTERN_RU,
LANG_PATTERN_FR,
LANG_PATTERN_PT,
LANG_PATTERN_TH,
LANG_PATTERN_DE,
LANG_PATTERN_IT,
LANG_PATTERN_VI,
LANG_PATTERN_PL,
LANG_PATTERN_HU,
LANG_PATTERN_NL
)
fun guessLang(title: String): Int {
val index = GUESS_LANG_PATTERNS.indexOfFirst { it.matcher(title).find() }
if (index >= 0) {
return GUESS_LANGS[index]
} else {
return LANG_UNKNOWN
}
}
private val LANG_ABBR_IDS = intArrayOf(
R.string.language_abbr_japanese,
R.string.language_abbr_english,
R.string.language_abbr_chinese,
R.string.language_abbr_dutch,
R.string.language_abbr_french,
R.string.language_abbr_german,
R.string.language_abbr_hungarian,
R.string.language_abbr_italian,
R.string.language_abbr_korean,
R.string.language_abbr_polish,
R.string.language_abbr_portuguese,
R.string.language_abbr_russian,
R.string.language_abbr_spanish,
R.string.language_abbr_thai,
R.string.language_abbr_vietnamese
)
private val LANG_IDS = intArrayOf(
R.string.language_japanese,
R.string.language_english,
R.string.language_chinese,
R.string.language_dutch,
R.string.language_french,
R.string.language_german,
R.string.language_hungarian,
R.string.language_italian,
R.string.language_korean,
R.string.language_polish,
R.string.language_portuguese,
R.string.language_russian,
R.string.language_spanish,
R.string.language_thai,
R.string.language_vietnamese,
R.string.language_n_a,
R.string.language_other
)
private val LANG_TEXTS = arrayOf(
"japanese",
"english",
"chinese",
"dutch",
"french",
"german",
"hungarian",
"italian",
"korean",
"polish",
"portuguese",
"russian",
"spanish",
"thai",
"vietnamese"
)
/**
* Returns abbreviation resource id for the language.
* Returns `0` if invalid.
*/
fun Int.langAbbr(): Int {
if (this in 0 until LANG_ABBR_IDS.size) {
return LANG_ABBR_IDS[this]
} else {
return 0
}
}
/**
* Returns language resource id for the language.
* Returns `0` if invalid.
*/
fun Int.lang(): Int {
if (this in 0 until LANG_IDS.size) {
return LANG_IDS[this]
} else {
return 0
}
}
/**
* Returns text for the language.
* Returns `null` if invalid.
*/
fun Int.langText(): String? {
if (this in 0 until LANG_TEXTS.size) {
return LANG_TEXTS[this]
} else {
return null
}
}
/**
* Returns value for the language.
* Returns [LANG_UNKNOWN] if invalid.
*/
fun String.lang(): Int {
val lowerCase = this.toLowerCase()
val index = LANG_TEXTS.indexOfFirst { it == lowerCase }
return if (index >= 0) index else LANG_UNKNOWN
}
///////////////////////////////////////////////////////////////////////////
// Favourites
///////////////////////////////////////////////////////////////////////////
const val FAV_CAT_UNKNOWN = -1
@@ -0,0 +1,144 @@
/*
* Copyright 2017 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.client
import android.content.Context
import android.os.Parcel
import android.os.Parcelable
import com.hippo.ehviewer.R
import com.hippo.ehviewer.client.data.TagSet
/*
* Created by Hippo on 2017/7/25.
*/
class GLUrlBuilder() : Parcelable {
var page: Int = 0
var category: Int = CATEGORY_NONE
var language: Int = LANG_UNKNOWN
var keyword: String? = null
val tags = TagSet()
fun set(builder: GLUrlBuilder) {
page = builder.page
category = builder.category
language = builder.language
keyword = builder.keyword
tags.set(builder.tags)
}
fun toTitle(): Any {
return keyword?.takeIf { it.isNotEmpty() } ?:
category.categoryString()?.takeIf { it.isNotEmpty() } ?:
language.lang().takeIf { it != 0 } ?:
tags.firstTag()?.let { "${it.first}:${it.second}" } ?:
if (tags.isEmpty() && category == CATEGORY_NONE) R.string.gl_url_builder_homepage
else R.string.gl_url_builder_search
}
private fun appendTag(sb: StringBuilder, namespace: String, tag: String) {
if (sb.isNotEmpty()) sb.append(' ')
sb.append(namespace).append(":\"").append(tag).append("$\"")
}
// Combine keyword, language and tags
private fun resolveKeyword(): String? {
val sb = StringBuilder()
if (!keyword.isNullOrBlank()) {
sb.append(keyword)
}
val language = this.language.langText()
if (language != null) {
appendTag(sb, "language", language)
}
for ((namespace, list) in tags) {
for (tag in list) {
appendTag(sb, namespace, tag)
}
}
return if (sb.isNotEmpty()) sb.toString() else null
}
/**
* Build query map.
*/
fun build(): Map<String, String> {
val query = mutableMapOf<String, String>()
// True if need ("f_apply", "Apply+Filter")
var filter = false
// Category
if (category != CATEGORY_NONE) {
if (category and CATEGORY_DOUJINSHI != 0) query.put("f_doujinshi", "on")
if (category and CATEGORY_MANGA != 0) query.put("f_manga", "on")
if (category and CATEGORY_ARTIST_CG != 0) query.put("f_artistcg", "on")
if (category and CATEGORY_GAME_CG != 0) query.put("f_gamecg", "on")
if (category and CATEGORY_WESTERN != 0) query.put("f_western", "on")
if (category and CATEGORY_NON_H != 0) query.put("f_non-h", "on")
if (category and CATEGORY_IMAGE_SET != 0) query.put("f_imageset", "on")
if (category and CATEGORY_COSPLAY != 0) query.put("f_cosplay", "on")
if (category and CATEGORY_ASIAN_PORN != 0) query.put("f_asianporn", "on")
if (category and CATEGORY_MISC != 0) query.put("f_misc", "on")
filter = true
}
// Keyword
val keyword = resolveKeyword()
if (keyword != null) {
query.put("f_search", keyword)
filter = true
}
// Page
if (page != 0) {
query.put("page", Integer.toString(page))
}
// Add filter foot
if (filter) {
query.put("f_apply", "Apply Filter")
}
return query
}
constructor(parcel: Parcel) : this() {
page = parcel.readInt()
category = parcel.readInt()
language = parcel.readInt()
keyword = parcel.readString()
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(page)
parcel.writeInt(category)
parcel.writeInt(language)
parcel.writeString(keyword)
}
override fun describeContents(): Int = 0
companion object CREATOR : Parcelable.Creator<GLUrlBuilder> {
override fun createFromParcel(parcel: Parcel): GLUrlBuilder = GLUrlBuilder(parcel)
override fun newArray(size: Int): Array<GLUrlBuilder?> = arrayOfNulls(size)
}
}
@@ -0,0 +1,71 @@
/*
* Copyright 2017 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.client.data
import android.os.Parcel
import android.os.Parcelable
/*
* Created by Hippo on 2017/8/11.
*/
class Comment() : Parcelable {
// 0 for uploader comment. can't vote
var id: Long = 0
var date: Long = 0
var user: String? = null
var comment: String? = null
var score: Int = 0
var votedUp: Boolean = false
var votedDown: Boolean = false
var voteState: String? = null
constructor(parcel: Parcel) : this() {
id = parcel.readLong()
date = parcel.readLong()
user = parcel.readString()
comment = parcel.readString()
score = parcel.readInt()
votedUp = parcel.readByte() != 0.toByte()
votedDown = parcel.readByte() != 0.toByte()
voteState = parcel.readString()
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeLong(id)
parcel.writeLong(date)
parcel.writeString(user)
parcel.writeString(comment)
parcel.writeInt(score)
parcel.writeByte(if (votedUp) 1 else 0)
parcel.writeByte(if (votedDown) 1 else 0)
parcel.writeString(voteState)
}
override fun describeContents(): Int = 0
companion object CREATOR : Parcelable.Creator<Comment> {
override fun createFromParcel(parcel: Parcel): Comment {
return Comment(parcel)
}
override fun newArray(size: Int): Array<Comment?> {
return arrayOfNulls(size)
}
}
}
@@ -0,0 +1,300 @@
/*
* Copyright 2017 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.client.data
import android.os.Parcel
import android.os.Parcelable
import com.hippo.ehviewer.client.CATEGORY_UNKNOWN
import com.hippo.ehviewer.client.FAV_CAT_UNKNOWN
import com.hippo.ehviewer.client.LANG_UNKNOWN
/*
* Created by Hippo on 2017/7/25.
*/
/**
* `GalleryInfo` is the information about a gallery from api or html parsing.
*/
class GalleryInfo() : Parcelable {
/**
* Gallery ID.
*
* `0` if invalid.
*/
var gid: Long = 0
/**
* Gallery token. Most gallery operations need it.
*
* Empty string if invalid
*
* Regex:
* ```
* [0-9a-f]{10}
* ```
*
* Example:
* ```
* c219d2cf41
* ```
*/
var token: String = ""
/**
* Gallery title.
*/
var title: String? = null
/**
* Gallery japanese title.
*/
var titleJpn: String? = null
/**
* The fingerprint of the first image.
*
* Format:
* ```
* [sha1]-[size]-[width]-[height]-[format]
* ```
*
* Regex:
* ```
* [0-9a-f]{40}-\d+-\d+-\d+-[0-9a-z]+
* ```
*
* Example:
* ```
* 7dd3e4a62807a6938910a14407d9867b18a58a9f-2333088-2831-4015-jpg
* ```
*/
var coverFingerprint: String? = null
/**
* The url of the first image.
*/
var coverUrl: String? = null
/**
* `width / height` of the first image.
*
* `0.0f` if invalid.
*/
var coverRatio: Float = 0.0f
/**
* Gallery category.
*
* [CATEGORY_UNKNOWN] if invalid.
*/
var category: Int = CATEGORY_UNKNOWN
/**
* Posted time stamp.
*
* `0` if invalid.
*/
var date: Long = 0
/**
* The user that uploads the gallery.
*/
var uploader: String? = null
/**
* Gallery Rating.
*
* Range:
* ```
* [0.5, 5]
* ```
*
* `0.0f` if invalid.
*/
var rating: Float = 0.0f
/**
* How many users rated the gallery.
*
* `0` if invalid.
*/
var rated: Int = 0
/**
* Gallery Language.
*
* [LANG_UNKNOWN] if invalid.
*/
var language: Int = LANG_UNKNOWN
/**
* How many users favourited the gallery.
*
* `0` if can't get it.
*/
var favourited: Int = 0
/**
* Favourite slot.
*
* Range: `[-1, 9]`
*
* `-1` if invalid.
*/
var favouriteSlot: Int = FAV_CAT_UNKNOWN
/**
* Expunged, deleted or replaced.
*/
var invalid: Boolean = false
/**
* The key to download archive.
*/
var archiveKey: String? = null
/**
* Gallery Pages.
*
* `0` if invalid.
*/
var pages: Int = 0
/**
* Gallery size in bytes.
*
* `0` if invalid.
*/
var size: Long = 0
/**
* Torrent count.
*
* `0` for default.
*/
var torrents = 0
/**
* Gallery tags.
*/
val tags: TagSet = TagSet()
/**
* The gid of the parent gallery.
*
* `0` if no parent.
*
* The parent is a gallery which is replaced by this gallery.
*/
var parentGid: Long = 0
/**
* The token of the parent gallery.
*
* `null` if no parent.
*
* The parent is a gallery which is replaced by this gallery.
*/
var parentToken: String? = null
/**
* The gid of the child gallery.
*
* `0` if no child.
*
* The child is a gallery which replaces this gallery.
*/
var childGid: Long = 0
/**
* The token of the child gallery.
*
* `null` if no child.
*
* The child is a gallery which replaces this gallery.
*/
var childToken: String? = null
constructor(parcel: Parcel) : this() {
gid = parcel.readLong()
token = parcel.readString()
title = parcel.readString()
titleJpn = parcel.readString()
coverFingerprint = parcel.readString()
coverUrl = parcel.readString()
coverRatio = parcel.readFloat()
category = parcel.readInt()
date = parcel.readLong()
uploader = parcel.readString()
rating = parcel.readFloat()
rated = parcel.readInt()
language = parcel.readInt()
favourited = parcel.readInt()
favouriteSlot = parcel.readInt()
invalid = parcel.readByte() != 0.toByte()
archiveKey = parcel.readString()
pages = parcel.readInt()
size = parcel.readLong()
torrents = parcel.readInt()
tags.set(parcel.readParcelable(this::class.java.classLoader))
parentGid = parcel.readLong()
parentToken = parcel.readString()
childGid = parcel.readLong()
childToken = parcel.readString()
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeLong(gid)
parcel.writeString(token)
parcel.writeString(title)
parcel.writeString(titleJpn)
parcel.writeString(coverFingerprint)
parcel.writeString(coverUrl)
parcel.writeFloat(coverRatio)
parcel.writeInt(category)
parcel.writeLong(date)
parcel.writeString(uploader)
parcel.writeFloat(rating)
parcel.writeInt(rated)
parcel.writeInt(language)
parcel.writeInt(favourited)
parcel.writeInt(favouriteSlot)
parcel.writeByte(if (invalid) 1 else 0)
parcel.writeString(archiveKey)
parcel.writeInt(pages)
parcel.writeLong(size)
parcel.writeInt(torrents)
parcel.writeParcelable(tags, flags)
parcel.writeLong(parentGid)
parcel.writeString(parentToken)
parcel.writeLong(childGid)
parcel.writeString(childToken)
}
override fun describeContents(): Int = 0
companion object CREATOR : Parcelable.Creator<GalleryInfo> {
override fun createFromParcel(parcel: Parcel): GalleryInfo {
return GalleryInfo(parcel)
}
override fun newArray(size: Int): Array<GalleryInfo?> {
return arrayOfNulls(size)
}
}
}
@@ -0,0 +1,114 @@
/*
* Copyright 2017 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.client.data
import android.os.Parcel
import android.os.Parcelable
/*
* Created by Hippo on 2017/7/25.
*/
class TagSet() : Iterable<Map.Entry<String, List<String>>>, Parcelable {
private val map = LinkedHashMap<String, MutableList<String>>()
fun add(namespace: String, tag: String) {
var list = map[namespace]
if (list == null) {
list = arrayListOf()
map[namespace] = list
}
list.add(tag)
}
fun remove(namespace: String, tag: String) {
val list = map[namespace]
if (list != null) {
list.remove(tag)
if (list.isEmpty()) {
map.remove(namespace)
}
}
}
override fun iterator(): Iterator<Map.Entry<String, List<String>>> = map.iterator()
fun size(): Int = map.values.sumBy { it.size }
fun isEmpty(): Boolean = map.isEmpty()
fun firstTag(): Pair<String, String>? {
val iterator = map.iterator()
if (iterator.hasNext()) {
val (namespace, tags) = iterator.next()
if (tags.isNotEmpty()) {
return Pair(namespace, tags[0])
} else {
return null
}
} else {
return null
}
}
fun clear(): Unit = map.clear()
fun set(tags: TagSet) {
map.clear()
for ((namespace, list) in tags) {
map[namespace] = ArrayList(list)
}
}
constructor(parcel: Parcel) : this() {
for (i in 0 until parcel.readInt()) {
val namespace = parcel.readString()
val list = arrayListOf<String>()
map[namespace] = list
for (j in 0 until parcel.readInt()) {
list.add(parcel.readString())
}
}
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(map.size)
for ((namespace, list) in map) {
parcel.writeString(namespace)
parcel.writeInt(list.size)
for (tag in list) {
parcel.writeString(tag)
}
}
}
override fun describeContents(): Int = 0
companion object CREATOR : Parcelable.Creator<TagSet> {
override fun createFromParcel(parcel: Parcel): TagSet {
return TagSet(parcel)
}
override fun newArray(size: Int): Array<TagSet?> {
return arrayOfNulls(size)
}
}
}
@@ -0,0 +1,199 @@
/*
* Copyright 2017 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.client.parser
import com.hippo.ehviewer.client.CATEGORY_UNKNOWN
import com.hippo.ehviewer.client.FAV_CAT_UNKNOWN
import com.hippo.ehviewer.client.categoryValue
import com.hippo.ehviewer.client.data.Comment
import com.hippo.ehviewer.client.data.GalleryInfo
import com.hippo.ehviewer.client.lang
import com.hippo.ehviewer.client.parser.url.parseArchiveUrl
import com.hippo.ehviewer.client.parser.url.parseCoverUrl
import com.hippo.ehviewer.client.parser.url.parseGalleryDetailUrl
import com.hippo.ehviewer.exception.ParseException
import com.hippo.ehviewer.util.strip
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.util.regex.Pattern
/*
* Created by Hippo on 2017/7/31.
*/
private val PATTERN_COVER = Pattern.compile("width:(\\d+)px; height:(\\d+)px.+?url\\((.+?)\\)")
private val PATTERN_ARCHIVE = Pattern.compile("<a[^<>]*onclick=\"return popUp\\('([^']+)'[^)]+\\)\">Archive Download</a>")
private val PATTERN_TORRENT = Pattern.compile("<a[^<>]*onclick=\"return popUp\\('([^']+)'[^)]+\\)\">Torrent Download \\( (\\d+) \\)</a>")
fun parseGalleryDetail(document: Document): GalleryInfo? {
// Get gid and toke from report url
val (gid, token) = document.elementById("gd5")?.firstChild()?.firstChild(1)?.attr("href")?.parseGalleryDetailUrl() ?: return null
val info = GalleryInfo()
info.gid = gid
info.token = token
document.elementById("gd1")?.firstChild()?.attr("style")?.also { style ->
// // width:250px; height:356px; background:transparent url(https://exhentai.org/t/fe/1f/fe1fcfa9bf8fba2f03982eda0aa347cc9d6a6372-145921-1050-1492-jpg_250.jpg) 0 0 no-repeat
PATTERN_COVER.matcher(style).takeIf { it.find() }?.also { matcher ->
val width = matcher.group(1).integer()
val height = matcher.group(2).integer()
if (width != null && height != null) {
info.coverRatio = width.toFloat() / height.toFloat()
}
matcher.group(3).unescape()?.also { url ->
info.coverUrl = url
info.coverFingerprint = url.parseCoverUrl()
}
}
}
document.elementById("gd2")?.also { gd2 ->
info.title = gd2.elementById("gn")?.unescape()
info.titleJpn = gd2.elementById("gj")?.unescape()
}
document.elementById("gd5")?.html()?.also { html ->
PATTERN_ARCHIVE.matcher(html).takeIf { it.find() }?.also { matcher ->
matcher.group(1).unescape()?.parseArchiveUrl()?.also { (gid, token, archiveKey) ->
if (info.gid == gid && info.token == token) {
info.archiveKey = archiveKey
}
}
}
PATTERN_TORRENT.matcher(html).takeIf { it.find() }?.also { matcher ->
info.torrents = matcher.group(2).integer() ?: 0
}
}
info.category = document.elementById("gdc")?.firstChild()?.firstChild()?.attr("alt")?.categoryValue() ?: CATEGORY_UNKNOWN
info.uploader = document.elementById("gdn")?.unescape()
document.elementById("gdd")?.elementByTag("tbody")?.children()?.forEach { element ->
element.children().takeIf { it.size >= 2 }?.also { children ->
val key = children[0].unescape() ?: ""
val value = children[1].ownText().unescape() ?: ""
if (key.startsWith("Posted")) {
info.date = value.date()
} else if (key.startsWith("Parent")) {
children[1].firstChild()?.attr("href")?.parseGalleryDetailUrl()?.also { (gid, token) ->
info.parentGid = gid
info.parentToken = token
}
} else if (key.startsWith("Visible")) {
info.invalid = value != "Yes"
} else if (key.startsWith("Language")) {
info.language = value.lang()
} else if (key.startsWith("File Size")) {
info.size = value.parseSize()
} else if (key.startsWith("Length")) {
info.pages = value.substringBefore(' ').integer() ?: 0
} else if (key.startsWith("Favorited")) {
info.favourited = when (value) {
"Never" -> 0
"Once" -> 1
else -> {
value.substringBefore(' ').integer() ?: 0
}
}
}
}
}
info.rating = document.elementById("rating_label")?.unescape()?.takeIf { it != "Not Yet Rated" }?.substringAfter(' ')?.float() ?: 0.0f
info.rated = document.elementById("rating_count")?.integer() ?: 0
info.favouriteSlot = document.elementById("fav")?.firstChild()?.attr("style")?.parseFavouriteSlotStyle() ?: FAV_CAT_UNKNOWN
document.elementById("taglist")?.elementByTag("tbody")?.children()?.forEach { element ->
element.children().takeIf { it.size >= 2 }?.also { children ->
children[0].unescape()?.trim(':')?.takeIf { it.isNotEmpty() }?.also { namespace ->
children[1].children().forEach { div ->
div.unescape()?.substringBefore("|")?.strip()?.takeIf { it.isNotEmpty() }?.also { info.tags.add(namespace, it) }
}
}
}
}
document.elementById("gnd")?.elementByTag("a")?.attr("href")?.parseGalleryDetailUrl()?.also { (gid, token) ->
info.childGid = gid
info.childToken = token
}
return info
}
private fun String.parseSize(): Long {
val index = indexOf(' ')
if (index < 0 || index >= length - 1) return 0
val num = substring(0, index).float() ?: return 0
return when (this[index + 1].toLowerCase()) {
'k' -> (num * 1024L).toLong()
'm' -> (num * 1024L * 1024L).toLong()
'g' -> (num * 1024L * 1024L * 1024L).toLong()
else -> num.toLong()
}
}
fun parseComments(document: Document): List<Comment> {
val comments = mutableListOf<Comment>()
document.elementById("cdiv")?.children()?.forEach { element ->
if (element.className() == "c1") {
val comment = parseComment(element)
if (comment != null) {
comments.add(comment)
}
}
}
return comments
}
private fun parseComment(element: Element): Comment? {
val id = element.previousElementSibling()?.attr("name")?.takeIf { it.length > 1 }?.substring(1)?.toLongOrNull() ?: return null
val comment = Comment()
comment.id = id
comment.comment = element.elementByClass("c6")?.html()
element.elementByClass("c3")?.let { c3 ->
comment.date = c3.ownText().unescape()?.substringAfter("Posted on")?.substringBefore("by:")?.strip()?.commentDate() ?: 0
comment.user = c3.firstChild()?.unescape()
}
comment.score = element.elementByClass("c5")?.firstChild()?.integer() ?: 0
element.elementByClass("c4")?.children()?.let { children ->
if (children.size == 2) {
comment.votedUp = children[0].attr("style").strip().isNotEmpty()
comment.votedDown = children[1].attr("style").strip().isNotEmpty()
}
}
comment.voteState = element.elementByClass("c7")?.unescape()
return comment
}
fun parseGalleryDetail(body: String): Pair<GalleryInfo, List<Comment>> {
val document = Jsoup.parse(body)
val info = parseGalleryDetail(document) ?: throw ParseException("Can't parse gallery detail")
val comments = parseComments(document)
return Pair(info, comments)
}
@@ -0,0 +1,219 @@
/*
* Copyright 2017 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.client.parser
import com.hippo.ehviewer.client.CATEGORY_UNKNOWN
import com.hippo.ehviewer.client.FAV_CAT_UNKNOWN
import com.hippo.ehviewer.client.categoryValue
import com.hippo.ehviewer.client.data.GalleryInfo
import com.hippo.ehviewer.client.guessLang
import com.hippo.ehviewer.client.parser.url.parseCoverUrl
import com.hippo.ehviewer.client.parser.url.parseGalleryDetailUrl
import com.hippo.ehviewer.exception.ParseException
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.util.regex.Pattern
/*
* Created by Hippo on 2017/7/25.
*/
private val EMPTY_KEYWORD = "No hits found</p>"
private val PATTERN_COVER_SIZE = Pattern.compile("height:(\\d+)px; width:(\\d+)px")
private val PATTERN_PX = Pattern.compile("(\\d+)px")
/**
* Parses gallery list.
*/
fun <T> parseGalleryList(document: Document, creator: (GalleryInfo, Element) -> T): List<T>? {
val tbody = document.elementByClass("itg")?.firstChild()
if (tbody != null) {
val list = mutableListOf<T>()
var isHeader = true
for (element in tbody.children()) {
// First one is table header, skip it
if (isHeader) {
isHeader = false
continue
}
val t = parseItem(element, creator)
if (t != null) {
list.add(t)
}
}
// Only returns the list if it's not empty
if (!list.isEmpty()) {
return list
}
}
return null
}
private fun <T> parseItem(element: Element, creator: (GalleryInfo, Element) -> T): T? {
val it5 = element.elementByClass("it5")?.firstChild()
val title = it5?.unescape() ?: return null
val (gid, token) = it5.attr("href")?.parseGalleryDetailUrl() ?: return null
val info = GalleryInfo()
info.gid = gid
info.token = token
info.title = title
info.language = guessLang(title)
info.category = element.elementByClass("ic")?.attr("alt")?.categoryValue() ?: CATEGORY_UNKNOWN
info.date = element.elementByClass("itd")?.date() ?: 0
val it2 = element.elementByClass("it2")
if (it2 != null) {
PATTERN_COVER_SIZE.matcher(it2.attr("style")).takeIf { it.find() }?.also { matcher ->
val width = matcher.group(2).integer() ?: 0
val height = matcher.group(1).integer() ?: 0
if (width >= 0 && height >= 0) {
info.coverRatio = width.toFloat() / height.toFloat()
}
}
val cover = it2.firstChild()
if (cover != null) {
info.coverUrl = cover.attr("src").unescape()
} else {
info.coverUrl = it2.text().parseCoverText()
}
if (info.coverUrl != null) {
info.coverFingerprint = info.coverUrl?.parseCoverUrl()
}
}
val it3 = element.elementByClass("it3")
if (it3 != null) {
val favId = "favicon_" + info.gid
for (child in it3.children()) {
if (favId == child.id()) {
info.favouriteSlot = child.attr("style").parseFavouriteSlotStyle()
}
if (child.firstChild()?.attr("alt") == "E") {
info.invalid = true
}
}
}
info.rating = element.elementByClass("it4r")?.attr("style")?.parseRatingStyle() ?: 0.0f
info.uploader = element.elementByClass("itu")?.unescape()
return creator(info, element)
}
// Parses url from a string like:
// inits~exhentai.org~t/53/a8/53a82a8deec79d3824ab413b4cf784d6df8589b2-1264635-1050-1540-png_l.jpg~(C91) [ガンバリマシン (Shino)] Pさん、今日も頑張ってくれませんか? (アイドルマスター シンデレラガールズ)
private fun String.parseCoverText(): String? {
val index1 = indexOf('~')
if (index1 == -1) return null
val index2 = indexOf('~', index1 + 1)
if (index2 == -1) return null
val index3 = indexOf('~', index2 + 1)
if (index3 == -1) return null
return "https://" + substring(index1 + 1, index2) + "/" + substring(index2 + 1, index3)
}
/**
* Parse the style string to get favourite slot.
*
* Ehentai website uses a picture to show favourite slot.
* Looks like:
* ```
* ◇
* ◇
* ◇
* ◇
* ◇
* ◇
* ◇
* ◇
* ◇
* ◇
* ```
* The style looks like:
* `background-position:0px -2px`.
* The first one is x offset, always 0.
* The second one is y offset, starts from -2, step -19.
*/
fun String.parseFavouriteSlotStyle(): Int {
val m = PATTERN_PX.matcher(this)
// Move to the second one
if (!m.find() || !m.find()) return FAV_CAT_UNKNOWN
val num = m.group(1).integer() ?: FAV_CAT_UNKNOWN
val slot = (num - 2) / 19
if (slot in 0..9) {
return slot
} else {
return FAV_CAT_UNKNOWN
}
}
/**
* ehentai website uses a picture to show rating.
* Looks like:
* ```
* ⛤ ⛤ ⛤ ⛤ ⛤
* ⛤ ⛤ ⛤ ⛤ half⛤
* ```
* The style looks like:
* ```
* background-position:-16px -1px
* ```
* The first one is x offset, 16px for a star.
* The second one is y offset, row1 is -1px, row2 is -21px
*/
fun String.parseRatingStyle(): Float {
val matcher = PATTERN_PX.matcher(this)
val num1 = matcher.takeIf { matcher.find() }?.group(1)?.integer() ?: return 0.0f
val num2 = matcher.takeIf { matcher.find() }?.group(1)?.integer() ?: return 0.0f
var rate = 5.0f - num1 / 16
if (num2 == 21) {
rate -= 0.5f
}
return rate
}
/**
* Parses GalleryInfo list.
*/
fun parseGalleryList(document: Document): List<GalleryInfo>? =
parseGalleryList(document, { info, _ -> info })
/**
* Parses gallery list pages.
*/
fun parseGalleryListPages(document: Document): Int? =
document.elementByClass("ptt")?.firstChild()?.firstChild()?.lastChild(1)?.integer() ?:
if (document.elementById("toppane")?.nextElementSibling()?.firstChild()?.text() == "No hits found") 0
else null
fun parseGalleryList(body: String): Pair<List<GalleryInfo>, Int> {
val document = Jsoup.parse(body)
val pages = parseGalleryListPages(document) ?: throw ParseException("Can't parse gallery list body")
val infos = parseGalleryList(document) ?: throw ParseException("Can't parse gallery list")
return Pair(infos, pages)
}
@@ -0,0 +1,28 @@
/*
* Copyright 2017 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.client.parser
import com.hippo.ehviewer.client.data.Comment
import com.hippo.ehviewer.client.data.GalleryInfo
/*
* Created by Hippo on 2017/7/31.
*/
fun parseLofiGalleryDetail(body: String): Pair<GalleryInfo, List<Comment>> {
TODO()
}
@@ -0,0 +1,28 @@
/*
* Copyright 2017 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.client.parser
import com.hippo.ehviewer.client.data.GalleryInfo
/*
* Created by Hippo on 2017/7/25.
*/
fun parseLofiGalleryList(body: String): Pair<List<GalleryInfo>, Int> {
TODO()
}
@@ -0,0 +1,70 @@
/*
* Copyright 2017 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.
*/
@file:Suppress("NOTHING_TO_INLINE")
package com.hippo.ehviewer.client.parser
import com.hippo.ehviewer.util.replaceEach
import com.hippo.ehviewer.util.strip
import org.jsoup.nodes.Element
import java.text.DateFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone
/*
* Created by Hippo on 2017/7/26.
*/
private val DATE_FORMAT: DateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH).apply { timeZone = TimeZone.getTimeZone("UTC") }
private val COMMENT_DATE_FORMAT: DateFormat = SimpleDateFormat("dd MMMMM yyyy, HH:mm z", Locale.ENGLISH)
fun String.integer(): Int? = dropWhile { it == ',' || Character.isSpaceChar(it) || Character.isWhitespace(it) }.toIntOrNull()
fun String.float(): Float? = dropWhile { it == ',' || Character.isSpaceChar(it) || Character.isWhitespace(it) }.toFloat()
fun String.unescape(): String? = replaceEach(
arrayOf("&amp;", "&lt;", "&gt;", "&quot;", "&#039;", "&times;", "&nbsp;"),
arrayOf("&", "<", ">", "\"", "'", "×", "\u00a0")).strip().let { if (it.isEmpty()) null else it }
fun String.date(): Long = try { DATE_FORMAT.parse(this).time } catch (e: ParseException) { 0 }
fun String.commentDate(): Long = try { COMMENT_DATE_FORMAT.parse(this).time } catch (e: ParseException) { 0 }
inline fun Element.elementById(id: String): Element? = getElementById(id)
inline fun Element.elementByClass(className: String): Element? = getElementsByClass(className).first()
inline fun Element.elementByTag(tagName: String): Element? = getElementsByTag(tagName).first()
inline fun Element.firstChild(): Element? = children().first()
inline fun Element.firstChild(index: Int): Element? = children().let { if (it.size > index) it[index] else null }
inline fun Element.lastChild(): Element? = children().last()
inline fun Element.lastChild(index: Int): Element? = children().let { if (it.size > index) it[it.size - index - 1] else null }
inline fun Element.integer(): Int? = text().integer()
inline fun Element.float(): Float? = text().float()
inline fun Element.unescape(): String? = text().unescape()
inline fun Element.date(): Long = text().date()
@@ -0,0 +1,41 @@
/*
* Copyright 2017 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.client.parser.url
import okhttp3.HttpUrl
/*
* Created by Hippo on 2017/7/31.
*/
/**
* Parses a archive url to gid, token and archive key.
*
* The url looks like:
* ```
* https://exhentai.org/archiver.php?gid=1063451&token=6cc24065cb&or=415253--00cbf86c557d53304ba6d23b7faf64f9928156ca
* ```
*
* Returns `null` if invalid.
*/
fun String.parseArchiveUrl(): Triple<Long, String, String>? {
val url = HttpUrl.parse(this) ?: return null
val gid = url.queryParameter("gid")?.toLongOrNull() ?: return null
val token = url.queryParameter("token") ?: return null
val archiveKey = url.queryParameter("or") ?: return null
return Triple(gid, token, archiveKey)
}
@@ -0,0 +1,54 @@
/*
* Copyright 2017 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.client.parser.url
import java.util.regex.Pattern
/*
* Created by Hippo on 2017/7/27.
*/
// A thumbnail url looks like:
// https://exhentai.org/t/e8/50/e850fc3d8fb7bfea934f66206fb8db8a86f57251-28396-1074-1538-jpg_l.jpg
private val PATTERN_THUMBNAIL = Pattern.compile("/([0-9a-f]{2})/([0-9a-f]{2})/([0-9a-f]{40}-\\d+-\\d+-\\d+-[0-9a-z]+)_([0-9a-zA-Z]+)\\.[0-9a-zA-Z]+")
/**
* Parses a cover url to fingerprint.
*
* Url:
* ```
* https://exhentai.org/t/e8/50/e850fc3d8fb7bfea934f66206fb8db8a86f57251-28396-1074-1538-jpg_l.jpg
* ```
* Fingerprint:
* ```
* e850fc3d8fb7bfea934f66206fb8db8a86f57251-28396-1074-1538-jpg
* ```
*
* Returns `null` if invalid.
*/
fun String.parseCoverUrl(): String? {
val m = PATTERN_THUMBNAIL.matcher(this)
if (m.find()) {
val g1 = m.group(1)
val g2 = m.group(2)
val g3 = m.group(3)
if (g1 == g3.substring(0, 2) && g2 == g3.substring(2, 4)) {
return g3
}
}
return null
}
@@ -0,0 +1,47 @@
/*
* Copyright 2017 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.client.parser.url
import java.util.regex.Pattern
/*
* Created by Hippo on 2017/7/26.
*/
private val URL_PATTERN = Pattern.compile("/g/(\\d+)/([0-9a-f]{10})")
/**
* Parses a gallery detail url to gid and token.
*
* The url looks like:
* ```
* https://exhentai.org/g/1060346/03702a68a5/
* ```
*
* Returns `null` if invalid.
*/
fun String.parseGalleryDetailUrl(): Pair<Long, String>? {
val matcher = URL_PATTERN.matcher(this)
if (matcher.find()) {
val gid = matcher.group(1).toLongOrNull()
val token = matcher.group(2)
if (gid != null) {
return Pair(gid, token)
}
}
return null
}
@@ -0,0 +1,123 @@
/*
* Copyright 2017 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.database
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import kotlin.reflect.KClass
/*
* Created by Hippo on 6/17/2017.
*/
class MSQLiteBuilder {
companion object {
const val COLUMN_ID = "_id"
val JAVA_TYPE_TO_SQLITE_TYPE = mapOf(
Boolean::class to "INTEGER NOT NULL DEFAULT 0",
Byte::class to "INTEGER NOT NULL DEFAULT 0",
Short::class to "INTEGER NOT NULL DEFAULT 0",
Int::class to "INTEGER NOT NULL DEFAULT 0",
Long::class to "INTEGER NOT NULL DEFAULT 0",
Float::class to "REAL NOT NULL DEFAULT 0",
Double::class to "REAL NOT NULL DEFAULT 0",
String::class to "TEXT"
)
internal fun javaTypeToSQLiteType(clazz: KClass<*>) = JAVA_TYPE_TO_SQLITE_TYPE[clazz] ?: error("Unknown type: $clazz")
}
private var version: Int = 0
private var commands: MutableList<Command>? = null
private val commandsMap = mutableMapOf<Int, List<Command>>()
/**
* Bump database version.
*/
fun version(version: Int): MSQLiteBuilder {
check(this.version < version, { "New version must be bigger than current version. " +
"current version: ${this.version}, new version: $version." })
this.version = version
this.commands = mutableListOf<Command>().also { commandsMap.put(version, it) }
return this
}
/**
* Creates a table.
*/
fun createTable(table: String, column: String = COLUMN_ID, clazz: KClass<*> = Int::class) =
command("CREATE TABLE $table ($column ${javaTypeToSQLiteType(clazz)} PRIMARY KEY);")
/**
* Drops a table.
*/
fun dropTable(table: String) = command("DROP TABLE $table;")
/**
* Inserts a column to the table.
*/
fun insertColumn(table: String, column: String, clazz: KClass<*>) =
command("ALTER TABLE $table ADD COLUMN $column ${javaTypeToSQLiteType(clazz)};")
private fun checkState(): MutableList<Command> {
check(version != 0, { "Call version() first!" })
return commands ?: error("Call version() first!")
}
/**
* Add a statement command.
*/
fun command(command: String) = command(StatementCommand(command))
/**
* Add a command.
*/
fun command(command: Command): MSQLiteBuilder = this.also { checkState().add(command) }
/**
* Build a SQLiteOpenHelper from it.
*/
fun build(context: Context, name: String, version: Int): SQLiteOpenHelper =
MSQLiteOpenHelper(context, name, version, this)
internal fun getCommands(oldVersion: Int, newVersion: Int): List<Command> {
val result = mutableListOf<Command>()
for (i in oldVersion + 1..newVersion) {
commandsMap[i]?.let { result.addAll(it) }
}
return result
}
/**
* One of commands to create or update `SQLiteDatabase`.
*/
abstract class Command {
abstract fun run(db: SQLiteDatabase)
}
/**
* A [Command] to execute a statement.
*/
class StatementCommand(private val statement: String) : Command() {
override fun run(db: SQLiteDatabase) {
db.execSQL(statement)
}
}
}
@@ -0,0 +1,56 @@
/*
* Copyright 2017 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.database
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
/*
* Created by Hippo on 6/17/2017.
*/
internal class MSQLiteOpenHelper(
context: Context,
name: String,
val version: Int,
val sqlBuilder: MSQLiteBuilder
) : SQLiteOpenHelper(context, name, null, version) {
override fun onCreate(db: SQLiteDatabase) { onUpgrade(db, 0, version) }
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) =
sqlBuilder.getCommands(oldVersion, newVersion).forEach { it.run(db) }
override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
dropAllTables(db)
onCreate(db)
}
private fun dropAllTables(db: SQLiteDatabase) {
val tables = mutableListOf<String>()
db.rawQuery("SELECT name FROM sqlite_master WHERE type='table';", null).use {
while (it.moveToNext()) {
val table = it.getString(0)
if ("android_metadata" != table && "sqlite_sequence" != table && table.isNotEmpty()) {
tables.add(table)
}
}
}
tables.forEach { db.execSQL("DROP TABLE IF EXISTS $it;") }
}
}
@@ -0,0 +1,188 @@
/*
* Copyright 2017 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.drawable
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PixelFormat
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
import android.support.v4.view.animation.PathInterpolatorCompat
import android.view.animation.Interpolator
import android.view.animation.LinearInterpolator
import com.hippo.ehviewer.util.Animate
import com.hippo.ehviewer.util.MAX_LEVEL
import com.hippo.ehviewer.util.centerTo
import com.hippo.ehviewer.util.forEachAny
import com.hippo.ehviewer.util.lerp
/*
* Created by Hippo on 6/6/2017.
*/
class ProgressDrawable : Drawable(), Animatable {
companion object {
private val TRIM_START_INTERPOLATOR: Interpolator
private val TRIM_END_INTERPOLATOR: Interpolator
private val LINEAR_INTERPOLATOR = LinearInterpolator()
init {
val trimStartPath = Path()
trimStartPath.moveTo(0.0f, 0.0f)
trimStartPath.lineTo(0.5f, 0.0f)
trimStartPath.cubicTo(0.7f, 0.0f, 0.6f, 1f, 1f, 1f)
TRIM_START_INTERPOLATOR = PathInterpolatorCompat.create(trimStartPath)
val trimEndPath = Path()
trimEndPath.moveTo(0.0f, 0.0f)
trimEndPath.cubicTo(0.2f, 0.0f, 0.1f, 1f, 0.5f, 1f)
trimEndPath.lineTo(1f, 1f)
TRIM_END_INTERPOLATOR = PathInterpolatorCompat.create(trimEndPath)
}
}
private val animates: List<Animate>
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val rect = RectF()
private var trimStart = 0.0f
private var trimEnd = 0.0f
private var trimOffset = 0.0f
private var trimRotation = 0.0f
var indeterminate: Boolean = false
set(value) {
if (field != value) {
field = value
if (value) {
animates.forEach { it.start() }
} else {
animates.forEach { it.cancel() }
}
invalidateSelf()
}
}
var color: Int
get() = paint.color
set(value) {
paint.color = value
invalidateSelf()
}
var size: Int = -1
set(value) {
if (field != value) {
field = value
invalidateSelf()
}
}
init {
paint.strokeCap = Paint.Cap.SQUARE
paint.strokeJoin = Paint.Join.MITER
paint.style = Paint.Style.STROKE
val trimStart = ProgressAnimate(0.0f, 0.75f, 1333L, TRIM_START_INTERPOLATOR, { trimStart = it })
val trimEnd = ProgressAnimate(0.0f, 0.75f, 1333L, TRIM_END_INTERPOLATOR, { trimEnd = it })
val trimOffset = ProgressAnimate(0.0f, 0.25f, 1333L, LINEAR_INTERPOLATOR, { trimOffset = it })
val trimRotation = ProgressAnimate(0.0f, 720.0f, 6665L, LINEAR_INTERPOLATOR, { trimRotation = it })
animates = listOf(trimStart, trimEnd, trimOffset, trimRotation)
}
override fun start() {
indeterminate = true
}
override fun stop() {
indeterminate = false
}
override fun isRunning(): Boolean = indeterminate
override fun onLevelChange(level: Int): Boolean {
indeterminate = false
trimStart = 0f
trimEnd = level.toFloat() / MAX_LEVEL.toFloat()
trimOffset = 0f
trimRotation = 0f
invalidateSelf()
return true
}
override fun onBoundsChange(bounds: Rect) {
if (bounds.isEmpty) { rect.setEmpty(); return }
val size = this.size.let { if (it < 0) Math.min(bounds.width(), bounds.height()).toFloat() else it.toFloat() }
val stroke = size / 12.0f
paint.strokeWidth = stroke
rect.set(0.0f, 0.0f, size, size)
rect.centerTo(bounds.centerX().toFloat(), bounds.centerY().toFloat())
val halfStroke = stroke * 0.5f
rect.inset(halfStroke, halfStroke)
}
override fun draw(canvas: Canvas) {
if (rect.isEmpty) return
val now = System.currentTimeMillis()
val invalidate = animates.forEachAny { it.calculate(now) }
val saved = canvas.save()
canvas.rotate(trimRotation, rect.centerX(), rect.centerY())
val startAngle = (trimStart + trimOffset) * 360.0f - 90.0f
val sweepAngle = (trimEnd - trimStart) * 360.0f
canvas.drawArc(rect, startAngle, sweepAngle, false, paint)
canvas.restoreToCount(saved)
if (invalidate) invalidateSelf()
}
override fun getIntrinsicWidth() = size
override fun getIntrinsicHeight() = size
override fun setAlpha(alpha: Int) { paint.alpha = alpha }
override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
override fun setColorFilter(colorFilter: ColorFilter?) { paint.colorFilter = colorFilter }
private class ProgressAnimate(
val from: Float,
val to: Float,
duration: Long,
interpolator: Interpolator,
val block: (Float) -> Unit
) : Animate() {
init {
this.duration = duration
this.interpolator = interpolator
this.repeat = INFINITE
}
override fun onCalculate(progress: Float) { block(progress.lerp(from, to)) }
}
}
@@ -0,0 +1,62 @@
/*
* Copyright 2017 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.drawable
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.RectF
import android.graphics.drawable.Drawable
/*
* Created by Hippo on 2017/8/9.
*/
class RoundRectDrawable(
val radius: Float = 0.0f,
val color: Int = Color.BLACK,
val edgeWidth: Float = 0.0f,
val edgeColor: Int = Color.BLACK
) : Drawable() {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG).also {
it.color = color
it.style = Paint.Style.FILL
}
private val edgePaint = if (edgeWidth <= 0.0f) null else Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG).also {
it.color = edgeColor
it.style = Paint.Style.FILL
}
override fun draw(canvas: Canvas) {
if (edgePaint != null) {
canvas.drawRoundRect(RectF(bounds), radius, radius, edgePaint)
canvas.drawRoundRect(RectF(bounds).apply { inset(edgeWidth, edgeWidth) }, radius, radius, paint)
} else {
canvas.drawRoundRect(RectF(bounds), radius, radius, paint)
}
}
override fun setAlpha(alpha: Int) {}
override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
override fun setColorFilter(colorFilter: ColorFilter?) {}
}
@@ -0,0 +1,111 @@
/*
* Copyright 2017 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.drawable
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.text.TextUtils
/*
* Created by Hippo on 6/10/2017.
*/
class TextDrawable(
private val text: String,
private val contentPercent: Float
) : Drawable() {
companion object {
private const val STANDARD_TEXT_SIZE = 1000.0f
private val STANDARD_PAINT: Paint = Paint().apply { textSize = STANDARD_TEXT_SIZE }
}
private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private var x: Float = 0.0f
private var y: Float = 0.0f
private var textSizeDirty = true
private val textBounds = Rect().apply { STANDARD_PAINT.getTextBounds(text, 0, text.length, this) }
var textColor: Int = 0
set(value) {
if (field != value) {
field = value
invalidateSelf()
}
}
var backgroundColor: Int = 0
set(value) {
if (field != value) {
field = value
invalidateSelf()
}
}
override fun setColorFilter(colorFilter: ColorFilter?) {
backgroundPaint.colorFilter = colorFilter
textPaint.colorFilter = colorFilter
invalidateSelf()
}
override fun getOpacity(): Int {
return PixelFormat.TRANSLUCENT
}
override fun setAlpha(alpha: Int) {}
override fun onBoundsChange(bounds: Rect) {
super.onBoundsChange(bounds)
textSizeDirty = true
}
private fun updateTextSizeIfDirty() {
if (!textSizeDirty) return
textSizeDirty = false
val contentWidth = (bounds.width() * contentPercent).toInt()
val contentHeight = (bounds.height() * contentPercent).toInt()
val widthRatio = contentWidth.toFloat() / textBounds.width()
val heightRatio = contentHeight.toFloat() / textBounds.height()
val ratio = Math.min(widthRatio, heightRatio)
val textSize = STANDARD_TEXT_SIZE * ratio
textPaint.textSize = textSize
x = (bounds.width() - textBounds.width() * ratio) / 2 - textBounds.left * ratio
y = (bounds.height() - textBounds.height() * ratio) / 2 - textBounds.top * ratio
}
override fun draw(canvas: Canvas) {
if (!bounds.isEmpty) {
// Draw background
backgroundPaint.color = backgroundColor
canvas.drawRect(bounds, backgroundPaint)
if (!TextUtils.isEmpty(text)) {
// Draw text
updateTextSizeIfDirty()
textPaint.color = textColor
canvas.drawText(text, x, y, textPaint)
}
}
}
}
@@ -0,0 +1,29 @@
/*
* Copyright 2017 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.exception
/*
* Created by Hippo on 6/21/2017.
*/
/**
* Exception with a special message.
*/
open class GeneralException(message: String): Exception(message) {
override val message: String
get() = super.message!!
}
@@ -0,0 +1,25 @@
/*
* Copyright 2017 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.exception
/*
* Created by Hippo on 2017/7/26.
*/
class ParseException(message: String): GeneralException(message) {
var body: String? = null
}
@@ -0,0 +1,26 @@
/*
* Copyright 2017 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.exception
/*
* Created by Hippo on 6/7/2017.
*/
/**
* Exception with a message, a localized message and a icon.
*/
class PresetException(message: String, val text: Int, val icon: Int) : Exception(message)
@@ -0,0 +1,23 @@
/*
* Copyright 2017 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.exception
/*
* Created by Hippo on 2017/7/26.
*/
class ResponseCodeException(val code: Int) : Exception()
@@ -0,0 +1,23 @@
/*
* Copyright 2017 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.exception
/*
* Created by Hippo on 2017/7/25.
*/
class SadPandaException : Exception("SAD PANDA")
@@ -0,0 +1,61 @@
/*
* Copyright 2017 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.mvp
import com.hippo.ehviewer.REF_WATCHER
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit
/*
* Created by Hippo on 6/19/2017.
*/
abstract class EhvPaper<This : Any>(
logic: MvpLogic<This>
) : MvpPaper<This>(logic) {
private val worker = AndroidSchedulers.mainThread().createWorker()
override fun onDestroy() {
super.onDestroy()
worker.dispose()
REF_WATCHER.watch(view, "EhvPaper.onDestroy()")
REF_WATCHER.watch(this, "EhvPaper.onDestroy()")
}
/**
* Schedules an action for execution in UI thread.
* The action will be cancelled after the paper destroyed.
* Returns `Disposables.disposed()` if the paper is already destroyed.
*/
fun schedule(action: () -> Unit): Disposable {
return worker.schedule(action)
}
/**
* Schedules an action for execution at some point in the future
* and in UI thread.
* The action will be cancelled after the paper destroyed.
* Returns `Disposables.disposed()` if the paper is already destroyed.
*/
fun schedule(action: () -> Unit, delayMillis: Long): Disposable {
return worker.schedule(action, delayMillis, TimeUnit.MILLISECONDS)
}
}
@@ -0,0 +1,112 @@
/*
* Copyright 2017 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.mvp
import com.hippo.ehviewer.REF_WATCHER
import com.hippo.ehviewer.util.MutableAny
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit
/*
* Created by Hippo on 6/19/2017.
*/
abstract class EhvPen<P : Any> : MvpPen<P>() {
private val worker = AndroidSchedulers.mainThread().createWorker()
private val disposableSet = CompositeDisposable()
override fun onDestroy() {
super.onDestroy()
worker.dispose()
disposableSet.dispose()
REF_WATCHER.watch(this, "EhvPen.onDestroy()")
}
/**
* Schedules an action for execution in UI thread.
* The action will be cancelled after the pen destroyed.
* Returns `Disposables.disposed()` if the pen is already destroyed.
*/
fun schedule(action: () -> Unit): Disposable {
return worker.schedule(action)
}
/**
* Schedules an action for execution at some point in the future
* and in UI thread.
* The action will be cancelled after the pen destroyed.
* Returns `Disposables.disposed()` if the view is already destroyed.
*/
fun schedule(action: () -> Unit, delayMillis: Long): Disposable {
return worker.schedule(action, delayMillis, TimeUnit.MILLISECONDS)
}
/**
* Register the `Single` to the pen.
* The disposable will be disposed after the pen destroyed.
*/
fun <T> Single<T>.register(
onSuccess: (T) -> Unit,
onError: (Throwable) -> Unit
) {
val mutable = MutableAny<Disposable>(null)
val disposable = subscribe({
onSuccess(it)
mutable.value?.let { disposableSet.delete(it) }
}, {
onError(it)
mutable.value?.let { disposableSet.delete(it) }
})
mutable.value = disposable
disposableSet.add(disposable)
}
/**
* Register the `Observable` to the pen.
* The disposable will be disposed after the pen destroyed.
*/
fun <T> Observable<T>.register(
onNext: (T) -> Unit,
onError: (Throwable) -> Unit
) {
val mutable = MutableAny<Disposable>(null)
val disposable = subscribe({
onNext(it)
}, {
onError(it)
mutable.value?.let { disposableSet.delete(it) }
}, {
mutable.value?.let { disposableSet.delete(it) }
})
mutable.value = disposable
disposableSet.add(disposable)
}
/**
* Register the `Observable` to the pen.
* The disposable will be disposed after the pen destroyed.
* Error will be ignore.
*/
fun <T> Observable<T>.register(onNext: (T) -> Unit) = register(onNext, { /* Ignore error */ })
}
@@ -0,0 +1,31 @@
/*
* Copyright 2017 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.mvp
import com.hippo.ehviewer.REF_WATCHER
/*
* Created by Hippo on 6/19/2017.
*/
abstract class EhvScene : MvpScene() {
override fun onDestroy() {
super.onDestroy()
REF_WATCHER.watch(this, "EhvScene.onDestroy()")
}
}
@@ -0,0 +1,96 @@
/*
* Copyright 2017 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.mvp
import android.os.Bundle
import android.view.ViewGroup
/*
* Created by Hippo on 6/19/2017.
*/
abstract class GroupPaper<This : Any>(
logic: MvpLogic<This>
) : EhvPaper<This>(logic) {
private val children = mutableListOf<MvpPaper<*>>()
fun addChild(paper: MvpPaper<*>) {
children.add(paper)
}
/**
* Inflates and adds child.
*/
fun <T : MvpPaper<*>> inflateChild(
containerId: Int,
creator: (ViewGroup) -> T
): T {
val container = view.findViewById(containerId) as ViewGroup
val child = creator(container)
container.addView(child.view, 0)
children.add(child)
return child
}
// Don't call children's create() in onCreate(), let them call it by themselves
override fun onAttach() {
super.onAttach()
children.forEach { it.attach() }
}
override fun onStart() {
super.onStart()
children.forEach { it.start() }
}
override fun onResume() {
super.onResume()
children.forEach { it.resume() }
}
override fun onPause() {
super.onPause()
children.forEach { it.pause() }
}
override fun onStop() {
super.onStop()
children.forEach { it.stop() }
}
override fun onDetach() {
super.onDetach()
children.forEach { it.detach() }
}
override fun onDestroy() {
super.onDestroy()
children.forEach { it.destroy() }
}
override fun onSaveState(outState: Bundle) {
super.onSaveState(outState)
children.forEach { it.saveState(outState) }
}
override fun onRestoreState(savedState: Bundle) {
super.onRestoreState(savedState)
children.forEach { it.restoreState(savedState) }
}
}
@@ -0,0 +1,40 @@
/*
* Copyright 2017 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.mvp
/*
* Created by Hippo on 6/20/2017.
*/
abstract class GroupPen<P : Any> : EhvPen<P>() {
private val children = mutableListOf<MvpPen<*>>()
fun addChild(pen: MvpPen<*>) {
children.add(pen)
}
override fun onCreate() {
super.onCreate()
children.forEach { it.create() }
}
override fun onDestroy() {
super.onDestroy()
children.forEach { it.destroy() }
}
}
@@ -0,0 +1,39 @@
/*
* Copyright 2017 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.mvp
/*
* Created by Hippo on 2017/7/14.
*/
interface MvpLogic<in Ui : Any> {
/**
* Attaches a ui to the logic.
*/
fun attach(ui: Ui)
/**
* Detaches the ui of the logic.
*/
fun detach()
/**
* Returns `true` if the ui is under restoring.
*/
fun isRestoring(): Boolean
}
@@ -0,0 +1,264 @@
/*
* Copyright 2017 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.mvp
import android.content.Context
import android.os.Bundle
import android.support.annotation.CallSuper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.disposables.Disposables
import io.reactivex.exceptions.Exceptions
/*
* Created by Hippo on 2017/7/13.
*/
abstract class MvpPaper<This : Any>(
private val logic: MvpLogic<This>
) : MvpUi {
companion object {
private const val INIT = 0
const val CREATE = 1
const val ATTACH = 2
const val START = 3
const val RESUME = 4
const val PAUSE = 5
const val STOP = 6
const val DETACH = 7
const val DESTROY = 8
}
lateinit var inflater: LayoutInflater
private set
lateinit var context: Context
private set
lateinit var view: View
protected set
private var step = INIT
private var lifecycleHandler: LifecycleHandler? = null
val lifecycle by lazy {
val lifecycleHandler = LifecycleHandler(step)
this.lifecycleHandler = lifecycleHandler
lifecycleHandler.observable
}
/**
* Creates the paper.
*/
internal fun create(inflater: LayoutInflater, container: ViewGroup) {
this.inflater = inflater
this.context = inflater.context
onCreate(inflater, container)
step = CREATE
lifecycleHandler?.emit(step)
@Suppress("UNCHECKED_CAST")
logic.attach(this as This)
}
/**
* Attaches the paper.
*/
internal fun attach() {
onAttach()
step = ATTACH
lifecycleHandler?.emit(step)
}
/**
* Starts the paper.
*/
internal fun start() {
onStart()
step = START
lifecycleHandler?.emit(step)
}
/**
* Resumes the paper.
*/
internal fun resume() {
onResume()
step = RESUME
lifecycleHandler?.emit(step)
}
/**
* Pauses the paper.
*/
internal fun pause() {
onPause()
step = PAUSE
lifecycleHandler?.emit(step)
}
/**
* Stops the paper.
*/
internal fun stop() {
onStop()
step = STOP
lifecycleHandler?.emit(step)
}
/**
* Detaches the paper.
*/
internal fun detach() {
onDetach()
step = DETACH
lifecycleHandler?.emit(step)
}
/**
* Destroys the paper.
*/
internal fun destroy() {
onDestroy()
step = DESTROY
lifecycleHandler?.emit(step)
logic.detach()
}
/**
* Save state of the paper.
*/
internal fun saveState(outState: Bundle) {
onSaveState(outState)
}
/**
* Restore state of the paper.
*/
internal fun restoreState(savedState: Bundle) {
onRestoreState(savedState)
}
/**
* Called when the paper created.
*/
@CallSuper
protected open fun onCreate(inflater: LayoutInflater, container: ViewGroup) {}
/**
* Called when the paper attached.
*/
@CallSuper
protected open fun onAttach() {}
/**
* Called when the paper started.
*/
@CallSuper
protected open fun onStart() {}
/**
* Called when the paper resumed.
*/
@CallSuper
protected open fun onResume() {}
/**
* Called when the paper paused.
*/
@CallSuper
protected open fun onPause() {}
/**
* Called when the paper stopped.
*/
@CallSuper
protected open fun onStop() {}
/**
* Called when the paper detached.
*/
@CallSuper
protected open fun onDetach() {}
/**
* Called when the paper destroyed.
*/
@CallSuper
protected open fun onDestroy() {}
/**
* Called when the paper state saved.
*/
@CallSuper
protected open fun onSaveState(outState: Bundle) {}
/**
* Called when the paper state restored.
*/
@CallSuper
protected open fun onRestoreState(savedState: Bundle) {}
private class LifecycleHandler(var step: Int) {
private val emitters = mutableListOf<ObservableEmitter<Int>>()
val observable : Observable<Int> by lazy {
Observable.create<Int> {
if (step != DESTROY) {
emitters.add(it)
it.setDisposable(Disposables.fromAction { emitters.remove(it) })
emitMissingStep(it)
} else {
it.setDisposable(Disposables.disposed())
}
}
}
private fun emitMissingStep(emitter: ObservableEmitter<Int>) {
if (step in CREATE until DESTROY) emit(emitter, CREATE)
if (step in ATTACH until DETACH) emit(emitter, ATTACH)
if (step in START until STOP) emit(emitter, START)
if (step in RESUME until PAUSE) emit(emitter, RESUME)
}
fun emit(step: Int) {
this.step = step
emitters.forEach { emit(it, step) }
if (step == DESTROY) {
emitters.clear()
}
}
private fun emit(emitter: ObservableEmitter<Int>, step: Int) {
if (!emitter.isDisposed) {
try {
emitter.onNext(step)
} catch (t: Throwable) {
Exceptions.throwIfFatal(t)
emitter.onError(t)
}
}
}
}
}
@@ -0,0 +1,78 @@
/*
* Copyright 2017 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.mvp
import android.support.annotation.CallSuper
import com.hippo.viewstate.ViewState
/*
* Created by Hippo on 2017/7/14.
*/
abstract class MvpPen<Ui : Any> : MvpLogic<Ui> {
lateinit var view: Ui
private set
private lateinit var state: ViewState<Ui>
override fun attach(ui: Ui) {
state.attach(ui)
}
/**
* Detaches the paper of the pen.
*/
override fun detach() {
state.detach()
}
override fun isRestoring(): Boolean = state.isRestoring
/**
* Creates view state for this pen.
*/
abstract fun createViewState(): ViewState<Ui>
/**
* Creates the pen.
*/
internal fun create() {
state = createViewState()
@Suppress("UNCHECKED_CAST")
view = state as Ui
onCreate()
}
/**
* Destroys the pen.
*/
internal fun destroy() {
onDestroy()
}
/**
* Called when the pen created.
*/
@CallSuper
protected open fun onCreate() {}
/**
* Called when the pen destroyed.
*/
@CallSuper
protected open fun onDestroy() {}
}
@@ -0,0 +1,112 @@
/*
* Copyright 2017 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.mvp
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hippo.stage.Scene
/*
* Created by Hippo on 2017/7/13.
*/
abstract class MvpScene : Scene() {
companion object {
private const val ERROR_PEN_NULL = "pen == null"
private const val ERROR_PAPER_NULL = "paper == null"
}
private var pen: MvpPen<*>? = null
private var paper: MvpPaper<*>? = null
/**
* Create a pen for this scene.
*/
protected abstract fun createPen(args: Bundle): MvpPen<*>
/**
* Create a paper for the scene.
*/
protected abstract fun createPaper(): MvpPaper<*>
override fun onCreate(args: Bundle) {
super.onCreate(args)
pen = createPen(args)
pen?.create() ?: error(ERROR_PEN_NULL)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
paper = createPaper()
paper?.create(inflater, container) ?: error(ERROR_PAPER_NULL)
return paper?.view ?: error(ERROR_PAPER_NULL)
}
override fun onAttachView(view: View) {
super.onAttachView(view)
paper?.attach() ?: error(ERROR_PAPER_NULL)
}
override fun onStart() {
super.onStart()
paper?.start() ?: error(ERROR_PAPER_NULL)
}
override fun onResume() {
super.onResume()
paper?.resume() ?: error(ERROR_PAPER_NULL)
}
override fun onPause() {
super.onPause()
paper?.pause() ?: error(ERROR_PAPER_NULL)
}
override fun onStop() {
super.onStop()
paper?.stop() ?: error(ERROR_PAPER_NULL)
}
override fun onDetachView(view: View) {
super.onDetachView(view)
paper?.detach() ?: error(ERROR_PAPER_NULL)
}
override fun onDestroyView(view: View) {
super.onDestroyView(view)
paper?.destroy() ?: error(ERROR_PAPER_NULL)
paper = null
}
override fun onDestroy() {
super.onDestroy()
pen?.destroy() ?: error(ERROR_PEN_NULL)
pen = null
}
override fun onSaveViewState(view: View, outViewState: Bundle) {
super.onSaveViewState(view, outViewState)
paper?.saveState(outViewState) ?: error(ERROR_PAPER_NULL)
}
override fun onRestoreViewState(view: View, savedViewState: Bundle) {
super.onRestoreViewState(view, savedViewState)
paper?.restoreState(savedViewState) ?: error(ERROR_PAPER_NULL)
}
}
@@ -0,0 +1,23 @@
/*
* Copyright 2017 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.mvp
/*
* Created by Hippo on 2017/7/14.
*/
interface MvpUi
@@ -0,0 +1,219 @@
/*
* Copyright 2017 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.network
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.util.Log
import com.hippo.ehviewer.database.MSQLiteBuilder
import com.hippo.ehviewer.util.getBoolean
import com.hippo.ehviewer.util.getLong
import com.hippo.ehviewer.util.getString
import com.hippo.ehviewer.util.rawQuery
import com.hippo.ehviewer.util.transaction
import okhttp3.Cookie
import java.util.concurrent.atomic.AtomicBoolean
/*
* Created by Hippo on 6/29/2017.
*/
internal class CookieDatabase(context: Context, name: String) {
companion object {
private val LOG_TAG = CookieDatabase::class.java.simpleName
private const val VERSION_1 = 1
private const val TABLE_COOKIE = "ok_http_cookie"
private const val COLUMN_ID = MSQLiteBuilder.COLUMN_ID
private const val COLUMN_NAME = "name"
private const val COLUMN_VALUE = "value"
private const val COLUMN_EXPIRES_AT = "expires_at"
private const val COLUMN_DOMAIN = "domain"
private const val COLUMN_PATH = "path"
private const val COLUMN_SECURE = "secure"
private const val COLUMN_HTTP_ONLY = "http_only"
private const val COLUMN_PERSISTENT = "persistent"
private const val COLUMN_HOST_ONLY = "host_only"
private const val DB_VERSION = VERSION_1
}
private val cookieIdMap = mutableMapOf<Cookie, Long>()
private val getAllCookiesCalled = AtomicBoolean()
private val helper = MSQLiteBuilder()
.version(VERSION_1)
.createTable(TABLE_COOKIE)
.insertColumn(TABLE_COOKIE, COLUMN_NAME, String::class)
.insertColumn(TABLE_COOKIE, COLUMN_VALUE, String::class)
.insertColumn(TABLE_COOKIE, COLUMN_EXPIRES_AT, Long::class)
.insertColumn(TABLE_COOKIE, COLUMN_DOMAIN, String::class)
.insertColumn(TABLE_COOKIE, COLUMN_PATH, String::class)
.insertColumn(TABLE_COOKIE, COLUMN_SECURE, Boolean::class)
.insertColumn(TABLE_COOKIE, COLUMN_HTTP_ONLY, Boolean::class)
.insertColumn(TABLE_COOKIE, COLUMN_PERSISTENT, Boolean::class)
.insertColumn(TABLE_COOKIE, COLUMN_HOST_ONLY, Boolean::class)
.build(context, name, DB_VERSION)
private val db = helper.writableDatabase
private fun Cursor.getCookie(currentTimeMillis: Long): Cookie? {
val name = getString(COLUMN_NAME, null) ?: return null
val value = getString(COLUMN_VALUE, null)
val expiresAt = getLong(COLUMN_EXPIRES_AT, 0)
val domain = getString(COLUMN_DOMAIN, null) ?: return null
val path = getString(COLUMN_PATH, null) ?: return null
val secure = getBoolean(COLUMN_SECURE, false)
val httpOnly = getBoolean(COLUMN_HTTP_ONLY, false)
val persistent = getBoolean(COLUMN_PERSISTENT, false)
val hostOnly = getBoolean(COLUMN_HOST_ONLY, false)
// Check non-persistent or expired
if (!persistent || expiresAt <= currentTimeMillis) {
return null
}
val builder = Cookie.Builder()
builder.name(name)
builder.value(value)
if (hostOnly) {
builder.hostOnlyDomain(domain)
} else {
builder.domain(domain)
}
builder.path(path)
builder.expiresAt(expiresAt)
if (secure) builder.secure()
if (httpOnly) builder.httpOnly()
return builder.build()
}
/**
* Return a domain-cookies map.
*/
fun getAllCookies(): MutableMap<String, CookieSet> {
if (!getAllCookiesCalled.compareAndSet(false, true)) {
throw IllegalStateException("Only call getAllCookies() once.")
}
val now = System.currentTimeMillis()
val map = mutableMapOf<String, CookieSet>()
val toRemove = mutableListOf<Long>()
db.rawQuery("SELECT * FROM $TABLE_COOKIE;", null) {
val id = it.getLong(COLUMN_ID, 0)
val cookie = it.getCookie(now)
if (cookie != null) {
// Save id of the cookie in db
cookieIdMap.put(cookie, id)
// Put cookie to set
var set: CookieSet? = map[cookie.domain()]
if (set == null) {
set = CookieSet()
map.put(cookie.domain(), set)
}
set.add(cookie)
} else {
// Mark to remove the cookie
toRemove.add(id)
}
}
// Remove invalid or expired cookie
if (!toRemove.isEmpty()) {
val statement = db.compileStatement(
"DELETE FROM $TABLE_COOKIE WHERE $COLUMN_ID = ?;")
db.transaction {
for (id in toRemove) {
statement.bindLong(1, id)
statement.executeUpdateDelete()
}
}
}
return map
}
private fun Cookie.toContentValues() = ContentValues(9)
.also {
it.put(COLUMN_NAME, name())
it.put(COLUMN_VALUE, value())
it.put(COLUMN_EXPIRES_AT, expiresAt())
it.put(COLUMN_DOMAIN, domain())
it.put(COLUMN_PATH, path())
it.put(COLUMN_SECURE, secure())
it.put(COLUMN_HTTP_ONLY, httpOnly())
it.put(COLUMN_PERSISTENT, persistent())
it.put(COLUMN_HOST_ONLY, hostOnly())
}
fun add(cookie: Cookie) {
val id = db.insert(TABLE_COOKIE, null, cookie.toContentValues())
if (id != -1L) {
val oldId = cookieIdMap.put(cookie, id)
if (oldId != null) Log.e(LOG_TAG, "Add a duplicate cookie")
} else {
Log.e(LOG_TAG, "An error occurred when insert a cookie")
}
}
fun update(from: Cookie, to: Cookie) {
val id = cookieIdMap[from]
if (id == null) {
Log.e(LOG_TAG, "Can't get id when update the cookie")
return
}
val values = to.toContentValues()
val whereClause = "$COLUMN_ID = ?"
val whereArgs = arrayOf(id.toString())
val count = db.update(TABLE_COOKIE, values, whereClause, whereArgs)
if (count != 1) Log.e(LOG_TAG, "Bad result when update cookie: $count")
// Update it in cookie-id map
cookieIdMap.remove(from)
cookieIdMap.put(to, id)
}
fun remove(cookie: Cookie) {
val id = cookieIdMap[cookie]
if (id == null) {
Log.e(LOG_TAG, "Can't get id when remove the cookie")
return
}
val whereClause = "$COLUMN_ID = ?"
val whereArgs = arrayOf(id.toString())
val count = db.delete(TABLE_COOKIE, whereClause, whereArgs)
if (count != 1) Log.e(LOG_TAG, "Bad result when remove cookie: $count")
// Remove it from cookie-id map
cookieIdMap.remove(cookie)
}
fun clear() {
db.delete(TABLE_COOKIE, null, null)
cookieIdMap.clear()
}
fun close() {
db.close()
helper.close()
}
}
@@ -0,0 +1,154 @@
/*
* Copyright 2017 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.network
import android.content.Context
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import java.util.Collections
import java.util.regex.Pattern
/*
* Created by Hippo on 6/29/2017.
*/
/** A persistent `CookieJar` which store cookies to database. */
class CookieRepository(context: Context) : CookieJar {
companion object {
private const val DB_NAME = "ehv_cookie_2"
}
private val db = CookieDatabase(context, DB_NAME)
internal val map = db.getAllCookies()
@Synchronized private fun addCookie(cookie: Cookie) {
// For cookie database
var toAdd: Cookie? = null
var toUpdate: Cookie? = null
var toRemove: Cookie? = null
var set: CookieSet? = map[cookie.domain()]
if (set == null) {
set = CookieSet()
map.put(cookie.domain(), set)
}
if (cookie.expiresAt() <= System.currentTimeMillis()) {
toRemove = set.remove(cookie)
// If the cookie is not persistent, it's not in database
if (toRemove != null && !toRemove.persistent()) {
toRemove = null
}
} else {
toAdd = cookie
toUpdate = set.add(cookie)
// If the cookie is not persistent, it's not in database
if (!toAdd.persistent()) toAdd = null
if (toUpdate != null && !toUpdate.persistent()) toUpdate = null
// Remove the cookie if it updates to null
if (toAdd == null && toUpdate != null) {
toRemove = toUpdate
toUpdate = null
}
}
if (toRemove != null) {
db.remove(toRemove)
}
if (toAdd != null) {
if (toUpdate != null) {
db.update(toUpdate, toAdd)
} else {
db.add(toAdd)
}
}
}
@Synchronized private fun getCookies(url: HttpUrl): List<Cookie> {
val accepted = mutableListOf<Cookie>()
val expired = mutableListOf<Cookie>()
for ((key, value) in map) {
if (domainMatch(url, key)) {
value.get(url, accepted, expired)
}
}
expired.forEach {
if (it.persistent()) {
db.remove(it)
}
}
// RFC 6265 Section-5.4 step 2, sort the cookie-list
// Cookies with longer paths are listed before cookies with shorter paths.
// Ignore creation-time, we don't store them.
Collections.sort(accepted) { o1, o2 -> o2.path().length - o1.path().length }
return accepted
}
@Synchronized fun clear() {
map.clear()
db.clear()
}
@Synchronized fun close() {
db.close()
}
// OkHttp checks public suffix
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) = cookies.forEach { addCookie(it) }
override fun loadForRequest(url: HttpUrl) = getCookies(url)
/**
* Quick and dirty pattern to differentiate IP addresses from hostnames. This is an approximation
* of Android's private InetAddress#isNumeric API.
*
* This matches IPv6 addresses as a hex string containing at least one colon, and possibly
* including dots after the first colon. It matches IPv4 addresses as strings containing only
* decimal digits and dots. This pattern matches strings like "a:.23" and "54" that are neither IP
* addresses nor hostnames; they will be verified as IP addresses (which is a more strict
* verification).
*/
private val VERIFY_AS_IP_ADDRESS = Pattern.compile("([0-9a-fA-F]*:[0-9a-fA-F:.]*)|([\\d.]+)")
/** Returns true if `host` is not a host name and might be an IP address. */
private fun verifyAsIpAddress(host: String): Boolean {
return VERIFY_AS_IP_ADDRESS.matcher(host).matches()
}
// okhttp3.Cookie.domainMatch(HttpUrl, String)
private fun domainMatch(url: HttpUrl, domain: String): Boolean {
val urlHost = url.host()
if (urlHost == domain) {
return true // As in 'example.com' matching 'example.com'.
}
if (urlHost.endsWith(domain)
&& urlHost[urlHost.length - domain.length - 1] == '.'
&& !verifyAsIpAddress(urlHost)) {
return true // As in 'example.com' matching 'www.example.com'.
}
return false
}
}
@@ -0,0 +1,65 @@
/*
* Copyright 2017 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.network
import com.hippo.ehviewer.util.forEachRemove
import okhttp3.Cookie
import okhttp3.HttpUrl
/*
* Created by Hippo on 2017/8/13.
*/
internal class CookieSet {
val map = mutableMapOf<Key, Cookie>()
/**
* Adds a cookie to this `CookieSet`.
* Returns a previous cookie with
* the same name, domain and path or `null`.
*/
fun add(cookie: Cookie) = map.put(Key(cookie), cookie)
/**
* Removes a cookie with the same name,
* domain and path as the cookie.
* Returns the removed cookie or `null`.
*/
fun remove(cookie: Cookie) = map.remove(Key(cookie))
/**
* Get cookies for the url. Fill `accepted` and `expired`.
*/
fun get(url: HttpUrl, accepted: MutableList<Cookie>, expired: MutableList<Cookie>) {
val now = System.currentTimeMillis()
map.forEachRemove { _, cookie ->
(cookie.expiresAt() <= now).also {
if (it) {
expired.add(cookie)
} else if (cookie.matches(url)) {
accepted.add(cookie)
}
}
}
}
data class Key(val name: String, val domain: String, val path: String) {
// It's sure name, domain and path is non-null
constructor(cookie: Cookie): this(cookie.name(), cookie.domain(), cookie.path())
}
}
@@ -0,0 +1,43 @@
/*
* Copyright 2017 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.network
import okhttp3.Headers
import okhttp3.MediaType
import okhttp3.ResponseBody
import okhttp3.internal.http.HttpHeaders
import okio.BufferedSource
/*
* Created by Hippo on 2017/7/24.
*/
class SimpleResponseBody(val headers: Headers, val source: BufferedSource) : ResponseBody() {
override fun contentType(): MediaType? {
val contentType = headers.get("Content-Type")
return if (contentType != null) MediaType.parse(contentType) else null
}
override fun contentLength(): Long {
return HttpHeaders.contentLength(headers)
}
override fun source(): BufferedSource {
return source
}
}
@@ -0,0 +1,79 @@
/*
* Copyright 2017 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.noi
import android.graphics.Bitmap
import java.util.LinkedHashMap
/*
* Created by Hippo on 2017/8/3.
*/
class BitmapCache(val maxSize: Int) {
private val map: LinkedHashMap<String, Bitmap> = LinkedHashMap(0, 0.75f, true)
private var size: Int = 0
operator fun get(key: String): Bitmap? {
synchronized(this) {
return map[key]
}
}
operator fun set(key: String, bitmap: Bitmap) {
val addedSize = bitmap.byteCount
if (addedSize > maxSize) {
return
}
synchronized(this) {
size += addedSize
val previous = map.put(key, bitmap)
if (previous != null) {
size -= previous.byteCount
}
}
trimToSize(maxSize)
}
private fun trimToSize(maxSize: Int) {
while (true) {
var key: String
var value: Bitmap
synchronized(this) {
if (size < 0 || map.isEmpty() && size != 0) {
throw IllegalStateException("bitmap.byteCount is reporting inconsistent results!")
}
if (size <= maxSize || map.isEmpty()) {
return
}
val toEvict = map.entries.iterator().next()
key = toEvict.key
value = toEvict.value
map.remove(key)
size -= value.byteCount
}
}
}
fun evictAll() {
trimToSize(-1) // -1 will evict 0-sized elements
}
}
@@ -0,0 +1,50 @@
/*
* Copyright 2017 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.noi
import android.content.res.Resources
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import com.hippo.ehviewer.NOI
import java.io.IOException
import java.io.InputStream
/*
* Created by Hippo on 2017/8/7.
*/
class BitmapDrawableResolver(private val resources: Resources) : NoiTask.DrawableResolver {
override fun getDrawable(uri: String): Drawable? =
NOI.bitmapCache[uri]?.let { BitmapDrawable(resources, it) }
override fun decodeDrawable(uri: String, stream: InputStream, checker: NoiTask.Checker): Drawable {
val bitmap = BitmapFactory.decodeStream(stream)
if (bitmap == null) {
throw IOException("Fail to decode stream")
} else if (!checker.valid) {
bitmap.recycle()
throw IOException("Response body isn't fully read.")
} else {
NOI.bitmapCache[uri] = bitmap
return BitmapDrawable(resources, bitmap)
}
}
override fun recycleDrawable(drawable: Drawable) {}
}
@@ -0,0 +1,125 @@
/*
* Copyright 2017 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.noi
import java.util.ArrayDeque
import java.util.concurrent.Executor
import java.util.concurrent.SynchronousQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
/*
* Created by Hippo on 2017/8/1.
*/
class HttpDispatcher(
private val maxRequests: Int = 64,
private val maxRequestsPerHost: Int = 5,
private val executor: Executor = ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, SynchronousQueue<Runnable>())
) {
private val lowRequests = ArrayDeque<HttpRequest>()
private val mediumRequests = ArrayDeque<HttpRequest>()
private val highRequests = ArrayDeque<HttpRequest>()
private val runningRequests = ArrayDeque<HttpRequest>()
private val runningRequestsPerHost = hashMapOf<String, Int>()
/** Returns `true` if the request added. **/
private fun tryAddingRequestForHost(host: String): Boolean {
val requestsPerHost = runningRequestsPerHost[host] ?: 0
if (requestsPerHost < maxRequestsPerHost) {
runningRequestsPerHost[host] = requestsPerHost + 1
return true
} else {
return false
}
}
private fun deleteRequestForHost(host: String) {
val requestsPerHost = runningRequestsPerHost[host]
if (requestsPerHost == null || requestsPerHost <= 0) {
error("Requests per host is invalid in finished(): $requestsPerHost")
} else if (requestsPerHost == 1) {
runningRequestsPerHost.remove(host)
} else {
runningRequestsPerHost[host] = requestsPerHost - 1
}
}
/** Return `true` if the request doesn't allow duplicate url and duplicate url is running **/
private fun checkDuplicateUrl(request: HttpRequest): Boolean {
if (request.concurrentDuplicateUrl) return false
val url = request.url()
return runningRequests.any { it.url() == url }
}
fun enqueue(request: HttpRequest) {
synchronized(this) {
if (runningRequests.size < maxRequests &&
tryAddingRequestForHost(request.url().host()) &&
!checkDuplicateUrl(request)) {
runningRequests.add(request)
executor.execute(request)
} else {
when (request.priority) {
Priority.LOW -> lowRequests
Priority.MEDIUM -> mediumRequests
Priority.HIGH -> highRequests
}.add(request)
}
}
}
fun cancel(request: HttpRequest) {
request.cancel()
synchronized(this) {
if (!runningRequests.contains(request)) {
when (request.priority) {
Priority.LOW -> lowRequests
Priority.MEDIUM -> mediumRequests
Priority.HIGH -> highRequests
}.remove(request)
}
}
}
fun finished(request: HttpRequest) {
synchronized(this) {
runningRequests.remove(request)
deleteRequestForHost(request.url().host())
// Promote request
if (runningRequests.size >= maxRequests) return
arrayOf(highRequests, mediumRequests, lowRequests).forEach { requests ->
val iterator = requests.iterator()
while (iterator.hasNext()) {
val req = iterator.next()
if (tryAddingRequestForHost(req.url().host()) && !checkDuplicateUrl(req)) {
iterator.remove()
runningRequests.add(req)
executor.execute(req)
}
if (runningRequests.size >= maxRequests) return
}
}
}
}
}
@@ -0,0 +1,108 @@
/*
* Copyright 2017 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.noi
import com.hippo.ehviewer.exception.ResponseCodeException
import com.hippo.ehviewer.util.buffer
import io.reactivex.Single
import io.reactivex.SingleObserver
import io.reactivex.disposables.Disposable
import okhttp3.Call
import okhttp3.HttpUrl
import okhttp3.Response
import okio.Okio
import okio.Source
import java.io.InputStream
/*
* Created by Hippo on 2017/8/1.
*/
class HttpRequest(
private val call: Call,
private val dispatcher: HttpDispatcher
) : Request<HttpRequest>(), Runnable {
var concurrentDuplicateUrl: Boolean = true
private set
private lateinit var observer: SingleObserver<in Response>
// It runs in io thread
override fun run() {
var response: Response? = null
try {
response = call.execute()
if (!call.isCanceled) {
observer.onSuccess(response)
}
} catch (e: Throwable) {
if (!call.isCanceled) {
observer.onError(e)
}
} finally {
response?.close()
dispatcher.finished(this)
}
}
/** Whether allow to concurrent duplicate url. `true` in default. **/
fun concurrentDuplicateUrl(concurrentDuplicateUrl: Boolean): HttpRequest {
checkSolid()
this.concurrentDuplicateUrl = concurrentDuplicateUrl
return this
}
internal fun url(): HttpUrl = call.request().url()
internal fun cancel() = call.cancel()
fun asResponse(): Single<Response> {
solidify()
return object : Single<Response>() {
override fun subscribeActual(observer: SingleObserver<in Response>) {
this@HttpRequest.observer = observer
observer.onSubscribe(object : Disposable {
override fun dispose() { dispatcher.cancel(this@HttpRequest) }
override fun isDisposed(): Boolean = call.isCanceled
})
dispatcher.enqueue(this@HttpRequest)
}
}
}
override fun asSource(): Single<Source> = asResponse().map {
if (it.isSuccessful) {
it.body()!!.source()
} else {
throw ResponseCodeException(it.code())
}
}
override fun asInputStream(): Single<InputStream> = asResponse().map {
if (it.isSuccessful) {
it.body()!!.byteStream()
} else {
throw ResponseCodeException(it.code())
}
}
/** Fetch the response to OkHttp cache **/
fun fetch() = asSource().subscribe({ source -> Okio.blackhole().buffer().use { it.writeAll(source) } }, { /* Ignore error */ })
}
@@ -0,0 +1,31 @@
/*
* Copyright 2017 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.noi
import android.content.Context
import android.util.AttributeSet
import android.view.View
/*
* Created by Hippo on 2017/7/28.
*/
class LargeNoiView : View {
constructor(context: Context): super(context)
constructor(context: Context, attrs: AttributeSet?): super(context, attrs)
}
@@ -0,0 +1,184 @@
/*
* Copyright (C) 2013 Square, Inc.
*
* 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.noi;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* An input stream wrapper that supports unlimited independent cursors for
* marking and resetting. Each cursor is a token, and it's the caller's
* responsibility to keep track of these.
*/
final class MarkableInputStream extends InputStream {
private static final int DEFAULT_BUFFER_SIZE = 4096;
private static final int DEFAULT_LIMIT_INCREMENT = 1024;
private final InputStream in;
private long offset;
private long reset;
private long limit;
private long defaultMark = -1;
private boolean allowExpire = true;
private int limitIncrement = -1;
public MarkableInputStream(InputStream in) {
this(in, DEFAULT_BUFFER_SIZE);
}
public MarkableInputStream(InputStream in, int size) {
this(in, size, DEFAULT_LIMIT_INCREMENT);
}
private MarkableInputStream(InputStream in, int size, int limitIncrement) {
if (!in.markSupported()) {
in = new BufferedInputStream(in, size);
}
this.in = in;
this.limitIncrement = limitIncrement;
}
/** Marks this place in the stream so we can reset back to it later. */
@Override public void mark(int readLimit) {
defaultMark = savePosition(readLimit);
}
/**
* Returns an opaque token representing the current position in the stream.
* Call {@link #reset(long)} to return to this position in the stream later.
* It is an error to call {@link #reset(long)} after consuming more than
* {@code readLimit} bytes from this stream.
*/
public long savePosition(int readLimit) {
long offsetLimit = offset + readLimit;
if (limit < offsetLimit) {
setLimit(offsetLimit);
}
return offset;
}
public void allowMarksToExpire(boolean allowExpire) {
this.allowExpire = allowExpire;
}
/**
* Makes sure that the underlying stream can backtrack the full range from
* {@code reset} thru {@code limit}. Since we can't call {@code mark()}
* without also adjusting the reset-to-position on the underlying stream this
* method resets first and then marks the union of the two byte ranges. On
* buffered streams this additional cursor motion shouldn't result in any
* additional I/O.
*/
private void setLimit(long limit) {
try {
if (reset < offset && offset <= this.limit) {
in.reset();
in.mark((int) (limit - reset));
skip(reset, offset);
} else {
reset = offset;
in.mark((int) (limit - offset));
}
this.limit = limit;
} catch (IOException e) {
throw new IllegalStateException("Unable to mark: " + e);
}
}
/** Resets the stream to the most recent {@link #mark mark}. */
@Override public void reset() throws IOException {
reset(defaultMark);
}
/** Resets the stream to the position recorded by {@code token}. */
public void reset(long token) throws IOException {
if (offset > limit || token < reset) {
throw new IOException("Cannot reset");
}
in.reset();
skip(reset, token);
offset = token;
}
/** Skips {@code target - current} bytes and returns. */
private void skip(long current, long target) throws IOException {
while (current < target) {
long skipped = in.skip(target - current);
if (skipped == 0) {
if (read() == -1) {
break; // EOF
} else {
skipped = 1;
}
}
current += skipped;
}
}
@Override public int read() throws IOException {
if (!allowExpire && (offset + 1 > limit)) {
setLimit(limit + limitIncrement);
}
int result = in.read();
if (result != -1) {
offset++;
}
return result;
}
@Override public int read(byte[] buffer) throws IOException {
if (!allowExpire && (offset + buffer.length > limit)) {
setLimit(offset + buffer.length + limitIncrement);
}
int count = in.read(buffer);
if (count != -1) {
offset += count;
}
return count;
}
@Override public int read(byte[] buffer, int offset, int length) throws IOException {
if (!allowExpire && (this.offset + length > limit)) {
setLimit(this.offset + length + limitIncrement);
}
int count = in.read(buffer, offset, length);
if (count != -1) {
this.offset += count;
}
return count;
}
@Override public long skip(long byteCount) throws IOException {
if (!allowExpire && (offset + byteCount > limit)) {
setLimit(offset + byteCount + limitIncrement);
}
long skipped = in.skip(byteCount);
offset += skipped;
return skipped;
}
@Override public int available() throws IOException {
return in.available();
}
@Override public void close() throws IOException {
in.close();
}
@Override public boolean markSupported() {
return in.markSupported();
}
}
@@ -0,0 +1,102 @@
/*
* Copyright 2017 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.noi
import android.app.ActivityManager
import android.content.ComponentCallbacks2
import android.content.Context
import android.content.pm.ApplicationInfo.FLAG_LARGE_HEAP
import android.content.res.Configuration
import okhttp3.OkHttpClient
import java.net.URL
/*
* Created by Hippo on 2017/8/1.
*/
// com.squareup.picasso.Utils
fun calculateMemoryCacheSize(context: Context): Int {
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val largeHeap = context.applicationInfo.flags and FLAG_LARGE_HEAP != 0
val memoryClass = if (largeHeap) am.largeMemoryClass else am.memoryClass
// Target ~15% of the available heap.
return (1024L * 1024L * memoryClass.toLong() / 7).toInt()
}
class Noi(
val context: Context,
val client: OkHttpClient = OkHttpClient.Builder().build(),
val dispatcher: HttpDispatcher = HttpDispatcher(),
val bitmapCache: BitmapCache = BitmapCache(calculateMemoryCacheSize(context))
) {
init {
context.registerComponentCallbacks(object : ComponentCallbacks2 {
override fun onConfigurationChanged(newConfig: Configuration?) {}
override fun onLowMemory() {}
override fun onTrimMemory(level: Int) {
when (level) {
ComponentCallbacks2.TRIM_MEMORY_COMPLETE,
ComponentCallbacks2.TRIM_MEMORY_MODERATE,
ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL,
ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW -> bitmapCache.evictAll()
}
}
})
}
fun http(url: String): HttpRequest = http(okhttp3.Request.Builder().get().url(url).build())
fun http(url: URL): HttpRequest = http(okhttp3.Request.Builder().get().url(url).build())
fun http(request: okhttp3.Request): HttpRequest = HttpRequest(client.newCall(request), dispatcher)
}
//fun Single<Source>.drawable(noi: Noi): Single<Drawable> = map { source ->
// val stream = MarkableInputStream(Okio.buffer(source).inputStream())
// stream.allowMarksToExpire(false)
// val mark = stream.savePosition(1024)
//
// val options = BitmapFactory.Options()
// options.inJustDecodeBounds = true
// BitmapFactory.decodeStream(stream, null, options)
//
// stream.reset(mark)
// stream.allowMarksToExpire(true)
//
// if (options.outWidth <= 0 || options.outHeight <= 0 || options.outMimeType == null) {
// throw IOException("Failed to decode stream.")
// }
//
// var drawable: Drawable? = null
// if (options.outMimeType == "image/gif") {
//
//
//
//
// } else {
// val bitmap = BitmapFactory.decodeStream(stream)
// if (bitmap != null) {
//
// noi.bitmapCache[]
//
// drawable = BitmapDrawable(noi.context.resources, bitmap)
// }
// }
//
// null
//}
@@ -0,0 +1,266 @@
/*
* Copyright 2017 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.noi
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Matrix
import android.graphics.PixelFormat
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.os.SystemClock
import android.view.Gravity
import com.hippo.ehviewer.util.Animate
import com.hippo.ehviewer.util.DURATION_IN
import com.hippo.ehviewer.util.DURATION_OUT
import com.hippo.ehviewer.util.clamp
/*
* Created by Hippo on 2017/8/4.
*/
class NoiDrawable : Drawable(), Drawable.Callback {
private val placeholder = ChildInfo()
private val actual = ChildInfo()
private val failure = ChildInfo()
var placeholderDrawable: Drawable?
get() = placeholder.drawable
set(value) = setDrawable(placeholder, value?.mutate())
var actualDrawable: Drawable?
get() = actual.drawable
set(value) = setDrawable(actual, value?.mutate())
var failureDrawable: Drawable?
get() = failure.drawable
set(value) = setDrawable(failure, value?.mutate())
var placeholderScaleType: ScaleType
get() = placeholder.scaleType
set(value) = setScaleType(placeholder, value)
var actualScaleType: ScaleType
get() = actual.scaleType
set(value) = setScaleType(actual, value)
var failureScaleType: ScaleType
get() = failure.scaleType
set(value) = setScaleType(failure, value)
var placeholderGravity: Int
get() = placeholder.gravity
set(value) = setGravity(placeholder, value)
var actualGravity: Int
get() = actual.gravity
set(value) = setGravity(actual, value)
var failureGravity: Int
get() = failure.gravity
set(value) = setGravity(failure, value)
val isPlaceholderVisible: Boolean get() = placeholder.visible
val isActualVisible: Boolean get() = actual.visible
val isFailureVisible: Boolean get() = failure.visible
private fun setDrawable(info: ChildInfo, drawable: Drawable?) {
info.drawable?.let { it.callback = null }
info.drawable = drawable
if (drawable != null) {
drawable.callback = this
val bounds = this.bounds
if (!bounds.isEmpty) {
info.refreshMatrix(bounds)
}
if (info.visible) {
invalidateSelf()
}
}
}
private fun setScaleType(info: ChildInfo, scaleType: ScaleType) {
if (info.scaleType != scaleType) {
info.scaleType = scaleType
val bounds = this.bounds
if (!bounds.isEmpty) {
info.refreshMatrix(bounds)
}
if (info.visible) {
invalidateSelf()
}
}
}
private fun setGravity(info: ChildInfo, gravity: Int) {
if (info.gravity != gravity) {
info.gravity = gravity
val bounds = this.bounds
if (!bounds.isEmpty) {
info.refreshMatrix(bounds)
}
if (info.visible) {
invalidateSelf()
}
}
}
fun showPlaceholder(animation: Boolean) {
placeholder.show(animation)
actual.hide(animation)
failure.hide(animation)
}
fun showActual(animation: Boolean) {
placeholder.hide(animation)
actual.show(animation)
failure.hide(animation)
}
fun showFailure(animation: Boolean) {
placeholder.hide(animation)
actual.hide(animation)
failure.show(animation)
}
override fun onBoundsChange(bounds: Rect) {
if (bounds.isEmpty) return
placeholder.refreshMatrix(bounds)
actual.refreshMatrix(bounds)
failure.refreshMatrix(bounds)
}
override fun draw(canvas: Canvas) {
if (bounds.isEmpty) return
val now = SystemClock.elapsedRealtime()
placeholder.draw(canvas, now)
actual.draw(canvas, now)
failure.draw(canvas, now)
}
override fun setAlpha(alpha: Int) {}
override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
override fun setColorFilter(colorFilter: ColorFilter?) {}
private fun verifyDrawable(drawable: Drawable?): Boolean = drawable != null &&
((placeholder.visible && drawable == placeholder.drawable) ||
(actual.visible && drawable == actual.drawable) ||
(failure.visible && drawable == failure.drawable))
override fun invalidateDrawable(who: Drawable?) {
if (verifyDrawable(who)) invalidateSelf()
}
override fun scheduleDrawable(who: Drawable?, what: Runnable?, `when`: Long) {
if (verifyDrawable(who)) scheduleSelf(what, `when`)
}
override fun unscheduleDrawable(who: Drawable?, what: Runnable?) {
if (verifyDrawable(who)) unscheduleSelf(what)
}
private class ChildInfo {
var drawable: Drawable? = null
var visible: Boolean = false
var scaleType: ScaleType = ScaleType.NONE
var gravity: Int = Gravity.CENTER
var matrix: Matrix = Matrix()
var showing: Boolean = false
val animate: Animate = object : Animate() {
override fun onCalculate(progress: Float) {
drawable?.alpha = ((if (showing) progress else (1.0f - progress)) * 255).toInt().clamp(0, 255)
}
override fun onEnd() {
drawable?.alpha = 255
visible = showing
}
}
fun show(animation: Boolean) {
if (!showing) {
animate.cancel()
showing = true
visible = true
if (animation) {
animate.duration = DURATION_IN
animate.start()
}
drawable?.invalidateSelf()
} else if (!animation) {
animate.cancel()
drawable?.invalidateSelf()
}
}
fun hide(animation: Boolean) {
if (showing) {
animate.cancel()
showing = false
if (animation) {
visible = true
animate.duration = DURATION_OUT
animate.start()
} else {
visible = false
}
drawable?.invalidateSelf()
} else if (!animation) {
animate.cancel()
drawable?.invalidateSelf()
}
}
fun refreshMatrix(bounds: Rect) {
val drawable = this.drawable
if (drawable != null) {
scaleType.refreshMatrix(drawable, bounds, matrix, gravity)
}
}
fun draw(canvas: Canvas, now: Long) {
val drawable = this.drawable
if (!visible || drawable == null) return
if (animate.calculate(now)) {
drawable.invalidateSelf()
}
if (!visible) return
val translate = scaleType != ScaleType.NONE
var saved: Int = 0
if (translate) {
saved = canvas.save()
canvas.concat(matrix)
}
drawable.draw(canvas)
if (translate) {
canvas.restoreToCount(saved)
}
}
}
}
@@ -0,0 +1,244 @@
/*
* Copyright 2017 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.noi
import android.content.Context
import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.os.Message
import com.hippo.ehviewer.NOI
import com.hippo.ehviewer.util.MAX_LEVEL
import com.hippo.ehviewer.util.MutableAny
import com.hippo.ehviewer.util.MutableBoolean
import com.hippo.ehviewer.util.check
import com.hippo.ehviewer.util.progress
import com.hippo.unifile.UniFile
import io.reactivex.Single
import io.reactivex.SingleObserver
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.disposables.Disposables
import io.reactivex.schedulers.Schedulers
import java.io.IOException
import java.io.InputStream
/*
* Created by Hippo on 2017/8/7.
*/
class NoiTask(
private val context: Context,
private val resolver: DrawableResolver
) {
companion object {
private val HANDLE: Handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
val obj = msg.obj
if (obj is NoiDrawable && obj.isPlaceholderVisible) {
obj.placeholderDrawable?.level = msg.what
}
}
}
}
val noiDrawable = NoiDrawable()
private var disposable: Disposable? = null
var enableProgress: Boolean = false
var enableFade: Boolean = true
private fun startPlaceholder() {
val placeholder = noiDrawable.placeholderDrawable
if (placeholder is Animatable) {
placeholder.start()
}
}
private fun stopPlaceholder() {
val placeholder = noiDrawable.placeholderDrawable
if (placeholder is Animatable) {
placeholder.stop()
}
}
fun load(drawable: Drawable) {
cancel()
noiDrawable.actualDrawable = drawable
noiDrawable.showActual(false)
}
fun load(uri: String) {
cancel()
val drawable = resolver.getDrawable(uri)
if (drawable != null) {
noiDrawable.actualDrawable = drawable
noiDrawable.showActual(false)
} else {
startPlaceholder()
noiDrawable.showPlaceholder(false)
download(uri)
}
}
private fun http(uri: String, checker: RealChecker): Single<InputStream> {
var obj = NOI.http(uri)
.concurrentDuplicateUrl(false)
.asResponse()
.check(checker.httpChecker)
if (enableProgress) {
obj = obj.progress { _, read, total ->
val level = (read * MAX_LEVEL / total).toInt()
HANDLE.sendMessage(HANDLE.obtainMessage(level, noiDrawable))
}
}
return obj.map { it.body()!!.byteStream() }
}
private fun file(uri: String, checker: RealChecker): Single<InputStream> {
// It's not http, always set http checker to true
checker.httpChecker.value = true
val obj = object : Single<InputStream>() {
override fun subscribeActual(observer: SingleObserver<in InputStream>) {
observer.onSubscribe(Disposables.empty())
observer.onSuccess(UniFile.fromUri(context, Uri.parse(uri)).openInputStream())
}
}
return obj.subscribeOn(Schedulers.io())
}
private fun isHttp(uri: String): Boolean = uri.startsWith("http://") || uri.startsWith("https://")
private fun download(uri: String) {
val checker = RealChecker()
val drawableHolder = MutableAny<Drawable>(null)
(if (isHttp(uri)) http(uri, checker) else file(uri, checker))
.map { stream ->
val drawable = stream.use { resolver.decodeDrawable(uri, it, checker) }
var valid: Boolean = false
synchronized(checker) {
valid = checker.valid
if (valid) {
drawableHolder.value = drawable
}
}
if (!valid) {
resolver.recycleDrawable(drawable)
throw IOException("Disposed")
} else {
drawable
}
}
.doOnDispose {
var drawable: Drawable? = null
synchronized(checker) {
checker.failed()
drawable = drawableHolder.value
drawableHolder.value = null
}
drawable?.let { resolver.recycleDrawable(it) }
}
.observeOn(AndroidSchedulers.mainThread())
.register({ drawable ->
stopPlaceholder()
noiDrawable.actualDrawable = drawable
noiDrawable.showActual(enableFade)
}, {
stopPlaceholder()
noiDrawable.showFailure(enableFade)
})
}
fun cancel() {
disposable?.run { dispose() }
disposable = null
stopPlaceholder()
val oldDrawable = noiDrawable.actualDrawable
if (oldDrawable != null) {
resolver.recycleDrawable(oldDrawable)
noiDrawable.actualDrawable = null
}
}
private fun <T> Single<T>.register(
onSuccess: (T) -> Unit,
onError: (Throwable) -> Unit
) {
disposable = subscribe({
onSuccess(it)
disposable = null
}, {
onError(it)
disposable = null
})
}
interface Checker {
val valid: Boolean
}
private class RealChecker : Checker {
val httpChecker = MutableBoolean(false)
private var failed = false
fun failed() {
failed = true
}
override val valid: Boolean get() = !failed && httpChecker.value
}
interface DrawableResolver {
/**
* Gets drawable for the uri. Returns `null` if can't get the drawable in a short time.
*
* It's called in UI thread.
*/
fun getDrawable(uri: String): Drawable?
/**
* Decodes the stream for the uri. Throws a [Throwable] if can't decode the stream.
*
* Checks the checker after decoding. The decoded resources should be cached if it's invalid.
*
* It's called in IO thread.
*/
@Throws(Throwable::class)
fun decodeDrawable(uri: String, stream: InputStream, checker: Checker): Drawable
/**
* Recycles the resources associated with the drawable.
*
* It's called in UI or IO thread.
*/
fun recycleDrawable(drawable: Drawable)
}
}
@@ -0,0 +1,211 @@
/*
* Copyright 2017 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.noi
import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.support.v4.view.ViewCompat
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import com.hippo.ehviewer.R
import com.hippo.ehviewer.util.getDrawable
/*
* Created by Hippo on 2017/8/7.
*/
open class NoiView : View {
constructor(context: Context): super(context)
constructor(context: Context, attrs: AttributeSet?): super(context, attrs) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.NoiView)
placeholderDrawable = typedArray.getDrawable(context, R.styleable.NoiView_placeholderDrawable)
failureDrawable = typedArray.getDrawable(context, R.styleable.NoiView_failureDrawable)
placeholderScaleType = typedArray.getInt(R.styleable.NoiView_placeholderScaleType, 0).scaleType
actualScaleType = typedArray.getInt(R.styleable.NoiView_actualScaleType, 0).scaleType
failureScaleType = typedArray.getInt(R.styleable.NoiView_failureScaleType, 0).scaleType
placeholderGravity = typedArray.getInt(R.styleable.NoiView_placeholderGravity, Gravity.CENTER)
actualGravity = typedArray.getInt(R.styleable.NoiView_actualGravity, Gravity.CENTER)
failureGravity = typedArray.getInt(R.styleable.NoiView_failureGravity, Gravity.CENTER)
aspectRatio = typedArray.getFloat(R.styleable.NoiView_aspectRatio, 0.0f)
enableProgress = typedArray.getBoolean(R.styleable.NoiView_enableProgress, false)
enableFade = typedArray.getBoolean(R.styleable.NoiView_enableFade, true)
drawable = typedArray.getDrawable(context, R.styleable.NoiView_drawable)
uri = typedArray.getString(R.styleable.NoiView_uri)
typedArray.recycle()
}
private val task = NoiTask(context, BitmapDrawableResolver(context.resources))
.also { it.noiDrawable.callback = this }
var placeholderDrawable: Drawable?
get() = task.noiDrawable.placeholderDrawable
set(value) { task.noiDrawable.placeholderDrawable = value }
val actualDrawable: Drawable? get() = task.noiDrawable.actualDrawable
var failureDrawable: Drawable?
get() = task.noiDrawable.failureDrawable
set(value) { task.noiDrawable.failureDrawable = value }
var placeholderScaleType: ScaleType
get() = task.noiDrawable.placeholderScaleType
set(value) { task.noiDrawable.placeholderScaleType = value }
var actualScaleType: ScaleType
get() = task.noiDrawable.actualScaleType
set(value) { task.noiDrawable.actualScaleType = value }
var failureScaleType: ScaleType
get() = task.noiDrawable.failureScaleType
set(value) { task.noiDrawable.failureScaleType = value }
var placeholderGravity: Int
get() = task.noiDrawable.placeholderGravity
set(value) { task.noiDrawable.placeholderGravity = value }
var actualGravity: Int
get() = task.noiDrawable.actualGravity
set(value) { task.noiDrawable.actualGravity = value }
var failureGravity: Int
get() = task.noiDrawable.failureGravity
set(value) { task.noiDrawable.failureGravity = value }
var aspectRatio: Float = 0.0f
set(value) {
if (field != value) {
field = value
requestLayout()
}
}
var enableProgress: Boolean
get() = task.enableProgress
set(value) { task.enableProgress = value }
var enableFade: Boolean
get() = task.enableFade
set(value) { task.enableFade = value }
var uri: String? = null
set(value) {
if (field != value) {
field = value
if (value != null) {
drawable = null
}
if (ViewCompat.isAttachedToWindow(this)) {
if (value != null) {
task.load(value)
} else {
task.cancel()
}
}
}
}
var drawable: Drawable? = null
set(value) {
if (field != value) {
field = value
if (value != null) {
uri = null
}
if (ViewCompat.isAttachedToWindow(this)) {
if (value != null) {
task.load(value)
} else {
task.cancel()
}
}
}
}
private val Int.scaleType get() = when (this) {
1 -> ScaleType.CENTER_INSIDE
2 -> ScaleType.CENTER_CROP
else -> ScaleType.NONE
}
override fun verifyDrawable(who: Drawable?): Boolean {
return who == task.noiDrawable || super.verifyDrawable(who)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
val url = this.uri
val drawable = this.drawable
if (url != null) {
task.load(url)
} else if (drawable != null) {
task.load(drawable)
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
if (uri != null || drawable != null) {
task.cancel()
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
task.noiDrawable.setBounds(0, 0, w, h)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
if (aspectRatio > 0.0f) {
val widthSize = MeasureSpec.getSize(widthMeasureSpec)
val widthMode = MeasureSpec.getMode(widthMeasureSpec)
val heightSize = MeasureSpec.getSize(heightMeasureSpec)
val heightMode = MeasureSpec.getMode(heightMeasureSpec)
if (widthMode == MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) {
setMeasuredDimension(
widthSize,
(widthSize / aspectRatio).toInt().let {
if (heightMode == MeasureSpec.AT_MOST) maxOf(it, heightSize)
else it
})
return
} else if (heightMode == MeasureSpec.EXACTLY || widthMode != MeasureSpec.EXACTLY) {
setMeasuredDimension(
(heightSize * aspectRatio).toInt().let {
if (widthMode == MeasureSpec.AT_MOST) maxOf(it, widthSize)
else it
},
heightSize)
return
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
override fun onDraw(canvas: Canvas) {
task.noiDrawable.draw(canvas)
}
}
@@ -0,0 +1,25 @@
/*
* Copyright 2017 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.noi
/*
* Created by Hippo on 2017/8/1.
*/
enum class Priority {
LOW, MEDIUM, HIGH
}
@@ -0,0 +1,53 @@
/*
* Copyright 2017 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.noi
import io.reactivex.Single
import okio.Source
import java.io.InputStream
/*
* Created by Hippo on 2017/8/1.
*/
@Suppress("UNCHECKED_CAST")
abstract class Request<out This> {
var solid: Boolean = false
private set
var priority: Priority = Priority.MEDIUM
private set
protected fun checkSolid() = check(!solid) { "Can't modify a solid Request" }
/** The priority of this request, [Priority.MEDIUM] in default. **/
fun priority(priority: Priority): This {
checkSolid()
this.priority = priority
return this as This
}
protected fun solidify() {
checkSolid()
solid = true
}
abstract fun asSource(): Single<Source>
abstract fun asInputStream(): Single<InputStream>
}
@@ -0,0 +1,134 @@
/*
* Copyright 2017 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.noi
import android.graphics.Matrix
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.Gravity
/*
* Created by Hippo on 2017/8/4.
*/
enum class ScaleType {
NONE {
override fun doRefreshMatrix(drawable: Drawable, bounds: Rect, matrix: Matrix, gravity: Int) {
drawable.bounds.set(bounds)
}
},
CENTER_INSIDE {
override fun doRefreshMatrix(drawable: Drawable, bounds: Rect, matrix: Matrix, gravity: Int) {
drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
val drawableRatio = drawable.intrinsicWidth.toFloat() / drawable.intrinsicHeight.toFloat()
val boundsRatio = bounds.width().toFloat() / bounds.height().toFloat()
val scale: Float
val dx: Float
val dy: Float
if (drawableRatio > boundsRatio) {
scale = bounds.width().toFloat() / drawable.intrinsicWidth.toFloat()
dx = 0.0f
dy = when (gravity and Gravity.VERTICAL_GRAVITY_MASK) {
Gravity.TOP -> 0.0f
Gravity.BOTTOM -> bounds.height() - (bounds.width() / drawableRatio)
else -> (bounds.height() - (bounds.width() / drawableRatio)) / 2
}
} else {
scale = bounds.height().toFloat() / drawable.intrinsicHeight.toFloat()
dx = when (gravity and Gravity.HORIZONTAL_GRAVITY_MASK) {
Gravity.LEFT -> 0.0f
Gravity.RIGHT -> bounds.width() - (bounds.height() * drawableRatio)
else -> (bounds.width() - (bounds.height() * drawableRatio)) / 2
}
dy = 0.0f
}
matrix.reset()
matrix.postScale(scale, scale)
matrix.postTranslate(dx, dy)
}
},
CENTER_CROP {
override fun doRefreshMatrix(drawable: Drawable, bounds: Rect, matrix: Matrix, gravity: Int) {
drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
val drawableRatio = drawable.intrinsicWidth.toFloat() / drawable.intrinsicHeight.toFloat()
val boundsRatio = bounds.width().toFloat() / bounds.height().toFloat()
val scale: Float
val dx: Float
val dy: Float
if (drawableRatio > boundsRatio) {
scale = bounds.height().toFloat() / drawable.intrinsicHeight.toFloat()
dx = when (gravity and Gravity.HORIZONTAL_GRAVITY_MASK) {
Gravity.LEFT -> 0.0f
Gravity.RIGHT -> bounds.width() - (bounds.height() * drawableRatio)
else -> (bounds.width() - (bounds.height() * drawableRatio)) / 2
}
dy = 0.0f
} else {
scale = bounds.width().toFloat() / drawable.intrinsicWidth.toFloat()
dx = 0.0f
dy = when (gravity and Gravity.VERTICAL_GRAVITY_MASK) {
Gravity.TOP -> 0.0f
Gravity.BOTTOM -> bounds.height() - (bounds.width() / drawableRatio)
else -> (bounds.height() - (bounds.width() / drawableRatio)) / 2
}
}
matrix.reset()
matrix.postScale(scale, scale)
matrix.postTranslate(dx, dy)
}
};
fun refreshMatrix(drawable: Drawable, bounds: Rect, matrix: Matrix, gravity: Int) {
val width = drawable.intrinsicWidth
val height = drawable.intrinsicHeight
if (width == -1 && height == -1) {
drawable.bounds = bounds
matrix.reset()
} else if (width == -1) {
val ratio = bounds.width().toFloat() / bounds.height().toFloat()
drawable.bounds.set(0, 0, (height * ratio).toInt(), height)
val scale = bounds.height().toFloat() / height.toFloat()
matrix.reset()
matrix.postScale(scale, scale)
} else if (height == -1) {
val ratio = bounds.width().toFloat() / bounds.height().toFloat()
drawable.bounds.set(0, 0, width, (width / ratio).toInt())
val scale = bounds.width().toFloat() / width.toFloat()
matrix.reset()
matrix.postScale(scale, scale)
} else {
doRefreshMatrix(drawable, bounds, matrix, gravity)
}
}
abstract fun doRefreshMatrix(drawable: Drawable, bounds: Rect, matrix: Matrix, gravity: Int)
}
@@ -0,0 +1,123 @@
/*
* Copyright 2017 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.SharedPreferences
import android.util.Log
import com.jakewharton.rxrelay2.BehaviorRelay
import com.jakewharton.rxrelay2.Relay
import io.reactivex.Observable
/*
* Created by Hippo on 6/29/2017.
*/
/**
* Base preferences.
*/
abstract class Preferences(protected val pref: SharedPreferences) {
private inline fun <T> setValue(
key: String,
value: T,
getter: SharedPreferences.Editor.(String, T) -> SharedPreferences.Editor
) {
pref.edit().getter(key, value).apply()
}
private inline fun <T> getValue(
key: String,
defValue: T,
typeName: String,
getter: SharedPreferences.(String, T) -> T
): T {
try {
return pref.getter(key, defValue)
} catch (e: ClassCastException) {
Log.e("Preferences", "The value of $key is not a $typeName.", e)
return defValue
}
}
protected fun setBoolean(key: String, value: Boolean) =
setValue(key, value, SharedPreferences.Editor::putBoolean)
protected fun getBoolean(key: String, defValue: Boolean) =
getValue(key, defValue, "boolean", SharedPreferences::getBoolean)
protected fun setInt(key: String, value: Int) =
setValue(key, value, SharedPreferences.Editor::putInt)
protected fun getInt(key: String, defValue: Int) =
getValue(key, defValue, "int", SharedPreferences::getInt)
protected fun setLong(key: String, value: Long) =
setValue(key, value, SharedPreferences.Editor::putLong)
protected fun getLong(key: String, defValue: Long) =
getValue(key, defValue, "long", SharedPreferences::getLong)
protected fun setFloat(key: String, value: Float) =
setValue(key, value, SharedPreferences.Editor::putFloat)
protected fun getFloat(key: String, defValue: Float) =
getValue(key, defValue, "float", SharedPreferences::getFloat)
protected fun setString(key: String, value: String) =
setValue(key, value, SharedPreferences.Editor::putString)
protected fun getString(key: String, defValue: String) =
getValue(key, defValue, "string", SharedPreferences::getString)!!
protected fun setDecimalInt(key: String, value: Int) =
setValue(key, value.toString(), SharedPreferences.Editor::putString)
protected fun getDecimalInt(key: String, defValue: Int) =
getValue(key, defValue.toString(), "decimal int", SharedPreferences::getString).toIntOrNull() ?: defValue
protected fun edit(): SharedPreferences.Editor {
return pref.edit()
}
abstract inner class Preference<T>(
private val key: String,
defValue: T,
getter: Preferences.(String, T) -> T,
private val setter: Preferences.(String, T) -> Unit
) {
private var relay : Relay<T>? = null
var value: T = getter(key, defValue)
set(value) {
if (field != value) {
field = value
setter(key, value)
relay?.accept(value)
}
}
val observable: Observable<T>
get() = relay ?: BehaviorRelay.createDefault(value).also { relay = it }
}
inner class BooleanPreference(key: String, defValue: Boolean) : Preference<Boolean>(key, defValue, Preferences::getBoolean, Preferences::setBoolean)
inner class IntPreference(key: String, defValue: Int) : Preference<Int>(key, defValue, Preferences::getInt, Preferences::setInt)
inner class LongPreference(key: String, defValue: Long) : Preference<Long>(key, defValue, Preferences::getLong, Preferences::setLong)
inner class FloatPreference(key: String, defValue: Float) : Preference<Float>(key, defValue, Preferences::getFloat, Preferences::setFloat)
inner class StringPreference(key: String, defValue: String) : Preference<String>(key, defValue, Preferences::getString, Preferences::setString)
inner class DecimalIntPreference(key: String, defValue: Int) : Preference<Int>(key, defValue, Preferences::getDecimalInt, Preferences::setDecimalInt)
}
@@ -0,0 +1,71 @@
/*
* Copyright 2017 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.scene
import android.os.Bundle
import com.hippo.ehviewer.client.GLUrlBuilder
import com.hippo.ehviewer.client.data.GalleryInfo
import com.hippo.ehviewer.mvp.EhvScene
import com.hippo.ehviewer.mvp.MvpPaper
import com.hippo.ehviewer.mvp.MvpPen
import com.hippo.ehviewer.slice.DumpPen
import com.hippo.ehviewer.slice.GalleryDetailPen
import com.hippo.ehviewer.slice.StatusBarPen
import com.hippo.ehviewer.slice.galleryDetail
import com.hippo.ehviewer.slice.papers
import com.hippo.ehviewer.slice.pens
/*
* Created by Hippo on 2017/7/24.
*/
/**
* Shows gallery detail.
*/
class GalleryDetailScene : EhvScene() {
companion object {
val KEY_GALLERY_INFO = "GalleryDetailScene:gallery_info"
}
private val statusBar = object : StatusBarPen() {}
private val galleryDetail = object : GalleryDetailPen() {
override fun onClickTag(namespace: String, tag: String) {
stage?.let { stage ->
val builder = GLUrlBuilder()
builder.tags.add(namespace, tag)
stage.pushScene(galleryList(builder))
}
}
}
private lateinit var pen: DumpPen
override fun createPen(args: Bundle): MvpPen<*> = pens(statusBar, galleryDetail) {
val info = args.getParcelable<GalleryInfo>(KEY_GALLERY_INFO)
if (info != null) {
galleryDetail.init(info)
} else {
// TODO
}
}.apply { pen = this }
override fun createPaper(): MvpPaper<*> = papers(pen) {
galleryDetail(galleryDetail, it)
}
}
@@ -0,0 +1,125 @@
/*
* Copyright 2017 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.scene
import android.os.Bundle
import android.view.MenuItem
import com.hippo.ehviewer.EHV_PREFERENCES
import com.hippo.ehviewer.LIST_MODE_BRIEF
import com.hippo.ehviewer.LIST_MODE_DETAIL
import com.hippo.ehviewer.R
import com.hippo.ehviewer.activity.EhvActivity
import com.hippo.ehviewer.client.GLUrlBuilder
import com.hippo.ehviewer.client.data.GalleryInfo
import com.hippo.ehviewer.mvp.EhvScene
import com.hippo.ehviewer.mvp.MvpPaper
import com.hippo.ehviewer.mvp.MvpPen
import com.hippo.ehviewer.slice.DumpPen
import com.hippo.ehviewer.slice.GalleryListPen
import com.hippo.ehviewer.slice.StatusBarPaper
import com.hippo.ehviewer.slice.StatusBarPen
import com.hippo.ehviewer.slice.ToolbarPaper
import com.hippo.ehviewer.slice.ToolbarPen
import com.hippo.ehviewer.slice.galleryList
import com.hippo.ehviewer.slice.papers
import com.hippo.ehviewer.slice.pens
import com.hippo.ehviewer.slice.setTitle
import com.hippo.ehviewer.slice.statusBar
import com.hippo.ehviewer.slice.toolbar
/*
* Created by Hippo on 2017/7/24.
*/
/**
* Shows gallery list. Only this gallery list, can't switch to another list.
*/
class GalleryListScene : EhvScene() {
companion object {
val KEY_GL_URL_BUILDER = "GalleryListScene:gl_url_builder"
}
private val statusBar: StatusBarPen = object : StatusBarPen() {}
private val toolbar: ToolbarPen = object : ToolbarPen() {
override fun onDoubleClick() {
galleryList.refresh()
}
override fun onClickNavigationIcon() {
pop()
}
override fun onClickMenuItem(item: MenuItem): Boolean = when (item.itemId) {
R.id.gallery_list_action_go_to -> {
// TODO
true
}
R.id.gallery_list_action_detail -> {
EHV_PREFERENCES.listMode.value = LIST_MODE_DETAIL
true
}
R.id.gallery_list_action_brief -> {
EHV_PREFERENCES.listMode.value = LIST_MODE_BRIEF
true
}
else -> super.onClickMenuItem(item)
}
}
private val galleryList: GalleryListPen = object : GalleryListPen() {
override fun showMessage(message: String) {
(activity as? EhvActivity)?.snack(message)
}
override fun onClickGalleryInfo(info: GalleryInfo) {
stage?.pushScene(galleryDetail(info))
}
}
private lateinit var pen: DumpPen
override fun createPen(args: Bundle): MvpPen<*> = pens(statusBar, toolbar, galleryList) {
toolbar.setDoubleClickEnabled()
toolbar.setNavigationIcon(R.drawable.arrow_left_dark_x24)
// Register menu updater
EHV_PREFERENCES.listMode.observable.register {
when (it) {
// If inflating menu at once, the text in dialog will change at once, that looks bad
LIST_MODE_DETAIL -> schedule({ toolbar.inflateMenu(R.menu.gallery_list_detail) }, 200)
LIST_MODE_BRIEF -> schedule({ toolbar.inflateMenu(R.menu.gallery_list_brief) }, 200)
}
}
// Register title updater
galleryList.builderObservable.register { toolbar.setTitle(it.toTitle()) }
val builder = args.getParcelable<GLUrlBuilder>(KEY_GL_URL_BUILDER)
galleryList.apply(builder)
}.apply { pen = this }
override fun createPaper(): MvpPaper<*> = papers(pen) {
statusBar(statusBar, it) {
toolbar(toolbar, StatusBarPaper.CONTAINER_ID) {
galleryList(galleryList, ToolbarPaper.CONTAINER_ID)
}
}
}
}
@@ -0,0 +1,128 @@
/*
* Copyright 2017 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.scene
import android.os.Bundle
import android.view.MenuItem
import com.hippo.ehviewer.EHV_PREFERENCES
import com.hippo.ehviewer.LIST_MODE_BRIEF
import com.hippo.ehviewer.LIST_MODE_DETAIL
import com.hippo.ehviewer.R
import com.hippo.ehviewer.activity.EhvActivity
import com.hippo.ehviewer.client.data.GalleryInfo
import com.hippo.ehviewer.mvp.EhvScene
import com.hippo.ehviewer.mvp.MvpPaper
import com.hippo.ehviewer.mvp.MvpPen
import com.hippo.ehviewer.slice.DrawerPaper
import com.hippo.ehviewer.slice.DrawerPen
import com.hippo.ehviewer.slice.DumpPen
import com.hippo.ehviewer.slice.GalleryListPen
import com.hippo.ehviewer.slice.ToolbarPaper
import com.hippo.ehviewer.slice.ToolbarPen
import com.hippo.ehviewer.slice.drawer
import com.hippo.ehviewer.slice.galleryList
import com.hippo.ehviewer.slice.papers
import com.hippo.ehviewer.slice.pens
import com.hippo.ehviewer.slice.setTitle
import com.hippo.ehviewer.slice.toolbar
import com.hippo.ehviewer.widget.Drawer
/*
* Created by Hippo on 2017/7/24.
*/
class MainScene : EhvScene() {
private val drawer: DrawerPen = object : DrawerPen() {}
private val toolbar: ToolbarPen = object : ToolbarPen() {
override fun onDoubleClick() {
galleryList.refresh()
}
override fun onClickMenuItem(item: MenuItem): Boolean = when (item.itemId) {
R.id.main_action_search -> {
// TODO
true
}
R.id.main_action_go_to -> {
// TODO
true
}
R.id.main_action_detail -> {
EHV_PREFERENCES.listMode.value = LIST_MODE_DETAIL
true
}
R.id.main_action_brief -> {
EHV_PREFERENCES.listMode.value = LIST_MODE_BRIEF
true
}
else -> super.onClickMenuItem(item)
}
override fun onClickNavigationIcon() {
drawer.toggleLeftDrawer()
}
}
private val galleryList: GalleryListPen = object : GalleryListPen() {
override fun showMessage(message: String) {
(activity as? EhvActivity)?.snack(message)
}
override fun onClickGalleryInfo(info: GalleryInfo) {
stage?.pushScene(galleryDetail(info))
}
}
private lateinit var pen: DumpPen
override fun createPen(args: Bundle): MvpPen<*> = pens(drawer, toolbar, galleryList) {
drawer.setDrawerContentMode(Drawer.FIT)
drawer.setLeftDrawerMode(Drawer.NONE)
drawer.setRightDrawerMode(Drawer.ACTION_BAR)
drawer.setLeftDrawerShadow(R.drawable.drawer_left_shadow)
drawer.setRightDrawerShadow(R.drawable.drawer_right_shadow)
drawer.setStatusBarAttrColor(R.attr.colorPrimaryDark)
toolbar.setDoubleClickEnabled()
toolbar.setNavigationIcon(R.drawable.menu_dark_x24)
// Register menu updater
EHV_PREFERENCES.listMode.observable.register {
when (it) {
// If inflating menu at once, the text in dialog will change at once, that looks bad
LIST_MODE_DETAIL -> schedule({ toolbar.inflateMenu(R.menu.main_detail) }, 200)
LIST_MODE_BRIEF -> schedule({ toolbar.inflateMenu(R.menu.main_brief) }, 200)
}
}
// Register title updater
galleryList.builderObservable.register { toolbar.setTitle(it.toTitle()) }
}.apply { pen = this }
override fun createPaper(): MvpPaper<*> = papers(pen) {
drawer(drawer, it) {
toolbar(toolbar, DrawerPaper.CONTAINER_ID_CONTENT) {
galleryList(galleryList, ToolbarPaper.CONTAINER_ID)
}
}
}
}
@@ -0,0 +1,41 @@
/*
* Copyright 2017 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.scene
import android.os.Bundle
import com.hippo.ehviewer.client.GLUrlBuilder
import com.hippo.ehviewer.client.data.GalleryInfo
/*
* Created by Hippo on 2017/8/6.
*/
fun galleryList(builder: GLUrlBuilder): GalleryListScene {
val args = Bundle()
args.putParcelable(GalleryListScene.KEY_GL_URL_BUILDER, builder)
val scene = GalleryListScene()
scene.setArgs(args)
return scene
}
fun galleryDetail(info: GalleryInfo): GalleryDetailScene {
val args = Bundle()
args.putParcelable(GalleryDetailScene.KEY_GALLERY_INFO, info)
val scene = GalleryDetailScene()
scene.setArgs(args)
return scene
}
@@ -0,0 +1,49 @@
/*
* Copyright 2017 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.slice
import com.hippo.ehviewer.mvp.EhvPen
import com.hippo.ehviewer.mvp.MvpLogic
import com.hippo.viewstate.ViewState
/*
* Created by Hippo on 2017/7/24.
*/
interface DrawerLogic : MvpLogic<DrawerUi> {
fun onOpenLeftDrawer()
fun onOpenRightDrawer()
fun onCloseLeftDrawer()
fun onCloseRightDrawer()
}
open class DrawerPen private constructor(
val state: DrawerUiState
) : EhvPen<DrawerUi>(), DrawerLogic, DrawerUi by state {
constructor() : this(DrawerUiState())
override fun createViewState(): ViewState<DrawerUi> = state
override fun onOpenLeftDrawer() {}
override fun onOpenRightDrawer() {}
override fun onCloseLeftDrawer() {}
override fun onCloseRightDrawer() {}
}
@@ -0,0 +1,208 @@
/*
* Copyright 2017 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.slice
import android.support.annotation.AttrRes
import android.support.annotation.DimenRes
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hippo.drawerlayout.DrawerLayout
import com.hippo.ehviewer.R
import com.hippo.ehviewer.mvp.GroupPaper
import com.hippo.ehviewer.mvp.MvpUi
import com.hippo.ehviewer.util.attrColor
import com.hippo.ehviewer.util.color
import com.hippo.ehviewer.util.dimensionPixelSize
import com.hippo.ehviewer.util.find
import com.hippo.ehviewer.widget.Drawer
import com.hippo.viewstate.GenerateViewState
import com.hippo.viewstate.strategy.SingleByMethod
import com.hippo.viewstate.strategy.SingleByTag
import com.hippo.viewstate.strategy.StrategyType
/*
* Created by Hippo on 2017/7/24.
*/
@GenerateViewState
interface DrawerUi : MvpUi {
companion object {
private const val TAG_STATUS_BAR_COLOR = "DrawerUi:status_bar_color"
}
@StrategyType(value = SingleByMethod::class)
fun setLeftDrawerWidth(@DimenRes resId: Int)
@StrategyType(value = SingleByMethod::class)
fun setRightDrawerWidth(@DimenRes resId: Int)
@StrategyType(value = SingleByMethod::class)
fun setDrawerContentMode(mode: Int)
@StrategyType(value = SingleByMethod::class)
fun setLeftDrawerMode(mode: Int)
@StrategyType(value = SingleByMethod::class)
fun setRightDrawerMode(mode: Int)
@StrategyType(value = SingleByMethod::class)
fun setLeftDrawerShadow(resId: Int)
@StrategyType(value = SingleByMethod::class)
fun setRightDrawerShadow(resId: Int)
fun closeDrawers()
fun closeLeftDrawer()
fun closeRightDrawer()
fun openLeftDrawer()
fun openRightDrawer()
fun toggleLeftDrawer()
fun toggleRightDrawer()
@StrategyType(value = SingleByTag::class, tag = TAG_STATUS_BAR_COLOR)
fun setStatusBarColor(@AttrRes id: Int)
@StrategyType(value = SingleByTag::class, tag = TAG_STATUS_BAR_COLOR)
fun setStatusBarAttrColor(@AttrRes id: Int)
}
class DrawerPaper(
private val logic: DrawerLogic
) : GroupPaper<DrawerUi>(logic), DrawerUi {
companion object {
const val CONTAINER_ID_CONTENT = R.id.drawer_content
const val CONTAINER_ID_LEFT = R.id.left_drawer
const val CONTAINER_ID_RIGHT = R.id.right_drawer
}
private lateinit var drawerLayout: DrawerLayout
private lateinit var drawerContent: Drawer
private lateinit var leftDrawer: Drawer
private lateinit var rightDrawer: Drawer
override fun onCreate(inflater: LayoutInflater, container: ViewGroup) {
super.onCreate(inflater, container)
view = inflater.inflate(R.layout.paper_drawer, container, false)
drawerLayout = view.find(R.id.drawer_layout)
drawerContent = view.find(R.id.drawer_content)
leftDrawer = view.find(R.id.left_drawer)
rightDrawer = view.find(R.id.right_drawer)
drawerLayout.setDrawerListener(object : DrawerLayout.DrawerListener {
override fun onDrawerStateChanged(view: View?, state: Int) {}
override fun onDrawerSlide(view: View?, percent: Float) {}
override fun onDrawerClosed(view: View?) {
when (view) {
leftDrawer -> logic.onCloseLeftDrawer()
rightDrawer -> logic.onCloseRightDrawer()
}
}
override fun onDrawerOpened(view: View?) {
when (view) {
leftDrawer -> logic.onOpenLeftDrawer()
rightDrawer -> logic.onOpenRightDrawer()
}
}
})
}
override fun setLeftDrawerWidth(resId: Int) {
leftDrawer.layoutParams.width = context.dimensionPixelSize(resId)
leftDrawer.requestLayout()
}
override fun setRightDrawerWidth(resId: Int) {
rightDrawer.layoutParams.width = context.dimensionPixelSize(resId)
rightDrawer.requestLayout()
}
override fun setDrawerContentMode(mode: Int) {
drawerContent.mode = mode
}
override fun setLeftDrawerMode(mode: Int) {
leftDrawer.mode = mode
}
override fun setRightDrawerMode(mode: Int) {
rightDrawer.mode = mode
}
override fun setLeftDrawerShadow(resId: Int) {
drawerLayout.setDrawerShadow(resId, Gravity.LEFT)
}
override fun setRightDrawerShadow(resId: Int) {
drawerLayout.setDrawerShadow(resId, Gravity.RIGHT)
}
override fun closeDrawers() {
drawerLayout.closeDrawers()
}
override fun closeLeftDrawer() {
drawerLayout.closeDrawer(Gravity.LEFT)
}
override fun closeRightDrawer() {
drawerLayout.closeDrawer(Gravity.RIGHT)
}
override fun openLeftDrawer() {
drawerLayout.openDrawer(Gravity.LEFT)
}
override fun openRightDrawer() {
drawerLayout.openDrawer(Gravity.RIGHT)
}
override fun toggleLeftDrawer() {
if (drawerLayout.isDrawerOpen(Gravity.LEFT)) {
drawerLayout.closeDrawer(Gravity.LEFT)
} else {
drawerLayout.openDrawer(Gravity.LEFT)
}
}
override fun toggleRightDrawer() {
if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
drawerLayout.closeDrawer(Gravity.RIGHT)
} else {
drawerLayout.openDrawer(Gravity.RIGHT)
}
}
override fun setStatusBarColor(id: Int) {
drawerLayout.statusBarColor = context.color(id)
}
override fun setStatusBarAttrColor(id: Int) {
drawerLayout.statusBarColor = context.attrColor(id)
}
}
@@ -0,0 +1,39 @@
/*
* Copyright 2017 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.slice
import com.hippo.ehviewer.mvp.GroupPaper
import com.hippo.ehviewer.mvp.GroupPen
import com.hippo.ehviewer.mvp.MvpLogic
import com.hippo.ehviewer.mvp.MvpUi
import com.hippo.viewstate.GenerateViewState
import com.hippo.viewstate.ViewState
/*
* Created by Hippo on 2017/7/24.
*/
@GenerateViewState
interface DumpUi : MvpUi
interface DumpLogic : MvpLogic<DumpUi>
open class DumpPaper(logic: DumpLogic) : GroupPaper<DumpUi>(logic), DumpUi
open class DumpPen : GroupPen<DumpUi>(), DumpLogic {
override fun createViewState(): ViewState<DumpUi> = DumpUiState()
}
@@ -0,0 +1,61 @@
/*
* Copyright 2017 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.slice
import com.hippo.ehviewer.EH_CLIENT
import com.hippo.ehviewer.EH_URL
import com.hippo.ehviewer.client.data.GalleryInfo
import com.hippo.ehviewer.mvp.EhvPen
import com.hippo.ehviewer.mvp.MvpLogic
import com.hippo.viewstate.ViewState
import io.reactivex.android.schedulers.AndroidSchedulers
/*
* Created by Hippo on 2017/8/5.
*/
interface GalleryDetailLogic : MvpLogic<GalleryDetailUi> {
fun onClickTag(namespace: String, tag: String)
}
open class GalleryDetailPen private constructor(
val state: GalleryDetailUiState
) : EhvPen<GalleryDetailUi>(), GalleryDetailLogic, GalleryDetailUi by state {
constructor() : this(GalleryDetailUiState())
override fun createViewState(): ViewState<GalleryDetailUi> = state
override fun onClickTag(namespace: String, tag: String) {}
fun init(info: GalleryInfo) {
showContent(info, false)
showContentProgress(false)
EH_CLIENT.galleryDetail(EH_URL.galleryDetailUrl(info.gid, info.token))
.observeOn(AndroidSchedulers.mainThread())
.register({ (info, comments) ->
showContentBody(info, comments, true)
}, {
showContentTip(it, true)
})
}
fun init(gid: Long, token: String) {
}
}
@@ -0,0 +1,256 @@
/*
* Copyright 2017 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.slice
import android.graphics.Color
import android.support.v7.widget.Toolbar
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.google.android.flexbox.FlexboxLayout
import com.hippo.ehviewer.R
import com.hippo.ehviewer.client.data.Comment
import com.hippo.ehviewer.client.data.GalleryInfo
import com.hippo.ehviewer.client.data.TagSet
import com.hippo.ehviewer.client.lang
import com.hippo.ehviewer.drawable.RoundRectDrawable
import com.hippo.ehviewer.mvp.EhvPaper
import com.hippo.ehviewer.mvp.MvpUi
import com.hippo.ehviewer.util.attrColor
import com.hippo.ehviewer.util.clamp
import com.hippo.ehviewer.util.dp2pix
import com.hippo.ehviewer.util.drawable
import com.hippo.ehviewer.util.explain
import com.hippo.ehviewer.util.explainVividly
import com.hippo.ehviewer.util.find
import com.hippo.ehviewer.util.fromHtml
import com.hippo.ehviewer.util.prettyTime
import com.hippo.ehviewer.util.string
import com.hippo.ehviewer.widget.ViewTransition
import com.hippo.ehviewer.widget.ehv.EhvCover
import com.hippo.ehviewer.widget.ehv.EhvDetailPants
import com.hippo.viewstate.GenerateViewState
import com.hippo.viewstate.strategy.SingleByTag
import com.hippo.viewstate.strategy.StrategyType
/*
* Created by Hippo on 2017/8/5.
*/
@GenerateViewState
interface GalleryDetailUi : MvpUi {
companion object {
private const val TAG_SHOW = "GalleryDetailUi:show"
private const val TAG_SHOW_CONTENT = "GalleryDetailUi:show_content"
}
@StrategyType(value = SingleByTag::class, tag = TAG_SHOW)
fun showContent(info: GalleryInfo, animation: Boolean)
@StrategyType(value = SingleByTag::class, tag = TAG_SHOW)
fun showTip(error: Throwable, animation: Boolean)
@StrategyType(value = SingleByTag::class, tag = TAG_SHOW)
fun showProgress(animation: Boolean)
@StrategyType(value = SingleByTag::class, tag = TAG_SHOW_CONTENT)
fun showContentBody(info: GalleryInfo, comments: List<Comment>, animation: Boolean)
@StrategyType(value = SingleByTag::class, tag = TAG_SHOW_CONTENT)
fun showContentTip(error: Throwable, animation: Boolean)
@StrategyType(value = SingleByTag::class, tag = TAG_SHOW_CONTENT)
fun showContentProgress(animation: Boolean)
}
class GalleryDetailPaper(
private val logic: GalleryDetailLogic
) : EhvPaper<GalleryDetailPaper>(logic), GalleryDetailUi {
lateinit var content: ViewGroup
lateinit var tip: ViewGroup
lateinit var progress: ViewGroup
lateinit var transition: ViewTransition
lateinit var contentBody: View
lateinit var contentTip: TextView
lateinit var contentProgress: View
lateinit var contentTransition: ViewTransition
override fun onCreate(inflater: LayoutInflater, container: ViewGroup) {
super.onCreate(inflater, container)
view = inflater.inflate(R.layout.paper_gallery_detail, container, false)
content = view.find<ViewGroup>(R.id.content)
tip = view.find<ViewGroup>(R.id.tip)
progress = view.find<ViewGroup>(R.id.progress)
transition = ViewTransition(content, tip, progress)
contentBody = view.find(R.id.content_body)
contentTip = view.find(R.id.content_tip)
contentProgress = view.find(R.id.content_progress)
contentTransition = ViewTransition(contentBody, contentTip, contentProgress)
}
override fun showTip(error: Throwable, animation: Boolean) {
transition.show(tip, animation && !logic.isRestoring())
tip.find<TextView>(R.id.tip_view).apply {
text = explain(error, context)
val drawable = explainVividly(error, context)
drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
setCompoundDrawables(null, drawable, null, null)
}
}
override fun showProgress(animation: Boolean) {
transition.show(progress, animation && !logic.isRestoring())
}
@Suppress("DEPRECATION")
override fun showContent(info: GalleryInfo, animation: Boolean) {
transition.show(content, animation && !logic.isRestoring())
content.find<EhvDetailPants>(R.id.pants).info = info
content.find<EhvCover>(R.id.cover).info = info
content.find<TextView>(R.id.title).text = info.title
content.find<TextView>(R.id.uploader).text = info.uploader
content.find<View>(R.id.download).apply {
setBackgroundDrawable(RoundRectDrawable(
radius = 2.dp2pix(context).toFloat(),
color = Color.WHITE,
edgeWidth = 2.dp2pix(context).toFloat(),
edgeColor = context.attrColor(R.attr.colorAccent)
))
}
content.find<View>(R.id.read).apply {
setBackgroundDrawable(RoundRectDrawable(
radius = 2.dp2pix(context).toFloat(),
color = context.attrColor(R.attr.colorAccent)
))
}
content.find<Toolbar>(R.id.toolbar).apply {
setNavigationIcon(R.drawable.arrow_left_dark_x24)
inflateMenu(R.menu.gallery_detail)
}
}
private fun Float.rating() : String =
if (this != 0.0f) String.format("%.1f", this) else "|∀゚"
private fun Float.ratingText() : String {
val id = if (this == 0.0f) R.string.rating_none
else when (Math.ceil((this * 2).toDouble()).toInt().clamp(0, 10)) {
10 -> R.string.rating_10
9 -> R.string.rating_9
8 -> R.string.rating_8
7 -> R.string.rating_7
6 -> R.string.rating_6
5 -> R.string.rating_5
4 -> R.string.rating_4
3 -> R.string.rating_3
2 -> R.string.rating_2
1 -> R.string.rating_1
0 -> R.string.rating_0
else -> R.string.rating_none
}
return context.string(id)
}
private fun FlexboxLayout.inflateTags(tags: TagSet) {
removeAllViews()
for ((namespace, list) in tags) {
val namespaceView = inflater.inflate(R.layout.gallery_detail_tags_namespace, this, false) as TextView
namespaceView.text = namespace
addView(namespaceView)
for (tag in list) {
val tagView = inflater.inflate(R.layout.gallery_detail_tags_tag, this, false) as TextView
tagView.text = tag
tagView.setOnClickListener { logic.onClickTag(namespace, tag) }
addView(tagView)
}
}
}
private fun ViewGroup.inflateComments(comments: List<Comment>) {
for (i in 0 until minOf(2, comments.size)) {
val comment = comments[i]
val view = inflater.inflate(R.layout.gallery_detail_comments_item, this, false) as ViewGroup
view.find<TextView>(R.id.user).text = comment.user
view.find<TextView>(R.id.date).text = comment.date.prettyTime(context)
view.find<TextView>(R.id.comment).text = comment.comment?.fromHtml()
addView(view, i)
}
view.find<TextView>(R.id.comments_tip).text = context.string(
if (comments.isEmpty()) R.string.gallery_detail_no_comment
else R.string.gallery_detail_more_comments
)
}
override fun showContentBody(info: GalleryInfo, comments: List<Comment>, animation: Boolean) {
contentTransition.show(contentBody, animation && !logic.isRestoring())
content.find<TextView>(R.id.language).text = info.language.lang().let { if (it != 0) it else R.string.language_unknown }.let { context.string(it) }
content.find<TextView>(R.id.pages).text = context.string(R.string.gallery_detail_pages_value, info.pages)
content.find<TextView>(R.id.favourited).text = context.string(R.string.gallery_detail_favourited_value, info.favourited)
content.find<TextView>(R.id.date).text = info.date.prettyTime(context)
content.find<TextView>(R.id.rating).text = info.rating.rating()
content.find<TextView>(R.id.rating_text).text = info.rating.ratingText()
content.find<TextView>(R.id.rated).let { rated ->
rated.text = info.rated.toString()
val drawable = context.drawable(R.drawable.account_primary_x16)
drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
rated.setCompoundDrawables(null, null, drawable, null)
}
content.find<ImageView>(R.id.rate).let { rate ->
val id = if (info.rating >= 2.5f || info.rating == 0.0f) R.drawable.thumb_up_primary_x32 else R.drawable.thumb_down_primary_x32
val drawable = context.drawable(id)
rate.setImageDrawable(drawable)
}
if (info.tags.isEmpty()) {
content.find<FlexboxLayout>(R.id.tags).visibility = View.GONE
content.find<TextView>(R.id.no_tag).visibility = View.VISIBLE
} else {
content.find<FlexboxLayout>(R.id.tags).let { tags ->
tags.visibility = View.VISIBLE
tags.inflateTags(info.tags)
}
content.find<TextView>(R.id.no_tag).visibility = View.GONE
}
content.find<ViewGroup>(R.id.comments).inflateComments(comments)
}
override fun showContentTip(error: Throwable, animation: Boolean) {
contentTransition.show(contentTip, animation && !logic.isRestoring())
contentTip.apply {
text = explain(error, context)
val drawable = explainVividly(error, context)
drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
setCompoundDrawables(null, drawable, null, null)
}
}
override fun showContentProgress(animation: Boolean) {
contentTransition.show(contentProgress, animation && !logic.isRestoring())
}
}
@@ -0,0 +1,136 @@
/*
* Copyright 2017 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.slice
import com.hippo.ehviewer.EHV_PREFERENCES
import com.hippo.ehviewer.EH_CLIENT
import com.hippo.ehviewer.EH_URL
import com.hippo.ehviewer.LIST_MODE_BRIEF
import com.hippo.ehviewer.LIST_MODE_DETAIL
import com.hippo.ehviewer.client.GLUrlBuilder
import com.hippo.ehviewer.client.data.GalleryInfo
import com.hippo.ehviewer.mvp.EhvPen
import com.hippo.ehviewer.mvp.MvpLogic
import com.hippo.ehviewer.widget.content.ContentData
import com.hippo.ehviewer.widget.content.ContentDataAdapter
import com.hippo.ehviewer.widget.content.ContentLayout
import com.hippo.viewstate.ViewState
import com.jakewharton.rxrelay2.BehaviorRelay
import com.jakewharton.rxrelay2.Relay
import io.reactivex.android.schedulers.AndroidSchedulers
/*
* Created by Hippo on 2017/7/24.
*/
interface GalleryListLogic : MvpLogic<GalleryListUi> {
fun initAdapter(adapter: ContentDataAdapter<GalleryInfo, *>)
fun termAdapter(adapter: ContentDataAdapter<GalleryInfo, *>)
fun initContentLayout(layout: ContentLayout)
fun termContentLayout(layout: ContentLayout)
fun showMessage(message: String)
fun onClickGalleryInfo(info: GalleryInfo)
}
open class GalleryListPen private constructor(
val state: GalleryListUiState
) : EhvPen<GalleryListUi>(), GalleryListLogic, GalleryListUi by state {
constructor() : this (GalleryListUiState())
private val data = GalleryData()
private val builder = GLUrlBuilder()
val builderObservable: Relay<GLUrlBuilder> = BehaviorRelay.createDefault(builder)
override fun onCreate() {
super.onCreate()
EHV_PREFERENCES.listMode.observable.register {
when (it) {
LIST_MODE_DETAIL -> view.asDetailList()
LIST_MODE_BRIEF -> view.asBriefGrid()
}
}
// `observeOn(AndroidSchedulers.mainThread())` to make sure
// it works after `EH_CLIENT` and `EH_URL` changes
EHV_PREFERENCES.ehMode.observable.observeOn(AndroidSchedulers.mainThread()).register {
data.goTo(0)
}
}
override fun createViewState(): ViewState<GalleryListUi> = state
override fun initAdapter(adapter: ContentDataAdapter<GalleryInfo, *>) {
adapter.data = data
adapter.notifyDataSetChanged()
}
override fun termAdapter(adapter: ContentDataAdapter<GalleryInfo, *>) {}
override fun initContentLayout(layout: ContentLayout) {
layout.logic = data
data.attach(layout)
}
override fun termContentLayout(layout: ContentLayout) {
data.detach()
}
override fun showMessage(message: String) {}
override fun onClickGalleryInfo(info: GalleryInfo) {}
fun refresh() {
data.goTo(0)
}
fun apply(builder: GLUrlBuilder) {
this.builder.set(builder)
builderObservable.accept(this.builder)
}
private inner class GalleryData : ContentData<GalleryInfo>() {
override fun onRequireData(id: Int, page: Int) {
builder.page = page
EH_CLIENT.galleryList(EH_URL.galleryListUrl(builder.build()))
.observeOn(AndroidSchedulers.mainThread())
.register({ (data, pages) ->
setData(id, data, pages)
}, {
setError(id, it)
})
}
override fun onRestoreData(id: Int) {
// TODO("not implemented")
}
override fun onBackupData(data: List<GalleryInfo>) {
// TODO("not implemented")
}
override fun isDuplicate(t1: GalleryInfo, t2: GalleryInfo): Boolean = t1.gid == t2.gid
}
}
@@ -0,0 +1,218 @@
/*
* Copyright 2017 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.slice
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.hippo.ehviewer.EHV_PREFERENCES
import com.hippo.ehviewer.R
import com.hippo.ehviewer.client.categoryColor
import com.hippo.ehviewer.client.categoryStringNonNull
import com.hippo.ehviewer.client.data.GalleryInfo
import com.hippo.ehviewer.client.langAbbr
import com.hippo.ehviewer.mvp.EhvPaper
import com.hippo.ehviewer.mvp.MvpUi
import com.hippo.ehviewer.util.INVALID_INDEX
import com.hippo.ehviewer.util.dp2pix
import com.hippo.ehviewer.util.find
import com.hippo.ehviewer.util.prettyTime
import com.hippo.ehviewer.util.string
import com.hippo.ehviewer.widget.NumberRatingView
import com.hippo.ehviewer.widget.SmallRatingView
import com.hippo.ehviewer.widget.content.ContentDataAdapter
import com.hippo.ehviewer.widget.content.ContentLayout
import com.hippo.ehviewer.widget.ehv.EhvCover
import com.hippo.ehviewer.widget.recyclerview.AutoGridLayoutManager
import com.hippo.ehviewer.widget.recyclerview.MarginItemDecoration
import com.hippo.viewstate.GenerateViewState
import com.hippo.viewstate.strategy.SingleByTag
import com.hippo.viewstate.strategy.StrategyType
/*
* Created by Hippo on 2017/7/24.
*/
@GenerateViewState
interface GalleryListUi : MvpUi {
companion object {
private const val TAG_MODE = "GalleryListUi:mode"
}
@StrategyType(value = SingleByTag::class, tag = TAG_MODE)
fun asDetailList()
@StrategyType(value = SingleByTag::class, tag = TAG_MODE)
fun asBriefGrid()
}
class GalleryListPaper(
private val logic: GalleryListLogic
) : EhvPaper<GalleryListPaper>(logic), GalleryListUi, ContentLayout.Extension {
private lateinit var contentLayout: ContentLayout
private lateinit var recyclerView: RecyclerView
private lateinit var layoutManager: AutoGridLayoutManager
private val detailAdapter by lazy { GalleryDetailAdapter() }
private val briefAdapter by lazy { GalleryBriefAdapter() }
private var hasInitAdapter = false
private lateinit var adapter: ContentDataAdapter<GalleryInfo, *>
private val detailDecoration by lazy { DividerItemDecoration(context, DividerItemDecoration.VERTICAL) }
private val briefDecoration by lazy { MarginItemDecoration(1.dp2pix(context)) }
private var hasInitDecoration = false
private lateinit var decoration: RecyclerView.ItemDecoration
override fun onCreate(inflater: LayoutInflater, container: ViewGroup) {
super.onCreate(inflater, container)
view = inflater.inflate(R.layout.paper_gallery_list, container, false)
contentLayout = view.find(R.id.content_layout)
recyclerView = view.find(R.id.recycler_view)
contentLayout.extension = this
logic.initContentLayout(contentLayout)
layoutManager = AutoGridLayoutManager(context)
recyclerView.layoutManager = layoutManager
}
override fun onDestroy() {
super.onDestroy()
logic.termAdapter(adapter)
logic.termContentLayout(contentLayout)
recyclerView.layoutManager = null
recyclerView.adapter = null
}
private fun setRecyclerViewStyle(
newAdapter: ContentDataAdapter<GalleryInfo, *>,
newDecoration: RecyclerView.ItemDecoration,
columnSize: Int,
padding: Int
) {
if (hasInitAdapter) {
logic.termAdapter(adapter)
}
hasInitAdapter = true
adapter = newAdapter
logic.initAdapter(newAdapter)
// RecyclerView will scroll to top after change adapter
// Just save the first visible item position, and scroll to it
val position = layoutManager.findFirstVisibleItemPosition()
recyclerView.adapter = newAdapter
if (position != INVALID_INDEX) {
layoutManager.scrollToPosition(position)
}
if (hasInitDecoration) {
recyclerView.removeItemDecoration(decoration)
}
hasInitDecoration = true
decoration = newDecoration
recyclerView.addItemDecoration(newDecoration)
layoutManager.setColumnSize(columnSize)
(recyclerView.layoutParams as ViewGroup.MarginLayoutParams).apply {
leftMargin = padding
topMargin = padding
rightMargin = padding
bottomMargin = padding
}
recyclerView.requestLayout()
}
override fun asDetailList() = setRecyclerViewStyle(detailAdapter, detailDecoration, EHV_PREFERENCES.detailWidth.value.dp2pix(context), 0)
override fun asBriefGrid() = setRecyclerViewStyle(briefAdapter, briefDecoration, EHV_PREFERENCES.briefWidth.value.dp2pix(context), -(1.dp2pix(context)))
override fun showMessage(message: String) {
logic.showMessage(message)
}
private inner class GalleryDetailHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val cover = itemView.find<EhvCover>(R.id.cover)
val title = itemView.find<TextView>(R.id.title)
val uploader = itemView.find<TextView>(R.id.uploader)
val rating = itemView.find<SmallRatingView>(R.id.rating)
val category = itemView.find<TextView>(R.id.category)
val date = itemView.find<TextView>(R.id.date)
val language = itemView.find<TextView>(R.id.language)
val item: GalleryInfo? get() = adapterPosition.takeIf { it in 0 until adapter.size }?.let { adapter[it] }
init {
itemView.setOnClickListener { item?.let { logic.onClickGalleryInfo(it) } }
}
}
private inner class GalleryDetailAdapter : ContentDataAdapter<GalleryInfo, GalleryDetailHolder>() {
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): GalleryDetailHolder =
GalleryDetailHolder(inflater.inflate(R.layout.gallery_list_item_detail, parent, false))
override fun onBindViewHolder(holder: GalleryDetailHolder, position: Int) {
val info = get(position)
holder.cover.info = info
holder.title.text = info.title
holder.uploader.text = info.uploader
holder.rating.rating = info.rating
holder.category.text = info.category.categoryStringNonNull()
holder.category.setBackgroundColor(info.category.categoryColor())
holder.date.text = info.date.prettyTime(context)
holder.language.text = info.language.langAbbr().let { if (it != 0) context.string(it) else null }
}
}
private inner class GalleryBriefHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val cover = itemView.find<EhvCover>(R.id.cover)
val category = itemView.find<View>(R.id.category)
val rating = itemView.find<NumberRatingView>(R.id.rating)
val language = itemView.find<TextView>(R.id.language)
val item: GalleryInfo? get() = adapterPosition.takeIf { it in 0 until adapter.size }?.let { adapter[it] }
init {
itemView.setOnClickListener { item?.let { logic.onClickGalleryInfo(it) } }
}
}
private inner class GalleryBriefAdapter : ContentDataAdapter<GalleryInfo, GalleryBriefHolder>() {
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): GalleryBriefHolder =
GalleryBriefHolder(inflater.inflate(R.layout.gallery_list_item_brief, parent, false))
override fun onBindViewHolder(holder: GalleryBriefHolder, position: Int) {
val info = get(position)
holder.cover.info = info
holder.category.setBackgroundColor(info.category.categoryColor() and 0xffffff or 0xa2000000.toInt())
holder.rating.rating = info.rating
holder.language.text = info.language.langAbbr().let { if (it != 0) context.string(it) else null }
}
}
}
@@ -0,0 +1,89 @@
/*
* Copyright 2017 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.slice
import android.view.LayoutInflater
import android.view.ViewGroup
import com.hippo.ehviewer.mvp.GroupPaper
import com.hippo.ehviewer.mvp.MvpPaper
/*
* Created by Hippo on 2017/7/24.
*/
fun papers(
logic: DumpLogic,
onCreate: GroupPaper<DumpUi>.(ViewGroup) -> MvpPaper<*>
) = object : DumpPaper(logic) {
override fun onCreate(inflater: LayoutInflater, container: ViewGroup) {
super.onCreate(inflater, container)
val paper = onCreate(container)
addChild(paper)
view = paper.view
}
}
fun GroupPaper<*>.drawer(
logic: DrawerLogic,
container: ViewGroup,
init: DrawerPaper.() -> Unit
) = DrawerPaper(logic).also { it.create(inflater, container); it.init() }
fun GroupPaper<*>.drawer(
logic: DrawerLogic,
containerId: Int,
init: DrawerPaper.() -> Unit
) = inflateChild(containerId) { container -> DrawerPaper(logic).also { it.create(inflater, container) } }.apply { init() }
fun GroupPaper<*>.statusBar(
logic: StatusBarLogic,
container: ViewGroup,
init: StatusBarPaper.() -> Unit
) = StatusBarPaper(logic).also { it.create(inflater, container); it.init() }
fun GroupPaper<*>.statusBar(
logic: StatusBarLogic,
containerId: Int,
init: StatusBarPaper.() -> Unit
) = inflateChild(containerId) { container -> StatusBarPaper(logic).also { it.create(inflater, container) } }.apply { init() }
fun GroupPaper<*>.toolbar(
logic: ToolbarLogic,
container: ViewGroup,
init: ToolbarPaper.() -> Unit
) = ToolbarPaper(logic).also { it.create(inflater, container); it.init() }
fun GroupPaper<*>.toolbar(
logic: ToolbarLogic,
containerId: Int,
init: ToolbarPaper.() -> Unit
) = inflateChild(containerId) { container -> ToolbarPaper(logic).also { it.create(inflater, container) } }.apply { init() }
fun GroupPaper<*>.galleryList(
logic: GalleryListLogic,
containerId: Int
) = inflateChild(containerId) { container -> GalleryListPaper(logic).also { it.create(inflater, container) } }
fun GroupPaper<*>.galleryDetail(
logic: GalleryDetailLogic,
container: ViewGroup
) = GalleryDetailPaper(logic).also { it.create(inflater, container) }
fun GroupPaper<*>.galleryDetail(
logic: GalleryDetailLogic,
containerId: Int
) = inflateChild(containerId) { container -> GalleryDetailPaper(logic).also { it.create(inflater, container) } }
@@ -0,0 +1,34 @@
/*
* Copyright 2017 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.slice
import com.hippo.ehviewer.mvp.EhvPen
/*
* Created by Hippo on 2017/7/14.
*/
fun pens(vararg pens: EhvPen<*>, init: DumpPen.() -> Unit): DumpPen = object : DumpPen() {
init {
pens.forEach { addChild(it) }
}
override fun onCreate() {
super.onCreate()
init()
}
}
@@ -0,0 +1,39 @@
/*
* Copyright 2017 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.slice
import com.hippo.ehviewer.mvp.EhvPen
import com.hippo.ehviewer.mvp.MvpLogic
import com.hippo.viewstate.ViewState
/*
* Created by Hippo on 2017/8/5.
*/
interface ScrollLogic : MvpLogic<ScrollUi> {
fun onScrollChange(scrollX: Int, scrollY: Int)
}
open class ScrollPen private constructor(
val state: ScrollUiState
) : EhvPen<ScrollUi>(), ScrollLogic, ScrollUi by state {
constructor() : this(ScrollUiState())
override fun createViewState(): ViewState<ScrollUi> = state
override fun onScrollChange(scrollX: Int, scrollY: Int) {}
}
@@ -0,0 +1,63 @@
/*
* Copyright 2017 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.slice
import android.support.v4.widget.NestedScrollView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.hippo.ehviewer.R
import com.hippo.ehviewer.mvp.GroupPaper
import com.hippo.ehviewer.mvp.MvpUi
import com.hippo.ehviewer.util.find
import com.hippo.viewstate.GenerateViewState
import com.hippo.viewstate.strategy.SingleByMethod
import com.hippo.viewstate.strategy.StrategyType
/*
* Created by Hippo on 2017/8/5.
*/
@GenerateViewState
interface ScrollUi : MvpUi {
@StrategyType(value = SingleByMethod::class)
fun setScrollChangeEnabled()
}
class ScrollPaper(
private val logic: ScrollLogic
) : GroupPaper<ScrollPaper>(logic), ScrollUi {
companion object {
const val CONTAINER_ID = R.id.scroll_container
}
private lateinit var scroll: NestedScrollView
override fun onCreate(inflater: LayoutInflater, container: ViewGroup) {
super.onCreate(inflater, container)
view = inflater.inflate(R.layout.paper_scroll, container, false)
scroll = view.find(R.id.scroll)
}
override fun setScrollChangeEnabled() {
scroll.setOnScrollChangeListener { _: NestedScrollView?, scrollX: Int, scrollY: Int, _: Int, _: Int ->
logic.onScrollChange(scrollX, scrollY)
}
}
}
@@ -0,0 +1,35 @@
/*
* Copyright 2017 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.slice
import com.hippo.ehviewer.mvp.EhvPen
import com.hippo.ehviewer.mvp.MvpLogic
import com.hippo.viewstate.ViewState
/*
* Created by Hippo on 2017/8/6.
*/
interface StatusBarLogic : MvpLogic<StatusBarUi>
open class StatusBarPen private constructor(
val state: StatusBarUiState
) : EhvPen<StatusBarUi>(), StatusBarLogic, StatusBarUi by state {
constructor() : this(StatusBarUiState())
override fun createViewState(): ViewState<StatusBarUi> = state
}
@@ -0,0 +1,64 @@
/*
* Copyright 2017 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.slice
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.WindowInsets
import android.widget.LinearLayout
import com.hippo.ehviewer.R
import com.hippo.ehviewer.mvp.GroupPaper
import com.hippo.ehviewer.mvp.MvpUi
import com.hippo.viewstate.GenerateViewState
/*
* Created by Hippo on 2017/8/6.
*/
@GenerateViewState
interface StatusBarUi : MvpUi
class StatusBarPaper(
private val logic: StatusBarLogic
) : GroupPaper<StatusBarPaper>(logic), StatusBarUi {
companion object {
const val CONTAINER_ID = R.id.status_bar_container
}
override fun onCreate(inflater: LayoutInflater, container: ViewGroup) {
super.onCreate(inflater, container)
view = inflater.inflate(R.layout.paper_status_bar, container, false)
}
class StatusBarLayout : LinearLayout {
constructor(context: Context): super(context)
constructor(context: Context, attrs: AttributeSet?): super(context, attrs)
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getChildAt(0)?.layoutParams?.height = insets.systemWindowInsetTop
insets.consumeSystemWindowInsets()
}
return insets
}
}
}
@@ -0,0 +1,47 @@
/*
* Copyright 2017 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.slice
import android.view.MenuItem
import com.hippo.ehviewer.mvp.EhvPen
import com.hippo.ehviewer.mvp.MvpLogic
import com.hippo.viewstate.ViewState
/*
* Created by Hippo on 2017/7/24.
*/
interface ToolbarLogic : MvpLogic<ToolbarUi> {
fun onClickNavigationIcon()
fun onClickMenuItem(item: MenuItem): Boolean
fun onDoubleClick()
}
open class ToolbarPen private constructor(
val state: ToolbarUiState
) : EhvPen<ToolbarUi>(), ToolbarLogic, ToolbarUi by state {
constructor() : this(ToolbarUiState())
override fun createViewState(): ViewState<ToolbarUi> = state
override fun onClickNavigationIcon() {}
override fun onClickMenuItem(item: MenuItem): Boolean { return false }
override fun onDoubleClick() {}
}
@@ -0,0 +1,136 @@
/*
* Copyright 2017 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.slice
import android.graphics.drawable.Drawable
import android.support.v7.widget.Toolbar
import android.view.GestureDetector
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.ViewGroup
import com.hippo.ehviewer.R
import com.hippo.ehviewer.mvp.GroupPaper
import com.hippo.ehviewer.mvp.MvpUi
import com.hippo.ehviewer.util.find
import com.hippo.viewstate.GenerateViewState
import com.hippo.viewstate.strategy.SingleByMethod
import com.hippo.viewstate.strategy.SingleByTag
import com.hippo.viewstate.strategy.StrategyType
/*
* Created by Hippo on 2017/7/24.
*/
@GenerateViewState
interface ToolbarUi : MvpUi {
companion object {
private const val TAG_SET_TITLE = "ToolbarUi:set_title"
private const val TAG_SET_SUBTITLE = "ToolbarUi:set_subtitle"
private const val TAG_SET_NAVIGATION_ICON = "ToolbarUi:set_navigation_icon"
}
@StrategyType(value = SingleByTag::class, tag = TAG_SET_TITLE)
fun setTitle(title: CharSequence?)
@StrategyType(value = SingleByTag::class, tag = TAG_SET_TITLE)
fun setTitle(resId: Int)
@StrategyType(value = SingleByTag::class, tag = TAG_SET_SUBTITLE)
fun setSubtitle(subtitle: CharSequence)
@StrategyType(value = SingleByTag::class, tag = TAG_SET_SUBTITLE)
fun setSubtitle(resId: Int)
@StrategyType(value = SingleByTag::class, tag = TAG_SET_NAVIGATION_ICON)
fun setNavigationIcon(icon: Drawable)
@StrategyType(value = SingleByTag::class, tag = TAG_SET_NAVIGATION_ICON)
fun setNavigationIcon(resId: Int)
@StrategyType(value = SingleByMethod::class)
fun setDoubleClickEnabled()
@StrategyType(value = SingleByMethod::class)
fun inflateMenu(resId: Int)
}
fun ToolbarUi.setTitle(title: Any) {
when (title) {
is String -> setTitle(title)
is Int -> setTitle(title)
}
}
class ToolbarPaper(
private val logic: ToolbarLogic
) : GroupPaper<ToolbarPaper>(logic), ToolbarUi {
companion object {
const val CONTAINER_ID = R.id.toolbar_container
}
private lateinit var toolbar: Toolbar
override fun onCreate(inflater: LayoutInflater, container: ViewGroup) {
super.onCreate(inflater, container)
view = inflater.inflate(R.layout.paper_toolbar, container, false)
toolbar = view.find(R.id.toolbar)
toolbar.setNavigationOnClickListener { logic.onClickNavigationIcon() }
toolbar.setOnMenuItemClickListener { logic.onClickMenuItem(it) }
}
override fun setTitle(title: CharSequence?) {
toolbar.title = title
}
override fun setTitle(resId: Int) {
toolbar.setTitle(resId)
}
override fun setSubtitle(subtitle: CharSequence) {
toolbar.subtitle = subtitle
}
override fun setSubtitle(resId: Int) {
toolbar.setSubtitle(resId)
}
override fun setNavigationIcon(icon: Drawable) {
toolbar.navigationIcon = icon
}
override fun setNavigationIcon(resId: Int) {
toolbar.setNavigationIcon(resId)
}
override fun setDoubleClickEnabled() {
val detector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onDoubleTap(e: MotionEvent?): Boolean {
logic.onDoubleClick()
return true
}
})
toolbar.setOnTouchListener { _, event -> detector.onTouchEvent(event) }
}
override fun inflateMenu(resId: Int) {
toolbar.menu.clear()
toolbar.inflateMenu(resId)
}
}
@@ -0,0 +1,26 @@
/*
* Copyright 2017 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.util
import android.app.Activity
import android.view.View
/*
* Created by Hippo on 2017/7/23.
*/
inline fun <reified T : View> Activity.find(id: Int): T = findViewById(id) as T
@@ -0,0 +1,105 @@
/*
* Copyright 2017 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.util
import android.view.animation.Interpolator
/*
* Created by Hippo on 6/7/2017.
*/
/**
* User-driving animation.
*/
abstract class Animate {
companion object {
const private val ANIMATION_START = -1L
const private val NO_ANIMATION = -2L
const val INFINITE = -1L
}
/** Animation duration, must be greater than 0 **/
var duration: Long = 300L
set(value) { check(value > 0L, { "Duration must be greater than 0" }).let { field = value } }
/** Animation interpolator **/
var interpolator: Interpolator? = null
/** Animation repeat times, must be greater than 0, or INFINITE **/
var repeat: Long = 1
set(value) { check(value > 0L || value == INFINITE, { "Repeat must be greater than 0, or INFINITE" }).let { field = value } }
private var startTime: Long = NO_ANIMATION
private var runCount: Long = 0L
/**
* Starts the animation. If the animation is started, ignore it.
*/
fun start() {
if (startTime == NO_ANIMATION) {
startTime = ANIMATION_START
runCount = 0L
}
}
/**
* Cancels the animation. If the animation isn't started, ignore it.
*/
fun cancel() {
if (startTime != NO_ANIMATION) {
startTime = NO_ANIMATION
onEnd()
}
}
/**
* Drives the animation. If the animation isn't started, ignore it.
*/
fun calculate(current: Long): Boolean {
check(current >= 0L, { "`current` must be greater than or equal 0" })
if (startTime == NO_ANIMATION) {
return false
}
if (startTime == ANIMATION_START) {
startTime = current
} else {
check(current >= startTime, { "`current` must be greater than or equal `startTime`" })
}
val elapse = current - startTime
runCount += elapse / duration
val end = repeat != INFINITE && runCount >= repeat
val factor = if (end) 1.0f else (elapse % duration) / duration.toFloat()
onCalculate(interpolator?.getInterpolation(factor) ?: factor)
if (end) {
onEnd()
startTime = NO_ANIMATION
}
return startTime != NO_ANIMATION
}
/** Called when calculated. **/
protected abstract fun onCalculate(progress: Float)
/** Called when end **/
open fun onEnd() {}
}
@@ -0,0 +1,245 @@
package com.hippo.ehviewer.util;
import android.graphics.Bitmap;
/**
* Created by jay on 11/7/15.
*/
public class Blur {
public static Bitmap blur(Bitmap sentBitmap, int radius, boolean canReuseInBitmap) {
// Stack Blur v1.0 from
// http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
//
// Java Author: Mario Klingemann <mario at quasimondo.com>
// http://incubator.quasimondo.com
// created Feburary 29, 2004
// Android port : Yahel Bouaziz <yahel at kayenko.com>
// http://www.kayenko.com
// ported april 5th, 2012
// This is a compromise between Gaussian Blur and Box blur
// It creates much better looking blurs than Box Blur, but is
// 7x faster than my Gaussian Blur implementation.
//
// I called it Stack Blur because this describes best how this
// filter works internally: it creates a kind of moving stack
// of colors whilst scanning through the image. Thereby it
// just has to add one new block of color to the right side
// of the stack and remove the leftmost color. The remaining
// colors on the topmost layer of the stack are either added on
// or reduced by one, depending on if they are on the right or
// on the left side of the stack.
//
// If you are using this algorithm in your code please add
// the following line:
//
// Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>
Bitmap bitmap;
if (canReuseInBitmap) {
bitmap = sentBitmap;
} else {
bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
}
if (radius < 1) {
return (null);
}
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int[] pix = new int[w * h];
bitmap.getPixels(pix, 0, w, 0, 0, w, h);
int wm = w - 1;
int hm = h - 1;
int wh = w * h;
int div = radius + radius + 1;
int r[] = new int[wh];
int g[] = new int[wh];
int b[] = new int[wh];
int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
int vmin[] = new int[Math.max(w, h)];
int divsum = (div + 1) >> 1;
divsum *= divsum;
int dv[] = new int[256 * divsum];
for (i = 0; i < 256 * divsum; i++) {
dv[i] = (i / divsum);
}
yw = yi = 0;
int[][] stack = new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
int r1 = radius + 1;
int routsum, goutsum, boutsum;
int rinsum, ginsum, binsum;
for (y = 0; y < h; y++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
for (i = -radius; i <= radius; i++) {
p = pix[yi + Math.min(wm, Math.max(i, 0))];
sir = stack[i + radius];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rbs = r1 - Math.abs(i);
rsum += sir[0] * rbs;
gsum += sir[1] * rbs;
bsum += sir[2] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
}
stackpointer = radius;
for (x = 0; x < w; x++) {
r[yi] = dv[rsum];
g[yi] = dv[gsum];
b[yi] = dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (y == 0) {
vmin[x] = Math.min(x + radius + 1, wm);
}
p = pix[yw + vmin[x]];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[(stackpointer) % div];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi++;
}
yw += w;
}
for (x = 0; x < w; x++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
yp = -radius * w;
for (i = -radius; i <= radius; i++) {
yi = Math.max(0, yp) + x;
sir = stack[i + radius];
sir[0] = r[yi];
sir[1] = g[yi];
sir[2] = b[yi];
rbs = r1 - Math.abs(i);
rsum += r[yi] * rbs;
gsum += g[yi] * rbs;
bsum += b[yi] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
if (i < hm) {
yp += w;
}
}
yi = x;
stackpointer = radius;
for (y = 0; y < h; y++) {
// Preserve alpha channel: ( 0xff000000 & pix[yi] )
pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (x == 0) {
vmin[y] = Math.min(y + r1, hm) * w;
}
p = x + vmin[y];
sir[0] = r[p];
sir[1] = g[p];
sir[2] = b[p];
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[stackpointer];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi += w;
}
}
bitmap.setPixels(pix, 0, w, 0, 0, w, h);
return (bitmap);
}
}
@@ -0,0 +1,45 @@
/*
* Copyright 2017 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.util
/*
* Created by Hippo on 2017/7/24.
*/
/**
* Performs the given [action] on each element. ANDs all results and returns it.
*/
inline fun <T> Iterable<T>.forEachAny(action: (T) -> Boolean): Boolean {
var result = false
for (element in this) {
result = action(element) || result
}
return result
}
/**
* Performs the given [action] on each entry. Remove the entry if return `true`.
*/
inline fun <K, V> MutableMap<K, V>.forEachRemove(action: (K, V) -> Boolean ) {
val iterator = entries.iterator()
while (iterator.hasNext()) {
val entry = iterator.next()
if (action(entry.key, entry.value)) {
iterator.remove()
}
}
}
@@ -0,0 +1,29 @@
/*
* Copyright 2017 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.util
/*
* Created by Hippo on 2017/7/24.
*/
const val INVALID_ID = 0
const val INVALID_INDEX = -1
const val DURATION_WHOLE = 375L
const val DURATION_IN = 225L
const val DURATION_OUT = 195L
@@ -0,0 +1,78 @@
/*
* Copyright 2017 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.
*/
@file:Suppress("NOTHING_TO_INLINE")
package com.hippo.ehviewer.util
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.drawable.Drawable
import android.support.annotation.AttrRes
import android.support.annotation.BoolRes
import android.support.annotation.ColorRes
import android.support.annotation.DimenRes
import android.support.annotation.DrawableRes
import android.support.annotation.IntegerRes
import android.support.annotation.PluralsRes
import android.support.annotation.StringRes
import android.support.v4.content.ContextCompat
import android.support.v7.content.res.AppCompatResources
import com.hippo.android.resource.AttrResources
/*
* Created by Hippo on 2017/7/18.
*/
inline fun Context.boolean(@BoolRes id: Int): Boolean = resources.getBoolean(id)
inline fun Context.integer(@IntegerRes id: Int): Int = resources.getInteger(id)
inline fun Context.dimension(@DimenRes id: Int): Float = resources.getDimension(id)
inline fun Context.dimensionPixelOffset(@DimenRes id: Int): Int = resources.getDimensionPixelOffset(id)
inline fun Context.dimensionPixelSize(@DimenRes id: Int): Int = resources.getDimensionPixelSize(id)
inline fun Context.color(@ColorRes id: Int): Int = ContextCompat.getColor(this, id)
inline fun Context.colorStateList(@ColorRes id: Int): ColorStateList = AppCompatResources.getColorStateList(this, id)
inline fun Context.drawable(@DrawableRes id: Int): Drawable = AppCompatResources.getDrawable(this, id)!!
inline fun Context.string(@StringRes id: Int): String = resources.getString(id)
inline fun Context.string(@StringRes id: Int, vararg formatArgs: Any): String = resources.getString(id, *formatArgs)
inline fun Context.quantityString(@PluralsRes id: Int, quantity: Int): String = resources.getQuantityString(id, quantity)
inline fun Context.quantityString(@PluralsRes id: Int, quantity: Int, vararg formatArgs: Any): String = resources.getQuantityString(id, quantity, *formatArgs)
inline fun Context.attrBoolean(@AttrRes id: Int): Boolean = AttrResources.getAttrBoolean(this, id)
inline fun Context.attrInteger(@AttrRes id: Int): Int = AttrResources.getAttrInteger(this, id)
inline fun Context.attrDimension(@AttrRes id: Int): Float = AttrResources.getAttrDimension(this, id)
inline fun Context.attrDimensionPixelOffset(@AttrRes id: Int): Int = AttrResources.getAttrDimensionPixelOffset(this, id)
inline fun Context.attrDimensionPixelSize(@AttrRes id: Int): Int = AttrResources.getAttrDimensionPixelSize(this, id)
inline fun Context.attrColor(@AttrRes id: Int): Int = AttrResources.getAttrColor(this, id)
inline fun Context.attrColorStateList(@AttrRes id: Int): ColorStateList = AttrResources.getAttrColorStateList(this, id)
inline fun Context.attrDrawable(@AttrRes id: Int): Drawable = AttrResources.getAttrDrawable(this, id)
@@ -0,0 +1,78 @@
/*
* Copyright 2017 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.util
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
/*
* Created by Hippo on 2017/8/13.
*/
private inline fun <T> Cursor.getValue(
column: String,
defValue: T,
getter: Cursor.(Int) -> T
): T {
try {
val index = getColumnIndex(column)
if (index != -1) {
return getter(index)
}
} catch (e: Throwable) {}
return defValue
}
/** Gets boolean value for special column from the `cursor`. */
fun Cursor.getBoolean(column: String, defValue: Boolean): Boolean =
getValue(column, if (defValue) 1 else 0, Cursor::getInt) != 0
/** Gets int value for special column from the `cursor`. */
fun Cursor.getInt(column: String, defValue: Int): Int =
getValue(column, defValue, Cursor::getInt)
/** Gets long value for special column from the `cursor`. */
fun Cursor.getLong(column: String, defValue: Long): Long =
getValue(column, defValue, Cursor::getLong)
/** Gets float value for special column from the `cursor`. */
fun Cursor.getFloat(column: String, defValue: Float): Float =
getValue(column, defValue, Cursor::getFloat)
/** Gets string value for special column from the `cursor`. */
fun Cursor.getString(column: String, defValue: String?): String? =
getValue(column, defValue, Cursor::getString)
/** Runs the provided SQL and executes the given [block] on each row. */
inline fun SQLiteDatabase.rawQuery(sql: String, selectionArgs: Array<String>?, block: (Cursor) -> Unit) {
val cursor = rawQuery(sql, selectionArgs)
cursor.use {
while (it.moveToNext()) {
block(cursor)
}
}
}
/** Executes the given [block] function in transaction. */
inline fun <R> SQLiteDatabase.transaction(block: (SQLiteDatabase) -> R): R {
beginTransaction()
try {
return block(this).also { setTransactionSuccessful() }
} finally {
endTransaction()
}
}
@@ -0,0 +1,27 @@
/*
* Copyright 2017 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.util
import android.graphics.drawable.Drawable
/*
* Created by Hippo on 2017/7/24.
*/
const val MAX_LEVEL = 10000
fun Drawable.setSelfBounds() = setBounds(0, 0, intrinsicWidth, intrinsicHeight)
@@ -0,0 +1,62 @@
/*
* Copyright 2017 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.util
import android.content.Context
import android.graphics.drawable.Drawable
import com.hippo.ehviewer.R
import com.hippo.ehviewer.exception.GeneralException
import com.hippo.ehviewer.exception.ParseException
import com.hippo.ehviewer.exception.PresetException
import com.hippo.ehviewer.exception.ResponseCodeException
import com.hippo.ehviewer.exception.SadPandaException
import java.io.InterruptedIOException
import java.net.MalformedURLException
import java.net.ProtocolException
import java.net.SocketException
import java.net.UnknownHostException
import javax.net.ssl.SSLException
/*
* Created by Hippo on 2017/7/24.
*/
/**
* Explains the exception with a String.
*/
fun explain(error: Throwable, context: Context): String = when {
error is GeneralException -> error.message
error is PresetException -> context.string(error.text)
error is ParseException -> context.string(R.string.error_parse)
error is SadPandaException -> context.string(R.string.error_sad_panda)
error is ResponseCodeException -> context.string(R.string.error_response_code, error.code)
error is MalformedURLException -> context.string(R.string.error_invalid_url)
error is InterruptedIOException -> context.string(R.string.error_timeout)
error is UnknownHostException -> context.string(R.string.error_unknown_host)
(error is ProtocolException) && (error.message?.startsWith("Too many follow-up requests:") ?: false) ->
context.string(R.string.error_redirection)
error is ProtocolException || error is SocketException || error is SSLException -> context.string(R.string.error_socket)
else -> context.string(R.string.error_unknown).apply { error.printStackTrace() }
}
/**
* Explains the exception with a Drawable.
*/
fun explainVividly(error: Throwable, context: Context): Drawable = when {
(error is PresetException) && (error.icon != 0) -> context.drawable(error.icon)
else -> context.drawable(R.drawable.emoticon_confused_primary_x64)
}
@@ -0,0 +1,25 @@
/*
* Copyright 2017 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.util
import android.content.Context
/*
* Created by Hippo on 2017/7/24.
*/
fun Int.dp2pix(context: Context) = (this * context.resources.displayMetrics.density + 0.5f).toInt()
@@ -0,0 +1,253 @@
/*
* Copyright 2017 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.util
import java.util.Random
/*
* Created by Hippo on 6/7/2017.
*/
/**
* Returns the absolute value.
*/
fun Long.abs() = Math.abs(this)
/**
* Clamped the `Int` to the range &#91;bound1, bound2&#93; if bound2 &gt;= bound1,
* otherwise &#91;bound2, bound1&#93;.
*/
fun Int.clamp(bound1: Int, bound2: Int): Int {
if (bound2 >= bound1) {
if (this > bound2) return bound2
if (this < bound1) return bound1
} else {
if (this > bound1) return bound1
if (this < bound2) return bound2
}
return this
}
/**
* Clamped the `Long` to the range &#91;bound1, bound2&#93; if bound2 &gt;= bound1,
* otherwise &#91;bound2, bound1&#93;.
*/
fun Long.clamp(bound1: Long, bound2: Long): Long {
if (bound2 >= bound1) {
if (this > bound2) return bound2
if (this < bound1) return bound1
} else {
if (this > bound1) return bound1
if (this < bound2) return bound2
}
return this
}
/**
* Clamped the `Float` to the range &#91;bound1, bound2&#93; if bound2 &gt;= bound1,
* otherwise &#91;bound2, bound1&#93;.
*
* Returns [Float.NaN] if any of `bound1` and `bound2` is [Float.NaN].
*/
fun Float.clamp(bound1: Float, bound2: Float): Float {
if (bound1.isNaN() || bound2.isNaN()) return Float.NaN
if (bound2 >= bound1) {
if (this > bound2) return bound2
if (this < bound1) return bound1
} else {
if (this > bound1) return bound1
if (this < bound2) return bound2
}
return this
}
/**
* Calculates a linear interpolation between two inputs.
*/
fun Float.lerp(from: Float, to: Float) = from + this * (to - from)
fun Int.delerp(from: Int, to: Int) = if (from == to) 1.0f else (this - from).toFloat() / (to - from).toFloat()
fun Float.delerp(from: Float, to: Float) = if (from == to) 1.0f else (this - from) / (to - from)
/**
* Returns the largest (closest to positive infinity)
* `int` value that is less than or equal to the algebraic quotient.
*
* @param x the dividend
* @param y the divisor
* @return the quotient
*/
fun floorDiv(x: Int, y: Int): Int {
var r = x / y
// if the signs are different and modulo not zero, round down
if (x xor y < 0 && r * y != x) {
--r
}
return r
}
/**
* Returns the largest (closest to positive infinity)
* `long` value that is less than or equal to the algebraic quotient.
*
* @param x the dividend
* @param y the divisor
* @return the quotient
*/
fun floorDiv(x: Long, y: Long): Long {
var r = x / y
// if the signs are different and modulo not zero, round down
if (x xor y < 0 && r * y != x) {
--r
}
return r
}
/**
* Returns the floor modulus of the `int` arguments.
*
* The relationship between `floorDiv` and `floorMod` is such that:
* * `floorDiv(x, y) * y + floorMod(x, y) == x`
*
* @param x the dividend
* @param y the divisor
* @return the remainder
*/
fun floorMod(x: Int, y: Int): Int {
return x - floorDiv(x, y) * y
}
/**
* Returns the floor modulus of the `long` arguments.
*
* The relationship between `floorDiv` and `floorMod` is such that:
* * `floorDiv(x, y) * y + floorMod(x, y) == x`
*
* @param x the dividend
* @param y the divisor
* @return the remainder
*/
fun floorMod(x: Long, y: Long): Long {
return x - floorDiv(x, y) * y
}
/**
* Returns the smallest (closest to positive infinity)
* `int` value that is greater than or equal to the algebraic quotient.
*
* @param x the dividend
* @param y the divisor
* @return the quotient
*/
fun ceilDiv(x: Int, y: Int): Int {
return -floorDiv(-x, y)
}
/**
* Returns the smallest (closest to positive infinity)
* `long` value that is greater than or equal to the algebraic quotient.
*
* @param x the dividend
* @param y the divisor
* @return the quotient
*/
fun ceilDiv(x: Long, y: Long): Long {
return -floorDiv(-x, y)
}
/**
* Returns the ceil modulus of the `int` arguments.
*
* The relationship between `ceilDiv` and `ceilMod` is such that:
* * `ceilDiv(x, y) * y + ceilMod(x, y) == x`
*
* @param x the dividend
* @param y the divisor
* @return the remainder
*/
fun ceilMod(x: Int, y: Int): Int {
return x - ceilDiv(x, y) * y
}
/**
* Returns the ceil modulus of the `long` arguments.
*
* The relationship between `ceilDiv` and `ceilMod` is such that:
* * `ceilDiv(x, y) * y + ceilMod(x, y) == x`
*
* @param x the dividend
* @param y the divisor
* @return the remainder
*/
fun ceilMod(x: Long, y: Long): Long {
return x - ceilDiv(x, y) * y
}
private val random = Random()
/**
* Returns a pseudo-random uniformly distributed `int`
* in the half-open range [0, howbig).
* @param howbig the upper bound (exclusive), must be positive
* *
* @return a random `int`
* *
* @throws IllegalArgumentException if howbig &lt;= 0
*/
@Throws(IllegalArgumentException::class)
fun random(howbig: Int): Int {
return random.nextInt(howbig)
}
/**
* Returns a pseudo-random uniformly distributed `int`
* in the half-open range [howsmall, howbig).
*
* @param howsmall the lower bound (inclusive)
* @param howbig the upper bound (exclusive)
*
* @return a random `int`
*
* @throws IllegalArgumentException if howbig &lt;= howsmall
*/
@Throws(IllegalArgumentException::class)
fun random(howsmall: Int, howbig: Int): Int {
if (howsmall >= howbig) {
throw IllegalArgumentException("howsmall >= howbig: $howsmall >= $howbig")
}
var r = random.nextInt()
val n = howbig - howsmall
val m = n - 1
if (n and m == 0)
r = (r and m) + howsmall
else if (n > 0) {
var u = r.ushr(1)
r = u % n
while (u + m - r < 0) {
u = random.nextInt().ushr(1)
r = u % n
}
r += howsmall
} else {
while (r < howsmall || r >= howbig)
r = random.nextInt()
}
return r
}
@@ -0,0 +1,23 @@
/*
* Copyright 2017 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.util
/*
* Created by Hippo on 2017/7/14.
*/
class MutableAny<T>(var value: T?)
@@ -0,0 +1,23 @@
/*
* Copyright 2017 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.util
/*
* Created by Hippo on 2017/8/3.
*/
class MutableBoolean(var value: Boolean)
@@ -0,0 +1,158 @@
/*
* Copyright 2017 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.util
import com.hippo.ehviewer.network.SimpleResponseBody
import io.reactivex.Single
import okhttp3.Response
import okio.Buffer
import okio.Okio
import okio.Sink
import okio.Source
import okio.Timeout
import java.io.IOException
/*
* Created by Hippo on 2017/7/23.
*/
/** Injects checker to check whether response body is fully read. **/
fun Single<Response>.check(result: MutableBoolean): Single<Response> = map { response ->
val body = response.body()!!
val contentLength = body.contentLength()
if (contentLength != -1L) {
result.value = false
val source = body.source()
val checkSource = object : Source {
private var read: Long = 0L
override fun read(sink: Buffer, byteCount: Long): Long = source.read(sink, byteCount).also { single ->
if (single != -1L) {
read += single
}
result.value = read == contentLength
}
override fun close() = source.close().also { result.value = read == contentLength }
override fun timeout(): Timeout = source.timeout()
}
response.newBuilder()
.body(SimpleResponseBody(response.headers(), Okio.buffer(checkSource)))
.build()
} else {
// No content length, can't check it, always set true
result.value = true
response
}
}
interface RequestProgress {
fun onUpdateProgress(single: Long, read: Long, total: Long)
}
/** Injects a progress indicator to the response body. **/
fun Single<Response>.progress(progress: (single: Long, read: Long, total: Long) -> Unit): Single<Response> = map { response ->
val body = response.body()!!
val contentLength = body.contentLength()
if (contentLength > 0) {
val source = body.source()
val progressSource = object : Source {
private var read: Long = 0L
override fun read(sink: Buffer, byteCount: Long): Long = source.read(sink, byteCount).also { single ->
if (single != -1L) {
read += single
progress(single, read, contentLength)
}
}
override fun close() = source.close()
override fun timeout(): Timeout = source.timeout()
}
response.newBuilder()
.body(SimpleResponseBody(response.headers(), Okio.buffer(progressSource)))
.build()
} else {
// No valid content length, just return original response
response
}
}
interface ResponseCache {
fun body(): Sink
fun abort()
}
/**
* Injects a cache to save response body.
*
* @param cache the cache to save response body
*/
fun Single<Response>.cache(cache: ResponseCache): Single<Response> = map { response ->
val source = response.body()!!.source()
val cacheBody = Okio.buffer(cache.body())
val cacheSource = object : Source {
private var cacheClosed: Boolean = false
override fun read(sink: Buffer, byteCount: Long): Long {
val bytesRead: Long
try {
bytesRead = source.read(sink, byteCount)
} catch (e: IOException) {
if (!cacheClosed) {
cacheClosed = true
cache.abort() // Failed to write a complete cache response.
}
throw e
}
if (bytesRead == -1L) {
if (!cacheClosed) {
cacheClosed = true
cacheBody.close() // The cache response is complete!
}
return -1L
}
sink.copyTo(cacheBody.buffer(), sink.size() - bytesRead, bytesRead)
cacheBody.emitCompleteSegments()
return bytesRead
}
override fun close() = source.close().also {
if (!cacheClosed) {
cacheClosed = true
cache.abort()
}
}
override fun timeout(): Timeout = source.timeout()
}
response.newBuilder()
.body(SimpleResponseBody(response.headers(), Okio.buffer(cacheSource)))
.build()
}
Loaded 100 of 218 files, more files were not shown because too many files have changed in this diff. Show more