Compare commits

...
375 Commits
Author SHA1 Message Date
seven332 4a5a426fd3 1.3.2 2018-12-20 20:11:48 +08:00
seven332 06adf8594c Fix HistoryScene crash
https://github.com/h6ah4i/android-advancedrecyclerview/issues/315
2018-12-20 19:39:48 +08:00
seven332 1ac43e6293 1.3.1 2018-12-20 18:21:28 +08:00
seven332 ceeb84812b Only ignore a special version update 2018-12-20 18:16:37 +08:00
seven332 bfd85e9bc7 Catch Throwable instead of Exception 2018-12-20 16:02:56 +08:00
seven332 8c3796605e Add scene_view action 2018-12-20 15:47:12 +08:00
seven332 3214bae157 Fix NullPointerException in ClearTask.clearFile() 2018-12-20 11:01:03 +08:00
seven332 a5b178df49 Returns null if IndexOutOfBoundsException in ContentHelper 2018-12-20 10:58:48 +08:00
seven332 c2a93f2ce4 Avoid NullPointerException in SpiderWorker.downloadImage() 2018-12-20 10:36:52 +08:00
seven332 257758b27d Avoid FingerprintManager.hasEnrolledFingerprints() crash on samsung devices 2018-12-20 10:18:32 +08:00
seven332 2681e4a6e6 Check FingerprintManager null 2018-12-19 22:17:51 +08:00
seven332 722653ac46 Update advrecyclerview 2018-12-19 20:02:27 +08:00
seven332 cb706941c5 Avoid TextInputEditText crash on some Meizu devices 2018-12-19 19:39:58 +08:00
seven332 195e9a5655 Revert "Set hint to TextInputEditText instead of TextInputLayout"
This reverts commit 405655d
2018-12-19 19:37:36 +08:00
seven332 ed2043ab7a Update Image 2018-12-19 19:16:09 +08:00
seven332 405655d0e2 Set hint to TextInputEditText instead of TextInputLayout 2018-12-19 16:03:02 +08:00
seven332 0cead11180 Update UniFile 2018-12-19 15:49:19 +08:00
seven332 141ab73089 1.3.0 2018-12-19 14:21:59 +08:00
seven332 7c349153de Fix fingerprint icon 2018-12-19 13:28:01 +08:00
seven332 168b701cca Remove G+ from readme 2018-12-19 12:49:04 +08:00
seven332 0b67e685d2 Print an error 2018-12-19 11:06:31 +08:00
seven332 741bb10a1c Allow http protocol 2018-12-19 11:06:01 +08:00
seven332 829591229d Update okhttp 2018-12-19 11:05:02 +08:00
seven332 cbed5ee8cb Add the declaration 2018-12-18 22:27:04 +08:00
seven332 a2db9038e3 Use sad pandroid icon instead of weird face icon 2018-12-18 17:44:16 +08:00
seven332 14328eaf83 Move webp images to v15 folder 2018-12-18 16:58:54 +08:00
seven332 a11fb869e2 Don't private classes or methods of support libraries 2018-12-18 16:50:15 +08:00
seven332 1285abdf71 Fix string resources 2018-12-18 15:33:53 +08:00
seven332 f0fa226b16 Use custom AssertUtils instead of Assert 2018-12-18 15:22:32 +08:00
seven332 88aebbd075 Add USE_BIOMETRIC and FOREGROUND_SERVICE permissions 2018-12-18 15:20:13 +08:00
seven332 2c08a7b56f Target SDK version 28 2018-12-18 15:19:22 +08:00
seven332 561e396c97 Use Firebase Crashlytics 2018-12-18 14:43:38 +08:00
seven332 f8676b71dc "Google Analytics" to "Google Analytics for Firebase" 2018-12-18 13:17:32 +08:00
seven332 259550e5cc Close #490, keep downloading after removing current download item 2018-12-17 17:02:19 +08:00
seven332 478e53ab96 Add download label delete button 2018-12-17 14:00:09 +08:00
seven332 286b39e679 Add quick search delete button 2018-12-17 13:44:32 +08:00
seven332 af771c7086 Remove specify gallery search 2018-12-16 02:08:56 +08:00
seven332 24d386da44 Don't scroll to top after delete a suggestion 2018-12-15 04:11:47 +08:00
seven332 419405f4e2 Apply theme color to navigation bar 2018-12-14 20:20:22 +08:00
seven332 e8de8ac5c8 Show clipboard url tip in Snackbar 2018-12-14 19:41:01 +08:00
seven332 934ec87390 Add gallery suggestion to search bar 2018-12-14 18:59:22 +08:00
seven332 46bd8e4297 Scroll suggestion list to top every time 2018-12-14 15:59:52 +08:00
seven332 70ceb83205 Increase suggestion count 2018-12-14 15:49:11 +08:00
seven332 0553fda3fa Long click category to set other categories to the opposite 2018-12-14 13:40:47 +08:00
seven332 b5f36dafdc Exclude solid archives 2018-12-13 23:29:48 +08:00
seven332 77fd0eb73e Update libraries 2018-12-13 21:50:35 +08:00
seven332 ff6b0bf01d Remove ZipGalleryProvider 2018-12-13 21:42:35 +08:00
seven332 6734ace077 Add ArchiveGalleryProvider 2018-12-13 15:15:39 +08:00
seven332 c013c82f90 Use NaturalComparator in DirGalleryProvider 2018-12-12 21:43:45 +08:00
seven332 618ca14eca Add NaturalComparator and PathNaturalComparator 2018-12-12 21:30:42 +08:00
seven332 700ebdfee3 Remove useless code 2018-12-11 09:55:31 +08:00
seven332 9899552e4b Close #488, detect gallery page url in clipboard 2018-12-04 21:45:22 +08:00
seven332 7104fddded GalleryPageUrlParser supports non-strict url 2018-12-04 21:27:37 +08:00
seven332 54f1c4806f GalleryDetailUrlParser supports non-strict url 2018-12-04 20:54:22 +08:00
UShimamura 9c66298cb8 Some little fixes 2018-11-29 21:57:35 +08:00
UShimamura bb266d46d3 Improved sentence to avoid ambiguity 2018-11-29 21:57:35 +08:00
UShimamura 8cd7d01e10 Add new translated strings 2018-11-29 21:57:35 +08:00
UShimamura 9692224dec Add new translated strings 2018-11-29 21:57:35 +08:00
UShimamura 41b4f00b91 Add translated strings 2018-11-29 21:57:35 +08:00
UShimamura 611a4c8853 Improve English strings. 2018-11-29 21:57:35 +08:00
UShimamura c8f1080b9e Update strings.xml
Error corrections
2018-11-24 11:53:04 +08:00
UShimamura 92ecf84c5e Update strings.xml
Polishing
2018-11-24 11:53:04 +08:00
UShimamura d9c0c80172 Update strings.xml
Grammar polishing
2018-11-24 11:53:04 +08:00
GUIHU 74a7b16252 Deleted wordy translations 2018-11-24 11:52:28 +08:00
GUIHU 5ccbeda6d5 Fixed incorrect spelled translations in values-zh-rTW 2018-11-24 11:52:28 +08:00
GUIHU 75a2be5d38 Translations polishing in values-zh-rTW 2018-11-24 11:52:28 +08:00
akazaa96 c5d5778961 Denmark strings.xml are missing a string argument 2018-11-19 21:35:04 +08:00
hbina4326 eb16df63e1 fixed french typo causing build failure 2018-11-16 14:08:38 +08:00
hzy980512 1bb2f6eb5f Update strings.xml 2018-11-05 14:54:24 +08:00
hzy980512 4a905a5226 Update strings.xml 2018-11-05 14:54:24 +08:00
hzy980512 fe60b26eec Update strings.xml 2018-11-05 14:54:24 +08:00
hzy980512 3b1028b9cc Add new translations. 2018-11-05 14:54:24 +08:00
hzy980512 36b7a6211e Update strings.xml 2018-11-05 14:54:24 +08:00
hzy980512 8cd89f8a06 Add new translations 2018-11-05 14:54:24 +08:00
hzy980512 b599f6e71c Update strings.xml 2018-11-05 14:54:24 +08:00
hzy980512 2e38237a99 Add new translations 2018-11-05 14:54:24 +08:00
seven332 d23c145790 Add shadow to adaptive icon 2018-11-03 20:26:57 +08:00
seven332 c3e0bbaa0a Exclude all google-services.json 2018-11-03 20:05:34 +08:00
seven332 4582556f65 Moved from Google Analytics to Firebase Analytics 2018-11-02 20:54:55 +08:00
seven332 e07316f25a Support mpv links 2018-10-30 18:34:26 +08:00
scese250 7379bdaa67 Translated new features to Spanish
And by the way, also I updated text.

btw thanks for add dark theme. 👍
2018-10-30 12:26:12 +08:00
seven332 c4519c5914 Fix missing gallery uploader 2018-10-29 20:30:06 +08:00
seven332 358d9861f5 Add changing theme shortcut to left drawer 2018-10-29 15:24:11 +08:00
seven332 bdf2df0ed1 Get simple language from tags 2018-10-29 13:53:11 +08:00
seven332 291a6515c1 Fix missing simple language 2018-10-29 11:38:20 +08:00
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
322 changed files with 12602 additions and 3628 deletions

No files matched your search

