From bdd502174d936129da00f7a1813a74cabaa92c89 Mon Sep 17 00:00:00 2001 From: Gregor Santner Date: Tue, 8 Aug 2017 14:02:20 +0200 Subject: [PATCH 001/181] Update README.md IRC Channel link badge --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 512a5f30..efa50121 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,11 @@ [![CircleCI](https://circleci.com/gh/Diaspora-for-Android/dandelion.svg?style=shield)](https://circleci.com/gh/Diaspora-for-Android/dandelion) [![Crowdin](https://d322cqt584bo4o.cloudfront.net/diaspora-for-android/localized.svg)](https://crowdin.com/project/diaspora-for-android) -[![Chat - Matrix](https://img.shields.io/badge/chat-on%20matrix-blue.svg)](https://matrix.to/#/#dandelion:matrix.org) +[![Chat - Matrix](https://img.shields.io/badge/chat-on%20matrix-blue.svg)](https://matrix.to/#/#dandelion:matrix.org) [![Chat - FreeNode IRC](https://img.shields.io/badge/chat-on%20irc-blue.svg)](https://kiwiirc.com/client/irc.freenode.net/?nick=dandelion-anon|?##dandelion) # dandelion\* -FORMERLY KNOWN AS DIASPORA-FOR-ANDROID This is an unofficial webview based client for the community-run, distributed social network **[diaspora*](https://diasporafoundation.org/)**. It's currently under development and should be used with that in mind. Please submit any bugs you might find. @@ -30,7 +29,7 @@ dandelion\* is released under GNU GENERAL PUBLIC LICENSE (see [LICENCE](https:// The translations (strings.xml) are licensed CC0 1.0. ### WebApp -The app is developed as a 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. +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. Why is a WebApp better than using the mobile site on a browser? From 92bd98ea28aea56ec70af6a44dd933e8d87d3020 Mon Sep 17 00:00:00 2001 From: Gregor Santner Date: Wed, 9 Aug 2017 17:23:19 +0200 Subject: [PATCH 002/181] Update opoc --- CHANGELOG.md | 3 + .../activity/MainActivity.java | 2 +- .../activity/PodSelectionFragment.java | 5 +- .../diaspora_android/util/AppSettings.java | 110 +++++------ .../dfa/diaspora_android/util/Helpers.java | 20 -- .../dfa/diaspora_android/util/HelpersA.java | 73 ++++++++ .../gsantner/opoc/util/AppSettingsBase.java | 172 +++++++++--------- .../io/github/gsantner/opoc/util/Helpers.java | 152 +++++++++++----- .../github/gsantner/opoc/util/HelpersA.java | 57 +++--- .../opoc/util/SimpleMarkdownParser.java | 63 ++++--- 10 files changed, 396 insertions(+), 261 deletions(-) create mode 100644 app/src/main/java/com/github/dfa/diaspora_android/util/HelpersA.java diff --git a/CHANGELOG.md b/CHANGELOG.md index bfa06b3e..0ed4efff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +### v1.0.3 +- Update opoc + ### v1.0.2 (2017-08-05) - Improve build script - Update translation file license diff --git a/app/src/main/java/com/github/dfa/diaspora_android/activity/MainActivity.java b/app/src/main/java/com/github/dfa/diaspora_android/activity/MainActivity.java index 55801b63..9f4574e4 100644 --- a/app/src/main/java/com/github/dfa/diaspora_android/activity/MainActivity.java +++ b/app/src/main/java/com/github/dfa/diaspora_android/activity/MainActivity.java @@ -89,8 +89,8 @@ import java.io.IOException; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; -import io.github.gsantner.opoc.util.HelpersA; import io.github.gsantner.opoc.util.SimpleMarkdownParser; +import com.github.dfa.diaspora_android.util.HelpersA; public class MainActivity extends ThemedActivity implements NavigationView.OnNavigationItemSelectedListener, 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 index ab102b61..6060db0e 100644 --- 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 @@ -56,6 +56,7 @@ 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.util.Helpers; +import com.github.dfa.diaspora_android.util.HelpersA; import org.json.JSONException; import org.json.JSONObject; @@ -128,7 +129,7 @@ public class PodSelectionFragment extends ThemedFragment implements SearchView.O } }); LocalBroadcastManager.getInstance(getContext()).registerReceiver(podListReceiver, new IntentFilter(FetchPodsService.MESSAGE_PODS_RECEIVED)); - Helpers.get().showInfoIfUserNotConnectedToInternet(getActivity(), listViewPod); + HelpersA.get(getActivity()).showInfoIfUserNotConnectedToInternet(listViewPod); } public void mergePodlistWithRessources(DiasporaPodList podlist) { @@ -244,7 +245,7 @@ public class PodSelectionFragment extends ThemedFragment implements SearchView.O public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_reload: { - if (!Helpers.get().showInfoIfUserNotConnectedToInternet(getActivity(), listViewPod)) { + if (!HelpersA.get(getActivity()).showInfoIfUserNotConnectedToInternet(listViewPod)) { Intent i = new Intent(getContext(), FetchPodsService.class); getContext().startService(i); return true; 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 index b5bb3e19..2a9812a2 100644 --- 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 @@ -48,7 +48,7 @@ public class AppSettings extends AppSettingsBase { private AppSettings(Context context) { super(context); - prefPod = this.context.getSharedPreferences("pod0", Context.MODE_PRIVATE); + prefPod = _context.getSharedPreferences("pod0", Context.MODE_PRIVATE); } /** @@ -63,14 +63,14 @@ public class AppSettings extends AppSettingsBase { } /** - * Clear all settings in prefApp (related to the App itself) + * 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); + super.resetSettings(_prefApp); } //################################# @@ -85,11 +85,11 @@ public class AppSettings extends AppSettingsBase { } public boolean isLoadImages() { - return getBool(prefApp, R.string.pref_key__load_images, true); + return getBool(_prefApp, R.string.pref_key__load_images, true); } public int getMinimumFontSize() { - switch (getString(prefApp, R.string.pref_key__font_size, "")) { + switch (getString(_prefApp, R.string.pref_key__font_size, "")) { case "huge": return 20; case "large": @@ -97,7 +97,7 @@ public class AppSettings extends AppSettingsBase { case "normal": return 8; default: - setString(prefApp, R.string.pref_key__font_size, "normal"); + setString(_prefApp, R.string.pref_key__font_size, "normal"); return 8; } } @@ -198,13 +198,13 @@ public class AppSettings extends AppSettingsBase { } public boolean isAppendSharedViaApp() { - return getBool(prefApp, R.string.pref_key__append_shared_via_app, true); + return getBool(_prefApp, 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(context.getString(R.string.pref_key__http_proxy_enabled), enabled).commit(); + _prefApp.edit().putBoolean(rstr(R.string.pref_key__http_proxy_enabled), enabled).commit(); } /** @@ -214,7 +214,7 @@ public class AppSettings extends AppSettingsBase { */ public boolean isProxyHttpEnabled() { try { - return getBool(prefApp, R.string.pref_key__http_proxy_enabled, false); + return getBool(_prefApp, R.string.pref_key__http_proxy_enabled, false); } catch (ClassCastException e) { setProxyHttpEnabled(false); return false; @@ -222,7 +222,7 @@ public class AppSettings extends AppSettingsBase { } public boolean wasProxyEnabled() { - return getBool(prefApp, R.string.pref_key__proxy_was_enabled, false); + return getBool(_prefApp, R.string.pref_key__proxy_was_enabled, false); } /** @@ -233,7 +233,7 @@ public class AppSettings extends AppSettingsBase { */ @SuppressLint("CommitPrefEdits") public void setProxyWasEnabled(boolean b) { - prefApp.edit().putBoolean(context.getString(R.string.pref_key__proxy_was_enabled), b).commit(); + _prefApp.edit().putBoolean(rstr(R.string.pref_key__proxy_was_enabled), b).commit(); } /** @@ -242,11 +242,11 @@ public class AppSettings extends AppSettingsBase { * @return proxy host */ public String getProxyHttpHost() { - return getString(prefApp, R.string.pref_key__http_proxy_host, ""); + return getString(_prefApp, R.string.pref_key__http_proxy_host, ""); } public void setProxyHttpHost(String value) { - setString(prefApp, R.string.pref_key__http_proxy_host, value); + setString(_prefApp, R.string.pref_key__http_proxy_host, value); } /** @@ -256,17 +256,17 @@ public class AppSettings extends AppSettingsBase { */ public int getProxyHttpPort() { try { - String str = getString(prefApp, R.string.pref_key__http_proxy_port, "0"); + String str = getString(_prefApp, R.string.pref_key__http_proxy_port, "0"); return Integer.parseInt(str); } catch (ClassCastException e) { - int port = getInt(prefApp, R.string.pref_key__http_proxy_port, 0); + int port = getInt(_prefApp, R.string.pref_key__http_proxy_port, 0); setProxyHttpPort(port); return port; } } public void setProxyHttpPort(int value) { - setString(prefApp, R.string.pref_key__http_proxy_port, Integer.toString(value)); + setString(_prefApp, R.string.pref_key__http_proxy_port, Integer.toString(value)); } public ProxyHandler.ProxySettings getProxySettings() { @@ -274,94 +274,94 @@ public class AppSettings extends AppSettingsBase { } public boolean isIntellihideToolbars() { - return getBool(prefApp, R.string.pref_key__intellihide_toolbars, true); + return getBool(_prefApp, R.string.pref_key__intellihide_toolbars, true); } public boolean isChromeCustomTabsEnabled() { - return getBool(prefApp, R.string.pref_key__chrome_custom_tabs_enabled, true); + return getBool(_prefApp, R.string.pref_key__chrome_custom_tabs_enabled, true); } public boolean isLoggingEnabled() { - return getBool(prefApp, R.string.pref_key__logging_enabled, false); + return getBool(_prefApp, R.string.pref_key__logging_enabled, false); } public boolean isLoggingSpamEnabled() { - return getBool(prefApp, R.string.pref_key__logging_spam_enabled, false); + return getBool(_prefApp, R.string.pref_key__logging_spam_enabled, false); } public boolean isVisibleInNavExit() { - return getBool(prefApp, R.string.pref_key__visibility_nav__exit, true); + return getBool(_prefApp, R.string.pref_key__visibility_nav__exit, true); } public boolean isVisibleInNavHelp_license() { - return getBool(prefApp, R.string.pref_key__visibility_nav__help_license, true); + return getBool(_prefApp, R.string.pref_key__visibility_nav__help_license, true); } public boolean isVisibleInNavPublic_activities() { - return getBool(prefApp, R.string.pref_key__visibility_nav__public_activities, false); + return getBool(_prefApp, R.string.pref_key__visibility_nav__public_activities, false); } public boolean isVisibleInNavMentions() { - return getBool(prefApp, R.string.pref_key__visibility_nav__mentions, false); + return getBool(_prefApp, R.string.pref_key__visibility_nav__mentions, false); } public boolean isVisibleInNavCommented() { - return getBool(prefApp, R.string.pref_key__visibility_nav__commented, true); + return getBool(_prefApp, R.string.pref_key__visibility_nav__commented, true); } public boolean isVisibleInNavLiked() { - return getBool(prefApp, R.string.pref_key__visibility_nav__liked, true); + return getBool(_prefApp, R.string.pref_key__visibility_nav__liked, true); } public boolean isVisibleInNavActivities() { - return getBool(prefApp, R.string.pref_key__visibility_nav__activities, true); + return getBool(_prefApp, R.string.pref_key__visibility_nav__activities, true); } public boolean isVisibleInNavAspects() { - return getBool(prefApp, R.string.pref_key__visibility_nav__aspects, true); + return getBool(_prefApp, R.string.pref_key__visibility_nav__aspects, true); } public boolean isVisibleInNavFollowed_tags() { - return getBool(prefApp, R.string.pref_key__visibility_nav__followed_tags, true); + return getBool(_prefApp, R.string.pref_key__visibility_nav__followed_tags, true); } public boolean isVisibleInNavProfile() { - return getBool(prefApp, R.string.pref_key__visibility_nav__profile, true); + return getBool(_prefApp, R.string.pref_key__visibility_nav__profile, true); } public boolean isVisibleInNavContacts() { - return getBool(prefApp, R.string.pref_key__visibility_nav__contacts, false); + return getBool(_prefApp, R.string.pref_key__visibility_nav__contacts, false); } public boolean isVisibleInNavStatistics() { - return getBool(prefApp, R.string.pref_key__visibility_nav__statistics, false); + return getBool(_prefApp, R.string.pref_key__visibility_nav__statistics, false); } public boolean isVisibleInNavReports() { - return getBool(prefApp, R.string.pref_key__visibility_nav__reports, false); + return getBool(_prefApp, R.string.pref_key__visibility_nav__reports, false); } public boolean isVisibleToggleMobileDesktop() { - return getBool(prefApp, R.string.pref_key__visibility_nav__toggle_mobile_desktop, false); + return getBool(_prefApp, R.string.pref_key__visibility_nav__toggle_mobile_desktop, false); } public boolean isTopbarStreamShortcutEnabled() { - return getBool(prefApp, R.string.pref_key__topbar_stream_shortcut, false); + return getBool(_prefApp, R.string.pref_key__topbar_stream_shortcut, false); } public String getScreenRotation() { - return getString(prefApp, R.string.pref_key__screen_rotation, R.string.rotation_val_system); + return getString(_prefApp, R.string.pref_key__screen_rotation, R.string.rotation_val_system); } public boolean isAppFirstStart() { - boolean value = getBool(prefApp, R.string.pref_key__app_first_start, true); - setBool(prefApp, R.string.pref_key__app_first_start, false); + boolean value = getBool(_prefApp, R.string.pref_key__app_first_start, true); + setBool(_prefApp, R.string.pref_key__app_first_start, false); return value; } public boolean isAppCurrentVersionFirstStart() { - int value = getInt(prefApp, R.string.pref_key__app_first_start_current_version, -1); - setInt(prefApp, R.string.pref_key__app_first_start_current_version, BuildConfig.VERSION_CODE); + int value = getInt(_prefApp, R.string.pref_key__app_first_start_current_version, -1); + setInt(_prefApp, R.string.pref_key__app_first_start_current_version, BuildConfig.VERSION_CODE); return value != BuildConfig.VERSION_CODE && !BuildConfig.IS_TEST_BUILD; } @@ -374,22 +374,22 @@ public class AppSettings extends AppSettingsBase { } public void setLanguage(String value) { - setString(prefApp, R.string.pref_key__language, value); + setString(_prefApp, R.string.pref_key__language, value); } public String getLanguage() { - return getString(prefApp, R.string.pref_key__language, ""); + return getString(_prefApp, R.string.pref_key__language, ""); } public void setPrimaryColorSettings(int base, int shade) { - setInt(prefApp, R.string.pref_key__primary_color_base, base); - setInt(prefApp, R.string.pref_key__primary_color_shade, shade); + setInt(_prefApp, R.string.pref_key__primary_color_base, base); + setInt(_prefApp, R.string.pref_key__primary_color_shade, shade); } public int[] getPrimaryColorSettings() { return new int[]{ - getInt(prefApp, R.string.pref_key__primary_color_base, rcolor(R.color.md_blue_650)), - getInt(prefApp, R.string.pref_key__primary_color_shade, rcolor(R.color.primary)) + getInt(_prefApp, R.string.pref_key__primary_color_base, rcolor(R.color.md_blue_650)), + getInt(_prefApp, R.string.pref_key__primary_color_shade, rcolor(R.color.primary)) }; } @@ -398,36 +398,36 @@ public class AppSettings extends AppSettingsBase { if (isAmoledColorMode()) { return Color.BLACK; } else { - return getInt(prefApp, R.string.pref_key__primary_color_shade, rcolor( + return getInt(_prefApp, 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(prefApp, R.string.pref_key__accent_color_base, base); - setInt(prefApp, R.string.pref_key__accent_color_shade, shade); + setInt(_prefApp, R.string.pref_key__accent_color_base, base); + setInt(_prefApp, R.string.pref_key__accent_color_shade, shade); } public int[] getAccentColorSettings() { return new int[]{ - getInt(prefApp, R.string.pref_key__accent_color_base, rcolor(R.color.md_green_400)), - getInt(prefApp, R.string.pref_key__accent_color_shade, rcolor(R.color.accent)) + getInt(_prefApp, R.string.pref_key__accent_color_base, rcolor(R.color.md_green_400)), + getInt(_prefApp, R.string.pref_key__accent_color_shade, rcolor(R.color.accent)) }; } public int getAccentColor() { - return getInt(prefApp, R.string.pref_key__accent_color_shade, rcolor(R.color.accent)); + return getInt(_prefApp, R.string.pref_key__accent_color_shade, rcolor(R.color.accent)); } public boolean isExtendedNotificationsActivated() { - return getBool(prefApp, R.string.pref_key__extended_notifications, false); + return getBool(_prefApp, R.string.pref_key__extended_notifications, false); } public boolean isAmoledColorMode() { - return getBool(prefApp, R.string.pref_key__primary_color__amoled_mode, false); + return getBool(_prefApp, R.string.pref_key__primary_color__amoled_mode, false); } public boolean isAdBlockEnabled() { - return getBool(prefApp, R.string.pref_key__adblock_enable, true); + return getBool(_prefApp, R.string.pref_key__adblock_enable, true); } } 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 index e98befde..9f175f5f 100644 --- 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 @@ -1,14 +1,10 @@ package com.github.dfa.diaspora_android.util; -import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Environment; -import android.view.View; import com.github.dfa.diaspora_android.App; -import com.github.dfa.diaspora_android.R; -import com.github.dfa.diaspora_android.web.WebHelper; import java.io.File; import java.io.IOException; @@ -17,8 +13,6 @@ import java.util.Arrays; import java.util.Date; import java.util.Locale; -import io.github.gsantner.opoc.util.HelpersA; - @SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue"}) public class Helpers extends io.github.gsantner.opoc.util.Helpers { protected Helpers(Context context) { @@ -44,20 +38,6 @@ public class Helpers extends io.github.gsantner.opoc.util.Helpers { ); } - /** - * Show Information if user is offline, returns true if is not connected to internet - * - * @param activity Activity - * @param anchor A view anchor - */ - public boolean showInfoIfUserNotConnectedToInternet(Activity activity, View anchor) { - boolean isOnline = WebHelper.isOnline(context); - if (!isOnline) { - HelpersA.get(activity).showSnackBar(R.string.no_internet, true); - } - return !isOnline; - } - public void logBundle(Bundle savedInstanceState, String k) { if (savedInstanceState != null) { for (String key : savedInstanceState.keySet()) { diff --git a/app/src/main/java/com/github/dfa/diaspora_android/util/HelpersA.java b/app/src/main/java/com/github/dfa/diaspora_android/util/HelpersA.java new file mode 100644 index 00000000..2afee084 --- /dev/null +++ b/app/src/main/java/com/github/dfa/diaspora_android/util/HelpersA.java @@ -0,0 +1,73 @@ +package com.github.dfa.diaspora_android.util; + +import android.app.Activity; +import android.os.Bundle; +import android.os.Environment; +import android.view.View; + +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 HelpersA extends io.github.gsantner.opoc.util.HelpersA { + protected HelpersA(Activity activity) { + super(activity); + } + + + public static HelpersA get(Activity activity) { + return new HelpersA(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(HelpersA.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.no_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()); + } + } + } + } + } +} diff --git a/app/src/main/java/io/github/gsantner/opoc/util/AppSettingsBase.java b/app/src/main/java/io/github/gsantner/opoc/util/AppSettingsBase.java index 76435609..48de2967 100644 --- a/app/src/main/java/io/github/gsantner/opoc/util/AppSettingsBase.java +++ b/app/src/main/java/io/github/gsantner/opoc/util/AppSettingsBase.java @@ -17,24 +17,26 @@ * with keys in resources. Extend from this class and add * getters/setters for the app's settings. * Example: - public boolean isAppFirstStart() { - return getBool(prefApp, R.string.pref_key__app_first_start, true); + public boolean isAppFirstStart(boolean doSet) { + boolean value = getBool(prefApp, R.string.pref_key__app_first_start, true); + if (doSet) { + setBool(prefApp, R.string.pref_key__app_first_start, false); + } + return value; } - public void setAppFirstStart(boolean value) { - setBool(prefApp, R.string.pref_key__app_first_start, value); - } - - public boolean isAppFirstStartCurrentVersion() { - int value = getInt(prefApp, R.string.pref_key__app_first_start_current_version, -1); - setInt(prefApp, R.string.pref_key__app_first_start_current_version, BuildConfig.VERSION_CODE); - return value != BuildConfig.VERSION_CODE && !BuildConfig.IS_TEST_BUILD; + public boolean isAppCurrentVersionFirstStart(boolean doSet) { + int value = getInt(prefApp, R.string.pref_key__app_first_start_current_version, -1); + if (doSet) { + setInt(prefApp, R.string.pref_key__app_first_start_current_version, BuildConfig.VERSION_CODE); + } + return value != BuildConfig.VERSION_CODE && !BuildConfig.IS_TEST_BUILD; } * Maybe add a singleton for this: * Whereas App.get() is returning ApplicationContext - private AppSettings(Context context) { - super(context); + private AppSettings(Context _context) { + super(_context); } public static AppSettings get() { @@ -61,32 +63,32 @@ import java.util.List; * Wrapper for settings based on SharedPreferences * with keys in resources */ -@SuppressWarnings({"WeakerAccess", "unused"}) +@SuppressWarnings({"WeakerAccess", "unused", "SpellCheckingInspection", "SameParameterValue"}) public class AppSettingsBase { protected static final String ARRAY_SEPARATOR = "%%%"; protected static final String ARRAY_SEPARATOR_SUBSTITUTE = "§§§"; public static final String SHARED_PREF_APP = "app"; - //##################### - //## Members - //##################### - protected final SharedPreferences prefApp; - protected final Context context; + //######################## + //## Members, Constructors + //######################## + protected final SharedPreferences _prefApp; + protected final Context _context; + + public AppSettingsBase(final Context context) { + this(context, SHARED_PREF_APP); + } + + public AppSettingsBase(final Context context, final String prefAppName) { + _context = context.getApplicationContext(); + _prefApp = _context.getSharedPreferences(prefAppName, Context.MODE_PRIVATE); + } //##################### //## Methods //##################### - public AppSettingsBase(Context context) { - this(context, SHARED_PREF_APP); - } - - public AppSettingsBase(Context context, String prefAppName) { - this.context = context.getApplicationContext(); - prefApp = this.context.getSharedPreferences(prefAppName, Context.MODE_PRIVATE); - } - public Context getContext() { - return context; + return _context; } public boolean isKeyEqual(String key, int stringKeyResourceId) { @@ -94,35 +96,35 @@ public class AppSettingsBase { } public void resetSettings() { - resetSettings(prefApp); + resetSettings(_prefApp); } @SuppressLint("ApplySharedPref") - public void resetSettings(SharedPreferences pref) { + public void resetSettings(final SharedPreferences pref) { pref.edit().clear().commit(); } public boolean isPrefSet(@StringRes int stringKeyResourceId) { - return isPrefSet(prefApp, stringKeyResourceId); + return isPrefSet(_prefApp, stringKeyResourceId); } - public boolean isPrefSet(SharedPreferences pref, @StringRes int stringKeyResourceId) { + public boolean isPrefSet(final SharedPreferences pref, @StringRes int stringKeyResourceId) { return pref.contains(rstr(stringKeyResourceId)); } public void registerPreferenceChangedListener(SharedPreferences.OnSharedPreferenceChangeListener value) { - registerPreferenceChangedListener(prefApp, value); + registerPreferenceChangedListener(_prefApp, value); } - public void registerPreferenceChangedListener(SharedPreferences pref, SharedPreferences.OnSharedPreferenceChangeListener value) { + public void registerPreferenceChangedListener(final SharedPreferences pref, SharedPreferences.OnSharedPreferenceChangeListener value) { pref.registerOnSharedPreferenceChangeListener(value); } public void unregisterPreferenceChangedListener(SharedPreferences.OnSharedPreferenceChangeListener value) { - unregisterPreferenceChangedListener(prefApp, value); + unregisterPreferenceChangedListener(_prefApp, value); } - public void unregisterPreferenceChangedListener(SharedPreferences pref, SharedPreferences.OnSharedPreferenceChangeListener value) { + public void unregisterPreferenceChangedListener(final SharedPreferences pref, SharedPreferences.OnSharedPreferenceChangeListener value) { pref.unregisterOnSharedPreferenceChangeListener(value); } @@ -130,45 +132,45 @@ public class AppSettingsBase { //## Getter for resources //################################# public String rstr(@StringRes int stringKeyResourceId) { - return context.getString(stringKeyResourceId); + return _context.getString(stringKeyResourceId); } public int rcolor(@ColorRes int resColorId) { - return ContextCompat.getColor(context, resColorId); + return ContextCompat.getColor(_context, resColorId); } //################################# //## Getter & Setter for settings //################################# public void setString(@StringRes int keyResourceId, String value) { - setString(prefApp, keyResourceId, value); + setString(_prefApp, keyResourceId, value); } - public void setString(SharedPreferences pref, @StringRes int keyResourceId, String value) { + public void setString(final SharedPreferences pref, @StringRes int keyResourceId, String value) { pref.edit().putString(rstr(keyResourceId), value).apply(); } public String getString(@StringRes int keyResourceId, String defaultValue) { - return getString(prefApp, keyResourceId, defaultValue); + return getString(_prefApp, keyResourceId, defaultValue); } - public String getString(SharedPreferences pref, @StringRes int keyResourceId, String defaultValue) { + public String getString(final SharedPreferences pref, @StringRes int keyResourceId, String defaultValue) { return pref.getString(rstr(keyResourceId), defaultValue); } public String getString(@StringRes int keyResourceId, @StringRes int keyResourceIdDefaultValue) { - return getString(prefApp, keyResourceId, keyResourceIdDefaultValue); + return getString(_prefApp, keyResourceId, keyResourceIdDefaultValue); } - public String getString(SharedPreferences pref, @StringRes int keyResourceId, @StringRes int keyResourceIdDefaultValue) { + public String getString(final SharedPreferences pref, @StringRes int keyResourceId, @StringRes int keyResourceIdDefaultValue) { return pref.getString(rstr(keyResourceId), rstr(keyResourceIdDefaultValue)); } public void setStringArray(@StringRes int keyResourceId, Object[] values) { - setStringArray(prefApp, keyResourceId, values); + setStringArray(_prefApp, keyResourceId, values); } - public void setStringArray(SharedPreferences pref, @StringRes int keyResourceId, Object[] values) { + public void setStringArray(final SharedPreferences pref, @StringRes int keyResourceId, Object[] values) { StringBuilder sb = new StringBuilder(); for (Object value : values) { sb.append(ARRAY_SEPARATOR); @@ -179,12 +181,12 @@ public class AppSettingsBase { @NonNull public String[] getStringArray(@StringRes int keyResourceId) { - return getStringArray(prefApp, keyResourceId); + return getStringArray(_prefApp, keyResourceId); } @NonNull - public String[] getStringArray(SharedPreferences pref, @StringRes int keyResourceId) { - String value = pref.getString(rstr(keyResourceId), ARRAY_SEPARATOR); + public String[] getStringArray(final SharedPreferences pref, @StringRes int keyResourceId) { + String value = pref.getString(rstr(keyResourceId), ARRAY_SEPARATOR).replace(ARRAY_SEPARATOR_SUBSTITUTE, ARRAY_SEPARATOR); if (value.equals(ARRAY_SEPARATOR)) { return new String[0]; } @@ -192,133 +194,133 @@ public class AppSettingsBase { } public void setStringList(@StringRes int keyResourceId, List values) { - setStringList(prefApp, keyResourceId, values); + setStringList(_prefApp, keyResourceId, values); } - public void setStringList(SharedPreferences pref, @StringRes int keyResourceId, List values) { + public void setStringList(final SharedPreferences pref, @StringRes int keyResourceId, List values) { setStringArray(pref, keyResourceId, values.toArray(new String[values.size()])); } public ArrayList getStringList(@StringRes int keyResourceId) { - return getStringList(prefApp, keyResourceId); + return getStringList(_prefApp, keyResourceId); } - public ArrayList getStringList(SharedPreferences pref, @StringRes int keyResourceId) { + public ArrayList getStringList(final SharedPreferences pref, @StringRes int keyResourceId) { return new ArrayList<>(Arrays.asList(getStringArray(pref, keyResourceId))); } public void setLong(@StringRes int keyResourceId, long value) { - setLong(prefApp, keyResourceId, value); + setLong(_prefApp, keyResourceId, value); } - public void setLong(SharedPreferences pref, @StringRes int keyResourceId, long value) { + public void setLong(final SharedPreferences pref, @StringRes int keyResourceId, long value) { pref.edit().putLong(rstr(keyResourceId), value).apply(); } public long getLong(@StringRes int keyResourceId, long defaultValue) { - return getLong(prefApp, keyResourceId, defaultValue); + return getLong(_prefApp, keyResourceId, defaultValue); } - public long getLong(SharedPreferences pref, @StringRes int keyResourceId, long defaultValue) { + public long getLong(final SharedPreferences pref, @StringRes int keyResourceId, long defaultValue) { return pref.getLong(rstr(keyResourceId), defaultValue); } public void setBool(@StringRes int keyResourceId, boolean value) { - setBool(prefApp, keyResourceId, value); + setBool(_prefApp, keyResourceId, value); } - public void setBool(SharedPreferences pref, @StringRes int keyResourceId, boolean value) { + public void setBool(final SharedPreferences pref, @StringRes int keyResourceId, boolean value) { pref.edit().putBoolean(rstr(keyResourceId), value).apply(); } public boolean getBool(@StringRes int keyResourceId, boolean defaultValue) { - return getBool(prefApp, keyResourceId, defaultValue); + return getBool(_prefApp, keyResourceId, defaultValue); } - public boolean getBool(SharedPreferences pref, @StringRes int keyResourceId, boolean defaultValue) { + public boolean getBool(final SharedPreferences pref, @StringRes int keyResourceId, boolean defaultValue) { return pref.getBoolean(rstr(keyResourceId), defaultValue); } public int getColor(String key, int defaultColor) { - return getColor(prefApp, key, defaultColor); + return getColor(_prefApp, key, defaultColor); } - public int getColor(SharedPreferences pref, String key, int defaultColor) { + public int getColor(final SharedPreferences pref, String key, int defaultColor) { return pref.getInt(key, defaultColor); } public int getColor(@StringRes int keyResourceId, int defaultColor) { - return getColor(prefApp, keyResourceId, defaultColor); + return getColor(_prefApp, keyResourceId, defaultColor); } - public int getColor(SharedPreferences pref, @StringRes int keyResourceId, int defaultColor) { + public int getColor(final SharedPreferences pref, @StringRes int keyResourceId, int defaultColor) { return pref.getInt(rstr(keyResourceId), defaultColor); } public void setDouble(@StringRes int keyResId, double value) { - setDouble(prefApp, keyResId, value); + setDouble(_prefApp, keyResId, value); } - public void setDouble(SharedPreferences pref, @StringRes int keyResId, double value) { - prefApp.edit().putLong(rstr(keyResId), Double.doubleToRawLongBits(value)).apply(); + public void setDouble(final SharedPreferences pref, @StringRes int keyResId, double value) { + _prefApp.edit().putLong(rstr(keyResId), Double.doubleToRawLongBits(value)).apply(); } public double getDouble(@StringRes int keyResId, double defaultValue) { - return getDouble(prefApp, keyResId, defaultValue); + return getDouble(_prefApp, keyResId, defaultValue); } - public double getDouble(SharedPreferences pref, @StringRes int keyResId, double defaultValue) { - return Double.longBitsToDouble(prefApp.getLong(rstr(keyResId), Double.doubleToLongBits(defaultValue))); + public double getDouble(final SharedPreferences pref, @StringRes int keyResId, double defaultValue) { + return Double.longBitsToDouble(_prefApp.getLong(rstr(keyResId), Double.doubleToLongBits(defaultValue))); } public int getIntOfStringPref(@StringRes int keyResId, int defaultValue) { - String strNum = prefApp.getString(context.getString(keyResId), Integer.toString(defaultValue)); + String strNum = _prefApp.getString(_context.getString(keyResId), Integer.toString(defaultValue)); return Integer.valueOf(strNum); } public void setInt(@StringRes int keyResourceId, int value) { - setInt(prefApp, keyResourceId, value); + setInt(_prefApp, keyResourceId, value); } - public void setInt(SharedPreferences pref, @StringRes int keyResourceId, int value) { + public void setInt(final SharedPreferences pref, @StringRes int keyResourceId, int value) { pref.edit().putInt(rstr(keyResourceId), value).apply(); } public int getInt(@StringRes int keyResourceId, int defaultValue) { - return getInt(prefApp, keyResourceId, defaultValue); + return getInt(_prefApp, keyResourceId, defaultValue); } - public int getInt(SharedPreferences pref, @StringRes int keyResourceId, int defaultValue) { + public int getInt(final SharedPreferences pref, @StringRes int keyResourceId, int defaultValue) { return pref.getInt(rstr(keyResourceId), defaultValue); } public void setIntList(@StringRes int keyResId, List values) { - setIntList(prefApp, keyResId, values); + setIntList(_prefApp, keyResId, values); } - public void setIntList(SharedPreferences pref, @StringRes int keyResId, List values) { + public void setIntList(final SharedPreferences pref, @StringRes int keyResId, List values) { StringBuilder sb = new StringBuilder(); for (int value : values) { sb.append(ARRAY_SEPARATOR); sb.append(Integer.toString(value)); } - setString(prefApp, keyResId, sb.toString().replaceFirst(ARRAY_SEPARATOR, "")); + setString(_prefApp, keyResId, sb.toString().replaceFirst(ARRAY_SEPARATOR, "")); } @NonNull public ArrayList getIntList(@StringRes int keyResId) { - return getIntList(prefApp, keyResId); + return getIntList(_prefApp, keyResId); } @NonNull - public ArrayList getIntList(SharedPreferences pref, @StringRes int keyResId) { - ArrayList ret = new ArrayList<>(); - String value = getString(prefApp, keyResId, ARRAY_SEPARATOR); + public ArrayList getIntList(final SharedPreferences pref, @StringRes int keyResId) { + final ArrayList ret = new ArrayList<>(); + final String value = getString(_prefApp, keyResId, ARRAY_SEPARATOR); if (value.equals(ARRAY_SEPARATOR)) { return ret; } - for (String s : value.split(ARRAY_SEPARATOR)) { - ret.add(Integer.parseInt(s)); + for (String intstr : value.split(ARRAY_SEPARATOR)) { + ret.add(Integer.parseInt(intstr)); } return ret; } diff --git a/app/src/main/java/io/github/gsantner/opoc/util/Helpers.java b/app/src/main/java/io/github/gsantner/opoc/util/Helpers.java index db593f95..d6695791 100644 --- a/app/src/main/java/io/github/gsantner/opoc/util/Helpers.java +++ b/app/src/main/java/io/github/gsantner/opoc/util/Helpers.java @@ -37,7 +37,6 @@ import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.method.LinkMovementMethod; -import android.text.util.Linkify; import android.util.DisplayMetrics; import android.webkit.WebView; import android.widget.TextView; @@ -45,38 +44,49 @@ import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; +import java.lang.reflect.Field; import java.util.Locale; -import com.github.dfa.diaspora_android.App; -import com.github.dfa.diaspora_android.BuildConfig; -import com.github.dfa.diaspora_android.R; - -@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue"}) +@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue", "SpellCheckingInspection"}) public class Helpers { - protected Context context; + //######################## + //## Members, Constructors + //######################## + protected Context _context; - protected Helpers(Context context) { - this.context = context; - } - - public static Helpers get() { - return new Helpers(App.get()); + public Helpers(Context context) { + _context = context; } + //######################## + //## Methods + //######################## public String str(@StringRes int strResId) { - return context.getString(strResId); + return _context.getString(strResId); + } + + static class ResType { + public static final String DRAWABLE = "drawable"; + public static final String STRING = "string"; + public static final String PLURAL = "plural"; + public static final String COLOR = "color"; + public static final String STYLE = "style"; + public static final String ARRAY = "array"; + public static final String DIMEN = "dimen"; + public static final String MENU = "menu"; + public static final String RAW = "raw"; } public Drawable drawable(@DrawableRes int resId) { - return ContextCompat.getDrawable(context, resId); + return ContextCompat.getDrawable(_context, resId); } public int color(@ColorRes int resId) { - return ContextCompat.getColor(context, resId); + return ContextCompat.getColor(_context, resId); } public Context context() { - return context; + return _context; } public String colorToHexString(int intColor) { @@ -85,35 +95,87 @@ public class Helpers { public String getAppVersionName() { try { - PackageManager manager = context.getPackageManager(); - PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0); + PackageManager manager = _context.getPackageManager(); + PackageInfo info = manager.getPackageInfo(_context.getPackageName(), 0); return info.versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); - return "unknown"; + return "?"; } } + public int getResId(final String type, final String name) { + return _context.getResources().getIdentifier(name, type, _context.getPackageName()); + } - public void openWebpageInExternalBrowser(String url) { + public boolean areResIdsAvailable(final String type, final String... names) { + for (String name : names) { + if (getResId(type, name) == 0) { + return false; + } + } + return true; + } + + public void openWebpageInExternalBrowser(final String url) { Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intent); + _context.startActivity(intent); } - public void showDonateBitcoinRequest() { - if (!BuildConfig.IS_GPLAY_BUILD) { + /** + * https://stackoverflow.com/a/25267049 + * Gets a field from the project's BuildConfig. This is useful when, for example, flavors + * are used at the project level to set custom fields. + * + * @param fieldName The name of the field-to-access + * @return The value of the field, or {@code null} if the field is not found. + */ + public Object getBuildConfigValue(String fieldName) { + try { + Class clazz = Class.forName(_context.getPackageName() + ".BuildConfig"); + Field field = clazz.getField(fieldName); + return field.get(null); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (NoSuchFieldException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } + + public boolean getBuildConfigBoolean(String fieldName, boolean defaultValue) { + Object field = getBuildConfigValue(fieldName); + if (field != null && field instanceof Boolean) { + return (Boolean) field; + } + return defaultValue; + } + + public boolean isGooglePlayBuild() { + return getBuildConfigBoolean("IS_GPLAY_BUILD", true); + } + + public boolean isFossBuild() { + return getBuildConfigBoolean("IS_FOSS_BUILD", false); + } + + // Requires donate__bitcoin_* resources (see below) to be available as string resource + public void showDonateBitcoinRequest(@StringRes final int strResBitcoinId, @StringRes final int strResBitcoinAmount, @StringRes final int strResBitcoinMessage, @StringRes final int strResAlternativeDonateUrl) { + if (!isGooglePlayBuild()) { String btcUri = String.format("bitcoin:%s?amount=%s&label=%s&message=%s", - str(R.string.donate__bitcoin_id), str(R.string.donate__bitcoin_amount), - str(R.string.donate__bitcoin_message), str(R.string.donate__bitcoin_message)); + str(strResBitcoinId), str(strResBitcoinAmount), + str(strResBitcoinMessage), str(strResBitcoinMessage)); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(btcUri)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { - context.startActivity(intent); + _context.startActivity(intent); } catch (ActivityNotFoundException e) { - openWebpageInExternalBrowser(str(R.string.donate__bitcoin_url)); + openWebpageInExternalBrowser(str(strResAlternativeDonateUrl)); } } } @@ -127,7 +189,7 @@ public class Helpers { linePostfix = linePostfix == null ? "" : linePostfix; try { - br = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(rawResId))); + br = new BufferedReader(new InputStreamReader(_context.getResources().openRawResource(rawResId))); while ((line = br.readLine()) != null) { sb.append(linePrefix); sb.append(line); @@ -147,9 +209,9 @@ public class Helpers { } public void showDialogWithRawFileInWebView(String fileInRaw, @StringRes int resTitleId) { - WebView wv = new WebView(context); + WebView wv = new WebView(_context); wv.loadUrl("file:///android_res/raw/" + fileInRaw); - AlertDialog.Builder dialog = new AlertDialog.Builder(context) + AlertDialog.Builder dialog = new AlertDialog.Builder(_context) .setPositiveButton(android.R.string.ok, null) .setTitle(resTitleId) .setView(wv); @@ -165,16 +227,16 @@ public class Helpers { public boolean isConnectedToInternet() { ConnectivityManager connectivityManager = (ConnectivityManager) - context.getSystemService(Context.CONNECTIVITY_SERVICE); + _context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); return activeNetInfo != null && activeNetInfo.isConnectedOrConnecting(); } public void restartApp(Class classToStartupWith) { - Intent restartIntent = new Intent(context, classToStartupWith); - PendingIntent restartIntentP = PendingIntent.getActivity(context, 555, + Intent restartIntent = new Intent(_context, classToStartupWith); + PendingIntent restartIntentP = PendingIntent.getActivity(_context, 555, restartIntent, PendingIntent.FLAG_CANCEL_CURRENT); - AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); + AlarmManager mgr = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, restartIntentP); System.exit(0); } @@ -182,9 +244,9 @@ public class Helpers { public String loadMarkdownForTextViewFromRaw(@RawRes int rawMdFile, String prepend) { try { return new SimpleMarkdownParser() - .parse(context.getResources().openRawResource(rawMdFile), + .parse(_context.getResources().openRawResource(rawMdFile), prepend, SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW) - .replaceColor("#000001", color(R.color.accent)) + .replaceColor("#000001", color(getResId(ResType.COLOR, "accent"))) .removeMultiNewlines().replaceBulletCharacter("*").getHtml(); } catch (IOException e) { e.printStackTrace(); @@ -204,7 +266,7 @@ public class Helpers { } public double getEstimatedScreenSizeInches() { - DisplayMetrics dm = context.getResources().getDisplayMetrics(); + DisplayMetrics dm = _context.getResources().getDisplayMetrics(); double density = dm.density * 160; double x = Math.pow(dm.widthPixels / density, 2); @@ -216,7 +278,7 @@ public class Helpers { } public boolean isInPortraitMode() { - return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; + return _context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; } public Locale getLocaleByAndroidCode(String code) { @@ -231,8 +293,16 @@ public class Helpers { // "en"/"de"/"de-rAt"; Empty string = default locale public void setAppLanguage(String androidLocaleString) { Locale locale = getLocaleByAndroidCode(androidLocaleString); - Configuration config = context.getResources().getConfiguration(); + Configuration config = _context.getResources().getConfiguration(); config.locale = locale != null ? locale : Locale.getDefault(); - context.getResources().updateConfiguration(config, null); + _context.getResources().updateConfiguration(config, null); + } + + public float px2dp(final float px) { + return px / _context.getResources().getDisplayMetrics().density; + } + + public float dp2px(final float dp) { + return dp * _context.getResources().getDisplayMetrics().density; } } diff --git a/app/src/main/java/io/github/gsantner/opoc/util/HelpersA.java b/app/src/main/java/io/github/gsantner/opoc/util/HelpersA.java index ff747a84..dbf530bb 100644 --- a/app/src/main/java/io/github/gsantner/opoc/util/HelpersA.java +++ b/app/src/main/java/io/github/gsantner/opoc/util/HelpersA.java @@ -24,23 +24,19 @@ import android.text.method.LinkMovementMethod; import android.util.TypedValue; import android.view.inputmethod.InputMethodManager; -import com.github.dfa.diaspora_android.R; - -@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue"}) +@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue", "SpellCheckingInspection"}) public class HelpersA extends Helpers { - protected Activity activity; + //######################## + //## Members, Constructors + //######################## + protected Activity _activity; - protected HelpersA(Activity activity) { + public HelpersA(final Activity activity) { super(activity); - this.activity = activity; + _activity = activity; } - public static HelpersA get(Activity activity) { - return new HelpersA(activity); - } - - //######################## //## Methods //######################## @@ -48,45 +44,46 @@ public class HelpersA extends Helpers { /** * Animate to specified Activity * - * @param to The class of the activity - * @param finishFromActivity true: Finish the current activity - * @param requestCode Request code for stating the activity, not waiting for result if null + * @param to The class of the _activity + * @param finishFromActivity true: Finish the current _activity + * @param requestCode Request code for stating the _activity, not waiting for result if null */ public void animateToActivity(Class to, Boolean finishFromActivity, Integer requestCode) { - animateToActivity(new Intent(activity, to), finishFromActivity, requestCode); + animateToActivity(new Intent(_activity, to), finishFromActivity, requestCode); } /** - * Animate to activity specified in intent + * Animate to Activity specified in intent + * Requires animation resources * - * @param intent Intent to open start an activity - * @param finishFromActivity true: Finish the current activity - * @param requestCode Request code for stating the activity, not waiting for result if null + * @param intent Intent to open start an _activity + * @param finishFromActivity true: Finish the current _activity + * @param requestCode Request code for stating the _activity, not waiting for result if null */ public void animateToActivity(Intent intent, Boolean finishFromActivity, Integer requestCode) { intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); if (requestCode != null) { - activity.startActivityForResult(intent, requestCode); + _activity.startActivityForResult(intent, requestCode); } else { - activity.startActivity(intent); + _activity.startActivity(intent); } - activity.overridePendingTransition(R.anim.fadein, R.anim.fadeout); + _activity.overridePendingTransition(getResId(ResType.DIMEN, "fadein"), getResId(ResType.DIMEN, "fadeout")); if (finishFromActivity != null && finishFromActivity) { - activity.finish(); + _activity.finish(); } } public void showSnackBar(@StringRes int stringId, boolean showLong) { - Snackbar.make(activity.findViewById(android.R.id.content), stringId, + Snackbar.make(_activity.findViewById(android.R.id.content), stringId, showLong ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT).show(); } public void hideSoftKeyboard() { - InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); - if (activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null) { - inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); + InputMethodManager inputMethodManager = (InputMethodManager) _activity.getSystemService(Activity.INPUT_METHOD_SERVICE); + if (_activity.getCurrentFocus() != null && _activity.getCurrentFocus().getWindowToken() != null) { + inputMethodManager.hideSoftInputFromWindow(_activity.getCurrentFocus().getWindowToken(), 0); } } @@ -95,14 +92,14 @@ public class HelpersA extends Helpers { } public void showDialogWithHtmlTextView(@StringRes int resTitleId, String text, boolean isHtml, DialogInterface.OnDismissListener dismissedListener) { - AppCompatTextView textView = new AppCompatTextView(context); + AppCompatTextView textView = new AppCompatTextView(_context); int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, - context.getResources().getDisplayMetrics()); + _context.getResources().getDisplayMetrics()); textView.setMovementMethod(new LinkMovementMethod()); textView.setPadding(padding, 0, padding, 0); textView.setText(isHtml ? new SpannableString(Html.fromHtml(text)) : text); - AlertDialog.Builder dialog = new AlertDialog.Builder(context) + AlertDialog.Builder dialog = new AlertDialog.Builder(_context) .setPositiveButton(android.R.string.ok, null) .setOnDismissListener(dismissedListener) .setTitle(resTitleId) diff --git a/app/src/main/java/io/github/gsantner/opoc/util/SimpleMarkdownParser.java b/app/src/main/java/io/github/gsantner/opoc/util/SimpleMarkdownParser.java index 17ed4ea7..b96f3c0f 100644 --- a/app/src/main/java/io/github/gsantner/opoc/util/SimpleMarkdownParser.java +++ b/app/src/main/java/io/github/gsantner/opoc/util/SimpleMarkdownParser.java @@ -21,7 +21,7 @@ * 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 + * 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. @@ -40,15 +40,9 @@ import java.io.InputStreamReader; */ @SuppressWarnings({"WeakerAccess", "CaughtExceptionImmediatelyRethrown", "SameParameterValue", "unused", "SpellCheckingInspection", "RepeatedSpace", "SingleCharAlternation"}) public class SimpleMarkdownParser { - private static SimpleMarkdownParser instance; - - public static SimpleMarkdownParser get() { - if (instance == null) { - instance = new SimpleMarkdownParser(); - } - return instance; - } - + //######################## + //## Statics + //######################## public interface SmpFilter { String filter(String text); } @@ -56,7 +50,7 @@ public class SimpleMarkdownParser { 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 + // 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 @@ -118,17 +112,32 @@ public class SimpleMarkdownParser { }; //######################## - //## Members + //## Singleton //######################## - private SmpFilter defaultSmpFilter; - private String html; + private static SimpleMarkdownParser instance; + + public static SimpleMarkdownParser get() { + if (instance == null) { + instance = new SimpleMarkdownParser(); + } + return instance; + } + + //######################## + //## Members, Constructors + //######################## + private SmpFilter _defaultSmpFilter; + private String _html; public SimpleMarkdownParser() { setDefaultSmpFilter(FILTER_WEB); } - public SimpleMarkdownParser setDefaultSmpFilter(SmpFilter defaultSmpFilter) { - this.defaultSmpFilter = defaultSmpFilter; + //######################## + //## Methods + //######################## + public SimpleMarkdownParser setDefaultSmpFilter(SmpFilter _defaultSmpFilter) { + this._defaultSmpFilter = _defaultSmpFilter; return this; } @@ -149,7 +158,7 @@ public class SimpleMarkdownParser { sb.append("\n"); } } catch (IOException rethrow) { - html = ""; + _html = ""; throw rethrow; } finally { if (br != null) { @@ -159,47 +168,47 @@ public class SimpleMarkdownParser { } } } - html = parse(sb.toString(), "", smpFilters).getHtml(); + _html = parse(sb.toString(), "", smpFilters).getHtml(); return this; } public SimpleMarkdownParser parse(String markdown, String lineMdPrefix, SmpFilter... smpFilters) throws IOException { - html = markdown; + _html = markdown; if (smpFilters.length == 0) { - smpFilters = new SmpFilter[]{defaultSmpFilter}; + smpFilters = new SmpFilter[]{_defaultSmpFilter}; } for (SmpFilter smpFilter : smpFilters) { - html = smpFilter.filter(html).trim(); + _html = smpFilter.filter(_html).trim(); } return this; } public String getHtml() { - return html; + return _html; } public SimpleMarkdownParser setHtml(String html) { - this.html = html; + _html = html; return this; } public SimpleMarkdownParser removeMultiNewlines() { - html = html.replace("\n", "").replaceAll("(
){3,}", "

"); + _html = _html.replace("\n", "").replaceAll("(
){3,}", "

"); return this; } public SimpleMarkdownParser replaceBulletCharacter(String replacment) { - html = html.replace("•", replacment); + _html = _html.replace("•", replacment); return this; } public SimpleMarkdownParser replaceColor(String hexColor, int newIntColor) { - html = html.replace(hexColor, String.format("#%06X", 0xFFFFFF & newIntColor)); + _html = _html.replace(hexColor, String.format("#%06X", 0xFFFFFF & newIntColor)); return this; } @Override public String toString() { - return html != null ? html : ""; + return _html != null ? _html : ""; } } From c988fc3bdd731b8f3f21604a9a4e93616923713d Mon Sep 17 00:00:00 2001 From: Gregor Santner Date: Sat, 12 Aug 2017 22:34:15 +0200 Subject: [PATCH 003/181] Lower butterknife version to not pull in more recent appcompat --- CODE_OF_CONDUCT.md | 74 ++++++++++++++++++++++++++++++++++++++++++++++ app/build.gradle | 7 ++--- 2 files changed, 77 insertions(+), 4 deletions(-) create mode 100644 CODE_OF_CONDUCT.md 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/app/build.gradle b/app/build.gradle index 08f02988..e2c38cf2 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -9,8 +9,8 @@ ext { ] version_sdk.targetSdk = version_sdk.compileSdk version_lib = [ - appcompat : "24.2.1", - butterknife : "8.7.0", + appcompat : "24.1.0", // Broken after 24.1.0, Fix announced at 26.0.0, but still not fixed... See https://issuetracker.google.com/issues/37118105 + butterknife : "8.4.0", netcipher : "2.0.0-alpha1", ] } @@ -76,8 +76,7 @@ dependencies { // Android standard libs compile "com.android.support:appcompat-v7:${version_lib.appcompat}" - //compile "com.android.support:design:${version_lib.appcompat}" // Broken after 24.1.0, Fix announced at 26.0.0, but still not fixed... See https://issuetracker.google.com/issues/37118105 - compile "com.android.support:design:24.1.0" + compile "com.android.support:design:${version_lib.appcompat}" compile "com.android.support:support-v4:${version_lib.appcompat}" compile "com.android.support:customtabs:${version_lib.appcompat}" compile "com.android.support:cardview-v7:${version_lib.appcompat}" From eb0e2b0997c01c3e3baca3d73b524e60ebb94bdd Mon Sep 17 00:00:00 2001 From: Gregor Santner Date: Sun, 13 Aug 2017 23:02:04 +0200 Subject: [PATCH 004/181] Improve badge and podselection colors ; Update podlist --- CHANGELOG.md | 4 + app/build.gradle | 4 +- app/src/main/AndroidManifest.xml | 88 +++ .../activity/MainActivity.java | 8 +- .../activity/PodSelectionFragment.java | 9 +- .../data/DiasporaPodList.java | 145 ++-- .../diaspora_android/ui/BadgeDrawable.java | 91 +-- .../diaspora_android/util/AppSettings.java | 6 +- .../util/DiasporaUrlHelper.java | 4 +- .../io/github/gsantner/opoc/util/Helpers.java | 8 + .../res/layout/podselection__fragment.xml | 12 +- app/src/main/res/menu/main__navdrawer.xml | 5 + app/src/main/res/raw/podlist.json | 679 +++++++++++++++--- app/src/main/res/values/dimens.xml | 2 +- .../res/values/strings-not_translatable.xml | 1 + .../xml/preferences__sub_navslider_vis.xml | 4 + 16 files changed, 844 insertions(+), 226 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ed4efff..d4fa48da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ### 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 diff --git a/app/build.gradle b/app/build.gradle index e2c38cf2..0524faf9 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -23,8 +23,8 @@ android { minSdkVersion version_sdk.minSdk targetSdkVersion version_sdk.targetSdk - versionCode 22 - versionName "1.0.2" + versionCode 23 + versionName "1.0.3" applicationId "com.github.dfa.diaspora_android" resValue 'string', 'app_name', "dandelion*" diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 150e8241..db1a273b 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -83,6 +83,7 @@ + @@ -223,7 +224,94 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/com/github/dfa/diaspora_android/activity/MainActivity.java b/app/src/main/java/com/github/dfa/diaspora_android/activity/MainActivity.java index 9f4574e4..94de6577 100644 --- a/app/src/main/java/com/github/dfa/diaspora_android/activity/MainActivity.java +++ b/app/src/main/java/com/github/dfa/diaspora_android/activity/MainActivity.java @@ -447,7 +447,8 @@ public class MainActivity extends ThemedActivity 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.isVisibleToggleMobileDesktop()); + navMenu.findItem(R.id.nav_toggle_desktop_page).setVisible(appSettings.isVisibleInNavToggleMobileDesktop()); + navMenu.findItem(R.id.nav_dandelion).setVisible(appSettings.isVisibleInNavDandelionAccount()); // Hide whole group (for logged in use) if no pod was selected @@ -1122,6 +1123,11 @@ public class MainActivity extends ThemedActivity } break; + case R.id.nav_dandelion: { + openDiasporaUrl(urls.getProfileUrl("48b78420923501341ef3782bcb452bd5")); + } + break; + case R.id.nav_exit: { moveTaskToBack(true); finish(); 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 index 6060db0e..c09cacde 100644 --- 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 @@ -177,8 +177,13 @@ public class PodSelectionFragment extends ThemedFragment implements SearchView.O rootView.setBackgroundColor(appSettings.isAmoledColorMode() ? Color.BLACK : Color.WHITE); listViewPod.setDivider(new ColorDrawable(Color.GRAY)); listViewPod.setDividerHeight(dividerHeight); - buttonUseCustomPod.setSupportBackgroundTintList(ColorStateList.valueOf(appSettings.isAmoledColorMode() ? Color.DKGRAY : Color.WHITE)); - buttonUseCustomPod.setTextColor(appSettings.isAmoledColorMode() ? Color.WHITE : Color.BLACK); + if (appSettings.isAmoledColorMode()) { + buttonUseCustomPod.setSupportBackgroundTintList(ColorStateList.valueOf(Color.DKGRAY)); + buttonUseCustomPod.setTextColor(Color.WHITE); + } else { + buttonUseCustomPod.setSupportBackgroundTintList(ColorStateList.valueOf(appSettings.getAccentColor())); + buttonUseCustomPod.setTextColor(Helpers.get().shouldColorOnTopBeLight(appSettings.getAccentColor()) ? Color.WHITE : Color.BLACK); + } } @Override 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 index 2047738b..5c806544 100644 --- 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 @@ -6,6 +6,7 @@ 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; @@ -18,8 +19,9 @@ import java.util.List; * 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_ACTIVE6 = false; + private static final boolean EXPORT_TOJSON_POST_COUNT_LOCAL = true; private List pods = new ArrayList<>(); private boolean trackMergeChanges = false; private Integer trackAddedIndexStart = -1; @@ -88,8 +90,8 @@ public class DiasporaPodList implements Iterable, S if (updatePodBak.getId() != 0 && updatePod.getId() == 0) { updatePod.setId(updatePodBak.getId()); } - if (updatePodBak.getActive6() != 0 && updatePod.getActive6() == 0) { - updatePod.setActive6(updatePodBak.getActive6()); + if (updatePodBak.getPostCountLocal() != 0 && updatePod.getPostCountLocal() == 0) { + updatePod.setPostCountLocal(updatePodBak.getPostCountLocal()); } if (updatePodBak.getScore() != 0 && updatePod.getScore() == 0) { updatePod.setScore(updatePodBak.getScore()); @@ -179,12 +181,12 @@ public class DiasporaPodList implements Iterable, S * ╚═╝ ╚═════╝ ╚═════╝ */ 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 active6 = 0; + 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() { @@ -199,14 +201,14 @@ public class DiasporaPodList implements Iterable, S JSONArray jarr; if (json.has("name")) { - name = json.getString("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 (!_mainLangs.contains(val)) { + _mainLangs.add(val); } } } @@ -214,19 +216,19 @@ public class DiasporaPodList implements Iterable, S 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 (!_podUrls.contains(podUrl)) { + _podUrls.add(podUrl); } } } if (json.has("score")) { - score = json.getInt("score"); + _score = json.getInt("score"); } - if (json.has("active6")) { - active6 = json.getLong("active6"); + if (json.has("postCountLocal")) { + _postCountLocal = json.getLong("postCountLocal"); } if (json.has("id")) { - id = json.getInt("id"); + _id = json.getInt("id"); } return this; } @@ -236,25 +238,28 @@ public class DiasporaPodList implements Iterable, S */ public JSONObject toJson() throws JSONException { JSONObject json = new JSONObject(); - json.put("name", name); - json.put("score", score); - json.put("id", id); + 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_ACTIVE6) { - json.put("active6", active6); + if (EXPORT_TOJSON_POST_COUNT_LOCAL && _postCountLocal > 0) { + json.put("postCountLocal", _postCountLocal); } // Pod urls JSONArray jarr = new JSONArray(); - for (DiasporaPodUrl value : podUrls) { + for (DiasporaPodUrl value : _podUrls) { jarr.put(value.toJson()); } json.put("podUrls", jarr); // main langs jarr = new JSONArray(); - for (String value : mainLangs) { + for (String value : _mainLangs) { jarr.put(value); } json.put("mainLangs", jarr); @@ -268,11 +273,11 @@ public class DiasporaPodList implements Iterable, S DiasporaPod otherPod = (DiasporaPod) o; // Check if id is equal - ret = this.id != 0 && this.id == otherPod.id; + ret = _id != 0 && _id == otherPod._id; - // Check if host is the same (fallback if id is 0) + // Check if _host is the same (fallback if id is 0) if (!ret) { - for (DiasporaPodUrl podUrl : podUrls) { + for (DiasporaPodUrl podUrl : _podUrls) { for (DiasporaPodUrl otherPodUrl : otherPod.getPodUrls()) { if (podUrl.getBaseUrl().equals(otherPodUrl.getBaseUrl())) { ret = true; @@ -292,45 +297,46 @@ public class DiasporaPodList implements Iterable, S if (!myPodUrls.isEmpty() && !otherPodUrls.isEmpty()) { return myPodUrls.get(0).getHost().compareTo(otherPodUrls.get(0).getHost()); } + return _name.compareTo(otherPod.getName()); } - return name.compareTo(otherPod.getName()); + return _name.compareTo(""); } @Override public String toString() { - return name + "(" + id + ")"; + return _name + "(" + _id + ")"; } /** * Iterator for Iterable interface (forEach, ..) */ public Iterator iterator() { - return podUrls.iterator(); + return _podUrls.iterator(); } /* * Getter & Setter */ public List getPodUrls() { - return podUrls; + return _podUrls; } public DiasporaPod setPodUrls(List podUrls) { - this.podUrls = podUrls; + _podUrls = podUrls; return this; } public List getMainLangs() { - return mainLangs; + return _mainLangs; } public DiasporaPod setMainLangs(List mainLangs) { - this.mainLangs = mainLangs; + _mainLangs = mainLangs; return this; } public DiasporaPod appendMainLangs(String... values) { - Collections.addAll(this.mainLangs, values); + _mainLangs.addAll(Arrays.asList(values)); return this; } @@ -338,50 +344,50 @@ public class DiasporaPodList implements Iterable, S * Returns the first DiasporaPodUrl in the list */ public DiasporaPodUrl getPodUrl() { - if (podUrls.size() > 0) { - return podUrls.get(0); + if (_podUrls.size() > 0) { + return _podUrls.get(0); } return null; } public DiasporaPod appendPodUrls(DiasporaPodUrl... values) { - Collections.addAll(this.podUrls, values); + _podUrls.addAll(Arrays.asList(values)); return this; } public String getName() { - return name; + return _name; } public DiasporaPod setName(String name) { - this.name = name; + _name = name; return this; } public int getScore() { - return score; + return _score; } public DiasporaPod setScore(int score) { - this.score = score; + _score = score; return this; } - public long getActive6() { - return active6; + public long getPostCountLocal() { + return _postCountLocal; } - public DiasporaPod setActive6(long active6) { - this.active6 = active6; + public DiasporaPod setPostCountLocal(long postCountLocal) { + _postCountLocal = postCountLocal; return this; } public int getId() { - return id; + return _id; } public DiasporaPod setId(int id) { - this.id = id; + _id = id; return this; } @@ -393,9 +399,9 @@ public class DiasporaPodList implements Iterable, S * ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ */ public static class DiasporaPodUrl implements Serializable { - private String host = ""; - private String protocol = "https"; - private Integer port = 443; + private String _host = ""; + private String _protocol = "https"; + private Integer _port = 443; public DiasporaPodUrl() { } @@ -407,10 +413,10 @@ public class DiasporaPodList implements Iterable, S /** * Get the base url * - * @return base url with port + * @return */ public String getBaseUrl() { - return protocol + "://" + host + (isPortNeeded() ? port : ""); + return _protocol + "://" + _host + (isPortNeeded() ? _port : ""); } /** @@ -420,13 +426,13 @@ public class DiasporaPodList implements Iterable, S */ public DiasporaPodUrl fromJson(JSONObject json) throws JSONException { if (json.has("host")) { - host = json.getString("host"); + _host = json.getString("host"); } if (json.has("protocol")) { - protocol = json.getString("protocol"); + _protocol = json.getString("protocol"); } if (json.has("port")) { - port = json.getInt("port"); + _port = json.getInt("port"); } return this; } @@ -436,12 +442,12 @@ public class DiasporaPodList implements Iterable, S */ public JSONObject toJson() throws JSONException { JSONObject json = new JSONObject(); - json.put("host", host); - if (!protocol.equals("https")) { - json.put("protocol", protocol); + json.put("host", _host); + if (!_protocol.equals("https")) { + json.put("protocol", _protocol); } - if (port != 443) { - json.put("port", port); + if (_port != 443) { + json.put("port", _port); } return json; } @@ -467,7 +473,7 @@ public class DiasporaPodList implements Iterable, S * Tells if the ports needs to shown */ public boolean isPortNeeded() { - return !((port == 80 && protocol.equals("http")) || (port == 443 && protocol.equals("https"))); + return !((_port == 80 && _protocol.equals("http")) || (_port == 443 && _protocol.equals("https"))); } @Override @@ -476,6 +482,7 @@ public class DiasporaPodList implements Iterable, S } @Override + @SuppressWarnings("SimplifiableIfStatement") public boolean equals(Object o) { if (o instanceof DiasporaPodUrl) { return getBaseUrl().equals(((DiasporaPodUrl) o).getBaseUrl()); @@ -487,29 +494,29 @@ public class DiasporaPodList implements Iterable, S * GETTER & SETTER */ public String getHost() { - return host; + return _host; } public DiasporaPodUrl setHost(String host) { - this.host = host; + _host = host; return this; } public String getProtocol() { - return protocol; + return _protocol; } public DiasporaPodUrl setProtocol(String protocol) { - this.protocol = protocol; + _protocol = protocol; return this; } public Integer getPort() { - return port; + return _port; } public DiasporaPodUrl setPort(Integer port) { - this.port = port; + _port = port; return this; } } 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 index 890295c9..d943deaf 100644 --- 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 @@ -28,95 +28,80 @@ import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; -import android.support.v4.content.ContextCompat; +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.Helpers; +@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 badgeStroke; - private Paint badgeText; - private Rect textRect = new Rect(); + private Paint _badgeBackground; + private Paint _badgeText; + private Rect _textRect = new Rect(); - private String badgeValue = ""; - private boolean shouldDraw; + 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); - badgeStroke = new Paint(); - badgeStroke.setColor(ContextCompat.getColor(context.getApplicationContext(), R.color.colorPrimaryDark)); - badgeStroke.setAntiAlias(true); - badgeStroke.setStyle(Paint.Style.FILL); + _badgeBackground = new Paint(); + _badgeBackground.setColor(settings.getAccentColor()); + _badgeBackground.setAntiAlias(true); + _badgeBackground.setStyle(Paint.Style.FILL); - badgeText = new Paint(); - badgeText.setColor(Color.WHITE); - badgeText.setTypeface(Typeface.DEFAULT); - badgeText.setTextSize(textSize); - badgeText.setAntiAlias(true); - badgeText.setTextAlign(Paint.Align.CENTER); + _badgeText = new Paint(); + _badgeText.setColor(Helpers.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(Canvas canvas) { - if (!shouldDraw) { + 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 = Helpers.get().dp2px(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) + 5; - float centerY = radius - 5; - if (badgeValue.length() <= 2) { - // Draw badge circle. - canvas.drawCircle(centerX, centerY, (int) (radius + 7.5), badgeStroke); - canvas.drawCircle(centerX, centerY, (int) (radius + 5.5), badgeBackground); - } else { - canvas.drawCircle(centerX, centerY, (int) (radius + 8.5), badgeStroke); - canvas.drawCircle(centerX, centerY, (int) (radius + 6.5), badgeBackground); - //canvas.drawRoundRect(radius, radius, radius, radius, 10, 10, badgeBackground); - } + 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; + _badgeText.getTextBounds(_badgeValue, 0, _badgeValue.length(), _textRect); + float textHeight = _textRect.bottom - _textRect.top; float textY = centerY + (textHeight / 2f); - if (badgeValue.length() > 2) - canvas.drawText(BADGE_VALUE_OVERFLOW, centerX, textY, badgeText); - else - canvas.drawText(badgeValue, centerX, textY, badgeText); + canvas.drawText(_badgeValue.length() > 2 ? BADGE_VALUE_OVERFLOW : _badgeValue, + centerX, textY, _badgeText); } - /* - Sets the count (i.e notifications) to display. - */ - public void setCount(String count) { - badgeValue = count; + // 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 there are notifications. - shouldDraw = !count.equalsIgnoreCase("0"); + // Only draw a badge if the value isn't a zero + _shouldDraw = !text.equalsIgnoreCase("0"); invalidateSelf(); } @Override public void setAlpha(int alpha) { - // do nothing } @Override public void setColorFilter(ColorFilter cf) { - // do nothing } @Override @@ -125,11 +110,11 @@ public class BadgeDrawable extends Drawable { } public static void setBadgeCount(Context context, LayerDrawable icon, Integer count) { - setBadgeCount(context, icon, count.toString()); + setBadgeText(context, icon, count.toString()); } - public static void setBadgeCount(Context context, LayerDrawable icon, String count) { - + // Max of 2 characters + public static void setBadgeText(Context context, LayerDrawable icon, String text) { BadgeDrawable badge; // Reuse drawable if possible @@ -140,7 +125,7 @@ public class BadgeDrawable extends Drawable { badge = new BadgeDrawable(context); } - badge.setCount(count); + badge.setBadgeText(text); icon.mutate(); icon.setDrawableByLayerId(R.id.ic_badge, badge); } 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 index 2a9812a2..81aaa21c 100644 --- 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 @@ -341,7 +341,11 @@ public class AppSettings extends AppSettingsBase { return getBool(_prefApp, R.string.pref_key__visibility_nav__reports, false); } - public boolean isVisibleToggleMobileDesktop() { + public boolean isVisibleInNavDandelionAccount() { + return getBool(_prefApp, R.string.pref_key__visibility_nav__dandelion_account, false); + } + + public boolean isVisibleInNavToggleMobileDesktop() { return getBool(_prefApp, R.string.pref_key__visibility_nav__toggle_mobile_desktop, false); } 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 eb7876c9..a4bf65c6 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 @@ -27,7 +27,7 @@ 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 final AppSettings settings; @@ -151,7 +151,7 @@ public class DiasporaUrlHelper { * @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; } diff --git a/app/src/main/java/io/github/gsantner/opoc/util/Helpers.java b/app/src/main/java/io/github/gsantner/opoc/util/Helpers.java index d6695791..adf4b046 100644 --- a/app/src/main/java/io/github/gsantner/opoc/util/Helpers.java +++ b/app/src/main/java/io/github/gsantner/opoc/util/Helpers.java @@ -21,6 +21,7 @@ import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.ColorStateList; import android.content.res.Configuration; +import android.graphics.Color; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; @@ -298,6 +299,13 @@ public class Helpers { _context.getResources().updateConfiguration(config, null); } + // Find out if color above the given color should be light or dark. true if light + public boolean shouldColorOnTopBeLight(int colorOnBottomInt) { + return 186 > (((0.299 * Color.red(colorOnBottomInt)) + + ((0.587 * Color.green(colorOnBottomInt)) + + (0.114 * Color.blue(colorOnBottomInt))))); + } + public float px2dp(final float px) { return px / _context.getResources().getDisplayMetrics().density; } diff --git a/app/src/main/res/layout/podselection__fragment.xml b/app/src/main/res/layout/podselection__fragment.xml index 9402ce26..c6d9f45f 100644 --- a/app/src/main/res/layout/podselection__fragment.xml +++ b/app/src/main/res/layout/podselection__fragment.xml @@ -2,14 +2,11 @@