diff --git a/.atomignore b/.atomignore
new file mode 100755
index 00000000..033e25f6
--- /dev/null
+++ b/.atomignore
@@ -0,0 +1,23 @@
+.git
+.github
+.gradle
+.idea
+build
+gradle
+.gitlab-ci.yml
+*.iml
+local.properties
+settings.gradle
+gradlew
+gradlew.bat
+LICENSE.md
+app/build
+app/.gitignore
+app/pom.xml
+app/proguard-rules.pro
+.hidden
+.travis.yml
+circle.yml
+CODE_OF_CONDUCT*
+gradle.properties
+LICENSE*
diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
index f33f53b0..5ac91667 100644
--- a/.github/ISSUE_TEMPLATE.md
+++ b/.github/ISSUE_TEMPLATE.md
@@ -1,40 +1,24 @@
#### General information
-* **Device:** eg Nexus 5, Samsung Galaxy S6
-* **Android Version:** eg Android 6.0.1 Stock or Android 4.2 CM
-* **Pod:** eg pod.geraspora.de, self hosted
-* **Diaspora pod version:** eg 0.5.99.0-p9bd2337c (can be found on the bottom)
-* **App source:** eg HEAD, F-Droid, PlayStore, self build (latest HEAD)
-* **App version:** eg 0.1.1, or commit
+* **App version:**
+* **System:**
+* **Pod:**
+#### Description
+
+
+#### Log
-
-#### 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:
-``
-
-
-#### Debug output
-
-Please post the output of adb logcat. The log should begin with the start of Diaspora for Android and include all the steps it takes to reproduce the problem.
-
-````
-adb logcat -s com.github.dfa.diaspora_android
-````
diff --git a/.github/PULL_REQUEST_TEMPLATE b/.github/PULL_REQUEST_TEMPLATE
new file mode 100644
index 00000000..863cd426
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE
@@ -0,0 +1,27 @@
+
+
+
+
+
+
+
diff --git a/.github/workflows/build-android-project.yml b/.github/workflows/build-android-project.yml
new file mode 100644
index 00000000..07923101
--- /dev/null
+++ b/.github/workflows/build-android-project.yml
@@ -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
diff --git a/.gitignore b/.gitignore
index 60b55eeb..59057232 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,39 +1,76 @@
-*~
+##############
+### Common ###
+*~*
+tmp/
+*.tmp
+*.bak
+*.log
-# Gradle
-.gradle/
+################
+### Intellij ###
+# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio
+*.iml
+/out/
+
+.idea/
+# if you remove the above rule, at least ignore the following:
+## User-specific stuff:
+# .idea/workspace.xml
+# .idea/tasks.xml
+# .idea/dictionaries
+## Sensitive or high-churn files:
+# .idea/dataSources.ids
+# .idea/dataSources.xml
+# .idea/sqlDataSources.xml
+# .idea/dynamic.xml
+# .idea/uiDesigner.xml
+
+# Gradle:
+# .idea/gradle.xml
+# .idea/libraries
+
+## File-based project format:
+*.ipr
+*.iws
+
+### Gradle ###
.gradle
build/
-/*/build/
+dist/
+gradle-app.setting
-# User-specific configurations
-local.properties
-crowdin.yaml
+# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
+!gradle-wrapper.jar
-.idea
-.idea/libraries/
-.idea/runConfigurations.xml
-.idea/gradle.xml
-.idea/workspace.xml
-.idea/tasks.xml
-.idea/.name
-.idea/compiler.xml
-.idea/copyright/profiles_settings.xml
-.idea/encodings.xml
-.idea/misc.xml
-.idea/modules.xml
-.idea/scopes/scope_settings.xml
-.idea/vcs.xml
-*.iml
+###############
+### Eclipse ###
+#.project
+*.pydevproject
+.metadata
+*.swp
+*~.nib
+.settings/
+.loadpath
+.externalToolBuilders/
+*.launch
+.cproject
+.classpath
+.factorypath
+.buildpath
+.target
+.texlipse
-# OS-specific files
-.DS_Store
-.DS_Store?
-._*
-.Trashes
-ehthumbs.db
-Thumbs.db
+############
+### Java ###
+*.class
+.mtj.tmp/
+*.jar
+*.war
+*.ear
+hs_err_pid*
+###############
+### Android ###
# Built application files
*.apk
*.ap_
@@ -41,14 +78,27 @@ Thumbs.db
# Files for the Dalvik VM
*.dex
-# Java class files
-*.class
-
# Generated files
bin/
gen/
+# Local configuration file (sdk path, etc)
local.properties
+
+# Proguard
proguard/
-*.log
+
+# 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
+
diff --git a/.hidden b/.hidden
index 8a68f745..51b5ac34 100755
--- a/.hidden
+++ b/.hidden
@@ -1,4 +1,3 @@
-build
crowdin.yaml
diaspora-android.iml
gradle
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 74b79b85..00000000
--- a/.travis.yml
+++ /dev/null
@@ -1,32 +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.1
- - 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="lintDebug"
- - TASK="build check --stacktrace"
-
-branches:
- except:
- - l10n_master
-notifications:
- webhooks:
- urls:
- - https://webhooks.gitter.im/e/e462044d3105a7bb4b4f
- 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
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8cd034ec..a5861d19 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,162 @@
-# v0.2.0 (WIP)
+### 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.
-# v0.1.5
+### 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
+
+### v1.0.4
+- Updated: README
+- Added: Hide statusbar option
+- Fixed: Language list
+- Added: Sardinian,Malayalam,Turkish translation
+
+### v1.0.3
+- Update opoc
+- Better visibility for counter badge
+- Refactor DiasporaPod model
+- Update PodList (many new pods!)
+- Fix CustomTab bug
+
+### v1.0.2 (2017-08-05)
+- Improve build script
+- Update translation file license
+
+### v1.0.1 (2017-07-30)
+- Update SimpleMarkdownParser
+- Move untranslatable strings
+
+### v1.0.0 (2017-06-14)
+- Added AMOLED mode
+- Improve NavDrawer
+- Improve Shared by notice
+- Use opoc/Helpers,AdBlock
+
+### v0.2.7 (2017-05-26)
+- Small improvements
+
+### v0.2.6 (2017-05-03)
+- Fixed #156 #158 #159
+- Added chinese traditional language
+- Added NavSlider option: Statistics
+- Changed shared-by-notice text
+- Fix bottom bar hint text background color (Fix #157)
+- Color improvements
+
+### v0.2.5 (2017-04-10)
+- Introduce minimalistic Markdown Parser
+- Show LICENSE at first start
+- Show CHANGELOG after update
+- Convert existing Markup files to Markdown
+- Update existing markdown files
+- Update AboutActivity to use new Parser
+- Added translations: Danish, Korean, Galician
+
+### v0.2.4 (2017-03-19)
+- Different icon and color for secondlion
+- Language switcher
+- Handle dia.so links
+- Improve security at internal browser decision
+- More icons for notification dropdown
+- Update gradle build scripts
+- Added CircleCI
+
+### v0.2.3 (2017-02-24)
+- Add Czech translation (thanks @bezcitu)
+- Add option to copy image urls to clipboard
+- Fixed some bugs related to image upload/download
+- Published secondlion\* (nighly version of dandelion\*)
+
+### v0.2.2
+- Move "toggle mobile/deskop" to nav-slider
+- Reduce messages sent via broadcast
+- Allow to jump to last visited page on stream
+- New language: Hungarian
+- FIX NullPtr in shared text methods
+- FIX #117 - Reset NavHeader on change account, reset web profile
+- FIX #92 Roation settings
+- FIX #111 Remove legacy code
+
+### v0.2.1
+- App name changed to **dandelion***
+- Rotation options
+- Top toolbar loads screen again (toggleable in settings)
+- Fixed overlapping fragments
+- Visual rework of the About-section of the app
+
+### v0.2.0a
+- Added: Customizable Theme Colors!
+- Improved account setup with easy tor hidden service configuration
+- Eye candy for the settings activity
+- Added: "Contacts" shortcut in the navigation slider
+- Increased the overall performance by using Fragments
+- Lots of bugfixes
+- Fixes for the bugfixes!
+
+### v0.1.6
+- Added: New languages
+- Changed: New delicious visual style + launcher icon
+- Changed: Notifications-/Messages-indicator does now display number of events!
+- Changed: Redesigned Navigation Drawer
+- Fixed: Immediately apply preference changes
+- Added: About screen that shows useful information
+- Changed: Updated NetCipher library to 2.0.0-alpha1
+- Fixed: Do not reload stream on orientation changes
+- Fixed: Image upload for older devices
+- Added: Option to open external links in Chrome CustomTab
+
+### v0.1.5
- Update title depending on what the user is doing
- New greenish color scheme
- Replaced SwipeToRefresh functionality with refresh button
@@ -15,7 +171,7 @@
- Allow slider customization
- Show aspect name after selection
-# v0.1.4 (2016-07-31)
+### v0.1.4 (2016-07-31)
- by @vanitasvitae, @gsantner, @di72nn
- Allow turning off toolbar intellihide
- Handle links from browseable intent filter #38
@@ -30,7 +186,7 @@
- Share screenshot fix; Minor Aspects rework
- Update to SDK 24 (Android N)
-# v0.1.3 (2016-07-04)
+### v0.1.3 (2016-07-04)
- Added titles on top toolbar (by @scoute-dich)
- Made bottom toolbar automatically disappear
- Added option to share images to external app
@@ -41,7 +197,7 @@
- Removed swipe-to-refresh functionality in some places
- Big thanks and good luck to @scoute-dich and @martinchodev for accompanying this project :)
-# v0.1.2 (2016-06-05)
+### v0.1.2 (2016-06-05)
- Extract and show aspects (by @gsantner)
- Cache last podlist
- Better sharing from app
@@ -54,7 +210,7 @@
- Lots of refactoring; Reworked Splash,PodSelectionActivity; Switch Pod; Clear settings;
- Activity transitions, usability MainActivity, green accent color
-# v0.1.1
+### v0.1.1
- Sharing updated (by @scoute-dich)
- Screenshotting updated
- Gitter integration (by @gsantner)
@@ -64,8 +220,8 @@
- Travis CI integration
- Bump Gradle, Build-Tools, Libs to Android Studio 2.1 defaults
-# v0.1.0 (Diaspora for Android)
-First version of the organization *Diaspora for Android*
+### v0.1.0 (Diaspora for Android)
+First version of the organization *Diaspora for Android*
Consists mostly of code from:
- Diaspora-Native-Webapp (by @martinchodev )
- scoutedich additions (by @scoute-dich)
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 00000000..47984ecf
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,74 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as
+contributors and maintainers pledge to making participation in our project and
+our community a harassment-free experience for everyone, regardless of age, body
+size, disability, ethnicity, gender identity and expression, level of experience,
+nationality, personal appearance, race, religion, or sexual identity and
+orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment
+include:
+
+* Using welcoming and inclusive language
+* Being respectful of differing viewpoints and experiences
+* Gracefully accepting constructive criticism
+* Focusing on what is best for the community
+* Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+* The use of sexualized language or imagery and unwelcome sexual attention or
+advances
+* Trolling, insulting/derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or electronic
+ address, without explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable
+behavior and are expected to take appropriate and fair corrective action in
+response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or
+reject comments, commits, code, wiki edits, issues, and other contributions
+that are not aligned to this Code of Conduct, or to ban temporarily or
+permanently any contributor for other behaviors that they deem inappropriate,
+threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies both within project spaces and in public spaces
+when an individual is representing the project or its community. Examples of
+representing a project or community include using an official project e-mail
+address, posting via an official social media account, or acting as an appointed
+representative at an online or offline event. Representation of a project may be
+further defined and clarified by project maintainers.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported by contacting the project team at . All
+complaints will be reviewed and investigated and will result in a response that
+is deemed necessary and appropriate to the circumstances. The project team is
+obligated to maintain confidentiality with regard to the reporter of an incident.
+Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good
+faith may face temporary or permanent repercussions as determined by other
+members of the project's leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
+available at [http://contributor-covenant.org/version/1/4][version]
+
+[homepage]: http://contributor-covenant.org
+[version]: http://contributor-covenant.org/version/1/4/
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
deleted file mode 100644
index 71824d42..00000000
--- a/CONTRIBUTING.md
+++ /dev/null
@@ -1,6 +0,0 @@
-We are always open for any kind of contribution. (PR's, bug reports, feature requests, translations, ..)
-If you got any questions feel free to join our XMPP/Jabber conference at `diaspora-android@conference.jabberhead.tk` or [Gitter](https://gitter.im/Diaspora-for-Android/diaspora-android).
-Note that the main project members are mostly busy with their job/university/school and may not react or start coding immediately.
-
-We use Crowdin to translate Diaspora for Android. Join our project here:
-If your desired language is not listed please contact the maintainers/owner.
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
new file mode 100644
index 00000000..16e6a136
--- /dev/null
+++ b/CONTRIBUTORS.md
@@ -0,0 +1,32 @@
+
+* **[Gregor Santner](http://github.com/gsantner)** ~° Development of dandelion
+* **[Paul Schaub](https://github.com/vanitasvitae)** ~° Development of dandelion
+* **[Martín Vukovic](martinvukovic AT protonmail DOT com)** ~° Diaspora Native WebApp
+* **[Gaukler Faun](https://github.com/scoute-dich)** ~° Diaspora Native WebApp additions
+* **[Airon90](https://diasp.eu/u/airon90)** ~° Italian translation
+* **[Nacho Fernández](nacho_f AT joindiaspora DOT com)** ~° Spanish translation
+* **[Naofumi Fukue](https://github.com/naofum)** ~° Japanese translation
+* **[pskosinski](email AT pskosinski DOT pl)** ~° Polish translation
+* **[SansPseudoFix](https://github.com/SansPseudoFix)** ~° French translation
+* **[Zsolt Szakács](maxigaz AT diaspora DOT zone)** ~° Hungarian translation
+* **[Luís F.S. Rosa](https://github.com/luisfsr)** ~° Brazilian Portuguese translation
+* **[Danilo Raffaelli](https://crowdin.com/profile/Daraf)** ~° Italian translation
+* **[Âng Iōngchun](https://pubpod.alqualonde.org/u/iongchun)** ~° Chinese traditional translation
+* **[Mikkel Kirkgaard Nielsen](http://www.mikini.dk)** ~° Danish translation
+* **[Jean Lucas](jean AT 4ray DOT co)** ~° Spanish translation
+* **[asereze](https://github.com/asereze)** ~° Sardinian translation
+* **[Xosé M. Lamas](http://xmgz.eu)** ~° Galician translation
+* **[massimiliano](https://framagit.org/massimiliano)** ~° Contributor
diff --git a/LICENSE.md b/LICENSE.md
index 7dce67d7..4292c03f 100644
--- a/LICENSE.md
+++ b/LICENSE.md
@@ -1,18 +1,25 @@
-# App
-
-This program is free software: you can redistribute it and/or modify
+# dandelion\*
+`---------------`
+This program 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.
+(at your option) any later version.
This program 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.
+GNU General Public License for more details.
You should have received a copy of the GNU General Public License
-along with this program. If not, see http://www.gnu.org/licenses/.
+along with this program. If not, see https://www.gnu.org/licenses/.
+`---------------`
+If you want to publish dandelion\* in an app store, you have to change the app name (dandelion\*), package name & launcher icon (blue). See "7. Additional Terms" of GPL.
+You also have to provide the modifications in source code somewhere online for free. This is explicitly not about building the app and sharing with some friends, it's about app stores.
+The reason is, that most app stores allow an app id just once, which would block our uploads if somebody else uploaded. Also, we want to keep control on where the app is published, and want to make sure there is no malware in it.
+The F-Droid project team is explicitly allowed to publish dandelion\* without listed required modifications above at official F-Droid repository.
-# Splashscreen-Images
-The splashscreen images can be found on [flickr](https://www.flickr.com/photos/129581906@N06/sets/72157651933980136/with/16594947123/).
+## Miscellaneous
+
+We took some inspiration and code from LeafPic. Go check it out, its free software as well!
+
diff --git a/Makefile b/Makefile
new file mode 100644
index 00000000..09b21c00
--- /dev/null
+++ b/Makefile
@@ -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 "@@' | sed 's@@@' | 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 "-----------------------------------------------------------------------------------"
+
diff --git a/NEWS.md b/NEWS.md
new file mode 100644
index 00000000..6139d132
--- /dev/null
+++ b/NEWS.md
@@ -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
diff --git a/README.md b/README.md
index dce5cb81..a061ee60 100644
--- a/README.md
+++ b/README.md
@@ -1,43 +1,81 @@
-[](https://f-droid.org/repository/browse/?fdid=com.github.dfa.diaspora_android)
+[](https://github.com/gsantner/dandelion/releases)
+[](https://github.com/gsantner/dandelion/releases)
+[](https://crowdin.com/project/diaspora-for-android/invite)
+[](https://matrix.to/#/#dandelion:matrix.org)
+[](https://github.com/gsantner/dandelion/actions)
+[](https://www.codacy.com/app/gsantner/dandelion)
-[](https://travis-ci.org/Diaspora-for-Android/diaspora-android)
-[](https://crowdin.com/project/diaspora-for-android)
-[](https://gitter.im/Diaspora-for-Android/diaspora-android?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+# dandelion\*
+
+This is an unofficial webview based client for the community-run, distributed social network diaspora*.
+
+
-# Diaspora for Android
+## Description
+This is an unofficial webview based client for the community-run, distributed social network diaspora*.
+It's currently under development and should be used with that in mind. Please submit any bugs you might find.
-This is an unofficial webview based client for the community-run, distributed social network **[Diaspora](https://joindiaspora.com/)**. It's currently under development and should be used with that in mind. Please submit any bugs you might find.
-**Notice:** This is the repo of the latest version of the unoffical Diaspora Android App.
+#### WebApp
+The app is developed as a WebApp because currently diaspora\* doesn't have an functional API that can be used to create a native interface to retrieve the user's data, publications, direct messages and so on. That's why there are currently only WebApps for diaspora\* out there.
+[Stay tuned on diaspora\* issues](https://github.com/diaspora/diaspora/labels/api) about API.
-- Download ([F-Droid](https://f-droid.org/repository/browse/?fdid=com.github.dfa.diaspora_android), [Release Archive](https://github.com/Diaspora-for-Android/diaspora-android/releases))
-- Watch [Changelog](https://github.com/Diaspora-for-Android/diaspora-android/blob/master/CHANGELOG.md)
-- See [Screenshots](https://github.com/Diaspora-for-Android/diaspora-android/blob/master/SCREENSHOTS.md)
-
-## Contributions
-We are always open for any kind of contribution. (PR's, bug reports, feature requests, translations, ..)
-If you got any questions feel free to join our XMPP/Jabber conference at `diaspora-android@conference.jabberhead.tk` or [Gitter](https://gitter.im/Diaspora-for-Android/diaspora-android).
-Note that the main project members are mostly busy with their job/university/school and may not react or start coding immediately.
-
-We use Crowdin to translate Diaspora for Android. Join our project here:
-If your desired language is not listed please contact the maintainers/owner.
-
-### License
-It's released under GNU GENERAL PUBLIC LICENSE (see [LICENCE](https://github.com/Diaspora-for-Android/diaspora-android/blob/master/LICENSE.md)).
-
-### WebApp
-The app is developed as an WebApp because currently Diaspora doesn't have an API that can be used to create a native interface to retrieve the user's data, publications, direct messages and so on, that's why there are only WebApps for Diaspora out there.
-API is discussed frequently on Diaspora, but the main developers seem to not give the API and mobile view the attention it needs. [Stay tuned on Diaspora* Issues](https://github.com/diaspora/diaspora/labels/api).
-
-Why a WebApp is better than using the mobile site on a browser?
+Why is a WebApp better than using the mobile site on a browser?
Basically it provides better integration with the system (events coming into and going out of the app), notifications, customized interface and functions and a nice little icon that takes you directly to your favorite social network :)
-### Device Requirements
-The minimum version supported is Jelly Bean, Android v4.2.0 / API 17
+#### Device Requirements
+The minimum Android version supported is Jelly Bean, Android v4.2.0 / API 17
-### App Permissions
-It requires access to the Internet and to external storage to be able to upload photos when creating a new post and for taking screenshots.
+### Privacy & Permissions
+dandelion\* requires access to the Internet and to external storage to be able to upload photos when creating a new post and for taking screenshots.
-## Maintainers
-- gsantner ([GitHub](https://github.com/gsantner), [Web](https://gsantner.github.io))
-- vanitasvitae ([GitHub](https://github.com/vanitasvitae))
+
+## Contributions
+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.
+
+Translations can be contributed on GitHub. You can use Stringlate ([](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. [](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/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/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
+
" + getString(R.string.licenses) + " " + 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();
+ }
+ }
+
+ /**
+ * Setup the user interface. Set up both toolbars and initialize the snackbars.
+ * Initialize the navigation drawer and apply intellihide settings.
+ */
+ private void setupUI() {
+ AppLog.i(this, "setupUI()");
+
+ // Setup _toolbar
+ setSupportActionBar(toolbarTop);
+ ActionBar actionBar = getSupportActionBar();
+ if (actionBar != null) {
+ actionBar.setDisplayHomeAsUpEnabled(true);
+ }
setTitle(R.string.app_name);
//Setup snackbar
snackbarExitApp = Snackbar
- .make(contentLayout, 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() {
- @Override
public void onClick(View view) {
finish();
moveTaskToBack(true);
}
});
- snackbarNewNotification = Snackbar
- .make(contentLayout, R.string.new_notifications, Snackbar.LENGTH_LONG)
- .setAction(android.R.string.yes, new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (WebHelper.isOnline(MainActivity.this)) {
- webView.loadUrlNew(urls.getNotificationsUrl());
- } else {
- Snackbar.make(contentLayout, R.string.no_internet, Snackbar.LENGTH_LONG).show();
- }
- }
- });
- snackbarNoInternet = Snackbar.make(contentLayout, R.string.no_internet, Snackbar.LENGTH_LONG);
+ snackbarLastVisitedTimestampInStream =
+ Snackbar.make(fragmentContainer,
+ 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.sorry_need_to_be_connected_to_internet, Snackbar.LENGTH_LONG);
// Load app settings
setupNavigationSlider();
-
- progressBar = (ProgressBar) findViewById(R.id.progressBar);
- podDomain = appSettings.getPodDomain();
-
- String url = urls.getPodUrl();
- if (savedInstanceState == null) {
- if (WebHelper.isOnline(MainActivity.this)) {
- webView.loadData("", "text/html", null);
- webView.loadUrlNew(url);
- } else {
- snackbarNoInternet.show();
- }
- }
-
- if (!appSettings.isIntellihideToolbars()) {
- AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbarTop.getLayoutParams();
- params.setScrollFlags(0); // clear all scroll flags
- }
-
- handleIntent(getIntent());
+ AppLog.v(this, "UI successfully set up");
}
- private void setupWebView(Bundle savedInstanceState) {
-
- webSettings = webView.getSettings();
- webSettings.setJavaScriptEnabled(true);
- webSettings.setAllowFileAccess(false);
- webSettings.setUseWideViewPort(true);
- webSettings.setLoadWithOverviewMode(true);
- webSettings.setDomStorageEnabled(true);
- webSettings.setMinimumFontSize(appSettings.getMinimumFontSize());
- webSettings.setLoadsImagesAutomatically(appSettings.isLoadImages());
- webSettings.setAppCacheEnabled(true);
-
- if (savedInstanceState != null) {
- webView.restoreState(savedInstanceState);
- }
-
- if (android.os.Build.VERSION.SDK_INT >= 21) {
- WebView.enableSlowWholeDocumentDraw();
- webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
- }
-
- this.registerForContextMenu(webView);
- webView.setParentActivity(this);
- webView.setOverScrollMode(WebView.OVER_SCROLL_ALWAYS);
-
- // Setup WebView
- webView.addJavascriptInterface(new JavaScriptInterface(), "AndroidBridge");
-
- //Set proxy
- if (appSettings.isProxyEnabled()) {
- if (!setProxy())
- Toast.makeText(this, R.string.toast_set_proxy_failed, Toast.LENGTH_LONG).show();
- }
-
- /*
- * WebViewClient
- */
- webViewClient = new CustomWebViewClient(app, webView);
- webView.setWebViewClient(webViewClient);
-
- /*
- * WebChromeClient
- */
- webView.setWebChromeClient(new WebChromeClient() {
-
- public void onProgressChanged(WebView wv, int progress) {
- progressBar.setProgress(progress);
-
- if (progress > 0 && progress <= 60) {
- WebHelper.getUserProfile(wv);
- WebHelper.optimizeMobileSiteLayout(wv);
- }
-
- if (progress > 60) {
- WebHelper.optimizeMobileSiteLayout(wv);
-
- if (textToBeShared != null) {
- WebHelper.shareTextIntoWebView(wv, textToBeShared);
- }
- }
-
- progressBar.setVisibility(progress == 100 ? View.GONE : View.VISIBLE);
+ /**
+ * 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 ThemedFragment getFragment(String fragmentTag) {
+ ThemedFragment fragment = (ThemedFragment) fm.findFragmentByTag(fragmentTag);
+ if (fragment != null) {
+ return fragment;
+ } else {
+ switch (fragmentTag) {
+ case DiasporaStreamFragment.TAG:
+ DiasporaStreamFragment dsf = new DiasporaStreamFragment();
+ fm.beginTransaction().add(dsf, fragmentTag).commit();
+ return dsf;
+ case BrowserFragment.TAG:
+ BrowserFragment bf = new BrowserFragment();
+ fm.beginTransaction().add(bf, fragmentTag).commit();
+ return bf;
+ case PodSelectionFragment.TAG:
+ PodSelectionFragment psf = new PodSelectionFragment();
+ fm.beginTransaction().add(psf, fragmentTag).commit();
+ return psf;
+ default:
+ AppLog.e(this, "Invalid Fragment Tag: " + fragmentTag
+ + "\nAdd Fragments Tag to getFragment()'s switch case.");
+ return getTopFragment();
}
-
- @Override
- public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {
- if (mFilePathCallback != null) mFilePathCallback.onReceiveValue(null);
-
- mFilePathCallback = filePathCallback;
-
- Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
- // Create the File where the photo should go
- File photoFile;
- try {
- photoFile = createImageFile();
- takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
- } catch (IOException ex) {
- // Error occurred while creating the File
- Snackbar.make(contentLayout, R.string.unable_to_load_image, Snackbar.LENGTH_LONG).show();
- return false;
- }
-
- // Continue only if the File was successfully created
- if (photoFile != null) {
- mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
- takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
- Uri.fromFile(photoFile));
- } else {
- takePictureIntent = null;
- }
- }
-
- Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
- contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
- contentSelectionIntent.setType("image/*");
-
- Intent[] intentArray;
- if (takePictureIntent != null) {
- intentArray = new Intent[]{takePictureIntent};
- } else {
- intentArray = new Intent[0];
- }
-
- Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
- chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
- chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
- chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
-
- startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
- return true;
- }
- });
+ }
}
+ /**
+ * Show DiasporaStreamFragment if necessary and load URL url
+ *
+ * @param url URL to load in the DiasporaStreamFragment
+ */
+ public void openDiasporaUrl(final String url) {
+ AppLog.v(this, "openDiasporaUrl()");
+ 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) {
+ if (url.equals(urls.getStreamUrl()) && diasporaUserProfile.hasLastVisitedTimestampInStream()) {
+ snackbarLastVisitedTimestampInStream.show();
+ diasporaUserProfile.resetLastVisitedPositionInStream();
+ }
+ }
+
+ /**
+ * Show the Fragment fragment in R.id.fragment_container. If the fragment was already visible, do nothing.
+ *
+ * @param fragment Fragment to show
+ */
+ 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()");
+ 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();
+ setToolbarIntellihide(_appSettings.isIntellihideToolbars() && fragment.isAllowedIntellihide());
+ } else {
+ AppLog.v(this, "Fragment was already visible. Do nothing.");
+ }
+ }
+
+ /**
+ * Initialize the navigation slider
+ */
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();
@@ -377,15 +396,14 @@ public class MainActivity extends AppCompatActivity
navView.setNavigationItemSelectedListener(this);
View navHeader = navView.getHeaderView(0);
- LinearLayout navheaderProfileSection = ButterKnife.findById(navHeader, R.id.nav_profile_picture);
- navheaderProfileSection.setOnClickListener(new View.OnClickListener() {
- @Override
+ navProfilePictureArea = ButterKnife.findById(navHeader, R.id.nav_profile_picture);
+ navDrawerLayout = ButterKnife.findById(navHeader, R.id.nav_drawer);
+ //Handle clicks on profile picture
+ navProfilePictureArea.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
navDrawer.closeDrawer(GravityCompat.START);
- if (WebHelper.isOnline(MainActivity.this)) {
- webView.loadUrlNew(urls.getProfileUrl());
- } else {
- snackbarNoInternet.show();
+ if (!_appSettings.getProfileId().equals("")) {
+ openDiasporaUrl(urls.getProfileUrl());
}
}
});
@@ -393,81 +411,138 @@ public class MainActivity extends AppCompatActivity
navheaderDescription = ButterKnife.findById(navHeader, R.id.podselection__podupti_notice);
navheaderImage = ButterKnife.findById(navHeader, R.id.navheader_user_image);
- if (!appSettings.getName().equals("")) {
- navheaderTitle.setText(appSettings.getName());
+ if (!_appSettings.getName().equals("")) {
+ navheaderTitle.setText(_appSettings.getName());
}
- if (!appSettings.getPodDomain().equals("")) {
- navheaderDescription.setText(appSettings.getPodDomain());
+ if (_appSettings.getPod() != null) {
+ navheaderDescription.setText(_appSettings.getPod().getName());
}
- if (!appSettings.getAvatarUrl().equals("")) {
- // Try to load image
- if (!app.getAvatarImageLoader().loadToImageView(navheaderImage)) {
- // If not yet loaded, start download
- app.getAvatarImageLoader().startImageDownload(navheaderImage, appSettings.getAvatarUrl());
+ String avatarUrl = _appSettings.getAvatarUrl();
+ if (!avatarUrl.equals("")) {
+ //Display app launcher icon instead of default avatar asset
+ //(Which would by the way not load because of missing pod domain prefix in the url)
+ if (avatarUrl.startsWith("/assets/user/default")) {
+ AppLog.v(this, "Avatar appears to be an asset. Display launcher icon instead (avatarUrl=" + avatarUrl + ")");
+ navheaderImage.setImageResource(R.drawable.ic_launcher);
+ } else {
+ // Try to load image
+ if (!app.getAvatarImageLoader().loadToImageView(navheaderImage)) {
+ // If not yet loaded, start download
+ AppLog.v(this, "Avatar not cached. Start download: " + avatarUrl);
+ app.getAvatarImageLoader().startImageDownload(navheaderImage, avatarUrl);
+ }
}
}
+ updateNavigationViewEntryVisibilities();
+ }
- // Set visibility
+ protected void updateNavigationViewEntryVisibilities() {
Menu navMenu = navView.getMenu();
- navMenu.findItem(R.id.nav_exit).setVisible(appSettings.isVisibleInNavExit());
- navMenu.findItem(R.id.nav_activities).setVisible(appSettings.isVisibleInNavActivities());
- navMenu.findItem(R.id.nav_aspects).setVisible(appSettings.isVisibleInNavAspects());
- navMenu.findItem(R.id.nav_commented).setVisible(appSettings.isVisibleInNavCommented());
- navMenu.findItem(R.id.nav_followed_tags).setVisible(appSettings.isVisibleInNavFollowed_tags());
- navMenu.findItem(R.id.nav_help_license).setVisible(appSettings.isVisibleInNavHelp_license());
- navMenu.findItem(R.id.nav_liked).setVisible(appSettings.isVisibleInNavLiked());
- navMenu.findItem(R.id.nav_mentions).setVisible(appSettings.isVisibleInNavMentions());
- navMenu.findItem(R.id.nav_profile).setVisible(appSettings.isVisibleInNavProfile());
- navMenu.findItem(R.id.nav_public).setVisible(appSettings.isVisibleInNavPublic_activities());
+
+ // Initially show all items visible when logged in
+ navMenu.setGroupVisible(navMenu.findItem(R.id.nav_exit).getGroupId(), true);
+
+ // Hide by app settings
+ navMenu.findItem(R.id.nav_exit).setVisible(_appSettings.isVisibleInNavExit());
+ navMenu.findItem(R.id.nav_activities).setVisible(_appSettings.isVisibleInNavActivities());
+ navMenu.findItem(R.id.nav_aspects).setVisible(_appSettings.isVisibleInNavAspects());
+ navMenu.findItem(R.id.nav_contacts).setVisible(_appSettings.isVisibleInNavContacts());
+ navMenu.findItem(R.id.nav_commented).setVisible(_appSettings.isVisibleInNavCommented());
+ navMenu.findItem(R.id.nav_followed_tags).setVisible(_appSettings.isVisibleInNavFollowed_tags());
+ navMenu.findItem(R.id.nav_about).setVisible(_appSettings.isVisibleInNavHelp_license());
+ navMenu.findItem(R.id.nav_liked).setVisible(_appSettings.isVisibleInNavLiked());
+ navMenu.findItem(R.id.nav_mentions).setVisible(_appSettings.isVisibleInNavMentions());
+ navMenu.findItem(R.id.nav_profile).setVisible(_appSettings.isVisibleInNavProfile());
+ navMenu.findItem(R.id.nav_public).setVisible(_appSettings.isVisibleInNavPublic_activities());
+ navMenu.findItem(R.id.nav_stream).setVisible(true);
+ 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_product_support).setVisible(_appSettings.isVisibleInNavGsantnerAccount());
+
+
+ // Hide whole group (for logged in use) if no pod was selected
+ if (!_appSettings.hasPod()) {
+ navMenu.setGroupVisible(navMenu.findItem(R.id.nav_exit).getGroupId(), false);
+ }
}
- @OnClick(R.id.toolbar)
+ /**
+ * Open Stream when clicked on top _toolbar AND preference stream shortcut is true
+ *
+ * @param view selected view
+ */
+ @OnClick(R.id.main__topbar)
public void onToolBarClicked(View view) {
- onNavigationItemSelected(navView.getMenu().findItem(R.id.nav_stream));
- }
-
- private File createImageFile() throws IOException {
- // Create an image file name
- String timeStamp = new SimpleDateFormat("dd-MM-yy_HH-mm", Locale.getDefault()).format(new Date());
- String imageFileName = "JPEG_" + timeStamp + "_";
- File storageDir = Environment.getExternalStoragePublicDirectory(
- Environment.DIRECTORY_PICTURES);
- return File.createTempFile(
- imageFileName, /* prefix */
- ".jpg", /* suffix */
- storageDir /* directory */
- );
+ AppLog.i(this, "onToolBarClicked()");
+ if (_appSettings.isTopbarStreamShortcutEnabled() && _appSettings.hasPod()) {
+ onNavigationItemSelected(navView.getMenu().findItem(R.id.nav_stream));
+ }
}
+ /**
+ * Forward incoming intents to handleIntent()
+ *
+ * @param intent incoming
+ */
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
-
handleIntent(intent);
}
+ /**
+ * Handle intents and execute intent specific actions
+ *
+ * @param intent intent to get handled
+ */
private void handleIntent(Intent intent) {
+ AppLog.i(this, "handleIntent()");
if (intent == null) {
+ AppLog.v(this, "Intent was null");
return;
}
String action = intent.getAction();
String type = intent.getType();
String loadUrl = null;
-
-
- if (ACTION_OPEN_URL.equals(action)) {
+ AppLog.v(this, "Action: " + action + " Type: " + type);
+ if (Intent.ACTION_MAIN.equals(action)) {
+ loadUrl = urls.getStreamUrl();
+ } else if (ACTION_OPEN_URL.equals(action)) {
loadUrl = intent.getStringExtra(URL_MESSAGE);
} else if (Intent.ACTION_VIEW.equals(action) && intent.getDataString() != null) {
- loadUrl = intent.getDataString();
+ Uri data = intent.getData();
+ if (data != null && data.toString().startsWith(CONTENT_HASHTAG)) {
+ handleHashtag(intent);
+ return;
+ } else {
+ loadUrl = intent.getDataString();
+ AppLog.v(this, "Intent has a delicious URL for us: " + loadUrl);
+ }
} else if (ACTION_CHANGE_ACCOUNT.equals(action)) {
- app.resetPodData(webView);
- Helpers.animateToActivity(MainActivity.this, PodSelectionActivity.class, true);
+ AppLog.v(this, "Reset pod data and show PodSelectionFragment");
+ _appSettings.setPod(null);
+ runOnUiThread(new Runnable() {
+ public void run() {
+ navheaderTitle.setText(R.string.app_name);
+ navheaderDescription.setText(R.string.app_subtitle);
+ navheaderImage.setImageResource(R.drawable.ic_launcher);
+ app.resetPodData(((DiasporaStreamFragment) getFragment(DiasporaStreamFragment.TAG)).getWebView());
+ }
+ });
+ showFragment(getFragment(PodSelectionFragment.TAG));
} else if (ACTION_CLEAR_CACHE.equals(action)) {
- webView.clearCache(true);
- } else if (ACTION_RELOAD_ACTIVITY.equals(action)) {
- recreate();
- return;
+ AppLog.v(this, "Clear WebView cache");
+ runOnUiThread(new Runnable() {
+ public void run() {
+ ContextMenuWebView wv = ((DiasporaStreamFragment) getFragment(DiasporaStreamFragment.TAG)).getWebView();
+ if (wv != null) {
+ wv.clearCache(true);
+ }
+ }
+ });
+
} else if (Intent.ACTION_SEND.equals(action) && type != null) {
switch (type) {
case "text/plain":
@@ -482,68 +557,80 @@ public class MainActivity extends AppCompatActivity
break;
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
- //TODO: Implement and add filter to manifest
+ /* 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) {
+ return;
}
if (loadUrl != null) {
- webView.stopLoading();
navDrawer.closeDrawers();
- webView.loadUrlNew(loadUrl);
+ openDiasporaUrl(loadUrl);
}
}
+ /**
+ * Handle activity results
+ *
+ * @param requestCode reqCode
+ * @param resultCode resCode
+ * @param data data
+ */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
- super.onActivityResult(requestCode, resultCode, data);
- return;
- }
- Uri[] results = null;
- if (resultCode == Activity.RESULT_OK) {
- if (data == null) {
- if (mCameraPhotoPath != null) {
- results = new Uri[]{Uri.parse(mCameraPhotoPath)};
- }
- } else {
- String dataString = data.getDataString();
- if (dataString != null) {
- results = new Uri[]{Uri.parse(dataString)};
- }
- }
- }
-
- mFilePathCallback.onReceiveValue(results);
- mFilePathCallback = null;
+ AppLog.v(this, "onActivityResult(): " + requestCode);
+ super.onActivityResult(requestCode, resultCode, data);
}
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- webView.saveState(outState);
- }
-
- @Override
- protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
- webView.restoreState(savedInstanceState);
- }
-
- @Override
- protected void onResume() {
- super.onResume();
- LocalBroadcastManager.getInstance(this).registerReceiver(brSetTitle, new IntentFilter(ACTION_UPDATE_TITLE_FROM_URL));
+ /**
+ * Return the fragment which is currently displayed in R.id.fragment_container
+ *
+ * @return top fragment or null if there is none displayed
+ */
+ private ThemedFragment getTopFragment() {
+ return (ThemedFragment) fm.findFragmentById(R.id.fragment_container);
}
+ /**
+ * Handle presses on the back button
+ */
@Override
public void onBackPressed() {
+ AppLog.v(this, "onBackPressed()");
if (navDrawer.isDrawerOpen(navView)) {
navDrawer.closeDrawer(navView);
return;
}
-
- if (webView.canGoBack()) {
- webView.goBack();
- return;
+ ThemedFragment top = getTopFragment();
+ if (top != null) {
+ AppLog.v(this, "Top Fragment is not null");
+ if (!top.onBackPressed()) {
+ AppLog.v(this, "Top Fragment.onBackPressed was false");
+ AppLog.v(this, "BackStackEntryCount: " + fm.getBackStackEntryCount());
+ if (fm.getBackStackEntryCount() > 0) {
+ fm.popBackStack();
+ } else {
+ snackbarExitApp.show();
+ }
+ return;
+ } else {
+ AppLog.v(this, "Top Fragment.onBackPressed was true");
+ return;
+ }
}
if (!snackbarExitApp.isShown()) {
@@ -551,79 +638,182 @@ public class MainActivity extends AppCompatActivity
}
}
- private final BroadcastReceiver brSetTitle = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- String url = intent.getStringExtra(EXTRA_URL);
- if (url != null && url.startsWith(urls.getPodUrl())) {
- String subUrl = url.substring((urls.getPodUrl()).length());
- if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_STREAM)) {
- setTitle(R.string.nav_stream);
- } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_POSTS)) {
- setTitle(R.string.diaspora); //TODO: Extract posts title somehow?
- } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_NOTIFICATIONS)) {
- setTitle(R.string.notifications);
- } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_CONVERSATIONS)) {
- setTitle(R.string.conversations);
- } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_NEW_POST)) {
- setTitle(R.string.new_post);
- } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_PEOPLE + appSettings.getProfileId())) {
- setTitle(R.string.nav_profile);
- } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_ACTIVITY)) {
- setTitle(R.string.nav_activities);
- } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_LIKED)) {
- setTitle(R.string.nav_liked);
- } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_COMMENTED)) {
- setTitle(R.string.nav_commented);
- } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_MENTIONS)) {
- setTitle(R.string.nav_mentions);
- } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_PUBLIC)) {
- setTitle(R.string.public_);
- } else if (urls.isAspectUrl(url)){
- setTitle(urls.getAspectNameFromUrl(url, app));
- }
- }
- }
- };
+ @Override
+ protected void onStart() {
+ super.onStart();
+ customTabActivityHelper.bindCustomTabsService(this);
+ }
+
+ @Override
+ protected void onStop() {
+ super.onStop();
+ customTabActivityHelper.unbindCustomTabsService(this);
+ }
@Override
protected void onPause() {
+ AppLog.v(this, "onPause()");
+ AppLog.v(this, "Unregister BroadcastReceivers");
LocalBroadcastManager.getInstance(this).unregisterReceiver(brSetTitle);
+ LocalBroadcastManager.getInstance(this).unregisterReceiver(brOpenExternalLink);
super.onPause();
}
+ @Override
+ protected void onResume() {
+ AppLog.v(this, "onResume()");
+ super.onResume();
+ AppLog.v(this, "Register BroadcastReceivers");
+ LocalBroadcastManager.getInstance(this).registerReceiver(brSetTitle, new IntentFilter(ACTION_UPDATE_TITLE_FROM_URL));
+ LocalBroadcastManager.getInstance(this).registerReceiver(brOpenExternalLink, new IntentFilter(ACTION_OPEN_EXTERNAL_URL));
+ invalidateOptionsMenu();
+ _appSettings = getAppSettings();
+ if (_appSettings.isRecreateMainActivity()) {
+ recreate();
+ }
+ setToolbarIntellihide(_appSettings.isIntellihideToolbars());
+ if (getSupportActionBar() != null) {
+ getSupportActionBar().setDisplayShowTitleEnabled(AppSettings.get().isShowTitleInMainView());
+ }
+ updateNavigationViewEntryVisibilities();
+ }
+
+ /**
+ * Clear and repopulate top and bottom _toolbar.
+ * Also add menu items of the displayed fragment
+ *
+ * @param menu top _toolbar
+ * @return boolean
+ */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.main__menu_top, menu);
+ AppLog.v(this, "onCreateOptionsMenu()");
+ boolean cache;
+
+ //Clear the menus
+ menu.clear();
+
+ ThemedFragment top = getTopFragment();
+ if (top != null) {
+ 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;
}
+ /**
+ * Set the notification and messages counter in the top _toolbar
+ *
+ * @param menu menu
+ * @return boolean
+ */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
- MenuItem itemNotification = menu.findItem(R.id.action_notifications);
- if (itemNotification != null) {
- if (podUserProfile.getNotificationCount() > 0) {
- itemNotification.setIcon(R.drawable.ic_notifications_colored_48px);
- } else {
- itemNotification.setIcon(R.drawable.ic_notifications_white_48px);
- }
+ MenuItem item;
+ updateNavigationViewEntryVisibilities();
- MenuItem itemConversation = menu.findItem(R.id.action_conversations);
- if (podUserProfile.getUnreadMessagesCount() > 0) {
- itemConversation.setIcon(R.drawable.ic_email_colored_48px);
- } else {
- itemConversation.setIcon(R.drawable.ic_mail_white_48px);
- }
+ if ((item = menu.findItem(R.id.action_notifications)) != null) {
+ LayerDrawable icon = (LayerDrawable) item.getIcon();
+ BadgeDrawable.setBadgeCount(this, icon, diasporaUserProfile.getNotificationCount());
+ }
+
+ if ((item = menu.findItem(R.id.action_conversations)) != null) {
+ LayerDrawable icon = (LayerDrawable) item.getIcon();
+ BadgeDrawable.setBadgeCount(this, icon, diasporaUserProfile.getUnreadMessagesCount());
}
return super.onPrepareOptionsMenu(menu);
}
+ /**
+ * Handle clicks on the optionsmenu
+ *
+ * @param item item
+ * @return boolean
+ */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
+ AppLog.i(this, "onOptionsItemSelected()");
switch (item.getItemId()) {
case R.id.action_notifications: {
+ if (_appSettings.isExtendedNotificationsActivated()) {
+ return true;
+ }
+ //Otherwise we execute the action of action_notifications_all
+ }
+ case R.id.action_notifications_all: {
if (WebHelper.isOnline(MainActivity.this)) {
- webView.loadUrlNew(urls.getNotificationsUrl());
+ openDiasporaUrl(urls.getNotificationsUrl());
+ return true;
+ } else {
+ snackbarNoInternet.show();
+ return false;
+ }
+ }
+
+
+ case R.id.action_notifications_also_commented: {
+ if (WebHelper.isOnline(MainActivity.this)) {
+ openDiasporaUrl(urls.getSuburlNotificationsAlsoCommentedUrl());
+ return true;
+ } else {
+ snackbarNoInternet.show();
+ return false;
+ }
+ }
+
+ case R.id.action_notifications_comment_on_post: {
+ if (WebHelper.isOnline(MainActivity.this)) {
+ openDiasporaUrl(urls.getSuburlNotificationsCommentOnPostUrl());
+ return true;
+ } else {
+ snackbarNoInternet.show();
+ return false;
+ }
+ }
+
+ case R.id.action_notifications_liked: {
+ if (WebHelper.isOnline(MainActivity.this)) {
+ openDiasporaUrl(urls.getSuburlNotificationsLikedUrl());
+ return true;
+ } else {
+ snackbarNoInternet.show();
+ return false;
+ }
+ }
+
+ case R.id.action_notifications_mentioned: {
+ if (WebHelper.isOnline(MainActivity.this)) {
+ openDiasporaUrl(urls.getSuburlNotificationsMentionedUrl());
+ return true;
+ } else {
+ snackbarNoInternet.show();
+ return false;
+ }
+ }
+
+ case R.id.action_notifications_reshared: {
+ if (WebHelper.isOnline(MainActivity.this)) {
+ openDiasporaUrl(urls.getSuburlNotificationsResharedUrl());
+ return true;
+ } else {
+ snackbarNoInternet.show();
+ return false;
+ }
+ }
+
+ case R.id.action_notifications_started_sharing: {
+ if (WebHelper.isOnline(MainActivity.this)) {
+ openDiasporaUrl(urls.getSuburlNotificationsStartedSharingUrl());
return true;
} else {
snackbarNoInternet.show();
@@ -633,7 +823,7 @@ public class MainActivity extends AppCompatActivity
case R.id.action_conversations: {
if (WebHelper.isOnline(MainActivity.this)) {
- webView.loadUrlNew(urls.getConversationsUrl());
+ openDiasporaUrl(urls.getConversationsUrl());
return true;
} else {
snackbarNoInternet.show();
@@ -641,110 +831,50 @@ public class MainActivity extends AppCompatActivity
}
}
- case R.id.action_reload: {
- if (WebHelper.isOnline(MainActivity.this)) {
- webView.reload();
- return true;
- } else {
- snackbarNoInternet.show();
- return false;
- }
- }
-
- case R.id.action_exit: {
- moveTaskToBack(true);
- finish();
- return true;
- }
-
- case R.id.action_toggle_desktop_page: {
- webView.loadUrlNew(urls.getToggleMobileUrl());
- return true;
- }
-
case R.id.action_compose: {
if (WebHelper.isOnline(MainActivity.this)) {
- webView.loadUrlNew(urls.getNewPostUrl());
+ openDiasporaUrl(urls.getNewPostUrl());
} else {
snackbarNoInternet.show();
}
return true;
}
- case R.id.action_go_to_top: {
- // Scroll to top (animated)
- ObjectAnimator anim = ObjectAnimator.ofInt(webView, "scrollY", webView.getScrollY(), 0);
- anim.setDuration(400);
- anim.start();
- return true;
- }
-
- case R.id.action_share_link: {
- Intent sharingIntent = new Intent(Intent.ACTION_SEND);
- 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)));
- return true;
- }
-
- case R.id.action_take_screenshot: {
- makeScreenshotOfWebView(false);
- return true;
- }
-
- case R.id.action_share_screenshot: {
- makeScreenshotOfWebView(true);
- return true;
- }
-
case R.id.action_search: {
if (WebHelper.isOnline(MainActivity.this)) {
final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
- LinearLayout layout = new LinearLayout(this);
- layout.setOrientation(LinearLayout.VERTICAL);
- layout.setGravity(Gravity.CENTER_HORIZONTAL);
- final EditText input = new EditText(this);
+
+ @SuppressLint("InflateParams") View layout = getLayoutInflater().inflate(R.layout.ui__dialog_search__people_tags, null, false);
+ final EditText input = layout.findViewById(R.id.dialog_search__input);
+ input.setMaxLines(1);
input.setSingleLine(true);
- layout.setPadding(50, 0, 50, 0);
- input.setHint(R.string.app_hashtag);
- layout.addView(input);
-
- final DialogInterface.OnClickListener onSearchAccepted = new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- boolean wasClickedOnSearchForPeople = which == DialogInterface.BUTTON_NEGATIVE;
-
- String inputTag = input.getText().toString().trim();
- String cleanTag = inputTag.replaceAll(wasClickedOnSearchForPeople ? "\\*" : "\\#", "");
- // this validate the input data for tagfind
- if (cleanTag == null || cleanTag.equals("")) {
- Snackbar.make(contentLayout, R.string.search_alert_bypeople_validate_needsomedata, Snackbar.LENGTH_LONG).show();
- } else { // User have added a search tag
- if (wasClickedOnSearchForPeople) {
- webView.loadUrlNew(urls.getSearchPeopleUrl(cleanTag));
- } else {
- webView.loadUrlNew(urls.getSearchTagsUrl(cleanTag));
- }
+ ThemeHelper.updateEditTextColor(input);
+ final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
+ @Override
+ 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.please_add_a_name, Snackbar.LENGTH_LONG).show();
+ } else {
+ openDiasporaUrl(which == DialogInterface.BUTTON_NEGATIVE ? urls.getSearchPeopleUrl(query) : urls.getSearchTagsUrl(query));
}
-
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
}
};
- final AlertDialog dialog = new AlertDialog.Builder(this)
- .setView(layout)
- .setTitle(R.string.search_alert_title)
+ final AlertDialog dialog = new ThemedAlertDialogBuilder(this, _appSettings)
+ .setView(layout).setTitle(R.string.search_alert_title)
.setCancelable(true)
- .setPositiveButton(R.string.search_alert_tag, onSearchAccepted)
- .setNegativeButton(R.string.search_alert_people, onSearchAccepted)
+ .setPositiveButton(R.string.by_tags, clickListener)
+ .setNegativeButton(R.string.by_people, clickListener)
.create();
input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
dialog.hide();
- onSearchAccepted.onClick(null, 0);
+ clickListener.onClick(null, 0);
return true;
}
return false;
@@ -767,194 +897,158 @@ public class MainActivity extends AppCompatActivity
return super.onOptionsItemSelected(item);
}
- @SuppressWarnings("ResultOfMethodCallIgnored")
- private boolean makeScreenshotOfWebView(boolean hasToShareScreenshot) {
- if (android.os.Build.VERSION.SDK_INT >= 23) {
- int hasWRITE_EXTERNAL_STORAGE = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
- if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
- if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
- new AlertDialog.Builder(MainActivity.this)
- .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},
- REQUEST_CODE_ASK_PERMISSIONS);
- }
- })
- .show();
- return false;
- }
- requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
- 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()) {
- fileSaveDirectory.mkdirs();
- }
-
- if (!hasToShareScreenshot) {
- Snackbar.make(contentLayout, 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);
- sendBroadcast(intent);
- }
- return true;
- }
-
@Override
- public void onUserProfileNameChanged(String name) {
+ public void onUserProfileNameChanged(DiasporaUserProfile diasporaUserProfile, String name) {
+ AppLog.i(this, "onUserProfileNameChanged()");
+ // Update the profile name in the navigation slider
navheaderTitle.setText(name);
}
@Override
- public void onUserProfileAvatarChanged(String avatarUrl) {
+ public void onUserProfileAvatarChanged(DiasporaUserProfile diasporaUserProfile, String avatarUrl) {
+ AppLog.i(this, "onUserProfileAvatarChanged()");
+ // Update the profile picture in the navigation slider
app.getAvatarImageLoader().startImageDownload(navheaderImage, avatarUrl);
}
- void handleSendText(Intent intent) {
- String content = WebHelper.replaceUrlWithMarkdown(intent.getStringExtra(Intent.EXTRA_TEXT));
- if (appSettings.isAppendSharedViaApp()) {
- //
= \n
- content = content + "\n\n" + getString(R.string.shared_by_diaspora_android);
+ /**
+ * Handle hashtag clicks. Open the new-post-url and inject the clicked hashtag into the post-editor
+ *
+ * @param intent intent
+ */
+ private void handleHashtag(Intent intent) {
+ AppLog.v(this, "handleHashtag()");
+ try {
+ setSharedTexts(null, intent.getData().toString().split("/")[3]);
+ } catch (Exception e) {
+ AppLog.e(this, e.toString());
}
+ openDiasporaUrl(urls.getNewPostUrl());
+ }
- final String sharedText = WebHelper.escapeHtmlText(content);
- if (sharedText != null) {
- textToBeShared = sharedText;
+ /**
+ * Open the new-post-url and inject text that was shared into the app into the post editors text field
+ *
+ * @param intent shareTextIntent
+ */
+ private void handleSendText(Intent intent) {
+ AppLog.v(this, "handleSendText()");
+ try {
+ setSharedTexts(null, intent.getStringExtra(Intent.EXTRA_TEXT));
+ openDiasporaUrl(urls.getNewPostUrl());
+ } catch (Exception e) {
+ AppLog.e(this, e.toString());
}
-
- webView.loadUrlNew(urls.getBlankUrl());
- webView.loadUrlNew(urls.getNewPostUrl());
}
/**
* Handle sent text + subject
*
- * @param intent
+ * @param intent intent
*/
- void handleSendSubject(Intent intent) {
- webView.loadUrlNew(urls.getNewPostUrl());
- String content = WebHelper.replaceUrlWithMarkdown(intent.getStringExtra(Intent.EXTRA_TEXT));
- String subject = WebHelper.replaceUrlWithMarkdown(intent.getStringExtra(Intent.EXTRA_SUBJECT));
-
- if (appSettings.isAppendSharedViaApp()) {
- //
= \n
- content = content + "\n\n" + getString(R.string.shared_by_diaspora_android);
+ private void handleSendSubject(Intent intent) {
+ AppLog.v(this, "handleSendSubject()");
+ try {
+ setSharedTexts(intent.getStringExtra(Intent.EXTRA_SUBJECT), intent.getStringExtra(Intent.EXTRA_TEXT));
+ openDiasporaUrl(urls.getNewPostUrl());
+ } catch (Exception e) {
+ AppLog.e(this, e.toString());
}
-
- final String sharedSubject = WebHelper.escapeHtmlText(subject);
- final String sharedContent = WebHelper.escapeHtmlText(content);
- textToBeShared = "**" + sharedSubject + "** " + sharedContent;
-
- webView.loadUrlNew(urls.getBlankUrl());
- webView.loadUrlNew(urls.getNewPostUrl());
}
- //TODO: Implement?
+ /**
+ * TODO: MOVE
+ * Set sharedText variable to escaped and formatted subject + body.
+ * If subject is null, only the body will be set. Else the subject will be set as header.
+ * Depending on whether the user has the setting isAppendSharedViaApp set, a reference to
+ * the app will be added at the bottom
+ *
+ * @param sharedSubject post subject or null
+ * @param sharedBody post text
+ */
+ private void setSharedTexts(String sharedSubject, String sharedBody) {
+ AppLog.i(this, "setSharedTexts()");
+ String body = WebHelper.replaceUrlWithMarkdown(sharedBody);
+ if (_appSettings.isAppendSharedViaApp()) {
+ AppLog.v(this, "Append app reference to shared text");
+ body = body + "\n\n" + getString(R.string.shared_via_app);
+ }
+ final String escapedBody = WebHelper.escapeHtmlText(body);
+ if (sharedSubject != null) {
+ AppLog.v(this, "Append subject to shared text");
+ String escapedSubject = WebHelper.escapeHtmlText(WebHelper.replaceUrlWithMarkdown(sharedSubject));
+ AppLog.v(this, "Set shared text; Subject: \"" + escapedSubject + "\" Body: \"" + escapedBody + "\"");
+ textToBeShared = "**" + escapedSubject + "** " + escapedBody;
+ } else {
+ AppLog.v(this, "Set shared text; Subject: \"null\" Body: \"" + sharedBody + "\"");
+ textToBeShared = escapedBody;
+ }
+ }
+
+ /**
+ * Share an image shared to the app via diaspora
+ *
+ * @param intent shareImageIntent
+ */
+ //TODO: Implement some day
private void handleSendImage(Intent intent) {
- final Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
+ AppLog.i(this, "handleSendImage()");
+ final Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
- // Update UI to reflect text being shared
+ AppLog.v(this, "imageUri is not null. Handle shared image");
+ } else {
+ AppLog.w(this, "imageUri is null. Cannot precede.");
}
Toast.makeText(this, "Not yet implemented.", Toast.LENGTH_SHORT).show();
}
- // TODO: Move from Javascript interface
@Override
- public void onNotificationCountChanged(int notificationCount) {
- // Count saved in PodUserProfile
+ public void onNotificationCountChanged(DiasporaUserProfile diasporaUserProfile, int notificationCount) {
+ AppLog.i(this, "onNotificationCountChanged()");
+ // Count saved in DiasporaUserProfile
+ // Invalidate the top _toolbar to update the unread messages counter
invalidateOptionsMenu();
+ }
- if (notificationCount > 0 && !snackbarNewNotification.isShown()
- && !webView.getUrl().equals(urls.getNotificationsUrl())) {
- snackbarNewNotification.show();
+
+ @Override
+ public void onUnreadMessageCountChanged(DiasporaUserProfile diasporaUserProfile, int unreadMessageCount) {
+ AppLog.i(this, "onUnreadMessageCountChanged()");
+ // Count saved in DiasporaUserProfile
+ // Invalidate the top _toolbar to update the unread messages counter
+ invalidateOptionsMenu();
+ }
+
+ @Override
+ public void onCustomTabsConnected() {
+ if (customTabsSession == null) {
+ AppLog.i(this, "CustomTabs warmup: " + customTabActivityHelper.warmup(0));
+ customTabsSession = customTabActivityHelper.getSession();
}
}
- // TODO: Move from Javascript interface
@Override
- public void onUnreadMessageCountChanged(int unreadMessageCount) {
- // Count saved in PodUserProfile
- invalidateOptionsMenu();
-
- if (unreadMessageCount > 0 && !snackbarNewNotification.isShown()
- && !webView.getUrl().equals(urls.getNotificationsUrl())) {
- snackbarNewNotification.show();
+ public void onPodSelectionDialogResult(DiasporaPodList.DiasporaPod pod, boolean accepted) {
+ if (accepted) {
+ invalidateOptionsMenu();
+ navheaderDescription.setText(pod.getName());
}
}
- private class JavaScriptInterface {
- @JavascriptInterface
- public void setUserProfile(final String webMessage) throws JSONException {
- if (podUserProfile.isRefreshNeeded()) {
- podUserProfile.parseJson(webMessage);
- }
- }
+ @Override
+ public void onCustomTabsDisconnected() {
- @JavascriptInterface
- public void contentHasBeenShared() {
- textToBeShared = null;
- }
-
- @JavascriptInterface
- public void log(final String log) {
- //Log.d(App.TAG, "[wv] " + log);
- }
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
+ AppLog.v(this, "onNavigationItemsSelected()");
// Handle navigation view item clicks here.
switch (item.getItemId()) {
case R.id.nav_stream: {
if (WebHelper.isOnline(MainActivity.this)) {
- webView.loadUrlNew(urls.getStreamUrl());
+ openDiasporaUrl(urls.getStreamUrl());
} else {
snackbarNoInternet.show();
}
@@ -962,29 +1056,52 @@ public class MainActivity extends AppCompatActivity
break;
case R.id.nav_profile: {
- if (WebHelper.isOnline(MainActivity.this)) {
- webView.loadUrlNew(urls.getProfileUrl());
- } else {
- snackbarNoInternet.show();
+ if (!_appSettings.getProfileId().equals("")) {
+ openDiasporaUrl(urls.getProfileUrl());
}
}
break;
case R.id.nav_followed_tags: {
- if (WebHelper.isOnline(MainActivity.this)) {
- WebHelper.showFollowedTagsList(webView, app);
- setTitle(R.string.nav_followed_tags);
- } else {
- snackbarNoInternet.show();
- }
+ 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: {
+ 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;
+
+ case R.id.nav_contacts: {
if (WebHelper.isOnline(MainActivity.this)) {
- webView.loadUrlNew(DiasporaUrlHelper.URL_BLANK);
- WebHelper.showAspectList(webView, app);
- setTitle(R.string.aspects);
+ openDiasporaUrl(urls.getContactsUrl());
} else {
snackbarNoInternet.show();
}
@@ -993,7 +1110,7 @@ public class MainActivity extends AppCompatActivity
case R.id.nav_activities: {
if (WebHelper.isOnline(MainActivity.this)) {
- webView.loadUrlNew(urls.getActivityUrl());
+ openDiasporaUrl(urls.getActivityUrl());
} else {
snackbarNoInternet.show();
}
@@ -1002,7 +1119,7 @@ public class MainActivity extends AppCompatActivity
case R.id.nav_liked: {
if (WebHelper.isOnline(MainActivity.this)) {
- webView.loadUrlNew(urls.getLikedPostsUrl());
+ openDiasporaUrl(urls.getLikedPostsUrl());
} else {
snackbarNoInternet.show();
}
@@ -1011,7 +1128,7 @@ public class MainActivity extends AppCompatActivity
case R.id.nav_commented: {
if (WebHelper.isOnline(MainActivity.this)) {
- webView.loadUrlNew(urls.getCommentedUrl());
+ openDiasporaUrl(urls.getCommentedUrl());
} else {
snackbarNoInternet.show();
}
@@ -1020,54 +1137,63 @@ public class MainActivity extends AppCompatActivity
case R.id.nav_mentions: {
if (WebHelper.isOnline(MainActivity.this)) {
- webView.loadUrlNew(urls.getMentionsUrl());
+ openDiasporaUrl(urls.getMentionsUrl());
} else {
snackbarNoInternet.show();
}
- break;
}
+ break;
case R.id.nav_public: {
if (WebHelper.isOnline(MainActivity.this)) {
- webView.loadUrlNew(urls.getPublicUrl());
+ openDiasporaUrl(urls.getPublicUrl());
} else {
snackbarNoInternet.show();
}
- break;
}
+ break;
+
+ case R.id.nav_reports: {
+ if (WebHelper.isOnline(MainActivity.this)) {
+ openDiasporaUrl(urls.getReportsUrl());
+ } else {
+ snackbarNoInternet.show();
+ }
+ }
+ break;
+
+ case R.id.nav_statistics: {
+ if (WebHelper.isOnline(MainActivity.this)) {
+ openDiasporaUrl(urls.getStatisticsUrl());
+ } else {
+ snackbarNoInternet.show();
+ }
+ }
+ break;
+
+ case R.id.nav_toggle_desktop_page: {
+ openDiasporaUrl(urls.getToggleMobileUrl());
+ }
+ break;
+
+ case R.id.nav_product_support: {
+ openDiasporaUrl(urls.getProfileUrl("d1cbdd70095301341e834860008dbc6c"));
+ }
+ break;
case R.id.nav_exit: {
moveTaskToBack(true);
finish();
- break;
}
+ break;
- case R.id.nav_settings_app: {
+ case R.id.nav_settings: {
startActivity(new Intent(this, SettingsActivity.class));
}
break;
- case R.id.nav_help_license: {
- final CharSequence[] options = {getString(R.string.help_license__name), getString(R.string.help_markdown__name)};
- new AlertDialog.Builder(MainActivity.this)
- .setItems(options, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int item) {
- if (options[item].equals(getString(R.string.help_license__name))) {
- final SpannableString s = new SpannableString(Html.fromHtml(getString(R.string.help_license__content)));
- Linkify.addLinks(s, Linkify.WEB_URLS);
- final AlertDialog d = new AlertDialog.Builder(MainActivity.this)
- .setTitle(R.string.help_license__years)
- .setMessage(s)
- .setPositiveButton(android.R.string.yes, null).show();
- d.show();
- ((TextView) d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
- }
- if (options[item].equals(getString(R.string.help_markdown__name))) {
- Helpers.loadUrlInExternalBrowser(MainActivity.this, getString(R.string.help_markdown__weblink));
- }
- }
- }).show();
+ case R.id.nav_about: {
+ startActivity(new Intent(MainActivity.this, AboutActivity.class));
}
break;
}
@@ -1076,13 +1202,22 @@ public class MainActivity extends AppCompatActivity
return true;
}
+ /**
+ * React to results of requestPermission
+ *
+ * @param requestCode resCode
+ * @param permissions requested permissions
+ * @param grantResults granted results
+ */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
- case REQUEST_CODE_ASK_PERMISSIONS_SAVE_IMAGE:
+ case REQUEST_CODE__ACCESS_EXTERNAL_STORAGE:
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
+ AppLog.i(this, "onRequestPermissionsResult: Permission to access external storage granted");
Toast.makeText(this, R.string.permission_granted_try_again, Toast.LENGTH_SHORT).show();
} else {
+ AppLog.w(this, "onRequestPermissionsResult: Permission to access external storage denied");
Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show();
}
return;
@@ -1094,63 +1229,51 @@ public class MainActivity extends AppCompatActivity
}
/**
- * Set proxy according to arguments. host must not be "" or null, port must be positive.
- * Return true on success and update appSettings' proxy related values.
+ * Return the string that will be shared into the new-post-editor
*
- * @param host proxy host (eg. localhost or 127.0.0.1)
- * @param port proxy port (eg. 8118)
- * @return success
- * @throws IllegalArgumentException if arguments do not fit specifications above
+ * @return String
*/
- private boolean setProxy(final String host, final int port) {
- if (host != null && !host.equals("") && port >= 0) {
- //Temporary change thread policy
- StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
- StrictMode.ThreadPolicy tmp = new StrictMode.ThreadPolicy.Builder().permitAll().build();
- StrictMode.setThreadPolicy(tmp);
+ public String getTextToBeShared() {
+ return textToBeShared;
+ }
- NetCipher.setProxy(host, port); //Proxy for HttpsUrlConnections
- try {
- //Proxy for the webview
- WebkitProxy.setProxy(MainActivity.class.getName(), getApplicationContext(), null, host, port);
- } catch (Exception e) { /*Nothing we can do*/ }
+ /**
+ * Set the string that will be shared into the new-post-editor
+ *
+ * @param textToBeShared text that will be shared into the post-editor
+ */
+ public void setTextToBeShared(String textToBeShared) {
+ this.textToBeShared = textToBeShared;
+ }
- appSettings.setProxyEnabled(true);
- appSettings.setProxyWasEnabled(true);
-
- StrictMode.setThreadPolicy(old);
- webView.reload();
- return true;
- } else {
- return false;
+ @Override
+ protected void applyColorToViews() {
+ ThemeHelper.updateToolbarColor(toolbarTop);
+ navDrawerLayout.setBackgroundColor(_appSettings.getPrimaryColor());
+ navProfilePictureArea.setBackgroundColor(_appSettings.getPrimaryColor());
+ if (_appSettings.isAmoledColorMode()) {
+ navView.setItemTextColor(ColorStateList.valueOf(Color.GRAY));
+ navView.setItemIconTintList(ColorStateList.valueOf(Color.GRAY));
+ navView.setBackgroundColor(Color.BLACK);
+ 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);
}
- private boolean setProxy() {
- return setProxy(appSettings.getProxyHost(), appSettings.getProxyPort());
- }
+ public void setToolbarIntellihide(boolean enable) {
+ AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbarTop.getLayoutParams();
+ if (enable) {
+ AppLog.d(this, "Enable Intellihide");
+ params.setScrollFlags(toolbarDefaultScrollFlags);
- private void resetProxy() {
- appSettings.setProxyEnabled(false);
- appSettings.setProxyWasEnabled(false);
-
- //Temporary change thread policy
- StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
- StrictMode.ThreadPolicy tmp = new StrictMode.ThreadPolicy.Builder().permitAll().build();
- StrictMode.setThreadPolicy(tmp);
-
- NetCipher.clearProxy();
- try {
- WebkitProxy.resetProxy(MainActivity.class.getName(), this);
- } catch (Exception e) {/*Nothing*/}
-
- StrictMode.setThreadPolicy(old);
-
- //Restart app
- Intent restartActivity = new Intent(this, MainActivity.class);
- PendingIntent pendingIntent = PendingIntent.getActivity(this, 12374, restartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
- AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
- mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent);
- System.exit(0);
+ } else {
+ AppLog.d(this, "Disable Intellihide");
+ params.setScrollFlags(0); // clear all scroll flags
+ }
+ appBarLayout.setExpanded(true, true);
}
}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/activity/PodSelectionActivity.java b/app/src/main/java/com/github/dfa/diaspora_android/activity/PodSelectionActivity.java
deleted file mode 100644
index 9dea2697..00000000
--- a/app/src/main/java/com/github/dfa/diaspora_android/activity/PodSelectionActivity.java
+++ /dev/null
@@ -1,248 +0,0 @@
-/*
- This file is part of the Diaspora for Android.
-
- Diaspora for Android 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.
-
- Diaspora for Android 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 Diaspora for Android.
-
- If not, see .
- */
-package com.github.dfa.diaspora_android.activity;
-
-import android.app.AlertDialog;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.os.Build;
-import android.os.Bundle;
-import android.support.design.widget.Snackbar;
-import android.support.v4.content.LocalBroadcastManager;
-import android.support.v7.app.AppCompatActivity;
-import android.support.v7.widget.Toolbar;
-import android.text.Editable;
-import android.text.SpannableString;
-import android.text.TextWatcher;
-import android.text.util.Linkify;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.View;
-import android.webkit.CookieManager;
-import android.widget.ArrayAdapter;
-import android.widget.EditText;
-import android.widget.ListView;
-
-import com.github.dfa.diaspora_android.App;
-import com.github.dfa.diaspora_android.R;
-import com.github.dfa.diaspora_android.task.GetPodsService;
-import com.github.dfa.diaspora_android.util.Helpers;
-import com.github.dfa.diaspora_android.util.WebHelper;
-
-import java.util.ArrayList;
-
-import butterknife.BindView;
-import butterknife.ButterKnife;
-import butterknife.OnClick;
-import butterknife.OnItemClick;
-
-
-public class PodSelectionActivity extends AppCompatActivity {
- private App app;
-
- @BindView(R.id.podselection__edit_filter)
- public EditText editFilter;
-
- @BindView(R.id.podselection__listpods)
- public ListView listPods;
-
- @BindView(R.id.toolbar)
- public Toolbar toolbar;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.podselection__activity);
- ButterKnife.bind(this);
- app = (App) getApplication();
- setSupportActionBar(toolbar);
-
-
- listPods.setTextFilterEnabled(true);
- setListedPods(app.getSettings().getPreviousPodlist());
- LocalBroadcastManager.getInstance(this).registerReceiver(podListReceiver, new IntentFilter(GetPodsService.MESSAGE_PODS_RECEIVED));
-
- if (!WebHelper.isOnline(PodSelectionActivity.this)) {
- Snackbar.make(listPods, R.string.no_internet, Snackbar.LENGTH_LONG).show();
- }
- }
-
-
- private final BroadcastReceiver podListReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- if (intent.hasExtra("pods")) {
- Bundle extras = intent.getExtras();
- String[] pods = extras.getStringArray("pods");
- if (pods != null && pods.length > 0) {
- app.getSettings().setPreviousPodlist(pods);
- setListedPods(pods);
- } else {
- setListedPods(app.getSettings().getPreviousPodlist());
- Snackbar.make(listPods, R.string.podlist_error, Snackbar.LENGTH_SHORT).show();
- }
- }
- }
- };
-
- @OnClick(R.id.podselection__button_select_pod)
- public void onButtonSelectPodClicked(View view) {
- if (editFilter.getText().length() > 4 && editFilter.getText().toString().contains("")) {
- showPodConfirmationDialog(editFilter.getText().toString());
- } else {
- Snackbar.make(listPods, R.string.valid_pod, Snackbar.LENGTH_LONG).show();
- }
- }
-
- @Override
- protected void onResume() {
- super.onResume();
- Intent i = new Intent(PodSelectionActivity.this, GetPodsService.class);
- startService(i);
- }
-
-
- private void setListedPods(String[] listedPodsArr) {
- final ArrayList listedPodsList = new ArrayList<>();
- for (String pod : listedPodsArr) {
- listedPodsList.add(pod.toLowerCase());
- }
-
- final ArrayAdapter adapter = new ArrayAdapter<>(
- PodSelectionActivity.this,
- android.R.layout.simple_list_item_1,
- listedPodsList);
-
- // save index and top position
- int index = listPods.getFirstVisiblePosition();
- View v = listPods.getChildAt(0);
- int top = (v == null) ? 0 : (v.getTop() - listPods.getPaddingTop());
- listPods.setAdapter(adapter);
- listPods.setSelectionFromTop(index, top);
-
- adapter.getFilter().filter(editFilter.getText());
- editFilter.addTextChangedListener(new TextWatcher() {
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- (adapter).getFilter().filter(s.toString());
- }
-
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
-
- public void afterTextChanged(Editable s) {
- }
- });
- }
-
- @OnItemClick(R.id.podselection__listpods)
- public void onListPodsItemClicked(int position) {
- showPodConfirmationDialog((String) listPods.getAdapter().getItem(position));
- }
-
- private void showPodConfirmationDialog(final String selectedPod) {
- // Make a clickable link
- final SpannableString dialogMessage = new SpannableString(getString(R.string.confirm_pod, selectedPod));
- Linkify.addLinks(dialogMessage, Linkify.ALL);
-
- // Check if online
- if (!WebHelper.isOnline(PodSelectionActivity.this)) {
- Snackbar.make(listPods, R.string.no_internet, Snackbar.LENGTH_LONG).show();
- return;
- }
-
- // Show dialog
- new AlertDialog.Builder(PodSelectionActivity.this)
- .setTitle(getString(R.string.confirmation))
- .setMessage(dialogMessage)
- .setPositiveButton(android.R.string.yes,
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- onPodSelectionConfirmed(selectedPod);
- }
- })
- .setNegativeButton(android.R.string.no, null)
- .show();
- }
-
- public void onPodSelectionConfirmed(String selectedPod) {
- app.getSettings().setPodDomain(selectedPod);
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- try {
- CookieManager.getInstance().removeAllCookies(null);
- CookieManager.getInstance().removeSessionCookies(null);
- } catch (Exception e) {
- e.printStackTrace();
- }
- } else {
- try {
- CookieManager.getInstance().removeAllCookie();
- CookieManager.getInstance().removeSessionCookie();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- Helpers.animateToActivity(this, MainActivity.class, true);
- }
-
-
- @Override
- public void onBackPressed() {
- Snackbar.make(listPods, R.string.confirm_exit, Snackbar.LENGTH_LONG)
- .setAction(android.R.string.yes, new View.OnClickListener() {
- public void onClick(View view) {
- finish();
- }
- })
- .show();
- }
-
- @Override
- protected void onDestroy() {
- LocalBroadcastManager.getInstance(this).unregisterReceiver(podListReceiver);
- super.onDestroy();
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.pods__menu, menu);
- return true;
- }
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.action_reload: {
- if (WebHelper.isOnline(PodSelectionActivity.this)) {
- Intent i = new Intent(PodSelectionActivity.this, GetPodsService.class);
- startService(i);
- return true;
- } else {
- Snackbar.make(listPods, R.string.no_internet, Snackbar.LENGTH_LONG).show();
- return false;
- }
- }
- }
- return super.onOptionsItemSelected(item);
- }
-}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/activity/PodSelectionFragment.java b/app/src/main/java/com/github/dfa/diaspora_android/activity/PodSelectionFragment.java
new file mode 100644
index 00000000..24da3d47
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/activity/PodSelectionFragment.java
@@ -0,0 +1,311 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.activity;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+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.Menu;
+import android.view.MenuInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.webkit.CookieManager;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.ListView;
+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.DiasporaPodList;
+import com.github.dfa.diaspora_android.data.DiasporaPodList.DiasporaPod;
+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.AppSettings;
+import com.github.dfa.diaspora_android.util.ContextUtils;
+import com.github.dfa.diaspora_android.util.DiasporaUrlHelper;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.ArrayList;
+
+import butterknife.BindView;
+import butterknife.ButterKnife;
+import butterknife.OnClick;
+
+/**
+ * Fragment that lets the user choose a Pod
+ * Created by vanitas on 01.10.16.
+ */
+
+public class PodSelectionFragment extends ThemedFragment implements SearchView.OnQueryTextListener, PodSelectionDialog.PodSelectionDialogResultListener {
+ public static final String TAG = "com.github.dfa.diaspora_android.PodSelectionFragment";
+
+ @BindView(R.id.podselection__fragment__listpods)
+ protected ListView listViewPod;
+
+ @BindView(R.id.podselection__fragment__root)
+ RelativeLayout rootView;
+
+ @BindView(R.id.podselection__fragment__button_use_custom_pod)
+ AppCompatButton buttonUseCustomPod;
+
+
+ protected App app;
+ protected AppSettings appSettings;
+ private DiasporaPodList podList;
+ private ArrayAdapter listViewPodAdapter;
+ private String filterString = "";
+
+ @Override
+ 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();
+
+ // Load local podlist
+ podList = new DiasporaPodList();
+ mergePodlistWithRessources(podList);
+ podList.setTrackMergeChanges(true);
+ updateListedPods();
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ listViewPod.setNestedScrollingEnabled(true);
+ }
+
+ listViewPod.setTextFilterEnabled(true);
+ listViewPod.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+ public void onItemClick(AdapterView> adapterView, View view, int i, long l) {
+ String text = ((TextView) view).getText().toString();
+ for (DiasporaPod pod : podList) {
+ if (pod.getPodUrl().getHost().equals(text)) {
+ showPodSelectionDialog(pod);
+ return;
+ }
+ }
+
+ }
+ });
+ LocalBroadcastManager.getInstance(getContext()).registerReceiver(podListReceiver, new IntentFilter(FetchPodsService.MESSAGE_PODS_RECEIVED));
+ ActivityUtils.get(getActivity()).showInfoIfUserNotConnectedToInternet(listViewPod);
+ }
+
+ public void mergePodlistWithRessources(DiasporaPodList podlist) {
+ String sPodlist = ContextUtils.get().readTextfileFromRawRes(R.raw.podlist, "", "");
+ try {
+ JSONObject jPodlist = new JSONObject(sPodlist);
+ podlist.mergeWithNewerEntries(new DiasporaPodList().fromJson(jPodlist));
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @OnClick(R.id.podselection__fragment__button_use_custom_pod)
+ public void onPodButtonClicked(View v) {
+ showPodSelectionDialog(new DiasporaPod());
+ }
+
+ @Override
+ public String getFragmentTag() {
+ return TAG;
+ }
+
+ private final BroadcastReceiver podListReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (intent.hasExtra(FetchPodsService.EXTRA_PODLIST)) {
+ Bundle extras = intent.getExtras();
+ DiasporaPodList newPods = (DiasporaPodList) extras.get(FetchPodsService.EXTRA_PODLIST);
+ if (newPods != null && newPods.getPods().size() > 0) {
+ try {
+ podList.mergeWithNewerEntries(newPods);
+ updateListedPods();
+ } catch (JSONException ignored) {
+ }
+ } else {
+ Snackbar.make(listViewPod, R.string.could_not_retrieve_list_of_pods__appspecific, Snackbar.LENGTH_SHORT).show();
+ }
+ }
+ }
+ };
+
+ @Override
+ protected void applyColorToViews() {
+ int dividerHeight = listViewPod.getDividerHeight();
+ rootView.setBackgroundColor(appSettings.isAmoledColorMode() ? Color.BLACK : Color.WHITE);
+ listViewPod.setDivider(new ColorDrawable(Color.GRAY));
+ listViewPod.setDividerHeight(dividerHeight);
+ int bgcolor = appSettings.isAmoledColorMode() ? Color.DKGRAY : appSettings.getAccentColor();
+ buttonUseCustomPod.setBackgroundColor(bgcolor);
+ buttonUseCustomPod.setTextColor(_cu.shouldColorOnTopBeLight(bgcolor) ? Color.WHITE : Color.BLACK);
+
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ Intent i = new Intent(getContext(), FetchPodsService.class);
+ getContext().startService(i);
+ }
+
+ private void updateListedPods() {
+ final ArrayList listedPodsList = new ArrayList<>();
+ for (DiasporaPod pod : this.podList) {
+ listedPodsList.add(pod.getPodUrl().getHost());
+ }
+
+ listViewPodAdapter = new ArrayAdapter(
+ getContext(),
+ android.R.layout.simple_list_item_1,
+ listedPodsList) {
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ View view = super.getView(position, convertView, parent);
+ TextView textView = view.findViewById(android.R.id.text1);
+ textView.setTextColor(appSettings.isAmoledColorMode() ? Color.GRAY : Color.BLACK);
+ return view;
+ }
+ };
+
+ // save index and top position
+ int index = listViewPod.getFirstVisiblePosition();
+ View v = listViewPod.getChildAt(0);
+ int top = (v == null) ? 0 : (v.getTop() - listViewPod.getPaddingTop());
+ listViewPod.setAdapter(listViewPodAdapter);
+ listViewPod.setSelectionFromTop(index, top);
+
+ listViewPodAdapter.getFilter().filter(filterString);
+ }
+
+ private void showPodSelectionDialog(final DiasporaPod selectedPod) {
+ PodSelectionDialog dialog = PodSelectionDialog.newInstance(selectedPod, this);
+ dialog.show(getFragmentManager(), PodSelectionDialog.TAG);
+ }
+
+ @Override
+ public void onDestroy() {
+ LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(podListReceiver);
+ super.onDestroy();
+ }
+
+ @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);
+ if (searchItem != null) {
+ SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
+ searchView.setOnQueryTextListener(this);
+ }
+
+ 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
+ public boolean onOptionsItemSelected(MenuItem item) {
+ switch (item.getItemId()) {
+ case R.id.action_reload: {
+ if (!ActivityUtils.get(getActivity()).showInfoIfUserNotConnectedToInternet(listViewPod)) {
+ Intent i = new Intent(getContext(), FetchPodsService.class);
+ getContext().startService(i);
+ return true;
+ }
+ }
+ }
+ return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public boolean onQueryTextChange(String newText) {
+ if (listViewPodAdapter != null) {
+ (listViewPodAdapter).getFilter().filter(newText);
+ }
+ return true;
+ }
+
+ @Override
+ public void onPodSelectionDialogResult(DiasporaPod pod, boolean accepted) {
+ System.out.println(accepted + ": " + pod.toString());
+ if (accepted) {
+ app.getSettings().setPod(pod);
+
+ try {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ CookieManager.getInstance().removeAllCookies(null);
+ CookieManager.getInstance().removeSessionCookies(null);
+ } else {
+ //noinspection deprecation
+ CookieManager.getInstance().removeAllCookie();
+ //noinspection deprecation
+ CookieManager.getInstance().removeSessionCookie();
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ MainActivity mainActivity = (MainActivity) getActivity();
+ DiasporaUrlHelper urlHelper = new DiasporaUrlHelper(appSettings);
+ mainActivity.onPodSelectionDialogResult(pod, accepted);
+ mainActivity.openDiasporaUrl(urlHelper.getSignInUrl());
+ }
+ }
+
+
+ /*
+ * Dummy implementations
+ */
+ @Override
+ public boolean onQueryTextSubmit(String query) {
+ return false;
+ }
+
+ @Override
+ public boolean onBackPressed() {
+ return false;
+ }
+
+ @Override
+ public boolean isAllowedIntellihide() {
+ return false;
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/activity/SettingsActivity.java b/app/src/main/java/com/github/dfa/diaspora_android/activity/SettingsActivity.java
index 9a82ee09..0a38744e 100644
--- a/app/src/main/java/com/github/dfa/diaspora_android/activity/SettingsActivity.java
+++ b/app/src/main/java/com/github/dfa/diaspora_android/activity/SettingsActivity.java
@@ -1,122 +1,232 @@
-/*
- This file is part of the Diaspora for Android.
-
- Diaspora for Android 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.
-
- Diaspora for Android 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 Diaspora for Android.
-
- If not, see .
- */
package com.github.dfa.diaspora_android.activity;
-import android.app.AlertDialog;
+import android.annotation.SuppressLint;
+import android.app.AlarmManager;
+import android.app.FragmentTransaction;
+import android.app.PendingIntent;
+import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
+import android.os.Build;
import android.os.Bundle;
-import android.preference.EditTextPreference;
-import android.preference.ListPreference;
import android.preference.Preference;
-import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
+import android.support.design.widget.AppBarLayout;
+import android.support.v7.widget.Toolbar;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.FrameLayout;
+import android.widget.TextView;
+import android.widget.Toast;
import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.R;
+import com.github.dfa.diaspora_android.ui.theme.ColorPalette;
+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.ThemedPreferenceFragment;
+import com.github.dfa.diaspora_android.util.AppLog;
+import com.github.dfa.diaspora_android.util.AppSettings;
+import com.github.dfa.diaspora_android.util.DiasporaUrlHelper;
+import com.github.dfa.diaspora_android.web.ProxyHandler;
-/**
- * @author vanitas
- */
-public class SettingsActivity extends PreferenceActivity {
- private boolean activityRestartRequired;
+import butterknife.BindView;
+import butterknife.ButterKnife;
+import uz.shift.colorpicker.LineColorPicker;
+import uz.shift.colorpicker.OnColorChangedListener;
+
+public class SettingsActivity extends ThemedActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
+
+ //Toolbar
+ @BindView(R.id.settings__appbar)
+ protected AppBarLayout appBarLayout;
+
+ @BindView(R.id.settings__toolbar)
+ protected Toolbar toolbar;
+
+ private ProxyHandler.ProxySettings oldProxySettings;
+
+ public void onCreate(Bundle b) {
+ super.onCreate(b);
+ setContentView(R.layout.settings__activity);
+ ButterKnife.bind(this);
+ toolbar.setTitle(R.string.settings);
+ setSupportActionBar(toolbar);
+
+ toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white_24px));
+ toolbar.setNavigationOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ SettingsActivity.this.onBackPressed();
+ }
+ });
+ getAppSettings().registerPreferenceChangedListener(this);
+ oldProxySettings = getAppSettings().getProxySettings();
+ showFragment(SettingsFragmentMaster.TAG, false);
+ }
+
+ protected void showFragment(String tag, boolean addToBackStack) {
+ PreferenceFragment fragment = (PreferenceFragment) getFragmentManager().findFragmentByTag(tag);
+ if (fragment == null) {
+ switch (tag) {
+ case SettingsFragmentThemes.TAG:
+ fragment = new SettingsFragmentThemes();
+ break;
+ case SettingsFragmentNavSlider.TAG:
+ fragment = new SettingsFragmentNavSlider();
+ break;
+ case SettingsFragmentProxy.TAG:
+ fragment = new SettingsFragmentProxy();
+ break;
+ case SettingsFragmentDebugging.TAG:
+ fragment = new SettingsFragmentDebugging();
+ break;
+ case SettingsFragmentMaster.TAG:
+ default:
+ fragment = new SettingsFragmentMaster();
+ break;
+ }
+ }
+ FragmentTransaction t = getFragmentManager().beginTransaction();
+ if (addToBackStack) {
+ t.addToBackStack(tag);
+ }
+ t.replace(R.id.settings__fragment_container, fragment, tag).commit();
+ }
@Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
+ public void applyColorToViews() {
+ //Toolbar
+ ThemeHelper.updateToolbarColor(toolbar);
}
- public void setActivityRestartRequired(boolean b) {
- this.activityRestartRequired = b;
+ @Override
+ protected void onStop() {
+ ProxyHandler.ProxySettings newProxySettings = getAppSettings().getProxySettings();
+ if (!oldProxySettings.equals(newProxySettings)) {
+ AppLog.d(this, "ProxySettings changed.");
+ //Proxy on-off? => Restart app
+ if (oldProxySettings.isEnabled() && !newProxySettings.isEnabled()) {
+ AppLog.d(this, "Proxy deactivated. Restarting app...");
+ Intent restartActivity = new Intent(SettingsActivity.this, MainActivity.class);
+ PendingIntent pendingIntent = PendingIntent.getActivity(SettingsActivity.this, 12374, restartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
+ AlarmManager mgr = (AlarmManager) SettingsActivity.this.getSystemService(Context.ALARM_SERVICE);
+ mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent);
+ System.exit(0);
+ } //Proxy changed? => Update
+ else {
+ ProxyHandler.getInstance().updateProxySettings(this);
+ }
+ }
+ getAppSettings().unregisterPreferenceChangedListener(this);
+ super.onStop();
}
- public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
- private SharedPreferences sharedPreferences;
+ @Override
+ public void onBackPressed() {
+ ThemedPreferenceFragment top = getTopFragment();
+ if (top != null && top.getFragmentTag().equals(SettingsFragmentProxy.TAG)) {
+ ProxyHandler.ProxySettings newProxySettings = getAppSettings().getProxySettings();
+ if (oldProxySettings.isEnabled() && !newProxySettings.isEnabled()) {
+ Toast.makeText(this, R.string.app_needs_restart_to_disable_proxy_usage, Toast.LENGTH_LONG).show();
+ }
+ }
+ super.onBackPressed();
+ }
+
+ /**
+ * Return the fragment which is currently displayed in R.id.fragment_container
+ *
+ * @return top fragment or null if there is none displayed
+ */
+ private ThemedPreferenceFragment getTopFragment() {
+ return (ThemedPreferenceFragment) getFragmentManager().findFragmentById(R.id.settings__fragment_container);
+ }
+
+ @Override
+ public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
+ if (key.equals(getString(R.string.pref_key__screen_rotation))) {
+ this.updateScreenRotation();
+ }
+ }
+
+ public static class SettingsFragmentMaster extends ThemedPreferenceFragment {
+ public static final String TAG = "com.github.dfa.diaspora_android.settings.SettingsFragmentMaster";
public void onCreate(Bundle savedInstances) {
super.onCreate(savedInstances);
getPreferenceManager().setSharedPreferencesName("app");
- addPreferencesFromResource(R.xml.preferences);
- sharedPreferences = getPreferenceScreen().getSharedPreferences();
- sharedPreferences.registerOnSharedPreferenceChangeListener(this);
- setPreferenceSummaries();
- sharedPreferences.edit().putBoolean(getString(R.string.pref_key__proxy_was_enabled),
- sharedPreferences.getBoolean(getString(R.string.pref_key__proxy_enabled), false)).apply();
- }
-
- private void setPreferenceSummaries() {
- String[] editTextKeys = new String[]{
- getString(R.string.pref_key__proxy_host), getString(R.string.pref_key__proxy_port)
- };
- for (String key : editTextKeys) {
- EditTextPreference p = (EditTextPreference) findPreference(key);
- p.setSummary(p.getText());
- }
+ addPreferencesFromResource(R.xml.preferences__master);
}
@Override
- public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
- updatePreference(findPreference(key));
- }
+ public void updateViewColors() {
- private void updatePreference(Preference preference) {
- if (preference == null) {
- return;
- }
- if (preference instanceof EditTextPreference) {
- EditTextPreference textPref = (EditTextPreference) preference;
- textPref.setSummary(textPref.getText());
- return;
- }
- if (preference instanceof ListPreference) {
- ListPreference listPref = (ListPreference) preference;
- listPref.setSummary(listPref.getEntry());
- }
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) {
- Intent intent = new Intent(getActivity(), MainActivity.class);
- String podDomain = ((App) getActivity().getApplication()).getSettings().getPodDomain();
- switch (preference.getTitleRes()) {
- case R.string.pref_title__personal_settings: {
- intent.setAction(MainActivity.ACTION_OPEN_URL);
- intent.putExtra(MainActivity.URL_MESSAGE, "https://" + podDomain + "/user/edit");
- break;
+ if (isAdded() && preference.hasKey()) {
+ AppSettings settings = ((App) getActivity().getApplication()).getSettings();
+ DiasporaUrlHelper diasporaUrlHelper = new DiasporaUrlHelper(settings);
+ String key = preference.getKey();
+ /** Sub-Categories */
+ if (settings.isKeyEqual(key, R.string.pref_key__cat_themes)) {
+ ((SettingsActivity) getActivity()).showFragment(SettingsFragmentThemes.TAG, true);
+ return true;
+ } else if (settings.isKeyEqual(key, R.string.pref_key__cat_nav_slider)) {
+ ((SettingsActivity) getActivity()).showFragment(SettingsFragmentNavSlider.TAG, true);
+ return true;
+ } else if (settings.isKeyEqual(key, R.string.pref_key__cat_proxy)) {
+ ((SettingsActivity) getActivity()).showFragment(SettingsFragmentProxy.TAG, true);
+ return true;
+ } else if (settings.isKeyEqual(key, R.string.pref_key__cat_debugging)) {
+ ((SettingsActivity) getActivity()).showFragment(SettingsFragmentDebugging.TAG, true);
+ return true;
}
- case R.string.pref_title__manage_tags: {
- intent.setAction(MainActivity.ACTION_OPEN_URL);
- intent.putExtra(MainActivity.URL_MESSAGE, "https://" + podDomain + "/tag_followings/manage");
- break;
+ /** 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)) {
+ AppSettings.get().setRecreateMainActivity(true);
}
- case R.string.pref_title__manage_contacts: {
- intent.setAction(MainActivity.ACTION_OPEN_URL);
- intent.putExtra(MainActivity.URL_MESSAGE, "https://" + podDomain + "/contacts");
- break;
+ /** Network */
+ else if (settings.isKeyEqual(key, R.string.pref_key__clear_cache)) {
+ Intent intent = new Intent(getActivity(), MainActivity.class);
+ intent.setAction(MainActivity.ACTION_CLEAR_CACHE);
+ startActivity(intent);
+ getActivity().finish();
+ return true;
}
- case R.string.pref_title__change_account: {
- new AlertDialog.Builder(getActivity())
+ /** Pod Settings */
+ if (settings.isKeyEqual(key, R.string.pref_key__personal_settings)) {
+ Intent intent = new Intent(getActivity(), MainActivity.class);
+ intent.setAction(MainActivity.ACTION_OPEN_URL);
+ intent.putExtra(MainActivity.URL_MESSAGE, diasporaUrlHelper.getPersonalSettingsUrl());
+ startActivity(intent);
+ getActivity().finish();
+ return true;
+ } else if (settings.isKeyEqual(key, R.string.pref_key__manage_tags)) {
+ Intent intent = new Intent(getActivity(), MainActivity.class);
+ intent.setAction(MainActivity.ACTION_OPEN_URL);
+ intent.putExtra(MainActivity.URL_MESSAGE, diasporaUrlHelper.getManageTagsUrl());
+ startActivity(intent);
+ getActivity().finish();
+ return true;
+ } else if (settings.isKeyEqual(key, R.string.pref_key__manage_contacts)) {
+ Intent intent = new Intent(getActivity(), MainActivity.class);
+ intent.setAction(MainActivity.ACTION_OPEN_URL);
+ intent.putExtra(MainActivity.URL_MESSAGE, diasporaUrlHelper.getContactsUrl());
+ startActivity(intent);
+ getActivity().finish();
+ return true;
+ } 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() {
@@ -129,41 +239,263 @@ public class SettingsActivity extends PreferenceActivity {
})
.show();
return true;
- }
- case R.string.pref_title__clear_cache: {
- intent.setAction(MainActivity.ACTION_CLEAR_CACHE);
- break;
- }
- case R.string.pref_title__intellihide_toolbars: {
- ((SettingsActivity) getActivity()).setActivityRestartRequired(true);
- return true;
- }
- default: {
- intent = null;
- break;
}
}
- if (preference.getKey() != null && preference.getKey().startsWith("pref_key__visibility_nav__")) {
- ((SettingsActivity) getActivity()).setActivityRestartRequired(true);
- return true;
- }
- if (intent != null) {
- startActivity(intent);
- getActivity().finish();
- return true;
- }
return super.onPreferenceTreeClick(screen, preference);
}
+
+ @Override
+ public String getFragmentTag() {
+ return TAG;
+ }
}
- @Override
- protected void onStop() {
- super.onStop();
- if (activityRestartRequired) {
- Intent intent = new Intent(this, MainActivity.class);
- intent.setAction(MainActivity.ACTION_RELOAD_ACTIVITY);
- startActivity(intent);
+ public static class SettingsFragmentThemes extends ThemedPreferenceFragment {
+ public static final String TAG = "com.github.dfa.diaspora_android.settings.SettingsFragmentThemes";
+
+ public void onCreate(Bundle savedInstances) {
+ super.onCreate(savedInstances);
+ getPreferenceManager().setSharedPreferencesName("app");
+ addPreferencesFromResource(R.xml.preferences__sub_themes);
+ }
+
+ @Override
+ public void updateViewColors() {
+ if (isAdded()) {
+ //Trigger redraw of whole preference screen in order to reflect changes
+ setPreferenceScreen(null);
+ addPreferencesFromResource(R.xml.preferences__sub_themes);
+ }
+ }
+
+ @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))) {
+ showColorPickerDialog(1);
+ return true;
+ } 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);
+ }
+
+ @Override
+ public String getFragmentTag() {
+ return TAG;
+ }
+
+ /**
+ * Show a colorPicker Dialog
+ *
+ * @param type 1 -> Primary Color, 2 -> Accent Color
+ */
+ @SuppressLint("InflateParams")
+ public void showColorPickerDialog(final int type) {
+ final AppSettings appSettings = ((App) getActivity().getApplication()).getSettings();
+ final Context context = getActivity();
+
+ //Inflate dialog layout
+ LayoutInflater inflater = getActivity().getLayoutInflater();
+ View dialogLayout = inflater.inflate(R.layout.ui__dialog__color_picker, null);
+ final ThemedAlertDialogBuilder builder = new ThemedAlertDialogBuilder(context, appSettings);
+ builder.setView(dialogLayout);
+
+ 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.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)));
+ base.setSelectedColor(current[0]);
+ shade.setColors(ColorPalette.getColors(context, current[0]));
+ shade.setSelectedColor(current[1]);
+ titleBackground.setBackgroundColor(shade.getColor());
+ base.setOnColorChangedListener(new OnColorChangedListener() {
+ @Override
+ public void onColorChanged(int i) {
+ shade.setColors(ColorPalette.getColors(context, i));
+ titleBackground.setBackgroundColor(i);
+ if (i == current[0]) {
+ shade.setSelectedColor(current[1]);
+ titleBackground.setBackgroundColor(shade.getColor());
+ } else {
+ shade.setSelectedColor(i);
+ }
+ }
+ });
+ shade.setOnColorChangedListener(new OnColorChangedListener() {
+ @Override
+ public void onColorChanged(int i) {
+ titleBackground.setBackgroundColor(i);
+ }
+ });
+
+ //Build dialog
+ builder
+ .setNegativeButton(android.R.string.cancel, null)
+ .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(DialogInterface dialogInterface, int i) {
+ if (type == 1) {
+ appSettings.setPrimaryColorSettings(base.getColor(), shade.getColor());
+ if (Build.VERSION.SDK_INT >= 21) {
+ getActivity().getWindow().setStatusBarColor(ThemeHelper.getPrimaryDarkColor());
+ }
+ ((SettingsActivity) getActivity()).applyColorToViews();
+ } else {
+ appSettings.setAccentColorSettings(base.getColor(), shade.getColor());
+ }
+ updateViewColors();
+ }
+ }).show();
+ }
+ }
+
+ public static class SettingsFragmentNavSlider extends ThemedPreferenceFragment {
+ public static final String TAG = "com.github.dfa.diaspora_android.settings.SettingsFragmentNavSlider";
+
+ public void onCreate(Bundle savedInstances) {
+ super.onCreate(savedInstances);
+ getPreferenceManager().setSharedPreferencesName("app");
+ addPreferencesFromResource(R.xml.preferences__sub_navslider_vis);
+ }
+
+ @Override
+ public void updateViewColors() {
+
+ }
+
+ @Override
+ public String getFragmentTag() {
+ return TAG;
+ }
+ }
+
+ public static class SettingsFragmentProxy extends ThemedPreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
+ public static final String TAG = "com.github.dfa.diaspora_android.settings.SettingsFragmentProxy";
+
+ public void onCreate(Bundle savedInstances) {
+ super.onCreate(savedInstances);
+ getPreferenceManager().setSharedPreferencesName("app");
+ addPreferencesFromResource(R.xml.preferences__sub_proxy);
+ SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences();
+ sharedPreferences.registerOnSharedPreferenceChangeListener(this);
+ }
+
+ @Override
+ public void onActivityCreated(Bundle bundle) {
+ super.onActivityCreated(bundle);
+ updateSummaries();
+ }
+
+ public void updateSummaries() {
+ if (isAdded()) {
+ AppSettings settings = ((App) getActivity().getApplication()).getSettings();
+ findPreference(settings.rstr(R.string.pref_key__http_proxy_host)).setSummary(settings.getProxyHttpHost());
+ findPreference(settings.rstr(R.string.pref_key__http_proxy_port)).setSummary(Integer.toString(settings.getProxyHttpPort()));
+ }
+ }
+
+ @Override
+ public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) {
+ if (isAdded() && preference.hasKey()) {
+ AppSettings appSettings = ((App) getActivity().getApplication()).getSettings();
+ String key = preference.getKey();
+ 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.orbot_proxy_preset_loaded, Toast.LENGTH_SHORT).show();
+ return true;
+ }
+ }
+ return super.onPreferenceTreeClick(screen, preference);
+ }
+
+ @Override
+ public String getFragmentTag() {
+ return TAG;
+ }
+
+ @Override
+ public void updateViewColors() {
+
+ }
+
+ @Override
+ public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
+ if (isAdded()) {
+ if (key.equals(getString(R.string.pref_key__http_proxy_host)) ||
+ key.equals(getString(R.string.pref_key__http_proxy_port))) {
+ updateSummaries();
+ }
+ }
+ }
+ }
+
+ public static class SettingsFragmentDebugging extends ThemedPreferenceFragment {
+ public static final String TAG = "com.github.dfa.diaspora_android.settings.SettingsFragmentDebugging";
+
+ public void onCreate(Bundle savedInstances) {
+ super.onCreate(savedInstances);
+ getPreferenceManager().setSharedPreferencesName("app");
+ addPreferencesFromResource(R.xml.preferences__sub_debugging);
+ }
+
+ @Override
+ public void updateViewColors() {
+
+ }
+
+ @Override
+ public String getFragmentTag() {
+ return TAG;
+ }
+
+ @Override
+ public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) {
+ if (isAdded() && preference.hasKey()) {
+ AppSettings appSettings = ((App) getActivity().getApplication()).getSettings();
+ String key = preference.getKey();
+ if (appSettings.isKeyEqual(key, R.string.pref_key__wipe_settings)) {
+ showWipeSettingsDialog();
+ return true;
+ }
+ }
+ return super.onPreferenceTreeClick(screen, preference);
+ }
+
+ private void showWipeSettingsDialog() {
+ final AppSettings appSettings = AppSettings.get();
+
+ ThemedAlertDialogBuilder builder = new ThemedAlertDialogBuilder(getActivity(), appSettings);
+ builder.setTitle(R.string.confirmation)
+ .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();
+ new net.gsantner.opoc.util.ContextUtils(appSettings.getContext()).restartApp(MainActivity.class);
+ }
+ }).setNegativeButton(android.R.string.cancel, null)
+ .create().show();
}
}
}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/activity/SplashActivity.java b/app/src/main/java/com/github/dfa/diaspora_android/activity/SplashActivity.java
deleted file mode 100644
index 99535239..00000000
--- a/app/src/main/java/com/github/dfa/diaspora_android/activity/SplashActivity.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- This file is part of the Diaspora for Android.
-
- Diaspora for Android 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.
-
- Diaspora for Android 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 Diaspora for Android.
-
- If not, see .
- */
-
-package com.github.dfa.diaspora_android.activity;
-
-import android.content.res.TypedArray;
-import android.os.Bundle;
-import android.os.Handler;
-import android.support.v7.app.AppCompatActivity;
-import android.widget.ImageView;
-
-import com.github.dfa.diaspora_android.App;
-import com.github.dfa.diaspora_android.R;
-import com.github.dfa.diaspora_android.util.Helpers;
-import com.github.dfa.diaspora_android.util.WebHelper;
-
-import butterknife.BindView;
-import butterknife.ButterKnife;
-
-
-public class SplashActivity extends AppCompatActivity {
- private App app;
-
- @BindView(R.id.splash__splashimage)
- public ImageView imgSplash;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.splash__activity);
- ButterKnife.bind(this);
- app = (App) getApplication();
-
- TypedArray images = getResources().obtainTypedArray(R.array.splash_images);
- int choice = (int) (Math.random() * images.length());
- imgSplash.setImageResource(images.getResourceId(choice, R.drawable.splashscreen1));
- images.recycle();
-
- int delay = getResources().getInteger(R.integer.splash_delay);
- new Handler().postDelayed(startActivityRunnable, delay);
- }
-
- final Runnable startActivityRunnable = new Runnable() {
- public void run() {
- boolean hasPodDomain = app.getSettings().hasPodDomain();
- Helpers.animateToActivity(SplashActivity.this,
- hasPodDomain ? MainActivity.class : PodSelectionActivity.class,
- true
- );
- }
- };
-}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/data/AppSettings.java b/app/src/main/java/com/github/dfa/diaspora_android/data/AppSettings.java
deleted file mode 100644
index d99af7ac..00000000
--- a/app/src/main/java/com/github/dfa/diaspora_android/data/AppSettings.java
+++ /dev/null
@@ -1,297 +0,0 @@
-/*
- This file is part of the Diaspora for Android.
-
- Diaspora for Android 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.
-
- Diaspora for Android 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 Diaspora for Android.
-
- If not, see .
- */
-package com.github.dfa.diaspora_android.data;
-
-import android.annotation.SuppressLint;
-import android.content.Context;
-import android.content.SharedPreferences;
-
-import com.github.dfa.diaspora_android.R;
-
-/**
- * Created by gsantner (https://gsantner.github.io/) on 20.03.16. Part of Diaspora for Android.
- */
-public class AppSettings {
- private final SharedPreferences prefApp;
- private final SharedPreferences prefPod;
- private final Context context;
-
- public AppSettings(Context context) {
- this.context = context.getApplicationContext();
- prefApp = this.context.getSharedPreferences("app", Context.MODE_PRIVATE);
- prefPod = this.context.getSharedPreferences("pod0", Context.MODE_PRIVATE);
- }
-
- public Context getApplicationContext() {
- return context;
- }
-
- public void clearPodSettings() {
- prefPod.edit().clear().apply();
- }
-
- public void clearAppSettings() {
- prefApp.edit().clear().apply();
- }
-
- private void setString(SharedPreferences pref, int keyRessourceId, String value) {
- pref.edit().putString(context.getString(keyRessourceId), value).apply();
- }
-
- private void setInt(SharedPreferences pref, int keyRessourceId, int value) {
- pref.edit().putInt(context.getString(keyRessourceId), value).apply();
- }
-
- private void setBool(SharedPreferences pref, int keyRessourceId, boolean value) {
- pref.edit().putBoolean(context.getString(keyRessourceId), value).apply();
- }
-
- private void setStringArray(SharedPreferences pref, int keyRessourceId, Object[] values) {
- StringBuffer sb = new StringBuffer();
- for (Object value : values) {
- sb.append("%%%");
- sb.append(value.toString());
- }
- setString(pref, keyRessourceId, sb.toString().replaceFirst("%%%", ""));
- }
-
- private String[] getStringArray(SharedPreferences pref, int keyRessourceId) {
- String value = pref.getString(context.getString(keyRessourceId), "%%%");
- if (value.equals("%%%")) {
- return new String[0];
- }
- return value.split("%%%");
- }
-
- private String getString(SharedPreferences pref, int ressourceId, String defaultValue) {
- return pref.getString(context.getString(ressourceId), defaultValue);
- }
-
- private boolean getBoolean(SharedPreferences pref, int ressourceId, boolean defaultValue) {
- return pref.getBoolean(context.getString(ressourceId), defaultValue);
- }
-
- private int getInt(SharedPreferences pref, int ressourceId, int defaultValue) {
- return pref.getInt(context.getString(ressourceId), defaultValue);
- }
-
-
- /*
- // Setters & Getters
- */
- public String getProfileId() {
- return getString(prefPod, R.string.pref_key__podprofile_id, "");
- }
-
- public void setProfileId(String profileId) {
- setString(prefPod, R.string.pref_key__podprofile_id, profileId);
- }
-
- public boolean isLoadImages() {
- return getBoolean(prefApp, R.string.pref_key__load_images, true);
- }
-
- public int getMinimumFontSize() {
- switch (getString(prefApp, R.string.pref_key__font_size, "")) {
- case "huge":
- return 20;
- case "large":
- return 16;
- case "normal":
- return 8;
- default:
- setString(prefApp, R.string.pref_key__font_size, "normal");
- return 8;
- }
- }
-
- public String getAvatarUrl() {
- return getString(prefPod, R.string.pref_key__podprofile_avatar_url, "");
- }
-
- public void setAvatarUrl(String avatarUrl) {
- setString(prefPod, R.string.pref_key__podprofile_avatar_url, avatarUrl);
- }
-
- public String getName() {
- return getString(prefPod, R.string.pref_key__podprofile_name, "");
- }
-
- public void setName(String name) {
- setString(prefPod, R.string.pref_key__podprofile_name, name);
- }
-
- public String getPodDomain() {
- return getString(prefPod, R.string.pref_key__poddomain, "");
- }
-
- public void setPodDomain(String podDomain) {
- setString(prefPod, R.string.pref_key__poddomain, podDomain);
- }
-
- public boolean hasPodDomain() {
- return !getString(prefPod, R.string.pref_key__poddomain, "").equals("");
- }
-
- public String[] getPreviousPodlist() {
- return getStringArray(prefApp, R.string.pref_key__previous_podlist);
- }
-
- public void setPreviousPodlist(String[] pods) {
- setStringArray(prefApp, R.string.pref_key__previous_podlist, pods);
- }
-
- public void setPodAspects(PodAspect[] aspects) {
- setStringArray(prefPod, R.string.pref_key__podprofile_aspects, aspects);
- }
-
- public PodAspect[] getPodAspects() {
- String[] s = getStringArray(prefPod, R.string.pref_key__podprofile_aspects);
- PodAspect[] aspects = new PodAspect[s.length];
- for (int i = 0; i < aspects.length; i++) {
- aspects[i] = new PodAspect(s[i]);
- }
- return aspects;
- }
-
- public String[] getFollowedTags() {
- return getStringArray(prefPod, R.string.pref_key__podprofile_followed_tags);
- }
-
- public void setFollowedTags(String[] tags) {
- setStringArray(prefPod, R.string.pref_key__podprofile_followed_tags, tags);
- }
-
- public int getUnreadMessageCount() {
- return getInt(prefPod, R.string.pref_key__podprofile_unread_message_count, 0);
- }
-
- public void setUnreadMessageCount(int unreadMessageCount) {
- setInt(prefPod, R.string.pref_key__podprofile_unread_message_count, unreadMessageCount);
- }
-
- public int getNotificationCount() {
- return getInt(prefPod, R.string.pref_key__podprofile_notification_count, 0);
- }
-
- public void setNotificationCount(int notificationCount) {
- setInt(prefPod, R.string.pref_key__podprofile_notification_count, notificationCount);
- }
-
- public boolean isAppendSharedViaApp() {
- return getBoolean(prefApp, R.string.pref_key__append_shared_via_app, true);
- }
-
- @SuppressLint("CommitPrefEdits")
- public void setProxyEnabled(boolean enabled) {
- //commit instead of apply because the app is likely to be killed before apply is called.
- prefApp.edit().putBoolean(context.getString(R.string.pref_key__proxy_enabled), enabled).commit();
- }
-
- /**
- * Default return value: false
- *
- * @return whether proxy is enabled or not
- */
- public boolean isProxyEnabled() {
- return getBoolean(prefApp, R.string.pref_key__proxy_enabled, false);
- }
-
- public boolean wasProxyEnabled() {
- return getBoolean(prefApp, R.string.pref_key__proxy_was_enabled, false);
- }
-
- /**
- * Needed in order to determine, whether the proxy has just been disabled (trigger app restart)
- * or if proxy was disabled before (do not restart app)
- *
- * @param b new value
- */
- @SuppressLint("CommitPrefEdits")
- public void setProxyWasEnabled(boolean b) {
- prefApp.edit().putBoolean(context.getString(R.string.pref_key__proxy_was_enabled), b).commit();
- }
-
- /**
- * Default value: ""
- *
- * @return proxy host
- */
- public String getProxyHost() {
- return getString(prefApp, R.string.pref_key__proxy_host, "");
- }
-
- /**
- * Default value: 0
- *
- * @return proxy port
- */
- public int getProxyPort() {
- try {
- return Integer.parseInt(getString(prefApp, R.string.pref_key__proxy_port, "0"));
- } catch (Exception e) {
- setString(prefApp, R.string.pref_key__proxy_port, "0");
- return 0;
- }
- }
-
- public boolean isIntellihideToolbars() {
- return getBoolean(prefApp, R.string.pref_key__intellihide_toolbars, true);
- }
-
- public boolean isVisibleInNavExit() {
- return getBoolean(prefApp, R.string.pref_key__visibility_nav__exit, false);
- }
-
- public boolean isVisibleInNavHelp_license() {
- return getBoolean(prefApp, R.string.pref_key__visibility_nav__help_license, true);
- }
-
- public boolean isVisibleInNavPublic_activities() {
- return getBoolean(prefApp, R.string.pref_key__visibility_nav__public_activities, false);
- }
-
- public boolean isVisibleInNavMentions() {
- return getBoolean(prefApp, R.string.pref_key__visibility_nav__mentions, true);
- }
-
- public boolean isVisibleInNavCommented() {
- return getBoolean(prefApp, R.string.pref_key__visibility_nav__commented, true);
- }
-
- public boolean isVisibleInNavLiked() {
- return getBoolean(prefApp, R.string.pref_key__visibility_nav__liked, true);
- }
-
- public boolean isVisibleInNavActivities() {
- return getBoolean(prefApp, R.string.pref_key__visibility_nav__activities, true);
- }
-
- public boolean isVisibleInNavAspects() {
- return getBoolean(prefApp, R.string.pref_key__visibility_nav__aspects, true);
- }
-
- public boolean isVisibleInNavFollowed_tags() {
- return getBoolean(prefApp, R.string.pref_key__visibility_nav__followed_tags, true);
- }
-
- public boolean isVisibleInNavProfile() {
- return getBoolean(prefApp, R.string.pref_key__visibility_nav__profile, false);
- }
-}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/data/PodAspect.java b/app/src/main/java/com/github/dfa/diaspora_android/data/DiasporaAspect.java
similarity index 73%
rename from app/src/main/java/com/github/dfa/diaspora_android/data/PodAspect.java
rename to app/src/main/java/com/github/dfa/diaspora_android/data/DiasporaAspect.java
index b878f679..97ad868d 100644
--- a/app/src/main/java/com/github/dfa/diaspora_android/data/PodAspect.java
+++ b/app/src/main/java/com/github/dfa/diaspora_android/data/DiasporaAspect.java
@@ -1,43 +1,44 @@
/*
- This file is part of the Diaspora for Android.
+ This file is part of the dandelion*.
- Diaspora for Android is free software: you can redistribute it and/or modify
+ 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.
- Diaspora for Android is distributed in the hope that it will be useful,
+ 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 Diaspora for Android.
+ along with the dandelion*.
If not, see .
*/
package com.github.dfa.diaspora_android.data;
import com.github.dfa.diaspora_android.App;
+import com.github.dfa.diaspora_android.util.AppSettings;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Locale;
-public class PodAspect {
+public class DiasporaAspect {
public long id;
public String name;
public boolean selected;
- public PodAspect(long id, String name, boolean selected) {
+ public DiasporaAspect(long id, String name, boolean selected) {
this.id = id;
this.name = name;
this.selected = selected;
}
- public PodAspect(String shareabletext) {
+ public DiasporaAspect(String shareabletext) {
// fromShareAbleText
String[] str = shareabletext.split("%");
selected = Integer.parseInt(str[0]) == 1;
@@ -45,7 +46,7 @@ public class PodAspect {
name = shareabletext.substring(shareabletext.indexOf(str[1]) + str[1].length() + 1);
}
- public PodAspect(JSONObject json) throws JSONException {
+ public DiasporaAspect(JSONObject json) throws JSONException {
if (json.has("id")) {
id = json.getLong("id");
}
@@ -70,8 +71,8 @@ public class PodAspect {
public String toHtmlLink(final App app) {
final AppSettings appSettings = app.getSettings();
return String.format(Locale.getDefault(),
- "%s",
- appSettings.getPodDomain(), id, name);
+ "%s",
+ appSettings.getPod().getPodUrl().getBaseUrl(), id, name);
}
@Override
@@ -81,7 +82,7 @@ public class PodAspect {
@Override
public boolean equals(Object o) {
- return o instanceof PodAspect && ((PodAspect) o).id == id;
+ return o instanceof DiasporaAspect && ((DiasporaAspect) o).id == id;
}
public String toShareAbleText() {
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/data/DiasporaPodList.java b/app/src/main/java/com/github/dfa/diaspora_android/data/DiasporaPodList.java
new file mode 100644
index 00000000..3052ea77
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/data/DiasporaPodList.java
@@ -0,0 +1,524 @@
+package com.github.dfa.diaspora_android.data;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+
+
+/**
+ * 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
+ * For all Classes a loading and saving to JSON method is available
+ */
+@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue", "SpellCheckingInspection", "UnusedReturnValue", "JavaDoc", "FieldCanBeLocal"})
+public class DiasporaPodList implements Iterable, Serializable {
+ private static final boolean EXPORT_TOJSON_POST_COUNT_LOCAL = true;
+ private List pods = new ArrayList<>();
+ private boolean trackMergeChanges = false;
+ private Integer trackAddedIndexStart = -1;
+ private List trackUpdatedIndexes = new ArrayList<>();
+ private boolean keepOldNameDuringMerge = false;
+ private long timestamp;
+
+ public DiasporaPodList() {
+ }
+
+ /**
+ * Load DiasporaPodList from Json
+ *
+ * @param json Json Object
+ */
+ public DiasporaPodList fromJson(JSONObject json) throws JSONException {
+ JSONArray jarr;
+ pods.clear();
+
+ if (json.has("pods")) {
+ jarr = json.getJSONArray("pods");
+ for (int i = 0; i < jarr.length(); i++) {
+ DiasporaPod pod = new DiasporaPod().fromJson(jarr.getJSONObject(i));
+ pods.add(pod);
+ }
+ }
+ if (json.has("timestamp")) {
+ timestamp = json.getLong("timestamp");
+ }
+ return this;
+ }
+
+ /**
+ * Convert DiasporaPodList to JSON
+ */
+ public JSONObject toJson() throws JSONException {
+ JSONObject json = new JSONObject();
+ JSONArray jpods = new JSONArray();
+ for (DiasporaPod pod : pods) {
+ jpods.put(pod.toJson());
+ }
+ json.put("pods", jpods);
+ json.put("timestamp", System.currentTimeMillis());
+ return json;
+ }
+
+ /**
+ * Merge newer entries into this podlist
+ * Will add new pods, and update data of pods with data from the new list
+ *
+ * @param newPodList Another podlist
+ */
+ public void mergeWithNewerEntries(final DiasporaPodList newPodList) throws JSONException {
+ if (isTrackMergeChanges()) {
+ trackAddedIndexStart = -1;
+ trackUpdatedIndexes.clear();
+ }
+ for (DiasporaPod newPod : newPodList) {
+ int index = pods.indexOf(newPod);
+ if (index >= 0) {
+ DiasporaPod updatePodBak = new DiasporaPod().fromJson(pods.get(index).toJson());
+ DiasporaPod updatePod = pods.get(index);
+ updatePod.fromJson(newPod.toJson());
+
+ // Restore Pod id (if was set to zero)
+ if (updatePodBak.getId() != 0 && updatePod.getId() == 0) {
+ updatePod.setId(updatePodBak.getId());
+ }
+ if (updatePodBak.getPostCountLocal() != 0 && updatePod.getPostCountLocal() == 0) {
+ updatePod.setPostCountLocal(updatePodBak.getPostCountLocal());
+ }
+ if (updatePodBak.getScore() != 0 && updatePod.getScore() == 0) {
+ updatePod.setScore(updatePodBak.getScore());
+ }
+ if (!updatePodBak.getName().equals("") && keepOldNameDuringMerge) {
+ updatePod.setName(updatePodBak.getName());
+ }
+ if (isTrackMergeChanges()) {
+ trackUpdatedIndexes.add(index);
+ }
+ } else {
+ pods.add(newPod);
+ if (isTrackMergeChanges() && trackAddedIndexStart == -1) {
+ trackAddedIndexStart = pods.size() - 1;
+ }
+ }
+ }
+ }
+
+ /**
+ * Sort the pod list
+ */
+ public void sortPods() {
+ Collections.sort(pods);
+ }
+
+ /**
+ * Iterator for Iterable interface (forEach, ..)
+ */
+ public Iterator iterator() {
+ return pods.iterator();
+ }
+
+ public int size() {
+ return pods.size();
+ }
+
+ public int indexOf(DiasporaPod pod) {
+ return pods.indexOf(pod);
+ }
+
+ public List getPods() {
+ return pods;
+ }
+
+ public void setPods(List pods) {
+ this.pods = pods;
+ }
+
+ public DiasporaPod getPodAt(int index) {
+ if (index >= 0 && index < pods.size()) {
+ return pods.get(index);
+ }
+ return null;
+ }
+
+ public boolean isTrackMergeChanges() {
+ return trackMergeChanges;
+ }
+
+ public void setTrackMergeChanges(boolean trackMergeChanges) {
+ this.trackMergeChanges = trackMergeChanges;
+ }
+
+ public Integer getTrackAddedIndexStart() {
+ return trackAddedIndexStart;
+ }
+
+ public List getTrackUpdatedIndexes() {
+ return trackUpdatedIndexes;
+ }
+
+ public boolean isKeepOldNameDuringMerge() {
+ return keepOldNameDuringMerge;
+ }
+
+ public void setKeepOldNameDuringMerge(boolean keepOldNameDuringMerge) {
+ this.keepOldNameDuringMerge = keepOldNameDuringMerge;
+ }
+
+
+ /* ██████╗ ██████╗ ██████╗
+ * ██╔══██╗██╔═══██╗██╔══██╗
+ * ██████╔╝██║ ██║██║ ██║
+ * ██╔═══╝ ██║ ██║██║ ██║
+ * ██║ ╚██████╔╝██████╔╝
+ * ╚═╝ ╚═════╝ ╚═════╝
+ */
+ public static class DiasporaPod implements Iterable, Comparable, Serializable {
+ private List _podUrls = new ArrayList<>();
+ private List _mainLangs = new ArrayList<>();
+ private String _name = "";
+ private int _score = 0;
+ private int _id = 0;
+ private long _postCountLocal = 0;
+
+
+ public DiasporaPod() {
+ }
+
+ /**
+ * Load a DiasporaPod from JSON
+ *
+ * @param json Json Object
+ */
+ public DiasporaPod fromJson(JSONObject json) throws JSONException {
+ JSONArray jarr;
+
+ if (json.has("name")) {
+ _name = json.getString("name");
+ }
+ if (json.has("mainLangs")) {
+ jarr = json.getJSONArray("mainLangs");
+ for (int i = 0; i < jarr.length(); i++) {
+ String val = jarr.getString(i);
+ if (!_mainLangs.contains(val)) {
+ _mainLangs.add(val);
+ }
+ }
+ }
+ if (json.has("podUrls")) {
+ jarr = json.getJSONArray("podUrls");
+ for (int i = 0; i < jarr.length(); i++) {
+ DiasporaPodUrl podUrl = new DiasporaPodUrl().fromJson(jarr.getJSONObject(i));
+ if (!_podUrls.contains(podUrl)) {
+ _podUrls.add(podUrl);
+ }
+ }
+ }
+ if (json.has("score")) {
+ _score = json.getInt("score");
+ }
+ if (json.has("postCountLocal")) {
+ _postCountLocal = json.getLong("postCountLocal");
+ }
+ if (json.has("id")) {
+ _id = json.getInt("id");
+ }
+ return this;
+ }
+
+ /**
+ * Convert DiasporaPod to JSON
+ */
+ public JSONObject toJson() throws JSONException {
+ JSONObject json = new JSONObject();
+ json.put("name", _name);
+ json.put("id", _id);
+
+ if (_score != 0) {
+ json.put("score", _score);
+ }
+
+ // Only export active6 (frequently changing if told to do)
+ if (EXPORT_TOJSON_POST_COUNT_LOCAL && _postCountLocal > 0) {
+ json.put("postCountLocal", _postCountLocal);
+ }
+
+ // Pod urls
+ JSONArray jarr = new JSONArray();
+ for (DiasporaPodUrl value : _podUrls) {
+ jarr.put(value.toJson());
+ }
+ json.put("podUrls", jarr);
+
+ // main langs
+ jarr = new JSONArray();
+ for (String value : _mainLangs) {
+ jarr.put(value);
+ }
+ json.put("mainLangs", jarr);
+ return json;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ boolean ret = false;
+ if (o instanceof DiasporaPod) {
+ DiasporaPod otherPod = (DiasporaPod) o;
+
+ // Check if id is equal
+ ret = _id != 0 && _id == otherPod._id;
+
+ // Check if _host is the same (fallback if id is 0)
+ if (!ret) {
+ for (DiasporaPodUrl podUrl : _podUrls) {
+ for (DiasporaPodUrl otherPodUrl : otherPod.getPodUrls()) {
+ if (podUrl.getBaseUrl().equals(otherPodUrl.getBaseUrl())) {
+ ret = true;
+ }
+ }
+ }
+ }
+ }
+ return ret;
+ }
+
+ @Override
+ public int compareTo(DiasporaPod otherPod) {
+ if (otherPod != null) {
+ List myPodUrls = getPodUrls();
+ List otherPodUrls = otherPod.getPodUrls();
+ if (!myPodUrls.isEmpty() && !otherPodUrls.isEmpty()) {
+ return myPodUrls.get(0).getHost().compareTo(otherPodUrls.get(0).getHost());
+ }
+ return _name.compareTo(otherPod.getName());
+ }
+ return _name.compareTo("");
+ }
+
+ @Override
+ public String toString() {
+ return _name + "(" + _id + ")";
+ }
+
+ /**
+ * Iterator for Iterable interface (forEach, ..)
+ */
+ public Iterator iterator() {
+ return _podUrls.iterator();
+ }
+
+ /*
+ * Getter & Setter
+ */
+ public List getPodUrls() {
+ return _podUrls;
+ }
+
+ public DiasporaPod setPodUrls(List podUrls) {
+ _podUrls = podUrls;
+ return this;
+ }
+
+ public List getMainLangs() {
+ return _mainLangs;
+ }
+
+ public DiasporaPod setMainLangs(List mainLangs) {
+ _mainLangs = mainLangs;
+ return this;
+ }
+
+ public DiasporaPod appendMainLangs(String... values) {
+ _mainLangs.addAll(Arrays.asList(values));
+ return this;
+ }
+
+ /**
+ * Returns the first DiasporaPodUrl in the list
+ */
+ public DiasporaPodUrl getPodUrl() {
+ if (_podUrls.size() > 0) {
+ return _podUrls.get(0);
+ }
+ return null;
+ }
+
+ public DiasporaPod appendPodUrls(DiasporaPodUrl... values) {
+ _podUrls.addAll(Arrays.asList(values));
+ return this;
+ }
+
+ public String getName() {
+ return _name;
+ }
+
+ public DiasporaPod setName(String name) {
+ _name = name;
+ return this;
+ }
+
+ public int getScore() {
+ return _score;
+ }
+
+ public DiasporaPod setScore(int score) {
+ _score = score;
+ return this;
+ }
+
+ public long getPostCountLocal() {
+ return _postCountLocal;
+ }
+
+ public DiasporaPod setPostCountLocal(long postCountLocal) {
+ _postCountLocal = postCountLocal;
+ return this;
+ }
+
+ public int getId() {
+ return _id;
+ }
+
+ public DiasporaPod setId(int id) {
+ _id = id;
+ return this;
+ }
+
+ /* ██████╗ ██████╗ ██████╗ ██╗ ██╗██████╗ ██╗
+ * ██╔══██╗██╔═══██╗██╔══██╗ ██║ ██║██╔══██╗██║
+ * ██████╔╝██║ ██║██║ ██║ ██║ ██║██████╔╝██║
+ * ██╔═══╝ ██║ ██║██║ ██║ ██║ ██║██╔══██╗██║
+ * ██║ ╚██████╔╝██████╔╝ ╚██████╔╝██║ ██║███████╗
+ * ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝
+ */
+ public static class DiasporaPodUrl implements Serializable {
+ private String _host = "";
+ private String _protocol = "https";
+ private Integer _port = 443;
+
+ public DiasporaPodUrl() {
+ }
+
+ public DiasporaPodUrl(JSONObject json) throws JSONException {
+ fromJson(json);
+ }
+
+ /**
+ * Get the base url
+ *
+ * @return
+ */
+ public String getBaseUrl() {
+ return _protocol + "://" + _host + (isPortNeeded() ? _port : "");
+ }
+
+ /**
+ * Convert JSON to DiasporaPodList
+ *
+ * @param json JSON Object
+ */
+ public DiasporaPodUrl fromJson(JSONObject json) throws JSONException {
+ if (json.has("host")) {
+ _host = json.getString("host");
+ }
+ if (json.has("protocol")) {
+ _protocol = json.getString("protocol");
+ }
+ if (json.has("port")) {
+ _port = json.getInt("port");
+ }
+ return this;
+ }
+
+ /***
+ * Convert DiasporaPodList to JSON
+ */
+ public JSONObject toJson() throws JSONException {
+ JSONObject json = new JSONObject();
+ json.put("host", _host);
+ if (!_protocol.equals("https")) {
+ json.put("protocol", _protocol);
+ }
+ if (_port != 443) {
+ json.put("port", _port);
+ }
+ return json;
+ }
+
+ /**
+ * Set default values for https
+ */
+ public void setHttpsDefaults() {
+ setProtocol("https");
+ setPort(443);
+ }
+
+
+ /**
+ * Set default values for http
+ */
+ public void setHttpDefaults() {
+ setProtocol("http");
+ setPort(80);
+ }
+
+ /**
+ * Tells if the ports needs to shown
+ */
+ public boolean isPortNeeded() {
+ return !((_port == 80 && _protocol.equals("http")) || (_port == 443 && _protocol.equals("https")));
+ }
+
+ @Override
+ public String toString() {
+ return getBaseUrl();
+ }
+
+ @Override
+ @SuppressWarnings("SimplifiableIfStatement")
+ public boolean equals(Object o) {
+ if (o instanceof DiasporaPodUrl) {
+ return getBaseUrl().equals(((DiasporaPodUrl) o).getBaseUrl());
+ }
+ return false;
+ }
+
+ /*
+ * GETTER & SETTER
+ */
+ public String getHost() {
+ return _host;
+ }
+
+ public DiasporaPodUrl setHost(String host) {
+ _host = host;
+ return this;
+ }
+
+ public String getProtocol() {
+ return _protocol;
+ }
+
+ public DiasporaPodUrl setProtocol(String protocol) {
+ _protocol = protocol;
+ return this;
+ }
+
+ public Integer getPort() {
+ return _port;
+ }
+
+ public DiasporaPodUrl setPort(Integer port) {
+ _port = port;
+ return this;
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/data/PodUserProfile.java b/app/src/main/java/com/github/dfa/diaspora_android/data/DiasporaUserProfile.java
similarity index 64%
rename from app/src/main/java/com/github/dfa/diaspora_android/data/PodUserProfile.java
rename to app/src/main/java/com/github/dfa/diaspora_android/data/DiasporaUserProfile.java
index 420d984b..22efea59 100644
--- a/app/src/main/java/com/github/dfa/diaspora_android/data/PodUserProfile.java
+++ b/app/src/main/java/com/github/dfa/diaspora_android/data/DiasporaUserProfile.java
@@ -1,77 +1,87 @@
/*
- This file is part of the Diaspora for Android.
+ This file is part of the dandelion*.
- Diaspora for Android is free software: you can redistribute it and/or modify
+ 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.
- Diaspora for Android is distributed in the hope that it will be useful,
+ 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 Diaspora for Android.
+ along with the dandelion*.
If not, see .
*/
package com.github.dfa.diaspora_android.data;
import android.os.Handler;
-import android.util.Log;
import com.github.dfa.diaspora_android.App;
-import com.github.dfa.diaspora_android.listener.WebUserProfileChangedListener;
+import com.github.dfa.diaspora_android.listener.DiasporaUserProfileChangedListener;
+import com.github.dfa.diaspora_android.util.AppLog;
+import com.github.dfa.diaspora_android.util.AppSettings;
+import com.github.dfa.diaspora_android.util.DiasporaUrlHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
- * Created by gsantner (https://gsantner.github.io/) on 24.03.16. Part of Diaspora for Android.
+ * User profile
+ * Created by gsantner (gsantner AT mailbox DOT org) on 24.03.16. Part of dandelion*.
*/
-public class PodUserProfile {
- private static final int MINIMUM_WEBUSERPROFILE_LOAD_TIMEDIFF = 5000;
+public class DiasporaUserProfile {
+ private static final int MINIMUM_USERPROFILE_LOAD_TIMEDIFF = 5000;
private Handler callbackHandler;
- private WebUserProfileChangedListener listener;
- private App app;
- private AppSettings appSettings;
+ private DiasporaUserProfileChangedListener listener;
+ private final App app;
+ private final AppSettings appSettings;
+ DiasporaUrlHelper urls;
private JSONObject json;
- private long lastLoaded;
+ private long userProfileLastLoadedTimestamp;
private boolean isWebUserProfileLoaded;
private String avatarUrl;
private String guid;
private String name;
- private PodAspect[] podAspects;
+ private DiasporaAspect[] aspects;
private String[] followedTags;
private int notificationCount;
private int unreadMessagesCount;
+ private long lastVisitedPositionInStream = -1;
- public PodUserProfile(App app) {
+ public DiasporaUserProfile(App app) {
this.app = app;
appSettings = app.getSettings();
+ urls = new DiasporaUrlHelper(appSettings);
+ loadFromAppSettings();
+ }
+ public void loadFromAppSettings() {
avatarUrl = appSettings.getAvatarUrl();
guid = appSettings.getProfileId();
name = appSettings.getName();
- podAspects = appSettings.getPodAspects();
+ aspects = appSettings.getAspects();
followedTags = appSettings.getFollowedTags();
notificationCount = appSettings.getNotificationCount();
unreadMessagesCount = appSettings.getUnreadMessageCount();
+ lastVisitedPositionInStream = appSettings.getLastVisitedPositionInStream();
}
- public PodUserProfile(App app, Handler callbackHandler, WebUserProfileChangedListener listener) {
+ public DiasporaUserProfile(App app, Handler callbackHandler, DiasporaUserProfileChangedListener listener) {
this(app);
this.listener = listener;
this.callbackHandler = callbackHandler;
}
public boolean isRefreshNeeded() {
- return (System.currentTimeMillis() - lastLoaded) >= MINIMUM_WEBUSERPROFILE_LOAD_TIMEDIFF;
+ return (System.currentTimeMillis() - userProfileLastLoadedTimestamp) >= MINIMUM_USERPROFILE_LOAD_TIMEDIFF;
}
public boolean isWebUserProfileLoaded() {
@@ -81,19 +91,19 @@ public class PodUserProfile {
public boolean parseJson(String jsonStr) {
try {
json = new JSONObject(jsonStr);
- lastLoaded = System.currentTimeMillis();
+ userProfileLastLoadedTimestamp = System.currentTimeMillis();
// Avatar
if (json.has("avatar")) {
JSONObject avatarJson = json.getJSONObject("avatar");
- if (avatarJson.has("medium") && setAvatarUrl(avatarJson.getString("medium"))) {
+ if (avatarJson.has("large") && setAvatarUrl(avatarJson.getString("large"))) {
app.getAvatarImageLoader().clearAvatarImage();
appSettings.setAvatarUrl(avatarUrl);
}
}
// GUID (User id)
- if (json.has("guid") && loadGuid(json.getString("guid"))) {
+ if (json.has("guid") && loadGuid(json.getString("guid")) && !guid.isEmpty()) {
appSettings.setProfileId(guid);
}
@@ -114,7 +124,7 @@ public class PodUserProfile {
// Aspect
if (json.has("aspects") && loadAspects(json.getJSONArray("aspects"))) {
- appSettings.setPodAspects(podAspects);
+ appSettings.setPodAspects(aspects);
}
// Followed tags
@@ -125,13 +135,23 @@ public class PodUserProfile {
isWebUserProfileLoaded = true;
} catch (JSONException e) {
- Log.d(App.TAG, e.getMessage());
+ AppLog.d(this, e.getMessage());
isWebUserProfileLoaded = false;
}
- lastLoaded = System.currentTimeMillis();
+ userProfileLastLoadedTimestamp = System.currentTimeMillis();
return isWebUserProfileLoaded;
}
+ public void analyzeUrl(String url) {
+ String prefix = urls.getPodUrl() + DiasporaUrlHelper.SUBURL_STREAM_WITH_TIMESTAMP;
+ if (url.startsWith(prefix)) {
+ try {
+ setLastVisitedPositionInStream(Long.parseLong(url.replace(prefix, "")));
+ } catch (NumberFormatException ignored) {
+ }
+ }
+ }
+
/*
// Getters & Setters
*/
@@ -156,24 +176,48 @@ public class PodUserProfile {
return unreadMessagesCount;
}
- public PodAspect[] getAspects() {
- return podAspects;
+ public DiasporaAspect[] getAspects() {
+ return aspects;
}
public String[] getFollowedTags() {
return followedTags;
}
+ public long getLastVisitedPositionInStream() {
+ return lastVisitedPositionInStream;
+ }
+
+ public void setLastVisitedPositionInStream(long lastVisitedPositionInStream) {
+ this.lastVisitedPositionInStream = lastVisitedPositionInStream;
+ appSettings.setLastVisitedPositionInStream(lastVisitedPositionInStream);
+ }
+
+ public boolean hasLastVisitedTimestampInStream() {
+ return appSettings.getLastVisitedPositionInStream() != -1;
+ }
+
+ public void resetLastVisitedPositionInStream() {
+ appSettings.setLastVisitedPositionInStream(-1);
+ }
+
/*
* Private property setters
*/
+
+ /**
+ * Sets the avatar, returns true if this was a new one, false if already the old one
+ *
+ * @param avatarUrl url
+ * @return true if new avatar url
+ */
private boolean setAvatarUrl(final String avatarUrl) {
if (!this.avatarUrl.equals(avatarUrl)) {
this.avatarUrl = avatarUrl;
if (listener != null && callbackHandler != null) {
callbackHandler.post(new Runnable() {
public void run() {
- listener.onUserProfileAvatarChanged(avatarUrl);
+ listener.onUserProfileAvatarChanged(DiasporaUserProfile.this, avatarUrl);
}
});
}
@@ -196,7 +240,7 @@ public class PodUserProfile {
if (listener != null && callbackHandler != null) {
callbackHandler.post(new Runnable() {
public void run() {
- listener.onUserProfileNameChanged(name);
+ listener.onUserProfileNameChanged(DiasporaUserProfile.this, name);
}
});
}
@@ -211,7 +255,7 @@ public class PodUserProfile {
if (listener != null && callbackHandler != null) {
callbackHandler.post(new Runnable() {
public void run() {
- listener.onNotificationCountChanged(notificationCount);
+ listener.onNotificationCountChanged(DiasporaUserProfile.this, notificationCount);
}
});
}
@@ -221,9 +265,9 @@ public class PodUserProfile {
}
private boolean loadAspects(final JSONArray jsonAspects) throws JSONException {
- podAspects = new PodAspect[jsonAspects.length()];
+ aspects = new DiasporaAspect[jsonAspects.length()];
for (int i = 0; i < jsonAspects.length(); i++) {
- podAspects[i] = new PodAspect(jsonAspects.getJSONObject(i));
+ aspects[i] = new DiasporaAspect(jsonAspects.getJSONObject(i));
}
return true;
}
@@ -242,7 +286,7 @@ public class PodUserProfile {
if (listener != null && callbackHandler != null) {
callbackHandler.post(new Runnable() {
public void run() {
- listener.onUnreadMessageCountChanged(unreadMessagesCount);
+ listener.onUnreadMessageCountChanged(DiasporaUserProfile.this, unreadMessagesCount);
}
});
}
@@ -259,11 +303,11 @@ public class PodUserProfile {
this.callbackHandler = callbackHandler;
}
- public WebUserProfileChangedListener getListener() {
+ public DiasporaUserProfileChangedListener getListener() {
return listener;
}
- public void setListener(WebUserProfileChangedListener listener) {
+ public void setListener(DiasporaUserProfileChangedListener listener) {
this.listener = listener;
}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/listener/DiasporaUserProfileChangedListener.java b/app/src/main/java/com/github/dfa/diaspora_android/listener/DiasporaUserProfileChangedListener.java
new file mode 100644
index 00000000..dc1b67dc
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/listener/DiasporaUserProfileChangedListener.java
@@ -0,0 +1,59 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.listener;
+
+import com.github.dfa.diaspora_android.data.DiasporaUserProfile;
+
+/**
+ * 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 {
+ /**
+ * Called when the DiasporaUserProfile name changed
+ *
+ * @param diasporaUserProfile The profile
+ * @param name The new name
+ */
+ void onUserProfileNameChanged(DiasporaUserProfile diasporaUserProfile, String name);
+
+ /**
+ * Called when the DiasporaUserProfile avatarUrl changed
+ *
+ * @param diasporaUserProfile The profile
+ * @param avatarUrl The new name
+ */
+ void onUserProfileAvatarChanged(DiasporaUserProfile diasporaUserProfile, String avatarUrl);
+
+ /**
+ * Called when the DiasporaUserProfile notificationCount changed
+ *
+ * @param diasporaUserProfile The profile
+ * @param notificationCount The new notificationCount
+ */
+ void onNotificationCountChanged(DiasporaUserProfile diasporaUserProfile, int notificationCount);
+
+ /**
+ * Called when the DiasporaUserProfile unreadMessageCount changed
+ *
+ * @param diasporaUserProfile The profile
+ * @param unreadMessageCount The new unreadMessageCount
+ */
+ void onUnreadMessageCountChanged(DiasporaUserProfile diasporaUserProfile, int unreadMessageCount);
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/listener/IntellihideToolbarActivityListener.java b/app/src/main/java/com/github/dfa/diaspora_android/listener/IntellihideToolbarActivityListener.java
new file mode 100644
index 00000000..58f04704
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/listener/IntellihideToolbarActivityListener.java
@@ -0,0 +1,14 @@
+package com.github.dfa.diaspora_android.listener;
+
+import android.support.design.widget.AppBarLayout;
+
+/**
+ * interface that adds options to control intellihide of toolbars to the Activity
+ * Created by vanitas on 08.10.16.
+ */
+
+public interface IntellihideToolbarActivityListener {
+ int toolbarDefaultScrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP;
+
+ void setToolbarIntellihide(boolean enable);
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/listener/OnSomethingClickListener.java b/app/src/main/java/com/github/dfa/diaspora_android/listener/OnSomethingClickListener.java
new file mode 100644
index 00000000..86ae6789
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/listener/OnSomethingClickListener.java
@@ -0,0 +1,15 @@
+package com.github.dfa.diaspora_android.listener;
+
+/**
+ * Listener for different types of click events
+ */
+public interface OnSomethingClickListener {
+ /**
+ * Triggered when something was clicked
+ *
+ * @param o Some object, or null
+ * @param i Some index, int value or null
+ * @param s Some String, or null
+ */
+ void onSomethingClicked(T o, Integer i, String s);
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/listener/WebUserProfileChangedListener.java b/app/src/main/java/com/github/dfa/diaspora_android/listener/WebUserProfileChangedListener.java
deleted file mode 100644
index 9ef24a1f..00000000
--- a/app/src/main/java/com/github/dfa/diaspora_android/listener/WebUserProfileChangedListener.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- This file is part of the Diaspora for Android.
-
- Diaspora for Android 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.
-
- Diaspora for Android 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 Diaspora for Android.
-
- If not, see .
- */
-package com.github.dfa.diaspora_android.listener;
-
-/**
- * Created by gsantner (https://gsantner.github.io/) on 26.03.16.
- * Interface that needs to be implemented by classes that listen for Profile related changes
- */
-public interface WebUserProfileChangedListener {
- void onUserProfileNameChanged(String name);
-
- void onUserProfileAvatarChanged(String avatarUrl);
-
- void onNotificationCountChanged(int notificationCount);
-
- void onUnreadMessageCountChanged(int unreadMessageCount);
-}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/receiver/OpenExternalLinkReceiver.java b/app/src/main/java/com/github/dfa/diaspora_android/receiver/OpenExternalLinkReceiver.java
new file mode 100644
index 00000000..496a8c6e
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/receiver/OpenExternalLinkReceiver.java
@@ -0,0 +1,83 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.receiver;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.net.Uri;
+import android.support.customtabs.CustomTabsIntent;
+
+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.util.AppLog;
+import com.github.dfa.diaspora_android.util.AppSettings;
+import com.github.dfa.diaspora_android.web.custom_tab.BrowserFallback;
+import com.github.dfa.diaspora_android.web.custom_tab.CustomTabActivityHelper;
+
+/**
+ * BroadcastReceiver that opens links in a Chrome CustomTab
+ * Created by vanitas on 11.09.16.
+ */
+public class OpenExternalLinkReceiver extends BroadcastReceiver {
+ private final Activity parent;
+
+ public OpenExternalLinkReceiver(Activity parent) {
+ this.parent = parent;
+ }
+
+ @Override
+ public void onReceive(Context c, Intent receiveIntent) {
+ AppSettings appSettings = AppSettings.get();
+ ThemeHelper.getInstance(appSettings);
+
+ AppLog.v(this, "OpenExternalLinkReceiver.onReceive(): url");
+
+ Uri url;
+ try {
+ String sUrl = receiveIntent.getStringExtra(MainActivity.EXTRA_URL);
+ url = Uri.parse(sUrl);
+ } catch (Exception _ignored) {
+ AppLog.v(this, "Could not open Chrome Custom Tab (bad URL)");
+ return;
+ }
+
+ if (appSettings.isChromeCustomTabsEnabled()) {
+ // Setup Chrome Custom Tab
+ CustomTabsIntent.Builder customTab = new CustomTabsIntent.Builder();
+ customTab.setToolbarColor(ThemeHelper.getPrimaryColor());
+ customTab.addDefaultShareMenuItem();
+
+ Bitmap backButtonIcon = BitmapFactory.decodeResource(c.getResources(), R.drawable.chrome_custom_tab__back);
+ customTab.setCloseButtonIcon(backButtonIcon);
+
+ // Launch Chrome Custom Tab
+ CustomTabActivityHelper.openCustomTab(parent, customTab.build(), url, new BrowserFallback());
+ } else {
+ // Open in normal browser (via intent)
+ Intent openBrowserIntent = new Intent(Intent.ACTION_VIEW, url);
+ openBrowserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ c.startActivity(openBrowserIntent);
+ }
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/receiver/UpdateTitleReceiver.java b/app/src/main/java/com/github/dfa/diaspora_android/receiver/UpdateTitleReceiver.java
new file mode 100644
index 00000000..c6dddb6b
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/receiver/UpdateTitleReceiver.java
@@ -0,0 +1,103 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.receiver;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+
+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.util.AppLog;
+import com.github.dfa.diaspora_android.util.AppSettings;
+import com.github.dfa.diaspora_android.util.DiasporaUrlHelper;
+
+/**
+ * BroadcastReceiver used to update the title of the MainActivity depending on the url of the ui__webview
+ * Created by vanitas on 11.09.16.
+ */
+public class UpdateTitleReceiver extends BroadcastReceiver {
+ private DiasporaUrlHelper urls;
+ private AppSettings appSettings;
+ private App app;
+ private TitleCallback callback;
+ private String lastUrl;
+
+ public UpdateTitleReceiver(App app, DiasporaUrlHelper urls, TitleCallback callback) {
+ this.urls = urls;
+ this.app = app;
+ this.appSettings = app.getSettings();
+ this.callback = callback;
+ }
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ lastUrl = intent.getStringExtra(MainActivity.EXTRA_URL);
+ if (lastUrl != null && lastUrl.startsWith(urls.getPodUrl())) {
+ String subUrl = lastUrl.substring((urls.getPodUrl()).length());
+ AppLog.spam(this, "onReceive()- Set title for subUrl " + subUrl);
+ if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_STREAM)) {
+ setTitle(R.string.nav_stream);
+ } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_POSTS)) {
+ setTitle(R.string.app_name);
+ } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_NOTIFICATIONS)) {
+ setTitle(R.string.notifications);
+ } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_CONVERSATIONS)) {
+ setTitle(R.string.conversations);
+ } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_NEW_POST)) {
+ setTitle(R.string.new_post);
+ } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_STATISTICS)) {
+ setTitle(R.string.statistics);
+ } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_CONTACTS)) {
+ setTitle(R.string.contacts);
+ } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_PEOPLE + appSettings.getProfileId())) {
+ setTitle(R.string.nav_profile);
+ } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_ACTIVITY)) {
+ setTitle(R.string.nav_activities);
+ } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_LIKED)) {
+ setTitle(R.string.nav_liked);
+ } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_COMMENTED)) {
+ setTitle(R.string.nav_commented);
+ } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_MENTIONS)) {
+ setTitle(R.string.nav_mentions);
+ } else if (subUrl.startsWith(DiasporaUrlHelper.SUBURL_PUBLIC)) {
+ setTitle(R.string.public_);
+ } else if (urls.isAspectUrl(lastUrl)) {
+ setTitle(urls.getAspectNameFromUrl(lastUrl, app));
+ }
+ } else {
+ AppLog.spam(this, "onReceive()- Invalid url: " + lastUrl);
+ }
+ }
+
+ private void setTitle(int rId) {
+ callback.setTitle(lastUrl, rId);
+ }
+
+ private void setTitle(String title) {
+ callback.setTitle(lastUrl, title);
+ }
+
+ public interface TitleCallback {
+ void setTitle(String url, int resId);
+
+ void setTitle(String url, String title);
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/util/AvatarImageLoader.java b/app/src/main/java/com/github/dfa/diaspora_android/service/AvatarImageLoader.java
similarity index 75%
rename from app/src/main/java/com/github/dfa/diaspora_android/util/AvatarImageLoader.java
rename to app/src/main/java/com/github/dfa/diaspora_android/service/AvatarImageLoader.java
index eee45f6a..ab975326 100644
--- a/app/src/main/java/com/github/dfa/diaspora_android/util/AvatarImageLoader.java
+++ b/app/src/main/java/com/github/dfa/diaspora_android/service/AvatarImageLoader.java
@@ -1,30 +1,30 @@
/*
- This file is part of the Diaspora for Android.
+ This file is part of the dandelion*.
- Diaspora for Android is free software: you can redistribute it and/or modify
+ 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.
- Diaspora for Android is distributed in the hope that it will be useful,
+ 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 Diaspora for Android.
+ along with the dandelion*.
If not, see .
*/
-
-package com.github.dfa.diaspora_android.util;
+
+package com.github.dfa.diaspora_android.service;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
-import com.github.dfa.diaspora_android.task.ImageDownloadTask;
+import net.gsantner.opoc.util.DownloadTask;
import java.io.File;
@@ -54,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);
}
}
}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/service/FetchPodsService.java b/app/src/main/java/com/github/dfa/diaspora_android/service/FetchPodsService.java
new file mode 100644
index 00000000..d9a24ecd
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/service/FetchPodsService.java
@@ -0,0 +1,114 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.service;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.AsyncTask;
+import android.os.IBinder;
+import android.support.v4.content.LocalBroadcastManager;
+
+import com.github.dfa.diaspora_android.data.DiasporaPodList;
+import com.github.dfa.diaspora_android.util.AppLog;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+
+import javax.net.ssl.HttpsURLConnection;
+
+import info.guardianproject.netcipher.NetCipher;
+
+public class FetchPodsService extends Service {
+ public static final String MESSAGE_PODS_RECEIVED = "com.github.dfa.diaspora.podsreceived";
+ public static final String EXTRA_PODLIST = "pods";
+
+ public FetchPodsService() {
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ new GetPodsTask(this).execute();
+ return super.onStartCommand(intent, flags, startId);
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ // TODO: Return the communication channel to the service.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+}
+
+class GetPodsTask extends AsyncTask {
+ 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;
+
+ GetPodsTask(Service service) {
+ this.service = service;
+ }
+
+ @Override
+ protected DiasporaPodList doInBackground(Void... params) {
+ StringBuilder sb = new StringBuilder();
+ BufferedReader br = null;
+ try {
+ HttpsURLConnection con = NetCipher.getHttpsURLConnection(PODDY_PODLIST_URL);
+ if (con.getResponseCode() == HttpsURLConnection.HTTP_OK) {
+ br = new BufferedReader(new InputStreamReader(con.getInputStream()));
+ String line;
+ while ((line = br.readLine()) != null) {
+ sb.append(line);
+ }
+
+ // Parse JSON & return pod list
+ JSONObject json = new JSONObject(sb.toString());
+ return new DiasporaPodList().fromJson(json);
+ } else {
+ AppLog.e(this, "Failed to download list of pods");
+ }
+ } catch (IOException | JSONException e) {
+ e.printStackTrace();
+ } finally {
+ if (br != null) {
+ try {
+ br.close();
+ } catch (IOException ignored) {
+ }
+ }
+ }
+
+ // Could not fetch list of pods :(
+ return new DiasporaPodList();
+ }
+
+ @Override
+ protected void onPostExecute(DiasporaPodList pods) {
+ if (pods == null) {
+ pods = new DiasporaPodList();
+ }
+ Intent broadcastIntent = new Intent(FetchPodsService.MESSAGE_PODS_RECEIVED);
+ broadcastIntent.putExtra(FetchPodsService.EXTRA_PODLIST, pods);
+ LocalBroadcastManager.getInstance(service.getApplicationContext()).sendBroadcast(broadcastIntent);
+ service.stopSelf();
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/service/HashtagContentProvider.java b/app/src/main/java/com/github/dfa/diaspora_android/service/HashtagContentProvider.java
new file mode 100644
index 00000000..4c7b744e
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/service/HashtagContentProvider.java
@@ -0,0 +1,60 @@
+/*
+ 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 .
+
+ This file is inspired from sourabhsoni.com/implementing-hashtags-in-android-application/
+ */
+package com.github.dfa.diaspora_android.service;
+
+import android.content.ContentProvider;
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.net.Uri;
+
+public class HashtagContentProvider extends ContentProvider {
+
+ @Override
+ public int delete(Uri arg0, String arg1, String[] arg2) {
+ return 0;
+ }
+
+ @Override
+ public String getType(Uri arg0) {
+ return "vnd.android.cursor.item/vnd.cc.tag";
+ }
+
+ @Override
+ public Uri insert(Uri arg0, ContentValues arg1) {
+ return null;
+ }
+
+ @Override
+ public boolean onCreate() {
+ return false;
+ }
+
+ @Override
+ public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3,
+ String arg4) {
+ return null;
+ }
+
+ @Override
+ public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
+ return 0;
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/task/ProfileFetchTask.java b/app/src/main/java/com/github/dfa/diaspora_android/service/ProfileFetchTask.java
similarity index 73%
rename from app/src/main/java/com/github/dfa/diaspora_android/task/ProfileFetchTask.java
rename to app/src/main/java/com/github/dfa/diaspora_android/service/ProfileFetchTask.java
index 093cf2bd..4f0b3491 100644
--- a/app/src/main/java/com/github/dfa/diaspora_android/task/ProfileFetchTask.java
+++ b/app/src/main/java/com/github/dfa/diaspora_android/service/ProfileFetchTask.java
@@ -1,30 +1,31 @@
/*
- This file is part of the Diaspora for Android.
+ This file is part of the dandelion*.
- Diaspora for Android is free software: you can redistribute it and/or modify
+ 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.
- Diaspora for Android is distributed in the hope that it will be useful,
+ 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 Diaspora for Android.
+ along with the dandelion*.
If not, see .
*/
-package com.github.dfa.diaspora_android.task;
+package com.github.dfa.diaspora_android.service;
import android.content.Context;
import android.os.AsyncTask;
-import android.util.Log;
import android.webkit.CookieManager;
import com.github.dfa.diaspora_android.App;
-import com.github.dfa.diaspora_android.data.PodUserProfile;
+import com.github.dfa.diaspora_android.data.DiasporaUserProfile;
+import com.github.dfa.diaspora_android.util.AppLog;
+import com.github.dfa.diaspora_android.util.DiasporaUrlHelper;
import java.io.BufferedReader;
import java.io.IOException;
@@ -43,12 +44,14 @@ public class ProfileFetchTask extends AsyncTask {
// Code for getting the profile async without any UI/WebView
// TODO: This is an early version,needs to be converted to Service
- final App app;
- final Context context;
+ private final App app;
+ private final Context context;
+ private final DiasporaUrlHelper urls;
public ProfileFetchTask(final App app) {
this.context = app.getApplicationContext();
this.app = app;
+ this.urls = new DiasporaUrlHelper(app.getSettings());
}
@@ -56,13 +59,13 @@ public class ProfileFetchTask extends AsyncTask {
protected Void doInBackground(Void... params) {
String extractedProfileData = null;
final CookieManager cookieManager = app.getCookieManager();
- String cookies = cookieManager.getCookie("https://" + app.getSettings().getPodDomain());
- Log.d(App.TAG, cookies);
+ String cookies = cookieManager.getCookie(urls.getPodUrl());
+ AppLog.d(this, cookies);
HttpsURLConnection connection;
InputStream inStream;
try {
- URL url = new URL("https://" + app.getSettings().getPodDomain() + "/stream");
+ URL url = new URL(urls.getStreamUrl());
connection = NetCipher.getHttpsURLConnection(url);
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
@@ -83,10 +86,10 @@ public class ProfileFetchTask extends AsyncTask {
}
}
- try{
+ try {
br.close();
inStream.close();
- } catch (IOException e){/*Nothing*/}
+ } catch (IOException e) {/*Nothing*/}
connection.disconnect();
@@ -96,9 +99,9 @@ public class ProfileFetchTask extends AsyncTask {
if (extractedProfileData != null) {
- PodUserProfile profile = new PodUserProfile(app);
+ DiasporaUserProfile profile = new DiasporaUserProfile(app);
profile.parseJson(extractedProfileData);
- Log.d(App.TAG, "Extracted new_messages (service):" + profile.getUnreadMessagesCount());
+ AppLog.d(this, "Extracted new_messages (service):" + profile.getUnreadMessagesCount());
}
return null;
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/task/GetPodsService.java b/app/src/main/java/com/github/dfa/diaspora_android/task/GetPodsService.java
deleted file mode 100644
index d9f964a8..00000000
--- a/app/src/main/java/com/github/dfa/diaspora_android/task/GetPodsService.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- This file is part of the Diaspora for Android.
-
- Diaspora for Android 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.
-
- Diaspora for Android 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 Diaspora for Android.
-
- If not, see .
- */
-package com.github.dfa.diaspora_android.task;
-
-import android.app.Service;
-import android.content.Intent;
-import android.os.AsyncTask;
-import android.os.IBinder;
-import android.support.v4.content.LocalBroadcastManager;
-import android.util.Log;
-
-import com.github.dfa.diaspora_android.App;
-
-import org.json.JSONArray;
-import org.json.JSONObject;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.net.ssl.HttpsURLConnection;
-
-import info.guardianproject.netcipher.NetCipher;
-
-public class GetPodsService extends Service {
- public static final String MESSAGE_PODS_RECEIVED = "com.github.dfa.diaspora.podsreceived";
- private static final String TAG = App.TAG;
-
- public GetPodsService() {
- }
-
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- getPods();
- return super.onStartCommand(intent, flags, startId);
- }
-
- private void getPods() {
- /*
- * Most of the code in this AsyncTask is from the file getPodlistTask.java
- * from the app "Diaspora Webclient".
- * A few modifications and adaptations were made by me.
- * Source:
- * https://github.com/voidcode/Diaspora-Webclient/blob/master/src/com/voidcode/diasporawebclient/getPodlistTask.java
- * Thanks to Terkel Sørensen ; License : GPLv3
- */
- AsyncTask getPodsAsync = new AsyncTask() {
- @Override
- protected String[] doInBackground(Void... params) {
-
- // TODO: Update deprecated code
-
- StringBuilder builder = new StringBuilder();
- //HttpClient client = new DefaultHttpClient();
- List list = null;
- HttpsURLConnection connection;
- InputStream inStream;
- try {
- connection = NetCipher.getHttpsURLConnection("https://podupti.me/api.php?key=4r45tg&format=json");
- int statusCode = connection.getResponseCode();
- if (statusCode == 200) {
- inStream = connection.getInputStream();
- BufferedReader reader = new BufferedReader(
- new InputStreamReader(inStream));
- String line;
- while ((line = reader.readLine()) != null) {
- builder.append(line);
- }
-
- try {
- inStream.close();
- } catch (IOException e) {/*Nothing to do*/}
-
- connection.disconnect();
- } else {
- Log.e(TAG, "Failed to download list of pods");
- }
- } catch (IOException e) {
- //TODO handle json buggy feed
- e.printStackTrace();
- }
- //Parse the JSON Data
- try {
- JSONObject jsonObjectAll = new JSONObject(builder.toString());
- JSONArray jsonArrayAll = jsonObjectAll.getJSONArray("pods");
- Log.d(TAG, "Number of entries " + jsonArrayAll.length());
- list = new ArrayList<>();
- for (int i = 0; i < jsonArrayAll.length(); i++) {
- JSONObject jo = jsonArrayAll.getJSONObject(i);
- if (jo.getString("secure").equals("true"))
- list.add(jo.getString("domain"));
- }
-
- } catch (Exception e) {
- //TODO Handle Parsing errors here
- e.printStackTrace();
- }
- if (list != null)
- return list.toArray(new String[list.size()]);
- else
- return null;
- }
-
- @Override
- protected void onPostExecute(String[] pods) {
- Intent broadcastIntent = new Intent(MESSAGE_PODS_RECEIVED);
- broadcastIntent.putExtra("pods", pods != null ? pods : new String[0]);
- LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent);
- stopSelf();
- }
- };
- getPodsAsync.execute();
- }
-
- @Override
- public IBinder onBind(Intent intent) {
- // TODO: Return the communication channel to the service.
- throw new UnsupportedOperationException("Not yet implemented");
- }
-
-}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/task/ImageDownloadTask.java b/app/src/main/java/com/github/dfa/diaspora_android/task/ImageDownloadTask.java
deleted file mode 100644
index 2a66c2c4..00000000
--- a/app/src/main/java/com/github/dfa/diaspora_android/task/ImageDownloadTask.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- This file is part of the Diaspora for Android.
-
- Diaspora for Android 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.
-
- Diaspora for Android 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 Diaspora for Android.
-
- If not, see .
- */
-package com.github.dfa.diaspora_android.task;
-
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.os.AsyncTask;
-import android.support.annotation.Nullable;
-import android.util.Log;
-import android.widget.ImageView;
-
-import com.github.dfa.diaspora_android.App;
-
-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 {
- ImageView imageView;
- 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) {
- Log.e(App.TAG, 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);
- }
- }
-}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/BadgeDrawable.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/BadgeDrawable.java
new file mode 100644
index 00000000..39701d29
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/BadgeDrawable.java
@@ -0,0 +1,132 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.ui;
+
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.ColorFilter;
+import android.graphics.Paint;
+import android.graphics.PixelFormat;
+import android.graphics.Rect;
+import android.graphics.Typeface;
+import android.graphics.drawable.Drawable;
+import android.graphics.drawable.LayerDrawable;
+import android.support.annotation.NonNull;
+
+import com.github.dfa.diaspora_android.R;
+import com.github.dfa.diaspora_android.util.AppSettings;
+import com.github.dfa.diaspora_android.util.ContextUtils;
+
+@SuppressWarnings("WeakerAccess")
+public class BadgeDrawable extends Drawable {
+ // Source: http://mobikul.com/adding-badge-count-on-menu-items-like-cart-notification-etc/
+ private static final String BADGE_VALUE_OVERFLOW = "*";
+
+ private Paint _badgeBackground;
+ private Paint _badgeText;
+ private Rect _textRect = new Rect();
+
+ private String _badgeValue = "";
+ private boolean _shouldDraw;
+
+ public BadgeDrawable(Context context) {
+ float textSize = context.getResources().getDimension(R.dimen.textsize_badge_count);
+
+ AppSettings settings = AppSettings.get();
+ _badgeBackground = new Paint();
+ _badgeBackground.setColor(settings.getAccentColor());
+ _badgeBackground.setAntiAlias(true);
+ _badgeBackground.setStyle(Paint.Style.FILL);
+
+ _badgeText = new Paint();
+ _badgeText.setColor(ContextUtils.get().shouldColorOnTopBeLight(settings.getAccentColor()) ? Color.WHITE : Color.BLACK);
+ _badgeText.setTypeface(Typeface.DEFAULT);
+ _badgeText.setTextSize(textSize);
+ _badgeText.setAntiAlias(true);
+ _badgeText.setTextAlign(Paint.Align.CENTER);
+ }
+
+ @Override
+ public void draw(@NonNull Canvas canvas) {
+ if (!_shouldDraw) {
+ return;
+ }
+ Rect bounds = getBounds();
+ float width = bounds.right - bounds.left;
+ float height = bounds.bottom - bounds.top;
+ 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;
+ float centerX = (width - radius - 1) + oneDp * 2;
+ float centerY = radius - 2 * oneDp;
+ canvas.drawCircle(centerX, centerY, (int) (radius + oneDp * 5), _badgeBackground);
+
+ // Draw badge count message inside the circle.
+ _badgeText.getTextBounds(_badgeValue, 0, _badgeValue.length(), _textRect);
+ float textHeight = _textRect.bottom - _textRect.top;
+ float textY = centerY + (textHeight / 2f);
+ canvas.drawText(_badgeValue.length() > 2 ? BADGE_VALUE_OVERFLOW : _badgeValue,
+ centerX, textY, _badgeText);
+ }
+
+ // Sets the text to display. Badge displays a '*' if more than 2 characters
+ private void setBadgeText(String text) {
+ _badgeValue = text;
+
+ // Only draw a badge if the value isn't a zero
+ _shouldDraw = !text.equalsIgnoreCase("0");
+ invalidateSelf();
+ }
+
+ @Override
+ public void setAlpha(int alpha) {
+ }
+
+ @Override
+ public void setColorFilter(ColorFilter cf) {
+ }
+
+ @Override
+ public int getOpacity() {
+ return PixelFormat.UNKNOWN;
+ }
+
+ public static void setBadgeCount(Context context, LayerDrawable icon, Integer count) {
+ setBadgeText(context, icon, count.toString());
+ }
+
+ // Max of 2 characters
+ public static void setBadgeText(Context context, LayerDrawable icon, String text) {
+ BadgeDrawable badge;
+
+ // Reuse drawable if possible
+ Drawable reuse = icon.findDrawableByLayerId(R.id.ic_badge);
+ if (reuse != null && reuse instanceof BadgeDrawable) {
+ badge = (BadgeDrawable) reuse;
+ } else {
+ badge = new BadgeDrawable(context);
+ }
+
+ badge.setBadgeText(text);
+ icon.mutate();
+ icon.setDrawableByLayerId(R.id.ic_badge, badge);
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/BottomBarBehavior.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/BottomBarBehavior.java
index 6e89bfc4..c9648574 100644
--- a/app/src/main/java/com/github/dfa/diaspora_android/ui/BottomBarBehavior.java
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/BottomBarBehavior.java
@@ -47,7 +47,7 @@ public class BottomBarBehavior extends CoordinatorLayout.Behavior
if (defaultDependencyTop == -1) {
defaultDependencyTop = dependency.getTop();
}
- if(dependency.getTop()<0)
+ if (dependency.getTop() < 0)
child.setTranslationY(-dependency.getTop() + defaultDependencyTop);
else
child.setTranslationY(defaultDependencyTop);
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/ContextMenuWebView.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/ContextMenuWebView.java
deleted file mode 100644
index 099b828d..00000000
--- a/app/src/main/java/com/github/dfa/diaspora_android/ui/ContextMenuWebView.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- This file is part of the Diaspora for Android.
-
- Diaspora for Android 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.
-
- Diaspora for Android 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 Diaspora for Android.
-
- If not, see .
- */
-package com.github.dfa.diaspora_android.ui;
-
-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.support.v4.content.LocalBroadcastManager;
-import android.util.AttributeSet;
-import android.view.ContextMenu;
-import android.view.MenuItem;
-import android.widget.Toast;
-
-import com.github.dfa.diaspora_android.R;
-import com.github.dfa.diaspora_android.activity.MainActivity;
-import com.github.dfa.diaspora_android.task.ImageDownloadTask;
-
-import java.io.File;
-
-/**
- * Subclass of WebView which adds a context menu for long clicks on images or links to share, save
- * or open with another browser
- */
-@SuppressWarnings("deprecation")
-public class ContextMenuWebView extends NestedWebView {
-
- public static final int ID_SAVE_IMAGE = 10;
- public static final int ID_IMAGE_EXTERNAL_BROWSER = 11;
- public static final int ID_COPY_LINK = 12;
- public static final int ID_SHARE_LINK = 13;
- public static final int ID_SHARE_IMAGE = 14;
-
- private Context context;
- private Activity parentActivity;
- private String lasLoadUrl = "";
-
- public ContextMenuWebView(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- this.context = context;
- }
-
- public ContextMenuWebView(Context context, AttributeSet attrs) {
- super(context, attrs);
- this.context = context;
- }
-
- @Override
- protected void onCreateContextMenu(ContextMenu menu) {
- super.onCreateContextMenu(menu);
-
- HitTestResult result = getHitTestResult();
-
- MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
- public boolean onMenuItemClick(MenuItem item) {
- HitTestResult result = getHitTestResult();
- String url = result.getExtra();
- 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_ASK_PERMISSIONS_SAVE_IMAGE);
- }
- })
- .setNegativeButton(context.getText(android.R.string.no), null)
- .show();
- }
- parentActivity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
- MainActivity.REQUEST_CODE_ASK_PERMISSIONS_SAVE_IMAGE);
- }
- }
- if (writeToStoragePermitted) {
- if (url != null) {
- 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();
- }
- }
- }
- break;
-
- case ID_SHARE_IMAGE:
- if (url != null) {
- 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, "Share image using"));
- }
- }.execute(url);
- } else {
- Toast.makeText(context, "Cannot share image: url is null", Toast.LENGTH_SHORT).show();
- }
- break;
-
- case ID_IMAGE_EXTERNAL_BROWSER:
- if (url != null) {
- Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
- context.startActivity(intent);
- }
- break;
-
- //Copy url to clipboard
- case ID_COPY_LINK:
- 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();
- }
- break;
-
- //Try to share link to other apps
- case ID_SHARE_LINK:
- if (url != null) {
- Intent sendIntent = new Intent();
- sendIntent.setAction(Intent.ACTION_SEND);
- sendIntent.putExtra(Intent.EXTRA_TEXT, url);
- sendIntent.setType("text/plain");
- context.startActivity(Intent.createChooser(sendIntent, getResources()
- .getText(R.string.context_menu_share_link)));
- }
- break;
- }
- return true;
- }
- };
-
- //Build context menu
- if (result.getType() == HitTestResult.IMAGE_TYPE ||
- 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);
- } 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);
- }
- }
-
- public void loadUrlNew(String url){
- stopLoading();
- loadUrl(url);
- }
-
- @Override
- public void loadUrl(String url) {
- super.loadUrl(url);
-
- // Don't spam intents ;)
- if (!lasLoadUrl.equals(url)) {
- Intent updateActivityTitleIntent = new Intent(MainActivity.ACTION_UPDATE_TITLE_FROM_URL);
- updateActivityTitleIntent.putExtra(MainActivity.EXTRA_URL, getUrl());
- LocalBroadcastManager.getInstance(context).sendBroadcast(updateActivityTitleIntent);
- }
- lasLoadUrl = url;
- }
-
- public void setParentActivity(Activity activity) {
- this.parentActivity = activity;
- }
-}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/CustomWebViewClient.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/CustomWebViewClient.java
deleted file mode 100644
index 8296b47f..00000000
--- a/app/src/main/java/com/github/dfa/diaspora_android/ui/CustomWebViewClient.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- This file is part of the Diaspora for Android.
-
- Diaspora for Android 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.
-
- Diaspora for Android 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 Diaspora for Android.
-
- If not, see .
- */
-package com.github.dfa.diaspora_android.ui;
-
-import android.content.Intent;
-import android.graphics.Bitmap;
-import android.net.Uri;
-import android.webkit.CookieManager;
-import android.webkit.WebView;
-import android.webkit.WebViewClient;
-
-import com.github.dfa.diaspora_android.App;
-
-public class CustomWebViewClient extends WebViewClient {
- private App app;
- private WebView webView;
-
- public CustomWebViewClient(App app, WebView webView) {
- this.app = app;
- this.webView = webView;
- }
-
- public boolean shouldOverrideUrlLoading(WebView view, String url) {
- if (!url.contains(app.getSettings().getPodDomain())) {
- Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
- i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- app.getApplicationContext().startActivity(i);
- return true;
- }
- return false;
- }
-
- public void onPageFinished(WebView view, String url) {
- super.onPageFinished(view, url);
-
- final CookieManager cookieManager = app.getCookieManager();
- String cookies = cookieManager.getCookie(url);
- //Log.d(App.TAG, "All the cookies in a string:" + cookies);
-
- if (cookies != null) {
- cookieManager.setCookie(url, cookies);
- cookieManager.setCookie("https://" + app.getSettings().getPodDomain(), cookies);
- //for (String c : cookies.split(";")) {
- // Log.d(App.TAG, "Cookie: " + c.split("=")[0] + " Value:" + c.split("=")[1]);
- //}
- //new ProfileFetchTask(app).execute();
- }
- }
-
-}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/HtmlTextView.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/HtmlTextView.java
new file mode 100644
index 00000000..26552ec1
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/HtmlTextView.java
@@ -0,0 +1,84 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.ui;
+
+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 com.github.dfa.diaspora_android.activity.MainActivity;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * TextView, that renders HTML with highlited and clickable links and hashtags.
+ * Links are opened in a webbrowser.
+ * 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 AppCompatTextView {
+
+ public HtmlTextView(Context context) {
+ super(context);
+ init();
+ }
+
+ public HtmlTextView(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ init();
+ }
+
+ public HtmlTextView(Context context, AttributeSet attrs, int defStyleAttr) {
+ super(context, attrs, defStyleAttr);
+ init();
+ }
+
+ /**
+ * Linkify, format markdown and escape the displayed message.
+ */
+ private void init() {
+ formatHtmlAndCustomTags();
+ }
+
+ public void setTextFormatted(String text) {
+ setText(text);
+ formatHtmlAndCustomTags();
+ }
+
+ private void formatHtmlAndCustomTags() {
+ setText(new SpannableString(Html.fromHtml(getText().toString())));
+ Linkify.TransformFilter filter = new Linkify.TransformFilter() {
+ public final String transformUrl(final Matcher match, String url) {
+ return match.group();
+ }
+ };
+
+ Pattern hashtagPattern = Pattern.compile("[#]+[A-Za-z0-9-_]+\\b");
+ String hashtagScheme = MainActivity.CONTENT_HASHTAG;
+ Linkify.addLinks(this, hashtagPattern, hashtagScheme, null, filter);
+
+ Pattern urlPattern = Patterns.WEB_URL;
+ Linkify.addLinks(this, urlPattern, null, null, filter);
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/PodSelectionDialog.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/PodSelectionDialog.java
new file mode 100644
index 00000000..abb31703
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/PodSelectionDialog.java
@@ -0,0 +1,275 @@
+package com.github.dfa.diaspora_android.ui;
+
+
+import android.annotation.SuppressLint;
+import android.app.Dialog;
+import android.os.Bundle;
+import android.support.annotation.NonNull;
+import android.support.v7.app.AlertDialog;
+import android.text.TextUtils;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.RadioGroup;
+import android.widget.Spinner;
+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.DiasporaPodList.DiasporaPod;
+import com.github.dfa.diaspora_android.data.DiasporaPodList.DiasporaPod.DiasporaPodUrl;
+import com.github.dfa.diaspora_android.ui.theme.ThemeHelper;
+import com.github.dfa.diaspora_android.ui.theme.ThemedAppCompatDialogFragment;
+import com.github.dfa.diaspora_android.util.AppSettings;
+import com.github.dfa.diaspora_android.web.ProxyHandler;
+
+import org.json.JSONException;
+
+import java.util.List;
+
+import butterknife.BindView;
+import butterknife.ButterKnife;
+import butterknife.OnClick;
+import butterknife.OnItemSelected;
+
+/**
+ * Dialog that helps the user configure a pod
+ * Created by gsantner on 06.10.16.
+ */
+public class PodSelectionDialog extends ThemedAppCompatDialogFragment {
+ public static final String TAG = "com.github.dfa.diaspora_android.ui.PodSelectionDialog";
+
+ public interface PodSelectionDialogResultListener {
+ void onPodSelectionDialogResult(DiasporaPod pod, boolean accepted);
+ }
+
+ public static PodSelectionDialog newInstance(PodSelectionDialogResultListener resultListener) {
+ return newInstance(new DiasporaPod(), resultListener);
+ }
+
+ public static PodSelectionDialog newInstance(DiasporaPod pod, PodSelectionDialogResultListener resultListener) {
+ PodSelectionDialog dialog = new PodSelectionDialog();
+ dialog.setPod(pod);
+ dialog.setResultListener(resultListener);
+ return dialog;
+ }
+
+ /*
+ // ██████╗ ██╗ █████╗ ██╗ ██████╗ ██████╗
+ // ██╔══██╗██║██╔══██╗██║ ██╔═══██╗██╔════╝
+ // ██║ ██║██║███████║██║ ██║ ██║██║ ███╗
+ // ██║ ██║██║██╔══██║██║ ██║ ██║██║ ██║
+ // ██████╔╝██║██║ ██║███████╗╚██████╔╝╚██████╔╝
+ // ╚═════╝ ╚═╝╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝
+ */
+
+ @BindView(R.id.podselection__dialog__edit_podaddress)
+ EditText editPodAddress;
+
+ @BindView(R.id.podselection__dialog__edit_pod_name)
+ EditText editPodName;
+
+ @BindView(R.id.podselection__dialog__radiogroup_protocol)
+ RadioGroup radiogrpProtocol;
+
+ @BindView(R.id.podselection__dialog__text_profile)
+ TextView textProfile;
+
+ @BindView(R.id.podselection__dialog__spinner_profile)
+ Spinner spinnerProfile;
+
+ @BindView(R.id.podselection__dialog__check_torpreset)
+ CheckBox checkboxTorPreset;
+
+ @BindView(R.id.podselection__dialog__text_torpreset)
+ TextView textTorPreset;
+
+ @BindView(R.id.podselection__dialog__text_pod_name)
+ TextView textPodName;
+
+ @BindView(R.id.podselection__dialog__text_pod_address)
+ TextView textPodAddress;
+
+ @BindView(R.id.podselection__dialog__text_protocol)
+ TextView textProtocol;
+
+ @BindView(R.id.podselection__dialog__btn_ok)
+ Button btnOk;
+
+ @BindView(R.id.podselection__dialog__btn_cancel)
+ Button btnCancel;
+
+ private PodSelectionDialogResultListener resultListener;
+ private View root;
+ private DiasporaPod pod = new DiasporaPod();
+ private App app;
+
+ @NonNull
+ @Override
+ @SuppressLint("InflateParams")
+ public Dialog onCreateDialog(Bundle savedInstanceState) {
+ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
+ LayoutInflater inflater = getActivity().getLayoutInflater();
+ app = (App) getActivity().getApplication();
+
+ // Bind UI
+ root = inflater.inflate(R.layout.podselection__dialog, null);
+ ButterKnife.bind(this, root);
+ editPodName.setText(pod.getName());
+ List podUrls = pod.getPodUrls();
+ if (podUrls.size() > 0) {
+ uiLoadDiasporaUrl(0);
+ }
+ if (podUrls.size() > 1) {
+ textProfile.setVisibility(View.VISIBLE);
+ spinnerProfile.setVisibility(View.VISIBLE);
+ String[] podUrlss = new String[podUrls.size()];
+ for (int i = 0; i < podUrls.size(); podUrlss[i] = podUrls.get(i++).getBaseUrl()) ;
+ ArrayAdapter spinnerAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, podUrlss);
+ spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
+ spinnerProfile.setAdapter(spinnerAdapter);
+ }
+ applyColorsToViews();
+ builder.setView(root);
+ return builder.create();
+ }
+
+ protected void applyColorsToViews() {
+ ThemeHelper.getInstance(app.getSettings());
+
+ textPodAddress.setTextColor(ThemeHelper.getAccentColor());
+ textPodName.setTextColor(ThemeHelper.getAccentColor());
+ textProfile.setTextColor(ThemeHelper.getAccentColor());
+ textProtocol.setTextColor(ThemeHelper.getAccentColor());
+ textTorPreset.setTextColor(ThemeHelper.getAccentColor());
+ btnOk.setTextColor(ThemeHelper.getAccentColor());
+ btnCancel.setTextColor(ThemeHelper.getAccentColor());
+
+ ThemeHelper.updateEditTextColor(editPodAddress);
+ ThemeHelper.updateEditTextColor(editPodName);
+ ThemeHelper.updateCheckBoxColor(checkboxTorPreset);
+ ThemeHelper.updateRadioGroupColor(radiogrpProtocol);
+ }
+
+ @Override
+ protected AppSettings getAppSettings() {
+ if (isAdded()) {
+ return ((App) getActivity().getApplication()).getSettings();
+ } else {
+ return AppSettings.get();
+ }
+ }
+
+ @OnItemSelected(R.id.podselection__dialog__spinner_profile)
+ public void spinnerItemSelected(Spinner spinner, int position) {
+ uiLoadDiasporaUrl(position);
+ }
+
+ public void uiLoadDiasporaUrl(int wantedPodUrlPos) {
+ List podUrls = pod.getPodUrls();
+ if (podUrls.size() == 0) {
+ return;
+ }
+ wantedPodUrlPos = wantedPodUrlPos < podUrls.size() ? wantedPodUrlPos : 0;
+
+ DiasporaPodUrl url1 = podUrls.get(wantedPodUrlPos);
+ editPodAddress.setText(url1.getHost());
+ radiogrpProtocol.check(url1.getProtocol().equals("https")
+ ? R.id.podselection__dialog__radio_https : R.id.podselection__dialog__radio_http);
+
+ // Tor
+ boolean isOnionUrl = url1.getHost().endsWith(".onion");
+ setUiVisible(textTorPreset, isOnionUrl);
+ setUiVisible(checkboxTorPreset, isOnionUrl);
+ checkboxTorPreset.setChecked(isOnionUrl);
+ }
+
+ public void setUiVisible(View view, boolean visible) {
+ if (view != null) {
+ view.setVisibility(visible ? View.VISIBLE : View.GONE);
+ }
+ }
+
+
+ @OnClick({R.id.podselection__dialog__btn_ok, R.id.podselection__dialog__btn_cancel})
+ public void onResultButtonClicked(View view) {
+ boolean POSITIVE_PRESSED = view.getId() == R.id.podselection__dialog__btn_ok;
+ if (POSITIVE_PRESSED) {
+ if (!checkInputs()) {
+ return;
+ }
+ DiasporaPodUrl podUrl = new DiasporaPodUrl();
+ if (radiogrpProtocol.getCheckedRadioButtonId() == R.id.podselection__dialog__radio_https) {
+ podUrl.setHttpsDefaults();
+ } else {
+ podUrl.setHttpDefaults();
+ }
+ podUrl.setHost(editPodAddress.getText().toString());
+ pod.setName(editPodName.getText().toString());
+ pod.getPodUrls().clear();
+ pod.getPodUrls().add(podUrl);
+
+ // Load Tor preset
+ if (pod.getPodUrl().getHost().endsWith(".onion") && checkboxTorPreset.isChecked()) {
+ AppSettings settings = app.getSettings();
+ settings.setProxyHttpEnabled(true);
+ settings.setProxyWasEnabled(false);
+ settings.setProxyHttpPort(8118);
+ settings.setProxyHttpHost("127.0.0.1");
+ ProxyHandler.getInstance().updateProxySettings(getContext());
+ }
+
+ getDialog().dismiss();
+ publishResult(true);
+ } else {
+ getDialog().cancel();
+ publishResult(false);
+ }
+ }
+
+ public boolean checkInputs() {
+ boolean ok = true;
+ String s = editPodAddress.getText().toString();
+ if (TextUtils.isEmpty(s) || s.length() < 3) {
+ editPodAddress.setError(getString(R.string.missing_value));
+ ok = false;
+ }
+ s = editPodName.getText().toString();
+ if (TextUtils.isEmpty(s) || s.length() < 3) {
+ editPodName.setError(getString(R.string.missing_value));
+ ok = false;
+ }
+ return ok;
+ }
+
+ public void publishResult(boolean accepted) {
+ if (resultListener != null) {
+ resultListener.onPodSelectionDialogResult(pod, accepted);
+ }
+ }
+
+ /*
+ * GETTER & SETTER
+ */
+ public PodSelectionDialogResultListener getResultListener() {
+ return resultListener;
+ }
+
+ public void setResultListener(PodSelectionDialogResultListener resultListener) {
+ this.resultListener = resultListener;
+ }
+
+ public DiasporaPod getPod() {
+ return pod;
+ }
+
+ public void setPod(DiasporaPod pod) {
+ try {
+ this.pod = new DiasporaPod().fromJson(pod.toJson());
+ } catch (JSONException ignored) {
+ }
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/SearchOrCustomTextDialogCreator.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/SearchOrCustomTextDialogCreator.java
new file mode 100644
index 00000000..c7421567
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/SearchOrCustomTextDialogCreator.java
@@ -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 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 hl = new ArrayList<>();
+ ArrayList 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 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 hl = new ArrayList<>();
+ ArrayList 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();
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ColorPalette.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ColorPalette.java
new file mode 100644
index 00000000..d483605e
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ColorPalette.java
@@ -0,0 +1,289 @@
+package com.github.dfa.diaspora_android.ui.theme;
+
+import android.content.Context;
+import android.graphics.Color;
+import android.support.v4.content.ContextCompat;
+import android.support.v4.graphics.ColorUtils;
+
+import com.github.dfa.diaspora_android.R;
+
+/**
+ * Class that handles Colors
+ * Created by dnld on 24/02/16.
+ */
+public class ColorPalette {
+
+ public static int[] getAccentColors(Context context) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_red_500),
+ ContextCompat.getColor(context, R.color.md_purple_500),
+ ContextCompat.getColor(context, R.color.md_deep_purple_500),
+ ContextCompat.getColor(context, R.color.md_blue_500),
+ ContextCompat.getColor(context, R.color.md_light_blue_500),
+ ContextCompat.getColor(context, R.color.md_cyan_500),
+ ContextCompat.getColor(context, R.color.md_teal_500),
+ ContextCompat.getColor(context, R.color.md_green_500),
+ ContextCompat.getColor(context, R.color.md_yellow_500),
+ ContextCompat.getColor(context, R.color.md_orange_500),
+ ContextCompat.getColor(context, R.color.md_deep_orange_500),
+ ContextCompat.getColor(context, R.color.md_brown_500),
+ ContextCompat.getColor(context, R.color.md_blue_grey_500),
+ };
+ }
+
+ public static int getObscuredColor(int c) {
+ float[] hsv = new float[3];
+ int color = c;
+ Color.colorToHSV(color, hsv);
+ hsv[2] *= 0.85f; // value component
+ color = Color.HSVToColor(hsv);
+ return color;
+ }
+
+ public static int getTransparentColor(int color, int alpha) {
+ return ColorUtils.setAlphaComponent(color, alpha);
+ }
+
+ public static int[] getTransparencyShadows(int color) {
+ int[] shadows = new int[10];
+ for (int i = 0; i < 10; i++)
+ shadows[i] = (ColorPalette.getTransparentColor(color, ((100 - (i * 10)) * 255) / 100));
+ return shadows;
+ }
+
+ public static int[] getBaseColors(Context context) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_red_500),
+ ContextCompat.getColor(context, R.color.md_pink_500),
+ ContextCompat.getColor(context, R.color.md_purple_500),
+ ContextCompat.getColor(context, R.color.md_deep_purple_500),
+ ContextCompat.getColor(context, R.color.md_indigo_500),
+ ContextCompat.getColor(context, R.color.md_blue_500),
+ ContextCompat.getColor(context, R.color.md_light_blue_500),
+ ContextCompat.getColor(context, R.color.md_cyan_500),
+ ContextCompat.getColor(context, R.color.md_teal_500),
+ ContextCompat.getColor(context, R.color.md_green_500),
+ ContextCompat.getColor(context, R.color.md_light_green_500),
+ ContextCompat.getColor(context, R.color.md_lime_500),
+ ContextCompat.getColor(context, R.color.md_yellow_500),
+ ContextCompat.getColor(context, R.color.md_amber_500),
+ ContextCompat.getColor(context, R.color.md_orange_500),
+ ContextCompat.getColor(context, R.color.md_deep_orange_500),
+ ContextCompat.getColor(context, R.color.md_brown_500),
+ ContextCompat.getColor(context, R.color.md_blue_grey_500),
+ ContextCompat.getColor(context, R.color.md_grey_500)
+ };
+ }
+
+ public static int[] getColors(Context context, int c) {
+ if (c == ContextCompat.getColor(context, R.color.md_red_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_red_200),
+ ContextCompat.getColor(context, R.color.md_red_300),
+ ContextCompat.getColor(context, R.color.md_red_400),
+ ContextCompat.getColor(context, R.color.md_red_500),
+ ContextCompat.getColor(context, R.color.md_red_600),
+ ContextCompat.getColor(context, R.color.md_red_700),
+ ContextCompat.getColor(context, R.color.md_red_800),
+ ContextCompat.getColor(context, R.color.md_red_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_pink_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_pink_200),
+ ContextCompat.getColor(context, R.color.md_pink_300),
+ ContextCompat.getColor(context, R.color.md_pink_400),
+ ContextCompat.getColor(context, R.color.md_pink_500),
+ ContextCompat.getColor(context, R.color.md_pink_600),
+ ContextCompat.getColor(context, R.color.md_pink_700),
+ ContextCompat.getColor(context, R.color.md_pink_800),
+ ContextCompat.getColor(context, R.color.md_pink_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_purple_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_purple_200),
+ ContextCompat.getColor(context, R.color.md_purple_300),
+ ContextCompat.getColor(context, R.color.md_purple_400),
+ ContextCompat.getColor(context, R.color.md_purple_500),
+ ContextCompat.getColor(context, R.color.md_purple_600),
+ ContextCompat.getColor(context, R.color.md_purple_700),
+ ContextCompat.getColor(context, R.color.md_purple_800),
+ ContextCompat.getColor(context, R.color.md_purple_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_deep_purple_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_deep_purple_200),
+ ContextCompat.getColor(context, R.color.md_deep_purple_300),
+ ContextCompat.getColor(context, R.color.md_deep_purple_400),
+ ContextCompat.getColor(context, R.color.md_deep_purple_500),
+ ContextCompat.getColor(context, R.color.md_deep_purple_600),
+ ContextCompat.getColor(context, R.color.md_deep_purple_700),
+ ContextCompat.getColor(context, R.color.md_deep_purple_800),
+ ContextCompat.getColor(context, R.color.md_deep_purple_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_indigo_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_indigo_200),
+ ContextCompat.getColor(context, R.color.md_indigo_300),
+ ContextCompat.getColor(context, R.color.md_indigo_400),
+ ContextCompat.getColor(context, R.color.md_indigo_500),
+ ContextCompat.getColor(context, R.color.md_indigo_600),
+ ContextCompat.getColor(context, R.color.md_indigo_700),
+ ContextCompat.getColor(context, R.color.md_indigo_800),
+ ContextCompat.getColor(context, R.color.md_indigo_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_blue_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_blue_200),
+ ContextCompat.getColor(context, R.color.md_blue_300),
+ ContextCompat.getColor(context, R.color.md_blue_400),
+ ContextCompat.getColor(context, R.color.md_blue_500),
+ ContextCompat.getColor(context, R.color.md_blue_600),
+ ContextCompat.getColor(context, R.color.md_blue_650),
+ ContextCompat.getColor(context, R.color.md_blue_700),
+ ContextCompat.getColor(context, R.color.md_blue_750),
+ ContextCompat.getColor(context, R.color.md_blue_800),
+ ContextCompat.getColor(context, R.color.md_blue_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_light_blue_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_light_blue_200),
+ ContextCompat.getColor(context, R.color.md_light_blue_300),
+ ContextCompat.getColor(context, R.color.md_light_blue_400),
+ ContextCompat.getColor(context, R.color.md_light_blue_500),
+ ContextCompat.getColor(context, R.color.md_light_blue_600),
+ ContextCompat.getColor(context, R.color.md_light_blue_700),
+ ContextCompat.getColor(context, R.color.md_light_blue_800),
+ ContextCompat.getColor(context, R.color.md_light_blue_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_cyan_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_cyan_200),
+ ContextCompat.getColor(context, R.color.md_cyan_300),
+ ContextCompat.getColor(context, R.color.md_cyan_400),
+ ContextCompat.getColor(context, R.color.md_cyan_500),
+ ContextCompat.getColor(context, R.color.md_cyan_600),
+ ContextCompat.getColor(context, R.color.md_cyan_700),
+ ContextCompat.getColor(context, R.color.md_cyan_800),
+ ContextCompat.getColor(context, R.color.md_cyan_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_teal_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_teal_200),
+ ContextCompat.getColor(context, R.color.md_teal_300),
+ ContextCompat.getColor(context, R.color.md_teal_400),
+ ContextCompat.getColor(context, R.color.md_teal_500),
+ ContextCompat.getColor(context, R.color.md_teal_600),
+ ContextCompat.getColor(context, R.color.md_teal_700),
+ ContextCompat.getColor(context, R.color.md_teal_800),
+ ContextCompat.getColor(context, R.color.md_teal_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_green_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_green_200),
+ ContextCompat.getColor(context, R.color.md_green_300),
+ ContextCompat.getColor(context, R.color.md_green_400),
+ ContextCompat.getColor(context, R.color.md_green_500),
+ ContextCompat.getColor(context, R.color.md_green_600),
+ ContextCompat.getColor(context, R.color.md_green_700),
+ ContextCompat.getColor(context, R.color.md_green_800),
+ ContextCompat.getColor(context, R.color.md_green_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_light_green_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_light_green_200),
+ ContextCompat.getColor(context, R.color.md_light_green_300),
+ ContextCompat.getColor(context, R.color.md_light_green_400),
+ ContextCompat.getColor(context, R.color.md_light_green_500),
+ ContextCompat.getColor(context, R.color.md_light_green_600),
+ ContextCompat.getColor(context, R.color.md_light_green_700),
+ ContextCompat.getColor(context, R.color.md_light_green_800),
+ ContextCompat.getColor(context, R.color.md_light_green_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_lime_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_lime_200),
+ ContextCompat.getColor(context, R.color.md_lime_300),
+ ContextCompat.getColor(context, R.color.md_lime_400),
+ ContextCompat.getColor(context, R.color.md_lime_500),
+ ContextCompat.getColor(context, R.color.md_lime_600),
+ ContextCompat.getColor(context, R.color.md_lime_700),
+ ContextCompat.getColor(context, R.color.md_lime_800),
+ ContextCompat.getColor(context, R.color.md_lime_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_yellow_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_yellow_400),
+ ContextCompat.getColor(context, R.color.md_yellow_500),
+ ContextCompat.getColor(context, R.color.md_yellow_600),
+ ContextCompat.getColor(context, R.color.md_yellow_700),
+ ContextCompat.getColor(context, R.color.md_yellow_800),
+ ContextCompat.getColor(context, R.color.md_yellow_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_amber_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_amber_200),
+ ContextCompat.getColor(context, R.color.md_amber_300),
+ ContextCompat.getColor(context, R.color.md_amber_400),
+ ContextCompat.getColor(context, R.color.md_amber_500),
+ ContextCompat.getColor(context, R.color.md_amber_600),
+ ContextCompat.getColor(context, R.color.md_amber_700),
+ ContextCompat.getColor(context, R.color.md_amber_800),
+ ContextCompat.getColor(context, R.color.md_amber_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_orange_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_orange_200),
+ ContextCompat.getColor(context, R.color.md_orange_300),
+ ContextCompat.getColor(context, R.color.md_orange_400),
+ ContextCompat.getColor(context, R.color.md_orange_500),
+ ContextCompat.getColor(context, R.color.md_orange_600),
+ ContextCompat.getColor(context, R.color.md_orange_700),
+ ContextCompat.getColor(context, R.color.md_orange_800),
+ ContextCompat.getColor(context, R.color.md_orange_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_deep_orange_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_deep_orange_200),
+ ContextCompat.getColor(context, R.color.md_deep_orange_300),
+ ContextCompat.getColor(context, R.color.md_deep_orange_400),
+ ContextCompat.getColor(context, R.color.md_deep_orange_500),
+ ContextCompat.getColor(context, R.color.md_deep_orange_600),
+ ContextCompat.getColor(context, R.color.md_deep_orange_650),
+ ContextCompat.getColor(context, R.color.md_deep_orange_700),
+ ContextCompat.getColor(context, R.color.md_deep_orange_800),
+ ContextCompat.getColor(context, R.color.md_deep_orange_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_brown_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_brown_200),
+ ContextCompat.getColor(context, R.color.md_brown_300),
+ ContextCompat.getColor(context, R.color.md_brown_400),
+ ContextCompat.getColor(context, R.color.md_brown_500),
+ ContextCompat.getColor(context, R.color.md_brown_600),
+ ContextCompat.getColor(context, R.color.md_brown_700),
+ ContextCompat.getColor(context, R.color.md_brown_800),
+ ContextCompat.getColor(context, R.color.md_brown_900)
+ };
+ } else if (c == ContextCompat.getColor(context, R.color.md_grey_500)) {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_grey_400),
+ ContextCompat.getColor(context, R.color.md_grey_500),
+ ContextCompat.getColor(context, R.color.md_grey_600),
+ ContextCompat.getColor(context, R.color.md_grey_700),
+ ContextCompat.getColor(context, R.color.md_grey_800),
+ ContextCompat.getColor(context, R.color.md_grey_900),
+ Color.parseColor("#000000")
+ };
+ } else {
+ return new int[]{
+ ContextCompat.getColor(context, R.color.md_blue_grey_300),
+ ContextCompat.getColor(context, R.color.md_blue_grey_400),
+ ContextCompat.getColor(context, R.color.md_blue_grey_500),
+ ContextCompat.getColor(context, R.color.md_blue_grey_600),
+ ContextCompat.getColor(context, R.color.md_blue_grey_700),
+ ContextCompat.getColor(context, R.color.md_blue_grey_800),
+ ContextCompat.getColor(context, R.color.md_blue_grey_900)
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemeHelper.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemeHelper.java
new file mode 100644
index 00000000..510bb566
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemeHelper.java
@@ -0,0 +1,179 @@
+/*
+ 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 .
+ This class is inspired by org.horasapps.LeafPic
+ */
+package com.github.dfa.diaspora_android.ui.theme;
+
+import android.content.DialogInterface;
+import android.content.res.ColorStateList;
+import android.graphics.Color;
+import android.graphics.PorterDuff;
+import android.os.Build;
+import android.support.design.widget.TabLayout;
+import android.support.v4.content.ContextCompat;
+import android.support.v4.widget.CompoundButtonCompat;
+import android.support.v7.app.AlertDialog;
+import android.support.v7.widget.ActionMenuView;
+import android.support.v7.widget.Toolbar;
+import android.view.View;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.ProgressBar;
+import android.widget.RadioButton;
+import android.widget.RadioGroup;
+import android.widget.TextView;
+
+import com.github.dfa.diaspora_android.R;
+import com.github.dfa.diaspora_android.util.AppSettings;
+
+/**
+ * Singleton that can be used to color views
+ * Created by vanitas on 06.10.16.
+ */
+
+public class ThemeHelper {
+ private AppSettings appSettings;
+ private static ThemeHelper instance;
+
+ private ThemeHelper(AppSettings appSettings) {
+ this.appSettings = appSettings;
+ }
+
+ public static ThemeHelper getInstance(AppSettings appSettings) {
+ if (instance == null) {
+ instance = new ThemeHelper(appSettings);
+ }
+ return instance;
+ }
+
+ public static ThemeHelper getInstance() {
+ if (instance == null)
+ throw new IllegalStateException("ThemeHelper must be initialized using getInstance(AppSettingsBase) before it can be used!");
+ return instance;
+ }
+
+ public static void updateEditTextColor(EditText editText) {
+ if (editText != null) {
+ editText.setHighlightColor(getInstance().appSettings.getAccentColor());
+ if (Build.VERSION.SDK_INT >= 21) {
+ editText.getBackground().mutate().setColorFilter(getAccentColor(), PorterDuff.Mode.SRC_ATOP);
+ }
+ }
+ }
+
+ public static void updateCheckBoxColor(CheckBox checkBox) {
+ if (checkBox != null) {
+ int states[][] = {{android.R.attr.state_checked}, {}};
+ int colors[] = {ThemeHelper.getAccentColor(), getNeutralGreyColor()};
+ CompoundButtonCompat.setButtonTintList(checkBox, new ColorStateList(states, colors));
+ }
+ }
+
+ public static void updateTabLayoutColor(TabLayout tabLayout) {
+ if (tabLayout != null) {
+ tabLayout.setBackgroundColor(getInstance().appSettings.getPrimaryColor());
+ tabLayout.setSelectedTabIndicatorColor(getInstance().appSettings.getAccentColor());
+ }
+ }
+
+ public static void updateTextViewLinkColor(TextView textView) {
+ if (textView != null) {
+ textView.setHighlightColor(getInstance().appSettings.getAccentColor());
+ textView.setLinkTextColor(getInstance().appSettings.getAccentColor());
+ }
+ }
+
+ public static void updateTextViewTextColor(TextView textView) {
+ if (textView != null) {
+ textView.setTextColor(getInstance().appSettings.getAccentColor());
+ }
+ }
+
+ public static void updateToolbarColor(Toolbar toolbar) {
+ if (toolbar != null) {
+ toolbar.setBackgroundColor(getInstance().appSettings.getPrimaryColor());
+ }
+ }
+
+ public static void updateActionMenuViewColor(ActionMenuView actionMenuView) {
+ if (actionMenuView != null) {
+ actionMenuView.setBackgroundColor(getInstance().appSettings.getPrimaryColor());
+ }
+ }
+
+ public static int getPrimaryColor() {
+ return getInstance().appSettings.getPrimaryColor();
+ }
+
+ public static int getAccentColor() {
+ return getInstance().appSettings.getAccentColor();
+ }
+
+ public static void setPrimaryColorAsBackground(View view) {
+ if (view != null) {
+ view.setBackgroundColor(getPrimaryColor());
+ }
+ }
+
+ public static int getPrimaryDarkColor() {
+ return ColorPalette.getObscuredColor(getPrimaryColor());
+ }
+
+ public static void updateProgressBarColor(ProgressBar progressBar) {
+ if (progressBar != null && progressBar.getProgressDrawable() != null) {
+ progressBar.getProgressDrawable().setColorFilter(getAccentColor(), PorterDuff.Mode.SRC_IN);
+ }
+ }
+
+ public static void updateRadioGroupColor(RadioGroup radioGroup) {
+ if (radioGroup != null && Build.VERSION.SDK_INT >= 21) {
+ for (int i = 0; i < radioGroup.getChildCount(); ++i) {
+ RadioButton btn = ((RadioButton) radioGroup.getChildAt(i));
+ btn.setButtonTintList(new ColorStateList(
+ new int[][]{new int[]{-android.R.attr.state_enabled}, new int[]{android.R.attr.state_enabled}},
+ new int[]{Color.BLACK, ThemeHelper.getAccentColor()}));
+ btn.invalidate();
+ }
+ }
+ }
+
+ public static int getNeutralGreyColor() {
+ return ContextCompat.getColor(getInstance().appSettings.getContext(), R.color.md_grey_800);
+ }
+
+ public static void updateAlertDialogColor(AlertDialog alertDialog) {
+ if (alertDialog != null) {
+ for (int i : new int[]{
+ DialogInterface.BUTTON_POSITIVE,
+ DialogInterface.BUTTON_NEUTRAL,
+ DialogInterface.BUTTON_NEGATIVE}) {
+ Button b = alertDialog.getButton(i);
+ if (b != null) {
+ b.setTextColor(getAccentColor());
+ }
+ }
+ }
+ }
+
+ public static void updateButtonTextColor(Button button) {
+ if (button != null) {
+ button.setTextColor(getAccentColor());
+ }
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/Themeable.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/Themeable.java
new file mode 100644
index 00000000..61ab17fa
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/Themeable.java
@@ -0,0 +1,10 @@
+package com.github.dfa.diaspora_android.ui.theme;
+
+/**
+ * Interface that allows setting Theme colors
+ * Created by vanitas on 24.10.16.
+ */
+
+public interface Themeable {
+ void setColors();
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedActivity.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedActivity.java
new file mode 100644
index 00000000..d8651bb5
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedActivity.java
@@ -0,0 +1,91 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.ui.theme;
+
+import android.annotation.TargetApi;
+import android.content.pm.ActivityInfo;
+import android.os.Build;
+import android.support.v7.app.AppCompatActivity;
+
+import com.github.dfa.diaspora_android.App;
+import com.github.dfa.diaspora_android.R;
+import com.github.dfa.diaspora_android.util.AppSettings;
+import com.github.dfa.diaspora_android.util.ContextUtils;
+
+/**
+ * Activity that supports color schemes
+ * Created by vanitas on 06.10.16.
+ */
+
+public abstract class ThemedActivity extends AppCompatActivity {
+
+ protected AppSettings getAppSettings() {
+ return ((App) getApplication()).getSettings();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ ThemeHelper.getInstance(getAppSettings());
+ updateLanguage();
+ updateStatusBarColor();
+ updateRecentAppColor();
+ applyColorToViews();
+ updateScreenRotation();
+ }
+
+ protected abstract void applyColorToViews();
+
+ /**
+ * Update color of the status bar
+ */
+ @TargetApi(Build.VERSION_CODES.LOLLIPOP)
+ private void updateStatusBarColor() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ getWindow().setStatusBarColor(ThemeHelper.getPrimaryDarkColor());
+ }
+ }
+
+ /**
+ * Update primary color in recent apps overview
+ */
+ @TargetApi(Build.VERSION_CODES.LOLLIPOP)
+ private void updateRecentAppColor() {
+
+ }
+
+ protected void updateScreenRotation() {
+ String setting = getAppSettings().getScreenRotation();
+ int rotation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; // Default (system settings)
+
+ if (setting.equals(getString(R.string.rotation_val_sensor))) {
+ rotation = ActivityInfo.SCREEN_ORIENTATION_SENSOR;
+ } else if (setting.equals(getString(R.string.rotation_val_portrait))) {
+ rotation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;
+ } else if (setting.equals(getString(R.string.rotation_val_landscape))) {
+ rotation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
+ }
+ setRequestedOrientation(rotation);
+ }
+
+ public void updateLanguage() {
+ AppSettings appSettings = getAppSettings();
+ ContextUtils.get().setAppLanguage(appSettings.getLanguage());
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedAlertDialogBuilder.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedAlertDialogBuilder.java
new file mode 100644
index 00000000..c5a3cde7
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedAlertDialogBuilder.java
@@ -0,0 +1,45 @@
+package com.github.dfa.diaspora_android.ui.theme;
+
+import android.content.Context;
+import android.content.DialogInterface;
+import android.support.annotation.NonNull;
+import android.support.annotation.StyleRes;
+import android.support.v7.app.AlertDialog;
+
+import com.github.dfa.diaspora_android.util.AppSettings;
+
+/**
+ * AlertDialog Builder that colors its buttons
+ * Created by vanitas on 06.11.16.
+ */
+
+public class ThemedAlertDialogBuilder extends AlertDialog.Builder {
+ protected AppSettings appSettings;
+
+ public ThemedAlertDialogBuilder(@NonNull Context context, AppSettings appSettings) {
+ super(context);
+ this.appSettings = appSettings;
+ }
+
+ public ThemedAlertDialogBuilder(@NonNull Context context, @StyleRes int themeResId, AppSettings appSettings) {
+ super(context, themeResId);
+ this.appSettings = appSettings;
+ }
+
+ @Override
+ public AlertDialog create() {
+ final AlertDialog dialog = super.create();
+ dialog.setOnShowListener(new DialogInterface.OnShowListener() {
+ @Override
+ public void onShow(DialogInterface dialogInterface) {
+ applyColors(dialog);
+ }
+ });
+ return dialog;
+ }
+
+ private void applyColors(AlertDialog alertDialog) {
+ ThemeHelper.getInstance(appSettings);
+ ThemeHelper.updateAlertDialogColor(alertDialog);
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedAppCompatDialogFragment.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedAppCompatDialogFragment.java
new file mode 100644
index 00000000..11e6f707
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedAppCompatDialogFragment.java
@@ -0,0 +1,28 @@
+package com.github.dfa.diaspora_android.ui.theme;
+
+import android.app.Dialog;
+import android.os.Bundle;
+import android.support.annotation.NonNull;
+import android.support.v7.app.AppCompatDialogFragment;
+
+import com.github.dfa.diaspora_android.util.AppSettings;
+
+/**
+ * Themed DialogFragment
+ * Created by vanitas on 22.10.16.
+ */
+
+public abstract class ThemedAppCompatDialogFragment extends AppCompatDialogFragment {
+
+ @NonNull
+ @Override
+ public Dialog onCreateDialog(Bundle savedInstanceState) {
+ Dialog dialog = super.onCreateDialog(savedInstanceState);
+ ThemeHelper.getInstance(getAppSettings());
+ return dialog;
+ }
+
+ protected abstract void applyColorsToViews();
+
+ protected abstract AppSettings getAppSettings();
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedCheckBoxPreference.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedCheckBoxPreference.java
new file mode 100644
index 00000000..0c829342
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedCheckBoxPreference.java
@@ -0,0 +1,48 @@
+package com.github.dfa.diaspora_android.ui.theme;
+
+import android.content.Context;
+import android.preference.CheckBoxPreference;
+import android.util.AttributeSet;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.CheckBox;
+
+import com.github.dfa.diaspora_android.util.AppSettings;
+
+/**
+ * CheckboxPreference that colors its checkbox with accent color
+ * Created by vanitas on 24.10.16.
+ */
+
+public class ThemedCheckBoxPreference extends CheckBoxPreference implements Themeable {
+ protected View rootLayout;
+
+ @SuppressWarnings("unused")
+ public ThemedCheckBoxPreference(Context context) {
+ super(context);
+ }
+
+ @SuppressWarnings("unused")
+ public ThemedCheckBoxPreference(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ @SuppressWarnings("unused")
+ public ThemedCheckBoxPreference(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+ }
+
+ @Override
+ protected View onCreateView(ViewGroup parent) {
+ rootLayout = super.onCreateView(parent);
+ setColors();
+ return rootLayout;
+ }
+
+ @Override
+ public void setColors() {
+ CheckBox checkBox = rootLayout.findViewById(android.R.id.checkbox);
+ ThemeHelper.getInstance(AppSettings.get());
+ ThemeHelper.updateCheckBoxColor(checkBox);
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedColorPickerPreference.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedColorPickerPreference.java
new file mode 100644
index 00000000..c335d929
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedColorPickerPreference.java
@@ -0,0 +1,64 @@
+package com.github.dfa.diaspora_android.ui.theme;
+
+import android.content.Context;
+import android.graphics.PorterDuff;
+import android.graphics.drawable.Drawable;
+import android.preference.Preference;
+import android.util.AttributeSet;
+import android.view.View;
+import android.widget.ImageView;
+
+import com.github.dfa.diaspora_android.R;
+import com.github.dfa.diaspora_android.util.AppSettings;
+import com.github.dfa.diaspora_android.util.ContextUtils;
+
+/**
+ * Preference that shows selected Color in a circle
+ * Created by vanitas on 25.10.16.
+ */
+
+public class ThemedColorPickerPreference extends Preference implements Themeable {
+ protected ImageView colorPreview;
+
+ @SuppressWarnings("unused")
+ public ThemedColorPickerPreference(Context context) {
+ super(context);
+ }
+
+ @SuppressWarnings("unused")
+ public ThemedColorPickerPreference(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ @SuppressWarnings("unused")
+ public ThemedColorPickerPreference(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+ }
+
+ @Override
+ protected void onBindView(View view) {
+ super.onBindView(view);
+ colorPreview = view.findViewById(android.R.id.icon);
+ setColors();
+ }
+
+ @Override
+ public void setColors() {
+ Drawable circle;
+ if (colorPreview != null && (circle = colorPreview.getDrawable()) != null) {
+ Context c = getContext();
+ AppSettings appSettings = AppSettings.get();
+ String key = getKey();
+
+ 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))) {
+ color = appSettings.getAccentColor();
+ } else {
+ color = appSettings.getColor(key, color, getSharedPreferences());
+ }
+ circle.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
+ }
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedFragment.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedFragment.java
new file mode 100644
index 00000000..6158a4a9
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedFragment.java
@@ -0,0 +1,49 @@
+/*
+ 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 .
+ */
+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 GsFragmentBase {
+ protected AppSettings getAppSettings() {
+ return ((App) getActivity().getApplication()).getSettings();
+ }
+
+ protected abstract void applyColorToViews();
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ ThemeHelper.getInstance(getAppSettings());
+ applyColorToViews();
+ }
+
+
+ public boolean isAllowedIntellihide() {
+ return true;
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedPreferenceCategory.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedPreferenceCategory.java
new file mode 100644
index 00000000..5df13fda
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedPreferenceCategory.java
@@ -0,0 +1,51 @@
+package com.github.dfa.diaspora_android.ui.theme;
+
+import android.content.Context;
+import android.preference.PreferenceCategory;
+import android.util.AttributeSet;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import com.github.dfa.diaspora_android.util.AppSettings;
+
+/**
+ * PreferenceCategory with a colored title
+ * Created by vanitas on 24.10.16.
+ */
+
+public class ThemedPreferenceCategory extends PreferenceCategory implements Themeable {
+ protected TextView titleTextView;
+
+ @SuppressWarnings("unused")
+ public ThemedPreferenceCategory(Context context) {
+ super(context);
+ }
+
+ @SuppressWarnings("unused")
+ public ThemedPreferenceCategory(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ @SuppressWarnings("unused")
+ public ThemedPreferenceCategory(Context context, AttributeSet attrs,
+ int defStyle) {
+ super(context, attrs, defStyle);
+ }
+
+ @Override
+ protected View onCreateView(ViewGroup parent) {
+ View rootLayout = super.onCreateView(parent);
+ this.titleTextView = rootLayout.findViewById(android.R.id.title);
+ setColors();
+ return rootLayout;
+ }
+
+ @Override
+ public void setColors() {
+ if (titleTextView != null) {
+ ThemeHelper.getInstance(AppSettings.get());
+ ThemeHelper.updateTextViewTextColor(titleTextView);
+ }
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedPreferenceFragment.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedPreferenceFragment.java
new file mode 100644
index 00000000..a3a96c5a
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedPreferenceFragment.java
@@ -0,0 +1,45 @@
+package com.github.dfa.diaspora_android.ui.theme;
+
+import android.os.Build;
+import android.preference.Preference;
+import android.preference.PreferenceFragment;
+import android.preference.PreferenceScreen;
+import android.view.Window;
+
+import com.github.dfa.diaspora_android.App;
+import com.github.dfa.diaspora_android.util.AppSettings;
+
+/**
+ * PreferenceFragment with a colored status bar
+ * Created by vanitas on 24.10.16.
+ */
+
+public abstract class ThemedPreferenceFragment extends PreferenceFragment {
+ public abstract void updateViewColors();
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ updateViewColors();
+ }
+
+ @Override
+ public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) {
+ if (isAdded()) {
+ App app = ((App) getActivity().getApplication());
+ AppSettings appSettings = app.getSettings();
+ if (Build.VERSION.SDK_INT >= 21) {
+ if (preference instanceof PreferenceScreen && ((PreferenceScreen) preference).getDialog() != null) {
+ Window window = ((PreferenceScreen) preference).getDialog().getWindow();
+ if (window != null) {
+ ThemeHelper.getInstance(appSettings);
+ window.setStatusBarColor(ThemeHelper.getPrimaryDarkColor());
+ }
+ }
+ }
+ }
+ return super.onPreferenceTreeClick(screen, preference);
+ }
+
+ public abstract String getFragmentTag();
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedVisibilityPreference.java b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedVisibilityPreference.java
new file mode 100644
index 00000000..6bd8c186
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/ui/theme/ThemedVisibilityPreference.java
@@ -0,0 +1,35 @@
+package com.github.dfa.diaspora_android.ui.theme;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.widget.CheckBox;
+
+import com.github.dfa.diaspora_android.R;
+import com.github.dfa.diaspora_android.util.AppSettings;
+
+/**
+ * ThemedCheckBoxPreference with visibility icons instead of checkbox. TODO: Make more flexible?
+ * Created by vanitas on 25.10.16.
+ */
+
+public class ThemedVisibilityPreference extends ThemedCheckBoxPreference {
+ public ThemedVisibilityPreference(Context context) {
+ super(context);
+ }
+
+ public ThemedVisibilityPreference(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ public ThemedVisibilityPreference(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+ }
+
+ @Override
+ public void setColors() {
+ CheckBox checkBox = rootLayout.findViewById(android.R.id.checkbox);
+ checkBox.setButtonDrawable(R.drawable.ic_visibility_selector);
+ ThemeHelper.getInstance(AppSettings.get());
+ ThemeHelper.updateCheckBoxColor(checkBox);
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/util/ActivityUtils.java b/app/src/main/java/com/github/dfa/diaspora_android/util/ActivityUtils.java
new file mode 100644
index 00000000..09ecb767
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/util/ActivityUtils.java
@@ -0,0 +1,86 @@
+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;
+
+import java.io.File;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.Locale;
+
+@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue"})
+public class ActivityUtils extends net.gsantner.opoc.util.ActivityUtils {
+ public ActivityUtils(Activity activity) {
+ super(activity);
+ }
+
+
+ public static ActivityUtils get(Activity activity) {
+ return new ActivityUtils(activity);
+ }
+
+ public File createImageFile() throws IOException {
+ // Create an image file name
+ String timeStamp = new SimpleDateFormat("dd-MM-yy_HH-mm", Locale.getDefault()).format(new Date());
+ String imageFileName = "JPEG_" + timeStamp + "_";
+ AppLog.d(ActivityUtils.class, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath());
+ File storageDir = Environment.getExternalStoragePublicDirectory(
+ Environment.DIRECTORY_PICTURES);
+ return new File(
+ imageFileName + /* prefix */
+ ".jpg", /* suffix */
+ storageDir.getAbsolutePath() /* directory */
+ );
+ }
+
+ /**
+ * Show Information if user is offline, returns true if is not connected to internet
+ *
+ * @param anchor A view anchor
+ */
+ public boolean showInfoIfUserNotConnectedToInternet(View anchor) {
+ boolean isOnline = WebHelper.isOnline(_context);
+ if (!isOnline) {
+ showSnackBar(R.string.sorry_need_to_be_connected_to_internet, true);
+ }
+ return !isOnline;
+ }
+
+ public void logBundle(Bundle savedInstanceState, String k) {
+ if (savedInstanceState != null) {
+ for (String key : savedInstanceState.keySet()) {
+ AppLog.d("Bundle", key + " is a key in the bundle " + k);
+ Object bun = savedInstanceState.get(key);
+ if (bun != null) {
+ if (bun instanceof Bundle) {
+ logBundle((Bundle) bun, k + "." + key);
+ } else if (bun instanceof byte[]) {
+ AppLog.d("Bundle", "Key: " + k + "." + key + ": " + Arrays.toString((byte[]) bun));
+ } else {
+ AppLog.d("Bundle", "Key: " + k + "." + key + ": " + bun.toString());
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * 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);
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/util/AndroidBug5497Workaround.java b/app/src/main/java/com/github/dfa/diaspora_android/util/AndroidBug5497Workaround.java
new file mode 100644
index 00000000..98017bde
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/util/AndroidBug5497Workaround.java
@@ -0,0 +1,58 @@
+package com.github.dfa.diaspora_android.util;
+
+
+import android.app.Activity;
+import android.graphics.Rect;
+import android.view.View;
+import android.view.ViewTreeObserver;
+import android.widget.FrameLayout;
+
+// From https://stackoverflow.com/a/19494006
+public class AndroidBug5497Workaround {
+
+ // For more information, see https://code.google.com/p/android/issues/detail?id=5497
+ // To use this class, simply invoke assistActivity() on an Activity that already has its content view set.
+
+ public static void assistActivity(Activity activity) {
+ new AndroidBug5497Workaround(activity);
+ }
+
+ private View mChildOfContent;
+ private int usableHeightPrevious;
+ private FrameLayout.LayoutParams frameLayoutParams;
+
+ private AndroidBug5497Workaround(Activity activity) {
+ FrameLayout content = activity.findViewById(android.R.id.content);
+ mChildOfContent = content.getChildAt(0);
+ mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
+ public void onGlobalLayout() {
+ possiblyResizeChildOfContent();
+ }
+ });
+ frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
+ }
+
+ private void possiblyResizeChildOfContent() {
+ int usableHeightNow = computeUsableHeight();
+ if (usableHeightNow != usableHeightPrevious) {
+ int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
+ int heightDifference = usableHeightSansKeyboard - usableHeightNow;
+ if (heightDifference > (usableHeightSansKeyboard / 4)) {
+ // keyboard probably just became visible
+ frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
+ } else {
+ // keyboard probably just became hidden
+ frameLayoutParams.height = usableHeightSansKeyboard;
+ }
+ mChildOfContent.requestLayout();
+ usableHeightPrevious = usableHeightNow;
+ }
+ }
+
+ private int computeUsableHeight() {
+ Rect r = new Rect();
+ mChildOfContent.getWindowVisibleDisplayFrame(r);
+ return (r.bottom - r.top);
+ }
+
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/util/AppLog.java b/app/src/main/java/com/github/dfa/diaspora_android/util/AppLog.java
new file mode 100644
index 00000000..2f0f38c8
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/util/AppLog.java
@@ -0,0 +1,244 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.util;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Observable;
+import java.util.Observer;
+
+/**
+ * Class that logs debug messages to Androids Log and to additional targets (like textviews)
+ * Created by gregor on 18.09.16.
+ */
+public class AppLog {
+ private final static String APP_TAG = "d*";
+ private static boolean loggingEnabled = true;
+ private static boolean loggingSpamEnabled = false;
+
+ public static boolean isLoggingEnabled() {
+ return loggingEnabled;
+ }
+
+ public static void setLoggingEnabled(boolean loggingEnabled) {
+ AppLog.loggingEnabled = loggingEnabled;
+ }
+
+ public static boolean isLoggingSpamEnabled() {
+ return loggingSpamEnabled;
+ }
+
+ public static void setLoggingSpamEnabled(boolean loggingSpamEnabled) {
+ AppLog.loggingSpamEnabled = loggingSpamEnabled;
+ }
+
+ private static String getLogPrefix(Object source) {
+ return APP_TAG + "-" + source.getClass().getCanonicalName();
+ }
+
+ /*
+ *
+ * LOGGER METHODS
+ *
+ */
+ public static void v(Object source, String _text) {
+ if (isLoggingEnabled()) {
+ if (source != null) {
+ Log.v(getLogPrefix(source), _text);
+ } else {
+ Log.v("null", _text);
+ }
+ }
+ }
+
+ public static void i(Object source, String _text) {
+ if (isLoggingEnabled()) {
+ if (source != null) {
+ Log.i(getLogPrefix(source), _text);
+ } else {
+ Log.i("null", _text);
+ }
+ }
+ }
+
+ public static void d(Object source, String _text) {
+ if (isLoggingEnabled()) {
+ if (source != null) {
+ Log.d(getLogPrefix(source), _text);
+ } else {
+ Log.d("null", _text);
+ }
+ }
+ }
+
+ public static void e(Object source, String _text) {
+ if (isLoggingEnabled()) {
+ if (source != null) {
+ Log.e(getLogPrefix(source), _text);
+ } else {
+ Log.e("null", _text);
+ }
+ }
+ }
+
+ public static void w(Object source, String _text) {
+ if (isLoggingEnabled()) {
+ if (source != null) {
+ Log.w(getLogPrefix(source), _text);
+ } else {
+ Log.w("null", _text);
+ }
+ }
+ }
+
+ public static void spam(Object source, String _text) {
+ if (isLoggingEnabled() && isLoggingSpamEnabled()) {
+ if (source != null) {
+ Log.v(getLogPrefix(source), _text);
+ } else {
+ Log.v("null", _text);
+ }
+ }
+ }
+
+
+ /**
+ * Class that saves logs eg. for later debugging.
+ * TODO: Differentiate log types (error/debug/info...)
+ */
+ public static class Log extends Observable {
+ public static final int MAX_BUFFER_SIZE = 100;
+
+ public static Log instance;
+ private AppSettings appSettings;
+ private final DateFormat dateFormat;
+ private final ArrayList logBuffer;
+ private final ArrayList observers;
+
+ private Log() {
+ this(null);
+ }
+
+ private Log(AppSettings appSettings) {
+ if (appSettings != null) {
+ //TODO: Store/Restore logBuffer between app starts
+ logBuffer = new ArrayList<>();
+ } else {
+ logBuffer = new ArrayList<>();
+ }
+ SimpleDateFormat.getTimeInstance();
+ dateFormat = SimpleDateFormat.getDateInstance();
+ observers = new ArrayList<>();
+ }
+
+ public static Log getInstance() {
+ if (instance == null) instance = new Log();
+ return instance;
+ }
+
+ public static Log getInstance(AppSettings appSettings) {
+ if (instance == null) instance = new Log(appSettings);
+ return instance;
+ }
+
+ private static String time() {
+ return getInstance().dateFormat.format(new Date()) + ": ";
+ }
+
+ public static void d(String tag, String msg) {
+ Log l = getInstance();
+ android.util.Log.d(tag, msg);
+ l.addLogEntry(msg);
+ l.notifyLogBufferChanged();
+ }
+
+ public static void e(String tag, String msg) {
+ Log l = getInstance();
+ android.util.Log.e(tag, msg);
+ l.addLogEntry(msg);
+ l.notifyLogBufferChanged();
+ }
+
+ public static void i(String tag, String msg) {
+ Log l = getInstance();
+ android.util.Log.i(tag, msg);
+ l.addLogEntry(msg);
+ l.notifyLogBufferChanged();
+ }
+
+ public static void v(String tag, String msg) {
+ Log l = getInstance();
+ android.util.Log.v(tag, msg);
+ l.addLogEntry(msg);
+ l.notifyLogBufferChanged();
+ }
+
+ public static void w(String tag, String msg) {
+ Log l = getInstance();
+ android.util.Log.w(tag, msg);
+ l.addLogEntry(msg);
+ l.notifyLogBufferChanged();
+ }
+
+ public static void wtf(String tag, String msg) {
+ Log l = getInstance();
+ android.util.Log.wtf(tag, msg);
+ l.addLogEntry(msg);
+ l.notifyLogBufferChanged();
+ }
+
+ public synchronized static ArrayList getLogBufferArray() {
+ return getInstance().logBuffer;
+ }
+
+ public synchronized static String getLogBuffer() {
+ String out = "";
+ for (String s : getInstance().logBuffer) {
+ out = out + s + "\n";
+ }
+ return out;
+ }
+
+ private void notifyLogBufferChanged() {
+ if (observers == null) return;
+ for (Observer o : observers) {
+ if (o != null) {
+ o.update(this, null);
+ }
+ }
+ }
+
+ private synchronized void addLogEntry(String msg) {
+ logBuffer.add(time() + msg);
+ while (logBuffer.size() > MAX_BUFFER_SIZE) {
+ logBuffer.remove(0);
+ }
+ }
+
+ public static void addLogObserver(Observer observer) {
+ getInstance().observers.add(observer);
+ }
+
+ public static void removeLogObserver(Observer o) {
+ getInstance().observers.remove(o);
+ }
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/util/AppSettings.java b/app/src/main/java/com/github/dfa/diaspora_android/util/AppSettings.java
new file mode 100644
index 00000000..1ced82bb
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/util/AppSettings.java
@@ -0,0 +1,480 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.util;
+
+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;
+import com.github.dfa.diaspora_android.R;
+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.preference.SharedPreferencesPropertyBackend;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.File;
+import java.util.List;
+
+/**
+ * Settings
+ * Created by gsantner (gsantner AT mailbox DOT org) on 20.03.16. Part of dandelion*.
+ */
+@SuppressWarnings("ConstantConditions")
+public class AppSettings extends SharedPreferencesPropertyBackend {
+ private final SharedPreferences _prefPod;
+ private DiasporaPod currentPod0Cached;
+
+ public static AppSettings get() {
+ return new AppSettings(App.get());
+ }
+
+ public AppSettings(Context context) {
+ super(context);
+ _prefPod = _context.getSharedPreferences("pod0", Context.MODE_PRIVATE);
+ }
+
+ /**
+ * Clear all settings in _prefPod (Settings related to the configured pod)
+ * This uses commit instead of apply, since
+ * SettingsActivity.SettingsFragmentDebugging.showWipeSettingsDialog()
+ * kills the app after the calling this, so we have to block until we are finished.
+ */
+ @SuppressLint("CommitPrefEdits")
+ public void resetPodSettings() {
+ super.resetSettings(_prefPod);
+ }
+
+ /**
+ * Clear all settings in _prefApp (related to the App itself)
+ * This uses commit instead of apply, since
+ * SettingsActivity.SettingsFragmentDebugging.showWipeSettingsDialog()
+ * kills the app after the calling this, so we have to block until we are finished.
+ */
+ @SuppressLint("CommitPrefEdits")
+ public void resetAppSettings() {
+ super.resetSettings(_prefApp);
+ }
+
+ //#################################
+ //## Getter & Setter for settings
+ //#################################
+ public String getProfileId() {
+ return getString(R.string.pref_key__podprofile_id, "", _prefPod);
+ }
+
+ public void setProfileId(String profileId) {
+ setString(R.string.pref_key__podprofile_id, profileId, _prefPod);
+ }
+
+ public boolean isLoadImages() {
+ return getBool(R.string.pref_key__load_images, true);
+ }
+
+ public int getMinimumFontSize() {
+ switch (getString(R.string.pref_key__font_size, "")) {
+ case "huge":
+ return 20;
+ case "large":
+ return 16;
+ case "normal":
+ return 8;
+ default:
+ setString(R.string.pref_key__font_size, "normal");
+ return 8;
+ }
+ }
+
+ public String getAvatarUrl() {
+ return getString(R.string.pref_key__podprofile_avatar_url, "", _prefPod);
+ }
+
+ public void setAvatarUrl(String avatarUrl) {
+ setString(R.string.pref_key__podprofile_avatar_url, avatarUrl, _prefPod);
+ }
+
+ public String getName() {
+ return getString(R.string.pref_key__podprofile_name, "", _prefPod);
+ }
+
+ public void setName(String name) {
+ setString(R.string.pref_key__podprofile_name, name, _prefPod);
+ }
+
+ public DiasporaPod getPod() {
+ if (currentPod0Cached == null) {
+ String pref = getString(R.string.pref_key__current_pod_0, "", _prefPod);
+
+ try {
+ currentPod0Cached = new DiasporaPod().fromJson(new JSONObject(pref));
+ } catch (JSONException e) {
+ currentPod0Cached = null;
+ }
+ }
+ return currentPod0Cached;
+ }
+
+ public void setPod(DiasporaPod pod) {
+ try {
+ setString(R.string.pref_key__current_pod_0,
+ pod == null ? null : pod.toJson().toString(), _prefPod);
+ currentPod0Cached = pod;
+ } catch (JSONException ignored) {
+ }
+ }
+
+ public boolean hasPod() {
+ return !getString(R.string.pref_key__current_pod_0, "", _prefPod).equals("");
+ }
+
+ public void setPodAspects(DiasporaAspect[] aspects) {
+ 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() {
+ String[] s = getStringArray(R.string.pref_key__podprofile_aspects, _prefPod);
+ DiasporaAspect[] aspects = new DiasporaAspect[s.length];
+ for (int i = 0; i < aspects.length; i++) {
+ aspects[i] = new DiasporaAspect(s[i]);
+ }
+ return aspects;
+ }
+
+ public String[] getFollowedTags() {
+ return getStringArray(R.string.pref_key__podprofile_followed_tags, _prefPod);
+ }
+
+ public void setFollowedTags(String[] values) {
+ setStringArray(R.string.pref_key__podprofile_followed_tags, values, _prefPod);
+ }
+
+ public String[] getFollowedTagsFavs() {
+ return getStringArray(R.string.pref_key__podprofile_followed_tags_favs, _prefPod);
+ }
+
+ public void setFollowedTagsFavs(List values) {
+ setStringList(R.string.pref_key__podprofile_followed_tags_favs, values, _prefPod);
+ }
+
+ public String[] getAspectFavs() {
+ return getStringArray(R.string.pref_key__podprofile_aspects_favs, _prefPod);
+ }
+
+ public void setAspectFavs(List values) {
+ setStringList(R.string.pref_key__podprofile_aspects_favs, values, _prefPod);
+ }
+
+ public int getUnreadMessageCount() {
+ return getInt(R.string.pref_key__podprofile_unread_message_count, 0, _prefPod);
+ }
+
+ public void setUnreadMessageCount(int unreadMessageCount) {
+ setInt(R.string.pref_key__podprofile_unread_message_count, unreadMessageCount, _prefPod);
+ }
+
+ public int getNotificationCount() {
+ return getInt(R.string.pref_key__podprofile_notification_count, 0, _prefPod);
+ }
+
+ public void setNotificationCount(int notificationCount) {
+ setInt(R.string.pref_key__podprofile_notification_count, notificationCount, _prefPod);
+ }
+
+ public boolean isAppendSharedViaApp() {
+ return getBool(R.string.pref_key__append_shared_via_app, true);
+ }
+
+ @SuppressLint("CommitPrefEdits")
+ public void setProxyHttpEnabled(boolean enabled) {
+ //commit instead of apply because the app is likely to be killed before apply is called.
+ _prefApp.edit().putBoolean(rstr(R.string.pref_key__http_proxy_enabled), enabled).commit();
+ }
+
+ /**
+ * Default return value: false
+ *
+ * @return whether proxy is enabled or not
+ */
+ public boolean isProxyHttpEnabled() {
+ try {
+ return getBool(R.string.pref_key__http_proxy_enabled, false);
+ } catch (ClassCastException e) {
+ setProxyHttpEnabled(false);
+ return false;
+ }
+ }
+
+ public boolean wasProxyEnabled() {
+ return getBool(R.string.pref_key__proxy_was_enabled, false);
+ }
+
+ /**
+ * Needed in order to determine, whether the proxy has just been disabled (trigger app restart)
+ * or if proxy was disabled before (do not restart app)
+ *
+ * @param b new value
+ */
+ @SuppressLint("CommitPrefEdits")
+ public void setProxyWasEnabled(boolean b) {
+ _prefApp.edit().putBoolean(rstr(R.string.pref_key__proxy_was_enabled), b).commit();
+ }
+
+ /**
+ * Default value: ""
+ *
+ * @return proxy host
+ */
+ public String getProxyHttpHost() {
+ return getString(R.string.pref_key__http_proxy_host, "");
+ }
+
+ public void setProxyHttpHost(String value) {
+ setString(R.string.pref_key__http_proxy_host, value);
+ }
+
+ /**
+ * Default value: 0
+ *
+ * @return proxy port
+ */
+ public int getProxyHttpPort() {
+ try {
+ String str = getString(R.string.pref_key__http_proxy_port, "0");
+ return Integer.parseInt(str);
+ } catch (ClassCastException e) {
+ int port = getInt(R.string.pref_key__http_proxy_port, 0);
+ setProxyHttpPort(port);
+ return port;
+ }
+ }
+
+ public void setProxyHttpPort(int value) {
+ setString(R.string.pref_key__http_proxy_port, Integer.toString(value));
+ }
+
+ public ProxyHandler.ProxySettings getProxySettings() {
+ return new ProxyHandler.ProxySettings(isProxyHttpEnabled(), getProxyHttpHost(), getProxyHttpPort());
+ }
+
+ public boolean isIntellihideToolbars() {
+ return getBool(R.string.pref_key__intellihide_toolbars, false);
+ }
+
+ public boolean isChromeCustomTabsEnabled() {
+ return getBool(R.string.pref_key__chrome_custom_tabs_enabled, true);
+ }
+
+ public boolean isLoggingEnabled() {
+ return getBool(R.string.pref_key__logging_enabled, false);
+ }
+
+ public boolean isLoggingSpamEnabled() {
+ return getBool(R.string.pref_key__logging_spam_enabled, false);
+ }
+
+ public boolean isVisibleInNavExit() {
+ return getBool(R.string.pref_key__visibility_nav__exit, true);
+ }
+
+ public boolean isVisibleInNavHelp_license() {
+ return getBool(R.string.pref_key__visibility_nav__help_license, true);
+ }
+
+ public boolean isVisibleInNavPublic_activities() {
+ return getBool(R.string.pref_key__visibility_nav__public_activities, false);
+ }
+
+ public boolean isVisibleInNavMentions() {
+ return getBool(R.string.pref_key__visibility_nav__mentions, false);
+ }
+
+ public boolean isVisibleInNavCommented() {
+ return getBool(R.string.pref_key__visibility_nav__commented, true);
+ }
+
+ public boolean isVisibleInNavLiked() {
+ return getBool(R.string.pref_key__visibility_nav__liked, true);
+ }
+
+ public boolean isVisibleInNavActivities() {
+ return getBool(R.string.pref_key__visibility_nav__activities, true);
+ }
+
+ public boolean isVisibleInNavAspects() {
+ return getBool(R.string.pref_key__visibility_nav__aspects, true);
+ }
+
+ public boolean isVisibleInNavFollowed_tags() {
+ return getBool(R.string.pref_key__visibility_nav__followed_tags, true);
+ }
+
+ public boolean isVisibleInNavProfile() {
+ return getBool(R.string.pref_key__visibility_nav__profile, true);
+ }
+
+ public boolean isVisibleInNavContacts() {
+ return getBool(R.string.pref_key__visibility_nav__contacts, false);
+ }
+
+ public boolean isVisibleInNavStatistics() {
+ return getBool(R.string.pref_key__visibility_nav__statistics, false);
+ }
+
+ public boolean isVisibleInNavReports() {
+ return getBool(R.string.pref_key__visibility_nav__reports, false);
+ }
+
+ public boolean isVisibleInNavGsantnerAccount() {
+ return getBool(R.string.pref_key__visibility_nav__gsantner_account, false);
+ }
+
+ public boolean isVisibleInNavToggleMobileDesktop() {
+ return getBool(R.string.pref_key__visibility_nav__toggle_mobile_desktop, false);
+ }
+
+ public boolean isTopbarStreamShortcutEnabled() {
+ 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);
+ }
+
+ public boolean isAppFirstStart() {
+ boolean value = getBool(R.string.pref_key__app_first_start, true);
+ setBool(R.string.pref_key__app_first_start, false);
+ 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 && !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);
+ }
+
+ public void setLastVisitedPositionInStream(long timestamp) {
+ setLong(R.string.pref_key__podprofile_last_stream_position, timestamp, _prefPod);
+ }
+
+ public void setLanguage(String value) {
+ setString(R.string.pref_key__language, value);
+ }
+
+ public String getLanguage() {
+ return getString(R.string.pref_key__language, "");
+ }
+
+ public void setPrimaryColorSettings(int base, int shade) {
+ setInt(R.string.pref_key__primary_color_base, base);
+ setInt(R.string.pref_key__primary_color_shade, shade);
+ }
+
+ public int[] getPrimaryColorSettings() {
+ return new int[]{
+ getInt(R.string.pref_key__primary_color_base, rcolor(R.color.md_blue_650)),
+ getInt(R.string.pref_key__primary_color_shade, rcolor(R.color.primary))
+ };
+ }
+
+ @SuppressWarnings("ConstantConditions")
+ public int getPrimaryColor() {
+ if (isAmoledColorMode()) {
+ return Color.BLACK;
+ } else {
+ return getInt(R.string.pref_key__primary_color_shade, rcolor(
+ BuildConfig.IS_TEST_BUILD ? R.color.md_brown_800 : R.color.primary));
+ }
+ }
+
+ public void setAccentColorSettings(int base, int shade) {
+ setInt(R.string.pref_key__accent_color_base, base);
+ setInt(R.string.pref_key__accent_color_shade, shade);
+ }
+
+ public int[] getAccentColorSettings() {
+ return new int[]{
+ getInt(R.string.pref_key__accent_color_base, rcolor(R.color.md_green_400)),
+ getInt(R.string.pref_key__accent_color_shade, rcolor(R.color.accent))
+ };
+ }
+
+ public int getAccentColor() {
+ return getInt(R.string.pref_key__accent_color_shade, rcolor(R.color.accent));
+ }
+
+ public boolean isExtendedNotificationsActivated() {
+ return getBool(R.string.pref_key__extended_notifications, false);
+ }
+
+ public boolean isAmoledColorMode() {
+ 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);
+ }
+
+ public boolean isEditorStatusBarHidden() {
+ return getBool(R.string.pref_key__is_overview_statusbar_hidden, false);
+ }
+
+ public void setRecreateMainActivity(boolean value) {
+ setBool(R.string.pref_key__recreate_main_activity, value);
+ }
+
+ public boolean isRecreateMainActivity() {
+ boolean value = getBool(R.string.pref_key__recreate_main_activity, false);
+ setRecreateMainActivity(false);
+ return value;
+ }
+
+ public boolean isShowTitleInMainView() {
+ return getBool(R.string.pref_key__show_title, false);
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/util/ContextUtils.java b/app/src/main/java/com/github/dfa/diaspora_android/util/ContextUtils.java
new file mode 100644
index 00000000..d2132cc4
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/util/ContextUtils.java
@@ -0,0 +1,58 @@
+package com.github.dfa.diaspora_android.util;
+
+import android.content.Context;
+import android.os.Bundle;
+import android.os.Environment;
+
+import com.github.dfa.diaspora_android.App;
+
+import java.io.File;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.Locale;
+
+@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue"})
+public class ContextUtils extends net.gsantner.opoc.util.ContextUtils {
+ protected ContextUtils(Context context) {
+ super(context);
+ }
+
+
+ public static ContextUtils get() {
+ return new ContextUtils(App.get());
+ }
+
+ public File createImageFile() throws IOException {
+ // Create an image file name
+ String timeStamp = new SimpleDateFormat("dd-MM-yy_HH-mm", Locale.getDefault()).format(new Date());
+ String imageFileName = "JPEG_" + timeStamp + "_";
+ AppLog.d(ContextUtils.class, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath());
+ File storageDir = Environment.getExternalStoragePublicDirectory(
+ Environment.DIRECTORY_PICTURES);
+ return new File(
+ imageFileName + /* prefix */
+ ".jpg", /* suffix */
+ storageDir.getAbsolutePath() /* directory */
+ );
+ }
+
+ public void logBundle(Bundle savedInstanceState, String k) {
+ if (savedInstanceState != null) {
+ for (String key : savedInstanceState.keySet()) {
+ AppLog.d("Bundle", key + " is a key in the bundle " + k);
+ Object bun = savedInstanceState.get(key);
+ if (bun != null) {
+ if (bun instanceof Bundle) {
+ logBundle((Bundle) bun, k + "." + key);
+ } else if (bun instanceof byte[]) {
+ AppLog.d("Bundle", "Key: " + k + "." + key + ": " + Arrays.toString((byte[]) bun));
+ } else {
+ AppLog.d("Bundle", "Key: " + k + "." + key + ": " + bun.toString());
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/util/DiasporaUrlHelper.java b/app/src/main/java/com/github/dfa/diaspora_android/util/DiasporaUrlHelper.java
index 7269d1a4..b272dac0 100644
--- a/app/src/main/java/com/github/dfa/diaspora_android/util/DiasporaUrlHelper.java
+++ b/app/src/main/java/com/github/dfa/diaspora_android/util/DiasporaUrlHelper.java
@@ -1,18 +1,18 @@
/*
- This file is part of the Diaspora for Android.
+ This file is part of the dandelion*.
- Diaspora for Android is free software: you can redistribute it and/or modify
+ 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.
- Diaspora for Android is distributed in the hope that it will be useful,
+ 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 Diaspora for Android.
+ along with the dandelion*.
If not, see .
*/
@@ -20,21 +20,22 @@ package com.github.dfa.diaspora_android.util;
import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.R;
-import com.github.dfa.diaspora_android.data.AppSettings;
-import com.github.dfa.diaspora_android.data.PodAspect;
+import com.github.dfa.diaspora_android.data.DiasporaAspect;
+import com.github.dfa.diaspora_android.data.DiasporaPodList.DiasporaPod;
/**
* Helper class that provides easy access to specific urls related to diaspora
* Created by vanitasvitae on 10.08.16.
*/
-@SuppressWarnings("unused")
+@SuppressWarnings({"unused", "SpellCheckingInspection", "SameParameterValue", "WeakerAccess"})
public class DiasporaUrlHelper {
- private AppSettings settings;
+ private final AppSettings settings;
- public static final String HTTPS = "https://";
+ public static final String URL_BLANK = "about:blank";
public static final String SUBURL_NOTIFICATIONS = "/notifications";
public static final String SUBURL_POSTS = "/posts/";
public static final String SUBURL_STREAM = "/stream";
+ public static final String SUBURL_STREAM_WITH_TIMESTAMP = SUBURL_STREAM + "?max_time=";
public static final String SUBURL_CONVERSATIONS = "/conversations";
public static final String SUBURL_NEW_POST = "/status_messages/new";
public static final String SUBURL_PEOPLE = "/people/";
@@ -43,29 +44,47 @@ public class DiasporaUrlHelper {
public static final String SUBURL_COMMENTED = "/commented";
public static final String SUBURL_MENTIONS = "/mentions";
public static final String SUBURL_PUBLIC = "/public";
+ public static final String SUBURL_ASPECT = "/aspects?a_ids[]=";
public static final String SUBURL_TOGGLE_MOBILE = "/mobile/toggle";
public static final String SUBURL_SEARCH_TAGS = "/tags/";
public static final String SUBURL_SEARCH_PEOPLE = "/people.mobile?q=";
public static final String SUBURL_FOLOWED_TAGS = "/followed_tags";
public static final String SUBURL_ASPECTS = "/aspects";
- public static final String URL_BLANK = "about:blank";
+ public static final String SUBURL_STATISTICS = "/statistics";
+ public static final String SUBURL_PERSONAL_SETTINGS = "/user/edit";
+ public static final String SUBURL_MANAGE_TAGS = "/tag_followings/manage";
+ public static final String SUBURL_SIGN_IN = "/users/sign_in";
+ public static final String SUBURL_CONTACTS = "/contacts";
+ public static final String SUBURL_REPORTS = "/reports";
+ public static final String SUBURL_NOTIFICATIONS_ALSO_COMMENTED = "/notifications?type=also_commented";
+ public static final String SUBURL_NOTIFICATIONS_COMMENT_ON_POST = "/notifications?type=comment_on_post";
+ public static final String SUBURL_NOTIFICATIONS_LIKED = "/notifications?type=liked";
+ 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;
}
/**
- * Return a https url of the pod set in AppSettings.
+ * Return a url of the pod set in AppSettingsBase.
* Eg. https://pod.geraspora.de
*
* @return https://(pod-domain.tld)
*/
public String getPodUrl() {
- return HTTPS + settings.getPodDomain();
+ DiasporaPod pod = settings.getPod();
+ if (pod != null) {
+ return pod.getPodUrl().getBaseUrl();
+ }
+ return "http://127.0.0.1";
+
}
/**
- * Return a https url that points to the stream of the configured diaspora account
+ * Return a url that points to the stream of the configured diaspora account
*
* @return https://(pod-domain.tld)/stream
*/
@@ -74,7 +93,16 @@ public class DiasporaUrlHelper {
}
/**
- * Return a https url that points to the notifications feed of the configured diaspora account
+ * Return a url that points to the stream of the configured diaspora account on a timestamp
+ *
+ * @return https://(pod-domain.tld)/stream?max_time=1482057867
+ */
+ public String getStreamWithTimestampUrl(long timestamp) {
+ return getPodUrl() + SUBURL_STREAM_WITH_TIMESTAMP + timestamp;
+ }
+
+ /**
+ * Return a url that points to the notifications feed of the configured diaspora account
*
* @return https://(pod-domain.tld)/notifications
*/
@@ -83,7 +111,7 @@ public class DiasporaUrlHelper {
}
/**
- * Returns a https url that points to the post with the id postId
+ * Returns a url that points to the post with the id postId
*
* @return https://(pod-domain.tld)/posts/(postId)
*/
@@ -92,7 +120,7 @@ public class DiasporaUrlHelper {
}
/**
- * Return a https url that points to the conversations overview of the registered diaspora account
+ * Return a url that points to the conversations overview of the registered diaspora account
*
* @return https://(pod-domain.tld)/conversations
*/
@@ -101,7 +129,7 @@ public class DiasporaUrlHelper {
}
/**
- * Return a https url that points to the new-post form that lets the user create a new post
+ * Return a url that points to the new-post form that lets the user create a new post
*
* @return https://(pod-domain.tld)/status_messages/new
*/
@@ -110,7 +138,7 @@ public class DiasporaUrlHelper {
}
/**
- * Return a https url that shows the profile of the currently registered diaspora account
+ * Return a url that shows the profile of the currently registered diaspora account
*
* @return https://(pod-domain.tld)/people/(profileId)
*/
@@ -119,17 +147,27 @@ public class DiasporaUrlHelper {
}
/**
- * Return a https url that shows the profile of the user with user id profileId
+ * Return a url that shows the profile of the user with user id profileId
*
* @param profileId Id of the profile to be shown
* @return https://(pod-domain.tld)/people/(profileId)
*/
- public String getProfileUrl(long profileId) {
+ public String getProfileUrl(String profileId) {
return getPodUrl() + SUBURL_PEOPLE + profileId;
}
/**
- * Return a https url that points to the activities feed of the currently registered diaspora account
+ * Return a url that queries posts from the given aspect
+ *
+ * @param aspectId ID of the aspect
+ * @return https://(pod-domain.tld)//aspects?a_ids[]=aspectId
+ */
+ public String getAspectUrl(String aspectId) {
+ return getPodUrl() + SUBURL_ASPECT + aspectId;
+ }
+
+ /**
+ * Return a url that points to the activities feed of the currently registered diaspora account
*
* @return https://(pod-domain.tld)/activity
*/
@@ -138,7 +176,7 @@ public class DiasporaUrlHelper {
}
/**
- * Return a https url that points to the feed of posts that were liked by the currently registered diaspora account
+ * Return a url that points to the feed of posts that were liked by the currently registered diaspora account
*
* @return https://(pod-domain.tld)/liked
*/
@@ -147,7 +185,7 @@ public class DiasporaUrlHelper {
}
/**
- * Return a https url that points to the stream of posts that were commented by the currently registered diaspora account
+ * Return a url that points to the stream of posts that were commented by the currently registered diaspora account
*
* @return https://(pod-domain.tld)/commented
*/
@@ -156,7 +194,7 @@ public class DiasporaUrlHelper {
}
/**
- * Return a https url that points to the stream of posts in which the currently registered diaspora account has been mentioned in
+ * Return a url that points to the stream of posts in which the currently registered diaspora account has been mentioned in
*
* @return https://(pod-domain.tld)/mentions
*/
@@ -165,7 +203,7 @@ public class DiasporaUrlHelper {
}
/**
- * Return a https url that points to the stream of public posts
+ * Return a url that points to the stream of public posts
*
* @return https://(pod-domain.tld)/public
*/
@@ -174,7 +212,7 @@ public class DiasporaUrlHelper {
}
/**
- * Return a https url that toggles between mobile and desktop view when opened
+ * Return a url that toggles between mobile and desktop view when opened
*
* @return https://(pod-domain.tld)/mobile/toggle
*/
@@ -183,7 +221,7 @@ public class DiasporaUrlHelper {
}
/**
- * Return a https url that queries posts for the given hashtag query
+ * Return a url that queries posts for the given hashtag query
*
* @param query hashtag to be searched
* @return https://(pod-domain.tld)/tags/query
@@ -193,7 +231,16 @@ public class DiasporaUrlHelper {
}
/**
- * Return a https url that queries user accounts for 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
*
* @param query search term
* @return https://(pod-domain.tld)/people.mobile?q=(query)
@@ -202,6 +249,85 @@ public class DiasporaUrlHelper {
return getPodUrl() + SUBURL_SEARCH_PEOPLE + query;
}
+ /**
+ * Return a url that points to the statistics page of the pod.
+ *
+ * @return https://(pod-domain.tld)/statistics
+ */
+ public String getStatisticsUrl() {
+ return getPodUrl() + SUBURL_STATISTICS;
+ }
+
+ /**
+ * Return an Url that points to the reports page of a the configured pod.
+ * Note: This url is only useful/visible for podmins and moderators.
+ *
+ * @return https://(pod-domain.tld)/reports
+ */
+ public String getReportsUrl() {
+ return getPodUrl() + SUBURL_REPORTS;
+ }
+
+ /**
+ * Return a url that points to the sign in page of the pod.
+ *
+ * @return https://(pod-domain.tld)/users/sign_in
+ */
+ public String getSignInUrl() {
+ return getPodUrl() + SUBURL_SIGN_IN;
+ }
+
+ /**
+ * Return a url that points to the personal settings page of the pod.
+ *
+ * @return https://(pod-domain.tld)/user/edit
+ */
+ public String getPersonalSettingsUrl() {
+ return getPodUrl() + SUBURL_PERSONAL_SETTINGS;
+ }
+
+ /**
+ * Return a url that points to the manage tags page of the pod.
+ *
+ * @return https://(pod-domain.tld)/tag_followings/manage
+ */
+ public String getManageTagsUrl() {
+ return getPodUrl() + SUBURL_MANAGE_TAGS;
+ }
+
+ /**
+ * Return a url that points to the manage tags page of the pod.
+ *
+ * @return https://(pod-domain.tld)/contacts
+ */
+ public String getContactsUrl() {
+ return getPodUrl() + SUBURL_CONTACTS;
+ }
+
+ public String getSuburlNotificationsAlsoCommentedUrl() {
+ return getPodUrl() + SUBURL_NOTIFICATIONS_ALSO_COMMENTED;
+ }
+
+ public String getSuburlNotificationsCommentOnPostUrl() {
+ return getPodUrl() + SUBURL_NOTIFICATIONS_COMMENT_ON_POST;
+ }
+
+ public String getSuburlNotificationsLikedUrl() {
+ return getPodUrl() + SUBURL_NOTIFICATIONS_LIKED;
+ }
+
+ public String getSuburlNotificationsMentionedUrl() {
+ return getPodUrl() + SUBURL_NOTIFICATIONS_MENTIONED;
+ }
+
+ public String getSuburlNotificationsResharedUrl() {
+ return getPodUrl() + SUBURL_NOTIFICATIONS_RESHARED;
+ }
+
+ public String getSuburlNotificationsStartedSharingUrl() {
+ return getPodUrl() + SUBURL_NOTIFICATIONS_STARTED_SHARING;
+ }
+
/**
* Returns the url of the blank WebView
*
@@ -219,7 +345,7 @@ public class DiasporaUrlHelper {
url = url.replace(getPodUrl() + "/aspects?a_ids[]=", "").split(",")[0];
try {
int id = Integer.parseInt(url);
- for (PodAspect aspect : app.getPodUserProfile().getAspects()) {
+ for (DiasporaAspect aspect : app.getDiasporaUserProfile().getAspects()) {
if (aspect.id == id) {
return aspect.name;
}
@@ -228,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;
+ }
}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/util/Helpers.java b/app/src/main/java/com/github/dfa/diaspora_android/util/Helpers.java
deleted file mode 100644
index a58abbc8..00000000
--- a/app/src/main/java/com/github/dfa/diaspora_android/util/Helpers.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- This file is part of the Diaspora for Android.
-
- Diaspora for Android 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.
-
- Diaspora for Android 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 Diaspora for Android.
-
- If not, see .
- */
-package com.github.dfa.diaspora_android.util;
-
-import android.app.Activity;
-import android.content.Context;
-import android.content.Intent;
-import android.net.Uri;
-
-import com.github.dfa.diaspora_android.R;
-
-public class Helpers {
-
- public static void animateToActivity(Activity from, Class to, boolean finishFromActivity) {
- Intent intent = new Intent(from, to);
- intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
- from.startActivity(intent);
- from.overridePendingTransition(R.anim.fadein, R.anim.fadeout);
- if (finishFromActivity) {
- from.finish();
- }
- }
-
- public static void loadUrlInExternalBrowser(Context context, String url) {
- try {
- Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
- context.startActivity(browserIntent);
- } catch (Exception ignored) {
- }
- }
-}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/web/BrowserFragment.java b/app/src/main/java/com/github/dfa/diaspora_android/web/BrowserFragment.java
new file mode 100644
index 00000000..bfc53fd9
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/web/BrowserFragment.java
@@ -0,0 +1,224 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.web;
+
+import android.content.Context;
+import android.content.MutableContextWrapper;
+import android.os.Bundle;
+import android.support.v4.widget.SwipeRefreshLayout;
+import android.view.View;
+import android.view.ViewGroup;
+import android.webkit.WebSettings;
+import android.webkit.WebView;
+import android.widget.ProgressBar;
+
+import com.github.dfa.diaspora_android.App;
+import com.github.dfa.diaspora_android.R;
+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;
+
+/**
+ * Fragment with a webView and a ProgressBar.
+ * This Fragment retains its instance.
+ * Created by vanitas on 26.09.16.
+ */
+
+public class BrowserFragment extends ThemedFragment {
+ public static final String TAG = "com.github.dfa.diaspora_android.BrowserFragment";
+
+ protected ContextMenuWebView webView;
+ protected ProgressBar progressBar;
+ protected AppSettings appSettings;
+ protected CustomWebViewClient webViewClient;
+ protected WebSettings webSettings;
+
+ protected String pendingUrl;
+ protected SwipeRefreshLayout swipe;//pull to refresh
+
+ @Override
+ protected int getLayoutResId() {
+ return R.layout.browser__fragment;
+ }
+
+
+ @Override
+ public void onViewCreated(View view, Bundle savedInstanceState) {
+ AppLog.d(this, "onViewCreated()");
+ super.onViewCreated(view, savedInstanceState);
+
+ if (this.appSettings == null) {
+ this.appSettings = ((App) getActivity().getApplication()).getSettings();
+ }
+
+ if (this.webView == null) {
+ this.webView = view.findViewById(R.id.webView);
+ getActivity().runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ BrowserFragment.this.applyWebViewSettings();
+ }
+ });
+
+ ProxyHandler.getInstance().addWebView(webView);
+ }
+
+ if (this.progressBar == null) {
+ this.progressBar = view.findViewById(R.id.progressBar);
+ }
+
+ if (pendingUrl != null) {
+ loadUrl(pendingUrl);
+ pendingUrl = null;
+ }
+
+ 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() && getView() != null && getView().getParent() instanceof ViewGroup) {
+ ((ViewGroup) getView().getParent()).removeView(getView());
+ }
+ }
+
+ private void applyWebViewSettings() {
+ this.webSettings = webView.getSettings();
+ webSettings.setAllowFileAccess(false);
+ webSettings.setUseWideViewPort(true);
+ webSettings.setLoadWithOverviewMode(true);
+ webSettings.setUserAgentString("Mozilla/5.0 (Linux; U; Android 4.4.4; Nexus 5 Build/KTU84P) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
+ webSettings.setDomStorageEnabled(true);
+ webSettings.setMinimumFontSize(appSettings.getMinimumFontSize());
+ webSettings.setLoadsImagesAutomatically(appSettings.isLoadImages());
+ webSettings.setAppCacheEnabled(true);
+
+ if (android.os.Build.VERSION.SDK_INT >= 21) {
+ WebView.enableSlowWholeDocumentDraw();
+ webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
+ }
+
+ this.registerForContextMenu(webView);
+ //webView.setParentActivity(this);
+ webView.setOverScrollMode(WebView.OVER_SCROLL_ALWAYS);
+
+ this.webViewClient = new CustomWebViewClient((App) getActivity().getApplication(), webView);
+ webView.setWebViewClient(webViewClient);
+ webView.setWebChromeClient(new ProgressBarWebChromeClient(webView, progressBar));
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ if (webView != null) {
+ webSettings.setMinimumFontSize(appSettings.getMinimumFontSize());
+ webSettings.setLoadsImagesAutomatically(appSettings.isLoadImages());
+ }
+ }
+
+ @Override
+ public String getFragmentTag() {
+ return TAG;
+ }
+
+ @Override
+ public void onAttach(Context context) {
+ super.onAttach(context);
+ if (webView != null && webView.getContext() instanceof MutableContextWrapper) {
+ ((MutableContextWrapper) webView.getContext()).setBaseContext(context);
+ }
+ }
+
+ public boolean onBackPressed() {
+ if (webView.canGoBack()) {
+ getActivity().runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ webView.goBack();
+ }
+ });
+ return true;
+ }
+ return false;
+ }
+
+ public void loadUrl(final String url) {
+ if (getWebView() != null) {
+ AppLog.v(this, "loadUrl(): load " + url);
+ getActivity().runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ getWebView().loadUrlNew(url);
+ }
+ });
+
+ } else {
+ AppLog.v(this, "loadUrl(): WebView null: Set pending url to " + url);
+ pendingUrl = url;
+ }
+ }
+
+ public String getUrl() {
+ if (getWebView() != null) {
+ return getWebView().getUrl();
+ } else {
+ return pendingUrl;
+ }
+ }
+
+ public void reloadUrl() {
+ AppLog.v(this, "reloadUrl()");
+ if (getWebView() != null) {
+ getActivity().runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ getWebView().reload();
+ swipe.setRefreshing(false);//pull to refresh
+ }
+ });
+
+ }
+ }
+
+ public ContextMenuWebView getWebView() {
+ return this.webView;
+ }
+
+ @Override
+ protected void applyColorToViews() {
+ ThemeHelper.updateProgressBarColor(progressBar);
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/web/ContextMenuWebView.java b/app/src/main/java/com/github/dfa/diaspora_android/web/ContextMenuWebView.java
new file mode 100644
index 00000000..e1194c9e
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/web/ContextMenuWebView.java
@@ -0,0 +1,187 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.web;
+
+import android.app.Activity;
+import android.content.ClipData;
+import android.content.ClipboardManager;
+import android.content.Context;
+import android.content.Intent;
+import android.net.Uri;
+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.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
+ * or open with another browser
+ */
+@SuppressWarnings("deprecation")
+public class ContextMenuWebView extends NestedWebView {
+
+ public static final int ID_SAVE_IMAGE = 10;
+ public static final int ID_IMAGE_EXTERNAL_BROWSER = 11;
+ public static final int ID_COPY_IMAGE_LINK = 15;
+ public static final int ID_COPY_LINK = 12;
+ public static final int ID_SHARE_LINK = 13;
+ public static final int ID_SHARE_IMAGE = 14;
+
+ private final Context context;
+ private Activity parentActivity;
+ private String lastLoadUrl = "";
+
+ public ContextMenuWebView(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+ this.context = context;
+ }
+
+ public ContextMenuWebView(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ this.context = context;
+ }
+
+ @Override
+ protected void onCreateContextMenu(ContextMenu menu) {
+ super.onCreateContextMenu(menu);
+
+ HitTestResult result = getHitTestResult();
+
+ MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
+ 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: {
+ 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);
+ 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 (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) {
+ Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
+ context.startActivity(intent);
+ }
+ break;
+
+ //Copy url to clipboard
+ case ID_COPY_IMAGE_LINK:
+ case ID_COPY_LINK:
+ if (url != null) {
+ ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
+ clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
+ Toast.makeText(context, R.string.link_adress_copied, Toast.LENGTH_SHORT).show();
+ }
+ break;
+
+ //Try to share link to other apps
+ case ID_SHARE_LINK:
+ if (url != null) {
+ Intent sendIntent = new Intent();
+ sendIntent.setAction(Intent.ACTION_SEND);
+ sendIntent.putExtra(Intent.EXTRA_TEXT, url);
+ sendIntent.setType("text/plain");
+ context.startActivity(Intent.createChooser(sendIntent, getResources()
+ .getText(R.string.share_link_address)));
+ }
+ break;
+ }
+ return true;
+ }
+ };
+
+ //Build context menu
+ if (result.getType() == HitTestResult.IMAGE_TYPE ||
+ 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.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.copy_link_adress_to_clipboard)).setOnMenuItemClickListener(handler);
+ menu.add(0, ID_SHARE_LINK, 0, context.getString(R.string.share_link_address)).setOnMenuItemClickListener(handler);
+ }
+ }
+
+ public void loadUrlNew(String url) {
+ stopLoading();
+ loadUrl(url);
+ }
+
+ @Override
+ public void loadUrl(String url) {
+ super.loadUrl(url);
+ WebHelper.sendUpdateTitleByUrlIntent(url, getContext());
+ }
+
+ public void setParentActivity(Activity activity) {
+ this.parentActivity = activity;
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/web/CustomWebViewClient.java b/app/src/main/java/com/github/dfa/diaspora_android/web/CustomWebViewClient.java
new file mode 100644
index 00000000..5e0011d8
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/web/CustomWebViewClient.java
@@ -0,0 +1,105 @@
+/*
+ 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 .
+ */
+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;
+import android.webkit.WebResourceResponse;
+import android.webkit.WebView;
+import android.webkit.WebViewClient;
+
+import com.github.dfa.diaspora_android.App;
+import com.github.dfa.diaspora_android.activity.MainActivity;
+import com.github.dfa.diaspora_android.data.DiasporaPodList;
+import com.github.dfa.diaspora_android.util.AppSettings;
+
+import net.gsantner.opoc.util.AdBlock;
+
+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;
+ isAdBlockEnabled = AppSettings.get().isAdBlockEnabled();
+ }
+
+ //Open non-diaspora links in customtab/external browser
+ public boolean shouldOverrideUrlLoading(WebView view, String url) {
+ DiasporaPodList.DiasporaPod pod = AppSettings.get().getPod();
+ String host = null;
+ if (pod != null && pod.getPodUrl() != null && pod.getPodUrl().getHost() != null) {
+ host = pod.getPodUrl().getHost();
+ }
+
+ if (url.startsWith("https://dia.so/")
+ || (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);
+ LocalBroadcastManager.getInstance(app.getApplicationContext()).sendBroadcast(i);
+ return true;
+ }
+ }
+
+ public void onPageFinished(WebView view, String url) {
+ super.onPageFinished(view, url);
+
+ final CookieManager cookieManager = app.getCookieManager();
+ String cookies = cookieManager.getCookie(url);
+ DiasporaPodList.DiasporaPod pod = AppSettings.get().getPod();
+
+ if (cookies != null) {
+ cookieManager.setCookie(url, cookies);
+ if (pod != null && pod.getPodUrl() != null) {
+ cookieManager.setCookie(pod.getPodUrl().getBaseUrl(), cookies);
+ cookieManager.setCookie(".dia.so", "pod=" + pod.getPodUrl().getHost());
+ }
+ for (String c : cookies.split(";")) {
+ //AppLog.d(this, "Cookie: " + c.split("=")[0] + " Value:" + c.split("=")[1]);
+ }
+ //new ProfileFetchTask(app).execute();
+ }
+ }
+
+
+ @SuppressWarnings("deprecation")
+ @TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
+ @Override
+ public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
+ if (isAdBlockEnabled && AdBlock.getInstance().isAdHost(url)) {
+ return AdBlock.createEmptyResponse();
+ }
+ return super.shouldInterceptRequest(view, url);
+ }
+
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/web/DiasporaStreamWebChromeClient.java b/app/src/main/java/com/github/dfa/diaspora_android/web/DiasporaStreamWebChromeClient.java
new file mode 100644
index 00000000..1dc21836
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/web/DiasporaStreamWebChromeClient.java
@@ -0,0 +1,82 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.web;
+
+import android.webkit.JsResult;
+import android.webkit.WebView;
+import android.widget.ProgressBar;
+
+import com.github.dfa.diaspora_android.R;
+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;
+
+/**
+ * WebChromeClient that handles sharing text to diaspora*
+ * Created by vanitas on 26.09.16.
+ */
+
+public class DiasporaStreamWebChromeClient extends FileUploadWebChromeClient {
+ protected SharedTextCallback sharedTextCallback;
+
+ public DiasporaStreamWebChromeClient(WebView webView, ProgressBar progressBar, FileUploadCallback fileUploadCallback, SharedTextCallback callback) {
+ super(webView, progressBar, fileUploadCallback);
+ this.sharedTextCallback = callback;
+ }
+
+ @Override
+ public void onProgressChanged(WebView wv, int progress) {
+ super.onProgressChanged(wv, progress);
+ WebHelper.optimizeMobileSiteLayout(wv);
+ WebHelper.sendUpdateTitleByUrlIntent(wv.getUrl(), wv.getContext());
+
+ if (progress > 0 && progress <= 85) {
+ WebHelper.getUserProfile(wv);
+ }
+
+ if (progress > 60) {
+ String textToBeShared = sharedTextCallback.getSharedText();
+ if (textToBeShared != null) {
+ AppLog.d(this, "Share text into webView");
+ WebHelper.shareTextIntoWebView(wv, textToBeShared);
+ }
+ }
+ }
+
+ @Override
+ public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
+ ThemedAlertDialogBuilder builder = new ThemedAlertDialogBuilder(view.getContext(), AppSettings.get());
+ builder.setTitle(view.getContext().getString(R.string.confirmation))
+ .setMessage(message)
+ .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;
+ }
+
+ public interface SharedTextCallback {
+ String getSharedText();
+
+ void setSharedText(String shared);
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/web/FileUploadWebChromeClient.java b/app/src/main/java/com/github/dfa/diaspora_android/web/FileUploadWebChromeClient.java
new file mode 100644
index 00000000..8197d6ff
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/web/FileUploadWebChromeClient.java
@@ -0,0 +1,55 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.web;
+
+import android.net.Uri;
+import android.webkit.ValueCallback;
+import android.webkit.WebView;
+import android.widget.ProgressBar;
+
+/**
+ * WebChromeClient that allows uploading images
+ * Created by vanitas on 26.09.16.
+ */
+
+public class FileUploadWebChromeClient extends ProgressBarWebChromeClient {
+ protected FileUploadCallback fileUploadCallback;
+
+ public FileUploadWebChromeClient(WebView webView, ProgressBar progressBar, FileUploadCallback fileUploadCallback) {
+ super(webView, progressBar);
+ this.fileUploadCallback = fileUploadCallback;
+ }
+
+ //For Android 4.1/4.2 only. DO NOT REMOVE!
+ @SuppressWarnings("unused")
+ protected void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
+ fileUploadCallback.legacyImageUpload(uploadMsg, acceptType, capture);
+ }
+
+ @Override
+ public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {
+ return fileUploadCallback.imageUpload(webView, filePathCallback, fileChooserParams);
+ }
+
+ public interface FileUploadCallback {
+ boolean imageUpload(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams);
+
+ void legacyImageUpload(ValueCallback uploadMsg, String acceptType, String capture);
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/ui/NestedWebView.java b/app/src/main/java/com/github/dfa/diaspora_android/web/NestedWebView.java
similarity index 97%
rename from app/src/main/java/com/github/dfa/diaspora_android/ui/NestedWebView.java
rename to app/src/main/java/com/github/dfa/diaspora_android/web/NestedWebView.java
index 4f59a339..2ee37f25 100644
--- a/app/src/main/java/com/github/dfa/diaspora_android/ui/NestedWebView.java
+++ b/app/src/main/java/com/github/dfa/diaspora_android/web/NestedWebView.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.github.dfa.diaspora_android.ui;
+package com.github.dfa.diaspora_android.web;
import android.content.Context;
import android.support.v4.view.MotionEventCompat;
@@ -89,6 +89,9 @@ public class NestedWebView extends WebView implements NestedScrollingChild {
stopNestedScroll();
break;
}
+ if (event != null) {
+ event.recycle();
+ }
return returnValue;
}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/web/ProgressBarWebChromeClient.java b/app/src/main/java/com/github/dfa/diaspora_android/web/ProgressBarWebChromeClient.java
new file mode 100644
index 00000000..f1f27931
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/web/ProgressBarWebChromeClient.java
@@ -0,0 +1,44 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.web;
+
+import android.view.View;
+import android.webkit.WebChromeClient;
+import android.webkit.WebView;
+import android.widget.ProgressBar;
+
+/**
+ * WebChromeClient that connects the ProgressBar and the WebView and updates the progress of the progressBar.
+ * Created by vanitas on 26.09.16.
+ */
+
+public class ProgressBarWebChromeClient extends WebChromeClient {
+ protected final ProgressBar progressBar;
+ protected final WebView webView;
+
+ public ProgressBarWebChromeClient(WebView webView, ProgressBar progressBar) {
+ this.webView = webView;
+ this.progressBar = progressBar;
+ }
+
+ public void onProgressChanged(WebView wv, int progress) {
+ progressBar.setProgress(progress);
+ progressBar.setVisibility(progress == 100 ? View.GONE : View.VISIBLE);
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/web/ProxyHandler.java b/app/src/main/java/com/github/dfa/diaspora_android/web/ProxyHandler.java
new file mode 100644
index 00000000..3b1f8d7b
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/web/ProxyHandler.java
@@ -0,0 +1,136 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.web;
+
+import android.content.Context;
+import android.os.StrictMode;
+import android.webkit.WebView;
+
+import com.github.dfa.diaspora_android.activity.MainActivity;
+import com.github.dfa.diaspora_android.util.AppLog;
+import com.github.dfa.diaspora_android.util.AppSettings;
+
+import java.util.ArrayList;
+
+import info.guardianproject.netcipher.NetCipher;
+import info.guardianproject.netcipher.webkit.WebkitProxy;
+
+/**
+ * Proxy Handler that applies proxy settings of the app to webviews etc.
+ * Created by vanitas on 10.10.16.
+ */
+
+public class ProxyHandler {
+ private static ProxyHandler instance;
+ private ArrayList webViews;
+
+
+ private ProxyHandler() {
+ /* Singleton, yo? */
+ this.webViews = new ArrayList<>();
+ }
+
+ public static ProxyHandler getInstance() {
+ if (instance == null) {
+ instance = new ProxyHandler();
+ }
+ return instance;
+ }
+
+ public void updateProxySettings(Context context) {
+ AppLog.d(this, "UpdateProxySettings()");
+ AppSettings appSettings = AppSettings.get();
+ StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
+ StrictMode.ThreadPolicy tmp = new StrictMode.ThreadPolicy.Builder().permitAll().build();
+ StrictMode.setThreadPolicy(tmp);
+ if (appSettings.isProxyHttpEnabled()) {
+ //Update NetCipher
+ NetCipher.setProxy(appSettings.getProxyHttpHost(), appSettings.getProxyHttpPort());
+ //Update webviews
+ for (WebView wv : webViews) {
+ if (wv != null) {
+ try {
+ WebkitProxy.setProxy(MainActivity.class.getName(), context.getApplicationContext(), wv, appSettings.getProxyHttpHost(), appSettings.getProxyHttpPort());
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ StrictMode.setThreadPolicy(old);
+ }
+
+ public void addWebView(WebView wv) {
+ AppLog.d(this, "AddWebView");
+ if (wv != null && !webViews.contains(wv)) {
+ webViews.add(wv);
+ updateWebViewProxySettings(wv, wv.getContext());
+ }
+ }
+
+ private void updateWebViewProxySettings(WebView wv, Context context) {
+ AppLog.d(this, "UpdateWebViewProxySettings()");
+ AppSettings appSettings = AppSettings.get();
+ StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
+ StrictMode.ThreadPolicy tmp = new StrictMode.ThreadPolicy.Builder().permitAll().build();
+ StrictMode.setThreadPolicy(tmp);
+ if (appSettings.isProxyHttpEnabled()) {
+ if (wv != null) {
+ try {
+ WebkitProxy.setProxy(MainActivity.class.getName(), context.getApplicationContext(), wv, appSettings.getProxyHttpHost(), appSettings.getProxyHttpPort());
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ StrictMode.setThreadPolicy(old);
+ }
+
+ public static class ProxySettings {
+ private final boolean enabled;
+ private final String host;
+ private final int port;
+
+ public ProxySettings(boolean enabled, String host, int port) {
+ this.enabled = enabled;
+ this.host = host;
+ this.port = port;
+ }
+
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ public String getHost() {
+ return host;
+ }
+
+ public int getPort() {
+ return port;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ return (other instanceof ProxySettings) &&
+ enabled == ((ProxySettings) other).isEnabled() &&
+ host.equals(((ProxySettings) other).getHost()) &&
+ port == ((ProxySettings) other).getPort();
+ }
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/util/WebHelper.java b/app/src/main/java/com/github/dfa/diaspora_android/web/WebHelper.java
similarity index 60%
rename from app/src/main/java/com/github/dfa/diaspora_android/util/WebHelper.java
rename to app/src/main/java/com/github/dfa/diaspora_android/web/WebHelper.java
index 691481be..49d10340 100644
--- a/app/src/main/java/com/github/dfa/diaspora_android/util/WebHelper.java
+++ b/app/src/main/java/com/github/dfa/diaspora_android/web/WebHelper.java
@@ -1,42 +1,37 @@
/*
- This file is part of the Diaspora for Android.
+ This file is part of the dandelion*.
- Diaspora for Android is free software: you can redistribute it and/or modify
+ 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.
- Diaspora for Android is distributed in the hope that it will be useful,
+ 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 Diaspora for Android.
+ along with the dandelion*.
If not, see .
*/
-
-package com.github.dfa.diaspora_android.util;
+
+package com.github.dfa.diaspora_android.web;
import android.content.Context;
+import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
+import android.support.v4.content.LocalBroadcastManager;
import android.text.Html;
import android.webkit.URLUtil;
import android.webkit.WebView;
-import com.github.dfa.diaspora_android.App;
-import com.github.dfa.diaspora_android.R;
-import com.github.dfa.diaspora_android.data.AppSettings;
-import com.github.dfa.diaspora_android.data.PodAspect;
-import com.github.dfa.diaspora_android.data.PodUserProfile;
-
-import java.util.Locale;
+import com.github.dfa.diaspora_android.activity.MainActivity;
/**
* Created by Gregor Santner on 07.08.16.
- * https://gsantner.github.io
*/
public class WebHelper {
@@ -46,14 +41,14 @@ public class WebHelper {
return ni != null && ni.isConnectedOrConnecting();
}
- public static String replaceUrlWithMarkdown(String url){
- if( url != null && URLUtil.isHttpUrl(url) || URLUtil.isHttpsUrl(url)){
+ public static String replaceUrlWithMarkdown(String url) {
+ if (url != null && URLUtil.isHttpUrl(url) || URLUtil.isHttpsUrl(url)) {
return "<" + url + ">";
}
return url;
}
- public static String escapeHtmlText(String text){
+ public static String escapeHtmlText(String text) {
text = Html.escapeHtml(text);
text = text.replace("\n", "
");
return text;
@@ -62,7 +57,7 @@ public class WebHelper {
public static void optimizeMobileSiteLayout(final WebView wv) {
wv.loadUrl("javascript: ( function() {" +
" if (document.documentElement == null || document.documentElement.style == null) { return; }" +
- " document.documentElement.style.paddingBottom = '260px';" +
+ " document.documentElement.style.paddingBottom = '50px';" +
" document.getElementById('main').style.paddingTop = '5px';" +
" if(document.getElementById('main_nav')) {" +
" document.getElementById('main_nav').parentNode.removeChild(" +
@@ -84,7 +79,7 @@ public class WebHelper {
" var links = followed_tags.nextElementSibling.children[0].children;" +
" var tags = [];" +
" for(var i = 0; i < links.length - 1; i++) {" + // the last element is "Manage followed tags" link
- " tags.push(links[i].innerText.substring(1));" +
+ " tags.push(links[i].innerText.replace('#',''));" +
" }" +
" gon.user[\"android_app.followed_tags\"] = tags;" +
" } catch(e) {}" +
@@ -95,7 +90,7 @@ public class WebHelper {
"})();");
}
- public static void shareTextIntoWebView(final WebView webView, String sharedText){
+ public static void shareTextIntoWebView(final WebView webView, String sharedText) {
sharedText = sharedText.replace("'", "'").replace("\"", """);
webView.loadUrl("javascript:(function() { " +
" document.documentElement.style.paddingBottom = '500px';" +
@@ -111,50 +106,20 @@ public class WebHelper {
"})();");
}
- public static void showAspectList(final WebView wv, final App app) {
- wv.stopLoading();
- PodUserProfile profile = app.getPodUserProfile();
- StringBuilder sb = new StringBuilder();
+ private static String lastUpdateTitleByUrl = "";
- sb.append("");
-
- // Content
- for (PodAspect aspect : profile.getAspects()) {
- sb.append("» ");
- sb.append(aspect.toHtmlLink(app));
- sb.append("");
+ public static synchronized void sendUpdateTitleByUrlIntent(String url, Context context) {
+ // Ignore javascript stuff
+ if (url != null && url.startsWith("javascript:")) {
+ return;
}
- // End
- sb.append("");
- wv.loadDataWithBaseURL(null, sb.toString(), "text/html", "UTF-16", null);
- }
-
- public static void showFollowedTagsList(final WebView wv, final App app) {
- wv.stopLoading();
- PodUserProfile profile = app.getPodUserProfile();
- StringBuilder sb = new StringBuilder();
-
- sb.append("");
-
- // Content
- AppSettings appSettings = app.getSettings();
- sb.append("» ");
- sb.append(String.format(Locale.getDefault(),
- "%s",
- appSettings.getPodDomain(), app.getString(R.string.all_tags)));
- sb.append("");
- for (String tag: profile.getFollowedTags()) {
- sb.append("» ");
- sb.append(String.format(Locale.getDefault(),
- "#%s",
- appSettings.getPodDomain(), tag, tag));
- sb.append("");
+ // Don't spam intents
+ if (lastUpdateTitleByUrl != null && !lastUpdateTitleByUrl.equals(url) && url != null) {
+ Intent updateActivityTitleIntent = new Intent(MainActivity.ACTION_UPDATE_TITLE_FROM_URL);
+ updateActivityTitleIntent.putExtra(MainActivity.EXTRA_URL, url);
+ LocalBroadcastManager.getInstance(context).sendBroadcast(updateActivityTitleIntent);
}
-
- // End
- sb.append("");
- wv.loadDataWithBaseURL(null, sb.toString(), "text/html", "UTF-16", null);
+ lastUpdateTitleByUrl = url;
}
-
}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/web/custom_tab/BrowserFallback.java b/app/src/main/java/com/github/dfa/diaspora_android/web/custom_tab/BrowserFallback.java
new file mode 100644
index 00000000..af10c11a
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/web/custom_tab/BrowserFallback.java
@@ -0,0 +1,36 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.web.custom_tab;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.net.Uri;
+
+/**
+ * Adapted from https://medium.com/ribot-labs/exploring-chrome-customs-tabs-on-android-ef427effe2f4
+ */
+
+public class BrowserFallback implements CustomTabActivityHelper.CustomTabFallback {
+ @Override
+ public void openUri(Activity activity, Uri uri) {
+ Intent intent = new Intent(Intent.ACTION_VIEW);
+ intent.setData(uri);
+ activity.startActivity(intent);
+ }
+}
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/web/custom_tab/CustomTabActivityHelper.java b/app/src/main/java/com/github/dfa/diaspora_android/web/custom_tab/CustomTabActivityHelper.java
new file mode 100644
index 00000000..fce06062
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/web/custom_tab/CustomTabActivityHelper.java
@@ -0,0 +1,172 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.web.custom_tab;
+
+import android.app.Activity;
+import android.content.ComponentName;
+import android.net.Uri;
+import android.os.Bundle;
+import android.support.customtabs.CustomTabsClient;
+import android.support.customtabs.CustomTabsIntent;
+import android.support.customtabs.CustomTabsServiceConnection;
+import android.support.customtabs.CustomTabsSession;
+
+import java.util.List;
+
+/**
+ * Adapted from https://medium.com/ribot-labs/exploring-chrome-customs-tabs-on-android-ef427effe2f4
+ */
+
+public class CustomTabActivityHelper {
+ private CustomTabsSession mCustomTabsSession;
+ private CustomTabsClient mClient;
+ private CustomTabsServiceConnection mConnection;
+ private ConnectionCallback mConnectionCallback;
+
+ /**
+ * Opens the URL on a Custom Tab if possible. Otherwise fallsback to opening it on a WebView
+ *
+ * @param activity The host activity
+ * @param customTabsIntent a CustomTabsIntent to be used if Custom Tabs is available
+ * @param uri the Uri to be opened
+ * @param fallback a CustomTabFallback to be used if Custom Tabs is not available
+ */
+ public static void openCustomTab(Activity activity,
+ CustomTabsIntent customTabsIntent,
+ Uri uri,
+ CustomTabFallback fallback) {
+ String packageName = CustomTabsHelper.getPackageNameToUse(activity);
+
+ //If we cant find a package name, it means there's no browser that supports
+ //Chrome Custom Tabs installed. So, we fallback to the ui__webview
+ if (packageName == null) {
+ if (fallback != null) {
+ fallback.openUri(activity, uri);
+ }
+ } else {
+ customTabsIntent.intent.setPackage(packageName);
+ customTabsIntent.launchUrl(activity, uri);
+ }
+ }
+
+ /**
+ * Unbinds the Activity from the Custom Tabs Service
+ *
+ * @param activity the activity that is connected to the service
+ */
+ public void unbindCustomTabsService(Activity activity) {
+ if (mConnection == null) return;
+ activity.unbindService(mConnection);
+ mClient = null;
+ mCustomTabsSession = null;
+ }
+
+ /**
+ * Creates or retrieves an exiting CustomTabsSession
+ *
+ * @return a CustomTabsSession
+ */
+ public CustomTabsSession getSession() {
+ if (mClient == null) {
+ mCustomTabsSession = null;
+ } else if (mCustomTabsSession == null) {
+ mCustomTabsSession = mClient.newSession(null);
+ }
+ return mCustomTabsSession;
+ }
+
+ /**
+ * Register a Callback to be called when connected or disconnected from the Custom Tabs Service
+ *
+ * @param connectionCallback callback
+ */
+ public void setConnectionCallback(ConnectionCallback connectionCallback) {
+ this.mConnectionCallback = connectionCallback;
+ }
+
+ /**
+ * Binds the Activity to the Custom Tabs Service
+ *
+ * @param activity the activity to be binded to the service
+ */
+ public void bindCustomTabsService(Activity activity) {
+ if (mClient != null) return;
+
+ String packageName = CustomTabsHelper.getPackageNameToUse(activity);
+ if (packageName == null) return;
+ mConnection = new CustomTabsServiceConnection() {
+ @Override
+ public void onCustomTabsServiceConnected(ComponentName name, CustomTabsClient client) {
+ mClient = client;
+ mClient.warmup(0L);
+ if (mConnectionCallback != null) mConnectionCallback.onCustomTabsConnected();
+ //Initialize a session as soon as possible.
+ getSession();
+ }
+
+ @Override
+ public void onServiceDisconnected(ComponentName name) {
+ mClient = null;
+ if (mConnectionCallback != null) mConnectionCallback.onCustomTabsDisconnected();
+ }
+ };
+ CustomTabsClient.bindCustomTabsService(activity, packageName, mConnection);
+ }
+
+ public boolean mayLaunchUrl(Uri uri, Bundle extras, List otherLikelyBundles) {
+ if (mClient == null) return false;
+
+ CustomTabsSession session = getSession();
+ if (session == null) return false;
+
+ return session.mayLaunchUrl(uri, extras, otherLikelyBundles);
+ }
+
+ public boolean warmup(int flags) {
+ return mClient.warmup(flags);
+ }
+
+ /**
+ * A Callback for when the service is connected or disconnected. Use those callbacks to
+ * handle UI changes when the service is connected or disconnected
+ */
+ public interface ConnectionCallback {
+ /**
+ * Called when the service is connected
+ */
+ void onCustomTabsConnected();
+
+ /**
+ * Called when the service is disconnected
+ */
+ void onCustomTabsDisconnected();
+ }
+
+ /**
+ * To be used as a fallback to open the Uri when Custom Tabs is not available
+ */
+ public interface CustomTabFallback {
+ /**
+ * @param activity The Activity that wants to open the Uri
+ * @param uri The uri to be opened by the fallback
+ */
+ void openUri(Activity activity, Uri uri);
+ }
+
+}
\ No newline at end of file
diff --git a/app/src/main/java/com/github/dfa/diaspora_android/web/custom_tab/CustomTabsHelper.java b/app/src/main/java/com/github/dfa/diaspora_android/web/custom_tab/CustomTabsHelper.java
new file mode 100644
index 00000000..aaa89f06
--- /dev/null
+++ b/app/src/main/java/com/github/dfa/diaspora_android/web/custom_tab/CustomTabsHelper.java
@@ -0,0 +1,151 @@
+/*
+ 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 .
+ */
+package com.github.dfa.diaspora_android.web.custom_tab;
+
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.net.Uri;
+import android.support.customtabs.CustomTabsService;
+import android.text.TextUtils;
+
+import com.github.dfa.diaspora_android.util.AppLog;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Helper class for Custom Tabs. Adapted from https://medium.com/ribot-labs/exploring-chrome-customs-tabs-on-android-ef427effe2f4
+ */
+public class CustomTabsHelper {
+ private static final String TAG = "CustomTabsHelper";
+ static final String STABLE_PACKAGE = "com.android.chrome";
+ 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";
+
+ private static String sPackageNameToUse;
+
+ private CustomTabsHelper() {
+ }
+
+ /**
+ * Goes through all apps that handle VIEW intents and have a warmup service. Picks
+ * the one chosen by the user if there is one, otherwise makes a best effort to return a
+ * valid package name.
+ *
+ * This is not threadsafe.
+ *
+ * @param context {@link Context} to use for accessing {@link PackageManager}.
+ * @return The package name recommended to use for connecting to custom tabs related components.
+ */
+ public static String getPackageNameToUse(Context context) {
+ if (sPackageNameToUse != null) return sPackageNameToUse;
+
+ PackageManager pm = context.getPackageManager();
+ // Get default VIEW intent handler.
+ Intent activityIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));
+ ResolveInfo defaultViewHandlerInfo = pm.resolveActivity(activityIntent, 0);
+ String defaultViewHandlerPackageName = null;
+ if (defaultViewHandlerInfo != null) {
+ defaultViewHandlerPackageName = defaultViewHandlerInfo.activityInfo.packageName;
+ }
+
+ // Get all apps that can handle VIEW intents.
+ List resolvedActivityList = pm.queryIntentActivities(activityIntent, 0);
+ List packagesSupportingCustomTabs = new ArrayList<>();
+ for (ResolveInfo info : resolvedActivityList) {
+ Intent serviceIntent = new Intent();
+ serviceIntent.setAction(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION);
+ serviceIntent.setPackage(info.activityInfo.packageName);
+ if (pm.resolveService(serviceIntent, 0) != null) {
+ packagesSupportingCustomTabs.add(info.activityInfo.packageName);
+ }
+ }
+
+ // Now packagesSupportingCustomTabs contains all apps that can handle both VIEW intents
+ // and service calls.
+ if (packagesSupportingCustomTabs.isEmpty()) {
+ sPackageNameToUse = null;
+ } else if (packagesSupportingCustomTabs.size() == 1) {
+ sPackageNameToUse = packagesSupportingCustomTabs.get(0);
+ } else if (!TextUtils.isEmpty(defaultViewHandlerPackageName)
+ && !hasSpecializedHandlerIntents(context, activityIntent)
+ && packagesSupportingCustomTabs.contains(defaultViewHandlerPackageName)) {
+ sPackageNameToUse = defaultViewHandlerPackageName;
+ } else if (packagesSupportingCustomTabs.contains(STABLE_PACKAGE)) {
+ sPackageNameToUse = STABLE_PACKAGE;
+ } else if (packagesSupportingCustomTabs.contains(BETA_PACKAGE)) {
+ sPackageNameToUse = BETA_PACKAGE;
+ } else if (packagesSupportingCustomTabs.contains(DEV_PACKAGE)) {
+ 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;
+ }
+
+ /**
+ * Used to check whether there is a specialized handler for a given intent.
+ *
+ * @param intent The intent to check with.
+ * @return Whether there is a specialized handler for the given intent.
+ */
+ private static boolean hasSpecializedHandlerIntents(Context context, Intent intent) {
+ try {
+ PackageManager pm = context.getPackageManager();
+ List handlers = pm.queryIntentActivities(
+ intent,
+ PackageManager.GET_RESOLVED_FILTER);
+ if (handlers == null || handlers.size() == 0) {
+ return false;
+ }
+ for (ResolveInfo resolveInfo : handlers) {
+ IntentFilter filter = resolveInfo.filter;
+ if (filter == null) continue;
+ if (filter.countDataAuthorities() == 0 || filter.countDataPaths() == 0) continue;
+ if (resolveInfo.activityInfo == null) continue;
+ return true;
+ }
+ } catch (RuntimeException e) {
+ AppLog.e(TAG, "Runtime exception while getting specialized handlers");
+ }
+ return false;
+ }
+
+ /**
+ * @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, CHROMIUM, FENNEC, KLAR};
+ }
+}
diff --git a/app/src/main/java/net/gsantner/opoc/activity/GsFragmentBase.java b/app/src/main/java/net/gsantner/opoc/activity/GsFragmentBase.java
new file mode 100644
index 00000000..479551d9
--- /dev/null
+++ b/app/src/main/java/net/gsantner/opoc/activity/GsFragmentBase.java
@@ -0,0 +1,160 @@
+/*#######################################################
+ *
+ * Maintained 2017-2023 by Gregor Santner
+ *
+ * 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;
+ }
+ }
+}
diff --git a/app/src/main/java/net/gsantner/opoc/android/dummy/MenuItemDummy.java b/app/src/main/java/net/gsantner/opoc/android/dummy/MenuItemDummy.java
new file mode 100644
index 00000000..5d3b5f97
--- /dev/null
+++ b/app/src/main/java/net/gsantner/opoc/android/dummy/MenuItemDummy.java
@@ -0,0 +1,351 @@
+/*
+ * Maintained 2017-2023 by Gregor Santner
+ * 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) {
+ }
+ }
+}
diff --git a/app/src/main/java/net/gsantner/opoc/android/dummy/TextWatcherDummy.java b/app/src/main/java/net/gsantner/opoc/android/dummy/TextWatcherDummy.java
new file mode 100644
index 00000000..e6a5ea94
--- /dev/null
+++ b/app/src/main/java/net/gsantner/opoc/android/dummy/TextWatcherDummy.java
@@ -0,0 +1,58 @@
+/*
+ * Maintained 2017-2023 by Gregor Santner
+ * 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 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 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 impl) {
+ return new TextWatcherDummy() {
+ public void afterTextChanged(final Editable s) {
+ impl.callback(s);
+ }
+ };
+ }
+}
diff --git a/app/src/main/java/net/gsantner/opoc/format/markdown/SimpleMarkdownParser.java b/app/src/main/java/net/gsantner/opoc/format/markdown/SimpleMarkdownParser.java
new file mode 100644
index 00000000..ea117a8a
--- /dev/null
+++ b/app/src/main/java/net/gsantner/opoc/format/markdown/SimpleMarkdownParser.java
@@ -0,0 +1,248 @@
+/*#######################################################
+ *
+ * Maintained 2018-2023 by Gregor Santner
+ *
+ * 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.
+ *
+ * You can e.g. apply a accent color by replacing #000001 with your accentColor string.
+ *
+ * FILTER_ANDROID_TEXTVIEW output is intended to be used at simple Android TextViews,
+ * were a limited set of _html tags is supported. This allow to still display e.g. a simple
+ * CHANGELOG.md file without including a WebView for showing HTML, or other additional UI-libraries.
+ *
+ * FILTER_WEB is intended to be used at engines understanding most common HTML tags.
+ */
+
+package net.gsantner.opoc.format.markdown;
+
+import java.io.BufferedReader;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+/**
+ * Simple Markdown Parser
+ */
+@SuppressWarnings({"WeakerAccess", "CaughtExceptionImmediatelyRethrown", "SameParameterValue", "unused", "SpellCheckingInspection", "RepeatedSpace", "SingleCharAlternation", "Convert2Lambda"})
+public class SimpleMarkdownParser {
+ //########################
+ //## Statics
+ //########################
+ public interface SmpFilter {
+ String filter(String text);
+ }
+
+ public final static SmpFilter FILTER_ANDROID_TEXTVIEW = new SmpFilter() {
+ @Override
+ public String filter(String text) {
+ // TextView supports a limited set of html tags, most notably
+ // a href, b, big, font size&color, i, li, small, u
+
+ // Don't start new line if 2 empty lines and heading
+ while (text.contains("\n\n#")) {
+ text = text.replace("\n\n#", "\n#");
+ }
+
+ return text
+ .replaceAll("(?s)", "") // HTML comments
+ .replace("\n\n", "\n \n") // Start new line if 2 empty lines
+ .replace("~°", " ") // double space/half tab
+ .replaceAll("(?m)^### (.*)$", " $1 ") // h3
+ .replaceAll("(?m)^## (.*)$", " $1