1
0
Fork 0
mirror of https://github.com/gsantner/dandelion synced 2025-09-08 17:59:42 +02:00

Compare commits

...

167 commits

Author SHA1 Message Date
Gregor Santner
774c5bec59 Merge dandelion news and FAQ content all into markdown files in the dandelion repository 2023-02-11 03:07:41 +01:00
Gregor Santner
c65aab3840 Update translations, project info 2023-01-28 17:21:07 +01:00
Gregor Santner
c2bea7bec0 Crowdin add Estonian, Update translations (PR #297) 2022-12-08 14:16:52 +01:00
Gregor Santner
36bd1af0b9 Translations: Add bulgarian 2022-07-13 01:51:31 +02:00
Gregor Santner
67b0bbbfd2
Update translations (PR #294) 2022-05-28 19:03:18 +00:00
Gregor Santner
b80cc3ab04 Add croatian & thai language to translation system 2022-05-28 20:55:42 +02:00
Gregor Santner
37f586912f
Change link to domain podupti.me -> diaspora.fediverse.observer, closes #295, by @gsantner 2021-10-09 20:17:11 +02:00
Gregor Santner
de378b8adc Add language Odia/Oriya (India), Update translations (#293) 2021-10-02 13:04:29 +02:00
Gregor Santner
8161353de7
New Crowdin updates (#292) 2021-09-09 22:46:37 +02:00
Gregor Santner
c42b4995b3 Update crowdin config 2021-09-09 22:43:58 +02:00
Gregor Santner
5a5d1d66b3 Update CHANGELOG 2021-08-01 14:31:44 +02:00
Gregor Santner
ceb0002546 Update translations (PR #286) 2021-08-01 14:12:24 +02:00
James Addison
0cf003ea38
Update README screenshot references (PR #291) 2021-08-01 13:38:59 +02:00
Gregor Santner
904f2af20a
Update gs/opoc utilities 2021-08-01 13:30:21 +02:00
Gregor Santner
d923630b42
Update README badges, remove IRC 2021-05-19 20:48:50 +02:00
Gregor Santner
a76a463cd4
Add language Esperanto, by @gsantner 2021-03-13 14:25:09 +01:00
Gregor Santner
c9c10a6fd4
Add language Sinhala (Sri Lanka) 2021-02-28 22:09:03 +01:00
Gregor Santner
e5866ffb2b
Update opoc 2021-01-18 21:32:50 +01:00
Gregor Santner
97d9bf434e
Various additions & improvements to opoc utils 2021-01-12 20:23:10 +01:00
Gregor Santner
f1464b5f8f
ci add comment for cleanup as github has no delete-all button 2020-12-23 14:45:38 +01:00
Gregor Santner
369abf14a5
CI/CD: Remove special junit/lint jobs 2020-12-22 03:39:33 +01:00
Gregor Santner
ceb98c4258
gh actions pull_request action 2020-12-21 23:50:58 +01:00
Gregor Santner
4ebd393250
Update v1.3.5 (translations/libs only) 2020-12-09 12:08:05 +01:00
Gregor Santner
f3b3c6a160
disable AndroidSupportMeWrapper 2020-12-09 11:59:36 +01:00
Gregor Santner
ff62aa5a07 Add Makefile; CI: Remove Circle/Travis, add GitHub Actions 2020-12-09 01:07:24 +01:00
Gregor Santner
6fbd399a4b
Update gsantner/opoc libs/utils 2020-12-09 00:57:31 +01:00
Gregor Santner
fa7e37ccba
Remove Travis CI - Open Source love is gone 2020-12-08 08:41:38 +01:00
Gregor Santner
20d75acd39
New Crowdin updates (#276) 2020-12-05 22:08:40 +01:00
Gregor Santner
7b1897b2e0 crowdin: Add macedonian 2020-11-13 21:56:27 +01:00
Gregor Santner
93aadae64b
[ci skip] Crowdin translation bot: New translations for Swedish (#272) 2020-09-24 23:18:12 +02:00
Gregor Santner
a7dd4a6166
New Crowdin translations (#267) 2020-05-29 21:27:09 +00:00
Gregor Santner
cf1f0100ba
Update crowdin bot commit message template 2020-05-29 23:22:35 +02:00
Gregor Santner
875f613cd9
Update supportme link to https 2020-04-20 02:01:40 +02:00
Gregor Santner
ea1ee6bc40 Update opoc 2020-03-29 19:53:32 +02:00
Gregor Santner
a66d7bf3b2 New Crowdin translations (#264) 2020-03-29 19:33:19 +02:00
Gregor Santner
c5849d7d6a Release v1.3.4 2020-02-09 13:12:59 +01:00
Gregor Santner
cc16b84011 Add seconds to 'save picture' date format, closes #262 2020-02-09 13:12:07 +01:00
Gregor Santner
0f6b1c3ec3
Update opoc 2020-02-09 12:49:26 +01:00
Gregor Santner
a686fea141 Bump junit from 4.12 to 4.13 (#261); New Crowdin translations (#260, #263) 2020-02-09 12:46:29 +01:00
Gregor Santner
f9951f3b16 Release v1.3.3 2019-12-23 21:21:10 +01:00
Gregor Santner
073a688db9
New Crowdin translations (#259) 2019-12-23 20:18:54 +00:00
Gregor Santner
1f3cde9326
Add albanian / Tamil 2019-12-23 21:11:39 +01:00
Gregor Santner
8326c2196c
Update tools 2019-12-06 22:02:24 +01:00
Gregor Santner
7361d4bc3f
Update opoc
Update shared helper utilities of my projects to latest state
2019-11-20 00:34:10 +01:00
Gregor Santner
1948c28cff
Crowdin: Update language mapping 2019-11-04 14:18:40 +01:00
Gregor Santner
d1be7f5215 Bump gradle from 3.5.0 to 3.5.1 (#254) 2019-10-04 01:38:43 +02:00
Gregor Santner
8d019b6c3b
New Crowdin translations (#253) 2019-09-22 13:55:33 +00:00
Gregor Santner
0708fcb02b
Update list of languages for crowdin 2019-09-22 13:35:33 +02:00
Gregor Santner
c5e3a42005
Update opoc 2019-09-07 21:54:08 +02:00
Gregor Santner
8c3c7da2ab
Release v1.3.2 2019-08-25 14:19:19 +02:00
Gregor Santner
3bc6afad03
Fix getDateOfDaysAgo 2019-08-25 14:07:07 +02:00
Gregor Santner
194fbf6927 Rename test flavor to atest (so it's default dev flavor when starting android studio) 2019-08-24 14:54:25 +02:00
dependabot-preview[bot]
6d45620181 Bump gradle from 3.4.2 to 3.5.0 (#250) 2019-08-21 12:22:56 +00:00
Gregor Santner
c9d3693515
New Crowdin translations (#245) 2019-07-26 01:28:14 +00:00
Gregor Santner
a618da97d8
Update opoc 2019-07-26 03:19:28 +02:00
imgbot[bot]
3ec8ab89c6 [ImgBot] Optimize images (#247)
*Total -- 1,011.84kb -> 914.41kb (9.63%)

/app/src/flavorTest/res/drawable-ldpi/ic_launcher.png -- 1.50kb -> 1.24kb (17.35%)
/app/src/main/res/drawable-ldpi/ic_launcher.png -- 1.67kb -> 1.40kb (16.03%)
/metadata/en-US/promoGraphic.png -- 3.58kb -> 3.04kb (15.17%)
/app/src/flavorDandelior/ic_launcher-web.png -- 29.94kb -> 26.33kb (12.05%)
/metadata/en-US/featureGraphic.png -- 861.38kb -> 773.90kb (10.16%)
/app/src/flavorDandelior/res/drawable-xhdpi/ic_launcher.png -- 9.28kb -> 8.74kb (5.83%)
/app/src/flavorDandelior/res/drawable-xhdpi/ic_launcher_round.png -- 9.28kb -> 8.74kb (5.83%)
/app/src/flavorDandelior/res/drawable-hdpi/ic_launcher_round.png -- 8.01kb -> 7.58kb (5.36%)
/app/src/flavorDandelior/res/drawable-hdpi/ic_launcher.png -- 8.01kb -> 7.58kb (5.36%)
/app/src/flavorDandelior/res/drawable-xxhdpi/ic_launcher_round.png -- 11.90kb -> 11.28kb (5.19%)
/app/src/flavorDandelior/res/drawable-xxhdpi/ic_launcher.png -- 11.90kb -> 11.28kb (5.19%)
/app/src/flavorDandelior/res/drawable-xxxhdpi/ic_launcher_round.png -- 14.72kb -> 14.08kb (4.31%)
/app/src/flavorDandelior/res/drawable-xxxhdpi/ic_launcher.png -- 14.72kb -> 14.08kb (4.31%)
/app/src/flavorDandelior/res/drawable-mdpi/ic_launcher_round.png -- 6.80kb -> 6.58kb (3.33%)
/app/src/flavorDandelior/res/drawable-mdpi/ic_launcher.png -- 6.80kb -> 6.58kb (3.33%)
/app/src/flavorDandelior/res/drawable-ldpi/ic_launcher_round.png -- 6.17kb -> 5.99kb (2.96%)
/app/src/flavorDandelior/res/drawable-ldpi/ic_launcher.png -- 6.17kb -> 5.99kb (2.96%)

Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com>
2019-07-26 00:35:39 +00:00
Gregor Santner
938a54fc74
Release v1.3.1 2019-04-26 00:55:53 +02:00
Gregor Santner
0732fe1b91
New Crowdin translations (#243) 2019-04-25 22:53:54 +00:00
Gregor Santner
a7054d3ff8 Update metadata 2019-04-21 15:57:49 +02:00
25020c1692
Merge pull request #240 from vanitasvitae/de_metadata
German translation of metadata
2019-03-11 15:51:39 +01:00
b1fb5d646a
German translation of metadata 2019-03-11 14:10:35 +01:00
Gregor Santner
51c3f68f22 Release v1.3.0 2019-03-08 14:49:29 +01:00
Gregor Santner
a80f6ebb45 New Crowdin translations (#238) 2019-03-08 14:45:02 +01:00
Gregor Santner
49c6a97ce7 Add AndroidSupportMeWrapper 2019-03-08 12:32:10 +01:00
Gregor Santner
4f44d1acd3
New Crowdin translations (#231) 2019-02-07 09:38:41 +00:00
Gregor Santner
24571f6921
Auto reformat code 2019-02-07 10:31:18 +01:00
massimilianoLe
fb8eb60974 pullRefresh as option + Shortcut to settings @themesettings (#226)
* pull to refresh page

* Make youtube links open external

* corrected a bit but still not able to check if app is installed

* corrected triggersync

* Added option For user to choose how to open youtube links

* removed unecessary comment

* update with dandelion

* pull refresh option+shortcut to themes

* Changes request applyed

* added name in contributors list
2019-02-07 09:25:06 +00:00
Gregor Santner
b833311353 Release v1.2.5 2019-01-11 02:43:53 +01:00
Gregor Santner
6f310985d6 Update gradle tooling & gsantner-opoc 2019-01-11 02:38:30 +01:00
Gregor Santner
6d62c70359
New Crowdin translations (#224) 2019-01-11 00:16:10 +00:00
Gregor Santner
d34cbe1ed1
Remove/move serbian 2019-01-11 01:11:05 +01:00
Gregor Santner
66cbf9a47d update crowdin yaml 2019-01-11 00:56:13 +01:00
Gregor Santner
b1d5e980c2
New Crowdin translations (#221) 2019-01-10 23:31:30 +00:00
massimilianoLe
f693418d64 Make youtube links open external, by @massimilianoLe (#220) 2018-12-01 17:12:04 +01:00
Gregor Santner
04e89e516c
New Crowdin translations (#218) 2018-11-23 10:31:00 +01:00
massimilianoLe
5854075080 pull to refresh page (#219) 2018-11-23 10:28:37 +01:00
Gregor Santner
1f8babd708 Release v1.2.3 2018-11-12 01:33:36 +01:00
Gregor Santner
2618bdf5ad
New Crowdin translations (#214) 2018-11-12 01:25:36 +01:00
Gregor Santner
19884c33c1
New Crowdin translations (#212) 2018-10-09 20:57:57 +02:00
Gregor Santner
2289c04f0f Update opoc and it's license headers 2018-10-01 21:12:17 +02:00
Gregor Santner
1129f1848a
New Crowdin translations (#210) 2018-09-27 11:17:17 +02:00
Gregor Santner
c77fd1db01
add more language remappings for crowdin 2018-09-27 11:13:25 +02:00
Gregor Santner
b072111b8b
add more language remappings for crowdin 2018-09-27 10:58:04 +02:00
Gregor Santner
351b2d6447
Mark only strings.xml as translatable on crowdin 2018-09-27 10:49:31 +02:00
Gregor Santner
ddc2549c66 Update Crowdin configuration file 2018-09-25 17:55:04 +02:00
Gregor Santner
c1d34fc5db
Merge pull request #204 from muhaaliss/stringlate-tr-9470
Updated tr (Turkish) translation, by @muhaaliss
2018-09-16 09:32:10 +02:00
Muha Aliss
33db3656fa Updated tr (Turkish) translation
Commit made via Stringlate
2018-09-16 03:17:33 +03:00
Gregor Santner
e194d2159e
Add @vanitasvitae 's unfinished image-viewer patch (deleted all test/demo branches for cleanup 2018-09-05 17:00:04 +02:00
Gregor Santner
e66c72d255 release v1.2.2 2018-09-04 20:00:55 +02:00
Gregor Santner
4cd88400ee Rework string ids to tell content 2018-09-04 19:16:51 +02:00
Gregor Santner
48a00b099e
. 2018-09-04 17:02:34 +02:00
Gregor Santner
e6b2fa606e
Merge pull request #201 from asereze/patch-1
Updated sc (Sardinian) translation xml file
2018-08-07 23:59:30 +02:00
asereze
0b66ef801f
Updated sc (Sardinian) translation xml file
I hope it's ok now.
2018-08-07 23:43:07 +02:00
Gregor Santner
e1ea19f02a Release v1.2.1 2018-08-06 23:36:04 +02:00
Gregor Santner
af9e3ad8a3
Update metadata 2018-07-30 21:40:30 +02:00
Gregor Santner
d76fe4b82b
Update metadata 2018-07-30 13:32:34 +02:00
Gregor Santner
dc07beafc3
Merge pull request #199 from xmgz/master
galician (gl) strings.xml updated, by @xmgz (#199)
2018-07-29 11:55:29 +02:00
Xosé M
423970ce39 faltaban 3 cadeas 2018-07-29 10:30:51 +02:00
Xosé M
215f67308e eliminar string preferences e about 2018-07-29 09:54:34 +02:00
Xosé M
376449486b minor gl fixes 2018-07-29 09:50:16 +02:00
Gregor Santner
1e15374229 Release v1.2.0 2018-07-25 03:30:28 +02:00
Gregor Santner
dbbd3cef35 Use searchable dialog for tag and aspect/contact list
* Remove seperate fragments for both cases
* Make use of opoc/SearchOrCustomTextDialog
* Basically also removes all fragment swaps
  * Only two fragments are stream and podselection
  * Pod logout restarts app
  * Thus long known Android Supportlib bug can't occur

* Fixes #198
2018-07-25 01:59:25 +02:00
Gregor Santner
918adcf358 Add flavor dandelior*, move flavor specific to folder instead gradle generated 2018-07-22 14:03:29 +02:00
Gregor Santner
957573ea83 Update opoc 2018-05-21 14:57:41 +02:00
Gregor Santner
65ba10712f Update paths 2018-05-13 12:08:27 +02:00
Gregor Santner
099eb9ca78
Update supportlib 2018-05-09 03:25:23 +02:00
Gregor Santner
ad3966dd85
Merge string resources to one file, propagte change to all translations 2018-05-09 03:23:12 +02:00
Gregor Santner
9a6798f9f4
Update french translation, by @arnaud-jacquemin, (closes #196) 2018-05-09 03:00:33 +02:00
Gregor Santner
2cc74ea613
Release v1.1.3 2018-04-08 22:10:53 +02:00
Gregor Santner
cebf0f473b
Fix podselection custom button color 2018-04-08 22:08:21 +02:00
Gregor Santner
9da1a910b3
Add existingconnection to opoc:networkutils:performCall 2018-04-08 20:12:51 +02:00
Gregor Santner
38cf36b46c Improve sharing *a lot* +GIF - add support for multiple filetypes
* now supporting GIFs too ;)
* Create connection over netcipher
2018-04-08 19:11:12 +02:00
Gregor Santner
68be2f3a4a
Load README when ow pod URL gets called and no pod selected , fixes #193 2018-04-08 18:05:56 +02:00
Gregor Santner
51093e0c3d
Rework screenshot saving and sharing; add new share options:
* Share option: Launcher shortcut (fixes #170)
* Share option: Copy link of current page to clipboard
* Share otpion: Export as PDF / print
2018-04-08 17:52:04 +02:00
Gregor Santner
d53128e5cb
Merge license and changelog dialog on first start 2018-04-08 09:01:52 +02:00
Gregor Santner
82ccc54436
Add FF Klar to custom tabs list 2018-04-08 08:44:00 +02:00
Gregor Santner
f6ab146fd7
Update github templates 2018-04-03 23:23:16 +02:00
Gregor Santner
80f8f10bf9 Release v1.1.2 2018-03-30 03:03:19 +02:00
Gregor Santner
dcc8728171 Update changelog
* fixes #180
2018-03-30 02:52:20 +02:00
Gregor Santner
b48dc5dcac
Fix loading non-pod links outside customtab/external browser 2018-03-30 02:46:44 +02:00
Gregor Santner
618f3eaaba
Fix webview-js dialog not dismissing correctly 2018-03-30 01:41:43 +02:00
Gregor Santner
08242760bb
Migrate to opoc/basefragment; Fix redundant casts 2018-03-30 00:38:31 +02:00
Gregor Santner
a88dc5d13c
. 2018-03-30 00:24:52 +02:00
Gregor Santner
586875e32b
Update gsantner-opoc to latest state 2018-03-30 00:14:54 +02:00
Gregor Santner
43a2ad25bc Update opoc license headers 2018-03-12 00:05:53 +01:00
Gregor Santner
6cac47763c
Release v1.1.1 2018-03-05 23:45:10 +01:00
Gregor Santner
5921549a9c Fix secondlion BuildConfig, githash 2018-03-05 23:37:24 +01:00
Gregor Santner
07acb6bd02 Redo icon as adaptive icon 2018-03-05 14:23:51 +01:00
Gregor Santner
dd0432f718 Update to latest opoc version
* Move various clases
* Especially improve language preference, backported from compat lib
2018-03-02 15:56:14 +01:00
x m l p
1bb061b563 Update galician translation, by @xmgz (#189) 2018-02-22 22:42:50 +01:00
XoseM
d8d74de22b actualizando o galego 2018-02-21 12:36:28 +01:00
XoseM
8df13fe283 Merge branch 'master' of https://github.com/xmgz/dandelion
pideumo o git
2018-02-21 12:32:21 +01:00
XoseM
724a0dbc9c actualizando a gl-translation 2018-02-21 12:31:45 +01:00
XoseM
1f873e2057 fixed strings from gl-tranlation branch 2018-02-21 12:14:48 +01:00
x m l p
ea66b57979
Update .gitignore 2018-02-21 12:02:03 +01:00
XoseM
cbb98f7c60 editando desde gl-translation 2018-02-21 11:51:25 +01:00
XoseM
ed511bec01 update using git help from gsantner 2018-02-21 11:45:02 +01:00
Xosé M
204429b8d5 engadido cómo traducir 2018-02-21 08:31:04 +01:00
Xosé M
120c48f702 actualizando segundo contexto 2018-02-21 08:02:47 +01:00
Gregor Santner
e4992870fe
Release v1.1.0 2018-02-07 00:17:24 +01:00
Gregor Santner
be4309ecd6
Replace shortcut's icons with vectors 2018-02-07 00:13:42 +01:00
Gregor Santner
a07bc144d8
Remove line breaks from fdroid metadata 2018-02-06 23:21:10 +01:00
Gregor Santner
3442f018e9
Update buildscript 2018-02-06 23:11:18 +01:00
8aec1aa74f Update podlink dorf-post.de (fix #181) (#184) 2018-01-15 22:52:04 +01:00
Gaukler Faun
a3cb818db4 implemented app shortcuts, template svg-file for shortcut icons (#183) 2018-01-07 16:03:02 +01:00
Xosé M. Lamas
15240fca49 pequenos erros tipográficos 2017-11-30 08:37:16 +01:00
Xose M
32a74e293a 1a modificacion en github (#179) 2017-11-28 10:15:54 +01:00
XoseM
b1c2219b4d 1ª modificación en github 2017-11-28 09:47:44 +01:00
Gregor Santner
7215cbd7e6
Update sc localization
* Closes #177
2017-11-24 00:55:43 +01:00
Gregor Santner
06119a52cd
Update github templates 2017-11-24 00:21:56 +01:00
Daria Szatan
755adb2ad9 Polish translation (#176)
Polish translation
2017-11-23 18:07:50 +01:00
Gregor Santner
1a99d53c5d
Last crowdin translation update 2017-11-22 21:02:12 +01:00
Gregor Santner
28dac50d84
Update and improve buildscript 2017-11-18 20:04:59 +01:00
Aditya Mehta
255c6d650e replaced traditional file sharing with FileProvider (#174)
replaced traditional file sharing with FileProvider (fixes #173)
2017-11-01 05:23:19 +01:00
Gregor Santner
8ac5c2dee9 Update translations 2017-10-31 18:12:02 +01:00
Gregor Santner
0393bf274f
Fix lint warnings in opoc ; update langprefs; more power for contextutils 2017-10-31 14:18:52 +01:00
Gregor Santner
d1c4e68df3
Release v1.0.8 2017-10-29 19:39:37 +01:00
Gregor Santner
08c450fc99
Update readme 2017-10-29 19:35:35 +01:00
Gregor Santner
ae226c9e16
Add metadata again 2017-10-29 18:05:49 +01:00
Gregor Santner
086f056216 Modify toolbar item positions 2017-10-29 17:26:13 +01:00
Gregor Santner
d1d2d7b4d1 Fix drawable lint issues 2017-10-29 15:33:59 +01:00
Gregor Santner
a96e91aefb
Top toolbar with overflow icons and light/dark theme 2017-10-29 14:47:00 +01:00
Gregor Santner
aaa2445bef
Merge extended notifications menu into main menu 2017-10-29 11:07:52 +01:00
Gregor Santner
cb811d8236 Update Gradle to 3.0/4.1 ; SDK 27 2017-10-29 11:01:27 +01:00
Gregor Santner
496faa7945
Release v1.0.7 2017-10-28 09:56:33 +02:00
Gregor Santner
34882ba69f
Remove metadata...again 2017-10-28 09:56:05 +02:00
Gregor Santner
ac8b8469b0
kabyle_init 2017-09-26 18:13:57 +02:00
311 changed files with 14362 additions and 6066 deletions

6
.atomignore Normal file → Executable file
View file

@ -15,3 +15,9 @@ app/build
app/.gitignore
app/pom.xml
app/proguard-rules.pro
.hidden
.travis.yml
circle.yml
CODE_OF_CONDUCT*
gradle.properties
LICENSE*

View file

@ -1,53 +1,24 @@
#### General information
* **App version:**
* **System:**
* **Pod:**
* **Android Device:**
* **Android API Version:**
* **App version:**
* **App source:**
* **Pod version:**
#### Description
#### Log
<!--
I have:
Look for already reported issues before posting!
Also take a look at documentation and wiki, or write in the project chat.
- At least version 0.2.0 installed, see About-> Debug. If it is not visible you have an very old version, and
your issue will be closed.
- searched open and closed issues for duplicates
- read <https://github.com/Diaspora-for-Android/dandelion/blob/master/CONTRIBUTING.md>
- not submitted translations - see [Crowdin](https://crowdin.com/project/diaspora-for-android/invite)
App version: The version of the app installed and the installation source. Example: v0.3.5 F-Droid
Please keep in mind that only the latest downloadable version is supported and that there are no backports to older versions.
System: Information about where the app is running. Give all details you know, but at least the Android OS version.
Example: Android 8.0.1, Nexus 5, LineageOS
Description:
What this is about, what happens and what is expected to happen. What needs to be done for it to happen.
If a crash is happening a log is needed. Screenshots or demonstration videos are always helpful too.
-->
#### Steps to reproduce
1. …
2. …
3. …
#### Expected result
**What is the expected output?**
**What do you see instead?**
Upload screenshots via drag&drop if needed and apply resizing:
`<img width="30%" height="30%" src="https://cloud.githubusercontent.com/assets/67..b55.jpg">`
#### Debug output
Please post the output of adb logcat. The log should begin with the start of dandelion* and include all the steps it takes to reproduce the problem.
IMPORTANT: In-App debug log must be activated and the app restarted first!
````
adb logcat -s com.github.dfa.diaspora_android
````
#### In-App debug log
This is useful for visual bugs without application crashes
````
You can long click on the in-app debug log in order to copy it to the clipboard
````

27
.github/PULL_REQUEST_TEMPLATE vendored Normal file
View file

@ -0,0 +1,27 @@
<!--
Hello, and thanks for contributing!
Please always do auto-reformat on code before creating a PR.
In Android-Studio do a right-click on java->Reformat and check the first two options.
After creating the PR please wait patiently till somebody from the team has time to give a review.
The top-priority requirement for this to get merged is, that building/tests don't fail.
If theres an continious integration system integrated in this project, you should see a colored checkmark in the PR window which tells the status.
## Contributors document
Add yourself! When adding your information to the `CONTRIBUTORS.md` file, please use the following format:
Schema: **[Name](Reference)**<br/>~° Text
Where:
* Name: username, first/lastname
* Reference: E-Mail, Webpage
* Text: Information about / kind of contribution
Example:
* **[Nice Guy](http://niceguy.web)**<br/>~° German localization
-->

View file

@ -0,0 +1,68 @@
##############################################################################################################################
# # Cleanup:
#const sleep = ms => () => new Promise((resolve, reject) => window.setTimeout(resolve, ms));
#Promise.resolve()
#.then(() => { document.getElementsByClassName("details-overlay details-reset position-relative d-inline-block ")[3].children[0].click(); })
#.then(sleep(500))
#.then(() => { document.getElementsByClassName("dropdown-item btn-link menu-item-danger")[0].click(); })
#.then(sleep(1000))
#.then(() => { document.getElementsByClassName("btn btn-block btn-danger")[0].click();});
#
# while [ 1 ] ; do sleep 4; xdotool key Up; sleep 0.1; xdotool key Return; done
##############################################################################################################################
name: "CI"
on: [push, pull_request]
jobs:
build:
if: "!contains(github.event.head_commit.message, 'ci skip') && (!contains(github.event_name, 'pull_request') || (contains(github.event_name, 'pull_request') && github.event.pull_request.head.repo.full_name != github.repository))"
runs-on: ubuntu-latest
steps:
- name: "Checkout: Code"
uses: actions/checkout@v2
- name: "Checkout: Code (PR)"
uses: actions/checkout@v2
if: "contains(github.event_name, 'pull_request')"
with:
ref: ${{github.event.pull_request.head.ref}}
repository: ${{github.event.pull_request.head.repo.full_name}}
- name: "Setup: Java"
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: "Cache: Gradle"
uses: actions/cache@v2
with:
path: |
~/.gradle
.gradle
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('gradle/wrapper/gradle-wrapper.*') }}
- name: "Build: Project with make"
run: make clean all
- name: "Build: List dist files"
if: always()
run: find dist -type f -maxdepth 2
- name: "Artifacts: All"
if: always()
uses: actions/upload-artifact@v2.2.1
with:
name: "all"
path: dist
retention-days: 5
- name: "Artifacts: Android APK"
uses: actions/upload-artifact@v2.2.1
with:
name: "android-apk"
path: |
dist/*.apk

21
.gitignore vendored
View file

@ -1,12 +1,3 @@
##############
### Project ##
app/src/main/res/raw/changelog.*
app/src/main/res/raw/contributors.*
app/src/main/res/raw/license.*
app/src/main/res/raw/readme.*
app/src/main/res/raw/contributors.*
#app/src/main/res/raw/podlist.json
##############
### Common ###
*~*
@ -45,6 +36,7 @@ tmp/
### Gradle ###
.gradle
build/
dist/
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
@ -99,3 +91,14 @@ proguard/
# Android Studio Stuff
.navigation/
gen-external-apklibs
### Project ##
app/src/main/res/raw/changelog.*
app/src/main/res/raw/license.*
app/src/main/res/raw/readme.*
app/src/main/res/raw/contributors.*
app/flavor*
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar

3
.gitmodules vendored
View file

@ -1,3 +0,0 @@
[submodule "metadata"]
path = metadata
url = https://github.com/diaspora-for-android/dandelion-metadata-latest.git

View file

@ -1,38 +0,0 @@
language: android
jdk:
- oraclejdk8
android:
components:
- tools
- tools # TODO https://github.com/travis-ci/travis-ci/issues/6193
- platform-tools
- build-tools-24.0.3
- android-24
- extra-android-m2repository
before_cache:
- rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
cache:
directories:
- $HOME/.gradle/caches/
- $HOME/.gradle/wrapper/
script: "./gradlew $TASK"
env:
- TASK="lintFlavorDefaultDebug"
- TASK="build check --stacktrace"
branches:
except:
- l10n_master
- l10n_master2
- crowdin
notifications:
webhooks:
urls:
- "https://webhooks.gitter.im/e/e462044d3105a7bb4b4f"
- "https://scalar.vector.im/api/neb/services/hooks/dHJhdmlzLWNpLyU0MGdzYW50bmVyJTNBbWF0cml4Lm9yZy8lMjFNUERTYURTaVBMZXdSQXBxa24lM0FtYXRyaXgub3Jn"
on_success: change # options: [always|never|change] default: always
on_failure: always # options: [always|never|change] default: always
on_start: never # options: [always|never|change] default: always
after_success:
- bash <(curl -s https://codecov.io/bash)

View file

@ -1,3 +1,58 @@
### Recent changes
- See [Discussions](https://github.com/gsantner/dandelion/discussions), [Issues](https://github.com/gsantner/dandelion/issues) and [Project page](https://github.com/gsantner/dandelion#readme) to see what is going on.
### v1.4.0
- Add seconds to 'save picture' date format
- Updated translations
- Added german F-Droid description translation
- Update to Android SDK 29
### v1.3.0
- Add option to open youtube links external/in YouTube app (optional)
- Pull to refresh
### v1.2.3
**Improved:**
- More supported languages, more complete translations!
### v1.2.1
**App release: dandelior**
- Added an (rebranded) flavor of dandelion: dandelior
- Only differenties in use are other (black) icon and AMOLED colors by default enabled
- Already available on F-Droid
**New features:**
- All new Aspects and Tags, using a searchable dialog
**Fixed:**
- Sometimes the Stream went white, which is due an still (>3 years) unfixed Android Support library bug. It should not occur very often anymore due less use of fragments.
**Improved:**
- Various small tweaks
- Updated translation files
### v1.1.3
- Improve sharing *a lot*, add support for multiple filetypes
- Support for downloading GIFs ;)
- Rework screenshot saving and sharing; add new share options:
- Merge license and changelog dialog on first start
### v1.1.2
- Fix: loading non-pod links outside customtab/external browser
- Fix: webview-js dialog not dismissing correctly
### v1.1.0
- Added: App shortcuts (Android 7+)
- Updated: podlist
- More supported languages
- File sharing fixes
### v1.0.8
- Modified: Navigation - Merge bottom toolbar into top
- Updated: Build for Android O/27
- Updated: Language change preference
- Added: B/W coloring of toolbar popup
### v1.0.5
- Updated: Language preference

View file

@ -1,7 +1,5 @@
<!--
This file contains references to people who contributed to the app.
If you helped by translating the app, please send a message on Crowdin.
You can also send a mail to [gsantner AT mailbox DOT org](https://gsantner.github.io#contact) to get included.
Schema: **[Name](Reference)**<br/>~° Text
@ -10,11 +8,11 @@ Where:
* Reference: E-Mail, Webpage
* Text: Information about / kind of contribution
## LIST OF CONTRIBUTORS
-->
* **[Gregor Santner](https://gsantner.github.io)**<br/>~° Current developer of dandelion
* **[Gregor Santner](http://github.com/gsantner)**<br/>~° Development of dandelion
* **[Paul Schaub](https://github.com/vanitasvitae)**<br/>~° Development of dandelion
* **[Martín Vukovic](martinvukovic AT protonmail DOT com)**<br/>~° Diaspora Native WebApp
* **[Gaukler Faun](https://github.com/scoute-dich)**<br/>~° Diaspora Native WebApp additions
@ -29,4 +27,6 @@ Where:
* **[Âng Iōngchun](https://pubpod.alqualonde.org/u/iongchun)**<br/>~° Chinese traditional translation
* **[Mikkel Kirkgaard Nielsen](http://www.mikini.dk)**<br/>~° Danish translation
* **[Jean Lucas](jean AT 4ray DOT co)**<br/>~° Spanish translation
* **[asereze](https://github.com/asereze)**<br/>~° Sardinian translation
* **[asereze](https://github.com/asereze)**<br/>~° Sardinian translation
* **[Xosé M. Lamas](http://xmgz.eu)**<br />~° Galician translation
* **[massimiliano](https://framagit.org/massimiliano)**<br />~° Contributor

99
Makefile Normal file
View file

@ -0,0 +1,99 @@
# License of Makefile: Public Domain / CC0
.PHONY: $(shell sed -n -e '/^$$/ { n ; /^[^ .\#][^ ]*:/ { s/:.*$$// ; p ; } ; }' $(MAKEFILE_LIST))
.NOTPARALLEL: clean
.DEFAULT_GOAL := all
env-%:
@: $(if ${${*}},,$(error Environment variable $* not set))
####################################################################################
DIST_DIR = dist
MOVE = mv
all: $(DIST_DIR) spellcheck lint deptree test build aapt_dump_badging
####################################################################################
$(DIST_DIR):
mkdir -p ${DIST_DIR}
ANDROID_BUILD_TOOLS := $(shell test -n "$ANDROID_SDK_ROOT" && find "${ANDROID_SDK_ROOT}/build-tools" -iname "aapt" | sort -r | head -n1 | xargs dirname)
TOOL_SPELLCHECKING_ISPELL := $(shell command -v ispell 2> /dev/null)
FLAVOR := $(or ${FLAVOR},${FLAVOR},Atest)
.NOTPARALLEL: gradle gradle-analyze-log
gradle: env-ANDROID_SDK_ROOT
mkdir -p $(DIST_DIR)/log/
chmod +x gradlew
./gradlew --no-daemon --parallel --stacktrace $A 2>&1 | tee "$(DIST_DIR)/log/gradle.log"
@echo "-----------------------------------------------------------------------------------"
gradle-analyze-log:
mv "$(DIST_DIR)/log/gradle.log" "$(DIST_DIR)/log/gradle$A.log"
cat "$(DIST_DIR)/log/gradle$A.log" | grep "BUILD " | tail -n1 | grep -q "BUILD SUCCESSFUL in"
adb: env-ANDROID_SDK_ROOT
"${ANDROID_SDK_ROOT}/platform-tools/adb" $A 2>&1 | tee "$(DIST_DIR)/log/adb-$L.log"
aapt: env-ANDROID_SDK_ROOT
"${ANDROID_BUILD_TOOLS}/aapt" $A 2>&1 | grep -v 'application-label-' | tee "$(DIST_DIR)/log/aapt$L.log"
build:
rm -f $(DIST_DIR)/*.apk
$(MAKE) A="clean assembleFlavor$(FLAVOR) -x lint" gradle
find app -type f -newermt '-300 seconds' -iname '*.apk' -not -iname '*unsigned.apk' | xargs cp -R -t $(DIST_DIR)/
$(MAKE) A="-build" gradle-analyze-log
lint:
rm -Rf $(DIST_DIR)/lint
mkdir -p $(DIST_DIR)/lint/
$(MAKE) A="lintFlavorDefaultDebug" gradle
find app -type f -iname 'lint-results-*' | grep -v 'intermediates' | xargs cp -R -t $(DIST_DIR)/lint
$(MAKE) A="-lint" gradle-analyze-log
test:
rm -Rf $(DIST_DIR)/tests
$(MAKE) A="testFlavorDefaultDebugUnitTest -x lint" gradle
mkdir -p app/build/test-results/testFlavorDefaultDebugUnitTest && echo 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHRlc3RzdWl0ZSBuYW1lPSJkdW1teSIgdGVzdHM9IjEiIHNraXBwZWQ9IjAiIGZhaWx1cmVzPSIwIiBlcnJvcnM9IjAiIHRpbWVzdGFtcD0iMjAyMC0xMi0wOFQwMDowMDowMCIgaG9zdG5hbWU9ImxvY2FsaG9zdCIgdGltZT0iMC4wMSI+CiAgPHByb3BlcnRpZXMvPgogIDx0ZXN0Y2FzZSBuYW1lPSJkdW1teSIgY2xhc3NuYW1lPSJkdW1teSIgdGltZT0iMC4wMSIvPgogIDxzeXN0ZW0tb3V0PjwhW0NEQVRBW11dPjwvc3lzdGVtLW91dD4KICA8c3lzdGVtLWVycj48IVtDREFUQVtdXT48L3N5c3RlbS1lcnI+CjwvdGVzdHN1aXRlPgo=' | base64 -d > 'app/build/test-results/testFlavorDefaultDebugUnitTest/TEST-dummy.xml'
find app -type d -iname 'testFlavorDefaultDebugUnitTest' | xargs cp -R -t $(DIST_DIR)/
mv ${DIST_DIR}/testFlavorDefaultDebugUnitTest $(DIST_DIR)/tests
$(MAKE) A="-test" gradle-analyze-log
deptree:
$(MAKE) A="app:dependencies --configuration flavor$(FLAVOR)DebugRuntimeClasspath" gradle
$(MAKE) A="-dependency-tree" gradle-analyze-log
clean:
$(MAKE) A="clean" gradle
rm -Rf $(DIST_DIR) app/build app/flavor* .idea dist
find . -type f -iname "*.iml" -delete
$(MAKE) $(DIST_DIR)
@echo "-----------------------------------------------------------------------------------"
install:
$(MAKE) A="install -r $(DIST_DIR)/*.apk" L="install" adb
run:
$(MAKE) A="shell monkey -p $$(aapt dump badging $(DIST_DIR)/*.apk | grep package: | sed 's@.* name=@@' | sed 's@ .*@@' | xargs | head -n1) -c android.intent.category.LAUNCHER 1" L="run" adb
aapt_dump_badging:
$(MAKE) A="dump badging $(DIST_DIR)/*.apk" aapt
@echo "-----------------------------------------------------------------------------------"
spellcheck:
mkdir -p "$(DIST_DIR)/lint/"
ifndef TOOL_SPELLCHECKING_ISPELL
@echo "Tool ispell (spellcheck) not found in PATH. Spellcheck skipped." > "$(DIST_DIR)/lint/stringsxml-spellcheck.txt"
else
@echo "Use ispell for spellchecking the original values/strings.xml"
find . -iname "strings.xml" -path "*/main*/values/*" | head -n1 | xargs cat \
| grep "<string name=" | sed 's@.*">@@' | sed 's@</string>@@' | sed 's@\\n@ @g' | sed 's@\\@@g' \
| ispell -W3 -a | grep ^\& | sed 's@[0-9]@@g' | sort | uniq | cut -d, -f1-4 \
| sed 's@^..@- @' | column -t -s: \
> "$(DIST_DIR)/lint/stringsxml-spellcheck.txt"
@echo "\nPotential words with bad spelling:"
endif
@cat "$(DIST_DIR)/lint/stringsxml-spellcheck.txt"
@echo "-----------------------------------------------------------------------------------"

96
NEWS.md Normal file
View file

@ -0,0 +1,96 @@
# dandelion - News
## General
### Installation
You can install and update from [F-Droid](https://f-droid.org/repository/browse/?fdid=com.github.dfa.diaspora_android) or [GitHub](https://github.com/gsantner/dandelion/releases/latest).
F-Droid is a store for free & open source apps.
The *.apk's available for download are signed by the F-Droid team and guaranteed to correspond to the (open source) source code of dandelion.
Generally this is the recommended way to install dandelion & keep it updated.
### Get informed
* Check the [project readme](https://github.com/gsantner/dandelion/tree/news#readme) for general project information.
* Check the [project news](https://github.com/gsantner/dandelion/blob/master/NEWS.md#readme) for more details on what is going on.
* Check the [project git history](https://github.com/gsantner/dandelion/commits/master) for most recent code changes.
### The right place to ask
If you have questions or found an issue please head to the [dandelion project](https://github.com/gsantner/dandelion/issues/new/choose) and ask there.
[Search](https://github.com/gsantner/dandelion/issues?q=#js-issues-search) for same/similar and related issues/questions before, it might be already answered or resolved.
### Navigation
* [dandelion v1.2 - Add dandelior - Searchable Tags and Aspects](#dandelion-v12---add-dandelior---searchable-tags-and-aspects)
* [dandelion v0.1.2 - Aspekte, Pod wechseln](#dandelion-v012---aspekte-pod-wechseln)
------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------
# dandelion\* v1.2 - Add dandelior\* - Searchable Tags and Aspects
_12. August 2018_
## dandelior\* is a rebranded version of dandelion\*
dandelior\* is based 100% on the same code and resources as dandelion\*. Its from the same code repository, just a different build flavor.
The main purpose of dandelior\* is the most requested feature till date - to support multiple accounts / another account at dandelion\*.
- Added an (rebranded) flavor of dandelion: dandelior
- Only differenties in use are other (black) icon and AMOLED colors by default enabled
- Already available on F-Droid
**New features:**
- All new Aspects and Tags, using a searchable dialog
**Fixed:**
- Sometimes the Stream went white, which is due an still (3+ years) unfixed Android Support library bug. It should not occur very often anymore due less use of fragments.
**Improved:**
- Various small tweaks
- Updated translation files
------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------
# dandelion v0.1.2 - Aspekte, Pod wechseln
_05. Juni 2016_
In den letzten Tagen hat @gsantner viel Zeit in die inoffizielle diaspora\* Android App ([dandelion\*](https://github.com/gsantner/dandelion)) investiert.
Dabei wurden unter anderem folgende Änderungen beigesteuert:
- Allgemeines zur Usability
- Animationen für den Activity-Wechsel und Startup, WebView-Scroll-Top
- Podliste caching
- Aspekt-Liste und Aspekte hinzugefügt
- Verbessertes Sharing aus der App
- Material Progressbar
- Suche verbessert
- Collapsing top menu
- toolbar/actions/menu geändert, fab entfernt
- Refactoring layout & menu files, dialogs
- Überarbeitete Main,Splash,PodSelectionActivity
- Pod wechseln

View file

@ -1,10 +1,9 @@
[![GitHub release](https://img.shields.io/github/tag/diaspora-for-android/dandelion.svg)](https://github.com/diaspora-for-android/dandelion/releases)
[![CircleCI](https://circleci.com/gh/Diaspora-for-Android/dandelion.svg?style=shield)](https://circleci.com/gh/Diaspora-for-Android/dandelion)
[![Crowdin](https://d322cqt584bo4o.cloudfront.net/diaspora-for-android/localized.svg)](https://crowdin.com/project/diaspora-for-android)
[![Chat - Matrix](https://img.shields.io/badge/chat-on%20matrix-blue.svg)](https://matrix.to/#/#dandelion:matrix.org) [![Chat - FreeNode IRC](https://img.shields.io/badge/chat-on%20irc-blue.svg)](https://kiwiirc.com/client/irc.freenode.net/?nick=dandelion-anon|?##dandelion)
[![Donate Bitcoin](https://img.shields.io/badge/donate-bitcoin-orange.svg)](https://gsantner.github.io/#donate)
[![Donate LiberaPay](https://img.shields.io/badge/donate-liberapay-orange.svg)](https://liberapay.com/gsantner/donate)
[![Donate GratiPay](https://img.shields.io/gratipay/team/dandelion.svg)](https://gratipay.com/dandelion/)
[![GitHub releases](https://img.shields.io/github/tag/gsantner/dandelion.svg)](https://github.com/gsantner/dandelion/releases)
[![GitHub downloads](https://img.shields.io/github/downloads/gsantner/dandelion/total.svg?logo=github&logoColor=lime)](https://github.com/gsantner/dandelion/releases)
[![Translate on Crowdin](https://img.shields.io/badge/translate-crowdin-green.svg)](https://crowdin.com/project/diaspora-for-android/invite)
[![Chat on Matrix](https://img.shields.io/badge/chat-matrix-blue.svg)](https://matrix.to/#/#dandelion:matrix.org)
[![GitHub CI](https://github.com/gsantner/dandelion/workflows/CI/badge.svg)](https://github.com/gsantner/dandelion/actions)
[![Codacy code quality](https://img.shields.io/codacy/grade/aff869c440bc48b7bd64680e97cbc453)](https://www.codacy.com/app/gsantner/dandelion)
# dandelion\*
<img src="/app/src/main/ic_launcher-web.png" align="left" width="100" hspace="10" vspace="10">
@ -42,44 +41,41 @@ dandelion\* requires access to the Internet and to external storage to be able t
The project is always open for contributions and accepts pull requests.
The project uses [AOSP Java Code Style](https://source.android.com/source/code-style#follow-field-naming-conventions), with one exception: private members are `_camelCase` instead of `mBigCamel`. You may use Android Studios _auto reformat feature_ before sending a PR.
We use Crowdin to translate dandelion\*. Join our project here: <https://crowdin.com/project/diaspora-for-android/invite>. If your desired language is not listed please contact the maintainers/owner.
Join our IRC or Matrix channel (bridged) and say hello! Don't be afraid to start talking. [![Chat - Matrix](https://img.shields.io/badge/chat-on%20matrix-blue.svg)](https://matrix.to/#/#dandelion:matrix.org) [![Chat - FreeNode IRC](https://img.shields.io/badge/chat-on%20irc-blue.svg)](https://kiwiirc.com/client/irc.freenode.net/?nick=dandelion-anon|?##dandelion)
Translations can be contributed on GitHub. You can use Stringlate ([![Translate - with Stringlate](https://img.shields.io/badge/stringlate-translate-green.svg)](https://lonamiwebs.github.io/stringlate/translate?git=https%3A%2F%2Fgithub.com%2Fgsantner%2Fdandelion.git)) to translate the project directly on your Android phone. It allows you to export as E-Mail attachement and to post on GitHub.
Join our Matrix channel and say hello! Don't be afraid to start talking. [![Chat - Matrix](https://img.shields.io/badge/chat-on%20matrix-blue.svg)](https://matrix.to/#/#dandelion:matrix.org)
Note that the main project members are working on this project for free during leisure time, are mostly busy with their job/university/school, and may not react or start coding immediately.
#### Resources
* Project: [Changelog](/CHANGELOG.md) | [Issues level/beginner](https://github.com/diaspora-for-android/dandelion/issues?q=is%3Aissue+is%3Aopen+label%3Alevel%2Fbeginner) | [License](/LICENSE.txt) | [CoC](/CODE_OF_CONDUCT.md)
* Project: [Changelog](/CHANGELOG.md) | [Issues level/beginner](https://github.com/gsantner/dandelion/issues?q=is%3Aissue+is%3Aopen+label%3Alevel%2Fbeginner) | [License](/LICENSE.txt) | [CoC](/CODE_OF_CONDUCT.md)
* Project diaspora\* account: [dandelion00@diasp.org](https://diasp.org/people/48b78420923501341ef3782bcb452bd5)
* diaspora\*: [GitHub](https://github.com/diaspora/diaspora) | [Web](https://diasporafoundation.org) | [d\* HQ account](https://pod.diaspora.software/people/7bca7c80311b01332d046c626dd55703)
* App on F-Droid: [Metadata](https://gitlab.com/fdroid/fdroiddata/blob/master/metadata/com.github.dfa.diaspora_android.txt) | [Page](https://f-droid.org/packages/com.github.dfa.diaspora_android/) | [Wiki](https://f-droid.org/wiki/page/com.github.dfa.diaspora_android) | [Build log](https://f-droid.org/wiki/page/com.github.dfa.diaspora_android/lastbuild)
## Licensing
dandelion\* is released under GNU GENERAL PUBLIC LICENSE (see [LICENCE](https://github.com/Diaspora-for-Android/dandelion/blob/master/LICENSE.md)).
dandelion\* is released under GNU GENERAL PUBLIC LICENSE (see [LICENCE](https://github.com/gsantner/dandelion/blob/master/LICENSE.md)).
The app is licensed GPL v3. Localization files and resources (strings\*.xml) are licensed CC0 1.0.
For more licensing informations, see [`3rd party licenses`](/app/src/main/res/raw/licenses_3rd_party.md).
## Screenshots
<div style="display:flex;" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/01.png" width="19%" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/02.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/03.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/04.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/05.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/gsantner/dandelion/master/metadata/en-US/phoneScreenshots/01.png" width="19%" >
<img src="https://raw.githubusercontent.com/gsantner/dandelion/master/metadata/en-US/phoneScreenshots/02.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/gsantner/dandelion/master/metadata/en-US/phoneScreenshots/03.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/gsantner/dandelion/master/metadata/en-US/phoneScreenshots/04.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/gsantner/dandelion/master/metadata/en-US/phoneScreenshots/05.png" width="19%" style="margin-left:10px;" >
</div>
<div style="display:flex;" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/06.png" width="19%" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/07.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/08.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/09.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/gsantner/dandelion/master/metadata/en-US/phoneScreenshots/06.png" width="19%" >
<img src="https://raw.githubusercontent.com/gsantner/dandelion/master/metadata/en-US/phoneScreenshots/07.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/gsantner/dandelion/master/metadata/en-US/phoneScreenshots/08.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/gsantner/dandelion/master/metadata/en-US/phoneScreenshots/09.png" width="19%" style="margin-left:10px;" >
</div>
### Notice
#### Maintainers
- gsantner ([GitHub](https://github.com/gsantner), [Web](https://gsantner.github.io), [diaspora*](https://pod.geraspora.de/people/d1cbdd70095301341e834860008dbc6c))
- Bitcoin: [1B9ZyYdQoY9BxMe9dRUEKaZbJWsbQqfXU5](https://gsantner.github.io/donate/#donate)
- gsantner ([GitHub](https://github.com/gsantner), [diaspora*](https://pod.geraspora.de/people/d1cbdd70095301341e834860008dbc6c))
- vanitasvitae ([GitHub](https://github.com/vanitasvitae), [diaspora*](https://pod.geraspora.de/people/bbd7af90fbec013213e34860008dbc6c))
- Bitcoin: 1Ao3W6NaQv3xKppviB7RSFKjHo6PGd8RTy

View file

@ -1,16 +0,0 @@
## Screenshots
<div style="display:flex;" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/01.png" width="19%" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/02.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/03.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/04.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/05.png" width="19%" style="margin-left:10px;" >
</div>
<div style="display:flex;" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/06.png" width="19%" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/07.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/08.png" width="19%" style="margin-left:10px;" >
<img src="https://raw.githubusercontent.com/diaspora-for-android/dandelion-metadata-latest/master/en-US/phoneScreenshots/09.png" width="19%" style="margin-left:10px;" >
</div>

View file

@ -1,48 +1,32 @@
apply plugin: 'com.android.application'
ext {
version_sdk = [
compileSdk : 24,
buildTools : "26.0.1",
minSdk : 17,
//targetSdk: compileSdk,
]
version_sdk.targetSdk = version_sdk.compileSdk
version_lib = [
appcompat : "24.1.0", // Broken after 24.1.0, Fix announced at 26.0.0, but still not fixed... See https://issuetracker.google.com/issues/37118105
butterknife : "8.4.0",
netcipher : "2.0.0-alpha1",
]
if (enable_plugin_kotlin) {
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
}
android {
compileSdkVersion version_sdk.compileSdk
buildToolsVersion version_sdk.buildTools
buildToolsVersion rootProject.ext.version_buildTools
compileSdkVersion rootProject.ext.version_compileSdk
defaultConfig {
minSdkVersion version_sdk.minSdk
targetSdkVersion version_sdk.targetSdk
versionCode 26
versionName "1.0.6"
resValue "string", "manifest_package_id", "com.github.dfa.diaspora_android"
applicationId "com.github.dfa.diaspora_android"
resValue 'string', 'app_name', "dandelion*"
manifestPlaceholders = [appIcon: "@drawable/ic_launcher"]
versionName "1.3.5"
versionCode 46
vectorDrawables.useSupportLibrary = true
minSdkVersion rootProject.ext.version_minSdk
targetSdkVersion rootProject.ext.version_compileSdk
buildConfigField "boolean", "IS_TEST_BUILD", "false"
buildConfigField "boolean", "IS_GPLAY_BUILD", "false"
buildConfigField("String[]", "APPLICATION_LANGUAGES", '{' + getUsedAndroidLanguages().collect {"\"${it}\""}.join(",") + '}')
vectorDrawables.useSupportLibrary = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
buildConfigField "String[]", "DETECTED_ANDROID_LOCALES", "${findUsedAndroidLocales()}"
buildConfigField "String", "BUILD_DATE", "\"${getBuildDate()}\""
buildConfigField "String", "GITHASH", "\"${getGitHash()}\""
setProperty("archivesBaseName", applicationId + "-v" + versionCode + "-" + versionName)
}
flavorDimensions "default"
productFlavors {
flavorDefault {
}
@ -50,80 +34,103 @@ android {
/*
flavorGplay {
buildConfigField "boolean", "IS_GPLAY_BUILD", "true"
}
*/
}*/
flavorTest {
applicationId "com.github.dfa.secondlion"
resValue 'string', 'app_name', "secondlion*"
manifestPlaceholders = [appIcon: "@drawable/ic_launcher_test"]
flavorDandelior {
applicationId "net.gsantner.dandelior"
}
flavorAtest {
applicationId "net.gsantner.secondlion"
versionCode = Integer.parseInt(new Date().format('yyMMdd'))
versionName = new Date().format('yyMMdd')
buildConfigField "boolean", "IS_TEST_BUILD", "true"
}
}
sourceSets {
main { assets.srcDirs = ['src/main/assets'] }
if (enable_plugin_kotlin) {
main.java.srcDirs += 'src/main/kotlin'
}
main.java.srcDirs += 'thirdparty/java'
main.res.srcDirs += 'thirdparty/res'
main.assets.srcDirs += 'thirdparty/assets'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
configurations.all {
resolutionStrategy {
eachDependency { details ->
if (details.requested.group == 'com.android.support') {
if (details.requested.name != 'multidex' && details.requested.name != 'multidex-instrumentation') {
details.useVersion "${rootProject.ext.version_library_appcompat}"
}
}
}
}
}
packagingOptions {
exclude 'META-INF/LICENSE-LGPL-2.1.txt'
exclude 'META-INF/LICENSE-LGPL-3.txt'
exclude 'META-INF/LICENSE-W3C-TEST'
}
compileOptions {
encoding = 'UTF-8'
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
lintOptions {
disable 'MissingTranslation'
disable 'MissingTranslation', 'InvalidPackage', 'ObsoleteLintCustomCheck', 'DefaultLocale', 'UnusedAttribute', 'VectorRaster', 'InflateParams', 'IconLocation', 'UnusedResources', 'TypographyEllipsis'
abortOnError false
}
}
dependencies {
// Sub-Projects
//compile project(':subprojectFromRoot')
//implementation project(':subprojectFromRoot')
// Jars
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
implementation fileTree(dir: 'libs', include: ['*.jar'])
testImplementation 'junit:junit:4.13'
// Android standard libs
compile "com.android.support:appcompat-v7:${version_lib.appcompat}"
compile "com.android.support:design:${version_lib.appcompat}"
compile "com.android.support:support-v4:${version_lib.appcompat}"
compile "com.android.support:customtabs:${version_lib.appcompat}"
compile "com.android.support:cardview-v7:${version_lib.appcompat}"
implementation "com.android.support:appcompat-v7:${version_library_appcompat}"
implementation "com.android.support:design:${version_library_appcompat}"
implementation "com.android.support:support-v4:${version_library_appcompat}"
implementation "com.android.support:customtabs:${version_library_appcompat}"
implementation "com.android.support:cardview-v7:${version_library_appcompat}"
implementation "com.android.support:preference-v7:${version_library_appcompat}"
// UI libraries
compile "com.github.DASAR:ShiftColorPicker:v0.5"
implementation "com.github.DASAR:ShiftColorPicker:v0.5"
// Tool libraries
compile "com.jakewharton:butterknife:${version_lib.butterknife}"
compile "info.guardianproject.netcipher:netcipher:${version_lib.netcipher}"
compile "info.guardianproject.netcipher:netcipher-webkit:${version_lib.netcipher}"
implementation 'commons-io:commons-io:2.6'
implementation "info.guardianproject.netcipher:netcipher:${version_library_netcipher}"
implementation "info.guardianproject.netcipher:netcipher-webkit:${version_library_netcipher}"
//noinspection AnnotationProcessorOnCompilePath
implementation "com.jakewharton:butterknife:${version_library_butterknife}"
if (enable_plugin_kotlin) {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${version_plugin_kotlin}"
}
annotationProcessor "com.jakewharton:butterknife-compiler:${version_lib.butterknife}"
}
@SuppressWarnings(["UnnecessaryQualifiedReference", "SpellCheckingInspection"])
static String[] getUsedAndroidLanguages() {
Set<String> langs = new HashSet<>()
new File('.').eachFileRecurse(groovy.io.FileType.DIRECTORIES) {
final foldername = it.name
if (foldername.startsWith('values-') && !it.canonicalPath.contains("build" + File.separator + "intermediates")) {
new File(it.toString()).eachFileRecurse(groovy.io.FileType.FILES) {
if (it.name.toLowerCase().endsWith(".xml") && it.getCanonicalFile().getText('UTF-8').contains("<string")) {
langs.add(foldername.replace("values-", ""))
}
}
// Processors
def anpros = ["com.jakewharton:butterknife-compiler:${version_library_butterknife}"]
for (anpro in anpros) {
if (enable_plugin_kotlin) {
kapt anpro
} else {
annotationProcessor anpro
}
}
return langs.toArray(new String[langs.size()])
}
// #####################
// Groovy Coding Area
// #####################
final String RAW_DIR = "app/src/main/res/raw"
final String[] ROOT_TO_RAW_COPYFILES = ["README.md", "LICENSE.md", "CHANGELOG.md", "CONTRIBUTORS.md"]
// Called before building
task copyRepoFiles(type: Copy) {
// Copy files over to raw dir
from rootProject.files(ROOT_TO_RAW_COPYFILES)
into RAW_DIR.replaceFirst("app/", "")
rename { String fileName ->
fileName.replace(fileName, fileName.toLowerCase())
}
}
tasks.copyRepoFiles.execute()

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="20"
android:viewportHeight="20">
<path
android:pathData="M0.025,-0.07h19.95v20.14H0.025z"
android:fillColor="#492600"/>
</vector>

View file

@ -0,0 +1,12 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="36.363636"
android:viewportHeight="36.363636">
<group android:translateX="8.181818"
android:translateY="8.181818">
<path
android:pathData="M11.337,14.123l-0.963,-1.345c-0.257,-0.36 -0.466,-0.64 -0.477,-0.64 -0.012,0 -0.416,0.544 -0.958,1.287a83.9,83.9 0,0 1,-0.947 1.287c-0.015,0 -1.86,-1.3 -1.865,-1.313 -0.002,-0.007 0.415,-0.62 0.927,-1.361 0.512,-0.742 0.931,-1.36 0.931,-1.375 0,-0.023 -0.166,-0.081 -1.468,-0.515l-1.485,-0.496c-0.013,-0.005 0.063,-0.263 0.327,-1.094 0.19,-0.599 0.349,-1.093 0.354,-1.099 0.005,-0.006 0.707,0.219 1.56,0.5 0.852,0.28 1.556,0.509 1.565,0.509 0.008,0 0.018,-0.013 0.022,-0.03 0.003,-0.015 0.01,-0.74 0.016,-1.612 0.006,-0.87 0.015,-1.59 0.02,-1.6 0.009,-0.012 0.248,-0.015 1.127,-0.015 0.614,0 1.123,0.004 1.13,0.01 0.01,0.006 0.027,0.485 0.056,1.56 0.046,1.766 0.047,1.79 0.075,1.79 0.01,0 0.686,-0.226 1.501,-0.503a50.795,50.795 0,0 1,1.49 -0.492c0.016,0.019 0.685,2.194 0.676,2.202 -0.004,0.005 -0.684,0.237 -1.51,0.517 -1.137,0.386 -1.504,0.515 -1.507,0.531 -0.003,0.012 0.388,0.597 0.886,1.324 0.49,0.716 0.888,1.308 0.886,1.314a96.945,96.945 0,0 1,-1.852 1.364c-0.006,0 -0.239,-0.317 -0.517,-0.705z"
android:fillColor="#fafafa"/>
</group>
</vector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name" translatable="false">secondlion*</string>
</resources>

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="20"
android:viewportHeight="20">
<path
android:pathData="M0.025,-0.07h19.95v20.14H0.025z"
android:fillColor="#000000"/>
</vector>

View file

@ -0,0 +1,12 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="36.363636"
android:viewportHeight="36.363636">
<group android:translateX="8.181818"
android:translateY="8.181818">
<path
android:pathData="M11.337,14.123l-0.963,-1.345c-0.257,-0.36 -0.466,-0.64 -0.477,-0.64 -0.012,0 -0.416,0.544 -0.958,1.287a83.9,83.9 0,0 1,-0.947 1.287c-0.015,0 -1.86,-1.3 -1.865,-1.313 -0.002,-0.007 0.415,-0.62 0.927,-1.361 0.512,-0.742 0.931,-1.36 0.931,-1.375 0,-0.023 -0.166,-0.081 -1.468,-0.515l-1.485,-0.496c-0.013,-0.005 0.063,-0.263 0.327,-1.094 0.19,-0.599 0.349,-1.093 0.354,-1.099 0.005,-0.006 0.707,0.219 1.56,0.5 0.852,0.28 1.556,0.509 1.565,0.509 0.008,0 0.018,-0.013 0.022,-0.03 0.003,-0.015 0.01,-0.74 0.016,-1.612 0.006,-0.87 0.015,-1.59 0.02,-1.6 0.009,-0.012 0.248,-0.015 1.127,-0.015 0.614,0 1.123,0.004 1.13,0.01 0.01,0.006 0.027,0.485 0.056,1.56 0.046,1.766 0.047,1.79 0.075,1.79 0.01,0 0.686,-0.226 1.501,-0.503a50.795,50.795 0,0 1,1.49 -0.492c0.016,0.019 0.685,2.194 0.676,2.202 -0.004,0.005 -0.684,0.237 -1.51,0.517 -1.137,0.386 -1.504,0.515 -1.507,0.531 -0.003,0.012 0.388,0.597 0.886,1.324 0.49,0.716 0.888,1.308 0.886,1.314a96.945,96.945 0,0 1,-1.852 1.364c-0.006,0 -0.239,-0.317 -0.517,-0.705z"
android:fillColor="#fafafa"/>
</group>
</vector>

View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name" translatable="false">dandelior*</string>
</resources>

File diff suppressed because it is too large Load diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 29 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

View file

@ -35,6 +35,8 @@ import com.github.dfa.diaspora_android.util.AppSettings;
import com.github.dfa.diaspora_android.util.DiasporaUrlHelper;
import net.gsantner.opoc.util.AdBlock;
import net.gsantner.opoc.util.ContextUtils;
import net.gsantner.opoc.util.ShareUtil;
public class App extends Application {
private volatile static App app;
@ -50,10 +52,18 @@ public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
ShareUtil.setFileProviderAuthority(BuildConfig.APPLICATION_ID);
app = this;
final Context c = getApplicationContext();
appSettings = AppSettings.get();
String a = new ContextUtils(this).bcstr("FLAVOR", "");
a += "__";
if (appSettings.isAppFirstStart() && "flavorDandelior".equals(new ContextUtils(this).bcstr("FLAVOR", ""))) {
appSettings.setAmoledColorMode(true);
}
// Init app log
AppLog.setLoggingEnabled(appSettings.isLoggingEnabled());
AppLog.setLoggingSpamEnabled(appSettings.isLoggingSpamEnabled());

View file

@ -20,12 +20,13 @@ package com.github.dfa.diaspora_android.activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
@ -34,8 +35,6 @@ import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
@ -107,11 +106,7 @@ public class AboutActivity extends ThemedActivity
@Override
public void onResume() {
super.onResume();
if (getAppSettings().isIntellihideToolbars()) {
this.enableToolbarHiding();
} else {
this.disableToolbarHiding();
}
setToolbarIntellihide(getAppSettings().isIntellihideToolbars());
}
@Override
@ -121,20 +116,16 @@ public class AboutActivity extends ThemedActivity
ThemeHelper.setPrimaryColorAsBackground(_linearLayout);
}
@Override
public void enableToolbarHiding() {
AppLog.d(this, "Enable Intellihide");
public void setToolbarIntellihide(boolean enable) {
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) _linearLayout.getLayoutParams();
//scroll|enterAlways|snap
params.setScrollFlags(toolbarDefaultScrollFlags);
_appBarLayout.setExpanded(true, true);
}
if (enable) {
AppLog.d(this, "Enable Intellihide");
params.setScrollFlags(toolbarDefaultScrollFlags);
@Override
public void disableToolbarHiding() {
AppLog.d(this, "Disable Intellihide");
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) _linearLayout.getLayoutParams();
params.setScrollFlags(0); // clear all scroll flags
} else {
AppLog.d(this, "Disable Intellihide");
params.setScrollFlags(0); // clear all scroll flags
}
_appBarLayout.setExpanded(true, true);
}
@ -167,20 +158,23 @@ public class AboutActivity extends ThemedActivity
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.about__fragment_about, container, false);
ButterKnife.bind(this, rootView);
protected int getLayoutResId() {
return R.layout.about__fragment_about;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
if (isAdded()) {
try {
PackageInfo pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
appVersion.setText(getString(R.string.fragment_debug__app_version, pInfo.versionName + " (" + pInfo.versionCode + ")"));
appVersion.setText(getString(R.string.app_version_with_arg, pInfo.versionName + " (" + pInfo.versionCode + ")"));
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
return rootView;
}
@Override
@ -198,11 +192,6 @@ public class AboutActivity extends ThemedActivity
return TAG;
}
@Override
public void onCreateBottomOptionsMenu(Menu menu, MenuInflater inflater) {
/* Nothing to do */
}
@Override
public boolean onBackPressed() {
return false;
@ -224,8 +213,8 @@ public class AboutActivity extends ThemedActivity
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.app_name));
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, getString(R.string.fragment_about__spread_the_word_share_text, getString(R.string.fragment_about__fdroid_link)));
startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.action_share_dotdotdot)));
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, getString(R.string.hey_checkout_dandelion_tag__appspecific, getString(R.string.fragment_about__fdroid_link)));
startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.share_dotdotdot)));
break;
}
}
@ -259,19 +248,22 @@ public class AboutActivity extends ThemedActivity
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.about__fragment_license, container, false);
ButterKnife.bind(this, rootView);
final Context context = rootView.getContext();
protected int getLayoutResId() {
return R.layout.about__fragment_license;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
accentColor = ContextUtils.get().colorToHexString(ThemeHelper.getAccentColor());
maintainers.setTextFormatted(getString(R.string.fragment_license__maintainers_text,
maintainers.setTextFormatted(getString(R.string.this_app_is_currently_developed_and_maintained_by_witharg,
ContextUtils.get().loadMarkdownForTextViewFromRaw(R.raw.maintainers, "")));
contributors.setTextFormatted(getString(R.string.fragment_license__contributors_thank_you,
contributors.setTextFormatted(getString(R.string.thank_you_witharg,
ContextUtils.get().loadMarkdownForTextViewFromRaw(R.raw.contributors, "")));
thirdPartyLibs.setTextFormatted(
ContextUtils.get().loadMarkdownForTextViewFromRaw(R.raw.license_third_party, ""));
return rootView;
ContextUtils.get().loadMarkdownForTextViewFromRaw(R.raw.licenses_3rd_party, ""));
}
@OnClick({R.id.fragment_license__leafpic_button, R.id.fragment_license__license_button})
@ -300,11 +292,6 @@ public class AboutActivity extends ThemedActivity
return TAG;
}
@Override
public void onCreateBottomOptionsMenu(Menu menu, MenuInflater inflater) {
/* Nothing to do */
}
@Override
public boolean onBackPressed() {
return false;
@ -354,7 +341,7 @@ public class AboutActivity extends ThemedActivity
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("DEBUG_LOG", AppLog.Log.getLogBuffer());
clipboard.setPrimaryClip(clip);
Toast.makeText(DebugFragment.this.getActivity(), R.string.fragment_debug__toast_log_copied, Toast.LENGTH_SHORT).show();
Toast.makeText(DebugFragment.this.getActivity(), R.string.debug_log_copied_to_clipboard, Toast.LENGTH_SHORT).show();
} else {
AppLog.d(this, "Not Added!");
}
@ -369,13 +356,13 @@ public class AboutActivity extends ThemedActivity
PackageInfo pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
AppSettings appSettings = ((App) getActivity().getApplication()).getSettings();
packageName.setText(pInfo.packageName);
appVersion.setText(getString(R.string.fragment_debug__app_version, pInfo.versionName + " (" + pInfo.versionCode + ")"));
appVersion.setText(getString(R.string.app_version_with_arg, pInfo.versionName + " (" + pInfo.versionCode + ")"));
osVersion.setText(getString(R.string.fragment_debug__android_version, Build.VERSION.RELEASE));
deviceName.setText(getString(R.string.fragment_debug__device_name, Build.MANUFACTURER + " " + Build.MODEL));
osVersion.setText(getString(R.string.android_version_witharg, Build.VERSION.RELEASE));
deviceName.setText(getString(R.string.device_name_witharg, Build.MANUFACTURER + " " + Build.MODEL));
if (app.getSettings().getPod() != null) {
podDomain.setText(getString(R.string.fragment_debug__pod_profile_url, app.getSettings().getPod().getPodUrl()));
podName.setText(getString(R.string.fragment_debug__pod_profile_name, app.getSettings().getPod().getName()));
podDomain.setText(getString(R.string.pod_domain_witharg__appspecific, app.getSettings().getPod().getPodUrl()));
podName.setText(getString(R.string.pod_profile_name_witharg__appspecific, app.getSettings().getPod().getName()));
}
} catch (PackageManager.NameNotFoundException e) {
@ -433,11 +420,11 @@ public class AboutActivity extends ThemedActivity
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.about_activity__title_about_app);
return getString(R.string.about);
case 1:
return getString(R.string.about_activity__title_about_license);
return getString(R.string.license);
case 2:
return getString(R.string.about_activity__title_debug_info);
return getString(R.string.debugging);
}
return null;
}

View file

@ -1,216 +0,0 @@
/*
This file is part of the dandelion*.
dandelion* is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
dandelion* is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the dandelion*.
If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.dfa.diaspora_android.activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.R;
import com.github.dfa.diaspora_android.data.DiasporaAspect;
import com.github.dfa.diaspora_android.listener.OnSomethingClickListener;
import com.github.dfa.diaspora_android.ui.theme.ThemedFragment;
import com.github.dfa.diaspora_android.util.AppLog;
import com.github.dfa.diaspora_android.util.AppSettings;
import com.github.dfa.diaspora_android.util.ContextUtils;
import com.github.dfa.diaspora_android.util.DiasporaUrlHelper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Fragment that shows a list of the Aspects
*/
public class AspectListFragment extends ThemedFragment implements OnSomethingClickListener<Object> {
public static final String TAG = "com.github.dfa.diaspora_android.AspectListFragment";
@BindView(R.id.fragment_list__recycler_view)
public RecyclerView aspectsRecyclerView;
@BindView(R.id.fragment_list__spacer)
public View space;
@BindView(R.id.fragment_list__root)
public RelativeLayout rootView;
protected App app;
protected DiasporaUrlHelper urls;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
AppLog.d(this, "onCreateView()");
return inflater.inflate(R.layout.recycler_list__fragment, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
app = (App) getActivity().getApplication();
AppSettings appSettings = app.getSettings();
urls = new DiasporaUrlHelper(appSettings);
aspectsRecyclerView.setHasFixedSize(true);
aspectsRecyclerView.setNestedScrollingEnabled(false);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
aspectsRecyclerView.setLayoutManager(layoutManager);
final AspectAdapter adapter = new AspectAdapter(appSettings, this);
aspectsRecyclerView.setAdapter(adapter);
//Set window title
getActivity().setTitle(R.string.nav_aspects);
}
@Override
public String getFragmentTag() {
return TAG;
}
@Override
public void onCreateBottomOptionsMenu(Menu menu, MenuInflater inflater) {
/* Nothing to do */
}
@Override
public boolean onBackPressed() {
return false;
}
@Override
public void onSomethingClicked(Object null1, Integer null2, String aspectId) {
((MainActivity) getActivity()).openDiasporaUrl(urls.getAspectUrl(aspectId));
}
@Override
protected void applyColorToViews() {
aspectsRecyclerView.invalidate();
if (getAppSettings().isAmoledColorMode()) {
rootView.setBackgroundColor(Color.BLACK);
space.setBackgroundColor(Color.BLACK);
}
}
public static class AspectAdapter extends RecyclerView.Adapter<AspectAdapter.ViewHolder> {
private boolean isAmoledColorMode;
private final AppSettings appSettings;
private final DiasporaAspect[] aspectList;
private final List<String> aspectFavsList;
private final OnSomethingClickListener<Object> aspectClickedListener;
static class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.recycler_view__list_item__text)
public TextView title;
@BindView(R.id.recycler_view__list_item__favourite)
AppCompatImageView favouriteImage;
@BindView(R.id.recycler_view__list_item__root)
RelativeLayout root;
ViewHolder(View v) {
super(v);
ButterKnife.bind(this, v);
}
}
AspectAdapter(AppSettings appSettings, OnSomethingClickListener<Object> aspectClickedListener) {
this.appSettings = appSettings;
this.aspectList = appSettings.getAspects();
this.aspectFavsList = new ArrayList<>(Arrays.asList(appSettings.getAspectFavs()));
this.aspectClickedListener = aspectClickedListener;
this.isAmoledColorMode = appSettings.isAmoledColorMode();
}
@Override
public int getItemCount() {
return aspectList.length;
}
@Override
public AspectAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_list__list_item_with_fav, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
// Alternating colors
final Context c = holder.root.getContext();
final DiasporaAspect aspect = aspectList[position];
holder.title.setText(aspect.name);
if (position % 2 == 1) {
holder.root.setBackgroundColor(isAmoledColorMode ? Color.BLACK : ContextUtils.get().color(R.color.alternate_row_color));
holder.title.setTextColor(isAmoledColorMode ? Color.GRAY : Color.BLACK);
} else {
holder.root.setBackgroundColor(isAmoledColorMode ? Color.BLACK : Color.WHITE);
holder.title.setTextColor(isAmoledColorMode ? Color.GRAY : Color.BLACK);
}
// Favourite (Star) Image
applyFavouriteImage(holder.favouriteImage, isAspectFaved(aspect.name));
// Click on fav button
holder.favouriteImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isAspectFaved(aspect.name)) {
aspectFavsList.remove(aspectFavsList.indexOf(aspect.name));
} else {
aspectFavsList.add(aspect.name);
}
appSettings.setAspectFavs(aspectFavsList);
applyFavouriteImage(holder.favouriteImage, isAspectFaved(aspect.name));
}
});
holder.root.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
aspectClickedListener.onSomethingClicked(null, null, aspect.id + "");
}
});
}
private boolean isAspectFaved(String tag) {
return aspectFavsList.contains(tag);
}
private void applyFavouriteImage(AppCompatImageView imageView, boolean isFaved) {
imageView.setImageResource(isFaved ? R.drawable.ic_star_filled_48px : R.drawable.ic_star_border_black_48px);
imageView.setColorFilter(isFaved ? appSettings.getAccentColor() : (isAmoledColorMode ? Color.GRAY : 0), PorterDuff.Mode.SRC_ATOP);
}
}
}

View file

@ -25,11 +25,13 @@ import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
@ -38,12 +40,15 @@ import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;
import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.BuildConfig;
import com.github.dfa.diaspora_android.R;
import com.github.dfa.diaspora_android.data.DiasporaUserProfile;
import com.github.dfa.diaspora_android.ui.theme.ThemedAlertDialogBuilder;
import com.github.dfa.diaspora_android.util.AppLog;
import com.github.dfa.diaspora_android.util.AppSettings;
import com.github.dfa.diaspora_android.util.ContextUtils;
import com.github.dfa.diaspora_android.util.DiasporaUrlHelper;
import com.github.dfa.diaspora_android.web.BrowserFragment;
@ -51,10 +56,14 @@ import com.github.dfa.diaspora_android.web.DiasporaStreamWebChromeClient;
import com.github.dfa.diaspora_android.web.FileUploadWebChromeClient;
import com.github.dfa.diaspora_android.web.WebHelper;
import net.gsantner.opoc.util.PermissionChecker;
import net.gsantner.opoc.util.ShareUtil;
import org.json.JSONException;
import java.io.File;
import java.io.IOException;
import java.util.Date;
/**
* Fragment that displays the Stream of the diaspora* user
@ -92,13 +101,15 @@ public class DiasporaStreamFragment extends BrowserFragment {
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.stream__menu_top, menu);
super.onCreateOptionsMenu(menu, inflater);
}
inflater.inflate(R.menu.stream__menu_top, menu);
@Override
public void onCreateBottomOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.stream__menu_bottom, menu);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
menu.findItem(R.id.action_share_pdf).setVisible(true);
}
final boolean darkBg = ContextUtils.get().shouldColorOnTopBeLight(AppSettings.get().getPrimaryColor());
ContextUtils.get().tintMenuItems(menu, true, ContextCompat.getColor(getActivity(), darkBg ? R.color.white : R.color.black));
}
@Override
@ -117,6 +128,8 @@ public class DiasporaStreamFragment extends BrowserFragment {
@Override
public boolean onOptionsItemSelected(MenuItem item) {
AppLog.d(this, "StreamFragment.onOptionsItemSelected()");
ShareUtil shu = new ShareUtil(getContext());
PermissionChecker permc = new PermissionChecker(getActivity());
switch (item.getItemId()) {
case R.id.action_reload: {
if (WebHelper.isOnline(getContext())) {
@ -139,17 +152,51 @@ public class DiasporaStreamFragment extends BrowserFragment {
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, webView.getTitle());
sharingIntent.putExtra(Intent.EXTRA_TEXT, webView.getUrl());
startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.action_share_dotdotdot)));
startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.share_dotdotdot)));
return true;
}
case R.id.action_share_pdf: {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
shu.createPdf(webView, "dandelion-" + ShareUtil.SDF_SHORT.format(new Date()));
}
return true;
}
case R.id.action_share_link_to_clipboard: {
shu.setClipboard(webView.getUrl());
Toast.makeText(getContext(), R.string.link_adress_copied, Toast.LENGTH_SHORT).show();
return true;
}
case R.id.action_create_launcher_shortcut: {
if (webView.getUrl() != null) {
Intent intent = new Intent(getContext(), MainActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(webView.getUrl()));
shu.createLauncherDesktopShortcut(intent, R.drawable.ic_launcher, webView.getTitle());
}
return true;
}
case R.id.action_take_screenshot: {
makeScreenshotOfWebView(false);
if (permc.doIfExtStoragePermissionGranted(getString(R.string.screenshot_permission__appspecific))) {
File fileSaveDirectory = appSettings.getAppSaveDirectory();
if (permc.mkdirIfStoragePermissionGranted(fileSaveDirectory)) {
Bitmap bmp = ShareUtil.getBitmapFromWebView(webView);
String filename = "dandelion-" + ShareUtil.SDF_SHORT.format(new Date()) + ".jpg";
_cu.writeImageToFile(new File(fileSaveDirectory, filename), bmp);
Snackbar.make(webView, getString(R.string.saving_screenshot_as)
+ " " + filename, Snackbar.LENGTH_LONG).show();
}
}
return true;
}
case R.id.action_share_screenshot: {
makeScreenshotOfWebView(true);
if (permc.doIfExtStoragePermissionGranted(getString(R.string.screenshot_permission__appspecific))) {
shu.shareImage(ShareUtil.getBitmapFromWebView(webView));
}
return true;
}
}
@ -246,7 +293,7 @@ public class DiasporaStreamFragment extends BrowserFragment {
if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
new ThemedAlertDialogBuilder(getContext(), appSettings)
.setMessage(R.string.permissions_image)
.setMessage(R.string.image_permission_description__appspecific)
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
@ -324,13 +371,30 @@ public class DiasporaStreamFragment extends BrowserFragment {
@SuppressWarnings("unused")
@JavascriptInterface
public void setUserProfile(final String webMessage) throws JSONException {
final DiasporaUserProfile pup = ((App) getActivity().getApplication()).getDiasporaUserProfile();
if (pup.isRefreshNeeded()) {
AppLog.v(this, "DiasporaUserProfile needs refresh; Try to parse JSON");
pup.parseJson(webMessage);
getActivity().runOnUiThread(new Runnable() {
final Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
pup.analyzeUrl(webView.getUrl());
App app = ((App) activity.getApplication());
final DiasporaUserProfile pup = app.getDiasporaUserProfile();
if (pup.isRefreshNeeded()) {
try {
// Try to very fail-safe check if user information gets really loaded from correct pod
if (!webView.getUrl().startsWith(app.getSettings().getPod().getPodUrl().getBaseUrl())) {
return;
}
} catch (Exception ignored) {
return;
}
AppLog.v(this, "DiasporaUserProfile needs refresh; Try to parse JSON");
pup.parseJson(webMessage);
getActivity().runOnUiThread(new Runnable() {
public void run() {
pup.analyzeUrl(webView.getUrl());
}
});
}
}
});
}

View file

@ -36,14 +36,15 @@ import android.support.customtabs.CustomTabsSession;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
@ -61,8 +62,8 @@ import android.widget.TextView;
import android.widget.Toast;
import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.BuildConfig;
import com.github.dfa.diaspora_android.R;
import com.github.dfa.diaspora_android.data.DiasporaAspect;
import com.github.dfa.diaspora_android.data.DiasporaPodList;
import com.github.dfa.diaspora_android.data.DiasporaUserProfile;
import com.github.dfa.diaspora_android.listener.DiasporaUserProfileChangedListener;
@ -71,10 +72,11 @@ import com.github.dfa.diaspora_android.receiver.OpenExternalLinkReceiver;
import com.github.dfa.diaspora_android.receiver.UpdateTitleReceiver;
import com.github.dfa.diaspora_android.ui.BadgeDrawable;
import com.github.dfa.diaspora_android.ui.PodSelectionDialog;
import com.github.dfa.diaspora_android.ui.theme.CustomFragment;
import com.github.dfa.diaspora_android.ui.SearchOrCustomTextDialogCreator;
import com.github.dfa.diaspora_android.ui.theme.ThemeHelper;
import com.github.dfa.diaspora_android.ui.theme.ThemedActivity;
import com.github.dfa.diaspora_android.ui.theme.ThemedAlertDialogBuilder;
import com.github.dfa.diaspora_android.ui.theme.ThemedFragment;
import com.github.dfa.diaspora_android.util.ActivityUtils;
import com.github.dfa.diaspora_android.util.AndroidBug5497Workaround;
import com.github.dfa.diaspora_android.util.AppLog;
@ -87,7 +89,7 @@ import com.github.dfa.diaspora_android.web.ProxyHandler;
import com.github.dfa.diaspora_android.web.WebHelper;
import com.github.dfa.diaspora_android.web.custom_tab.CustomTabActivityHelper;
import net.gsantner.opoc.util.SimpleMarkdownParser;
import net.gsantner.opoc.format.markdown.SimpleMarkdownParser;
import java.io.IOException;
@ -138,9 +140,6 @@ public class MainActivity extends ThemedActivity
@BindView(R.id.main__topbar)
Toolbar toolbarTop;
@BindView(R.id.main__bottombar)
ActionMenuView toolbarBottom;
@BindView(R.id.fragment_container)
FrameLayout fragmentContainer;
@ -178,6 +177,7 @@ public class MainActivity extends ThemedActivity
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
// Bind UI
setContentView(R.layout.main__activity);
ButterKnife.bind(this);
@ -201,7 +201,7 @@ public class MainActivity extends ThemedActivity
brOpenExternalLink = new OpenExternalLinkReceiver(this);
brSetTitle = new UpdateTitleReceiver(app, urls, new UpdateTitleReceiver.TitleCallback() {
public void setTitle(String url, int resId) {
CustomFragment top = getTopFragment();
ThemedFragment top = getTopFragment();
if (top != null && top.getFragmentTag().equals(DiasporaStreamFragment.TAG)) {
MainActivity.this.setTitle(resId);
showLastVisitedTimestampMessageIfNeeded(url);
@ -209,7 +209,7 @@ public class MainActivity extends ThemedActivity
}
public void setTitle(String url, String title) {
CustomFragment top = getTopFragment();
ThemedFragment top = getTopFragment();
if (top != null && top.getFragmentTag().equals(DiasporaStreamFragment.TAG)) {
MainActivity.this.setTitle(title);
}
@ -231,23 +231,16 @@ public class MainActivity extends ThemedActivity
}
}
// Show first start dialog
// Show first start / update dialog
try {
SimpleMarkdownParser mdParser = SimpleMarkdownParser.get().setDefaultSmpFilter(SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW);
if (_appSettings.isAppFirstStart()) {
mdParser.parse(
getResources().openRawResource(R.raw.license), "");
String html = mdParser.getHtml()
+ "<br/><br/><br/>"
+ "<h1>" + getString(R.string.fragment_license__thirdparty_libs) + "</h1>"
+ mdParser.parse(getResources().openRawResource(R.raw.license_third_party), "");
html = mdParser.setHtml(html).removeMultiNewlines().getHtml();
ActivityUtils.get(this).showDialogWithHtmlTextView(R.string.about_activity__title_about_license, html);
_appSettings.isAppCurrentVersionFirstStart();
} else if (_appSettings.isAppCurrentVersionFirstStart()) {
SimpleMarkdownParser smp = new SimpleMarkdownParser().parse(
getResources().openRawResource(R.raw.changelog), "");
ActivityUtils.get(this).showDialogWithHtmlTextView(R.string.changelog, smp.getHtml());
if (_appSettings.isAppCurrentVersionFirstStart(true)) {
SimpleMarkdownParser smp = SimpleMarkdownParser.get().setDefaultSmpFilter(SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW);
String html = "";
html += smp.parse(getString(R.string.copyright_license_text_official).replace("\n", " \n"), "").getHtml();
html += "<br/><br/><br/><big><big>" + getString(R.string.changelog) + "</big></big><br/>" + smp.parse(getResources().openRawResource(R.raw.changelog), "", SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW, SimpleMarkdownParser.FILTER_CHANGELOG).getHtml();
html += "<br/><br/><br/><big><big>" + getString(R.string.licenses) + "</big></big><br/>" + smp.parse(getResources().openRawResource(R.raw.licenses_3rd_party), "").getHtml();
ActivityUtils _au = new ActivityUtils(this);
_au.showDialogWithHtmlTextView(R.string.licenses, html);
}
} catch (IOException e) {
e.printStackTrace();
@ -267,17 +260,11 @@ public class MainActivity extends ThemedActivity
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
toolbarBottom.setOnMenuItemClickListener(new ActionMenuView.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
CustomFragment top = getTopFragment();
return MainActivity.this.onOptionsItemSelected(item) || (top != null && top.onOptionsItemSelected(item));
}
});
setTitle(R.string.app_name);
//Setup snackbar
snackbarExitApp = Snackbar
.make(fragmentContainer, R.string.confirm_exit, Snackbar.LENGTH_LONG)
.make(fragmentContainer, R.string.do_you_want_to_exit, Snackbar.LENGTH_LONG)
.setAction(android.R.string.yes, new View.OnClickListener() {
public void onClick(View view) {
finish();
@ -286,13 +273,13 @@ public class MainActivity extends ThemedActivity
});
snackbarLastVisitedTimestampInStream =
Snackbar.make(fragmentContainer,
R.string.jump_to_last_visited_timestamp_in_stream, Snackbar.LENGTH_LONG)
R.string.jump_to_last_visited_page_in_stream__appspecific, Snackbar.LENGTH_LONG)
.setAction(android.R.string.yes, new View.OnClickListener() {
public void onClick(View view) {
openDiasporaUrl(urls.getStreamWithTimestampUrl(diasporaUserProfile.getLastVisitedPositionInStream()));
}
});
snackbarNoInternet = Snackbar.make(fragmentContainer, R.string.no_internet, Snackbar.LENGTH_LONG);
snackbarNoInternet = Snackbar.make(fragmentContainer, R.string.sorry_need_to_be_connected_to_internet, Snackbar.LENGTH_LONG);
// Load app settings
setupNavigationSlider();
@ -300,15 +287,15 @@ public class MainActivity extends ThemedActivity
}
/**
* Get an instance of the CustomFragment with the tag fragmentTag.
* Get an instance of the ThemedFragment with the tag fragmentTag.
* If there was no instance so far, create a new one and add it to the FragmentManagers pool.
* If there is no Fragment with the corresponding Tag, return the top fragment.
*
* @param fragmentTag tag
* @return corresponding Fragment
*/
protected CustomFragment getFragment(String fragmentTag) {
CustomFragment fragment = (CustomFragment) fm.findFragmentByTag(fragmentTag);
protected ThemedFragment getFragment(String fragmentTag) {
ThemedFragment fragment = (ThemedFragment) fm.findFragmentByTag(fragmentTag);
if (fragment != null) {
return fragment;
} else {
@ -321,14 +308,6 @@ public class MainActivity extends ThemedActivity
BrowserFragment bf = new BrowserFragment();
fm.beginTransaction().add(bf, fragmentTag).commit();
return bf;
case TagListFragment.TAG:
TagListFragment hlf = new TagListFragment();
fm.beginTransaction().add(hlf, fragmentTag).commit();
return hlf;
case AspectListFragment.TAG:
AspectListFragment alf = new AspectListFragment();
fm.beginTransaction().add(alf, fragmentTag).commit();
return alf;
case PodSelectionFragment.TAG:
PodSelectionFragment psf = new PodSelectionFragment();
fm.beginTransaction().add(psf, fragmentTag).commit();
@ -346,12 +325,30 @@ public class MainActivity extends ThemedActivity
*
* @param url URL to load in the DiasporaStreamFragment
*/
public void openDiasporaUrl(String url) {
public void openDiasporaUrl(final String url) {
AppLog.v(this, "openDiasporaUrl()");
DiasporaStreamFragment streamFragment = (DiasporaStreamFragment) getFragment(DiasporaStreamFragment.TAG);
showFragment(streamFragment);
showLastVisitedTimestampMessageIfNeeded(url);
streamFragment.loadUrl(url);
if (url != null && url.startsWith("http://127.0.0.1")) {
// This URL seems to be called somehow, but it doesn't make sense ;)
toolbarTop.postDelayed(() -> {
Intent i = new Intent(ACTION_OPEN_EXTERNAL_URL);
i.putExtra(EXTRA_URL, "https://github.com/gsantner/dandelion/blob/master/README.md");
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
}, 1000);
return;
}
if (_appSettings.getPod() != null && _appSettings.getPod().getPodUrl() != null && _appSettings.getPod().getPodUrl().getBaseUrl() != null
&& url.startsWith(_appSettings.getPod().getPodUrl().getBaseUrl()) && !url.startsWith("https://dia.so/")) {
DiasporaStreamFragment streamFragment = (DiasporaStreamFragment) getFragment(DiasporaStreamFragment.TAG);
showFragment(streamFragment);
showLastVisitedTimestampMessageIfNeeded(url);
streamFragment.loadUrl(url);
} else {
toolbarTop.postDelayed(() -> {
Intent i = new Intent(ACTION_OPEN_EXTERNAL_URL);
i.putExtra(EXTRA_URL, url);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
}, 1000);
}
}
public void showLastVisitedTimestampMessageIfNeeded(String url) {
@ -366,18 +363,21 @@ public class MainActivity extends ThemedActivity
*
* @param fragment Fragment to show
*/
protected void showFragment(CustomFragment fragment) {
protected void showFragment(ThemedFragment fragment) {
if (PodSelectionFragment.TAG.equals(fragment.getTag())) {
Fragment fragment1 = fm.findFragmentByTag(DiasporaStreamFragment.TAG);
if (fragment1 != null) {
new net.gsantner.opoc.util.ContextUtils(this).restartApp(MainActivity.class);
}
}
AppLog.v(this, "showFragment()");
CustomFragment currentTop = (CustomFragment) fm.findFragmentById(R.id.fragment_container);
ThemedFragment currentTop = (ThemedFragment) fm.findFragmentById(R.id.fragment_container);
if (currentTop == null || !currentTop.getFragmentTag().equals(fragment.getFragmentTag())) {
AppLog.v(this, "Fragment was not visible. Replace it.");
fm.beginTransaction().addToBackStack(null).replace(R.id.fragment_container, fragment, fragment.getFragmentTag()).commit();
invalidateOptionsMenu();
if (_appSettings.isIntellihideToolbars() && fragment.isAllowedIntellihide()) {
this.enableToolbarHiding();
} else {
this.disableToolbarHiding();
}
setToolbarIntellihide(_appSettings.isIntellihideToolbars() && fragment.isAllowedIntellihide());
} else {
AppLog.v(this, "Fragment was already visible. Do nothing.");
}
@ -388,7 +388,7 @@ public class MainActivity extends ThemedActivity
*/
private void setupNavigationSlider() {
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, navDrawer, toolbarTop, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
this, navDrawer, toolbarTop, R.string.open_navdrawer, R.string.close_navdrawer);
navDrawer.addDrawerListener(toggle);
toggle.syncState();
@ -432,8 +432,6 @@ public class MainActivity extends ThemedActivity
app.getAvatarImageLoader().startImageDownload(navheaderImage, avatarUrl);
}
}
} else if (BuildConfig.IS_TEST_BUILD) {
navheaderImage.setImageResource(R.drawable.ic_launcher_test);
}
updateNavigationViewEntryVisibilities();
}
@ -460,7 +458,7 @@ public class MainActivity extends ThemedActivity
navMenu.findItem(R.id.nav_statistics).setVisible(_appSettings.isVisibleInNavStatistics());
navMenu.findItem(R.id.nav_reports).setVisible(_appSettings.isVisibleInNavReports());
navMenu.findItem(R.id.nav_toggle_desktop_page).setVisible(_appSettings.isVisibleInNavToggleMobileDesktop());
navMenu.findItem(R.id.nav_dandelion).setVisible(_appSettings.isVisibleInNavDandelionAccount());
navMenu.findItem(R.id.nav_product_support).setVisible(_appSettings.isVisibleInNavGsantnerAccount());
// Hide whole group (for logged in use) if no pod was selected
@ -561,6 +559,18 @@ public class MainActivity extends ThemedActivity
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
/* TODO: Implement and add filter to manifest */
return;
} else if ("sc_new_post".equals(action)) {
openDiasporaUrl(urls.getNewPostUrl());
return;
} else if ("sc_activities".equals(action)) {
openDiasporaUrl(urls.getActivityUrl());
return;
} else if ("sc_contacts".equals(action)) {
onNavigationItemSelected(navView.getMenu().findItem(R.id.nav_aspects));
return;
} else if ("sc_tags".equals(action)) {
onNavigationItemSelected(navView.getMenu().findItem(R.id.nav_followed_tags));
return;
}
//Catch split screen recreation
if (action != null && action.equals(Intent.ACTION_MAIN) && getTopFragment() != null) {
@ -591,8 +601,8 @@ public class MainActivity extends ThemedActivity
*
* @return top fragment or null if there is none displayed
*/
private CustomFragment getTopFragment() {
return (CustomFragment) fm.findFragmentById(R.id.fragment_container);
private ThemedFragment getTopFragment() {
return (ThemedFragment) fm.findFragmentById(R.id.fragment_container);
}
/**
@ -605,7 +615,7 @@ public class MainActivity extends ThemedActivity
navDrawer.closeDrawer(navView);
return;
}
CustomFragment top = getTopFragment();
ThemedFragment top = getTopFragment();
if (top != null) {
AppLog.v(this, "Top Fragment is not null");
if (!top.onBackPressed()) {
@ -661,10 +671,9 @@ public class MainActivity extends ThemedActivity
if (_appSettings.isRecreateMainActivity()) {
recreate();
}
if (_appSettings.isIntellihideToolbars()) {
enableToolbarHiding();
} else {
disableToolbarHiding();
setToolbarIntellihide(_appSettings.isIntellihideToolbars());
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(AppSettings.get().isShowTitleInMainView());
}
updateNavigationViewEntryVisibilities();
}
@ -679,24 +688,26 @@ public class MainActivity extends ThemedActivity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
AppLog.v(this, "onCreateOptionsMenu()");
boolean cache;
//Clear the menus
menu.clear();
toolbarBottom.getMenu().clear();
toolbarBottom.setVisibility(View.VISIBLE);
CustomFragment top = getTopFragment();
ThemedFragment top = getTopFragment();
if (top != null) {
//PodSelectionFragment?
if (top.getFragmentTag().equals(PodSelectionFragment.TAG)) {
///Hide bottom _toolbar
toolbarBottom.setVisibility(View.GONE);
} else {
getMenuInflater().inflate(_appSettings.isExtendedNotificationsActivated() ?
R.menu.main__menu_top__notifications_dropdown : R.menu.main__menu_top, menu);
getMenuInflater().inflate(R.menu.main__menu_bottom, toolbarBottom.getMenu());
top.onCreateBottomOptionsMenu(toolbarBottom.getMenu(), getMenuInflater());
if (!top.getFragmentTag().equals(PodSelectionFragment.TAG)) {
cache = _appSettings.isExtendedNotificationsActivated();
getMenuInflater().inflate(R.menu.main__menu_top, menu);
menu.findItem(R.id.action_notifications).setVisible(!cache);
menu.findItem(R.id.action_notifications_extended).setVisible(cache);
}
}
ContextUtils cu = ContextUtils.get();
final boolean darkBg = cu.get().shouldColorOnTopBeLight(AppSettings.get().getPrimaryColor());
cu.tintMenuItems(menu, true, ContextCompat.getColor(this, darkBg ? R.color.white : R.color.black));
cu.setSubMenuIconsVisiblity(menu, true);
return true;
}
@ -834,7 +845,7 @@ public class MainActivity extends ThemedActivity
final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
@SuppressLint("InflateParams") View layout = getLayoutInflater().inflate(R.layout.ui__dialog_search__people_tags, null, false);
final EditText input = (EditText) layout.findViewById(R.id.dialog_search__input);
final EditText input = layout.findViewById(R.id.dialog_search__input);
input.setMaxLines(1);
input.setSingleLine(true);
ThemeHelper.updateEditTextColor(input);
@ -843,7 +854,7 @@ public class MainActivity extends ThemedActivity
public void onClick(DialogInterface dialogInterface, int which) {
String query = input.getText().toString().trim().replaceAll((which == DialogInterface.BUTTON_NEGATIVE ? "\\*" : "\\#"), "");
if (query.equals("")) {
Snackbar.make(fragmentContainer, R.string.search_alert_bypeople_validate_needsomedata, Snackbar.LENGTH_LONG).show();
Snackbar.make(fragmentContainer, R.string.please_add_a_name, Snackbar.LENGTH_LONG).show();
} else {
openDiasporaUrl(which == DialogInterface.BUTTON_NEGATIVE ? urls.getSearchPeopleUrl(query) : urls.getSearchTagsUrl(query));
}
@ -855,8 +866,8 @@ public class MainActivity extends ThemedActivity
final AlertDialog dialog = new ThemedAlertDialogBuilder(this, _appSettings)
.setView(layout).setTitle(R.string.search_alert_title)
.setCancelable(true)
.setPositiveButton(R.string.search_alert_tag, clickListener)
.setNegativeButton(R.string.search_alert_people, clickListener)
.setPositiveButton(R.string.by_tags, clickListener)
.setNegativeButton(R.string.by_people, clickListener)
.create();
input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@ -1052,12 +1063,39 @@ public class MainActivity extends ThemedActivity
break;
case R.id.nav_followed_tags: {
showFragment(getFragment(TagListFragment.TAG));
SearchOrCustomTextDialogCreator.showDiasporaTagsDialog(this, arg -> {
if (arg.startsWith(SearchOrCustomTextDialogCreator.SPECIAL_PREFIX)) {
arg = arg.replace(SearchOrCustomTextDialogCreator.SPECIAL_PREFIX, "").trim();
if (arg.equals(getString(R.string.manage_hashtags))) {
openDiasporaUrl(urls.getManageTagsUrl());
} else {
openDiasporaUrl(urls.getAllFollowedTagsUrl());
}
} else {
openDiasporaUrl(urls.getSearchTagsUrl(arg));
}
});
}
break;
case R.id.nav_aspects: {
showFragment(getFragment(AspectListFragment.TAG));
SearchOrCustomTextDialogCreator.showDiasporaAspectsDialog(this, arg -> {
if (arg.startsWith(SearchOrCustomTextDialogCreator.SPECIAL_PREFIX)) {
arg = arg.replace(SearchOrCustomTextDialogCreator.SPECIAL_PREFIX, "").trim();
if (arg.equals(getString(R.string.manage_your_contact_list))) {
openDiasporaUrl(urls.getContactsUrl());
} else if (arg.equals(getString(R.string.nav_profile))) {
openDiasporaUrl(urls.getProfileUrl());
}
} else {
for (DiasporaAspect daspect : _appSettings.getAspects()) {
if (arg.equals(daspect.name)) {
openDiasporaUrl(urls.getAspectUrl(Long.toString(daspect.id)));
break;
}
}
}
});
}
break;
@ -1138,8 +1176,8 @@ public class MainActivity extends ThemedActivity
}
break;
case R.id.nav_dandelion: {
openDiasporaUrl(urls.getProfileUrl("48b78420923501341ef3782bcb452bd5"));
case R.id.nav_product_support: {
openDiasporaUrl(urls.getProfileUrl("d1cbdd70095301341e834860008dbc6c"));
}
break;
@ -1211,7 +1249,6 @@ public class MainActivity extends ThemedActivity
@Override
protected void applyColorToViews() {
ThemeHelper.updateToolbarColor(toolbarTop);
ThemeHelper.updateActionMenuViewColor(toolbarBottom);
navDrawerLayout.setBackgroundColor(_appSettings.getPrimaryColor());
navProfilePictureArea.setBackgroundColor(_appSettings.getPrimaryColor());
if (_appSettings.isAmoledColorMode()) {
@ -1221,22 +1258,22 @@ public class MainActivity extends ThemedActivity
navheaderTitle.setTextColor(Color.GRAY);
navheaderDescription.setTextColor(Color.DKGRAY);
}
int popupTheme = ContextUtils.get().shouldColorOnTopBeLight(AppSettings.get().getPrimaryColor())
? R.style.AppTheme_PopupOverlay_Dark : R.style.AppTheme_PopupOverlay_Light;
toolbarTop.setPopupTheme(popupTheme);
}
@Override
public void enableToolbarHiding() {
AppLog.d(this, "Enable Intellihide");
public void setToolbarIntellihide(boolean enable) {
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbarTop.getLayoutParams();
//scroll|enterAlways|snap
params.setScrollFlags(toolbarDefaultScrollFlags);
appBarLayout.setExpanded(true, true);
}
if (enable) {
AppLog.d(this, "Enable Intellihide");
params.setScrollFlags(toolbarDefaultScrollFlags);
@Override
public void disableToolbarHiding() {
AppLog.d(this, "Disable Intellihide");
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbarTop.getLayoutParams();
params.setScrollFlags(0); // clear all scroll flags
} else {
AppLog.d(this, "Disable Intellihide");
params.setScrollFlags(0); // clear all scroll flags
}
appBarLayout.setExpanded(true, true);
}
}

View file

@ -22,17 +22,16 @@ import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
@ -53,7 +52,6 @@ import com.github.dfa.diaspora_android.service.FetchPodsService;
import com.github.dfa.diaspora_android.ui.PodSelectionDialog;
import com.github.dfa.diaspora_android.ui.theme.ThemedFragment;
import com.github.dfa.diaspora_android.util.ActivityUtils;
import com.github.dfa.diaspora_android.util.AppLog;
import com.github.dfa.diaspora_android.util.AppSettings;
import com.github.dfa.diaspora_android.util.ContextUtils;
import com.github.dfa.diaspora_android.util.DiasporaUrlHelper;
@ -92,16 +90,14 @@ public class PodSelectionFragment extends ThemedFragment implements SearchView.O
private String filterString = "";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
AppLog.d(this, "onCreateView()");
View view = inflater.inflate(R.layout.podselection__fragment, container, false);
ButterKnife.bind(this, view);
return view;
protected int getLayoutResId() {
return R.layout.podselection__fragment;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
app = (App) getActivity().getApplication();
appSettings = app.getSettings();
@ -165,7 +161,7 @@ public class PodSelectionFragment extends ThemedFragment implements SearchView.O
} catch (JSONException ignored) {
}
} else {
Snackbar.make(listViewPod, R.string.podlist_error, Snackbar.LENGTH_SHORT).show();
Snackbar.make(listViewPod, R.string.could_not_retrieve_list_of_pods__appspecific, Snackbar.LENGTH_SHORT).show();
}
}
}
@ -177,13 +173,10 @@ public class PodSelectionFragment extends ThemedFragment implements SearchView.O
rootView.setBackgroundColor(appSettings.isAmoledColorMode() ? Color.BLACK : Color.WHITE);
listViewPod.setDivider(new ColorDrawable(Color.GRAY));
listViewPod.setDividerHeight(dividerHeight);
if (appSettings.isAmoledColorMode()) {
buttonUseCustomPod.setSupportBackgroundTintList(ColorStateList.valueOf(Color.DKGRAY));
buttonUseCustomPod.setTextColor(Color.WHITE);
} else {
buttonUseCustomPod.setSupportBackgroundTintList(ColorStateList.valueOf(appSettings.getAccentColor()));
buttonUseCustomPod.setTextColor(ContextUtils.get().shouldColorOnTopBeLight(appSettings.getAccentColor()) ? Color.WHITE : Color.BLACK);
}
int bgcolor = appSettings.isAmoledColorMode() ? Color.DKGRAY : appSettings.getAccentColor();
buttonUseCustomPod.setBackgroundColor(bgcolor);
buttonUseCustomPod.setTextColor(_cu.shouldColorOnTopBeLight(bgcolor) ? Color.WHITE : Color.BLACK);
}
@Override
@ -206,7 +199,7 @@ public class PodSelectionFragment extends ThemedFragment implements SearchView.O
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view.findViewById(android.R.id.text1);
TextView textView = view.findViewById(android.R.id.text1);
textView.setTextColor(appSettings.isAmoledColorMode() ? Color.GRAY : Color.BLACK);
return view;
}
@ -235,6 +228,7 @@ public class PodSelectionFragment extends ThemedFragment implements SearchView.O
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.podselection__menu, menu);
MenuItem searchItem = menu.findItem(R.id.podselection__action_search);
@ -243,7 +237,8 @@ public class PodSelectionFragment extends ThemedFragment implements SearchView.O
searchView.setOnQueryTextListener(this);
}
super.onCreateOptionsMenu(menu, inflater);
final boolean darkBg = ContextUtils.get().shouldColorOnTopBeLight(AppSettings.get().getPrimaryColor());
ContextUtils.get().tintMenuItems(menu, true, ContextCompat.getColor(getActivity(), darkBg ? R.color.white : R.color.black));
}
@Override
@ -299,11 +294,6 @@ public class PodSelectionFragment extends ThemedFragment implements SearchView.O
/*
* Dummy implementations
*/
@Override
public void onCreateBottomOptionsMenu(Menu menu, MenuInflater inflater) {
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;

View file

@ -131,7 +131,7 @@ public class SettingsActivity extends ThemedActivity implements SharedPreference
if (top != null && top.getFragmentTag().equals(SettingsFragmentProxy.TAG)) {
ProxyHandler.ProxySettings newProxySettings = getAppSettings().getProxySettings();
if (oldProxySettings.isEnabled() && !newProxySettings.isEnabled()) {
Toast.makeText(this, R.string.toast__proxy_disabled__restart_required, Toast.LENGTH_LONG).show();
Toast.makeText(this, R.string.app_needs_restart_to_disable_proxy_usage, Toast.LENGTH_LONG).show();
}
}
super.onBackPressed();
@ -190,8 +190,7 @@ public class SettingsActivity extends ThemedActivity implements SharedPreference
/** Usability */
else if (settings.isKeyEqual(key, R.string.pref_key__is_overview_statusbar_hidden)) {
AppSettings.get().setRecreateMainActivity(true);
}
else if (settings.isKeyEqual(key, R.string.pref_key__language)) {
} else if (settings.isKeyEqual(key, R.string.pref_key__language)) {
AppSettings.get().setRecreateMainActivity(true);
}
/** Network */
@ -227,7 +226,7 @@ public class SettingsActivity extends ThemedActivity implements SharedPreference
} else if (settings.isKeyEqual(key, R.string.pref_key__change_account)) {
new ThemedAlertDialogBuilder(getActivity(), AppSettings.get())
.setTitle(getString(R.string.confirmation))
.setMessage(getString(R.string.pref_warning__change_account))
.setMessage(getString(R.string.logout_warning_description))
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
@ -272,6 +271,8 @@ public class SettingsActivity extends ThemedActivity implements SharedPreference
@Override
public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) {
AppSettings settings = ((App) getActivity().getApplication()).getSettings();
DiasporaUrlHelper diasporaUrlHelper = new DiasporaUrlHelper(settings);
if (isAdded() && preference.hasKey()) {
String key = preference.getKey();
if (key.equals(getString(R.string.pref_key__primary_color__preference_click))) {
@ -280,6 +281,13 @@ public class SettingsActivity extends ThemedActivity implements SharedPreference
} else if (key.equals(getString(R.string.pref_key__accent_color__preference_click))) {
showColorPickerDialog(2);
return true;
} else if (key.equals(getString(R.string.pref_key__manage_theme))) {
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.setAction(MainActivity.ACTION_OPEN_URL);
intent.putExtra(MainActivity.URL_MESSAGE, diasporaUrlHelper.getThemeUrl());
startActivity(intent);
getActivity().finish();
return true;
}
}
return super.onPreferenceTreeClick(screen, preference);
@ -306,12 +314,12 @@ public class SettingsActivity extends ThemedActivity implements SharedPreference
final ThemedAlertDialogBuilder builder = new ThemedAlertDialogBuilder(context, appSettings);
builder.setView(dialogLayout);
final FrameLayout titleBackground = (FrameLayout) dialogLayout.findViewById(R.id.color_picker_dialog__title_background);
final TextView title = (TextView) dialogLayout.findViewById(R.id.color_picker_dialog__title);
final LineColorPicker base = (LineColorPicker) dialogLayout.findViewById(R.id.color_picker_dialog__base_picker);
final LineColorPicker shade = (LineColorPicker) dialogLayout.findViewById(R.id.color_picker_dialog__shade_picker);
final FrameLayout titleBackground = dialogLayout.findViewById(R.id.color_picker_dialog__title_background);
final TextView title = dialogLayout.findViewById(R.id.color_picker_dialog__title);
final LineColorPicker base = dialogLayout.findViewById(R.id.color_picker_dialog__base_picker);
final LineColorPicker shade = dialogLayout.findViewById(R.id.color_picker_dialog__shade_picker);
title.setText(type == 1 ? R.string.pref_title__primary_color : R.string.pref_title__accent_color);
title.setText(type == 1 ? R.string.primary_colors : R.string.accent_color);
title.setTextColor(getResources().getColor(R.color.white));
final int[] current = (type == 1 ? appSettings.getPrimaryColorSettings() : appSettings.getAccentColorSettings());
base.setColors((type == 1 ? ColorPalette.getBaseColors(context) : ColorPalette.getAccentColors(context)));
@ -413,7 +421,7 @@ public class SettingsActivity extends ThemedActivity implements SharedPreference
if (appSettings.isKeyEqual(key, R.string.pref_key__http_proxy_load_tor_preset)) {
appSettings.setProxyHttpHost("127.0.0.1");
appSettings.setProxyHttpPort(8118);
Toast.makeText(screen.getContext(), R.string.toast__proxy_orbot_preset_loaded, Toast.LENGTH_SHORT).show();
Toast.makeText(screen.getContext(), R.string.orbot_proxy_preset_loaded, Toast.LENGTH_SHORT).show();
return true;
}
}
@ -478,17 +486,13 @@ public class SettingsActivity extends ThemedActivity implements SharedPreference
ThemedAlertDialogBuilder builder = new ThemedAlertDialogBuilder(getActivity(), appSettings);
builder.setTitle(R.string.confirmation)
.setMessage(R.string.dialog_content__wipe_settings)
.setMessage(R.string.wipe_settings_warning__appspecific)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
appSettings.resetAppSettings();
appSettings.resetPodSettings();
Intent restartActivity = new Intent(getActivity(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 12374, restartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent);
System.exit(0);
new net.gsantner.opoc.util.ContextUtils(appSettings.getContext()).restartApp(MainActivity.class);
}
}).setNegativeButton(android.R.string.cancel, null)
.create().show();

View file

@ -1,215 +0,0 @@
/*
This file is part of the dandelion*.
dandelion* is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
dandelion* is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the dandelion*.
If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.dfa.diaspora_android.activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.R;
import com.github.dfa.diaspora_android.listener.OnSomethingClickListener;
import com.github.dfa.diaspora_android.ui.theme.ThemedFragment;
import com.github.dfa.diaspora_android.util.AppLog;
import com.github.dfa.diaspora_android.util.AppSettings;
import com.github.dfa.diaspora_android.util.ContextUtils;
import com.github.dfa.diaspora_android.util.DiasporaUrlHelper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Fragment that shows a list of the HashTags the user follows
*/
public class TagListFragment extends ThemedFragment implements OnSomethingClickListener<Object> {
public static final String TAG = "com.github.dfa.diaspora_android.TagListFragment";
@BindView(R.id.fragment_list__recycler_view)
public RecyclerView followedTagsRecyclerView;
@BindView(R.id.fragment_list__spacer)
public View space;
@BindView(R.id.fragment_list__root)
public RelativeLayout rootView;
protected App app;
protected DiasporaUrlHelper urls;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
AppLog.d(this, "onCreateView()");
return inflater.inflate(R.layout.recycler_list__fragment, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
app = (App) getActivity().getApplication();
AppSettings appSettings = app.getSettings();
urls = new DiasporaUrlHelper(appSettings);
followedTagsRecyclerView.setHasFixedSize(true);
followedTagsRecyclerView.setNestedScrollingEnabled(false);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
followedTagsRecyclerView.setLayoutManager(layoutManager);
final FollowedTagsAdapter adapter = new FollowedTagsAdapter(appSettings, this);
followedTagsRecyclerView.setAdapter(adapter);
//Set window title
getActivity().setTitle(R.string.nav_followed_tags);
}
@Override
public String getFragmentTag() {
return TAG;
}
@Override
public void onCreateBottomOptionsMenu(Menu menu, MenuInflater inflater) {
/* Nothing to do */
}
@Override
public boolean onBackPressed() {
return false;
}
@Override
public void onSomethingClicked(Object null1, Integer null2, String tag) {
((MainActivity) getActivity()).openDiasporaUrl(urls.getSearchTagsUrl(tag));
}
@Override
protected void applyColorToViews() {
followedTagsRecyclerView.invalidate();
if (getAppSettings().isAmoledColorMode()) {
rootView.setBackgroundColor(Color.BLACK);
space.setBackgroundColor(Color.BLACK);
}
}
public static class FollowedTagsAdapter extends RecyclerView.Adapter<FollowedTagsAdapter.ViewHolder> {
private boolean isAmoledColorMode;
private AppSettings appSettings;
private String[] followedTagsList;
private List<String> followedTagsFavsList;
private OnSomethingClickListener<Object> tagClickedListener;
static class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.recycler_view__list_item__text)
public TextView title;
@BindView(R.id.recycler_view__list_item__favourite)
AppCompatImageView favouriteImage;
@BindView(R.id.recycler_view__list_item__root)
RelativeLayout root;
ViewHolder(View v) {
super(v);
ButterKnife.bind(this, v);
}
}
FollowedTagsAdapter(AppSettings appSettings, OnSomethingClickListener<Object> tagClickedListener) {
this.appSettings = appSettings;
this.followedTagsList = appSettings.getFollowedTags();
this.followedTagsFavsList = new ArrayList<>(Arrays.asList(appSettings.getFollowedTagsFavs()));
this.tagClickedListener = tagClickedListener;
this.isAmoledColorMode = appSettings.isAmoledColorMode();
}
@Override
public int getItemCount() {
return followedTagsList.length;
}
@Override
public FollowedTagsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_list__list_item_with_fav, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// Alternating colors
final Context c = holder.root.getContext();
final String tag = followedTagsList[position];
holder.title.setText(tag);
if (position % 2 == 1) {
holder.root.setBackgroundColor(isAmoledColorMode ? Color.BLACK : ContextUtils.get().color(R.color.alternate_row_color));
holder.title.setTextColor(isAmoledColorMode ? Color.GRAY : Color.BLACK);
} else {
holder.root.setBackgroundColor(isAmoledColorMode ? Color.BLACK : Color.WHITE);
holder.title.setTextColor(isAmoledColorMode ? Color.GRAY : Color.BLACK);
}
// Favourite (Star) Image
applyFavouriteImage(holder.favouriteImage, isFollowedTagFaved(tag));
// Click on fav button
holder.favouriteImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isFollowedTagFaved(tag)) {
followedTagsFavsList.remove(followedTagsFavsList.indexOf(tag));
} else {
followedTagsFavsList.add(tag);
}
appSettings.setFollowedTagsFavs(followedTagsFavsList);
applyFavouriteImage(holder.favouriteImage, isFollowedTagFaved(tag));
}
});
holder.root.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tagClickedListener.onSomethingClicked(null, null, tag);
}
});
}
private boolean isFollowedTagFaved(String tag) {
return followedTagsFavsList.contains(tag);
}
private void applyFavouriteImage(AppCompatImageView imageView, boolean isFaved) {
imageView.setImageResource(isFaved ? R.drawable.ic_star_filled_48px : R.drawable.ic_star_border_black_48px);
imageView.setColorFilter(isFaved ? appSettings.getAccentColor() : (isAmoledColorMode ? Color.GRAY : 0), PorterDuff.Mode.SRC_ATOP);
}
}
}

View file

@ -13,7 +13,7 @@ import java.util.List;
/**
* Created by gsantner (https://gsantner.github.io/ on 30.09.16.
* Created by gsantner (gsantner AT mailbox DOT org on 30.09.16.
* DiasporaPodList - List container for DiasporaPod's, with methods to merge with other DiasporaPodLists
* DiasporaPod - Data container for a Pod, can include N DiasporaPodUrl's
* DiasporaPodUrl - A Url of an DiasporaPod
@ -315,8 +315,8 @@ public class DiasporaPodList implements Iterable<DiasporaPodList.DiasporaPod>, S
}
/*
* Getter & Setter
*/
* Getter & Setter
*/
public List<DiasporaPodUrl> getPodUrls() {
return _podUrls;
}

View file

@ -32,7 +32,7 @@ import org.json.JSONObject;
/**
* User profile
* Created by gsantner (https://gsantner.github.io/) on 24.03.16. Part of dandelion*.
* Created by gsantner (gsantner AT mailbox DOT org) on 24.03.16. Part of dandelion*.
*/
public class DiasporaUserProfile {
private static final int MINIMUM_USERPROFILE_LOAD_TIMEDIFF = 5000;

View file

@ -21,7 +21,7 @@ package com.github.dfa.diaspora_android.listener;
import com.github.dfa.diaspora_android.data.DiasporaUserProfile;
/**
* Created by gsantner (https://gsantner.github.io/) on 26.03.16.
* Created by gsantner (gsantner AT mailbox DOT org) on 26.03.16.
* Interface that needs to be implemented by classes that listen for Profile related changes
*/
public interface DiasporaUserProfileChangedListener {

View file

@ -10,7 +10,5 @@ import android.support.design.widget.AppBarLayout;
public interface IntellihideToolbarActivityListener {
int toolbarDefaultScrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP;
void enableToolbarHiding();
void disableToolbarHiding();
void setToolbarIntellihide(boolean enable);
}

View file

@ -24,6 +24,8 @@ import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import net.gsantner.opoc.util.DownloadTask;
import java.io.File;
public class AvatarImageLoader {
@ -52,7 +54,9 @@ public class AvatarImageLoader {
public void startImageDownload(ImageView imageView, String avatarUrl) {
if (!avatarUrl.equals("")) {
new ImageDownloadTask(imageView, avatarFile.getAbsolutePath()).execute(avatarUrl);
new DownloadTask(new File(avatarFile.getAbsolutePath()), (ok, file) -> {
loadToImageView(imageView);
}).execute(avatarUrl);
}
}
}

View file

@ -59,7 +59,7 @@ public class FetchPodsService extends Service {
}
class GetPodsTask extends AsyncTask<Void, Void, DiasporaPodList> {
private static final String PODDY_PODLIST_URL = "https://raw.githubusercontent.com/Diaspora-for-Android/dandelion/master/app/src/main/res/raw/podlist.json";
private static final String PODDY_PODLIST_URL = "https://raw.githubusercontent.com/gsantner/dandelion/master/app/src/main/res/raw/podlist.json";
private final Service service;

View file

@ -1,98 +0,0 @@
/*
This file is part of the dandelion*.
dandelion* is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
dandelion* is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the dandelion*.
If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.dfa.diaspora_android.service;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.widget.ImageView;
import com.github.dfa.diaspora_android.util.AppLog;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.net.ssl.HttpsURLConnection;
import info.guardianproject.netcipher.NetCipher;
/**
* Task that can be used to download images from URLs and store them in storage
* Created by gsantner (https://gsantner.github.io/) on 24.03.16.
*/
public class ImageDownloadTask extends AsyncTask<String, Void, Bitmap> {
private final ImageView imageView;
private String savePath;
/**
* Download image from URL
*
* @param imageView ImageView to set image to (null = don't set)
* @param savePath Save image to file (null = don't save)
*/
public ImageDownloadTask(@Nullable ImageView imageView, @Nullable String savePath) {
this.imageView = imageView;
this.savePath = savePath;
}
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
Bitmap bitmap = null;
FileOutputStream out = null;
InputStream inStream;
HttpsURLConnection connection;
try {
connection = NetCipher.getHttpsURLConnection(url);
inStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inStream);
// Save to file if not null
if (savePath != null) {
out = new FileOutputStream(savePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
}
try {
inStream.close();
} catch (IOException e) {/*Nothing*/}
connection.disconnect();
} catch (Exception e) {
AppLog.e(this, e.getMessage());
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ignored) {
}
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
// Display on imageview if not null
if (imageView != null) {
imageView.setImageBitmap(result);
}
}
}

View file

@ -71,7 +71,7 @@ public class BadgeDrawable extends Drawable {
Rect bounds = getBounds();
float width = bounds.right - bounds.left;
float height = bounds.bottom - bounds.top;
float oneDp = ContextUtils.get().dp2px(1);
float oneDp = ContextUtils.get().convertDpToPx(1);
// Position the badge in the top-right quadrant of the icon.
float radius = ((Math.max(width, height) / 2)) / 2;

View file

@ -18,14 +18,13 @@
*/
package com.github.dfa.diaspora_android.ui;
import android.annotation.TargetApi;
import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.text.Html;
import android.text.SpannableString;
import android.text.util.Linkify;
import android.util.AttributeSet;
import android.util.Patterns;
import android.widget.TextView;
import com.github.dfa.diaspora_android.activity.MainActivity;
@ -38,7 +37,7 @@ import java.util.regex.Pattern;
* Hashtags open the MainActivity, load the new-post site of the selected pod and insert the
* hashtag into the post editor. See data/HashtagContentProvider.
*/
public class HtmlTextView extends TextView {
public class HtmlTextView extends AppCompatTextView {
public HtmlTextView(Context context) {
super(context);
@ -55,12 +54,6 @@ public class HtmlTextView extends TextView {
init();
}
@TargetApi(21)
public HtmlTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
/**
* Linkify, format markdown and escape the displayed message.
*/

View file

@ -37,7 +37,7 @@ import butterknife.OnItemSelected;
/**
* Dialog that helps the user configure a pod
* Created by gsantner (https://gsantner.github.io) on 06.10.16.
* Created by gsantner on 06.10.16.
*/
public class PodSelectionDialog extends ThemedAppCompatDialogFragment {
public static final String TAG = "com.github.dfa.diaspora_android.ui.PodSelectionDialog";

View file

@ -0,0 +1,85 @@
package com.github.dfa.diaspora_android.ui;
import android.app.Activity;
import android.support.v4.content.ContextCompat;
import com.github.dfa.diaspora_android.R;
import com.github.dfa.diaspora_android.data.DiasporaAspect;
import com.github.dfa.diaspora_android.util.AppSettings;
import net.gsantner.opoc.ui.SearchOrCustomTextDialog;
import net.gsantner.opoc.util.Callback;
import java.util.ArrayList;
import java.util.Arrays;
public class SearchOrCustomTextDialogCreator {
public static final String SPECIAL_PREFIX = "\uD83D\uDCA0";
public static void showDiasporaTagsDialog(final Activity activity, final Callback.a1<String> callback) {
SearchOrCustomTextDialog.DialogOptions dopt = new SearchOrCustomTextDialog.DialogOptions();
baseConf(activity, dopt);
dopt.callback = callback;
dopt.isSearchEnabled = true;
dopt.searchHintText = R.string.search;
dopt.titleText = R.string.tags;
new Thread(() -> {
AppSettings appSettings = AppSettings.get();
ArrayList<String> hl = new ArrayList<>();
ArrayList<String> data = new ArrayList<>(Arrays.asList(appSettings.getFollowedTags()));
if (data.size() > 0) {
String highlighted = surroundString(data.remove(0));
data.add(0, highlighted);
hl.add(highlighted);
}
for (int strid : new int[]{R.string.manage_hashtags}) {
String special = surroundString(appSettings.rstr(strid));
data.add(0, special);
hl.add(special);
}
dopt.data = data;
dopt.highlightData = hl;
activity.runOnUiThread(() -> SearchOrCustomTextDialog.showMultiChoiceDialogWithSearchFilterUI(activity, dopt));
}).start();
}
private static String surroundString(String text) {
return SPECIAL_PREFIX + " " + text + " ";
}
public static void showDiasporaAspectsDialog(final Activity activity, final Callback.a1<String> callback) {
SearchOrCustomTextDialog.DialogOptions dopt = new SearchOrCustomTextDialog.DialogOptions();
baseConf(activity, dopt);
dopt.callback = callback;
dopt.isSearchEnabled = false;
dopt.titleText = R.string.contacts;
new Thread(() -> {
AppSettings appSettings = AppSettings.get();
ArrayList<String> hl = new ArrayList<>();
ArrayList<String> data = new ArrayList<>();
for (DiasporaAspect aspect : AppSettings.get().getAspects()) {
data.add(aspect.name);
}
for (int strid : new int[]{R.string.nav_profile, R.string.manage_your_contact_list}) {
String special = surroundString(appSettings.rstr(strid));
data.add(0, special);
hl.add(special);
}
dopt.data = data;
dopt.highlightData = hl;
activity.runOnUiThread(() -> SearchOrCustomTextDialog.showMultiChoiceDialogWithSearchFilterUI(activity, dopt));
}).start();
}
private static void baseConf(Activity activity, SearchOrCustomTextDialog.DialogOptions dopt) {
AppSettings as = new AppSettings(activity);
dopt.isDarkDialog = as.isAmoledColorMode();
dopt.textColor = ContextCompat.getColor(activity, dopt.isDarkDialog ? R.color.white : R.color.primary_text);
dopt.highlightColor = as.getAccentColor();
}
}

View file

@ -1,73 +0,0 @@
/*
This file is part of the dandelion*.
dandelion* is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
dandelion* is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the dandelion*.
If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.dfa.diaspora_android.ui.theme;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Menu;
import android.view.MenuInflater;
/**
* Customized abstract Fragment class with some useful methods
* Created by vanitas on 21.09.16.
*/
public abstract class CustomFragment extends Fragment {
public static final String TAG = "com.github.dfa.diaspora_android.ui.theme.CustomFragment";
/**
* We have an optionsMenu
*
* @param savedInstanceState state
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
/**
* Return the tag used to identify the Fragment.
*
* @return tag
*/
public abstract String getFragmentTag();
/**
* Add fragment-dependent options to the bottom options _toolbar
*
* @param menu bottom menu
* @param inflater inflater
*/
public abstract void onCreateBottomOptionsMenu(Menu menu, MenuInflater inflater);
/**
* Return true if the fragment reacted to a back button press, false else.
* In case the fragment returned false, the parent activity should handle the backPress.
*
* @return did we react to the back press?
*/
public abstract boolean onBackPressed();
public boolean isAllowedIntellihide() {
return true;
}
}

View file

@ -19,10 +19,7 @@
package com.github.dfa.diaspora_android.ui.theme;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
@ -31,8 +28,6 @@ import com.github.dfa.diaspora_android.R;
import com.github.dfa.diaspora_android.util.AppSettings;
import com.github.dfa.diaspora_android.util.ContextUtils;
import java.util.Locale;
/**
* Activity that supports color schemes
* Created by vanitas on 06.10.16.
@ -72,15 +67,7 @@ public abstract class ThemedActivity extends AppCompatActivity {
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void updateRecentAppColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
BitmapDrawable drawable = ((BitmapDrawable) getDrawable(R.drawable.ic_launcher));
if (drawable != null) {
setTaskDescription(new ActivityManager.TaskDescription(
getResources().getString(R.string.app_name),
drawable.getBitmap(),
getAppSettings().getPrimaryColor()));
}
}
}
protected void updateScreenRotation() {

View file

@ -41,7 +41,7 @@ public class ThemedCheckBoxPreference extends CheckBoxPreference implements Them
@Override
public void setColors() {
CheckBox checkBox = (CheckBox) rootLayout.findViewById(android.R.id.checkbox);
CheckBox checkBox = rootLayout.findViewById(android.R.id.checkbox);
ThemeHelper.getInstance(AppSettings.get());
ThemeHelper.updateCheckBoxColor(checkBox);
}

View file

@ -38,7 +38,7 @@ public class ThemedColorPickerPreference extends Preference implements Themeable
@Override
protected void onBindView(View view) {
super.onBindView(view);
colorPreview = (ImageView) view.findViewById(android.R.id.icon);
colorPreview = view.findViewById(android.R.id.icon);
setColors();
}
@ -50,7 +50,7 @@ public class ThemedColorPickerPreference extends Preference implements Themeable
AppSettings appSettings = AppSettings.get();
String key = getKey();
int color = ContextUtils.get().color(R.color.primary);
int color = ContextUtils.get().rcolor(R.color.primary);
if ((appSettings.isKeyEqual(key, R.string.pref_key__primary_color_shade))) {
color = appSettings.getPrimaryColor();
} else if ((appSettings.isKeyEqual(key, R.string.pref_key__accent_color_shade))) {

View file

@ -21,12 +21,14 @@ package com.github.dfa.diaspora_android.ui.theme;
import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.util.AppSettings;
import net.gsantner.opoc.activity.GsFragmentBase;
/**
* Fragment that supports color schemes
* Created by vanitas on 06.10.16.
*/
public abstract class ThemedFragment extends CustomFragment {
public abstract class ThemedFragment extends GsFragmentBase {
protected AppSettings getAppSettings() {
return ((App) getActivity().getApplication()).getSettings();
}
@ -39,4 +41,9 @@ public abstract class ThemedFragment extends CustomFragment {
ThemeHelper.getInstance(getAppSettings());
applyColorToViews();
}
public boolean isAllowedIntellihide() {
return true;
}
}

View file

@ -36,7 +36,7 @@ public class ThemedPreferenceCategory extends PreferenceCategory implements Them
@Override
protected View onCreateView(ViewGroup parent) {
View rootLayout = super.onCreateView(parent);
this.titleTextView = (TextView) rootLayout.findViewById(android.R.id.title);
this.titleTextView = rootLayout.findViewById(android.R.id.title);
setColors();
return rootLayout;
}

View file

@ -27,7 +27,7 @@ public class ThemedVisibilityPreference extends ThemedCheckBoxPreference {
@Override
public void setColors() {
CheckBox checkBox = (CheckBox) rootLayout.findViewById(android.R.id.checkbox);
CheckBox checkBox = rootLayout.findViewById(android.R.id.checkbox);
checkBox.setButtonDrawable(R.drawable.ic_visibility_selector);
ThemeHelper.getInstance(AppSettings.get());
ThemeHelper.updateCheckBoxColor(checkBox);

View file

@ -1,10 +1,14 @@
package com.github.dfa.diaspora_android.util;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.view.View;
import com.github.dfa.diaspora_android.BuildConfig;
import com.github.dfa.diaspora_android.R;
import com.github.dfa.diaspora_android.web.WebHelper;
@ -17,7 +21,7 @@ import java.util.Locale;
@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue"})
public class ActivityUtils extends net.gsantner.opoc.util.ActivityUtils {
protected ActivityUtils(Activity activity) {
public ActivityUtils(Activity activity) {
super(activity);
}
@ -48,7 +52,7 @@ public class ActivityUtils extends net.gsantner.opoc.util.ActivityUtils {
public boolean showInfoIfUserNotConnectedToInternet(View anchor) {
boolean isOnline = WebHelper.isOnline(_context);
if (!isOnline) {
showSnackBar(R.string.no_internet, true);
showSnackBar(R.string.sorry_need_to_be_connected_to_internet, true);
}
return !isOnline;
}
@ -70,4 +74,13 @@ public class ActivityUtils extends net.gsantner.opoc.util.ActivityUtils {
}
}
}
/**
* This method creates file sharing uri by using FileProvider
*
* @return
*/
public static Uri getFileSharingUri(Context context, File file) {
return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, file);
}
}

View file

@ -22,7 +22,7 @@ public class AndroidBug5497Workaround {
private FrameLayout.LayoutParams frameLayoutParams;
private AndroidBug5497Workaround(Activity activity) {
FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
FrameLayout content = activity.findViewById(android.R.id.content);
mChildOfContent = content.getChildAt(0);
mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {

View file

@ -18,6 +18,7 @@ import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Environment;
import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.BuildConfig;
@ -26,19 +27,20 @@ import com.github.dfa.diaspora_android.data.DiasporaAspect;
import com.github.dfa.diaspora_android.data.DiasporaPodList.DiasporaPod;
import com.github.dfa.diaspora_android.web.ProxyHandler;
import net.gsantner.opoc.util.AppSettingsBase;
import net.gsantner.opoc.preference.SharedPreferencesPropertyBackend;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.List;
/**
* Settings
* Created by gsantner (https://gsantner.github.io/) on 20.03.16. Part of dandelion*.
* Created by gsantner (gsantner AT mailbox DOT org) on 20.03.16. Part of dandelion*.
*/
@SuppressWarnings("ConstantConditions")
public class AppSettings extends AppSettingsBase {
public class AppSettings extends SharedPreferencesPropertyBackend {
private final SharedPreferences _prefPod;
private DiasporaPod currentPod0Cached;
@ -46,7 +48,7 @@ public class AppSettings extends AppSettingsBase {
return new AppSettings(App.get());
}
private AppSettings(Context context) {
public AppSettings(Context context) {
super(context);
_prefPod = _context.getSharedPreferences("pod0", Context.MODE_PRIVATE);
}
@ -145,7 +147,11 @@ public class AppSettings extends AppSettingsBase {
}
public void setPodAspects(DiasporaAspect[] aspects) {
setStringArray(R.string.pref_key__podprofile_aspects, aspects, _prefPod);
String[] strs = new String[aspects.length];
for (int i = 0; i < strs.length; i++) {
strs[i] = aspects[i].toShareAbleText();
}
setStringArray(R.string.pref_key__podprofile_aspects, strs, _prefPod);
}
public DiasporaAspect[] getAspects() {
@ -341,8 +347,8 @@ public class AppSettings extends AppSettingsBase {
return getBool(R.string.pref_key__visibility_nav__reports, false);
}
public boolean isVisibleInNavDandelionAccount() {
return getBool(R.string.pref_key__visibility_nav__dandelion_account, false);
public boolean isVisibleInNavGsantnerAccount() {
return getBool(R.string.pref_key__visibility_nav__gsantner_account, false);
}
public boolean isVisibleInNavToggleMobileDesktop() {
@ -353,6 +359,14 @@ public class AppSettings extends AppSettingsBase {
return getBool(R.string.pref_key__topbar_stream_shortcut, false);
}
public boolean isOpenYoutubeExternalEnabled() {
return getBool(R.string.pref_key__open_youtube_external_enabled, true);
}
public boolean isSwipeRefreshEnabled() {
return getBool(R.string.pref_key__swipe_refresh_enabled, true);
}
public String getScreenRotation() {
return getString(R.string.pref_key__screen_rotation, R.string.rotation_val_system);
}
@ -363,12 +377,19 @@ public class AppSettings extends AppSettingsBase {
return value;
}
public boolean isAppCurrentVersionFirstStart() {
public boolean isAppCurrentVersionFirstStart(boolean doSet) {
int value = getInt(R.string.pref_key__app_first_start_current_version, -1);
setInt(R.string.pref_key__app_first_start_current_version, BuildConfig.VERSION_CODE);
if (doSet) {
setInt(R.string.pref_key__app_first_start_current_version, BuildConfig.VERSION_CODE);
}
return value != BuildConfig.VERSION_CODE && !BuildConfig.IS_TEST_BUILD;
}
public File getAppSaveDirectory() {
return new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/dandelion");
}
public long getLastVisitedPositionInStream() {
return getLong(R.string.pref_key__podprofile_last_stream_position, -1, _prefPod);
}
@ -431,6 +452,10 @@ public class AppSettings extends AppSettingsBase {
return getBool(R.string.pref_key__primary_color__amoled_mode, false);
}
public void setAmoledColorMode(boolean enable) {
setBool(R.string.pref_key__primary_color__amoled_mode, enable);
}
public boolean isAdBlockEnabled() {
return getBool(R.string.pref_key__adblock_enable, true);
}
@ -448,4 +473,8 @@ public class AppSettings extends AppSettingsBase {
setRecreateMainActivity(false);
return value;
}
public boolean isShowTitleInMainView() {
return getBool(R.string.pref_key__show_title, false);
}
}

View file

@ -62,6 +62,7 @@ public class DiasporaUrlHelper {
public static final String SUBURL_NOTIFICATIONS_MENTIONED = "/notifications?type=mentioned";
public static final String SUBURL_NOTIFICATIONS_RESHARED = "/notifications?type=reshared";
public static final String SUBURL_NOTIFICATIONS_STARTED_SHARING = "/notifications?type=started_sharing";
public static final String SUBURL_THEME = "/user/edit";
public DiasporaUrlHelper(AppSettings settings) {
this.settings = settings;
@ -229,6 +230,15 @@ public class DiasporaUrlHelper {
return getPodUrl() + SUBURL_SEARCH_TAGS + query;
}
/**
* Return a url that queries posts for the given hashtag query
*
* @return https://(pod-domain.tld)/followed_tags
*/
public String getAllFollowedTagsUrl() {
return getPodUrl() + SUBURL_FOLOWED_TAGS;
}
/**
* Return a url that queries user accounts for query
*
@ -344,4 +354,13 @@ public class DiasporaUrlHelper {
}
return app.getString(R.string.aspects);
}
/**
* Return a url that points to the settings of the pod.
*
* @return https://(pod-domain.tld)/user/edit
*/
public String getThemeUrl() {
return getPodUrl() + SUBURL_THEME;
}
}

View file

@ -18,21 +18,10 @@
*/
package com.github.dfa.diaspora_android.web;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.MutableContextWrapper;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
@ -41,21 +30,11 @@ import android.widget.ProgressBar;
import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.R;
import com.github.dfa.diaspora_android.activity.MainActivity;
import com.github.dfa.diaspora_android.ui.theme.ThemeHelper;
import com.github.dfa.diaspora_android.ui.theme.ThemedFragment;
import com.github.dfa.diaspora_android.util.AppLog;
import com.github.dfa.diaspora_android.util.AppSettings;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Fragment with a webView and a ProgressBar.
* This Fragment retains its instance.
@ -65,7 +44,6 @@ import java.util.Locale;
public class BrowserFragment extends ThemedFragment {
public static final String TAG = "com.github.dfa.diaspora_android.BrowserFragment";
protected View rootLayout;
protected ContextMenuWebView webView;
protected ProgressBar progressBar;
protected AppSettings appSettings;
@ -73,20 +51,14 @@ public class BrowserFragment extends ThemedFragment {
protected WebSettings webSettings;
protected String pendingUrl;
protected SwipeRefreshLayout swipe;//pull to refresh
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
AppLog.d(this, "onCreateView()");
if (rootLayout == null) {
LayoutInflater inflater1 = inflater.cloneInContext(new MutableContextWrapper(getContext()));
rootLayout = inflater1.inflate(R.layout.browser__fragment, container, false);
} else {
MutableContextWrapper context = (MutableContextWrapper) rootLayout.getContext();
context.setBaseContext(getContext());
}
return rootLayout;
protected int getLayoutResId() {
return R.layout.browser__fragment;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
AppLog.d(this, "onViewCreated()");
@ -97,7 +69,7 @@ public class BrowserFragment extends ThemedFragment {
}
if (this.webView == null) {
this.webView = (ContextMenuWebView) view.findViewById(R.id.webView);
this.webView = view.findViewById(R.id.webView);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
@ -109,7 +81,7 @@ public class BrowserFragment extends ThemedFragment {
}
if (this.progressBar == null) {
this.progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
this.progressBar = view.findViewById(R.id.progressBar);
}
if (pendingUrl != null) {
@ -120,14 +92,26 @@ public class BrowserFragment extends ThemedFragment {
webView.setParentActivity(getActivity());
this.setRetainInstance(true);
//pull to refresh
swipe = view.findViewById(R.id.swipe);
swipe.setDistanceToTriggerSync(2000);
swipe.setOnRefreshListener(() -> reloadUrl());
if (appSettings.isSwipeRefreshEnabled()) {
swipe.setEnabled(true);
} else {
swipe.setRefreshing(false);
swipe.setEnabled(false);
return;
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (getRetainInstance() && rootLayout.getParent() instanceof ViewGroup) {
((ViewGroup) rootLayout.getParent()).removeView(rootLayout);
if (getRetainInstance() && getView() != null && getView().getParent() instanceof ViewGroup) {
((ViewGroup) getView().getParent()).removeView(getView());
}
}
@ -165,98 +149,11 @@ public class BrowserFragment extends ThemedFragment {
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
protected boolean makeScreenshotOfWebView(boolean hasToShareScreenshot) {
AppLog.i(this, "StreamFragment.makeScreenshotOfWebView()");
if (android.os.Build.VERSION.SDK_INT >= 23) {
int hasWRITE_EXTERNAL_STORAGE = getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(getContext())
.setMessage(R.string.permissions_screenshot)
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (android.os.Build.VERSION.SDK_INT >= 23)
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MainActivity.REQUEST_CODE_ASK_PERMISSIONS);
}
})
.show();
return false;
}
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MainActivity.REQUEST_CODE_ASK_PERMISSIONS);
return false;
}
}
Date dateNow = new Date();
DateFormat dateFormat = new SimpleDateFormat("yy_MM_dd--HH_mm_ss", Locale.getDefault());
File fileSaveDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Diaspora");
String fileSaveName = hasToShareScreenshot ? ".DfA_share.jpg" : String.format("DfA_%s.jpg", dateFormat.format(dateNow));
if (!fileSaveDirectory.exists()) {
if (!fileSaveDirectory.mkdirs()) {
AppLog.w(this, "Could not mkdir " + fileSaveDirectory.getAbsolutePath());
}
}
if (!hasToShareScreenshot) {
Snackbar.make(webView, getString(R.string.share__toast_screenshot) + " " + fileSaveName, Snackbar.LENGTH_LONG).show();
}
Bitmap bitmap;
webView.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(webView.getDrawingCache());
webView.setDrawingCacheEnabled(false);
OutputStream bitmapWriter = null;
try {
bitmapWriter = new FileOutputStream(new File(fileSaveDirectory, fileSaveName));
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bitmapWriter);
bitmapWriter.flush();
bitmap.recycle();
} catch (Exception e) {
return false;
} finally {
if (bitmapWriter != null) {
try {
bitmapWriter.close();
} catch (IOException _ignSaveored) {/* Nothing */}
}
}
// Only show share intent when Action Share Screenshot was selected
if (hasToShareScreenshot) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/jpeg");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, webView.getTitle());
sharingIntent.putExtra(Intent.EXTRA_TEXT, webView.getUrl());
Uri bmpUri = Uri.fromFile(new File(fileSaveDirectory, fileSaveName));
sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
startActivity(Intent.createChooser(sharingIntent, getString(R.string.action_share_dotdotdot)));
} else {
// Broadcast that this file is indexable
File file = new File(fileSaveDirectory, fileSaveName);
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
getActivity().sendBroadcast(intent);
}
return true;
}
@Override
public String getFragmentTag() {
return TAG;
}
@Override
public void onCreateBottomOptionsMenu(Menu menu, MenuInflater inflater) {
/* Nothing to do here */
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
@ -309,6 +206,7 @@ public class BrowserFragment extends ThemedFragment {
@Override
public void run() {
getWebView().reload();
swipe.setRefreshing(false);//pull to refresh
}
});

View file

@ -18,29 +18,27 @@
*/
package com.github.dfa.diaspora_android.web;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.widget.Toast;
import com.github.dfa.diaspora_android.BuildConfig;
import com.github.dfa.diaspora_android.R;
import com.github.dfa.diaspora_android.activity.MainActivity;
import com.github.dfa.diaspora_android.service.ImageDownloadTask;
import com.github.dfa.diaspora_android.util.AppSettings;
import net.gsantner.opoc.util.DownloadTask;
import net.gsantner.opoc.util.PermissionChecker;
import net.gsantner.opoc.util.ShareUtil;
import java.io.File;
import java.util.Date;
/**
* Subclass of WebView which adds a context menu for long clicks on images or links to share, save
@ -80,106 +78,46 @@ public class ContextMenuWebView extends NestedWebView {
public boolean onMenuItemClick(MenuItem item) {
HitTestResult result = getHitTestResult();
String url = result.getExtra();
final ShareUtil shu = new ShareUtil(context);
final PermissionChecker permc = new PermissionChecker(parentActivity);
final AppSettings appSettings = new AppSettings(context);
switch (item.getItemId()) {
//Save image to external memory
case ID_SAVE_IMAGE: {
boolean writeToStoragePermitted = true;
if (android.os.Build.VERSION.SDK_INT >= 23) {
int hasWRITE_EXTERNAL_STORAGE = parentActivity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
writeToStoragePermitted = false;
if (!parentActivity.shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(parentActivity)
.setMessage(R.string.permissions_image)
.setPositiveButton(context.getText(android.R.string.yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (android.os.Build.VERSION.SDK_INT >= 23)
parentActivity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
}
})
.setNegativeButton(context.getText(android.R.string.no), null)
.show();
}
parentActivity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
}
}
if (writeToStoragePermitted) {
//Make sure, Diaspora Folder exists
File destinationFolder = new File(Environment.getExternalStorageDirectory() + "/Pictures/Diaspora");
if (!destinationFolder.exists()) {
destinationFolder.mkdirs();
}
if (url != null) {
Uri source = Uri.parse(url);
if (permc.doIfExtStoragePermissionGranted(context.getString(R.string.image_permission_description__appspecific))) {
File fileSaveDirectory = appSettings.getAppSaveDirectory();
if (permc.mkdirIfStoragePermissionGranted(fileSaveDirectory)) {
String filename = "dandelion-" + ShareUtil.SDF_SHORT.format(new Date()) + url.substring(url.lastIndexOf("."));
/*Uri source = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(source);
File destinationFile = new File(Environment.getExternalStorageDirectory() + "/Pictures/Diaspora/" + System.currentTimeMillis() + ".png");
request.setDestinationUri(Uri.fromFile(destinationFile));
((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE)).enqueue(request);
Toast.makeText(context, context.getText(R.string.share__toast_saved_image_to_location) + " " +
destinationFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
request.setDestinationUri(Uri.fromFile(new File(fileSaveDirectory, filename)));
((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE)).enqueue(request);*/
new DownloadTask(new File(fileSaveDirectory, filename), (ok, dlfile) -> {
if (ok) {
Toast.makeText(context, context.getText(R.string.saving_image_to) + " " + dlfile.getName(), Toast.LENGTH_LONG).show();
}
}).execute(url);
}
}
}
break;
case ID_SHARE_IMAGE:
if (url != null) {
boolean writeToStoragePermitted = true;
if (android.os.Build.VERSION.SDK_INT >= 23) {
int hasWRITE_EXTERNAL_STORAGE = parentActivity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
writeToStoragePermitted = false;
if (!parentActivity.shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(parentActivity)
.setMessage(R.string.permissions_image)
.setPositiveButton(context.getText(android.R.string.yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (android.os.Build.VERSION.SDK_INT >= 23)
parentActivity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
}
})
.setNegativeButton(context.getText(android.R.string.no), null)
.show();
} else {
parentActivity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
}
}
}
if (writeToStoragePermitted) {
//Make sure, Diaspora Folder exists
File destinationFolder = new File(Environment.getExternalStorageDirectory() + "/Pictures/Diaspora");
if (!destinationFolder.exists()) {
destinationFolder.mkdirs();
}
final Uri local = Uri.parse(Environment.getExternalStorageDirectory() + "/Pictures/Diaspora/" + System.currentTimeMillis() + ".png");
new ImageDownloadTask(null, local.getPath()) {
@Override
protected void onPostExecute(Bitmap result) {
Uri myUri = Uri.fromFile(new File(local.getPath()));
Intent sharingIntent = new Intent();
sharingIntent.setAction(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_STREAM, myUri);
sharingIntent.setType("image/png");
sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.action_share_dotdotdot)));
}
}.execute(url);
}
} else {
Toast.makeText(context, "Cannot share image: url is null", Toast.LENGTH_SHORT).show();
}
break;
}
case ID_SHARE_IMAGE: {
if (permc.doIfExtStoragePermissionGranted(context.getString(R.string.image_permission_description__appspecific))) {
File fileSaveDirectory = appSettings.getAppSaveDirectory();
if (permc.mkdirIfStoragePermissionGranted(fileSaveDirectory)) {
String filename = ".dandelion-shared" + url.substring(url.lastIndexOf("."));
new DownloadTask(new File(fileSaveDirectory, filename), (ok, dlfile) -> {
if (ok) {
Toast.makeText(context, context.getText(R.string.saving_image_to) + " " + dlfile.getName(), Toast.LENGTH_LONG).show();
shu.shareStream(dlfile, "image/" + dlfile.getAbsolutePath().lastIndexOf(".") + 1);
}
}).execute(url);
}
}
break;
}
case ID_IMAGE_EXTERNAL_BROWSER:
if (url != null) {
@ -194,7 +132,7 @@ public class ContextMenuWebView extends NestedWebView {
if (url != null) {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
Toast.makeText(context, R.string.share__toast_link_address_copied, Toast.LENGTH_SHORT).show();
Toast.makeText(context, R.string.link_adress_copied, Toast.LENGTH_SHORT).show();
}
break;
@ -206,7 +144,7 @@ public class ContextMenuWebView extends NestedWebView {
sendIntent.putExtra(Intent.EXTRA_TEXT, url);
sendIntent.setType("text/plain");
context.startActivity(Intent.createChooser(sendIntent, getResources()
.getText(R.string.context_menu_share_link)));
.getText(R.string.share_link_address)));
}
break;
}
@ -219,16 +157,16 @@ public class ContextMenuWebView extends NestedWebView {
result.getType() == HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
// Menu options for an image.
menu.setHeaderTitle(result.getExtra());
menu.add(0, ID_SAVE_IMAGE, 0, context.getString(R.string.context_menu_save_image)).setOnMenuItemClickListener(handler);
menu.add(0, ID_IMAGE_EXTERNAL_BROWSER, 0, context.getString(R.string.context_menu_open_external_browser)).setOnMenuItemClickListener(handler);
menu.add(0, ID_SHARE_IMAGE, 0, context.getString(R.string.context_menu_share_image)).setOnMenuItemClickListener(handler);
menu.add(0, ID_COPY_IMAGE_LINK, 0, context.getString(R.string.context_menu_copy_image_link)).setOnMenuItemClickListener(handler);
menu.add(0, ID_SAVE_IMAGE, 0, context.getString(R.string.save_image)).setOnMenuItemClickListener(handler);
menu.add(0, ID_IMAGE_EXTERNAL_BROWSER, 0, context.getString(R.string.open_in_external_browser)).setOnMenuItemClickListener(handler);
menu.add(0, ID_SHARE_IMAGE, 0, context.getString(R.string.share_image)).setOnMenuItemClickListener(handler);
menu.add(0, ID_COPY_IMAGE_LINK, 0, context.getString(R.string.copy_image_address_to_clipboard)).setOnMenuItemClickListener(handler);
} else if (result.getType() == HitTestResult.ANCHOR_TYPE ||
result.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
// Menu options for a hyperlink.
menu.setHeaderTitle(result.getExtra());
menu.add(0, ID_COPY_LINK, 0, context.getString(R.string.context_menu_copy_link)).setOnMenuItemClickListener(handler);
menu.add(0, ID_SHARE_LINK, 0, context.getString(R.string.context_menu_share_link)).setOnMenuItemClickListener(handler);
menu.add(0, ID_COPY_LINK, 0, context.getString(R.string.copy_link_adress_to_clipboard)).setOnMenuItemClickListener(handler);
menu.add(0, ID_SHARE_LINK, 0, context.getString(R.string.share_link_address)).setOnMenuItemClickListener(handler);
}
}

View file

@ -20,6 +20,7 @@ package com.github.dfa.diaspora_android.web;
import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.LocalBroadcastManager;
import android.webkit.CookieManager;
@ -38,6 +39,7 @@ public class CustomWebViewClient extends WebViewClient {
private final App app;
private String lastLoadUrl = "";
private boolean isAdBlockEnabled = false;
AppSettings appSettings = AppSettings.get();
public CustomWebViewClient(App app, WebView webView) {
this.app = app;
@ -56,6 +58,11 @@ public class CustomWebViewClient extends WebViewClient {
|| (host != null && (url.startsWith("https://" + host)
|| url.startsWith("http://" + host)))) {
return false;
}//make youtube links open external-->never customtab
else if (appSettings.isOpenYoutubeExternalEnabled() && (url.startsWith("https://youtube.com/") || url.startsWith("https://www.youtube.com/") || url.startsWith("https://m.youtube.com/") || url.startsWith("https://youtu.be/"))) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
} else {
Intent i = new Intent(MainActivity.ACTION_OPEN_EXTERNAL_URL);
i.putExtra(MainActivity.EXTRA_URL, url);

View file

@ -18,7 +18,6 @@
*/
package com.github.dfa.diaspora_android.web;
import android.content.DialogInterface;
import android.webkit.JsResult;
import android.webkit.WebView;
import android.widget.ProgressBar;
@ -65,20 +64,13 @@ public class DiasporaStreamWebChromeClient extends FileUploadWebChromeClient {
ThemedAlertDialogBuilder builder = new ThemedAlertDialogBuilder(view.getContext(), AppSettings.get());
builder.setTitle(view.getContext().getString(R.string.confirmation))
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
})
.create()
.show();
.setPositiveButton(android.R.string.ok, (dialog, which) -> result.confirm())
.setNegativeButton(android.R.string.cancel, (dialog, which) -> result.cancel())
.setOnCancelListener(dialog -> {
result.cancel();
dialog.dismiss();
})
.create().show();
return true;
}

View file

@ -32,7 +32,6 @@ import com.github.dfa.diaspora_android.activity.MainActivity;
/**
* Created by Gregor Santner on 07.08.16.
* https://gsantner.github.io
*/
public class WebHelper {

View file

@ -41,6 +41,9 @@ public class CustomTabsHelper {
static final String BETA_PACKAGE = "com.chrome.beta";
static final String DEV_PACKAGE = "com.chrome.dev";
static final String LOCAL_PACKAGE = "com.google.android.apps.chrome";
static final String CHROMIUM = "org.chromium.chrome";
static final String FENNEC = "org.mozilla.fennec_fdroid";
static final String KLAR = "org.mozilla.klar";
private static final String EXTRA_CUSTOM_TABS_KEEP_ALIVE =
"android.support.customtabs.extra.KEEP_ALIVE";
@ -101,6 +104,12 @@ public class CustomTabsHelper {
sPackageNameToUse = DEV_PACKAGE;
} else if (packagesSupportingCustomTabs.contains(LOCAL_PACKAGE)) {
sPackageNameToUse = LOCAL_PACKAGE;
} else if (packagesSupportingCustomTabs.contains(CHROMIUM)) {
sPackageNameToUse = CHROMIUM;
} else if (packagesSupportingCustomTabs.contains(FENNEC)) {
sPackageNameToUse = FENNEC;
} else if (packagesSupportingCustomTabs.contains(KLAR)) {
sPackageNameToUse = KLAR;
}
return sPackageNameToUse;
}
@ -137,6 +146,6 @@ public class CustomTabsHelper {
* @return All possible chrome package names that provide custom tabs feature.
*/
public static String[] getPackages() {
return new String[]{"", STABLE_PACKAGE, BETA_PACKAGE, DEV_PACKAGE, LOCAL_PACKAGE};
return new String[]{"", STABLE_PACKAGE, BETA_PACKAGE, DEV_PACKAGE, LOCAL_PACKAGE, CHROMIUM, FENNEC, KLAR};
}
}

View file

@ -0,0 +1,160 @@
/*#######################################################
*
* Maintained 2017-2023 by Gregor Santner <gsantner AT mailbox DOT org>
*
* License: Apache 2.0
* https://github.com/gsantner/opoc/#licensing
* https://www.apache.org/licenses/LICENSE-2.0
*
#########################################################*/
package net.gsantner.opoc.activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import net.gsantner.opoc.android.dummy.MenuItemDummy;
import net.gsantner.opoc.util.ContextUtils;
import butterknife.ButterKnife;
/**
* A common base fragment to extend from
*/
public abstract class GsFragmentBase extends Fragment {
private boolean _fragmentFirstTimeVisible = true;
private final Object _fragmentFirstTimeVisibleSync = new Object();
protected ContextUtils _cu;
protected Bundle _savedInstanceState = null;
protected Menu _fragmentMenu = new MenuItemDummy.Menu();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
/**
* Inflate the fragments layout. Don't override this method, just supply the needed
* {@link LayoutRes} via abstract method {@link #getLayoutResId()}, super does the rest
*/
@Deprecated
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
_cu = new ContextUtils(inflater.getContext());
_cu.setAppLanguage(getAppLanguage());
_savedInstanceState = savedInstanceState;
if (getLayoutResId() == 0) {
Log.e(getClass().getCanonicalName(), "Error: GsFragmentbase.onCreateview: Returned 0 for getLayoutResId");
}
View view = inflater.inflate(getLayoutResId(), container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.postDelayed(() -> {
synchronized (_fragmentFirstTimeVisibleSync) {
if (getUserVisibleHint() && isVisible() && _fragmentFirstTimeVisible) {
_fragmentFirstTimeVisible = false;
onFragmentFirstTimeVisible();
}
}
}, 1);
}
/**
* Get a tag from the fragment, allows faster distinction
*
* @return This fragments tag
*/
public abstract String getFragmentTag();
/**
* Get the layout to be inflated in the fragment
*
* @return Layout resource id
*/
@LayoutRes
protected abstract int getLayoutResId();
/**
* Event to be called when the back button was pressed
* True should be returned when this was handled by the fragment
* and no further handling in the view hierarchy is needed
*
* @return True if back handled by fragment
*/
public boolean onBackPressed() {
return false;
}
/**
* Set the language to be used in this fragment
* Defaults to resolve the language from sharedpreferences: pref_key__language
*
* @return Empty string for system language, or an android locale code
*/
public String getAppLanguage() {
if (getContext() != null) {
return getContext().getSharedPreferences("app", Context.MODE_PRIVATE)
.getString("pref_key__language", "");
}
return "";
}
/**
* This will be called when this fragment gets the first time visible
*/
public void onFragmentFirstTimeVisible() {
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
synchronized (_fragmentFirstTimeVisibleSync) {
if (isVisibleToUser && _fragmentFirstTimeVisible) {
_fragmentFirstTimeVisible = false;
onFragmentFirstTimeVisible();
}
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
_fragmentMenu = menu;
}
public Menu getFragmentMenu() {
return _fragmentMenu;
}
/**
* Get the toolbar from activity
* Requires id to be set to @+id/toolbar
*/
@SuppressWarnings("ConstantConditions")
protected Toolbar getToolbar() {
try {
return (Toolbar) getActivity().findViewById(new ContextUtils(getActivity()).getResId(ContextUtils.ResType.ID, "toolbar"));
} catch (Exception e) {
return null;
}
}
}

View file

@ -0,0 +1,351 @@
/*
* Maintained 2017-2023 by Gregor Santner <gsantner AT mailbox DOT org>
* License: Creative Commons Zero (CC0 1.0) / Public Domain
* http://creativecommons.org/publicdomain/zero/1.0/
*
* You can do whatever you want with this. If we meet some day, and you think it is worth it,
* you can buy me a drink in return. Provided as is without any kind of warranty. Do not blame
* or ask for support if something goes wrong. - Gregor Santner
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package net.gsantner.opoc.android.dummy;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.ActionProvider;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
public class MenuItemDummy implements MenuItem {
private final int _itemId;
public MenuItemDummy(final int itemId) {
_itemId = itemId;
}
@Override
public int getItemId() {
return _itemId;
}
@Override
public int getGroupId() {
return 0;
}
@Override
public int getOrder() {
return 0;
}
@Override
public MenuItem setTitle(CharSequence title) {
return null;
}
@Override
public MenuItem setTitle(int title) {
return null;
}
@Override
public CharSequence getTitle() {
return null;
}
@Override
public MenuItem setTitleCondensed(CharSequence title) {
return null;
}
@Override
public CharSequence getTitleCondensed() {
return null;
}
@Override
public MenuItem setIcon(Drawable icon) {
return null;
}
@Override
public MenuItem setIcon(int iconRes) {
return null;
}
@Override
public Drawable getIcon() {
return null;
}
@Override
public MenuItem setIntent(Intent intent) {
return null;
}
@Override
public Intent getIntent() {
return null;
}
@Override
public MenuItem setShortcut(char numericChar, char alphaChar) {
return null;
}
@Override
public MenuItem setNumericShortcut(char numericChar) {
return null;
}
@Override
public char getNumericShortcut() {
return 0;
}
@Override
public MenuItem setAlphabeticShortcut(char alphaChar) {
return null;
}
@Override
public char getAlphabeticShortcut() {
return 0;
}
@Override
public MenuItem setCheckable(boolean checkable) {
return null;
}
@Override
public boolean isCheckable() {
return false;
}
@Override
public MenuItem setChecked(boolean checked) {
return null;
}
@Override
public boolean isChecked() {
return false;
}
@Override
public MenuItem setVisible(boolean visible) {
return null;
}
@Override
public boolean isVisible() {
return false;
}
@Override
public MenuItem setEnabled(boolean enabled) {
return null;
}
@Override
public boolean isEnabled() {
return false;
}
@Override
public boolean hasSubMenu() {
return false;
}
@Override
public SubMenu getSubMenu() {
return null;
}
@Override
public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) {
return null;
}
@Override
public ContextMenu.ContextMenuInfo getMenuInfo() {
return null;
}
@Override
public void setShowAsAction(int actionEnum) {
}
@Override
public MenuItem setShowAsActionFlags(int actionEnum) {
return null;
}
@Override
public MenuItem setActionView(View view) {
return null;
}
@Override
public MenuItem setActionView(int resId) {
return null;
}
@Override
public View getActionView() {
return null;
}
@Override
public MenuItem setActionProvider(ActionProvider actionProvider) {
return null;
}
@Override
public ActionProvider getActionProvider() {
return null;
}
@Override
public boolean expandActionView() {
return false;
}
@Override
public boolean collapseActionView() {
return false;
}
@Override
public boolean isActionViewExpanded() {
return false;
}
@Override
public MenuItem setOnActionExpandListener(OnActionExpandListener listener) {
return null;
}
public static class Menu implements android.view.Menu {
@Override
public MenuItem add(CharSequence title) {
return add(0, 0, 0, "");
}
@Override
public MenuItem add(int titleRes) {
return add(0, 0, 0, "");
}
@Override
public MenuItem add(int groupId, int itemId, int order, CharSequence title) {
return new MenuItemDummy(itemId);
}
@Override
public MenuItem add(int groupId, int itemId, int order, int titleRes) {
return add(0, 0, 0, "");
}
@Override
public SubMenu addSubMenu(CharSequence title) {
return null;
}
@Override
public SubMenu addSubMenu(int titleRes) {
return null;
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) {
return null;
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) {
return null;
}
@Override
public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) {
return 0;
}
@Override
public void removeItem(int id) {
}
@Override
public void removeGroup(int groupId) {
}
@Override
public void clear() {
}
@Override
public void setGroupCheckable(int group, boolean checkable, boolean exclusive) {
}
@Override
public void setGroupVisible(int group, boolean visible) {
}
@Override
public void setGroupEnabled(int group, boolean enabled) {
}
@Override
public boolean hasVisibleItems() {
return false;
}
@Override
public MenuItem findItem(int id) {
return null;
}
@Override
public int size() {
return 0;
}
@Override
public MenuItem getItem(int index) {
return null;
}
@Override
public void close() {
}
@Override
public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
return false;
}
@Override
public boolean isShortcutKey(int keyCode, KeyEvent event) {
return false;
}
@Override
public boolean performIdentifierAction(int id, int flags) {
return false;
}
@Override
public void setQwertyMode(boolean isQwerty) {
}
}
}

View file

@ -0,0 +1,58 @@
/*
* Maintained 2017-2023 by Gregor Santner <gsantner AT mailbox DOT org>
* License: Creative Commons Zero (CC0 1.0) / Public Domain
* http://creativecommons.org/publicdomain/zero/1.0/
*
* You can do whatever you want with this. If we meet some day, and you think it is worth it,
* you can buy me a drink in return. Provided as is without any kind of warranty. Do not blame
* or ask for support if something goes wrong. - Gregor Santner
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package net.gsantner.opoc.android.dummy;
import android.text.Editable;
import android.text.TextWatcher;
import net.gsantner.opoc.util.Callback;
@SuppressWarnings({"unused", "SpellCheckingInspection"})
public class TextWatcherDummy implements TextWatcher {
@Override
public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
}
@Override
public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
}
@Override
public void afterTextChanged(final Editable s) {
}
public static TextWatcher before(final Callback.a4<CharSequence, Integer, Integer, Integer> impl) {
return new TextWatcherDummy() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
impl.callback(s, start, count, after);
}
};
}
public static TextWatcher on(final Callback.a4<CharSequence, Integer, Integer, Integer> impl) {
return new TextWatcherDummy() {
public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
impl.callback(s, start, before, count);
}
};
}
public static TextWatcher after(final Callback.a1<Editable> impl) {
return new TextWatcherDummy() {
public void afterTextChanged(final Editable s) {
impl.callback(s);
}
};
}
}

View file

@ -1,20 +1,14 @@
/*
* ------------------------------------------------------------------------------
* Gregor Santner <gsantner.github.io> wrote this. You can do whatever you want
* with it. If we meet some day, and you think it is worth it, you can buy me a
* coke in return. Provided as is without any kind of warranty. Do not blame or
* sue me if something goes wrong. No attribution required. - Gregor Santner
/*#######################################################
*
* License: Creative Commons Zero (CC0 1.0)
* http://creativecommons.org/publicdomain/zero/1.0/
* ----------------------------------------------------------------------------
*/
/*
* Get updates:
* https://github.com/gsantner/onePieceOfCode/blob/master/java/SimpleMarkdownParser.java
* Apply to TextView:
* See https://github.com/gsantner/onePieceOfCode/blob/master/android/ContextUtils.java
* Maintained 2018-2023 by Gregor Santner <gsantner AT mailbox DOT org>
*
* License: Apache 2.0
* https://github.com/gsantner/opoc/#licensing
* https://www.apache.org/licenses/LICENSE-2.0
*
#########################################################*/
/*
* Parses most common markdown tags. Only inline tags are supported, multiline/block syntax
* is not supported (citation, multiline code, ..). This is intended to stay as easy as possible.
*
@ -27,7 +21,7 @@
* FILTER_WEB is intended to be used at engines understanding most common HTML tags.
*/
package net.gsantner.opoc.util;
package net.gsantner.opoc.format.markdown;
import java.io.BufferedReader;
import java.io.FileInputStream;
@ -38,7 +32,7 @@ import java.io.InputStreamReader;
/**
* Simple Markdown Parser
*/
@SuppressWarnings({"WeakerAccess", "CaughtExceptionImmediatelyRethrown", "SameParameterValue", "unused", "SpellCheckingInspection", "RepeatedSpace", "SingleCharAlternation"})
@SuppressWarnings({"WeakerAccess", "CaughtExceptionImmediatelyRethrown", "SameParameterValue", "unused", "SpellCheckingInspection", "RepeatedSpace", "SingleCharAlternation", "Convert2Lambda"})
public class SimpleMarkdownParser {
//########################
//## Statics
@ -98,8 +92,8 @@ public class SimpleMarkdownParser {
.replaceAll("!\\[(.*?)\\]\\((.*?)\\)", "<img src=\\'$2\\' alt='$1' />") // img
.replaceAll("<(http|https):\\/\\/(.*)>", "<a href='$1://$2'>$1://$2</a>") // a href (DEP: img)
.replaceAll("\\[(.*?)\\]\\((.*?)\\)", "<a href=\\'$2\\'>$1</a>") // a href (DEP: img)
.replaceAll("(?m)^([-*] )(.*)$", "<font color='#000001'>&#8226;</font> $2 ") // unordered list + end line
.replaceAll("(?m)^ (-|\\*) ([^<]*)$", "&nbsp;&nbsp;<font color='#000001'>&#8226;</font> $2 ") // unordered list2 + end line
.replaceAll("(?m)^[-*] (.*)$", "<font color='#000001'>&#8226;</font> $1 ") // unordered list + end line
.replaceAll("(?m)^ [-*] (.*)$", "&nbsp;&nbsp;<font color='#000001'>&#8226;</font> $1 ") // unordered list2 + end line
.replaceAll("`([^<]*)`", "<code>$1</code>") // code
.replace("\\*", "") // temporary replace escaped star symbol
.replaceAll("(?m)\\*\\*(.*)\\*\\*", "<b>$1</b>") // bold (DEP: temp star)
@ -116,6 +110,7 @@ public class SimpleMarkdownParser {
public String filter(String text) {
text = text
.replace("New:", "<font color='#276230'>New:</font>")
.replace("New features:", "<font color='#276230'>New:</font>")
.replace("Added:", "<font color='#276230'>Added:</font>")
.replace("Add:", "<font color='#276230'>Add:</font>")
.replace("Fixed:", "<font color='#005688'>Fixed:</font>")
@ -129,6 +124,26 @@ public class SimpleMarkdownParser {
return text;
}
};
public final static SmpFilter FILTER_H_TO_SUP = new SmpFilter() {
@Override
public String filter(String text) {
text = text
.replace("<h1>", "<sup><sup><sup>")
.replace("</h1>", "</sup></sup></sup>")
.replace("<h2>", "<sup><sup>")
.replace("</h2>", "</sup></sup>")
.replace("<h3>", "<sup>")
.replace("</h3>", "</sup>")
;
return text;
}
};
public final static SmpFilter FILTER_NONE = new SmpFilter() {
@Override
public String filter(String text) {
return text;
}
};
//########################
//## Singleton

View file

@ -0,0 +1,47 @@
/*#######################################################
*
* Maintained 2018-2023 by Gregor Santner <gsantner AT mailbox DOT org>
*
* License: Apache 2.0
* https://github.com/gsantner/opoc/#licensing
* https://www.apache.org/licenses/LICENSE-2.0
*
#########################################################*/
package net.gsantner.opoc.preference;
import java.util.List;
@SuppressWarnings({"UnusedReturnValue", "SpellCheckingInspection", "unused", "SameParameterValue"})
public interface PropertyBackend<TKEY, TTHIS> {
String getString(TKEY key, String defaultValue);
int getInt(TKEY key, int defaultValue);
long getLong(TKEY key, long defaultValue);
boolean getBool(TKEY key, boolean defaultValue);
float getFloat(TKEY key, float defaultValue);
double getDouble(TKEY key, double defaultValue);
List<Integer> getIntList(TKEY key);
List<String> getStringList(TKEY key);
TTHIS setString(TKEY key, String value);
TTHIS setInt(TKEY key, int value);
TTHIS setLong(TKEY key, long value);
TTHIS setBool(TKEY key, boolean value);
TTHIS setFloat(TKEY key, float value);
TTHIS setDouble(TKEY key, double value);
TTHIS setIntList(TKEY key, List<Integer> value);
TTHIS setStringList(TKEY key, List<String> value);
}

View file

@ -0,0 +1,617 @@
/*#######################################################
*
* Maintained 2016-2023 by Gregor Santner <gsantner AT mailbox DOT org>
*
* License: Apache 2.0
* https://github.com/gsantner/opoc/#licensing
* https://www.apache.org/licenses/LICENSE-2.0
*
#########################################################*/
/*
* This is a wrapper for settings based on SharedPreferences
* with keys in resources. Extend from this class and add
* getters/setters for the app's settings.
* Example:
public boolean isAppFirstStart(boolean doSet) {
int value = getInt(R.string.pref_key__app_first_start, -1);
if (doSet) {
setBool(true);
}
return value;
}
public boolean isAppCurrentVersionFirstStart(boolean doSet) {
int value = getInt(R.string.pref_key__app_first_start_current_version, -1);
if (doSet) {
setInt(R.string.pref_key__app_first_start_current_version, BuildConfig.VERSION_CODE);
}
return value != BuildConfig.VERSION_CODE;
}
*/
package net.gsantner.opoc.preference;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.ColorRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
/**
* Wrapper for settings based on SharedPreferences, optionally with keys in resources
* Default SharedPreference (_prefApp) will be taken if no SP is specified, else the first one
*/
@SuppressWarnings({"WeakerAccess", "unused", "SpellCheckingInspection", "SameParameterValue"})
public class SharedPreferencesPropertyBackend implements PropertyBackend<String, SharedPreferencesPropertyBackend> {
protected static final String ARRAY_SEPARATOR = "%%%";
protected static final String ARRAY_SEPARATOR_SUBSTITUTE = "§§§";
public static final String SHARED_PREF_APP = "app";
private static String _debugLog = "";
//
// Members, Constructors
//
protected final SharedPreferences _prefApp;
protected final String _prefAppName;
protected final Context _context;
public SharedPreferencesPropertyBackend(final Context context) {
this(context, SHARED_PREF_APP);
}
public SharedPreferencesPropertyBackend(final Context context, final String prefAppName) {
_context = context.getApplicationContext();
_prefAppName = TextUtils.isEmpty(prefAppName) ?
_context.getPackageName() + "_preferences" : prefAppName;
_prefApp = _context.getSharedPreferences(_prefAppName, Context.MODE_PRIVATE);
}
//
// Methods
//
public Context getContext() {
return _context;
}
public boolean isKeyEqual(String key, int stringKeyResourceId) {
return key.equals(rstr(stringKeyResourceId));
}
public void resetSettings() {
resetSettings(_prefApp);
}
@SuppressLint("ApplySharedPref")
public void resetSettings(final SharedPreferences pref) {
pref.edit().clear().commit();
}
public boolean isPrefSet(@StringRes int stringKeyResourceId) {
return isPrefSet(_prefApp, stringKeyResourceId);
}
public boolean isPrefSet(final SharedPreferences pref, @StringRes int stringKeyResourceId) {
return pref.contains(rstr(stringKeyResourceId));
}
public void registerPreferenceChangedListener(SharedPreferences.OnSharedPreferenceChangeListener value) {
registerPreferenceChangedListener(_prefApp, value);
}
public void registerPreferenceChangedListener(final SharedPreferences pref, SharedPreferences.OnSharedPreferenceChangeListener value) {
pref.registerOnSharedPreferenceChangeListener(value);
}
public void unregisterPreferenceChangedListener(SharedPreferences.OnSharedPreferenceChangeListener value) {
unregisterPreferenceChangedListener(_prefApp, value);
}
public void unregisterPreferenceChangedListener(final SharedPreferences pref, SharedPreferences.OnSharedPreferenceChangeListener value) {
pref.unregisterOnSharedPreferenceChangeListener(value);
}
public SharedPreferences getDefaultPreferences() {
return _prefApp;
}
public SharedPreferences.Editor getDefaultPreferencesEditor() {
return _prefApp.edit();
}
public String getDefaultPreferencesName() {
return _prefAppName;
}
private SharedPreferences gp(final SharedPreferences... pref) {
return (pref != null && pref.length > 0 ? pref[0] : _prefApp);
}
public static void limitListTo(final List<?> list, int maxSize, boolean removeDuplicates) {
Object o;
int pos;
for (int i = 0; removeDuplicates && i < list.size(); i++) {
o = list.get(i);
while ((pos = list.lastIndexOf(o)) != i && pos >= 0) {
list.remove(pos);
}
}
while ((pos = list.size()) > maxSize && pos > 0) {
list.remove(list.size() - 1);
}
}
//
// Getter for resources
//
public String rstr(@StringRes int stringKeyResourceId) {
return _context.getString(stringKeyResourceId);
}
public int rcolor(@ColorRes int resColorId) {
return ContextCompat.getColor(_context, resColorId);
}
public String[] rstrs(int... keyResourceIds) {
String[] ret = new String[keyResourceIds.length];
for (int i = 0; i < keyResourceIds.length; i++) {
ret[i] = rstr(keyResourceIds[i]);
}
return ret;
}
//
// Getter & Setter for String
//
public void setString(@StringRes int keyResourceId, String value, final SharedPreferences... pref) {
gp(pref).edit().putString(rstr(keyResourceId), value).apply();
}
public void setString(String key, String value, final SharedPreferences... pref) {
gp(pref).edit().putString(key, value).apply();
}
public void setString(@StringRes int keyResourceId, @StringRes int defaultValueResourceId, final SharedPreferences... pref) {
gp(pref).edit().putString(rstr(keyResourceId), rstr(defaultValueResourceId)).apply();
}
public String getString(@StringRes int keyResourceId, String defaultValue, final SharedPreferences... pref) {
return gp(pref).getString(rstr(keyResourceId), defaultValue);
}
public String getString(@StringRes int keyResourceId, @StringRes int defaultValueResourceId, final SharedPreferences... pref) {
return gp(pref).getString(rstr(keyResourceId), rstr(defaultValueResourceId));
}
public String getString(String key, String defaultValue, final SharedPreferences... pref) {
try {
return gp(pref).getString(key, defaultValue);
} catch (ClassCastException e) {
return defaultValue;
}
}
public String getString(@StringRes int keyResourceId, String defaultValue, @StringRes int keyResourceIdDefaultValue, final SharedPreferences... pref) {
return getString(rstr(keyResourceId), rstr(keyResourceIdDefaultValue), pref);
}
private void setStringListOne(String key, List<String> values, final SharedPreferences pref) {
StringBuilder sb = new StringBuilder();
for (String value : values) {
sb.append(ARRAY_SEPARATOR);
sb.append(value.replace(ARRAY_SEPARATOR, ARRAY_SEPARATOR_SUBSTITUTE));
}
setString(key, sb.toString().replaceFirst(ARRAY_SEPARATOR, ""), pref);
}
private ArrayList<String> getStringListOne(String key, final SharedPreferences pref) {
ArrayList<String> ret = new ArrayList<>();
String value = getString(key, ARRAY_SEPARATOR).replace(ARRAY_SEPARATOR_SUBSTITUTE, ARRAY_SEPARATOR);
if (value.equals(ARRAY_SEPARATOR) || TextUtils.isEmpty(value)) {
return ret;
}
ret.addAll(Arrays.asList(value.split(ARRAY_SEPARATOR)));
return ret;
}
public void setStringArray(@StringRes int keyResourceId, String[] values, final SharedPreferences... pref) {
setStringArray(rstr(keyResourceId), values, pref);
}
public void setStringArray(String key, String[] values, final SharedPreferences... pref) {
setStringListOne(key, Arrays.asList(values), gp(pref));
}
public void setStringList(@StringRes int keyResourceId, List<String> values, final SharedPreferences... pref) {
setStringArray(rstr(keyResourceId), values.toArray(new String[values.size()]), pref);
}
public void setStringList(String key, List<String> values, final SharedPreferences... pref) {
setStringArray(key, values.toArray(new String[values.size()]), pref);
}
@NonNull
public String[] getStringArray(@StringRes int keyResourceId, final SharedPreferences... pref) {
return getStringArray(rstr(keyResourceId), pref);
}
@NonNull
public String[] getStringArray(String key, final SharedPreferences... pref) {
List<String> list = getStringListOne(key, gp(pref));
return list.toArray(new String[list.size()]);
}
public ArrayList<String> getStringList(@StringRes int keyResourceId, final SharedPreferences... pref) {
return getStringListOne(rstr(keyResourceId), gp(pref));
}
public ArrayList<String> getStringList(String key, final SharedPreferences... pref) {
return getStringListOne(key, gp(pref));
}
//
// Getter & Setter for integer
//
public void setInt(@StringRes int keyResourceId, int value, final SharedPreferences... pref) {
gp(pref).edit().putInt(rstr(keyResourceId), value).apply();
}
public void setInt(String key, int value, final SharedPreferences... pref) {
gp(pref).edit().putInt(key, value).apply();
}
public int getInt(@StringRes int keyResourceId, int defaultValue, final SharedPreferences... pref) {
return getInt(rstr(keyResourceId), defaultValue, pref);
}
public int getInt(String key, int defaultValue, final SharedPreferences... pref) {
try {
return gp(pref).getInt(key, defaultValue);
} catch (ClassCastException e) {
return defaultValue;
}
}
public int getIntOfStringPref(@StringRes int keyResId, int defaultValue, final SharedPreferences... pref) {
return getIntOfStringPref(rstr(keyResId), defaultValue, gp(pref));
}
public int getIntOfStringPref(String key, int defaultValue, final SharedPreferences... pref) {
String strNum = getString(key, Integer.toString(defaultValue), gp(pref));
return Integer.valueOf(strNum);
}
private void setIntListOne(String key, List<Integer> values, final SharedPreferences pref) {
StringBuilder sb = new StringBuilder();
for (Integer value : values) {
sb.append(ARRAY_SEPARATOR);
sb.append(value.toString());
}
setString(key, sb.toString().replaceFirst(ARRAY_SEPARATOR, ""), pref);
}
private ArrayList<Integer> getIntListOne(String key, final SharedPreferences pref) {
ArrayList<Integer> ret = new ArrayList<>();
String value = getString(key, ARRAY_SEPARATOR);
if (value.equals(ARRAY_SEPARATOR)) {
return ret;
}
for (String s : value.split(ARRAY_SEPARATOR)) {
ret.add(Integer.parseInt(s));
}
return ret;
}
public void setIntArray(@StringRes int keyResourceId, Integer[] values, final SharedPreferences... pref) {
setIntArray(rstr(keyResourceId), values, gp(pref));
}
public void setIntArray(String key, Integer[] values, final SharedPreferences... pref) {
setIntListOne(key, Arrays.asList(values), gp(pref));
}
public Integer[] getIntArray(@StringRes int keyResourceId, final SharedPreferences... pref) {
return getIntArray(rstr(keyResourceId), gp(pref));
}
public Integer[] getIntArray(String key, final SharedPreferences... pref) {
List<Integer> data = getIntListOne(key, gp(pref));
return data.toArray(new Integer[data.size()]);
}
public void setIntList(@StringRes int keyResourceId, List<Integer> values, final SharedPreferences... pref) {
setIntListOne(rstr(keyResourceId), values, gp(pref));
}
public void setIntList(String key, List<Integer> values, final SharedPreferences... pref) {
setIntListOne(key, values, gp(pref));
}
public ArrayList<Integer> getIntList(@StringRes int keyResourceId, final SharedPreferences... pref) {
return getIntListOne(rstr(keyResourceId), gp(pref));
}
public ArrayList<Integer> getIntList(String key, final SharedPreferences... pref) {
return getIntListOne(key, gp(pref));
}
//
// Getter & Setter for Long
//
public void setLong(@StringRes int keyResourceId, long value, final SharedPreferences... pref) {
gp(pref).edit().putLong(rstr(keyResourceId), value).apply();
}
public void setLong(String key, long value, final SharedPreferences... pref) {
gp(pref).edit().putLong(key, value).apply();
}
public long getLong(@StringRes int keyResourceId, long defaultValue, final SharedPreferences... pref) {
return getLong(rstr(keyResourceId), defaultValue, pref);
}
public long getLong(String key, long defaultValue, final SharedPreferences... pref) {
try {
return gp(pref).getLong(key, defaultValue);
} catch (ClassCastException e) {
return defaultValue;
}
}
//
// Getter & Setter for Float
//
public void setFloat(@StringRes int keyResourceId, float value, final SharedPreferences... pref) {
gp(pref).edit().putFloat(rstr(keyResourceId), value).apply();
}
public void setFloat(String key, float value, final SharedPreferences... pref) {
gp(pref).edit().putFloat(key, value).apply();
}
public float getFloat(@StringRes int keyResourceId, float defaultValue, final SharedPreferences... pref) {
return getFloat(rstr(keyResourceId), defaultValue);
}
public float getFloat(String key, float defaultValue, final SharedPreferences... pref) {
try {
return gp(pref).getFloat(key, defaultValue);
} catch (ClassCastException e) {
return defaultValue;
}
}
//
// Getter & Setter for Double
//
public void setDouble(@StringRes int keyResourceId, double value, final SharedPreferences... pref) {
setLong(rstr(keyResourceId), Double.doubleToRawLongBits(value));
}
public void setDouble(String key, double value, final SharedPreferences... pref) {
setLong(key, Double.doubleToRawLongBits(value));
}
public double getDouble(@StringRes int keyResourceId, double defaultValue, final SharedPreferences... pref) {
return getDouble(rstr(keyResourceId), defaultValue, gp(pref));
}
public double getDouble(String key, double defaultValue, final SharedPreferences... pref) {
return Double.longBitsToDouble(getLong(key, Double.doubleToRawLongBits(defaultValue), gp(pref)));
}
//
// Getter & Setter for boolean
//
public void setBool(@StringRes int keyResourceId, boolean value, final SharedPreferences... pref) {
gp(pref).edit().putBoolean(rstr(keyResourceId), value).apply();
}
public void setBool(String key, boolean value, final SharedPreferences... pref) {
gp(pref).edit().putBoolean(key, value).apply();
}
public boolean getBool(@StringRes int keyResourceId, boolean defaultValue, final SharedPreferences... pref) {
return getBool(rstr(keyResourceId), defaultValue);
}
public boolean getBool(String key, boolean defaultValue, final SharedPreferences... pref) {
try {
return gp(pref).getBoolean(key, defaultValue);
} catch (ClassCastException e) {
return defaultValue;
}
}
//
// Getter & Setter for Color
//
public int getColor(String key, @ColorRes int defaultColor, final SharedPreferences... pref) {
return getInt(key, rcolor(defaultColor));
}
public int getColor(@StringRes int keyResourceId, @ColorRes int defaultColor, final SharedPreferences... pref) {
return getColor(rstr(keyResourceId), defaultColor);
}
//
// PropertyBackend<String> implementations
//
@Override
public String getString(String key, String defaultValue) {
return getString(key, defaultValue, _prefApp);
}
@Override
public int getInt(String key, int defaultValue) {
return getInt(key, defaultValue, _prefApp);
}
@Override
public long getLong(String key, long defaultValue) {
return getLong(key, defaultValue, _prefApp);
}
@Override
public boolean getBool(String key, boolean defaultValue) {
return getBool(key, defaultValue, _prefApp);
}
@Override
public float getFloat(String key, float defaultValue) {
return getFloat(key, defaultValue, _prefApp);
}
@Override
public double getDouble(String key, double defaultValue) {
return getDouble(key, defaultValue, _prefApp);
}
@Override
public ArrayList<Integer> getIntList(String key) {
return getIntList(key, _prefApp);
}
@Override
public ArrayList<String> getStringList(String key) {
return getStringList(key, _prefApp);
}
@Override
public SharedPreferencesPropertyBackend setString(String key, String value) {
setString(key, value, _prefApp);
return this;
}
@Override
public SharedPreferencesPropertyBackend setInt(String key, int value) {
setInt(key, value, _prefApp);
return this;
}
@Override
public SharedPreferencesPropertyBackend setLong(String key, long value) {
setLong(key, value, _prefApp);
return this;
}
@Override
public SharedPreferencesPropertyBackend setBool(String key, boolean value) {
setBool(key, value, _prefApp);
return this;
}
@Override
public SharedPreferencesPropertyBackend setFloat(String key, float value) {
setFloat(key, value, _prefApp);
return this;
}
@Override
public SharedPreferencesPropertyBackend setDouble(String key, double value) {
setDouble(key, value, _prefApp);
return this;
}
@Override
public SharedPreferencesPropertyBackend setIntList(String key, List<Integer> value) {
setIntListOne(key, value, _prefApp);
return this;
}
@Override
public SharedPreferencesPropertyBackend setStringList(String key, List<String> value) {
setStringListOne(key, value, _prefApp);
return this;
}
public boolean contains(String key, final SharedPreferences... pref) {
return gp(pref).contains(key);
}
/**
* A method to determine if current hour is between begin and end.
* This is especially useful for time-based light/dark mode
*/
public static boolean isCurrentHourOfDayBetween(int begin, int end) {
begin = (begin >= 23 || begin < 0) ? 0 : begin;
end = (end >= 23 || end < 0) ? 0 : end;
int h = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
return h >= begin && h <= end;
}
/**
* Substract current datetime by given amount of days
*/
public Date getDateOfDaysAgo(int days) {
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DATE, -days);
return cal.getTime();
}
/**
* Substract current datetime by given amount of days and check if the given date passed
*/
public boolean didDaysPassedSince(Date date, int days) {
if (date == null || days < 0) {
return false;
}
return date.before(getDateOfDaysAgo(days));
}
public boolean afterDaysTrue(String key, int daysSinceLastTime, int firstTime, final SharedPreferences... pref) {
Date d = new Date(System.currentTimeMillis());
if (!contains(key)) {
d = getDateOfDaysAgo(daysSinceLastTime - firstTime);
setLong(key, d.getTime());
return firstTime < 1;
} else {
d = new Date(getLong(key, d.getTime()));
}
boolean trigger = didDaysPassedSince(d, daysSinceLastTime);
if (trigger) {
setLong(key, new Date(System.currentTimeMillis()).getTime());
}
return trigger;
}
public static void clearDebugLog() {
_debugLog = "";
}
public static String getDebugLog() {
return _debugLog;
}
public static synchronized void appendDebugLog(String text) {
_debugLog += "[" + new Date().toString() + "] " + text + "\n";
}
public static boolean ne(final String str) {
return str != null && !str.trim().isEmpty();
}
public static boolean fexists(final String fp) {
return ne(fp) && (new File(fp)).exists();
}
}

View file

@ -1,26 +1,24 @@
/*
* ------------------------------------------------------------------------------
* Gregor Santner <gsantner.github.io> wrote this. You can do whatever you want
* with it. If we meet some day, and you think it is worth it, you can buy me a
* coke in return. Provided as is without any kind of warranty. Do not blame or
* sue me if something goes wrong. No attribution required. - Gregor Santner
/*#######################################################
*
* License: Creative Commons Zero (CC0 1.0)
* http://creativecommons.org/publicdomain/zero/1.0/
* ----------------------------------------------------------------------------
*/
* Maintained 2017-2023 by Gregor Santner <gsantner AT mailbox DOT org>
*
* License: Apache 2.0
* https://github.com/gsantner/opoc/#licensing
* https://www.apache.org/licenses/LICENSE-2.0
*
#########################################################*/
/*
* A ListPreference that displays a list of available languages
* Requires:
* The BuildConfig field "APPLICATION_LANGUAGES" which is a array of all available languages
* opoc/ContextUtils
The BuildConfig field "APPLICATION_LANGUAGES" which is a array of all available languages
opoc/ContextUtils
* BuildConfig field can be defined by using the method below
buildConfigField("String[]", "APPLICATION_LANGUAGES", '{' + getUsedAndroidLanguages().collect {"\"${it}\""}.join(",") + '}')
buildConfigField "String[]", "APPLICATION_LANGUAGES", "${getUsedAndroidLanguages()}"
@SuppressWarnings(["UnnecessaryQualifiedReference", "SpellCheckingInspection"])
static String[] getUsedAndroidLanguages() {
@SuppressWarnings(["UnnecessaryQualifiedReference", "SpellCheckingInspection", "GroovyUnusedDeclaration"])
// Returns used android languages as a buildConfig array: {'de', 'it', ..}"
static String getUsedAndroidLanguages() {
Set<String> langs = new HashSet<>()
new File('.').eachFileRecurse(groovy.io.FileType.DIRECTORIES) {
final foldername = it.name
@ -28,29 +26,30 @@ static String[] getUsedAndroidLanguages() {
new File(it.toString()).eachFileRecurse(groovy.io.FileType.FILES) {
if (it.name.toLowerCase().endsWith(".xml") && it.getCanonicalFile().getText('UTF-8').contains("<string")) {
langs.add(foldername.replace("values-", ""))
}
}
}
}
return langs.toArray(new String[langs.size()])
return '{' + langs.collect { "\"${it}\"" }.join(",") + '}'
}
* Summary: Change language of this app. Restart app for changes to take effect
* Define element in Preferences-XML:
<net.gsantner.opoc.ui.LanguagePreference
<net.gsantner.opoc.preference.LanguagePreference
android:icon="@drawable/ic_language_black_24dp"
android:key="@string/pref_key__language"
android:summary="@string/pref_desc__language"
android:title="@string/pref_title__language"/>
*/
package net.gsantner.opoc.ui;
package net.gsantner.opoc.preference.nonsupport;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.preference.ListPreference;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import net.gsantner.opoc.util.ContextUtils;
@ -66,36 +65,35 @@ import java.util.Locale;
@SuppressWarnings({"unused", "SpellCheckingInspection", "WeakerAccess"})
public class LanguagePreference extends ListPreference {
private static final String SYSTEM_LANGUAGE_CODE = "";
public static String SYSTEM_LANGUAGE_NAME = "System";
// The language of res/values/ -> (usually English)
public static String DEFAULT_LANGUAGE_NAME = "English";
public static String DEFAULT_LANGUAGE_CODE = "en";
public String _systemLanguageName = "System";
public String _defaultLanguageCode = "en";
public LanguagePreference(Context context) {
super(context);
init(context, null);
loadLangs(context, null);
}
public LanguagePreference(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
loadLangs(context, attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public LanguagePreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
loadLangs(context, attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public LanguagePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs);
loadLangs(context, attrs);
}
@Override
protected boolean callChangeListener(Object newValue) {
public boolean callChangeListener(Object newValue) {
if (newValue instanceof String) {
// Does not apply to existing UI, use recreate()
new ContextUtils(getContext()).setAppLanguage((String) newValue);
@ -103,17 +101,22 @@ public class LanguagePreference extends ListPreference {
return super.callChangeListener(newValue);
}
private void init(Context context, AttributeSet attrs) {
private void loadLangs(Context context) {
loadLangs(context, null);
}
private void loadLangs(Context context, @Nullable AttributeSet attrs) {
setDefaultValue(SYSTEM_LANGUAGE_CODE);
// Fetch readable details
ContextUtils contextUtils = new ContextUtils(context);
List<String> languages = new ArrayList<>();
Object bcof = contextUtils.getBuildConfigValue("APPLICATION_LANGUAGES");
Object bcof = contextUtils.getBuildConfigValue("DETECTED_ANDROID_LOCALES");
if (bcof instanceof String[]) {
for (String langId : (String[]) bcof) {
Locale locale = contextUtils.getLocaleByAndroidCode(langId);
languages.add(summarizeLocale(locale) + ";" + langId);
languages.add(summarizeLocale(locale, langId) + ";" + langId);
}
}
@ -127,10 +130,10 @@ public class LanguagePreference extends ListPreference {
entries[i + 2] = languages.get(i).split(";")[0];
entryval[i + 2] = languages.get(i).split(";")[1];
}
entries[0] = SYSTEM_LANGUAGE_NAME;
entryval[0] = SYSTEM_LANGUAGE_CODE;
entries[1] = DEFAULT_LANGUAGE_NAME;
entryval[1] = DEFAULT_LANGUAGE_CODE;
entries[0] = _systemLanguageName + " » " + summarizeLocale(context.getResources().getConfiguration().locale, "");
entryval[1] = _defaultLanguageCode;
entries[1] = summarizeLocale(contextUtils.getLocaleByAndroidCode(_defaultLanguageCode), _defaultLanguageCode);
setEntries(entries);
setEntryValues(entryval);
@ -138,19 +141,47 @@ public class LanguagePreference extends ListPreference {
// Concat english and localized language name
// Append country if country specific (e.g. Portuguese Brazil)
private String summarizeLocale(Locale locale) {
private String summarizeLocale(final Locale locale, final String localeAndroidCode) {
String country = locale.getDisplayCountry(locale);
String language = locale.getDisplayLanguage(locale);
return locale.getDisplayLanguage(Locale.ENGLISH)
+ " (" + language.substring(0, 1).toUpperCase() + language.substring(1)
+ ((!country.isEmpty() && !country.toLowerCase().equals(language.toLowerCase())) ? (", " + country) : "")
String ret = locale.getDisplayLanguage(Locale.ENGLISH)
+ " (" + language.substring(0, 1).toUpperCase(Locale.getDefault()) + language.substring(1)
+ ((!country.isEmpty() && !country.toLowerCase(Locale.getDefault()).equals(language.toLowerCase(Locale.getDefault()))) ? (", " + country) : "")
+ ")";
if (localeAndroidCode.equals("zh-rCN")) {
ret = ret.substring(0, ret.indexOf(" ") + 1) + "Simplified" + ret.substring(ret.indexOf(" "));
} else if (localeAndroidCode.equals("zh-rTW")) {
ret = ret.substring(0, ret.indexOf(" ") + 1) + "Traditional" + ret.substring(ret.indexOf(" "));
}
return ret;
}
// Add current language to summary
@Override
public CharSequence getSummary() {
Locale locale = new ContextUtils(getContext()).getLocaleByAndroidCode(getValue());
return super.getSummary() + "\n\n" + summarizeLocale(locale);
String prefix = TextUtils.isEmpty(super.getSummary())
? "" : super.getSummary() + "\n\n";
return prefix + summarizeLocale(locale, getValue());
}
public String getSystemLanguageName() {
return _systemLanguageName;
}
public void setSystemLanguageName(String systemLanguageName) {
_systemLanguageName = systemLanguageName;
loadLangs(getContext());
}
public String getDefaultLanguageCode() {
return _defaultLanguageCode;
}
public void setDefaultLanguageCode(String defaultLanguageCode) {
_defaultLanguageCode = defaultLanguageCode;
loadLangs(getContext());
}
}

View file

@ -0,0 +1,394 @@
/*#######################################################
*
* Maintained 2017-2023 by Gregor Santner <gsantner AT mailbox DOT org>
*
* License: Apache 2.0
* https://github.com/gsantner/opoc/#licensing
* https://www.apache.org/licenses/LICENSE-2.0
*
#########################################################*/
package net.gsantner.opoc.ui;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.TooltipCompat;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Checkable;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import net.gsantner.opoc.android.dummy.TextWatcherDummy;
import net.gsantner.opoc.util.Callback;
import net.gsantner.opoc.util.ContextUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
@SuppressLint("SetTextI18n")
public class SearchOrCustomTextDialog {
public static class DialogOptions {
// Callback for search text or text of single item
@Nullable
public Callback.a1<String> callback = null;
// Callback for indices of selected items.
// List will contain single item if isMultiSelectEnabled == false;
@Nullable
public Callback.a1<List<Integer>> positionCallback = null;
public boolean isMultiSelectEnabled = false;
public List<? extends CharSequence> data = null;
public List<? extends CharSequence> highlightData = null;
public List<Integer> iconsForData;
public String messageText = "";
public String defaultText = "";
public boolean isSearchEnabled = true;
public boolean isDarkDialog = false;
public int dialogWidthDp = WindowManager.LayoutParams.MATCH_PARENT;
public int dialogHeightDp = WindowManager.LayoutParams.WRAP_CONTENT;
public int gravity = Gravity.NO_GRAVITY;
public int searchInputType = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
public boolean searchIsRegex = false;
public Callback.a1<Spannable> highlighter = null;
public String extraFilter = null;
public List<Integer> preSelected = null;
public Callback.a0 neutralButtonCallback = null;
@ColorInt
public int textColor = 0xFF000000;
@ColorInt
public int highlightColor = 0xFF00FF00;
@StringRes
public int cancelButtonText = android.R.string.cancel;
@StringRes
public int neutralButtonText = 0;
@StringRes
public int okButtonText = android.R.string.ok;
@StringRes
public int titleText = 0;
@StringRes
public int searchHintText = android.R.string.search_go;
@DrawableRes
public int clearInputIcon = android.R.drawable.ic_input_delete;
}
private static class Adapter extends ArrayAdapter<Integer> {
@LayoutRes
private final int _layout;
private final int _layoutHeight;
private final LayoutInflater _inflater;
private final DialogOptions _dopt;
private final List<Integer> _filteredItems;
private final Set<Integer> _selectedItems;
private final Pattern _extraPattern;
public static Adapter create(final Context context, final DialogOptions dopt) {
return new Adapter(context, dopt, dopt.isMultiSelectEnabled ? android.R.layout.simple_list_item_multiple_choice : android.R.layout.simple_list_item_1, new ArrayList<>());
}
private Adapter(final Context context, final DialogOptions dopt, final int layout, final List<Integer> filteredItems) {
super(context, layout, filteredItems);
_layout = layout;
_filteredItems = filteredItems;
_inflater = LayoutInflater.from(context);
_dopt = dopt;
_extraPattern = (_dopt.extraFilter == null ? null : Pattern.compile(_dopt.extraFilter));
_selectedItems = new HashSet<>(_dopt.preSelected != null ? _dopt.preSelected : Collections.emptyList());
ContextUtils cu = new ContextUtils(context);
_layoutHeight = (int) cu.convertDpToPx(36);
cu.freeContextRef();
}
@NonNull
@Override
public View getView(int pos, @Nullable View convertView, @NonNull ViewGroup parent) {
final int index = getItem(pos);
final TextView textView;
if (convertView == null) {
textView = (TextView) _inflater.inflate(_layout, parent, false);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setMinHeight(_layoutHeight);
} else {
textView = (TextView) convertView;
}
if (textView instanceof Checkable) {
((Checkable) textView).setChecked(_selectedItems.contains(index));
}
if (index >= 0 && _dopt.iconsForData != null && index < _dopt.iconsForData.size() && _dopt.iconsForData.get(index) != 0) {
textView.setCompoundDrawablesWithIntrinsicBounds(_dopt.iconsForData.get(index), 0, 0, 0);
textView.setCompoundDrawablePadding(32);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.setCompoundDrawableTintList(ColorStateList.valueOf(_dopt.isDarkDialog ? Color.WHITE : Color.BLACK));
}
} else {
textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
final CharSequence text = _dopt.data.get(index).toString();
if (_dopt.highlightData != null) {
final boolean hl = _dopt.highlightData.contains(text);
textView.setTextColor(hl ? _dopt.highlightColor : _dopt.textColor);
textView.setTypeface(null, hl ? Typeface.BOLD : Typeface.NORMAL);
}
if (_dopt.highlighter != null) {
Spannable s = new SpannableString(text);
_dopt.highlighter.callback(s);
textView.setText(s);
} else {
textView.setText(text);
}
return textView;
}
@NonNull
@Override
public Filter getFilter() {
return new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(final CharSequence constraint, final FilterResults results) {
_filteredItems.clear();
_filteredItems.addAll((List<Integer>) results.values);
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(final CharSequence constraint) {
final List<Integer> resList = new ArrayList<>();
if (_dopt.data != null) {
final String fil = constraint.toString();
final boolean emptySearch = fil.isEmpty();
for (int i = 0; i < _dopt.data.size(); i++) {
final String str = _dopt.data.get(i).toString();
final boolean matchExtra = (_extraPattern == null) || _extraPattern.matcher(str).find();
final Locale locale = Locale.getDefault();
final boolean matchNormal = str.toLowerCase(locale).contains(fil.toLowerCase(locale));
final boolean matchRegex = _dopt.searchIsRegex && (str.matches(fil));
if (matchExtra && (matchNormal || matchRegex || emptySearch)) {
resList.add(i);
}
}
}
final FilterResults res = new FilterResults();
res.values = resList;
res.count = resList.size();
return res;
}
};
}
}
public static void showMultiChoiceDialogWithSearchFilterUI(final Activity activity, final DialogOptions dopt) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity, dopt.isDarkDialog
? android.support.v7.appcompat.R.style.Theme_AppCompat_Dialog
: android.support.v7.appcompat.R.style.Theme_AppCompat_Light_Dialog
);
final Adapter listAdapter = Adapter.create(activity, dopt);
final AppCompatEditText searchEditText = new AppCompatEditText(activity);
searchEditText.setText(dopt.defaultText);
searchEditText.setSingleLine(true);
searchEditText.setMaxLines(1);
searchEditText.setTextColor(dopt.textColor);
searchEditText.setHintTextColor((dopt.textColor & 0x00FFFFFF) | 0x99000000);
searchEditText.setHint(dopt.searchHintText);
searchEditText.setInputType(dopt.searchInputType == 0 ? searchEditText.getInputType() : dopt.searchInputType);
searchEditText.addTextChangedListener(TextWatcherDummy.after((cbEditable) -> listAdapter.getFilter().filter(cbEditable)));
final ContextUtils cu = new ContextUtils(activity);
final int margin = (int) cu.convertDpToPx(8);
cu.freeContextRef();
final LinearLayout searchLayout = new LinearLayout(activity);
searchLayout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams lp;
lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT, 1);
lp.gravity = Gravity.START | Gravity.BOTTOM;
searchLayout.addView(searchEditText, lp);
// 'Button to clear the search box'
final ImageView clearButton = new ImageView(activity);
clearButton.setImageResource(dopt.clearInputIcon);
TooltipCompat.setTooltipText(clearButton, activity.getString(android.R.string.cancel));
clearButton.setColorFilter(dopt.isDarkDialog ? Color.WHITE : Color.parseColor("#ff505050"));
lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT, 0);
lp.gravity = Gravity.END | Gravity.CENTER_VERTICAL;
lp.setMargins(margin, 0, (int) (margin * 1.5), 0);
searchLayout.addView(clearButton, lp);
clearButton.setOnClickListener((v) -> searchEditText.setText(""));
final ListView listView = new ListView(activity);
final LinearLayout linearLayout = new LinearLayout(activity);
listView.setAdapter(listAdapter);
listView.setVisibility(dopt.data != null && !dopt.data.isEmpty() ? View.VISIBLE : View.GONE);
linearLayout.setOrientation(LinearLayout.VERTICAL);
if (dopt.isSearchEnabled) {
lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(margin, margin / 2, margin, margin / 2);
linearLayout.addView(searchLayout, lp);
}
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0);
layoutParams.weight = 1;
linearLayout.addView(listView, layoutParams);
if (!TextUtils.isEmpty(dopt.messageText)) {
dialogBuilder.setMessage(dopt.messageText);
}
dialogBuilder.setView(linearLayout)
.setOnCancelListener(null)
.setNegativeButton(dopt.cancelButtonText, (dialogInterface, i) -> dialogInterface.dismiss());
if (dopt.titleText != 0) {
dialogBuilder.setTitle(dopt.titleText);
}
// Ok button action
if ((dopt.isSearchEnabled && dopt.callback != null) || (dopt.isMultiSelectEnabled)) {
dialogBuilder.setPositiveButton(dopt.okButtonText, (dialogInterface, i) -> {
final String searchText = dopt.isSearchEnabled ? searchEditText.getText().toString() : null;
if (dopt.positionCallback != null && !listAdapter._selectedItems.isEmpty()) {
final List<Integer> sel = new ArrayList<>(listAdapter._selectedItems);
Collections.sort(sel);
dopt.positionCallback.callback(sel);
} else if (dopt.callback != null && !TextUtils.isEmpty(searchText)) {
dopt.callback.callback(searchText);
}
});
}
// Setup neutralbutton
if (dopt.neutralButtonCallback != null && dopt.neutralButtonText != 0) {
dialogBuilder.setNeutralButton(dopt.neutralButtonText, (dialogInterface, i) -> {
dopt.neutralButtonCallback.callback();
});
}
final AlertDialog dialog = dialogBuilder.create();
searchEditText.setOnKeyListener((keyView, keyCode, keyEvent) -> {
if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
dialog.dismiss();
if (dopt.callback != null && !TextUtils.isEmpty(searchEditText.getText().toString())) {
dopt.callback.callback(searchEditText.getText().toString());
}
return true;
}
return false;
});
Window w;
if ((w = dialog.getWindow()) != null && dopt.isSearchEnabled) {
w.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
dialog.show();
if ((w = dialog.getWindow()) != null) {
int ds_w = dopt.dialogWidthDp < 100 ? dopt.dialogWidthDp : ((int) (dopt.dialogWidthDp * activity.getResources().getDisplayMetrics().density));
int ds_h = dopt.dialogHeightDp < 100 ? dopt.dialogHeightDp : ((int) (dopt.dialogHeightDp * activity.getResources().getDisplayMetrics().density));
w.setLayout(ds_w, ds_h);
}
if ((w = dialog.getWindow()) != null && dopt.gravity != Gravity.NO_GRAVITY) {
WindowManager.LayoutParams wlp = w.getAttributes();
wlp.gravity = dopt.gravity;
w.setAttributes(wlp);
}
if (dopt.isSearchEnabled) {
searchEditText.requestFocus();
}
if (dopt.defaultText != null) {
listAdapter.getFilter().filter(searchEditText.getText());
}
// Helper function to trigger callback with single item
final Callback.b1<Integer> directActivate = (position) -> {
final int index = listAdapter._filteredItems.get(position);
dialog.dismiss();
if (dopt.callback != null) {
dopt.callback.callback(dopt.data.get(index).toString());
}
if (dopt.positionCallback != null) {
dopt.positionCallback.callback(Collections.singletonList(index));
}
return true;
};
// Helper function to append selection count to OK button
final Button okButton = dialog.getButton(Dialog.BUTTON_POSITIVE);
final String okText = activity.getString(dopt.okButtonText) + (dopt.isMultiSelectEnabled ? " (%d)" : "");
final Callback.a0 setOkButtonState = () -> {
okButton.setText(okText.replace("%d", Integer.toString(listAdapter._selectedItems.size())));
};
// Set ok button text initially
setOkButtonState.callback();
// Item click action
listView.setOnItemClickListener((parent, textView, pos, id) -> {
if (dopt.isMultiSelectEnabled) {
final int index = listAdapter._filteredItems.get(pos);
if (listAdapter._selectedItems.contains(index)) {
listAdapter._selectedItems.remove(index);
} else {
listAdapter._selectedItems.add(index);
}
if (textView instanceof Checkable) {
((Checkable) textView).setChecked(listAdapter._selectedItems.contains(index));
}
setOkButtonState.callback();
} else {
directActivate.callback(pos);
}
});
// long click always activates
listView.setOnItemLongClickListener((parent, view, pos, id) -> directActivate.callback(pos));
}
}

View file

@ -1,21 +1,30 @@
/*
* ------------------------------------------------------------------------------
* Gregor Santner <gsantner.github.io> wrote this. You can do whatever you want
* with it. If we meet some day, and you think it is worth it, you can buy me a
* coke in return. Provided as is without any kind of warranty. Do not blame or
* sue me if something goes wrong. No attribution required. - Gregor Santner
/*#######################################################
*
* License: Creative Commons Zero (CC0 1.0)
* http://creativecommons.org/publicdomain/zero/1.0/
* ----------------------------------------------------------------------------
*/
* Maintained 2016-2023 by Gregor Santner <gsantner AT mailbox DOT org>
*
* License of this file: Apache 2.0
* https://www.apache.org/licenses/LICENSE-2.0
* https://github.com/gsantner/opoc/#licensing
*
#########################################################*/
package net.gsantner.opoc.util;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Build;
import android.provider.CalendarContract;
import android.support.annotation.ColorInt;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.text.Html;
@ -23,11 +32,16 @@ import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.ScrollView;
import java.util.List;
@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue", "SpellCheckingInspection"})
@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue", "SpellCheckingInspection", "rawtypes", "UnusedReturnValue"})
public class ActivityUtils extends net.gsantner.opoc.util.ContextUtils {
//########################
//## Members, Constructors
@ -39,6 +53,12 @@ public class ActivityUtils extends net.gsantner.opoc.util.ContextUtils {
_activity = activity;
}
@Override
public void freeContextRef() {
super.freeContextRef();
_activity = null;
}
//########################
//## Methods
//########################
@ -77,9 +97,11 @@ public class ActivityUtils extends net.gsantner.opoc.util.ContextUtils {
}
public void showSnackBar(@StringRes int stringResId, boolean showLong) {
Snackbar.make(_activity.findViewById(android.R.id.content), stringResId,
showLong ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT).show();
public Snackbar showSnackBar(@StringRes int stringResId, boolean showLong) {
Snackbar s = Snackbar.make(_activity.findViewById(android.R.id.content), stringResId,
showLong ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT);
s.show();
return s;
}
public void showSnackBar(@StringRes int stringResId, boolean showLong, @StringRes int actionResId, View.OnClickListener listener) {
@ -89,11 +111,58 @@ public class ActivityUtils extends net.gsantner.opoc.util.ContextUtils {
.show();
}
public void hideSoftKeyboard() {
InputMethodManager inputMethodManager = (InputMethodManager) _activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (_activity.getCurrentFocus() != null && _activity.getCurrentFocus().getWindowToken() != null) {
inputMethodManager.hideSoftInputFromWindow(_activity.getCurrentFocus().getWindowToken(), 0);
public ActivityUtils setSoftKeyboardVisibile(boolean visible, View... editView) {
final Activity activity = _activity;
if (activity != null) {
final View v = (editView != null && editView.length > 0) ? (editView[0]) : (activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null ? activity.getCurrentFocus() : null);
final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (v != null && imm != null) {
Runnable r = () -> {
if (visible) {
v.requestFocus();
imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
} else {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
};
r.run();
for (int d : new int[]{100, 350}) {
v.postDelayed(r, d);
}
}
}
return this;
}
public ActivityUtils hideSoftKeyboard() {
if (_activity != null) {
InputMethodManager imm = (InputMethodManager) _activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm != null && _activity.getCurrentFocus() != null && _activity.getCurrentFocus().getWindowToken() != null) {
imm.hideSoftInputFromWindow(_activity.getCurrentFocus().getWindowToken(), 0);
}
}
return this;
}
public ActivityUtils showSoftKeyboard() {
if (_activity != null) {
InputMethodManager imm = (InputMethodManager) _activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm != null && _activity.getCurrentFocus() != null && _activity.getCurrentFocus().getWindowToken() != null) {
showSoftKeyboard(_activity.getCurrentFocus());
}
}
return this;
}
public ActivityUtils showSoftKeyboard(View textInputView) {
if (_activity != null) {
InputMethodManager imm = (InputMethodManager) _activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm != null && textInputView != null) {
imm.showSoftInput(textInputView, InputMethodManager.SHOW_FORCED);
}
}
return this;
}
public void showDialogWithHtmlTextView(@StringRes int resTitleId, String html) {
@ -101,23 +170,37 @@ public class ActivityUtils extends net.gsantner.opoc.util.ContextUtils {
}
public void showDialogWithHtmlTextView(@StringRes int resTitleId, String text, boolean isHtml, DialogInterface.OnDismissListener dismissedListener) {
ScrollView scroll = new ScrollView(_context);
AppCompatTextView textView = new AppCompatTextView(_context);
int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16,
_context.getResources().getDisplayMetrics());
textView.setMovementMethod(new LinkMovementMethod());
textView.setPadding(padding, 0, padding, 0);
int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, _context.getResources().getDisplayMetrics());
scroll.setPadding(padding, 0, padding, 0);
scroll.addView(textView);
textView.setMovementMethod(new LinkMovementMethod());
textView.setText(isHtml ? new SpannableString(Html.fromHtml(text)) : text);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
AlertDialog.Builder dialog = new AlertDialog.Builder(_context)
.setPositiveButton(android.R.string.ok, null).setOnDismissListener(dismissedListener)
.setView(scroll);
if (resTitleId != 0) {
dialog.setTitle(resTitleId);
}
dialogFullWidth(dialog.show(), true, false);
}
public void showDialogWithRawFileInWebView(String fileInRaw, @StringRes int resTitleId) {
WebView wv = new WebView(_context);
wv.loadUrl("file:///android_res/raw/" + fileInRaw);
AlertDialog.Builder dialog = new AlertDialog.Builder(_context)
.setPositiveButton(android.R.string.ok, null)
.setOnDismissListener(dismissedListener)
.setTitle(resTitleId)
.setView(textView);
dialog.show();
.setView(wv);
dialogFullWidth(dialog.show(), true, false);
}
// Toggle with no param, else set visibility according to first bool
public void toggleStatusbarVisibility(boolean... optionalForceVisible) {
public ActivityUtils toggleStatusbarVisibility(boolean... optionalForceVisible) {
WindowManager.LayoutParams attrs = _activity.getWindow().getAttributes();
int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
if (optionalForceVisible.length == 0) {
@ -128,5 +211,136 @@ public class ActivityUtils extends net.gsantner.opoc.util.ContextUtils {
attrs.flags |= flag;
}
_activity.getWindow().setAttributes(attrs);
return this;
}
public ActivityUtils showGooglePlayEntryForThisApp() {
String pkgId = "details?id=" + _activity.getPackageName();
Intent goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("market://" + pkgId));
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
(Build.VERSION.SDK_INT >= 21 ? Intent.FLAG_ACTIVITY_NEW_DOCUMENT : Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
_activity.startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
_activity.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/" + pkgId)));
}
return this;
}
public ActivityUtils setStatusbarColor(int color, boolean... fromRes) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (fromRes != null && fromRes.length > 0 && fromRes[0]) {
color = ContextCompat.getColor(_context, color);
}
_activity.getWindow().setStatusBarColor(color);
}
return this;
}
public ActivityUtils setLauncherActivityEnabled(Class activityClass, boolean enable) {
try {
ComponentName component = new ComponentName(_context, activityClass);
_context.getPackageManager().setComponentEnabledSetting(component, enable ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
} catch (Exception ignored) {
}
return this;
}
public boolean isLauncherEnabled(Class activityClass) {
try {
ComponentName component = new ComponentName(_context, activityClass);
return _context.getPackageManager().getComponentEnabledSetting(component) != PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
} catch (Exception ignored) {
}
return false;
}
@ColorInt
public Integer getCurrentPrimaryColor() {
TypedValue typedValue = new TypedValue();
_context.getTheme().resolveAttribute(getResId(ResType.ATTR, "colorPrimary"), typedValue, true);
return typedValue.data;
}
@ColorInt
public Integer getCurrentPrimaryDarkColor() {
TypedValue typedValue = new TypedValue();
_context.getTheme().resolveAttribute(getResId(ResType.ATTR, "colorPrimaryDark"), typedValue, true);
return typedValue.data;
}
@ColorInt
public Integer getCurrentAccentColor() {
TypedValue typedValue = new TypedValue();
_context.getTheme().resolveAttribute(getResId(ResType.ATTR, "colorAccent"), typedValue, true);
return typedValue.data;
}
@ColorInt
public Integer getActivityBackgroundColor() {
TypedArray array = _activity.getTheme().obtainStyledAttributes(new int[]{
android.R.attr.colorBackground,
});
int c = array.getColor(0, 0xFF0000);
array.recycle();
return c;
}
public ActivityUtils startCalendarApp() {
Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
builder.appendPath("time");
builder.appendPath(Long.toString(System.currentTimeMillis()));
Intent intent = new Intent(Intent.ACTION_VIEW, builder.build());
_activity.startActivity(intent);
return this;
}
/**
* Detect if the activity is currently in splitscreen/multiwindow mode
*/
public boolean isInSplitScreenMode() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return _activity.isInMultiWindowMode();
}
return false;
}
/**
* Show dialog in full width / show keyboard
*
* @param dialog Get via dialog.show()
*/
public void dialogFullWidth(AlertDialog dialog, boolean fullWidth, boolean showKeyboard) {
try {
Window w;
if (dialog != null && (w = dialog.getWindow()) != null) {
if (fullWidth) {
w.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
}
if (showKeyboard) {
w.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
} catch (Exception ignored) {
}
}
// Make activity/app not show up in the recents history - call before finish / System.exit
public ActivityUtils removeActivityFromHistory() {
try {
ActivityManager am = (ActivityManager) _activity.getSystemService(Context.ACTIVITY_SERVICE);
if (am != null && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
List<ActivityManager.AppTask> tasks = am.getAppTasks();
if (tasks != null && !tasks.isEmpty()) {
tasks.get(0).setExcludeFromRecents(true);
}
}
} catch (Exception ignored) {
}
return this;
}
}

View file

@ -1,14 +1,12 @@
/*
* ---------------------------------------------------------------------------- *
* Gregor Santner <gsantner.github.io> wrote this file. You can do whatever
* you want with this stuff. If we meet some day, and you think this stuff is
* worth it, you can buy me a coke in return. Provided as is without any kind
* of warranty. No attribution required. - Gregor Santner
/*#######################################################
*
* License of this file: Creative Commons Zero (CC0 1.0)
* http://creativecommons.org/publicdomain/zero/1.0/
* ----------------------------------------------------------------------------
*/
* Maintained 2017-2023 by Gregor Santner <gsantner AT mailbox DOT org>
*
* License: Apache 2.0
* https://github.com/gsantner/opoc/#licensing
* https://www.apache.org/licenses/LICENSE-2.0
*
#########################################################*/
/*
* Place adblock hosts file in raw: src/main/res/raw/adblock_domains__xyz.txt
@ -47,8 +45,9 @@ import java.util.Set;
/**
* Simple Host-Based AdBlocker
*/
@SuppressWarnings({"WeakerAccess", "SpellCheckingInspection", "unused"})
@SuppressWarnings({"WeakerAccess", "SpellCheckingInspection", "unused", "TryFinallyCanBeTryWithResources"})
public class AdBlock {
private static final Object synchronizeObj = new Object();
private static final AdBlock instance = new AdBlock();
public static AdBlock getInstance() {
@ -62,7 +61,9 @@ public class AdBlock {
//########################
private final Set<String> _adblockHostsFromRaw = new HashSet<>();
private final Set<String> _adblockHosts = new HashSet<>();
private boolean _isLoaded;
private final List<Callback.b3<URI, String, String>> _customBlockCallbacks = new ArrayList<>();
private boolean _isLoaded = false;
private boolean _isAdblockLogging = false;
//########################
//##
@ -73,25 +74,47 @@ public class AdBlock {
}
public boolean isAdHost(String urlS) {
boolean block = false;
if (urlS != null && !urlS.isEmpty() && urlS.startsWith("http")) {
try {
URI url = new URI(urlS);
URI url;
try {
url = new URI(urlS);
} catch (Exception e) {
url = new URI(urlS.replaceFirst("[?].*", ""));
}
String host = url.getHost().trim();
if (host.startsWith("www.") && host.length() >= 4) {
host = host.substring(4);
}
return _adblockHosts.contains(host) || _adblockHosts.contains("www." + host);
block = _adblockHosts.contains(host) || _adblockHosts.contains("www." + host);
for (Callback.b3<URI, String, String> cb : _customBlockCallbacks) {
if (block) {
break;
}
try {
block = cb.callback(url, urlS, host);
} catch (Exception ignored) {
}
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return false;
if (_isAdblockLogging) {
Log.d(getClass().getSimpleName(), "UrlAllowed-" + (block ? "N" : "Y") + " " + urlS);
}
return block;
}
public AdBlock reset() {
_adblockHosts.clear();
_adblockHosts.addAll(_adblockHostsFromRaw);
synchronized (synchronizeObj) {
_adblockHosts.clear();
_adblockHosts.addAll(_adblockHostsFromRaw);
_customBlockCallbacks.clear();
}
return this;
}
@ -103,7 +126,7 @@ public class AdBlock {
return new WebResourceResponse("text/plain", "utf-8", new ByteArrayInputStream("".getBytes()));
}
public void addBlockedHosts(String... hosts) {
public AdBlock addBlockedHosts(String... hosts) {
for (String host : hosts) {
if (host != null) {
host = host.trim();
@ -111,23 +134,29 @@ public class AdBlock {
host = host.substring(4);
}
if (!host.startsWith("#") && !host.startsWith("\"")) {
_adblockHosts.add(host);
synchronized (synchronizeObj) {
_adblockHosts.add(host);
}
}
}
}
return this;
}
public void loadHostsFromRawAssetsAsync(final Context context) {
new Thread(new Runnable() {
@Override
public void run() {
try {
public void loadHostsFromRawAssetsAsync(final Context context, final boolean... debugIgnoreAssets) {
if (debugIgnoreAssets != null && debugIgnoreAssets.length > 0 && debugIgnoreAssets[0]) {
_isLoaded = true;
return;
}
new Thread(() -> {
try {
synchronized (synchronizeObj) {
loadHostsFromRawAssets(context);
_isLoaded = true;
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
@ -173,4 +202,17 @@ public class AdBlock {
}
return adblockResIds;
}
// URI uri, String url, String host
public AdBlock addCustomBlockCallback(Callback.b3<URI, String, String> cb) {
synchronized (synchronizeObj) {
_customBlockCallbacks.add(cb);
}
return this;
}
public AdBlock setLogEnabled(boolean isAdblockLogging) {
_isAdblockLogging = isAdblockLogging;
return this;
}
}

View file

@ -1,408 +0,0 @@
/*
* ------------------------------------------------------------------------------
* Gregor Santner <gsantner.github.io> wrote this. You can do whatever you want
* with it. If we meet some day, and you think it is worth it, you can buy me a
* coke in return. Provided as is without any kind of warranty. Do not blame or
* sue me if something goes wrong. No attribution required. - Gregor Santner
*
* License: Creative Commons Zero (CC0 1.0)
* http://creativecommons.org/publicdomain/zero/1.0/
* ----------------------------------------------------------------------------
*/
/*
* This is a wrapper for settings based on SharedPreferences
* with keys in resources. Extend from this class and add
* getters/setters for the app's settings.
* Example:
public boolean isAppFirstStart(boolean doSet) {
boolean value = getBool(prefApp, R.string.pref_key__app_first_start, true);
if (doSet) {
setBool(prefApp, R.string.pref_key__app_first_start, false);
}
return value;
}
public boolean isAppCurrentVersionFirstStart(boolean doSet) {
int value = getInt(prefApp, R.string.pref_key__app_first_start_current_version, -1);
if (doSet) {
setInt(prefApp, R.string.pref_key__app_first_start_current_version, BuildConfig.VERSION_CODE);
}
return value != BuildConfig.VERSION_CODE && !BuildConfig.IS_TEST_BUILD;
}
* Maybe add a singleton for this:
* Whereas App.get() is returning ApplicationContext
private AppSettings(Context _context) {
super(_context);
}
public static AppSettings get() {
return new AppSettings(App.get());
}
*/
package net.gsantner.opoc.util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.ColorRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Wrapper for settings based on SharedPreferences with keys in resources
* Default SharedPreference (_prefApp) will be taken if no SP is specified, else the first one
*/
@SuppressWarnings({"WeakerAccess", "unused", "SpellCheckingInspection", "SameParameterValue"})
public class AppSettingsBase {
protected static final String ARRAY_SEPARATOR = "%%%";
protected static final String ARRAY_SEPARATOR_SUBSTITUTE = "§§§";
public static final String SHARED_PREF_APP = "app";
//########################
//## Members, Constructors
//########################
protected final SharedPreferences _prefApp;
protected final String _prefAppName;
protected final Context _context;
public AppSettingsBase(final Context context) {
this(context, SHARED_PREF_APP);
}
public AppSettingsBase(final Context context, final String prefAppName) {
_context = context.getApplicationContext();
_prefAppName = TextUtils.isEmpty(prefAppName) ?
_context.getPackageName() + "_preferences" : prefAppName;
_prefApp = _context.getSharedPreferences(_prefAppName, Context.MODE_PRIVATE);
}
//#####################
//## Methods
//#####################
public Context getContext() {
return _context;
}
public boolean isKeyEqual(String key, int stringKeyResourceId) {
return key.equals(rstr(stringKeyResourceId));
}
public void resetSettings() {
resetSettings(_prefApp);
}
@SuppressLint("ApplySharedPref")
public void resetSettings(final SharedPreferences pref) {
pref.edit().clear().commit();
}
public boolean isPrefSet(@StringRes int stringKeyResourceId) {
return isPrefSet(_prefApp, stringKeyResourceId);
}
public boolean isPrefSet(final SharedPreferences pref, @StringRes int stringKeyResourceId) {
return pref.contains(rstr(stringKeyResourceId));
}
public void registerPreferenceChangedListener(SharedPreferences.OnSharedPreferenceChangeListener value) {
registerPreferenceChangedListener(_prefApp, value);
}
public void registerPreferenceChangedListener(final SharedPreferences pref, SharedPreferences.OnSharedPreferenceChangeListener value) {
pref.registerOnSharedPreferenceChangeListener(value);
}
public void unregisterPreferenceChangedListener(SharedPreferences.OnSharedPreferenceChangeListener value) {
unregisterPreferenceChangedListener(_prefApp, value);
}
public void unregisterPreferenceChangedListener(final SharedPreferences pref, SharedPreferences.OnSharedPreferenceChangeListener value) {
pref.unregisterOnSharedPreferenceChangeListener(value);
}
public SharedPreferences getDefaultPreferences() {
return _prefApp;
}
public SharedPreferences.Editor getDefaultPreferencesEditor() {
return _prefApp.edit();
}
public String getDefaultPreferencesName() {
return _prefAppName;
}
private SharedPreferences gp(final SharedPreferences... pref) {
return (pref != null && pref.length > 0 ? pref[0] : _prefApp);
}
//#################################
//## Getter for resources
//#################################
public String rstr(@StringRes int stringKeyResourceId) {
return _context.getString(stringKeyResourceId);
}
public int rcolor(@ColorRes int resColorId) {
return ContextCompat.getColor(_context, resColorId);
}
//#################################
//## Getter & Setter for String
//#################################
public void setString(@StringRes int keyResourceId, String value, final SharedPreferences... pref) {
gp(pref).edit().putString(rstr(keyResourceId), value).apply();
}
public void setString(String key, String value, final SharedPreferences... pref) {
gp(pref).edit().putString(key, value).apply();
}
public void setString(@StringRes int keyResourceId, @StringRes int defaultValueResourceId, final SharedPreferences... pref) {
gp(pref).edit().putString(rstr(keyResourceId), rstr(defaultValueResourceId)).apply();
}
public String getString(@StringRes int keyResourceId, String defaultValue, final SharedPreferences... pref) {
return gp(pref).getString(rstr(keyResourceId), defaultValue);
}
public String getString(@StringRes int keyResourceId, @StringRes int defaultValueResourceId, final SharedPreferences... pref) {
return gp(pref).getString(rstr(keyResourceId), rstr(defaultValueResourceId));
}
public String getString(String key, String defaultValue, final SharedPreferences... pref) {
return gp(pref).getString(key, defaultValue);
}
public String getString(@StringRes int keyResourceId, String defaultValue, @StringRes int keyResourceIdDefaultValue, final SharedPreferences... pref) {
return gp(pref).getString(rstr(keyResourceId), rstr(keyResourceIdDefaultValue));
}
public void setStringArray(@StringRes int keyResourceId, Object[] values, final SharedPreferences... pref) {
setStringArray(rstr(keyResourceId), values, gp(pref));
}
public void setStringArray(String key, Object[] values, final SharedPreferences... pref) {
setStringArray(key, values, gp(pref));
}
private void setStringArray(String key, Object[] values, final SharedPreferences pref) {
StringBuilder sb = new StringBuilder();
for (Object value : values) {
sb.append(ARRAY_SEPARATOR);
sb.append(value.toString().replace(ARRAY_SEPARATOR, ARRAY_SEPARATOR_SUBSTITUTE));
}
setString(key, sb.toString().replaceFirst(ARRAY_SEPARATOR, ""), pref);
}
@NonNull
public String[] getStringArray(@StringRes int keyResourceId, final SharedPreferences... pref) {
return getStringArray(rstr(keyResourceId), gp(pref));
}
private String[] getStringArray(String key, final SharedPreferences... pref) {
String value = gp(pref)
.getString(key, ARRAY_SEPARATOR)
.replace(ARRAY_SEPARATOR_SUBSTITUTE, ARRAY_SEPARATOR);
if (value.equals(ARRAY_SEPARATOR)) {
return new String[0];
}
return value.split(ARRAY_SEPARATOR);
}
public void setStringList(@StringRes int keyResourceId, List<String> values, final SharedPreferences... pref) {
setStringArray(rstr(keyResourceId), values.toArray(new String[values.size()]), pref);
}
public void setStringList(String key, List<String> values, final SharedPreferences... pref) {
setStringArray(key, values.toArray(new String[values.size()]), pref);
}
public ArrayList<String> getStringList(@StringRes int keyResourceId, final SharedPreferences... pref) {
return new ArrayList<>(Arrays.asList(getStringArray(rstr(keyResourceId), gp(pref))));
}
public ArrayList<String> getStringList(String key, final SharedPreferences... pref) {
return new ArrayList<>(Arrays.asList(getStringArray(key, gp(pref))));
}
//#################################
//## Getter & Setter for integer
//#################################
public void setInt(@StringRes int keyResourceId, int value, final SharedPreferences... pref) {
gp(pref).edit().putInt(rstr(keyResourceId), value).apply();
}
public void setInt(String key, int value, final SharedPreferences... pref) {
gp(pref).edit().putInt(key, value).apply();
}
public int getInt(@StringRes int keyResourceId, int defaultValue, final SharedPreferences... pref) {
return gp(pref).getInt(rstr(keyResourceId), defaultValue);
}
public int getInt(String key, int defaultValue, final SharedPreferences... pref) {
return gp(pref).getInt(key, defaultValue);
}
public int getIntOfStringPref(@StringRes int keyResId, int defaultValue, final SharedPreferences... pref) {
return getIntOfStringPref(rstr(keyResId), defaultValue, gp(pref));
}
public int getIntOfStringPref(String key, int defaultValue, final SharedPreferences... pref) {
String strNum = getString(key, Integer.toString(defaultValue), gp(pref));
return Integer.valueOf(strNum);
}
public void setIntArray(@StringRes int keyResourceId, Object[] values, final SharedPreferences... pref) {
setIntArray(rstr(keyResourceId), values, gp(pref));
}
public void setIntArray(String key, Object[] values, final SharedPreferences... pref) {
setIntArray(key, values, gp(pref));
}
private void setIntArray(String key, Object[] values, final SharedPreferences pref) {
StringBuilder sb = new StringBuilder();
for (Object value : values) {
sb.append(ARRAY_SEPARATOR);
sb.append(value.toString());
}
setString(key, sb.toString().replaceFirst(ARRAY_SEPARATOR, ""), pref);
}
@NonNull
public Integer[] getIntArray(@StringRes int keyResourceId, final SharedPreferences... pref) {
return getIntArray(rstr(keyResourceId), gp(pref));
}
private Integer[] getIntArray(String key, final SharedPreferences... pref) {
String value = gp(pref).getString(key, ARRAY_SEPARATOR);
if (value.equals(ARRAY_SEPARATOR)) {
return new Integer[0];
}
String[] split = value.split(ARRAY_SEPARATOR);
Integer[] ret = new Integer[split.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = Integer.parseInt(split[i]);
}
return ret;
}
public void setIntList(@StringRes int keyResourceId, List<Integer> values, final SharedPreferences... pref) {
setIntArray(rstr(keyResourceId), values.toArray(new Integer[values.size()]), pref);
}
public void setIntList(String key, List<Integer> values, final SharedPreferences... pref) {
setIntArray(key, values.toArray(new Integer[values.size()]), pref);
}
public ArrayList<Integer> getIntList(@StringRes int keyResourceId, final SharedPreferences... pref) {
return new ArrayList<>(Arrays.asList(getIntArray(rstr(keyResourceId), gp(pref))));
}
public ArrayList<Integer> getIntList(String key, final SharedPreferences... pref) {
return new ArrayList<>(Arrays.asList(getIntArray(key, gp(pref))));
}
//#################################
//## Getter & Setter for Long
//#################################
public void setLong(@StringRes int keyResourceId, long value, final SharedPreferences... pref) {
gp(pref).edit().putLong(rstr(keyResourceId), value).apply();
}
public void setLong(String key, long value, final SharedPreferences... pref) {
gp(pref).edit().putLong(key, value).apply();
}
public long getLong(@StringRes int keyResourceId, long defaultValue, final SharedPreferences... pref) {
return gp(pref).getLong(rstr(keyResourceId), defaultValue);
}
public long getLong(String key, long defaultValue, final SharedPreferences... pref) {
return gp(pref).getLong(key, defaultValue);
}
//#################################
//## Getter & Setter for Float
//#################################
public void setFloat(@StringRes int keyResourceId, float value, final SharedPreferences... pref) {
gp(pref).edit().putFloat(rstr(keyResourceId), value).apply();
}
public void setFloat(String key, float value, final SharedPreferences... pref) {
gp(pref).edit().putFloat(key, value).apply();
}
public float getFloat(@StringRes int keyResourceId, float defaultValue, final SharedPreferences... pref) {
return gp(pref).getFloat(rstr(keyResourceId), defaultValue);
}
public float getFloat(String key, float defaultValue, final SharedPreferences... pref) {
return gp(pref).getFloat(key, defaultValue);
}
//#################################
//## Getter & Setter for Double
//#################################
public void setDouble(@StringRes int keyResourceId, double value, final SharedPreferences... pref) {
setLong(rstr(keyResourceId), Double.doubleToRawLongBits(value));
}
public void setDouble(String key, double value, final SharedPreferences... pref) {
setLong(key, Double.doubleToRawLongBits(value));
}
public double getDouble(@StringRes int keyResourceId, double defaultValue, final SharedPreferences... pref) {
return getDouble(rstr(keyResourceId), defaultValue, gp(pref));
}
public double getDouble(String key, double defaultValue, final SharedPreferences... pref) {
return Double.longBitsToDouble(getLong(key, Double.doubleToRawLongBits(defaultValue), gp(pref)));
}
//#################################
//## Getter & Setter for boolean
//#################################
public void setBool(@StringRes int keyResourceId, boolean value, final SharedPreferences... pref) {
gp(pref).edit().putBoolean(rstr(keyResourceId), value).apply();
}
public void setBool(String key, boolean value, final SharedPreferences... pref) {
gp(pref).edit().putBoolean(key, value).apply();
}
public boolean getBool(@StringRes int keyResourceId, boolean defaultValue, final SharedPreferences... pref) {
return gp(pref).getBoolean(rstr(keyResourceId), defaultValue);
}
public boolean getBool(String key, boolean defaultValue, final SharedPreferences... pref) {
return gp(pref).getBoolean(key, defaultValue);
}
//#################################
//## Getter & Setter for Color
//#################################
public int getColor(String key, @ColorRes int defaultColor, final SharedPreferences... pref) {
return gp(pref).getInt(key, rcolor(defaultColor));
}
public int getColor(@StringRes int keyResourceId, @ColorRes int defaultColor, final SharedPreferences... pref) {
return gp(pref).getInt(rstr(keyResourceId), rcolor(defaultColor));
}
}

View file

@ -0,0 +1,86 @@
/*#######################################################
*
* Maintained 2018-2023 by Gregor Santner <gsantner AT mailbox DOT org>
*
* License of this file: Apache 2.0
* https://www.apache.org/licenses/LICENSE-2.0
* https://github.com/gsantner/opoc/#licensing
*
#########################################################*/
package net.gsantner.opoc.util;
@SuppressWarnings("unused")
public class Callback {
public interface a0 {
void callback();
}
public interface a1<A> {
void callback(A arg1);
}
public interface a2<A, B> {
void callback(A arg1, B arg2);
}
public interface a3<A, B, C> {
void callback(A arg1, B arg2, C arg3);
}
public interface a4<A, B, C, D> {
void callback(A arg1, B arg2, C arg3, D arg4);
}
public interface a5<A, B, C, D, E> {
void callback(A arg1, B arg2, C arg3, D arg4, E arg5);
}
public interface b0 {
boolean callback();
}
public interface b1<A> {
boolean callback(A arg1);
}
public interface b2<A, B> {
boolean callback(A arg1, B arg2);
}
public interface b3<A, B, C> {
boolean callback(A arg1, B arg2, C arg3);
}
public interface b4<A, B, C, D> {
boolean callback(A arg1, B arg2, C arg3, D arg4);
}
public interface b5<A, B, C, D, E> {
boolean callback(A arg1, B arg2, C arg3, D arg4, E arg5);
}
public interface s0 {
String callback();
}
public interface s1<A> {
String callback(A arg1);
}
public interface s2<A, B> {
String callback(A arg1, B arg2);
}
public interface s3<A, B, C> {
String callback(A arg1, B arg2, C arg3);
}
public interface s4<A, B, C, D> {
String callback(A arg1, B arg2, C arg3, D arg4);
}
public interface s5<A, B, C, D, E> {
String callback(A arg1, B arg2, C arg3, D arg4, E arg5);
}
}

Some files were not shown because too many files have changed in this diff Show more