Compare commits

...
392 Commits
Author SHA1 Message Date
seven332 2667bacd9d 1.2.1 2018-10-27 13:55:56 +08:00
seven332 7967f289b7 Fix preference header background 2018-10-27 12:09:48 +08:00
seven332 31e1cb7e6d Fix gallery comments EditText bg color 2018-10-27 10:42:44 +08:00
seven332 a472d0509a 1.2.0 2018-10-25 20:08:37 +08:00
seven332 3f71a97cbd Change colorEdgeEffect 2018-10-25 19:26:06 +08:00
seven332 ed8c818d4f Adjust dark theme color 2018-10-25 18:40:27 +08:00
seven332 1db14cd998 Parse gallery list in thumbnail view 2018-10-25 16:02:04 +08:00
seven332 d06dd87ff4 Adjust text color 2018-10-25 14:32:26 +08:00
seven332 a31a64efd6 Revert textColor of ButtonInCard 2018-10-25 14:14:18 +08:00
seven332 cfa87a5a02 Adjust text color 2018-10-25 14:00:03 +08:00
seven332 2833691c34 Adjust text color 2018-10-25 13:37:25 +08:00
seven332 22d6ed8c39 Revert colorPrimary and colorAccent 2018-10-24 19:05:29 +08:00
seven332 110bae7cb7 Adjust progress view color 2018-10-22 13:45:15 +08:00
seven332 5bd7d6fae3 Adjust gallery detail header button background color 2018-10-22 13:35:59 +08:00
seven332 afa45fd8d9 Change black colorPrimary and colorAccent to grey_700 2018-10-22 13:08:16 +08:00
seven332 2c544607ec Add tagGroupBackgroundColor and tagBackgroundColor attribute 2018-10-22 13:05:38 +08:00
seven332 730b52d6cd Fix RatingBar color 2018-10-20 01:45:54 +08:00
seven332 0704579d26 Adjust card elevation 2018-10-20 01:41:20 +08:00
seven332 cb92fbad3d Don't finish the activity in second level of SettingsActivity 2018-10-19 23:07:45 +08:00
seven332 c7c6f8f706 Disable right swipe of HistoryScene 2018-10-19 23:04:06 +08:00
seven332 fdd81e21b1 Adjust card color 2018-10-19 22:54:02 +08:00
seven332 1093da6565 Update strings.xml 2018-10-19 22:13:12 +08:00
seven332 c625315a76 Apply theme to GalleryActivity 2018-10-19 22:09:04 +08:00
seven332 1deb4c2d6c Add dark widget color 2018-10-19 21:55:48 +08:00
seven332 9201b9baed Apply theme to dialog background 2018-10-19 21:52:43 +08:00
seven332 557bd9f54b Apply theme to play icon 2018-10-19 21:47:28 +08:00
seven332 0353dbdb27 Add activated color to reactive items 2018-10-19 21:45:13 +08:00
seven332 8b07cf62a9 Yellow RatingBar 2018-10-19 21:12:32 +08:00
seven332 111025cb98 Change colorControlActivated 2018-10-19 20:39:57 +08:00
seven332 b3d9c4c2b9 Apply theme to Security 2018-10-19 20:04:32 +08:00
seven332 f2695b6a2c Apply theme to some drawables 2018-10-19 19:39:52 +08:00
seven332 f6ec40e8ed Revert colorPrimary and colorAccent 2018-10-19 19:19:39 +08:00
seven332 9bc6920448 Add galleryDetailDivider attribute 2018-10-19 19:03:31 +08:00
seven332 abb8483723 Apply theme to Guides 2018-10-19 18:47:53 +08:00
seven332 81eadbb794 Apply theme to image_failed 2018-10-19 18:11:33 +08:00
seven332 22cc32778d Use system image in Html 2018-10-19 16:56:59 +08:00
seven332 c9d432b7c8 Change colorPrimary and colorAccent of dark theme and black theme 2018-10-19 16:48:53 +08:00
seven332 168a1dcfb2 Apply theme to text 2018-10-19 16:39:42 +08:00
seven332 b6718078f2 Add widgetColorThemePrimary and widgetColorThemeAccent attributes 2018-10-19 15:59:59 +08:00
seven332 960a7751ad Apply theme to ShadowLinearLayout 2018-10-19 15:34:22 +08:00
seven332 e5335de859 Apply theme to content color 2018-10-19 15:26:46 +08:00
seven332 1eb960eaf9 Clean theme 2018-10-19 14:57:09 +08:00
seven332 6bc9f0da64 Apply theme to big icons 2018-10-19 14:08:48 +08:00
seven332 f4d986a5bd Rename attributes
colorDivider -> dividerColor
colorToolbar -> toolbarColor
colorDrawablePrimary -> textColorThemeAccent
colorDrawableThemePrimary -> drawableColorPrimary
colorTextThemeAccent -> drawableColorThemePrimary
2018-10-19 13:56:33 +08:00
seven332 9aa22aab34 Apply theme to accent text 2018-10-18 23:08:31 +08:00
seven332 afa839ed0b Rename color drawable attribute
colorDrawableOpposite -> colorDrawablePrimary
colorDrawablePrimary -> colorDrawableThemePrimary
2018-10-18 23:01:57 +08:00
seven332 f2725331fe Fix duplicate clipboard text test 2018-10-18 22:20:55 +08:00
seven332 590963024a Apply theme to Ripple 2018-10-18 22:10:50 +08:00
seven332 1f55977182 Apply theme to the color of comment vote 2018-10-18 21:51:18 +08:00
seven332 4bed3d5b8e Rename colorXXXDrawable to colorDrawableXXX 2018-10-18 21:45:42 +08:00
seven332 7eab4e00e1 Replace @color/primary_text_light with ?android:attr/textColorPrimary 2018-10-18 21:39:28 +08:00
seven332 776813df17 Add colorPrimaryDrawable attribute 2018-10-18 21:36:22 +08:00
seven332 12beeedf29 Rename colorPrimaryDrawable to colorOppositeDrawable 2018-10-18 20:06:11 +08:00
seven332 d0e7f25fd9 Apply theme to AddDeleteDrawable and DrawerArrowDrawable 2018-10-18 19:58:50 +08:00
seven332 ab2a066992 Optimize themes.xml 2018-10-18 18:42:19 +08:00
seven332 596f95e463 Fix toolbarPopupTheme 2018-10-18 16:43:46 +08:00
seven332 79d07f98a8 Change Toolbar popup them 2018-10-18 15:53:42 +08:00
seven332 22ec2e8926 Change Toolbar background color 2018-10-18 15:33:53 +08:00
seven332 bc4d20d0a4 Fix SearchBar animations 2018-10-18 14:44:47 +08:00
seven332 84ed520c1c Change divider color 2018-10-18 14:37:59 +08:00
seven332 34eb6a423a Use CardView instead of card 9 png drawable 2018-10-18 13:28:07 +08:00
seven332 7dc1491c26 Use ?android:attr/windowBackground to draw background 2018-10-18 13:02:25 +08:00
seven332 6ecce9ddc5 Add dark theme and black theme 2018-10-18 12:56:56 +08:00
seven332 029373a8d2 Recreate all activities if theme changed 2018-10-18 12:44:43 +08:00
seven332 e8c06fd876 Add theme setting 2018-10-17 23:07:01 +08:00
seven332 8c9218e8af Use a non-reflect way to change how PreferenceActivity looks
Android P doesn't support invoking hidden API.
2018-10-15 22:31:53 +08:00
jerry855202 f922d41775 Fixed rCN text in rTW
"不允許螢幕抓取" was still rCN, fixed in this commit
2018-10-13 17:59:29 +08:00
seven332 e483105eb2 Android Studio 3.2.0 2018-10-10 18:26:20 +08:00
seven332 9aecb79b17 Calculate height of history item at runtime 2018-10-10 18:25:33 +08:00
seven332 bfc6bf07d9 Calculate height of download item at runtime 2018-10-10 15:51:39 +08:00
seven332 b671999e5a Calculate height of gallery list item at runtime 2018-10-10 13:13:20 +08:00
seven332 3ed2cb329c Remove the link of Google+ Community
Google+ is dying.
2018-10-09 15:20:05 +08:00
seven332 fe9970523f Avoid detecting current gallery 2018-09-23 16:00:30 +08:00
seven332 62944f7b71 Lint on release builds 2018-09-19 20:00:09 +08:00
seven332 a7e1101c87 Statement about about donation 2018-09-19 19:58:40 +08:00
seven332 b79d991b25 Set favoriteName null if isFavorited is false 2018-09-19 16:19:08 +08:00
seven332 10a15fc5cf fix: only update favoriteName after success 2018-09-19 15:50:37 +08:00
Tsukatsuki Kanade 428a5ab20e fix: change favoriteName b4 send request 2018-09-19 15:47:58 +08:00
Tsukatsuki Kanade b3d19d752b fix: update favoriteName after added favorite 2018-09-19 15:47:58 +08:00
Tsukatsuki Kanade 73b702aa56 feat: Add favorite gallery name to scene 2018-09-19 15:47:58 +08:00
hzy980512 3360035402 Fix choices of words 2018-09-18 10:19:26 +08:00
hzy980512 b97069a04e A little fix 2018-09-18 10:19:26 +08:00
hzy980512 9df8d050b2 Add some new translations 2018-09-18 10:19:26 +08:00
hzy980512 ba4ca96b77 Add some translations 2018-09-18 10:19:26 +08:00
hzy980512 fd93baf583 Add some new translations 2018-09-18 10:19:26 +08:00
hzy980512 0a9a1976cd Grammar fix 2018-09-18 10:19:26 +08:00
hzy980512 450e05c819 Make some sentences shorter 2018-09-18 10:19:26 +08:00
hzy980512 59d36d29da Fix some bugs, where quotes break the sentences 2018-09-18 10:19:26 +08:00
seven332 f0cd92f82e Check settings while try showing gallery page count 2018-09-17 11:34:32 +08:00
seven332 e847338ef4 Light background toolbar popup 2018-09-17 00:32:17 +08:00
seven332 23c34258ff Update strings.xml 2018-09-16 23:36:58 +08:00
seven332 d441960107 Update strings.xml 2018-09-16 23:35:53 +08:00
seven332 185ae6beb4 1.1.0 2018-09-16 22:18:06 +08:00
seven332 d84376e4dc Google style reorder icon 2018-09-16 22:12:26 +08:00
seven332 dcc6af3367 Update local favourites count 2018-09-14 19:48:48 +08:00
seven332 1cd8ef1b47 Back up gallery list moved from local favourites to cloud favourites 2018-09-14 19:35:02 +08:00
seven332 f8c5caf6bc Don't throw null exception 2018-09-14 19:15:39 +08:00
seven332 8e84b5b67b Update libraries 2018-09-14 13:33:32 +08:00
seven332 dc697af081 Show identity cookies 2018-09-14 13:32:03 +08:00
seven332 a69f36b652 Don't cache gif while reading
Update GLGallery
2018-09-02 14:53:33 +08:00
seven332 d5c788fe80 Add resetting reading progress 2018-09-02 01:25:43 +08:00
seven332 021fe45c8d Fix string format in zh-rTW translation 2018-09-01 20:56:43 +08:00
seven332 18881e549f Save gallery toke to saved filename 2018-08-15 21:54:35 +08:00
seven332 ed2f3510d8 Android Studio 3.1.4 2018-08-07 14:02:04 +08:00
seven332 5290340b97 Show gallery pages 2018-08-06 13:25:12 +08:00
hzy980512 9514d42032 Fix translations 2018-07-31 10:38:23 +08:00
hzy980512 2cc140eaf4 Translations fix 2018-07-31 10:38:23 +08:00
hzy980512 c4934fc89e Fix translations 2018-07-31 10:38:23 +08:00
seven332 7feb5552c1 Always print errors in EhEngine 2018-07-30 10:03:24 +08:00
seven332 fce659c41c Fix error_bad_status_code chinese string 2018-07-23 19:13:53 +08:00
seven332 2e899f5fa8 SSLException is network error 2018-07-20 14:03:43 +08:00
hzy980512 4580d781db Correct a typo 2018-07-18 12:14:16 +08:00
hzy980512 6fdab6f89c Fix a typo 2018-07-18 12:14:16 +08:00
hzy980512 145b6523e9 Fixed grammar 2018-07-18 12:14:16 +08:00
hzy980512 1d03d35685 Fix translation 2018-07-18 12:14:16 +08:00
hzy980512 71396bc632 Fix translation 2018-07-18 12:14:16 +08:00
hzy980512 511d70838a Fix more translations 2018-07-18 12:14:16 +08:00
hzy980512 1e31052767 Some fixes 2018-07-18 12:14:16 +08:00
hzy980512 e1c88c53f3 Some more corrections 2018-07-18 12:14:16 +08:00
hzy980512 de16081c79 Some corrections 2018-07-18 12:14:16 +08:00
hzy980512 e9d1ce1720 Some corrections 2018-07-18 12:14:16 +08:00
hzy980512 3bce3c41f2 Some corrections 2018-07-18 12:14:16 +08:00
hzy980512 c71729c560 Correcting sentences 2018-07-18 12:14:16 +08:00
seven332 3cbf5d0a8f Disable no media file checker at during startup 2018-07-16 13:56:07 +08:00
hzy980512 6f99f5a226 Fix translations 2018-07-12 16:48:34 +08:00
hzy980512 252dcb6175 Corrections 2018-07-12 16:48:34 +08:00
hzy980512 72971341b2 Corrections 2018-07-12 16:48:34 +08:00
hzy980512 32f4205240 Improved 2018-07-12 16:48:34 +08:00
hzy980512 36e66a8714 Grammar fix 2018-07-12 16:48:34 +08:00
hzy980512 7ee1777e7b More fixes of errors 2018-07-12 16:48:34 +08:00
hzy980512 d8dc9ad576 Fix of translation 2018-07-11 22:17:20 +08:00
hzy980512 8ae8842f81 A little fix of translation 2018-07-11 21:31:35 +08:00
hzy980512 ddb82292f9 Update strings.xml 2018-07-11 21:31:35 +08:00
hzy980512 83ade321bb A little fix 2018-07-11 21:31:35 +08:00
hzy980512 a4ea8a6bfc Add support for French and German translations 2018-07-11 21:31:35 +08:00
hzy980512 2d32852d18 Update Spanish translations (partly) 2018-07-11 21:31:35 +08:00
hzy980512 3ef3510ad3 Fix crash when there's an image in clipboard 2018-07-11 21:31:35 +08:00
hzy980512 82cb0eb7d6 Add strings for language switcher 2018-07-11 21:31:35 +08:00
hzy980512 2c428d3306 Add new languages to language switcher 2018-07-11 21:31:35 +08:00
hzy980512 5fa9e8677d Improve English translation 2018-07-11 21:31:35 +08:00
hzy980512 b57abfdc57 Add French and German translations 2018-07-11 21:31:35 +08:00
hzy980512 2f7906d3db Correct errors and update Japanese translation 2018-07-11 21:31:35 +08:00
seven332 d56f86b47e Show password toggle 2018-07-02 19:25:25 +08:00
seven332 e558be2b89 Disable clipboard check if the top scene is solid 2018-06-25 14:53:33 +08:00
seven332 66cab7b41e Close #417, click error text to refresh 2018-06-25 13:55:49 +08:00
seven332 4f431bb7ea Check ClipData null 2018-06-22 15:37:24 +08:00
seven332 d411623da6 Only save the hash code of the text in the clipboard 2018-06-21 13:42:53 +08:00
seven332 d121e839c9 Close #312, read gallery link from clipboard 2018-06-14 20:28:31 +08:00
seven332 c397bd0211 Close #276, save drawer view state 2018-06-13 15:18:48 +08:00
seven332 ec2782ddad Android Studio 3.1.3 2018-06-11 21:52:40 +08:00
scese250 6b6a60ae02 Updated spanish translation
Translated new options and updated some texts.

Thanks for keep working in this great app!!
2018-06-07 18:55:10 +08:00
seven332 f870674bd2 Use intent chooser when sharing 2018-06-05 21:03:59 +08:00
seven332 6af75a9758 1.0.30 2018-06-04 11:07:40 +08:00
seven332 e4fc925b04 Fix preview page estimation 2018-05-24 20:11:05 +08:00
seven332 2262779ba0 Close #396, fix preload pages calculation 2018-05-10 20:32:16 +08:00
lilymaniac b52cd2a619 Update Korean localization
Catch up to commit 8bad20e58c ("add option of disable auto update").
2018-05-02 22:03:06 +08:00
onlymash 8bad20e58c add option of disable auto update 2018-05-02 13:03:56 +08:00
seven332 30ca44b9c6 Android Studio 3.1.2 2018-04-28 22:47:30 +08:00
seven332 cf43ed965e Add Filter.hashCode() 2018-04-28 22:47:01 +08:00
onlymash dab29819bd make gradlew executable for linux 2018-04-28 22:29:50 +08:00
seven332 5fb090f241 No more mandatory check on igneous field 2018-04-20 09:15:59 +08:00
onlymash ff84c63445 update fav drawer 2018-04-10 22:13:37 +08:00
onlymash 140ace739e update support libs 2018-04-10 22:13:37 +08:00
onlymash 5f8c078367 rename recyclerview drawer layout 2018-04-10 22:13:37 +08:00
onlymash faddb37557 save favorites count 2018-04-10 22:13:37 +08:00
onlymash 5d8fe06d5c fix favories layout & count issue 2018-04-10 22:13:37 +08:00
seven332 2e34913c7d Android Studio 3.1.1 2018-04-10 22:10:10 +08:00
onlymash 6cc607469b update favorites list layout 2018-04-08 12:10:12 +08:00
onlymash 26eff55e6d update favorites right drawer layout 2018-04-08 12:10:12 +08:00
PYC 9a5743dd67 Correct the japanese sentence. 2018-04-02 12:02:32 +08:00
onlymash 0b547147b1 fix judgment issue 2018-04-02 11:56:56 +08:00
onlymash 6bd3bd5e80 fix judgment issue 2018-04-02 11:56:56 +08:00
onlymash af93a6730e update shortcut background 2018-03-29 19:30:58 +08:00
onlymash 27e4bd4e0b merge background color to color.xml 2018-03-29 19:30:58 +08:00
onlymash 459b27253a redraw shortcut icon 2018-03-29 19:30:58 +08:00
onlymash bb99570cd4 update shortcut foreground icon inset 2018-03-29 19:30:58 +08:00
onlymash 3f2b62c119 restore unifile 2018-03-29 19:30:58 +08:00
onlymash 91e9975a24 update shortcut 2018-03-29 19:30:58 +08:00
onlymash 00485efd0e update shortcut 2018-03-29 19:30:58 +08:00
onlymash c5d56243e0 update shortcut icon 2018-03-29 19:30:58 +08:00
onlymash b8c3229d9f add license to shortcut icon 2018-03-29 19:30:58 +08:00
onlymash 8cf935accc fix shortcuts 2018-03-29 19:30:58 +08:00
onlymash 2cf5589369 shortcuts: update icons 2018-03-29 19:30:58 +08:00
onlymash 89addaf211 update unifile 2018-03-29 19:30:58 +08:00
onlymash f5409c7b8a update shortcut 2018-03-29 19:30:58 +08:00
onlymash 733ddb5964 remove process 2018-03-29 19:30:58 +08:00
onlymash 537380eeb7 update shortcut categories 2018-03-29 19:30:58 +08:00
onlymash e44473f26b clean import 2018-03-29 19:30:58 +08:00
onlymash a503832016 update app shortcuts 2018-03-29 19:30:58 +08:00
onlymash 4935995342 update manifest 2018-03-29 19:30:58 +08:00
onlymash a367373c87 add shortcut icon for android 7.1 2018-03-29 19:30:58 +08:00
onlymash 62cd2e4809 add app shortcuts 2018-03-29 19:30:58 +08:00
seven332 7df7defa92 Save the images, which will be shared, to temp dir 2018-03-28 09:35:17 +08:00
seven332 56b42c67d5 Fix gallery favorite block 2018-03-27 18:06:05 +08:00
seven332 d1afcc2f54 Fix the parsing, language to Local 2018-03-27 17:09:09 +08:00
seven332 f6b05ed42b Fix strings 2018-03-27 16:51:01 +08:00
seven332 095334d338 Recreate all activities after changing app language 2018-03-27 14:01:05 +08:00
seven332 dac0ef178d Add RecordingApplication 2018-03-27 13:59:35 +08:00
seven332 c23a502e9e Add app language option 2018-03-27 13:40:58 +08:00
seven332 5ddd652076 Ignore past error while reading 2018-03-27 10:53:45 +08:00
seven332 3f9e3f620d Android Studio 3.1.0 2018-03-27 10:29:50 +08:00
seven332 1c62fe9615 1.0.29 2018-03-26 22:46:55 +08:00
seven332 8703102c97 Update UniFile 2018-03-26 22:45:45 +08:00
onlymash 28ab591769 update showPageDialog 2018-03-26 20:42:12 +08:00
onlymash 8cc2bfbced dynamically add dialog items 2018-03-26 20:42:12 +08:00
onlymash 7612dde6d4 clean string.xml 2018-03-26 20:42:12 +08:00
onlymash 5188fe7170 only show 'Save to...' at KiKat or higher 2018-03-26 20:42:12 +08:00
onlymash c31048e829 clean import 2018-03-26 20:42:12 +08:00
onlymash 44629bb405 support image custom save 2018-03-26 20:42:12 +08:00
seven332 3e387b1833 1.0.28 2018-03-26 18:24:03 +08:00
seven332 080693656a Update adaptive icon 2018-03-26 17:56:25 +08:00
seven332 bc5479fa96 Add built-in hosts 2018-03-26 12:02:44 +08:00
seven332 b95892d3b6 Use "Custom hosts.txt" to distinguish "built-in" and "custom" 2018-03-26 11:07:13 +08:00
seven332 e1eea40fd7 Use "hosts.txt" instead of "Hosts"
Users might be more familiar with the former
2018-03-26 10:16:51 +08:00
seven332 c00fb901a0 Close #363, select download pipe if download dir exists 2018-03-25 20:23:16 +08:00
seven332 029bca22ed Add hosts UI 2018-03-24 02:17:58 +08:00
seven332 facb931cb6 Use Java 8 language features 2018-03-24 01:16:32 +08:00
onlymash 2f319afd40 restore app_name 2018-03-23 21:24:08 +08:00
onlymash 95114502c9 add strings.xml to debug 2018-03-23 21:24:08 +08:00
onlymash 2eef9b8fb0 rename FILE_PROVIDER_AUTHORITY 2018-03-23 21:24:08 +08:00
onlymash 6180ea3302 remove productFlavors 2018-03-23 21:24:08 +08:00
onlymash bf3ebc5ff8 remove unused applicationId 2018-03-23 21:24:08 +08:00
onlymash 5f77728a7b use another package name for debug 2018-03-23 21:24:08 +08:00
seven332 e823834889 Fix UConfigActivity registered name 2018-03-23 12:48:06 +08:00
seven332 35c97a7772 Add Hosts 2018-03-23 12:10:03 +08:00
seven332 d59a520aa5 Fix test 2018-03-23 12:09:15 +08:00
seven332 6bcdbfeaa4 Use field mLocation instead of local variable location 2018-03-21 19:41:12 +08:00
bfkro dcb11102f6 use ViewUtils to calculate offset between SeekBar and SeekBarPanel 2018-03-21 19:25:12 +08:00
bfkro a0e957b1fd Fix a bug so when user clicks the SeekBarPanel, the x coordinate with the correct x-offset is sent to SeekBar. 2018-03-21 19:25:12 +08:00
onlymash c8c0a3aae0 update foreground 2018-03-20 23:10:52 +08:00
onlymash aed7acfdc8 update foreground 2018-03-20 23:10:52 +08:00
onlymash 6707f0ee35 update launcher backgound 2018-03-20 23:10:52 +08:00
onlymash 44694f351e add adaptive icons for android 8.0+ 2018-03-20 23:10:52 +08:00
onlymash 8e3585b32d use implementation for gradle 3.0+ 2018-03-20 15:18:47 +08:00
onlymash 25312953af add notification channel for Oreo 2018-03-19 22:44:23 +08:00
seven332 c8a32ba76e Update ISSUE_TEMPLATE.md
能说中文就别说英文了
2018-03-19 18:15:10 +08:00
lilymaniac a97a6682fb Add Korean localization 2018-03-19 09:28:03 +08:00
lilymaniac ed8151632e Add Korean to resConfigs entry 2018-03-19 09:28:03 +08:00
seven332 aca061ecf6 Ignore release dir 2018-03-08 20:42:32 +08:00
seven332 b2bef7a4b0 Update okhttp 2018-03-08 20:35:02 +08:00
seven332 db63a8f05b Print exception in ExceptionUtils.getReadableString()
I don't want to track all callings, just add it here
2018-03-08 19:33:44 +08:00
seven332 998f57f435 Fix gallery comment parsing 2018-03-05 10:09:47 +08:00
seven332 46c9197cce Update sdk version and libraries 2018-03-04 15:59:32 +08:00
seven332 3f3c0c6c6a Show sign in failure reason 2018-03-03 23:52:54 +08:00
seven332 ff34acfe59 Update values-zh-rTW/strings.xml 2018-03-02 09:03:42 +08:00
seven332 b969177244 Update values-zh-rHK/strings.xml 2018-02-28 17:03:00 +08:00
seven332 32efad2b33 1.0.27 2018-02-28 10:08:03 +08:00
trhjew bad4cdac1a Update strings.xml 2018-02-27 22:35:27 +08:00
seven332 5cebca42e9 Add Japanese support 2018-02-27 22:20:08 +08:00
trhjew 3ef2447eef Update strings.xml 2018-02-27 22:06:34 +08:00
trhjew a8faa2930a Update strings.xml 2018-02-27 22:06:34 +08:00
trhjew 02abba52a7 Create strings.xml 2018-02-27 22:06:34 +08:00
seven332 6da2bc352d Update gradle 2018-02-25 20:27:40 +08:00
seven332 cc39e0dda3 Show post gallery comment error 2018-02-25 20:26:34 +08:00
seven332 c81145d46e Close #341, update gallery comment post format 2018-02-24 19:03:09 +08:00
0w0@0w0.pw a56c79d4bb Remove some translations
Rename Privacy settings
2018-02-11 13:20:18 +08:00
0w0@0w0.pw fa3f409a70 Clean up the import 2018-02-11 13:20:18 +08:00
0w0@0w0.pw 1865924469 Clean Code 2018-02-11 13:20:18 +08:00
0w0@0w0.pw b3a23ad4e8 Add Privacy and Security Settings 2018-02-11 13:20:18 +08:00
seven332 7a02103e05 Close #328, fix Chinese language detection
Add 中国翻訳
2018-02-10 21:50:22 +08:00
seven332 95ed0eb7ea 1.0.26 2018-02-10 16:02:41 +08:00
seven332 9ec74934bc Always show the help route in error message 2018-02-10 15:56:21 +08:00
seven332 4f868a4556 Add uconfig saving tip 2018-02-10 14:51:18 +08:00
seven332 21bff4dff7 Merge branch 'master' of https://github.com/seven332/EhViewer 2018-02-10 14:03:03 +08:00
seven332 30819fc7c6 Add UConfigActivity 2018-02-10 14:02:20 +08:00
scese250 ce70859fb2 Fixed orthography and translation (Spanish)
Some words weren't translated and there were several orthographic errors.
2018-02-06 00:06:35 +08:00
seven332 197a34721b Closes #320, fix strings.xml 2018-01-29 20:04:40 +08:00
seven332 3a21724342 Add an option to disable page interval 2018-01-25 22:33:43 +08:00
seven332 ffceda72b1 Merge branch 'master' of https://github.com/seven332/EhViewer 2018-01-25 21:42:26 +08:00
seven332 bb655783b8 Update GLView-Image library to fix invalid gif autoplay 2018-01-25 21:38:06 +08:00
seven332 d5cd23c130 Update Image library to avoid gif super short delay 2018-01-25 18:42:29 +08:00
seven332 70bb0d06b2 Update ISSUE_TEMPLATE.md 2018-01-25 11:19:59 +08:00
GUIHU 18f1ec7403 Update strings.xml 2018-01-13 22:05:36 +08:00
gui 20c0030cdc polish 2018-01-13 22:05:36 +08:00
gui 7509bf9776 polish 2018-01-13 22:05:36 +08:00
gui fb7b9b28a7 針對台灣使用者慣用語(或已有既有用法)的文字字串進行調整
以迎合台灣使用者使用習慣
localization for values-zh-rTW  in order to fit Taiwanese user's habit
2018-01-13 22:05:36 +08:00
seven332 185ab00431 1.0.25 2017-12-28 22:00:51 +08:00
LackOfDream b48b38e8c4 remove redundant trailing whitespace of tags when parsing gallery detail 2017-12-24 18:12:44 +08:00
LackOfDream 34632342fc Notify change of single item instead of the whole data set, disable item animation 2017-12-19 15:46:42 +08:00
LackOfDream c7bf9509e3 Add enable/disable feature on Filter 2017-12-19 15:46:42 +08:00
seven332 877c354f84 Add the Telegram link 2017-11-14 21:42:58 +08:00
seven332 6c7b33e86f Add community links 2017-11-14 21:35:02 +08:00
seven332 2c3fa31e91 Add recaptcha 2017-09-06 16:49:48 +08:00
scese250 550d3735c7 Fixed typos, incorrect capital and added accents
Thanks for add spanish translation, I'll help for correct errors.
2017-07-24 12:48:05 +08:00
Jabasukuriputo Wang 71f654635c Add textbox for cookie:igneous.
Fix #208 #274
It seems that login via other ways is impossible to get correct igneous atm.
(DAMN, SAVE IT ELSEWHERE NOW)
2017-07-14 21:08:12 +08:00
seven332 e9c7695367 1.0.24 2017-06-04 23:03:28 +08:00
seven332 b2e34e622c Set default request id to invalid one 2017-06-04 23:02:13 +08:00
seven332 78db7ecbc5 1.0.23 2017-06-01 22:31:41 +08:00
seven332 4896a1edbc Use HashMap instead of WeakHashMap for GlobalStuffMap 2017-06-01 22:30:02 +08:00
seven332 61b2075302 Add e-hentai.org to intent-filter
Close #249
2017-05-25 01:04:35 +08:00
seven332 b21fe89ea1 1.0.22 2017-05-23 16:35:42 +08:00
seven332 4af054a9cd Update gradle tools 2017-05-23 16:35:19 +08:00
seven332 3f579060b5 Fix GalleryDetailParser parsing gallery cover 2017-05-23 16:31:26 +08:00
seven332 1e87279310 Avoid saving large data in ContentLayout 2017-05-23 16:21:05 +08:00
seven332 5fae1df78c Update libraries 2017-04-22 20:48:26 +08:00
seven332 84949442ee Add ISSUE_TEMPLATE English translate 2017-04-07 19:48:21 +08:00
seven332 3b395380c7 Merge remote-tracking branch 'origin/master' 2017-04-05 20:26:00 +08:00
seven332 3e3de0ff2a Update gradle library 2017-04-05 20:24:45 +08:00
seven332 da802c5371 Update ISSUE_TEMPLATE 2017-04-05 20:23:20 +08:00
seven332 24405f7c44 Merge pull request #251 from danthe100/mycommits
Fixed Spanish translation
2017-03-30 22:09:41 -05:00
Dante Garcia 9ed826a87e Fixed certain errors 2017-03-30 12:01:03 -05:00
seven332 9c5c9dfa95 Add ISSUE_TEMPLATE 2017-03-27 23:26:21 +08:00
seven332 6eb29c783a 1.0.21 2017-03-20 22:36:05 +08:00
seven332 cb11ecc9f0 Fix category parsing 2017-03-20 22:34:05 +08:00
seven332 bf5feaacd1 Merge pull request #242 from sorz/master
Add fingerprint unlock
2017-03-18 01:41:53 -05:00
seven332 0ef4088b88 Update gradle 2017-03-17 23:12:11 +08:00
sorz 1e87d34806 Add translations for fingerprint setting
Spanish by Google Translate
2017-03-16 01:52:54 +11:00
sorz 0b35fb01ee Add fingerprint on SecurityScene 2017-03-16 01:11:19 +11:00
sorz 7f1d590fbd Add fingerprint protection switch 2017-03-15 22:38:47 +11:00
seven332 97ce2bbe54 Apply Spanish strings.xml to all countries 2017-02-23 16:54:06 +08:00
seven332 d8a6424ecc Merge pull request #235 from danthe100/mycommits
Added translation into Spanish
2017-02-23 13:10:04 +08:00
Dante Garcia fdc199cc49 Added translation into Spanish 2017-02-22 20:18:17 -05:00
seven332 a02fe88765 1.0.20 2017-02-09 21:45:24 +08:00
seven332 6488de75f1 Adjust gallery detail actions order 2017-02-09 21:40:24 +08:00
seven332 439f199a10 Sanitize torrent filename 2017-02-09 21:36:44 +08:00
seven332 e535b2fa09 Fix TorrentParser 2017-02-09 21:30:07 +08:00
seven332 81ae752975 Fix Chinese translations 2017-02-09 21:24:28 +08:00
seven332 5dd584776a Fix Chinese translations 2017-02-09 21:19:36 +08:00
seven332 f617e62b85 Add android-chinese-string 2017-02-09 21:09:58 +08:00
Lin, Yi-Li 4d95a7163f use snackbar to tell users that H@H client is required for this feature 2017-01-29 17:27:56 +09:00
Lin, Yi-Li b5cae76de5 able to request archive download 2017-01-29 02:00:02 +09:00
seven332 9065e7457a 1.0.19 2017-01-26 13:30:48 +08:00
seven332 08ab9159a5 Fix RecyclerView crashing 2017-01-26 11:39:56 +08:00
seven332 6b5b961986 1.0.18 2017-01-25 13:22:09 +08:00
seven332 6a96035149 Avoid RecyclerView scrolling after detached 2017-01-25 13:19:23 +08:00
seven332 1ce035591a Fix GalleryPageParser 2017-01-25 00:13:55 +08:00
seven332 6cc78802ee 1.0.17 2017-01-24 19:41:23 +08:00
seven332 636c011c23 Rename XXX_G to XXX_E 2017-01-24 19:39:05 +08:00
seven332 92490ca1a6 e-hentai switched to HTTPS 2017-01-24 19:34:24 +08:00
seven332 b6a5d237ac Add EhUrl.getFixedPreviewThumbUrl() 2017-01-24 19:22:58 +08:00
seven332 8be0b5c588 Don't use jack anymore 2016-12-31 19:29:33 +08:00
seven332 fcbe129b6e Fix URL_PREFIX_THUMB_EX 2016-12-30 12:10:59 +08:00
seven332 befbcd6720 Add fix thumb url 2016-12-29 21:50:26 +08:00
seven332 ee5062d4c7 Add round icon 2016-12-19 00:38:26 +08:00
seven332 a4392523d6 1.0.16 2016-12-15 02:06:46 +08:00
seven332 b3371304bf Sync media store after saving image 2016-12-15 02:05:23 +08:00
seven332 38911c2d34 Be compatible with some bad share mechanism
Some apps need file path to share it, but it's not necessary at all.
2016-12-15 01:59:49 +08:00
seven332 6c5ad068d2 Update gradle tools and libraries 2016-12-15 01:30:32 +08:00
seven332 868521f19f Try to get image reload key more than once 2016-12-15 01:13:58 +08:00
seven332 c4cd965306 Add excluding japanese original
Eh site doesn't support it, but just modifying the cookie works fine.
2016-12-03 19:38:49 +08:00
seven332 639adaf7fa Close #201, list local favorites by favorited time 2016-10-29 00:05:18 +08:00
seven332 e174ee0b2c Ensure dao gen called 2016-10-22 00:42:41 +08:00
seven332 04da83f950 Set targetSdkVersion to 25 2016-10-22 00:16:06 +08:00
seven332 84a35e9283 1.0.15 2016-10-18 00:10:10 +08:00
seven332 a907db43be Update libraries 2016-10-18 00:06:09 +08:00
seven332 890be41aa5 Update gradle tool 2016-08-13 18:49:57 +08:00
seven332 f3db305cee Add https in intent-filter 2016-08-13 18:48:57 +08:00
seven332 4626ab1ec4 Update image search url 2016-07-31 19:27:59 +08:00
seven332 a44b070120 1.0.14 2016-07-28 14:28:23 +08:00
seven332 1760fb65e2 Use LinearLayout instead of android.support.v7.widget.ButtonBarLayout 2016-07-28 14:25:01 +08:00
seven332 47d28beddd 1.0.13 2016-07-28 00:17:39 +08:00
seven332 8d39829e54 Update libraries 2016-07-28 00:17:06 +08:00
seven332 2cb8319c91 Check download image size 2016-07-27 23:34:09 +08:00
seven332 27ca88f0c2 Use https for ex and forums 2016-07-27 23:32:31 +08:00
seven332 9aa033c31b Add https support for url parser 2016-07-27 23:27:27 +08:00
seven332 1f1d968766 Make error message different 2016-07-27 23:24:53 +08:00
seven332 3b8ba148dc Save temp share image to internal folder 2016-06-20 23:27:03 +08:00
seven332 5448bdf7bb Use FileProvider to share image
For apps targeting Android N, file:// URIs outside app is not supported any more.
2016-06-18 22:08:29 +08:00
seven332 e7cfd8831e Set targetSdkVersion to 24, upgrade libraries 2016-06-18 21:04:26 +08:00
seven332 148588e53a Show version name in about 2016-06-10 20:37:27 +08:00
seven332 cacfd58330 1.0.12 2016-06-09 21:14:23 +08:00
seven332 97cf075ffb Upgrade libraries 2016-06-09 21:10:21 +08:00
seven332 d93ce846e2 Remove item from decode queue when cancel request 2016-06-08 21:20:53 +08:00
seven332 7e45e379b3 Fix fragment class check 2016-06-08 20:43:21 +08:00
seven332 f3c90d46fd Remove AssertUtils 2016-06-08 20:31:47 +08:00
seven332 c80445e43a Upgrade libraries 2016-06-08 19:33:21 +08:00
seven332 4faa031ae1 Upgrade gradle tool 2016-06-07 17:55:58 +08:00
seven332 17bdb7cb93 Use Queue for decode list 2016-06-07 17:55:10 +08:00
seven332 d17f98f3e4 Upgrade GLGallery to 0.1.2 2016-06-03 01:31:34 +08:00
seven332 52bc260998 Start gallery provider before get start page 2016-06-01 18:58:44 +08:00
seven332 ebaba88cde Add GLGallery library 2016-05-31 00:01:05 +08:00
seven332 94c50b27bf Check existence of views in onAnimationEnd 2016-05-30 00:28:32 +08:00
seven332 b2cf4d1fb0 Check existence of index when clear pToken 2016-05-30 00:25:20 +08:00
seven332 b52f260c9e Avoid restore download null 2016-05-30 00:20:04 +08:00
seven332 b4fc856a51 Fix SpiderInfo read 2016-05-30 00:18:20 +08:00
seven332 e1b07b715f Add GLView library 2016-05-29 15:52:33 +08:00
seven332 1e434c09e6 Use webp image resources 2016-05-28 22:13:53 +08:00
seven332 7fb4ae682a Add compileOptions.incremental 2016-05-25 20:14:38 +08:00
seven332 f2f7821b55 Don't use TransitionDrawable when LoadImageView is not showing 2016-05-25 13:59:00 +08:00
seven332 02b5f6289e Run executeDaoGenerator after copyNotice 2016-05-24 01:30:12 +08:00
seven332 9293e92a99 Upgrade build tool and image library 2016-05-24 00:53:34 +08:00
seven332 ccd98ff36e Block new intent when SolidScene is shown 2016-05-19 16:16:48 +08:00
seven332 6c5cbd9f2f Fix for java6 2016-05-19 15:18:10 +08:00
seven332 4a7edf648b 1.0.11 2016-05-14 13:56:15 +08:00
seven332 cfc9411223 Clean up 2016-05-14 13:23:59 +08:00
seven332 05030e9bb6 Save separated memory information in crash file
app memory, app native memory, app max memory, system total memory
2016-05-14 12:54:38 +08:00
seven332 ab3fc7d842 Avoid create dir when loading thumb in download list 2016-05-14 12:45:02 +08:00
seven332 fb216a960b Lock drawer when suggestion list showing 2016-05-13 13:43:37 +08:00
seven332 c0fbdee61f Copy email address when click donate item 2016-05-13 02:12:10 +08:00
seven332 901c0ae3ec Disable zero rating to gallery 2016-05-12 14:53:46 +08:00
seven332 f727554afd Update libraries 2016-05-12 14:32:09 +08:00
seven332 b0a5666a6d Fix gallery restore
SpiderInfo has changed, but restore code was the old version
2016-05-12 01:22:31 +08:00
373 changed files with 12569 additions and 16864 deletions

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
感谢您提交 Issue,请在提交前仔细阅读以下信息。
请在阅读完毕后,删除这些文字,并写下对该 Issue 的描述。
若您能熟练使用现代标准汉语,请务必使用该语言描述 Issue。
Issue 的内容仅可为
* Bug 反馈
* 功能申请
若您希望得到使用指导(譬如如何删除快速搜索),请至 [G+ 社区](https://plus.google.com/u/1/communities/103823982034655188459) 发贴。若有其他问题,可在应用内找到开发者的邮箱地址,使用电子邮件与开发者交流。
若内容为 Bug 反馈,请先查看 [release 页面](https://github.com/seven332/EhViewer/releases),以帮助确认该 bug 是否存在于最新版中;同时应详细描述 bug 内容与重现方法,必要时可附加截图,但请确定截图符合风序良俗。
功能申请包括添加新功能与改进现有功能。
一个 Issue 只包含一个 Bug 反馈或者功能申请。若有多个需求,请提交多个 Issue。
尽量不提交重复的 Issue,可先进行搜索。对于重复的 Issue,开发者可能会直接关闭并添加 Duplicate 标签。
Thank you for taking the time to submit an issue. Before you proceed, please consider the following.
An issue can only be about:
* Bug Report
* Feature Request
If you need application instructions, please post your question in [G+ community](https://plus.google.com/u/1/communities/103823982034655188459). If you have other questions, please get the developer's email address in the application, and send him/her an email.
One issue one bug report or feature request.
+1
View File
@@ -6,3 +6,4 @@
*.iml
.idea
/captures
release
+2 -2
View File
@@ -1,3 +1,5 @@
[![Telegram](https://img.shields.io/badge/chat-Telegram-blue.svg)](https://t.me/ehviewer) [![G+](https://img.shields.io/badge/chat-G%2B-red.svg)](https://plus.google.com/communities/103823982034655188459)
# EhViewer
![Icon](art/launcher_icon-web.png)
@@ -18,14 +20,12 @@ Windows
> git clone https://github.com/seven332/EhViewer
> cd EhViewer
> gradlew daogenerator:executeDaoGenerator
> gradlew app:assembleDebug
Linux
$ git clone https://github.com/seven332/EhViewer
$ cd EhViewer
$ ./gradlew daogenerator:executeDaoGenerator
$ ./gradlew app:assembleDebug
生成的 apk 文件在 app\build\outputs\apk 目录下
+61 -37
View File
@@ -1,21 +1,18 @@
apply plugin: 'com.android.application'
apply plugin: 'android-chinese-string'
android {
compileSdkVersion 23
buildToolsVersion "24.0.0 rc3"
compileSdkVersion 27
defaultConfig {
applicationId "com.hippo.ehviewer"
minSdkVersion 14
targetSdkVersion 23
versionCode 63
versionName "1.0.10"
targetSdkVersion 27
versionCode 86
versionName "1.2.1"
vectorDrawables.useSupportLibrary = true
resConfigs "zh", "zh-rCN", "zh-rHK", "zh-rTW"
jackOptions {
enabled true
}
resConfigs "zh", "zh-rCN", "zh-rHK", "zh-rTW",
"es", "ja", "ko", "fr", "de"
}
compileOptions {
@@ -24,13 +21,20 @@ android {
}
lintOptions {
disable 'MissingTranslation'
abortOnError true
checkReleaseBuilds true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField 'String', 'FILE_PROVIDER_AUTHORITY', '"com.hippo.ehviewer.fileprovider"'
}
debug {
applicationIdSuffix ".debug"
buildConfigField 'String', 'FILE_PROVIDER_AUTHORITY', '"com.hippo.ehviewer.debug.fileprovider"'
}
}
@@ -44,10 +48,11 @@ android {
task copyNotice(type: Copy) {
from '../NOTICE.html'
into './src/main/assets'
finalizedBy ":daogenerator:executeDaoGenerator"
}
tasks.withType(AbstractCompile) {
compileTask -> compileTask.dependsOn copyNotice
tasks.withType(JavaCompile) {
task -> task.dependsOn copyNotice
}
clean {
@@ -55,29 +60,48 @@ clean {
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'com.github.amlcurran.showcaseview:library:5.4.3'
compile 'com.github.seven332:animator:0.1.0'
compile 'com.github.seven332:beerbelly:0.1.4'
compile 'com.github.seven332:conaco:0.1.4-eh'
compile 'com.github.seven332:drawerlayout:0.1.0'
compile 'com.github.seven332:easyrecyclerview:0.1.0'
compile 'com.github.seven332:hotspot:0.1.0'
compile 'com.github.seven332:image:0.1.7-jpeg-png-gif'
compile 'com.github.seven332:okhttp:3.2.0-eh'
compile 'com.github.seven332:refreshlayout:0.1.0'
compile 'com.github.seven332:ripple:0.1.1'
compile 'com.github.seven332:streampipe:0.1.0'
compile 'com.github.seven332:tuxiang:0.1.2'
compile 'com.github.seven332:unifile:0.1.3'
compile 'com.github.seven332:yorozuya:0.1.1'
compile 'com.github.seven332:yorozuya-thread:0.1.1'
compile 'com.github.seven332:yorozuya-collect:0.1.2'
compile 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.8.7'
compile 'org.ccil.cowan.tagsoup:tagsoup:1.2.1'
compile 'org.greenrobot:greendao:2.2.0'
compile 'org.jsoup:jsoup:1.9.1'
testCompile 'junit:junit:4.12'
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "com.android.support:appcompat-v7:$supportLibrary"
implementation "com.android.support:cardview-v7:$supportLibrary"
implementation "com.android.support:design:$supportLibrary"
implementation 'com.github.amlcurran.showcaseview:library:5.4.3'
implementation 'com.github.seven332:android-recaptcha:2bbb3459a8'
implementation 'com.github.seven332:android-resource:0.1.0'
implementation 'com.github.seven332:animator:0.1.0'
implementation 'com.github.seven332:beerbelly:0.1.4'
implementation 'com.github.seven332:conaco:0.1.5-eh'
implementation 'com.github.seven332:drawerlayout:0.2.1'
implementation 'com.github.seven332:easyrecyclerview:0.1.1'
implementation 'com.github.seven332:glgallery:0.1.2'
implementation 'com.github.seven332:glview:0.1.0'
implementation 'com.github.seven332:glview-image:0.1.0'
implementation 'com.github.seven332:hotspot:0.1.0'
implementation 'com.github.seven332:image:0.1.12'
implementation 'com.github.seven332:okhttp:3.5.0'
implementation 'com.github.seven332:refreshlayout:0.1.0'
implementation 'com.github.seven332:ripple:0.1.2'
implementation 'com.github.seven332:streampipe:0.1.0'
implementation 'com.github.seven332:tuxiang:0.1.2'
implementation 'com.github.seven332:unifile:b59c14e47b'
implementation 'com.github.seven332:yorozuya:0.1.2'
implementation 'com.github.seven332:yorozuya-thread:0.1.1'
implementation 'com.github.seven332:yorozuya-collect:0.1.4'
implementation 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.9.2'
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
implementation 'org.ccil.cowan.tagsoup:tagsoup:1.2.1'
implementation 'org.greenrobot:greendao:2.2.1'
implementation 'org.jsoup:jsoup:1.11.3'
testImplementation 'junit:junit:4.12'
testImplementation 'org.robolectric:robolectric:3.8'
testImplementation 'org.jooq:joor:0.9.6'
}
configurations.all {
resolutionStrategy {
force 'com.github.seven332:glgallery:c56b14c6fa'
force 'com.github.seven332:glview-image:4c744db'
force 'com.github.seven332:image:bbf0bbb0a0'
exclude group: 'com.github.seven332', module: 'okhttp'
}
}
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 Hippo Seven
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 Hippo Seven
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 Hippo Seven
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 Hippo Seven
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 Hippo Seven
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 Hippo Seven
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 Hippo Seven
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:shortcutId="start_all"
android:enabled="true"
android:icon="@drawable/ic_shortcut_start"
android:shortcutShortLabel="@string/download_start_all"
android:shortcutLongLabel="@string/download_start_all"
android:shortcutDisabledMessage="@string/download_start_all">
<intent
android:action="start_all"
android:targetPackage="com.hippo.ehviewer.debug"
android:targetClass="com.hippo.ehviewer.shortcuts.ShortcutsActivity"/>
<categories android:name="android.shortcut.conversation" />
</shortcut>
<shortcut
android:shortcutId="stop_all"
android:enabled="true"
android:icon="@drawable/ic_shortcut_stop"
android:shortcutShortLabel="@string/download_stop_all"
android:shortcutLongLabel="@string/download_stop_all"
android:shortcutDisabledMessage="@string/download_stop_all">
<intent
android:action="stop_all"
android:targetPackage="com.hippo.ehviewer.debug"
android:targetClass="com.hippo.ehviewer.shortcuts.ShortcutsActivity" />
<categories android:name="android.shortcut.conversation" />
</shortcut>
</shortcuts>
Regular → Executable
+44 -7
View File
@@ -22,12 +22,14 @@
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<application
android:name="com.hippo.ehviewer.EhApplication"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:allowBackup="true"
@@ -46,12 +48,17 @@
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="http"/>
<data android:scheme="https"/>
<data android:host="exhentai.org"/>
<data android:host="e-hentai.org"/>
<data android:host="g.e-hentai.org"/>
<data android:host="lofi.e-hentai.org"/>
</intent-filter>
@@ -96,42 +103,72 @@
<activity
android:name="com.hippo.ehviewer.ui.SettingsActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme"/>
android:theme="@style/AppTheme.Settings"/>
<activity
android:name="com.hippo.ehviewer.ui.ExcludedLanguagesActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/excluded_languages"/>
<activity
android:name="com.hippo.ehviewer.ui.DirPickerActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/dir_picker"/>
<activity
android:name="com.hippo.ehviewer.ui.LicenseActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/license"/>
<activity
android:name="com.hippo.ehviewer.ui.FilterActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/filter"/>
<activity
android:name="com.hippo.ehviewer.ui.SetSecurityActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/set_pattern_protection"/>
<activity
android:name="com.hippo.ehviewer.ui.UConfigActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/u_config"/>
<activity
android:name="com.hippo.ehviewer.ui.HostsActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/hosts"/>
<activity
android:name="com.hippo.ehviewer.shortcuts.ShortcutsActivity"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:excludeFromRecents="true"
android:taskAffinity=""
android:launchMode="singleTask">
</activity>
<service
android:name="com.hippo.ehviewer.download.DownloadService"
android:icon="@mipmap/ic_launcher"
android:label="@string/download_service_label"/>
<provider
android:name="com.hippo.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths"/>
</provider>
</application>
</manifest>
@@ -37,7 +37,7 @@ import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
public class AppCompatPreferenceActivity extends PreferenceActivity implements AppCompatCallback,
public abstract class AppCompatPreferenceActivity extends PreferenceActivity implements AppCompatCallback,
TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider {
private AppCompatDelegate mDelegate;
@@ -0,0 +1,108 @@
/*
* Copyright 2018 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.app;
import android.content.Context;
import android.preference.PreferenceActivity;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.hippo.ehviewer.R;
import java.util.ArrayList;
import java.util.List;
public abstract class PrettyPreferenceActivity extends AppCompatPreferenceActivity {
@Override
public void setListAdapter(ListAdapter adapter) {
int count = adapter.getCount();
List<PreferenceActivity.Header> headers = new ArrayList<>(count);
for (int i = 0; i < count; ++i) {
headers.add((PreferenceActivity.Header) adapter.getItem(i));
}
super.setListAdapter(new HeaderAdapter(this, headers, R.layout.item_preference_header, true));
}
private static class HeaderAdapter extends ArrayAdapter<PreferenceActivity.Header> {
private static class HeaderViewHolder {
ImageView icon;
TextView title;
TextView summary;
}
private LayoutInflater mInflater;
private int mLayoutResId;
private boolean mRemoveIconIfEmpty;
private HeaderAdapter(Context context, List<PreferenceActivity.Header> objects, int layoutResId,
boolean removeIconBehavior) {
super(context, 0, objects);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mLayoutResId = layoutResId;
mRemoveIconIfEmpty = removeIconBehavior;
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
HeaderViewHolder holder;
View view;
if (convertView == null) {
view = mInflater.inflate(mLayoutResId, parent, false);
holder = new HeaderViewHolder();
holder.icon = view.findViewById(android.R.id.icon);
holder.title = view.findViewById(android.R.id.title);
holder.summary = view.findViewById(android.R.id.summary);
view.setTag(holder);
} else {
view = convertView;
holder = (HeaderViewHolder) view.getTag();
}
// All view fields must be updated every time, because the view may be recycled
PreferenceActivity.Header header = getItem(position);
if (mRemoveIconIfEmpty) {
if (header.iconRes == 0) {
holder.icon.setVisibility(View.GONE);
} else {
holder.icon.setVisibility(View.VISIBLE);
holder.icon.setImageResource(header.iconRes);
}
} else {
holder.icon.setImageResource(header.iconRes);
}
holder.title.setText(header.getTitle(getContext().getResources()));
CharSequence summary = header.getSummary(getContext().getResources());
if (!TextUtils.isEmpty(summary)) {
holder.summary.setVisibility(View.VISIBLE);
holder.summary.setText(summary);
} else {
holder.summary.setVisibility(View.GONE);
}
return view;
}
}
}
@@ -0,0 +1,61 @@
/*
* Copyright 2018 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.content;
/*
* Created by Hippo on 2018/3/27.
*/
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import java.util.Locale;
public class ContextLocalWrapper extends ContextWrapper {
public ContextLocalWrapper(Context base) {
super(base);
}
public static ContextLocalWrapper wrap(Context context, Locale newLocale) {
Resources res = context.getResources();
Configuration configuration = res.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
configuration.setLocale(newLocale);
LocaleList localeList = new LocaleList(newLocale);
LocaleList.setDefault(localeList);
configuration.setLocales(localeList);
context = context.createConfigurationContext(configuration);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLocale(newLocale);
context = context.createConfigurationContext(configuration);
} else {
configuration.locale = newLocale;
res.updateConfiguration(configuration, res.getDisplayMetrics());
}
return new ContextLocalWrapper(context);
}
}
@@ -0,0 +1,816 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.content;
import android.content.ClipData;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
import static org.xmlpull.v1.XmlPullParser.START_TAG;
/**
* FileProvider is a special subclass of {@link ContentProvider} that facilitates secure sharing
* of files associated with an app by creating a <code>content://</code> {@link Uri} for a file
* instead of a <code>file:///</code> {@link Uri}.
* <p>
* A content URI allows you to grant read and write access using
* temporary access permissions. When you create an {@link Intent} containing
* a content URI, in order to send the content URI
* to a client app, you can also call {@link Intent#setFlags(int) Intent.setFlags()} to add
* permissions. These permissions are available to the client app for as long as the stack for
* a receiving {@link android.app.Activity} is active. For an {@link Intent} going to a
* {@link android.app.Service}, the permissions are available as long as the
* {@link android.app.Service} is running.
* <p>
* In comparison, to control access to a <code>file:///</code> {@link Uri} you have to modify the
* file system permissions of the underlying file. The permissions you provide become available to
* <em>any</em> app, and remain in effect until you change them. This level of access is
* fundamentally insecure.
* <p>
* The increased level of file access security offered by a content URI
* makes FileProvider a key part of Android's security infrastructure.
* <p>
* This overview of FileProvider includes the following topics:
* </p>
* <ol>
* <li><a href="#ProviderDefinition">Defining a FileProvider</a></li>
* <li><a href="#SpecifyFiles">Specifying Available Files</a></li>
* <li><a href="#GetUri">Retrieving the Content URI for a File</li>
* <li><a href="#Permissions">Granting Temporary Permissions to a URI</a></li>
* <li><a href="#ServeUri">Serving a Content URI to Another App</a></li>
* </ol>
* <h3 id="ProviderDefinition">Defining a FileProvider</h3>
* <p>
* Since the default functionality of FileProvider includes content URI generation for files, you
* don't need to define a subclass in code. Instead, you can include a FileProvider in your app
* by specifying it entirely in XML. To specify the FileProvider component itself, add a
* <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></code>
* element to your app manifest. Set the <code>android:name</code> attribute to
* <code>android.support.v4.content.FileProvider</code>. Set the <code>android:authorities</code>
* attribute to a URI authority based on a domain you control; for example, if you control the
* domain <code>mydomain.com</code> you should use the authority
* <code>com.mydomain.fileprovider</code>. Set the <code>android:exported</code> attribute to
* <code>false</code>; the FileProvider does not need to be public. Set the
* <a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn"
* >android:grantUriPermissions</a> attribute to <code>true</code>, to allow you
* to grant temporary access to files. For example:
* <pre class="prettyprint">
*&lt;manifest&gt;
* ...
* &lt;application&gt;
* ...
* &lt;provider
* android:name="android.support.v4.content.FileProvider"
* android:authorities="com.mydomain.fileprovider"
* android:exported="false"
* android:grantUriPermissions="true"&gt;
* ...
* &lt;/provider&gt;
* ...
* &lt;/application&gt;
*&lt;/manifest&gt;</pre>
* <p>
* If you want to override any of the default behavior of FileProvider methods, extend
* the FileProvider class and use the fully-qualified class name in the <code>android:name</code>
* attribute of the <code>&lt;provider&gt;</code> element.
* <h3 id="SpecifyFiles">Specifying Available Files</h3>
* A FileProvider can only generate a content URI for files in directories that you specify
* beforehand. To specify a directory, specify the its storage area and path in XML, using child
* elements of the <code>&lt;paths&gt;</code> element.
* For example, the following <code>paths</code> element tells FileProvider that you intend to
* request content URIs for the <code>images/</code> subdirectory of your private file area.
* <pre class="prettyprint">
*&lt;paths xmlns:android="http://schemas.android.com/apk/res/android"&gt;
* &lt;files-path name="my_images" path="images/"/&gt;
* ...
*&lt;/paths&gt;
*</pre>
* <p>
* The <code>&lt;paths&gt;</code> element must contain one or more of the following child elements:
* </p>
* <dl>
* <dt>
* <pre class="prettyprint">
*&lt;files-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the <code>files/</code> subdirectory of your app's internal storage
* area. This subdirectory is the same as the value returned by {@link Context#getFilesDir()
* Context.getFilesDir()}.
* </dd>
* <dt>
* <pre>
*&lt;cache-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* <dt>
* <dd>
* Represents files in the cache subdirectory of your app's internal storage area. The root path
* of this subdirectory is the same as the value returned by {@link Context#getCacheDir()
* getCacheDir()}.
* </dd>
* <dt>
* <pre class="prettyprint">
*&lt;external-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the root of the external storage area. The root path of this subdirectory
* is the same as the value returned by
* {@link Environment#getExternalStorageDirectory() Environment.getExternalStorageDirectory()}.
* </dd>
* <dt>
* <pre class="prettyprint">
*&lt;external-files-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the root of your app's external storage area. The root path of this
* subdirectory is the same as the value returned by
* {@code Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)}.
* </dd>
* <dt>
* <pre class="prettyprint">
*&lt;external-cache-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the root of your app's external cache area. The root path of this
* subdirectory is the same as the value returned by
* {@link Context#getExternalCacheDir() Context.getExternalCacheDir()}.
* </dd>
* </dl>
* <p>
* These child elements all use the same attributes:
* </p>
* <dl>
* <dt>
* <code>name="<i>name</i>"</code>
* </dt>
* <dd>
* A URI path segment. To enforce security, this value hides the name of the subdirectory
* you're sharing. The subdirectory name for this value is contained in the
* <code>path</code> attribute.
* </dd>
* <dt>
* <code>path="<i>path</i>"</code>
* </dt>
* <dd>
* The subdirectory you're sharing. While the <code>name</code> attribute is a URI path
* segment, the <code>path</code> value is an actual subdirectory name. Notice that the
* value refers to a <b>subdirectory</b>, not an individual file or files. You can't
* share a single file by its file name, nor can you specify a subset of files using
* wildcards.
* </dd>
* </dl>
* <p>
* You must specify a child element of <code>&lt;paths&gt;</code> for each directory that contains
* files for which you want content URIs. For example, these XML elements specify two directories:
* <pre class="prettyprint">
*&lt;paths xmlns:android="http://schemas.android.com/apk/res/android"&gt;
* &lt;files-path name="my_images" path="images/"/&gt;
* &lt;files-path name="my_docs" path="docs/"/&gt;
*&lt;/paths&gt;
*</pre>
* <p>
* Put the <code>&lt;paths&gt;</code> element and its children in an XML file in your project.
* For example, you can add them to a new file called <code>res/xml/file_paths.xml</code>.
* To link this file to the FileProvider, add a
* <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">&lt;meta-data&gt;</a> element
* as a child of the <code>&lt;provider&gt;</code> element that defines the FileProvider. Set the
* <code>&lt;meta-data&gt;</code> element's "android:name" attribute to
* <code>android.support.FILE_PROVIDER_PATHS</code>. Set the element's "android:resource" attribute
* to <code>&#64;xml/file_paths</code> (notice that you don't specify the <code>.xml</code>
* extension). For example:
* <pre class="prettyprint">
*&lt;provider
* android:name="android.support.v4.content.FileProvider"
* android:authorities="com.mydomain.fileprovider"
* android:exported="false"
* android:grantUriPermissions="true"&gt;
* &lt;meta-data
* android:name="android.support.FILE_PROVIDER_PATHS"
* android:resource="&#64;xml/file_paths" /&gt;
*&lt;/provider&gt;
*</pre>
* <h3 id="GetUri">Generating the Content URI for a File</h3>
* <p>
* To share a file with another app using a content URI, your app has to generate the content URI.
* To generate the content URI, create a new {@link File} for the file, then pass the {@link File}
* to {@link #getUriForFile(Context, String, File) getUriForFile()}. You can send the content URI
* returned by {@link #getUriForFile(Context, String, File) getUriForFile()} to another app in an
* {@link android.content.Intent}. The client app that receives the content URI can open the file
* and access its contents by calling
* {@link android.content.ContentResolver#openFileDescriptor(Uri, String)
* ContentResolver.openFileDescriptor} to get a {@link ParcelFileDescriptor}.
* <p>
* For example, suppose your app is offering files to other apps with a FileProvider that has the
* authority <code>com.mydomain.fileprovider</code>. To get a content URI for the file
* <code>default_image.jpg</code> in the <code>images/</code> subdirectory of your internal storage
* add the following code:
* <pre class="prettyprint">
*File imagePath = new File(Context.getFilesDir(), "images");
*File newFile = new File(imagePath, "default_image.jpg");
*Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);
*</pre>
* As a result of the previous snippet,
* {@link #getUriForFile(Context, String, File) getUriForFile()} returns the content URI
* <code>content://com.mydomain.fileprovider/my_images/default_image.jpg</code>.
* <h3 id="Permissions">Granting Temporary Permissions to a URI</h3>
* To grant an access permission to a content URI returned from
* {@link #getUriForFile(Context, String, File) getUriForFile()}, do one of the following:
* <ul>
* <li>
* Call the method
* {@link Context#grantUriPermission(String, Uri, int)
* Context.grantUriPermission(package, Uri, mode_flags)} for the <code>content://</code>
* {@link Uri}, using the desired mode flags. This grants temporary access permission for the
* content URI to the specified package, according to the value of the
* the <code>mode_flags</code> parameter, which you can set to
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}, {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}
* or both. The permission remains in effect until you revoke it by calling
* {@link Context#revokeUriPermission(Uri, int) revokeUriPermission()} or until the device
* reboots.
* </li>
* <li>
* Put the content URI in an {@link Intent} by calling {@link Intent#setData(Uri) setData()}.
* </li>
* <li>
* Next, call the method {@link Intent#setFlags(int) Intent.setFlags()} with either
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} or
* {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} or both.
* </li>
* <li>
* Finally, send the {@link Intent} to
* another app. Most often, you do this by calling
* {@link android.app.Activity#setResult(int, android.content.Intent) setResult()}.
* <p>
* Permissions granted in an {@link Intent} remain in effect while the stack of the receiving
* {@link android.app.Activity} is active. When the stack finishes, the permissions are
* automatically removed. Permissions granted to one {@link android.app.Activity} in a client
* app are automatically extended to other components of that app.
* </p>
* </li>
* </ul>
* <h3 id="ServeUri">Serving a Content URI to Another App</h3>
* <p>
* There are a variety of ways to serve the content URI for a file to a client app. One common way
* is for the client app to start your app by calling
* {@link android.app.Activity#startActivityForResult(Intent, int, Bundle) startActivityResult()},
* which sends an {@link Intent} to your app to start an {@link android.app.Activity} in your app.
* In response, your app can immediately return a content URI to the client app or present a user
* interface that allows the user to pick a file. In the latter case, once the user picks the file
* your app can return its content URI. In both cases, your app returns the content URI in an
* {@link Intent} sent via {@link android.app.Activity#setResult(int, Intent) setResult()}.
* </p>
* <p>
* You can also put the content URI in a {@link android.content.ClipData} object and then add the
* object to an {@link Intent} you send to a client app. To do this, call
* {@link Intent#setClipData(ClipData) Intent.setClipData()}. When you use this approach, you can
* add multiple {@link android.content.ClipData} objects to the {@link Intent}, each with its own
* content URI. When you call {@link Intent#setFlags(int) Intent.setFlags()} on the {@link Intent}
* to set temporary access permissions, the same permissions are applied to all of the content
* URIs.
* </p>
* <p class="note">
* <strong>Note:</strong> The {@link Intent#setClipData(ClipData) Intent.setClipData()} method is
* only available in platform version 16 (Android 4.1) and later. If you want to maintain
* compatibility with previous versions, you should send one content URI at a time in the
* {@link Intent}. Set the action to {@link Intent#ACTION_SEND} and put the URI in data by calling
* {@link Intent#setData setData()}.
* </p>
* <h3 id="">More Information</h3>
* <p>
* To learn more about FileProvider, see the Android training class
* <a href="{@docRoot}training/secure-file-sharing/index.html">Sharing Files Securely with URIs</a>.
* </p>
*/
public class FileProvider extends ContentProvider {
private static final String[] COLUMNS = {
MediaStore.MediaColumns.DISPLAY_NAME,
MediaStore.MediaColumns.SIZE,
MediaStore.MediaColumns.DATA
};
private static final String
META_DATA_FILE_PROVIDER_PATHS = "android.support.FILE_PROVIDER_PATHS";
private static final String TAG_ROOT_PATH = "root-path";
private static final String TAG_FILES_PATH = "files-path";
private static final String TAG_CACHE_PATH = "cache-path";
private static final String TAG_EXTERNAL = "external-path";
private static final String TAG_EXTERNAL_FILES = "external-files-path";
private static final String TAG_EXTERNAL_CACHE = "external-cache-path";
private static final String ATTR_NAME = "name";
private static final String ATTR_PATH = "path";
private static final File DEVICE_ROOT = new File("/");
// @GuardedBy("sCache")
private static HashMap<String, PathStrategy> sCache = new HashMap<String, PathStrategy>();
private PathStrategy mStrategy;
/**
* The default FileProvider implementation does not need to be initialized. If you want to
* override this method, you must provide your own subclass of FileProvider.
*/
@Override
public boolean onCreate() {
return true;
}
/**
* After the FileProvider is instantiated, this method is called to provide the system with
* information about the provider.
*
* @param context A {@link Context} for the current component.
* @param info A {@link ProviderInfo} for the new provider.
*/
@Override
public void attachInfo(Context context, ProviderInfo info) {
super.attachInfo(context, info);
// Sanity check our security
if (info.exported) {
throw new SecurityException("Provider must not be exported");
}
if (!info.grantUriPermissions) {
throw new SecurityException("Provider must grant uri permissions");
}
mStrategy = getPathStrategy(context, info.authority);
}
/**
* Return a content URI for a given {@link File}. Specific temporary
* permissions for the content URI can be set with
* {@link Context#grantUriPermission(String, Uri, int)}, or added
* to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then
* {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and
* {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a
* <code>content</code> {@link Uri} for file paths defined in their <code>&lt;paths&gt;</code>
* meta-data element. See the Class Overview for more information.
*
* @param context A {@link Context} for the current component.
* @param authority The authority of a {@link FileProvider} defined in a
* {@code <provider>} element in your app's manifest.
* @param file A {@link File} pointing to the filename for which you want a
* <code>content</code> {@link Uri}.
* @return A content URI for the file.
* @throws IllegalArgumentException When the given {@link File} is outside
* the paths supported by the provider.
*/
public static Uri getUriForFile(Context context, String authority, File file) {
final PathStrategy strategy = getPathStrategy(context, authority);
return strategy.getUriForFile(file);
}
/**
* Use a content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file
* managed by the FileProvider.
* FileProvider reports the column names defined in {@link android.provider.MediaStore.MediaColumns}:
* <ul>
* <li>{@link android.provider.MediaStore.MediaColumns#DISPLAY_NAME}</li>
* <li>{@link android.provider.MediaStore.MediaColumns#SIZE}</li>
* <li>{@link android.provider.MediaStore.MediaColumns#DATA}</li>
* </ul>
* For more information, see
* {@link ContentProvider#query(Uri, String[], String, String[], String)
* ContentProvider.query()}.
*
* @param uri A content URI returned by {@link #getUriForFile}.
* @param projection The list of columns to put into the {@link Cursor}. If null all columns are
* included.
* @param selection Selection criteria to apply. If null then all data that matches the content
* URI is returned.
* @param selectionArgs An array of {@link java.lang.String}, containing arguments to bind to
* the <i>selection</i> parameter. The <i>query</i> method scans <i>selection</i> from left to
* right and iterates through <i>selectionArgs</i>, replacing the current "?" character in
* <i>selection</i> with the value at the current position in <i>selectionArgs</i>. The
* values are bound to <i>selection</i> as {@link java.lang.String} values.
* @param sortOrder A {@link java.lang.String} containing the column name(s) on which to sort
* the resulting {@link Cursor}.
* @return A {@link Cursor} containing the results of the query.
*
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
if (projection == null) {
projection = COLUMNS;
}
String[] cols = new String[projection.length];
Object[] values = new Object[projection.length];
int i = 0;
for (String col : projection) {
if (MediaStore.MediaColumns.DISPLAY_NAME.equals(col)) {
cols[i] = MediaStore.MediaColumns.DISPLAY_NAME;
values[i++] = file.getName();
} else if (MediaStore.MediaColumns.SIZE.equals(col)) {
cols[i] = MediaStore.MediaColumns.SIZE;
values[i++] = file.length();
} else if (MediaStore.MediaColumns.DATA.equals(col)) {
cols[i] = MediaStore.MediaColumns.DATA;
values[i++] = file.getPath();
}
}
cols = copyOf(cols, i);
values = copyOf(values, i);
final MatrixCursor cursor = new MatrixCursor(cols, 1);
cursor.addRow(values);
return cursor;
}
/**
* Returns the MIME type of a content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
*
* @param uri A content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @return If the associated file has an extension, the MIME type associated with that
* extension; otherwise <code>application/octet-stream</code>.
*/
@Override
public String getType(Uri uri) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
final int lastDot = file.getName().lastIndexOf('.');
if (lastDot >= 0) {
final String extension = file.getName().substring(lastDot + 1);
final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if (mime != null) {
return mime;
}
}
return "application/octet-stream";
}
/**
* By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must
* subclass FileProvider if you want to provide different functionality.
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException("No external inserts");
}
/**
* By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must
* subclass FileProvider if you want to provide different functionality.
*/
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException("No external updates");
}
/**
* Deletes the file associated with the specified content URI, as
* returned by {@link #getUriForFile(Context, String, File) getUriForFile()}. Notice that this
* method does <b>not</b> throw an {@link java.io.IOException}; you must check its return value.
*
* @param uri A content URI for a file, as returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @param selection Ignored. Set to {@code null}.
* @param selectionArgs Ignored. Set to {@code null}.
* @return 1 if the delete succeeds; otherwise, 0.
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
return file.delete() ? 1 : 0;
}
/**
* By default, FileProvider automatically returns the
* {@link ParcelFileDescriptor} for a file associated with a <code>content://</code>
* {@link Uri}. To get the {@link ParcelFileDescriptor}, call
* {@link android.content.ContentResolver#openFileDescriptor(Uri, String)
* ContentResolver.openFileDescriptor}.
*
* To override this method, you must provide your own subclass of FileProvider.
*
* @param uri A content URI associated with a file, as returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @param mode Access mode for the file. May be "r" for read-only access, "rw" for read and
* write access, or "rwt" for read and write access that truncates any existing file.
* @return A new {@link ParcelFileDescriptor} with which you can access the file.
*/
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
final int fileMode = modeToMode(mode);
return ParcelFileDescriptor.open(file, fileMode);
}
/**
* Return {@link PathStrategy} for given authority, either by parsing or
* returning from cache.
*/
private static PathStrategy getPathStrategy(Context context, String authority) {
PathStrategy strat;
synchronized (sCache) {
strat = sCache.get(authority);
if (strat == null) {
try {
strat = parsePathStrategy(context, authority);
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
} catch (XmlPullParserException e) {
throw new IllegalArgumentException(
"Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
}
sCache.put(authority, strat);
}
}
return strat;
}
/**
* Parse and return {@link PathStrategy} for given authority as defined in
* {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <meta-data>}.
*
* @see #getPathStrategy(Context, String)
*/
private static PathStrategy parsePathStrategy(Context context, String authority)
throws IOException, XmlPullParserException {
final SimplePathStrategy strat = new SimplePathStrategy(authority);
final ProviderInfo info = context.getPackageManager()
.resolveContentProvider(authority, PackageManager.GET_META_DATA);
final XmlResourceParser in = info.loadXmlMetaData(
context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
if (in == null) {
throw new IllegalArgumentException(
"Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
}
int type;
while ((type = in.next()) != END_DOCUMENT) {
if (type == START_TAG) {
final String tag = in.getName();
final String name = in.getAttributeValue(null, ATTR_NAME);
String path = in.getAttributeValue(null, ATTR_PATH);
File target = null;
if (TAG_ROOT_PATH.equals(tag)) {
target = DEVICE_ROOT;
} else if (TAG_FILES_PATH.equals(tag)) {
target = context.getFilesDir();
} else if (TAG_CACHE_PATH.equals(tag)) {
target = context.getCacheDir();
} else if (TAG_EXTERNAL.equals(tag)) {
target = Environment.getExternalStorageDirectory();
} else if (TAG_EXTERNAL_FILES.equals(tag)) {
File[] externalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);
if (externalFilesDirs.length > 0) {
target = externalFilesDirs[0];
}
} else if (TAG_EXTERNAL_CACHE.equals(tag)) {
File[] externalCacheDirs = ContextCompat.getExternalCacheDirs(context);
if (externalCacheDirs.length > 0) {
target = externalCacheDirs[0];
}
}
if (target != null) {
strat.addRoot(name, buildPath(target, path));
}
}
}
return strat;
}
/**
* Strategy for mapping between {@link File} and {@link Uri}.
* <p>
* Strategies must be symmetric so that mapping a {@link File} to a
* {@link Uri} and then back to a {@link File} points at the original
* target.
* <p>
* Strategies must remain consistent across app launches, and not rely on
* dynamic state. This ensures that any generated {@link Uri} can still be
* resolved if your process is killed and later restarted.
*
* @see SimplePathStrategy
*/
interface PathStrategy {
/**
* Return a {@link Uri} that represents the given {@link File}.
*/
public Uri getUriForFile(File file);
/**
* Return a {@link File} that represents the given {@link Uri}.
*/
public File getFileForUri(Uri uri);
}
/**
* Strategy that provides access to files living under a narrow whitelist of
* filesystem roots. It will throw {@link SecurityException} if callers try
* accessing files outside the configured roots.
* <p>
* For example, if configured with
* {@code addRoot("myfiles", context.getFilesDir())}, then
* {@code context.getFileStreamPath("foo.txt")} would map to
* {@code content://myauthority/myfiles/foo.txt}.
*/
static class SimplePathStrategy implements PathStrategy {
private final String mAuthority;
private final HashMap<String, File> mRoots = new HashMap<String, File>();
public SimplePathStrategy(String authority) {
mAuthority = authority;
}
/**
* Add a mapping from a name to a filesystem root. The provider only offers
* access to files that live under configured roots.
*/
public void addRoot(String name, File root) {
if (TextUtils.isEmpty(name)) {
throw new IllegalArgumentException("Name must not be empty");
}
try {
// Resolve to canonical path to keep path checking fast
root = root.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed to resolve canonical path for " + root, e);
}
mRoots.put(name, root);
}
@Override
public Uri getUriForFile(File file) {
String path;
try {
path = file.getCanonicalPath();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
}
// Find the most-specific root path
Map.Entry<String, File> mostSpecific = null;
for (Map.Entry<String, File> root : mRoots.entrySet()) {
final String rootPath = root.getValue().getPath();
if (path.startsWith(rootPath) && (mostSpecific == null
|| rootPath.length() > mostSpecific.getValue().getPath().length())) {
mostSpecific = root;
}
}
if (mostSpecific == null) {
throw new IllegalArgumentException(
"Failed to find configured root that contains " + path);
}
// Start at first char of path under root
final String rootPath = mostSpecific.getValue().getPath();
if (rootPath.endsWith("/")) {
path = path.substring(rootPath.length());
} else {
path = path.substring(rootPath.length() + 1);
}
// Encode the tag and path separately
path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/");
return new Uri.Builder().scheme("content")
.authority(mAuthority).encodedPath(path).build();
}
@Override
public File getFileForUri(Uri uri) {
String path = uri.getEncodedPath();
final int splitIndex = path.indexOf('/', 1);
final String tag = Uri.decode(path.substring(1, splitIndex));
path = Uri.decode(path.substring(splitIndex + 1));
final File root = mRoots.get(tag);
if (root == null) {
throw new IllegalArgumentException("Unable to find configured root for " + uri);
}
File file = new File(root, path);
try {
file = file.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
}
if (!file.getPath().startsWith(root.getPath())) {
throw new SecurityException("Resolved path jumped beyond configured root");
}
return file;
}
}
/**
* Copied from ContentResolver.java
*/
private static int modeToMode(String mode) {
int modeBits;
if ("r".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_ONLY;
} else if ("w".equals(mode) || "wt".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_TRUNCATE;
} else if ("wa".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_APPEND;
} else if ("rw".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_WRITE
| ParcelFileDescriptor.MODE_CREATE;
} else if ("rwt".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_WRITE
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_TRUNCATE;
} else {
throw new IllegalArgumentException("Invalid mode: " + mode);
}
return modeBits;
}
private static File buildPath(File base, String... segments) {
File cur = base;
for (String segment : segments) {
if (segment != null) {
cur = new File(cur, segment);
}
}
return cur;
}
private static String[] copyOf(String[] original, int newLength) {
final String[] result = new String[newLength];
System.arraycopy(original, 0, result, 0, newLength);
return result;
}
private static Object[] copyOf(Object[] original, int newLength) {
final Object[] result = new Object[newLength];
System.arraycopy(original, 0, result, 0, newLength);
return result;
}
}
@@ -0,0 +1,90 @@
/*
* Copyright 2018 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.content;
/*
* Created by Hippo on 2018/3/27.
*/
import android.app.Activity;
import android.os.Bundle;
import com.hippo.scene.SceneApplication;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public abstract class RecordingApplication extends SceneApplication {
private List<WeakReference<Activity>> list = new LinkedList<>();
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
list.add(new java.lang.ref.WeakReference<>(activity));
}
@Override
public void onActivityDestroyed(Activity activity) {
Iterator<WeakReference<Activity>> iterator = list.iterator();
while (iterator.hasNext()) {
WeakReference<Activity> reference = iterator.next();
Activity a = reference.get();
// Remove current activity and null
if (a == null || a == activity) {
iterator.remove();
}
}
}
@Override
public void onActivityStarted(Activity activity) {}
@Override
public void onActivityResumed(Activity activity) {}
@Override
public void onActivityPaused(Activity activity) {}
@Override
public void onActivityStopped(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
});
}
public void recreate() {
// Copy list
ArrayList<Activity> listCopy = new ArrayList<>(list.size());
for (WeakReference<Activity> reference: list) {
Activity activity = reference.get();
if (activity == null) continue;
listCopy.add(activity);
}
// Finish all activities
for (int i = listCopy.size() - 1; i >= 0; --i) {
listCopy.get(i).recreate();
}
}
}
@@ -0,0 +1,130 @@
/*
* 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.database;
/*
* Created by Hippo on 2017/9/3.
*/
import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.SparseArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MSQLiteBuilder {
public static final String COLUMN_ID = "_id";
private static final Map<Class, String> JAVA_TYPE_TO_SQLITE_TYPE = new HashMap<>();
static {
JAVA_TYPE_TO_SQLITE_TYPE.put(boolean.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(byte.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(short.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(int.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(long.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(float.class, "REAL NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(double.class, "REAL NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(String.class, "TEXT");
}
private static String javaTypeToSQLiteType(Class clazz) {
String type = JAVA_TYPE_TO_SQLITE_TYPE.get(clazz);
if (type == null) {
throw new IllegalStateException("Unknown type: " + clazz);
}
return type;
}
private int version = 0;
private List<String> statements;
private SparseArray<List<String>> statementsMap = new SparseArray<>();
/**
* Bump database version.
*/
public MSQLiteBuilder version(int version) {
if (version <= this.version) {
throw new IllegalStateException("New version must be bigger than current version. "
+ "current version: " + this.version + ", new version: " + version + ".");
}
this.version = version;
this.statements = new ArrayList<>();
this.statementsMap.put(version, this.statements);
return this;
}
/**
* Creates a table with int {@link #COLUMN_ID} primary key.
*/
public MSQLiteBuilder createTable(String table) {
return createTable(table, COLUMN_ID, int.class);
}
/**
* Creates a table.
*/
public MSQLiteBuilder createTable(String table, String column, Class clazz) {
return statement("CREATE TABLE " + table + " (" + column + " " + javaTypeToSQLiteType(clazz) + " PRIMARY KEY);");
}
/**
* Drops a table.
*/
public MSQLiteBuilder dropTable(String table) {
return statement("DROP TABLE " + table + ";");
}
/**
* Inserts a column to the table.
*/
public MSQLiteBuilder insertColumn(String table, String column, Class clazz) {
return statement("ALTER TABLE " + table + " ADD COLUMN " + column + " " + javaTypeToSQLiteType(clazz) + ";");
}
/**
* Add a statement.
*/
public MSQLiteBuilder statement(String statement) {
if (version == 0 || statements == null) {
throw new IllegalStateException("Call version() first!");
}
statements.add(statement);
return this;
}
/**
* Build a SQLiteOpenHelper from it.
*/
public SQLiteOpenHelper build(Context context, String name, int version) {
return new MSQLiteOpenHelper(context, name, version, this);
}
List<String> getStatements(int oldVersion, int newVersion) {
List<String> result = new ArrayList<>();
for (int i = oldVersion + 1; i <= newVersion; ++i) {
List<String> list = statementsMap.get(i);
if (list != null) {
result.addAll(list);
}
}
return result;
}
}
@@ -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.database;
/*
* Created by Hippo on 2017/9/4.
*/
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.hippo.util.SqlUtils;
class MSQLiteOpenHelper extends SQLiteOpenHelper {
private final int version;
private final MSQLiteBuilder builder;
public MSQLiteOpenHelper(Context context, String name, int version, MSQLiteBuilder builder) {
super(context, name, null, version);
this.version = version;
this.builder = builder;
}
@Override
public void onCreate(SQLiteDatabase db) {
onUpgrade(db, 0, version);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
for (String command : builder.getStatements(oldVersion, newVersion)) {
db.execSQL(command);
}
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
SqlUtils.dropAllTable(db);
onCreate(db);
}
}
@@ -46,13 +46,13 @@ public class AddDeleteDrawable extends Drawable {
/**
* @param context used to get the configuration for the drawable from
*/
public AddDeleteDrawable(Context context) {
public AddDeleteDrawable(Context context, int color) {
Resources resources = context.getResources();
mSize = resources.getDimensionPixelSize(R.dimen.add_size);
float barThickness = Math.round(resources.getDimension(R.dimen.add_thickness));
mPaint.setColor(resources.getColor(R.color.primary_drawable_light));
mPaint.setColor(color);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.MITER);
mPaint.setStrokeCap(Paint.Cap.BUTT);
@@ -28,6 +28,7 @@ import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.ColorInt;
import com.hippo.ehviewer.R;
import com.hippo.yorozuya.MathUtils;
@@ -66,11 +67,11 @@ public class DrawerArrowDrawable extends Drawable {
/**
* @param context used to get the configuration for the drawable from
*/
public DrawerArrowDrawable(Context context) {
public DrawerArrowDrawable(Context context, int color) {
Resources resources = context.getResources();
mPaint.setAntiAlias(true);
mPaint.setColor(resources.getColor(R.color.primary_drawable_light));
mPaint.setColor(color);
mSize = resources.getDimensionPixelSize(R.dimen.dad_drawable_size);
// round this because having this floating may cause bad measurements
mBarSize = Math.round(resources.getDimension(R.dimen.dad_bar_size));
@@ -144,6 +145,11 @@ public class DrawerArrowDrawable extends Drawable {
canvas.restore();
}
public void setColor(@ColorInt int color) {
mPaint.setColor(color);
invalidateSelf();
}
@Override
public void setAlpha(int i) {
mPaint.setAlpha(i);
@@ -0,0 +1,140 @@
/*
* 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.drawable;
/*
* Created by Hippo on 2017/9/6.
*/
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
public class TextDrawable extends Drawable {
private static final float STANDARD_TEXT_SIZE = 1000.0f;
private static final Paint STANDARD_PAINT = new Paint();
static {
STANDARD_PAINT.setTextSize(STANDARD_TEXT_SIZE);
}
private String text;
private float contentPercent;
private Paint backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int textColor = Color.BLACK;
private int backgroundColor = Color.BLACK;
private float x = 0.0f;
private float y = 0.0f;
private boolean textSizeDirty = false;
private Rect textBounds = new Rect();
public TextDrawable(String text, float contentPercent) {
this.text = text;
this.contentPercent = contentPercent;
STANDARD_PAINT.getTextBounds(text, 0, text.length(), textBounds);
}
public int getTextColor() {
return textColor;
}
public void setTextColor(int textColor) {
if (this.textColor != textColor) {
this.textColor = textColor;
invalidateSelf();
}
}
public int getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(int backgroundColor) {
if (this.backgroundColor != backgroundColor) {
this.backgroundColor = backgroundColor;
invalidateSelf();
}
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
textSizeDirty = true;
}
private void updateTextSizeIfDirty(Rect bounds) {
if (!textSizeDirty) {
return;
}
textSizeDirty = false;
int contentWidth = (int) (bounds.width() * contentPercent);
int contentHeight = (int) (bounds.height() * contentPercent);
float widthRatio = (float) contentWidth / (float) textBounds.width();
float heightRatio = (float) contentHeight / (float) textBounds.height();
float ratio = Math.min(widthRatio, heightRatio);
float textSize = STANDARD_TEXT_SIZE * ratio;
textPaint.setTextSize(textSize);
x = (bounds.width() - textBounds.width() * ratio) / 2 - textBounds.left * ratio;
y = (bounds.height() - textBounds.height() * ratio) / 2 - textBounds.top * ratio;
}
@Override
public void draw(@NonNull Canvas canvas) {
Rect bounds = getBounds();
if (!bounds.isEmpty()) {
// Draw background
backgroundPaint.setColor(backgroundColor);
canvas.drawRect(bounds, backgroundPaint);
if (!TextUtils.isEmpty(text)) {
// Draw text
updateTextSizeIfDirty(bounds);
textPaint.setColor(textColor);
canvas.drawText(text, x, y, textPaint);
}
}
}
@Override
public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
backgroundPaint.setColorFilter(colorFilter);
textPaint.setColorFilter(colorFilter);
invalidateSelf();
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
@@ -21,6 +21,7 @@ import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Debug;
import android.support.annotation.NonNull;
import com.hippo.scene.StageActivity;
@@ -37,7 +38,8 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
public class Crash {
public final class Crash {
private Crash() {}
@NonNull
private static String avoidNull(String str) {
@@ -67,14 +69,17 @@ public class Crash {
}
// Runtime
String topActivityClazzName = null;
String topSceneClazzName = null;
String topActivityClazzName = "null";
String topSceneClazzName = "null";
try {
Activity topActivity = ((EhApplication) context.getApplicationContext()).getTopActivity();
if (null != topActivity) {
topActivityClazzName = topActivity.getClass().getName();
if (topActivity instanceof StageActivity) {
topSceneClazzName = ((StageActivity) topActivity).getTopSceneClazzName();
Class<?> clazz = ((StageActivity) topActivity).getTopSceneClass();
if (clazz != null) {
topSceneClazzName = clazz.getName();
}
}
}
} catch (Throwable e) {
@@ -109,8 +114,10 @@ public class Crash {
fw.write("INCREMENTAL=");fw.write(Build.VERSION.INCREMENTAL);fw.write("\r\n");
fw.write("RELEASE=");fw.write(Build.VERSION.RELEASE);fw.write("\r\n");
fw.write("SDK=");fw.write(Integer.toString(Build.VERSION.SDK_INT));fw.write("\r\n");
fw.write("MEMORY=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getAppAllocatedMemory(), false));
fw.write("/");fw.write(FileUtils.humanReadableByteCount(OSUtils.getTotalMemory(), false));fw.write("\r\n");
fw.write("MEMORY=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getAppAllocatedMemory(), false));fw.write("\r\n");
fw.write("MEMORY_NATIVE=");fw.write(FileUtils.humanReadableByteCount(Debug.getNativeHeapAllocatedSize(), false));fw.write("\r\n");
fw.write("MEMORY_MAX=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getAppMaxMemory(), false));fw.write("\r\n");
fw.write("MEMORY_TOTAL=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getTotalMemory(), false));fw.write("\r\n");
fw.write("\r\n");
}
@@ -26,13 +26,13 @@ import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.LruCache;
import android.util.Log;
import com.hippo.beerbelly.SimpleDiskCache;
import com.hippo.conaco.Conaco;
import com.hippo.content.RecordingApplication;
import com.hippo.ehviewer.client.EhClient;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhDns;
import com.hippo.ehviewer.client.EhEngine;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.data.GalleryDetail;
import com.hippo.ehviewer.download.DownloadManager;
import com.hippo.ehviewer.spider.SpiderDen;
@@ -40,8 +40,6 @@ import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.image.Image;
import com.hippo.image.ImageBitmap;
import com.hippo.network.StatusCodeException;
import com.hippo.okhttp.CookieDB;
import com.hippo.scene.SceneApplication;
import com.hippo.text.Html;
import com.hippo.unifile.UniFile;
import com.hippo.util.BitmapUtils;
@@ -50,23 +48,20 @@ import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IntIdGenerator;
import com.hippo.yorozuya.OSUtils;
import com.hippo.yorozuya.SimpleHandler;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
public class EhApplication extends SceneApplication implements Thread.UncaughtExceptionHandler {
public class EhApplication extends RecordingApplication implements Thread.UncaughtExceptionHandler {
private static final String TAG = EhApplication.class.getSimpleName();
public static final boolean BETA = false;
public static final boolean AUTO_UPDATE = true;
private static final boolean DEBUG_CONACO = false;
private static final boolean DEBUG_PRINT_NATIVE_MEMORY = false;
@@ -76,7 +71,7 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
private Thread.UncaughtExceptionHandler mDefaultHandler;
private final IntIdGenerator mIdGenerator = new IntIdGenerator();
private final WeakHashMap<Integer, Object> mGlobalStuffMap = new WeakHashMap<>();
private final HashMap<Integer, Object> mGlobalStuffMap = new HashMap<>();
private EhCookieStore mEhCookieStore;
private EhClient mEhClient;
private OkHttpClient mOkHttpClient;
@@ -85,6 +80,7 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
private LruCache<Long, GalleryDetail> mGalleryDetailCache;
private SimpleDiskCache mSpiderInfoCache;
private DownloadManager mDownloadManager;
private Hosts mHosts;
private final List<Activity> mActivityList = new ArrayList<>();
@@ -97,7 +93,6 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
super.onCreate();
GetText.initialize(this);
CookieDB.initialize(this);
StatusCodeException.initialize(this);
Settings.initialize(this);
ReadableTime.initialize(this);
@@ -116,13 +111,14 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
Analytics.start(this);
}
// Check no media file
UniFile downloadLocation = Settings.getDownloadLocation();
if (Settings.getMediaScan()) {
CommonOperations.removeNoMediaFile(downloadLocation);
} else {
CommonOperations.ensureNoMediaFile(downloadLocation);
}
// Disable no media file checker for now. Some devices stuck here.
// // Check no media file
// UniFile downloadLocation = Settings.getDownloadLocation();
// if (Settings.getMediaScan()) {
// CommonOperations.removeNoMediaFile(downloadLocation);
// } else {
// CommonOperations.ensureNoMediaFile(downloadLocation);
// }
// Clear temp dir
clearTempDir();
@@ -152,6 +148,9 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
if (null != dir) {
FileUtils.deleteContent(dir);
}
// Add .nomedia to external temp dir
CommonOperations.ensureNoMediaFile(UniFile.fromFile(AppConfig.getExternalTempDir()));
}
private void update() {
@@ -159,29 +158,6 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
if (version < 52) {
Settings.putGuideGallery(true);
}
if (version < 56) { // Make cookie long live
HttpUrl eUrl = HttpUrl.parse(EhUrl.HOST_E);
HttpUrl exUrl = HttpUrl.parse(EhUrl.HOST_EX);
EhCookieStore cookieStore = getEhCookieStore(this);
Cookie c;
c = cookieStore.get(eUrl, EhCookieStore.KEY_IPD_MEMBER_ID);
if (null != c) {
cookieStore.add(EhCookieStore.newCookie(c, c.domain(), true, true, true));
}
c = cookieStore.get(eUrl, EhCookieStore.KEY_IPD_PASS_HASH);
if (null != c) {
cookieStore.add(EhCookieStore.newCookie(c, c.domain(), true, true, true));
}
c = cookieStore.get(exUrl, EhCookieStore.KEY_IPD_MEMBER_ID);
if (null != c) {
cookieStore.add(EhCookieStore.newCookie(c, c.domain(), true, true, true));
}
c = cookieStore.get(exUrl, EhCookieStore.KEY_IPD_PASS_HASH);
if (null != c) {
cookieStore.add(EhCookieStore.newCookie(c, c.domain(), true, true, true));
}
}
}
public void clearMemoryCache() {
@@ -243,7 +219,7 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
public static EhCookieStore getEhCookieStore(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mEhCookieStore == null) {
application.mEhCookieStore = new EhCookieStore();
application.mEhCookieStore = new EhCookieStore(context);
}
return application.mEhCookieStore;
}
@@ -266,6 +242,7 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.cookieJar(getEhCookieStore(application))
.dns(new EhDns(application))
.build();
}
return application.mOkHttpClient;
@@ -331,6 +308,15 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
return application.mDownloadManager;
}
@NonNull
public static Hosts getHosts(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mHosts == null) {
application.mHosts = new Hosts(application, "hosts.db");
}
return application.mHosts;
}
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
+20 -2
View File
@@ -93,6 +93,19 @@ public class EhDB {
switch (oldVersion) {
case 1: // 1 to 2
FilterDao.createTable(db, true);
break;
case 2: // add ENABLE column to table FILTER
db.execSQL("CREATE TABLE " + "\"FILTER2\" (" +
"\"_id\" INTEGER PRIMARY KEY ," +
"\"MODE\" INTEGER NOT NULL ," +
"\"TEXT\" TEXT," +
"\"ENABLE\" INTEGER);");
db.execSQL("INSERT INTO \"FILTER2\" (" +
"_id, MODE, TEXT, ENABLE)" +
"SELECT _id, MODE, TEXT, 1 FROM FILTER;");
db.execSQL("DROP TABLE FILTER");
db.execSQL("ALTER TABLE FILTER2 RENAME TO FILTER");
break;
}
}
@@ -449,7 +462,7 @@ public class EhDB {
public static synchronized List<GalleryInfo> getAllLocalFavorites() {
LocalFavoritesDao dao = sDaoSession.getLocalFavoritesDao();
List<LocalFavoriteInfo> list = dao.queryBuilder().orderAsc(LocalFavoritesDao.Properties.Time).list();
List<LocalFavoriteInfo> list = dao.queryBuilder().orderDesc(LocalFavoritesDao.Properties.Time).list();
List<GalleryInfo> result = new ArrayList<>();
result.addAll(list);
return result;
@@ -458,7 +471,7 @@ public class EhDB {
public static synchronized List<GalleryInfo> searchLocalFavorites(String query) {
query = SqlUtils.sqlEscapeString("%" + query+ "%");
LocalFavoritesDao dao = sDaoSession.getLocalFavoritesDao();
List<LocalFavoriteInfo> list = dao.queryBuilder().orderAsc(LocalFavoritesDao.Properties.Time)
List<LocalFavoriteInfo> list = dao.queryBuilder().orderDesc(LocalFavoritesDao.Properties.Time)
.where(LocalFavoritesDao.Properties.Title.like(query)).list();
List<GalleryInfo> result = new ArrayList<>();
result.addAll(list);
@@ -606,6 +619,11 @@ public class EhDB {
sDaoSession.getFilterDao().delete(filter);
}
public static synchronized void triggerFilter(Filter filter) {
filter.setEnable(!filter.enable);
sDaoSession.getFilterDao().update(filter);
}
public static synchronized boolean exportDB(Context context, File file) {
File dbFile = context.getDatabasePath("eh.db");
if (null == dbFile || !dbFile.isFile()) {
@@ -0,0 +1,350 @@
/*
* Copyright 2018 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;
/*
* Created by Hippo on 2018/3/21.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.Nullable;
import android.util.Pair;
import com.hippo.database.MSQLiteBuilder;
import com.hippo.util.SqlUtils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
public class Hosts {
private static final int VERSION_1 = 1;
private static final String TABLE_HOSTS = "HOSTS";
private static final String COLUMN_HOST = "HOST";
private static final String COLUMN_IP = "IP";
private static final int DB_VERSION = VERSION_1;
private final SQLiteOpenHelper helper;
private final SQLiteDatabase db;
public Hosts(Context context, String name) {
helper = new MSQLiteBuilder()
.version(VERSION_1)
.createTable(TABLE_HOSTS)
.insertColumn(TABLE_HOSTS, COLUMN_HOST, String.class)
.insertColumn(TABLE_HOSTS, COLUMN_IP, String.class)
.build(context, name, DB_VERSION);
db = helper.getWritableDatabase();
}
/**
* Gets a InetAddress with the host.
*/
@Nullable
public InetAddress get(String host) {
if (!isValidHost(host)) {
return null;
}
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_HOSTS + " WHERE " + COLUMN_HOST + " = ?;", new String[] {host});
try {
if (cursor.moveToNext()) {
String ip = SqlUtils.getString(cursor, COLUMN_IP, null);
return toInetAddress(host, ip);
} else {
return null;
}
} finally {
cursor.close();
}
}
private boolean contains(String host) {
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_HOSTS + " WHERE " + COLUMN_HOST + " = ?;", new String[] {host});
try {
return cursor.moveToNext();
} finally {
cursor.close();
}
}
/**
* Puts the host-ip pair into this hosts.
*/
public boolean put(String host, String ip) {
if (!isValidHost(host) || !isValidIp(ip)) {
return false;
}
ContentValues values = new ContentValues();
values.put(COLUMN_HOST, host);
values.put(COLUMN_IP, ip);
if (contains(host)) {
db.update(TABLE_HOSTS, values, COLUMN_HOST + " = ?", new String[] { host });
} else {
db.insert(TABLE_HOSTS, null, values);
}
return true;
}
/**
* Puts delete the entry with the host.
*/
public void delete(String host) {
db.delete(TABLE_HOSTS, COLUMN_HOST + " = ?", new String[] { host });
}
/**
* Get all data from this host.
*/
public List<Pair<String, String>> getAll() {
List<Pair<String, String>> result = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_HOSTS + ";", null);
try {
while (cursor.moveToNext()) {
String host = SqlUtils.getString(cursor, COLUMN_HOST, null);
String ip = SqlUtils.getString(cursor, COLUMN_IP, null);
InetAddress inetAddress = toInetAddress(host, ip);
if (inetAddress == null) {
continue;
}
result.add(new Pair<>(host, ip));
}
} finally {
cursor.close();
}
return result;
}
@Nullable
public static InetAddress toInetAddress(String host, String ip) {
if (!isValidHost(host)) {
return null;
}
if (ip == null) {
return null;
}
byte[] bytes = parseV4(ip);
if (bytes == null) {
bytes = parseV6(ip);
}
if (bytes == null) {
return null;
}
try {
return InetAddress.getByAddress(host, bytes);
} catch (UnknownHostException e) {
return null;
}
}
/**
* Returns true if the host is valid.
*/
public static boolean isValidHost(String host) {
if (host == null) {
return false;
}
if (host.length() > 253) {
return false;
}
int labelLength = 0;
for (int i = 0, n = host.length(); i < n; i++) {
char ch = host.charAt(i);
if (ch == '.') {
if (labelLength < 1 || labelLength > 63) {
return false;
}
labelLength = 0;
} else {
labelLength++;
}
if ((ch < 'a' || ch > 'z') && (ch < '0' || ch > '9') && ch != '-' && ch != '.') {
return false;
}
}
if (labelLength < 1 || labelLength > 63) {
return false;
}
return true;
}
/**
* Returns true if the ip is valid.
*/
public static boolean isValidIp(String ip) {
return ip != null && (parseV4(ip) != null || parseV6(ip) != null);
}
// org.xbill.DNS.Address.parseV4
@Nullable
private static byte[] parseV4(String s) {
int numDigits;
int currentOctet;
byte [] values = new byte[4];
int currentValue;
int length = s.length();
currentOctet = 0;
currentValue = 0;
numDigits = 0;
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
/* Can't have more than 3 digits per octet. */
if (numDigits == 3)
return null;
/* Octets shouldn't start with 0, unless they are 0. */
if (numDigits > 0 && currentValue == 0)
return null;
numDigits++;
currentValue *= 10;
currentValue += (c - '0');
/* 255 is the maximum value for an octet. */
if (currentValue > 255)
return null;
} else if (c == '.') {
/* Can't have more than 3 dots. */
if (currentOctet == 3)
return null;
/* Two consecutive dots are bad. */
if (numDigits == 0)
return null;
values[currentOctet++] = (byte) currentValue;
currentValue = 0;
numDigits = 0;
} else
return null;
}
/* Must have 4 octets. */
if (currentOctet != 3)
return null;
/* The fourth octet can't be empty. */
if (numDigits == 0)
return null;
values[currentOctet] = (byte) currentValue;
return values;
}
// org.xbill.DNS.Address.parseV6
@Nullable
private static byte[] parseV6(String s) {
int range = -1;
byte [] data = new byte[16];
String [] tokens = s.split(":", -1);
int first = 0;
int last = tokens.length - 1;
if (tokens[0].length() == 0) {
// If the first two tokens are empty, it means the string
// started with ::, which is fine. If only the first is
// empty, the string started with :, which is bad.
if (last - first > 0 && tokens[1].length() == 0)
first++;
else
return null;
}
if (tokens[last].length() == 0) {
// If the last two tokens are empty, it means the string
// ended with ::, which is fine. If only the last is
// empty, the string ended with :, which is bad.
if (last - first > 0 && tokens[last - 1].length() == 0)
last--;
else
return null;
}
if (last - first + 1 > 8)
return null;
int i, j;
for (i = first, j = 0; i <= last; i++) {
if (tokens[i].length() == 0) {
if (range >= 0)
return null;
range = j;
continue;
}
if (tokens[i].indexOf('.') >= 0) {
// An IPv4 address must be the last component
if (i < last)
return null;
// There can't have been more than 6 components.
if (i > 6)
return null;
byte [] v4addr = parseV4(tokens[i]);
if (v4addr == null)
return null;
for (int k = 0; k < 4; k++)
data[j++] = v4addr[k];
break;
}
try {
for (int k = 0; k < tokens[i].length(); k++) {
char c = tokens[i].charAt(k);
if (Character.digit(c, 16) < 0)
return null;
}
int x = Integer.parseInt(tokens[i], 16);
if (x > 0xFFFF || x < 0)
return null;
data[j++] = (byte)(x >>> 8);
data[j++] = (byte)(x & 0xFF);
}
catch (NumberFormatException e) {
return null;
}
}
if (j < 16 && range < 0)
return null;
if (range >= 0) {
int empty = 16 - j;
System.arraycopy(data, range, data, range + empty, j - range);
for (i = range; i < range + empty; i++)
data[i] = 0;
}
return data;
}
}
+192 -31
View File
@@ -29,15 +29,15 @@ import android.util.Log;
import com.hippo.ehviewer.client.EhConfig;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.FavListUrlBuilder;
import com.hippo.ehviewer.gallery.gl.GalleryView;
import com.hippo.ehviewer.gallery.gl.ImageView;
import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.glgallery.GalleryView;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.NumberUtils;
import junit.framework.Assert;
import java.io.File;
public class Settings {
@@ -237,6 +237,17 @@ public class Settings {
/********************
****** Eh
********************/
public static final String KEY_THEME = "theme";
public static final int THEME_LIGHT = 0;
public static final int THEME_DARK = 1;
public static final int THEME_BLACK = 2;
private static final int DEFAULT_THEME = THEME_LIGHT;
public static int getTheme() {
return getIntFromStr(KEY_THEME, DEFAULT_THEME);
}
public static final String KEY_GALLERY_SITE = "gallery_site";
private static final int DEFAULT_GALLERY_SITE = 1;
@@ -300,6 +311,13 @@ public class Settings {
return getIntFromStr(KEY_THUMB_RESOLUTION, DEFAULT_THUMB_RESOLUTION);
}
private static final String KEY_FIX_THUMB_URL = "fix_thumb_url";
private static final boolean DEFAULT_FIX_THUMB_URL = false;
public static boolean getFixThumbUrl() {
return getBoolean(KEY_FIX_THUMB_URL, DEFAULT_FIX_THUMB_URL);
}
private static final String KEY_SHOW_JPN_TITLE = "show_jpn_title";
private static final boolean DEFAULT_SHOW_JPN_TITLE = false;
@@ -307,6 +325,13 @@ public class Settings {
return getBoolean(KEY_SHOW_JPN_TITLE, DEFAULT_SHOW_JPN_TITLE);
}
private static final String KEY_SHOW_GALLERY_PAGES = "show_gallery_pages";
private static final boolean DEFAULT_SHOW_GALLERY_PAGES = false;
public static boolean getShowGalleryPages() {
return getBoolean(KEY_SHOW_GALLERY_PAGES, DEFAULT_SHOW_GALLERY_PAGES);
}
public static final String KEY_DEFAULT_CATEGORIES = "default_categories";
public static final int DEFAULT_DEFAULT_CATEGORIES = EhUtils.ALL_CATEGORY;
@@ -434,7 +459,7 @@ public class Settings {
}
private static final String KEY_READING_DIRECTION = "reading_direction";
private static final int DEFAULT_READING_DIRECTION = GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT;
private static final int DEFAULT_READING_DIRECTION = GalleryView.LAYOUT_RIGHT_TO_LEFT;
@GalleryView.LayoutMode
public static int getReadingDirection() {
@@ -446,11 +471,11 @@ public class Settings {
}
private static final String KEY_PAGE_SCALING = "page_scaling";
private static final int DEFAULT_PAGE_SCALING = ImageView.SCALE_FIT;
private static final int DEFAULT_PAGE_SCALING = GalleryView.SCALE_FIT;
@ImageView.Scale
@GalleryView.ScaleMode
public static int getPageScaling() {
return ImageView.sanitizeScaleMode(getIntFromStr(KEY_PAGE_SCALING, DEFAULT_PAGE_SCALING));
return GalleryView.sanitizeScaleMode(getIntFromStr(KEY_PAGE_SCALING, DEFAULT_PAGE_SCALING));
}
public static void putPageScaling(int value) {
@@ -458,11 +483,11 @@ public class Settings {
}
private static final String KEY_START_POSITION = "start_position";
private static final int DEFAULT_START_POSITION = ImageView.START_POSITION_TOP_RIGHT;
private static final int DEFAULT_START_POSITION = GalleryView.START_POSITION_TOP_RIGHT;
@ImageView.StartPosition
@GalleryView.StartPosition
public static int getStartPosition() {
return ImageView.sanitizeStartPosition(getIntFromStr(KEY_START_POSITION, DEFAULT_START_POSITION));
return GalleryView.sanitizeStartPosition(getIntFromStr(KEY_START_POSITION, DEFAULT_START_POSITION));
}
public static void putStartPosition(int value) {
@@ -513,6 +538,17 @@ public class Settings {
putBoolean(KEY_SHOW_BATTERY, value);
}
private static final String KEY_SHOW_PAGE_INTERVAL = "gallery_show_page_interval";
private static final boolean DEFAULT_SHOW_PAGE_INTERVAL = true;
public static boolean getShowPageInterval() {
return getBoolean(KEY_SHOW_PAGE_INTERVAL, DEFAULT_SHOW_PAGE_INTERVAL);
}
public static void putShowPageInterval(boolean value) {
putBoolean(KEY_SHOW_PAGE_INTERVAL, value);
}
private static final String KEY_VOLUME_PAGE = "volume_page";
private static final boolean DEFAULT_VOLUME_PAGE = false;
@@ -557,6 +593,19 @@ public class Settings {
putInt(KEY_SCREEN_LIGHTNESS, value);
}
/********************
****** Privacy and Security
********************/
public static final String KEY_SEC_SECURITY = "enable_secure";
public static final boolean VALUE_SEC_SECURITY = false;
public static boolean getEnabledSecurity() {
return getBoolean(KEY_SEC_SECURITY, VALUE_SEC_SECURITY);
}
public static void putEnabledSecurity(boolean value) {
putBoolean(KEY_READING_FULLSCREEN, value);
}
/********************
****** Download
********************/
@@ -687,26 +736,42 @@ public class Settings {
/********************
****** Favorites
********************/
public static final String KEY_FAV_CAT_0 = "fav_cat_0";
public static final String KEY_FAV_CAT_1 = "fav_cat_1";
public static final String KEY_FAV_CAT_2 = "fav_cat_2";
public static final String KEY_FAV_CAT_3 = "fav_cat_3";
public static final String KEY_FAV_CAT_4 = "fav_cat_4";
public static final String KEY_FAV_CAT_5 = "fav_cat_5";
public static final String KEY_FAV_CAT_6 = "fav_cat_6";
public static final String KEY_FAV_CAT_7 = "fav_cat_7";
public static final String KEY_FAV_CAT_8 = "fav_cat_8";
public static final String KEY_FAV_CAT_9 = "fav_cat_9";
public static final String DEFAULT_FAV_CAT_0 = "Favorites 0";
public static final String DEFAULT_FAV_CAT_1 = "Favorites 1";
public static final String DEFAULT_FAV_CAT_2 = "Favorites 2";
public static final String DEFAULT_FAV_CAT_3 = "Favorites 3";
public static final String DEFAULT_FAV_CAT_4 = "Favorites 4";
public static final String DEFAULT_FAV_CAT_5 = "Favorites 5";
public static final String DEFAULT_FAV_CAT_6 = "Favorites 6";
public static final String DEFAULT_FAV_CAT_7 = "Favorites 7";
public static final String DEFAULT_FAV_CAT_8 = "Favorites 8";
public static final String DEFAULT_FAV_CAT_9 = "Favorites 9";
private static final String KEY_FAV_CAT_0 = "fav_cat_0";
private static final String KEY_FAV_CAT_1 = "fav_cat_1";
private static final String KEY_FAV_CAT_2 = "fav_cat_2";
private static final String KEY_FAV_CAT_3 = "fav_cat_3";
private static final String KEY_FAV_CAT_4 = "fav_cat_4";
private static final String KEY_FAV_CAT_5 = "fav_cat_5";
private static final String KEY_FAV_CAT_6 = "fav_cat_6";
private static final String KEY_FAV_CAT_7 = "fav_cat_7";
private static final String KEY_FAV_CAT_8 = "fav_cat_8";
private static final String KEY_FAV_CAT_9 = "fav_cat_9";
private static final String DEFAULT_FAV_CAT_0 = "Favorites 0";
private static final String DEFAULT_FAV_CAT_1 = "Favorites 1";
private static final String DEFAULT_FAV_CAT_2 = "Favorites 2";
private static final String DEFAULT_FAV_CAT_3 = "Favorites 3";
private static final String DEFAULT_FAV_CAT_4 = "Favorites 4";
private static final String DEFAULT_FAV_CAT_5 = "Favorites 5";
private static final String DEFAULT_FAV_CAT_6 = "Favorites 6";
private static final String DEFAULT_FAV_CAT_7 = "Favorites 7";
private static final String DEFAULT_FAV_CAT_8 = "Favorites 8";
private static final String DEFAULT_FAV_CAT_9 = "Favorites 9";
private static final String KEY_FAV_COUNT_0 = "fav_count_0";
private static final String KEY_FAV_COUNT_1 = "fav_count_1";
private static final String KEY_FAV_COUNT_2 = "fav_count_2";
private static final String KEY_FAV_COUNT_3 = "fav_count_3";
private static final String KEY_FAV_COUNT_4 = "fav_count_4";
private static final String KEY_FAV_COUNT_5 = "fav_count_5";
private static final String KEY_FAV_COUNT_6 = "fav_count_6";
private static final String KEY_FAV_COUNT_7 = "fav_count_7";
private static final String KEY_FAV_COUNT_8 = "fav_count_8";
private static final String KEY_FAV_COUNT_9 = "fav_count_9";
private static final String KEY_FAV_LOCAL = "fav_local";
private static final String KEY_FAV_CLOUD = "fav_cloud";
private static final int DEFAULT_FAV_COUNT = 0;
public static String[] getFavCat() {
String[] favCat = new String[10];
@@ -724,7 +789,7 @@ public class Settings {
}
public static void putFavCat(String[] value) {
AssertUtils.assertEquals(10, value.length);
Assert.assertEquals(10, value.length);
sSettingsPre.edit()
.putString(KEY_FAV_CAT_0, value[0])
.putString(KEY_FAV_CAT_1, value[1])
@@ -739,6 +804,53 @@ public class Settings {
.apply();
}
public static int[] getFavCount() {
int[] favCount = new int[10];
favCount[0] = sSettingsPre.getInt(KEY_FAV_COUNT_0, DEFAULT_FAV_COUNT);
favCount[1] = sSettingsPre.getInt(KEY_FAV_COUNT_1, DEFAULT_FAV_COUNT);
favCount[2] = sSettingsPre.getInt(KEY_FAV_COUNT_2, DEFAULT_FAV_COUNT);
favCount[3] = sSettingsPre.getInt(KEY_FAV_COUNT_3, DEFAULT_FAV_COUNT);
favCount[4] = sSettingsPre.getInt(KEY_FAV_COUNT_4, DEFAULT_FAV_COUNT);
favCount[5] = sSettingsPre.getInt(KEY_FAV_COUNT_5, DEFAULT_FAV_COUNT);
favCount[6] = sSettingsPre.getInt(KEY_FAV_COUNT_6, DEFAULT_FAV_COUNT);
favCount[7] = sSettingsPre.getInt(KEY_FAV_COUNT_7, DEFAULT_FAV_COUNT);
favCount[8] = sSettingsPre.getInt(KEY_FAV_COUNT_8, DEFAULT_FAV_COUNT);
favCount[9] = sSettingsPre.getInt(KEY_FAV_COUNT_9, DEFAULT_FAV_COUNT);
return favCount;
}
public static void putFavCount(int[] count) {
Assert.assertEquals(10, count.length);
sSettingsPre.edit()
.putInt(KEY_FAV_COUNT_0, count[0])
.putInt(KEY_FAV_COUNT_1, count[1])
.putInt(KEY_FAV_COUNT_2, count[2])
.putInt(KEY_FAV_COUNT_3, count[3])
.putInt(KEY_FAV_COUNT_4, count[4])
.putInt(KEY_FAV_COUNT_5, count[5])
.putInt(KEY_FAV_COUNT_6, count[6])
.putInt(KEY_FAV_COUNT_7, count[7])
.putInt(KEY_FAV_COUNT_8, count[8])
.putInt(KEY_FAV_COUNT_9, count[9])
.apply();
}
public static int getFavLocalCount() {
return sSettingsPre.getInt(KEY_FAV_LOCAL, DEFAULT_FAV_COUNT);
}
public static void putFavLocalCount(int count) {
sSettingsPre.edit().putInt(KEY_FAV_LOCAL, count).apply();
}
public static int getFavCloudCount() {
return sSettingsPre.getInt(KEY_FAV_CLOUD, DEFAULT_FAV_COUNT);
}
public static void putFavCloudCount(int count) {
sSettingsPre.edit().putInt(KEY_FAV_CLOUD, count).apply();
}
private static final String KEY_RECENT_FAV_CAT = "recent_fav_cat";
private static final int DEFAULT_RECENT_FAV_CAT = FavListUrlBuilder.FAV_CAT_ALL;
@@ -855,6 +967,8 @@ public class Settings {
********************/
private static final String KEY_BETA_UPDATE_CHANNEL = "beta_update_channel";
private static final boolean DEFAULT_BETA_UPDATE_CHANNEL = EhApplication.BETA;
private static final String KEY_AUTO_CHECK_FOR_UPDATES = "auto_check_for_updates";
private static final boolean DEFAULT_AUTO_CHECK_FOR_UPDATES = EhApplication.AUTO_UPDATE;
public static boolean getBetaUpdateChannel() {
return getBoolean(KEY_BETA_UPDATE_CHANNEL, DEFAULT_BETA_UPDATE_CHANNEL);
@@ -864,6 +978,10 @@ public class Settings {
putBoolean(KEY_BETA_UPDATE_CHANNEL, value);
}
public static boolean getAutoCheckUpdateEnable() {
return getBoolean(KEY_AUTO_CHECK_FOR_UPDATES, DEFAULT_AUTO_CHECK_FOR_UPDATES);
}
/********************
****** Crash
********************/
@@ -904,6 +1022,16 @@ public class Settings {
putString(KEY_SECURITY, value);
}
public static final String KEY_ENABLE_FINGERPRINT = "enable_fingerprint";
public static boolean getEnableFingerprint() {
return getBoolean(KEY_ENABLE_FINGERPRINT, false);
}
public static void putEnableFingerprint(boolean value) {
putBoolean(KEY_ENABLE_FINGERPRINT, value);
}
public static final String KEY_READ_CACHE_SIZE = "read_cache_size";
public static final int DEFAULT_READ_CACHE_SIZE = 160;
@@ -911,6 +1039,28 @@ public class Settings {
return getIntFromStr(KEY_READ_CACHE_SIZE, DEFAULT_READ_CACHE_SIZE);
}
public static final String KEY_BUILT_IN_HOSTS = "built_in_hosts";
private static final boolean DEFAULT_BUILT_IN_HOSTS = false;
public static boolean getBuiltInHosts() {
return getBoolean(KEY_BUILT_IN_HOSTS, DEFAULT_BUILT_IN_HOSTS);
}
public static void putBuiltInHosts(boolean value) {
putBoolean(KEY_BUILT_IN_HOSTS, value);
}
public static final String KEY_APP_LANGUAGE = "app_language";
private static final String DEFAULT_APP_LANGUAGE = "system";
public static String getAppLanguage() {
return getString(KEY_APP_LANGUAGE, DEFAULT_APP_LANGUAGE);
}
public static void putAppLanguage(String value) {
putString(KEY_APP_LANGUAGE, value);
}
/********************
****** Guide
********************/
@@ -968,4 +1118,15 @@ public class Settings {
public static void putGuideGallery(boolean value) {
putBoolean(KEY_GUIDE_GALLERY, value);
}
private static final String KEY_CLIPBOARD_TEXT_HASH_CODE = "clipboard_text_hash_code";
private static final int DEFAULT_CLIPBOARD_TEXT_HASH_CODE = 0;
public static int getClipboardTextHashCode() {
return getInt(KEY_CLIPBOARD_TEXT_HASH_CODE, DEFAULT_CLIPBOARD_TEXT_HASH_CODE);
}
public static void putClipboardTextHashCode(int value) {
putInt(KEY_CLIPBOARD_TEXT_HASH_CODE, value);
}
}
@@ -59,6 +59,8 @@ public class EhClient {
public static final int METHOD_GET_PROFILE = 14;
public static final int METHOD_VOTE_COMMENT = 15;
public static final int METHOD_IMAGE_SEARCH = 16;
public static final int METHOD_ARCHIVE_LIST = 17;
public static final int METHOD_DOWNLOAD_ARCHIVE = 18;
private final ThreadPoolExecutor mRequestThreadPool;
private final OkHttpClient mOkHttpClient;
@@ -151,7 +153,7 @@ public class EhClient {
try {
switch (mMethod) {
case METHOD_SIGN_IN:
return EhEngine.signIn(this, mOkHttpClient, (String) params[0], (String) params[1]);
return EhEngine.signIn(this, mOkHttpClient, (String) params[0], (String) params[1], (String) params[2], (String) params[3]);
case METHOD_GET_GALLERY_LIST:
return EhEngine.getGalleryList(this, mOkHttpClient, (String) params[0]);
case METHOD_FILL_GALLERY_LIST_BY_API:
@@ -184,6 +186,10 @@ public class EhClient {
return EhEngine.voteComment(this, mOkHttpClient, (Long) params[0], (String) params[1], (Long) params[2], (String) params[3], (Long) params[4], (Integer) params[5]);
case METHOD_IMAGE_SEARCH:
return EhEngine.imageSearch(this, mOkHttpClient, (File) params[0], (Boolean) params[1], (Boolean) params[2], (Boolean) params[3]);
case METHOD_ARCHIVE_LIST:
return EhEngine.getArchiveList(this, mOkHttpClient, (String) params[0]);
case METHOD_DOWNLOAD_ARCHIVE:
return EhEngine.downloadArchive(this, mOkHttpClient, (Long) params[0], (String) params[1], (String) params[2], (String) params[3]);
default:
return new IllegalStateException("Can't detect method " + mMethod);
}
@@ -299,6 +299,7 @@ public class EhConfig implements Cloneable {
public static final int NAMESPACES_MALE = 0x40;
public static final int NAMESPACES_FEMALE = 0x80;
public static final String JAPANESE_ORIGINAL = "0";
public static final String JAPANESE_TRANSLATED = "1024";
public static final String JAPANESE_REWRITE = "2048";
public static final String ENGLISH_ORIGINAL = "1";
@@ -16,7 +16,9 @@
package com.hippo.ehviewer.client;
import com.hippo.okhttp.CookieDBStore;
import android.content.Context;
import com.hippo.network.CookieRepository;
import java.util.ArrayList;
import java.util.Collections;
@@ -24,29 +26,34 @@ import java.util.List;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
import okhttp3.Request;
public class EhCookieStore extends CookieDBStore {
public class EhCookieStore extends CookieRepository {
public static final String KEY_IPD_MEMBER_ID = "ipb_member_id";
public static final String KEY_IPD_PASS_HASH = "ipb_pass_hash";
public static final String KEY_IGNEOUS = "igneous";
public static final Cookie sTipsCookie =
new Cookie.Builder()
.name(EhConfig.KEY_CONTENT_WARNING)
.value(EhConfig.CONTENT_WARNING_NOT_SHOW)
.domain(EhUrl.DOMAIN_G)
.domain(EhUrl.DOMAIN_E)
.path("/")
.expiresAt(Long.MAX_VALUE)
.build();
public EhCookieStore(Context context) {
super(context, "okhttp3-cookie.db");
}
public void signOut() {
removeAll();
clear();
}
public boolean hasSignedIn() {
return contain(EhUrl.DOMAIN_EX, KEY_IPD_MEMBER_ID) &&
contain(EhUrl.DOMAIN_EX, KEY_IPD_PASS_HASH);
HttpUrl url = HttpUrl.parse(EhUrl.HOST_E);
return contains(url, KEY_IPD_MEMBER_ID) &&
contains(url, KEY_IPD_PASS_HASH);
}
public static Cookie newCookie(Cookie cookie, String newDomain, boolean forcePersistent,
@@ -78,66 +85,29 @@ public class EhCookieStore extends CookieDBStore {
}
@Override
public List<Cookie> loadForRequest(HttpUrl url, Request request) {
List<Cookie> cookies = super.loadForRequest(url, request);
Object tag = request.tag();
String host = url.host();
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = super.loadForRequest(url);
boolean checkTips = domainMatch(host, EhUrl.DOMAIN_G);
boolean checkUconfig = (domainMatch(host, EhUrl.DOMAIN_E) || domainMatch(host, EhUrl.DOMAIN_EX)) && tag instanceof EhConfig;
boolean checkTips = domainMatch(url, EhUrl.DOMAIN_E);
if (checkTips || checkUconfig) {
if (checkTips) {
List<Cookie> result = new ArrayList<>(cookies.size() + 1);
// Add all but skip some
for (Cookie cookie: cookies) {
String name = cookie.name();
if (checkTips && EhConfig.KEY_CONTENT_WARNING.equals(name)) {
if (EhConfig.KEY_CONTENT_WARNING.equals(name)) {
continue;
}
if (checkUconfig && EhConfig.KEY_UCONFIG.equals(name)) {
if (EhConfig.KEY_UCONFIG.equals(name)) {
continue;
}
result.add(cookie);
}
// Add some
if (checkTips) {
result.add(sTipsCookie);
}
if (checkUconfig) {
EhConfig ehConfig = (EhConfig) tag;
Cookie uconfigCookie = new Cookie.Builder()
.name(EhConfig.KEY_UCONFIG)
.value(ehConfig.uconfig())
.domain(host)
.path("/")
.expiresAt(Long.MAX_VALUE)
.build();
result.add(uconfigCookie);
}
result.add(sTipsCookie);
return Collections.unmodifiableList(result);
} else {
return cookies;
}
}
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
List<Cookie> result = new ArrayList<>(cookies.size() + 2);
for (Cookie cookie: cookies) {
if (EhUrl.DOMAIN_E.equals(cookie.domain())) {
// Save id and hash for exhentai
if (KEY_IPD_MEMBER_ID.equals(cookie.name()) ||
KEY_IPD_PASS_HASH.equals(cookie.name())) {
result.add(newCookie(cookie, EhUrl.DOMAIN_E, true, true, true));
result.add(newCookie(cookie, EhUrl.DOMAIN_EX, true, true, true));
continue;
}
}
result.add(cookie);
}
super.saveFromResponse(url, Collections.unmodifiableList(result));
}
}
@@ -0,0 +1,85 @@
/*
* Copyright 2018 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;
/*
* Created by Hippo on 2018/3/23.
*/
import android.content.Context;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.Hosts;
import com.hippo.ehviewer.Settings;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.Dns;
public class EhDns implements Dns {
private static final Map<String, InetAddress> builtInHosts;
static {
Map<String, InetAddress> map = new HashMap<>();
put(map, "e-hentai.org", "104.24.255.11");
put(map, "forums.e-hentai.org", "94.100.18.243");
builtInHosts = map;
}
private static void put(Map<String, InetAddress> map, String host, String ip) {
InetAddress address = Hosts.toInetAddress(host, ip);
if (address != null) {
map.put(host, address);
}
}
private final Hosts hosts;
public EhDns(Context context) {
hosts = EhApplication.getHosts(context);
}
@Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
if (hostname == null) throw new UnknownHostException("hostname == null");
InetAddress inetAddress = hosts.get(hostname);
if (inetAddress != null) {
return Collections.singletonList(inetAddress);
}
if (Settings.getBuiltInHosts()) {
inetAddress = builtInHosts.get(hostname);
if (inetAddress != null) {
return Collections.singletonList(inetAddress);
}
}
try {
return Arrays.asList(InetAddress.getAllByName(hostname));
} catch (NullPointerException e) {
UnknownHostException unknownHostException =
new UnknownHostException("Broken system behaviour for dns lookup of " + hostname);
unknownHostException.initCause(e);
throw unknownHostException;
}
}
}
@@ -17,6 +17,7 @@
package com.hippo.ehviewer.client;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
@@ -30,7 +31,9 @@ import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.data.PreviewSet;
import com.hippo.ehviewer.client.exception.CancelledException;
import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.ehviewer.client.exception.NoHAtHClientException;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.ArchiveParser;
import com.hippo.ehviewer.client.parser.FavoritesParser;
import com.hippo.ehviewer.client.parser.ForumsParser;
import com.hippo.ehviewer.client.parser.GalleryApiParser;
@@ -45,16 +48,20 @@ import com.hippo.ehviewer.client.parser.TorrentParser;
import com.hippo.ehviewer.client.parser.VoteCommentParser;
import com.hippo.ehviewer.client.parser.WhatsHotParser;
import com.hippo.network.StatusCodeException;
import com.hippo.yorozuya.AssertUtils;
import junit.framework.Assert;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import okhttp3.Call;
import okhttp3.FormBody;
@@ -77,13 +84,15 @@ public class EhEngine {
public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
private static final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
private static final Pattern PATTERN_NEED_HATH_CLIENT = Pattern.compile("(You must have a H@H client assigned to your account to use this feature\\.)");
public static EhFilter sEhFilter;
public static void initialize() {
sEhFilter = EhFilter.getInstance();
}
private static void throwException(Call call, int code, @Nullable Headers headers,
private static void doThrowException(Call call, int code, @Nullable Headers headers,
@Nullable String body, Exception e) throws Exception {
if (call.isCanceled()) {
throw new CancelledException();
@@ -110,16 +119,34 @@ public class EhEngine {
if (code >= 400) {
throw new StatusCodeException(code);
}
if (e != null) {
throw e;
}
}
private static void throwException(Call call, int code, @Nullable Headers headers,
@Nullable String body, Exception e) throws Exception {
try {
doThrowException(call, code, headers, body, e);
} catch (Throwable error) {
error.printStackTrace();
throw error;
}
}
public static String signIn(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String username, String password) throws Exception {
String username, String password, String recaptchaChallenge, String recaptchaResponse) throws Exception {
FormBody.Builder builder = new FormBody.Builder()
.add("UserName", username)
.add("PassWord", password)
.add("submit", "Log me in")
.add("CookieDate", "1")
.add("temporary_https", "off");
if (!TextUtils.isEmpty(recaptchaChallenge) && !TextUtils.isEmpty(recaptchaResponse)) {
builder.add("recaptcha_challenge_field", recaptchaChallenge);
builder.add("recaptcha_response_field", recaptchaResponse);
}
String url = EhUrl.API_SIGN_IN;
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
@@ -184,7 +211,7 @@ public class EhEngine {
}
}
if (list.size() > 0 && (Settings.getShowJpnTitle() || sEhFilter.needCallApi())) {
if (list.size() > 0 && (Settings.getShowJpnTitle() || Settings.getShowGalleryPages() || sEhFilter.needCallApi())) {
// Fill by api
fillGalleryListByApi(task, okHttpClient, list);
@@ -199,6 +226,10 @@ public class EhEngine {
}
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
return result;
}
@@ -354,8 +385,7 @@ public class EhEngine {
public static GalleryComment[] commentGallery(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, String url, String comment) throws Exception {
FormBody.Builder builder = new FormBody.Builder()
.add("commenttext", comment)
.add("postcomment", "Post New");
.add("commenttext_new", comment);
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
.post(builder.build())
@@ -376,6 +406,12 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
Document document = Jsoup.parse(body);
Elements elements = document.select("#chd + p");
if (elements.size() > 0) {
throw new EhException(elements.get(0).text());
}
return GalleryDetailParser.parseComments(document);
} catch (Exception e) {
throwException(call, code, headers, body, e);
@@ -447,6 +483,10 @@ public class EhEngine {
fillGalleryListByApi(task, okHttpClient, result.galleryInfoList);
}
for (GalleryInfo info : result.galleryInfoList) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
return result;
}
@@ -501,7 +541,7 @@ public class EhEngine {
public static Void addFavoritesRange(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long[] gidArray, String[] tokenArray, int dstCat) throws Exception {
AssertUtils.assertEqualsEx(gidArray.length, tokenArray.length);
Assert.assertEquals(gidArray.length, tokenArray.length);
for (int i = 0, n = gidArray.length; i < n; i++) {
addFavorites(task, okHttpClient, gidArray[i], tokenArray[i], dstCat, null);
}
@@ -554,6 +594,10 @@ public class EhEngine {
fillGalleryListByApi(task, okHttpClient, result.galleryInfoList);
}
for (GalleryInfo info : result.galleryInfoList) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
return result;
}
@@ -586,9 +630,82 @@ public class EhEngine {
return result;
}
public static Pair<String, Pair<String, String>[]> getArchiveList(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Exception {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
// Put call
if (null != task) {
task.setCall(call);
}
String body = null;
Headers headers = null;
Pair<String, Pair<String, String>[]> result;
int code = -1;
try {
Response response = call.execute();
code = response.code();
headers = response.headers();
body = response.body().string();
result = ArchiveParser.parse(body);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
return result;
}
public static Void downloadArchive(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long gid, String token, String or, String res) throws Exception {
if (or == null || or.length() == 0) {
throw new EhException("Invalid form param or: " + or);
}
if (res == null || res.length() == 0) {
throw new EhException("Invalid res: " + res);
}
FormBody.Builder builder = new FormBody.Builder();
builder.add("hathdl_xres", res);
String url = EhUrl.getDownloadArchive(gid, token, or);
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
.post(builder.build())
.build();
Call call = okHttpClient.newCall(request);
// Put call
if (null != task) {
task.setCall(call);
}
String body = null;
Headers headers = null;
int code = -1;
try {
Response response = call.execute();
code = response.code();
headers = response.headers();
body = response.body().string();
throwException(call, code, headers, body, null);
} catch (Exception e) {
throwException(call, code, headers, body, e);
throw e;
}
Matcher m = PATTERN_NEED_HATH_CLIENT.matcher(body);
if (m.find()) {
throw new NoHAtHClientException("No H@H client");
}
return null;
}
public static List<GalleryInfo> getWhatsHot(@Nullable EhClient.Task task,
OkHttpClient okHttpClient) throws Exception {
String url = EhUrl.HOST_G;
String url = EhUrl.HOST_E;
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -618,6 +735,10 @@ public class EhEngine {
fillGalleryListByApi(task, okHttpClient, list);
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
return list;
}
@@ -786,7 +907,7 @@ public class EhEngine {
}
}
if (list.size() > 0 && (Settings.getShowJpnTitle() || sEhFilter.needCallApi())) {
if (list.size() > 0 && (Settings.getShowJpnTitle() || Settings.getShowGalleryPages() || sEhFilter.needCallApi())) {
// Fill by api
fillGalleryListByApi(task, okHttpClient, list);
@@ -801,6 +922,10 @@ public class EhEngine {
}
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
return result;
}
@@ -92,6 +92,8 @@ public final class EhFilter {
}
public synchronized void addFilter(Filter filter) {
// enable filter by default before it is added to database
filter.enable = true;
EhDB.addFilter(filter);
switch (filter.mode) {
@@ -116,6 +118,10 @@ public final class EhFilter {
}
}
public synchronized void triggerFilter(Filter filter) {
EhDB.triggerFilter(filter);
}
public synchronized void deleteFilter(Filter filter) {
EhDB.deleteFilter(filter);
@@ -153,7 +159,7 @@ public final class EhFilter {
if (null != title && filters.size() > 0) {
title = title.toLowerCase();
for (int i = 0, n = filters.size(); i < n; i++) {
if (title.contains(filters.get(i).text)) {
if (filters.get(i).enable && title.contains(filters.get(i).text)) {
return false;
}
}
@@ -172,7 +178,7 @@ public final class EhFilter {
List<Filter> filters = mUploaderFilterList;
if (null != uploader && filters.size() > 0) {
for (int i = 0, n = filters.size(); i < n; i++) {
if (uploader.equals(filters.get(i).text)) {
if (filters.get(i).enable && uploader.equals(filters.get(i).text)) {
return false;
}
}
@@ -229,7 +235,7 @@ public final class EhFilter {
if (null != tags && filters.size() > 0) {
for (String tag: tags) {
for (int i = 0, n = filters.size(); i < n; i++) {
if (matchTag(tag, filters.get(i).text)) {
if (filters.get(i).enable && matchTag(tag, filters.get(i).text)) {
return false;
}
}
@@ -264,7 +270,7 @@ public final class EhFilter {
if (null != tags && filters.size() > 0) {
for (String tag: tags) {
for (int i = 0, n = filters.size(); i < n; i++) {
if (matchTagNamespace(tag, filters.get(i).text)) {
if (filters.get(i).enable && matchTagNamespace(tag, filters.get(i).text)) {
return false;
}
}
@@ -17,35 +17,49 @@
package com.hippo.ehviewer.client;
import android.support.annotation.NonNull;
import android.util.Pair;
import com.hippo.ehviewer.Settings;
import com.hippo.network.UrlBuilder;
import java.util.List;
import java.util.ListIterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import okhttp3.HttpUrl;
public class EhUrl {
public static final int SITE_G = 0;
public static final int SITE_E = 0;
public static final int SITE_EX = 1;
public static final String DOMAIN_EX = "exhentai.org";
public static final String DOMAIN_E = "e-hentai.org";
public static final String DOMAIN_G = "g.e-hentai.org";
public static final String DOMAIN_LOFI = "lofi.e-hentai.org";
public static final String HOST_E = "http://" + DOMAIN_E + "/";
public static final String HOST_EX = "http://" + DOMAIN_EX + "/";
public static final String HOST_G = "http://" + DOMAIN_G + "/";
public static final String HOST_EX = "https://" + DOMAIN_EX + "/";
public static final String HOST_E = "https://" + DOMAIN_E + "/";
public static final String API_SIGN_IN = "http://forums.e-hentai.org/index.php?act=Login&CODE=01";
public static final String API_SIGN_IN = "https://forums.e-hentai.org/index.php?act=Login&CODE=01";
public static final String API_G = HOST_G + "api.php";
public static final String API_E = HOST_E + "api.php";
public static final String API_EX = HOST_EX + "api.php";
public static final String URL_SIGN_IN = "http://forums.e-hentai.org/index.php?act=Login";
public static final String URL_REGISTER = "http://forums.e-hentai.org/index.php?act=Reg&CODE=00";
public static final String URL_FAVORITES_G = HOST_G + "favorites.php";
public static final String URL_IMAGE_SEARCH_E = "https://upload.e-hentai.org/image_lookup.php";
public static final String URL_IMAGE_SEARCH_EX = "https://exhentai.org/upload/image_lookup.php";
public static final String URL_SIGN_IN = "https://forums.e-hentai.org/index.php?act=Login";
public static final String URL_REGISTER = "https://forums.e-hentai.org/index.php?act=Reg&CODE=00";
public static final String URL_FAVORITES_E = HOST_E + "favorites.php";
public static final String URL_FAVORITES_EX = HOST_EX + "favorites.php";
public static final String URL_FORUMS = "https://forums.e-hentai.org/";
public static final String UCONFIG_E = HOST_E + "uconfig.php";
public static final String UCONFIG_EX = HOST_EX + "uconfig.php";
private static final String URL_PREFIX_THUMB_E = "https://ehgt.org/t/";
private static final String URL_PREFIX_THUMB_EX = "https://exhentai.org/t/";
public static final Pattern PATTERN_DETAIL_URL = Pattern.compile("g/(\\d+)/([0-9a-f]{10})");
public static String getGalleryDetailUrl(long gid, String token) {
return getGalleryDetailUrl(gid, token, 0, false);
}
@@ -53,8 +67,8 @@ public class EhUrl {
public static String getHost() {
switch (Settings.getGallerySite()) {
default:
case SITE_G:
return HOST_G;
case SITE_E:
return HOST_E;
case SITE_EX:
return HOST_EX;
}
@@ -63,8 +77,8 @@ public class EhUrl {
public static String getFavoritesUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_G:
return URL_FAVORITES_G;
case SITE_E:
return URL_FAVORITES_E;
case SITE_EX:
return URL_FAVORITES_EX;
}
@@ -73,13 +87,23 @@ public class EhUrl {
public static String getApiUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_G:
return API_G;
case SITE_E:
return API_E;
case SITE_EX:
return API_EX;
}
}
public static String getUConfigUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_E:
return UCONFIG_E;
case SITE_EX:
return UCONFIG_EX;
}
}
public static String getGalleryDetailUrl(long gid, String token, int index, boolean allComment) {
UrlBuilder builder = new UrlBuilder(getHost() + "g/" + gid + '/' + token + '/');
if (index != 0) {
@@ -99,6 +123,10 @@ public class EhUrl {
return getHost() + "gallerypopups.php?gid=" + gid + "&t=" + token + "&act=addfav";
}
public static String getDownloadArchive(long gid, String token, String or) {
return getHost() + "archiver.php?gid=" + gid + "&token=" + token + "&or=" + or;
}
public static String getTagDefinitionUrl(String tag) {
return "https://ehwiki.org/wiki/" + tag.replace(' ', '_');
}
@@ -107,10 +135,59 @@ public class EhUrl {
public static String getImageSearchUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_G:
return "http://ul.e-hentai.org/image_lookup.php";
case SITE_E:
return URL_IMAGE_SEARCH_E;
case SITE_EX:
return "http://ul.exhentai.org/image_lookup.php";
return URL_IMAGE_SEARCH_EX;
}
}
public static String getThumbUrlPrefix() {
switch (Settings.getGallerySite()) {
default:
//case SITE_E:
return URL_PREFIX_THUMB_E;
//case SITE_EX:
// return URL_PREFIX_THUMB_EX;
}
}
public static String getFixedPreviewThumbUrl(String originUrl) {
HttpUrl url = HttpUrl.parse(originUrl);
if (url == null) return originUrl;
List<String> pathSegments = url.pathSegments();
if (pathSegments == null || pathSegments.size() < 3) return originUrl;
ListIterator<String> iterator = pathSegments.listIterator(pathSegments.size());
// The last segments, like
// 317a1a254cd9c3269e71b2aa2671fe8d28c91097-260198-640-480-png_250.jpg
if (!iterator.hasPrevious()) return originUrl;
String lastSegment = iterator.previous();
// The second last segments, like
// 7a
if (!iterator.hasPrevious()) return originUrl;
String secondLastSegment = iterator.previous();
// The third last segments, like
// 31
if (!iterator.hasPrevious()) return originUrl;
String thirdLastSegment = iterator.previous();
// Check path segments
if (lastSegment != null && secondLastSegment != null
&& thirdLastSegment != null
&& lastSegment.startsWith(thirdLastSegment)
&& lastSegment.startsWith(secondLastSegment, thirdLastSegment.length())) {
return getThumbUrlPrefix() + thirdLastSegment + "/" + secondLastSegment + "/" + lastSegment;
} else {
return originUrl;
}
}
public static Pair<Long, String> parseGalleryDetailUrl(String url) {
Matcher matcher = PATTERN_DETAIL_URL.matcher(url);
if (matcher.find()) {
return new Pair<>(Long.parseLong(matcher.group(1)), matcher.group(2));
} else {
return null;
}
}
}
@@ -27,6 +27,7 @@ public class GalleryDetail extends GalleryInfo {
public String apiKey;
public int torrentCount;
public String torrentUrl;
public String archiveUrl;
public String parent;
public String visible;
public String language;
@@ -39,6 +40,7 @@ public class GalleryDetail extends GalleryInfo {
public GalleryComment[] comments;
public int previewPages;
public PreviewSet previewSet;
public String favoriteName;
@Override
public int describeContents() {
@@ -50,6 +52,7 @@ public class GalleryDetail extends GalleryInfo {
super.writeToParcel(dest, flags);
dest.writeInt(this.torrentCount);
dest.writeString(this.torrentUrl);
dest.writeString(this.archiveUrl);
dest.writeString(this.parent);
dest.writeString(this.visible);
dest.writeString(this.language);
@@ -62,6 +65,7 @@ public class GalleryDetail extends GalleryInfo {
dest.writeParcelableArray(this.comments, 0);
dest.writeInt(this.previewPages);
dest.writeParcelable(previewSet, flags);
dest.writeString(this.favoriteName);
}
public GalleryDetail() {
@@ -71,6 +75,7 @@ public class GalleryDetail extends GalleryInfo {
super(in);
this.torrentCount = in.readInt();
this.torrentUrl = in.readString();
this.archiveUrl = in.readString();
this.parent = in.readString();
this.visible = in.readString();
this.language = in.readString();
@@ -93,6 +98,7 @@ public class GalleryDetail extends GalleryInfo {
}
this.previewPages = in.readInt();
this.previewSet = in.readParcelable(PreviewSet.class.getClassLoader());
this.favoriteName = in.readString();
}
public static final Creator<GalleryDetail> CREATOR = new Creator<GalleryDetail>() {
@@ -63,8 +63,8 @@ public class GalleryInfo implements Parcelable {
public static final Pattern[] S_LANG_PATTERNS = {
Pattern.compile("[(\\[]eng(?:lish)?[)\\]]", Pattern.CASE_INSENSITIVE),
// [((\[]ch(?:inese)?[))\]]|[汉漢]化|中[国國][语語]|中文
Pattern.compile("[(\uFF08\\[]ch(?:inese)?[)\uFF09\\]]|[汉漢]化|中[国國][语語]|中文", Pattern.CASE_INSENSITIVE),
// [((\[]ch(?:inese)?[))\]]|[汉漢]化|中[国國][语語]|中文|中国翻訳
Pattern.compile("[(\uFF08\\[]ch(?:inese)?[)\uFF09\\]]|[汉漢]化|中[国國][语語]|中文|中国翻訳", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]spanish[)\\]]|[(\\[]Español[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]korean?[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]rus(?:sian)?[)\\]]", Pattern.CASE_INSENSITIVE),
@@ -90,6 +90,7 @@ public class GalleryInfo implements Parcelable {
public float rating;
@Nullable
public String[] simpleTags;
public int pages;
public int thumbWidth;
public int thumbHeight;
@@ -14,17 +14,12 @@
* limitations under the License.
*/
package com.hippo.okhttp;
package com.hippo.ehviewer.client.exception;
import okhttp3.Cookie;
public class NoHAtHClientException extends EhException {
public class CookieWithID {
public long id;
public Cookie cookie;
public CookieWithID(long id, Cookie cookie) {
this.id = id;
this.cookie = cookie;
public NoHAtHClientException(String detailMessage) {
super(detailMessage);
}
}
@@ -0,0 +1,48 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.client.parser;
import android.util.Pair;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ArchiveParser {
private static final Pattern PATTERN_FORM = Pattern.compile("<form id=\"hathdl_form\" action=\"[^\"]*?or=([^=\"]*?)\" method=\"post\">");
private static final Pattern PATTERN_ARCHIVE = Pattern.compile("<a href=\"[^\"]*\" onclick=\"return do_hathdl\\('([0-9]+|org)'\\)\">([^<]+)</a>");
@SuppressWarnings("unchecked")
public static Pair<String, Pair<String, String>[]> parse(String body) {
Matcher m = PATTERN_FORM.matcher(body);
if (!m.find()) {
return new Pair<String, Pair<String, String>[]>("", new Pair[0]);
}
String paramOr = m.group(1);
List<Pair<String, String>> archiveList = new ArrayList<>();
m = PATTERN_ARCHIVE.matcher(body);
while (m.find()) {
String res = ParserUtils.trim(m.group(1));
String name = ParserUtils.trim(m.group(2));
Pair<String, String> item = new Pair<>(res, name);
archiveList.add(item);
}
return new Pair<String, Pair<String, String>[]>(paramOr, archiveList.toArray(new Pair[archiveList.size()]));
}
}
@@ -22,7 +22,8 @@ import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.JsoupUtils;
import com.hippo.yorozuya.AssertUtils;
import junit.framework.Assert;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
@@ -53,7 +54,7 @@ public class FavoritesParser {
//noinspection ConstantConditions
Elements fps = ido.getElementsByClass("fp");
// Last one is "fp fps"
AssertUtils.assertEqualsEx(11, fps.size());
Assert.assertEquals(11, fps.size());
for (int i = 0; i < 10; i++) {
Element fp = fps.get(i);
@@ -53,6 +53,7 @@ public class GalleryApiParser {
tags[j] = tagJa.getString(j);
}
gi.simpleTags = tags;
gi.pages = Integer.parseInt(g.getString("filecount"));
}
}
@@ -20,6 +20,8 @@ import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryComment;
import com.hippo.ehviewer.client.data.GalleryDetail;
@@ -56,6 +58,8 @@ public class GalleryDetailParser {
private static final Pattern PATTERN_ERROR = Pattern.compile("<div class=\"d\">\n<p>([^<]+)</p>");
private static final Pattern PATTERN_DETAIL = Pattern.compile("var gid = (\\d+);.+?var token = \"([a-f0-9]+)\";.+?var apiuid = ([\\-\\d]+);.+?var apikey = \"([a-f0-9]+)\";", Pattern.DOTALL);
private static final Pattern PATTERN_TORRENT = Pattern.compile("<a[^<>]*onclick=\"return popUp\\('([^']+)'[^)]+\\)\">Torrent Download \\( (\\d+) \\)</a>");
private static final Pattern PATTERN_ARCHIVE = Pattern.compile("<a[^<>]*onclick=\"return popUp\\('([^']+)'[^)]+\\)\">Archive Download</a>");
private static final Pattern PATTERN_COVER = Pattern.compile("width:(\\d+)px; height:(\\d+)px.+?url\\((.+?)\\)");
private static final Pattern PATTERN_TAG_GROUP = Pattern.compile("<tr><td[^<>]+>([\\w\\s]+):</td><td>(?:<div[^<>]+><a[^<>]+>[\\w\\s]+</a></div>)+</td></tr>");
private static final Pattern PATTERN_TAG = Pattern.compile("<div[^<>]+><a[^<>]+>([\\w\\s]+)</a></div>");
private static final Pattern PATTERN_COMMENT = Pattern.compile("<div class=\"c3\">Posted on ([^<>]+) by: &nbsp; <a[^<>]+>([^<>]+)</a>.+?<div class=\"c6\"[^>]*>(.+?)</div><div class=\"c[78]\"");
@@ -124,13 +128,20 @@ public class GalleryDetailParser {
gd.torrentUrl = "";
}
matcher = PATTERN_ARCHIVE.matcher(body);
if (matcher.find()) {
gd.archiveUrl = StringUtils.unescapeXml(StringUtils.trim(matcher.group(1)));
} else {
gd.archiveUrl = "";
}
try {
Element gm = JsoupUtils.getElementByClass(d, "gm");
// Thumb url
Element gd1 = gm.getElementById("gd1");
try {
gd.thumb = EhUtils.handleThumbUrlResolution(StringUtils.trim(gd1.child(0).attr("src")));
gd.thumb = parseCoverStyle(StringUtils.trim(gd1.child(0).attr("style")));
} catch (Exception e) {
gd.thumb = "";
}
@@ -154,7 +165,9 @@ public class GalleryDetailParser {
// Category
Element gdc = gm.getElementById("gdc");
try {
gd.category = EhUtils.getCategory(gdc.child(0).child(0).attr("alt"));
String href = gdc.child(0).attr("href");
String category = href.substring(href.lastIndexOf('/') + 1);
gd.category = EhUtils.getCategory(category);
} catch (Exception e) {
gd.category = EhUtils.UNKNOWN;
}
@@ -214,11 +227,29 @@ public class GalleryDetailParser {
// isFavorited
Element gdf = gm.getElementById("gdf");
gd.isFavorited = null != gdf && !StringUtils.trim(gdf.text()).equals("Add to Favorites");
if (gdf != null) {
final String favoriteName = StringUtils.trim(gdf.text());
if (favoriteName.equals("Add to Favorites")) {
gd.favoriteName = null;
} else {
gd.favoriteName = StringUtils.trim(gdf.text());
}
}
} catch (Exception e) {
throw new ParseException("Can't parse gallery detail", body);
}
}
// width:250px; height:356px; background:transparent url(https://exhentai.org/t/fe/1f/fe1fcfa9bf8fba2f03982eda0aa347cc9d6a6372-145921-1050-1492-jpg_250.jpg) 0 0 no-repeat
private static String parseCoverStyle(String str) {
Matcher matcher = PATTERN_COVER.matcher(str);
if (matcher.find()) {
return EhUtils.handleThumbUrlResolution(matcher.group(3));
} else {
return "";
}
}
private static void parseDetailInfo(GalleryDetail gd, Element e, String body) {
Elements es = e.children();
if (es.size() < 2) {
@@ -280,7 +311,7 @@ public class GalleryDetailParser {
// Sometimes parody tag is followed with '|' and english translate, just remove them
int index = tag.indexOf('|');
if (index >= 0) {
tag = tag.substring(0, index);
tag = tag.substring(0, index).trim();
}
group.addTag(tag);
}
@@ -374,7 +405,7 @@ public class GalleryDetailParser {
// time
Element c3 = JsoupUtils.getElementByClass(element, "c3");
String temp = c3.ownText();
temp = temp.substring("Posted on ".length(), temp.length() - " by:  ".length());
temp = temp.substring("Posted on ".length(), temp.length() - " by:".length());
comment.time = WEB_COMMENT_DATE_FORMAT.parse(temp).getTime();
// user
comment.user = c3.child(0).text();
@@ -511,6 +542,9 @@ public class GalleryDetailParser {
String pageUrl = element.attr("href");
element = element.child(0);
String imageUrl = element.attr("src");
if (Settings.getFixThumbUrl()) {
imageUrl = EhUrl.getFixedPreviewThumbUrl(imageUrl);
}
int index = Integer.parseInt(element.attr("alt")) - 1;
largePreviewSet.addItem(index, imageUrl, pageUrl);
}
@@ -529,8 +563,13 @@ public class GalleryDetailParser {
LargePreviewSet largePreviewSet = new LargePreviewSet();
while (m.find()) {
largePreviewSet.addItem(ParserUtils.parseInt(m.group(2)) - 1,
ParserUtils.trim(m.group(3)), ParserUtils.trim(m.group(1)));
int index = ParserUtils.parseInt(m.group(2)) - 1;
String imageUrl = ParserUtils.trim(m.group(3));
String pageUrl = ParserUtils.trim(m.group(1));
if (Settings.getFixThumbUrl()) {
imageUrl = EhUrl.getFixedPreviewThumbUrl(imageUrl);
}
largePreviewSet.addItem(index, imageUrl, pageUrl);
}
if (largePreviewSet.size() == 0) {
@@ -29,8 +29,8 @@ import java.util.regex.Pattern;
*/
public final class GalleryDetailUrlParser {
public static final Pattern URL_PATTERN = Pattern.compile("http://(?:" +
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_G + "|" + EhUrl.DOMAIN_LOFI + ")/g/(\\d+)/(\\w+)");
public static final Pattern URL_PATTERN = Pattern.compile("https?://(?:" +
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_E + "|" + EhUrl.DOMAIN_LOFI + ")/g/(\\d+)/(\\w+)");
@Nullable
public static Result parse(String url) {
@@ -143,18 +143,18 @@ public class GalleryListParser {
// Title (required)
Element it5 = JsoupUtils.getElementByClass(e, "it5");
if (null == it5) {
Log.e(TAG, "Can't parse gallery info title");
Log.e(TAG, "Can't parse gallery info title, step 1");
return null;
}
Elements es = it5.children();
if (null == es || es.size() <= 0) {
Log.e(TAG, "Can't parse gallery info title");
Log.e(TAG, "Can't parse gallery info title, step 2");
return null;
}
Element a = es.get(0);
GalleryDetailUrlParser.Result result = GalleryDetailUrlParser.parse(a.attr("href"));
if (null == result) {
Log.e(TAG, "Can't parse gallery info title");
Log.e(TAG, "Can't parse gallery info title, step 3");
return null;
}
gi.gid = result.gid;
@@ -182,6 +182,60 @@ public class GalleryListParser {
return gi;
}
@Nullable
private static GalleryInfo parseGalleryInfoThumbVersion(Element e) {
GalleryInfo gi = new GalleryInfo();
// Title (required)
Element id2 = JsoupUtils.getElementByClass(e, "id2");
if (id2 == null) {
return null;
}
gi.title = id2.text().trim();
// gid, token (required)
Element a = id2.children().first();
if (a == null) {
return null;
}
GalleryDetailUrlParser.Result result = GalleryDetailUrlParser.parse(a.attr("href"));
if (result == null) {
return null;
}
gi.gid = result.gid;
gi.token = result.token;
// Thumbnail
Element id3 = JsoupUtils.getElementByClass(e, "id3");
if (id3 != null) {
a = id3.children().first();
if (a != null) {
Element img = a.children().first();
if (img != null) {
gi.thumb = EhUtils.handleThumbUrlResolution(img.attr("src"));
}
}
}
// Category
Element id41 = JsoupUtils.getElementByClass(e, "id41");
if (id41 != null) {
gi.category = EhUtils.getCategory(id41.attr("title").trim());
} else {
gi.category = EhUtils.UNKNOWN;
}
// Rating
Element id43 = JsoupUtils.getElementByClass(e, "id43");
if (id43 != null) {
gi.rating = NumberUtils.parseFloatSafely(parseRating(id43.attr("style")), -1.0f);
} else {
gi.rating = -1.0f;
}
return gi;
}
public static Result parse(@NonNull String body) throws Exception {
Result result = new Result();
Document d = Jsoup.parse(body);
@@ -213,6 +267,23 @@ public class GalleryListParser {
throw new ParseException("Can't parse gallery list", body);
}
// Maybe it's thumbnail version
if (result.galleryInfoList.isEmpty()) {
try {
Elements es = d.getElementsByClass("itg").first().children();
List<GalleryInfo> list = new ArrayList<>(es.size() - 1);
for (int i = 0; i < es.size(); i++) {
GalleryInfo gi = parseGalleryInfoThumbVersion(es.get(i));
if (null != gi) {
list.add(gi);
}
}
result.galleryInfoList = list;
} catch (Exception e) {
throw new ParseException("Can't parse gallery list", body);
}
}
return result;
}
}
@@ -29,7 +29,7 @@ import java.net.URLDecoder;
public final class GalleryListUrlParser {
private static final String[] VALID_HOSTS = {EhUrl.DOMAIN_EX, EhUrl.DOMAIN_G, EhUrl.DOMAIN_LOFI};
private static final String[] VALID_HOSTS = {EhUrl.DOMAIN_EX, EhUrl.DOMAIN_E, EhUrl.DOMAIN_LOFI};
private static final String PATH_NORMAL = "/";
private static final String PATH_UPLOADER = "/uploader/";
@@ -26,7 +26,7 @@ import java.util.regex.Pattern;
public class GalleryPageParser {
private static final Pattern PATTERN_IMAGE_URL = Pattern.compile("<(?:/iframe|div id=\"i3\")[^>]*><a[^>]+><img[^>]*src=\"(.+?)\"");
private static final Pattern PATTERN_IMAGE_URL = Pattern.compile("<img[^>]*src=\"([^\"]+)\" style");
private static final Pattern PATTERN_SKIP_HATH_KEY = Pattern.compile("onclick=\"return nl\\('([^\\)]+)'\\)");
private static final Pattern PATTERN_ORIGIN_IMAGE_URL = Pattern.compile("<a href=\"([^\"]+)fullimg.php([^\"]+)\">");
@@ -26,8 +26,8 @@ import java.util.regex.Pattern;
*/
public final class GalleryPageUrlParser {
public static final Pattern URL_PATTERN = Pattern.compile("http://(?:" +
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_G + "|" + EhUrl.DOMAIN_LOFI + ")/s/(\\w+)/(\\d+)-(\\d+)");
public static final Pattern URL_PATTERN = Pattern.compile("https?://(?:" +
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_E + "|" + EhUrl.DOMAIN_LOFI + ")/s/(\\w+)/(\\d+)-(\\d+)");
public static Result parse(String url) {
if (url == null) {
@@ -25,7 +25,7 @@ import java.util.regex.Pattern;
public class TorrentParser {
private static final Pattern PATTERN_TORRENT = Pattern.compile("<td colspan=\"5\"> &nbsp; <a href=\"([^\"]+)\">([^<]+)</a></td>");
private static final Pattern PATTERN_TORRENT = Pattern.compile("<td colspan=\"5\"> &nbsp; <a href=\"([^\"]+)\"[^<]+>([^<]+)</a></td>");
@SuppressWarnings("unchecked")
public static Pair<String, String>[] parse(String body) {
@@ -16,7 +16,9 @@
package com.hippo.ehviewer.download;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
@@ -25,8 +27,11 @@ import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.dao.DownloadInfo;
import com.hippo.ehviewer.dao.DownloadLabel;
import com.hippo.ehviewer.spider.SpiderDen;
import com.hippo.ehviewer.spider.SpiderInfo;
import com.hippo.ehviewer.spider.SpiderQueen;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.ConcurrentPool;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.ObjectUtils;
@@ -35,6 +40,7 @@ import com.hippo.yorozuya.collect.LongList;
import com.hippo.yorozuya.collect.SparseIJArray;
import com.hippo.yorozuya.collect.SparseJLArray;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
@@ -562,6 +568,49 @@ public class DownloadManager implements SpiderQueen.OnSpiderListener {
}
}
@SuppressLint("StaticFieldLeak")
public void resetAllReadingProgress() {
LinkedList<DownloadInfo> list = new LinkedList<>(mAllInfoList);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
GalleryInfo galleryInfo = new GalleryInfo();
for (DownloadInfo downloadInfo : list) {
galleryInfo.gid = downloadInfo.gid;
galleryInfo.token = downloadInfo.token;
galleryInfo.title = downloadInfo.title;
galleryInfo.thumb = downloadInfo.thumb;
galleryInfo.category = downloadInfo.category;
galleryInfo.posted = downloadInfo.posted;
galleryInfo.uploader = downloadInfo.uploader;
galleryInfo.rating = downloadInfo.rating;
UniFile downloadDir = SpiderDen.getGalleryDownloadDir(galleryInfo);
if (downloadDir == null) {
continue;
}
UniFile file = downloadDir.findFile(".ehviewer");
if (file == null) {
continue;
}
SpiderInfo spiderInfo = SpiderInfo.read(file);
if (spiderInfo == null) {
continue;
}
spiderInfo.startPage = 0;
try {
spiderInfo.write(file.openOutputStream());
} catch (IOException e) {
Log.e(TAG, "Can't write SpiderInfo", e);
}
}
return null;
}
}.execute();
}
// Update in DB
// Update listener
// No ensureDownload
@@ -16,12 +16,14 @@
package com.hippo.ehviewer.download;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
@@ -90,6 +92,8 @@ public class DownloadService extends Service implements DownloadManager.Download
private static int sFinishedCount;
private static int sDownloadedCount;
private String CHANNEL_ID;
public static void clear() {
sFailedCount = 0;
sFinishedCount = 0;
@@ -102,7 +106,12 @@ public class DownloadService extends Service implements DownloadManager.Download
public void onCreate() {
super.onCreate();
CHANNEL_ID = getPackageName()+".download";
mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
mNotifyManager.createNotificationChannel(new NotificationChannel(CHANNEL_ID, getString(R.string.download_service),
NotificationManager.IMPORTANCE_LOW));
}
mDownloadManager = EhApplication.getDownloadManager(getApplicationContext());
mDownloadManager.setDownloadListener(this);
}
@@ -208,14 +217,15 @@ public class DownloadService extends Service implements DownloadManager.Download
stopAllIntent.setAction(ACTION_STOP_ALL);
PendingIntent piStopAll = PendingIntent.getService(this, 0, stopAllIntent, 0);
mDownloadingBuilder = new NotificationCompat.Builder(getApplicationContext())
mDownloadingBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setOngoing(true)
.setAutoCancel(false)
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
.setColor(getResources().getColor(R.color.colorPrimary))
.addAction(R.drawable.ic_pause_x24, getString(R.string.stat_download_action_stop_all), piStopAll)
.setShowWhen(false);
.setShowWhen(false)
.setChannelId(CHANNEL_ID);
mDownloadingDelay = new NotificationDelay(this, mNotifyManager, mDownloadingBuilder, ID_DOWNLOADING);
}
@@ -238,14 +248,15 @@ public class DownloadService extends Service implements DownloadManager.Download
PendingIntent piActivity = PendingIntent.getActivity(DownloadService.this, 0,
activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mDownloadedBuilder = new NotificationCompat.Builder(getApplicationContext())
mDownloadedBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setSmallIcon(android.R.drawable.stat_sys_download_done)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentTitle(getString(R.string.stat_download_done_title))
.setDeleteIntent(piClear)
.setOngoing(false)
.setAutoCancel(true)
.setContentIntent(piActivity);
.setContentIntent(piActivity)
.setChannelId(CHANNEL_ID);
mDownloadedDelay = new NotificationDelay(this, mNotifyManager, mDownloadedBuilder, ID_DOWNLOADED);
}
@@ -255,14 +266,15 @@ public class DownloadService extends Service implements DownloadManager.Download
return;
}
m509dBuilder = new NotificationCompat.Builder(getApplicationContext())
m509dBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_alert)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentText(getString(R.string.stat_509_alert_title))
.setContentText(getString(R.string.stat_509_alert_text))
.setAutoCancel(true)
.setOngoing(false)
.setCategory(NotificationCompat.CATEGORY_ERROR);
.setCategory(NotificationCompat.CATEGORY_ERROR)
.setChannelId(CHANNEL_ID);
m509Delay = new NotificationDelay(this, mNotifyManager, m509dBuilder, ID_509);
}
@@ -23,7 +23,7 @@ import android.util.Log;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.FileUtils;
@@ -41,7 +41,7 @@ import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class DirGalleryProvider extends GalleryProvider implements Runnable {
public class DirGalleryProvider extends GalleryProvider2 implements Runnable {
private static final String TAG = DirGalleryProvider.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
@@ -22,13 +22,14 @@ import android.support.annotation.Nullable;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.spider.SpiderQueen;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.SimpleHandler;
import java.util.Locale;
public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.OnSpiderListener {
public class EhGalleryProvider extends GalleryProvider2 implements SpiderQueen.OnSpiderListener {
private final Context mContext;
private final GalleryInfo mGalleryInfo;
@@ -72,7 +73,7 @@ public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.On
@NonNull
@Override
public String getImageFilename(int index) {
return String.format(Locale.US, "%d-%08d", mGalleryInfo.gid, index + 1);
return String.format(Locale.US, "%d-%s-%08d", mGalleryInfo.gid, mGalleryInfo.token, index + 1);
}
@Override
@@ -1,277 +0,0 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import com.hippo.beerbelly.LruCache;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.gl.glrenderer.ImageWrapper;
import com.hippo.gl.view.GLRoot;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.ConcurrentPool;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.OSUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public abstract class GalleryProvider {
public static final int STATE_WAIT = -1;
public static final int STATE_ERROR = -2;
// With dot
public static final String[] SUPPORT_IMAGE_EXTENSIONS = {
".jpg", // Joint Photographic Experts Group
".jpeg",
".png", // Portable Network Graphics
".gif", // Graphics Interchange Format
};
private final ConcurrentPool<NotifyTask> mNotifyTaskPool = new ConcurrentPool<>(5);
private volatile GalleryProviderListener mGalleryProviderListener;
private volatile GLRoot mGLRoot;
private final ImageCache mImageCache = new ImageCache();
private boolean mStarted = false;
@UiThread
public void start() {
OSUtils.checkMainLoop();
if (mStarted) {
throw new IllegalStateException("Can't start it twice");
}
mStarted = true;
}
@UiThread
public void stop() {
OSUtils.checkMainLoop();
mImageCache.close();
}
public void setGLRoot(GLRoot glRoot) {
mGLRoot = glRoot;
}
/**
* @return {@link #STATE_WAIT} for wait, 0 for empty
*/
public abstract int size();
public final void request(int index) {
ImageWrapper imageWrapper = mImageCache.get(index);
if (imageWrapper != null) {
notifyPageSucceed(index, imageWrapper);
} else {
onRequest(index);
}
}
public final void forceRequest(int index) {
onForceRequest(index);
}
protected abstract void onRequest(int index);
protected abstract void onForceRequest(int index);
public final void cancelRequest(int index) {
onCancelRequest(index);
}
protected abstract void onCancelRequest(int index);
public abstract String getError();
public int getStartPage() {
return 0;
}
/**
* @return without extension
*/
@NonNull
public abstract String getImageFilename(int index);
public abstract boolean save(int index, @NonNull UniFile file);
/**
* @param filename without extension
*/
@Nullable
public abstract UniFile save(int index, @NonNull UniFile dir, @NonNull String filename);
public void putStartPage(int page) {}
public void setGalleryProviderListener(GalleryProviderListener listener) {
mGalleryProviderListener = listener;
}
public void notifyDataChanged() {
notify(NotifyTask.TYPE_DATA_CHANGED, -1, 0.0f, null, null);
}
public void notifyDataChanged(int index) {
notify(NotifyTask.TYPE_DATA_CHANGED, index, 0.0f, null, null);
}
public void notifyPageWait(int index) {
notify(NotifyTask.TYPE_WAIT, index, 0.0f, null, null);
}
public void notifyPagePercent(int index, float percent) {
notify(NotifyTask.TYPE_PERCENT, index, percent, null, null);
}
public void notifyPageSucceed(int index, Image image) {
ImageWrapper imageWrapper = new ImageWrapper(image);
mImageCache.add(index, imageWrapper);
notifyPageSucceed(index, imageWrapper);
}
public void notifyPageSucceed(int index, ImageWrapper image) {
notify(NotifyTask.TYPE_SUCCEED, index, 0.0f, image, null);
}
public void notifyPageFailed(int index, String error) {
notify(NotifyTask.TYPE_FAILED, index, 0.0f, null, error);
}
private void notify(@NotifyTask.Type int type, int index, float percent, ImageWrapper image, String error) {
GalleryProviderListener listener = mGalleryProviderListener;
if (listener == null) {
return;
}
GLRoot glRoot = mGLRoot;
if (glRoot == null) {
return;
}
NotifyTask task = mNotifyTaskPool.pop();
if (task == null) {
task = new NotifyTask(listener, mNotifyTaskPool);
}
task.setData(type, index, percent, image, error);
glRoot.addOnGLIdleListener(task);
}
private static class NotifyTask implements GLRoot.OnGLIdleListener {
@IntDef({TYPE_DATA_CHANGED, NotifyTask.TYPE_WAIT, TYPE_PERCENT, TYPE_SUCCEED, TYPE_FAILED})
@Retention(RetentionPolicy.SOURCE)
public @interface Type {}
public static final int TYPE_DATA_CHANGED = 0;
public static final int TYPE_WAIT = 1;
public static final int TYPE_PERCENT = 2;
public static final int TYPE_SUCCEED = 3;
public static final int TYPE_FAILED = 4;
private final GalleryProviderListener mGalleryProviderListener;
private final ConcurrentPool<NotifyTask> mPool;
@Type
private int mType;
private int mIndex;
private float mPercent;
private ImageWrapper mImage;
private String mError;
public NotifyTask(GalleryProviderListener galleryProviderListener, ConcurrentPool<NotifyTask> pool) {
mGalleryProviderListener = galleryProviderListener;
mPool = pool;
}
public void setData(@Type int type, int index, float percent, ImageWrapper image, String error) {
mType = type;
mIndex = index;
mPercent = percent;
mImage = image;
mError = error;
}
@Override
public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
switch (mType) {
case TYPE_DATA_CHANGED:
if (mIndex < 0) {
mGalleryProviderListener.onDataChanged();
} else {
mGalleryProviderListener.onDataChanged(mIndex);
}
break;
case TYPE_WAIT:
mGalleryProviderListener.onPageWait(mIndex);
break;
case TYPE_PERCENT:
mGalleryProviderListener.onPagePercent(mIndex, mPercent);
break;
case TYPE_SUCCEED:
mGalleryProviderListener.onPageSucceed(mIndex, mImage);
break;
case TYPE_FAILED:
mGalleryProviderListener.onPageFailed(mIndex, mError);
break;
}
// Clean data
mImage = null;
mError = null;
// Push back
mPool.push(this);
return false;
}
}
private static class ImageCache extends LruCache<Integer, ImageWrapper> {
private static final long MAX_CACHE_SIZE = 128 * 1024 * 1024;
private static final long MIN_CACHE_SIZE = 32 * 1024 * 1024;
public ImageCache() {
super((int) MathUtils.clamp(OSUtils.getTotalMemory() / 16, MIN_CACHE_SIZE, MAX_CACHE_SIZE));
}
public void add(Integer key, ImageWrapper value) {
if (value.obtain()) {
put(key, value);
}
}
@Override
protected int sizeOf(Integer key, ImageWrapper value) {
return value.getWidth() * value.getHeight() * 4;
}
@Override
protected void entryRemoved(boolean evicted, Integer key, ImageWrapper oldValue, ImageWrapper newValue) {
if (oldValue != null) {
oldValue.release();
}
}
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.unifile.UniFile;
public abstract class GalleryProvider2 extends GalleryProvider {
// With dot
public static final String[] SUPPORT_IMAGE_EXTENSIONS = {
".jpg", // Joint Photographic Experts Group
".jpeg",
".png", // Portable Network Graphics
".gif", // Graphics Interchange Format
};
public int getStartPage() {
return 0;
}
public void putStartPage(int page) {}
/**
* @return without extension
*/
@NonNull
public abstract String getImageFilename(int index);
public abstract boolean save(int index, @NonNull UniFile file);
/**
* @param filename without extension
*/
@Nullable
public abstract UniFile save(int index, @NonNull UniFile dir, @NonNull String filename);
}
@@ -23,7 +23,7 @@ import android.util.Log;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.StringUtils;
@@ -43,7 +43,7 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
public class ZipGalleryProvider extends GalleryProvider implements Runnable {
public class ZipGalleryProvider extends GalleryProvider2 implements Runnable {
private static final String TAG = ZipGalleryProvider.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
@@ -1,67 +0,0 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.gl;
import android.view.MotionEvent;
public class DownUpDetector {
public interface DownUpListener {
void onDown(MotionEvent e);
void onUp(MotionEvent e);
void onPointerDown(MotionEvent e);
void onPointerUp(MotionEvent e);
}
private boolean mStillDown;
private DownUpListener mListener;
public DownUpDetector(DownUpListener listener) {
mListener = listener;
}
private void setState(boolean down, MotionEvent e) {
if (down == mStillDown) return;
mStillDown = down;
if (down) {
mListener.onDown(e);
} else {
mListener.onUp(e);
}
}
public void onTouchEvent(MotionEvent ev) {
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
setState(true, ev);
break;
case MotionEvent.ACTION_POINTER_DOWN:
mListener.onPointerDown(ev);
break;
case MotionEvent.ACTION_UP:
mListener.onPointerUp(ev);
setState(false, ev);
break;
case MotionEvent.ACTION_CANCEL:
setState(false, ev);
break;
}
}
public boolean isDown() {
return mStillDown;
}
}
@@ -1,138 +0,0 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.gl;
import android.content.Context;
import android.hardware.SensorManager;
import android.view.ViewConfiguration;
import android.view.animation.Interpolator;
import com.hippo.gl.anim.Animation;
public abstract class Fling extends Animation {
private static final float DECELERATION_RATE = (float) (Math.log(0.78) / Math.log(0.9));
private static final float INFLEXION = 0.35f; // Tension lines cross at (INFLEXION, 1)
private static final float START_TENSION = 0.5f;
private static final float END_TENSION = 1.0f;
private static final float P1 = START_TENSION * INFLEXION;
private static final float P2 = 1.0f - END_TENSION * (1.0f - INFLEXION);
private static final float FLING_FRICTION = ViewConfiguration.getScrollFriction();
private static final int NB_SAMPLES = 100;
private static final float[] SPLINE_POSITION = new float[NB_SAMPLES + 1];
private static final float[] SPLINE_TIME = new float[NB_SAMPLES + 1];
private float mPhysicalCoeff;
static {
float x_min = 0.0f;
float y_min = 0.0f;
for (int i = 0; i < NB_SAMPLES; i++) {
final float alpha = (float) i / NB_SAMPLES;
float x_max = 1.0f;
float x, tx, coef;
while (true) {
x = x_min + (x_max - x_min) / 2.0f;
coef = 3.0f * x * (1.0f - x);
tx = coef * ((1.0f - x) * P1 + x * P2) + x * x * x;
if (Math.abs(tx - alpha) < 1E-5) break;
if (tx > alpha) x_max = x;
else x_min = x;
}
SPLINE_POSITION[i] = coef * ((1.0f - x) * START_TENSION + x) + x * x * x;
float y_max = 1.0f;
float y, dy;
while (true) {
y = y_min + (y_max - y_min) / 2.0f;
coef = 3.0f * y * (1.0f - y);
dy = coef * ((1.0f - y) * START_TENSION + y) + y * y * y;
if (Math.abs(dy - alpha) < 1E-5) break;
if (dy > alpha) y_max = y;
else y_min = y;
}
SPLINE_TIME[i] = coef * ((1.0f - y) * P1 + y * P2) + y * y * y;
}
SPLINE_POSITION[NB_SAMPLES] = SPLINE_TIME[NB_SAMPLES] = 1.0f;
}
private static final Interpolator FLING_INTERPOLATOR = new Interpolator() {
@Override
public float getInterpolation(float input) {
final int index = (int) (NB_SAMPLES * input);
float distanceCoef = 1.f;
float velocityCoef = 0.f;
if (index < NB_SAMPLES) {
final float t_inf = (float) index / NB_SAMPLES;
final float t_sup = (float) (index + 1) / NB_SAMPLES;
final float d_inf = SPLINE_POSITION[index];
final float d_sup = SPLINE_POSITION[index + 1];
velocityCoef = (d_sup - d_inf) / (t_sup - t_inf);
distanceCoef = d_inf + (input - t_inf) * velocityCoef;
}
return distanceCoef;
}
};
public Fling(Context context) {
final float ppi = context.getResources().getDisplayMetrics().density * 160.0f;
mPhysicalCoeff = SensorManager.GRAVITY_EARTH // g (m/s^2)
* 39.37f // inch/meter
* ppi
* 0.84f; // look and feel tuning
setInterpolator(FLING_INTERPOLATOR);
}
private double getSplineDeceleration(int velocity) {
return Math.log(INFLEXION * Math.abs(velocity) / (FLING_FRICTION * mPhysicalCoeff));
}
/* Returns the duration, expressed in milliseconds */
protected int getSplineFlingDuration(int velocity) {
final double l = getSplineDeceleration(velocity);
final double decelMinusOne = DECELERATION_RATE - 1.0;
return (int) (1000.0 * Math.exp(l / decelMinusOne));
}
protected double getSplineFlingDistance(int velocity) {
final double l = getSplineDeceleration(velocity);
final double decelMinusOne = DECELERATION_RATE - 1.0;
return FLING_FRICTION * mPhysicalCoeff * Math.exp(DECELERATION_RATE / decelMinusOne * l);
}
/**
* Modifies mDuration to the duration it takes to get from start to newFinal using the
* spline interpolation. The previous duration was needed to get to oldFinal.
**/
protected int adjustDuration(int start, int oldFinal, int newFinal, int duration) {
final int oldDistance = oldFinal - start;
final int newDistance = newFinal - start;
final float x = Math.abs((float) newDistance / oldDistance);
final int index = (int) (NB_SAMPLES * x);
if (index < NB_SAMPLES) {
final float x_inf = (float) index / NB_SAMPLES;
final float x_sup = (float) (index + 1) / NB_SAMPLES;
final float t_inf = SPLINE_TIME[index];
final float t_sup = SPLINE_TIME[index + 1];
final float timeCoef = t_inf + (x - x_inf) / (x_sup - x_inf) * (t_sup - t_inf);
duration *= timeCoef;
}
return duration;
}
}
@@ -1,188 +0,0 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.gl;
import android.content.Context;
import com.hippo.gl.glrenderer.BasicTexture;
import com.hippo.gl.glrenderer.ImageMovableTextTexture;
import com.hippo.gl.glrenderer.ImageTexture;
import com.hippo.gl.glrenderer.Texture;
import com.hippo.gl.view.Gravity;
import com.hippo.gl.widget.GLFrameLayout;
import com.hippo.gl.widget.GLLinearLayout;
import com.hippo.gl.widget.GLMovableTextView;
import com.hippo.gl.widget.GLProgressView;
import com.hippo.gl.widget.GLTextureView;
import com.hippo.yorozuya.LayoutUtils;
public class GalleryPageView extends GLFrameLayout {
public static final int INVALID_INDEX = -1;
private static final int INFO_INTERVAL = 24;
public static final float PROGRESS_GONE = -1.0f;
public static final float PROGRESS_INDETERMINATE = -2.0f;
private static final int PAGE_MIN_HEIGHT = 256;
private final ImageView mImage;
private final GLLinearLayout mInfo;
private final GLMovableTextView mPage;
private final GLTextureView mError;
private final GLProgressView mProgress;
private final int mPageMinHeight;
private int mIndex = INVALID_INDEX;
public GalleryPageView(Context context, ImageMovableTextTexture pageTextTexture,
int progressColor, int progressSize) {
// Add image
mImage = new ImageView();
GravityLayoutParams glp = new GravityLayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
addComponent(mImage, glp);
// Add other panel
mInfo = new GLLinearLayout();
mInfo.setOrientation(GLLinearLayout.VERTICAL);
mInfo.setInterval(LayoutUtils.dp2pix(context, INFO_INTERVAL));
glp = new GravityLayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
glp.gravity = Gravity.CENTER;
addComponent(mInfo, glp);
// Add page
mPage = new GLMovableTextView();
mPage.setTextTexture(pageTextTexture);
GLLinearLayout.LayoutParams lp = new GLLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
mInfo.addComponent(mPage, lp);
// Add error
mError = new GLTextureView();
lp = new GLLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
mInfo.addComponent(mError, lp);
// Add progress
mProgress = new GLProgressView();
mProgress.setBgColor(GalleryView.BACKGROUND_COLOR);
mProgress.setColor(progressColor);
mProgress.setMinimumWidth(progressSize);
mProgress.setMinimumHeight(progressSize);
lp = new GLLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
mInfo.addComponent(mProgress, lp);
mPageMinHeight = LayoutUtils.dp2pix(context, PAGE_MIN_HEIGHT);
}
@Override
protected int getSuggestedMinimumHeight() {
// The height of the actual image may be smaller than mPageMinHeight.
// Set min height as 0 when the image is visible.
// For PageLayoutManager, min height is useless.
if (mImage.getVisibility() == VISIBLE) {
return 0;
} else {
return mPageMinHeight;
}
}
int getIndex() {
return mIndex;
}
void setIndex(int index) {
mIndex = index;
}
public void showImage() {
mImage.setVisibility(VISIBLE);
mInfo.setVisibility(GONE);
}
public void showInfo() {
// For image valid rect
mImage.setVisibility(INVISIBLE);
mInfo.setVisibility(VISIBLE);
}
private void unbindImage() {
ImageTexture texture = mImage.getImageTexture();
if (texture != null) {
mImage.setImageTexture(null);
texture.recycle();
}
}
public void setImage(ImageTexture imageTexture) {
unbindImage();
if (imageTexture != null) {
mImage.setImageTexture(imageTexture);
}
}
public void setPage(int page) {
mPage.setText(Integer.toString(page));
}
public void setProgress(float progress) {
if (progress == PROGRESS_GONE) {
mProgress.setVisibility(GONE);
} else if (progress == PROGRESS_INDETERMINATE) {
mProgress.setVisibility(VISIBLE);
mProgress.setIndeterminate(true);
} else {
mProgress.setVisibility(VISIBLE);
mProgress.setIndeterminate(false);
mProgress.setProgress(progress);
}
}
private void unbindError() {
Texture texture = mError.getTexture();
if (texture != null) {
mError.setTexture(null);
if (texture instanceof BasicTexture) {
((BasicTexture) texture).recycle();
}
}
}
public void setError(String error, GalleryView galleryView) {
unbindError();
if (error == null) {
mError.setVisibility(GONE);
} else {
mError.setVisibility(VISIBLE);
galleryView.bindErrorView(mError, error);
}
}
public ImageView getImageView() {
return mImage;
}
public boolean isLoaded() {
return mImage.getVisibility() == VISIBLE;
}
}
@@ -1,989 +0,0 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.gl;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import com.hippo.ehviewer.R;
import com.hippo.gl.annotation.RenderThread;
import com.hippo.gl.glrenderer.BasicTexture;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.gl.glrenderer.ImageMovableTextTexture;
import com.hippo.gl.glrenderer.StringTexture;
import com.hippo.gl.glrenderer.Texture;
import com.hippo.gl.util.GalleryUtils;
import com.hippo.gl.view.AnimationTime;
import com.hippo.gl.view.GLRoot;
import com.hippo.gl.view.GLView;
import com.hippo.gl.widget.GLEdgeView;
import com.hippo.gl.widget.GLProgressView;
import com.hippo.gl.widget.GLTextureView;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.Pool;
import com.hippo.yorozuya.ResourcesUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class GalleryView extends GLView implements GestureRecognizer.Listener {
@IntDef({LAYOUT_MODE_LEFT_TO_RIGHT, LAYOUT_MODE_RIGHT_TO_LEFT, LAYOUT_MODE_TOP_TO_BOTTOM})
@Retention(RetentionPolicy.SOURCE)
public @interface LayoutMode {}
public static final int BACKGROUND_COLOR = 0xff212121;
private static final int PROGRESS_SIZE_IN_DP = 48;
public static final int LAYOUT_MODE_LEFT_TO_RIGHT = 0;
public static final int LAYOUT_MODE_RIGHT_TO_LEFT = 1;
public static final int LAYOUT_MODE_TOP_TO_BOTTOM = 2;
private static final float[] LEFT_AREA = {0.0f, 0.0f, 1.0f / 3.0f, 1f};
private static final float[] RIGHT_AREA = {2.0f / 3.0f, 0.0f, 1.0f, 1f};
private static final float[] MENU_AREA = {1.0f / 3.0f, 0.0f, 2.0f / 3.0f, 1.0f / 2.0f};
private static final float[] SLIDER_AREA = {1.0f / 3.0f, 1.0f / 2.0f, 2.0f / 3.0f, 1.0f};
private static final int METHOD_ON_SINGLE_TAP_UP = 0;
private static final int METHOD_ON_SINGLE_TAP_CONFIRMED = 1;
private static final int METHOD_ON_DOUBLE_TAP = 2;
private static final int METHOD_ON_DOUBLE_TAP_CONFIRMED = 3;
private static final int METHOD_ON_LONG_PRESS = 4;
private static final int METHOD_ON_SCROLL = 5;
private static final int METHOD_ON_FLING = 6;
private static final int METHOD_ON_SCALE_BEGIN = 7;
private static final int METHOD_ON_SCALE = 8;
private static final int METHOD_ON_SCALE_END = 9;
private static final int METHOD_ON_DOWN = 10;
private static final int METHOD_ON_UP = 11;
private static final int METHOD_ON_POINTER_DOWN = 12;
private static final int METHOD_ON_POINTER_UP = 13;
private static final int METHOD_SET_LAYOUT_MODE = 14;
private static final int METHOD_SET_CURRENT_PAGE = 15;
private static final int METHOD_PAGE_LEFT = 16;
private static final int METHOD_PAGE_RIGHT = 17;
private static final int METHOD_SET_SCALE_MODE = 18;
private static final int METHOD_SET_START_POSITION = 19;
private static final int METHOD_ON_ATTACH_TO_ROOT = 20;
private final Context mContext;
private ImageMovableTextTexture mPageTextTexture;
private final GestureRecognizer mGestureRecognizer;
private Adapter mAdapter;
private PagerLayoutManager mPagerLayoutManager;
private ScrollLayoutManager mScrollLayoutManager;
@Nullable
private LayoutManager mLayoutManager;
private final Pool<GalleryPageView> mGalleryPageViewPool = new Pool<>(5);
private final GLEdgeView mEdgeView;
private GLProgressView mProgressCache;
private GLTextureView mErrorViewCache;
private final int mProgressColor;
private final int mProgressSize;
private final float mErrorSize;
private final int mErrorColor;
private boolean mEnableRequestFill = true;
private boolean mRequestFill = false;
private boolean mWillFill = false;
private boolean mScale = false;
private boolean mScroll = false;
private boolean mFirstScroll = false;
private final Rect mLeftArea = new Rect();
private final Rect mRightArea = new Rect();
private final Rect mMenuArea = new Rect();
private final Rect mSliderArea = new Rect();
private final String mDefaultErrorStr;
private final String mEmptyStr;
@LayoutMode
private int mLayoutMode = LAYOUT_MODE_RIGHT_TO_LEFT;
@ImageView.Scale
private int mScaleMode = ImageView.SCALE_FIT;
@ImageView.StartPosition
private int mStartPosition = ImageView.START_POSITION_TOP_LEFT;
private int mIndex;
private final Listener mListener;
private final List<Integer> mMethodList = new ArrayList<>(5);
private final List<Object[]> mArgsList = new ArrayList<>(5);
private final List<Integer> mMethodListTemp = new ArrayList<>(5);
private final List<Object[]> mArgsListTemp = new ArrayList<>(5);
private final AtomicInteger mCurrentIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
@SuppressWarnings("deprecation")
public GalleryView(@NonNull Context context, @NonNull Adapter adapter,
Listener listener, @LayoutMode int layoutMode, @ImageView.Scale int scaleMode,
@ImageView.StartPosition int startPosition, int startPage) {
mContext = context;
mAdapter = adapter;
mListener = listener;
mEdgeView = new GLEdgeView(context);
mGestureRecognizer = new GestureRecognizer(context, this);
adapter.setGalleryView(this);
mLayoutMode = layoutMode;
mScaleMode = scaleMode;
mStartPosition = startPosition;
mIndex = MathUtils.clamp(startPage, 0, Integer.MAX_VALUE);
mProgressColor = ResourcesUtils.getAttrColor(context, R.attr.colorPrimary);
mProgressSize = LayoutUtils.dp2pix(context, PROGRESS_SIZE_IN_DP);
mErrorSize = context.getResources().getDimension(R.dimen.text_large);
mErrorColor = context.getResources().getColor(R.color.red_500);
mDefaultErrorStr = context.getResources().getString(R.string.error_unknown);
mEmptyStr = context.getResources().getString(R.string.error_empty);
setBackgroundColor(BACKGROUND_COLOR);
}
private void ensurePagerLayoutManager() {
if (mPagerLayoutManager == null) {
mPagerLayoutManager = new PagerLayoutManager(mContext, this, mScaleMode, mStartPosition, 1.0f);
}
}
private void ensureScrollLayoutManager() {
if (mScrollLayoutManager == null) {
mScrollLayoutManager = new ScrollLayoutManager(mContext, this);
}
}
private void attachLayoutManager() {
if (null != mLayoutManager) {
return;
}
switch (mLayoutMode) {
case LAYOUT_MODE_LEFT_TO_RIGHT:
ensurePagerLayoutManager();
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_LEFT_TO_RIGHT);
mPagerLayoutManager.onAttach(mAdapter);
mPagerLayoutManager.setCurrentIndex(mIndex);
mAdapter = null;
mLayoutManager = mPagerLayoutManager;
break;
case LAYOUT_MODE_RIGHT_TO_LEFT:
ensurePagerLayoutManager();
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_RIGHT_TO_LEFT);
mPagerLayoutManager.onAttach(mAdapter);
mPagerLayoutManager.setCurrentIndex(mIndex);
mAdapter = null;
mLayoutManager = mPagerLayoutManager;
break;
case LAYOUT_MODE_TOP_TO_BOTTOM:
ensureScrollLayoutManager();
mScrollLayoutManager.onAttach(mAdapter);
mScrollLayoutManager.setCurrentIndex(mIndex);
mAdapter = null;
mLayoutManager = mScrollLayoutManager;
break;
}
requestFill();
}
private void detachLayoutManager() {
if (null == mLayoutManager) {
return;
}
mIndex = mLayoutManager.getInternalCurrentIndex();
mAdapter = mLayoutManager.onDetach();
mLayoutManager = null;
}
@SuppressWarnings("deprecation")
private void onAttachToRootInternal() {
if (null == mPageTextTexture) {
mPageTextTexture = ImageMovableTextTexture.create(Typeface.DEFAULT,
mContext.getResources().getDimensionPixelSize(R.dimen.gallery_page_text),
mContext.getResources().getColor(R.color.secondary_text_dark),
new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'});
}
attachLayoutManager();
}
@Override
public void onAttachToRoot(GLRoot root) {
super.onAttachToRoot(root);
mEdgeView.onAttachToRoot(root);
postMethod(METHOD_ON_ATTACH_TO_ROOT);
}
@Override
public void onDetachFromRoot() {
// When detached, render() will not be called. So do it here
detachLayoutManager();
if (null != mPageTextTexture) {
mPageTextTexture.recycle();
mPageTextTexture = null;
}
super.onDetachFromRoot();
mEdgeView.onDetachFromRoot();
}
@LayoutMode
public static int sanitizeLayoutMode(int layoutMode) {
if (layoutMode != GalleryView.LAYOUT_MODE_LEFT_TO_RIGHT &&
layoutMode != GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT &&
layoutMode != GalleryView.LAYOUT_MODE_TOP_TO_BOTTOM) {
return GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT;
} else {
return layoutMode;
}
}
public int getLayoutMode() {
return mLayoutMode;
}
public int getCurrentIndex() {
return mCurrentIndex.get();
}
@Override
public void requestLayout() {
// Do not need requestLayout, because the size will not change
requestFill();
}
public void requestFill() {
if (mEnableRequestFill) {
mRequestFill = true;
if (!mWillFill) {
invalidate();
}
}
}
@Override
protected boolean dispatchTouchEvent(MotionEvent event) {
// Do not pass event to component, so handle event here
mGestureRecognizer.onTouchEvent(event);
return true;
}
GLEdgeView getEdgeView() {
return mEdgeView;
}
String getDefaultErrorStr() {
return mDefaultErrorStr;
}
String getEmptyStr() {
return mEmptyStr;
}
boolean isFirstScroll() {
boolean firstScroll = mFirstScroll;
mFirstScroll = false;
return firstScroll;
}
// Make sure method run in render thread to ensure thread safe
private void postMethod(int method, Object... args) {
synchronized (this) {
mMethodList.add(method);
mArgsList.add(args);
}
invalidate();
}
public void setLayoutMode(@LayoutMode int layoutMode) {
postMethod(METHOD_SET_LAYOUT_MODE, layoutMode);
}
public void setCurrentPage(int page) {
postMethod(METHOD_SET_CURRENT_PAGE, page);
}
public void pageLeft() {
postMethod(METHOD_PAGE_LEFT);
}
public void pageRight() {
postMethod(METHOD_PAGE_RIGHT);
}
public void setScaleMode(@ImageView.Scale int scaleMode) {
postMethod(METHOD_SET_SCALE_MODE, scaleMode);
}
public void setStartPosition(@ImageView.StartPosition int startPosition) {
postMethod(METHOD_SET_START_POSITION, startPosition);
}
@Override
public boolean onSingleTapUp(float x, float y) {
postMethod(METHOD_ON_SINGLE_TAP_UP, x, y);
return true;
}
@Override
public boolean onSingleTapConfirmed(float x, float y) {
postMethod(METHOD_ON_SINGLE_TAP_CONFIRMED, x, y);
return true;
}
@Override
public boolean onDoubleTap(float x, float y) {
postMethod(METHOD_ON_DOUBLE_TAP, x, y);
return true;
}
@Override
public boolean onDoubleTapConfirmed(float x, float y) {
postMethod(METHOD_ON_DOUBLE_TAP_CONFIRMED, x, y);
return true;
}
@Override
public void onLongPress(float x, float y) {
if (mLayoutManager != null && !mLayoutManager.isTapOrPressEnable()) {
return;
}
postMethod(METHOD_ON_LONG_PRESS, x, y);
}
@Override
public boolean onScroll(float dx, float dy, float totalX, float totalY, float x, float y) {
postMethod(METHOD_ON_SCROLL, dx, dy, totalX, totalY, x, y);
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
postMethod(METHOD_ON_FLING, velocityX, velocityY);
return true;
}
@Override
public boolean onScaleBegin(float focusX, float focusY) {
postMethod(METHOD_ON_SCALE_BEGIN, focusX, focusY);
return true;
}
@Override
public boolean onScale(float focusX, float focusY, float scale) {
postMethod(METHOD_ON_SCALE, focusX, focusY, scale);
return true;
}
@Override
public void onScaleEnd() {
postMethod(METHOD_ON_SCALE_END);
}
@Override
public void onDown(float x, float y) {
postMethod(METHOD_ON_DOWN, x, y);
}
@Override
public void onUp() {
postMethod(METHOD_ON_UP);
}
@Override
public void onPointerDown(float x, float y) {
postMethod(METHOD_ON_POINTER_DOWN, x, y);
}
@Override
public void onPointerUp() {
postMethod(METHOD_ON_POINTER_UP);
}
@Override
protected void onLayout(boolean changeSize, int left, int top, int right, int bottom) {
mEdgeView.layout(left, top, right, bottom);
fill();
if (changeSize) {
int width = right - left;
int height = bottom - top;
mLeftArea.set((int) (LEFT_AREA[0] * width), (int) (LEFT_AREA[1] * height),
(int) (LEFT_AREA[2] * width), (int) (LEFT_AREA[3] * height));
mRightArea.set((int) (RIGHT_AREA[0] * width), (int) (RIGHT_AREA[1] * height),
(int) (RIGHT_AREA[2] * width), (int) (RIGHT_AREA[3] * height));
mMenuArea.set((int) (MENU_AREA[0] * width), (int) (MENU_AREA[1] * height),
(int) (MENU_AREA[2] * width), (int) (MENU_AREA[3] * height));
mSliderArea.set((int) (SLIDER_AREA[0] * width), (int) (SLIDER_AREA[1] * height),
(int) (SLIDER_AREA[2] * width), (int) (SLIDER_AREA[3] * height));
}
}
@RenderThread
public void onDataChanged() {
GalleryUtils.assertInRenderThread();
if (mLayoutManager != null){
mLayoutManager.onDataChanged();
}
}
private void onSingleTapUpInternal(float x, float y) {
}
private void onSingleTapConfirmedInternal(float x, float y) {
if (mLayoutManager == null || !mLayoutManager.isTapOrPressEnable()) {
return;
}
if (mSliderArea.contains((int) x, (int) y)) {
mListener.onTapSliderArea();
} else if (mMenuArea.contains((int) x, (int) y)) {
mListener.onTapMenuArea();
} else if (mLeftArea.contains((int) x, (int) y)) {
mLayoutManager.onPageLeft();
} else if (mRightArea.contains((int) x, (int) y)) {
mLayoutManager.onPageRight();
}
}
private void onDoubleTapInternal(float x, float y) {
}
private void onDoubleTapConfirmedInternal(float x, float y) {
if (mScale) {
return;
}
if (mLayoutManager != null) {
mLayoutManager.onDoubleTapConfirmed(x, y);
}
}
private void onLongPressInternal(float x, float y) {
if (mScale) {
return;
}
if (mLayoutManager == null) {
return;
}
int index = mLayoutManager.getIndexUnder(x, y);
if (index == GalleryPageView.INVALID_INDEX) {
return;
}
mListener.onLongPressPage(index);
}
private void onScrollInternal(float dx, float dy, float totalX, float totalY, float x, float y) {
if (mScale) {
return;
}
mScroll = true;
if (mLayoutManager != null) {
mLayoutManager.onScroll(dx, dy, totalX, totalY, x, y);
}
}
private void onFlingInternal(float velocityX, float velocityY) {
if (mLayoutManager != null) {
mLayoutManager.onFling(velocityX, velocityY);
}
}
private void onScaleBeginInternal(float focusX, float focusY) {
onScaleInternal(focusX, focusY, 1.0f);
}
private void onScaleInternal(float focusX, float focusY, float scale) {
if (mScroll || (mLayoutManager != null && !mLayoutManager.canScale())) {
return;
}
mScale = true;
if (mLayoutManager != null) {
mLayoutManager.onScale(focusX, focusY, scale);
}
}
private void onScaleEndInternal() {
}
private void onDownInternal(float x, float y) {
mScale = false;
mScroll = false;
mFirstScroll = true;
if (mLayoutManager != null) {
mLayoutManager.onDown();
}
}
private void onUpInternal() {
if (mLayoutManager != null) {
mLayoutManager.onUp();
}
}
private void onPointerDownInternal(float x, float y) {
if (!mScroll && (mLayoutManager != null && mLayoutManager.canScale())) {
mScale = true;
}
}
private void onPointerUpInternal() {
}
private void setLayoutModeInternal(int layoutMode) {
if (mLayoutMode == layoutMode) {
return;
}
mLayoutMode = layoutMode;
if (mLayoutManager == null) {
return;
}
switch (mLayoutMode) {
case LAYOUT_MODE_LEFT_TO_RIGHT:
if (mLayoutManager == mPagerLayoutManager) {
// mPagerLayoutManager already attached, just change mode
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_LEFT_TO_RIGHT);
} else {
ensurePagerLayoutManager();
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_LEFT_TO_RIGHT);
int index = mLayoutManager.getInternalCurrentIndex();
mPagerLayoutManager.onAttach(mLayoutManager.onDetach());
mPagerLayoutManager.setCurrentIndex(index);
mLayoutManager = mPagerLayoutManager;
}
break;
case LAYOUT_MODE_RIGHT_TO_LEFT:
if (mLayoutManager == mPagerLayoutManager) {
// mPagerLayoutManager already attached, just change mode
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_RIGHT_TO_LEFT);
} else {
ensurePagerLayoutManager();
mPagerLayoutManager.setMode(PagerLayoutManager.MODE_RIGHT_TO_LEFT);
int index = mLayoutManager.getInternalCurrentIndex();
mPagerLayoutManager.onAttach(mLayoutManager.onDetach());
mPagerLayoutManager.setCurrentIndex(index);
mLayoutManager = mPagerLayoutManager;
}
break;
case LAYOUT_MODE_TOP_TO_BOTTOM:
ensureScrollLayoutManager();
int index = mLayoutManager.getInternalCurrentIndex();
mScrollLayoutManager.onAttach(mLayoutManager.onDetach());
mScrollLayoutManager.setCurrentIndex(index);
mLayoutManager = mScrollLayoutManager;
break;
}
requestFill();
}
private void setCurrentPageInternal(int page) {
if (mLayoutManager != null) {
mLayoutManager.setCurrentIndex(page);
} else {
mIndex = page;
}
}
private void pageLeftInternal() {
if (mLayoutManager != null) {
mLayoutManager.onPageLeft();
}
}
private void pageRightInternal() {
if (mLayoutManager != null) {
mLayoutManager.onPageRight();
}
}
private void setScaleModeInternal(int scaleMode) {
mScaleMode = scaleMode;
if (mPagerLayoutManager != null) {
mPagerLayoutManager.setScaleMode(scaleMode);
}
}
private void setStartPositionInternal(int startPosition) {
mStartPosition = startPosition;
if (mPagerLayoutManager != null) {
mPagerLayoutManager.setStartPosition(startPosition);
}
}
@RenderThread
void forceFill() {
mRequestFill = true;
fill();
}
@RenderThread
private void fill() {
GalleryUtils.assertInRenderThread();
if (!mRequestFill) {
return;
}
// Disable request layout
mEnableRequestFill = false;
if (mLayoutManager != null) {
mLayoutManager.onFill();
}
mEnableRequestFill = true;
mRequestFill = false;
}
private void dispatchMethod() {
List<Integer> methodListTemp = mMethodListTemp;
List<Object[]> argsListTemp = mArgsListTemp;
synchronized (this) {
if (mMethodList.isEmpty()) {
return;
}
methodListTemp.addAll(mMethodList);
argsListTemp.addAll(mArgsList);
mMethodList.clear();
mArgsList.clear();
}
for (int i = 0, n = methodListTemp.size(); i < n; i++) {
int method = methodListTemp.get(i);
Object[] args = argsListTemp.get(i);
switch (method) {
case METHOD_ON_SINGLE_TAP_UP:
onSingleTapUpInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_SINGLE_TAP_CONFIRMED:
onSingleTapConfirmedInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_DOUBLE_TAP:
onDoubleTapInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_DOUBLE_TAP_CONFIRMED:
onDoubleTapConfirmedInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_LONG_PRESS:
onLongPressInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_SCROLL:
onScrollInternal((Float) args[0], (Float) args[1], (Float) args[2],
(Float) args[3], (Float) args[4], (Float) args[5]);
break;
case METHOD_ON_FLING:
onFlingInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_SCALE_BEGIN:
onScaleBeginInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_SCALE:
onScaleInternal((Float) args[0], (Float) args[1], (Float) args[2]);
break;
case METHOD_ON_SCALE_END:
onScaleEndInternal();
break;
case METHOD_ON_DOWN:
onDownInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_UP:
onUpInternal();
break;
case METHOD_ON_POINTER_DOWN:
onPointerDownInternal((Float) args[0], (Float) args[1]);
break;
case METHOD_ON_POINTER_UP:
onPointerUpInternal();
break;
case METHOD_SET_LAYOUT_MODE:
setLayoutModeInternal((Integer) args[0]);
break;
case METHOD_SET_CURRENT_PAGE:
setCurrentPageInternal((Integer) args[0]);
break;
case METHOD_PAGE_LEFT:
pageLeftInternal();
break;
case METHOD_PAGE_RIGHT:
pageRightInternal();
break;
case METHOD_SET_SCALE_MODE:
setScaleModeInternal((Integer) args[0]);
break;
case METHOD_SET_START_POSITION:
setStartPositionInternal((Integer) args[0]);
break;
case METHOD_ON_ATTACH_TO_ROOT:
onAttachToRootInternal();
break;
}
}
methodListTemp.clear();
argsListTemp.clear();
}
@Override
public void render(GLCanvas canvas) {
mWillFill = true;
int oldCurrentIndex = mCurrentIndex.get();
// Dispatch method
dispatchMethod();
long time = AnimationTime.get();
if (mLayoutManager != null && mLayoutManager.onUpdateAnimation(time)) {
invalidate();
}
fill();
mWillFill = false;
super.render(canvas);
mEdgeView.render(canvas);
int newCurrentIndex;
if (mLayoutManager != null) {
newCurrentIndex = mLayoutManager.getCurrentIndex();
} else {
newCurrentIndex = GalleryPageView.INVALID_INDEX;
}
mCurrentIndex.lazySet(newCurrentIndex);
if (oldCurrentIndex != newCurrentIndex) {
mListener.onUpdateCurrentIndex(newCurrentIndex);
}
}
@RenderThread
public GalleryPageView findPageByIndex(int id) {
if (mLayoutManager != null) {
return mLayoutManager.findPageByIndex(id);
} else {
return null;
}
}
GalleryPageView obtainPage() {
GalleryPageView page = mGalleryPageViewPool.pop();
if (page == null) {
page = new GalleryPageView(mContext, mPageTextTexture, mProgressColor, mProgressSize);
}
return page;
}
void releasePage(GalleryPageView page) {
mGalleryPageViewPool.push(page);
}
/**
* Indeterminate GLProgressView
*/
GLProgressView obtainProgress() {
GLProgressView progress;
if (mProgressCache != null) {
progress = mProgressCache;
mProgressCache = null;
} else {
progress = new GLProgressView();
progress.setColor(mProgressColor);
progress.setBgColor(BACKGROUND_COLOR);
progress.setIndeterminate(true);
progress.setMinimumWidth(mProgressSize);
progress.setMinimumHeight(mProgressSize);
}
return progress;
}
/**
* @param progress Indeterminate GLProgressView
*/
void releaseProgress(GLProgressView progress) {
mProgressCache = progress;
}
GLTextureView obtainErrorView() {
GLTextureView errorView;
if (mErrorViewCache != null) {
errorView = mErrorViewCache;
mErrorViewCache = null;
} else {
errorView = new GLTextureView();
}
return errorView;
}
void unbindErrorView(GLTextureView errorView) {
Texture texture = errorView.getTexture();
if (texture != null) {
errorView.setTexture(null);
if (texture instanceof BasicTexture) {
((BasicTexture) texture).recycle();
}
}
}
void bindErrorView(GLTextureView errorView, String error) {
unbindErrorView(errorView);
Texture texture = StringTexture.newInstance(error, mErrorSize, mErrorColor);
errorView.setTexture(texture);
}
void releaseErrorView(GLTextureView errorView) {
unbindErrorView(errorView);
mErrorViewCache = errorView;
}
public static abstract class Adapter {
protected GalleryView mGalleryView;
private void setGalleryView(@NonNull GalleryView galleryView) {
mGalleryView = galleryView;
}
public void bind(GalleryPageView view, int index) {
onBind(view, index);
view.setIndex(index);
}
public void unbind(GalleryPageView view) {
onUnbind(view, view.getIndex());
view.setIndex(GalleryPageView.INVALID_INDEX);
}
public abstract void onBind(GalleryPageView view, int index);
public abstract void onUnbind(GalleryPageView view, int index);
/**
* @return Null for no error
*/
public abstract String getError();
public abstract int size();
}
public static abstract class LayoutManager {
protected GalleryView mGalleryView;
public LayoutManager(@NonNull GalleryView galleryView) {
mGalleryView = galleryView;
}
public abstract void onAttach(Adapter iterator);
public abstract Adapter onDetach();
public abstract void onFill();
public abstract void onDown();
public abstract void onUp();
public abstract void onDoubleTapConfirmed(float x, float y);
public abstract void onLongPress(float x, float y);
public abstract void onScroll(float dx, float dy, float totalX, float totalY, float x, float y);
public abstract void onFling(float velocityX, float velocityY);
public abstract boolean canScale();
public abstract void onScale(float focusX, float focusY, float scale);
public abstract boolean onUpdateAnimation(long time);
public abstract void onDataChanged();
public abstract void onPageLeft();
public abstract void onPageRight();
public abstract boolean isTapOrPressEnable();
public abstract GalleryPageView findPageByIndex(int index);
/**
* @return {@link GalleryPageView#INVALID_INDEX} for error
*/
public abstract int getCurrentIndex();
public abstract void setCurrentIndex(int index);
public abstract int getIndexUnder(float x, float y);
abstract int getInternalCurrentIndex();
protected void placeCenter(GLView view) {
int spec = GLView.MeasureSpec.makeMeasureSpec(GLView.LayoutParams.WRAP_CONTENT,
GLView.LayoutParams.WRAP_CONTENT);
view.measure(spec, spec);
int viewWidth = view.getMeasuredWidth();
int viewHeight = view.getMeasuredHeight();
int viewLeft = mGalleryView.getWidth() / 2 - viewWidth / 2;
int viewTop = mGalleryView.getHeight() / 2 - viewHeight / 2;
view.layout(viewLeft, viewTop, viewLeft + viewWidth, viewTop + viewHeight);
}
}
public interface Listener {
@RenderThread
void onUpdateCurrentIndex(int index);
@RenderThread
void onTapSliderArea();
@RenderThread
void onTapMenuArea();
@RenderThread
void onLongPressPage(int index);
}
}
@@ -1,174 +0,0 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.gl;
import android.content.Context;
import android.os.SystemClock;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
// This class aggregates three gesture detectors: GestureDetector,
// ScaleGestureDetector, and DownUpDetector.
public class GestureRecognizer {
@SuppressWarnings("unused")
private static final String TAG = "GestureRecognizer";
public interface Listener {
boolean onSingleTapUp(float x, float y);
boolean onSingleTapConfirmed(float x, float y);
boolean onDoubleTap(float x, float y);
boolean onDoubleTapConfirmed(float x, float y);
void onLongPress(float x, float y);
boolean onScroll(float dx, float dy, float totalX, float totalY, float x, float y);
/**
* @param velocityX Finger from top to bottom is positive
* @param velocityY Finger from left to right is positive
*/
boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);
boolean onScaleBegin(float focusX, float focusY);
boolean onScale(float focusX, float focusY, float scale);
void onScaleEnd();
void onDown(float x, float y);
void onUp();
void onPointerDown(float x, float y);
void onPointerUp();
}
private final GestureDetectorCompat mGestureDetector;
private final ScaleGestureDetector mScaleDetector;
private final DownUpDetector mDownUpDetector;
private final Listener mListener;
public GestureRecognizer(Context context, Listener listener) {
mListener = listener;
MyGestureListener gestureListener = new MyGestureListener();
mGestureDetector = new GestureDetectorCompat(context, gestureListener,
null /* ignoreMultitouch */);
mGestureDetector.setOnDoubleTapListener(gestureListener);
mScaleDetector = new ScaleGestureDetector(
context, new MyScaleListener());
mDownUpDetector = new DownUpDetector(new MyDownUpListener());
}
public void onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
mGestureDetector.onTouchEvent(event);
mDownUpDetector.onTouchEvent(event);
}
public boolean isDown() {
return mDownUpDetector.isDown();
}
public void cancelScale() {
long now = SystemClock.uptimeMillis();
MotionEvent cancelEvent = MotionEvent.obtain(
now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0);
mScaleDetector.onTouchEvent(cancelEvent);
cancelEvent.recycle();
}
private class MyGestureListener
extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return mListener.onSingleTapUp(e.getX(), e.getY());
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return mListener.onSingleTapConfirmed(e.getX(), e.getY());
}
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_UP) {
return mListener.onDoubleTapConfirmed(e.getX(), e.getY());
} else {
return true;
}
}
@Override
public boolean onDoubleTap(MotionEvent e) {
return mListener.onDoubleTap(e.getX(), e.getY());
}
@Override
public void onLongPress(MotionEvent e) {
mListener.onLongPress(e.getX(), e.getY());
}
@Override
public boolean onScroll(
MotionEvent e1, MotionEvent e2, float dx, float dy) {
return mListener.onScroll(
dx, dy, e2.getX() - e1.getX(), e2.getY() - e1.getY(), e2.getX(), e2.getY());
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return mListener.onFling(e1, e2, velocityX, velocityY);
}
}
private class MyScaleListener
extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return mListener.onScaleBegin(
detector.getFocusX(), detector.getFocusY());
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
return mListener.onScale(detector.getFocusX(),
detector.getFocusY(), detector.getScaleFactor());
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
mListener.onScaleEnd();
}
}
private class MyDownUpListener implements DownUpDetector.DownUpListener {
@Override
public void onDown(MotionEvent e) {
mListener.onDown(e.getX(), e.getY());
}
@Override
public void onUp(MotionEvent e) {
mListener.onUp();
}
@Override
public void onPointerDown(MotionEvent e) {
mListener.onPointerDown(e.getX(), e.getY());
}
@Override
public void onPointerUp(MotionEvent e) {
mListener.onPointerUp();
}
}
}
@@ -1,620 +0,0 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.gallery.gl;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.IntDef;
import com.hippo.gl.anim.AlphaAnimation;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.gl.glrenderer.ImageTexture;
import com.hippo.gl.glrenderer.Texture;
import com.hippo.gl.view.GLView;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.MathUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
public class ImageView extends GLView implements ImageTexture.Callback {
@IntDef({SCALE_ORIGIN, SCALE_FIT_WIDTH, SCALE_FIT_HEIGHT, SCALE_FIT, SCALE_FIXED})
@Retention(RetentionPolicy.SOURCE)
public @interface Scale {}
@IntDef({START_POSITION_TOP_LEFT, START_POSITION_TOP_RIGHT, START_POSITION_BOTTOM_LEFT,
START_POSITION_BOTTOM_RIGHT, START_POSITION_CENTER})
@Retention(RetentionPolicy.SOURCE)
public @interface StartPosition {}
// TODO adjust scale max and min according to image size and screen size
private static final float SCALE_MIN = 1 / 10.0f;
private static final float SCALE_MAX = 10.0f;
public static final int SCALE_ORIGIN = 0;
public static final int SCALE_FIT_WIDTH = 1;
public static final int SCALE_FIT_HEIGHT = 2;
public static final int SCALE_FIT = 3;
public static final int SCALE_FIXED = 4;
public static final int START_POSITION_TOP_LEFT = 0;
public static final int START_POSITION_TOP_RIGHT = 1;
public static final int START_POSITION_BOTTOM_LEFT = 2;
public static final int START_POSITION_BOTTOM_RIGHT = 3;
public static final int START_POSITION_CENTER = 4;
private static final long ALPHA_ANIMATION_DURING = 300L;
private ImageTexture mImageTexture;
private int mTextureWidth;
private int mTextureHeight;
private final RectF mDst = new RectF();
private final RectF mSrcActual = new RectF();
private final RectF mDstActual = new RectF();
private final Rect mValidRect = new Rect();
private int mScaleMode = SCALE_FIT;
private int mStartPosition = START_POSITION_TOP_RIGHT;
private float mScaleValue = 1.0f;
private float mScale = 1.0f;
private boolean mScaleOffsetDirty = true;
private boolean mPositionInRootDirty = true;
private final AlphaAnimation mAlphaAnimation;
public ImageView() {
mAlphaAnimation = new AlphaAnimation(0.0f, 1.0f);
mAlphaAnimation.setDuration(ALPHA_ANIMATION_DURING);
mAlphaAnimation.setInterpolator(AnimationUtils.FAST_SLOW_INTERPOLATOR);
}
@Scale
public static int sanitizeScaleMode(int scaleMode) {
if (scaleMode != SCALE_ORIGIN &&
scaleMode != SCALE_FIT_WIDTH &&
scaleMode != SCALE_FIT_HEIGHT &&
scaleMode != SCALE_FIT &&
scaleMode != SCALE_FIXED) {
return SCALE_FIT;
} else {
return scaleMode;
}
}
@StartPosition
public static int sanitizeStartPosition(int startPosition) {
if (startPosition != START_POSITION_TOP_LEFT &&
startPosition != START_POSITION_TOP_RIGHT &&
startPosition != START_POSITION_BOTTOM_LEFT &&
startPosition != START_POSITION_BOTTOM_RIGHT &&
startPosition != START_POSITION_CENTER) {
return START_POSITION_TOP_RIGHT;
} else {
return startPosition;
}
}
@Override
protected int getSuggestedMinimumWidth() {
return Math.max(super.getSuggestedMinimumWidth(),
mImageTexture == null ? 0 : mTextureWidth);
}
@Override
protected int getSuggestedMinimumHeight() {
return Math.max(super.getSuggestedMinimumHeight(),
mImageTexture == null ? 0 : mTextureHeight);
}
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
if (mImageTexture == null) {
super.onMeasure(widthSpec, heightSpec);
} else {
float ratio = (float) mTextureWidth / mTextureHeight;
int widthSize = MeasureSpec.getSize(widthSpec);
int heightSize = MeasureSpec.getSize(heightSpec);
int widthMode = MeasureSpec.getMode(widthSpec);
int heightMode = MeasureSpec.getMode(heightSpec);
int measureWidth = -1;
int measureHeight = -1;
if (widthMode == MeasureSpec.EXACTLY) {
measureWidth = widthSize;
if (heightMode == MeasureSpec.EXACTLY) {
measureHeight = heightSize;
} else {
measureHeight = (int) (widthSize / ratio);
if (heightMode == MeasureSpec.AT_MOST) {
measureHeight = Math.min(measureHeight, heightSize);
}
}
} else if (heightMode == MeasureSpec.EXACTLY) {
measureHeight = heightSize;
measureWidth = (int) (heightSize * ratio);
if (widthMode == MeasureSpec.AT_MOST) {
measureWidth = Math.min(measureWidth, widthSize);
}
}
if (measureWidth == -1 || measureHeight == -1) {
super.onMeasure(widthSpec, heightSpec);
} else {
setMeasuredSize(measureWidth, measureHeight);
}
}
}
@Override
protected void onSizeChanged(int newW, int newH, int oldW, int oldH) {
mScaleOffsetDirty = true;
mPositionInRootDirty = true;
}
@Override
protected void onPositionInRootChanged(int x, int y, int oldX, int oldY) {
mPositionInRootDirty = true;
if (mImageTexture != null) {
getValidRect(mValidRect);
if (!mValidRect.isEmpty()) {
mImageTexture.start();
} else {
mImageTexture.stop();
}
}
}
public void getScaleDefault(float[] scaleDefault) {
if (mImageTexture == null) {
return;
}
scaleDefault[0] = 1.0f;
scaleDefault[1] = (float) getWidth() / mTextureWidth;
scaleDefault[2] = (float) getHeight() / mTextureHeight;
scaleDefault[3] = Math.max(scaleDefault[1], scaleDefault[2]) * 2;
scaleDefault[0] = MathUtils.clamp(scaleDefault[0], SCALE_MIN, SCALE_MAX);
scaleDefault[1] = MathUtils.clamp(scaleDefault[1], SCALE_MIN, SCALE_MAX);
scaleDefault[2] = MathUtils.clamp(scaleDefault[2], SCALE_MIN, SCALE_MAX);
scaleDefault[3] = MathUtils.clamp(scaleDefault[3], SCALE_MIN, SCALE_MAX);
Arrays.sort(scaleDefault);
}
public void setImageTexture(ImageTexture imageTexture) {
// Remove callback
if (mImageTexture != null) {
mImageTexture.setCallback(null);
mImageTexture.stop();
}
int oldTextureWidth = mTextureWidth;
int oldTextureHeight = mTextureHeight;
mImageTexture = imageTexture;
if (imageTexture != null) {
imageTexture.setCallback(this);
mTextureWidth = imageTexture.getWidth();
mTextureHeight = imageTexture.getHeight();
// Avoid zero and negative
if (mTextureWidth <= 0) {
mTextureWidth = 1;
}
if (mTextureHeight <= 0) {
mTextureHeight = 1;
}
// Start alpha animation, do not show animation for image has no valid rect
getValidRect(mValidRect);
if (!mValidRect.isEmpty()) {
startAnimation(mAlphaAnimation, true);
mImageTexture.start();
}
} else {
mTextureWidth = 1;
mTextureHeight = 1;
}
mScaleOffsetDirty = true;
mPositionInRootDirty = true;
if (oldTextureWidth != mTextureWidth || oldTextureHeight != mTextureHeight) {
requestLayout();
}
}
public ImageTexture getImageTexture() {
return mImageTexture;
}
public boolean isLoaded() {
return mImageTexture != null;
}
public boolean canFlingVertically() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return false;
}
}
return mDst.top < 0.0f || mDst.bottom > getHeight();
}
public boolean canFlingHorizontally() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return false;
}
}
return mDst.left < 0.0f || mDst.right > getWidth();
}
public boolean canFling() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return false;
}
}
return mDst.left < 0.0f || mDst.top < 0.0f || mDst.right > getWidth() || mDst.bottom > getHeight();
}
public int getMaxDx() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return 0;
}
}
return Math.max(0, -(int) mDst.left);
}
public int getMinDx() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return 0;
}
}
return Math.min(0, getWidth() - (int) mDst.right);
}
public int getMaxDy() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return 0;
}
}
return Math.max(0, -(int) mDst.top);
}
public int getMinDy() {
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
if (mScaleOffsetDirty) {
return 0;
}
}
return Math.min(0, getHeight() - (int) mDst.bottom);
}
public float getScale() {
return mScale;
}
/**
* If target is shorter then screen, make it in screen center. If target is
* longer then parent, make sure target fill parent over
*/
private void adjustPosition() {
RectF dst = mDst;
int screenWidth = getWidth();
int screenHeight = getHeight();
float targetWidth = dst.width();
float targetHeight = dst.height();
if (targetWidth > screenWidth) {
float fixXOffset = dst.left;
if (fixXOffset > 0) {
dst.left -= fixXOffset;
dst.right -= fixXOffset;
} else if ((fixXOffset = screenWidth - dst.right) > 0) {
dst.left += fixXOffset;
dst.right += fixXOffset;
}
} else {
float left = (screenWidth - targetWidth) / 2;
dst.offsetTo(left, dst.top);
}
if (targetHeight > screenHeight) {
float fixYOffset = dst.top;
if (fixYOffset > 0) {
dst.top -= fixYOffset;
dst.bottom -= fixYOffset;
} else if ((fixYOffset = screenHeight - dst.bottom) > 0) {
dst.top += fixYOffset;
dst.bottom += fixYOffset;
}
} else {
float top = (screenHeight - targetHeight) / 2;
dst.offsetTo(dst.left, top);
}
}
public void setScaleOffset(@Scale int scaleMode, @StartPosition int startPosition, float scaleValue) {
mScaleMode = scaleMode;
mStartPosition = startPosition;
mScaleValue = scaleValue;
int screenWidth = getWidth();
int screenHeight = getHeight();
if (mImageTexture == null || screenWidth == 0 || screenHeight == 0) {
mScaleOffsetDirty = true;
return;
}
int textureWidth = mTextureWidth;
int textureHeight = mTextureHeight;
// Set scale
float targetWidth;
float targetHeight;
switch (scaleMode) {
case SCALE_ORIGIN:
mScale = 1.0f;
targetWidth = textureWidth;
targetHeight = textureHeight;
break;
case SCALE_FIT_WIDTH:
mScale = (float) screenWidth / textureWidth;
targetWidth = screenWidth;
targetHeight = textureHeight * mScale;
break;
case SCALE_FIT_HEIGHT:
mScale = (float) screenHeight / textureHeight;
targetWidth = textureWidth * mScale;
targetHeight = screenHeight;
break;
case SCALE_FIT:
float scaleX = (float) screenWidth / textureWidth;
float scaleY = (float) screenHeight / textureHeight;
if (scaleX < scaleY) {
mScale = scaleX;
targetWidth = screenWidth;
targetHeight = textureHeight * scaleX;
} else {
mScale = scaleY;
targetWidth = textureWidth * scaleY;
targetHeight = screenHeight;
break;
}
break;
case SCALE_FIXED:
default:
mScale = scaleValue;
targetWidth = textureWidth * scaleValue;
targetHeight = textureHeight * scaleValue;
break;
}
// adjust scale, not too big, not too small
if (mScale < SCALE_MIN) {
mScale = SCALE_MIN;
targetWidth = textureWidth * SCALE_MIN;
targetHeight = textureHeight * SCALE_MIN;
} else if (mScale > SCALE_MAX) {
mScale = SCALE_MAX;
targetWidth = textureWidth * SCALE_MAX;
targetHeight = textureHeight * SCALE_MAX;
}
// Set mDst.left and mDst.right
RectF dst = mDst;
switch (startPosition) {
case START_POSITION_TOP_LEFT:
dst.left = 0;
dst.top = 0;
break;
case START_POSITION_TOP_RIGHT:
dst.left = screenWidth - targetWidth;
dst.top = 0;
break;
case START_POSITION_BOTTOM_LEFT:
dst.left = 0;
dst.top = screenHeight - targetHeight;
break;
case START_POSITION_BOTTOM_RIGHT:
dst.left = screenWidth - targetWidth;
dst.top = screenHeight - targetHeight;
break;
case START_POSITION_CENTER:
default:
dst.left = (screenWidth - targetWidth) / 2;
dst.top = (screenHeight - targetHeight) / 2;
break;
}
// Set mDst.right and mDst.bottom
dst.right = dst.left + targetWidth;
dst.bottom = dst.top + targetHeight;
// adjust position
adjustPosition();
mScaleOffsetDirty = false;
mPositionInRootDirty = true;
}
public void scroll(int dx, int dy, int[] remain) {
// Only work after layout
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
}
if (mScaleOffsetDirty) {
remain[0] = dx;
remain[1] = dy;
return;
}
RectF dst = mDst;
int screenWidth = getWidth();
int screenHeight = getHeight();
float targetWidth = dst.width();
float targetHeight = dst.height();
if (targetWidth > screenWidth) {
dst.left -= dx;
dst.right -= dx;
float fixXOffset = dst.left;
if (fixXOffset > 0) {
dst.left -= fixXOffset;
dst.right -= fixXOffset;
remain[0] = -(int) fixXOffset;
} else if ((fixXOffset = screenWidth - dst.right) > 0) {
dst.left += fixXOffset;
dst.right += fixXOffset;
remain[0] = (int) fixXOffset;
} else {
remain[0] = 0;
}
} else {
remain[0] = dx;
}
if (targetHeight > screenHeight) {
dst.top -= dy;
dst.bottom -= dy;
float fixYOffset = dst.top;
if (fixYOffset > 0) {
dst.top -= fixYOffset;
dst.bottom -= fixYOffset;
remain[1] = -(int) fixYOffset;
} else if ((fixYOffset = screenHeight - dst.bottom) > 0) {
dst.top += fixYOffset;
dst.bottom += fixYOffset;
remain[1] = (int) fixYOffset;
} else {
remain[1] = 0;
}
} else {
remain[1] = dy;
}
if (dx != remain[0] || dy != remain[1]) {
mPositionInRootDirty = true;
invalidate();
}
}
public void scale(float focusX, float focusY, float scale) {
// Only work after layout
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
}
if (mScaleOffsetDirty) {
return;
}
if ((mScale == SCALE_MAX && scale >= 1.0f) || (mScale == SCALE_MIN && scale < 1.0f)) {
return;
}
float newScale = mScale * scale;
newScale = MathUtils.clamp(newScale, SCALE_MIN, SCALE_MAX);
mScale = newScale;
RectF dst = mDst;
float left = (focusX - ((focusX - dst.left) * scale));
float top = (focusY - ((focusY - dst.top) * scale));
dst.set(left, top,
(left + (mImageTexture.getWidth() * newScale)),
(top + (mImageTexture.getHeight() * newScale)));
// adjust position
adjustPosition();
mPositionInRootDirty = true;
invalidate();
}
private void applyPositionInRoot() {
int width = mImageTexture.getWidth();
int height = mImageTexture.getHeight();
RectF dst = mDst;
RectF dstActual = mDstActual;
RectF srcActual = mSrcActual;
dstActual.set(dst);
getValidRect(mValidRect);
if (dstActual.intersect(mValidRect.left, mValidRect.top, mValidRect.right, mValidRect.bottom)) {
srcActual.left = MathUtils.lerp(0, width,
MathUtils.delerp(dst.left, dst.right, dstActual.left));
srcActual.right = MathUtils.lerp(0, width,
MathUtils.delerp(dst.left, dst.right, dstActual.right));
srcActual.top = MathUtils.lerp(0, height,
MathUtils.delerp(dst.top, dst.bottom, dstActual.top));
srcActual.bottom = MathUtils.lerp(0, height,
MathUtils.delerp(dst.top, dst.bottom, dstActual.bottom));
} else {
// Can't be seen, set src and dst empty
srcActual.setEmpty();
dstActual.setEmpty();
}
mPositionInRootDirty = false;
}
@Override
public void onRender(GLCanvas canvas) {
Texture texture = mImageTexture;
if (texture == null) {
return;
}
if (mScaleOffsetDirty) {
setScaleOffset(mScaleMode, mStartPosition, mScaleValue);
}
if (mPositionInRootDirty) {
applyPositionInRoot();
}
if (!mSrcActual.isEmpty()) {
texture.draw(canvas, mSrcActual, mDstActual);
}
}
@Override
public void invalidateImageTexture(ImageTexture who) {
invalidate();
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,105 @@
/*
* Copyright 2018 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.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import android.widget.Toast;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.preference.MessagePreference;
import com.hippo.text.Html;
import java.util.LinkedList;
import java.util.List;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
public class IdentityCookiePreference extends MessagePreference {
private String message;
public IdentityCookiePreference(Context context) {
super(context);
init();
}
public IdentityCookiePreference(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public IdentityCookiePreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
EhCookieStore store = EhApplication.getEhCookieStore(getContext());
List<Cookie> eCookies = store.getCookies(HttpUrl.get(EhUrl.HOST_E));
List<Cookie> exCookies = store.getCookies(HttpUrl.get(EhUrl.HOST_EX));
List<Cookie> cookies = new LinkedList<>(eCookies);
cookies.addAll(exCookies);
String ipbMemberId = null;
String ipbPassHash = null;
String igneous = null;
for (int i = 0, n = cookies.size(); i < n; i++) {
Cookie cookie = cookies.get(i);
switch (cookie.name()) {
case EhCookieStore.KEY_IPD_MEMBER_ID:
ipbMemberId = cookie.value();
break;
case EhCookieStore.KEY_IPD_PASS_HASH:
ipbPassHash = cookie.value();
break;
case EhCookieStore.KEY_IGNEOUS:
igneous = cookie.value();
break;
}
}
if (ipbMemberId != null || ipbPassHash != null || igneous != null) {
message = EhCookieStore.KEY_IPD_MEMBER_ID + ": " + ipbMemberId + "<br>"
+ EhCookieStore.KEY_IPD_PASS_HASH + ": " + ipbPassHash + "<br>"
+ EhCookieStore.KEY_IGNEOUS + ": " + igneous;
setDialogMessage(Html.fromHtml(getContext().getString(R.string.settings_eh_identity_cookies_signed, message)));
message = message.replace("<br>", "\n");
} else {
setDialogMessage(getContext().getString(R.string.settings_eh_identity_cookies_tourist));
}
}
@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
super.onPrepareDialogBuilder(builder);
if (message != null) {
builder.setPositiveButton(R.string.settings_eh_identity_cookies_copy, (dialog, which) -> {
ClipboardManager cmb = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setPrimaryClip(ClipData.newPlainText(null, message));
Toast.makeText(getContext(), R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
IdentityCookiePreference.this.onClick(dialog, which);
});
}
}
}
@@ -31,6 +31,7 @@ import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhEngine;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.download.DownloadManager;
import com.hippo.ehviewer.spider.SpiderInfo;
import com.hippo.ehviewer.spider.SpiderQueen;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.IOUtils;
@@ -88,13 +89,15 @@ public class RestoreDownloadPreference extends TaskPreference {
InputStream is = null;
try {
is = siFile.openInputStream();
// Skip start page
IOUtils.readAsciiLine(is);
long gid = Long.parseLong(IOUtils.readAsciiLine(is));
SpiderInfo spiderInfo = SpiderInfo.read(is);
if (spiderInfo == null) {
return null;
}
long gid = spiderInfo.gid;
if (mManager.containDownloadInfo(gid)) {
return null;
}
String token = IOUtils.readAsciiLine(is);
String token = spiderInfo.token;
RestoreItem restoreItem = new RestoreItem();
restoreItem.gid = gid;
restoreItem.token = token;
@@ -0,0 +1,57 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.preference;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.preference.Preference;
import android.util.AttributeSet;
import com.hippo.ehviewer.R;
public class VersionPreference extends Preference {
public VersionPreference(Context context) {
super(context);
init(context);
}
public VersionPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public VersionPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
setTitle(R.string.settings_about_version);
String version;
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
version = context.getString(R.string.error_unknown);
}
setSummary(version);
}
}
@@ -0,0 +1,44 @@
/*
* Copyright 2018 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.shortcuts;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.hippo.ehviewer.download.DownloadService;
/**
* Created by onlymash on 3/25/18.
*/
public class ShortcutsActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String action = null;
Intent intent = getIntent();
if (intent != null){
action = intent.getAction();
if (action != null && (action.equals(DownloadService.ACTION_START_ALL) ||
action.equals(DownloadService.ACTION_STOP_ALL))){
startService(new Intent(this, DownloadService.class).setAction(action));
}
}
finish();
}
}
@@ -27,7 +27,7 @@ import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhCacheKeyFactory;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.gallery.GalleryProvider;
import com.hippo.ehviewer.gallery.GalleryProvider2;
import com.hippo.io.UniFileInputStreamPipe;
import com.hippo.io.UniFileOutputStreamPipe;
import com.hippo.streampipe.InputStreamPipe;
@@ -169,7 +169,7 @@ public final class SpiderDen {
@Nullable
private static UniFile findImageFile(UniFile dir, int index) {
for (String extension : GalleryProvider.SUPPORT_IMAGE_EXTENSIONS) {
for (String extension : GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS) {
String filename = generateImageFilename(index, extension);
UniFile file = dir.findFile(filename);
if (file != null) {
@@ -193,10 +193,10 @@ public final class SpiderDen {
* @param extension with dot
*/
private String fixExtension(String extension) {
if (Utilities.contain(GalleryProvider.SUPPORT_IMAGE_EXTENSIONS, extension)) {
if (Utilities.contain(GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS, extension)) {
return extension;
} else {
return GalleryProvider.SUPPORT_IMAGE_EXTENSIONS[0];
return GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS[0];
}
}
@@ -275,8 +275,8 @@ public final class SpiderDen {
}
boolean result = false;
for (int i = 0, n = GalleryProvider.SUPPORT_IMAGE_EXTENSIONS.length; i < n; i++) {
String filename = generateImageFilename(index, GalleryProvider.SUPPORT_IMAGE_EXTENSIONS[i]);
for (int i = 0, n = GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS.length; i < n; i++) {
String filename = generateImageFilename(index, GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS[i]);
UniFile file = dir.subFile(filename);
if (file != null) {
result |= file.delete();
@@ -323,7 +323,12 @@ public final class SpiderDen {
@Nullable
public OutputStreamPipe openOutputStreamPipe(int index, @Nullable String extension) {
if (mMode == SpiderQueen.MODE_READ) {
return openCacheOutputStreamPipe(index);
// Return the download pipe is the gallery has been downloaded
OutputStreamPipe pipe = openDownloadOutputStreamPipe(index, extension);
if (pipe == null) {
pipe = openCacheOutputStreamPipe(index);
}
return pipe;
} else if (mMode == SpiderQueen.MODE_DOWNLOAD) {
return openDownloadOutputStreamPipe(index, extension);
} else {
@@ -40,13 +40,13 @@ public class SpiderInfo {
static final String TOKEN_FAILED = "failed";
int startPage = 0;
long gid = -1;
String token = null;
int pages = -1;
int previewPages = -1;
int previewPerPage = -1;
SparseArray<String> pTokenMap = null;
public int startPage = 0;
public long gid = -1;
public String token = null;
public int pages = -1;
public int previewPages = -1;
public int previewPerPage = -1;
public SparseArray<String> pTokenMap = null;
public static SpiderInfo read(@Nullable UniFile file) {
if (file == null) {
@@ -94,6 +94,7 @@ public class SpiderInfo {
}
}
@Nullable
@SuppressWarnings("InfiniteLoopStatement")
public static SpiderInfo read(@Nullable InputStream is) {
if (null == is) {
@@ -143,7 +144,7 @@ public class SpiderInfo {
while (true) { // EOFException will raise
line = IOUtils.readAsciiLine(is);
int pos = line.indexOf(" ");
if (pos > 0 || pos < line.length() - 1) {
if (pos > 0) {
int index = Integer.parseInt(line.substring(0, pos));
String pToken = line.substring(pos + 1);
if (!TextUtils.isEmpty(pToken)) {
@@ -45,8 +45,9 @@ import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.GalleryDetailParser;
import com.hippo.ehviewer.client.parser.GalleryPageParser;
import com.hippo.ehviewer.client.parser.GalleryPageUrlParser;
import com.hippo.ehviewer.gallery.GalleryProvider;
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.ehviewer.gallery.GalleryProvider2;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.image.Image;
import com.hippo.streampipe.InputStreamPipe;
import com.hippo.streampipe.OutputStreamPipe;
@@ -70,7 +71,6 @@ import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
@@ -138,7 +138,7 @@ public final class SpiderQueen implements Runnable {
private final Thread[] mDecodeThreadArray = new Thread[DECODE_THREAD_NUM];
private final int[] mDecodeIndexArray = new int[DECODE_THREAD_NUM];
private final Stack<Integer> mDecodeRequestStack = new Stack<>();
private final Queue<Integer> mDecodeRequestQueue = new LinkedList<>();
private final Object mWorkerLock = new Object();
private ThreadPoolExecutor mWorkerPoolExecutor;
@@ -422,7 +422,6 @@ public final class SpiderQueen implements Runnable {
}
public String getError() {
// TODO
if (mQueenThread == null) {
return "Error";
} else {
@@ -431,11 +430,11 @@ public final class SpiderQueen implements Runnable {
}
public Object forceRequest(int index) {
return request(index, true, false);
return request(index, true, true, false);
}
public Object request(int index) {
return request(index, false, true);
return request(index, true, false, true);
}
private int getPageState(int index) {
@@ -473,6 +472,9 @@ public final class SpiderQueen implements Runnable {
synchronized (mRequestPageQueue) {
mRequestPageQueue.remove(index);
}
synchronized (mDecodeRequestQueue) {
mDecodeRequestQueue.remove(index);
}
}
/**
@@ -481,7 +483,7 @@ public final class SpiderQueen implements Runnable {
* Float for download percent<br>
* null for wait
*/
private Object request(int index, boolean force, boolean addNeighbor) {
private Object request(int index, boolean ignoreError, boolean force, boolean addNeighbor) {
if (mQueenThread == null) {
return null;
}
@@ -490,7 +492,8 @@ public final class SpiderQueen implements Runnable {
int state = getPageState(index);
// Fix state for force
if (force && (state == STATE_FINISHED || state == STATE_FAILED)) {
if ((force && (state == STATE_FINISHED || state == STATE_FAILED)) ||
(ignoreError && state == STATE_FAILED)) {
// Update state to none at once
updatePageState(index, STATE_NONE);
state = STATE_NONE;
@@ -516,7 +519,7 @@ public final class SpiderQueen implements Runnable {
} else {
size = Integer.MAX_VALUE;
}
for (int i = index + 1, n = index + i + mPreloadNumber; i < n && i < size; i++) {
for (int i = index + 1, n = index + 1 + mPreloadNumber; i < n && i < size; i++) {
if (STATE_NONE == getPageState(i)) {
mRequestPageQueue2.add(i);
}
@@ -542,10 +545,10 @@ public final class SpiderQueen implements Runnable {
result = error;
break;
case STATE_FINISHED:
synchronized (mDecodeRequestStack) {
if (!contain(mDecodeIndexArray, index) && !mDecodeRequestStack.contains(index)) {
mDecodeRequestStack.add(index);
mDecodeRequestStack.notify();
synchronized (mDecodeRequestQueue) {
if (!contain(mDecodeIndexArray, index) && !mDecodeRequestQueue.contains(index)) {
mDecodeRequestQueue.add(index);
mDecodeRequestQueue.notify();
}
}
result = null;
@@ -711,10 +714,13 @@ public final class SpiderQueen implements Runnable {
spiderInfo.pages = GalleryDetailParser.parsePages(body);
spiderInfo.previewPages = GalleryDetailParser.parsePreviewPages(body);
PreviewSet previewSet = GalleryDetailParser.parsePreviewSet(body);
if ((index >= 0 && index < spiderInfo.pages - 1) || (index == 0 && spiderInfo.pages == 1)) {
spiderInfo.previewPerPage = previewSet.size();
} else {
spiderInfo.previewPerPage = Math.max(spiderInfo.previewPerPage, previewSet.size());
if (previewSet.size() > 0) {
if (index == 0) {
spiderInfo.previewPerPage = previewSet.size();
} else {
spiderInfo.previewPerPage = previewSet.getPosition(0) / index;
}
}
for (int i = 0, n = previewSet.size(); i < n; i++) {
@@ -760,6 +766,9 @@ public final class SpiderQueen implements Runnable {
} else {
previewIndex = 0;
}
if (spiderInfo.previewPages > 0) {
previewIndex = Math.min(previewIndex, spiderInfo.previewPages - 1);
}
try {
String url = EhUrl.getGalleryDetailUrl(
@@ -1005,14 +1014,27 @@ public final class SpiderQueen implements Runnable {
mGid = mGalleryInfo.gid;
}
private GalleryPageParser.Result getImageUrl(long gid, int index, String pToken,
String skipHathKey) throws Exception {
String url = EhUrl.getPageUrl(gid, index, pToken);
if (skipHathKey != null) {
url = url + "?nl=" + skipHathKey;
private String getPageUrl(long gid, int index, String pToken,
String oldPageUrl, String skipHathKey) {
String pageUrl;
if (oldPageUrl != null) {
pageUrl = oldPageUrl;
} else {
pageUrl = EhUrl.getPageUrl(gid, index, pToken);
}
// Add skipHathKey
if (skipHathKey != null) {
if (pageUrl.contains("?")) {
pageUrl += "&nl=" + skipHathKey;
} else {
pageUrl += "?nl=" + skipHathKey;
}
}
return pageUrl;
}
GalleryPageParser.Result result = EhEngine.getGalleryPage(null, mHttpClient, url);
private GalleryPageParser.Result getImageUrl(int index, String pageUrl) throws Exception {
GalleryPageParser.Result result = EhEngine.getGalleryPage(null, mHttpClient, pageUrl);
if (StringUtils.endsWith(result.imageUrl, URL_509_SUFFIX_ARRAY)) {
// Get 509
// Notify listeners
@@ -1025,21 +1047,27 @@ public final class SpiderQueen implements Runnable {
// false for stop
private boolean downloadImage(long gid, int index, String pToken, boolean force) {
List<String> skipHathKeys = new ArrayList<>(5);
String skipHathKey = null;
String imageUrl;
String error = null;
String pageUrl = null;
boolean interrupt = false;
boolean leakSkipHathKey = false;
Log.d("TAG", "index = " + index);
// Try twice
for (int i = 0; i < 2; i++) {
if (i > 0 && TextUtils.isEmpty(skipHathKey)) {
// No need to get image url twice without skip hath key
for (int i = 0; i < 5; i++) {
if (leakSkipHathKey) {
break;
}
pageUrl = getPageUrl(gid, index, pToken, pageUrl, skipHathKey);
GalleryPageParser.Result result = null;
try {
result = getImageUrl(gid, index, pToken, skipHathKey);
result = getImageUrl(index, pageUrl);
} catch (Image509Exception e) {
error = GetText.getString(R.string.error_509);
} catch (Exception e) {
@@ -1051,6 +1079,7 @@ public final class SpiderQueen implements Runnable {
}
// Check interrupted
if (Thread.currentThread().isInterrupted()) {
error = "Interrupted";
interrupt = true;
break;
}
@@ -1061,11 +1090,22 @@ public final class SpiderQueen implements Runnable {
imageUrl = result.imageUrl;
}
skipHathKey = result.skipHathKey;
if (!TextUtils.isEmpty(skipHathKey)) {
if (skipHathKeys.contains(skipHathKey)) {
// Duplicate skip hath key, don't run next turn
leakSkipHathKey = true;
} else {
skipHathKeys.add(skipHathKey);
}
} else {
// No skip hath key, don't run next turn
leakSkipHathKey = true;
}
// If it is force request, skip first image
if (force && i == 0) {
continue;
}
//if (force && i == 0) {
// continue;
//}
if (DEBUG_LOG) {
Log.d(TAG, imageUrl);
@@ -1084,6 +1124,7 @@ public final class SpiderQueen implements Runnable {
if (response.code() >= 400) {
// Maybe 404
response.body().close();
error = "Bad code: " + response.code();
continue;
}
ResponseBody responseBody = response.body();
@@ -1092,8 +1133,8 @@ public final class SpiderQueen implements Runnable {
String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(
responseBody.contentType().toString());
// Ensure extension
if (!Utilities.contain(GalleryProvider.SUPPORT_IMAGE_EXTENSIONS, extension)) {
extension = GalleryProvider.SUPPORT_IMAGE_EXTENSIONS[0];
if (!Utilities.contain(GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS, extension)) {
extension = GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS[0];
}
// Get out put pipe
@@ -1130,9 +1171,21 @@ public final class SpiderQueen implements Runnable {
}
os.flush();
// check download size
if (contentLength >= 0) {
if (receivedSize < contentLength) {
Log.e(TAG, "Can't download all of image data");
error = "Incomplete";
continue;
} else if (receivedSize > contentLength) {
Log.w(TAG, "Received data is more than contentLength");
}
}
// Check interrupted
if (Thread.currentThread().isInterrupted()) {
interrupt = true;
error = "Interrupted";
break;
}
@@ -1222,9 +1275,11 @@ public final class SpiderQueen implements Runnable {
if (force) {
synchronized (mPTokenLock) {
int i = spiderInfo.pTokenMap.indexOfKey(index);
String pToken = spiderInfo.pTokenMap.valueAt(i);
if (SpiderInfo.TOKEN_FAILED.equals(pToken)) {
spiderInfo.pTokenMap.remove(i);
if (i >= 0) {
String pToken = spiderInfo.pTokenMap.valueAt(i);
if (SpiderInfo.TOKEN_FAILED.equals(pToken)) {
spiderInfo.pTokenMap.remove(i);
}
}
}
}
@@ -1261,7 +1316,7 @@ public final class SpiderQueen implements Runnable {
if (pToken == null) {
// Interrupted
// Get token failed
updatePageState(index, STATE_FAILED, null);
updatePageState(index, STATE_FAILED, "Interrupted");
return false;
}
@@ -1314,7 +1369,7 @@ public final class SpiderQueen implements Runnable {
}
private void resetDecodeIndex() {
synchronized (mDecodeRequestStack) {
synchronized (mDecodeRequestQueue) {
mDecodeIndexArray[mThreadIndex] = GalleryPageView.INVALID_INDEX;
}
}
@@ -1327,17 +1382,17 @@ public final class SpiderQueen implements Runnable {
while (!Thread.currentThread().isInterrupted()) {
int index;
synchronized (mDecodeRequestStack) {
if (mDecodeRequestStack.isEmpty()) {
synchronized (mDecodeRequestQueue) {
if (mDecodeRequestQueue.isEmpty()) {
try {
mDecodeRequestStack.wait();
mDecodeRequestQueue.wait();
} catch (InterruptedException e) {
// Interrupted
break;
}
continue;
}
index = mDecodeRequestStack.pop();
index = mDecodeRequestQueue.remove();
mDecodeIndexArray[mThreadIndex] = index;
}
@@ -1354,7 +1409,7 @@ public final class SpiderQueen implements Runnable {
// Can't find the file, it might be removed from cache,
// Reset it state and request it
updatePageState(index, STATE_NONE, null);
request(index, false, false);
request(index, false, false, false);
continue;
}
@@ -33,6 +33,7 @@ import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.UrlOpener;
import com.hippo.ehviewer.client.EhClient;
import com.hippo.ehviewer.client.EhRequest;
import com.hippo.ehviewer.client.data.GalleryDetail;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.dao.DownloadLabel;
import com.hippo.ehviewer.download.DownloadManager;
@@ -185,27 +186,31 @@ public final class CommonOperations {
public static void addToFavorites(final Activity activity, final GalleryInfo galleryInfo,
final EhClient.Callback<Void> listener) {
int slot = Settings.getDefaultFavSlot();
String[] items = new String[11];
items[0] = activity.getString(R.string.local_favorites);
String[] favCat = Settings.getFavCat();
System.arraycopy(favCat, 0, items, 1, 10);
if (slot >= -1 && slot <= 9) {
doAddToFavorites(activity, galleryInfo, slot, listener);
String newFavoriteName = slot >= 0 ? items[slot + 1] : null;
doAddToFavorites(activity, galleryInfo, slot, galleryInfo instanceof GalleryDetail
? new UpdateFavoriteNameCallback(listener, (GalleryDetail) galleryInfo, newFavoriteName)
: listener);
} else {
String[] items = new String[11];
items[0] = activity.getString(R.string.local_favorites);
String[] favCat = Settings.getFavCat();
System.arraycopy(favCat, 0, items, 1, 10);
new ListCheckBoxDialogBuilder(activity, items,
new ListCheckBoxDialogBuilder.OnItemClickListener() {
@Override
public void onItemClick(ListCheckBoxDialogBuilder builder, AlertDialog dialog, int position) {
int slot = position - 1;
doAddToFavorites(activity, galleryInfo, slot, listener);
if (builder.isChecked()) {
Settings.putDefaultFavSlot(slot);
} else {
Settings.putDefaultFavSlot(Settings.INVALID_DEFAULT_FAV_SLOT);
}
(builder, dialog, position) -> {
int slot1 = position - 1;
String newFavoriteName = (slot1 >= 0 && slot1 <= 9) ? items[slot1+1] : null;
doAddToFavorites(activity, galleryInfo, slot1, galleryInfo instanceof GalleryDetail
? new UpdateFavoriteNameCallback(listener, (GalleryDetail) galleryInfo, newFavoriteName)
: listener);
if (builder.isChecked()) {
Settings.putDefaultFavSlot(slot1);
} else {
Settings.putDefaultFavSlot(Settings.INVALID_DEFAULT_FAV_SLOT);
}
}, activity.getString(R.string.remember_favorite_collection), false)
.setTitle(R.string.add_favorites_dialog_title)
.setOnCancelListener(dialog -> listener.onCancel())
.show();
}
}
@@ -216,10 +221,42 @@ public final class CommonOperations {
EhRequest request = new EhRequest();
request.setMethod(EhClient.METHOD_ADD_FAVORITES);
request.setArgs(galleryInfo.gid, galleryInfo.token, -1, "");
request.setCallback(listener);
request.setCallback(galleryInfo instanceof GalleryDetail
? new UpdateFavoriteNameCallback(listener, (GalleryDetail) galleryInfo, null)
: listener);
client.execute(request);
}
private static class UpdateFavoriteNameCallback implements EhClient.Callback<Void> {
private final EhClient.Callback<Void> delegate;
private final GalleryDetail detail;
private final String newFavoriteName;
UpdateFavoriteNameCallback(EhClient.Callback<Void> delegate, GalleryDetail detail,
String newFavoriteName) {
this.delegate = delegate;
this.detail = detail;
this.newFavoriteName = newFavoriteName;
}
@Override
public void onSuccess(Void result) {
detail.favoriteName = newFavoriteName;
delegate.onSuccess(result);
}
@Override
public void onFailure(Exception e) {
delegate.onFailure(e);
}
@Override
public void onCancel() {
delegate.onCancel();
}
}
// TODO Add context if activity and context are different style
public static void startDownload(final MainActivity activity, final GalleryInfo galleryInfo, boolean forceDefault) {
final DownloadManager dm = EhApplication.getDownloadManager(activity);
@@ -25,12 +25,11 @@ import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.hippo.android.resource.AttrResources;
import com.hippo.ehviewer.R;
import com.hippo.ripple.Ripple;
import com.hippo.widget.DirExplorer;
import com.hippo.yorozuya.ViewUtils;
import java.io.File;
public class DirPickerActivity extends ToolbarActivity
@@ -70,7 +69,7 @@ public class DirPickerActivity extends ToolbarActivity
mDirExplorer.setCurrentFile(file);
mDirExplorer.setOnChangeDirListener(this);
Ripple.addRipple(mOk, false);
Ripple.addRipple(mOk, !AttrResources.getAttrBoolean(this, R.attr.isLightTheme));
mOk.setOnClickListener(this);
@@ -16,20 +16,29 @@
package com.hippo.ehviewer.ui;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import com.google.analytics.tracking.android.EasyTracker;
import com.hippo.content.ContextLocalWrapper;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.Settings;
import java.util.Locale;
public class EhActivity extends AppCompatActivity {
public abstract class EhActivity extends AppCompatActivity {
private boolean mTrackStarted;
@StyleRes
protected abstract int getThemeResId(int theme);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
setTheme(getThemeResId(Settings.getTheme()));
super.onCreate(savedInstanceState);
((EhApplication) getApplication()).registerActivity(this);
@@ -61,4 +70,37 @@ public class EhActivity extends AppCompatActivity {
mTrackStarted = false;
}
}
@Override
protected void onResume() {
super.onResume();
if(Settings.getEnabledSecurity()){
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
}else{
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
}
}
@Override
protected void attachBaseContext(Context newBase) {
Locale locale = null;
String language = Settings.getAppLanguage();
if (language != null && !language.equals("system")) {
String[] split = language.split("-");
if (split.length == 1) {
locale = new Locale(split[0]);
} else if (split.length == 2) {
locale = new Locale(split[0], split[1]);
} else if (split.length == 3) {
locale = new Locale(split[0], split[1], split[2]);
}
}
if (locale != null) {
newBase = ContextLocalWrapper.wrap(newBase, locale);
}
super.attachBaseContext(newBase);
}
}
@@ -16,20 +16,30 @@
package com.hippo.ehviewer.ui;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.view.WindowManager;
import com.google.analytics.tracking.android.EasyTracker;
import com.hippo.app.AppCompatPreferenceActivity;
import com.hippo.app.PrettyPreferenceActivity;
import com.hippo.content.ContextLocalWrapper;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.Settings;
import java.util.Locale;
public class EhPreferenceActivity extends AppCompatPreferenceActivity {
public abstract class EhPreferenceActivity extends PrettyPreferenceActivity {
private boolean mTrackStarted;
@StyleRes
protected abstract int getThemeResId(int theme);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
setTheme(getThemeResId(Settings.getTheme()));
super.onCreate(savedInstanceState);
((EhApplication) getApplication()).registerActivity(this);
@@ -61,4 +71,38 @@ public class EhPreferenceActivity extends AppCompatPreferenceActivity {
mTrackStarted = false;
}
}
@Override
protected void onResume() {
super.onResume();
if(Settings.getEnabledSecurity()){
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
}else{
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
}
}
@Override
protected void attachBaseContext(Context newBase) {
Locale locale = null;
String language = Settings.getAppLanguage();
if (language != null && !language.equals("system")) {
String[] split = language.split("-");
if (split.length == 1) {
locale = new Locale(split[0]);
} else if (split.length == 2) {
locale = new Locale(split[0], split[1]);
} else if (split.length == 3) {
locale = new Locale(split[0], split[1], split[2]);
}
}
if (locale == null) {
locale = Resources.getSystem().getConfiguration().locale;
}
newBase = ContextLocalWrapper.wrap(newBase, locale);
super.attachBaseContext(newBase);
}
}
@@ -25,7 +25,7 @@ import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.hippo.android.resource.AttrResources;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
@@ -61,6 +61,7 @@ public class ExcludedLanguagesActivity extends ToolbarActivity
};
private static final String[] LANGUAGES = {
EhConfig.JAPANESE_ORIGINAL,
EhConfig.JAPANESE_TRANSLATED,
EhConfig.JAPANESE_REWRITE,
EhConfig.ENGLISH_ORIGINAL,
@@ -163,11 +164,12 @@ public class ExcludedLanguagesActivity extends ToolbarActivity
mDeselectAll.setOnClickListener(this);
mInvertSelection.setOnClickListener(this);
Ripple.addRipple(mCancel, false);
Ripple.addRipple(mOk, false);
Ripple.addRipple(mSelectAll, false);
Ripple.addRipple(mDeselectAll, false);
Ripple.addRipple(mInvertSelection, false);
boolean isDarkTheme = !AttrResources.getAttrBoolean(this, R.attr.isLightTheme);
Ripple.addRipple(mCancel, isDarkTheme);
Ripple.addRipple(mOk, isDarkTheme);
Ripple.addRipple(mSelectAll, isDarkTheme);
Ripple.addRipple(mDeselectAll, isDarkTheme);
Ripple.addRipple(mInvertSelection, isDarkTheme);
}
private boolean isDecimal(String str) {
@@ -207,8 +209,8 @@ public class ExcludedLanguagesActivity extends ToolbarActivity
String pattern = LANGUAGES[j];
if (pattern.equals(language)) {
// Get it
int row = (j + 1) / 3;
int column = (j + 1) % 3;
int row = j / 3;
int column = j % 3;
mSelections[row][column] = true;
break;
}
@@ -282,22 +284,19 @@ public class ExcludedLanguagesActivity extends ToolbarActivity
finish();
} else if (v == mOk) {
StringBuilder sb = new StringBuilder();
int i = -1;
int i = 0;
boolean first = true;
for (boolean[] selections : mSelections) {
for (boolean b : selections) {
i++;
if (i == 0) {
continue;
}
if (b) {
if (!first) {
sb.append("x");
} else {
first = false;
}
sb.append(LANGUAGES[i - 1]);
sb.append(LANGUAGES[i]);
}
i++;
}
}
@@ -383,11 +382,6 @@ public class ExcludedLanguagesActivity extends ToolbarActivity
@Override
public void onBindViewHolder(LanguageHolder holder, int position) {
holder.language.setText(LANGUAGE_STR_IDS[position]);
if (position == 0) {
holder.original.setVisibility(View.INVISIBLE);
} else {
holder.original.setVisibility(View.VISIBLE);
}
boolean[] selections = mSelections[position];
holder.original.setChecked(selections[0]);
holder.translated.setChecked(selections[1]);
@@ -17,6 +17,7 @@
package com.hippo.ehviewer.ui;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
@@ -77,6 +78,7 @@ public class FilterActivity extends ToolbarActivity {
mRecyclerView.setClipChildren(false);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.hasFixedSize();
mRecyclerView.setItemAnimator(null);
updateView(false);
}
@@ -247,6 +249,8 @@ public class FilterActivity extends ToolbarActivity {
if (null != icon) {
icon.setOnClickListener(this);
}
// click on the filter text to enable/disable it
text.setOnClickListener(this);
}
@Override
@@ -257,7 +261,15 @@ public class FilterActivity extends ToolbarActivity {
}
Filter filter = mFilterList.get(position);
if (FilterList.MODE_HEADER != filter.mode) {
showDeleteFilterDialog(filter);
if (v instanceof ImageView) {
showDeleteFilterDialog(filter);
} else if (v instanceof TextView) {
mFilterList.trigger(filter);
//for updating delete line on filter text
mAdapter.notifyItemChanged(getAdapterPosition());
}
}
}
}
@@ -314,12 +326,18 @@ public class FilterActivity extends ToolbarActivity {
holder.text.setText(filter.text);
} else {
holder.text.setText(filter.text);
// add a delete line if the filter is disabled
if (!filter.enable) {
holder.text.setPaintFlags(holder.text.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
} else {
holder.text.setPaintFlags(holder.text.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
}
}
}
@Override
public int getItemCount() {
return null != mFilterList ? mFilterList.size(): 0;
return null != mFilterList ? mFilterList.size() : 0;
}
}
@@ -450,5 +468,9 @@ public class FilterActivity extends ToolbarActivity {
public void delete(Filter filter) {
mEhFilter.deleteFilter(filter);
}
public void trigger(Filter filter) {
mEhFilter.triggerFilter(filter);
}
}
}
@@ -20,11 +20,14 @@ import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
@@ -45,38 +48,41 @@ import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.hippo.android.resource.AttrResources;
import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.BuildConfig;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.gallery.DirGalleryProvider;
import com.hippo.ehviewer.gallery.EhGalleryProvider;
import com.hippo.ehviewer.gallery.GalleryProvider;
import com.hippo.ehviewer.gallery.GalleryProviderListener;
import com.hippo.ehviewer.gallery.GalleryProvider2;
import com.hippo.ehviewer.gallery.ZipGalleryProvider;
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.ehviewer.gallery.gl.GalleryView;
import com.hippo.ehviewer.gallery.gl.ImageView;
import com.hippo.ehviewer.widget.GalleryGuideView;
import com.hippo.ehviewer.widget.ReversibleSeekBar;
import com.hippo.gl.glrenderer.ImageTexture;
import com.hippo.gl.glrenderer.ImageWrapper;
import com.hippo.gl.view.GLRootView;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.glgallery.GalleryView;
import com.hippo.glgallery.SimpleAdapter;
import com.hippo.glview.view.GLRootView;
import com.hippo.unifile.UniFile;
import com.hippo.util.SystemUiHelper;
import com.hippo.widget.ColorView;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.ConcurrentPool;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.SimpleAnimatorListener;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.ViewUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class GalleryActivity extends EhActivity
implements GalleryProviderListener, SeekBar.OnSeekBarChangeListener,
public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChangeListener,
GalleryView.Listener {
public static final String ACTION_DIR = "dir";
@@ -93,21 +99,23 @@ public class GalleryActivity extends EhActivity
private static final long SLIDER_ANIMATION_DURING = 150;
private static final long HIDE_SLIDER_DELAY = 3000;
private static final int WRITE_REQUEST_CODE = 43;
private String mAction;
private String mFilename;
private Uri mUri;
private GalleryInfo mGalleryInfo;
private int mPage;
private String mCacheFileName;
@Nullable
private GLRootView mGLRootView;
@Nullable
private GalleryView mGalleryView;
@Nullable
private ImageTexture.Uploader mUploader;
private GalleryProvider2 mGalleryProvider;
@Nullable
private GalleryProvider mGalleryProvider;
private GalleryAdapter mGalleryAdapter;
@Nullable
private SystemUiHelper mSystemUiHelper;
@@ -173,6 +181,19 @@ public class GalleryActivity extends EhActivity
}
};
@Override
protected int getThemeResId(int theme) {
switch (theme) {
case Settings.THEME_LIGHT:
default:
return R.style.AppTheme_Gallery;
case Settings.THEME_DARK:
return R.style.AppTheme_Gallery_Dark;
case Settings.THEME_BLACK:
return R.style.AppTheme_Gallery_Black;
}
}
private void buildProvider() {
if (mGalleryProvider != null) {
return;
@@ -236,6 +257,7 @@ public class GalleryActivity extends EhActivity
}
@Override
@SuppressWarnings({"deprecation", "WrongConstant"})
protected void onCreate(@Nullable Bundle savedInstanceState) {
if (Settings.getReadingFullscreen() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window w = getWindow();
@@ -257,14 +279,9 @@ public class GalleryActivity extends EhActivity
finish();
return;
}
mGalleryProvider.setGalleryProviderListener(this);
mGalleryProvider.start();
setContentView(R.layout.activity_gallery);
mGLRootView = (GLRootView) ViewUtils.$$(this, R.id.gl_root_view);
mGalleryProvider.setGLRoot(mGLRootView);
mUploader = new ImageTexture.Uploader(mGLRootView);
// Get start page
int startPage;
if (savedInstanceState == null) {
startPage = mPage >= 0 ? mPage : mGalleryProvider.getStartPage();
@@ -272,10 +289,36 @@ public class GalleryActivity extends EhActivity
startPage = mCurrentIndex;
}
mGalleryView = new GalleryView(this, new GalleryAdapter(), this,
Settings.getReadingDirection(), Settings.getPageScaling(),
Settings.getStartPosition(), startPage);
setContentView(R.layout.activity_gallery);
mGLRootView = (GLRootView) ViewUtils.$$(this, R.id.gl_root_view);
mGalleryAdapter = new GalleryAdapter(mGLRootView, mGalleryProvider);
Resources resources = getResources();
mGalleryView = new GalleryView.Builder(this, mGalleryAdapter)
.setListener(this)
.setLayoutMode(Settings.getReadingDirection())
.setScaleMode(Settings.getPageScaling())
.setStartPosition(Settings.getStartPosition())
.setStartPage(startPage)
.setBackgroundColor(AttrResources.getAttrColor(this, android.R.attr.colorBackground))
.setEdgeColor(AttrResources.getAttrColor(this, R.attr.colorEdgeEffect) & 0xffffff | 0x33000000)
.setPagerInterval(Settings.getShowPageInterval() ? resources.getDimensionPixelOffset(R.dimen.gallery_pager_interval) : 0)
.setScrollInterval(Settings.getShowPageInterval() ? resources.getDimensionPixelOffset(R.dimen.gallery_scroll_interval) : 0)
.setPageMinHeight(resources.getDimensionPixelOffset(R.dimen.gallery_page_min_height))
.setPageInfoInterval(resources.getDimensionPixelOffset(R.dimen.gallery_page_info_interval))
.setProgressColor(ResourcesUtils.getAttrColor(this, R.attr.colorPrimary))
.setProgressSize(resources.getDimensionPixelOffset(R.dimen.gallery_progress_size))
.setPageTextColor(AttrResources.getAttrColor(this, android.R.attr.textColorSecondary))
.setPageTextSize(resources.getDimensionPixelOffset(R.dimen.gallery_page_text_size))
.setPageTextTypeface(Typeface.DEFAULT)
.setErrorTextColor(resources.getColor(R.color.red_500))
.setErrorTextSize(resources.getDimensionPixelOffset(R.dimen.gallery_error_text_size))
.setDefaultErrorString(resources.getString(R.string.error_unknown))
.setEmptyString(resources.getString(R.string.error_empty))
.build();
mGLRootView.setContentPane(mGalleryView);
mGalleryProvider.setListener(mGalleryAdapter);
mGalleryProvider.setGLRoot(mGLRootView);
// System UI helper
if (Settings.getReadingFullscreen()) {
@@ -347,12 +390,12 @@ public class GalleryActivity extends EhActivity
super.onDestroy();
mGLRootView = null;
mGalleryView = null;
if (mUploader != null) {
mUploader.clear();
mUploader = null;
if (mGalleryAdapter != null) {
mGalleryAdapter.clearUploader();
mGalleryAdapter = null;
}
if (mGalleryProvider != null) {
mGalleryProvider.setGalleryProviderListener(null);
mGalleryProvider.setListener(null);
mGalleryProvider.stop();
mGalleryProvider = null;
}
@@ -409,14 +452,14 @@ public class GalleryActivity extends EhActivity
// Check volume
if (Settings.getVolumePage()) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
mGalleryView.pageRight();
} else {
mGalleryView.pageLeft();
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
mGalleryView.pageLeft();
} else {
mGalleryView.pageRight();
@@ -429,7 +472,7 @@ public class GalleryActivity extends EhActivity
switch (keyCode) {
case KeyEvent.KEYCODE_PAGE_UP:
case KeyEvent.KEYCODE_DPAD_UP:
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
mGalleryView.pageRight();
} else {
mGalleryView.pageLeft();
@@ -440,7 +483,7 @@ public class GalleryActivity extends EhActivity
return true;
case KeyEvent.KEYCODE_PAGE_DOWN:
case KeyEvent.KEYCODE_DPAD_DOWN:
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
mGalleryView.pageLeft();
} else {
mGalleryView.pageRight();
@@ -513,7 +556,7 @@ public class GalleryActivity extends EhActivity
TextView start;
TextView end;
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
start = mRightText;
end = mLeftText;
mSeekBar.setReverse(true);
@@ -528,96 +571,11 @@ public class GalleryActivity extends EhActivity
mSeekBar.setProgress(mCurrentIndex);
}
@Override
public void onDataChanged() {
if (mGalleryView != null) {
mGalleryView.onDataChanged();
}
if (mGalleryProvider != null) {
int size = mGalleryProvider.size();
NotifyTask task = mNotifyTaskPool.pop();
if (task == null) {
task = new NotifyTask();
}
task.setData(NotifyTask.KEY_SIZE, size);
SimpleHandler.getInstance().post(task);
}
}
@Override
public void onPageWait(int index) {
GalleryPageView page = findPageByIndex(index);
if (page != null) {
page.showInfo();
page.setImage(null);
page.setPage(index + 1);
page.setProgress(GalleryPageView.PROGRESS_INDETERMINATE);
page.setError(null, null);
}
}
@Override
public void onPagePercent(int index, float percent) {
GalleryPageView page = findPageByIndex(index);
if (page != null) {
page.showInfo();
page.setImage(null);
page.setPage(index + 1);
page.setProgress(percent);
page.setError(null, null);
}
}
@Override
public void onPageSucceed(int index, ImageWrapper image) {
GalleryPageView page = findPageByIndex(index);
if (page != null) {
if (image.obtain()) {
ImageTexture imageTexture = new ImageTexture(image);
if (mUploader != null) {
mUploader.addTexture(imageTexture);
}
page.showImage();
page.setImage(imageTexture);
page.setPage(index + 1);
page.setProgress(GalleryPageView.PROGRESS_GONE);
page.setError(null, null);
} else {
// The image is recycled, request again.
// TODO request loop ?
if (mGalleryProvider != null) {
mGalleryProvider.request(index);
}
}
}
}
@Override
public void onPageFailed(int index, String error) {
GalleryPageView page = findPageByIndex(index);
if (page != null && mGalleryView != null) {
page.showInfo();
page.setImage(null);
page.setPage(index + 1);
page.setProgress(GalleryPageView.PROGRESS_GONE);
page.setError(error, mGalleryView);
}
}
@Override
public void onDataChanged(int index) {
GalleryPageView page = findPageByIndex(index);
if (page != null && mGalleryProvider != null) {
mGalleryProvider.request(index);
}
}
@Override
@SuppressLint("SetTextI18n")
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
TextView start;
if (mLayoutMode == GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT) {
if (mLayoutMode == GalleryView.LAYOUT_RIGHT_TO_LEFT) {
start = mRightText;
} else {
start = mLeftText;
@@ -675,6 +633,16 @@ public class GalleryActivity extends EhActivity
SimpleHandler.getInstance().post(task);
}
@Override
public void onTapErrorText(int index) {
NotifyTask task = mNotifyTaskPool.pop();
if (task == null) {
task = new NotifyTask();
}
task.setData(NotifyTask.KEY_TAP_ERROR_TEXT, index);
SimpleHandler.getInstance().post(task);
}
@Override
public void onLongPressPage(int index) {
NotifyTask task = mNotifyTaskPool.pop();
@@ -765,6 +733,7 @@ public class GalleryActivity extends EhActivity
private final SwitchCompat mShowClock;
private final SwitchCompat mShowProgress;
private final SwitchCompat mShowBattery;
private final SwitchCompat mShowPageInterval;
private final SwitchCompat mVolumePage;
private final SwitchCompat mReadingFullscreen;
private final SwitchCompat mCustomScreenLightness;
@@ -781,6 +750,7 @@ public class GalleryActivity extends EhActivity
mShowClock = (SwitchCompat) mView.findViewById(R.id.show_clock);
mShowProgress = (SwitchCompat) mView.findViewById(R.id.show_progress);
mShowBattery = (SwitchCompat) mView.findViewById(R.id.show_battery);
mShowPageInterval = (SwitchCompat) mView.findViewById(R.id.show_page_interval);
mVolumePage = (SwitchCompat) mView.findViewById(R.id.volume_page);
mReadingFullscreen = (SwitchCompat) mView.findViewById(R.id.reading_fullscreen);
mCustomScreenLightness = (SwitchCompat) mView.findViewById(R.id.custom_screen_lightness);
@@ -794,6 +764,7 @@ public class GalleryActivity extends EhActivity
mShowClock.setChecked(Settings.getShowClock());
mShowProgress.setChecked(Settings.getShowProgress());
mShowBattery.setChecked(Settings.getShowBattery());
mShowPageInterval.setChecked(Settings.getShowPageInterval());
mVolumePage.setChecked(Settings.getVolumePage());
mReadingFullscreen.setChecked(Settings.getReadingFullscreen());
mCustomScreenLightness.setChecked(Settings.getCustomScreenLightness());
@@ -816,12 +787,13 @@ public class GalleryActivity extends EhActivity
public void onClick(DialogInterface dialog, int which) {
int screenRotation = mScreenRotation.getSelectedItemPosition();
int layoutMode = GalleryView.sanitizeLayoutMode(mReadingDirection.getSelectedItemPosition());
int scaleMode = ImageView.sanitizeScaleMode(mScaleMode.getSelectedItemPosition());
int startPosition = ImageView.sanitizeStartPosition(mStartPosition.getSelectedItemPosition());
int scaleMode = GalleryView.sanitizeScaleMode(mScaleMode.getSelectedItemPosition());
int startPosition = GalleryView.sanitizeStartPosition(mStartPosition.getSelectedItemPosition());
boolean keepScreenOn = mKeepScreenOn.isChecked();
boolean showClock = mShowClock.isChecked();
boolean showProgress = mShowProgress.isChecked();
boolean showBattery = mShowBattery.isChecked();
boolean showPageInterval = mShowPageInterval.isChecked();
boolean volumePage = mVolumePage.isChecked();
boolean readingFullscreen = mReadingFullscreen.isChecked();
boolean customScreenLightness = mCustomScreenLightness.isChecked();
@@ -837,6 +809,7 @@ public class GalleryActivity extends EhActivity
Settings.putShowClock(showClock);
Settings.putShowProgress(showProgress);
Settings.putShowBattery(showBattery);
Settings.putShowPageInterval(showPageInterval);
Settings.putVolumePage(volumePage);
Settings.putReadingFullscreen(readingFullscreen);
Settings.putCustomScreenLightness(customScreenLightness);
@@ -875,6 +848,8 @@ public class GalleryActivity extends EhActivity
if (mBattery != null) {
mBattery.setVisibility(showBattery ? View.VISIBLE : View.GONE);
}
mGalleryView.setPagerInterval(showPageInterval ? getResources().getDimensionPixelOffset(R.dimen.gallery_pager_interval) : 0);
mGalleryView.setScrollInterval(showPageInterval ? getResources().getDimensionPixelOffset(R.dimen.gallery_scroll_interval) : 0);
setScreenLightness(customScreenLightness, screenLightness);
// Update slider
@@ -898,18 +873,29 @@ public class GalleryActivity extends EhActivity
return;
}
UniFile file;
if (null == (file = mGalleryProvider.save(page, UniFile.fromFile(dir), Long.toString(System.currentTimeMillis())))) {
if (null == (file = mGalleryProvider.save(page, UniFile.fromFile(dir), mGalleryProvider.getImageFilename(page)))) {
Toast.makeText(this, R.string.error_cant_save_image, Toast.LENGTH_SHORT).show();
return;
}
String filename = file.getName();
if (filename == null) {
Toast.makeText(this, R.string.error_cant_save_image, Toast.LENGTH_SHORT).show();
return;
}
// TODO Create ContentProvider for some app are not grand storage write permission
Uri uri = file.getUri();
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(uri.toString()));
MimeTypeMap.getFileExtensionFromUrl(filename));
if (TextUtils.isEmpty(mimeType)) {
mimeType = "image/jpeg";
}
Uri uri = new Uri.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority(BuildConfig.FILE_PROVIDER_AUTHORITY)
.appendPath("temp")
.appendPath(filename)
.build();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
@@ -934,34 +920,112 @@ public class GalleryActivity extends EhActivity
}
Toast.makeText(this, getString(R.string.image_saved, file.getUri()), Toast.LENGTH_SHORT).show();
// Sync media store
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, file.getUri()));
}
private void saveImageTo(int page) {
if (null == mGalleryProvider) {
return;
}
File dir = getCacheDir();
UniFile file;
if (null == (file = mGalleryProvider.save(page, UniFile.fromFile(dir), mGalleryProvider.getImageFilename(page)))) {
Toast.makeText(this, R.string.error_cant_save_image, Toast.LENGTH_SHORT).show();
return;
}
String filename = file.getName();
if (filename == null) {
Toast.makeText(this, R.string.error_cant_save_image, Toast.LENGTH_SHORT).show();
return;
}
mCacheFileName = filename;
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_TITLE, filename);
startActivityForResult(intent, WRITE_REQUEST_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (requestCode == WRITE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if (resultData != null){
Uri uri = resultData.getData();
String filepath = getCacheDir() + "/" + mCacheFileName;
File cachefile = new File(filepath);
InputStream is = null;
OutputStream os = null;
ContentResolver resolver = getContentResolver();
try {
is = new FileInputStream(cachefile);
os = resolver.openOutputStream(uri);
IOUtils.copy(is, os);
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
cachefile.delete();
Toast.makeText(this, getString(R.string.image_saved, uri.getPath()), Toast.LENGTH_SHORT).show();
// Sync media store
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
}
}
}
private void showPageDialog(final int page) {
Resources resources = GalleryActivity.this.getResources();
new AlertDialog.Builder(GalleryActivity.this)
.setTitle(resources.getString(R.string.page_menu_title, page + 1))
.setItems(R.array.page_menu_entries, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mGalleryProvider == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(GalleryActivity.this);
builder.setTitle(resources.getString(R.string.page_menu_title, page + 1));
switch (which) {
case 0: // Refresh
mGalleryProvider.forceRequest(page);
break;
case 1: // Share
shareImage(page);
break;
case 2: // Save
saveImage(page);
break;
case 3: // Add a bookmark
break;
}
}
}).show();
final CharSequence[] items;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
items = new CharSequence[]{
getString(R.string.page_menu_refresh),
getString(R.string.page_menu_share),
getString(R.string.page_menu_save),
getString(R.string.page_menu_save_to)};
}else {
items = new CharSequence[]{
getString(R.string.page_menu_refresh),
getString(R.string.page_menu_share),
getString(R.string.page_menu_save)};
}
pageDialogListener(builder, items, page);
builder.show();
}
private void pageDialogListener(AlertDialog.Builder builder, CharSequence[] items, int page){
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mGalleryProvider == null) {
return;
}
switch (which) {
case 0: // Refresh
mGalleryProvider.forceRequest(page);
break;
case 1: // Share
shareImage(page);
break;
case 2: // Save
saveImage(page);
break;
case 3: // Save to
saveImageTo(page);
break;
}
}
});
}
private class NotifyTask implements Runnable {
@@ -971,7 +1035,8 @@ public class GalleryActivity extends EhActivity
public static final int KEY_CURRENT_INDEX = 2;
public static final int KEY_TAP_SLIDER_AREA = 3;
public static final int KEY_TAP_MENU_AREA = 4;
public static final int KEY_LONG_PRESS_PAGE = 5;
public static final int KEY_TAP_ERROR_TEXT = 5;
public static final int KEY_LONG_PRESS_PAGE = 6;
private int mKey;
private int mValue;
@@ -1004,6 +1069,12 @@ public class GalleryActivity extends EhActivity
}
}
private void onTapErrorText(int index) {
if (mGalleryProvider != null) {
mGalleryProvider.forceRequest(index);
}
}
private void onLongPressPage(final int index) {
showPageDialog(index);
}
@@ -1031,6 +1102,9 @@ public class GalleryActivity extends EhActivity
case KEY_TAP_SLIDER_AREA:
onTapSliderArea();
break;
case KEY_TAP_ERROR_TEXT:
onTapErrorText(mValue);
break;
case KEY_LONG_PRESS_PAGE:
onLongPressPage(mValue);
break;
@@ -1039,46 +1113,25 @@ public class GalleryActivity extends EhActivity
}
}
private class GalleryAdapter extends GalleryView.Adapter {
private class GalleryAdapter extends SimpleAdapter {
@Override
public String getError() {
if (mGalleryProvider == null) {
return getString(R.string.error_no_provider);
} else if (mGalleryProvider.size() <= GalleryProvider.STATE_ERROR) {
return mGalleryProvider.getError();
}
return null;
public GalleryAdapter(@NonNull GLRootView glRootView, @NonNull GalleryProvider provider) {
super(glRootView, provider);
}
@Override
public int size() {
if (mGalleryProvider == null) {
return GalleryProvider.STATE_ERROR;
} else {
return mGalleryProvider.size();
}
}
public void onDataChanged() {
super.onDataChanged();
@Override
public void onBind(GalleryPageView view, int index) {
if (mGalleryProvider != null && mGalleryView != null) {
mGalleryProvider.request(index);
view.showInfo();
view.setImage(null);
view.setPage(index + 1);
view.setProgress(GalleryPageView.PROGRESS_INDETERMINATE);
view.setError(null, null);
}
}
@Override
public void onUnbind(GalleryPageView view, int index) {
if (mGalleryProvider != null) {
mGalleryProvider.cancelRequest(index);
int size = mGalleryProvider.size();
NotifyTask task = mNotifyTaskPool.pop();
if (task == null) {
task = new NotifyTask();
}
task.setData(NotifyTask.KEY_SIZE, size);
SimpleHandler.getInstance().post(task);
}
view.setImage(null);
view.setError(null, null);
}
}
}
@@ -0,0 +1,273 @@
/*
* Copyright 2018 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.ui;
/*
* Created by Hippo on 2018/3/23.
*/
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.hippo.android.resource.AttrResources;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.LinearDividerItemDecoration;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.Hosts;
import com.hippo.ehviewer.R;
import com.hippo.ripple.Ripple;
import com.hippo.yorozuya.LayoutUtils;
import java.util.List;
import java.util.Locale;
public class HostsActivity extends ToolbarActivity
implements EasyRecyclerView.OnItemClickListener, View.OnClickListener {
private static final String DIALOG_TAG_ADD_HOST = AddHostDialogFragment.class.getName();
private static final String DIALOG_TAG_EDIT_HOST = EditHostDialogFragment.class.getName();
private static final String KEY_HOST = "com.hippo.ehviewer.ui.HostsActivity.HOST";
private static final String KEY_IP = "com.hippo.ehviewer.ui.HostsActivity.IP";
private Hosts hosts;
private List<Pair<String, String>> data;
private EasyRecyclerView recyclerView;
private View tip;
private HostsAdapter adapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
hosts = EhApplication.getHosts(this);
data = hosts.getAll();
setContentView(R.layout.activity_hosts);
setNavigationIcon(R.drawable.v_arrow_left_dark_x24);
recyclerView = findViewById(R.id.recycler_view);
tip = findViewById(R.id.tip);
FloatingActionButton fab = findViewById(R.id.fab);
adapter = new HostsAdapter();
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
LinearDividerItemDecoration decoration = new LinearDividerItemDecoration(
LinearDividerItemDecoration.VERTICAL,
AttrResources.getAttrColor(this, R.attr.dividerColor),
LayoutUtils.dp2pix(this, 1));
decoration.setShowLastDivider(true);
recyclerView.addItemDecoration(decoration);
recyclerView.setSelector(Ripple.generateRippleDrawable(this, !AttrResources.getAttrBoolean(this, R.attr.isLightTheme)));
recyclerView.setHasFixedSize(true);
recyclerView.setOnItemClickListener(this);
recyclerView.setPadding(
recyclerView.getPaddingLeft(),
recyclerView.getPaddingTop(),
recyclerView.getPaddingRight(),
recyclerView.getPaddingBottom() + getResources().getDimensionPixelOffset(R.dimen.gallery_padding_bottom_fab));
fab.setOnClickListener(this);
recyclerView.setVisibility(data.isEmpty() ? View.GONE : View.VISIBLE);
tip.setVisibility(data.isEmpty() ? View.VISIBLE : View.GONE);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onItemClick(EasyRecyclerView easyRecyclerView, View view, int position, long id) {
Pair<String, String> pair = data.get(position);
Bundle args = new Bundle();
args.putString(KEY_HOST, pair.first);
args.putString(KEY_IP, pair.second);
DialogFragment fragment = new EditHostDialogFragment();
fragment.setArguments(args);
fragment.show(getSupportFragmentManager(), DIALOG_TAG_EDIT_HOST);
return true;
}
@Override
public void onClick(View v) {
new AddHostDialogFragment().show(getSupportFragmentManager(), DIALOG_TAG_ADD_HOST);
}
private void notifyHostsChanges() {
data = hosts.getAll();
recyclerView.setVisibility(data.isEmpty() ? View.GONE : View.VISIBLE);
tip.setVisibility(data.isEmpty() ? View.VISIBLE : View.GONE);
adapter.notifyDataSetChanged();
}
private class HostsHolder extends RecyclerView.ViewHolder {
public final TextView host;
public final TextView ip;
public HostsHolder(View itemView) {
super(itemView);
host = itemView.findViewById(R.id.host);
ip = itemView.findViewById(R.id.ip);
}
}
private class HostsAdapter extends RecyclerView.Adapter<HostsHolder> {
private final LayoutInflater inflater = getLayoutInflater();
@NonNull
@Override
public HostsHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new HostsHolder(inflater.inflate(R.layout.item_hosts, parent, false));
}
@Override
public void onBindViewHolder(@NonNull HostsHolder holder, int position) {
Pair<String, String> pair = data.get(position);
holder.host.setText(pair.first);
holder.ip.setText(pair.second);
}
@Override
public int getItemCount() {
return data.size();
}
}
public abstract static class HostDialogFragment extends DialogFragment {
private TextView host;
private TextView ip;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_hosts, null, false);
host = view.findViewById(R.id.host);
ip = view.findViewById(R.id.ip);
Bundle arguments = getArguments();
if (savedInstanceState == null && arguments != null) {
host.setText(arguments.getString(KEY_HOST));
ip.setText(arguments.getString(KEY_IP));
}
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()).setView(view);
onCreateDialogBuilder(builder);
AlertDialog dialog = builder.create();
dialog.setOnShowListener(d -> onCreateDialog((AlertDialog) d));
return dialog;
}
protected abstract void onCreateDialogBuilder(AlertDialog.Builder builder);
protected abstract void onCreateDialog(AlertDialog dialog);
protected void put(AlertDialog dialog) {
TextView host = dialog.findViewById(R.id.host);
TextView ip = dialog.findViewById(R.id.ip);
String hostString = host.getText().toString().trim().toLowerCase(Locale.US);
String ipString = ip.getText().toString().trim();
if (!Hosts.isValidHost(hostString)) {
TextInputLayout hostInputLayout = dialog.findViewById(R.id.host_input_layout);
hostInputLayout.setError(getContext().getString(R.string.invalid_host));
return;
}
if (!Hosts.isValidIp(ipString)) {
TextInputLayout ipInputLayout = dialog.findViewById(R.id.ip_input_layout);
ipInputLayout.setError(getContext().getString(R.string.invalid_ip));
return;
}
HostsActivity activity = (HostsActivity) dialog.getOwnerActivity();
activity.hosts.put(hostString, ipString);
activity.notifyHostsChanges();
dialog.dismiss();
}
protected void delete(AlertDialog dialog) {
TextView host = dialog.findViewById(R.id.host);
String hostString = host.getText().toString().trim().toLowerCase(Locale.US);
HostsActivity activity = (HostsActivity) dialog.getOwnerActivity();
activity.hosts.delete(hostString);
activity.notifyHostsChanges();
dialog.dismiss();
}
}
public static class AddHostDialogFragment extends HostDialogFragment {
@Override
protected void onCreateDialogBuilder(AlertDialog.Builder builder) {
builder.setTitle(R.string.add_host);
builder.setPositiveButton(R.string.add_host_add, null);
}
@Override
protected void onCreateDialog(AlertDialog dialog) {
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(v -> put(dialog));
}
}
public static class EditHostDialogFragment extends HostDialogFragment {
@Override
protected void onCreateDialogBuilder(AlertDialog.Builder builder) {
builder.setTitle(R.string.edit_host);
builder.setPositiveButton(R.string.edit_host_confirm, null);
builder.setNegativeButton(R.string.edit_host_delete, null);
}
@Override
protected void onCreateDialog(AlertDialog dialog) {
dialog.findViewById(R.id.host_input_layout).setEnabled(false);
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(v -> put(dialog));
dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener(v -> delete(dialog));
}
}
}
@@ -17,6 +17,9 @@
package com.hippo.ehviewer.ui;
import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
@@ -33,19 +36,19 @@ import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hippo.drawerlayout.DrawerLayout;
import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.Crash;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUrlOpener;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.ListUrlBuilder;
@@ -67,6 +70,7 @@ import com.hippo.ehviewer.ui.scene.QuickSearchScene;
import com.hippo.ehviewer.ui.scene.SecurityScene;
import com.hippo.ehviewer.ui.scene.SelectSiteScene;
import com.hippo.ehviewer.ui.scene.SignInScene;
import com.hippo.ehviewer.ui.scene.SolidScene;
import com.hippo.ehviewer.ui.scene.WarningScene;
import com.hippo.ehviewer.ui.scene.WebViewSignInScene;
import com.hippo.ehviewer.widget.EhDrawerLayout;
@@ -81,8 +85,8 @@ import com.hippo.util.PermissionRequester;
import com.hippo.widget.LoadImageView;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.ViewUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -91,23 +95,12 @@ import java.io.OutputStream;
public final class MainActivity extends StageActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
private static final int REQUEST_CODE_SETTINGS = 0;
private static final String KEY_NAV_CHECKED_ITEM = "nav_checked_item";
public static final int CHECK_STEP_SECURITY = 0;
public static final int CHECK_STEP_WARNING = 1;
public static final int CHECK_STEP_ANALYTICS = 2;
public static final int CHECK_STEP_CRASH = 3;
public static final int CHECK_STEP_SIGN_IN = 4;
public static final int CHECK_STEP_SELECT_SITE = 5;
public static final String KEY_TARGET_SCENE = "target_scene";
public static final String KEY_TARGET_ARGS = "target_args";
private static final String KEY_CLIP_TEXT_HASH_CODE = "clip_text_hash_code";
/*---------------
Whole life cycle
@@ -125,6 +118,8 @@ public final class MainActivity extends StageActivity
private int mNavCheckedItem = 0;
private int mClipTextHashCode = 0;
static {
registerLaunchMode(SecurityScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
registerLaunchMode(WarningScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
@@ -147,58 +142,16 @@ public final class MainActivity extends StageActivity
registerLaunchMode(ProgressScene.class, SceneFragment.LAUNCH_MODE_STANDARD);
}
public void startSceneForCheckStep(int checkStep, Bundle args) {
switch (checkStep) {
case CHECK_STEP_SECURITY:
if (Settings.getShowWarning()) {
startScene(new Announcer(WarningScene.class).setArgs(args));
break;
}
case CHECK_STEP_WARNING:
if (Settings.getAskAnalytics()) {
startScene(new Announcer(AnalyticsScene.class).setArgs(args));
break;
}
case CHECK_STEP_ANALYTICS:
if (Crash.hasCrashFile()) {
startScene(new Announcer(CrashScene.class).setArgs(args));
break;
}
case CHECK_STEP_CRASH:
if (EhUtils.needSignedIn(this)) {
startScene(new Announcer(SignInScene.class).setArgs(args));
break;
}
case CHECK_STEP_SIGN_IN:
if (Settings.getSelectSite()) {
startScene(new Announcer(SelectSiteScene.class).setArgs(args));
break;
}
case CHECK_STEP_SELECT_SITE:
String targetScene = null;
Bundle targetArgs = null;
if (null != args) {
targetScene = args.getString(KEY_TARGET_SCENE);
targetArgs = args.getBundle(KEY_TARGET_ARGS);
}
Class<?> clazz = null;
if (targetScene != null) {
try {
clazz = Class.forName(targetScene);
} catch (ClassNotFoundException e) {
Log.e(TAG, "Can't find class with name: " + targetScene);
}
}
if (clazz != null) {
startScene(new Announcer(clazz).setArgs(targetArgs));
} else {
Bundle newArgs = new Bundle();
newArgs.putString(GalleryListScene.KEY_ACTION, GalleryListScene.ACTION_HOMEPAGE);
startScene(new Announcer(GalleryListScene.class).setArgs(newArgs));
}
break;
@Override
protected int getThemeResId(int theme) {
switch (theme) {
case Settings.THEME_LIGHT:
default:
return R.style.AppTheme_Main;
case Settings.THEME_DARK:
return R.style.AppTheme_Main_Dark;
case Settings.THEME_BLACK:
return R.style.AppTheme_Main_Black;
}
}
@@ -234,33 +187,33 @@ public final class MainActivity extends StageActivity
if (0 == getSceneCount()) {
if (!TextUtils.isEmpty(Settings.getSecurity())) {
Bundle newArgs = new Bundle();
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(SecurityScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(SecurityScene.KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(SecurityScene.class).setArgs(newArgs);
} else if (Settings.getShowWarning()) {
Bundle newArgs = new Bundle();
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(WarningScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(WarningScene.KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(WarningScene.class).setArgs(newArgs);
} else if (Settings.getAskAnalytics()) {
Bundle newArgs = new Bundle();
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(AnalyticsScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(AnalyticsScene.KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(AnalyticsScene.class).setArgs(newArgs);
} else if (Crash.hasCrashFile()) {
Bundle newArgs = new Bundle();
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(CrashScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(CrashScene.KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(CrashScene.class).setArgs(newArgs);
} else if (EhUtils.needSignedIn(this)) {
Bundle newArgs = new Bundle();
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(SignInScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(SignInScene.KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(SignInScene.class).setArgs(newArgs);
} else if (Settings.getSelectSite()) {
Bundle newArgs = new Bundle();
newArgs.putString(KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(KEY_TARGET_ARGS, announcer.getArgs());
newArgs.putString(SelectSiteScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
newArgs.putBundle(SelectSiteScene.KEY_TARGET_ARGS, announcer.getArgs());
return new Announcer(SelectSiteScene.class).setArgs(newArgs);
}
}
@@ -341,6 +294,12 @@ public final class MainActivity extends StageActivity
@Override
protected void onUnrecognizedIntent(@Nullable Intent intent) {
Class<?> clazz = getTopSceneClass();
if (clazz != null && SolidScene.class.isAssignableFrom(clazz)) {
// TODO the intent lost
return;
}
if (!handleIntent(intent)) {
boolean handleUrl = false;
if (intent != null && Intent.ACTION_VIEW.equals(intent.getAction())) {
@@ -392,7 +351,9 @@ public final class MainActivity extends StageActivity
if (savedInstanceState == null) {
onInit();
CommonOperations.checkUpdate(this, false);
if (Settings.getAutoCheckUpdateEnable()) {
CommonOperations.checkUpdate(this, false);
}
checkDownloadLocation();
if (Settings.getCellularNetworkWarning()) {
checkCellularNetwork();
@@ -425,16 +386,20 @@ public final class MainActivity extends StageActivity
// Check permission
PermissionRequester.request(this, Manifest.permission.WRITE_EXTERNAL_STORAGE,
getString(R.string.write_rationale), PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
mClipTextHashCode = Settings.getClipboardTextHashCode();
}
private void onRestore(Bundle savedInstanceState) {
mNavCheckedItem = savedInstanceState.getInt(KEY_NAV_CHECKED_ITEM);
mClipTextHashCode = savedInstanceState.getInt(KEY_CLIP_TEXT_HASH_CODE);
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putInt(KEY_NAV_CHECKED_ITEM, mNavCheckedItem);
outState.putInt(KEY_CLIP_TEXT_HASH_CODE, mClipTextHashCode);
}
@Override
@@ -453,6 +418,69 @@ public final class MainActivity extends StageActivity
super.onResume();
setNavCheckedItem(mNavCheckedItem);
checkClipboardUrl();
}
@Override
protected void onTransactScene() {
super.onTransactScene();
checkClipboardUrl();
}
private void checkClipboardUrl() {
SimpleHandler.getInstance().postDelayed(() -> {
if (!isSolid()) {
checkClipboardUrlInternal();
}
}, 300);
}
private boolean isSolid() {
Class<?> topClass = getTopSceneClass();
return topClass == null || SolidScene.class.isAssignableFrom(topClass);
}
private String getTextFromClipboard() {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard != null) {
ClipData clip = clipboard.getPrimaryClip();
if (clip != null && clip.getItemCount() > 0 && clip.getItemAt(0).getText() != null) {
return clip.getItemAt(0).getText().toString();
}
}
return null;
}
private void checkClipboardUrlInternal() {
String text = getTextFromClipboard();
int hashCode = text != null ? text.hashCode() : 0;
if (text != null && hashCode != 0 && mClipTextHashCode != hashCode && Settings.getClipboardTextHashCode() != hashCode) {
Pair<Long, String> pair = EhUrl.parseGalleryDetailUrl(text);
if (pair != null) {
long gid = pair.first;
String token = pair.second;
new AlertDialog.Builder(this)
.setTitle(R.string.clipboard_gallery_url_dialog_title)
.setMessage(R.string.clipboard_gallery_url_dialog_message)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
Bundle args = new Bundle();
args.putString(GalleryDetailScene.KEY_ACTION, GalleryDetailScene.ACTION_GID_TOKEN);
args.putLong(GalleryDetailScene.KEY_GID, gid);
args.putString(GalleryDetailScene.KEY_TOKEN, token);
startScene(new Announcer(GalleryDetailScene.class).setArgs(args));
})
.show();
}
}
if (mClipTextHashCode != hashCode) {
mClipTextHashCode = hashCode;
Settings.putClipboardTextHashCode(hashCode);
}
}
@Override
@@ -474,7 +502,7 @@ public final class MainActivity extends StageActivity
if (scene instanceof BaseScene && mRightDrawer != null && mDrawerLayout != null) {
BaseScene baseScene = (BaseScene) scene;
mRightDrawer.removeAllViews();
View drawerView = baseScene.onCreateDrawerView(
View drawerView = baseScene.createDrawerView(
baseScene.getLayoutInflater2(), mRightDrawer, savedInstanceState);
if (drawerView != null) {
mRightDrawer.addView(drawerView);
@@ -491,7 +519,7 @@ public final class MainActivity extends StageActivity
if (scene instanceof BaseScene) {
BaseScene baseScene = (BaseScene) scene;
baseScene.onDestroyDrawerView();
baseScene.destroyDrawerView();
}
}
+18 -1
View File
@@ -16,11 +16,13 @@
package com.hippo.ehviewer.ui;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
@@ -36,6 +38,8 @@ public class SetSecurityActivity extends ToolbarActivity implements View.OnClick
private View mCancel;
@Nullable
private View mSet;
@Nullable
private CheckBox mFingerprint;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
@@ -46,6 +50,7 @@ public class SetSecurityActivity extends ToolbarActivity implements View.OnClick
mPatternView = (LockPatternView) ViewUtils.$$(this, R.id.pattern_view);
mCancel = ViewUtils.$$(this, R.id.cancel);
mSet = ViewUtils.$$(this, R.id.set);
mFingerprint = (CheckBox) ViewUtils.$$(this, R.id.fingerprint_checkbox);
String pattern = Settings.getSecurity();
if (!TextUtils.isEmpty(pattern)) {
@@ -53,6 +58,16 @@ public class SetSecurityActivity extends ToolbarActivity implements View.OnClick
LockPatternUtils.stringToPattern(pattern));
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
FingerprintManager fingerprintManager = getSystemService(FingerprintManager.class);
// The line below prevents the false positive inspection from Android Studio
// noinspection ResourceType
if (fingerprintManager.hasEnrolledFingerprints()) {
mFingerprint.setVisibility(View.VISIBLE);
mFingerprint.setChecked(Settings.getEnableFingerprint());
}
}
mCancel.setOnClickListener(this);
mSet.setOnClickListener(this);
}
@@ -79,7 +94,7 @@ public class SetSecurityActivity extends ToolbarActivity implements View.OnClick
if (v == mCancel) {
finish();
} else if (v == mSet) {
if (null != mPatternView) {
if (null != mPatternView && null != mFingerprint) {
String security;
if (mPatternView.getCellSize() <= 1) {
security = "";
@@ -87,6 +102,8 @@ public class SetSecurityActivity extends ToolbarActivity implements View.OnClick
security = mPatternView.getPatternString();
}
Settings.putSecurity(security);
Settings.putEnableFingerprint(mFingerprint.getVisibility() == View.VISIBLE &&
mFingerprint.isChecked() && !security.isEmpty());
}
finish();
}
@@ -17,30 +17,22 @@
package com.hippo.ehviewer.ui;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.StringRes;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.ui.fragment.AboutFragment;
import com.hippo.ehviewer.ui.fragment.AdvancedFragment;
import com.hippo.ehviewer.ui.fragment.DownloadFragment;
import com.hippo.ehviewer.ui.fragment.EhFragment;
import com.hippo.ehviewer.ui.fragment.PrivacyFragment;
import com.hippo.ehviewer.ui.fragment.ReadFragment;
import com.hippo.util.DrawableManager;
import java.lang.reflect.Field;
import java.util.List;
public final class SettingsActivity extends EhPreferenceActivity {
@@ -53,77 +45,20 @@ public final class SettingsActivity extends EhPreferenceActivity {
DownloadFragment.class.getName(),
AdvancedFragment.class.getName(),
AboutFragment.class.getName(),
PrivacyFragment.class.getName(),
};
private class FakeLayoutInflater extends LayoutInflater {
private final LayoutInflater mInflater;
protected FakeLayoutInflater(LayoutInflater inflater) {
super(null);
mInflater = inflater;
}
@Override
public LayoutInflater cloneInContext(Context newContext) {
return null;
}
@Override
public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
return mInflater.inflate(R.layout.item_preference_header, root, attachToRoot);
}
}
@SuppressWarnings("TryWithIdenticalCatches")
private void replaceHeaderLayoutResId() {
try {
ListAdapter adapter = getListAdapter();
Class headerAdapterClazz = Class.forName("android.preference.PreferenceActivity$HeaderAdapter");
if (!headerAdapterClazz.isInstance(adapter)) {
return;
}
boolean ok = false;
// For lollipop and above this work
try {
Field field = headerAdapterClazz.getDeclaredField("mLayoutResId");
field.setAccessible(true);
field.setInt(adapter, R.layout.item_preference_header);
ok = true;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
// For pre-lollipop this work
if (!ok) {
try {
Field field = headerAdapterClazz.getDeclaredField("mInflater");
field.setAccessible(true);
field.set(adapter, new FakeLayoutInflater((LayoutInflater) field.get(adapter)));
ok = true;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (ClassCastException e) {
e.printStackTrace();
}
}
if (ok) {
getListView().setDivider(new ColorDrawable(Color.TRANSPARENT));
getListView().setDividerHeight(0);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
@Override
protected int getThemeResId(int theme) {
switch (theme) {
case Settings.THEME_LIGHT:
default:
return R.style.AppTheme_Settings;
case Settings.THEME_DARK:
return R.style.AppTheme_Settings_Dark;
case Settings.THEME_BLACK:
return R.style.AppTheme_Settings_Black;
}
}
private void setActionBarUpIndicator(Drawable drawable) {
@@ -143,15 +78,13 @@ public final class SettingsActivity extends EhPreferenceActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setActionBarUpIndicator(DrawableManager.getDrawable(this, R.drawable.v_arrow_left_dark_x24));
replaceHeaderLayoutResId();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
@@ -25,8 +25,22 @@ import android.view.View;
import android.view.ViewGroup;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
public class ToolbarActivity extends EhActivity {
public abstract class ToolbarActivity extends EhActivity {
@Override
protected int getThemeResId(int theme) {
switch (theme) {
case Settings.THEME_LIGHT:
default:
return R.style.AppTheme_Toolbar;
case Settings.THEME_DARK:
return R.style.AppTheme_Toolbar_Dark;
case Settings.THEME_BLACK:
return R.style.AppTheme_Toolbar_Black;
}
}
@Override
public void setContentView(@LayoutRes int layoutResID) {
@@ -0,0 +1,251 @@
/*
* Copyright 2018 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.ui;
/*
* Created by Hippo on 2018/2/9.
*/
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.widget.ProgressView;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
public class UConfigActivity extends ToolbarActivity {
private WebView webView;
private ProgressView progress;
private String url;
private boolean loaded;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// http://stackoverflow.com/questions/32284642/how-to-handle-an-uncatched-exception
CookieManager cookieManager = CookieManager.getInstance();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.flush();
cookieManager.removeAllCookies(null);
cookieManager.removeSessionCookies(null);
} else {
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(this);
cookieSyncManager.startSync();
cookieManager.removeAllCookie();
cookieManager.removeSessionCookie();
cookieSyncManager.stopSync();
}
// Copy cookies from okhttp cookie store to CookieManager
url = EhUrl.getUConfigUrl();
EhCookieStore store = EhApplication.getEhCookieStore(this);
for (Cookie cookie : store.getCookies(HttpUrl.parse(url))) {
cookieManager.setCookie(url, cookie.toString());
}
setContentView(R.layout.activity_u_config);
setNavigationIcon(R.drawable.v_arrow_left_dark_x24);
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new UConfigWebViewClient());
webView.setWebChromeClient(new UConfigWebChromeClient());
webView.loadUrl(url);
progress = (ProgressView) findViewById(R.id.progress);
Snackbar.make(webView, R.string.apply_tip, Snackbar.LENGTH_LONG).show();
}
private void apply() {
webView.loadUrl("javascript:"
+ "(function() {\n"
+ " var apply = document.getElementById(\"apply\").children[0];\n"
+ " apply.click();\n"
+ "})();");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_u_config, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_apply:
if (loaded) {
apply();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private Cookie longLive(Cookie cookie) {
return new Cookie.Builder()
.name(cookie.name())
.value(cookie.value())
.domain(cookie.domain())
.path(cookie.path())
.expiresAt(Long.MAX_VALUE)
.build();
}
@Override
protected void onDestroy() {
super.onDestroy();
webView.destroy();
// Put cookies back to okhttp cookie store
CookieManager cookieManager = CookieManager.getInstance();
String cookiesString = cookieManager.getCookie(url);
if (cookiesString != null && !cookiesString.isEmpty()) {
EhCookieStore store = EhApplication.getEhCookieStore(this);
HttpUrl eUrl = HttpUrl.parse(EhUrl.HOST_E);
HttpUrl exUrl = HttpUrl.parse(EhUrl.HOST_EX);
// The cookies saved in the uconfig page should be shared between e and ex
for (String header : cookiesString.split(";")) {
Cookie eCookie = Cookie.parse(eUrl, header);
if (eCookie != null) {
store.addCookie(longLive(eCookie));
}
Cookie exCookie = Cookie.parse(exUrl, header);
if (exCookie != null) {
store.addCookie(longLive(exCookie));
}
}
}
}
private class UConfigWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Never load other urls
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progress.setVisibility(View.VISIBLE);
loaded = false;
}
@Override
public void onPageFinished(WebView view, String url) {
progress.setVisibility(View.GONE);
loaded = true;
}
}
private class UConfigWebChromeClient extends WebChromeClient {
private Context context = UConfigActivity.this;
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
final JsPromptResult result) {
View promptView = UConfigActivity.this.getLayoutInflater()
.inflate(R.layout.dialog_js_prompt, null, false);
TextView messageView = (TextView) promptView.findViewById(R.id.message);
messageView.setText(message);
final EditText valueView = (EditText) promptView.findViewById(R.id.value);
valueView.setText(defaultValue);
new AlertDialog.Builder(context)
.setView(promptView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm(valueView.getText().toString());
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
result.cancel();
}
})
.show();
return true;
}
private void showMessageDialog(String message, final JsResult result) {
new AlertDialog.Builder(context)
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
result.cancel();
}
})
.show();
}
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
showMessageDialog(message, result);
return true;
}
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
showMessageDialog(message, result);
return true;
}
}
}
@@ -16,21 +16,26 @@
package com.hippo.ehviewer.ui.fragment;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.v7.app.AlertDialog;
import com.hippo.ehviewer.Analytics;
import android.util.Base64;
import android.widget.TextView;
import android.widget.Toast;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.util.AppHelper;
import java.io.UnsupportedEncodingException;
public class AboutFragment extends PreferenceFragment
implements Preference.OnPreferenceChangeListener,
Preference.OnPreferenceClickListener {
implements Preference.OnPreferenceClickListener {
private static final String KEY_AUTHOR = "author";
private static final String KEY_DONATE = "donate";
@@ -42,30 +47,14 @@ public class AboutFragment extends PreferenceFragment
addPreferencesFromResource(R.xml.about_settings);
Preference author = findPreference(KEY_AUTHOR);
Preference enableAnalytics = findPreference(Settings.KEY_ENABLE_ANALYTICS);
Preference donate = findPreference(KEY_DONATE);
Preference checkForUpdate = findPreference(KEY_CHECK_FOR_UPDATES);
author.setSummary(getString(R.string.settings_about_author_summary).replace('$', '@'));
donate.setSummary(getString(R.string.settings_about_donate_summary).replace('$', '@'));
author.setOnPreferenceClickListener(this);
donate.setOnPreferenceClickListener(this);
checkForUpdate.setOnPreferenceClickListener(this);
enableAnalytics.setOnPreferenceChangeListener(this);
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
if (Settings.KEY_ENABLE_ANALYTICS.equals(key)) {
if (newValue instanceof Boolean && (Boolean) newValue) {
Analytics.start(getActivity());
}
return true;
}
return true;
}
@Override
@@ -75,13 +64,51 @@ public class AboutFragment extends PreferenceFragment
AppHelper.sendEmail(getActivity(), EhApplication.getDeveloperEmail(),
"About EhViewer", null);
} else if (KEY_DONATE.equals(key)) {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.settings_about_donate)
.setMessage(getString(R.string.settings_about_donate_message).replace('$', '@'))
.show();
showDonationDialog();
} else if (KEY_CHECK_FOR_UPDATES.equals(key)) {
CommonOperations.checkUpdate(getActivity(), true);
}
return true;
}
private void showDonationDialog() {
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setView(R.layout.dialog_donate)
.show();
String alipayStr = base64Decode("c2V2ZW4zMzJAMTYzLmNvbQ==");
TextView alipayText = dialog.findViewById(R.id.alipay_text);
alipayText.setText(alipayStr);
dialog.findViewById(R.id.alipay_copy).setOnClickListener(v -> copyToClipboard(alipayStr));
String paypalStr = base64Decode("aHR0cHM6Ly9wYXlwYWwubWUvc2V2ZW4zMzI=");
TextView paypalText = dialog.findViewById(R.id.paypal_text);
paypalText.setText(paypalStr);
dialog.findViewById(R.id.paypal_open).setOnClickListener(v -> openUrl(paypalStr));
dialog.findViewById(R.id.paypal_copy).setOnClickListener(v -> copyToClipboard(paypalStr));
}
private static String base64Decode(String encoded) {
byte[] bytes = Base64.decode(encoded, Base64.DEFAULT);
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
}
private void copyToClipboard(String text) {
ClipboardManager cmb = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
if (cmb != null) {
cmb.setPrimaryClip(ClipData.newPlainText(null, text));
Toast.makeText(getActivity(), R.string.settings_about_donate_copied, Toast.LENGTH_SHORT).show();
}
}
private void openUrl(String url) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
Intent chooser = Intent.createChooser(intent, "");
startActivity(chooser);
}
}
@@ -24,25 +24,24 @@ import android.content.res.Resources;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.text.TextUtils;
import android.widget.Toast;
import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.util.LogCat;
import com.hippo.util.ReadableTime;
import java.io.File;
import java.util.Arrays;
public class AdvancedFragment extends PreferenceFragment implements Preference.OnPreferenceClickListener {
public class AdvancedFragment extends PreferenceFragment
implements Preference.OnPreferenceClickListener, Preference.OnPreferenceChangeListener {
private static final String KEY_DUMP_LOGCAT = "dump_logcat";
private static final String KEY_CLEAR_MEMORY_CACHE = "clear_memory_cache";
private static final String KEY_PATTERN_PROTECTION = "pattern_protection";
private static final String KEY_APP_LANGUAGE = "app_language";
private static final String KEY_EXPORT_DATA = "export_data";
private static final String KEY_IMPORT_DATA = "import_data";
@@ -53,6 +52,7 @@ public class AdvancedFragment extends PreferenceFragment implements Preference.O
Preference dumpLogcat = findPreference(KEY_DUMP_LOGCAT);
Preference clearMemoryCache = findPreference(KEY_CLEAR_MEMORY_CACHE);
Preference appLanguage = findPreference(KEY_APP_LANGUAGE);
Preference exportData = findPreference(KEY_EXPORT_DATA);
Preference importData = findPreference(KEY_IMPORT_DATA);
@@ -60,16 +60,13 @@ public class AdvancedFragment extends PreferenceFragment implements Preference.O
clearMemoryCache.setOnPreferenceClickListener(this);
exportData.setOnPreferenceClickListener(this);
importData.setOnPreferenceClickListener(this);
appLanguage.setOnPreferenceChangeListener(this);
}
@Override
public void onResume() {
super.onResume();
Preference patternProtection = findPreference(KEY_PATTERN_PROTECTION);
patternProtection.setSummary(TextUtils.isEmpty(Settings.getSecurity()) ?
R.string.settings_advanced_pattern_protection_not_set :
R.string.settings_advanced_pattern_protection_set);
}
@Override
@@ -137,4 +134,14 @@ public class AdvancedFragment extends PreferenceFragment implements Preference.O
}
}).show();
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
if (KEY_APP_LANGUAGE.equals(key)) {
((EhApplication) getActivity().getApplication()).recreate();
return true;
}
return false;
}
}
@@ -20,7 +20,7 @@ import android.app.Activity;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
@@ -32,11 +32,13 @@ public class EhFragment extends PreferenceFragment
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.eh_settings);
Preference theme = findPreference(Settings.KEY_THEME);
Preference gallerySite = findPreference(Settings.KEY_GALLERY_SITE);
Preference listMode = findPreference(Settings.KEY_LIST_MODE);
Preference detailSize = findPreference(Settings.KEY_DETAIL_SIZE);
Preference thumbSize = findPreference(Settings.KEY_THUMB_SIZE);
theme.setOnPreferenceChangeListener(this);
gallerySite.setOnPreferenceChangeListener(this);
listMode.setOnPreferenceChangeListener(this);
detailSize.setOnPreferenceChangeListener(this);
@@ -46,7 +48,10 @@ public class EhFragment extends PreferenceFragment
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
if (Settings.KEY_GALLERY_SITE.equals(key)) {
if (Settings.KEY_THEME.equals(key)) {
((EhApplication) getActivity().getApplication()).recreate();
return true;
} else if (Settings.KEY_GALLERY_SITE.equals(key)) {
getActivity().setResult(Activity.RESULT_OK);
return true;
} else if (Settings.KEY_LIST_MODE.equals(key)) {
@@ -0,0 +1,47 @@
package com.hippo.ehviewer.ui.fragment;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.text.TextUtils;
import com.hippo.ehviewer.Analytics;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
/**
* Created by Mo10 on 2018/2/10.
*/
public class PrivacyFragment extends PreferenceFragment
implements Preference.OnPreferenceChangeListener {
private static final String KEY_PATTERN_PROTECTION = "pattern_protection";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.privacy_settings);
Preference enableAnalytics = findPreference(Settings.KEY_ENABLE_ANALYTICS);
enableAnalytics.setOnPreferenceChangeListener(this);
}
@Override
public void onResume() {
super.onResume();
Preference patternProtection = findPreference(KEY_PATTERN_PROTECTION);
patternProtection.setSummary(TextUtils.isEmpty(Settings.getSecurity()) ?
R.string.settings_privacy_pattern_protection_not_set :
R.string.settings_privacy_pattern_protection_set);
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
if (Settings.KEY_ENABLE_ANALYTICS.equals(key)) {
if (newValue instanceof Boolean && (Boolean) newValue) {
Analytics.start(getActivity());
}
return true;
}
return true;
}
}
@@ -32,7 +32,7 @@ import com.hippo.text.Html;
import com.hippo.text.LinkMovementMethod2;
import com.hippo.yorozuya.ViewUtils;
public class AnalyticsScene extends BaseScene implements View.OnClickListener {
public class AnalyticsScene extends SolidScene implements View.OnClickListener {
@Nullable
private View mReject;
@@ -90,7 +90,7 @@ public class AnalyticsScene extends BaseScene implements View.OnClickListener {
// Start new scene and finish it self
MainActivity activity = getActivity2();
if (null != activity) {
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_ANALYTICS, getArguments());
startSceneForCheckStep(CHECK_STEP_ANALYTICS, getArguments());
}
finish();
}
@@ -19,18 +19,20 @@ package com.hippo.ehviewer.ui.scene;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.StyleRes;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.util.SparseArray;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.scene.SceneFragment;
import com.hippo.util.AppHelper;
@@ -40,8 +42,16 @@ public abstract class BaseScene extends SceneFragment {
public static final int LENGTH_SHORT = 0;
public static final int LENGTH_LONG = 1;
public static final String KEY_DRAWER_VIEW_STATE =
"com.hippo.ehviewer.ui.scene.BaseScene:DRAWER_VIEW_STATE";
private Context mThemeContext;
@Nullable
private View drawerView;
@Nullable
private SparseArray<Parcelable> drawerViewState;
public void updateAvatar() {
FragmentActivity activity = getActivity();
if (activity instanceof MainActivity) {
@@ -132,11 +142,39 @@ public abstract class BaseScene extends SceneFragment {
return 0;
}
public final View createDrawerView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
drawerView = onCreateDrawerView(inflater, container, savedInstanceState);
if (drawerView != null) {
SparseArray<Parcelable> saved = drawerViewState;
if (saved == null && savedInstanceState != null) {
saved = savedInstanceState.getSparseParcelableArray(KEY_DRAWER_VIEW_STATE);
}
if (saved != null) {
drawerView.restoreHierarchyState(saved);
}
}
return drawerView;
}
public View onCreateDrawerView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return null;
}
public final void destroyDrawerView() {
if (drawerView != null) {
drawerViewState = new SparseArray<>();
drawerView.saveHierarchyState(drawerViewState);
}
onDestroyDrawerView();
drawerView = null;
}
public void onDestroyDrawerView() {
}
@@ -222,4 +260,15 @@ public abstract class BaseScene extends SceneFragment {
AppHelper.showSoftInput(activity, view);
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
if (drawerView != null) {
drawerViewState = new SparseArray<>();
drawerView.saveHierarchyState(drawerViewState);
outState.putSparseParcelableArray(KEY_DRAWER_VIEW_STATE, drawerViewState);
}
}
}
@@ -30,18 +30,16 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import okhttp3.Cookie;
public class CookieSignInScene extends BaseScene implements EditText.OnEditorActionListener,
public class CookieSignInScene extends SolidScene implements EditText.OnEditorActionListener,
View.OnClickListener {
/*---------------
@@ -52,10 +50,14 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
@Nullable
private TextInputLayout mIpbPassHashLayout;
@Nullable
private TextInputLayout mIgneousLayout;
@Nullable
private EditText mIpbMemberId;
@Nullable
private EditText mIpbPassHash;
@Nullable
private EditText mIgneous;
@Nullable
private View mOk;
@Override
@@ -70,10 +72,13 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
View view = inflater.inflate(R.layout.scene_cookie_sign_in, container, false);
mIpbMemberIdLayout = (TextInputLayout) ViewUtils.$$(view, R.id.ipb_member_id_layout);
mIpbMemberId = mIpbMemberIdLayout.getEditText();
AssertUtils.assertNotNull(mIpbMemberId);
Assert.assertNotNull(mIpbMemberId);
mIpbPassHashLayout = (TextInputLayout) ViewUtils.$$(view, R.id.ipb_pass_hash_layout);
mIpbPassHash = mIpbPassHashLayout.getEditText();
AssertUtils.assertNotNull(mIpbPassHash);
Assert.assertNotNull(mIpbPassHash);
mIgneousLayout = (TextInputLayout) ViewUtils.$$(view, R.id.igneous_layout);
mIgneous = mIgneousLayout.getEditText();
Assert.assertNotNull(mIgneous);
mOk = ViewUtils.$$(view, R.id.ok);
mIpbPassHash.setOnEditorActionListener(this);
@@ -82,10 +87,11 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
// Try to get old version cookie info
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
SharedPreferences sharedPreferences = context.getSharedPreferences("eh_info", 0);
String ipbMemberId = sharedPreferences.getString("ipb_member_id", null);
String ipbPassHash = sharedPreferences.getString("ipb_pass_hash", null);
String igneous = sharedPreferences.getString("igneous", null);
boolean getIt = false;
if (!TextUtils.isEmpty(ipbMemberId)) {
mIpbMemberId.setText(ipbMemberId);
@@ -95,6 +101,10 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
mIpbPassHash.setText(ipbPassHash);
getIt = true;
}
if (!TextUtils.isEmpty(igneous)) {
mIgneous.setText(igneous);
getIt = true;
}
if (getIt) {
showTip(R.string.found_cookies, LENGTH_SHORT);
}
@@ -116,8 +126,10 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
mIpbMemberIdLayout = null;
mIpbPassHashLayout = null;
mIgneousLayout = null;
mIpbMemberId = null;
mIpbPassHash = null;
mIgneous = null;
}
@Override
@@ -163,12 +175,14 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
public void enter() {
Context context = getContext2();
if (null == context || null == mIpbMemberIdLayout || null == mIpbPassHashLayout ||
null == mIpbMemberId || null == mIpbPassHash) {
null == mIgneousLayout || null == mIpbMemberId || null == mIpbPassHash ||
null == mIgneous) {
return;
}
final String ipbMemberId = mIpbMemberId.getText().toString().trim();
final String ipbPassHash = mIpbPassHash.getText().toString().trim();
final String igneous = mIgneous.getText().toString().trim();
if (TextUtils.isEmpty(ipbMemberId)) {
mIpbMemberIdLayout.setError(getString(R.string.text_is_empty));
@@ -192,13 +206,13 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
.setPositiveButton(R.string.i_will_check_it, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
storeCookie(ipbMemberId, ipbPassHash);
storeCookie(ipbMemberId, ipbPassHash, igneous);
setResult(RESULT_OK, null);
finish();
}
}).show();
} else {
storeCookie(ipbMemberId, ipbPassHash);
storeCookie(ipbMemberId, ipbPassHash, igneous);
setResult(RESULT_OK, null);
finish();
}
@@ -209,7 +223,7 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
.domain(domain).expiresAt(Long.MAX_VALUE).build();
}
private void storeCookie(String id, String hash) {
private void storeCookie(String id, String hash, String igneous) {
Context context = getContext2();
if (null == context) {
return;
@@ -218,9 +232,13 @@ public class CookieSignInScene extends BaseScene implements EditText.OnEditorAct
EhUtils.signOut(context);
EhCookieStore store = EhApplication.getEhCookieStore(context);
store.add(newCookie(EhCookieStore.KEY_IPD_MEMBER_ID, id, EhUrl.DOMAIN_E));
store.add(newCookie(EhCookieStore.KEY_IPD_MEMBER_ID, id, EhUrl.DOMAIN_EX));
store.add(newCookie(EhCookieStore.KEY_IPD_PASS_HASH, hash, EhUrl.DOMAIN_E));
store.add(newCookie(EhCookieStore.KEY_IPD_PASS_HASH, hash, EhUrl.DOMAIN_EX));
store.addCookie(newCookie(EhCookieStore.KEY_IPD_MEMBER_ID, id, EhUrl.DOMAIN_E));
store.addCookie(newCookie(EhCookieStore.KEY_IPD_MEMBER_ID, id, EhUrl.DOMAIN_EX));
store.addCookie(newCookie(EhCookieStore.KEY_IPD_PASS_HASH, hash, EhUrl.DOMAIN_E));
store.addCookie(newCookie(EhCookieStore.KEY_IPD_PASS_HASH, hash, EhUrl.DOMAIN_EX));
if (!igneous.isEmpty()) {
store.addCookie(newCookie(EhCookieStore.KEY_IGNEOUS, igneous, EhUrl.DOMAIN_E));
store.addCookie(newCookie(EhCookieStore.KEY_IGNEOUS, igneous, EhUrl.DOMAIN_EX));
}
}
}
@@ -21,7 +21,7 @@ import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hippo.android.resource.AttrResources;
import com.hippo.ehviewer.Crash;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
@@ -30,7 +30,7 @@ import com.hippo.ripple.Ripple;
import com.hippo.util.AppHelper;
import com.hippo.yorozuya.ViewUtils;
public class CrashScene extends BaseScene implements View.OnClickListener {
public class CrashScene extends SolidScene implements View.OnClickListener {
/*---------------
Whole life cycle
@@ -70,8 +70,9 @@ public class CrashScene extends BaseScene implements View.OnClickListener {
mCancel.setOnClickListener(this);
mSend.setOnClickListener(this);
Ripple.addRipple(mCancel, true);
Ripple.addRipple(mSend, true);
boolean isDarkTheme = !AttrResources.getAttrBoolean(getContext2(), R.attr.isLightTheme);
Ripple.addRipple(mCancel, isDarkTheme);
Ripple.addRipple(mSend, isDarkTheme);
return view;
}
@@ -88,7 +89,7 @@ public class CrashScene extends BaseScene implements View.OnClickListener {
// Start new scene and finish it self
if (null != activity) {
activity.startSceneForCheckStep(MainActivity.CHECK_STEP_CRASH, getArguments());
startSceneForCheckStep(CHECK_STEP_CRASH, getArguments());
}
finish();
}
@@ -53,9 +53,10 @@ import com.hippo.ehviewer.R;
import com.hippo.ehviewer.dao.DownloadLabel;
import com.hippo.util.DrawableManager;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.List;
public class DownloadLabelsScene extends ToolbarScene {
@@ -100,7 +101,7 @@ public class DownloadLabelsScene extends ToolbarScene {
mViewTransition = new ViewTransition(mRecyclerView, tip);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_label);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
tip.setCompoundDrawables(null, drawable, null, null);
@@ -340,7 +341,7 @@ public class DownloadLabelsScene extends ToolbarScene {
public LabelAdapter() {
mInflater = getLayoutInflater2();
AssertUtils.assertNotNull(mInflater);
Assert.assertNotNull(mInflater);
}
@Override
@@ -389,6 +390,11 @@ public class DownloadLabelsScene extends ToolbarScene {
}
}
@Override
public boolean onCheckCanDrop(int draggingPosition, int dropPosition) {
return true;
}
@Override
public int onGetSwipeReactionType(LabelHolder holder, int position, int x, int y) {
if (ViewUtils.isViewUnder(holder.getSwipeableContainerView(), x, y, 0)) {
@@ -50,11 +50,11 @@ import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.github.amlcurran.showcaseview.ShowcaseView;
import com.github.amlcurran.showcaseview.SimpleShowcaseEventListener;
import com.github.amlcurran.showcaseview.targets.PointTarget;
import com.github.amlcurran.showcaseview.targets.ViewTarget;
import com.hippo.android.resource.AttrResources;
import com.hippo.app.CheckBoxDialogBuilder;
import com.hippo.conaco.DataContainer;
import com.hippo.conaco.ProgressNotifier;
@@ -88,20 +88,18 @@ import com.hippo.view.ViewTransition;
import com.hippo.widget.FabLayout;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.recyclerview.AutoStaggeredGridLayoutManager;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.ObjectUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.ViewUtils;
import com.hippo.yorozuya.collect.LongList;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import junit.framework.Assert;
public class DownloadsScene extends ToolbarScene
implements DownloadManager.DownloadInfoListener,
@@ -193,7 +191,7 @@ public class DownloadsScene extends ToolbarScene
super.onCreate(savedInstanceState);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
mDownloadManager = EhApplication.getDownloadManager(context);
mDownloadManager.addDownloadInfoListener(this);
@@ -286,7 +284,7 @@ public class DownloadsScene extends ToolbarScene
mViewTransition = new ViewTransition(content, tip);
Context context = getContext2();
AssertUtils.assertNotNull(content);
Assert.assertNotNull(content);
Resources resources = context.getResources();
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_download);
@@ -300,7 +298,7 @@ public class DownloadsScene extends ToolbarScene
mLayoutManager.setColumnSize(resources.getDimensionPixelOffset(Settings.getDetailSizeResId()));
mLayoutManager.setStrategy(AutoStaggeredGridLayoutManager.STRATEGY_MIN_SIZE);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, !AttrResources.getAttrBoolean(context, R.attr.isLightTheme)));
mRecyclerView.setDrawSelectorOnTop(true);
mRecyclerView.hasFixedSize();
mRecyclerView.setClipToPadding(false);
@@ -326,7 +324,7 @@ public class DownloadsScene extends ToolbarScene
fastScroller.attachToRecyclerView(mRecyclerView);
HandlerDrawable handlerDrawable = new HandlerDrawable();
handlerDrawable.setColor(ResourcesUtils.getAttrColor(context, R.attr.colorAccent));
handlerDrawable.setColor(AttrResources.getAttrColor(context, R.attr.widgetColorThemeAccent));
fastScroller.setHandlerDrawable(handlerDrawable);
fastScroller.setOnDragHandlerListener(this);
@@ -488,6 +486,17 @@ public class DownloadsScene extends ToolbarScene
}
return true;
}
case R.id.action_reset_reading_progress: {
new AlertDialog.Builder(getContext())
.setMessage(R.string.reset_reading_progress_message)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
if (mDownloadManager != null) {
mDownloadManager.resetAllReadingProgress();
}
}).show();
return true;
}
}
return false;
}
@@ -508,7 +517,7 @@ public class DownloadsScene extends ToolbarScene
View view = inflater.inflate(R.layout.drawer_list, container, false);
final Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.setTitle(R.string.download_labels);
@@ -634,7 +643,7 @@ public class DownloadsScene extends ToolbarScene
if (list == null) {
return false;
}
if (position < 0 && position >= list.size()) {
if (position < 0 || position >= list.size()) {
return false;
}
@@ -1073,8 +1082,10 @@ public class DownloadsScene extends ToolbarScene
thumb.setOnClickListener(this);
start.setOnClickListener(this);
stop.setOnClickListener(this);
Ripple.addRipple(start, false);
Ripple.addRipple(stop, false);
boolean isDarkTheme = !AttrResources.getAttrBoolean(getContext2(), R.attr.isLightTheme);
Ripple.addRipple(start, isDarkTheme);
Ripple.addRipple(stop, isDarkTheme);
}
@Override
@@ -1091,7 +1102,7 @@ public class DownloadsScene extends ToolbarScene
}
int size = list.size();
int index = recyclerView.getChildAdapterPosition(itemView);
if (index < 0 && index >= size) {
if (index < 0 || index >= size) {
return;
}
@@ -1120,10 +1131,17 @@ public class DownloadsScene extends ToolbarScene
private class DownloadAdapter extends RecyclerView.Adapter<DownloadHolder> {
private final LayoutInflater mInflater;
private final int mListThumbWidth;
private final int mListThumbHeight;
public DownloadAdapter() {
mInflater = getLayoutInflater2();
AssertUtils.assertNotNull(mInflater);
Assert.assertNotNull(mInflater);
View calculator = mInflater.inflate(R.layout.item_gallery_list_thumb_height, null);
ViewUtils.measureView(calculator, 1024, ViewGroup.LayoutParams.WRAP_CONTENT);
mListThumbHeight = calculator.getMeasuredHeight();
mListThumbWidth = mListThumbHeight * 2 / 3;
}
@Override
@@ -1136,7 +1154,14 @@ public class DownloadsScene extends ToolbarScene
@Override
public DownloadHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new DownloadHolder(mInflater.inflate(R.layout.item_download, parent, false));
DownloadHolder holder = new DownloadHolder(mInflater.inflate(R.layout.item_download, parent, false));
ViewGroup.LayoutParams lp = holder.thumb.getLayoutParams();
lp.width = mListThumbWidth;
lp.height = mListThumbHeight;
holder.thumb.setLayoutParams(lp);
return holder;
}
@Override
@@ -1211,24 +1236,31 @@ public class DownloadsScene extends ToolbarScene
private class ThumbDataContainer implements DataContainer {
private final DownloadInfo mInfo;
@Nullable
private UniFile mFile;
public ThumbDataContainer(@NonNull DownloadInfo info) {
mInfo = info;
}
@Override
public void onUrlMoved(String requestUrl, String responseUrl) {}
private void ensureFile() {
if (mFile == null) {
UniFile dir = SpiderDen.getGalleryDownloadDir(mInfo);
if (dir != null && dir.ensureDir()) {
if (dir != null && dir.isDirectory()) {
mFile = dir.createFile(".thumb");
}
}
}
@Override
public boolean isEnabled() {
ensureFile();
return mFile != null;
}
@Override
public void onUrlMoved(String requestUrl, String responseUrl) {}
@Override
public boolean save(InputStream is, long length, String mediaType, ProgressNotifier notify) {
ensureFile();
@@ -1261,7 +1293,9 @@ public class DownloadsScene extends ToolbarScene
@Override
public void remove() {
mFile.delete();
if (mFile != null) {
mFile.delete();
}
}
}
}
@@ -40,6 +40,14 @@ public abstract class EhCallback<E extends SceneFragment, T> implements EhClient
public abstract boolean isInstance(SceneFragment scene);
public Context getContent() {
Context context = getStageActivity();
if (context == null) {
context = getApplication();
}
return context;
}
public EhApplication getApplication() {
return mApplication;
}
@@ -71,4 +79,14 @@ public abstract class EhCallback<E extends SceneFragment, T> implements EhClient
length == BaseScene.LENGTH_LONG ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show();
}
}
public void showTip(String tip, int length) {
StageActivity activity = getStageActivity();
if (activity instanceof MainActivity) {
((MainActivity) activity).showTip(tip, length);
} else {
Toast.makeText(getApplication(), tip,
length == BaseScene.LENGTH_LONG ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show();
}
}
}
@@ -29,6 +29,7 @@ import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
@@ -43,19 +44,16 @@ import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.github.amlcurran.showcaseview.ShowcaseView;
import com.github.amlcurran.showcaseview.SimpleShowcaseEventListener;
import com.github.amlcurran.showcaseview.targets.PointTarget;
import com.hippo.android.resource.AttrResources;
import com.hippo.annotation.Implemented;
import com.hippo.drawable.DrawerArrowDrawable;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.FastScroller;
import com.hippo.easyrecyclerview.LinearDividerItemDecoration;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.R;
@@ -70,6 +68,7 @@ import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.ehviewer.ui.annotation.DrawerLifeCircle;
import com.hippo.ehviewer.ui.annotation.ViewLifeCircle;
import com.hippo.ehviewer.ui.annotation.WholeLifeCircle;
import com.hippo.ehviewer.widget.EhDrawerLayout;
import com.hippo.ehviewer.widget.SearchBar;
import com.hippo.refreshlayout.RefreshLayout;
import com.hippo.ripple.Ripple;
@@ -80,13 +79,12 @@ import com.hippo.util.DrawableManager;
import com.hippo.widget.ContentLayout;
import com.hippo.widget.FabLayout;
import com.hippo.widget.SearchBarMover;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ObjectUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -95,7 +93,7 @@ import java.util.List;
public class FavoritesScene extends BaseScene implements
EasyRecyclerView.OnItemClickListener, EasyRecyclerView.OnItemLongClickListener,
FastScroller.OnDragHandlerListener, SearchBarMover.Helper, SearchBar.Helper,
FabLayout.OnClickFabListener, EasyRecyclerView.CustomChoiceListener, AdapterView.OnItemClickListener {
FabLayout.OnClickFabListener, EasyRecyclerView.CustomChoiceListener {
private static final long ANIMATE_TIME = 300L;
@@ -128,12 +126,11 @@ public class FavoritesScene extends BaseScene implements
private DrawerArrowDrawable mLeftDrawable;
@Nullable
@DrawerLifeCircle
private ArrayAdapter<String> mDrawerAdapter;
private EhDrawerLayout mDrawerLayout;
@Nullable
@DrawerLifeCircle
private List<String> mDrawerList;
private FavDrawerAdapter mDrawerAdapter;
@Nullable
@WholeLifeCircle
private EhClient mClient;
@@ -142,13 +139,16 @@ public class FavoritesScene extends BaseScene implements
private String[] mFavCatArray;
@Nullable
@WholeLifeCircle
private int[] mFavCountArray;
@Nullable
@WholeLifeCircle
private FavListUrlBuilder mUrlBuilder;
public int current; // -1 for error
public int limit; // -1 for error
@Nullable
private int[] mFavCountArray;
private int mFavLocalCount = 0;
private int mFavCountSum = 0;
private boolean mHasFirstRefresh;
private boolean mSearchMode;
@@ -177,9 +177,12 @@ public class FavoritesScene extends BaseScene implements
super.onCreate(savedInstanceState);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
mClient = EhApplication.getEhClient(context);
mFavCatArray = Settings.getFavCat();
mFavCountArray = Settings.getFavCount();
mFavLocalCount = Settings.getFavLocalCount();
mFavCountSum = Settings.getFavCloudCount();
if (savedInstanceState == null) {
onInit();
@@ -205,7 +208,7 @@ public class FavoritesScene extends BaseScene implements
}
@Override
public void onSaveInstanceState(Bundle outState) {
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
boolean hasFirstRefresh;
@@ -226,6 +229,8 @@ public class FavoritesScene extends BaseScene implements
mClient = null;
mFavCatArray = null;
mFavCountArray = null;
mFavCountSum = 0;
mUrlBuilder = null;
}
@@ -235,6 +240,9 @@ public class FavoritesScene extends BaseScene implements
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.scene_favorites, container, false);
ContentLayout contentLayout = (ContentLayout) view.findViewById(R.id.content_layout);
MainActivity activity = getActivity2();
Assert.assertNotNull(activity);
mDrawerLayout = (EhDrawerLayout) ViewUtils.$$(activity, R.id.draw_view);
mRecyclerView = contentLayout.getRecyclerView();
FastScroller fastScroller = contentLayout.getFastScroller();
RefreshLayout refreshLayout = contentLayout.getRefreshLayout();
@@ -242,7 +250,7 @@ public class FavoritesScene extends BaseScene implements
mFabLayout = (FabLayout) ViewUtils.$$(view, R.id.fab_layout);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Resources resources = context.getResources();
int paddingTopSB = resources.getDimensionPixelOffset(R.dimen.gallery_padding_top_search_bar);
@@ -252,7 +260,7 @@ public class FavoritesScene extends BaseScene implements
contentLayout.getFastScroller().setOnDragHandlerListener(this);
mAdapter = new FavoritesAdapter(inflater, resources, mRecyclerView, Settings.getListMode());
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, !AttrResources.getAttrBoolean(context, R.attr.isLightTheme)));
mRecyclerView.setDrawSelectorOnTop(true);
mRecyclerView.hasFixedSize();
mRecyclerView.setClipToPadding(false);
@@ -266,7 +274,7 @@ public class FavoritesScene extends BaseScene implements
refreshLayout.setHeaderTranslationY(paddingTopSB);
mLeftDrawable = new DrawerArrowDrawable(context);
mLeftDrawable = new DrawerArrowDrawable(context, AttrResources.getAttrColor(context, R.attr.drawableColorPrimary));
mSearchBar.setLeftDrawable(mLeftDrawable);
mSearchBar.setRightDrawable(DrawableManager.getDrawable(context, R.drawable.v_magnify_x24));
mSearchBar.setHelper(this);
@@ -388,7 +396,6 @@ public class FavoritesScene extends BaseScene implements
if (1 == mHelper.getShownViewIndex()) {
mHasFirstRefresh = false;
}
mHelper = null;
}
if (null != mRecyclerView) {
mRecyclerView.stopScroll();
@@ -410,96 +417,77 @@ public class FavoritesScene extends BaseScene implements
mOldKeyword = null;
}
private class InfoHolder extends RecyclerView.ViewHolder {
private class FavDrawerHolder extends RecyclerView.ViewHolder {
private final TextView key;
private final TextView value;
public InfoHolder(View itemView) {
private FavDrawerHolder(View itemView) {
super(itemView);
key = (TextView) ViewUtils.$$(itemView, R.id.key);
value = (TextView) ViewUtils.$$(itemView, R.id.value);
}
}
private class InfoAdapter extends RecyclerView.Adapter<InfoHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_DATA = 1;
private class FavDrawerAdapter extends RecyclerView.Adapter<FavDrawerHolder> {
private final LayoutInflater mInflater;
public InfoAdapter(LayoutInflater inflater) {
private FavDrawerAdapter(LayoutInflater inflater) {
mInflater = inflater;
}
@Override
public int getItemViewType(int position) {
return 0 == position ? TYPE_HEADER : TYPE_DATA;
return position;
}
@NonNull
@Override
public InfoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new InfoHolder(mInflater.inflate(TYPE_HEADER == viewType ?
R.layout.item_favorite_info_header : R.layout.item_favorite_info_data, parent, false));
public FavDrawerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new FavDrawerHolder(mInflater.inflate(R.layout.item_drawer_favorites, parent, false));
}
@Override
@SuppressLint("SetTextI18n")
public void onBindViewHolder(InfoHolder holder, int position) {
public void onBindViewHolder(@NonNull FavDrawerHolder holder, int position) {
if (0 == position) {
holder.key.setText(R.string.collections);
holder.value.setText(R.string.count);
holder.itemView.setEnabled(false);
holder.key.setText(R.string.local_favorites);
holder.value.setText(Integer.toString(mFavLocalCount));
holder.itemView.setEnabled(true);
} else if (1 == position){
holder.key.setText(R.string.cloud_favorites);
holder.value.setText(Integer.toString(mFavCountSum));
holder.itemView.setEnabled(true);
} else {
if (null == mFavCatArray || null == mFavCountArray ||
mFavCatArray.length < position || mFavCountArray.length < position) {
mFavCatArray.length < (position - 1) ||
mFavCountArray.length < (position - 1)) {
return;
}
holder.key.setText(mFavCatArray[position - 1]);
holder.value.setText(Integer.toString(mFavCountArray[position - 1]));
holder.key.setText(mFavCatArray[position - 2]);
holder.value.setText(Integer.toString(mFavCountArray[position - 2]));
holder.itemView.setEnabled(true);
}
}
@Override
public int getItemCount() {
return 11;
if (null == mFavCatArray) {
return 2;
}
return 12;
}
}
@SuppressLint("InflateParams")
private void showFavoritesInfoDialog() {
Context context = getContext2();
if (null == context || null == mFavCatArray || null == mFavCountArray) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
context = builder.getContext();
final LayoutInflater inflater = LayoutInflater.from(context);
EasyRecyclerView rv = (EasyRecyclerView) inflater.inflate(R.layout.dialog_recycler_view, null);
rv.setAdapter(new InfoAdapter(inflater));
rv.setLayoutManager(new LinearLayoutManager(context));
LinearDividerItemDecoration decoration = new LinearDividerItemDecoration(
LinearDividerItemDecoration.VERTICAL, context.getResources().getColor(R.color.divider),
LayoutUtils.dp2pix(context, 1));
decoration.setPadding(ResourcesUtils.getAttrDimensionPixelOffset(context, R.attr.dialogPreferredPadding));
rv.addItemDecoration(decoration);
rv.setSelector(Ripple.generateRippleDrawable(context, false));
rv.setClipToPadding(false);
builder.setView(rv).show();
}
@Override
public View onCreateDrawerView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.drawer_list, container, false);
Toolbar toolbar = (Toolbar) ViewUtils.$$(view, R.id.toolbar);
ListView listView = (ListView) view.findViewById(R.id.list_view);
View view = inflater.inflate(R.layout.drawer_list_rv, container, false);
final Context context = getContext2();
AssertUtils.assertNotNull(context);
Toolbar toolbar = (Toolbar) ViewUtils.$$(view, R.id.toolbar);
Assert.assertNotNull(context);
toolbar.setTitle(R.string.collections);
toolbar.inflateMenu(R.menu.drawer_favorites);
@@ -508,9 +496,6 @@ public class FavoritesScene extends BaseScene implements
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_info:
showFavoritesInfoDialog();
return true;
case R.id.action_default_favorites_slot:
String[] items = new String[12];
items[0] = getString(R.string.let_me_select);
@@ -531,15 +516,13 @@ public class FavoritesScene extends BaseScene implements
}
});
mDrawerList = new ArrayList<>(12);
mDrawerList.add(getString(R.string.local_favorites));
mDrawerList.add(getString(R.string.cloud_favorites));
if (mFavCatArray != null) {
Collections.addAll(mDrawerList, mFavCatArray);
}
mDrawerAdapter = new ArrayAdapter<>(context, R.layout.item_simple_list, mDrawerList);
listView.setAdapter(mDrawerAdapter);
listView.setOnItemClickListener(this);
EasyRecyclerView recyclerView = (EasyRecyclerView) view.findViewById(R.id.recycler_view_drawer);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
mDrawerAdapter = new FavDrawerAdapter(inflater);
recyclerView.setAdapter(mDrawerAdapter);
recyclerView.setOnItemClickListener(this);
return view;
}
@@ -549,7 +532,6 @@ public class FavoritesScene extends BaseScene implements
super.onDestroyDrawerView();
mDrawerAdapter = null;
mDrawerList = null;
}
@Override
@@ -590,19 +572,53 @@ public class FavoritesScene extends BaseScene implements
@Override
@Implemented(EasyRecyclerView.OnItemClickListener.class)
public boolean onItemClick(EasyRecyclerView parent, View view, int position, long id) {
if (mRecyclerView != null && mRecyclerView.isInCustomChoice()) {
mRecyclerView.toggleItemChecked(position);
} else if (mHelper != null) {
GalleryInfo gi = mHelper.getDataAt(position);
Bundle args = new Bundle();
args.putString(GalleryDetailScene.KEY_ACTION, GalleryDetailScene.ACTION_GALLERY_INFO);
args.putParcelable(GalleryDetailScene.KEY_GALLERY_INFO, gi);
Announcer announcer = new Announcer(GalleryDetailScene.class).setArgs(args);
View thumb;
if (ApiHelper.SUPPORT_TRANSITION && null != (thumb = view.findViewById(R.id.thumb))) {
announcer.setTranHelper(new EnterGalleryDetailTransaction(thumb));
if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(Gravity.RIGHT)){
// Skip if in search mode
if (mRecyclerView != null && mRecyclerView.isInCustomChoice()) {
return true;
}
if (mUrlBuilder == null || mHelper == null) {
return true;
}
// Local favorite position is 0, All favorite position is 1, so position - 2 is OK
int newFavCat = position - 2;
// Check is the same
if (mUrlBuilder.getFavCat() == newFavCat) {
return true;
}
// Ensure outOfCustomChoiceMode to avoid error
if (mRecyclerView != null) {
mRecyclerView.isInCustomChoice();
}
exitSearchMode(true);
mUrlBuilder.setKeyword(null);
mUrlBuilder.setFavCat(newFavCat);
updateSearchBar();
mHelper.refresh();
closeDrawer(Gravity.RIGHT);
} else {
if (mRecyclerView != null && mRecyclerView.isInCustomChoice()) {
mRecyclerView.toggleItemChecked(position);
} else if (mHelper != null) {
GalleryInfo gi = mHelper.getDataAt(position);
Bundle args = new Bundle();
args.putString(GalleryDetailScene.KEY_ACTION, GalleryDetailScene.ACTION_GALLERY_INFO);
args.putParcelable(GalleryDetailScene.KEY_GALLERY_INFO, gi);
Announcer announcer = new Announcer(GalleryDetailScene.class).setArgs(args);
View thumb;
if (ApiHelper.SUPPORT_TRANSITION && null != (thumb = view.findViewById(R.id.thumb))) {
announcer.setTranHelper(new EnterGalleryDetailTransaction(thumb));
}
startScene(announcer);
}
startScene(announcer);
}
return true;
}
@@ -805,41 +821,6 @@ public class FavoritesScene extends BaseScene implements
}
}
@Override
@Implemented(AdapterView.OnItemClickListener.class)
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Skip if in search mode
if (mRecyclerView != null && mRecyclerView.isInCustomChoice()) {
return;
}
if (mUrlBuilder == null || mHelper == null) {
return;
}
// Local favorite position is 0, All favorite position is 1, so position - 2 is OK
int newFavCat = position - 2;
// Check is the same
if (mUrlBuilder.getFavCat() == newFavCat) {
return;
}
// Ensure outOfCustomChoiceMode to avoid error
if (mRecyclerView != null) {
mRecyclerView.isInCustomChoice();
}
exitSearchMode(true);
mUrlBuilder.setKeyword(null);
mUrlBuilder.setFavCat(newFavCat);
updateSearchBar();
mHelper.refresh();
closeDrawer(Gravity.RIGHT);
}
private void enterSearchMode(boolean animation) {
if (mSearchMode ||mSearchBar == null || mSearchBarMover == null || mLeftDrawable == null) {
return;
@@ -864,22 +845,26 @@ public class FavoritesScene extends BaseScene implements
if (mHelper != null && mSearchBarMover != null &&
mHelper.isCurrentTask(taskId)) {
if (mFavCatArray != null && mDrawerList != null) {
for (int i = 0; i < 10; i++) {
mFavCatArray[i] = result.catArray[i];
mDrawerList.set(i + 2, result.catArray[i]);
}
if (mDrawerAdapter != null) {
mDrawerAdapter.notifyDataSetChanged();
}
if (mFavCatArray != null) {
System.arraycopy(result.catArray, 0, mFavCatArray, 0,10);
}
mFavCountArray = result.countArray;
if (mFavCountArray != null){
mFavCountSum = 0;
for (int i = 0; i < 10; i++ ){
mFavCountSum = mFavCountSum + mFavCountArray[i];
}
Settings.putFavCloudCount(mFavCountSum);
}
updateSearchBar();
mHelper.setPages(taskId, result.pages);
mHelper.onGetPageData(taskId, result.galleryInfoList);
if (mDrawerAdapter != null) {
mDrawerAdapter.notifyDataSetChanged();
}
}
}
@@ -899,6 +884,7 @@ public class FavoritesScene extends BaseScene implements
} else {
list = EhDB.searchLocalFavorites(keyword);
}
if (list.size() == 0) {
mHelper.setPages(taskId, 0);
mHelper.onGetPageData(taskId, Collections.EMPTY_LIST);
@@ -906,6 +892,14 @@ public class FavoritesScene extends BaseScene implements
mHelper.setPages(taskId, 1);
mHelper.onGetPageData(taskId, list);
}
if (TextUtils.isEmpty(keyword)) {
mFavLocalCount = list.size();
Settings.putFavLocalCount(mFavLocalCount);
if (mDrawerAdapter != null) {
mDrawerAdapter.notifyDataSetChanged();
}
}
}
}
@@ -1037,13 +1031,14 @@ public class FavoritesScene extends BaseScene implements
gidArray[i] = gi.gid;
tokenArray[i] = gi.token;
}
List<GalleryInfo> modifyGiListBackup = new ArrayList<>(mModifyGiList);
mModifyGiList.clear();
EhRequest request = new EhRequest();
request.setMethod(EhClient.METHOD_ADD_FAVORITES_RANGE);
request.setCallback(new AddFavoritesListener(getContext(),
activity.getStageId(), getTag(),
taskId, mUrlBuilder.getKeyword()));
taskId, mUrlBuilder.getKeyword(), modifyGiListBackup));
request.setArgs(gidArray, tokenArray, mModifyFavCat);
mClient.execute(request);
} else {
@@ -1143,12 +1138,14 @@ public class FavoritesScene extends BaseScene implements
private final int mTaskId;
private final String mKeyword;
private final List<GalleryInfo> mBackup;
public AddFavoritesListener(Context context, int stageId,
String sceneTag, int taskId, String keyword) {
private AddFavoritesListener(Context context, int stageId,
String sceneTag, int taskId, String keyword, List<GalleryInfo> backup) {
super(context, stageId, sceneTag);
mTaskId = taskId;
mKeyword = keyword;
mBackup = backup;
}
@Override
@@ -1161,6 +1158,10 @@ public class FavoritesScene extends BaseScene implements
@Override
public void onFailure(Exception e) {
// TODO It's a failure, add all of backup back to db.
// But how to known which one is failed?
EhDB.putLocalFavorites(mBackup);
FavoritesScene scene = getScene();
if (scene != null) {
scene.onGetFavoritesLocal(mKeyword, mTaskId);
@@ -1183,7 +1184,7 @@ public class FavoritesScene extends BaseScene implements
private final boolean mLocal;
private final String mKeyword;
public GetFavoritesListener(Context context, int stageId,
private GetFavoritesListener(Context context, int stageId,
String sceneTag, int taskId, boolean local, String keyword) {
super(context, stageId, sceneTag);
mTaskId = taskId;
@@ -1195,6 +1196,7 @@ public class FavoritesScene extends BaseScene implements
public void onSuccess(FavoritesParser.Result result) {
// Put fav cat
Settings.putFavCat(result.catArray);
Settings.putFavCount(result.countArray);
FavoritesScene scene = getScene();
if (scene != null) {
if (mLocal) {
@@ -27,8 +27,8 @@ import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hippo.drawable.TriangleDrawable;
import com.hippo.easyrecyclerview.MarginItemDecoration;
import com.hippo.ehviewer.R;
@@ -38,7 +38,7 @@ import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.widget.TileThumb;
import com.hippo.widget.recyclerview.AutoStaggeredGridLayoutManager;
import com.hippo.yorozuya.ViewUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -59,6 +59,8 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> {
private final int mPaddingTopSB;
private MarginItemDecoration mListDecoration;
private MarginItemDecoration mGirdDecoration;
private final int mListThumbWidth;
private final int mListThumbHeight;
private int mType = TYPE_INVALID;
public GalleryAdapter(@NonNull LayoutInflater inflater, @NonNull Resources resources,
@@ -72,6 +74,11 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> {
mRecyclerView.setAdapter(this);
mRecyclerView.setLayoutManager(mLayoutManager);
View calculator = inflater.inflate(R.layout.item_gallery_list_thumb_height, null);
ViewUtils.measureView(calculator, 1024, ViewGroup.LayoutParams.WRAP_CONTENT);
mListThumbHeight = calculator.getMeasuredHeight();
mListThumbWidth = mListThumbHeight * 2 / 3;
setType(type);
}
@@ -147,7 +154,17 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> {
layoutId = R.layout.item_gallery_grid;
break;
}
return new GalleryHolder(mInflater.inflate(layoutId, parent, false));
GalleryHolder holder = new GalleryHolder(mInflater.inflate(layoutId, parent, false));
if (viewType == TYPE_LIST) {
ViewGroup.LayoutParams lp = holder.thumb.getLayoutParams();
lp.width = mListThumbWidth;
lp.height = mListThumbHeight;
holder.thumb.setLayoutParams(lp);
}
return holder;
}
@Override
@@ -179,6 +196,17 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> {
category.setBackgroundColor(EhUtils.getCategoryColor(gi.category));
}
holder.posted.setText(gi.posted);
if (gi.pages == 0 || !Settings.getShowGalleryPages()) {
holder.pages.setText(null);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) holder.simpleLanguage.getLayoutParams();
lp.addRule(RelativeLayout.LEFT_OF, 0);
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
} else {
holder.pages.setText(Integer.toString(gi.pages) + "P");
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) holder.simpleLanguage.getLayoutParams();
lp.addRule(RelativeLayout.LEFT_OF, R.id.pages);
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
}
holder.simpleLanguage.setText(gi.simpleLanguage);
break;
}
@@ -51,7 +51,7 @@ import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.hippo.android.resource.AttrResources;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.LinearDividerItemDecoration;
import com.hippo.ehviewer.EhApplication;
@@ -69,6 +69,7 @@ import com.hippo.scene.SceneFragment;
import com.hippo.text.Html;
import com.hippo.text.URLImageGetter;
import com.hippo.util.DrawableManager;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.ReadableTime;
import com.hippo.util.TextUrl;
import com.hippo.view.ViewTransition;
@@ -76,16 +77,15 @@ import com.hippo.widget.FabLayout;
import com.hippo.widget.LinkifyTextView;
import com.hippo.widget.ObservedTextView;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.SimpleAnimatorListener;
import com.hippo.yorozuya.StringUtils;
import com.hippo.yorozuya.ViewUtils;
import com.hippo.yorozuya.collect.IntList;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Assert;
public final class GalleryCommentsScene extends ToolbarScene
implements EasyRecyclerView.OnItemClickListener,
@@ -190,7 +190,7 @@ public final class GalleryCommentsScene extends ToolbarScene
mFab = (FloatingActionButton) ViewUtils.$$(view, R.id.fab);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Resources resources = context.getResources();
int paddingBottomFab = resources.getDimensionPixelOffset(R.dimen.gallery_padding_bottom_fab);
@@ -203,11 +203,11 @@ public final class GalleryCommentsScene extends ToolbarScene
mRecyclerView.setLayoutManager(new LinearLayoutManager(context,
LinearLayoutManager.VERTICAL, false));
LinearDividerItemDecoration decoration = new LinearDividerItemDecoration(
LinearDividerItemDecoration.VERTICAL, context.getResources().getColor(R.color.divider),
LinearDividerItemDecoration.VERTICAL, AttrResources.getAttrColor(context, R.attr.dividerColor),
LayoutUtils.dp2pix(context, 1));
decoration.setShowLastDivider(true);
mRecyclerView.addItemDecoration(decoration);
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, !AttrResources.getAttrBoolean(context, R.attr.isLightTheme)));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setOnItemClickListener(this);
mRecyclerView.setPadding(mRecyclerView.getPaddingLeft(), mRecyclerView.getPaddingTop(),
@@ -320,7 +320,7 @@ public final class GalleryCommentsScene extends ToolbarScene
rv.setAdapter(new RecyclerView.Adapter<InfoHolder>() {
@Override
public InfoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new InfoHolder(inflater.inflate(R.layout.item_favorite_info_data, parent, false));
return new InfoHolder(inflater.inflate(R.layout.item_drawer_favorites, parent, false));
}
@Override
@@ -336,11 +336,11 @@ public final class GalleryCommentsScene extends ToolbarScene
});
rv.setLayoutManager(new LinearLayoutManager(context));
LinearDividerItemDecoration decoration = new LinearDividerItemDecoration(
LinearDividerItemDecoration.VERTICAL, context.getResources().getColor(R.color.divider),
LinearDividerItemDecoration.VERTICAL, AttrResources.getAttrColor(context, R.attr.dividerColor),
LayoutUtils.dp2pix(context, 1));
decoration.setPadding(ResourcesUtils.getAttrDimensionPixelOffset(context, R.attr.dialogPreferredPadding));
rv.addItemDecoration(decoration);
rv.setSelector(Ripple.generateRippleDrawable(context, false));
rv.setSelector(Ripple.generateRippleDrawable(context, !AttrResources.getAttrBoolean(context, R.attr.isLightTheme)));
rv.setClipToPadding(false);
builder.setView(rv).show();
}
@@ -454,6 +454,10 @@ public final class GalleryCommentsScene extends ToolbarScene
.setDuration(300L).setListener(new SimpleAnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
if (null == mFab || null == mEditPanel) {
return;
}
mFab.setVisibility(View.INVISIBLE);
mEditPanel.setVisibility(View.VISIBLE);
int halfW = mEditPanel.getWidth() / 2;
@@ -497,6 +501,10 @@ public final class GalleryCommentsScene extends ToolbarScene
animator.addListener(new SimpleAnimatorListener() {
@Override
public void onAnimationEnd(Animator a) {
if (null == mFab || null == mEditPanel) {
return;
}
mEditPanel.setVisibility(View.GONE);
mFab.setVisibility(View.VISIBLE);
int fabStartX = mEditPanel.getLeft() + (mEditPanel.getWidth() / 2) - (mFab.getWidth() / 2);
@@ -609,7 +617,7 @@ public final class GalleryCommentsScene extends ToolbarScene
public CommentAdapter() {
mInflater = getLayoutInflater2();
AssertUtils.assertNotNull(mInflater);
Assert.assertNotNull(mInflater);
}
@Override
@@ -627,7 +635,7 @@ public final class GalleryCommentsScene extends ToolbarScene
SpannableString ss = new SpannableString(scoreString);
ss.setSpan(new RelativeSizeSpan(0.8f), 0, scoreString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new StyleSpan(Typeface.BOLD), 0, scoreString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.secondary_text_default_light))
ss.setSpan(new ForegroundColorSpan(AttrResources.getAttrColor(context, android.R.attr.textColorSecondary))
, 0, scoreString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.append(" ").append(ss);
}
@@ -728,7 +736,7 @@ public final class GalleryCommentsScene extends ToolbarScene
@Override
public void onFailure(Exception e) {
showTip(R.string.comment_failed, LENGTH_SHORT);
showTip(getContent().getString(R.string.comment_failed) + "\n" + ExceptionUtils.getReadableString(e), LENGTH_SHORT);
}
@Override
@@ -53,7 +53,7 @@ import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.hippo.android.resource.AttrResources;
import com.hippo.beerbelly.BeerBelly;
import com.hippo.drawable.RoundSideRectDrawable;
import com.hippo.ehviewer.AppConfig;
@@ -74,6 +74,7 @@ import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.data.GalleryTagGroup;
import com.hippo.ehviewer.client.data.ListUrlBuilder;
import com.hippo.ehviewer.client.data.PreviewSet;
import com.hippo.ehviewer.client.exception.NoHAtHClientException;
import com.hippo.ehviewer.client.parser.RateGalleryParser;
import com.hippo.ehviewer.dao.DownloadInfo;
import com.hippo.ehviewer.dao.Filter;
@@ -81,6 +82,7 @@ import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.ehviewer.ui.GalleryActivity;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.ehviewer.ui.annotation.WholeLifeCircle;
import com.hippo.ehviewer.widget.GalleryRatingBar;
import com.hippo.reveal.ViewAnimationUtils;
import com.hippo.ripple.Ripple;
import com.hippo.scene.Announcer;
@@ -98,13 +100,12 @@ import com.hippo.widget.AutoWrapLayout;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.ObservedTextView;
import com.hippo.widget.ProgressView;
import com.hippo.widget.ProgressiveRatingBar;
import com.hippo.widget.SimpleGridAutoSpanLayout;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.IntIdGenerator;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.ViewUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
@@ -112,6 +113,7 @@ import java.io.OutputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
import junit.framework.Assert;
public class GalleryDetailScene extends BaseScene implements View.OnClickListener,
com.hippo.ehviewer.download.DownloadManager.DownloadInfoListener,
@@ -201,6 +203,8 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
@Nullable
private TextView mTorrent;
@Nullable
private TextView mArchive;
@Nullable
private TextView mShare;
@Nullable
private TextView mRate;
@@ -245,10 +249,13 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
@Nullable
private GalleryDetail mGalleryDetail;
private int mRequestId;
private int mRequestId = IntIdGenerator.INVALID_ID;
private Pair<String, String>[] mTorrentList;
private String mArchiveFormParamOr;
private Pair<String, String>[] mArchiveList;
@State
private int mState = STATE_INIT;
@@ -400,7 +407,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
long gid = getGid();
if (gid != -1) {
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
mDownloadState = EhApplication.getDownloadManager(context).getDownloadState(gid);
} else {
mDownloadState = DownloadInfo.STATE_INVALID;
@@ -415,13 +422,14 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mViewTransition = new ViewTransition(mainView, progressView, mTip);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_weird_face);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
mTip.setCompoundDrawables(null, drawable, null, null);
mTip.setOnClickListener(this);
boolean isDarkTheme = !AttrResources.getAttrBoolean(context, R.attr.isLightTheme);
mHeader = ViewUtils.$$(mainView, R.id.header);
mColorBg = ViewUtils.$$(mHeader, R.id.color_bg);
mThumb = (LoadImageView) ViewUtils.$$(mHeader, R.id.thumb);
@@ -432,9 +440,9 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mActionGroup = (ViewGroup) ViewUtils.$$(mHeader, R.id.action_card);
mDownload = (TextView) ViewUtils.$$(mActionGroup, R.id.download);
mRead = ViewUtils.$$(mActionGroup, R.id.read);
Ripple.addRipple(mOtherActions, false);
Ripple.addRipple(mDownload, false);
Ripple.addRipple(mRead, false);
Ripple.addRipple(mOtherActions, isDarkTheme);
Ripple.addRipple(mDownload, isDarkTheme);
Ripple.addRipple(mRead, isDarkTheme);
mUploader.setOnClickListener(this);
mCategory.setOnClickListener(this);
mOtherActions.setOnClickListener(this);
@@ -453,7 +461,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mSize = (TextView) ViewUtils.$$(mInfo, R.id.size);
mPosted = (TextView) ViewUtils.$$(mInfo, R.id.posted);
mFavoredTimes = (TextView) ViewUtils.$$(mInfo, R.id.favoredTimes);
Ripple.addRipple(mInfo, false);
Ripple.addRipple(mInfo, isDarkTheme);
mInfo.setOnClickListener(this);
mActions = ViewUtils.$$(belowHeader, R.id.actions);
@@ -463,18 +471,21 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mHeart = (TextView) ViewUtils.$$(mHeartGroup, R.id.heart);
mHeartOutline = (TextView) ViewUtils.$$(mHeartGroup, R.id.heart_outline);
mTorrent = (TextView) ViewUtils.$$(mActions, R.id.torrent);
mArchive = (TextView) ViewUtils.$$(mActions, R.id.archive);
mShare = (TextView) ViewUtils.$$(mActions, R.id.share);
mRate = (TextView) ViewUtils.$$(mActions, R.id.rate);
mSimilar = (TextView) ViewUtils.$$(mActions, R.id.similar);
mSearchCover = (TextView) ViewUtils.$$(mActions, R.id.search_cover);
Ripple.addRipple(mHeartGroup, false);
Ripple.addRipple(mTorrent, false);
Ripple.addRipple(mShare, false);
Ripple.addRipple(mRate, false);
Ripple.addRipple(mSimilar, false);
Ripple.addRipple(mSearchCover, false);
Ripple.addRipple(mHeartGroup, isDarkTheme);
Ripple.addRipple(mTorrent, isDarkTheme);
Ripple.addRipple(mArchive, isDarkTheme);
Ripple.addRipple(mShare, isDarkTheme);
Ripple.addRipple(mRate, isDarkTheme);
Ripple.addRipple(mSimilar, isDarkTheme);
Ripple.addRipple(mSearchCover, isDarkTheme);
mHeartGroup.setOnClickListener(this);
mTorrent.setOnClickListener(this);
mArchive.setOnClickListener(this);
mShare.setOnClickListener(this);
mRate.setOnClickListener(this);
mSimilar.setOnClickListener(this);
@@ -486,13 +497,13 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mComments = (LinearLayout) ViewUtils.$$(belowHeader, R.id.comments);
mCommentsText = (TextView) ViewUtils.$$(mComments, R.id.comments_text);
Ripple.addRipple(mComments, false);
Ripple.addRipple(mComments, isDarkTheme);
mComments.setOnClickListener(this);
mPreviews = ViewUtils.$$(belowHeader, R.id.previews);
mGridLayout = (SimpleGridAutoSpanLayout) ViewUtils.$$(mPreviews, R.id.grid_layout);
mPreviewText = (TextView) ViewUtils.$$(mPreviews, R.id.preview_text);
Ripple.addRipple(mPreviews, false);
Ripple.addRipple(mPreviews, isDarkTheme);
mPreviews.setOnClickListener(this);
mProgress = ViewUtils.$$(mainView, R.id.progress);
@@ -531,7 +542,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
super.onDestroyView();
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
EhApplication.getDownloadManager(context).removeDownloadInfoListener(this);
mTip = null;
@@ -563,6 +574,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mHeart = null;
mHeartOutline = null;
mTorrent = null;
mArchive = null;
mShare = null;
mRate = null;
mSimilar = null;
@@ -587,7 +599,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
private boolean prepareData() {
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
if (mGalleryDetail != null) {
return true;
@@ -646,6 +658,8 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
setActionDrawable(mHeartOutline, heartOutline);
Drawable torrent = DrawableManager.getDrawable(context, R.drawable.v_utorrent_primary_x48);
setActionDrawable(mTorrent, torrent);
Drawable archive = DrawableManager.getDrawable(context, R.drawable.v_archive_primary_x48);
setActionDrawable(mArchive, archive);
Drawable share = DrawableManager.getDrawable(context, R.drawable.v_share_primary_x48);
setActionDrawable(mShare, share);
Drawable rate = DrawableManager.getDrawable(context, R.drawable.v_thumb_up_primary_x48);
@@ -709,7 +723,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
if ((oldState == STATE_INIT || oldState == STATE_FAILED || oldState == STATE_REFRESH) &&
(state == STATE_NORMAL || state == STATE_REFRESH_HEADER)) {
(state == STATE_NORMAL || state == STATE_REFRESH_HEADER) && AttrResources.getAttrBoolean(getContext2(), R.attr.isLightTheme)) {
if (!createCircularReveal()) {
SimpleHandler.getInstance().post(new Runnable() {
@Override
@@ -751,6 +765,11 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
if (gd.isFavorited || EhDB.containLocalFavorites(gd.gid)) {
mHeart.setVisibility(View.VISIBLE);
if (gd.favoriteName == null) {
mHeart.setText(R.string.local_favorites);
} else {
mHeart.setText(gd.favoriteName);
}
mHeartOutline.setVisibility(View.GONE);
} else {
mHeart.setVisibility(View.GONE);
@@ -770,7 +789,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
Resources resources = getResources2();
AssertUtils.assertNotNull(resources);
Assert.assertNotNull(resources);
mThumb.load(EhCacheKeyFactory.getThumbKey(gd.gid), gd.thumb);
mTitle.setText(EhUtils.getSuitableTitle(gd));
@@ -815,8 +834,8 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mNoTags.setVisibility(View.GONE);
}
int colorTag = resources.getColor(R.color.colorPrimary);
int colorName = resources.getColor(R.color.purple_a400);
int colorTag = AttrResources.getAttrColor(context, R.attr.tagBackgroundColor);
int colorName = AttrResources.getAttrColor(context, R.attr.tagGroupBackgroundColor);
for (GalleryTagGroup tg : tagGroups) {
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.gallery_tag_group, mTags, false);
ll.setOrientation(LinearLayout.HORIZONTAL);
@@ -946,7 +965,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
private String getAllRatingText(float rating, int ratingCount) {
Resources resources = getResources2();
AssertUtils.assertNotNull(resources);
Assert.assertNotNull(resources);
return resources.getString(R.string.rating_text, getRatingText(rating, resources), rating, ratingCount);
}
@@ -969,7 +988,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
PopupMenu popup = new PopupMenu(context, mOtherActions, Gravity.TOP);
mPopupMenu = popup;
popup.getMenuInflater().inflate(R.menu.scene_gallery_detail, popup.getMenu());
@@ -1165,6 +1184,21 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
.show();
helper.setDialog(dialog, mGalleryDetail.torrentUrl);
}
} else if (mArchive == v) {
if (mGalleryDetail == null) {
return;
}
if (mGalleryDetail.apiUid < 0) {
showTip(R.string.sign_in_first, LENGTH_SHORT);
return;
}
ArchiveListDialogHelper helper = new ArchiveListDialogHelper();
Dialog dialog = new AlertDialog.Builder(context)
.setTitle(R.string.dialog_archive_title)
.setView(R.layout.dialog_archive_list)
.setOnDismissListener(helper)
.show();
helper.setDialog(dialog, mGalleryDetail.archiveUrl);
} else if (mRate == v) {
if (mGalleryDetail == null) {
return;
@@ -1503,11 +1537,19 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
private void onModifyFavoritesSuccess(boolean addOrRemove) {
mModifingFavorites = false;
if (mGalleryDetail != null) {
mGalleryDetail.isFavorited = !addOrRemove;
mGalleryDetail.isFavorited = !addOrRemove && mGalleryDetail.favoriteName != null;
updateFavoriteDrawable();
}
}
private void onModifyFavoritesFailure(boolean addOrRemove) {
mModifingFavorites = false;
}
private void onModifyFavoritesCancel(boolean addOrRemove) {
mModifingFavorites = false;
}
private class ModifyFavoritesListener extends EhCallback<GalleryDetailScene, Void> {
private final boolean mAddOrRemove;
@@ -1534,6 +1576,44 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
public void onFailure(Exception e) {
showTip(mAddOrRemove ? R.string.remove_from_favorite_failure :
R.string.add_to_favorite_failure, LENGTH_SHORT);
GalleryDetailScene scene = getScene();
if (scene != null) {
scene.onModifyFavoritesFailure(mAddOrRemove);
}
}
@Override
public void onCancel() {
GalleryDetailScene scene = getScene();
if (scene != null) {
scene.onModifyFavoritesCancel(mAddOrRemove);
}
}
@Override
public boolean isInstance(SceneFragment scene) {
return scene instanceof GalleryDetailScene;
}
}
private class DownloadArchiveListener extends EhCallback<GalleryDetailScene, Void> {
public DownloadArchiveListener(Context context, int stageId, String sceneTag) {
super(context, stageId, sceneTag);
}
@Override
public void onSuccess(Void result) {
showTip(R.string.download_archive_started, LENGTH_SHORT);
}
@Override
public void onFailure(Exception e) {
if (e instanceof NoHAtHClientException) {
showTip(R.string.download_archive_failure_no_hath, LENGTH_SHORT);
} else {
showTip(R.string.download_archive_failure, LENGTH_SHORT);
}
}
@Override
@@ -1545,6 +1625,121 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
}
private class ArchiveListDialogHelper implements AdapterView.OnItemClickListener,
DialogInterface.OnDismissListener, EhClient.Callback<Pair<String, Pair<String, String>[]>> {
@Nullable
private ProgressView mProgressView;
@Nullable
private TextView mErrorText;
@Nullable
private ListView mListView;
@Nullable
private EhRequest mRequest;
@Nullable
private Dialog mDialog;
public void setDialog(@Nullable Dialog dialog, String url) {
mDialog = dialog;
mProgressView = (ProgressView) ViewUtils.$$(dialog, R.id.progress);
mErrorText = (TextView) ViewUtils.$$(dialog, R.id.text);
mListView = (ListView) ViewUtils.$$(dialog, R.id.list_view);
mListView.setOnItemClickListener(this);
Context context = getContext2();
if (context != null) {
if (mArchiveList == null) {
mErrorText.setVisibility(View.GONE);
mListView.setVisibility(View.GONE);
mRequest = new EhRequest().setMethod(EhClient.METHOD_ARCHIVE_LIST)
.setArgs(url)
.setCallback(this);
EhApplication.getEhClient(context).execute(mRequest);
} else {
bind(mArchiveList);
}
}
}
private void bind(Pair<String, String>[] data) {
if (null == mDialog || null == mProgressView || null == mErrorText || null == mListView) {
return;
}
if (0 == data.length) {
mProgressView.setVisibility(View.GONE);
mErrorText.setVisibility(View.VISIBLE);
mListView.setVisibility(View.GONE);
mErrorText.setText(R.string.no_archives);
} else {
String[] nameArray = new String[data.length];
for (int i = 0, n = data.length; i < n; i++) {
nameArray[i] = data[i].second;
}
mProgressView.setVisibility(View.GONE);
mErrorText.setVisibility(View.GONE);
mListView.setVisibility(View.VISIBLE);
mListView.setAdapter(new ArrayAdapter<>(mDialog.getContext(), R.layout.item_select_dialog, nameArray));
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Context context = getContext2();
MainActivity activity = getActivity2();
if (null != context && null != activity && null != mArchiveList && position < mArchiveList.length) {
String res = mArchiveList[position].first;
EhRequest request = new EhRequest();
request.setMethod(EhClient.METHOD_DOWNLOAD_ARCHIVE);
request.setArgs(mGalleryDetail.gid, mGalleryDetail.token, mArchiveFormParamOr, res);
request.setCallback(new DownloadArchiveListener(context, activity.getStageId(), getTag()));
EhApplication.getEhClient(context).execute(request);
}
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
}
}
@Override
public void onDismiss(DialogInterface dialog) {
if (mRequest != null) {
mRequest.cancel();
mRequest = null;
}
mDialog = null;
mProgressView = null;
mErrorText = null;
mListView = null;
}
@Override
public void onSuccess(Pair<String, Pair<String, String>[]> result) {
if (mRequest != null) {
mRequest = null;
mArchiveFormParamOr = result.first;
mArchiveList = result.second;
bind(result.second);
}
}
@Override
public void onFailure(Exception e) {
mRequest = null;
Context context = getContext2();
if (null != context && null != mProgressView && null != mErrorText && null != mListView) {
mProgressView.setVisibility(View.GONE);
mErrorText.setVisibility(View.VISIBLE);
mListView.setVisibility(View.GONE);
mErrorText.setText(ExceptionUtils.getReadableString(e));
}
}
@Override
public void onCancel() { mRequest = null; }
}
private class TorrentListDialogHelper implements AdapterView.OnItemClickListener,
DialogInterface.OnDismissListener, EhClient.Callback<Pair<String, String>[]> {
@@ -1611,7 +1806,8 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
String name = mTorrentList[position].second;
// Use system download service
DownloadManager.Request r = new DownloadManager.Request(Uri.parse(url));
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, name + ".torrent");
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
FileUtils.sanitizeFilename(name + ".torrent"));
r.allowScanningByMediaScanner();
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
@@ -1706,17 +1902,17 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
}
private class RateDialogHelper implements ProgressiveRatingBar.OnUserRateListener,
private class RateDialogHelper implements GalleryRatingBar.OnUserRateListener,
DialogInterface.OnClickListener {
@Nullable
private ProgressiveRatingBar mRatingBar;
private GalleryRatingBar mRatingBar;
@Nullable
private TextView mRatingText;
public void setDialog(Dialog dialog, float rating) {
mRatingText = (TextView) ViewUtils.$$(dialog, R.id.rating_text);
mRatingBar = (ProgressiveRatingBar) ViewUtils.$$(dialog, R.id.rating_view);
mRatingBar = (GalleryRatingBar) ViewUtils.$$(dialog, R.id.rating_view);
mRatingText.setText(getRatingText(rating, getResources2()));
mRatingBar.setRating(rating);
mRatingBar.setOnUserRateListener(this);
@@ -32,6 +32,7 @@ class GalleryHolder extends RecyclerView.ViewHolder {
public final SimpleRatingView rating;
public final TextView category;
public final TextView posted;
public final TextView pages;
public final TextView simpleLanguage;
public GalleryHolder(View itemView) {
@@ -43,6 +44,7 @@ class GalleryHolder extends RecyclerView.ViewHolder {
rating = (SimpleRatingView) itemView.findViewById(R.id.rating);
category = (TextView) itemView.findViewById(R.id.category);
posted = (TextView) itemView.findViewById(R.id.posted);
pages = (TextView) itemView.findViewById(R.id.pages);
simpleLanguage = (TextView) itemView.findViewById(R.id.simple_language);
}
}
@@ -29,19 +29,19 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.hippo.android.resource.AttrResources;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.LinearDividerItemDecoration;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryDetail;
import com.hippo.ripple.Ripple;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ViewUtils;
import java.util.ArrayList;
import junit.framework.Assert;
public final class GalleryInfoScene extends ToolbarScene implements EasyRecyclerView.OnItemClickListener {
@@ -84,7 +84,7 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
}
Resources resources = getResources2();
AssertUtils.assertNotNull(resources);
Assert.assertNotNull(resources);
mKeys.add(resources.getString(R.string.header_key));
mValues.add(resources.getString(R.string.header_value));
mKeys.add(resources.getString(R.string.key_gid));
@@ -127,6 +127,8 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
mValues.add(Integer.toString(gd.torrentCount));
mKeys.add(resources.getString(R.string.key_torrent_url));
mValues.add(gd.torrentUrl);
mKeys.add(resources.getString(R.string.favorite_name));
mValues.add(gd.favoriteName);
}
protected void onInit() {
@@ -155,18 +157,19 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
View view = inflater.inflate(R.layout.scene_gallery_info, container, false);
Context context = getContext2();
AssertUtils.assertNotNull(context);
Assert.assertNotNull(context);
mRecyclerView = (EasyRecyclerView) ViewUtils.$$(view, R.id.recycler_view);
InfoAdapter adapter = new InfoAdapter();
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
LinearDividerItemDecoration decoration = new LinearDividerItemDecoration(
LinearDividerItemDecoration.VERTICAL, context.getResources().getColor(R.color.divider),
LinearDividerItemDecoration.VERTICAL,
AttrResources.getAttrColor(context, R.attr.dividerColor),
LayoutUtils.dp2pix(context, 1));
decoration.setPadding(context.getResources().getDimensionPixelOffset(R.dimen.keyline_margin));
mRecyclerView.addItemDecoration(decoration);
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, !AttrResources.getAttrBoolean(context, R.attr.isLightTheme)));
mRecyclerView.setClipToPadding(false);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setOnItemClickListener(this);
@@ -196,6 +199,12 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
if (null != context && 0 != position && null != mValues) {
ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setPrimaryClip(ClipData.newPlainText(null, mValues.get(position)));
if (position == 3) {
// Save it to avoid detect the gallery
Settings.putClipboardTextHashCode(mValues.get(position).hashCode());
}
showTip(R.string.copied_to_clipboard, LENGTH_SHORT);
return true;
} else {
@@ -230,7 +239,7 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
public InfoAdapter() {
mInflater = getLayoutInflater2();
AssertUtils.assertNotNull(mInflater);
Assert.assertNotNull(mInflater);
}
@Override
Loaded 100 of 373 files, more files were not shown because too many files have changed in this diff. Show more