+4
View File
@@ -1,5 +1,9 @@
感谢您提交 Issue,请在提交前仔细阅读以下信息。
请在阅读完毕后,删除这些文字,并写下对该 Issue 的描述。
若您能熟练使用现代标准汉语,请务必使用该语言描述 Issue。
Issue 的内容仅可为
* Bug 反馈
* 功能申请
+2
View File
@@ -6,3 +6,5 @@
*.iml
.idea
/captures
release
google-services.json
+2
View File
@@ -1,3 +1,5 @@
[![Telegram](https://img.shields.io/badge/chat-Telegram-blue.svg)](https://t.me/ehviewer)
# EhViewer
![Icon](art/launcher_icon-web.png)
+69 -37
View File
@@ -1,31 +1,42 @@
import com.android.build.gradle.internal.tasks.DefaultAndroidTask
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'io.fabric'
apply plugin: 'android-chinese-string'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
compileSdkVersion 28
defaultConfig {
applicationId "com.hippo.ehviewer"
minSdkVersion 14
targetSdkVersion 25
versionCode 75
versionName "1.0.22"
targetSdkVersion 28
versionCode 89
versionName "1.3.2"
vectorDrawables.useSupportLibrary = true
resConfigs "zh", "zh-rCN", "zh-rHK", "zh-rTW",
"es"
"es", "ja", "ko", "fr", "de"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
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"'
}
}
@@ -42,7 +53,7 @@ task copyNotice(type: Copy) {
finalizedBy ":daogenerator:executeDaoGenerator"
}
tasks.withType(DefaultAndroidTask) {
tasks.withType(JavaCompile) {
task -> task.dependsOn copyNotice
}
@@ -51,32 +62,53 @@ clean {
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile "com.android.support:appcompat-v7:$supportLibrary"
compile "com.android.support:design:$supportLibrary"
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.5-eh'
compile 'com.github.seven332:drawerlayout:0.2.1'
compile 'com.github.seven332:easyrecyclerview:0.1.1'
compile 'com.github.seven332:glgallery:0.1.2'
compile 'com.github.seven332:glview:0.1.0'
compile 'com.github.seven332:glview-image:0.1.0'
compile 'com.github.seven332:hotspot:0.1.0'
compile 'com.github.seven332:image:0.1.12'
compile 'com.github.seven332:okhttp:3.5.0'
compile 'com.github.seven332:refreshlayout:0.1.0'
compile 'com.github.seven332:ripple:0.1.2'
compile 'com.github.seven332:streampipe:0.1.0'
compile 'com.github.seven332:tuxiang:0.1.2'
compile 'com.github.seven332:unifile:0.2.0'
compile 'com.github.seven332:yorozuya:0.1.2'
compile 'com.github.seven332:yorozuya-thread:0.1.1'
compile 'com.github.seven332:yorozuya-collect:0.1.4'
compile 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.9.2'
compile 'org.ccil.cowan.tagsoup:tagsoup:1.2.1'
compile 'org.greenrobot:greendao:2.2.0'
compile 'org.jsoup:jsoup:1.9.2'
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.google.firebase:firebase-core:16.0.6'
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.7'
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.commons-compress:android-lite:464e96d3b4'
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.junrar:android-lite:46ecc9630a'
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:a3571536be'
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.11.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.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:29266a3c7b'
exclude group: 'com.github.seven332', module: 'okhttp'
exclude group: 'com.squareup.okio', module: 'okio'
}
}
Binary file not shown.
+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>
+60 -9
View File
@@ -22,7 +22,9 @@
<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-permission android:name="android.permission.USE_BIOMETRIC"/>
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
@@ -34,7 +36,8 @@
android:theme="@style/AppTheme"
android:allowBackup="true"
android:fullBackupContent="@xml/backup_scheme"
android:largeHeap="true">
android:largeHeap="true"
android:networkSecurityConfig="@xml/network_security_config">
<activity
android:name="com.hippo.ehviewer.ui.MainActivity"
@@ -48,6 +51,9 @@
<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"/>
@@ -55,6 +61,7 @@
<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>
@@ -81,17 +88,41 @@
<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="file"/>
<data android:scheme="content"/>
<data android:host="*"/>
<data android:mimeType="application/octet-stream"/>
<data android:mimeType="application/7z"/>
<data android:mimeType="application/rar"/>
<data android:mimeType="application/zip"/>
<data android:mimeType="application/x-7z-compressed"/>
<data android:mimeType="application/x-rar-compressed"/>
<data android:mimeType="application/x-zip-compressed"/>
</intent-filter>
<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="file"/>
<data android:scheme="content"/>
<data android:host="*"/>
<data android:pathPattern=".*\\.7z"/>
<data android:pathPattern=".*\\.rar"/>
<data android:pathPattern=".*\\.zip"/>
</intent-filter>
<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="file"/>
<data android:scheme="content"/>
<data android:host="*"/>
<data android:mimeType="*/*"/>
<data android:pathPattern=".*\\.7z"/>
<data android:pathPattern=".*\\.rar"/>
<data android:pathPattern=".*\\.zip"/>
</intent-filter>
</activity>
@@ -99,45 +130,65 @@
<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:label="@string/download_service_label"/>
<provider
android:name="com.hippo.content.FileProvider"
android:authorities="com.hippo.ehviewer.fileprovider"
android:authorities="${applicationId}.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
@@ -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,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);
@@ -0,0 +1,180 @@
/*
* 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.drawable;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.graphics.drawable.DrawableCompat;
public class DrawableWrapper extends Drawable implements Drawable.Callback {
private Drawable mDrawable;
public DrawableWrapper(Drawable drawable) {
this.setWrappedDrawable(drawable);
}
public void draw(@NonNull Canvas canvas) {
this.mDrawable.draw(canvas);
}
protected void onBoundsChange(Rect bounds) {
this.mDrawable.setBounds(bounds);
}
public void setChangingConfigurations(int configs) {
this.mDrawable.setChangingConfigurations(configs);
}
public int getChangingConfigurations() {
return this.mDrawable.getChangingConfigurations();
}
public void setDither(boolean dither) {
this.mDrawable.setDither(dither);
}
public void setFilterBitmap(boolean filter) {
this.mDrawable.setFilterBitmap(filter);
}
public void setAlpha(int alpha) {
this.mDrawable.setAlpha(alpha);
}
public void setColorFilter(ColorFilter cf) {
this.mDrawable.setColorFilter(cf);
}
public boolean isStateful() {
return this.mDrawable.isStateful();
}
public boolean setState(@NonNull int[] stateSet) {
return this.mDrawable.setState(stateSet);
}
@NonNull
public int[] getState() {
return this.mDrawable.getState();
}
public void jumpToCurrentState() {
this.mDrawable.jumpToCurrentState();
}
@NonNull
public Drawable getCurrent() {
return this.mDrawable.getCurrent();
}
public boolean setVisible(boolean visible, boolean restart) {
return super.setVisible(visible, restart) || this.mDrawable.setVisible(visible, restart);
}
public int getOpacity() {
return this.mDrawable.getOpacity();
}
public Region getTransparentRegion() {
return this.mDrawable.getTransparentRegion();
}
public int getIntrinsicWidth() {
return this.mDrawable.getIntrinsicWidth();
}
public int getIntrinsicHeight() {
return this.mDrawable.getIntrinsicHeight();
}
public int getMinimumWidth() {
return this.mDrawable.getMinimumWidth();
}
public int getMinimumHeight() {
return this.mDrawable.getMinimumHeight();
}
public boolean getPadding(@NonNull Rect padding) {
return this.mDrawable.getPadding(padding);
}
public void invalidateDrawable(@NonNull Drawable who) {
this.invalidateSelf();
}
public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
this.scheduleSelf(what, when);
}
public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
this.unscheduleSelf(what);
}
protected boolean onLevelChange(int level) {
return this.mDrawable.setLevel(level);
}
public void setAutoMirrored(boolean mirrored) {
DrawableCompat.setAutoMirrored(this.mDrawable, mirrored);
}
public boolean isAutoMirrored() {
return DrawableCompat.isAutoMirrored(this.mDrawable);
}
public void setTint(int tint) {
DrawableCompat.setTint(this.mDrawable, tint);
}
public void setTintList(ColorStateList tint) {
DrawableCompat.setTintList(this.mDrawable, tint);
}
public void setTintMode(@NonNull PorterDuff.Mode tintMode) {
DrawableCompat.setTintMode(this.mDrawable, tintMode);
}
public void setHotspot(float x, float y) {
DrawableCompat.setHotspot(this.mDrawable, x, y);
}
public void setHotspotBounds(int left, int top, int right, int bottom) {
DrawableCompat.setHotspotBounds(this.mDrawable, left, top, right, bottom);
}
public Drawable getWrappedDrawable() {
return this.mDrawable;
}
public void setWrappedDrawable(Drawable drawable) {
if (this.mDrawable != null) {
this.mDrawable.setCallback(null);
}
this.mDrawable = drawable;
if (drawable != null) {
drawable.setCallback(this);
}
}
}
@@ -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);
@@ -20,7 +20,6 @@ import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.v7.graphics.drawable.DrawableWrapper;
import com.hippo.yorozuya.MathUtils;
@@ -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;
}
}
@@ -17,15 +17,32 @@
package com.hippo.ehviewer;
import android.content.Context;
import com.google.analytics.tracking.android.EasyTracker;
import android.os.Bundle;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.hippo.scene.SceneFragment;
public final class Analytics {
private static FirebaseAnalytics analytics;
private Analytics() {}
public static void start(Context context) {
EasyTracker.getInstance(context).set("&uid", Settings.getUserID());
analytics = FirebaseAnalytics.getInstance(context);
analytics.setUserId(Settings.getUserID());
}
public static boolean isEnabled() {
return analytics != null && Settings.getEnableAnalytics();
}
public static void onSceneView(SceneFragment scene) {
if (isEnabled()) {
Bundle bundle = new Bundle();
bundle.putString("scene_simple_class", scene.getClass().getSimpleName());
bundle.putString("scene_class", scene.getClass().getName());
analytics.logEvent("scene_view", bundle);
}
}
}
@@ -37,7 +37,6 @@ public class AppConfig {
private static final String DOWNLOAD = "download";
private static final String TEMP = "temp";
private static final String IMAGE = "image";
private static final String CRASH = "crash";
private static final String PARSE_ERROR = "parse_error";
private static final String LOGCAT = "logcat";
private static final String DATA = "data";
@@ -95,11 +94,6 @@ public class AppConfig {
return getDirInExternalAppDir(IMAGE);
}
@Nullable
public static File getExternalCrashDir() {
return getDirInExternalAppDir(CRASH);
}
@Nullable
public static File getExternalParseErrorDir() {
return getDirInExternalAppDir(PARSE_ERROR);
@@ -1,205 +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;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Debug;
import android.support.annotation.NonNull;
import com.hippo.scene.StageActivity;
import com.hippo.util.PackageUtils;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.OSUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
public final class Crash {
private Crash() {}
@NonNull
private static String avoidNull(String str) {
return null != str ? str : "null";
}
@SuppressWarnings("deprecation")
private static void collectInfo(Context context, FileWriter fw) throws IOException {
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = String.valueOf(pi.versionCode);
fw.write("======== PackageInfo ========\r\n");
fw.write("PackageName=");fw.write(pi.packageName);fw.write("\r\n");
fw.write("VersionName=");fw.write(versionName);fw.write("\r\n");
fw.write("VersionCode=");fw.write(versionCode);fw.write("\r\n");
String signature = PackageUtils.getSignature(context, pi.packageName);
fw.write("Signature=");fw.write(null != signature ? signature : "null");fw.write("\r\n");
fw.write("\r\n");
}
} catch (PackageManager.NameNotFoundException e) {
fw.write("======== PackageInfo ========\r\n");
fw.write("Can't get package information\r\n");
fw.write("\r\n");
}
// Runtime
String topActivityClazzName = "null";
String topSceneClazzName = "null";
try {
Activity topActivity = ((EhApplication) context.getApplicationContext()).getTopActivity();
if (null != topActivity) {
topActivityClazzName = topActivity.getClass().getName();
if (topActivity instanceof StageActivity) {
Class<?> clazz = ((StageActivity) topActivity).getTopSceneClass();
if (clazz != null) {
topSceneClazzName = clazz.getName();
}
}
}
} catch (Throwable e) {
// Ignore
}
fw.write("======== Runtime ========\r\n");
fw.write("TopActivity=");fw.write(avoidNull(topActivityClazzName));fw.write("\r\n");
fw.write("TopScene=");fw.write(avoidNull(topSceneClazzName));fw.write("\r\n");
fw.write("\r\n");
// Device info
fw.write("======== DeviceInfo ========\r\n");
fw.write("BOARD=");fw.write(Build.BOARD);fw.write("\r\n");
fw.write("BOOTLOADER=");fw.write(Build.BOOTLOADER);fw.write("\r\n");
fw.write("CPU_ABI=");fw.write(Build.CPU_ABI);fw.write("\r\n");
fw.write("CPU_ABI2=");fw.write(Build.CPU_ABI2);fw.write("\r\n");
fw.write("DEVICE=");fw.write(Build.DEVICE);fw.write("\r\n");
fw.write("DISPLAY=");fw.write(Build.DISPLAY);fw.write("\r\n");
fw.write("FINGERPRINT=");fw.write(Build.FINGERPRINT);fw.write("\r\n");
fw.write("HARDWARE=");fw.write(Build.HARDWARE);fw.write("\r\n");
fw.write("HOST=");fw.write(Build.HOST);fw.write("\r\n");
fw.write("ID=");fw.write(Build.ID);fw.write("\r\n");
fw.write("MANUFACTURER=");fw.write(Build.MANUFACTURER);fw.write("\r\n");
fw.write("MODEL=");fw.write(Build.MODEL);fw.write("\r\n");
fw.write("PRODUCT=");fw.write(Build.PRODUCT);fw.write("\r\n");
fw.write("RADIO=");fw.write(Build.getRadioVersion());fw.write("\r\n");
fw.write("SERIAL=");fw.write(Build.SERIAL);fw.write("\r\n");
fw.write("TAGS=");fw.write(Build.TAGS);fw.write("\r\n");
fw.write("TYPE=");fw.write(Build.TYPE);fw.write("\r\n");
fw.write("USER=");fw.write(Build.USER);fw.write("\r\n");
fw.write("CODENAME=");fw.write(Build.VERSION.CODENAME);fw.write("\r\n");
fw.write("INCREMENTAL=");fw.write(Build.VERSION.INCREMENTAL);fw.write("\r\n");
fw.write("RELEASE=");fw.write(Build.VERSION.RELEASE);fw.write("\r\n");
fw.write("SDK=");fw.write(Integer.toString(Build.VERSION.SDK_INT));fw.write("\r\n");
fw.write("MEMORY=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getAppAllocatedMemory(), false));fw.write("\r\n");
fw.write("MEMORY_NATIVE=");fw.write(FileUtils.humanReadableByteCount(Debug.getNativeHeapAllocatedSize(), false));fw.write("\r\n");
fw.write("MEMORY_MAX=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getAppMaxMemory(), false));fw.write("\r\n");
fw.write("MEMORY_TOTAL=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getTotalMemory(), false));fw.write("\r\n");
fw.write("\r\n");
}
public static void getThrowableInfo(Throwable t, FileWriter fw) {
PrintWriter printWriter = new PrintWriter(fw);
t.printStackTrace(printWriter);
Throwable cause = t.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
}
public static void saveCrashInfo2File(Context context, Throwable ex) {
File dir = AppConfig.getExternalCrashDir();
if (dir == null) {
return;
}
String nowString = ReadableTime.getFilenamableTime(System.currentTimeMillis());
String fileName = "crash-" + nowString + ".log";
File file = new File(dir, fileName);
FileWriter fw = null;
try {
fw = new FileWriter(file);
fw.write("TIME=");fw.write(nowString);fw.write("\r\n");
fw.write("\r\n");
collectInfo(context, fw);
fw.write("======== CrashInfo ========\r\n");
getThrowableInfo(ex, fw);
fw.write("\r\n");
fw.flush();
Settings.putCrashFilename(fileName);
} catch (Exception e) {
file.delete();
} finally {
IOUtils.closeQuietly(fw);
}
}
public static boolean hasCrashFile() {
String filename = Settings.getCrashFilename();
if (filename == null) {
return false;
}
File dir = AppConfig.getExternalCrashDir();
if (dir == null) {
return false;
}
return new File(dir, filename).isFile();
}
public static String getCrashContent() {
String filename = Settings.getCrashFilename();
if (filename == null) {
return null;
}
File dir = AppConfig.getExternalCrashDir();
if (dir == null) {
return null;
}
File file = new File(dir, filename);
InputStream is = null;
try {
is = new FileInputStream(file);
return IOUtils.readString(is, "UTF-8");
} catch (IOException e) {
return null;
} finally {
IOUtils.closeQuietly(is);
}
}
public static void resetCrashFile() {
Settings.putCrashFilename(null);
}
}
@@ -26,13 +26,14 @@ import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.LruCache;
import android.util.Log;
import com.facebook.soloader.SoLoader;
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 +41,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,19 +49,16 @@ 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.io.IOException;
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 {
private static final String TAG = EhApplication.class.getSimpleName();
@@ -73,10 +69,8 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
private static final boolean DEBUG_PRINT_IMAGE_COUNT = false;
private static final long DEBUG_PRINT_INTERVAL = 3000L;
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,19 +79,21 @@ 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<>();
@Override
public void onCreate() {
// Prepare to catch crash
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
super.onCreate();
try {
SoLoader.init(this, 0);
} catch (IOException e) {
throw new RuntimeException("Could not initialize SoLoader", e);
}
GetText.initialize(this);
CookieDB.initialize(this);
StatusCodeException.initialize(this);
Settings.initialize(this);
ReadableTime.initialize(this);
@@ -116,13 +112,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 +149,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 +159,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 +220,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 +243,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,32 +309,13 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
return application.mDownloadManager;
}
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
@NonNull
public static Hosts getHosts(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mHosts == null) {
application.mHosts = new Hosts(application, "hosts.db");
}
try {
ex.printStackTrace();
Crash.saveCrashInfo2File(this, ex);
return true;
} catch (Throwable tr) {
return false;
}
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
}
Activity activity = getTopActivity();
if (activity != null) {
activity.finish();
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
return application.mHosts;
}
@NonNull
+37 -9
View File
@@ -43,6 +43,7 @@ import com.hippo.ehviewer.dao.LocalFavoritesDao;
import com.hippo.ehviewer.dao.QuickSearch;
import com.hippo.ehviewer.dao.QuickSearchDao;
import com.hippo.ehviewer.download.DownloadManager;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.SqlUtils;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
@@ -93,6 +94,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;
}
}
@@ -143,7 +157,8 @@ public class EhDB {
SQLiteDatabase oldDB;
try {
oldDB = oldDBHelper.getReadableDatabase();
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
return;
}
@@ -165,7 +180,8 @@ public class EhDB {
try {
// In 0.6.x version, NaN is stored
gi.rating = cursor.getFloat(7);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
gi.rating = -1.0f;
}
@@ -176,7 +192,8 @@ public class EhDB {
}
cursor.close();
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
@@ -206,7 +223,8 @@ public class EhDB {
}
cursor.close();
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
@@ -242,7 +260,8 @@ public class EhDB {
}
cursor.close();
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
@@ -283,7 +302,8 @@ public class EhDB {
}
cursor.close();
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
@@ -312,13 +332,15 @@ public class EhDB {
}
cursor.close();
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
try {
oldDBHelper.close();
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
}
@@ -606,6 +628,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()) {
@@ -708,7 +735,8 @@ public class EhDB {
}
return null;
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
return context.getString(R.string.cant_read_the_file);
}
@@ -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;
}
}
@@ -16,7 +16,6 @@
package com.hippo.ehviewer;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
@@ -25,19 +24,17 @@ import android.support.annotation.DimenRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
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.ui.CommonOperations;
import com.hippo.glgallery.GalleryView;
import com.hippo.unifile.UniFile;
import com.hippo.util.ExceptionUtils;
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 +234,28 @@ 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 void putTheme(int theme) {
putIntToStr(KEY_THEME, theme);
}
public static final String KEY_APPLY_NAV_BAR_THEME_COLOR = "apply_nav_bar_theme_color";
private static final boolean DEFAULT_APPLY_NAV_BAR_THEME_COLOR = false;
public static boolean getApplyNavBarThemeColor() {
return getBoolean(KEY_APPLY_NAV_BAR_THEME_COLOR, DEFAULT_APPLY_NAV_BAR_THEME_COLOR);
}
public static final String KEY_GALLERY_SITE = "gallery_site";
private static final int DEFAULT_GALLERY_SITE = 1;
@@ -314,6 +333,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;
@@ -520,6 +546,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;
@@ -564,6 +601,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
********************/
@@ -584,7 +634,8 @@ public class Settings {
builder.encodedQuery(getString(KEY_DOWNLOAD_SAVE_QUERY, null));
builder.encodedFragment(getString(KEY_DOWNLOAD_SAVE_FRAGMENT, null));
dir = UniFile.fromUri(sContext, builder.build());
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
return dir != null ? dir : UniFile.fromFile(AppConfig.getDefaultDownloadDir());
@@ -694,26 +745,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];
@@ -731,7 +798,7 @@ public class Settings {
}
public static void putFavCat(String[] value) {
Assert.assertEquals(10, value.length);
AssertUtils.assertEquals(10, value.length);
sSettingsPre.edit()
.putString(KEY_FAV_CAT_0, value[0])
.putString(KEY_FAV_CAT_1, value[1])
@@ -746,6 +813,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) {
AssertUtils.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;
@@ -862,6 +976,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_SKIP_UPDATE_VERSION = "skip_update_version";
private static final int DEFAULT_SKIP_UPDATE_VERSION = 0;
public static boolean getBetaUpdateChannel() {
return getBoolean(KEY_BETA_UPDATE_CHANNEL, DEFAULT_BETA_UPDATE_CHANNEL);
@@ -871,19 +987,12 @@ public class Settings {
putBoolean(KEY_BETA_UPDATE_CHANNEL, value);
}
/********************
****** Crash
********************/
private static final String KEY_CRASH_FILENAME = "crash_filename";
private static final String DEFAULT_CRASH_FILENAME = null;
public static String getCrashFilename() {
return getString(KEY_CRASH_FILENAME, DEFAULT_CRASH_FILENAME);
public static int getSkipUpdateVersion() {
return getInt(KEY_SKIP_UPDATE_VERSION, DEFAULT_SKIP_UPDATE_VERSION);
}
@SuppressLint("CommitPrefEdits")
public static void putCrashFilename(String value) {
sSettingsPre.edit().putString(KEY_CRASH_FILENAME, value).commit();
public static void putSkipUpdateVersion(int value) {
putInt(KEY_SKIP_UPDATE_VERSION, value);
}
/********************
@@ -928,6 +1037,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
********************/
@@ -985,4 +1116,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);
}
}
@@ -18,13 +18,12 @@ package com.hippo.ehviewer.client;
import android.content.Context;
import android.os.AsyncTask;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.CancelledException;
import com.hippo.util.ExceptionUtils;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.thread.PriorityThreadFactory;
import java.io.File;
import java.util.List;
import java.util.concurrent.BlockingQueue;
@@ -34,7 +33,6 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.Call;
import okhttp3.OkHttpClient;
@@ -153,7 +151,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:
@@ -193,7 +191,8 @@ public class EhClient {
default:
return new IllegalStateException("Can't detect method " + mMethod);
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
return e;
}
}
@@ -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,12 +26,12 @@ 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()
@@ -40,13 +42,18 @@ public class EhCookieStore extends CookieDBStore {
.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_E);
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,9 +17,9 @@
package com.hippo.ehviewer.client;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
@@ -47,20 +47,13 @@ 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 junit.framework.Assert;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import com.hippo.util.ExceptionUtils;
import com.hippo.yorozuya.AssertUtils;
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;
import okhttp3.Headers;
@@ -70,6 +63,11 @@ import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class EhEngine {
@@ -90,8 +88,8 @@ public class EhEngine {
sEhFilter = EhFilter.getInstance();
}
private static void throwException(Call call, int code, @Nullable Headers headers,
@Nullable String body, Exception e) throws Exception {
private static void doThrowException(Call call, int code, @Nullable Headers headers,
@Nullable String body, Throwable e) throws Throwable {
if (call.isCanceled()) {
throw new CancelledException();
}
@@ -117,16 +115,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, Throwable e) throws Throwable {
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 Throwable {
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())
@@ -148,14 +164,15 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return SignInParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
public static GalleryListParser.Result getGalleryList(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Exception {
String url) throws Throwable {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -175,7 +192,8 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = GalleryListParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -191,7 +209,7 @@ public class EhEngine {
}
}
if (list.size() > 0 && (Settings.getShowJpnTitle() || sEhFilter.needCallApi())) {
if (list.size() > 0 && (TextUtils.isEmpty(list.get(0).uploader) || Settings.getShowJpnTitle() || Settings.getShowGalleryPages() || sEhFilter.needCallApi())) {
// Fill by api
fillGalleryListByApi(task, okHttpClient, list);
@@ -215,7 +233,7 @@ public class EhEngine {
// At least, GalleryInfo contain valid gid and token
public static List<GalleryInfo> fillGalleryListByApi(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
List<GalleryInfo> galleryInfoList) throws Exception {
List<GalleryInfo> galleryInfoList) throws Throwable {
// We can only request 25 items one time at most
final int MAX_REQUEST_SIZE = 25;
List<GalleryInfo> requestItems = new ArrayList<>(MAX_REQUEST_SIZE);
@@ -230,7 +248,7 @@ public class EhEngine {
}
private static void doFillGalleryListByApi(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
List<GalleryInfo> galleryInfoList) throws Exception {
List<GalleryInfo> galleryInfoList) throws Throwable {
JSONObject json = new JSONObject();
json.put("method", "gdata");
JSONArray ja = new JSONArray();
@@ -264,14 +282,15 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
GalleryApiParser.parse(body, galleryInfoList);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
public static GalleryDetail getGalleryDetail(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Exception {
String url) throws Throwable {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -290,7 +309,8 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return GalleryDetailParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -298,7 +318,7 @@ public class EhEngine {
public static Pair<PreviewSet, Integer> getPreviewSet(
@Nullable EhClient.Task task, OkHttpClient okHttpClient, String url) throws Exception {
@Nullable EhClient.Task task, OkHttpClient okHttpClient, String url) throws Throwable {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -318,7 +338,8 @@ public class EhEngine {
body = response.body().string();
return Pair.create(GalleryDetailParser.parsePreviewSet(body),
GalleryDetailParser.parsePreviewPages(body));
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -326,7 +347,7 @@ public class EhEngine {
public static RateGalleryParser.Result rateGallery(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, long apiUid, String apiKey, long gid,
String token, float rating) throws Exception {
String token, float rating) throws Throwable {
final JSONObject json = new JSONObject();
json.put("method", "rategallery");
json.put("apiuid", apiUid);
@@ -356,17 +377,17 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return RateGalleryParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
public static GalleryComment[] commentGallery(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, String url, String comment) throws Exception {
OkHttpClient okHttpClient, String url, String comment) throws Throwable {
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())
@@ -387,15 +408,22 @@ 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) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
public static String getGalleryToken(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long gid, String gtoken, int page) throws Exception {
long gid, String gtoken, int page) throws Throwable {
JSONObject json = new JSONObject()
.put("method", "gtoken")
.put("pagelist", new JSONArray().put(
@@ -422,14 +450,15 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return GalleryTokenApiParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
public static FavoritesParser.Result getFavorites(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url, boolean callApi) throws Exception {
String url, boolean callApi) throws Throwable {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -449,16 +478,19 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = FavoritesParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
if (callApi && result.galleryInfoList.size() > 0) {
fillGalleryListByApi(task, okHttpClient, result.galleryInfoList);
List<GalleryInfo> list = result.galleryInfoList;
if (list.size() > 0 && (TextUtils.isEmpty(list.get(0).uploader) || Settings.getShowJpnTitle() || Settings.getShowGalleryPages())) {
fillGalleryListByApi(task, okHttpClient, list);
}
for (GalleryInfo info : result.galleryInfoList) {
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
@@ -470,7 +502,7 @@ public class EhEngine {
* @param note max 250 characters
*/
public static Void addFavorites(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long gid, String token, int dstCat, String note) throws Exception {
long gid, String token, int dstCat, String note) throws Throwable {
String catStr;
if (dstCat == -1) {
catStr = "favdel";
@@ -506,7 +538,8 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
throwException(call, code, headers, body, null);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -515,8 +548,8 @@ public class EhEngine {
}
public static Void addFavoritesRange(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long[] gidArray, String[] tokenArray, int dstCat) throws Exception {
Assert.assertEquals(gidArray.length, tokenArray.length);
long[] gidArray, String[] tokenArray, int dstCat) throws Throwable {
AssertUtils.assertEquals(gidArray.length, tokenArray.length);
for (int i = 0, n = gidArray.length; i < n; i++) {
addFavorites(task, okHttpClient, gidArray[i], tokenArray[i], dstCat, null);
}
@@ -524,7 +557,7 @@ public class EhEngine {
}
public static FavoritesParser.Result modifyFavorites(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url, long[] gidArray, int dstCat, boolean callApi) throws Exception {
String url, long[] gidArray, int dstCat, boolean callApi) throws Throwable {
String catStr;
if (dstCat == -1) {
catStr = "delete";
@@ -560,16 +593,18 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = FavoritesParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
if (callApi && result.galleryInfoList.size() > 0) {
fillGalleryListByApi(task, okHttpClient, result.galleryInfoList);
List<GalleryInfo> list = result.galleryInfoList;
if (list.size() > 0 && (TextUtils.isEmpty(list.get(0).uploader) || Settings.getShowJpnTitle() || Settings.getShowGalleryPages())) {
fillGalleryListByApi(task, okHttpClient, list);
}
for (GalleryInfo info : result.galleryInfoList) {
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
@@ -577,7 +612,7 @@ public class EhEngine {
}
public static Pair<String, String>[] getTorrentList(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Exception {
String url) throws Throwable {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -597,7 +632,8 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = TorrentParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -606,7 +642,7 @@ public class EhEngine {
}
public static Pair<String, Pair<String, String>[]> getArchiveList(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Exception {
String url) throws Throwable {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -626,7 +662,8 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = ArchiveParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -635,7 +672,7 @@ public class EhEngine {
}
public static Void downloadArchive(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long gid, String token, String or, String res) throws Exception {
long gid, String token, String or, String res) throws Throwable {
if (or == null || or.length() == 0) {
throw new EhException("Invalid form param or: " + or);
}
@@ -665,7 +702,8 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
throwException(call, code, headers, body, null);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -679,7 +717,7 @@ public class EhEngine {
}
public static List<GalleryInfo> getWhatsHot(@Nullable EhClient.Task task,
OkHttpClient okHttpClient) throws Exception {
OkHttpClient okHttpClient) throws Throwable {
String url = EhUrl.HOST_E;
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
@@ -700,7 +738,8 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
list = WhatsHotParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -718,7 +757,7 @@ public class EhEngine {
}
private static ProfileParser.Result getProfileInternal(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, String url) throws Exception {
OkHttpClient okHttpClient, String url) throws Throwable {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -737,14 +776,15 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return ProfileParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
public static ProfileParser.Result getProfile(@Nullable EhClient.Task task,
OkHttpClient okHttpClient) throws Exception {
OkHttpClient okHttpClient) throws Throwable {
String url = EhUrl.URL_FORUMS;
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
@@ -764,14 +804,15 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return getProfileInternal(task, okHttpClient, ForumsParser.parse(body));
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
public static VoteCommentParser.Result voteComment(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long apiUid, String apiKey, long gid, String token, long commentId, int commentVote) throws Exception {
long apiUid, String apiKey, long gid, String token, long commentId, int commentVote) throws Throwable {
final JSONObject json = new JSONObject();
json.put("method", "votecomment");
json.put("apiuid", apiUid);
@@ -802,7 +843,8 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return VoteCommentParser.parse(body, commentVote);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -812,7 +854,7 @@ public class EhEngine {
* @param image Must be jpeg
*/
public static GalleryListParser.Result imageSearch(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
File image, boolean uss, boolean osc, boolean se) throws Exception {
File image, boolean uss, boolean osc, boolean se) throws Throwable {
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addPart(
@@ -866,7 +908,8 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = GalleryListParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -882,7 +925,7 @@ public class EhEngine {
}
}
if (list.size() > 0 && (Settings.getShowJpnTitle() || sEhFilter.needCallApi())) {
if (list.size() > 0 && (TextUtils.isEmpty(list.get(0).uploader) || Settings.getShowJpnTitle() || Settings.getShowGalleryPages() || sEhFilter.needCallApi())) {
// Fill by api
fillGalleryListByApi(task, okHttpClient, list);
@@ -905,7 +948,7 @@ public class EhEngine {
}
public static GalleryPageParser.Result getGalleryPage(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, String url) throws Exception {
OkHttpClient okHttpClient, String url) throws Throwable {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
@@ -924,7 +967,8 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return GalleryPageParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -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,13 +17,10 @@
package com.hippo.ehviewer.client;
import android.support.annotation.NonNull;
import com.hippo.ehviewer.Settings;
import com.hippo.network.UrlBuilder;
import java.util.List;
import java.util.ListIterator;
import okhttp3.HttpUrl;
public class EhUrl {
@@ -52,6 +49,9 @@ public class EhUrl {
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/";
@@ -89,6 +89,16 @@ public class EhUrl {
}
}
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) {
@@ -40,6 +40,7 @@ public class GalleryDetail extends GalleryInfo {
public GalleryComment[] comments;
public int previewPages;
public PreviewSet previewSet;
public String favoriteName;
@Override
public int describeContents() {
@@ -64,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() {
@@ -96,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),
@@ -79,6 +79,23 @@ public class GalleryInfo implements Parcelable {
Pattern.compile("[(\\[]dutch[)\\]]", Pattern.CASE_INSENSITIVE),
};
public static final String[] S_LANG_TAGS = {
"language:english",
"language:chinese",
"language:spanish",
"language:korean",
"language:russian",
"language:french",
"language:portuguese",
"language:thai",
"language:german",
"language:italian",
"language:vietnamese",
"language:polish",
"language:hungarian",
"language:dutch",
};
public long gid ;
public String token;
public String title;
@@ -90,6 +107,7 @@ public class GalleryInfo implements Parcelable {
public float rating;
@Nullable
public String[] simpleTags;
public int pages;
public int thumbWidth;
public int thumbHeight;
@@ -104,6 +122,26 @@ public class GalleryInfo implements Parcelable {
public String simpleLanguage;
public final void generateSLang() {
if (simpleTags != null) {
generateSLangFromTags();
}
if (simpleLanguage == null && title != null) {
generateSLangFromTitle();
}
}
private void generateSLangFromTags() {
for (String tag : simpleTags) {
for (int i = 0; i < S_LANGS.length; i++) {
if (S_LANG_TAGS[i].equals(tag)) {
simpleLanguage = S_LANGS[i];
return;
}
}
}
}
private void generateSLangFromTitle() {
for (int i = 0; i < S_LANGS.length; i++) {
if (S_LANG_PATTERNS[i].matcher(title).find()) {
simpleLanguage = S_LANGS[i];
@@ -21,17 +21,15 @@ import com.hippo.ehviewer.R;
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.ExceptionUtils;
import com.hippo.util.JsoupUtils;
import junit.framework.Assert;
import com.hippo.yorozuya.AssertUtils;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.List;
public class FavoritesParser {
public static class Result {
@@ -54,14 +52,15 @@ public class FavoritesParser {
//noinspection ConstantConditions
Elements fps = ido.getElementsByClass("fp");
// Last one is "fp fps"
Assert.assertEquals(11, fps.size());
AssertUtils.assertEquals(11, fps.size());
for (int i = 0; i < 10; i++) {
Element fp = fps.get(i);
countArray[i] = ParserUtils.parseInt(fp.child(0).text());
catArray[i] = ParserUtils.trim(fp.child(2).text());
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
throw new ParseException("Parse favorites error", body);
}
@@ -18,7 +18,7 @@ package com.hippo.ehviewer.client.parser;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ExceptionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
@@ -31,7 +31,8 @@ public class ForumsParser {
Element userlinks = d.getElementById("userlinks");
Element child = userlinks.child(0).child(0).child(0);
return child.attr("href");
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new ParseException("Parse forums error", body);
}
}
@@ -53,6 +53,8 @@ public class GalleryApiParser {
tags[j] = tagJa.getString(j);
}
gi.simpleTags = tags;
gi.pages = Integer.parseInt(g.getString("filecount"));
gi.generateSLang();
}
}
@@ -19,7 +19,6 @@ package com.hippo.ehviewer.client.parser;
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;
@@ -33,15 +32,10 @@ import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.ehviewer.client.exception.OffensiveException;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.exception.PiningException;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.JsoupUtils;
import com.hippo.yorozuya.NumberUtils;
import com.hippo.yorozuya.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
@@ -52,6 +46,10 @@ import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class GalleryDetailParser {
@@ -142,7 +140,8 @@ public class GalleryDetailParser {
Element gd1 = gm.getElementById("gd1");
try {
gd.thumb = parseCoverStyle(StringUtils.trim(gd1.child(0).attr("style")));
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
gd.thumb = "";
}
@@ -168,7 +167,8 @@ public class GalleryDetailParser {
String href = gdc.child(0).attr("href");
String category = href.substring(href.lastIndexOf('/') + 1);
gd.category = EhUtils.getCategory(category);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
gd.category = EhUtils.UNKNOWN;
}
@@ -193,7 +193,8 @@ public class GalleryDetailParser {
for (int i = 0, n = es.size(); i < n; i++) {
parseDetailInfo(gd, es.get(i), body);
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
@@ -227,7 +228,16 @@ public class GalleryDetailParser {
// isFavorited
Element gdf = gm.getElementById("gdf");
gd.isFavorited = null != gdf && !StringUtils.trim(gdf.text()).equals("Add to Favorites");
} catch (Exception e) {
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 (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new ParseException("Can't parse gallery detail", body);
}
}
@@ -303,13 +313,14 @@ 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);
}
return group.size() > 0 ? group : null;
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
return null;
}
@@ -332,7 +343,8 @@ public class GalleryDetailParser {
}
}
return list.toArray(new GalleryTagGroup[list.size()]);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
return EMPTY_GALLERY_TAG_GROUP_ARRAY;
}
@@ -397,14 +409,15 @@ 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();
// comment
comment.comment = JsoupUtils.getElementByClass(element, "c6").html();
return comment;
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
return null;
}
@@ -427,7 +440,8 @@ public class GalleryDetailParser {
}
}
return list.toArray(new GalleryComment[list.size()]);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
return EMPTY_GALLERY_COMMENT_ARRAY;
}
@@ -466,7 +480,8 @@ public class GalleryDetailParser {
try {
Elements elements = document.getElementsByClass("ptt").first().child(0).child(0).children();
return Integer.parseInt(elements.get(elements.size() - 2).text());
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
throw new ParseException("Can't parse preview pages", body);
}
@@ -541,7 +556,8 @@ public class GalleryDetailParser {
largePreviewSet.addItem(index, imageUrl, pageUrl);
}
return largePreviewSet;
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
throw new ParseException("Can't parse large preview", body);
}
@@ -29,16 +29,25 @@ import java.util.regex.Pattern;
*/
public final class GalleryDetailUrlParser {
public static final Pattern URL_PATTERN = Pattern.compile("https?://(?:" +
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_E + "|" + EhUrl.DOMAIN_LOFI + ")/g/(\\d+)/(\\w+)");
private static final Pattern URL_STRICT_PATTERN = Pattern.compile(
"https?://(?:" + EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_E + "|" + EhUrl.DOMAIN_LOFI + ")/(?:g|mpv)/(\\d+)/([0-9a-f]{10})");
private static final Pattern URL_PATTERN = Pattern.compile(
"(\\d+)/([0-9a-f]{10})");
@Nullable
public static Result parse(String url) {
return parse(url, true);
}
@Nullable
public static Result parse(String url, boolean strict) {
if (url == null) {
return null;
}
Matcher m = URL_PATTERN.matcher(url);
Pattern pattern = strict ? URL_STRICT_PATTERN : URL_PATTERN;
Matcher m = pattern.matcher(url);
if (m.find()) {
Result result = new Result();
result.gid = Long.parseLong(m.group(1));
@@ -19,24 +19,22 @@ package com.hippo.ehviewer.client.parser;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.JsoupUtils;
import com.hippo.yorozuya.NumberUtils;
import com.hippo.yorozuya.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class GalleryListParser {
@@ -54,7 +52,8 @@ public class GalleryListParser {
try {
Elements es = d.getElementsByClass("ptt").first().child(0).child(0).children();
return Integer.parseInt(es.get(es.size() - 2).text().trim());
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new ParseException("Can't parse gallery list pages", body);
}
}
@@ -182,6 +181,62 @@ 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;
}
gi.generateSLang();
return gi;
}
public static Result parse(@NonNull String body) throws Exception {
Result result = new Result();
Document d = Jsoup.parse(body);
@@ -209,10 +264,29 @@ public class GalleryListParser {
}
}
result.galleryInfoList = list;
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
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 (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new ParseException("Can't parse gallery list", body);
}
}
return result;
}
}
@@ -16,8 +16,8 @@
package com.hippo.ehviewer.client.parser;
import android.support.annotation.Nullable;
import com.hippo.ehviewer.client.EhUrl;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -26,15 +26,25 @@ import java.util.regex.Pattern;
*/
public final class GalleryPageUrlParser {
public static final Pattern URL_PATTERN = Pattern.compile("https?://(?:" +
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_E + "|" + EhUrl.DOMAIN_LOFI + ")/s/(\\w+)/(\\d+)-(\\d+)");
private static final Pattern URL_STRICT_PATTERN = Pattern.compile(
"https?://(?:" + EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_E + "|" + EhUrl.DOMAIN_LOFI + ")/s/([0-9a-f]{10})/(\\d+)-(\\d+)");
private static final Pattern URL_PATTERN = Pattern.compile(
"([0-9a-f]{10})/(\\d+)-(\\d+)");
@Nullable
public static Result parse(String url) {
return parse(url, true);
}
@Nullable
public static Result parse(String url, boolean strict) {
if (url == null) {
return null;
}
Matcher m = URL_PATTERN.matcher(url);
Pattern pattern = strict ? URL_STRICT_PATTERN : URL_PATTERN;
Matcher m = pattern.matcher(url);
if (m.find()) {
Result result = new Result();
result.gid = Long.parseLong(m.group(2));
@@ -17,7 +17,7 @@
package com.hippo.ehviewer.client.parser;
import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.util.ExceptionUtils;
import org.json.JSONObject;
public class GalleryTokenApiParser {
@@ -36,7 +36,8 @@ public class GalleryTokenApiParser {
JSONObject jo = new JSONObject(body).getJSONArray("tokenlist").getJSONObject(0);
try {
return jo.getString("token");
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new EhException(jo.getString("error"));
}
}
@@ -18,10 +18,9 @@ package com.hippo.ehviewer.client.parser;
import android.text.TextUtils;
import android.util.Log;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ExceptionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
@@ -43,11 +42,13 @@ public class ProfileParser {
} else if (!result.avatar.startsWith("http")) {
result.avatar = EhUrl.URL_FORUMS + result.avatar;
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
Log.i(TAG, "No avatar");
}
return result;
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new ParseException("Parse forums error", body);
}
}
@@ -19,16 +19,15 @@ package com.hippo.ehviewer.client.parser;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.JsoupUtils;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
public class WhatsHotParser {
@SuppressWarnings("ConstantConditions")
@@ -54,7 +53,8 @@ public class WhatsHotParser {
galleryInfoList.add(galleryInfo);
}
return galleryInfoList;
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new ParseException("Parse whats hot error", 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;
@@ -560,6 +566,52 @@ public class DownloadManager implements SpiderQueen.OnSpiderListener {
for (DownloadInfoListener l: mDownloadInfoListeners) {
l.onReload();
}
// Ensure download
ensureDownload();
}
@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
@@ -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);
}
@@ -0,0 +1,218 @@
/*
* 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.gallery;
import android.content.Context;
import android.net.Uri;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.gallery.archive.Archive;
import com.hippo.ehviewer.gallery.archive.ArchiveEntry;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.unifile.UniRandomAccessFile;
import com.hippo.util.NaturalComparator;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.thread.PriorityThread;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
public class ArchiveGalleryProvider extends GalleryProvider2 implements Runnable {
private static final String TAG = ArchiveGalleryProvider.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
private final UniFile file;
private final Stack<Integer> requests = new Stack<>();
private final AtomicInteger decodingIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
@Nullable
private Thread bgThread;
private volatile int size = STATE_WAIT;
private String error;
public ArchiveGalleryProvider(Context context, Uri uri) {
file = UniFile.fromUri(context, uri);
}
@Override
public void start() {
super.start();
bgThread = new PriorityThread(this, TAG + '-' + sIdGenerator.incrementAndGet(),
Process.THREAD_PRIORITY_BACKGROUND);
bgThread.start();
}
@Override
public void stop() {
super.stop();
if (bgThread != null) {
bgThread.interrupt();
bgThread = null;
}
}
@Override
public int size() {
return size;
}
@Override
protected void onRequest(int index) {
synchronized (requests) {
if (!requests.contains(index) && index != decodingIndex.get()) {
requests.add(index);
requests.notify();
}
}
notifyPageWait(index);
}
@Override
protected void onForceRequest(int index) {
onRequest(index);
}
@Override
protected void onCancelRequest(int index) {
synchronized (requests) {
requests.remove(Integer.valueOf(index));
}
}
@Override
public String getError() {
return error;
}
@NonNull
@Override
public String getImageFilename(int index) {
// TODO
return Integer.toString(index);
}
@Override
public boolean save(int index, @NonNull UniFile file) {
// TODO
return false;
}
@Nullable
@Override
public UniFile save(int index, @NonNull UniFile dir, @NonNull String filename) {
// TODO
return null;
}
@Override
public void run() {
UniRandomAccessFile uraf = null;
if (file != null) {
try {
uraf = file.createRandomAccessFile("r");
} catch (IOException e) {
e.printStackTrace();
}
}
if (uraf == null) {
size = STATE_ERROR;
error = GetText.getString(R.string.error_reading_failed);
notifyDataChanged();
return;
}
Archive archive = null;
try {
archive = Archive.create(uraf);
} catch (IOException e) {
e.printStackTrace();
}
if (archive == null) {
size = STATE_ERROR;
error = GetText.getString(R.string.error_invalid_archive);
notifyDataChanged();
return;
}
List<ArchiveEntry> entries = archive.getArchiveEntries();
Collections.sort(entries, naturalComparator);
// Update size and notify changed
size = entries.size();
notifyDataChanged();
while (!Thread.currentThread().isInterrupted()) {
int index;
synchronized (requests) {
if (requests.isEmpty()) {
try {
requests.wait();
} catch (InterruptedException e) {
// Interrupted
break;
}
continue;
}
index = requests.pop();
decodingIndex.lazySet(index);
}
// Check index valid
if (index < 0 || index >= entries.size()) {
decodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyPageFailed(index, GetText.getString(R.string.error_out_of_range));
continue;
}
try {
InputStream is = entries.get(index).getInputStream();
Image image = Image.decode(is, true);
decodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
if (image != null) {
notifyPageSucceed(index, image);
} else {
notifyPageFailed(index, GetText.getString(R.string.error_decoding_failed));
}
} catch (IOException e) {
decodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyPageFailed(index, GetText.getString(R.string.error_reading_failed));
}
}
// Clear
IOUtils.closeQuietly(archive);
}
private static Comparator<ArchiveEntry> naturalComparator = new Comparator<ArchiveEntry>() {
private NaturalComparator comparator = new NaturalComparator();
@Override
public int compare(ArchiveEntry o1, ArchiveEntry o2) {
return comparator.compare(o1.getName(), o2.getName());
}
};
}
@@ -20,23 +20,22 @@ import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.FilenameFilter;
import com.hippo.unifile.UniFile;
import com.hippo.util.NaturalComparator;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.StringUtils;
import com.hippo.yorozuya.thread.PriorityThread;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
@@ -173,7 +172,7 @@ public class DirGalleryProvider extends GalleryProvider2 implements Runnable {
@Override
public void run() {
// It may take a long time, so run it in new thread
UniFile[] files = mDir.listFiles();
UniFile[] files = mDir.listFiles(imageFilter);
if (files == null) {
mSize = STATE_ERROR;
@@ -187,7 +186,7 @@ public class DirGalleryProvider extends GalleryProvider2 implements Runnable {
}
// Sort it
Arrays.sort(files);
Arrays.sort(files, naturalComparator);
// Put file list
mFileList.lazySet(files);
@@ -244,11 +243,14 @@ public class DirGalleryProvider extends GalleryProvider2 implements Runnable {
Log.i(TAG, "ImageDecoder end");
}
private static class ImageFilter implements FilenameFilter {
private static FilenameFilter imageFilter =
(dir, name) -> StringUtils.endsWith(name.toLowerCase(), SUPPORT_IMAGE_EXTENSIONS);
private static Comparator<UniFile> naturalComparator = new Comparator<UniFile>() {
private NaturalComparator comparator = new NaturalComparator();
@Override
public boolean accept(File dir, String filename) {
return StringUtils.endsWith(filename.toLowerCase(), SUPPORT_IMAGE_EXTENSIONS);
public int compare(UniFile o1, UniFile o2) {
return comparator.compare(o1.getName(), o2.getName());
}
}
};
}
@@ -73,7 +73,7 @@ public class EhGalleryProvider extends GalleryProvider2 implements SpiderQueen.O
@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,228 +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.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.StringUtils;
import com.hippo.yorozuya.thread.PriorityThread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
public class ZipGalleryProvider extends GalleryProvider2 implements Runnable {
private static final String TAG = ZipGalleryProvider.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
private final File mFile;
private final Stack<Integer> mRequests = new Stack<>();
private final AtomicInteger mDecodingIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
@Nullable
private Thread mBgThread;
private volatile int mSize = STATE_WAIT;
private String mError;
public ZipGalleryProvider(File file) {
mFile = file;
}
@Override
public void start() {
super.start();
mBgThread = new PriorityThread(this, TAG + '-' + sIdGenerator.incrementAndGet(),
Process.THREAD_PRIORITY_BACKGROUND);
mBgThread.start();
}
@Override
public void stop() {
super.stop();
if (mBgThread != null) {
mBgThread.interrupt();
mBgThread = null;
}
}
@Override
public int size() {
return mSize;
}
@Override
protected void onRequest(int index) {
synchronized (mRequests) {
if (!mRequests.contains(index) && index != mDecodingIndex.get()) {
mRequests.add(index);
mRequests.notify();
}
}
notifyPageWait(index);
}
@Override
protected void onForceRequest(int index) {
onRequest(index);
}
@Override
protected void onCancelRequest(int index) {
synchronized (mRequests) {
mRequests.remove(Integer.valueOf(index));
}
}
@Override
public String getError() {
return mError;
}
@NonNull
@Override
public String getImageFilename(int index) {
// TODO
return Integer.toString(index);
}
@Override
public boolean save(int index, @NonNull UniFile file) {
// TODO
return false;
}
@Nullable
@Override
public UniFile save(int index, @NonNull UniFile dir, @NonNull String filename) {
// TODO
return null;
}
@Override
public void run() {
ZipFile zipFile = null;
try {
zipFile = new ZipFile(mFile);
} catch (ZipException e) {
mError = GetText.getString(R.string.error_invalid_zip_file);
} catch (FileNotFoundException e) {
mError = GetText.getString(R.string.error_not_found);
} catch (IOException e) {
mError = GetText.getString(R.string.error_reading_failed);
}
// Check zip file null
if (zipFile == null) {
mSize = STATE_ERROR;
// Notify to to show error
notifyDataChanged();
Log.i(TAG, "ImageDecoder end with error");
return;
}
// Get all image name
List<String> filenames = new ArrayList<>(zipFile.size());
Enumeration<? extends ZipEntry> enumeration = zipFile.entries();
while (enumeration.hasMoreElements()) {
ZipEntry zipEntry = enumeration.nextElement();
String filename = zipEntry.getName();
if (!zipEntry.isDirectory() && StringUtils.endsWith(filename, SUPPORT_IMAGE_EXTENSIONS)) {
filenames.add(filename);
}
}
Collections.sort(filenames);
// Update size and notify changed
mSize = filenames.size();
notifyDataChanged();
while (!Thread.currentThread().isInterrupted()) {
int index;
synchronized (mRequests) {
if (mRequests.isEmpty()) {
try {
mRequests.wait();
} catch (InterruptedException e) {
// Interrupted
break;
}
continue;
}
index = mRequests.pop();
mDecodingIndex.lazySet(index);
}
// Check index valid
if (index < 0 || index >= filenames.size()) {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyPageFailed(index, GetText.getString(R.string.error_out_of_range));
continue;
}
try {
ZipEntry zipEntry = zipFile.getEntry(filenames.get(index));
if (zipEntry != null) {
InputStream is = zipFile.getInputStream(zipEntry);
Image image = Image.decode(is, true);
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
if (image != null) {
notifyPageSucceed(index, image);
} else {
notifyPageFailed(index, GetText.getString(R.string.error_decoding_failed));
}
} else {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyPageFailed(index, GetText.getString(R.string.error_reading_failed));
}
} catch (IOException e) {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyPageFailed(index, GetText.getString(R.string.error_reading_failed));
}
}
// Clear
try {
zipFile.close();
} catch (IOException e) {
// Ignore
}
Log.i(TAG, "ImageDecoder end");
}
}
@@ -0,0 +1,91 @@
/*
* 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.gallery.archive;
import com.hippo.ehviewer.gallery.GalleryProvider2;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
public abstract class Archive implements Closeable {
private static final byte[] FILE_SIGNATURE_SEVEN_Z = { 0x37, 0x7A, (byte) 0xBC, (byte) 0xAF, 0x27, 0x1C };
private static final byte[] FILE_SIGNATURE_ZIP = { 0x50, 0x4B };
private static final byte[] FILE_SIGNATURE_RAR = { 0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00 };
public abstract List<ArchiveEntry> getArchiveEntries();
public static Archive create(UniRandomAccessFile file) throws IOException {
byte[] bytes = new byte[8];
readFully(file, bytes, 8);
file.seek(0);
if (equals(bytes, FILE_SIGNATURE_SEVEN_Z, FILE_SIGNATURE_SEVEN_Z.length)) {
return SevenZArchive.create(file);
} else if (equals(bytes, FILE_SIGNATURE_ZIP, FILE_SIGNATURE_ZIP.length)) {
return ZipArchive.create(file);
} else if (equals(bytes, FILE_SIGNATURE_RAR, FILE_SIGNATURE_RAR.length)) {
return RarArchive.create(file);
}
return null;
}
static boolean isSupportedFilename(String name) {
for (String extension : GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS) {
if (name.endsWith(extension)) {
return true;
}
}
return false;
}
private static int readFully(UniRandomAccessFile file, byte[] bytes, int count) throws IOException {
if (count <= 0) {
return 0;
}
int read = 0;
do {
int l = file.read(bytes, read, count - read);
if (l < 0)
break;
read += l;
} while (read < count);
if (read == 0) {
return -1;
} else {
return read;
}
}
private static boolean equals(byte[] b1, byte[] b2, int size) {
if (b1.length < size || b2.length < size) {
return false;
}
for (int i = 0; i < size; i++) {
if (b1[i] != b2[i]) {
return false;
}
}
return true;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2016 Hippo Seven
* 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.
@@ -14,17 +14,14 @@
* limitations under the License.
*/
package com.hippo.okhttp;
package com.hippo.ehviewer.gallery.archive;
import okhttp3.Cookie;
import java.io.IOException;
import java.io.InputStream;
public class CookieWithID {
public abstract class ArchiveEntry {
public long id;
public Cookie cookie;
public abstract String getName();
public CookieWithID(long id, Cookie cookie) {
this.id = id;
this.cookie = cookie;
}
public abstract InputStream getInputStream() throws IOException;
}
@@ -0,0 +1,198 @@
/*
* 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.gallery.archive;
import com.github.junrar.Volume;
import com.github.junrar.VolumeManager;
import com.github.junrar.exception.RarException;
import com.github.junrar.io.IReadOnlyAccess;
import com.github.junrar.rarfile.FileHeader;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class RarArchive extends Archive {
private com.github.junrar.Archive file;
private RarArchive(com.github.junrar.Archive file) {
this.file = file;
}
@Override
public List<ArchiveEntry> getArchiveEntries() {
List<ArchiveEntry> result = new ArrayList<>();
for (FileHeader fileHeader : file.getFileHeaders()) {
if (isSupportedFilename(fileHeader.getFileNameString().toLowerCase())) {
result.add(new RarArchiveEntry(file, fileHeader));
}
}
return result;
}
@Override
public void close() throws IOException {
file.close();
}
public static Archive create(UniRandomAccessFile file) throws IOException {
VolumeManager volumeManager = new UniRandomAccessFileVolumeManager(file);
com.github.junrar.Archive archive;
try {
archive = new com.github.junrar.Archive(volumeManager);
if (archive.getMainHeader().isSolid()) {
throw new IOException("Solid archive is not supported");
}
} catch (RarException e) {
throw new IOException("Invalid rar archive", e);
}
return new RarArchive(archive);
}
public static class RarArchiveEntry extends ArchiveEntry {
private com.github.junrar.Archive file;
private FileHeader header;
private RarArchiveEntry(com.github.junrar.Archive file, FileHeader header) {
this.file = file;
this.header = header;
}
@Override
public String getName() {
return header.getFileNameString();
}
@Override
public InputStream getInputStream() throws IOException {
try {
return file.getInputStream(header);
} catch (RarException e) {
throw new IOException("Can't getInputStream from rar archive", e);
}
}
}
private static class UniRandomAccessFileVolumeManager implements VolumeManager {
private UniRandomAccessFile file;
private UniRandomAccessFileVolumeManager(UniRandomAccessFile file) {
this.file = file;
}
@Override
public Volume nextArchive(com.github.junrar.Archive archive, Volume lastVolume) {
if (lastVolume == null) {
return new UniRandomAccessFileVolume(archive, file);
} else {
return null;
}
}
}
private static class UniRandomAccessFileVolume implements Volume {
private com.github.junrar.Archive archive;
private UniRandomAccessFile file;
private UniRandomAccessFileVolume(com.github.junrar.Archive archive, UniRandomAccessFile file) {
this.archive = archive;
this.file = file;
}
@Override
public IReadOnlyAccess getReadOnlyAccess() {
return new UniReadOnlyAccessFile(file);
}
@Override
public long getLength() throws IOException {
return file.length();
}
@Override
public com.github.junrar.Archive getArchive() {
return archive;
}
}
private static class UniReadOnlyAccessFile implements IReadOnlyAccess {
private UniRandomAccessFile file;
private UniReadOnlyAccessFile(UniRandomAccessFile file) {
this.file = file;
}
@Override
public long getPosition() throws IOException {
return file.getFilePointer();
}
@Override
public void setPosition(long pos) throws IOException {
file.seek(pos);
}
@Override
public int read() throws IOException {
byte[] b = new byte[1];
if (file.read(b) == -1) {
return -1;
} else {
return b[0];
}
}
@Override
public int read(byte[] buffer, int off, int count) throws IOException {
return file.read(buffer, off, count);
}
@Override
public int readFully(byte[] buffer, int count) throws IOException {
if (count <= 0) {
return 0;
}
int read = 0;
do {
int l = read(buffer, read, count - read);
if (l < 0)
break;
read += l;
} while (read < count);
if (read == 0) {
return -1;
} else {
return read;
}
}
@Override
public void close() throws IOException {
file.close();
}
}
}
@@ -0,0 +1,96 @@
/*
* 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.gallery.archive;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import okio.Store;
import okio.UniRandomAccessFileStore;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
public class SevenZArchive extends Archive {
private SevenZFile file;
public SevenZArchive(SevenZFile file) {
this.file = file;
}
@Override
public List<ArchiveEntry> getArchiveEntries() {
List<ArchiveEntry> result = new ArrayList<>();
for (org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry archive : file.getEntries()) {
if (archive.getSize() != 0
&& !archive.isDirectory()
&& isSupportedFilename(archive.getName().toLowerCase())) {
result.add(new SevenZArchiveEntry(file, archive));
}
}
return result;
}
@Override
public void close() throws IOException {
file.close();
}
public static Archive create(UniRandomAccessFile file) throws IOException {
Store store = new UniRandomAccessFileStore(file);
SevenZFile sevenZFile = new SevenZFile(store);
// Check whether the archive is solid
for (org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry entry : sevenZFile.getEntries()) {
if (entry.getSize() != 0
&& !entry.isDirectory()
&& !entry.isFirstInFolder()) {
throw new IOException("Solid archive is not supported");
}
}
return new SevenZArchive(sevenZFile);
}
public static class SevenZArchiveEntry extends ArchiveEntry {
private SevenZFile file;
private org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry entry;
private SevenZArchiveEntry(
SevenZFile file,
org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry entry
) {
this.file = file;
this.entry = entry;
}
@Override
public String getName() {
return entry.getName();
}
@Override
public InputStream getInputStream() throws IOException {
file.setEntry(entry);
return file.getInputStreamForCurrentEntry();
}
}
}
@@ -0,0 +1,86 @@
/*
* 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.gallery.archive;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import okio.Store;
import okio.UniRandomAccessFileStore;
import org.apache.commons.compress.archivers.zip.ZipFile;
public class ZipArchive extends Archive {
private ZipFile file;
private ZipArchive(ZipFile file) {
this.file = file;
}
@Override
public List<ArchiveEntry> getArchiveEntries() {
List<ArchiveEntry> result = new ArrayList<>();
Enumeration<org.apache.commons.compress.archivers.zip.ZipArchiveEntry> entries = file.getEntries();
while (entries.hasMoreElements()) {
org.apache.commons.compress.archivers.zip.ZipArchiveEntry entry = entries.nextElement();
if (isSupportedFilename(entry.getName().toLowerCase())) {
result.add(new ZipArchiveEntry(file, entry));
}
}
return result;
}
@Override
public void close() throws IOException {
file.close();
}
public static Archive create(UniRandomAccessFile file) throws IOException {
Store store = new UniRandomAccessFileStore(file);
ZipFile zipFile = new ZipFile(store);
return new ZipArchive(zipFile);
}
public static class ZipArchiveEntry extends ArchiveEntry {
private ZipFile file;
private org.apache.commons.compress.archivers.zip.ZipArchiveEntry entry;
private ZipArchiveEntry(
ZipFile file,
org.apache.commons.compress.archivers.zip.ZipArchiveEntry entry
) {
this.file = file;
this.entry = entry;
}
@Override
public String getName() {
return entry.getName();
}
@Override
public InputStream getInputStream() throws IOException {
return file.getInputStream(entry);
}
}
}
@@ -62,6 +62,9 @@ public class CleanRedundancyPreference extends TaskPreference {
// True for cleared
private boolean clearFile(UniFile file) {
String name = file.getName();
if (name == null) {
return false;
}
int index = name.indexOf('-');
if (index >= 0) {
name = name.substring(0, index);
@@ -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);
});
}
}
}
@@ -23,7 +23,6 @@ import android.preference.Preference;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.widget.Toast;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.R;
@@ -34,14 +33,13 @@ 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.util.ExceptionUtils;
import com.hippo.yorozuya.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import okhttp3.OkHttpClient;
public class RestoreDownloadPreference extends TaskPreference {
@@ -133,7 +131,8 @@ public class RestoreDownloadPreference extends TaskPreference {
try {
return EhEngine.fillGalleryListByApi(null, mHttpClient, new ArrayList<GalleryInfo>(restoreItemList));
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
return null;
}
@@ -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();
}
}
@@ -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 {
@@ -80,6 +80,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@@ -430,11 +431,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) {
@@ -483,7 +484,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;
}
@@ -492,7 +493,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;
@@ -518,7 +520,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);
}
@@ -713,10 +715,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++) {
@@ -744,7 +749,8 @@ public final class SpiderQueen implements Runnable {
spiderInfo.pTokenMap = new SparseArray<>(spiderInfo.pages);
readPreviews(body, 0, spiderInfo);
return spiderInfo;
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
return null;
}
}
@@ -762,6 +768,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(
@@ -783,7 +792,8 @@ public final class SpiderQueen implements Runnable {
pToken = spiderInfo.pTokenMap.get(index);
}
return pToken;
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
return null;
}
}
@@ -795,7 +805,8 @@ public final class SpiderQueen implements Runnable {
UniFile file = downloadDir.createFile(SPIDER_INFO_FILENAME);
try {
spiderInfo.write(file.openOutputStream());
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
}
@@ -1026,7 +1037,7 @@ public final class SpiderQueen implements Runnable {
return pageUrl;
}
private GalleryPageParser.Result getImageUrl(int index, String pageUrl) throws Exception {
private GalleryPageParser.Result getImageUrl(int index, String pageUrl) throws Throwable {
GalleryPageParser.Result result = EhEngine.getGalleryPage(null, mHttpClient, pageUrl);
if (StringUtils.endsWith(result.imageUrl, URL_509_SUFFIX_ARRAY)) {
// Get 509
@@ -1048,6 +1059,8 @@ public final class SpiderQueen implements Runnable {
boolean interrupt = false;
boolean leakSkipHathKey = false;
Log.d("TAG", "index = " + index);
// Try twice
for (int i = 0; i < 5; i++) {
if (leakSkipHathKey) {
@@ -1061,7 +1074,8 @@ public final class SpiderQueen implements Runnable {
result = getImageUrl(index, pageUrl);
} catch (Image509Exception e) {
error = GetText.getString(R.string.error_509);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
error = ExceptionUtils.getReadableString(e);
}
if (result == null) {
@@ -1112,17 +1126,26 @@ public final class SpiderQueen implements Runnable {
Call call = mHttpClient.newCall(new EhRequestBuilder(imageUrl).build());
Response response = call.execute();
ResponseBody responseBody = response.body();
if (response.code() >= 400) {
// Maybe 404
response.body().close();
response.close();
error = "Bad code: " + response.code();
continue;
}
ResponseBody responseBody = response.body();
if (responseBody == null) {
error = "Empty response body";
continue;
}
// Get extension
String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(
responseBody.contentType().toString());
String extension = null;
MediaType mediaType = responseBody.contentType();
if (mediaType != null) {
extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mediaType.toString());
}
// Ensure extension
if (!Utilities.contain(GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS, extension)) {
extension = GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS[0];
@@ -1133,7 +1156,7 @@ public final class SpiderQueen implements Runnable {
if (null == pipe) {
// Can't get pipe
error = GetText.getString(R.string.error_write_failed);
response.body().close();
response.close();
break;
}
@@ -1148,7 +1171,7 @@ public final class SpiderQueen implements Runnable {
while (!Thread.currentThread().isInterrupted()) {
int bytesRead = is.read(data);
if (bytesRead == -1) {
response.body().close();
response.close();
break;
}
os.write(data, 0, bytesRead);
@@ -1188,6 +1211,7 @@ public final class SpiderQueen implements Runnable {
updatePageState(index, STATE_FINISHED);
return true;
} catch (IOException e) {
e.printStackTrace();
error = GetText.getString(R.string.error_socket);
} finally {
IOUtils.closeQuietly(is);
@@ -1400,7 +1424,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;
@@ -100,17 +101,13 @@ public final class CommonOperations {
}
private void showUpToDateDialog() {
if (!mFeedback) {
return;
}
new AlertDialog.Builder(mActivity)
.setMessage(R.string.update_to_date)
.setPositiveButton(android.R.string.ok, null)
.show();
}
private void showUpdateDialog(String versionName, String size, CharSequence info, final String url) {
private void showUpdateDialog(String versionName, int versionCode, String size, CharSequence info, final String url) {
new AlertDialog.Builder(mActivity)
.setTitle(R.string.update)
.setMessage(mActivity.getString(R.string.update_plain, versionName, size, info))
@@ -119,16 +116,22 @@ public final class CommonOperations {
public void onClick(DialogInterface dialog, int which) {
UrlOpener.openUrl(mActivity, url, false);
}
})
.setNegativeButton(R.string.update_ignore, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Settings.putSkipUpdateVersion(versionCode);
}
}).show();
}
private void handleResult(JSONObject jo) {
if (null == jo || mActivity.isFinishing()) {
return;
}
String versionName;
int versionCode;
String size;
CharSequence info;
String url;
@@ -137,10 +140,12 @@ public final class CommonOperations {
PackageManager pm = mActivity.getPackageManager();
PackageInfo pi = pm.getPackageInfo(mActivity.getPackageName(), PackageManager.GET_ACTIVITIES);
int currentVersionCode = pi.versionCode;
int newVersionCode = jo.getInt("version_code");
if (currentVersionCode >= newVersionCode) {
versionCode = jo.getInt("version_code");
if (currentVersionCode >= versionCode) {
// Update to date
showUpToDateDialog();
if (mFeedback) {
showUpToDateDialog();
}
return;
}
@@ -152,7 +157,9 @@ public final class CommonOperations {
return;
}
showUpdateDialog(versionName, size, info, url);
if (mFeedback || versionCode != Settings.getSkipUpdateVersion()) {
showUpdateDialog(versionName, versionCode, size, info, url);
}
}
@Override
@@ -185,27 +192,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 +227,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,23 +16,42 @@
package com.hippo.ehviewer.ui;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.support.v7.app.AppCompatActivity;
import com.google.analytics.tracking.android.EasyTracker;
import android.view.WindowManager;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.hippo.android.resource.AttrResources;
import com.hippo.content.ContextLocalWrapper;
import com.hippo.ehviewer.Analytics;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import java.util.Locale;
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);
if (Analytics.isEnabled()) {
FirebaseAnalytics.getInstance(this);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Settings.getApplyNavBarThemeColor()) {
getWindow().setNavigationBarColor(AttrResources.getAttrColor(this, R.attr.colorPrimaryDark));
}
}
@Override
@@ -43,22 +62,35 @@ public abstract class EhActivity extends AppCompatActivity {
}
@Override
public void onStart() {
super.onStart();
if (Settings.getEnableAnalytics()) {
EasyTracker.getInstance(this).activityStart(this);
mTrackStarted = true;
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
public void onStop() {
super.onStop();
if (mTrackStarted) {
EasyTracker.getInstance(this).activityStop(this);
mTrackStarted = false;
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,23 +16,43 @@
package com.hippo.ehviewer.ui;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import com.google.analytics.tracking.android.EasyTracker;
import com.hippo.app.AppCompatPreferenceActivity;
import android.support.annotation.StyleRes;
import android.view.WindowManager;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.hippo.android.resource.AttrResources;
import com.hippo.app.PrettyPreferenceActivity;
import com.hippo.content.ContextLocalWrapper;
import com.hippo.ehviewer.Analytics;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import java.util.Locale;
public abstract 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);
if (Analytics.isEnabled()) {
FirebaseAnalytics.getInstance(this);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Settings.getApplyNavBarThemeColor()) {
getWindow().setNavigationBarColor(AttrResources.getAttrColor(this, R.attr.colorPrimaryDark));
}
}
@Override
@@ -43,22 +63,36 @@ public abstract class EhPreferenceActivity extends AppCompatPreferenceActivity {
}
@Override
public void onStart() {
super.onStart();
if (Settings.getEnableAnalytics()) {
EasyTracker.getInstance(this).activityStart(this);
mTrackStarted = true;
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
public void onStop() {
super.onStop();
if (mTrackStarted) {
EasyTracker.getInstance(this).activityStop(this);
mTrackStarted = false;
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;
@@ -164,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) {
@@ -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;
@@ -67,7 +68,7 @@ public class FilterActivity extends ToolbarActivity {
TextView tip = (TextView) ViewUtils.$$(this, R.id.tip);
mViewTransition = new ViewTransition(mRecyclerView, tip);
Drawable drawable = DrawableManager.getDrawable(this, R.drawable.big_filter);
Drawable drawable = DrawableManager.getVectorDrawable(this, R.drawable.big_filter);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
tip.setCompoundDrawables(null, drawable, null, null);
@@ -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());
}
}
}
}
@@ -297,7 +309,7 @@ public class FilterActivity extends ToolbarActivity {
if (R.layout.item_filter == layoutId) {
holder.icon.setImageDrawable(
DrawableManager.getDrawable(FilterActivity.this, R.drawable.v_delete_x24));
DrawableManager.getVectorDrawable(FilterActivity.this, R.drawable.v_delete_x24));
}
return holder;
@@ -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,6 +20,7 @@ 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;
@@ -47,15 +48,16 @@ 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.ArchiveGalleryProvider;
import com.hippo.ehviewer.gallery.DirGalleryProvider;
import com.hippo.ehviewer.gallery.EhGalleryProvider;
import com.hippo.ehviewer.gallery.GalleryProvider2;
import com.hippo.ehviewer.gallery.ZipGalleryProvider;
import com.hippo.ehviewer.widget.GalleryGuideView;
import com.hippo.ehviewer.widget.ReversibleSeekBar;
import com.hippo.glgallery.GalleryPageView;
@@ -68,19 +70,22 @@ 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 SeekBar.OnSeekBarChangeListener,
GalleryView.Listener {
public static final String ACTION_DIR = "dir";
public static final String ACTION_ZIP = "zip";
public static final String ACTION_EH = "eh";
public static final String KEY_ACTION = "action";
@@ -93,11 +98,14 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
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;
@@ -172,6 +180,19 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
}
};
@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;
@@ -181,10 +202,6 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
if (mFilename != null) {
mGalleryProvider = new DirGalleryProvider(UniFile.fromFile(new File(mFilename)));
}
} else if (ACTION_ZIP.equals(mAction)) {
if (mFilename != null) {
mGalleryProvider = new ZipGalleryProvider(new File(mFilename));
}
} else if (ACTION_EH.equals(mAction)) {
if (mGalleryInfo != null) {
mGalleryProvider = new EhGalleryProvider(this, mGalleryInfo);
@@ -192,7 +209,7 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
} else if (Intent.ACTION_VIEW.equals(mAction)) {
if (mUri != null) {
// Only support zip now
mGalleryProvider = new ZipGalleryProvider(new File(mUri.getPath()));
mGalleryProvider = new ArchiveGalleryProvider(this, mUri);
}
}
}
@@ -271,22 +288,21 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
mGLRootView = (GLRootView) ViewUtils.$$(this, R.id.gl_root_view);
mGalleryAdapter = new GalleryAdapter(mGLRootView, mGalleryProvider);
Resources resources = getResources();
int primaryColor = ResourcesUtils.getAttrColor(this, R.attr.colorPrimary);
mGalleryView = new GalleryView.Builder(this, mGalleryAdapter)
.setListener(this)
.setLayoutMode(Settings.getReadingDirection())
.setScaleMode(Settings.getPageScaling())
.setStartPosition(Settings.getStartPosition())
.setStartPage(startPage)
.setBackgroundColor(resources.getColor(R.color.gallery_background))
.setEdgeColor(primaryColor & 0xffffff | 0x33000000)
.setPagerInterval(resources.getDimensionPixelOffset(R.dimen.gallery_pager_interval))
.setScrollInterval(resources.getDimensionPixelOffset(R.dimen.gallery_scroll_interval))
.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(primaryColor)
.setProgressColor(ResourcesUtils.getAttrColor(this, R.attr.colorPrimary))
.setProgressSize(resources.getDimensionPixelOffset(R.dimen.gallery_progress_size))
.setPageTextColor(resources.getColor(R.color.secondary_text_default_dark))
.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))
@@ -612,6 +628,16 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
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();
@@ -702,6 +728,7 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
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;
@@ -718,6 +745,7 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
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);
@@ -731,6 +759,7 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
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());
@@ -759,6 +788,7 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
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();
@@ -774,6 +804,7 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
Settings.putShowClock(showClock);
Settings.putShowProgress(showProgress);
Settings.putShowBattery(showBattery);
Settings.putShowPageInterval(showPageInterval);
Settings.putVolumePage(volumePage);
Settings.putReadingFullscreen(readingFullscreen);
Settings.putCustomScreenLightness(customScreenLightness);
@@ -812,6 +843,8 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
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
@@ -829,7 +862,7 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
return;
}
File dir = AppConfig.getExternalImageDir();
File dir = AppConfig.getExternalTempDir();
if (null == dir) {
Toast.makeText(this, R.string.error_cant_create_temp_file, Toast.LENGTH_SHORT).show();
return;
@@ -853,18 +886,16 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
Uri uri = new Uri.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority("com.hippo.ehviewer.fileprovider")
.appendPath("image")
.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);
intent.setType(mimeType);
startActivity(Intent.createChooser(intent, getString(R.string.share_image)));
// Sync media store
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, file.getUri()));
}
private void saveImage(int page) {
@@ -889,32 +920,107 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
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 {
@@ -924,7 +1030,8 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
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;
@@ -957,6 +1064,12 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
}
}
private void onTapErrorText(int index) {
if (mGalleryProvider != null) {
mGalleryProvider.forceRequest(index);
}
}
private void onLongPressPage(final int index) {
showPageDialog(index);
}
@@ -984,6 +1097,9 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
case KEY_TAP_SLIDER_AREA:
onTapSliderArea();
break;
case KEY_TAP_ERROR_TEXT:
onTapErrorText(mValue);
break;
case KEY_LONG_PRESS_PAGE:
onLongPressPage(mValue);
break;
@@ -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;
@@ -36,22 +39,23 @@ import android.text.TextUtils;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
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.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhUrlOpener;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.ListUrlBuilder;
import com.hippo.ehviewer.client.parser.GalleryDetailUrlParser;
import com.hippo.ehviewer.client.parser.GalleryPageUrlParser;
import com.hippo.ehviewer.ui.scene.AnalyticsScene;
import com.hippo.ehviewer.ui.scene.BaseScene;
import com.hippo.ehviewer.ui.scene.CookieSignInScene;
import com.hippo.ehviewer.ui.scene.CrashScene;
import com.hippo.ehviewer.ui.scene.DownloadLabelsScene;
import com.hippo.ehviewer.ui.scene.DownloadsScene;
import com.hippo.ehviewer.ui.scene.FavoritesScene;
@@ -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;
@@ -96,6 +100,7 @@ public final class MainActivity extends StageActivity
private static final int REQUEST_CODE_SETTINGS = 0;
private static final String KEY_NAV_CHECKED_ITEM = "nav_checked_item";
private static final String KEY_CLIP_TEXT_HASH_CODE = "clip_text_hash_code";
/*---------------
Whole life cycle
@@ -110,6 +115,8 @@ public final class MainActivity extends StageActivity
private LoadImageView mAvatar;
@Nullable
private TextView mDisplayName;
@Nullable
private Button mChangeTheme;
private int mNavCheckedItem = 0;
@@ -117,7 +124,6 @@ public final class MainActivity extends StageActivity
registerLaunchMode(SecurityScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
registerLaunchMode(WarningScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
registerLaunchMode(AnalyticsScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
registerLaunchMode(CrashScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
registerLaunchMode(SignInScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
registerLaunchMode(WebViewSignInScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
registerLaunchMode(CookieSignInScene.class, SceneFragment.LAUNCH_MODE_SINGLE_TASK);
@@ -135,6 +141,19 @@ public final class MainActivity extends StageActivity
registerLaunchMode(ProgressScene.class, SceneFragment.LAUNCH_MODE_STANDARD);
}
@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;
}
}
@Override
public int getContainerViewId() {
return R.id.fragment_container;
@@ -149,8 +168,6 @@ public final class MainActivity extends StageActivity
return new Announcer(WarningScene.class);
} else if (Settings.getAskAnalytics()) {
return new Announcer(AnalyticsScene.class);
} else if (Crash.hasCrashFile()) {
return new Announcer(CrashScene.class);
} else if (EhUtils.needSignedIn(this)) {
return new Announcer(SignInScene.class);
} else if (Settings.getSelectSite()) {
@@ -180,11 +197,6 @@ public final class MainActivity extends StageActivity
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(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(SignInScene.KEY_TARGET_SCENE, announcer.getClazz().getName());
@@ -315,6 +327,7 @@ public final class MainActivity extends StageActivity
View headerLayout = mNavView.getHeaderView(0);
mAvatar = (LoadImageView) ViewUtils.$$(headerLayout, R.id.avatar);
mDisplayName = (TextView) ViewUtils.$$(headerLayout, R.id.display_name);
mChangeTheme = (Button) ViewUtils.$$(this, R.id.change_theme);
mDrawerLayout.setStatusBarColor(ResourcesUtils.getAttrColor(this, R.attr.colorPrimaryDark));
// Pre-L need shadow drawable
@@ -329,6 +342,12 @@ public final class MainActivity extends StageActivity
mNavView.setNavigationItemSelectedListener(this);
}
mChangeTheme.setText(getThemeText());
mChangeTheme.setOnClickListener(v -> {
Settings.putTheme(getNextTheme());
((EhApplication) getApplication()).recreate();
});
if (savedInstanceState == null) {
onInit();
CommonOperations.checkUpdate(this, false);
@@ -341,6 +360,35 @@ public final class MainActivity extends StageActivity
}
}
private String getThemeText() {
int resId;
switch (Settings.getTheme()) {
default:
case Settings.THEME_LIGHT:
resId = R.string.theme_light;
break;
case Settings.THEME_DARK:
resId = R.string.theme_dark;
break;
case Settings.THEME_BLACK:
resId = R.string.theme_black;
break;
}
return getString(resId);
}
private int getNextTheme() {
switch (Settings.getTheme()) {
default:
case Settings.THEME_LIGHT:
return Settings.THEME_DARK;
case Settings.THEME_DARK:
return Settings.THEME_BLACK;
case Settings.THEME_BLACK:
return Settings.THEME_LIGHT;
}
}
private void checkDownloadLocation() {
UniFile uniFile = Settings.getDownloadLocation();
// null == uniFile for first start
@@ -392,6 +440,79 @@ 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;
}
@Nullable
private Announcer createAnnouncerFromClipboardUrl(String url) {
GalleryDetailUrlParser.Result result1 = GalleryDetailUrlParser.parse(url, false);
if (result1 != null) {
Bundle args = new Bundle();
args.putString(GalleryDetailScene.KEY_ACTION, GalleryDetailScene.ACTION_GID_TOKEN);
args.putLong(GalleryDetailScene.KEY_GID, result1.gid);
args.putString(GalleryDetailScene.KEY_TOKEN, result1.token);
return new Announcer(GalleryDetailScene.class).setArgs(args);
}
GalleryPageUrlParser.Result result2 = GalleryPageUrlParser.parse(url, false);
if (result2 != null) {
Bundle args = new Bundle();
args.putString(ProgressScene.KEY_ACTION, ProgressScene.ACTION_GALLERY_TOKEN);
args.putLong(ProgressScene.KEY_GID, result2.gid);
args.putString(ProgressScene.KEY_PTOKEN, result2.pToken);
args.putInt(ProgressScene.KEY_PAGE, result2.page);
return new Announcer(ProgressScene.class).setArgs(args);
}
return null;
}
private void checkClipboardUrlInternal() {
String text = getTextFromClipboard();
int hashCode = text != null ? text.hashCode() : 0;
if (text != null && hashCode != 0 && Settings.getClipboardTextHashCode() != hashCode) {
Announcer announcer = createAnnouncerFromClipboardUrl(text);
if (announcer != null && mDrawerLayout != null) {
Snackbar snackbar = Snackbar.make(mDrawerLayout, R.string.clipboard_gallery_url_snack_message, Snackbar.LENGTH_INDEFINITE);
snackbar.setAction(R.string.clipboard_gallery_url_snack_action, v -> startScene(announcer));
snackbar.show();
}
}
Settings.putClipboardTextHashCode(hashCode);
}
@Override
@@ -413,7 +534,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);
@@ -430,7 +551,7 @@ public final class MainActivity extends StageActivity
if (scene instanceof BaseScene) {
BaseScene baseScene = (BaseScene) scene;
baseScene.onDestroyDrawerView();
baseScene.destroyDrawerView();
}
}
@@ -17,8 +17,10 @@
package com.hippo.ehviewer.ui;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
@@ -62,7 +64,7 @@ public class SetSecurityActivity extends ToolbarActivity implements View.OnClick
FingerprintManager fingerprintManager = getSystemService(FingerprintManager.class);
// The line below prevents the false positive inspection from Android Studio
// noinspection ResourceType
if (fingerprintManager.hasEnrolledFingerprints()) {
if (fingerprintManager != null && hasEnrolledFingerprints(fingerprintManager)) {
mFingerprint.setVisibility(View.VISIBLE);
mFingerprint.setChecked(Settings.getEnableFingerprint());
}
@@ -72,6 +74,16 @@ public class SetSecurityActivity extends ToolbarActivity implements View.OnClick
mSet.setOnClickListener(this);
}
@RequiresApi(api = Build.VERSION_CODES.M)
public static boolean hasEnrolledFingerprints(FingerprintManager fingerprintManager) {
try {
return fingerprintManager.isHardwareDetected()
&& fingerprintManager.hasEnrolledFingerprints();
} catch (Throwable e) {
return false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
@@ -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) {
@@ -142,16 +77,14 @@ public final class SettingsActivity extends EhPreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setActionBarUpIndicator(DrawableManager.getDrawable(this, R.drawable.v_arrow_left_dark_x24));
replaceHeaderLayoutResId();
setActionBarUpIndicator(DrawableManager.getVectorDrawable(this, R.drawable.v_arrow_left_dark_x24));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
@@ -25,9 +25,23 @@ import android.view.View;
import android.view.ViewGroup;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
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) {
super.setContentView(R.layout.activity_toolbar);
@@ -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;
}
}
}
@@ -19,22 +19,23 @@ 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 android.util.Base64;
import android.widget.TextView;
import android.widget.Toast;
import com.hippo.ehviewer.Analytics;
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";
@@ -46,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
@@ -79,17 +64,51 @@ public class AboutFragment extends PreferenceFragment
AppHelper.sendEmail(getActivity(), EhApplication.getDeveloperEmail(),
"About EhViewer", null);
} else if (KEY_DONATE.equals(key)) {
ClipboardManager cmb = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setPrimaryClip(ClipData.newPlainText(null, "seven332$163.com".replace('$', '@')));
Toast.makeText(getActivity(), R.string.settings_about_donate_toast, Toast.LENGTH_SHORT).show();
new AlertDialog.Builder(getActivity())
.setTitle(R.string.settings_about_donate)
.setMessage(getString(R.string.settings_about_donate_message).replace('$', '@'))
.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;
}
}
@@ -17,10 +17,11 @@
package com.hippo.ehviewer.ui.fragment;
import android.app.Activity;
import android.os.Build;
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,21 +33,35 @@ public class EhFragment extends PreferenceFragment
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.eh_settings);
Preference theme = findPreference(Settings.KEY_THEME);
Preference applyNavBarThemeColor = findPreference(Settings.KEY_APPLY_NAV_BAR_THEME_COLOR);
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);
applyNavBarThemeColor.setOnPreferenceChangeListener(this);
gallerySite.setOnPreferenceChangeListener(this);
listMode.setOnPreferenceChangeListener(this);
detailSize.setOnPreferenceChangeListener(this);
thumbSize.setOnPreferenceChangeListener(this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
getPreferenceScreen().removePreference(applyNavBarThemeColor);
}
}
@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_APPLY_NAV_BAR_THEME_COLOR.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;
}
}
@@ -19,18 +19,21 @@ 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.Analytics;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.scene.SceneFragment;
import com.hippo.util.AppHelper;
@@ -40,8 +43,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 +143,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 +261,21 @@ public abstract class BaseScene extends SceneFragment {
AppHelper.showSoftInput(activity, view);
}
}
@Override
public void onResume() {
super.onResume();
Analytics.onSceneView(this);
}
@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,16 +30,13 @@ 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 SolidScene implements EditText.OnEditorActionListener,
@@ -53,10 +50,14 @@ public class CookieSignInScene extends SolidScene implements EditText.OnEditorAc
@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
@@ -71,10 +72,13 @@ public class CookieSignInScene extends SolidScene implements EditText.OnEditorAc
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();
Assert.assertNotNull(mIpbMemberId);
AssertUtils.assertNotNull(mIpbMemberId);
mIpbPassHashLayout = (TextInputLayout) ViewUtils.$$(view, R.id.ipb_pass_hash_layout);
mIpbPassHash = mIpbPassHashLayout.getEditText();
Assert.assertNotNull(mIpbPassHash);
AssertUtils.assertNotNull(mIpbPassHash);
mIgneousLayout = (TextInputLayout) ViewUtils.$$(view, R.id.igneous_layout);
mIgneous = mIgneousLayout.getEditText();
AssertUtils.assertNotNull(mIgneous);
mOk = ViewUtils.$$(view, R.id.ok);
mIpbPassHash.setOnEditorActionListener(this);
@@ -83,10 +87,11 @@ public class CookieSignInScene extends SolidScene implements EditText.OnEditorAc
// Try to get old version cookie info
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.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);
@@ -96,6 +101,10 @@ public class CookieSignInScene extends SolidScene implements EditText.OnEditorAc
mIpbPassHash.setText(ipbPassHash);
getIt = true;
}
if (!TextUtils.isEmpty(igneous)) {
mIgneous.setText(igneous);
getIt = true;
}
if (getIt) {
showTip(R.string.found_cookies, LENGTH_SHORT);
}
@@ -117,8 +126,10 @@ public class CookieSignInScene extends SolidScene implements EditText.OnEditorAc
mIpbMemberIdLayout = null;
mIpbPassHashLayout = null;
mIgneousLayout = null;
mIpbMemberId = null;
mIpbPassHash = null;
mIgneous = null;
}
@Override
@@ -164,12 +175,14 @@ public class CookieSignInScene extends SolidScene implements EditText.OnEditorAc
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));
@@ -193,13 +206,13 @@ public class CookieSignInScene extends SolidScene implements EditText.OnEditorAc
.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();
}
@@ -210,7 +223,7 @@ public class CookieSignInScene extends SolidScene implements EditText.OnEditorAc
.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;
@@ -219,9 +232,13 @@ public class CookieSignInScene extends SolidScene implements EditText.OnEditorAc
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));
}
}
}
@@ -1,95 +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.ui.scene;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hippo.ehviewer.Crash;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.ripple.Ripple;
import com.hippo.util.AppHelper;
import com.hippo.yorozuya.ViewUtils;
public class CrashScene extends SolidScene implements View.OnClickListener {
/*---------------
Whole life cycle
---------------*/
@Nullable
private String mCrash;
/*---------------
View life cycle
---------------*/
@Nullable
private View mCancel;
@Nullable
private View mSend;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrash = Crash.getCrashContent();
}
@Override
public void onDestroyView() {
super.onDestroyView();
mCrash = null;
}
@Nullable
@Override
public View onCreateView2(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.scene_crash, container, false);
mCancel = ViewUtils.$$(view, R.id.cancel);
mSend = ViewUtils.$$(view, R.id.send);
mCancel.setOnClickListener(this);
mSend.setOnClickListener(this);
Ripple.addRipple(mCancel, true);
Ripple.addRipple(mSend, true);
return view;
}
@Override
public void onClick(View v) {
MainActivity activity = getActivity2();
if (mSend == v && null != mCrash && null != activity) {
AppHelper.sendEmail(activity, EhApplication.getDeveloperEmail(),
"I found a bug in EhViewer !", mCrash);
}
Crash.resetCrashFile();
// Start new scene and finish it self
if (null != activity) {
startSceneForCheckStep(CHECK_STEP_CRASH, getArguments());
}
finish();
}
}
@@ -32,20 +32,13 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.h6ah4i.android.widget.advrecyclerview.animator.GeneralItemAnimator;
import com.h6ah4i.android.widget.advrecyclerview.animator.SwipeDismissItemAnimator;
import com.h6ah4i.android.widget.advrecyclerview.draggable.DraggableItemAdapter;
import com.h6ah4i.android.widget.advrecyclerview.draggable.ItemDraggableRange;
import com.h6ah4i.android.widget.advrecyclerview.draggable.RecyclerViewDragDropManager;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.RecyclerViewSwipeManager;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.SwipeableItemAdapter;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.SwipeableItemConstants;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.action.SwipeResultAction;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.action.SwipeResultActionDefault;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.action.SwipeResultActionMoveToSwipedDirection;
import com.h6ah4i.android.widget.advrecyclerview.touchguard.RecyclerViewTouchActionGuardManager;
import com.h6ah4i.android.widget.advrecyclerview.utils.AbstractDraggableSwipeableItemViewHolder;
import com.h6ah4i.android.widget.advrecyclerview.utils.AbstractDraggableItemViewHolder;
import com.hippo.app.EditTextDialogBuilder;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.ehviewer.EhApplication;
@@ -53,10 +46,8 @@ 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 {
@@ -101,8 +92,8 @@ public class DownloadLabelsScene extends ToolbarScene {
mViewTransition = new ViewTransition(mRecyclerView, tip);
Context context = getContext2();
Assert.assertNotNull(context);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_label);
AssertUtils.assertNotNull(context);
Drawable drawable = DrawableManager.getVectorDrawable(context, R.drawable.big_label);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
tip.setCompoundDrawables(null, drawable, null, null);
tip.setText(R.string.no_download_label);
@@ -115,12 +106,9 @@ public class DownloadLabelsScene extends ToolbarScene {
RecyclerViewDragDropManager dragDropManager = new RecyclerViewDragDropManager();
dragDropManager.setDraggingItemShadowDrawable(
(NinePatchDrawable) context.getResources().getDrawable(R.drawable.shadow_8dp));
// swipe manager
RecyclerViewSwipeManager swipeManager = new RecyclerViewSwipeManager();
RecyclerView.Adapter adapter = new LabelAdapter();
adapter.setHasStableIds(true);
adapter = dragDropManager.createWrappedAdapter(adapter); // wrap for dragging
adapter = swipeManager.createWrappedAdapter(adapter); // wrap for swiping
mAdapter = adapter;
final GeneralItemAnimator animator = new SwipeDismissItemAnimator();
animator.setSupportsChangeAnimations(false);
@@ -129,7 +117,6 @@ public class DownloadLabelsScene extends ToolbarScene {
mRecyclerView.setAdapter(adapter);
mRecyclerView.setItemAnimator(animator);
guardManager.attachRecyclerView(mRecyclerView);
swipeManager.attachRecyclerView(mRecyclerView);
dragDropManager.attachRecyclerView(mRecyclerView);
updateView();
@@ -287,66 +274,77 @@ public class DownloadLabelsScene extends ToolbarScene {
}
}
private class LabelHolder extends AbstractDraggableSwipeableItemViewHolder
private class LabelHolder extends AbstractDraggableItemViewHolder
implements View.OnClickListener {
public final View swipeHandler;
public final TextView label;
public final View dragHandler;
public final View delete;
public LabelHolder(View itemView) {
super(itemView);
swipeHandler = ViewUtils.$$(itemView, R.id.swipe_handler);
label = (TextView) ViewUtils.$$(itemView, R.id.label);
dragHandler = ViewUtils.$$(itemView, R.id.drag_handler);
delete = ViewUtils.$$(itemView, R.id.delete);
label.setOnClickListener(this);
delete.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int position = getAdapterPosition();
Context context = getContext2();
if (null == context || null == mList || null == mRecyclerView) {
return;
}
int index = mRecyclerView.getChildAdapterPosition(itemView);
if (index < 0 || index >= mList.size()) {
return;
}
if (label == v) {
DownloadLabel raw = mList.get(index);
DownloadLabel raw = mList.get(position);
EditTextDialogBuilder builder = new EditTextDialogBuilder(
context, raw.getLabel(), getString(R.string.download_labels));
builder.setTitle(R.string.rename_label_title);
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.show();
new RenameLabelDialogHelper(builder, dialog, raw.getLabel(), index);
new RenameLabelDialogHelper(builder, dialog, raw.getLabel(), position);
} else if (delete == v) {
final DownloadLabel label = mList.get(position);
new AlertDialog.Builder(context)
.setTitle(R.string.delete_label_title)
.setMessage(getString(R.string.delete_label_message, label.getLabel()))
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EhApplication.getDownloadManager(context).deleteLabel(label.getLabel());
}
})
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
if (null != mAdapter) {
mAdapter.notifyDataSetChanged();
}
updateView();
}
}).show();
}
}
@Override
public View getSwipeableContainerView() {
return swipeHandler;
}
}
private class LabelAdapter extends RecyclerView.Adapter<LabelHolder>
implements DraggableItemAdapter<LabelHolder>,
SwipeableItemAdapter<LabelHolder> {
implements DraggableItemAdapter<LabelHolder> {
private final LayoutInflater mInflater;
public LabelAdapter() {
mInflater = getLayoutInflater2();
Assert.assertNotNull(mInflater);
AssertUtils.assertNotNull(mInflater);
}
@Override
public LabelHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new LabelHolder(mInflater.inflate(R.layout.item_label_list, parent, false));
return new LabelHolder(mInflater.inflate(R.layout.item_download_label, parent, false));
}
@Override
@@ -354,7 +352,6 @@ public class DownloadLabelsScene extends ToolbarScene {
if (mList != null) {
holder.label.setText(mList.get(position).getLabel());
}
holder.setSwipeItemHorizontalSlideAmount(0);
}
@Override
@@ -396,69 +393,9 @@ public class DownloadLabelsScene extends ToolbarScene {
}
@Override
public int onGetSwipeReactionType(LabelHolder holder, int position, int x, int y) {
if (ViewUtils.isViewUnder(holder.getSwipeableContainerView(), x, y, 0)) {
return SwipeableItemConstants.REACTION_CAN_SWIPE_LEFT;
} else {
return SwipeableItemConstants.REACTION_CAN_NOT_SWIPE_BOTH_H;
}
}
public void onItemDragStarted(int position) { }
@Override
public void onSetSwipeBackground(LabelHolder holder, int position, int type) {}
@Override
public SwipeResultAction onSwipeItem(LabelHolder holder, int position, int result) {
switch (result) {
// swipe left --- pin
case SwipeableItemConstants.RESULT_SWIPED_LEFT:
return new SwipeLeftResultAction(position);
// other --- do nothing
case SwipeableItemConstants.RESULT_SWIPED_RIGHT:
case SwipeableItemConstants.RESULT_CANCELED:
default:
return new SwipeResultActionDefault();
}
}
}
private class SwipeLeftResultAction extends SwipeResultActionMoveToSwipedDirection {
private final int mPosition;
public SwipeLeftResultAction(int position) {
mPosition = position;
}
@Override
protected void onPerformAction() {
super.onPerformAction();
final Context context = getContext2();
final List<DownloadLabel> list = mList;
if (null == context || null == list || mPosition < 0 || mPosition >= list.size()) {
return;
}
final DownloadLabel label = list.get(mPosition);
new AlertDialog.Builder(context)
.setTitle(R.string.delete_label_title)
.setMessage(getString(R.string.delete_label_message, label.getLabel()))
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EhApplication.getDownloadManager(context).deleteLabel(label.getLabel());
}
})
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
if (null != mAdapter) {
mAdapter.notifyDataSetChanged();
}
updateView();
}
}).show();
}
public void onItemDragFinished(int fromPosition, int toPosition, boolean result) { }
}
}
@@ -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,15 +88,12 @@ 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 junit.framework.Assert;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -194,7 +191,7 @@ public class DownloadsScene extends ToolbarScene
super.onCreate(savedInstanceState);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
mDownloadManager = EhApplication.getDownloadManager(context);
mDownloadManager.addDownloadInfoListener(this);
@@ -287,10 +284,10 @@ public class DownloadsScene extends ToolbarScene
mViewTransition = new ViewTransition(content, tip);
Context context = getContext2();
Assert.assertNotNull(content);
AssertUtils.assertNotNull(content);
Resources resources = context.getResources();
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_download);
Drawable drawable = DrawableManager.getVectorDrawable(context, R.drawable.big_download);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
tip.setCompoundDrawables(null, drawable, null, null);
@@ -301,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);
@@ -327,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);
@@ -489,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;
}
@@ -509,7 +517,7 @@ public class DownloadsScene extends ToolbarScene
View view = inflater.inflate(R.layout.drawer_list, container, false);
final Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.setTitle(R.string.download_labels);
@@ -635,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;
}
@@ -1074,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
@@ -1092,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;
}
@@ -1121,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();
Assert.assertNotNull(mInflater);
AssertUtils.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
@@ -1137,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
@@ -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,15 @@ 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 +67,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,14 +78,10 @@ import com.hippo.util.DrawableManager;
import com.hippo.widget.ContentLayout;
import com.hippo.widget.FabLayout;
import com.hippo.widget.SearchBarMover;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.AssertUtils;
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;
@@ -96,7 +90,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;
@@ -129,12 +123,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;
@@ -143,13 +136,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;
@@ -178,9 +174,12 @@ public class FavoritesScene extends BaseScene implements
super.onCreate(savedInstanceState);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
mClient = EhApplication.getEhClient(context);
mFavCatArray = Settings.getFavCat();
mFavCountArray = Settings.getFavCount();
mFavLocalCount = Settings.getFavLocalCount();
mFavCountSum = Settings.getFavCloudCount();
if (savedInstanceState == null) {
onInit();
@@ -206,7 +205,7 @@ public class FavoritesScene extends BaseScene implements
}
@Override
public void onSaveInstanceState(Bundle outState) {
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
boolean hasFirstRefresh;
@@ -227,6 +226,8 @@ public class FavoritesScene extends BaseScene implements
mClient = null;
mFavCatArray = null;
mFavCountArray = null;
mFavCountSum = 0;
mUrlBuilder = null;
}
@@ -236,6 +237,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();
AssertUtils.assertNotNull(activity);
mDrawerLayout = (EhDrawerLayout) ViewUtils.$$(activity, R.id.draw_view);
mRecyclerView = contentLayout.getRecyclerView();
FastScroller fastScroller = contentLayout.getFastScroller();
RefreshLayout refreshLayout = contentLayout.getRefreshLayout();
@@ -243,7 +247,7 @@ public class FavoritesScene extends BaseScene implements
mFabLayout = (FabLayout) ViewUtils.$$(view, R.id.fab_layout);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Resources resources = context.getResources();
int paddingTopSB = resources.getDimensionPixelOffset(R.dimen.gallery_padding_top_search_bar);
@@ -253,7 +257,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);
@@ -267,9 +271,9 @@ 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.setRightDrawable(DrawableManager.getVectorDrawable(context, R.drawable.v_magnify_x24));
mSearchBar.setHelper(this);
mSearchBar.setAllowEmptySearch(false);
updateSearchBar();
@@ -358,7 +362,7 @@ public class FavoritesScene extends BaseScene implements
// Update hint
if (!ObjectUtils.equal(favCatName, mOldFavCat)) {
Drawable searchImage = DrawableManager.getDrawable(context, R.drawable.v_magnify_x24);
Drawable searchImage = DrawableManager.getVectorDrawable(context, R.drawable.v_magnify_x24);
SpannableStringBuilder ssb = new SpannableStringBuilder(" ");
ssb.append(getString(R.string.favorites_search_bar_hint, favCatName));
int textSize = (int) (mSearchBar.getEditTextTextSize() * 1.25);
@@ -410,96 +414,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();
Assert.assertNotNull(context);
Toolbar toolbar = (Toolbar) ViewUtils.$$(view, R.id.toolbar);
AssertUtils.assertNotNull(context);
toolbar.setTitle(R.string.collections);
toolbar.inflateMenu(R.menu.drawer_favorites);
@@ -508,9 +493,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 +513,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 +529,6 @@ public class FavoritesScene extends BaseScene implements
super.onDestroyDrawerView();
mDrawerAdapter = null;
mDrawerList = null;
}
@Override
@@ -590,19 +569,56 @@ 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.getDataAtEx(position);
if (gi == null) {
return true;
}
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;
}
@@ -738,7 +754,10 @@ public class FavoritesScene extends BaseScene implements
SparseBooleanArray stateArray = mRecyclerView.getCheckedItemPositions();
for (int i = 0, n = stateArray.size(); i < n; i++) {
if (stateArray.valueAt(i)) {
mModifyGiList.add(mHelper.getDataAt(stateArray.keyAt(i)));
GalleryInfo gi = mHelper.getDataAtEx(stateArray.keyAt(i));
if (gi != null) {
mModifyGiList.add(gi);
}
}
}
@@ -805,41 +824,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 +848,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 +887,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 +895,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();
}
}
}
}
@@ -1011,7 +1008,7 @@ public class FavoritesScene extends BaseScene implements
@Nullable
@Override
public GalleryInfo getDataAt(int position) {
return null != mHelper ? mHelper.getDataAt(position) : null;
return null != mHelper ? mHelper.getDataAtEx(position) : null;
}
}
@@ -1037,13 +1034,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 +1141,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 +1161,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 +1187,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 +1199,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,15 +77,13 @@ 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 junit.framework.Assert;
import java.util.ArrayList;
import java.util.List;
@@ -191,11 +190,11 @@ public final class GalleryCommentsScene extends ToolbarScene
mFab = (FloatingActionButton) ViewUtils.$$(view, R.id.fab);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Resources resources = context.getResources();
int paddingBottomFab = resources.getDimensionPixelOffset(R.dimen.gallery_padding_bottom_fab);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_weird_face);
Drawable drawable = DrawableManager.getVectorDrawable(context, R.drawable.big_sad_pandroid);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
tip.setCompoundDrawables(null, drawable, null, null);
@@ -204,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(),
@@ -321,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
@@ -337,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();
}
@@ -459,7 +458,7 @@ public final class GalleryCommentsScene extends ToolbarScene
return;
}
mFab.setVisibility(View.INVISIBLE);
((View) mFab).setVisibility(View.INVISIBLE);
mEditPanel.setVisibility(View.VISIBLE);
int halfW = mEditPanel.getWidth() / 2;
int halfH = mEditPanel.getHeight() / 2;
@@ -484,7 +483,7 @@ public final class GalleryCommentsScene extends ToolbarScene
return;
}
mFab.setVisibility(View.INVISIBLE);
((View) mFab).setVisibility(View.INVISIBLE);
mEditPanel.setVisibility(View.VISIBLE);
}
}
@@ -507,7 +506,7 @@ public final class GalleryCommentsScene extends ToolbarScene
}
mEditPanel.setVisibility(View.GONE);
mFab.setVisibility(View.VISIBLE);
((View) mFab).setVisibility(View.VISIBLE);
int fabStartX = mEditPanel.getLeft() + (mEditPanel.getWidth() / 2) - (mFab.getWidth() / 2);
int fabStartY = mEditPanel.getTop() + (mEditPanel.getHeight() / 2) - (mFab.getHeight() / 2);
mFab.setX(fabStartX);
@@ -536,7 +535,7 @@ public final class GalleryCommentsScene extends ToolbarScene
return;
}
mFab.setVisibility(View.VISIBLE);
((View) mFab).setVisibility(View.VISIBLE);
mEditPanel.setVisibility(View.INVISIBLE);
}
}
@@ -618,7 +617,7 @@ public final class GalleryCommentsScene extends ToolbarScene
public CommentAdapter() {
mInflater = getLayoutInflater2();
Assert.assertNotNull(mInflater);
AssertUtils.assertNotNull(mInflater);
}
@Override
@@ -636,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);
}
@@ -737,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
+61 -39
View File
@@ -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;
@@ -101,13 +101,12 @@ import com.hippo.widget.LoadImageView;
import com.hippo.widget.ObservedTextView;
import com.hippo.widget.ProgressView;
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 junit.framework.Assert;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
@@ -250,7 +249,7 @@ 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;
@@ -408,7 +407,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
long gid = getGid();
if (gid != -1) {
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
mDownloadState = EhApplication.getDownloadManager(context).getDownloadState(gid);
} else {
mDownloadState = DownloadInfo.STATE_INVALID;
@@ -423,13 +422,14 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
mViewTransition = new ViewTransition(mainView, progressView, mTip);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_weird_face);
Drawable drawable = DrawableManager.getVectorDrawable(context, R.drawable.big_sad_pandroid);
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);
@@ -440,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);
@@ -461,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);
@@ -476,13 +476,13 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
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(mArchive, 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);
@@ -497,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);
@@ -542,7 +542,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
super.onDestroyView();
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
EhApplication.getDownloadManager(context).removeDownloadInfoListener(this);
mTip = null;
@@ -599,7 +599,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
private boolean prepareData() {
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
if (mGalleryDetail != null) {
return true;
@@ -652,21 +652,21 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
private void ensureActionDrawable(Context context) {
Drawable heart = DrawableManager.getDrawable(context, R.drawable.v_heart_primary_x48);
Drawable heart = DrawableManager.getVectorDrawable(context, R.drawable.v_heart_primary_x48);
setActionDrawable(mHeart, heart);
Drawable heartOutline = DrawableManager.getDrawable(context, R.drawable.v_heart_outline_primary_x48);
Drawable heartOutline = DrawableManager.getVectorDrawable(context, R.drawable.v_heart_outline_primary_x48);
setActionDrawable(mHeartOutline, heartOutline);
Drawable torrent = DrawableManager.getDrawable(context, R.drawable.v_utorrent_primary_x48);
Drawable torrent = DrawableManager.getVectorDrawable(context, R.drawable.v_utorrent_primary_x48);
setActionDrawable(mTorrent, torrent);
Drawable archive = DrawableManager.getDrawable(context, R.drawable.v_archive_primary_x48);
Drawable archive = DrawableManager.getVectorDrawable(context, R.drawable.v_archive_primary_x48);
setActionDrawable(mArchive, archive);
Drawable share = DrawableManager.getDrawable(context, R.drawable.v_share_primary_x48);
Drawable share = DrawableManager.getVectorDrawable(context, R.drawable.v_share_primary_x48);
setActionDrawable(mShare, share);
Drawable rate = DrawableManager.getDrawable(context, R.drawable.v_thumb_up_primary_x48);
Drawable rate = DrawableManager.getVectorDrawable(context, R.drawable.v_thumb_up_primary_x48);
setActionDrawable(mRate, rate);
Drawable similar = DrawableManager.getDrawable(context, R.drawable.v_similar_primary_x48);
Drawable similar = DrawableManager.getVectorDrawable(context, R.drawable.v_similar_primary_x48);
setActionDrawable(mSimilar, similar);
Drawable searchCover = DrawableManager.getDrawable(context, R.drawable.v_file_find_primary_x48);
Drawable searchCover = DrawableManager.getVectorDrawable(context, R.drawable.v_file_find_primary_x48);
setActionDrawable(mSearchCover, searchCover);
}
@@ -723,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
@@ -765,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);
@@ -784,7 +789,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
Resources resources = getResources2();
Assert.assertNotNull(resources);
AssertUtils.assertNotNull(resources);
mThumb.load(EhCacheKeyFactory.getThumbKey(gd.gid), gd.thumb);
mTitle.setText(EhUtils.getSuitableTitle(gd));
@@ -829,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);
@@ -960,7 +965,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
private String getAllRatingText(float rating, int ratingCount) {
Resources resources = getResources2();
Assert.assertNotNull(resources);
AssertUtils.assertNotNull(resources);
return resources.getString(R.string.rating_text, getRatingText(rating, resources), rating, ratingCount);
}
@@ -983,7 +988,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
PopupMenu popup = new PopupMenu(context, mOtherActions, Gravity.TOP);
mPopupMenu = popup;
popup.getMenuInflater().inflate(R.menu.scene_gallery_detail, popup.getMenu());
@@ -1532,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;
@@ -1563,10 +1576,19 @@ 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() {}
public void onCancel() {
GalleryDetailScene scene = getScene();
if (scene != null) {
scene.onModifyFavoritesCancel(mAddOrRemove);
}
}
@Override
public boolean isInstance(SceneFragment scene) {
@@ -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,18 @@ 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 junit.framework.Assert;
import java.util.ArrayList;
public final class GalleryInfoScene extends ToolbarScene implements EasyRecyclerView.OnItemClickListener {
@@ -85,7 +84,7 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
}
Resources resources = getResources2();
Assert.assertNotNull(resources);
AssertUtils.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));
@@ -128,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() {
@@ -156,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();
Assert.assertNotNull(context);
AssertUtils.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);
@@ -197,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 {
@@ -231,7 +239,7 @@ public final class GalleryInfoScene extends ToolbarScene implements EasyRecycler
public InfoAdapter() {
mInflater = getLayoutInflater2();
Assert.assertNotNull(mInflater);
AssertUtils.assertNotNull(mInflater);
}
@Override
@@ -49,10 +49,10 @@ 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.app.CheckBoxDialogBuilder;
import com.hippo.app.EditTextDialogBuilder;
import com.hippo.drawable.AddDeleteDrawable;
@@ -70,7 +70,9 @@ import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.data.ListUrlBuilder;
import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.ehviewer.client.parser.GalleryDetailUrlParser;
import com.hippo.ehviewer.client.parser.GalleryListParser;
import com.hippo.ehviewer.client.parser.GalleryPageUrlParser;
import com.hippo.ehviewer.dao.QuickSearch;
import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.ehviewer.ui.MainActivity;
@@ -88,16 +90,15 @@ import com.hippo.widget.ContentLayout;
import com.hippo.widget.FabLayout;
import com.hippo.widget.SearchBarMover;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.SimpleAnimatorListener;
import com.hippo.yorozuya.StringUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.io.File;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collections;
import java.util.List;
public final class GalleryListScene extends BaseScene
@@ -171,7 +172,7 @@ public final class GalleryListScene extends BaseScene
@Override
public void onAnimationEnd(Animator animation) {
if (null != mFabLayout) {
mFabLayout.getPrimaryFab().setVisibility(View.INVISIBLE);
((View) mFabLayout.getPrimaryFab()).setVisibility(View.INVISIBLE);
}
}
};
@@ -257,7 +258,7 @@ public final class GalleryListScene extends BaseScene
super.onCreate(savedInstanceState);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
mClient = EhApplication.getEhClient(context);
if (savedInstanceState == null) {
@@ -304,7 +305,7 @@ public final class GalleryListScene extends BaseScene
private void setSearchBarHint(Context context, SearchBar searchBar) {
Resources resources = context.getResources();
Drawable searchImage = DrawableManager.getDrawable(context, R.drawable.v_magnify_x24);
Drawable searchImage = DrawableManager.getVectorDrawable(context, R.drawable.v_magnify_x24);
SpannableStringBuilder ssb = new SpannableStringBuilder(" ");
ssb.append(resources.getString(EhUrl.SITE_EX == Settings.getGallerySite() ?
R.string.gallery_list_search_bar_hint_exhentai :
@@ -317,6 +318,92 @@ public final class GalleryListScene extends BaseScene
searchBar.setEditTextHint(ssb);
}
private void setSearchBarSuggestionProvider(SearchBar searchBar) {
searchBar.setSuggestionProvider(text -> {
GalleryDetailUrlParser.Result result1 = GalleryDetailUrlParser.parse(text, false);
if (result1 != null) {
return Collections.singletonList(new GalleryDetailUrlSuggestion(result1.gid, result1.token));
}
GalleryPageUrlParser.Result result2 = GalleryPageUrlParser.parse(text, false);
if (result2 != null) {
return Collections.singletonList(new GalleryPageUrlSuggestion(result2.gid, result2.pToken, result2.page));
}
return null;
});
}
private abstract class UrlSuggestion extends SearchBar.Suggestion {
@Override
public CharSequence getText(float textSize) {
Drawable bookImage = DrawableManager.getVectorDrawable(getContext2(), R.drawable.v_book_open_x24);
SpannableStringBuilder ssb = new SpannableStringBuilder(" ");
ssb.append(getResources2().getString(R.string.gallery_list_search_bar_open_gallery));
int imageSize = (int) (textSize * 1.25);
if (bookImage != null) {
bookImage.setBounds(0, 0, imageSize, imageSize);
ssb.setSpan(new ImageSpan(bookImage), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return ssb;
}
@Override
public void onClick() {
startScene(createAnnouncer());
if (mState == STATE_SIMPLE_SEARCH) {
setState(STATE_NORMAL);
} else if (mState == STATE_SEARCH_SHOW_LIST) {
setState(STATE_SEARCH);
}
}
public abstract Announcer createAnnouncer();
@Override
public void onLongClick() { }
}
private class GalleryDetailUrlSuggestion extends UrlSuggestion {
private long mGid;
private String mToken;
private GalleryDetailUrlSuggestion(long gid, String token) {
mGid = gid;
mToken = token;
}
@Override
public Announcer createAnnouncer() {
Bundle args = new Bundle();
args.putString(GalleryDetailScene.KEY_ACTION, GalleryDetailScene.ACTION_GID_TOKEN);
args.putLong(GalleryDetailScene.KEY_GID, mGid);
args.putString(GalleryDetailScene.KEY_TOKEN, mToken);
return new Announcer(GalleryDetailScene.class).setArgs(args);
}
}
private class GalleryPageUrlSuggestion extends UrlSuggestion {
private long mGid;
private String mPToken;
private int mPage;
private GalleryPageUrlSuggestion(long gid, String pToken, int page) {
mGid = gid;
mPToken = pToken;
mPage = page;
}
@Override
public Announcer createAnnouncer() {
Bundle args = new Bundle();
args.putString(ProgressScene.KEY_ACTION, ProgressScene.ACTION_GALLERY_TOKEN);
args.putLong(ProgressScene.KEY_GID, mGid);
args.putString(ProgressScene.KEY_PTOKEN, mPToken);
args.putInt(ProgressScene.KEY_PAGE, mPage);
return new Announcer(ProgressScene.class).setArgs(args);
}
}
@Nullable
private static String getSuitableTitleForUrlBuilder(
Resources resources, ListUrlBuilder urlBuilder, boolean appName) {
@@ -386,7 +473,7 @@ public final class GalleryListScene extends BaseScene
View view = inflater.inflate(R.layout.scene_gallery_list, container, false);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Resources resources = context.getResources();
mHideActionFabSlop = ViewConfiguration.get(context).getScaledTouchSlop();
@@ -414,7 +501,7 @@ public final class GalleryListScene extends BaseScene
mAdapter = new GalleryListAdapter(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);
@@ -427,13 +514,14 @@ public final class GalleryListScene extends BaseScene
refreshLayout.setHeaderTranslationY(paddingTopSB);
mLeftDrawable = new DrawerArrowDrawable(context);
mRightDrawable = new AddDeleteDrawable(context);
mLeftDrawable = new DrawerArrowDrawable(context, AttrResources.getAttrColor(context, R.attr.drawableColorPrimary));
mRightDrawable = new AddDeleteDrawable(context, AttrResources.getAttrColor(context, R.attr.drawableColorPrimary));
mSearchBar.setLeftDrawable(mLeftDrawable);
mSearchBar.setRightDrawable(mRightDrawable);
mSearchBar.setHelper(this);
mSearchBar.setOnStateChangeListener(this);
setSearchBarHint(context, mSearchBar);
setSearchBarSuggestionProvider(mSearchBar);
mSearchLayout.setHelper(this);
mSearchLayout.setPadding(mSearchLayout.getPaddingLeft(), mSearchLayout.getPaddingTop() + paddingTopSB,
@@ -446,8 +534,7 @@ public final class GalleryListScene extends BaseScene
mFabLayout.setOnExpandListener(this);
addAboveSnackView(mFabLayout);
mActionFabDrawable = new AddDeleteDrawable(context);
mActionFabDrawable.setColor(resources.getColor(R.color.primary_drawable_dark));
mActionFabDrawable = new AddDeleteDrawable(context, resources.getColor(R.color.primary_drawable_dark));
mFabLayout.getPrimaryFab().setImageDrawable(mActionFabDrawable);
mSearchFab.setOnClickListener(this);
@@ -632,7 +719,7 @@ public final class GalleryListScene extends BaseScene
final ListView listView = (ListView) ViewUtils.$$(view, R.id.list_view);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
final List<QuickSearch> list = EhDB.getAllQuickSearch();
final ArrayAdapter<QuickSearch> adapter = new ArrayAdapter<>(context, R.layout.item_simple_list, list);
@@ -745,7 +832,11 @@ public final class GalleryListScene extends BaseScene
return false;
}
GalleryInfo gi = mHelper.getDataAt(position);
GalleryInfo gi = mHelper.getDataAtEx(position);
if (gi == null) {
return true;
}
Bundle args = new Bundle();
args.putString(GalleryDetailScene.KEY_ACTION, GalleryDetailScene.ACTION_GALLERY_INFO);
args.putParcelable(GalleryDetailScene.KEY_GALLERY_INFO, gi);
@@ -859,7 +950,11 @@ public final class GalleryListScene extends BaseScene
return false;
}
final GalleryInfo gi = mHelper.getDataAt(position);
final GalleryInfo gi = mHelper.getDataAtEx(position);
if (gi == null) {
return true;
}
new AlertDialog.Builder(context)
.setTitle(EhUtils.getSuitableTitle(gi))
.setItems(R.array.gallery_list_menu_entries, new DialogInterface.OnClickListener() {
@@ -1106,36 +1201,11 @@ public final class GalleryListScene extends BaseScene
}
if (mState == STATE_SEARCH || mState == STATE_SEARCH_SHOW_LIST) {
if (mSearchLayout.isSpecifyGallery()) {
int index = query.indexOf(' ');
if (index <= 0 || index >= query.length() - 1) {
showTip(R.string.error_invalid_specify_gallery, LENGTH_LONG);
return;
}
long gid;
String token;
try {
gid = Long.parseLong(query.substring(0, index));
} catch (NumberFormatException e) {
showTip(R.string.error_invalid_specify_gallery, LENGTH_LONG);
return;
}
token = query.substring(index + 1);
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));
try {
mSearchLayout.formatListUrlBuilder(mUrlBuilder, query);
} catch (EhException e) {
showTip(e.getMessage(), LENGTH_LONG);
return;
} else {
try {
mSearchLayout.formatListUrlBuilder(mUrlBuilder, query);
} catch (EhException e) {
showTip(e.getMessage(), LENGTH_LONG);
return;
}
}
} else {
mUrlBuilder.reset();
@@ -1278,7 +1348,7 @@ public final class GalleryListScene extends BaseScene
@Nullable
@Override
public GalleryInfo getDataAt(int position) {
return null != mHelper ? mHelper.getDataAt(position) : null;
return null != mHelper ? mHelper.getDataAtEx(position) : null;
}
}
@@ -53,11 +53,10 @@ import com.hippo.widget.ContentLayout;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.Slider;
import com.hippo.widget.recyclerview.AutoGridLayoutManager;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.ArrayList;
import java.util.Locale;
@@ -91,7 +90,7 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
super.onCreate(savedInstanceState);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
mClient = EhApplication.getEhClient(context);
if (savedInstanceState == null) {
onInit();
@@ -138,7 +137,7 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
mRecyclerView = contentLayout.getRecyclerView();
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Resources resources = context.getResources();
mAdapter = new GalleryPreviewAdapter();
@@ -232,12 +231,14 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
public boolean onItemClick(EasyRecyclerView parent, View view, int position, long id) {
Context context = getContext2();
if (null != context && null != mHelper && null != mGalleryInfo) {
GalleryPreview p = mHelper.getDataAt(position);
Intent intent = new Intent(context, GalleryActivity.class);
intent.setAction(GalleryActivity.ACTION_EH);
intent.putExtra(GalleryActivity.KEY_GALLERY_INFO, mGalleryInfo);
intent.putExtra(GalleryActivity.KEY_PAGE, p.getPosition());
startActivity(intent);
GalleryPreview p = mHelper.getDataAtEx(position);
if (p != null) {
Intent intent = new Intent(context, GalleryActivity.class);
intent.setAction(GalleryActivity.ACTION_EH);
intent.putExtra(GalleryActivity.KEY_GALLERY_INFO, mGalleryInfo);
intent.putExtra(GalleryActivity.KEY_PAGE, p.getPosition());
startActivity(intent);
}
}
return true;
}
@@ -261,7 +262,7 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
public GalleryPreviewAdapter() {
mInflater = getLayoutInflater2();
Assert.assertNotNull(mInflater);
AssertUtils.assertNotNull(mInflater);
}
@Override
@@ -273,9 +274,11 @@ public class GalleryPreviewsScene extends ToolbarScene implements EasyRecyclerVi
@SuppressLint("SetTextI18n")
public void onBindViewHolder(GalleryPreviewHolder holder, int position) {
if (null != mHelper) {
GalleryPreview preview = mHelper.getDataAt(position);
preview.load(holder.image);
holder.text.setText(Integer.toString(preview.getPosition() + 1));
GalleryPreview preview = mHelper.getDataAtEx(position);
if (preview != null) {
preview.load(holder.image);
holder.text.setText(Integer.toString(preview.getPosition() + 1));
}
}
}
@@ -31,7 +31,6 @@ import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.h6ah4i.android.widget.advrecyclerview.animator.GeneralItemAnimator;
import com.h6ah4i.android.widget.advrecyclerview.animator.SwipeDismissItemAnimator;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.RecyclerViewSwipeManager;
@@ -42,6 +41,7 @@ import com.h6ah4i.android.widget.advrecyclerview.swipeable.action.SwipeResultAct
import com.h6ah4i.android.widget.advrecyclerview.swipeable.action.SwipeResultActionRemoveItem;
import com.h6ah4i.android.widget.advrecyclerview.touchguard.RecyclerViewTouchActionGuardManager;
import com.h6ah4i.android.widget.advrecyclerview.utils.AbstractSwipeableItemViewHolder;
import com.hippo.android.resource.AttrResources;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.FastScroller;
import com.hippo.easyrecyclerview.HandlerDrawable;
@@ -64,11 +64,8 @@ import com.hippo.util.DrawableManager;
import com.hippo.view.ViewTransition;
import com.hippo.widget.LoadImageView;
import com.hippo.widget.recyclerview.AutoStaggeredGridLayoutManager;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import de.greenrobot.dao.query.LazyList;
public class HistoryScene extends ToolbarScene
@@ -104,10 +101,10 @@ public class HistoryScene extends ToolbarScene
mViewTransition = new ViewTransition(content, tip);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Resources resources = context.getResources();
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_history);
Drawable drawable = DrawableManager.getVectorDrawable(context, R.drawable.big_history);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
tip.setCompoundDrawables(null, drawable, null, null);
@@ -127,7 +124,7 @@ public class HistoryScene extends ToolbarScene
layoutManager.setColumnSize(resources.getDimensionPixelOffset(Settings.getDetailSizeResId()));
layoutManager.setStrategy(AutoStaggeredGridLayoutManager.STRATEGY_MIN_SIZE);
mRecyclerView.setLayoutManager(layoutManager);
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);
@@ -144,7 +141,7 @@ public class HistoryScene 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);
updateLazyList();
@@ -293,6 +290,7 @@ public class HistoryScene extends ToolbarScene
private class HistoryHolder extends AbstractSwipeableItemViewHolder {
public final View card;
public final LoadImageView thumb;
public final TextView title;
public final TextView uploader;
@@ -304,6 +302,7 @@ public class HistoryScene extends ToolbarScene
public HistoryHolder(View itemView) {
super(itemView);
card = itemView.findViewById(R.id.card);
thumb = (LoadImageView) itemView.findViewById(R.id.thumb);
title = (TextView) itemView.findViewById(R.id.title);
uploader = (TextView) itemView.findViewById(R.id.uploader);
@@ -315,7 +314,7 @@ public class HistoryScene extends ToolbarScene
@Override
public View getSwipeableContainerView() {
return itemView;
return card;
}
}
@@ -323,9 +322,16 @@ public class HistoryScene extends ToolbarScene
implements SwipeableItemAdapter<HistoryHolder> {
private final LayoutInflater mInflater;
private final int mListThumbWidth;
private final int mListThumbHeight;
public HistoryAdapter() {
mInflater = getLayoutInflater2();
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
@@ -339,7 +345,14 @@ public class HistoryScene extends ToolbarScene
@Override
public HistoryHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new HistoryHolder(mInflater.inflate(R.layout.item_gallery_list, parent, false));
HistoryHolder holder = new HistoryHolder(mInflater.inflate(R.layout.item_history, parent, false));
ViewGroup.LayoutParams lp = holder.thumb.getLayoutParams();
lp.width = mListThumbWidth;
lp.height = mListThumbHeight;
holder.thumb.setLayoutParams(lp);
return holder;
}
@Override
@@ -376,9 +389,12 @@ public class HistoryScene extends ToolbarScene
@Override
public int onGetSwipeReactionType(HistoryHolder holder, int position, int x, int y) {
return SwipeableItemConstants.REACTION_CAN_SWIPE_BOTH_H;
return SwipeableItemConstants.REACTION_CAN_SWIPE_LEFT;
}
@Override
public void onSwipeItemStarted(HistoryHolder holder, int position) { }
@Override
public void onSetSwipeBackground(HistoryHolder holder, int position, int type) {}
@@ -386,8 +402,8 @@ public class HistoryScene extends ToolbarScene
public SwipeResultAction onSwipeItem(HistoryHolder holder, int position, int result) {
switch (result) {
case SwipeableItemConstants.RESULT_SWIPED_LEFT:
case SwipeableItemConstants.RESULT_SWIPED_RIGHT:
return new SwipeResultActionClear(position);
case SwipeableItemConstants.RESULT_SWIPED_RIGHT:
case SwipeableItemConstants.RESULT_CANCELED:
default:
return new SwipeResultActionDefault();
@@ -25,7 +25,6 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhClient;
@@ -36,10 +35,9 @@ import com.hippo.scene.SceneFragment;
import com.hippo.util.DrawableManager;
import com.hippo.util.ExceptionUtils;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
/**
* Only show a progress with jobs in background
*/
@@ -170,9 +168,9 @@ public final class ProgressScene extends BaseScene implements View.OnClickListen
mTip = (TextView) ViewUtils.$$(view, R.id.tip);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_weird_face);
Drawable drawable = DrawableManager.getVectorDrawable(context, R.drawable.big_sad_pandroid);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
mTip.setCompoundDrawables(null, drawable, null, null);
mTip.setOnClickListener(this);
@@ -29,30 +29,21 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.h6ah4i.android.widget.advrecyclerview.animator.GeneralItemAnimator;
import com.h6ah4i.android.widget.advrecyclerview.animator.SwipeDismissItemAnimator;
import com.h6ah4i.android.widget.advrecyclerview.draggable.DraggableItemAdapter;
import com.h6ah4i.android.widget.advrecyclerview.draggable.ItemDraggableRange;
import com.h6ah4i.android.widget.advrecyclerview.draggable.RecyclerViewDragDropManager;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.RecyclerViewSwipeManager;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.SwipeableItemAdapter;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.SwipeableItemConstants;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.action.SwipeResultAction;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.action.SwipeResultActionDefault;
import com.h6ah4i.android.widget.advrecyclerview.swipeable.action.SwipeResultActionMoveToSwipedDirection;
import com.h6ah4i.android.widget.advrecyclerview.touchguard.RecyclerViewTouchActionGuardManager;
import com.h6ah4i.android.widget.advrecyclerview.utils.AbstractDraggableSwipeableItemViewHolder;
import com.h6ah4i.android.widget.advrecyclerview.utils.AbstractDraggableItemViewHolder;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.dao.QuickSearch;
import com.hippo.util.DrawableManager;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ViewUtils;
import junit.framework.Assert;
import java.util.List;
public final class QuickSearchScene extends ToolbarScene {
@@ -97,9 +88,9 @@ public final class QuickSearchScene extends ToolbarScene {
mViewTransition = new ViewTransition(mRecyclerView, tip);
Context context = getContext2();
Assert.assertNotNull(context);
AssertUtils.assertNotNull(context);
Drawable drawable = DrawableManager.getDrawable(context, R.drawable.big_search);
Drawable drawable = DrawableManager.getVectorDrawable(context, R.drawable.big_search);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
tip.setCompoundDrawables(null, drawable, null, null);
tip.setText(R.string.no_quick_search);
@@ -113,11 +104,9 @@ public final class QuickSearchScene extends ToolbarScene {
dragDropManager.setDraggingItemShadowDrawable(
(NinePatchDrawable) context.getResources().getDrawable(R.drawable.shadow_8dp));
// swipe manager
RecyclerViewSwipeManager swipeManager = new RecyclerViewSwipeManager();
RecyclerView.Adapter adapter = new QuickSearchAdapter();
adapter.setHasStableIds(true);
adapter = dragDropManager.createWrappedAdapter(adapter); // wrap for dragging
adapter = swipeManager.createWrappedAdapter(adapter); // wrap for swiping
mAdapter = adapter;
final GeneralItemAnimator animator = new SwipeDismissItemAnimator();
animator.setSupportsChangeAnimations(false);
@@ -126,7 +115,6 @@ public final class QuickSearchScene extends ToolbarScene {
mRecyclerView.setAdapter(adapter);
mRecyclerView.setItemAnimator(animator);
guardManager.attachRecyclerView(mRecyclerView);
swipeManager.attachRecyclerView(mRecyclerView);
dragDropManager.attachRecyclerView(mRecyclerView);
updateView();
@@ -151,7 +139,6 @@ public final class QuickSearchScene extends ToolbarScene {
}
mViewTransition = null;
mAdapter = null;
}
@Override
@@ -169,41 +156,66 @@ public final class QuickSearchScene extends ToolbarScene {
}
}
private class QuickSearchHolder extends AbstractDraggableSwipeableItemViewHolder {
private class QuickSearchHolder extends AbstractDraggableItemViewHolder implements View.OnClickListener {
public final View swipeHandler;
public final TextView label;
public final View dragHandler;
public final View delete;
public QuickSearchHolder(View itemView) {
super(itemView);
swipeHandler = ViewUtils.$$(itemView, R.id.swipe_handler);
label = (TextView) ViewUtils.$$(itemView, R.id.label);
dragHandler = ViewUtils.$$(itemView, R.id.drag_handler);
delete = ViewUtils.$$(itemView, R.id.delete);
delete.setOnClickListener(this);
}
@Override
public View getSwipeableContainerView() {
return swipeHandler;
public void onClick(View v) {
int position = getAdapterPosition();
Context context = getContext2();
if (position == RecyclerView.NO_POSITION || mQuickSearchList == null) {
return;
}
final QuickSearch quickSearch = mQuickSearchList.get(position);
new AlertDialog.Builder(context)
.setTitle(R.string.delete_quick_search_title)
.setMessage(getString(R.string.delete_quick_search_message, quickSearch.name))
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EhDB.deleteQuickSearch(quickSearch);
mQuickSearchList.remove(position);
}
})
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
if (null != mAdapter) {
mAdapter.notifyDataSetChanged();
}
updateView();
}
}).show();
}
}
private class QuickSearchAdapter extends RecyclerView.Adapter<QuickSearchHolder>
implements DraggableItemAdapter<QuickSearchHolder>,
SwipeableItemAdapter<QuickSearchHolder> {
implements DraggableItemAdapter<QuickSearchHolder> {
private final LayoutInflater mInflater;
public QuickSearchAdapter() {
mInflater = getLayoutInflater2();
Assert.assertNotNull(mInflater);
AssertUtils.assertNotNull(mInflater);
}
@Override
public QuickSearchHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new QuickSearchHolder(mInflater.inflate(R.layout.item_label_list, parent, false));
return new QuickSearchHolder(mInflater.inflate(R.layout.item_quick_search, parent, false));
}
@Override
@@ -211,7 +223,6 @@ public final class QuickSearchScene extends ToolbarScene {
if (mQuickSearchList != null) {
holder.label.setText(mQuickSearchList.get(position).name);
}
holder.setSwipeItemHorizontalSlideAmount(0);
}
@Override
@@ -255,71 +266,9 @@ public final class QuickSearchScene extends ToolbarScene {
}
@Override
public int onGetSwipeReactionType(QuickSearchHolder holder, int position, int x, int y) {
if (ViewUtils.isViewUnder(holder.getSwipeableContainerView(), x, y, 0)) {
return SwipeableItemConstants.REACTION_CAN_SWIPE_LEFT;
} else {
return SwipeableItemConstants.REACTION_CAN_NOT_SWIPE_BOTH_H;
}
}
public void onItemDragStarted(int position) { }
@Override
public void onSetSwipeBackground(QuickSearchHolder holder, int position, int type) {}
@Override
public SwipeResultAction onSwipeItem(QuickSearchHolder holder, int position, int result) {
switch (result) {
// swipe left --- pin
case SwipeableItemConstants.RESULT_SWIPED_LEFT:
return new SwipeLeftResultAction(position);
// other --- do nothing
case SwipeableItemConstants.RESULT_SWIPED_RIGHT:
case SwipeableItemConstants.RESULT_CANCELED:
default:
return new SwipeResultActionDefault();
}
}
}
private class SwipeLeftResultAction extends SwipeResultActionMoveToSwipedDirection {
private final int mPosition;
public SwipeLeftResultAction(int position) {
mPosition = position;
}
@Override
protected void onPerformAction() {
super.onPerformAction();
Context context = getContext2();
final List<QuickSearch> quickSearchList = mQuickSearchList;
if (null == context || null == quickSearchList || mPosition < 0 || mPosition >= quickSearchList.size()) {
return;
}
final QuickSearch quickSearch = quickSearchList.get(mPosition);
new AlertDialog.Builder(context)
.setTitle(R.string.delete_quick_search_title)
.setMessage(getString(R.string.delete_quick_search_message, quickSearch.name))
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EhDB.deleteQuickSearch(quickSearch);
quickSearchList.remove(mPosition);
}
})
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
if (null != mAdapter) {
mAdapter.notifyDataSetChanged();
}
updateView();
}
}).show();
}
public void onItemDragFinished(int fromPosition, int toPosition, boolean result) { }
}
}
Loaded 100 of 322 files, more files were not shown because too many files have changed in this diff. Show more