From 8acebd22f9218921d287d69ba54cceeaa0e8ba4e Mon Sep 17 00:00:00 2001 From: Victor Shcherb Date: Tue, 19 May 2020 14:33:53 +0200 Subject: [PATCH 01/95] Initial refactoring --- OsmAnd/src/net/osmand/aidl/ConnectedApp.java | 4 +- .../core/android/MapRendererContext.java | 2 +- .../src/net/osmand/data/FavouritePoint.java | 4 +- .../osmand/plus/AppVersionUpgradeOnInit.java | 153 ++ .../net/osmand/plus/ContextMenuAdapter.java | 7 +- OsmAnd/src/net/osmand/plus/OsmandPlugin.java | 35 +- .../activities/FavoritesTreeFragment.java | 7 +- .../osmand/plus/activities/MapActivity.java | 3 +- .../plus/activities/MapActivityLayers.java | 2 +- .../plus/activities/SettingsBaseActivity.java | 4 +- .../SettingsNavigationActivity.java | 7 +- .../audionotes/AudioVideoNotesPlugin.java | 4 +- .../SortByMenuBottomSheetDialogFragment.java | 4 +- .../chooseplan/OsmLiveCancelledDialog.java | 2 +- .../DashboardSettingsDialogFragment.java | 2 +- .../plus/development/TestVoiceActivity.java | 6 +- .../osmand/plus/dialogs/ConfigureMapMenu.java | 37 +- .../osmand/plus/dialogs/RasterMapMenu.java | 9 +- ...endAnalyticsBottomSheetDialogFragment.java | 2 +- .../plus/download/DownloadIndexesThread.java | 2 +- .../net/osmand/plus/helpers/GpxUiHelper.java | 7 +- .../net/osmand/plus/helpers/LockHelper.java | 2 +- .../plus/inapp/InAppPurchaseHelper.java | 2 +- .../plus/liveupdates/LiveUpdatesFragment.java | 15 +- .../plus/liveupdates/LiveUpdatesHelper.java | 15 +- .../LiveUpdatesSettingsDialogFragment.java | 11 +- .../PerformLiveUpdateAsyncTask.java | 5 +- .../plus/mapcontextmenu/CollapsableView.java | 2 +- .../MapContextMenuFragment.java | 3 +- .../controllers/MapMarkerMenuController.java | 4 +- ...rdinateInputBottomSheetDialogFragment.java | 5 +- .../CoordinateInputDialogFragment.java | 4 +- .../DirectionIndicationDialogFragment.java | 2 +- .../MonitoringSettingsFragment.java | 9 +- .../TrackActivityFragmentAdapter.java | 3 +- .../osmand/plus/osmedit/OsmEditingPlugin.java | 5 +- .../net/osmand/plus/osmedit/OsmNotesMenu.java | 4 +- .../parkingpoint/ParkingPositionPlugin.java | 2 +- .../plus/rastermaps/MapUnderlayAction.java | 3 +- .../rastermaps/OsmandRasterMapsPlugin.java | 4 +- .../plus/render/MapRenderRepositories.java | 2 +- .../RegionAddressRepositoryBinary.java | 2 +- .../AvoidRoadsBottomSheetDialogFragment.java | 6 +- .../MapRouteInfoMenu.java | 4 +- .../RoutingOptionsHelper.java | 8 +- .../osmand/plus/routing/RouteProvider.java | 2 +- .../plus/routing/TransportRoutingHelper.java | 3 +- .../BooleanAccessibilityPreference.java | 33 + .../settings/backend/BooleanPreference.java | 23 + .../settings/backend/CommonPreference.java | 234 ++ .../backend/ContextMenuItemsPreference.java | 48 + .../backend/ContextMenuItemsSettings.java | 96 + .../backend/EnumStringPreference.java | 45 + .../settings/backend/FloatPreference.java | 27 + .../backend/ImpassableRoadsStorage.java | 194 ++ .../plus/settings/backend/IntPreference.java | 27 + .../backend/IntermediatePointsStorage.java | 23 + .../backend/ListStringPreference.java | 127 + .../plus/settings/backend/LongPreference.java | 27 + .../backend/MainContextMenuItemsSettings.java | 45 + .../backend/OsmAndPreferencesDataStore.java | 120 + .../settings/backend/OsmandPreference.java | 43 + .../plus/settings/backend/OsmandSettings.java | 2079 +++-------------- .../backend/PreferenceWithListener.java | 49 + .../plus/settings/backend/SettingsHelper.java | 14 +- .../backend/SettingsMapPointsStorage.java | 141 ++ .../settings/backend/StringPreference.java | 26 + .../BooleanPreferenceBottomSheet.java | 7 +- ...ecalculateRouteInDeviationBottomSheet.java | 3 +- .../fragments/BaseSettingsFragment.java | 7 +- .../fragments/ConfigureMenuItemsFragment.java | 18 +- .../fragments/RouteParametersFragment.java | 17 +- .../fragments/VehicleParametersFragment.java | 4 +- .../preferences/ListPreferenceEx.java | 10 +- .../MultiSelectBooleanPreference.java | 10 +- .../plus/srtmplugin/ContourLinesAction.java | 4 +- .../plus/srtmplugin/ContourLinesMenu.java | 9 +- .../osmand/plus/srtmplugin/SRTMPlugin.java | 14 +- .../plus/transport/TransportLinesMenu.java | 2 +- .../net/osmand/plus/views/AidlMapLayer.java | 2 +- .../src/net/osmand/plus/views/GPXLayer.java | 2 +- .../osmand/plus/views/MapControlsLayer.java | 5 +- .../osmand/plus/views/RulerControlLayer.java | 3 +- .../plus/views/TransportStopsLayer.java | 3 +- .../mapwidgets/MapInfoWidgetsFactory.java | 3 +- .../views/mapwidgets/MapWidgetRegistry.java | 2 +- .../mapwidgets/RouteInfoWidgetsFactory.java | 4 +- .../plus/voice/MediaCommandPlayerImpl.java | 4 +- .../plus/voice/TTSCommandPlayerImpl.java | 4 +- ...pediaOptionsBottomSheetDialogFragment.java | 4 +- ...oyageOptionsBottomSheetDialogFragment.java | 4 +- 91 files changed, 2089 insertions(+), 1907 deletions(-) create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/BooleanAccessibilityPreference.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/BooleanPreference.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsPreference.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsSettings.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/EnumStringPreference.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/FloatPreference.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/ImpassableRoadsStorage.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/IntPreference.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/IntermediatePointsStorage.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/ListStringPreference.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/LongPreference.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/MainContextMenuItemsSettings.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/OsmAndPreferencesDataStore.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/OsmandPreference.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/PreferenceWithListener.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/SettingsMapPointsStorage.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/StringPreference.java diff --git a/OsmAnd/src/net/osmand/aidl/ConnectedApp.java b/OsmAnd/src/net/osmand/aidl/ConnectedApp.java index a8b709972e..e1375b6838 100644 --- a/OsmAnd/src/net/osmand/aidl/ConnectedApp.java +++ b/OsmAnd/src/net/osmand/aidl/ConnectedApp.java @@ -15,7 +15,7 @@ import net.osmand.AndroidUtils; import net.osmand.plus.ContextMenuAdapter; import net.osmand.plus.ContextMenuItem; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.views.AidlMapLayer; @@ -54,7 +54,7 @@ public class ConnectedApp implements Comparable { private Map layers = new ConcurrentHashMap<>(); private Map mapLayers = new ConcurrentHashMap<>(); - private OsmandSettings.CommonPreference layersPref; + private CommonPreference layersPref; private String pack; private String name; diff --git a/OsmAnd/src/net/osmand/core/android/MapRendererContext.java b/OsmAnd/src/net/osmand/core/android/MapRendererContext.java index 03d88fa11c..d65880877c 100644 --- a/OsmAnd/src/net/osmand/core/android/MapRendererContext.java +++ b/OsmAnd/src/net/osmand/core/android/MapRendererContext.java @@ -25,7 +25,7 @@ import net.osmand.core.jni.ResolvedMapStyle; import net.osmand.core.jni.SwigUtilities; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.render.RendererRegistry; import net.osmand.render.RenderingRuleProperty; import net.osmand.render.RenderingRuleStorageProperties; diff --git a/OsmAnd/src/net/osmand/data/FavouritePoint.java b/OsmAnd/src/net/osmand/data/FavouritePoint.java index 3f7d74b412..d6a99b8916 100644 --- a/OsmAnd/src/net/osmand/data/FavouritePoint.java +++ b/OsmAnd/src/net/osmand/data/FavouritePoint.java @@ -9,8 +9,8 @@ import androidx.annotation.StringRes; import net.osmand.GPXUtilities.WptPt; import net.osmand.plus.FavouritesDbHelper; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings.BooleanPreference; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.BooleanPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.parkingpoint.ParkingPositionPlugin; import net.osmand.util.Algorithms; diff --git a/OsmAnd/src/net/osmand/plus/AppVersionUpgradeOnInit.java b/OsmAnd/src/net/osmand/plus/AppVersionUpgradeOnInit.java index e4f720fa14..a3d4589201 100644 --- a/OsmAnd/src/net/osmand/plus/AppVersionUpgradeOnInit.java +++ b/OsmAnd/src/net/osmand/plus/AppVersionUpgradeOnInit.java @@ -3,6 +3,22 @@ package net.osmand.plus; import android.annotation.SuppressLint; import android.content.SharedPreferences; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; + +import net.osmand.data.FavouritePoint; +import net.osmand.data.LatLon; +import net.osmand.plus.settings.backend.CommonPreference; +import net.osmand.plus.settings.backend.EnumStringPreference; +import net.osmand.plus.settings.backend.OsmandPreference; +import net.osmand.util.Algorithms; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + class AppVersionUpgradeOnInit { public static final String FIRST_TIME_APP_RUN = "FIRST_TIME_APP_RUN"; //$NON-NLS-1$ public static final String VERSION_INSTALLED_NUMBER = "VERSION_INSTALLED_NUMBER"; //$NON-NLS-1$ @@ -154,4 +170,141 @@ class AppVersionUpgradeOnInit { public boolean isFirstTime() { return firstTime; } + + private OsmandPreference[] generalPrefs = new OsmandPreference[]{ + EXTERNAL_INPUT_DEVICE, + CENTER_POSITION_ON_MAP, + ROTATE_MAP, + MAP_SCREEN_ORIENTATION, + LIVE_MONITORING_URL, + LIVE_MONITORING_MAX_INTERVAL_TO_SEND, + LIVE_MONITORING_INTERVAL, + LIVE_MONITORING, + SHOW_TRIP_REC_NOTIFICATION, + AUTO_SPLIT_RECORDING, + SAVE_TRACK_MIN_SPEED, + SAVE_TRACK_PRECISION, + SAVE_TRACK_MIN_DISTANCE, + SAVE_TRACK_INTERVAL, + TRACK_STORAGE_DIRECTORY, + SAVE_HEADING_TO_GPX, + DISABLE_RECORDING_ONCE_APP_KILLED, + SAVE_TRACK_TO_GPX, + SAVE_GLOBAL_TRACK_REMEMBER, + SAVE_GLOBAL_TRACK_INTERVAL, + MAP_EMPTY_STATE_ALLOWED, + DO_NOT_USE_ANIMATIONS, + USE_KALMAN_FILTER_FOR_COMPASS, + USE_MAGNETIC_FIELD_SENSOR_COMPASS, + USE_TRACKBALL_FOR_MOVEMENTS, + SPEED_SYSTEM, + ANGULAR_UNITS, + METRIC_SYSTEM, + DRIVING_REGION, + DRIVING_REGION_AUTOMATIC + }; + + public void migratePreferences() { + migrateEnumPreferences(); + SharedPreferences globalSharedPreferences = (SharedPreferences) globalPreferences; + Map globalPrefsMap = globalSharedPreferences.getAll(); + for (String key : globalPrefsMap.keySet()) { + OsmandPreference pref = getPreference(key); + if (pref instanceof CommonPreference) { + CommonPreference commonPreference = (CommonPreference) pref; + if (!commonPreference.global) { + for (ApplicationMode mode : ApplicationMode.allPossibleValues()) { + if (!commonPreference.isSetForMode(mode) && !commonPreference.hasDefaultValueForMode(mode)) { + setPreference(key, globalPrefsMap.get(key), mode); + } + } + } + } + } + SharedPreferences defaultProfilePreferences = (SharedPreferences) getProfilePreferences(ApplicationMode.DEFAULT); + Map defaultPrefsMap = defaultProfilePreferences.getAll(); + for (String key : defaultPrefsMap.keySet()) { + OsmandPreference pref = getPreference(key); + if (pref instanceof CommonPreference) { + CommonPreference commonPreference = (CommonPreference) pref; + if (commonPreference.global && !commonPreference.isSet()) { + setPreference(key, defaultPrefsMap.get(key)); + } + } + } + for (OsmandPreference pref : generalPrefs) { + if (pref instanceof CommonPreference) { + CommonPreference commonPref = (CommonPreference) pref; + Object defaultVal = commonPref.getModeValue(ApplicationMode.DEFAULT); + for (ApplicationMode mode : ApplicationMode.allPossibleValues()) { + if (!commonPref.isSetForMode(mode) && !commonPref.hasDefaultValueForMode(mode)) { + setPreference(commonPref.getId(), defaultVal, mode); + } + } + } + } + + String json = settingsAPI.getString(globalPreferences, "custom_app_profiles", ""); + if (!Algorithms.isEmpty(json)) { + Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); + Type t = new TypeToken>() { + }.getType(); + List customProfiles = gson.fromJson(json, t); + if (!Algorithms.isEmpty(customProfiles)) { + for (ApplicationMode.ApplicationModeBean modeBean : customProfiles) { + ApplicationMode.ApplicationModeBuilder builder = ApplicationMode.fromModeBean(ctx, modeBean); + ApplicationMode.saveProfile(builder, ctx); + } + } + } + } + + public void migrateEnumPreferences() { + for (OsmandPreference pref : registeredPreferences.values()) { + if (pref instanceof EnumStringPreference) { + EnumStringPreference enumPref = (EnumStringPreference) pref; + if (enumPref.isGlobal()) { + migrateEnumPref(enumPref, (SharedPreferences) globalPreferences); + } else { + for (ApplicationMode mode : ApplicationMode.allPossibleValues()) { + migrateEnumPref(enumPref, (SharedPreferences) getProfilePreferences(mode)); + } + } + } + } + } + + private void migrateEnumPref(EnumStringPreference enumPref, SharedPreferences sharedPreferences) { + Object value = sharedPreferences.getAll().get(enumPref.getId()); + if (value instanceof Integer) { + int enumIndex = (int) value; + if (enumIndex >= 0 && enumIndex < enumPref.values.length) { + Enum savedValue = enumPref.values[enumIndex]; + enumPref.setValue(sharedPreferences, savedValue); + } + } + } + + public void migrateHomeWorkParkingToFavorites() { + FavouritesDbHelper favorites = ctx.getFavorites(); + + LatLon homePoint = null; + float lat = settingsAPI.getFloat(globalPreferences, "home_point_lat", 0); + float lon = settingsAPI.getFloat(globalPreferences, "home_point_lon", 0); + if (lat != 0 || lon != 0) { + homePoint = new LatLon(lat, lon); + } + LatLon workPoint = null; + lat = settingsAPI.getFloat(globalPreferences, "work_point_lat", 0); + lon = settingsAPI.getFloat(globalPreferences, "work_point_lon", 0); + if (lat != 0 || lon != 0) { + workPoint = new LatLon(lat, lon); + } + if (homePoint != null) { + favorites.setSpecialPoint(homePoint, FavouritePoint.SpecialPointType.HOME, null); + } + if (workPoint != null) { + favorites.setSpecialPoint(workPoint, FavouritePoint.SpecialPointType.WORK, null); + } + } } diff --git a/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java b/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java index 4777ec73d8..f067564530 100644 --- a/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java +++ b/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java @@ -36,9 +36,8 @@ import net.osmand.plus.activities.actions.AppModeDialog; import net.osmand.plus.dialogs.ConfigureMapMenu; import net.osmand.plus.dialogs.HelpArticleDialogFragment; import net.osmand.plus.helpers.AndroidUiHelper; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.ContextMenuItemsPreference; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.ContextMenuItemsPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.util.Algorithms; import org.apache.commons.logging.Log; @@ -629,7 +628,7 @@ public class ContextMenuAdapter { return makeDeleteAction(prefs.toArray(new OsmandPreference[prefs.size()])); } - private static void resetSetting(ApplicationMode appMode, OsmandSettings.OsmandPreference preference, boolean profileOnly) { + private static void resetSetting(ApplicationMode appMode, OsmandPreference preference, boolean profileOnly) { if (profileOnly) { preference.resetModeToDefault(appMode); } else { diff --git a/OsmAnd/src/net/osmand/plus/OsmandPlugin.java b/OsmAnd/src/net/osmand/plus/OsmandPlugin.java index d10e4e6b7f..a2eab459b2 100644 --- a/OsmAnd/src/net/osmand/plus/OsmandPlugin.java +++ b/OsmAnd/src/net/osmand/plus/OsmandPlugin.java @@ -41,7 +41,8 @@ import net.osmand.plus.osmedit.OsmEditingPlugin; import net.osmand.plus.parkingpoint.ParkingPositionPlugin; import net.osmand.plus.quickaction.QuickActionType; import net.osmand.plus.rastermaps.OsmandRasterMapsPlugin; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.CommonPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.settings.fragments.BaseSettingsFragment; import net.osmand.plus.skimapsplugin.SkiMapsPlugin; import net.osmand.plus.srtmplugin.SRTMPlugin; @@ -73,7 +74,7 @@ public abstract class OsmandPlugin { protected OsmandApplication app; - protected List pluginPreferences = new ArrayList<>(); + protected List pluginPreferences = new ArrayList<>(); private boolean active; private String installURL = null; @@ -111,7 +112,7 @@ public abstract class OsmandPlugin { return null; } - public List getPreferences() { + public List getPreferences() { return pluginPreferences; } @@ -841,44 +842,44 @@ public abstract class OsmandPlugin { } } - protected OsmandSettings.CommonPreference registerBooleanPreference(OsmandApplication app, String prefId, boolean defValue) { - OsmandSettings.CommonPreference preference = app.getSettings().registerBooleanPreference(prefId, defValue); + protected CommonPreference registerBooleanPreference(OsmandApplication app, String prefId, boolean defValue) { + CommonPreference preference = app.getSettings().registerBooleanPreference(prefId, defValue); pluginPreferences.add(preference); return preference; } - private OsmandSettings.CommonPreference registerBooleanAccessibilityPreference(OsmandApplication app, String prefId, boolean defValue) { - OsmandSettings.CommonPreference preference = app.getSettings().registerBooleanAccessibilityPreference(prefId, defValue); + private CommonPreference registerBooleanAccessibilityPreference(OsmandApplication app, String prefId, boolean defValue) { + CommonPreference preference = app.getSettings().registerBooleanAccessibilityPreference(prefId, defValue); pluginPreferences.add(preference); return preference; } - protected OsmandSettings.CommonPreference registerStringPreference(OsmandApplication app, String prefId, String defValue) { - OsmandSettings.CommonPreference preference = app.getSettings().registerStringPreference(prefId, defValue); + protected CommonPreference registerStringPreference(OsmandApplication app, String prefId, String defValue) { + CommonPreference preference = app.getSettings().registerStringPreference(prefId, defValue); pluginPreferences.add(preference); return preference; } - protected OsmandSettings.CommonPreference registerIntPreference(OsmandApplication app, String prefId, int defValue) { - OsmandSettings.CommonPreference preference = app.getSettings().registerIntPreference(prefId, defValue); + protected CommonPreference registerIntPreference(OsmandApplication app, String prefId, int defValue) { + CommonPreference preference = app.getSettings().registerIntPreference(prefId, defValue); pluginPreferences.add(preference); return preference; } - protected OsmandSettings.CommonPreference registerLongPreference(OsmandApplication app, String prefId, long defValue) { - OsmandSettings.CommonPreference preference = app.getSettings().registerLongPreference(prefId, defValue); + protected CommonPreference registerLongPreference(OsmandApplication app, String prefId, long defValue) { + CommonPreference preference = app.getSettings().registerLongPreference(prefId, defValue); pluginPreferences.add(preference); return preference; } - protected OsmandSettings.CommonPreference registerFloatPreference(OsmandApplication app, String prefId, float defValue) { - OsmandSettings.CommonPreference preference = app.getSettings().registerFloatPreference(prefId, defValue); + protected CommonPreference registerFloatPreference(OsmandApplication app, String prefId, float defValue) { + CommonPreference preference = app.getSettings().registerFloatPreference(prefId, defValue); pluginPreferences.add(preference); return preference; } - protected OsmandSettings.CommonPreference registerEnumIntPreference(OsmandApplication app, String prefId, Enum defaultValue, Enum[] values, Class clz) { - OsmandSettings.CommonPreference preference = app.getSettings().registerEnumIntPreference(prefId, defaultValue, values, clz); + protected CommonPreference registerEnumIntPreference(OsmandApplication app, String prefId, Enum defaultValue, Enum[] values, Class clz) { + CommonPreference preference = app.getSettings().registerEnumIntPreference(prefId, defaultValue, values, clz); pluginPreferences.add(preference); return preference; } diff --git a/OsmAnd/src/net/osmand/plus/activities/FavoritesTreeFragment.java b/OsmAnd/src/net/osmand/plus/activities/FavoritesTreeFragment.java index 71084c00e2..af1024c690 100644 --- a/OsmAnd/src/net/osmand/plus/activities/FavoritesTreeFragment.java +++ b/OsmAnd/src/net/osmand/plus/activities/FavoritesTreeFragment.java @@ -44,6 +44,7 @@ import net.osmand.plus.FavouritesDbHelper.FavoriteGroup; import net.osmand.plus.FavouritesDbHelper.FavoritesListener; import net.osmand.plus.MapMarkersHelper; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; @@ -97,7 +98,7 @@ public class FavoritesTreeFragment extends OsmandExpandableListFragment implemen private Set groupsToDelete = new LinkedHashSet<>(); private ActionMode actionMode; private Drawable arrowImageDisabled; - private HashMap> preferenceCache = new HashMap<>(); + private HashMap> preferenceCache = new HashMap<>(); private View footerView; private Location lastLocation; private float lastHeading; @@ -763,8 +764,8 @@ public class FavoritesTreeFragment extends OsmandExpandableListFragment implemen } } - private OsmandSettings.OsmandPreference getGroupExpandedPreference(String groupName) { - OsmandSettings.OsmandPreference preference = preferenceCache.get(groupName); + private OsmandPreference getGroupExpandedPreference(String groupName) { + OsmandPreference preference = preferenceCache.get(groupName); if (preference == null) { String groupKey = groupName + GROUP_EXPANDED_POSTFIX; preference = getSettings().registerBooleanPreference(groupKey, false); diff --git a/OsmAnd/src/net/osmand/plus/activities/MapActivity.java b/OsmAnd/src/net/osmand/plus/activities/MapActivity.java index 8a65f81d7a..5202f00c60 100644 --- a/OsmAnd/src/net/osmand/plus/activities/MapActivity.java +++ b/OsmAnd/src/net/osmand/plus/activities/MapActivity.java @@ -77,6 +77,7 @@ import net.osmand.plus.OsmAndConstants; import net.osmand.plus.OsmAndLocationSimulation; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.TargetPointsHelper; @@ -548,7 +549,7 @@ public class MapActivity extends OsmandActionBarActivity implements DownloadEven @Override public void requestPrivateAccessRouting() { if (!settings.FORCE_PRIVATE_ACCESS_ROUTING_ASKED.getModeValue(getRoutingHelper().getAppMode())) { - final OsmandSettings.CommonPreference allowPrivate + final CommonPreference allowPrivate = settings.getCustomRoutingBooleanProperty(GeneralRouter.ALLOW_PRIVATE, false); final List modes = ApplicationMode.values(app); for (ApplicationMode mode : modes) { diff --git a/OsmAnd/src/net/osmand/plus/activities/MapActivityLayers.java b/OsmAnd/src/net/osmand/plus/activities/MapActivityLayers.java index ae8af82440..5f872bc5ac 100644 --- a/OsmAnd/src/net/osmand/plus/activities/MapActivityLayers.java +++ b/OsmAnd/src/net/osmand/plus/activities/MapActivityLayers.java @@ -28,7 +28,7 @@ import net.osmand.plus.DialogListItemAdapter; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.SQLiteTileSource; import net.osmand.plus.activities.MapActivity.ShowQuickSearchMode; diff --git a/OsmAnd/src/net/osmand/plus/activities/SettingsBaseActivity.java b/OsmAnd/src/net/osmand/plus/activities/SettingsBaseActivity.java index 525b9e0d02..686627bd61 100644 --- a/OsmAnd/src/net/osmand/plus/activities/SettingsBaseActivity.java +++ b/OsmAnd/src/net/osmand/plus/activities/SettingsBaseActivity.java @@ -26,8 +26,8 @@ import net.osmand.PlatformUtil; import net.osmand.plus.ApplicationMode; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.CommonPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.profiles.AppProfileArrayAdapter; import net.osmand.plus.profiles.ProfileDataObject; diff --git a/OsmAnd/src/net/osmand/plus/activities/SettingsNavigationActivity.java b/OsmAnd/src/net/osmand/plus/activities/SettingsNavigationActivity.java index 1cdca6db8f..4ef400af38 100644 --- a/OsmAnd/src/net/osmand/plus/activities/SettingsNavigationActivity.java +++ b/OsmAnd/src/net/osmand/plus/activities/SettingsNavigationActivity.java @@ -35,9 +35,10 @@ import net.osmand.plus.ContextMenuAdapter; import net.osmand.plus.ContextMenuItem; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.OsmandSettings.AutoZoomMap; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.settings.backend.OsmandSettings.SpeedConstants; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; @@ -406,7 +407,7 @@ public class SettingsNavigationActivity extends SettingsBaseActivity { } public static boolean isRoutingParameterSelected(OsmandSettings settings, ApplicationMode am, RoutingParameter routingParameter) { - final OsmandSettings.CommonPreference property = + final CommonPreference property = settings.getCustomRoutingBooleanProperty(routingParameter.getId(), routingParameter.getDefaultBoolean()); if(am != null) { return property.getModeValue(am); @@ -416,7 +417,7 @@ public class SettingsNavigationActivity extends SettingsBaseActivity { } public static void setRoutingParameterSelected(OsmandSettings settings, ApplicationMode am, String routingParameterId, boolean defaultBoolean, boolean isChecked) { - final OsmandSettings.CommonPreference property = settings.getCustomRoutingBooleanProperty(routingParameterId, defaultBoolean); + final CommonPreference property = settings.getCustomRoutingBooleanProperty(routingParameterId, defaultBoolean); if (am != null) { property.setModeValue(am, isChecked); } else { diff --git a/OsmAnd/src/net/osmand/plus/audionotes/AudioVideoNotesPlugin.java b/OsmAnd/src/net/osmand/plus/audionotes/AudioVideoNotesPlugin.java index d8d32df458..cabbcad3ce 100644 --- a/OsmAnd/src/net/osmand/plus/audionotes/AudioVideoNotesPlugin.java +++ b/OsmAnd/src/net/osmand/plus/audionotes/AudioVideoNotesPlugin.java @@ -53,8 +53,8 @@ import net.osmand.plus.ContextMenuAdapter.ItemClickListener; import net.osmand.plus.ContextMenuItem; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.CommonPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.MapActivity; diff --git a/OsmAnd/src/net/osmand/plus/audionotes/SortByMenuBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/audionotes/SortByMenuBottomSheetDialogFragment.java index de1208a735..2e228874b0 100644 --- a/OsmAnd/src/net/osmand/plus/audionotes/SortByMenuBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/audionotes/SortByMenuBottomSheetDialogFragment.java @@ -3,7 +3,7 @@ package net.osmand.plus.audionotes; import android.os.Bundle; import android.view.View; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings.NotesSortByMode; import net.osmand.plus.R; import net.osmand.plus.base.MenuBottomSheetDialogFragment; @@ -53,7 +53,7 @@ public class SortByMenuBottomSheetDialogFragment extends MenuBottomSheetDialogFr } private void selectSortByMode(NotesSortByMode mode) { - final OsmandSettings.CommonPreference sortByMode = getMyApplication().getSettings().NOTES_SORT_BY_MODE; + final CommonPreference sortByMode = getMyApplication().getSettings().NOTES_SORT_BY_MODE; if (sortByMode.get() != mode) { sortByMode.set(mode); if (listener != null) { diff --git a/OsmAnd/src/net/osmand/plus/chooseplan/OsmLiveCancelledDialog.java b/OsmAnd/src/net/osmand/plus/chooseplan/OsmLiveCancelledDialog.java index 788b605eec..76c5ca0823 100644 --- a/OsmAnd/src/net/osmand/plus/chooseplan/OsmLiveCancelledDialog.java +++ b/OsmAnd/src/net/osmand/plus/chooseplan/OsmLiveCancelledDialog.java @@ -24,7 +24,7 @@ import androidx.fragment.app.FragmentManager; import net.osmand.PlatformUtil; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.base.BaseOsmAndDialogFragment; diff --git a/OsmAnd/src/net/osmand/plus/dashboard/tools/DashboardSettingsDialogFragment.java b/OsmAnd/src/net/osmand/plus/dashboard/tools/DashboardSettingsDialogFragment.java index 8b7e47a941..3495cadb32 100644 --- a/OsmAnd/src/net/osmand/plus/dashboard/tools/DashboardSettingsDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/dashboard/tools/DashboardSettingsDialogFragment.java @@ -25,7 +25,7 @@ import net.osmand.PlatformUtil; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.MapActivity; diff --git a/OsmAnd/src/net/osmand/plus/development/TestVoiceActivity.java b/OsmAnd/src/net/osmand/plus/development/TestVoiceActivity.java index 674b9e067d..cc1268bd3e 100644 --- a/OsmAnd/src/net/osmand/plus/development/TestVoiceActivity.java +++ b/OsmAnd/src/net/osmand/plus/development/TestVoiceActivity.java @@ -19,7 +19,7 @@ import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.activities.OsmandActionBarActivity; import net.osmand.plus.routing.data.StreetName; @@ -149,7 +149,7 @@ public class TestVoiceActivity extends OsmandActionBarActivity { v += "\n \u25CF BT SCO: The current app profile is not set to use 'Phone call audio'."; } - OsmandSettings.OsmandPreference pref = ((OsmandApplication) getApplication()).getSettings().VOICE_PROMPT_DELAY[stream]; + OsmandPreference pref = ((OsmandApplication) getApplication()).getSettings().VOICE_PROMPT_DELAY[stream]; if(pref != null) { v += "\n \u25CF Voice prompt delay for selected output: " + pref.get() + "\u00A0ms"; } @@ -288,7 +288,7 @@ public class TestVoiceActivity extends OsmandActionBarActivity { } if (description.startsWith("\u25BA (11.2)")) { int ams = ((OsmandApplication) getApplication()).getSettings().AUDIO_MANAGER_STREAM.get(); - OsmandSettings.OsmandPreference pref = ((OsmandApplication) getApplication()).getSettings().VOICE_PROMPT_DELAY[ams]; + OsmandPreference pref = ((OsmandApplication) getApplication()).getSettings().VOICE_PROMPT_DELAY[ams]; if (pref != null) { if (pref.get() >= 3000) { pref.set(0); diff --git a/OsmAnd/src/net/osmand/plus/dialogs/ConfigureMapMenu.java b/OsmAnd/src/net/osmand/plus/dialogs/ConfigureMapMenu.java index 4c3378c77e..69ab2273c0 100644 --- a/OsmAnd/src/net/osmand/plus/dialogs/ConfigureMapMenu.java +++ b/OsmAnd/src/net/osmand/plus/dialogs/ConfigureMapMenu.java @@ -37,9 +37,10 @@ import net.osmand.plus.DialogListItemAdapter; import net.osmand.plus.GpxSelectionHelper; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.ListStringPreference; +import net.osmand.plus.settings.backend.CommonPreference; +import net.osmand.plus.settings.backend.ListStringPreference; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.MapActivity; @@ -571,7 +572,7 @@ public class ConfigureMapMenu { public boolean onContextMenuClick(final ArrayAdapter ad, int itemId, final int pos, boolean isChecked, int[] viewCoordinates) { final OsmandMapTileView view = activity.getMapView(); - final OsmandSettings.OsmandPreference mapDensity = view.getSettings().MAP_DENSITY; + final OsmandPreference mapDensity = view.getSettings().MAP_DENSITY; AlertDialog.Builder bld = new AlertDialog.Builder(new ContextThemeWrapper(view.getContext(), themeRes)); int p = (int) (mapDensity.get() * 100); final TIntArrayList tlist = new TIntArrayList(new int[]{25, 33, 50, 75, 100, 125, 150, 200, 300, 400}); @@ -858,25 +859,25 @@ public class ConfigureMapMenu { @ColorInt final int selectedProfileColor) { final List ps = new ArrayList<>(); - final List> prefs = new ArrayList<>(); + final List> prefs = new ArrayList<>(); Iterator it = customRules.iterator(); while (it.hasNext()) { RenderingRuleProperty p = it.next(); if (category.equals(p.getCategory()) && p.isBoolean()) { ps.add(p); - final OsmandSettings.CommonPreference pref = activity.getMyApplication().getSettings() + final CommonPreference pref = activity.getMyApplication().getSettings() .getCustomRenderBooleanProperty(p.getAttrName()); prefs.add(pref); it.remove(); } } if (prefs.size() > 0) { - final List> includedPrefs = new ArrayList<>(); + final List> includedPrefs = new ArrayList<>(); if (customRulesIncluded != null) { for (RenderingRuleProperty p : customRulesIncluded) { if (!p.isBoolean()) { - final OsmandSettings.CommonPreference pref = activity.getMyApplication().getSettings() + final CommonPreference pref = activity.getMyApplication().getSettings() .getCustomRenderProperty(p.getAttrName()); includedPrefs.add(pref); } @@ -914,14 +915,14 @@ public class ConfigureMapMenu { .setId(id) .setIcon(icon).setListener(clickListener); boolean selected = false; - for (OsmandSettings.CommonPreference p : prefs) { + for (CommonPreference p : prefs) { if (p.get()) { selected = true; break; } } if (!selected && includedPrefs.size() > 0) { - for (OsmandSettings.CommonPreference p : includedPrefs) { + for (CommonPreference p : includedPrefs) { if (!Algorithms.isEmpty(p.get())) { selected = true; break; @@ -958,17 +959,17 @@ public class ConfigureMapMenu { return null; } - protected String getDescription(final List> prefs, - final List> includedPrefs) { + protected String getDescription(final List> prefs, + final List> includedPrefs) { int count = 0; int enabled = 0; - for (OsmandSettings.CommonPreference p : prefs) { + for (CommonPreference p : prefs) { count++; if (p.get()) { enabled++; } } - for (OsmandSettings.CommonPreference p : includedPrefs) { + for (CommonPreference p : includedPrefs) { count++; if (!Algorithms.isEmpty(p.get())) { enabled++; @@ -1039,11 +1040,11 @@ public class ConfigureMapMenu { prefs.get(i).set(tempPrefs[i]); selected |= tempPrefs[i]; } - final List> includedPrefs = new ArrayList<>(); + final List> includedPrefs = new ArrayList<>(); if (customRulesIncluded != null) { for (RenderingRuleProperty p : customRulesIncluded) { if (p.getAttrName().equals(HIKING_ROUTES_OSMC_ATTR)) { - final OsmandSettings.CommonPreference pref = activity.getMyApplication().getSettings() + final CommonPreference pref = activity.getMyApplication().getSettings() .getCustomRenderProperty(p.getAttrName()); includedPrefs.add(pref); if (hikingRouteOSMCValue == 0) { @@ -1077,7 +1078,7 @@ public class ConfigureMapMenu { if (customRulesIncluded != null) { for (RenderingRuleProperty p : customRulesIncluded) { if (!p.isBoolean()) { - final OsmandSettings.CommonPreference pref = activity.getMyApplication().getSettings() + final CommonPreference pref = activity.getMyApplication().getSettings() .getCustomRenderProperty(p.getAttrName()); View spinnerView = View.inflate(new ContextThemeWrapper(activity, themeRes), R.layout.spinner_rule_layout, null); @@ -1214,7 +1215,7 @@ public class ConfigureMapMenu { final String propertyDescr = SettingsActivity.getStringPropertyDescription(view.getContext(), p.getAttrName(), p.getName()); if (p.isBoolean()) { - final OsmandSettings.CommonPreference pref = view.getApplication().getSettings() + final CommonPreference pref = view.getApplication().getSettings() .getCustomRenderBooleanProperty(p.getAttrName()); return ContextMenuItem.createBuilder(propertyName) .setId(id) @@ -1230,7 +1231,7 @@ public class ConfigureMapMenu { .setSelected(pref.get()) .createItem(); } else { - final OsmandSettings.CommonPreference pref = view.getApplication().getSettings() + final CommonPreference pref = view.getApplication().getSettings() .getCustomRenderProperty(p.getAttrName()); final String descr; if (!Algorithms.isEmpty(pref.get())) { diff --git a/OsmAnd/src/net/osmand/plus/dialogs/RasterMapMenu.java b/OsmAnd/src/net/osmand/plus/dialogs/RasterMapMenu.java index 44d50db194..f62f16016c 100644 --- a/OsmAnd/src/net/osmand/plus/dialogs/RasterMapMenu.java +++ b/OsmAnd/src/net/osmand/plus/dialogs/RasterMapMenu.java @@ -10,6 +10,7 @@ import net.osmand.plus.ContextMenuAdapter; import net.osmand.plus.ContextMenuItem; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.OsmandSettings.LayerTransparencySeekbarMode; import net.osmand.plus.R; @@ -39,9 +40,9 @@ public class RasterMapMenu { final OsmandSettings settings = app.getSettings(); final OsmandRasterMapsPlugin plugin = OsmandPlugin.getEnabledPlugin(OsmandRasterMapsPlugin.class); assert plugin != null; - final OsmandSettings.CommonPreference mapTransparencyPreference; - final OsmandSettings.CommonPreference mapTypePreference; - final OsmandSettings.CommonPreference exMapTypePreference; + final CommonPreference mapTransparencyPreference; + final CommonPreference mapTypePreference; + final CommonPreference exMapTypePreference; final LayerTransparencySeekbarMode currentMapTypeSeekbarMode = type == RasterMapType.OVERLAY ? LayerTransparencySeekbarMode.OVERLAY : LayerTransparencySeekbarMode.UNDERLAY; @StringRes final int mapTypeString; @@ -62,7 +63,7 @@ public class RasterMapMenu { throw new RuntimeException("Unexpected raster map type"); } - final OsmandSettings.CommonPreference hidePolygonsPref = + final CommonPreference hidePolygonsPref = mapActivity.getMyApplication().getSettings().getCustomRenderBooleanProperty("noPolygons"); String mapTypeDescr = mapTypePreference.get(); diff --git a/OsmAnd/src/net/osmand/plus/dialogs/SendAnalyticsBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/dialogs/SendAnalyticsBottomSheetDialogFragment.java index f84ac5239e..983315c503 100644 --- a/OsmAnd/src/net/osmand/plus/dialogs/SendAnalyticsBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/dialogs/SendAnalyticsBottomSheetDialogFragment.java @@ -19,7 +19,7 @@ import androidx.fragment.app.FragmentManager; import net.osmand.PlatformUtil; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.base.MenuBottomSheetDialogFragment; import net.osmand.plus.base.bottomsheetmenu.BottomSheetItemWithCompoundButton; diff --git a/OsmAnd/src/net/osmand/plus/download/DownloadIndexesThread.java b/OsmAnd/src/net/osmand/plus/download/DownloadIndexesThread.java index 4b0dd632aa..80ce6cfb27 100644 --- a/OsmAnd/src/net/osmand/plus/download/DownloadIndexesThread.java +++ b/OsmAnd/src/net/osmand/plus/download/DownloadIndexesThread.java @@ -22,7 +22,7 @@ import net.osmand.map.WorldRegion; import net.osmand.map.WorldRegion.RegionParams; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.Version; import net.osmand.plus.base.BasicProgressAsyncTask; diff --git a/OsmAnd/src/net/osmand/plus/helpers/GpxUiHelper.java b/OsmAnd/src/net/osmand/plus/helpers/GpxUiHelper.java index 356f8c9870..443f42922f 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/GpxUiHelper.java +++ b/OsmAnd/src/net/osmand/plus/helpers/GpxUiHelper.java @@ -80,6 +80,7 @@ import net.osmand.plus.OsmAndConstants; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; @@ -513,9 +514,9 @@ public class GpxUiHelper { } else { final View apprTitleView = View.inflate(new ContextThemeWrapper(activity, themeRes), R.layout.select_gpx_appearance_title, null); - final OsmandSettings.CommonPreference prefWidth + final CommonPreference prefWidth = app.getSettings().getCustomRenderProperty(CURRENT_TRACK_WIDTH_ATTR); - final OsmandSettings.CommonPreference prefColor + final CommonPreference prefColor = app.getSettings().getCustomRenderProperty(CURRENT_TRACK_COLOR_ATTR); updateAppearanceTitle(activity, app, trackWidthProp, renderer, apprTitleView, prefWidth.get(), prefColor.get()); @@ -567,7 +568,7 @@ public class GpxUiHelper { public void onClick(DialogInterface dialog, int which) { if (gpxAppearanceParams.size() > 0) { for (Map.Entry entry : gpxAppearanceParams.entrySet()) { - final OsmandSettings.CommonPreference pref + final CommonPreference pref = app.getSettings().getCustomRenderProperty(entry.getKey()); pref.set(entry.getValue()); } diff --git a/OsmAnd/src/net/osmand/plus/helpers/LockHelper.java b/OsmAnd/src/net/osmand/plus/helpers/LockHelper.java index 34d31e1489..1d4faa4304 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/LockHelper.java +++ b/OsmAnd/src/net/osmand/plus/helpers/LockHelper.java @@ -17,7 +17,7 @@ import androidx.annotation.Nullable; import net.osmand.plus.OsmAndAppCustomization.OsmAndAppCustomizationListener; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.routing.VoiceRouter.VoiceMessageListener; import java.util.List; diff --git a/OsmAnd/src/net/osmand/plus/inapp/InAppPurchaseHelper.java b/OsmAnd/src/net/osmand/plus/inapp/InAppPurchaseHelper.java index 2fe36e624d..baa7c140f0 100644 --- a/OsmAnd/src/net/osmand/plus/inapp/InAppPurchaseHelper.java +++ b/OsmAnd/src/net/osmand/plus/inapp/InAppPurchaseHelper.java @@ -23,7 +23,7 @@ import net.osmand.AndroidNetworkUtils.RequestResponse; import net.osmand.PlatformUtil; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.Version; import net.osmand.plus.inapp.InAppPurchases.InAppPurchase; diff --git a/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesFragment.java b/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesFragment.java index f96ebf4ff6..a4cff566d2 100644 --- a/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesFragment.java +++ b/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesFragment.java @@ -35,6 +35,7 @@ import androidx.fragment.app.FragmentManager; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.Version; @@ -312,7 +313,7 @@ public class LiveUpdatesFragment extends BaseOsmAndFragment implements InAppPurc } public void add(LocalIndexInfo info) { - OsmandSettings.CommonPreference preference = preferenceLiveUpdatesOn( + CommonPreference preference = preferenceLiveUpdatesOn( info.getFileName(), getSettings()); if (preference.get()) { dataShouldUpdate.add(info); @@ -324,7 +325,7 @@ public class LiveUpdatesFragment extends BaseOsmAndFragment implements InAppPurc public void notifyLiveUpdatesChanged() { Set changedSet = new HashSet<>(); for (LocalIndexInfo localIndexInfo : dataShouldUpdate) { - OsmandSettings.CommonPreference preference = + CommonPreference preference = preferenceLiveUpdatesOn(localIndexInfo.getFileName(), getSettings()); if (!preference.get()) { changedSet.add(localIndexInfo); @@ -334,7 +335,7 @@ public class LiveUpdatesFragment extends BaseOsmAndFragment implements InAppPurc dataShouldNotUpdate.addAll(changedSet); changedSet.clear(); for (LocalIndexInfo localIndexInfo : dataShouldNotUpdate) { - OsmandSettings.CommonPreference preference = + CommonPreference preference = preferenceLiveUpdatesOn(localIndexInfo.getFileName(), getSettings()); if (preference.get()) { changedSet.add(localIndexInfo); @@ -475,9 +476,9 @@ public class LiveUpdatesFragment extends BaseOsmAndFragment implements InAppPurc PendingIntent alarmIntent = getPendingIntent(getActivity(), fileName); if (enable) { - final OsmandSettings.CommonPreference updateFrequencyPreference = + final CommonPreference updateFrequencyPreference = preferenceUpdateFrequency(fileName, getSettings()); - final OsmandSettings.CommonPreference timeOfDayPreference = + final CommonPreference timeOfDayPreference = preferenceTimeOfDayToUpdate(fileName, getSettings()); UpdateFrequency updateFrequency = UpdateFrequency.values()[updateFrequencyPreference.get()]; TimeOfDay timeOfDayToUpdate = TimeOfDay.values()[timeOfDayPreference.get()]; @@ -572,7 +573,7 @@ public class LiveUpdatesFragment extends BaseOsmAndFragment implements InAppPurc public void bindLocalIndexInfo(@NonNull final String item, boolean isLastChild) { OsmandApplication context = fragment.getMyActivity().getMyApplication(); - final OsmandSettings.CommonPreference shouldUpdatePreference = + final CommonPreference shouldUpdatePreference = preferenceLiveUpdatesOn(item, fragment.getSettings()); IncrementalChangesManager changesManager = context.getResourceManager().getChangesManager(); @@ -602,7 +603,7 @@ public class LiveUpdatesFragment extends BaseOsmAndFragment implements InAppPurc Algorithms.getFileNameWithoutExtension(new File(item)); final long timestamp = changesManager.getTimestamp(fileNameWithoutExtension); final long lastCheck = preferenceLastCheck(item, fragment.getSettings()).get(); - OsmandSettings.CommonPreference liveUpdateOn = preferenceLiveUpdatesOn(item, fragment.getSettings()); + CommonPreference liveUpdateOn = preferenceLiveUpdatesOn(item, fragment.getSettings()); if(liveUpdateOn.get() && lastCheck != DEFAULT_LAST_CHECK) { String lastCheckString = formatDateTime(fragment.getActivity(), lastCheck ); descriptionTextView.setText(context.getString(R.string.last_update, lastCheckString)); diff --git a/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesHelper.java b/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesHelper.java index ec4afd6861..ce9d3d9c5b 100644 --- a/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesHelper.java +++ b/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesHelper.java @@ -8,6 +8,7 @@ import android.os.AsyncTask; import androidx.annotation.NonNull; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.activities.OsmandActionBarActivity; @@ -32,7 +33,7 @@ public class LiveUpdatesHelper { public static final int DEFAULT_LAST_CHECK = -1; - private static OsmandSettings.CommonPreference checkPref(OsmandSettings.CommonPreference p) { + private static CommonPreference checkPref(CommonPreference p) { if (p.isSet()) { T vl = p.get(); p = p.makeGlobal(); @@ -44,37 +45,37 @@ public class LiveUpdatesHelper { } return p; } - public static OsmandSettings.CommonPreference preferenceForLocalIndex( + public static CommonPreference preferenceForLocalIndex( String fileName, OsmandSettings settings) { final String settingId = fileName + LIVE_UPDATES_ON_POSTFIX; return checkPref(settings.registerBooleanPreference(settingId, false)); } - public static OsmandSettings.CommonPreference preferenceLiveUpdatesOn( + public static CommonPreference preferenceLiveUpdatesOn( String fileName, OsmandSettings settings) { final String settingId = fileName + LIVE_UPDATES_ON_POSTFIX; return checkPref(settings.registerBooleanPreference(settingId, false)); } - public static OsmandSettings.CommonPreference preferenceDownloadViaWiFi( + public static CommonPreference preferenceDownloadViaWiFi( String fileName, OsmandSettings settings) { final String settingId = fileName + DOWNLOAD_VIA_WIFI_POSTFIX; return checkPref(settings.registerBooleanPreference(settingId, false)); } - public static OsmandSettings.CommonPreference preferenceUpdateFrequency( + public static CommonPreference preferenceUpdateFrequency( String fileName, OsmandSettings settings) { final String settingId = fileName + UPDATE_TIMES_POSTFIX; return checkPref(settings.registerIntPreference(settingId, UpdateFrequency.HOURLY.ordinal())); } - public static OsmandSettings.CommonPreference preferenceTimeOfDayToUpdate( + public static CommonPreference preferenceTimeOfDayToUpdate( String fileName, OsmandSettings settings) { final String settingId = fileName + TIME_OF_DAY_TO_UPDATE_POSTFIX; return checkPref(settings.registerIntPreference(settingId, TimeOfDay.NIGHT.ordinal())); } - public static OsmandSettings.CommonPreference preferenceLastCheck( + public static CommonPreference preferenceLastCheck( String fileName, OsmandSettings settings) { final String settingId = fileName + LAST_UPDATE_ATTEMPT_ON_POSTFIX; return checkPref(settings.registerLongPreference(settingId, DEFAULT_LAST_CHECK)); diff --git a/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesSettingsDialogFragment.java b/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesSettingsDialogFragment.java index d3f8f2ed4e..d27e733d7a 100644 --- a/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesSettingsDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesSettingsDialogFragment.java @@ -23,6 +23,7 @@ import androidx.fragment.app.DialogFragment; import net.osmand.AndroidUtils; import net.osmand.PlatformUtil; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.download.AbstractDownloadActivity; @@ -85,7 +86,7 @@ public class LiveUpdatesSettingsDialogFragment extends DialogFragment { final long lastCheck = preferenceLastCheck(fileName, getSettings()).get(); - OsmandSettings.CommonPreference preference = preferenceLiveUpdatesOn(fileName, + CommonPreference preference = preferenceLiveUpdatesOn(fileName, getSettings()); if (preference.get() && lastCheck != DEFAULT_LAST_CHECK) { String lastCheckString = formatDateTime(getActivity(), lastCheck); @@ -94,13 +95,13 @@ public class LiveUpdatesSettingsDialogFragment extends DialogFragment { lastUpdateTextView.setVisibility(View.GONE); } - final OsmandSettings.CommonPreference liveUpdatePreference = + final CommonPreference liveUpdatePreference = preferenceForLocalIndex(fileName, getSettings()); - final OsmandSettings.CommonPreference downloadViaWiFiPreference = + final CommonPreference downloadViaWiFiPreference = preferenceDownloadViaWiFi(fileName, getSettings()); - final OsmandSettings.CommonPreference updateFrequencyPreference = + final CommonPreference updateFrequencyPreference = preferenceUpdateFrequency(fileName, getSettings()); - final OsmandSettings.CommonPreference timeOfDayPreference = + final CommonPreference timeOfDayPreference = preferenceTimeOfDayToUpdate(fileName, getSettings()); downloadOverWiFiCheckBox.setChecked(!liveUpdatePreference.get() || downloadViaWiFiPreference.get()); diff --git a/OsmAnd/src/net/osmand/plus/liveupdates/PerformLiveUpdateAsyncTask.java b/OsmAnd/src/net/osmand/plus/liveupdates/PerformLiveUpdateAsyncTask.java index c95ac1a2a6..4cebb245f9 100644 --- a/OsmAnd/src/net/osmand/plus/liveupdates/PerformLiveUpdateAsyncTask.java +++ b/OsmAnd/src/net/osmand/plus/liveupdates/PerformLiveUpdateAsyncTask.java @@ -9,6 +9,7 @@ import androidx.annotation.NonNull; import net.osmand.PlatformUtil; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.download.AbstractDownloadActivity; @@ -50,7 +51,7 @@ public class PerformLiveUpdateAsyncTask activity.setSupportProgressBarIndeterminateVisibility(true); } final OsmandApplication myApplication = getMyApplication(); - OsmandSettings.CommonPreference lastCheckPreference = + CommonPreference lastCheckPreference = LiveUpdatesHelper.preferenceLastCheck(localIndexFileName, myApplication.getSettings()); lastCheckPreference.set(System.currentTimeMillis()); } @@ -148,7 +149,7 @@ public class PerformLiveUpdateAsyncTask public static void tryRescheduleDownload(@NonNull Context context, @NonNull OsmandSettings settings, @NonNull String localIndexFileName) { - final OsmandSettings.CommonPreference updateFrequencyPreference = + final CommonPreference updateFrequencyPreference = preferenceUpdateFrequency(localIndexFileName, settings); final Integer frequencyOrdinal = updateFrequencyPreference.get(); if (LiveUpdatesHelper.UpdateFrequency.values()[frequencyOrdinal] diff --git a/OsmAnd/src/net/osmand/plus/mapcontextmenu/CollapsableView.java b/OsmAnd/src/net/osmand/plus/mapcontextmenu/CollapsableView.java index 5daa14ba27..394547f570 100644 --- a/OsmAnd/src/net/osmand/plus/mapcontextmenu/CollapsableView.java +++ b/OsmAnd/src/net/osmand/plus/mapcontextmenu/CollapsableView.java @@ -4,7 +4,7 @@ import android.view.View; import androidx.annotation.NonNull; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.mapcontextmenu.MenuBuilder.CollapseExpandListener; public class CollapsableView { diff --git a/OsmAnd/src/net/osmand/plus/mapcontextmenu/MapContextMenuFragment.java b/OsmAnd/src/net/osmand/plus/mapcontextmenu/MapContextMenuFragment.java index 99da51fc51..1bfa41fc13 100644 --- a/OsmAnd/src/net/osmand/plus/mapcontextmenu/MapContextMenuFragment.java +++ b/OsmAnd/src/net/osmand/plus/mapcontextmenu/MapContextMenuFragment.java @@ -57,6 +57,7 @@ import net.osmand.plus.ContextMenuItem; import net.osmand.plus.LockableScrollView; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.settings.backend.MainContextMenuItemsSettings; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; @@ -569,7 +570,7 @@ public class MapContextMenuFragment extends BaseOsmAndFragment implements Downlo // Action buttons ContextMenuAdapter adapter = menu.getActionsContextMenuAdapter(false); List items = adapter.getVisibleItems(); - List mainIds = ((OsmandSettings.MainContextMenuItemsSettings) app.getSettings().CONTEXT_MENU_ACTIONS_ITEMS.get()).getMainIds(); + List mainIds = ((MainContextMenuItemsSettings) app.getSettings().CONTEXT_MENU_ACTIONS_ITEMS.get()).getMainIds(); ContextMenuAdapter mainAdapter = new ContextMenuAdapter(requireMyApplication()); ContextMenuAdapter additionalAdapter = new ContextMenuAdapter(requireMyApplication()); diff --git a/OsmAnd/src/net/osmand/plus/mapcontextmenu/controllers/MapMarkerMenuController.java b/OsmAnd/src/net/osmand/plus/mapcontextmenu/controllers/MapMarkerMenuController.java index 5641f125ec..f0061440ad 100644 --- a/OsmAnd/src/net/osmand/plus/mapcontextmenu/controllers/MapMarkerMenuController.java +++ b/OsmAnd/src/net/osmand/plus/mapcontextmenu/controllers/MapMarkerMenuController.java @@ -13,7 +13,7 @@ import androidx.core.content.ContextCompat; import net.osmand.data.PointDescription; import net.osmand.plus.MapMarkersHelper; import net.osmand.plus.MapMarkersHelper.MapMarker; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.helpers.MapMarkerDialogHelper; @@ -56,7 +56,7 @@ public class MapMarkerMenuController extends MenuController { public void buttonPressed() { MapActivity activity = getMapActivity(); if (activity != null) { - OsmandSettings.OsmandPreference indication + OsmandPreference indication = activity.getMyApplication().getSettings().MARKERS_DISTANCE_INDICATION_ENABLED; if (!indication.get()) { indication.set(true); diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/CoordinateInputBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/mapmarkers/CoordinateInputBottomSheetDialogFragment.java index cf769223f1..f3bf7cfb7a 100644 --- a/OsmAnd/src/net/osmand/plus/mapmarkers/CoordinateInputBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/CoordinateInputBottomSheetDialogFragment.java @@ -6,6 +6,7 @@ import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.View; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.base.MenuBottomSheetDialogFragment; @@ -83,7 +84,7 @@ public class CoordinateInputBottomSheetDialogFragment extends MenuBottomSheetDia @Override public void onClick(View v) { if (listener != null) { - OsmandSettings.CommonPreference pref = settings.COORDS_INPUT_TWO_DIGITS_LONGTITUDE; + CommonPreference pref = settings.COORDS_INPUT_TWO_DIGITS_LONGTITUDE; pref.set(!pref.get()); listener.onInputSettingsChanged(); } @@ -108,7 +109,7 @@ public class CoordinateInputBottomSheetDialogFragment extends MenuBottomSheetDia @Override public void onClick(View v) { if (listener != null) { - OsmandSettings.CommonPreference pref = settings.COORDS_INPUT_USE_RIGHT_SIDE; + CommonPreference pref = settings.COORDS_INPUT_USE_RIGHT_SIDE; pref.set(!pref.get()); listener.onHandChanged(); } diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/CoordinateInputDialogFragment.java b/OsmAnd/src/net/osmand/plus/mapmarkers/CoordinateInputDialogFragment.java index 2059bcf25e..4cef32026c 100644 --- a/OsmAnd/src/net/osmand/plus/mapmarkers/CoordinateInputDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/CoordinateInputDialogFragment.java @@ -66,7 +66,7 @@ import net.osmand.plus.MapMarkersHelper; import net.osmand.plus.OsmAndLocationProvider.OsmAndCompassListener; import net.osmand.plus.OsmAndLocationProvider.OsmAndLocationListener; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.Version; @@ -1020,7 +1020,7 @@ public class CoordinateInputDialogFragment extends DialogFragment implements Osm } private void changeOsmandKeyboardSetting() { - OsmandSettings.OsmandPreference pref = getMyApplication().getSettings().COORDS_INPUT_USE_OSMAND_KEYBOARD; + OsmandPreference pref = getMyApplication().getSettings().COORDS_INPUT_USE_OSMAND_KEYBOARD; pref.set(!pref.get()); } diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/DirectionIndicationDialogFragment.java b/OsmAnd/src/net/osmand/plus/mapmarkers/DirectionIndicationDialogFragment.java index ee5a632281..292da8aa8b 100644 --- a/OsmAnd/src/net/osmand/plus/mapmarkers/DirectionIndicationDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/DirectionIndicationDialogFragment.java @@ -33,7 +33,7 @@ import net.osmand.AndroidUtils; import net.osmand.plus.ApplicationMode; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.OsmandSettings.MapMarkersMode; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.MapActivity; diff --git a/OsmAnd/src/net/osmand/plus/monitoring/MonitoringSettingsFragment.java b/OsmAnd/src/net/osmand/plus/monitoring/MonitoringSettingsFragment.java index 5a0a21f0e9..2efe004611 100644 --- a/OsmAnd/src/net/osmand/plus/monitoring/MonitoringSettingsFragment.java +++ b/OsmAnd/src/net/osmand/plus/monitoring/MonitoringSettingsFragment.java @@ -13,7 +13,8 @@ import androidx.preference.Preference; import net.osmand.plus.ApplicationMode; import net.osmand.plus.OsmAndAppCustomization; import net.osmand.plus.OsmandPlugin; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.CommonPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.helpers.FontCache; @@ -288,11 +289,11 @@ public class MonitoringSettingsFragment extends BaseSettingsFragment @Override public void onApplyPreferenceChange(String prefId, boolean applyToAllProfiles, Object newValue) { if (SAVE_GLOBAL_TRACK_INTERVAL.equals(prefId)) { - OsmandSettings.OsmandPreference pref = settings.getPreference(prefId); + OsmandPreference pref = settings.getPreference(prefId); if (newValue instanceof Boolean) { applyPreference(settings.SAVE_GLOBAL_TRACK_REMEMBER.getId(), applyToAllProfiles, false); - } else if (pref instanceof OsmandSettings.CommonPreference - && !((OsmandSettings.CommonPreference) pref).hasDefaultValueForMode(getSelectedAppMode())) { + } else if (pref instanceof CommonPreference + && !((CommonPreference) pref).hasDefaultValueForMode(getSelectedAppMode())) { applyPreference(SAVE_GLOBAL_TRACK_INTERVAL, applyToAllProfiles, newValue); applyPreference(settings.SAVE_GLOBAL_TRACK_REMEMBER.getId(), applyToAllProfiles, true); } diff --git a/OsmAnd/src/net/osmand/plus/myplaces/TrackActivityFragmentAdapter.java b/OsmAnd/src/net/osmand/plus/myplaces/TrackActivityFragmentAdapter.java index 25d9d7450a..d45804b496 100644 --- a/OsmAnd/src/net/osmand/plus/myplaces/TrackActivityFragmentAdapter.java +++ b/OsmAnd/src/net/osmand/plus/myplaces/TrackActivityFragmentAdapter.java @@ -49,6 +49,7 @@ import net.osmand.plus.GpxSelectionHelper.GpxDisplayItemType; import net.osmand.plus.GpxSelectionHelper.SelectedGpxFile; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; @@ -760,7 +761,7 @@ public class TrackActivityFragmentAdapter implements TrackBitmapDrawerListener { } if (color == 0) { final RenderingRulesStorage renderer = app.getRendererRegistry().getCurrentSelectedRenderer(); - final OsmandSettings.CommonPreference prefColor + final CommonPreference prefColor = app.getSettings().getCustomRenderProperty(CURRENT_TRACK_COLOR_ATTR); color = ConfigureMapMenu.GpxAppearanceAdapter.parseTrackColor(renderer, prefColor.get()); } diff --git a/OsmAnd/src/net/osmand/plus/osmedit/OsmEditingPlugin.java b/OsmAnd/src/net/osmand/plus/osmedit/OsmEditingPlugin.java index 157188fbb1..abab2339d9 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/OsmEditingPlugin.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/OsmEditingPlugin.java @@ -30,6 +30,7 @@ import net.osmand.plus.ContextMenuAdapter.ItemClickListener; import net.osmand.plus.ContextMenuItem; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.activities.EnumAdapter; @@ -355,7 +356,7 @@ public class OsmEditingPlugin extends OsmandPlugin { @Override public boolean onContextMenuClick(ArrayAdapter adapter, int itemId, int pos, boolean isChecked, int[] viewCoordinates) { if (itemId == R.string.layer_osm_bugs) { - OsmandSettings.OsmandPreference showOsmBugs = settings.SHOW_OSM_BUGS; + OsmandPreference showOsmBugs = settings.SHOW_OSM_BUGS; showOsmBugs.set(isChecked); adapter.getItem(pos).setColorRes(showOsmBugs.get() ? R.color.osmand_orange : ContextMenuItem.INVALID_ID); @@ -378,7 +379,7 @@ public class OsmEditingPlugin extends OsmandPlugin { @Override public boolean onContextMenuClick(ArrayAdapter adapter, int itemId, int pos, boolean isChecked, int[] viewCoordinates) { if (itemId == R.string.layer_osm_edits) { - OsmandSettings.OsmandPreference showOsmEdits = settings.SHOW_OSM_EDITS; + OsmandPreference showOsmEdits = settings.SHOW_OSM_EDITS; showOsmEdits.set(isChecked); adapter.getItem(pos).setColorRes(showOsmEdits.get() ? R.color.osmand_orange : ContextMenuItem.INVALID_ID); adapter.notifyDataSetChanged(); diff --git a/OsmAnd/src/net/osmand/plus/osmedit/OsmNotesMenu.java b/OsmAnd/src/net/osmand/plus/osmedit/OsmNotesMenu.java index 65a2dfe3ee..0eefb8b51a 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/OsmNotesMenu.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/OsmNotesMenu.java @@ -14,8 +14,8 @@ import net.osmand.plus.DialogListItemAdapter; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.CommonPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; diff --git a/OsmAnd/src/net/osmand/plus/parkingpoint/ParkingPositionPlugin.java b/OsmAnd/src/net/osmand/plus/parkingpoint/ParkingPositionPlugin.java index c0461e6931..1521d70352 100644 --- a/OsmAnd/src/net/osmand/plus/parkingpoint/ParkingPositionPlugin.java +++ b/OsmAnd/src/net/osmand/plus/parkingpoint/ParkingPositionPlugin.java @@ -29,7 +29,7 @@ import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.MapActivity; diff --git a/OsmAnd/src/net/osmand/plus/rastermaps/MapUnderlayAction.java b/OsmAnd/src/net/osmand/plus/rastermaps/MapUnderlayAction.java index 12f6f909cf..d938174c1f 100644 --- a/OsmAnd/src/net/osmand/plus/rastermaps/MapUnderlayAction.java +++ b/OsmAnd/src/net/osmand/plus/rastermaps/MapUnderlayAction.java @@ -15,6 +15,7 @@ import com.google.gson.reflect.TypeToken; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.OsmandSettings.LayerTransparencySeekbarMode; import net.osmand.plus.R; @@ -144,7 +145,7 @@ public class MapUnderlayAction extends SwitchableAction> { } - final OsmandSettings.CommonPreference hidePolygonsPref = + final CommonPreference hidePolygonsPref = activity.getMyApplication().getSettings().getCustomRenderBooleanProperty("noPolygons"); hidePolygonsPref.set(hasUnderlay); diff --git a/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java b/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java index 9194949691..02b1e8dac7 100644 --- a/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java +++ b/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java @@ -35,7 +35,7 @@ import net.osmand.plus.DialogListItemAdapter; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings.LayerTransparencySeekbarMode; import net.osmand.plus.R; import net.osmand.plus.SQLiteTileSource; @@ -626,7 +626,7 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { OsmandMapTileView mapView = mapActivity.getMapView(); CommonPreference mapTypePreference; CommonPreference exMapTypePreference; - OsmandSettings.CommonPreference mapTransparencyPreference; + CommonPreference mapTransparencyPreference; //boolean isMapSelected; MapTileLayer layer; diff --git a/OsmAnd/src/net/osmand/plus/render/MapRenderRepositories.java b/OsmAnd/src/net/osmand/plus/render/MapRenderRepositories.java index 048de5ddb9..dc68f23d0b 100644 --- a/OsmAnd/src/net/osmand/plus/render/MapRenderRepositories.java +++ b/OsmAnd/src/net/osmand/plus/render/MapRenderRepositories.java @@ -43,7 +43,7 @@ import net.osmand.plus.OsmAndAppCustomization.OsmAndAppCustomizationListener; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.development.OsmandDevelopmentPlugin; import net.osmand.plus.render.OsmandRenderer.RenderingContext; diff --git a/OsmAnd/src/net/osmand/plus/resources/RegionAddressRepositoryBinary.java b/OsmAnd/src/net/osmand/plus/resources/RegionAddressRepositoryBinary.java index 6da4f7ecab..702028d851 100644 --- a/OsmAnd/src/net/osmand/plus/resources/RegionAddressRepositoryBinary.java +++ b/OsmAnd/src/net/osmand/plus/resources/RegionAddressRepositoryBinary.java @@ -18,7 +18,7 @@ import net.osmand.data.MapObject; import net.osmand.data.QuadRect; import net.osmand.data.QuadTree; import net.osmand.data.Street; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.resources.ResourceManager.BinaryMapReaderResource; import net.osmand.plus.resources.ResourceManager.BinaryMapReaderResourceType; import net.osmand.util.MapUtils; diff --git a/OsmAnd/src/net/osmand/plus/routepreparationmenu/AvoidRoadsBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/routepreparationmenu/AvoidRoadsBottomSheetDialogFragment.java index 9d7a8f3ab1..78773b5171 100644 --- a/OsmAnd/src/net/osmand/plus/routepreparationmenu/AvoidRoadsBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/routepreparationmenu/AvoidRoadsBottomSheetDialogFragment.java @@ -20,7 +20,7 @@ import androidx.fragment.app.Fragment; import net.osmand.AndroidUtils; import net.osmand.data.LatLon; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.MapActivity; @@ -292,7 +292,7 @@ public class AvoidRoadsBottomSheetDialogFragment extends MenuBottomSheetDialogFr GeneralRouter.RoutingParameter parameter = routingOptionsHelper.getRoutingPrefsForAppModeById(app.getRoutingHelper().getAppMode(), parameterId); if (parameter != null) { boolean checked = entry.getValue(); - OsmandSettings.CommonPreference preference = app.getSettings().getCustomRoutingBooleanProperty(parameter.getId(), parameter.getDefaultBoolean()); + CommonPreference preference = app.getSettings().getCustomRoutingBooleanProperty(parameter.getId(), parameter.getDefaultBoolean()); preference.setModeValue(app.getRoutingHelper().getAppMode(), checked); } } @@ -318,7 +318,7 @@ public class AvoidRoadsBottomSheetDialogFragment extends MenuBottomSheetDialogFr List avoidParameters = routingOptionsHelper.getAvoidRoutingPrefsForAppMode(app.getRoutingHelper().getAppMode()); for (GeneralRouter.RoutingParameter parameter : avoidParameters) { - OsmandSettings.CommonPreference preference = app.getSettings().getCustomRoutingBooleanProperty(parameter.getId(), parameter.getDefaultBoolean()); + CommonPreference preference = app.getSettings().getCustomRoutingBooleanProperty(parameter.getId(), parameter.getDefaultBoolean()); res.put(parameter.getId(), preference.getModeValue(app.getRoutingHelper().getAppMode())); } diff --git a/OsmAnd/src/net/osmand/plus/routepreparationmenu/MapRouteInfoMenu.java b/OsmAnd/src/net/osmand/plus/routepreparationmenu/MapRouteInfoMenu.java index 8ffcc49b10..f36fc056e7 100644 --- a/OsmAnd/src/net/osmand/plus/routepreparationmenu/MapRouteInfoMenu.java +++ b/OsmAnd/src/net/osmand/plus/routepreparationmenu/MapRouteInfoMenu.java @@ -54,8 +54,8 @@ import net.osmand.plus.MapMarkersHelper.MapMarker; import net.osmand.plus.OsmAndLocationProvider; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.CommonPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.TargetPointsHelper; import net.osmand.plus.TargetPointsHelper.TargetPoint; diff --git a/OsmAnd/src/net/osmand/plus/routepreparationmenu/RoutingOptionsHelper.java b/OsmAnd/src/net/osmand/plus/routepreparationmenu/RoutingOptionsHelper.java index 3fed04affc..14ab797699 100644 --- a/OsmAnd/src/net/osmand/plus/routepreparationmenu/RoutingOptionsHelper.java +++ b/OsmAnd/src/net/osmand/plus/routepreparationmenu/RoutingOptionsHelper.java @@ -26,6 +26,8 @@ import net.osmand.plus.ContextMenuAdapter; import net.osmand.plus.ContextMenuItem; import net.osmand.plus.DialogListItemAdapter; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.settings.backend.CommonPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.TargetPointsHelper; @@ -186,7 +188,7 @@ public class RoutingOptionsHelper { public void applyVoiceProvider(MapActivity mapActivity, String provider, boolean applyAllModes) { OsmandApplication app = mapActivity.getMyApplication(); ApplicationMode selectedAppMode = app.getRoutingHelper().getAppMode(); - OsmandSettings.OsmandPreference VP = app.getSettings().VOICE_PROVIDER; + OsmandPreference VP = app.getSettings().VOICE_PROVIDER; if (applyAllModes) { for (ApplicationMode mode : ApplicationMode.allPossibleValues()) { VP.setModeValue(mode, provider); @@ -662,7 +664,7 @@ public class RoutingOptionsHelper { } public boolean isSelected(OsmandSettings settings) { - final OsmandSettings.CommonPreference property = + final CommonPreference property = settings.getCustomRoutingBooleanProperty(routingParameter.getId(), routingParameter.getDefaultBoolean()); if (am != null) { return property.getModeValue(am); @@ -672,7 +674,7 @@ public class RoutingOptionsHelper { } public void setSelected(OsmandSettings settings, boolean isChecked) { - final OsmandSettings.CommonPreference property = + final CommonPreference property = settings.getCustomRoutingBooleanProperty(routingParameter.getId(), routingParameter.getDefaultBoolean()); if (am != null) { property.setModeValue(am, isChecked); diff --git a/OsmAnd/src/net/osmand/plus/routing/RouteProvider.java b/OsmAnd/src/net/osmand/plus/routing/RouteProvider.java index 2d121ccecf..eaff07dec2 100644 --- a/OsmAnd/src/net/osmand/plus/routing/RouteProvider.java +++ b/OsmAnd/src/net/osmand/plus/routing/RouteProvider.java @@ -22,7 +22,7 @@ import net.osmand.osm.io.NetworkUtils; import net.osmand.plus.ApplicationMode; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.TargetPointsHelper; import net.osmand.plus.TargetPointsHelper.TargetPoint; diff --git a/OsmAnd/src/net/osmand/plus/routing/TransportRoutingHelper.java b/OsmAnd/src/net/osmand/plus/routing/TransportRoutingHelper.java index e2f196cf48..54b159c9eb 100644 --- a/OsmAnd/src/net/osmand/plus/routing/TransportRoutingHelper.java +++ b/OsmAnd/src/net/osmand/plus/routing/TransportRoutingHelper.java @@ -16,6 +16,7 @@ import net.osmand.osm.edit.Node; import net.osmand.plus.ApplicationMode; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.render.NativeOsmandLibrary; @@ -478,7 +479,7 @@ public class TransportRoutingHelper { GeneralRouter.RoutingParameter pr = e.getValue(); String vl; if(pr.getType() == GeneralRouter.RoutingParameterType.BOOLEAN) { - OsmandSettings.CommonPreference pref = settings.getCustomRoutingBooleanProperty(key, pr.getDefaultBoolean()); + CommonPreference pref = settings.getCustomRoutingBooleanProperty(key, pr.getDefaultBoolean()); Boolean bool = pref.getModeValue(params.mode); vl = bool ? "true" : null; } else { diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/BooleanAccessibilityPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanAccessibilityPreference.java new file mode 100644 index 0000000000..7a796b6a6a --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanAccessibilityPreference.java @@ -0,0 +1,33 @@ +package net.osmand.plus.settings.backend; + +import net.osmand.plus.ApplicationMode; + +class BooleanAccessibilityPreference extends BooleanPreference { + + private OsmandSettings osmandSettings; + + BooleanAccessibilityPreference(OsmandSettings osmandSettings, String id, boolean defaultValue) { + super(id, defaultValue); + this.osmandSettings = osmandSettings; + } + + @Override + public Boolean get() { + return osmandSettings.ctx.accessibilityEnabled() ? super.get() : getDefaultValue(); + } + + @Override + public Boolean getModeValue(ApplicationMode mode) { + return osmandSettings.ctx.accessibilityEnabledForMode(mode) ? super.getModeValue(mode) : getDefaultValue(); + } + + @Override + public boolean set(Boolean obj) { + return osmandSettings.ctx.accessibilityEnabled() && super.set(obj); + } + + @Override + public boolean setModeValue(ApplicationMode mode, Boolean obj) { + return osmandSettings.ctx.accessibilityEnabledForMode(mode) && super.setModeValue(mode, obj); + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/BooleanPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanPreference.java new file mode 100644 index 0000000000..3a1c0cd363 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanPreference.java @@ -0,0 +1,23 @@ +package net.osmand.plus.settings.backend; + +public class BooleanPreference extends CommonPreference { + + BooleanPreference(OsmandSettings osmandSettings, String id, boolean defaultValue) { + super(osmandSettings, id, defaultValue); + } + + @Override + protected Boolean getValue(Object prefs, Boolean defaultValue) { + return osmandSettings.settingsAPI.getBoolean(prefs, getId(), defaultValue); + } + + @Override + protected boolean setValue(Object prefs, Boolean val) { + return osmandSettings.settingsAPI.edit(prefs).putBoolean(getId(), val).commit(); + } + + @Override + public Boolean parseString(String s) { + return Boolean.parseBoolean(s); + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java new file mode 100644 index 0000000000..4e1e69f1b4 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java @@ -0,0 +1,234 @@ +package net.osmand.plus.settings.backend; + +import net.osmand.plus.ApplicationMode; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.LinkedHashMap; +import java.util.Map; + +public abstract class CommonPreference extends PreferenceWithListener { + private OsmandSettings osmandSettings; + private final String id; + private boolean global; + private T cachedValue; + private Object cachedPreference; + private boolean cache; + private Map defaultValues; + private T defaultValue; + + + public CommonPreference(OsmandSettings osmandSettings, String id, T defaultValue) { + this.osmandSettings = osmandSettings; + this.id = id; + this.defaultValue = defaultValue; + osmandSettings.registerInternalPreference(id, this); + } + + // Methods to possibly override + protected abstract T getValue(Object prefs, T defaultValue); + + protected abstract boolean setValue(Object prefs, T val); + + public abstract T parseString(String s); + + protected String toString(T o) { + return o == null ? null : o.toString(); + } + + + // common methods + + public final CommonPreference makeGlobal() { + global = true; + return this; + } + + public final CommonPreference cache() { + cache = true; + return this; + } + + public final CommonPreference makeProfile() { + global = false; + return this; + } + + protected final Object getPreferences() { + return osmandSettings.getPreferences(global); + + } + + public final void setModeDefaultValue(ApplicationMode mode, T defValue) { + if (defaultValues == null) { + defaultValues = new LinkedHashMap(); + } + defaultValues.put(mode, defValue); + } + + // TODO final + @Override + public boolean setModeValue(ApplicationMode mode, T obj) { + if (global) { + return set(obj); + } + + Object profilePrefs = osmandSettings.getProfilePreferences(mode); + boolean valueSaved = setValue(profilePrefs, obj); + if (valueSaved && cache && cachedPreference == profilePrefs) { + cachedValue = obj; + } + fireEvent(obj); + + return valueSaved; + } + + // TODO final + public T getProfileDefaultValue(ApplicationMode mode) { + if (global) { + return defaultValue; + } + if (defaultValues != null && defaultValues.containsKey(mode)) { + return defaultValues.get(mode); + } + ApplicationMode pt = mode.getParent(); + if (pt != null) { + return getProfileDefaultValue(pt); + } + return defaultValue; + } + + public final boolean hasDefaultValues() { + return defaultValues != null && !defaultValues.isEmpty(); + } + + public final boolean hasDefaultValueForMode(ApplicationMode mode) { + return defaultValues != null && defaultValues.containsKey(mode); + } + + // TODO final + protected T getDefaultValue() { + return getProfileDefaultValue(osmandSettings.currentMode); + } + + @Override + public final void overrideDefaultValue(T newDefaultValue) { + this.defaultValue = newDefaultValue; + } + + + + // TODO final + @Override + public T getModeValue(ApplicationMode mode) { + if (global) { + return get(); + } + T defaultV = getProfileDefaultValue(mode); + return getValue(osmandSettings.getProfilePreferences(mode), defaultV); + } + + // TODO final + @Override + public T get() { + if (cache && cachedValue != null && cachedPreference == getPreferences()) { + return cachedValue; + } + cachedPreference = getPreferences(); + cachedValue = getValue(cachedPreference, getProfileDefaultValue(osmandSettings.currentMode)); + return cachedValue; + } + + @Override + public final String getId() { + return id; + } + + @Override + public final void resetToDefault() { + T o = getProfileDefaultValue(osmandSettings.currentMode); + set(o); + } + + @Override + public final void resetModeToDefault(ApplicationMode mode) { + if (global) { + resetToDefault(); + } else { + T o = getProfileDefaultValue(mode); + setModeValue(mode, o); + } + } + + // TODO final + @Override + public boolean set(T obj) { + Object prefs = getPreferences(); + if (setValue(prefs, obj)) { + cachedValue = obj; + cachedPreference = prefs; + fireEvent(obj); + return true; + } + return false; + } + + public final boolean isSet() { + return osmandSettings.isSet(global, getId()); + } + + public boolean isSetForMode(ApplicationMode mode) { + return osmandSettings.isSet(mode, getId()); + } + + public final boolean isGlobal() { + return global; + } + + // TODO final + @Override + public boolean writeToJson(JSONObject json, ApplicationMode appMode) throws JSONException { + if (appMode != null) { + if (!global) { + String value = asStringModeValue(appMode); + if (value != null) { + json.put(getId(), value); + } + return true; + } + } else if (global) { + String value = asString(); + if (value != null) { + json.put(getId(), value); + } + return true; + } + return false; + } + // TODO final + @Override + public void readFromJson(JSONObject json, ApplicationMode appMode) throws JSONException { + if (appMode != null) { + if (!global) { + String modeValue = json.getString(getId()); + setModeValue(appMode, parseString(modeValue)); + } + } else if (global) { + String globalValue = json.getString(getId()); + set(parseString(globalValue)); + } + } + + @Override + public final String asString() { + T o = get(); + return toString(o); + } + + @Override + public final String asStringModeValue(ApplicationMode m) { + T v = getModeValue(m); + return toString(v); + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsPreference.java new file mode 100644 index 0000000000..a671d6141b --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsPreference.java @@ -0,0 +1,48 @@ +package net.osmand.plus.settings.backend; + +import androidx.annotation.NonNull; + +public class ContextMenuItemsPreference extends CommonPreference { + private OsmandSettings osmandSettings; + @NonNull + private String idScheme; + + ContextMenuItemsPreference(OsmandSettings osmandSettings, String id, @NonNull String idScheme, @NonNull ContextMenuItemsSettings defValue) { + super(id, defValue); + this.osmandSettings = osmandSettings; + this.idScheme = idScheme; + } + + @Override + protected ContextMenuItemsSettings getValue(Object prefs, ContextMenuItemsSettings defaultValue) { + String s = osmandSettings.settingsAPI.getString(prefs, getId(), ""); + return readValue(s); + } + + @Override + protected boolean setValue(Object prefs, ContextMenuItemsSettings val) { + return osmandSettings.settingsAPI.edit(prefs).putString(getId(), val.writeToJsonString(idScheme)).commit(); + } + + + @Override + protected String toString(ContextMenuItemsSettings o) { + return o.writeToJsonString(idScheme); + } + + @Override + public ContextMenuItemsSettings parseString(String s) { + return readValue(s); + } + + private ContextMenuItemsSettings readValue(String s) { + ContextMenuItemsSettings value = getDefaultValue().newInstance(); + value.readFromJsonString(s, idScheme); + return value; + } + + @NonNull + public String getIdScheme() { + return idScheme; + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsSettings.java b/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsSettings.java new file mode 100644 index 0000000000..85046ba00a --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsSettings.java @@ -0,0 +1,96 @@ +package net.osmand.plus.settings.backend; + +import net.osmand.util.Algorithms; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import androidx.annotation.NonNull; + +public class ContextMenuItemsSettings implements Serializable { + private static final String HIDDEN = "hidden"; + private static final String ORDER = "order"; + private List hiddenIds = new ArrayList<>(); + private List orderIds = new ArrayList<>(); + + public ContextMenuItemsSettings() { + + } + + public ContextMenuItemsSettings(@NonNull List hiddenIds, @NonNull List orderIds) { + this.hiddenIds = hiddenIds; + this.orderIds = orderIds; + } + + public ContextMenuItemsSettings newInstance() { + return new ContextMenuItemsSettings(); + } + + public void readFromJsonString(String jsonString, @NonNull String idScheme) { + if (Algorithms.isEmpty(jsonString)) { + return; + } + try { + JSONObject json = new JSONObject(jsonString); + readFromJson(json, idScheme); + } catch (JSONException e) { + OsmandSettings.LOG.error("Error converting to json string: " + e); + } + } + + public void readFromJson(JSONObject json, String idScheme) { + hiddenIds = readIdsList(json.optJSONArray(HIDDEN), idScheme); + orderIds = readIdsList(json.optJSONArray(ORDER), idScheme); + } + + protected List readIdsList(JSONArray jsonArray, @NonNull String idScheme) { + List list = new ArrayList<>(); + if (jsonArray != null) { + for (int i = 0; i < jsonArray.length(); i++) { + String id = jsonArray.optString(i); + list.add(idScheme + id); + } + } + return list; + } + + public String writeToJsonString(@NonNull String idScheme) { + try { + JSONObject json = new JSONObject(); + writeToJson(json, idScheme); + return json.toString(); + } catch (JSONException e) { + OsmandSettings.LOG.error("Error converting to json string: " + e); + } + return ""; + } + + public void writeToJson(JSONObject json, String idScheme) throws JSONException { + json.put(HIDDEN, getJsonArray(hiddenIds, idScheme)); + json.put(ORDER, getJsonArray(orderIds, idScheme)); + } + + protected JSONArray getJsonArray(List ids, @NonNull String idScheme) { + JSONArray jsonArray = new JSONArray(); + if (ids != null && !ids.isEmpty()) { + for (String id : ids) { + jsonArray.put(id.replace(idScheme, "")); + } + } + return jsonArray; + } + + public List getHiddenIds() { + return Collections.unmodifiableList(hiddenIds); + } + + public List getOrderIds() { + return Collections.unmodifiableList(orderIds); + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/EnumStringPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/EnumStringPreference.java new file mode 100644 index 0000000000..d8d01e4091 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/EnumStringPreference.java @@ -0,0 +1,45 @@ +package net.osmand.plus.settings.backend; + +public class EnumStringPreference> extends CommonPreference { + + private OsmandSettings osmandSettings; + private final E[] values; + + EnumStringPreference(OsmandSettings osmandSettings, String id, E defaultValue, E[] values) { + super(id, defaultValue); + this.osmandSettings = osmandSettings; + this.values = values; + } + + @Override + protected E getValue(Object prefs, E defaultValue) { + try { + String name = osmandSettings.settingsAPI.getString(prefs, getId(), defaultValue.name()); + E value = parseString(name); + return value != null ? value : defaultValue; + } catch (ClassCastException ex) { + setValue(prefs, defaultValue); + } + return defaultValue; + } + + @Override + protected boolean setValue(Object prefs, E val) { + return osmandSettings.settingsAPI.edit(prefs).putString(getId(), val.name()).commit(); + } + + @Override + protected String toString(E o) { + return o.name(); + } + + @Override + public E parseString(String s) { + for (E value : values) { + if (value.name().equals(s)) { + return value; + } + } + return null; + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/FloatPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/FloatPreference.java new file mode 100644 index 0000000000..9c10a314f9 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/FloatPreference.java @@ -0,0 +1,27 @@ +package net.osmand.plus.settings.backend; + +public class FloatPreference extends CommonPreference { + + + private OsmandSettings osmandSettings; + + FloatPreference(OsmandSettings osmandSettings, String id, float defaultValue) { + super(id, defaultValue); + this.osmandSettings = osmandSettings; + } + + @Override + protected Float getValue(Object prefs, Float defaultValue) { + return osmandSettings.settingsAPI.getFloat(prefs, getId(), defaultValue); + } + + @Override + protected boolean setValue(Object prefs, Float val) { + return osmandSettings.settingsAPI.edit(prefs).putFloat(getId(), val).commit(); + } + + @Override + public Float parseString(String s) { + return Float.parseFloat(s); + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/ImpassableRoadsStorage.java b/OsmAnd/src/net/osmand/plus/settings/backend/ImpassableRoadsStorage.java new file mode 100644 index 0000000000..dacadbf149 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/ImpassableRoadsStorage.java @@ -0,0 +1,194 @@ +package net.osmand.plus.settings.backend; + +import net.osmand.data.LatLon; +import net.osmand.data.PointDescription; +import net.osmand.plus.helpers.AvoidSpecificRoads; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.StringTokenizer; + +class ImpassableRoadsStorage extends SettingsMapPointsStorage { + + private OsmandSettings osmandSettings; + protected String roadsIdsKey; + protected String appModeKey; + + public ImpassableRoadsStorage(OsmandSettings osmandSettings) { + this.osmandSettings = osmandSettings; + pointsKey = OsmandSettings.IMPASSABLE_ROAD_POINTS; + descriptionsKey = OsmandSettings.IMPASSABLE_ROADS_DESCRIPTIONS; + roadsIdsKey = OsmandSettings.IMPASSABLE_ROADS_IDS; + appModeKey = OsmandSettings.IMPASSABLE_ROADS_APP_MODE_KEYS; + } + + public List getRoadIds(int size) { + List list = new ArrayList<>(); + String roadIds = osmandSettings.settingsAPI.getString(osmandSettings.globalPreferences, roadsIdsKey, ""); + if (roadIds.trim().length() > 0) { + StringTokenizer tok = new StringTokenizer(roadIds, ","); + while (tok.hasMoreTokens() && list.size() <= size) { + list.add(Long.parseLong(tok.nextToken())); + } + } + while (list.size() < size) { + list.add(0L); + } + return list; + } + + public List getAppModeKeys(int size) { + List list = new ArrayList<>(); + String roadIds = osmandSettings.settingsAPI.getString(osmandSettings.globalPreferences, appModeKey, ""); + if (roadIds.trim().length() > 0) { + StringTokenizer tok = new StringTokenizer(roadIds, ","); + while (tok.hasMoreTokens() && list.size() <= size) { + list.add(tok.nextToken()); + } + } + while (list.size() < size) { + list.add(""); + } + return list; + } + + public List getImpassableRoadsInfo() { + List points = getPoints(); + List roadIds = getRoadIds(points.size()); + List appModeKeys = getAppModeKeys(points.size()); + List descriptions = getPointDescriptions(points.size()); + + List avoidRoadsInfo = new ArrayList<>(); + + for (int i = 0; i < points.size(); i++) { + LatLon latLon = points.get(i); + PointDescription description = PointDescription.deserializeFromString(descriptions.get(i), null); + + AvoidSpecificRoads.AvoidRoadInfo avoidRoadInfo = new AvoidSpecificRoads.AvoidRoadInfo(); + avoidRoadInfo.id = roadIds.get(i); + avoidRoadInfo.latitude = latLon.getLatitude(); + avoidRoadInfo.longitude = latLon.getLongitude(); + avoidRoadInfo.name = description.getName(); + avoidRoadInfo.appModeKey = appModeKeys.get(i); + avoidRoadsInfo.add(avoidRoadInfo); + } + + return avoidRoadsInfo; + } + + public boolean addImpassableRoadInfo(AvoidSpecificRoads.AvoidRoadInfo avoidRoadInfo) { + List points = getPoints(); + List roadIds = getRoadIds(points.size()); + List appModeKeys = getAppModeKeys(points.size()); + List descriptions = getPointDescriptions(points.size()); + + roadIds.add(0, avoidRoadInfo.id); + points.add(0, new LatLon(avoidRoadInfo.latitude, avoidRoadInfo.longitude)); + appModeKeys.add(0, avoidRoadInfo.appModeKey); + descriptions.add(0, PointDescription.serializeToString(new PointDescription("", avoidRoadInfo.name))); + + return saveAvoidRoadData(points, descriptions, roadIds, appModeKeys); + } + + public boolean updateImpassableRoadInfo(AvoidSpecificRoads.AvoidRoadInfo avoidRoadInfo) { + List points = getPoints(); + + int index = points.indexOf(new LatLon(avoidRoadInfo.latitude, avoidRoadInfo.longitude)); + if (index != -1) { + List roadIds = getRoadIds(points.size()); + List appModeKeys = getAppModeKeys(points.size()); + List descriptions = getPointDescriptions(points.size()); + + roadIds.set(index, avoidRoadInfo.id); + appModeKeys.set(index, avoidRoadInfo.appModeKey); + descriptions.set(index, PointDescription.serializeToString(new PointDescription("", avoidRoadInfo.name))); + return saveAvoidRoadData(points, descriptions, roadIds, appModeKeys); + } + return false; + } + + @Override + public boolean deletePoint(int index) { + List points = getPoints(); + List roadIds = getRoadIds(points.size()); + List appModeKeys = getAppModeKeys(points.size()); + List descriptions = getPointDescriptions(points.size()); + + if (index < points.size()) { + points.remove(index); + roadIds.remove(index); + appModeKeys.remove(index); + descriptions.remove(index); + return saveAvoidRoadData(points, descriptions, roadIds, appModeKeys); + } + return false; + } + + @Override + public boolean deletePoint(LatLon latLon) { + List points = getPoints(); + List roadIds = getRoadIds(points.size()); + List appModeKeys = getAppModeKeys(points.size()); + List descriptions = getPointDescriptions(points.size()); + + int index = points.indexOf(latLon); + if (index != -1) { + points.remove(index); + roadIds.remove(index); + appModeKeys.remove(index); + descriptions.remove(index); + return saveAvoidRoadData(points, descriptions, roadIds, appModeKeys); + } + return false; + } + + @Override + public boolean movePoint(LatLon latLonEx, LatLon latLonNew) { + List points = getPoints(); + List roadIds = getRoadIds(points.size()); + List appModeKeys = getAppModeKeys(points.size()); + List descriptions = getPointDescriptions(points.size()); + + int i = points.indexOf(latLonEx); + if (i != -1) { + points.set(i, latLonNew); + return saveAvoidRoadData(points, descriptions, roadIds, appModeKeys); + } else { + return false; + } + } + + public boolean saveAvoidRoadData(List points, List descriptions, + List roadIds, List appModeKeys) { + return savePoints(points, descriptions) && saveRoadIds(roadIds) && saveAppModeKeys(appModeKeys); + } + + public boolean saveRoadIds(List roadIds) { + StringBuilder stringBuilder = new StringBuilder(); + Iterator iterator = roadIds.iterator(); + while (iterator.hasNext()) { + stringBuilder.append(iterator.next()); + if (iterator.hasNext()) { + stringBuilder.append(","); + } + } + return osmandSettings.settingsAPI.edit(osmandSettings.globalPreferences) + .putString(roadsIdsKey, stringBuilder.toString()) + .commit(); + } + + public boolean saveAppModeKeys(List appModeKeys) { + StringBuilder stringBuilder = new StringBuilder(); + Iterator iterator = appModeKeys.iterator(); + while (iterator.hasNext()) { + stringBuilder.append(iterator.next()); + if (iterator.hasNext()) { + stringBuilder.append(","); + } + } + return osmandSettings.settingsAPI.edit(osmandSettings.globalPreferences) + .putString(appModeKey, stringBuilder.toString()) + .commit(); + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/IntPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/IntPreference.java new file mode 100644 index 0000000000..3c040821b9 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/IntPreference.java @@ -0,0 +1,27 @@ +package net.osmand.plus.settings.backend; + +class IntPreference extends CommonPreference { + + + private OsmandSettings osmandSettings; + + IntPreference(OsmandSettings osmandSettings, String id, int defaultValue) { + super(id, defaultValue); + this.osmandSettings = osmandSettings; + } + + @Override + protected Integer getValue(Object prefs, Integer defaultValue) { + return osmandSettings.settingsAPI.getInt(prefs, getId(), defaultValue); + } + + @Override + protected boolean setValue(Object prefs, Integer val) { + return osmandSettings.settingsAPI.edit(prefs).putInt(getId(), val).commit(); + } + + @Override + public Integer parseString(String s) { + return Integer.parseInt(s); + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/IntermediatePointsStorage.java b/OsmAnd/src/net/osmand/plus/settings/backend/IntermediatePointsStorage.java new file mode 100644 index 0000000000..aaf90f0efd --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/IntermediatePointsStorage.java @@ -0,0 +1,23 @@ +package net.osmand.plus.settings.backend; + +import net.osmand.data.LatLon; + +import java.util.List; + +class IntermediatePointsStorage extends SettingsMapPointsStorage { + + private OsmandSettings osmandSettings; + + public IntermediatePointsStorage(OsmandSettings osmandSettings) { + this.osmandSettings = osmandSettings; + pointsKey = OsmandSettings.INTERMEDIATE_POINTS; + descriptionsKey = OsmandSettings.INTERMEDIATE_POINTS_DESCRIPTION; + } + + @Override + public boolean savePoints(List ps, List ds) { + boolean res = super.savePoints(ps, ds); + osmandSettings.backupTargetPoints(); + return res; + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/ListStringPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/ListStringPreference.java new file mode 100644 index 0000000000..81b7a01f60 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/ListStringPreference.java @@ -0,0 +1,127 @@ +package net.osmand.plus.settings.backend; + +import net.osmand.plus.ApplicationMode; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class ListStringPreference extends StringPreference { + + private OsmandSettings osmandSettings; + private String delimiter; + + ListStringPreference(OsmandSettings osmandSettings, String id, String defaultValue, String delimiter) { + super(id, defaultValue); + this.osmandSettings = osmandSettings; + this.delimiter = delimiter; + } + + public boolean addValue(String res) { + return addModeValue(osmandSettings.getApplicationMode(), res); + } + + public boolean addModeValue(ApplicationMode appMode, String res) { + String vl = getModeValue(appMode); + if (vl == null || vl.isEmpty()) { + vl = res + delimiter; + } else { + vl = vl + res + delimiter; + } + setModeValue(appMode, vl); + return true; + } + + public void clearAll() { + clearAllForProfile(osmandSettings.getApplicationMode()); + } + + public void clearAllForProfile(ApplicationMode appMode) { + setModeValue(appMode, ""); + } + + public boolean containsValue(String res) { + return containsValue(osmandSettings.getApplicationMode(), res); + } + + public boolean containsValue(ApplicationMode appMode, String res) { + String vl = getModeValue(appMode); + String r = res + delimiter; + return vl.startsWith(r) || vl.contains(delimiter + r); + } + + public boolean removeValue(String res) { + return removeValueForProfile(osmandSettings.getApplicationMode(), res); + } + + public boolean removeValueForProfile(ApplicationMode appMode, String res) { + String vl = getModeValue(appMode); + String r = res + delimiter; + if(vl != null) { + if(vl.startsWith(r)) { + vl = vl.substring(r.length()); + setModeValue(appMode, vl); + return true; + } else { + int it = vl.indexOf(delimiter + r); + if(it >= 0) { + vl = vl.substring(0, it + delimiter.length()) + vl.substring(it + delimiter.length() + r.length()); + } + setModeValue(appMode, vl); + return true; + } + } + return false; + } + + public List getStringsList() { + return getStringsListForProfile(osmandSettings.getApplicationMode()); + } + + public List getStringsListForProfile(ApplicationMode appMode) { + final String listAsString = getModeValue(appMode); + if (listAsString != null) { + if (listAsString.contains(delimiter)) { + return Arrays.asList(listAsString.split(delimiter)); + } else { + return new ArrayList() { + {add(listAsString);} + }; + } + } + return null; + } + + public void setStringsList(List values) { + setStringsListForProfile(osmandSettings.getApplicationMode(), values); + } + + public void setStringsListForProfile(ApplicationMode appMode, List values) { + if (values == null || values.size() == 0) { + setModeValue(appMode, null); + return; + } + clearAllForProfile(appMode); + for (String value : values) { + addModeValue(appMode, value); + } + } + + public boolean setModeValues(ApplicationMode mode, List values) { + if (values == null || values.size() == 0) { + setModeValue(mode,null); + return false; + } + clearAll(); + String vl = get(); + for (String value : values) { + addValue(value); + if (vl == null || vl.isEmpty()) { + vl = value + delimiter; + } else { + vl = vl + value + delimiter; + } + } + return setModeValue(mode, vl); + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/LongPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/LongPreference.java new file mode 100644 index 0000000000..8993919e23 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/LongPreference.java @@ -0,0 +1,27 @@ +package net.osmand.plus.settings.backend; + +class LongPreference extends CommonPreference { + + + private OsmandSettings osmandSettings; + + LongPreference(OsmandSettings osmandSettings, String id, long defaultValue) { + super(id, defaultValue); + this.osmandSettings = osmandSettings; + } + + @Override + protected Long getValue(Object prefs, Long defaultValue) { + return osmandSettings.settingsAPI.getLong(prefs, getId(), defaultValue); + } + + @Override + protected boolean setValue(Object prefs, Long val) { + return osmandSettings.settingsAPI.edit(prefs).putLong(getId(), val).commit(); + } + + @Override + public Long parseString(String s) { + return Long.parseLong(s); + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/MainContextMenuItemsSettings.java b/OsmAnd/src/net/osmand/plus/settings/backend/MainContextMenuItemsSettings.java new file mode 100644 index 0000000000..51407a36ba --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/MainContextMenuItemsSettings.java @@ -0,0 +1,45 @@ +package net.osmand.plus.settings.backend; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import androidx.annotation.NonNull; + +public class MainContextMenuItemsSettings extends ContextMenuItemsSettings { + private static final String MAIN = "main"; + private List mainIds = new ArrayList<>(); + + public MainContextMenuItemsSettings() { + + } + + public MainContextMenuItemsSettings(@NonNull List mainIds, @NonNull List hiddenIds, @NonNull List orderIds) { + super(hiddenIds, orderIds); + this.mainIds = mainIds; + } + + @Override + public ContextMenuItemsSettings newInstance() { + return new MainContextMenuItemsSettings(); + } + + @Override + public void readFromJson(JSONObject json, String idScheme) { + super.readFromJson(json, idScheme); + mainIds = readIdsList(json.optJSONArray(MAIN), idScheme); + } + + @Override + public void writeToJson(JSONObject json, String idScheme) throws JSONException { + super.writeToJson(json, idScheme); + json.put(MAIN, getJsonArray(mainIds, idScheme)); + } + + public List getMainIds() { + return Collections.unmodifiableList(mainIds); + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndPreferencesDataStore.java b/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndPreferencesDataStore.java new file mode 100644 index 0000000000..0a6f464b77 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndPreferencesDataStore.java @@ -0,0 +1,120 @@ +package net.osmand.plus.settings.backend; + +import net.osmand.plus.ApplicationMode; + +import java.util.Set; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.preference.PreferenceDataStore; + +public class OsmAndPreferencesDataStore extends PreferenceDataStore { + + private OsmandSettings osmandSettings; + private ApplicationMode appMode; + + public OsmAndPreferencesDataStore(OsmandSettings osmandSettings, @NonNull ApplicationMode appMode) { + this.osmandSettings = osmandSettings; + this.appMode = appMode; + } + + @Override + public void putString(String key, @Nullable String value) { + osmandSettings.setPreference(key, value, appMode); + } + + @Override + public void putStringSet(String key, @Nullable Set values) { + osmandSettings.setPreference(key, values, appMode); + } + + @Override + public void putInt(String key, int value) { + osmandSettings.setPreference(key, value, appMode); + } + + @Override + public void putLong(String key, long value) { + osmandSettings.setPreference(key, value, appMode); + } + + @Override + public void putFloat(String key, float value) { + osmandSettings.setPreference(key, value, appMode); + } + + @Override + public void putBoolean(String key, boolean value) { + osmandSettings.setPreference(key, value, appMode); + } + + public void putValue(String key, Object value) { + osmandSettings.setPreference(key, value, appMode); + } + + @Nullable + @Override + public String getString(String key, @Nullable String defValue) { + OsmandPreference preference = osmandSettings.getPreference(key); + if (preference instanceof StringPreference) { + return ((StringPreference) preference).getModeValue(appMode); + } else { + Object value = preference.getModeValue(appMode); + if (value != null) { + return value.toString(); + } + } + return defValue; + } + + @Nullable + @Override + public Set getStringSet(String key, @Nullable Set defValues) { + return super.getStringSet(key, defValues); + } + + @Override + public int getInt(String key, int defValue) { + OsmandPreference preference = osmandSettings.getPreference(key); + if (preference instanceof OsmandSettings.IntPreference) { + return ((OsmandSettings.IntPreference) preference).getModeValue(appMode); + } + return defValue; + } + + @Override + public long getLong(String key, long defValue) { + OsmandPreference preference = osmandSettings.getPreference(key); + if (preference instanceof OsmandSettings.LongPreference) { + return ((OsmandSettings.LongPreference) preference).getModeValue(appMode); + } + return defValue; + } + + @Override + public float getFloat(String key, float defValue) { + OsmandPreference preference = osmandSettings.getPreference(key); + if (preference instanceof FloatPreference) { + return ((FloatPreference) preference).getModeValue(appMode); + } + return defValue; + } + + @Override + public boolean getBoolean(String key, boolean defValue) { + OsmandPreference preference = osmandSettings.getPreference(key); + if (preference instanceof BooleanPreference) { + return ((BooleanPreference) preference).getModeValue(appMode); + } + return defValue; + } + + @Nullable + public Object getValue(String key, Object defValue) { + OsmandPreference preference = osmandSettings.getPreference(key); + if (preference != null) { + return preference.getModeValue(appMode); + } + return defValue; + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/OsmandPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/OsmandPreference.java new file mode 100644 index 0000000000..ae9a3f5e3a --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/OsmandPreference.java @@ -0,0 +1,43 @@ +package net.osmand.plus.settings.backend; + +import net.osmand.StateChangedListener; +import net.osmand.plus.ApplicationMode; + +import org.json.JSONException; +import org.json.JSONObject; + +public interface OsmandPreference { + T get(); + + boolean set(T obj); + + boolean setModeValue(ApplicationMode m, T obj); + + T getModeValue(ApplicationMode m); + + String getId(); + + void resetToDefault(); + + void resetModeToDefault(ApplicationMode m); + + void overrideDefaultValue(T newDefaultValue); + + void addListener(StateChangedListener listener); + + void removeListener(StateChangedListener listener); + + boolean isSet(); + + boolean isSetForMode(ApplicationMode m); + + boolean writeToJson(JSONObject json, ApplicationMode appMode) throws JSONException; + + void readFromJson(JSONObject json, ApplicationMode appMode) throws JSONException; + + String asString(); + + String asStringModeValue(ApplicationMode m); + + T parseString(String s); +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java b/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java index 24b01d96dc..93705e3c69 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java @@ -18,18 +18,11 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.core.util.Pair; -import androidx.preference.PreferenceDataStore; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; import net.osmand.IndexConstants; import net.osmand.PlatformUtil; -import net.osmand.StateChangedListener; import net.osmand.ValueHolder; import net.osmand.aidl.OsmandAidlApi; -import net.osmand.data.FavouritePoint; import net.osmand.data.LatLon; import net.osmand.data.PointDescription; import net.osmand.map.ITileSource; @@ -37,9 +30,6 @@ import net.osmand.map.TileSourceManager; import net.osmand.map.TileSourceManager.TileSourceTemplate; import net.osmand.osm.io.NetworkUtils; import net.osmand.plus.ApplicationMode; -import net.osmand.plus.ApplicationMode.ApplicationModeBean; -import net.osmand.plus.ApplicationMode.ApplicationModeBuilder; -import net.osmand.plus.FavouritesDbHelper; import net.osmand.plus.OsmandApplication; import net.osmand.plus.R; import net.osmand.plus.SQLiteTileSource; @@ -63,15 +53,11 @@ import net.osmand.render.RenderingRulesStorage; import net.osmand.util.Algorithms; import org.apache.commons.logging.Log; -import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; -import java.io.Serializable; -import java.lang.ref.WeakReference; -import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -79,7 +65,6 @@ import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; -import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; @@ -96,83 +81,6 @@ public class OsmandSettings { public static final int VERSION = 1; - public interface OsmandPreference { - T get(); - - boolean set(T obj); - - boolean setModeValue(ApplicationMode m, T obj); - - T getModeValue(ApplicationMode m); - - String getId(); - - void resetToDefault(); - - void resetModeToDefault(ApplicationMode m); - - void overrideDefaultValue(T newDefaultValue); - - void addListener(StateChangedListener listener); - - void removeListener(StateChangedListener listener); - - boolean isSet(); - - boolean isSetForMode(ApplicationMode m); - - boolean writeToJson(JSONObject json, ApplicationMode appMode) throws JSONException; - - void readFromJson(JSONObject json, ApplicationMode appMode) throws JSONException; - - String asString(); - - String asStringModeValue(ApplicationMode m); - - T parseString(String s); - } - - private abstract class PreferenceWithListener implements OsmandPreference { - private List>> l = null; - - @Override - public synchronized void addListener(StateChangedListener listener) { - if (l == null) { - l = new LinkedList>>(); - } - if (!l.contains(new WeakReference>(listener))) { - l.add(new WeakReference>(listener)); - } - } - - public synchronized void fireEvent(T value) { - if (l != null) { - Iterator>> it = l.iterator(); - while (it.hasNext()) { - StateChangedListener t = it.next().get(); - if (t == null) { - it.remove(); - } else { - t.stateChanged(value); - } - } - } - } - - @Override - public synchronized void removeListener(StateChangedListener listener) { - if (l != null) { - Iterator>> it = l.iterator(); - while (it.hasNext()) { - StateChangedListener t = it.next().get(); - if (t == listener) { - it.remove(); - } - } - } - } - } - // These settings are stored in SharedPreferences private static final String CUSTOM_SHARED_PREFERENCES_PREFIX = "net.osmand.customsettings."; private static final String SHARED_PREFERENCES_NAME = "net.osmand.settings"; @@ -182,16 +90,29 @@ public class OsmandSettings { /// Settings variables private final OsmandApplication ctx; private SettingsAPI settingsAPI; - private Object globalPreferences; - private Object profilePreferences; - private ApplicationMode currentMode; - private Map> registeredPreferences = - new LinkedHashMap>(); + Object globalPreferences; + Object profilePreferences; + ApplicationMode currentMode; + Map> registeredPreferences = + new LinkedHashMap>(); + // cache variables private long lastTimeInternetConnectionChecked = 0; private boolean internetConnectionAvailable = true; + // TODO variable + Map> customBooleanRendersProps = new LinkedHashMap>(); + Map> customRoutingProps = new LinkedHashMap>(); + Map> customBooleanRoutingProps = new LinkedHashMap>(); + Map> customRendersProps = new LinkedHashMap>(); + private IntermediatePointsStorage intermediatePointsStorage = new IntermediatePointsStorage(this); + private ImpassableRoadsStorage mImpassableRoadsStorage = new ImpassableRoadsStorage(this); + + private Object objectToShow; + private boolean editObjectToShow; + private String searchRequestToShow; + protected OsmandSettings(OsmandApplication clientContext, SettingsAPI settinsAPI) { ctx = clientContext; @@ -237,8 +158,8 @@ public class OsmandSettings { return settingsAPI; } - public PreferencesDataStore getDataStore(@Nullable ApplicationMode appMode) { - return new PreferencesDataStore(appMode != null ? appMode : APPLICATION_MODE.get()); + public OsmAndPreferencesDataStore getDataStore(@Nullable ApplicationMode appMode) { + return new OsmAndPreferencesDataStore(this, appMode != null ? appMode : APPLICATION_MODE.get()); } public static String getSharedPreferencesName(ApplicationMode mode) { @@ -263,109 +184,7 @@ public class OsmandSettings { return globalPreferences != null && globalPreferences.getBoolean(SETTING_CUSTOMIZED_ID, false); } - public void migratePreferences() { - migrateEnumPreferences(); - SharedPreferences globalSharedPreferences = (SharedPreferences) globalPreferences; - Map globalPrefsMap = globalSharedPreferences.getAll(); - for (String key : globalPrefsMap.keySet()) { - OsmandPreference pref = getPreference(key); - if (pref instanceof CommonPreference) { - CommonPreference commonPreference = (CommonPreference) pref; - if (!commonPreference.global) { - for (ApplicationMode mode : ApplicationMode.allPossibleValues()) { - if (!commonPreference.isSetForMode(mode) && !commonPreference.hasDefaultValueForMode(mode)) { - setPreference(key, globalPrefsMap.get(key), mode); - } - } - } - } - } - SharedPreferences defaultProfilePreferences = (SharedPreferences) getProfilePreferences(ApplicationMode.DEFAULT); - Map defaultPrefsMap = defaultProfilePreferences.getAll(); - for (String key : defaultPrefsMap.keySet()) { - OsmandPreference pref = getPreference(key); - if (pref instanceof CommonPreference) { - CommonPreference commonPreference = (CommonPreference) pref; - if (commonPreference.global && !commonPreference.isSet()) { - setPreference(key, defaultPrefsMap.get(key)); - } - } - } - for (OsmandPreference pref : generalPrefs) { - if (pref instanceof CommonPreference) { - CommonPreference commonPref = (CommonPreference) pref; - Object defaultVal = commonPref.getModeValue(ApplicationMode.DEFAULT); - for (ApplicationMode mode : ApplicationMode.allPossibleValues()) { - if (!commonPref.isSetForMode(mode) && !commonPref.hasDefaultValueForMode(mode)) { - setPreference(commonPref.getId(), defaultVal, mode); - } - } - } - } - String json = settingsAPI.getString(globalPreferences, "custom_app_profiles", ""); - if (!Algorithms.isEmpty(json)) { - Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); - Type t = new TypeToken>() { - }.getType(); - List customProfiles = gson.fromJson(json, t); - if (!Algorithms.isEmpty(customProfiles)) { - for (ApplicationModeBean modeBean : customProfiles) { - ApplicationModeBuilder builder = ApplicationMode.fromModeBean(ctx, modeBean); - ApplicationMode.saveProfile(builder, ctx); - } - } - } - } - - public void migrateEnumPreferences() { - for (OsmandPreference pref : registeredPreferences.values()) { - if (pref instanceof EnumStringPreference) { - EnumStringPreference enumPref = (EnumStringPreference) pref; - if (enumPref.isGlobal()) { - migrateEnumPref(enumPref, (SharedPreferences) globalPreferences); - } else { - for (ApplicationMode mode : ApplicationMode.allPossibleValues()) { - migrateEnumPref(enumPref, (SharedPreferences) getProfilePreferences(mode)); - } - } - } - } - } - - private void migrateEnumPref(EnumStringPreference enumPref, SharedPreferences sharedPreferences) { - Object value = sharedPreferences.getAll().get(enumPref.getId()); - if (value instanceof Integer) { - int enumIndex = (int) value; - if (enumIndex >= 0 && enumIndex < enumPref.values.length) { - Enum savedValue = enumPref.values[enumIndex]; - enumPref.setValue(sharedPreferences, savedValue); - } - } - } - - public void migrateHomeWorkParkingToFavorites() { - FavouritesDbHelper favorites = ctx.getFavorites(); - - LatLon homePoint = null; - float lat = settingsAPI.getFloat(globalPreferences, "home_point_lat", 0); - float lon = settingsAPI.getFloat(globalPreferences, "home_point_lon", 0); - if (lat != 0 || lon != 0) { - homePoint = new LatLon(lat, lon); - } - LatLon workPoint = null; - lat = settingsAPI.getFloat(globalPreferences, "work_point_lat", 0); - lon = settingsAPI.getFloat(globalPreferences, "work_point_lon", 0); - if (lat != 0 || lon != 0) { - workPoint = new LatLon(lat, lon); - } - if (homePoint != null) { - favorites.setSpecialPoint(homePoint, FavouritePoint.SpecialPointType.HOME, null); - } - if (workPoint != null) { - favorites.setSpecialPoint(workPoint, FavouritePoint.SpecialPointType.WORK, null); - } - } public Object getProfilePreferences(ApplicationMode mode) { return settingsAPI.getPreferenceObject(getSharedPreferencesName(mode)); @@ -714,697 +533,98 @@ public class OsmandSettings { } } - - /////////////// PREFERENCES classes //////////////// - - public abstract class CommonPreference extends PreferenceWithListener { - private final String id; - private boolean global; - private T cachedValue; - private Object cachedPreference; - private boolean cache; - private Map defaultValues; - private T defaultValue; - - - public CommonPreference(String id, T defaultValue) { - this.id = id; - this.defaultValue = defaultValue; - registeredPreferences.put(id, this); - } - - // Methods to possibly override - protected abstract T getValue(Object prefs, T defaultValue); - - protected abstract boolean setValue(Object prefs, T val); - - public abstract T parseString(String s); - - protected String toString(T o) { - return o == null ? null : o.toString(); - } - - - // common methods - - public final CommonPreference makeGlobal() { - global = true; - return this; - } - - public final CommonPreference cache() { - cache = true; - return this; - } - - public final CommonPreference makeProfile() { - global = false; - return this; - } - - protected final Object getPreferences() { - return global ? globalPreferences : profilePreferences; - } - - public final void setModeDefaultValue(ApplicationMode mode, T defValue) { - if (defaultValues == null) { - defaultValues = new LinkedHashMap(); - } - defaultValues.put(mode, defValue); - } - - // TODO final - @Override - public boolean setModeValue(ApplicationMode mode, T obj) { - if (global) { - return set(obj); - } - - Object profilePrefs = getProfilePreferences(mode); - boolean valueSaved = setValue(profilePrefs, obj); - if (valueSaved && cache && cachedPreference == profilePrefs) { - cachedValue = obj; - } - fireEvent(obj); - - return valueSaved; - } - - // TODO final - public T getProfileDefaultValue(ApplicationMode mode) { - if (global) { - return defaultValue; - } - if (defaultValues != null && defaultValues.containsKey(mode)) { - return defaultValues.get(mode); - } - ApplicationMode pt = mode.getParent(); - if (pt != null) { - return getProfileDefaultValue(pt); - } - return defaultValue; - } - - public final boolean hasDefaultValues() { - return defaultValues != null && !defaultValues.isEmpty(); - } - - public final boolean hasDefaultValueForMode(ApplicationMode mode) { - return defaultValues != null && defaultValues.containsKey(mode); - } - - // TODO final - protected T getDefaultValue() { - return getProfileDefaultValue(currentMode); - } - - @Override - public final void overrideDefaultValue(T newDefaultValue) { - this.defaultValue = newDefaultValue; - } - - - - // TODO final - @Override - public T getModeValue(ApplicationMode mode) { - if (global) { - return get(); - } - T defaultV = getProfileDefaultValue(mode); - return getValue(getProfilePreferences(mode), defaultV); - } - - // TODO final - @Override - public T get() { - if (cache && cachedValue != null && cachedPreference == getPreferences()) { - return cachedValue; - } - cachedPreference = getPreferences(); - cachedValue = getValue(cachedPreference, getProfileDefaultValue(currentMode)); - return cachedValue; - } - - @Override - public final String getId() { - return id; - } - - @Override - public final void resetToDefault() { - T o = getProfileDefaultValue(currentMode); - set(o); - } - - @Override - public final void resetModeToDefault(ApplicationMode mode) { - if (global) { - resetToDefault(); - } else { - T o = getProfileDefaultValue(mode); - setModeValue(mode, o); - } - } - - // TODO final - @Override - public boolean set(T obj) { - Object prefs = getPreferences(); - if (setValue(prefs, obj)) { - cachedValue = obj; - cachedPreference = prefs; - fireEvent(obj); - return true; - } - return false; - } - - public final boolean isSet() { - return settingsAPI.contains(getPreferences(), getId()); - } - - public boolean isSetForMode(ApplicationMode mode) { - return settingsAPI.contains(getProfilePreferences(mode), getId()); - } - - public final boolean isGlobal() { - return global; - } - - // TODO final - @Override - public boolean writeToJson(JSONObject json, ApplicationMode appMode) throws JSONException { - if (appMode != null) { - if (!global) { - String value = asStringModeValue(appMode); - if (value != null) { - json.put(getId(), value); - } - return true; - } - } else if (global) { - String value = asString(); - if (value != null) { - json.put(getId(), value); - } - return true; - } - return false; - } - // TODO final - @Override - public void readFromJson(JSONObject json, ApplicationMode appMode) throws JSONException { - if (appMode != null) { - if (!global) { - String modeValue = json.getString(getId()); - setModeValue(appMode, parseString(modeValue)); - } - } else if (global) { - String globalValue = json.getString(getId()); - set(parseString(globalValue)); - } - } - - @Override - public final String asString() { - T o = get(); - return toString(o); - } - - @Override - public final String asStringModeValue(ApplicationMode m) { - T v = getModeValue(m); - return toString(v); - } + void registerInternalPreference(String id, CommonPreference tCommonPreference) { + registeredPreferences.put(id, tCommonPreference); } - public class BooleanPreference extends CommonPreference { - - - private BooleanPreference(String id, boolean defaultValue) { - super(id, defaultValue); - } - - @Override - protected Boolean getValue(Object prefs, Boolean defaultValue) { - return settingsAPI.getBoolean(prefs, getId(), defaultValue); - } - - @Override - protected boolean setValue(Object prefs, Boolean val) { - return settingsAPI.edit(prefs).putBoolean(getId(), val).commit(); - } - - @Override - public Boolean parseString(String s) { - return Boolean.parseBoolean(s); - } + boolean isSet(boolean global, String id) { + return settingsAPI.contains(getPreferences(global), id); } - private class BooleanAccessibilityPreference extends BooleanPreference { - - private BooleanAccessibilityPreference(String id, boolean defaultValue) { - super(id, defaultValue); - } - - @Override - public Boolean get() { - return ctx.accessibilityEnabled() ? super.get() : getDefaultValue(); - } - - @Override - public Boolean getModeValue(ApplicationMode mode) { - return ctx.accessibilityEnabledForMode(mode) ? super.getModeValue(mode) : getDefaultValue(); - } - - @Override - public boolean set(Boolean obj) { - return ctx.accessibilityEnabled() && super.set(obj); - } - - @Override - public boolean setModeValue(ApplicationMode mode, Boolean obj) { - return ctx.accessibilityEnabledForMode(mode) && super.setModeValue(mode, obj); - } + boolean isSet(ApplicationMode m, String id) { + return settingsAPI.contains(getProfilePreferences(m), id); } - private class IntPreference extends CommonPreference { - - - private IntPreference(String id, int defaultValue) { - super(id, defaultValue); - } - - @Override - protected Integer getValue(Object prefs, Integer defaultValue) { - return settingsAPI.getInt(prefs, getId(), defaultValue); - } - - @Override - protected boolean setValue(Object prefs, Integer val) { - return settingsAPI.edit(prefs).putInt(getId(), val).commit(); - } - - @Override - public Integer parseString(String s) { - return Integer.parseInt(s); - } + Object getPreferences(boolean global) { + return global ? globalPreferences : profilePreferences; } - private class LongPreference extends CommonPreference { - - private LongPreference(String id, long defaultValue) { - super(id, defaultValue); - } - - @Override - protected Long getValue(Object prefs, Long defaultValue) { - return settingsAPI.getLong(prefs, getId(), defaultValue); - } - - @Override - protected boolean setValue(Object prefs, Long val) { - return settingsAPI.edit(prefs).putLong(getId(), val).commit(); - } - - @Override - public Long parseString(String s) { - return Long.parseLong(s); + @SuppressWarnings("unchecked") + public CommonPreference registerBooleanPreference(String id, boolean defValue) { + if (registeredPreferences.containsKey(id)) { + return (CommonPreference) registeredPreferences.get(id); } + BooleanPreference p = new BooleanPreference(this, id, defValue); + registeredPreferences.put(id, p); + return p; } - public class FloatPreference extends CommonPreference { - - - private FloatPreference(String id, float defaultValue) { - super(id, defaultValue); - } - - @Override - protected Float getValue(Object prefs, Float defaultValue) { - return settingsAPI.getFloat(prefs, getId(), defaultValue); - } - - @Override - protected boolean setValue(Object prefs, Float val) { - return settingsAPI.edit(prefs).putFloat(getId(), val).commit(); - } - - @Override - public Float parseString(String s) { - return Float.parseFloat(s); + @SuppressWarnings("unchecked") + public CommonPreference registerBooleanAccessibilityPreference(String id, boolean defValue) { + if (registeredPreferences.containsKey(id)) { + return (CommonPreference) registeredPreferences.get(id); } + BooleanPreference p = new BooleanAccessibilityPreference(this, id, defValue); + registeredPreferences.put(id, p); + return p; } - public class StringPreference extends CommonPreference { - - private StringPreference(String id, String defaultValue) { - super(id, defaultValue); - } - - @Override - protected String getValue(Object prefs, String defaultValue) { - return settingsAPI.getString(prefs, getId(), defaultValue); - } - - @Override - protected boolean setValue(Object prefs, String val) { - return settingsAPI.edit(prefs).putString(getId(), (val != null) ? val.trim() : val).commit(); - } - - @Override - public String parseString(String s) { - return s; - } - } - - public class ListStringPreference extends StringPreference { - - private String delimiter; - - private ListStringPreference(String id, String defaultValue, String delimiter) { - super(id, defaultValue); - this.delimiter = delimiter; - } - - public boolean addValue(String res) { - return addModeValue(getApplicationMode(), res); - } - - public boolean addModeValue(ApplicationMode appMode, String res) { - String vl = getModeValue(appMode); - if (vl == null || vl.isEmpty()) { - vl = res + delimiter; - } else { - vl = vl + res + delimiter; - } - setModeValue(appMode, vl); - return true; - } - - public void clearAll() { - clearAllForProfile(getApplicationMode()); - } - - public void clearAllForProfile(ApplicationMode appMode) { - setModeValue(appMode, ""); - } - - public boolean containsValue(String res) { - return containsValue(getApplicationMode(), res); - } - - public boolean containsValue(ApplicationMode appMode, String res) { - String vl = getModeValue(appMode); - String r = res + delimiter; - return vl.startsWith(r) || vl.contains(delimiter + r); - } - - public boolean removeValue(String res) { - return removeValueForProfile(getApplicationMode(), res); - } - - public boolean removeValueForProfile(ApplicationMode appMode, String res) { - String vl = getModeValue(appMode); - String r = res + delimiter; - if(vl != null) { - if(vl.startsWith(r)) { - vl = vl.substring(r.length()); - setModeValue(appMode, vl); - return true; - } else { - int it = vl.indexOf(delimiter + r); - if(it >= 0) { - vl = vl.substring(0, it + delimiter.length()) + vl.substring(it + delimiter.length() + r.length()); - } - setModeValue(appMode, vl); - return true; - } - } - return false; - } - - public List getStringsList() { - return getStringsListForProfile(getApplicationMode()); - } - - public List getStringsListForProfile(ApplicationMode appMode) { - final String listAsString = getModeValue(appMode); - if (listAsString != null) { - if (listAsString.contains(delimiter)) { - return Arrays.asList(listAsString.split(delimiter)); - } else { - return new ArrayList() { - {add(listAsString);} - }; - } - } - return null; - } - - public void setStringsList(List values) { - setStringsListForProfile(getApplicationMode(), values); - } - - public void setStringsListForProfile(ApplicationMode appMode, List values) { - if (values == null || values.size() == 0) { - setModeValue(appMode, null); - return; - } - clearAllForProfile(appMode); - for (String value : values) { - addModeValue(appMode, value); - } - } - - public boolean setModeValues(ApplicationMode mode, List values) { - if (values == null || values.size() == 0) { - setModeValue(mode,null); - return false; - } - clearAll(); - String vl = get(); - for (String value : values) { - addValue(value); - if (vl == null || vl.isEmpty()) { - vl = value + delimiter; - } else { - vl = vl + value + delimiter; - } - } - return setModeValue(mode, vl); + @SuppressWarnings("unchecked") + public CommonPreference registerStringPreference(String id, String defValue) { + if (registeredPreferences.containsKey(id)) { + return (CommonPreference) registeredPreferences.get(id); } + StringPreference p = new StringPreference(this, id, defValue); + registeredPreferences.put(id, p); + return p; } - public class ContextMenuItemsPreference extends CommonPreference { - @NonNull - private String idScheme; - - private ContextMenuItemsPreference(String id, @NonNull String idScheme, @NonNull ContextMenuItemsSettings defValue) { - super(id, defValue); - this.idScheme = idScheme; - } - - @Override - protected ContextMenuItemsSettings getValue(Object prefs, ContextMenuItemsSettings defaultValue) { - String s = settingsAPI.getString(prefs, getId(), ""); - return readValue(s); - } - - @Override - protected boolean setValue(Object prefs, ContextMenuItemsSettings val) { - return settingsAPI.edit(prefs).putString(getId(), val.writeToJsonString(idScheme)).commit(); - } - - - @Override - protected String toString(ContextMenuItemsSettings o) { - return o.writeToJsonString(idScheme); - } - - @Override - public ContextMenuItemsSettings parseString(String s) { - return readValue(s); - } - - private ContextMenuItemsSettings readValue(String s) { - ContextMenuItemsSettings value = getDefaultValue().newInstance(); - value.readFromJsonString(s, idScheme); - return value; - } - - @NonNull - public String getIdScheme() { - return idScheme; + @SuppressWarnings("unchecked") + public CommonPreference registerIntPreference(String id, int defValue) { + if (registeredPreferences.containsKey(id)) { + return (CommonPreference) registeredPreferences.get(id); } + IntPreference p = new IntPreference(this, id, defValue); + registeredPreferences.put(id, p); + return p; } - public static class ContextMenuItemsSettings implements Serializable { - private static final String HIDDEN = "hidden"; - private static final String ORDER = "order"; - private List hiddenIds = new ArrayList<>(); - private List orderIds = new ArrayList<>(); - - public ContextMenuItemsSettings() { - - } - - public ContextMenuItemsSettings(@NonNull List hiddenIds, @NonNull List orderIds) { - this.hiddenIds = hiddenIds; - this.orderIds = orderIds; - } - - public ContextMenuItemsSettings newInstance() { - return new ContextMenuItemsSettings(); - } - - public void readFromJsonString(String jsonString, @NonNull String idScheme) { - if (Algorithms.isEmpty(jsonString)) { - return; - } - try { - JSONObject json = new JSONObject(jsonString); - readFromJson(json, idScheme); - } catch (JSONException e) { - LOG.error("Error converting to json string: " + e); - } - } - - public void readFromJson(JSONObject json, String idScheme) { - hiddenIds = readIdsList(json.optJSONArray(HIDDEN), idScheme); - orderIds = readIdsList(json.optJSONArray(ORDER), idScheme); - } - - protected List readIdsList(JSONArray jsonArray, @NonNull String idScheme) { - List list = new ArrayList<>(); - if (jsonArray != null) { - for (int i = 0; i < jsonArray.length(); i++) { - String id = jsonArray.optString(i); - list.add(idScheme + id); - } - } - return list; - } - - public String writeToJsonString(@NonNull String idScheme) { - try { - JSONObject json = new JSONObject(); - writeToJson(json, idScheme); - return json.toString(); - } catch (JSONException e) { - LOG.error("Error converting to json string: " + e); - } - return ""; - } - - public void writeToJson(JSONObject json, String idScheme) throws JSONException { - json.put(HIDDEN, getJsonArray(hiddenIds, idScheme)); - json.put(ORDER, getJsonArray(orderIds, idScheme)); - } - - protected JSONArray getJsonArray(List ids, @NonNull String idScheme) { - JSONArray jsonArray = new JSONArray(); - if (ids != null && !ids.isEmpty()) { - for (String id : ids) { - jsonArray.put(id.replace(idScheme, "")); - } - } - return jsonArray; - } - - public List getHiddenIds() { - return Collections.unmodifiableList(hiddenIds); - } - - public List getOrderIds() { - return Collections.unmodifiableList(orderIds); + @SuppressWarnings("unchecked") + public CommonPreference registerLongPreference(String id, long defValue) { + if (registeredPreferences.containsKey(id)) { + return (CommonPreference) registeredPreferences.get(id); } + LongPreference p = new LongPreference(this, id, defValue); + registeredPreferences.put(id, p); + return p; } - public static class MainContextMenuItemsSettings extends ContextMenuItemsSettings { - private static final String MAIN = "main"; - private List mainIds = new ArrayList<>(); - - public MainContextMenuItemsSettings() { - - } - - public MainContextMenuItemsSettings(@NonNull List mainIds, @NonNull List hiddenIds, @NonNull List orderIds) { - super(hiddenIds, orderIds); - this.mainIds = mainIds; - } - - @Override - public ContextMenuItemsSettings newInstance() { - return new MainContextMenuItemsSettings(); - } - - @Override - public void readFromJson(JSONObject json, String idScheme) { - super.readFromJson(json, idScheme); - mainIds = readIdsList(json.optJSONArray(MAIN), idScheme); - } - - @Override - public void writeToJson(JSONObject json, String idScheme) throws JSONException { - super.writeToJson(json, idScheme); - json.put(MAIN, getJsonArray(mainIds, idScheme)); - } - - public List getMainIds() { - return Collections.unmodifiableList(mainIds); + @SuppressWarnings("unchecked") + public CommonPreference registerFloatPreference(String id, float defValue) { + if (registeredPreferences.containsKey(id)) { + return (CommonPreference) registeredPreferences.get(id); } + FloatPreference p = new FloatPreference(this, id, defValue); + registeredPreferences.put(id, p); + return p; } - public class EnumStringPreference> extends CommonPreference { - - private final E[] values; - - private EnumStringPreference(String id, E defaultValue, E[] values) { - super(id, defaultValue); - this.values = values; - } - - @Override - protected E getValue(Object prefs, E defaultValue) { - try { - String name = settingsAPI.getString(prefs, getId(), defaultValue.name()); - E value = parseString(name); - return value != null ? value : defaultValue; - } catch (ClassCastException ex) { - setValue(prefs, defaultValue); - } - return defaultValue; - } - - @Override - protected boolean setValue(Object prefs, E val) { - return settingsAPI.edit(prefs).putString(getId(), val.name()).commit(); - } - - @Override - protected String toString(E o) { - return o.name(); - } - - @Override - public E parseString(String s) { - for (E value : values) { - if (value.name().equals(s)) { - return value; - } - } - return null; + @SuppressWarnings("unchecked") + public CommonPreference registerEnumIntPreference(String id, Enum defaultValue, Enum[] values, Class clz) { + if (registeredPreferences.containsKey(id)) { + return (CommonPreference) registeredPreferences.get(id); } + EnumStringPreference p = new EnumStringPreference(this, id, defaultValue, values); + registeredPreferences.put(id, p); + return p; } - ///////////// PREFERENCES classes //////////////// + ///////////////////// PREFERENCES //////////////// public static final String NUMBER_OF_FREE_DOWNLOADS_ID = "free_downloads_v3"; // this value string is synchronized with settings_pref.xml preference name - private final OsmandPreference PLUGINS = new StringPreference("enabled_plugins", MapillaryPlugin.ID).makeGlobal(); + private final OsmandPreference PLUGINS = new StringPreference(this, "enabled_plugins", MapillaryPlugin.ID).makeGlobal(); public Set getEnabledPlugins() { String plugs = PLUGINS.get(); @@ -1453,124 +673,54 @@ public class OsmandSettings { } - @SuppressWarnings("unchecked") - public CommonPreference registerBooleanPreference(String id, boolean defValue) { - if (registeredPreferences.containsKey(id)) { - return (CommonPreference) registeredPreferences.get(id); - } - BooleanPreference p = new BooleanPreference(id, defValue); - registeredPreferences.put(id, p); - return p; - } + public final CommonPreference RULER_MODE = new EnumStringPreference<>(this, "ruler_mode", RulerMode.FIRST, RulerMode.values()).makeGlobal(); - @SuppressWarnings("unchecked") - public CommonPreference registerBooleanAccessibilityPreference(String id, boolean defValue) { - if (registeredPreferences.containsKey(id)) { - return (CommonPreference) registeredPreferences.get(id); - } - BooleanPreference p = new BooleanAccessibilityPreference(id, defValue); - registeredPreferences.put(id, p); - return p; - } + public final OsmandPreference SHOW_COMPASS_CONTROL_RULER = new BooleanPreference(this, "show_compass_ruler", true).makeGlobal(); - @SuppressWarnings("unchecked") - public CommonPreference registerStringPreference(String id, String defValue) { - if (registeredPreferences.containsKey(id)) { - return (CommonPreference) registeredPreferences.get(id); - } - StringPreference p = new StringPreference(id, defValue); - registeredPreferences.put(id, p); - return p; - } + public final CommonPreference SHOW_LINES_TO_FIRST_MARKERS = new BooleanPreference(this, "show_lines_to_first_markers", false).makeProfile(); + public final CommonPreference SHOW_ARROWS_TO_FIRST_MARKERS = new BooleanPreference(this, "show_arrows_to_first_markers", false).makeProfile(); - @SuppressWarnings("unchecked") - public CommonPreference registerIntPreference(String id, int defValue) { - if (registeredPreferences.containsKey(id)) { - return (CommonPreference) registeredPreferences.get(id); - } - IntPreference p = new IntPreference(id, defValue); - registeredPreferences.put(id, p); - return p; - } + public final CommonPreference WIKI_ARTICLE_SHOW_IMAGES_ASKED = new BooleanPreference(this, "wikivoyage_show_images_asked", false).makeGlobal(); + public final CommonPreference WIKI_ARTICLE_SHOW_IMAGES = new EnumStringPreference<>(this, "wikivoyage_show_imgs", WikiArticleShowImages.OFF, WikiArticleShowImages.values()).makeGlobal(); + public final CommonPreference SHOW_WIKIPEDIA_POI = new BooleanPreference(this, "show_wikipedia_poi", false).makeProfile(); + public final CommonPreference GLOBAL_WIKIPEDIA_POI_ENABLED = new BooleanPreference(this, "global_wikipedia_poi_enabled", false).makeProfile(); + public final ListStringPreference WIKIPEDIA_POI_ENABLED_LANGUAGES = (ListStringPreference) new ListStringPreference(this, "wikipedia_poi_enabled_languages", null, ",").makeProfile().cache(); - @SuppressWarnings("unchecked") - public CommonPreference registerLongPreference(String id, long defValue) { - if (registeredPreferences.containsKey(id)) { - return (CommonPreference) registeredPreferences.get(id); - } - LongPreference p = new LongPreference(id, defValue); - registeredPreferences.put(id, p); - return p; - } + public final CommonPreference SELECT_MARKER_ON_SINGLE_TAP = new BooleanPreference(this, "select_marker_on_single_tap", false).makeProfile(); + public final CommonPreference KEEP_PASSED_MARKERS_ON_MAP = new BooleanPreference(this, "keep_passed_markers_on_map", true).makeProfile(); - @SuppressWarnings("unchecked") - public CommonPreference registerFloatPreference(String id, float defValue) { - if (registeredPreferences.containsKey(id)) { - return (CommonPreference) registeredPreferences.get(id); - } - FloatPreference p = new FloatPreference(id, defValue); - registeredPreferences.put(id, p); - return p; - } + public final CommonPreference COORDS_INPUT_USE_RIGHT_SIDE = new BooleanPreference(this, "coords_input_use_right_side", true).makeGlobal(); + public final OsmandPreference COORDS_INPUT_FORMAT = new EnumStringPreference<>(this, "coords_input_format", Format.DD_MM_MMM, Format.values()).makeGlobal(); + public final CommonPreference COORDS_INPUT_USE_OSMAND_KEYBOARD = new BooleanPreference(this, "coords_input_use_osmand_keyboard", Build.VERSION.SDK_INT >= 16).makeGlobal(); + public final CommonPreference COORDS_INPUT_TWO_DIGITS_LONGTITUDE = new BooleanPreference(this, "coords_input_two_digits_longitude", false).makeGlobal(); - @SuppressWarnings("unchecked") - public CommonPreference registerEnumIntPreference(String id, Enum defaultValue, Enum[] values, Class clz) { - if (registeredPreferences.containsKey(id)) { - return (CommonPreference) registeredPreferences.get(id); - } - EnumStringPreference p = new EnumStringPreference(id, defaultValue, values); - registeredPreferences.put(id, p); - return p; - } + public final CommonPreference USE_MAPILLARY_FILTER = new BooleanPreference(this, "use_mapillary_filters", false).makeGlobal(); + public final CommonPreference MAPILLARY_FILTER_USER_KEY = new StringPreference(this, "mapillary_filter_user_key", "").makeGlobal(); + public final CommonPreference MAPILLARY_FILTER_USERNAME = new StringPreference(this, "mapillary_filter_username", "").makeGlobal(); + public final CommonPreference MAPILLARY_FILTER_FROM_DATE = new LongPreference(this, "mapillary_filter_from_date", 0).makeGlobal(); + public final CommonPreference MAPILLARY_FILTER_TO_DATE = new LongPreference(this, "mapillary_filter_to_date", 0).makeGlobal(); + public final CommonPreference MAPILLARY_FILTER_PANO = new BooleanPreference(this, "mapillary_filter_pano", false).makeGlobal(); - public final CommonPreference RULER_MODE = new EnumStringPreference<>("ruler_mode", RulerMode.FIRST, RulerMode.values()).makeGlobal(); + public final CommonPreference USE_FAST_RECALCULATION = new BooleanPreference(this, "use_fast_recalculation", true).makeGlobal().cache(); + public final CommonPreference FORCE_PRIVATE_ACCESS_ROUTING_ASKED = new BooleanPreference(this, "force_private_access_routing", false).makeProfile().cache(); - public final OsmandPreference SHOW_COMPASS_CONTROL_RULER = new BooleanPreference("show_compass_ruler", true).makeGlobal(); + public final CommonPreference SHOW_CARD_TO_CHOOSE_DRAWER = new BooleanPreference(this, "show_card_to_choose_drawer", false).makeGlobal(); + public final CommonPreference SHOW_DASHBOARD_ON_START = new BooleanPreference(this, "should_show_dashboard_on_start", false).makeGlobal(); + public final CommonPreference SHOW_DASHBOARD_ON_MAP_SCREEN = new BooleanPreference(this, "show_dashboard_on_map_screen", false).makeGlobal(); + public final CommonPreference SHOW_OSMAND_WELCOME_SCREEN = new BooleanPreference(this, "show_osmand_welcome_screen", true).makeGlobal(); - public final CommonPreference SHOW_LINES_TO_FIRST_MARKERS = new BooleanPreference("show_lines_to_first_markers", false).makeProfile(); - public final CommonPreference SHOW_ARROWS_TO_FIRST_MARKERS = new BooleanPreference("show_arrows_to_first_markers", false).makeProfile(); + public final CommonPreference API_NAV_DRAWER_ITEMS_JSON = new StringPreference(this, "api_nav_drawer_items_json", "{}").makeGlobal(); + public final CommonPreference API_CONNECTED_APPS_JSON = new StringPreference(this, "api_connected_apps_json", "[]").makeGlobal(); + public final CommonPreference NAV_DRAWER_LOGO = new StringPreference(this, "drawer_logo", "").makeProfile(); + public final CommonPreference NAV_DRAWER_URL = new StringPreference(this, "drawer_url", "").makeProfile(); - public final CommonPreference WIKI_ARTICLE_SHOW_IMAGES_ASKED = new BooleanPreference("wikivoyage_show_images_asked", false).makeGlobal(); - public final CommonPreference WIKI_ARTICLE_SHOW_IMAGES = new EnumStringPreference<>("wikivoyage_show_imgs", WikiArticleShowImages.OFF, WikiArticleShowImages.values()).makeGlobal(); - public final CommonPreference SHOW_WIKIPEDIA_POI = new BooleanPreference("show_wikipedia_poi", false).makeProfile(); - public final CommonPreference GLOBAL_WIKIPEDIA_POI_ENABLED = new BooleanPreference("global_wikipedia_poi_enabled", false).makeProfile(); - public final ListStringPreference WIKIPEDIA_POI_ENABLED_LANGUAGES = (ListStringPreference) new ListStringPreference("wikipedia_poi_enabled_languages", null, ",").makeProfile().cache(); + public final CommonPreference NUMBER_OF_STARTS_FIRST_XMAS_SHOWN = new IntPreference(this, "number_of_starts_first_xmas_shown", 0).makeGlobal(); - public final CommonPreference SELECT_MARKER_ON_SINGLE_TAP = new BooleanPreference("select_marker_on_single_tap", false).makeProfile(); - public final CommonPreference KEEP_PASSED_MARKERS_ON_MAP = new BooleanPreference("keep_passed_markers_on_map", true).makeProfile(); + public final OsmandPreference AVAILABLE_APP_MODES = new StringPreference(this, "available_application_modes", "car,bicycle,pedestrian,public_transport,").makeGlobal().cache(); - public final CommonPreference COORDS_INPUT_USE_RIGHT_SIDE = new BooleanPreference("coords_input_use_right_side", true).makeGlobal(); - public final OsmandPreference COORDS_INPUT_FORMAT = new EnumStringPreference<>("coords_input_format", Format.DD_MM_MMM, Format.values()).makeGlobal(); - public final CommonPreference COORDS_INPUT_USE_OSMAND_KEYBOARD = new BooleanPreference("coords_input_use_osmand_keyboard", Build.VERSION.SDK_INT >= 16).makeGlobal(); - public final CommonPreference COORDS_INPUT_TWO_DIGITS_LONGTITUDE = new BooleanPreference("coords_input_two_digits_longitude", false).makeGlobal(); + public final OsmandPreference LAST_FAV_CATEGORY_ENTERED = new StringPreference(this, "last_fav_category", "").makeGlobal(); - public final CommonPreference USE_MAPILLARY_FILTER = new BooleanPreference("use_mapillary_filters", false).makeGlobal(); - public final CommonPreference MAPILLARY_FILTER_USER_KEY = new StringPreference("mapillary_filter_user_key", "").makeGlobal(); - public final CommonPreference MAPILLARY_FILTER_USERNAME = new StringPreference("mapillary_filter_username", "").makeGlobal(); - public final CommonPreference MAPILLARY_FILTER_FROM_DATE = new LongPreference("mapillary_filter_from_date", 0).makeGlobal(); - public final CommonPreference MAPILLARY_FILTER_TO_DATE = new LongPreference("mapillary_filter_to_date", 0).makeGlobal(); - public final CommonPreference MAPILLARY_FILTER_PANO = new BooleanPreference("mapillary_filter_pano", false).makeGlobal(); - - public final CommonPreference USE_FAST_RECALCULATION = new BooleanPreference("use_fast_recalculation", true).makeGlobal().cache(); - public final CommonPreference FORCE_PRIVATE_ACCESS_ROUTING_ASKED = new BooleanPreference("force_private_access_routing", false).makeProfile().cache(); - - public final CommonPreference SHOW_CARD_TO_CHOOSE_DRAWER = new BooleanPreference("show_card_to_choose_drawer", false).makeGlobal(); - public final CommonPreference SHOW_DASHBOARD_ON_START = new BooleanPreference("should_show_dashboard_on_start", false).makeGlobal(); - public final CommonPreference SHOW_DASHBOARD_ON_MAP_SCREEN = new BooleanPreference("show_dashboard_on_map_screen", false).makeGlobal(); - public final CommonPreference SHOW_OSMAND_WELCOME_SCREEN = new BooleanPreference("show_osmand_welcome_screen", true).makeGlobal(); - - public final CommonPreference API_NAV_DRAWER_ITEMS_JSON = new StringPreference("api_nav_drawer_items_json", "{}").makeGlobal(); - public final CommonPreference API_CONNECTED_APPS_JSON = new StringPreference("api_connected_apps_json", "[]").makeGlobal(); - public final CommonPreference NAV_DRAWER_LOGO = new StringPreference("drawer_logo", "").makeProfile(); - public final CommonPreference NAV_DRAWER_URL = new StringPreference("drawer_url", "").makeProfile(); - - public final CommonPreference NUMBER_OF_STARTS_FIRST_XMAS_SHOWN = new IntPreference("number_of_starts_first_xmas_shown", 0).makeGlobal(); - - public final OsmandPreference AVAILABLE_APP_MODES = new StringPreference("available_application_modes", "car,bicycle,pedestrian,public_transport,").makeGlobal().cache(); - - public final OsmandPreference LAST_FAV_CATEGORY_ENTERED = new StringPreference("last_fav_category", "").makeGlobal(); - - public final OsmandPreference DEFAULT_APPLICATION_MODE = new CommonPreference("default_application_mode_string", ApplicationMode.DEFAULT) { + public final OsmandPreference DEFAULT_APPLICATION_MODE = new CommonPreference(this, "default_application_mode_string", ApplicationMode.DEFAULT) { @Override protected ApplicationMode getValue(Object prefs, ApplicationMode defaultValue) { @@ -1616,7 +766,7 @@ public class OsmandSettings { } }.makeGlobal(); - public final OsmandPreference LAST_ROUTE_APPLICATION_MODE = new CommonPreference("last_route_application_mode_backup_string", ApplicationMode.DEFAULT) { + public final OsmandPreference LAST_ROUTE_APPLICATION_MODE = new CommonPreference(this, "last_route_application_mode_backup_string", ApplicationMode.DEFAULT) { @Override protected ApplicationMode getValue(Object prefs, ApplicationMode defaultValue) { @@ -1657,11 +807,11 @@ public class OsmandSettings { } }.makeGlobal(); - public final OsmandPreference FIRST_MAP_IS_DOWNLOADED = new BooleanPreference( + public final OsmandPreference FIRST_MAP_IS_DOWNLOADED = new BooleanPreference(this, "first_map_is_downloaded", false); - public final CommonPreference DRIVING_REGION_AUTOMATIC = new BooleanPreference("driving_region_automatic", true).makeProfile().cache(); - public final OsmandPreference DRIVING_REGION = new EnumStringPreference( + public final CommonPreference DRIVING_REGION_AUTOMATIC = new BooleanPreference(this, "driving_region_automatic", true).makeProfile().cache(); + public final OsmandPreference DRIVING_REGION = new EnumStringPreference(this, "default_driving_region", DrivingRegion.EUROPE_ASIA, DrivingRegion.values()) { protected boolean setValue(Object prefs, DrivingRegion val) { if (val != null) { @@ -1693,7 +843,7 @@ public class OsmandSettings { // this value string is synchronized with settings_pref.xml preference name // cache of metrics constants as they are used very often - public final OsmandPreference METRIC_SYSTEM = new EnumStringPreference( + public final OsmandPreference METRIC_SYSTEM = new EnumStringPreference(this, "default_metric_system", MetricsConstants.KILOMETERS_AND_METERS, MetricsConstants.values()) { protected MetricsConstants getDefaultValue() { return DRIVING_REGION.get().defMetrics; @@ -1703,8 +853,8 @@ public class OsmandSettings { //public final OsmandPreference COORDINATES_FORMAT = new IntPreference("coordinates_format", PointDescription.FORMAT_DEGREES).makeGlobal(); - public final OsmandPreference ANGULAR_UNITS = new EnumStringPreference( - "angular_measurement", AngularConstants.DEGREES, AngularConstants.values()).makeProfile(); + public final OsmandPreference ANGULAR_UNITS = new EnumStringPreference(this, + "angular_measurement", AngularConstants.DEGREES, AngularConstants.values()).makeProfile(); public static final String LAST_START_LAT = "last_searched_lat"; //$NON-NLS-1$ public static final String LAST_START_LON = "last_searched_lon"; //$NON-NLS-1$ @@ -1730,7 +880,7 @@ public class OsmandSettings { putFloat(LAST_START_LON, (float) lon).commit(); } - public final OsmandPreference SPEED_SYSTEM = new EnumStringPreference( + public final OsmandPreference SPEED_SYSTEM = new EnumStringPreference(this, "default_speed_system", SpeedConstants.KILOMETERS_PER_HOUR, SpeedConstants.values()) { @Override @@ -1759,25 +909,25 @@ public class OsmandSettings { // this value string is synchronized with settings_pref.xml preference name // cache of metrics constants as they are used very often - public final OsmandPreference DIRECTION_STYLE = new EnumStringPreference( + public final OsmandPreference DIRECTION_STYLE = new EnumStringPreference(this, "direction_style", RelativeDirectionStyle.SIDEWISE, RelativeDirectionStyle.values()).makeProfile().cache(); // this value string is synchronized with settings_pref.xml preference name // cache of metrics constants as they are used very often - public final OsmandPreference ACCESSIBILITY_MODE = new EnumStringPreference( + public final OsmandPreference ACCESSIBILITY_MODE = new EnumStringPreference(this, "accessibility_mode", AccessibilityMode.DEFAULT, AccessibilityMode.values()).makeProfile().cache(); // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference SPEECH_RATE = - new FloatPreference("speech_rate", 1f).makeProfile(); + new FloatPreference(this, "speech_rate", 1f).makeProfile(); public final OsmandPreference ARRIVAL_DISTANCE_FACTOR = - new FloatPreference("arrival_distance_factor", 1f).makeProfile(); + new FloatPreference(this, "arrival_distance_factor", 1f).makeProfile(); public final OsmandPreference SPEED_LIMIT_EXCEED = - new FloatPreference("speed_limit_exceed", 5f).makeProfile(); + new FloatPreference(this, "speed_limit_exceed", 5f).makeProfile(); - public final CommonPreference DEFAULT_SPEED = new FloatPreference("default_speed", 10f).makeProfile().cache(); + public final CommonPreference DEFAULT_SPEED = new FloatPreference(this, "default_speed", 10f).makeProfile().cache(); { DEFAULT_SPEED.setModeDefaultValue(ApplicationMode.DEFAULT, 1.5f); @@ -1789,13 +939,13 @@ public class OsmandSettings { DEFAULT_SPEED.setModeDefaultValue(ApplicationMode.SKI, 1.38f); } - public final OsmandPreference MIN_SPEED = new FloatPreference( + public final OsmandPreference MIN_SPEED = new FloatPreference(this, "min_speed", 0f).makeProfile().cache(); - public final OsmandPreference MAX_SPEED = new FloatPreference( + public final OsmandPreference MAX_SPEED = new FloatPreference(this, "max_speed", 0f).makeProfile().cache(); - public final CommonPreference ICON_RES_NAME = new StringPreference("app_mode_icon_res_name", "ic_world_globe_dark").makeProfile().cache(); + public final CommonPreference ICON_RES_NAME = new StringPreference(this, "app_mode_icon_res_name", "ic_world_globe_dark").makeProfile().cache(); { ICON_RES_NAME.setModeDefaultValue(ApplicationMode.DEFAULT, "ic_world_globe_dark"); @@ -1808,13 +958,13 @@ public class OsmandSettings { ICON_RES_NAME.setModeDefaultValue(ApplicationMode.SKI, "ic_action_skiing"); } - public final CommonPreference ICON_COLOR = new EnumStringPreference<>("app_mode_icon_color", ProfileIconColors.DEFAULT, ProfileIconColors.values()).makeProfile().cache(); + public final CommonPreference ICON_COLOR = new EnumStringPreference<>(this, "app_mode_icon_color", ProfileIconColors.DEFAULT, ProfileIconColors.values()).makeProfile().cache(); - public final CommonPreference USER_PROFILE_NAME = new StringPreference("user_profile_name", "").makeProfile().cache(); + public final CommonPreference USER_PROFILE_NAME = new StringPreference(this, "user_profile_name", "").makeProfile().cache(); - public final CommonPreference PARENT_APP_MODE = new StringPreference("parent_app_mode", null).makeProfile().cache(); + public final CommonPreference PARENT_APP_MODE = new StringPreference(this, "parent_app_mode", null).makeProfile().cache(); - public final CommonPreference ROUTING_PROFILE = new StringPreference("routing_profile", "").makeProfile().cache(); + public final CommonPreference ROUTING_PROFILE = new StringPreference(this, "routing_profile", "").makeProfile().cache(); { ROUTING_PROFILE.setModeDefaultValue(ApplicationMode.CAR, "car"); @@ -1826,13 +976,13 @@ public class OsmandSettings { ROUTING_PROFILE.setModeDefaultValue(ApplicationMode.SKI, "ski"); } - public final CommonPreference ROUTE_SERVICE = new EnumStringPreference<>("route_service", RouteService.OSMAND, RouteService.values()).makeProfile().cache(); + public final CommonPreference ROUTE_SERVICE = new EnumStringPreference<>(this, "route_service", RouteService.OSMAND, RouteService.values()).makeProfile().cache(); { ROUTE_SERVICE.setModeDefaultValue(ApplicationMode.AIRCRAFT, RouteService.STRAIGHT); } - public final CommonPreference NAVIGATION_ICON = new EnumStringPreference<>("navigation_icon", NavigationIcon.DEFAULT, NavigationIcon.values()).makeProfile().cache(); + public final CommonPreference NAVIGATION_ICON = new EnumStringPreference<>(this, "navigation_icon", NavigationIcon.DEFAULT, NavigationIcon.values()).makeProfile().cache(); { NAVIGATION_ICON.setModeDefaultValue(ApplicationMode.DEFAULT, NavigationIcon.DEFAULT); @@ -1843,7 +993,7 @@ public class OsmandSettings { NAVIGATION_ICON.setModeDefaultValue(ApplicationMode.SKI, NavigationIcon.DEFAULT); } - public final CommonPreference LOCATION_ICON = new EnumStringPreference<>("location_icon", LocationIcon.DEFAULT, LocationIcon.values()).makeProfile().cache(); + public final CommonPreference LOCATION_ICON = new EnumStringPreference<>(this, "location_icon", LocationIcon.DEFAULT, LocationIcon.values()).makeProfile().cache(); { LOCATION_ICON.setModeDefaultValue(ApplicationMode.DEFAULT, LocationIcon.DEFAULT); @@ -1854,26 +1004,26 @@ public class OsmandSettings { LOCATION_ICON.setModeDefaultValue(ApplicationMode.SKI, LocationIcon.BICYCLE); } - public final CommonPreference APP_MODE_ORDER = new IntPreference("app_mode_order", 0).makeProfile().cache(); + public final CommonPreference APP_MODE_ORDER = new IntPreference(this, "app_mode_order", 0).makeProfile().cache(); public final OsmandPreference SWITCH_MAP_DIRECTION_TO_COMPASS = - new FloatPreference("speed_for_map_to_direction_of_movement", 0f).makeProfile(); + new FloatPreference(this, "speed_for_map_to_direction_of_movement", 0f).makeProfile(); // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference USE_TRACKBALL_FOR_MOVEMENTS = - new BooleanPreference("use_trackball_for_movements", true).makeProfile(); + new BooleanPreference(this, "use_trackball_for_movements", true).makeProfile(); // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference ACCESSIBILITY_SMART_AUTOANNOUNCE = - new BooleanAccessibilityPreference("accessibility_smart_autoannounce", true).makeProfile(); + new BooleanAccessibilityPreference(this, "accessibility_smart_autoannounce", true).makeProfile(); // this value string is synchronized with settings_pref.xml preference name // cache of metrics constants as they are used very often - public final OsmandPreference ACCESSIBILITY_AUTOANNOUNCE_PERIOD = new IntPreference("accessibility_autoannounce_period", 10000).makeProfile().cache(); + public final OsmandPreference ACCESSIBILITY_AUTOANNOUNCE_PERIOD = new IntPreference(this, "accessibility_autoannounce_period", 10000).makeProfile().cache(); // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference DISABLE_OFFROUTE_RECALC = - new BooleanAccessibilityPreference("disable_offroute_recalc", false).makeProfile(); + new BooleanAccessibilityPreference(this, "disable_offroute_recalc", false).makeProfile(); // this value string is synchronized with settings_pref.xml preference name // public final OsmandPreference DISABLE_WRONG_DIRECTION_RECALC = @@ -1881,103 +1031,103 @@ public class OsmandSettings { // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference DIRECTION_AUDIO_FEEDBACK = - new BooleanAccessibilityPreference("direction_audio_feedback", false).makeProfile(); + new BooleanAccessibilityPreference(this, "direction_audio_feedback", false).makeProfile(); // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference DIRECTION_HAPTIC_FEEDBACK = - new BooleanAccessibilityPreference("direction_haptic_feedback", false).makeProfile(); + new BooleanAccessibilityPreference(this, "direction_haptic_feedback", false).makeProfile(); // magnetic field doesn'torkmost of the time on some phones - public final OsmandPreference USE_MAGNETIC_FIELD_SENSOR_COMPASS = new BooleanPreference("use_magnetic_field_sensor_compass", false).makeProfile().cache(); - public final OsmandPreference USE_KALMAN_FILTER_FOR_COMPASS = new BooleanPreference("use_kalman_filter_compass", true).makeProfile().cache(); + public final OsmandPreference USE_MAGNETIC_FIELD_SENSOR_COMPASS = new BooleanPreference(this, "use_magnetic_field_sensor_compass", false).makeProfile().cache(); + public final OsmandPreference USE_KALMAN_FILTER_FOR_COMPASS = new BooleanPreference(this, "use_kalman_filter_compass", true).makeProfile().cache(); - public final OsmandPreference DO_NOT_SHOW_STARTUP_MESSAGES = new BooleanPreference("do_not_show_startup_messages", false).makeGlobal().cache(); - public final OsmandPreference SHOW_DOWNLOAD_MAP_DIALOG = new BooleanPreference("show_download_map_dialog", true).makeGlobal().cache(); - public final OsmandPreference DO_NOT_USE_ANIMATIONS = new BooleanPreference("do_not_use_animations", false).makeProfile().cache(); + public final OsmandPreference DO_NOT_SHOW_STARTUP_MESSAGES = new BooleanPreference(this, "do_not_show_startup_messages", false).makeGlobal().cache(); + public final OsmandPreference SHOW_DOWNLOAD_MAP_DIALOG = new BooleanPreference(this, "show_download_map_dialog", true).makeGlobal().cache(); + public final OsmandPreference DO_NOT_USE_ANIMATIONS = new BooleanPreference(this, "do_not_use_animations", false).makeProfile().cache(); - public final OsmandPreference SEND_ANONYMOUS_MAP_DOWNLOADS_DATA = new BooleanPreference("send_anonymous_map_downloads_data", false).makeGlobal().cache(); - public final OsmandPreference SEND_ANONYMOUS_APP_USAGE_DATA = new BooleanPreference("send_anonymous_app_usage_data", false).makeGlobal().cache(); - public final OsmandPreference SEND_ANONYMOUS_DATA_REQUEST_PROCESSED = new BooleanPreference("send_anonymous_data_request_processed", false).makeGlobal().cache(); - public final OsmandPreference SEND_ANONYMOUS_DATA_REQUESTS_COUNT = new IntPreference("send_anonymous_data_requests_count", 0).makeGlobal().cache(); - public final OsmandPreference SEND_ANONYMOUS_DATA_LAST_REQUEST_NS = new IntPreference("send_anonymous_data_last_request_ns", -1).makeGlobal().cache(); + public final OsmandPreference SEND_ANONYMOUS_MAP_DOWNLOADS_DATA = new BooleanPreference(this, "send_anonymous_map_downloads_data", false).makeGlobal().cache(); + public final OsmandPreference SEND_ANONYMOUS_APP_USAGE_DATA = new BooleanPreference(this, "send_anonymous_app_usage_data", false).makeGlobal().cache(); + public final OsmandPreference SEND_ANONYMOUS_DATA_REQUEST_PROCESSED = new BooleanPreference(this, "send_anonymous_data_request_processed", false).makeGlobal().cache(); + public final OsmandPreference SEND_ANONYMOUS_DATA_REQUESTS_COUNT = new IntPreference(this, "send_anonymous_data_requests_count", 0).makeGlobal().cache(); + public final OsmandPreference SEND_ANONYMOUS_DATA_LAST_REQUEST_NS = new IntPreference(this, "send_anonymous_data_last_request_ns", -1).makeGlobal().cache(); - public final OsmandPreference MAP_EMPTY_STATE_ALLOWED = new BooleanPreference("map_empty_state_allowed", false).makeProfile().cache(); + public final OsmandPreference MAP_EMPTY_STATE_ALLOWED = new BooleanPreference(this, "map_empty_state_allowed", false).makeProfile().cache(); - public final CommonPreference TEXT_SCALE = new FloatPreference("text_scale", 1f).makeProfile().cache(); + public final CommonPreference TEXT_SCALE = new FloatPreference(this, "text_scale", 1f).makeProfile().cache(); { TEXT_SCALE.setModeDefaultValue(ApplicationMode.CAR, 1.25f); } - public final CommonPreference MAP_DENSITY = new FloatPreference("map_density_n", 1f).makeProfile().cache(); + public final CommonPreference MAP_DENSITY = new FloatPreference(this, "map_density_n", 1f).makeProfile().cache(); { MAP_DENSITY.setModeDefaultValue(ApplicationMode.CAR, 1.5f); } - public final OsmandPreference SHOW_POI_LABEL = new BooleanPreference("show_poi_label", false).makeProfile(); + public final OsmandPreference SHOW_POI_LABEL = new BooleanPreference(this, "show_poi_label", false).makeProfile(); - public final OsmandPreference SHOW_MAPILLARY = new BooleanPreference("show_mapillary", false).makeProfile(); - public final OsmandPreference MAPILLARY_FIRST_DIALOG_SHOWN = new BooleanPreference("mapillary_first_dialog_shown", false).makeGlobal(); - public final OsmandPreference ONLINE_PHOTOS_ROW_COLLAPSED = new BooleanPreference("mapillary_menu_collapsed", true).makeGlobal(); - public final OsmandPreference WEBGL_SUPPORTED = new BooleanPreference("webgl_supported", true).makeGlobal(); + public final OsmandPreference SHOW_MAPILLARY = new BooleanPreference(this, "show_mapillary", false).makeProfile(); + public final OsmandPreference MAPILLARY_FIRST_DIALOG_SHOWN = new BooleanPreference(this, "mapillary_first_dialog_shown", false).makeGlobal(); + public final OsmandPreference ONLINE_PHOTOS_ROW_COLLAPSED = new BooleanPreference(this, "mapillary_menu_collapsed", true).makeGlobal(); + public final OsmandPreference WEBGL_SUPPORTED = new BooleanPreference(this, "webgl_supported", true).makeGlobal(); // this value string is synchronized with settings_pref.xml preference name - public final OsmandPreference PREFERRED_LOCALE = new StringPreference("preferred_locale", "").makeGlobal(); + public final OsmandPreference PREFERRED_LOCALE = new StringPreference(this, "preferred_locale", "").makeGlobal(); - public final OsmandPreference MAP_PREFERRED_LOCALE = new StringPreference("map_preferred_locale", "").makeGlobal().cache(); - public final OsmandPreference MAP_TRANSLITERATE_NAMES = new BooleanPreference("map_transliterate_names", false).makeGlobal().cache(); + public final OsmandPreference MAP_PREFERRED_LOCALE = new StringPreference(this, "map_preferred_locale", "").makeGlobal().cache(); + public final OsmandPreference MAP_TRANSLITERATE_NAMES = new BooleanPreference(this, "map_transliterate_names", false).makeGlobal().cache(); public boolean usingEnglishNames() { return MAP_PREFERRED_LOCALE.get().equals("en"); } // this value string is synchronized with settings_pref.xml preference name - public final OsmandPreference USER_NAME = new StringPreference("user_name", "").makeGlobal(); + public final OsmandPreference USER_NAME = new StringPreference(this, "user_name", "").makeGlobal(); public static final String BILLING_USER_DONATION_WORLD_PARAMETER = ""; public static final String BILLING_USER_DONATION_NONE_PARAMETER = "none"; - public final OsmandPreference INAPPS_READ = new BooleanPreference("inapps_read", false).makeGlobal(); + public final OsmandPreference INAPPS_READ = new BooleanPreference(this, "inapps_read", false).makeGlobal(); - public final OsmandPreference BILLING_USER_ID = new StringPreference("billing_user_id", "").makeGlobal(); - public final OsmandPreference BILLING_USER_TOKEN = new StringPreference("billing_user_token", "").makeGlobal(); - public final OsmandPreference BILLING_USER_NAME = new StringPreference("billing_user_name", "").makeGlobal(); - public final OsmandPreference BILLING_USER_EMAIL = new StringPreference("billing_user_email", "").makeGlobal(); - public final OsmandPreference BILLING_USER_COUNTRY = new StringPreference("billing_user_country", "").makeGlobal(); - public final OsmandPreference BILLING_USER_COUNTRY_DOWNLOAD_NAME = new StringPreference("billing_user_country_download_name", BILLING_USER_DONATION_NONE_PARAMETER).makeGlobal(); - public final OsmandPreference BILLING_HIDE_USER_NAME = new BooleanPreference("billing_hide_user_name", false).makeGlobal(); - public final OsmandPreference BILLING_PURCHASE_TOKEN_SENT = new BooleanPreference("billing_purchase_token_sent", false).makeGlobal(); - public final OsmandPreference BILLING_PURCHASE_TOKENS_SENT = new StringPreference("billing_purchase_tokens_sent", "").makeGlobal(); - public final OsmandPreference LIVE_UPDATES_PURCHASED = new BooleanPreference("billing_live_updates_purchased", false).makeGlobal(); - public final OsmandPreference LIVE_UPDATES_PURCHASE_CANCELLED_TIME = new LongPreference("live_updates_purchase_cancelled_time", 0).makeGlobal(); - public final OsmandPreference LIVE_UPDATES_PURCHASE_CANCELLED_FIRST_DLG_SHOWN = new BooleanPreference("live_updates_purchase_cancelled_first_dlg_shown", false).makeGlobal(); - public final OsmandPreference LIVE_UPDATES_PURCHASE_CANCELLED_SECOND_DLG_SHOWN = new BooleanPreference("live_updates_purchase_cancelled_second_dlg_shown", false).makeGlobal(); - public final OsmandPreference FULL_VERSION_PURCHASED = new BooleanPreference("billing_full_version_purchased", false).makeGlobal(); - public final OsmandPreference DEPTH_CONTOURS_PURCHASED = new BooleanPreference("billing_sea_depth_purchased", false).makeGlobal(); - public final OsmandPreference EMAIL_SUBSCRIBED = new BooleanPreference("email_subscribed", false).makeGlobal(); + public final OsmandPreference BILLING_USER_ID = new StringPreference(this, "billing_user_id", "").makeGlobal(); + public final OsmandPreference BILLING_USER_TOKEN = new StringPreference(this, "billing_user_token", "").makeGlobal(); + public final OsmandPreference BILLING_USER_NAME = new StringPreference(this, "billing_user_name", "").makeGlobal(); + public final OsmandPreference BILLING_USER_EMAIL = new StringPreference(this, "billing_user_email", "").makeGlobal(); + public final OsmandPreference BILLING_USER_COUNTRY = new StringPreference(this, "billing_user_country", "").makeGlobal(); + public final OsmandPreference BILLING_USER_COUNTRY_DOWNLOAD_NAME = new StringPreference(this, "billing_user_country_download_name", BILLING_USER_DONATION_NONE_PARAMETER).makeGlobal(); + public final OsmandPreference BILLING_HIDE_USER_NAME = new BooleanPreference(this, "billing_hide_user_name", false).makeGlobal(); + public final OsmandPreference BILLING_PURCHASE_TOKEN_SENT = new BooleanPreference(this, "billing_purchase_token_sent", false).makeGlobal(); + public final OsmandPreference BILLING_PURCHASE_TOKENS_SENT = new StringPreference(this, "billing_purchase_tokens_sent", "").makeGlobal(); + public final OsmandPreference LIVE_UPDATES_PURCHASED = new BooleanPreference(this, "billing_live_updates_purchased", false).makeGlobal(); + public final OsmandPreference LIVE_UPDATES_PURCHASE_CANCELLED_TIME = new LongPreference(this, "live_updates_purchase_cancelled_time", 0).makeGlobal(); + public final OsmandPreference LIVE_UPDATES_PURCHASE_CANCELLED_FIRST_DLG_SHOWN = new BooleanPreference(this, "live_updates_purchase_cancelled_first_dlg_shown", false).makeGlobal(); + public final OsmandPreference LIVE_UPDATES_PURCHASE_CANCELLED_SECOND_DLG_SHOWN = new BooleanPreference(this, "live_updates_purchase_cancelled_second_dlg_shown", false).makeGlobal(); + public final OsmandPreference FULL_VERSION_PURCHASED = new BooleanPreference(this, "billing_full_version_purchased", false).makeGlobal(); + public final OsmandPreference DEPTH_CONTOURS_PURCHASED = new BooleanPreference(this, "billing_sea_depth_purchased", false).makeGlobal(); + public final OsmandPreference EMAIL_SUBSCRIBED = new BooleanPreference(this, "email_subscribed", false).makeGlobal(); - public final OsmandPreference DISCOUNT_ID = new IntPreference("discount_id", 0).makeGlobal(); - public final OsmandPreference DISCOUNT_SHOW_NUMBER_OF_STARTS = new IntPreference("number_of_starts_on_discount_show", 0).makeGlobal(); - public final OsmandPreference DISCOUNT_TOTAL_SHOW = new IntPreference("discount_total_show", 0).makeGlobal(); - public final OsmandPreference DISCOUNT_SHOW_DATETIME_MS = new LongPreference("show_discount_datetime_ms", 0).makeGlobal(); + public final OsmandPreference DISCOUNT_ID = new IntPreference(this, "discount_id", 0).makeGlobal(); + public final OsmandPreference DISCOUNT_SHOW_NUMBER_OF_STARTS = new IntPreference(this, "number_of_starts_on_discount_show", 0).makeGlobal(); + public final OsmandPreference DISCOUNT_TOTAL_SHOW = new IntPreference(this, "discount_total_show", 0).makeGlobal(); + public final OsmandPreference DISCOUNT_SHOW_DATETIME_MS = new LongPreference(this, "show_discount_datetime_ms", 0).makeGlobal(); // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference USER_OSM_BUG_NAME = - new StringPreference("user_osm_bug_name", "NoName/OsmAnd").makeGlobal(); + new StringPreference(this, "user_osm_bug_name", "NoName/OsmAnd").makeGlobal(); // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference USER_PASSWORD = - new StringPreference("user_password", "").makeGlobal(); + new StringPreference(this, "user_password", "").makeGlobal(); // this value boolean is synchronized with settings_pref.xml preference offline POI/Bugs edition - public final OsmandPreference OFFLINE_EDITION = new BooleanPreference("offline_osm_editing", true).makeGlobal(); + public final OsmandPreference OFFLINE_EDITION = new BooleanPreference(this, "offline_osm_editing", true).makeGlobal(); // this value string is synchronized with settings_pref.xml preference name public final CommonPreference DAYNIGHT_MODE = - new EnumStringPreference("daynight_mode", DayNightMode.DAY, DayNightMode.values()); + new EnumStringPreference(this, "daynight_mode", DayNightMode.DAY, DayNightMode.values()); { DAYNIGHT_MODE.makeProfile().cache(); @@ -1987,7 +1137,7 @@ public class OsmandSettings { } // this value string is synchronized with settings_pref.xml preference name - public final CommonPreference AUTO_ZOOM_MAP = new BooleanPreference("auto_zoom_map_on_off", false).makeProfile().cache(); + public final CommonPreference AUTO_ZOOM_MAP = new BooleanPreference(this, "auto_zoom_map_on_off", false).makeProfile().cache(); { AUTO_ZOOM_MAP.setModeDefaultValue(ApplicationMode.CAR, true); AUTO_ZOOM_MAP.setModeDefaultValue(ApplicationMode.BICYCLE, false); @@ -1995,7 +1145,7 @@ public class OsmandSettings { } public final CommonPreference AUTO_ZOOM_MAP_SCALE = - new EnumStringPreference("auto_zoom_map_scale", AutoZoomMap.FAR, + new EnumStringPreference(this, "auto_zoom_map_scale", AutoZoomMap.FAR, AutoZoomMap.values()).makeProfile().cache(); { AUTO_ZOOM_MAP_SCALE.setModeDefaultValue(ApplicationMode.CAR, AutoZoomMap.FAR); @@ -2003,7 +1153,7 @@ public class OsmandSettings { AUTO_ZOOM_MAP_SCALE.setModeDefaultValue(ApplicationMode.PEDESTRIAN, AutoZoomMap.CLOSE); } - public final CommonPreference DELAY_TO_START_NAVIGATION = new IntPreference("delay_to_start_navigation", -1) { + public final CommonPreference DELAY_TO_START_NAVIGATION = new IntPreference(this, "delay_to_start_navigation", -1) { protected Integer getDefaultValue() { if (DEFAULT_APPLICATION_MODE.get().isDerivedRoutingFrom(ApplicationMode.CAR)) { @@ -2013,16 +1163,16 @@ public class OsmandSettings { } }.makeGlobal().cache(); - public final CommonPreference SNAP_TO_ROAD = new BooleanPreference("snap_to_road", false).makeProfile().cache(); + public final CommonPreference SNAP_TO_ROAD = new BooleanPreference(this, "snap_to_road", false).makeProfile().cache(); { SNAP_TO_ROAD.setModeDefaultValue(ApplicationMode.CAR, true); SNAP_TO_ROAD.setModeDefaultValue(ApplicationMode.BICYCLE, true); } - public final CommonPreference INTERRUPT_MUSIC = new BooleanPreference("interrupt_music", false).makeProfile(); + public final CommonPreference INTERRUPT_MUSIC = new BooleanPreference(this, "interrupt_music", false).makeProfile(); - public final CommonPreference ENABLE_PROXY = new BooleanPreference("enable_proxy", false) { + public final CommonPreference ENABLE_PROXY = new BooleanPreference(this, "enable_proxy", false) { @Override protected boolean setValue(Object prefs, Boolean val) { boolean valueSaved = super.setValue(prefs, val); @@ -2033,21 +1183,21 @@ public class OsmandSettings { } }.makeGlobal(); - public final CommonPreference PROXY_HOST = new StringPreference("proxy_host", "127.0.0.1").makeGlobal(); - public final CommonPreference PROXY_PORT = new IntPreference("proxy_port", 8118).makeGlobal(); - public final CommonPreference USER_ANDROID_ID = new StringPreference("user_android_id", "").makeGlobal(); + public final CommonPreference PROXY_HOST = new StringPreference(this, "proxy_host", "127.0.0.1").makeGlobal(); + public final CommonPreference PROXY_PORT = new IntPreference(this, "proxy_port", 8118).makeGlobal(); + public final CommonPreference USER_ANDROID_ID = new StringPreference(this, "user_android_id", "").makeGlobal(); - public final CommonPreference USE_SYSTEM_SCREEN_TIMEOUT = new BooleanPreference("use_system_screen_timeout", false).makeGlobal(); + public final CommonPreference USE_SYSTEM_SCREEN_TIMEOUT = new BooleanPreference(this, "use_system_screen_timeout", false).makeGlobal(); // this value string is synchronized with settings_pref.xml preference name public static final String SAVE_CURRENT_TRACK = "save_current_track"; //$NON-NLS-1$ - public final CommonPreference SAVE_GLOBAL_TRACK_TO_GPX = new BooleanPreference("save_global_track_to_gpx", false).makeGlobal().cache(); - public final CommonPreference SAVE_GLOBAL_TRACK_INTERVAL = new IntPreference("save_global_track_interval", 5000).makeProfile().cache(); - public final CommonPreference SAVE_GLOBAL_TRACK_REMEMBER = new BooleanPreference("save_global_track_remember", false).makeProfile().cache(); - public final CommonPreference SHOW_SAVED_TRACK_REMEMBER = new BooleanPreference("show_saved_track_remember", true).makeGlobal(); + public final CommonPreference SAVE_GLOBAL_TRACK_TO_GPX = new BooleanPreference(this, "save_global_track_to_gpx", false).makeGlobal().cache(); + public final CommonPreference SAVE_GLOBAL_TRACK_INTERVAL = new IntPreference(this, "save_global_track_interval", 5000).makeProfile().cache(); + public final CommonPreference SAVE_GLOBAL_TRACK_REMEMBER = new BooleanPreference(this, "save_global_track_remember", false).makeProfile().cache(); + public final CommonPreference SHOW_SAVED_TRACK_REMEMBER = new BooleanPreference(this, "show_saved_track_remember", true).makeGlobal(); // this value string is synchronized with settings_pref.xml preference name - public final CommonPreference SAVE_TRACK_TO_GPX = new BooleanPreference("save_track_to_gpx", false).makeProfile().cache(); + public final CommonPreference SAVE_TRACK_TO_GPX = new BooleanPreference(this, "save_track_to_gpx", false).makeProfile().cache(); { SAVE_TRACK_TO_GPX.setModeDefaultValue(ApplicationMode.CAR, false); @@ -2059,66 +1209,66 @@ public class OsmandSettings { public static final Integer MONTHLY_DIRECTORY = 1; // public static final Integer DAILY_DIRECTORY = 2; - public final CommonPreference DISABLE_RECORDING_ONCE_APP_KILLED = new BooleanPreference("disable_recording_once_app_killed", false).makeProfile(); + public final CommonPreference DISABLE_RECORDING_ONCE_APP_KILLED = new BooleanPreference(this, "disable_recording_once_app_killed", false).makeProfile(); - public final CommonPreference SAVE_HEADING_TO_GPX = new BooleanPreference("save_heading_to_gpx", false).makeProfile(); + public final CommonPreference SAVE_HEADING_TO_GPX = new BooleanPreference(this, "save_heading_to_gpx", false).makeProfile(); - public final CommonPreference TRACK_STORAGE_DIRECTORY = new IntPreference("track_storage_directory", 0).makeProfile(); + public final CommonPreference TRACK_STORAGE_DIRECTORY = new IntPreference(this, "track_storage_directory", 0).makeProfile(); // this value string is synchronized with settings_pref.xml preference name - public final OsmandPreference FAST_ROUTE_MODE = new BooleanPreference("fast_route_mode", true).makeProfile(); + public final OsmandPreference FAST_ROUTE_MODE = new BooleanPreference(this, "fast_route_mode", true).makeProfile(); // dev version - public final CommonPreference DISABLE_COMPLEX_ROUTING = new BooleanPreference("disable_complex_routing", false).makeGlobal(); - public final CommonPreference ENABLE_TIME_CONDITIONAL_ROUTING = new BooleanPreference("enable_time_conditional_routing", true).makeProfile(); + public final CommonPreference DISABLE_COMPLEX_ROUTING = new BooleanPreference(this, "disable_complex_routing", false).makeGlobal(); + public final CommonPreference ENABLE_TIME_CONDITIONAL_ROUTING = new BooleanPreference(this, "enable_time_conditional_routing", true).makeProfile(); public boolean simulateNavigation = false; - public final CommonPreference SHOW_ROUTING_ALARMS = new BooleanPreference("show_routing_alarms", true).makeProfile().cache(); + public final CommonPreference SHOW_ROUTING_ALARMS = new BooleanPreference(this, "show_routing_alarms", true).makeProfile().cache(); - public final CommonPreference SHOW_TRAFFIC_WARNINGS = new BooleanPreference("show_traffic_warnings", false).makeProfile().cache(); + public final CommonPreference SHOW_TRAFFIC_WARNINGS = new BooleanPreference(this, "show_traffic_warnings", false).makeProfile().cache(); { SHOW_TRAFFIC_WARNINGS.setModeDefaultValue(ApplicationMode.CAR, true); } - public final CommonPreference SHOW_PEDESTRIAN = new BooleanPreference("show_pedestrian", false).makeProfile().cache(); + public final CommonPreference SHOW_PEDESTRIAN = new BooleanPreference(this, "show_pedestrian", false).makeProfile().cache(); { SHOW_PEDESTRIAN.setModeDefaultValue(ApplicationMode.CAR, true); } - public final CommonPreference SHOW_TUNNELS = new BooleanPreference("show_tunnels", false).makeProfile().cache(); + public final CommonPreference SHOW_TUNNELS = new BooleanPreference(this, "show_tunnels", false).makeProfile().cache(); { SHOW_TUNNELS.setModeDefaultValue(ApplicationMode.CAR, true); } - public final OsmandPreference SHOW_CAMERAS = new BooleanPreference("show_cameras", false).makeProfile().cache(); - public final CommonPreference SHOW_LANES = new BooleanPreference("show_lanes", false).makeProfile().cache(); + public final OsmandPreference SHOW_CAMERAS = new BooleanPreference(this, "show_cameras", false).makeProfile().cache(); + public final CommonPreference SHOW_LANES = new BooleanPreference(this, "show_lanes", false).makeProfile().cache(); { SHOW_LANES.setModeDefaultValue(ApplicationMode.CAR, true); SHOW_LANES.setModeDefaultValue(ApplicationMode.BICYCLE, true); } - public final OsmandPreference SHOW_WPT = new BooleanPreference("show_gpx_wpt", true).makeGlobal().cache(); - public final OsmandPreference SHOW_NEARBY_FAVORITES = new BooleanPreference("show_nearby_favorites", false).makeProfile().cache(); - public final OsmandPreference SHOW_NEARBY_POI = new BooleanPreference("show_nearby_poi", false).makeProfile().cache(); + public final OsmandPreference SHOW_WPT = new BooleanPreference(this, "show_gpx_wpt", true).makeGlobal().cache(); + public final OsmandPreference SHOW_NEARBY_FAVORITES = new BooleanPreference(this, "show_nearby_favorites", false).makeProfile().cache(); + public final OsmandPreference SHOW_NEARBY_POI = new BooleanPreference(this, "show_nearby_poi", false).makeProfile().cache(); - public final OsmandPreference SPEAK_STREET_NAMES = new BooleanPreference("speak_street_names", true).makeProfile().cache(); - public final CommonPreference SPEAK_TRAFFIC_WARNINGS = new BooleanPreference("speak_traffic_warnings", true).makeProfile().cache(); + public final OsmandPreference SPEAK_STREET_NAMES = new BooleanPreference(this, "speak_street_names", true).makeProfile().cache(); + public final CommonPreference SPEAK_TRAFFIC_WARNINGS = new BooleanPreference(this, "speak_traffic_warnings", true).makeProfile().cache(); { SPEAK_TRAFFIC_WARNINGS.setModeDefaultValue(ApplicationMode.CAR, true); } - public final CommonPreference SPEAK_PEDESTRIAN = new BooleanPreference("speak_pedestrian", false).makeProfile().cache(); + public final CommonPreference SPEAK_PEDESTRIAN = new BooleanPreference(this, "speak_pedestrian", false).makeProfile().cache(); { SPEAK_PEDESTRIAN.setModeDefaultValue(ApplicationMode.CAR, true); } - public final OsmandPreference SPEAK_SPEED_LIMIT = new BooleanPreference("speak_speed_limit", false).makeProfile().cache(); - public final OsmandPreference SPEAK_SPEED_CAMERA = new BooleanPreference("speak_cameras", false).makeProfile().cache(); - public final OsmandPreference SPEAK_TUNNELS = new BooleanPreference("speak_tunnels", false).makeProfile().cache(); + public final OsmandPreference SPEAK_SPEED_LIMIT = new BooleanPreference(this, "speak_speed_limit", false).makeProfile().cache(); + public final OsmandPreference SPEAK_SPEED_CAMERA = new BooleanPreference(this, "speak_cameras", false).makeProfile().cache(); + public final OsmandPreference SPEAK_TUNNELS = new BooleanPreference(this, "speak_tunnels", false).makeProfile().cache(); - public final OsmandPreference ANNOUNCE_WPT = new BooleanPreference("announce_wpt", true) { + public final OsmandPreference ANNOUNCE_WPT = new BooleanPreference(this, "announce_wpt", true) { @Override protected boolean setValue(Object prefs, Boolean val) { boolean valueSaved = super.setValue(prefs, val); @@ -2130,7 +1280,7 @@ public class OsmandSettings { } }.makeProfile().cache(); - public final OsmandPreference ANNOUNCE_NEARBY_FAVORITES = new BooleanPreference("announce_nearby_favorites", false) { + public final OsmandPreference ANNOUNCE_NEARBY_FAVORITES = new BooleanPreference(this, "announce_nearby_favorites", false) { @Override protected boolean setValue(Object prefs, Boolean val) { boolean valueSaved = super.setValue(prefs, val); @@ -2142,7 +1292,7 @@ public class OsmandSettings { } }.makeProfile().cache(); - public final OsmandPreference ANNOUNCE_NEARBY_POI = new BooleanPreference("announce_nearby_poi", false) { + public final OsmandPreference ANNOUNCE_NEARBY_POI = new BooleanPreference(this, "announce_nearby_poi", false) { @Override protected boolean setValue(Object prefs, Boolean val) { boolean valueSaved = super.setValue(prefs, val); @@ -2154,23 +1304,23 @@ public class OsmandSettings { } }.makeProfile().cache(); - public final OsmandPreference GPX_ROUTE_CALC_OSMAND_PARTS = new BooleanPreference("gpx_routing_calculate_osmand_route", true).makeGlobal().cache(); - public final OsmandPreference GPX_CALCULATE_RTEPT = new BooleanPreference("gpx_routing_calculate_rtept", true).makeGlobal().cache(); - public final OsmandPreference GPX_ROUTE_CALC = new BooleanPreference("calc_gpx_route", false).makeGlobal().cache(); + public final OsmandPreference GPX_ROUTE_CALC_OSMAND_PARTS = new BooleanPreference(this, "gpx_routing_calculate_osmand_route", true).makeGlobal().cache(); + public final OsmandPreference GPX_CALCULATE_RTEPT = new BooleanPreference(this, "gpx_routing_calculate_rtept", true).makeGlobal().cache(); + public final OsmandPreference GPX_ROUTE_CALC = new BooleanPreference(this, "calc_gpx_route", false).makeGlobal().cache(); - public final OsmandPreference AVOID_TOLL_ROADS = new BooleanPreference("avoid_toll_roads", false).makeProfile().cache(); - public final OsmandPreference AVOID_MOTORWAY = new BooleanPreference("avoid_motorway", false).makeProfile().cache(); - public final OsmandPreference AVOID_UNPAVED_ROADS = new BooleanPreference("avoid_unpaved_roads", false).makeProfile().cache(); - public final OsmandPreference AVOID_FERRIES = new BooleanPreference("avoid_ferries", false).makeProfile().cache(); + public final OsmandPreference AVOID_TOLL_ROADS = new BooleanPreference(this, "avoid_toll_roads", false).makeProfile().cache(); + public final OsmandPreference AVOID_MOTORWAY = new BooleanPreference(this, "avoid_motorway", false).makeProfile().cache(); + public final OsmandPreference AVOID_UNPAVED_ROADS = new BooleanPreference(this, "avoid_unpaved_roads", false).makeProfile().cache(); + public final OsmandPreference AVOID_FERRIES = new BooleanPreference(this, "avoid_ferries", false).makeProfile().cache(); - public final OsmandPreference PREFER_MOTORWAYS = new BooleanPreference("prefer_motorways", false).makeProfile().cache(); + public final OsmandPreference PREFER_MOTORWAYS = new BooleanPreference(this, "prefer_motorways", false).makeProfile().cache(); - public final OsmandPreference LAST_UPDATES_CARD_REFRESH = new LongPreference("last_updates_card_refresh", 0).makeGlobal(); + public final OsmandPreference LAST_UPDATES_CARD_REFRESH = new LongPreference(this, "last_updates_card_refresh", 0).makeGlobal(); - public final CommonPreference CURRENT_TRACK_COLOR = new IntPreference("current_track_color", 0).makeGlobal().cache(); + public final CommonPreference CURRENT_TRACK_COLOR = new IntPreference(this, "current_track_color", 0).makeGlobal().cache(); // this value string is synchronized with settings_pref.xml preference name - public final CommonPreference SAVE_TRACK_INTERVAL = new IntPreference("save_track_interval", 5000).makeProfile(); + public final CommonPreference SAVE_TRACK_INTERVAL = new IntPreference(this, "save_track_interval", 5000).makeProfile(); { SAVE_TRACK_INTERVAL.setModeDefaultValue(ApplicationMode.CAR, 3000); @@ -2179,52 +1329,52 @@ public class OsmandSettings { } // Please note that SAVE_TRACK_MIN_DISTANCE, SAVE_TRACK_PRECISION, SAVE_TRACK_MIN_SPEED should all be "0" for the default profile, as we have no interface to change them - public final CommonPreference SAVE_TRACK_MIN_DISTANCE = new FloatPreference("save_track_min_distance", 0).makeProfile(); + public final CommonPreference SAVE_TRACK_MIN_DISTANCE = new FloatPreference(this, "save_track_min_distance", 0).makeProfile(); //{ // SAVE_TRACK_MIN_DISTANCE.setModeDefaultValue(ApplicationMode.CAR, 5.f); // SAVE_TRACK_MIN_DISTANCE.setModeDefaultValue(ApplicationMode.BICYCLE, 5.f); // SAVE_TRACK_MIN_DISTANCE.setModeDefaultValue(ApplicationMode.PEDESTRIAN, 5.f); //} - public final CommonPreference SAVE_TRACK_PRECISION = new FloatPreference("save_track_precision", 50.0f).makeProfile(); + public final CommonPreference SAVE_TRACK_PRECISION = new FloatPreference(this, "save_track_precision", 50.0f).makeProfile(); //{ // SAVE_TRACK_PRECISION.setModeDefaultValue(ApplicationMode.CAR, 50.f); // SAVE_TRACK_PRECISION.setModeDefaultValue(ApplicationMode.BICYCLE, 50.f); // SAVE_TRACK_PRECISION.setModeDefaultValue(ApplicationMode.PEDESTRIAN, 50.f); //} - public final CommonPreference SAVE_TRACK_MIN_SPEED = new FloatPreference("save_track_min_speed", 0.f).makeProfile(); + public final CommonPreference SAVE_TRACK_MIN_SPEED = new FloatPreference(this, "save_track_min_speed", 0.f).makeProfile(); //{ // SAVE_TRACK_MIN_SPEED.setModeDefaultValue(ApplicationMode.CAR, 2.f); // SAVE_TRACK_MIN_SPEED.setModeDefaultValue(ApplicationMode.BICYCLE, 1.f); // SAVE_TRACK_MIN_SPEED.setModeDefaultValue(ApplicationMode.PEDESTRIAN, 0.f); //} - public final CommonPreference AUTO_SPLIT_RECORDING = new BooleanPreference("auto_split_recording", true).makeProfile(); + public final CommonPreference AUTO_SPLIT_RECORDING = new BooleanPreference(this, "auto_split_recording", true).makeProfile(); - public final CommonPreference SHOW_TRIP_REC_NOTIFICATION = new BooleanPreference("show_trip_recording_notification", true).makeProfile(); + public final CommonPreference SHOW_TRIP_REC_NOTIFICATION = new BooleanPreference(this, "show_trip_recording_notification", true).makeProfile(); // this value string is synchronized with settings_pref.xml preference name - public final CommonPreference LIVE_MONITORING = new BooleanPreference("live_monitoring", false).makeProfile(); + public final CommonPreference LIVE_MONITORING = new BooleanPreference(this, "live_monitoring", false).makeProfile(); // this value string is synchronized with settings_pref.xml preference name - public final CommonPreference LIVE_MONITORING_INTERVAL = new IntPreference("live_monitoring_interval", 5000).makeProfile(); + public final CommonPreference LIVE_MONITORING_INTERVAL = new IntPreference(this, "live_monitoring_interval", 5000).makeProfile(); // this value string is synchronized with settings_pref.xml preference name - public final CommonPreference LIVE_MONITORING_MAX_INTERVAL_TO_SEND = new IntPreference("live_monitoring_maximum_interval_to_send", 900000).makeProfile(); + public final CommonPreference LIVE_MONITORING_MAX_INTERVAL_TO_SEND = new IntPreference(this, "live_monitoring_maximum_interval_to_send", 900000).makeProfile(); // this value string is synchronized with settings_pref.xml preference name - public final CommonPreference LIVE_MONITORING_URL = new StringPreference("live_monitoring_url", + public final CommonPreference LIVE_MONITORING_URL = new StringPreference(this, "live_monitoring_url", "https://example.com?lat={0}&lon={1}×tamp={2}&hdop={3}&altitude={4}&speed={5}").makeProfile(); - public final CommonPreference GPS_STATUS_APP = new StringPreference("gps_status_app", "").makeGlobal(); + public final CommonPreference GPS_STATUS_APP = new StringPreference(this, "gps_status_app", "").makeGlobal(); // this value string is synchronized with settings_pref.xml preference name - public final OsmandPreference SHOW_OSM_BUGS = new BooleanPreference("show_osm_bugs", false).makeProfile().cache(); + public final OsmandPreference SHOW_OSM_BUGS = new BooleanPreference(this, "show_osm_bugs", false).makeProfile().cache(); - public final OsmandPreference SHOW_OSM_EDITS = new BooleanPreference("show_osm_edits", true).makeProfile().cache(); + public final OsmandPreference SHOW_OSM_EDITS = new BooleanPreference(this, "show_osm_edits", true).makeProfile().cache(); - public final CommonPreference SHOW_CLOSED_OSM_BUGS = new BooleanPreference("show_closed_osm_bugs", false).makeProfile().cache(); - public final CommonPreference SHOW_OSM_BUGS_MIN_ZOOM = new IntPreference("show_osm_bugs_min_zoom", 8).makeProfile().cache(); + public final CommonPreference SHOW_CLOSED_OSM_BUGS = new BooleanPreference(this, "show_closed_osm_bugs", false).makeProfile().cache(); + public final CommonPreference SHOW_OSM_BUGS_MIN_ZOOM = new IntPreference(this, "show_osm_bugs_min_zoom", 8).makeProfile().cache(); - public final CommonPreference MAP_INFO_CONTROLS = new StringPreference("map_info_controls", "").makeProfile(); + public final CommonPreference MAP_INFO_CONTROLS = new StringPreference(this, "map_info_controls", "").makeProfile(); { for (ApplicationMode mode : ApplicationMode.allPossibleValues()) { MAP_INFO_CONTROLS.setModeDefaultValue(mode, ""); @@ -2233,23 +1383,23 @@ public class OsmandSettings { // this value string is synchronized with settings_pref.xml preference name - public final OsmandPreference DEBUG_RENDERING_INFO = new BooleanPreference("debug_rendering", false).makeGlobal(); + public final OsmandPreference DEBUG_RENDERING_INFO = new BooleanPreference(this, "debug_rendering", false).makeGlobal(); // this value string is synchronized with settings_pref.xml preference name - public final OsmandPreference SHOW_FAVORITES = new BooleanPreference("show_favorites", true).makeProfile().cache(); + public final OsmandPreference SHOW_FAVORITES = new BooleanPreference(this, "show_favorites", true).makeProfile().cache(); - public final CommonPreference SHOW_ZOOM_BUTTONS_NAVIGATION = new BooleanPreference("show_zoom_buttons_navigation", false).makeProfile().cache(); + public final CommonPreference SHOW_ZOOM_BUTTONS_NAVIGATION = new BooleanPreference(this, "show_zoom_buttons_navigation", false).makeProfile().cache(); { SHOW_ZOOM_BUTTONS_NAVIGATION.setModeDefaultValue(ApplicationMode.PEDESTRIAN, true); } // Json - public final OsmandPreference SELECTED_GPX = new StringPreference("selected_gpx", "").makeGlobal(); + public final OsmandPreference SELECTED_GPX = new StringPreference(this, "selected_gpx", "").makeGlobal(); // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference MAP_SCREEN_ORIENTATION = - new IntPreference("map_screen_orientation", -1/*ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED*/).makeProfile(); + new IntPreference(this, "map_screen_orientation", -1/*ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED*/).makeProfile(); // this value string is synchronized with settings_pref.xml preference name // public final CommonPreference SHOW_VIEW_ANGLE = new BooleanPreference("show_view_angle", false).makeProfile().cache(); @@ -2261,7 +1411,7 @@ public class OsmandSettings { // this value string is synchronized with settings_pref.xml preference name // seconds to auto_follow - public final CommonPreference AUTO_FOLLOW_ROUTE = new IntPreference("auto_follow_route", 0).makeProfile(); + public final CommonPreference AUTO_FOLLOW_ROUTE = new IntPreference(this, "auto_follow_route", 0).makeProfile(); { AUTO_FOLLOW_ROUTE.setModeDefaultValue(ApplicationMode.CAR, 15); @@ -2271,7 +1421,7 @@ public class OsmandSettings { // this value string is synchronized with settings_pref.xml preference name // seconds to auto_follow - public final CommonPreference KEEP_INFORMING = new IntPreference("keep_informing", 0).makeProfile(); + public final CommonPreference KEEP_INFORMING = new IntPreference(this, "keep_informing", 0).makeProfile(); { KEEP_INFORMING.setModeDefaultValue(ApplicationMode.CAR, 0); @@ -2279,9 +1429,9 @@ public class OsmandSettings { KEEP_INFORMING.setModeDefaultValue(ApplicationMode.PEDESTRIAN, 0); } - public final CommonPreference TURN_SCREEN_ON_ENABLED = new BooleanPreference("turn_screen_on_enabled", false).makeProfile(); + public final CommonPreference TURN_SCREEN_ON_ENABLED = new BooleanPreference(this, "turn_screen_on_enabled", false).makeProfile(); - public final CommonPreference TURN_SCREEN_ON_TIME_INT = new IntPreference("turn_screen_on_time_int", 0).makeProfile(); + public final CommonPreference TURN_SCREEN_ON_TIME_INT = new IntPreference(this, "turn_screen_on_time_int", 0).makeProfile(); { TURN_SCREEN_ON_TIME_INT.setModeDefaultValue(ApplicationMode.CAR, 0); @@ -2289,7 +1439,7 @@ public class OsmandSettings { TURN_SCREEN_ON_TIME_INT.setModeDefaultValue(ApplicationMode.PEDESTRIAN, 0); } - public final CommonPreference TURN_SCREEN_ON_SENSOR = new BooleanPreference("turn_screen_on_sensor", false).makeProfile(); + public final CommonPreference TURN_SCREEN_ON_SENSOR = new BooleanPreference(this, "turn_screen_on_sensor", false).makeProfile(); { TURN_SCREEN_ON_SENSOR.setModeDefaultValue(ApplicationMode.CAR, false); @@ -2306,7 +1456,7 @@ public class OsmandSettings { public static final int ROTATE_MAP_BEARING = 1; public static final int ROTATE_MAP_COMPASS = 2; public final CommonPreference ROTATE_MAP = - new IntPreference("rotate_map", ROTATE_MAP_NONE).makeProfile().cache(); + new IntPreference(this, "rotate_map", ROTATE_MAP_NONE).makeProfile().cache(); { ROTATE_MAP.setModeDefaultValue(ApplicationMode.CAR, ROTATE_MAP_BEARING); @@ -2320,16 +1470,16 @@ public class OsmandSettings { public static final int MIDDLE_BOTTOM_CONSTANT = 2; public static final int MIDDLE_TOP_CONSTANT = 3; public static final int LANDSCAPE_MIDDLE_RIGHT_CONSTANT = 4; - public final CommonPreference CENTER_POSITION_ON_MAP = new BooleanPreference("center_position_on_map", false).makeProfile(); + public final CommonPreference CENTER_POSITION_ON_MAP = new BooleanPreference(this, "center_position_on_map", false).makeProfile(); // this value string is synchronized with settings_pref.xml preference name - public final OsmandPreference MAX_LEVEL_TO_DOWNLOAD_TILE = new IntPreference("max_level_download_tile", 20).makeProfile().cache(); + public final OsmandPreference MAX_LEVEL_TO_DOWNLOAD_TILE = new IntPreference(this, "max_level_download_tile", 20).makeProfile().cache(); // this value string is synchronized with settings_pref.xml preference name - public final OsmandPreference LEVEL_TO_SWITCH_VECTOR_RASTER = new IntPreference("level_to_switch_vector_raster", 1).makeGlobal().cache(); + public final OsmandPreference LEVEL_TO_SWITCH_VECTOR_RASTER = new IntPreference(this, "level_to_switch_vector_raster", 1).makeGlobal().cache(); // this value string is synchronized with settings_pref.xml preference name - public final OsmandPreference AUDIO_MANAGER_STREAM = new IntPreference("audio_stream", 3/*AudioManager.STREAM_MUSIC*/) { + public final OsmandPreference AUDIO_MANAGER_STREAM = new IntPreference(this, "audio_stream", 3/*AudioManager.STREAM_MUSIC*/) { @Override protected boolean setValue(Object prefs, Integer stream) { boolean valueSaved = super.setValue(prefs, stream); @@ -2355,7 +1505,7 @@ public class OsmandSettings { }.makeProfile(); // Corresponding USAGE value for AudioAttributes - public final OsmandPreference AUDIO_USAGE = new IntPreference("audio_usage", + public final OsmandPreference AUDIO_USAGE = new IntPreference(this, "audio_usage", 12/*AudioAttributes.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE*/).makeProfile(); // For now this can be changed only in TestVoiceActivity @@ -2363,66 +1513,66 @@ public class OsmandSettings { { // 1500 ms delay works for most configurations to establish a BT SCO link - VOICE_PROMPT_DELAY[0] = new IntPreference("voice_prompt_delay_0", 1500).makeGlobal().cache(); /*AudioManager.STREAM_VOICE_CALL*/ + VOICE_PROMPT_DELAY[0] = new IntPreference(this, "voice_prompt_delay_0", 1500).makeGlobal().cache(); /*AudioManager.STREAM_VOICE_CALL*/ // On most devices sound output works pomptly so usually no voice prompt delay needed - VOICE_PROMPT_DELAY[3] = new IntPreference("voice_prompt_delay_3", 0).makeGlobal().cache(); /*AudioManager.STREAM_MUSIC*/ - VOICE_PROMPT_DELAY[5] = new IntPreference("voice_prompt_delay_5", 0).makeGlobal().cache(); /*AudioManager.STREAM_NOTIFICATION*/ + VOICE_PROMPT_DELAY[3] = new IntPreference(this, "voice_prompt_delay_3", 0).makeGlobal().cache(); /*AudioManager.STREAM_MUSIC*/ + VOICE_PROMPT_DELAY[5] = new IntPreference(this, "voice_prompt_delay_5", 0).makeGlobal().cache(); /*AudioManager.STREAM_NOTIFICATION*/ } // this value string is synchronized with settings_pref.xml preference name - public final CommonPreference MAP_ONLINE_DATA = new BooleanPreference("map_online_data", false).makeProfile(); + public final CommonPreference MAP_ONLINE_DATA = new BooleanPreference(this, "map_online_data", false).makeProfile(); - public final CommonPreference TERRAIN_MODE = new EnumStringPreference<>("terrain_mode", TerrainMode.HILLSHADE, TerrainMode.values()).makeProfile(); + public final CommonPreference TERRAIN_MODE = new EnumStringPreference<>(this, "terrain_mode", TerrainMode.HILLSHADE, TerrainMode.values()).makeProfile(); - public final CommonPreference HILLSHADE_MIN_ZOOM = new IntPreference("hillshade_min_zoom", 3).makeProfile(); + public final CommonPreference HILLSHADE_MIN_ZOOM = new IntPreference(this, "hillshade_min_zoom", 3).makeProfile(); - public final CommonPreference HILLSHADE_MAX_ZOOM = new IntPreference("hillshade_max_zoom", 17).makeProfile(); + public final CommonPreference HILLSHADE_MAX_ZOOM = new IntPreference(this, "hillshade_max_zoom", 17).makeProfile(); - public final CommonPreference HILLSHADE_TRANSPARENCY = new IntPreference("hillshade_transparency", 100).makeProfile(); + public final CommonPreference HILLSHADE_TRANSPARENCY = new IntPreference(this, "hillshade_transparency", 100).makeProfile(); - public final CommonPreference SLOPE_MIN_ZOOM = new IntPreference("slope_min_zoom", 3).makeProfile(); + public final CommonPreference SLOPE_MIN_ZOOM = new IntPreference(this, "slope_min_zoom", 3).makeProfile(); - public final CommonPreference SLOPE_MAX_ZOOM = new IntPreference("slope_max_zoom", 17).makeProfile(); + public final CommonPreference SLOPE_MAX_ZOOM = new IntPreference(this, "slope_max_zoom", 17).makeProfile(); - public final CommonPreference SLOPE_TRANSPARENCY = new IntPreference("slope_transparency", 80).makeProfile(); + public final CommonPreference SLOPE_TRANSPARENCY = new IntPreference(this, "slope_transparency", 80).makeProfile(); - public final CommonPreference TERRAIN = new BooleanPreference("terrain_layer", true).makeProfile(); + public final CommonPreference TERRAIN = new BooleanPreference(this, "terrain_layer", true).makeProfile(); - public final CommonPreference CONTOUR_LINES_ZOOM = new StringPreference("contour_lines_zoom", null).makeProfile().cache(); + public final CommonPreference CONTOUR_LINES_ZOOM = new StringPreference(this, "contour_lines_zoom", null).makeProfile().cache(); // this value string is synchronized with settings_pref.xml preference name - public final CommonPreference MAP_OVERLAY = new StringPreference("map_overlay", null).makeProfile().cache(); + public final CommonPreference MAP_OVERLAY = new StringPreference(this, "map_overlay", null).makeProfile().cache(); // this value string is synchronized with settings_pref.xml preference name - public final CommonPreference MAP_UNDERLAY = new StringPreference("map_underlay", null).makeProfile().cache(); + public final CommonPreference MAP_UNDERLAY = new StringPreference(this, "map_underlay", null).makeProfile().cache(); // this value string is synchronized with settings_pref.xml preference name - public final CommonPreference MAP_OVERLAY_TRANSPARENCY = new IntPreference("overlay_transparency", 100).makeProfile().cache(); + public final CommonPreference MAP_OVERLAY_TRANSPARENCY = new IntPreference(this, "overlay_transparency", 100).makeProfile().cache(); // this value string is synchronized with settings_pref.xml preference name - public final CommonPreference MAP_TRANSPARENCY = new IntPreference("map_transparency", 255).makeProfile().cache(); + public final CommonPreference MAP_TRANSPARENCY = new IntPreference(this, "map_transparency", 255).makeProfile().cache(); // this value string is synchronized with settings_pref.xml preference name - public final CommonPreference MAP_TILE_SOURCES = new StringPreference("map_tile_sources", + public final CommonPreference MAP_TILE_SOURCES = new StringPreference(this, "map_tile_sources", TileSourceManager.getMapnikSource().getName()).makeProfile(); public final CommonPreference LAYER_TRANSPARENCY_SEEKBAR_MODE = - new EnumStringPreference<>("layer_transparency_seekbar_mode", LayerTransparencySeekbarMode.UNDEFINED, LayerTransparencySeekbarMode.values()); + new EnumStringPreference<>(this, "layer_transparency_seekbar_mode", LayerTransparencySeekbarMode.UNDEFINED, LayerTransparencySeekbarMode.values()); - public final CommonPreference MAP_OVERLAY_PREVIOUS = new StringPreference("map_overlay_previous", null).makeGlobal().cache(); + public final CommonPreference MAP_OVERLAY_PREVIOUS = new StringPreference(this, "map_overlay_previous", null).makeGlobal().cache(); - public final CommonPreference MAP_UNDERLAY_PREVIOUS = new StringPreference("map_underlay_previous", null).makeGlobal().cache(); + public final CommonPreference MAP_UNDERLAY_PREVIOUS = new StringPreference(this, "map_underlay_previous", null).makeGlobal().cache(); - public CommonPreference PREVIOUS_INSTALLED_VERSION = new StringPreference("previous_installed_version", "").makeGlobal(); + public CommonPreference PREVIOUS_INSTALLED_VERSION = new StringPreference(this, "previous_installed_version", "").makeGlobal(); - public final OsmandPreference SHOULD_SHOW_FREE_VERSION_BANNER = new BooleanPreference("should_show_free_version_banner", false).makeGlobal().cache(); + public final OsmandPreference SHOULD_SHOW_FREE_VERSION_BANNER = new BooleanPreference(this, "should_show_free_version_banner", false).makeGlobal().cache(); - public final OsmandPreference MARKERS_DISTANCE_INDICATION_ENABLED = new BooleanPreference("markers_distance_indication_enabled", true).makeProfile(); + public final OsmandPreference MARKERS_DISTANCE_INDICATION_ENABLED = new BooleanPreference(this, "markers_distance_indication_enabled", true).makeProfile(); - public final OsmandPreference DISPLAYED_MARKERS_WIDGETS_COUNT = new IntPreference("displayed_markers_widgets_count", 1).makeProfile(); + public final OsmandPreference DISPLAYED_MARKERS_WIDGETS_COUNT = new IntPreference(this, "displayed_markers_widgets_count", 1).makeProfile(); public final CommonPreference MAP_MARKERS_MODE = - new EnumStringPreference<>("map_markers_mode", MapMarkersMode.TOOLBAR, MapMarkersMode.values()); + new EnumStringPreference<>(this, "map_markers_mode", MapMarkersMode.TOOLBAR, MapMarkersMode.values()); { MAP_MARKERS_MODE.makeProfile().cache(); @@ -2432,18 +1582,18 @@ public class OsmandSettings { MAP_MARKERS_MODE.setModeDefaultValue(ApplicationMode.PEDESTRIAN, MapMarkersMode.TOOLBAR); } - public final OsmandPreference SHOW_MAP_MARKERS = new BooleanPreference("show_map_markers", true).makeProfile(); + public final OsmandPreference SHOW_MAP_MARKERS = new BooleanPreference(this, "show_map_markers", true).makeProfile(); - public final OsmandPreference SHOW_COORDINATES_WIDGET = new BooleanPreference("show_coordinates_widget", false).makeProfile().cache(); + public final OsmandPreference SHOW_COORDINATES_WIDGET = new BooleanPreference(this, "show_coordinates_widget", false).makeProfile().cache(); - public final CommonPreference NOTES_SORT_BY_MODE = new EnumStringPreference<>("notes_sort_by_mode", NotesSortByMode.BY_DATE, NotesSortByMode.values()); + public final CommonPreference NOTES_SORT_BY_MODE = new EnumStringPreference<>(this, "notes_sort_by_mode", NotesSortByMode.BY_DATE, NotesSortByMode.values()); - public final OsmandPreference ANIMATE_MY_LOCATION = new BooleanPreference("animate_my_location", true).makeProfile().cache(); + public final OsmandPreference ANIMATE_MY_LOCATION = new BooleanPreference(this, "animate_my_location", true).makeProfile().cache(); - public final OsmandPreference EXTERNAL_INPUT_DEVICE = new IntPreference("external_input_device", 0).makeProfile(); + public final OsmandPreference EXTERNAL_INPUT_DEVICE = new IntPreference(this, "external_input_device", 0).makeProfile(); - public final OsmandPreference ROUTE_MAP_MARKERS_START_MY_LOC = new BooleanPreference("route_map_markers_start_my_loc", false).makeGlobal().cache(); - public final OsmandPreference ROUTE_MAP_MARKERS_ROUND_TRIP = new BooleanPreference("route_map_markers_round_trip", false).makeGlobal().cache(); + public final OsmandPreference ROUTE_MAP_MARKERS_START_MY_LOC = new BooleanPreference(this, "route_map_markers_start_my_loc", false).makeGlobal().cache(); + public final OsmandPreference ROUTE_MAP_MARKERS_ROUND_TRIP = new BooleanPreference(this, "route_map_markers_round_trip", false).makeGlobal().cache(); public ITileSource getMapTileSource(boolean warnWhenSelected) { String tileName = MAP_TILE_SOURCES.get(); @@ -2571,7 +1721,7 @@ public class OsmandSettings { public static final int EXTERNAL_STORAGE_TYPE_INTERNAL_FILE = 2; // ctx.getFilesDir() public static final int EXTERNAL_STORAGE_TYPE_OBB = 3; // ctx.getObbDirs public static final int EXTERNAL_STORAGE_TYPE_SPECIFIED = 4; - public final OsmandPreference OSMAND_USAGE_SPACE = new LongPreference("osmand_usage_space", 0).makeGlobal(); + public final OsmandPreference OSMAND_USAGE_SPACE = new LongPreference(this, "osmand_usage_space", 0).makeGlobal(); public void freezeExternalStorageDirectory() { @@ -2807,10 +1957,6 @@ public class OsmandSettings { } } - private Object objectToShow; - private boolean editObjectToShow; - private String searchRequestToShow; - public void setSearchRequestToShow(String request) { this.searchRequestToShow = request; } @@ -2902,10 +2048,10 @@ public class OsmandSettings { public final static String INTERMEDIATE_POINTS = "intermediate_points"; //$NON-NLS-1$ public final static String INTERMEDIATE_POINTS_DESCRIPTION = "intermediate_points_description"; //$NON-NLS-1$ - private IntermediatePointsStorage intermediatePointsStorage = new IntermediatePointsStorage(); - public final static String POINT_NAVIGATE_LAT_BACKUP = "point_navigate_lat_backup"; //$NON-NLS-1$ - public final static String POINT_NAVIGATE_LON_BACKUP = "point_navigate_lon_backup"; //$NON-NLS-1$ + + final static String POINT_NAVIGATE_LAT_BACKUP = "point_navigate_lat_backup"; //$NON-NLS-1$ + final static String POINT_NAVIGATE_LON_BACKUP = "point_navigate_lon_backup"; //$NON-NLS-1$ public final static String POINT_NAVIGATE_DESCRIPTION_BACKUP = "point_navigate_description_backup"; //$NON-NLS-1$ public final static String START_POINT_LAT_BACKUP = "start_point_lat_backup"; //$NON-NLS-1$ public final static String START_POINT_LON_BACKUP = "start_point_lon_backup"; //$NON-NLS-1$ @@ -2920,7 +2066,6 @@ public class OsmandSettings { private static final String IMPASSABLE_ROADS_DESCRIPTIONS = "impassable_roads_descriptions"; private static final String IMPASSABLE_ROADS_IDS = "impassable_roads_ids"; private static final String IMPASSABLE_ROADS_APP_MODE_KEYS = "impassable_roads_app_mode_keys"; - private ImpassableRoadsStorage mImpassableRoadsStorage = new ImpassableRoadsStorage(); public void backupPointToStart() { settingsAPI.edit(globalPreferences) @@ -3070,334 +2215,7 @@ public class OsmandSettings { } public final CommonPreference USE_INTERMEDIATE_POINTS_NAVIGATION = - new BooleanPreference("use_intermediate_points_navigation", false).makeGlobal().cache(); - - - private class IntermediatePointsStorage extends MapPointsStorage { - - public IntermediatePointsStorage() { - pointsKey = INTERMEDIATE_POINTS; - descriptionsKey = INTERMEDIATE_POINTS_DESCRIPTION; - } - - @Override - public boolean savePoints(List ps, List ds) { - boolean res = super.savePoints(ps, ds); - backupTargetPoints(); - return res; - } - } - - private class ImpassableRoadsStorage extends MapPointsStorage { - - protected String roadsIdsKey; - protected String appModeKey; - - public ImpassableRoadsStorage() { - pointsKey = IMPASSABLE_ROAD_POINTS; - descriptionsKey = IMPASSABLE_ROADS_DESCRIPTIONS; - roadsIdsKey = IMPASSABLE_ROADS_IDS; - appModeKey = IMPASSABLE_ROADS_APP_MODE_KEYS; - } - - public List getRoadIds(int size) { - List list = new ArrayList<>(); - String roadIds = settingsAPI.getString(globalPreferences, roadsIdsKey, ""); - if (roadIds.trim().length() > 0) { - StringTokenizer tok = new StringTokenizer(roadIds, ","); - while (tok.hasMoreTokens() && list.size() <= size) { - list.add(Long.parseLong(tok.nextToken())); - } - } - while (list.size() < size) { - list.add(0L); - } - return list; - } - - public List getAppModeKeys(int size) { - List list = new ArrayList<>(); - String roadIds = settingsAPI.getString(globalPreferences, appModeKey, ""); - if (roadIds.trim().length() > 0) { - StringTokenizer tok = new StringTokenizer(roadIds, ","); - while (tok.hasMoreTokens() && list.size() <= size) { - list.add(tok.nextToken()); - } - } - while (list.size() < size) { - list.add(""); - } - return list; - } - - public List getImpassableRoadsInfo() { - List points = getPoints(); - List roadIds = getRoadIds(points.size()); - List appModeKeys = getAppModeKeys(points.size()); - List descriptions = getPointDescriptions(points.size()); - - List avoidRoadsInfo = new ArrayList<>(); - - for (int i = 0; i < points.size(); i++) { - LatLon latLon = points.get(i); - PointDescription description = PointDescription.deserializeFromString(descriptions.get(i), null); - - AvoidRoadInfo avoidRoadInfo = new AvoidRoadInfo(); - avoidRoadInfo.id = roadIds.get(i); - avoidRoadInfo.latitude = latLon.getLatitude(); - avoidRoadInfo.longitude = latLon.getLongitude(); - avoidRoadInfo.name = description.getName(); - avoidRoadInfo.appModeKey = appModeKeys.get(i); - avoidRoadsInfo.add(avoidRoadInfo); - } - - return avoidRoadsInfo; - } - - public boolean addImpassableRoadInfo(AvoidRoadInfo avoidRoadInfo) { - List points = getPoints(); - List roadIds = getRoadIds(points.size()); - List appModeKeys = getAppModeKeys(points.size()); - List descriptions = getPointDescriptions(points.size()); - - roadIds.add(0, avoidRoadInfo.id); - points.add(0, new LatLon(avoidRoadInfo.latitude, avoidRoadInfo.longitude)); - appModeKeys.add(0, avoidRoadInfo.appModeKey); - descriptions.add(0, PointDescription.serializeToString(new PointDescription("", avoidRoadInfo.name))); - - return saveAvoidRoadData(points, descriptions, roadIds, appModeKeys); - } - - public boolean updateImpassableRoadInfo(AvoidRoadInfo avoidRoadInfo) { - List points = getPoints(); - - int index = points.indexOf(new LatLon(avoidRoadInfo.latitude, avoidRoadInfo.longitude)); - if (index != -1) { - List roadIds = getRoadIds(points.size()); - List appModeKeys = getAppModeKeys(points.size()); - List descriptions = getPointDescriptions(points.size()); - - roadIds.set(index, avoidRoadInfo.id); - appModeKeys.set(index, avoidRoadInfo.appModeKey); - descriptions.set(index, PointDescription.serializeToString(new PointDescription("", avoidRoadInfo.name))); - return saveAvoidRoadData(points, descriptions, roadIds, appModeKeys); - } - return false; - } - - @Override - public boolean deletePoint(int index) { - List points = getPoints(); - List roadIds = getRoadIds(points.size()); - List appModeKeys = getAppModeKeys(points.size()); - List descriptions = getPointDescriptions(points.size()); - - if (index < points.size()) { - points.remove(index); - roadIds.remove(index); - appModeKeys.remove(index); - descriptions.remove(index); - return saveAvoidRoadData(points, descriptions, roadIds, appModeKeys); - } - return false; - } - - @Override - public boolean deletePoint(LatLon latLon) { - List points = getPoints(); - List roadIds = getRoadIds(points.size()); - List appModeKeys = getAppModeKeys(points.size()); - List descriptions = getPointDescriptions(points.size()); - - int index = points.indexOf(latLon); - if (index != -1) { - points.remove(index); - roadIds.remove(index); - appModeKeys.remove(index); - descriptions.remove(index); - return saveAvoidRoadData(points, descriptions, roadIds, appModeKeys); - } - return false; - } - - @Override - public boolean movePoint(LatLon latLonEx, LatLon latLonNew) { - List points = getPoints(); - List roadIds = getRoadIds(points.size()); - List appModeKeys = getAppModeKeys(points.size()); - List descriptions = getPointDescriptions(points.size()); - - int i = points.indexOf(latLonEx); - if (i != -1) { - points.set(i, latLonNew); - return saveAvoidRoadData(points, descriptions, roadIds, appModeKeys); - } else { - return false; - } - } - - public boolean saveAvoidRoadData(List points, List descriptions, - List roadIds, List appModeKeys) { - return savePoints(points, descriptions) && saveRoadIds(roadIds) && saveAppModeKeys(appModeKeys); - } - - public boolean saveRoadIds(List roadIds) { - StringBuilder stringBuilder = new StringBuilder(); - Iterator iterator = roadIds.iterator(); - while (iterator.hasNext()) { - stringBuilder.append(iterator.next()); - if (iterator.hasNext()) { - stringBuilder.append(","); - } - } - return settingsAPI.edit(globalPreferences) - .putString(roadsIdsKey, stringBuilder.toString()) - .commit(); - } - - public boolean saveAppModeKeys(List appModeKeys) { - StringBuilder stringBuilder = new StringBuilder(); - Iterator iterator = appModeKeys.iterator(); - while (iterator.hasNext()) { - stringBuilder.append(iterator.next()); - if (iterator.hasNext()) { - stringBuilder.append(","); - } - } - return settingsAPI.edit(globalPreferences) - .putString(appModeKey, stringBuilder.toString()) - .commit(); - } - } - - private abstract class MapPointsStorage { - - protected String pointsKey; - protected String descriptionsKey; - - public MapPointsStorage() { - } - - public List getPointDescriptions(int sz) { - List list = new ArrayList<>(); - String ip = settingsAPI.getString(globalPreferences, descriptionsKey, ""); - if (ip.trim().length() > 0) { - list.addAll(Arrays.asList(ip.split("--"))); - } - while (list.size() > sz) { - list.remove(list.size() - 1); - } - while (list.size() < sz) { - list.add(""); - } - return list; - } - - public List getPoints() { - List list = new ArrayList<>(); - String ip = settingsAPI.getString(globalPreferences, pointsKey, ""); - if (ip.trim().length() > 0) { - StringTokenizer tok = new StringTokenizer(ip, ","); - while (tok.hasMoreTokens()) { - String lat = tok.nextToken(); - if (!tok.hasMoreTokens()) { - break; - } - String lon = tok.nextToken(); - list.add(new LatLon(Float.parseFloat(lat), Float.parseFloat(lon))); - } - } - return list; - } - - public boolean insertPoint(double latitude, double longitude, PointDescription historyDescription, int index) { - List ps = getPoints(); - List ds = getPointDescriptions(ps.size()); - ps.add(index, new LatLon(latitude, longitude)); - ds.add(index, PointDescription.serializeToString(historyDescription)); - if (historyDescription != null && !historyDescription.isSearchingAddress(ctx)) { - SearchHistoryHelper.getInstance(ctx).addNewItemToHistory(latitude, longitude, historyDescription); - } - return savePoints(ps, ds); - } - - public boolean updatePoint(double latitude, double longitude, PointDescription historyDescription) { - List ps = getPoints(); - List ds = getPointDescriptions(ps.size()); - int i = ps.indexOf(new LatLon(latitude, longitude)); - if (i != -1) { - ds.set(i, PointDescription.serializeToString(historyDescription)); - if (historyDescription != null && !historyDescription.isSearchingAddress(ctx)) { - SearchHistoryHelper.getInstance(ctx).addNewItemToHistory(latitude, longitude, historyDescription); - } - return savePoints(ps, ds); - } else { - return false; - } - } - - public boolean deletePoint(int index) { - List ps = getPoints(); - List ds = getPointDescriptions(ps.size()); - if (index < ps.size()) { - ps.remove(index); - ds.remove(index); - return savePoints(ps, ds); - } else { - return false; - } - } - - public boolean deletePoint(LatLon latLon) { - List ps = getPoints(); - List ds = getPointDescriptions(ps.size()); - int index = ps.indexOf(latLon); - if (index != -1) { - ps.remove(index); - ds.remove(index); - return savePoints(ps, ds); - } else { - return false; - } - } - - public boolean savePoints(List ps, List ds) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < ps.size(); i++) { - if (i > 0) { - sb.append(","); - } - sb.append(((float) ps.get(i).getLatitude() + "")).append(",").append(((float) ps.get(i).getLongitude() + "")); - } - StringBuilder tb = new StringBuilder(); - for (int i = 0; i < ds.size(); i++) { - if (i > 0) { - tb.append("--"); - } - if (ds.get(i) == null) { - tb.append(""); - } else { - tb.append(ds.get(i)); - } - } - return settingsAPI.edit(globalPreferences) - .putString(pointsKey, sb.toString()) - .putString(descriptionsKey, tb.toString()) - .commit(); - } - - public boolean movePoint(LatLon latLonEx, LatLon latLonNew) { - List ps = getPoints(); - List ds = getPointDescriptions(ps.size()); - int i = ps.indexOf(latLonEx); - if (i != -1) { - ps.set(i, latLonNew); - return savePoints(ps, ds); - } else { - return false; - } - } - } + new BooleanPreference(this, "use_intermediate_points_navigation", false).makeGlobal().cache(); public List getIntermediatePointDescriptions(int sz) { @@ -3490,16 +2308,16 @@ public class OsmandSettings { public static final String QUICK_FAB_MARGIN_X_LANDSCAPE_MARGIN = "quick_fab_margin_x_landscape_margin"; public static final String QUICK_FAB_MARGIN_Y_LANDSCAPE_MARGIN = "quick_fab_margin_y_landscape_margin"; - public final CommonPreference QUICK_ACTION = new StringPreference("quick_action_new", "").makeGlobal(); + public final CommonPreference QUICK_ACTION = new StringPreference(this, "quick_action_new", "").makeGlobal(); - public final CommonPreference QUICK_ACTION_LIST = new StringPreference("quick_action_list", "").makeGlobal(); + public final CommonPreference QUICK_ACTION_LIST = new StringPreference(this, "quick_action_list", "").makeGlobal(); - public final CommonPreference IS_QUICK_ACTION_TUTORIAL_SHOWN = new BooleanPreference("quick_action_tutorial", false).makeGlobal(); + public final CommonPreference IS_QUICK_ACTION_TUTORIAL_SHOWN = new BooleanPreference(this, "quick_action_tutorial", false).makeGlobal(); - private final CommonPreference QUICK_ACTION_FAB_MARGIN_X_PORTRAIT = new IntPreference(QUICK_FAB_MARGIN_X_PORTRAIT_MARGIN, 0).makeProfile(); - private final CommonPreference QUICK_ACTION_FAB_MARGIN_Y_PORTRAIT = new IntPreference(QUICK_FAB_MARGIN_Y_PORTRAIT_MARGIN, 0).makeProfile(); - private final CommonPreference QUICK_ACTION_FAB_MARGIN_X_LANDSCAPE_MARGIN = new IntPreference(QUICK_FAB_MARGIN_X_LANDSCAPE_MARGIN, 0).makeProfile(); - private final CommonPreference QUICK_ACTION_FAB_MARGIN_Y_LANDSCAPE_MARGIN = new IntPreference(QUICK_FAB_MARGIN_Y_LANDSCAPE_MARGIN, 0).makeProfile(); + private final CommonPreference QUICK_ACTION_FAB_MARGIN_X_PORTRAIT = new IntPreference(this, QUICK_FAB_MARGIN_X_PORTRAIT_MARGIN, 0).makeProfile(); + private final CommonPreference QUICK_ACTION_FAB_MARGIN_Y_PORTRAIT = new IntPreference(this, QUICK_FAB_MARGIN_Y_PORTRAIT_MARGIN, 0).makeProfile(); + private final CommonPreference QUICK_ACTION_FAB_MARGIN_X_LANDSCAPE_MARGIN = new IntPreference(this, QUICK_FAB_MARGIN_X_LANDSCAPE_MARGIN, 0).makeProfile(); + private final CommonPreference QUICK_ACTION_FAB_MARGIN_Y_LANDSCAPE_MARGIN = new IntPreference(this, QUICK_FAB_MARGIN_Y_LANDSCAPE_MARGIN, 0).makeProfile(); public boolean setPortraitFabMargin(int x, int y) { return QUICK_ACTION_FAB_MARGIN_X_PORTRAIT.set(x) && QUICK_ACTION_FAB_MARGIN_Y_PORTRAIT.set(y); @@ -3645,10 +2463,10 @@ public class OsmandSettings { return settingsAPI.edit(globalPreferences).putString(LAST_SEARCHED_INTERSECTED_STREET, street).commit(); } - public final OsmandPreference LAST_SELECTED_GPX_TRACK_FOR_NEW_POINT = new StringPreference("last_selected_gpx_track_for_new_point", null).makeGlobal().cache(); + public final OsmandPreference LAST_SELECTED_GPX_TRACK_FOR_NEW_POINT = new StringPreference(this, "last_selected_gpx_track_for_new_point", null).makeGlobal().cache(); // Avoid using this property, probably you need to use PoiFiltersHelper.getSelectedPoiFilters() - public final OsmandPreference SELECTED_POI_FILTER_FOR_MAP = new StringPreference("selected_poi_filter_for_map", null).makeProfile().cache(); + public final OsmandPreference SELECTED_POI_FILTER_FOR_MAP = new StringPreference(this, "selected_poi_filter_for_map", null).makeProfile().cache(); public Set getSelectedPoiFilters() { Set result = new LinkedHashSet<>(); @@ -3664,21 +2482,21 @@ public class OsmandSettings { } public final ListStringPreference POI_FILTERS_ORDER = (ListStringPreference) - new ListStringPreference("poi_filters_order", null, ",,").makeProfile().cache(); + new ListStringPreference(this, "poi_filters_order", null, ",,").makeProfile().cache(); public final ListStringPreference INACTIVE_POI_FILTERS = (ListStringPreference) - new ListStringPreference("inactive_poi_filters", null, ",,").makeProfile().cache(); + new ListStringPreference(this, "inactive_poi_filters", null, ",,").makeProfile().cache(); public final ContextMenuItemsPreference DRAWER_ITEMS = - (ContextMenuItemsPreference) new ContextMenuItemsPreference("drawer_items", DRAWER_ITEM_ID_SCHEME, new ContextMenuItemsSettings()) + (ContextMenuItemsPreference) new ContextMenuItemsPreference(this, "drawer_items", DRAWER_ITEM_ID_SCHEME, new ContextMenuItemsSettings()) .makeProfile().cache(); public final ContextMenuItemsPreference CONFIGURE_MAP_ITEMS = - (ContextMenuItemsPreference) new ContextMenuItemsPreference("configure_map_items", CONFIGURE_MAP_ITEM_ID_SCHEME, new ContextMenuItemsSettings()) + (ContextMenuItemsPreference) new ContextMenuItemsPreference(this, "configure_map_items", CONFIGURE_MAP_ITEM_ID_SCHEME, new ContextMenuItemsSettings()) .makeProfile().cache(); public final ContextMenuItemsPreference CONTEXT_MENU_ACTIONS_ITEMS = - (ContextMenuItemsPreference) new ContextMenuItemsPreference("context_menu_items", MAP_CONTEXT_MENU_ACTIONS, new MainContextMenuItemsSettings()) + (ContextMenuItemsPreference) new ContextMenuItemsPreference(this, "context_menu_items", MAP_CONTEXT_MENU_ACTIONS, new MainContextMenuItemsSettings()) .makeProfile().cache(); public final List CONTEXT_MENU_ITEMS_PREFERENCES = Arrays.asList(DRAWER_ITEMS, CONFIGURE_MAP_ITEMS, CONTEXT_MENU_ACTIONS_ITEMS); @@ -3700,7 +2518,7 @@ public class OsmandSettings { }; // this value string is synchronized with settings_pref.xml preference name // this value could localized - public final OsmandPreference VOICE_PROVIDER = new StringPreference("voice_provider", null) { + public final OsmandPreference VOICE_PROVIDER = new StringPreference(this, "voice_provider", null) { protected String getDefaultValue() { Configuration config = ctx.getResources().getConfiguration(); @@ -3715,7 +2533,7 @@ public class OsmandSettings { // this value string is synchronized with settings_pref.xml preference name - public final CommonPreference RENDERER = new StringPreference("renderer", RendererRegistry.DEFAULT_RENDER) { + public final CommonPreference RENDERER = new StringPreference(this, "renderer", RendererRegistry.DEFAULT_RENDER) { @Override protected boolean setValue(Object prefs, String val) { @@ -3736,11 +2554,9 @@ public class OsmandSettings { RENDERER.setModeDefaultValue(ApplicationMode.SKI, RendererRegistry.WINTER_SKI_RENDER); } - Map> customRendersProps = new LinkedHashMap>(); - public CommonPreference getCustomRenderProperty(String attrName) { if (!customRendersProps.containsKey(attrName)) { - customRendersProps.put(attrName, new StringPreference("nrenderer_" + attrName, "").makeProfile()); + customRendersProps.put(attrName, new StringPreference(this, "nrenderer_" + attrName, "").makeProfile()); } return customRendersProps.get(attrName); } @@ -3750,20 +2566,19 @@ public class OsmandSettings { getCustomRenderProperty("defAppMode"); } - Map> customBooleanRendersProps = new LinkedHashMap>(); public CommonPreference getCustomRenderBooleanProperty(String attrName) { if (!customBooleanRendersProps.containsKey(attrName)) { - customBooleanRendersProps.put(attrName, new BooleanPreference("nrenderer_" + attrName, false).makeProfile()); + customBooleanRendersProps.put(attrName, new BooleanPreference(this, "nrenderer_" + attrName, false).makeProfile()); } return customBooleanRendersProps.get(attrName); } - Map> customRoutingProps = new LinkedHashMap>(); + public CommonPreference getCustomRoutingProperty(String attrName, String defValue) { if (!customRoutingProps.containsKey(attrName)) { - customRoutingProps.put(attrName, new StringPreference("prouting_" + attrName, defValue).makeProfile()); + customRoutingProps.put(attrName, new StringPreference(this, "prouting_" + attrName, defValue).makeProfile()); } return customRoutingProps.get(attrName); } @@ -3773,73 +2588,73 @@ public class OsmandSettings { // pref.setModeDefaultValue(ApplicationMode.CAR, "car"); } - Map> customBooleanRoutingProps = new LinkedHashMap>(); + public CommonPreference getCustomRoutingBooleanProperty(String attrName, boolean defaulfValue) { if (!customBooleanRoutingProps.containsKey(attrName)) { - customBooleanRoutingProps.put(attrName, new BooleanPreference("prouting_" + attrName, defaulfValue).makeProfile()); + customBooleanRoutingProps.put(attrName, new BooleanPreference(this, "prouting_" + attrName, defaulfValue).makeProfile()); } return customBooleanRoutingProps.get(attrName); } - public final CommonPreference ROUTE_RECALCULATION_DISTANCE = new FloatPreference("routing_recalc_distance", 0.f).makeProfile(); - public final CommonPreference ROUTE_STRAIGHT_ANGLE = new FloatPreference("routing_straight_angle", 30.f).makeProfile(); + public final CommonPreference ROUTE_RECALCULATION_DISTANCE = new FloatPreference(this, "routing_recalc_distance", 0.f).makeProfile(); + public final CommonPreference ROUTE_STRAIGHT_ANGLE = new FloatPreference(this, "routing_straight_angle", 30.f).makeProfile(); - public final OsmandPreference USE_OSM_LIVE_FOR_ROUTING = new BooleanPreference("enable_osmc_routing", true).makeGlobal(); + public final OsmandPreference USE_OSM_LIVE_FOR_ROUTING = new BooleanPreference(this, "enable_osmc_routing", true).makeGlobal(); - public final OsmandPreference USE_OSM_LIVE_FOR_PUBLIC_TRANSPORT = new BooleanPreference("enable_osmc_public_transport", false).makeGlobal(); + public final OsmandPreference USE_OSM_LIVE_FOR_PUBLIC_TRANSPORT = new BooleanPreference(this, "enable_osmc_public_transport", false).makeGlobal(); - public final OsmandPreference VOICE_MUTE = new BooleanPreference("voice_mute", false).makeProfile().cache(); + public final OsmandPreference VOICE_MUTE = new BooleanPreference(this, "voice_mute", false).makeProfile().cache(); // for background service - public final OsmandPreference MAP_ACTIVITY_ENABLED = new BooleanPreference("map_activity_enabled", false).makeGlobal(); + public final OsmandPreference MAP_ACTIVITY_ENABLED = new BooleanPreference(this, "map_activity_enabled", false).makeGlobal(); // this value string is synchronized with settings_pref.xml preference name - public final OsmandPreference SAFE_MODE = new BooleanPreference("safe_mode", false).makeGlobal(); - public final OsmandPreference PT_SAFE_MODE = new BooleanPreference("pt_safe_mode", true).makeGlobal(); - public final OsmandPreference NATIVE_RENDERING_FAILED = new BooleanPreference("native_rendering_failed_init", false).makeGlobal(); + public final OsmandPreference SAFE_MODE = new BooleanPreference(this, "safe_mode", false).makeGlobal(); + public final OsmandPreference PT_SAFE_MODE = new BooleanPreference(this, "pt_safe_mode", true).makeGlobal(); + public final OsmandPreference NATIVE_RENDERING_FAILED = new BooleanPreference(this, "native_rendering_failed_init", false).makeGlobal(); - public final OsmandPreference USE_OPENGL_RENDER = new BooleanPreference("use_opengl_render", + public final OsmandPreference USE_OPENGL_RENDER = new BooleanPreference(this, "use_opengl_render", false /*Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH*/ ).makeGlobal().cache(); - public final OsmandPreference OPENGL_RENDER_FAILED = new BooleanPreference("opengl_render_failed", false).makeGlobal().cache(); + public final OsmandPreference OPENGL_RENDER_FAILED = new BooleanPreference(this, "opengl_render_failed", false).makeGlobal().cache(); // this value string is synchronized with settings_pref.xml preference name - public final OsmandPreference CONTRIBUTION_INSTALL_APP_DATE = new StringPreference("CONTRIBUTION_INSTALL_APP_DATE", null).makeGlobal(); + public final OsmandPreference CONTRIBUTION_INSTALL_APP_DATE = new StringPreference(this, "CONTRIBUTION_INSTALL_APP_DATE", null).makeGlobal(); - public final OsmandPreference COORDINATES_FORMAT = new IntPreference("coordinates_format", PointDescription.FORMAT_DEGREES).makeProfile(); + public final OsmandPreference COORDINATES_FORMAT = new IntPreference(this, "coordinates_format", PointDescription.FORMAT_DEGREES).makeProfile(); - public final OsmandPreference FOLLOW_THE_ROUTE = new BooleanPreference("follow_to_route", false).makeGlobal(); - public final OsmandPreference FOLLOW_THE_GPX_ROUTE = new StringPreference("follow_gpx", null).makeGlobal(); + public final OsmandPreference FOLLOW_THE_ROUTE = new BooleanPreference(this, "follow_to_route", false).makeGlobal(); + public final OsmandPreference FOLLOW_THE_GPX_ROUTE = new StringPreference(this, "follow_gpx", null).makeGlobal(); - public final OsmandPreference SELECTED_TRAVEL_BOOK = new StringPreference("selected_travel_book", "").makeGlobal(); + public final OsmandPreference SELECTED_TRAVEL_BOOK = new StringPreference(this, "selected_travel_book", "").makeGlobal(); public final ListStringPreference DISPLAYED_TRANSPORT_SETTINGS = (ListStringPreference) - new ListStringPreference("displayed_transport_settings", null, ",").makeProfile(); + new ListStringPreference(this, "displayed_transport_settings", null, ",").makeProfile(); public final OsmandPreference SHOW_ARRIVAL_TIME_OTHERWISE_EXPECTED_TIME = - new BooleanPreference("show_arrival_time", true).makeProfile(); + new BooleanPreference(this, "show_arrival_time", true).makeProfile(); public final OsmandPreference SHOW_INTERMEDIATE_ARRIVAL_TIME_OTHERWISE_EXPECTED_TIME = - new BooleanPreference("show_intermediate_arrival_time", true).makeProfile(); + new BooleanPreference(this, "show_intermediate_arrival_time", true).makeProfile(); public final OsmandPreference SHOW_RELATIVE_BEARING_OTHERWISE_REGULAR_BEARING = - new BooleanPreference("show_relative_bearing", true).makeProfile(); + new BooleanPreference(this, "show_relative_bearing", true).makeProfile(); public final OsmandPreference AGPS_DATA_LAST_TIME_DOWNLOADED = - new LongPreference("agps_data_downloaded", 0).makeGlobal(); + new LongPreference(this, "agps_data_downloaded", 0).makeGlobal(); // Live Updates public final OsmandPreference IS_LIVE_UPDATES_ON = - new BooleanPreference("is_live_updates_on", false).makeGlobal(); + new BooleanPreference(this, "is_live_updates_on", false).makeGlobal(); public final OsmandPreference LIVE_UPDATES_RETRIES = - new IntPreference("live_updates_retryes", 2).makeGlobal(); + new IntPreference(this, "live_updates_retryes", 2).makeGlobal(); // UI boxes public final CommonPreference TRANSPARENT_MAP_THEME = - new BooleanPreference("transparent_map_theme", true).makeProfile(); + new BooleanPreference(this, "transparent_map_theme", true).makeProfile(); { TRANSPARENT_MAP_THEME.setModeDefaultValue(ApplicationMode.CAR, false); @@ -3848,7 +2663,7 @@ public class OsmandSettings { } public final CommonPreference SHOW_STREET_NAME = - new BooleanPreference("show_street_name", false).makeProfile(); + new BooleanPreference(this, "show_street_name", false).makeProfile(); { SHOW_STREET_NAME.setModeDefaultValue(ApplicationMode.DEFAULT, false); @@ -3866,16 +2681,16 @@ public class OsmandSettings { public static final int PARROT_EXTERNAL_DEVICE = 3; public final CommonPreference SEARCH_TAB = - new IntPreference("SEARCH_TAB", 0).makeGlobal().cache(); + new IntPreference(this, "SEARCH_TAB", 0).makeGlobal().cache(); public final CommonPreference FAVORITES_TAB = - new IntPreference("FAVORITES_TAB", 0).makeGlobal().cache(); + new IntPreference(this, "FAVORITES_TAB", 0).makeGlobal().cache(); public final CommonPreference OSMAND_THEME = - new IntPreference("osmand_theme", OSMAND_LIGHT_THEME).makeProfile().cache(); + new IntPreference(this, "osmand_theme", OSMAND_LIGHT_THEME).makeProfile().cache(); public final OsmandPreference OPEN_ONLY_HEADER_STATE_ROUTE_CALCULATED = - new BooleanPreference("open_only_header_route_calculated", false).makeProfile(); + new BooleanPreference(this, "open_only_header_route_calculated", false).makeProfile(); public boolean isLightActionBar() { return isLightContent(); @@ -3891,29 +2706,29 @@ public class OsmandSettings { } public final CommonPreference FLUORESCENT_OVERLAYS = - new BooleanPreference("fluorescent_overlays", false).makeGlobal().cache(); + new BooleanPreference(this, "fluorescent_overlays", false).makeGlobal().cache(); // public final OsmandPreference NUMBER_OF_FREE_DOWNLOADS_V2 = new IntPreference("free_downloads_v2", 0).makeGlobal(); - public final OsmandPreference NUMBER_OF_FREE_DOWNLOADS = new IntPreference(NUMBER_OF_FREE_DOWNLOADS_ID, 0).makeGlobal(); + public final OsmandPreference NUMBER_OF_FREE_DOWNLOADS = new IntPreference(this, NUMBER_OF_FREE_DOWNLOADS_ID, 0).makeGlobal(); // For RateUsDialog public final OsmandPreference LAST_DISPLAY_TIME = - new LongPreference("last_display_time", 0).makeGlobal().cache(); + new LongPreference(this, "last_display_time", 0).makeGlobal().cache(); public final OsmandPreference LAST_CHECKED_UPDATES = - new LongPreference("last_checked_updates", 0).makeGlobal(); + new LongPreference(this, "last_checked_updates", 0).makeGlobal(); public final OsmandPreference NUMBER_OF_APP_STARTS_ON_DISLIKE_MOMENT = - new IntPreference("number_of_app_starts_on_dislike_moment", 0).makeGlobal().cache(); + new IntPreference(this, "number_of_app_starts_on_dislike_moment", 0).makeGlobal().cache(); public final OsmandPreference RATE_US_STATE = - new EnumStringPreference<>("rate_us_state", RateUsState.INITIAL_STATE, RateUsState.values()).makeGlobal(); + new EnumStringPreference<>(this, "rate_us_state", RateUsState.INITIAL_STATE, RateUsState.values()).makeGlobal(); public final CommonPreference CUSTOM_APP_MODES_KEYS = - new StringPreference("custom_app_modes_keys", "").makeGlobal().cache(); + new StringPreference(this, "custom_app_modes_keys", "").makeGlobal().cache(); public Set getCustomAppModesKeys() { String appModesKeys = CUSTOM_APP_MODES_KEYS.get(); @@ -4189,158 +3004,4 @@ public class OsmandSettings { SLOPE } - private OsmandPreference[] generalPrefs = new OsmandPreference[]{ - EXTERNAL_INPUT_DEVICE, - CENTER_POSITION_ON_MAP, - ROTATE_MAP, - MAP_SCREEN_ORIENTATION, - LIVE_MONITORING_URL, - LIVE_MONITORING_MAX_INTERVAL_TO_SEND, - LIVE_MONITORING_INTERVAL, - LIVE_MONITORING, - SHOW_TRIP_REC_NOTIFICATION, - AUTO_SPLIT_RECORDING, - SAVE_TRACK_MIN_SPEED, - SAVE_TRACK_PRECISION, - SAVE_TRACK_MIN_DISTANCE, - SAVE_TRACK_INTERVAL, - TRACK_STORAGE_DIRECTORY, - SAVE_HEADING_TO_GPX, - DISABLE_RECORDING_ONCE_APP_KILLED, - SAVE_TRACK_TO_GPX, - SAVE_GLOBAL_TRACK_REMEMBER, - SAVE_GLOBAL_TRACK_INTERVAL, - MAP_EMPTY_STATE_ALLOWED, - DO_NOT_USE_ANIMATIONS, - USE_KALMAN_FILTER_FOR_COMPASS, - USE_MAGNETIC_FIELD_SENSOR_COMPASS, - USE_TRACKBALL_FOR_MOVEMENTS, - SPEED_SYSTEM, - ANGULAR_UNITS, - METRIC_SYSTEM, - DRIVING_REGION, - DRIVING_REGION_AUTOMATIC - }; - - String[] - appModeBeanPrefsIds = new String[] { - ICON_COLOR.getId(), - ICON_RES_NAME.getId(), - PARENT_APP_MODE.getId(), - ROUTING_PROFILE.getId(), - ROUTE_SERVICE.getId(), - USER_PROFILE_NAME.getId(), - LOCATION_ICON.getId(), - NAVIGATION_ICON.getId(), - APP_MODE_ORDER.getId() - }; - - public class PreferencesDataStore extends PreferenceDataStore { - - private ApplicationMode appMode; - - public PreferencesDataStore(@NonNull ApplicationMode appMode) { - this.appMode = appMode; - } - - @Override - public void putString(String key, @Nullable String value) { - setPreference(key, value, appMode); - } - - @Override - public void putStringSet(String key, @Nullable Set values) { - setPreference(key, values, appMode); - } - - @Override - public void putInt(String key, int value) { - setPreference(key, value, appMode); - } - - @Override - public void putLong(String key, long value) { - setPreference(key, value, appMode); - } - - @Override - public void putFloat(String key, float value) { - setPreference(key, value, appMode); - } - - @Override - public void putBoolean(String key, boolean value) { - setPreference(key, value, appMode); - } - - public void putValue(String key, Object value) { - setPreference(key, value, appMode); - } - - @Nullable - @Override - public String getString(String key, @Nullable String defValue) { - OsmandPreference preference = getPreference(key); - if (preference instanceof StringPreference) { - return ((StringPreference) preference).getModeValue(appMode); - } else { - Object value = preference.getModeValue(appMode); - if (value != null) { - return value.toString(); - } - } - return defValue; - } - - @Nullable - @Override - public Set getStringSet(String key, @Nullable Set defValues) { - return super.getStringSet(key, defValues); - } - - @Override - public int getInt(String key, int defValue) { - OsmandPreference preference = getPreference(key); - if (preference instanceof IntPreference) { - return ((IntPreference) preference).getModeValue(appMode); - } - return defValue; - } - - @Override - public long getLong(String key, long defValue) { - OsmandPreference preference = getPreference(key); - if (preference instanceof LongPreference) { - return ((LongPreference) preference).getModeValue(appMode); - } - return defValue; - } - - @Override - public float getFloat(String key, float defValue) { - OsmandPreference preference = getPreference(key); - if (preference instanceof FloatPreference) { - return ((FloatPreference) preference).getModeValue(appMode); - } - return defValue; - } - - @Override - public boolean getBoolean(String key, boolean defValue) { - OsmandPreference preference = getPreference(key); - if (preference instanceof BooleanPreference) { - return ((BooleanPreference) preference).getModeValue(appMode); - } - return defValue; - } - - @Nullable - public Object getValue(String key, Object defValue) { - OsmandPreference preference = getPreference(key); - if (preference != null) { - return preference.getModeValue(appMode); - } - return defValue; - } - } } diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/PreferenceWithListener.java b/OsmAnd/src/net/osmand/plus/settings/backend/PreferenceWithListener.java new file mode 100644 index 0000000000..082febfe90 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/PreferenceWithListener.java @@ -0,0 +1,49 @@ +package net.osmand.plus.settings.backend; + +import net.osmand.StateChangedListener; + +import java.lang.ref.WeakReference; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +abstract class PreferenceWithListener implements OsmandPreference { + private List>> l = null; + + @Override + public synchronized void addListener(StateChangedListener listener) { + if (l == null) { + l = new LinkedList>>(); + } + if (!l.contains(new WeakReference>(listener))) { + l.add(new WeakReference>(listener)); + } + } + + public synchronized void fireEvent(T value) { + if (l != null) { + Iterator>> it = l.iterator(); + while (it.hasNext()) { + StateChangedListener t = it.next().get(); + if (t == null) { + it.remove(); + } else { + t.stateChanged(value); + } + } + } + } + + @Override + public synchronized void removeListener(StateChangedListener listener) { + if (l != null) { + Iterator>> it = l.iterator(); + while (it.hasNext()) { + StateChangedListener t = it.next().get(); + if (t == listener) { + it.remove(); + } + } + } + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/SettingsHelper.java b/OsmAnd/src/net/osmand/plus/settings/backend/SettingsHelper.java index 6c053f9c08..50ee1c028e 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/SettingsHelper.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/SettingsHelper.java @@ -30,7 +30,6 @@ import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.R; import net.osmand.plus.SQLiteTileSource; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; import net.osmand.plus.helpers.AvoidSpecificRoads; import net.osmand.plus.helpers.AvoidSpecificRoads.AvoidRoadInfo; import net.osmand.plus.poi.PoiUIFilter; @@ -907,6 +906,19 @@ public class SettingsHelper { } } + String[] + appModeBeanPrefsIds = new String[] { + ICON_COLOR.getId(), + ICON_RES_NAME.getId(), + PARENT_APP_MODE.getId(), + ROUTING_PROFILE.getId(), + ROUTE_SERVICE.getId(), + USER_PROFILE_NAME.getId(), + LOCATION_ICON.getId(), + NAVIGATION_ICON.getId(), + APP_MODE_ORDER.getId() + }; + public static class ProfileSettingsItem extends OsmandSettingsItem { private ApplicationMode appMode; diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/SettingsMapPointsStorage.java b/OsmAnd/src/net/osmand/plus/settings/backend/SettingsMapPointsStorage.java new file mode 100644 index 0000000000..cdb923ed23 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/SettingsMapPointsStorage.java @@ -0,0 +1,141 @@ +package net.osmand.plus.settings.backend; + +import net.osmand.data.LatLon; +import net.osmand.data.PointDescription; +import net.osmand.plus.helpers.SearchHistoryHelper; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.StringTokenizer; + +abstract class SettingsMapPointsStorage { + + private OsmandSettings osmandSettings; + protected String pointsKey; + protected String descriptionsKey; + + public SettingsMapPointsStorage(OsmandSettings osmandSettings) { + this.osmandSettings = osmandSettings; + } + + public List getPointDescriptions(int sz) { + List list = new ArrayList<>(); + String ip = osmandSettings.settingsAPI.getString(osmandSettings.globalPreferences, descriptionsKey, ""); + if (ip.trim().length() > 0) { + list.addAll(Arrays.asList(ip.split("--"))); + } + while (list.size() > sz) { + list.remove(list.size() - 1); + } + while (list.size() < sz) { + list.add(""); + } + return list; + } + + public List getPoints() { + List list = new ArrayList<>(); + String ip = osmandSettings.settingsAPI.getString(osmandSettings.globalPreferences, pointsKey, ""); + if (ip.trim().length() > 0) { + StringTokenizer tok = new StringTokenizer(ip, ","); + while (tok.hasMoreTokens()) { + String lat = tok.nextToken(); + if (!tok.hasMoreTokens()) { + break; + } + String lon = tok.nextToken(); + list.add(new LatLon(Float.parseFloat(lat), Float.parseFloat(lon))); + } + } + return list; + } + + public boolean insertPoint(double latitude, double longitude, PointDescription historyDescription, int index) { + List ps = getPoints(); + List ds = getPointDescriptions(ps.size()); + ps.add(index, new LatLon(latitude, longitude)); + ds.add(index, PointDescription.serializeToString(historyDescription)); + if (historyDescription != null && !historyDescription.isSearchingAddress(osmandSettings.ctx)) { + SearchHistoryHelper.getInstance(osmandSettings.ctx).addNewItemToHistory(latitude, longitude, historyDescription); + } + return savePoints(ps, ds); + } + + public boolean updatePoint(double latitude, double longitude, PointDescription historyDescription) { + List ps = getPoints(); + List ds = getPointDescriptions(ps.size()); + int i = ps.indexOf(new LatLon(latitude, longitude)); + if (i != -1) { + ds.set(i, PointDescription.serializeToString(historyDescription)); + if (historyDescription != null && !historyDescription.isSearchingAddress(osmandSettings.ctx)) { + SearchHistoryHelper.getInstance(osmandSettings.ctx).addNewItemToHistory(latitude, longitude, historyDescription); + } + return savePoints(ps, ds); + } else { + return false; + } + } + + public boolean deletePoint(int index) { + List ps = getPoints(); + List ds = getPointDescriptions(ps.size()); + if (index < ps.size()) { + ps.remove(index); + ds.remove(index); + return savePoints(ps, ds); + } else { + return false; + } + } + + public boolean deletePoint(LatLon latLon) { + List ps = getPoints(); + List ds = getPointDescriptions(ps.size()); + int index = ps.indexOf(latLon); + if (index != -1) { + ps.remove(index); + ds.remove(index); + return savePoints(ps, ds); + } else { + return false; + } + } + + public boolean savePoints(List ps, List ds) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < ps.size(); i++) { + if (i > 0) { + sb.append(","); + } + sb.append(((float) ps.get(i).getLatitude() + "")).append(",").append(((float) ps.get(i).getLongitude() + "")); + } + StringBuilder tb = new StringBuilder(); + for (int i = 0; i < ds.size(); i++) { + if (i > 0) { + tb.append("--"); + } + if (ds.get(i) == null) { + tb.append(""); + } else { + tb.append(ds.get(i)); + } + } + return osmandSettings.settingsAPI.edit(osmandSettings.globalPreferences) + .putString(pointsKey, sb.toString()) + .putString(descriptionsKey, tb.toString()) + .commit(); + } + + public boolean movePoint(LatLon latLonEx, LatLon latLonNew) { + List ps = getPoints(); + List ds = getPointDescriptions(ps.size()); + int i = ps.indexOf(latLonEx); + if (i != -1) { + ps.set(i, latLonNew); + return savePoints(ps, ds); + } else { + return false; + } + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/StringPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/StringPreference.java new file mode 100644 index 0000000000..3ee07b43bd --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/StringPreference.java @@ -0,0 +1,26 @@ +package net.osmand.plus.settings.backend; + +public class StringPreference extends CommonPreference { + + private OsmandSettings osmandSettings; + + StringPreference(OsmandSettings osmandSettings, String id, String defaultValue) { + super(id, defaultValue); + this.osmandSettings = osmandSettings; + } + + @Override + protected String getValue(Object prefs, String defaultValue) { + return osmandSettings.settingsAPI.getString(prefs, getId(), defaultValue); + } + + @Override + protected boolean setValue(Object prefs, String val) { + return osmandSettings.settingsAPI.edit(prefs).putString(getId(), (val != null) ? val.trim() : val).commit(); + } + + @Override + public String parseString(String s) { + return s; + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/bottomsheets/BooleanPreferenceBottomSheet.java b/OsmAnd/src/net/osmand/plus/settings/bottomsheets/BooleanPreferenceBottomSheet.java index a68867e4c0..6b73dd69f0 100644 --- a/OsmAnd/src/net/osmand/plus/settings/bottomsheets/BooleanPreferenceBottomSheet.java +++ b/OsmAnd/src/net/osmand/plus/settings/bottomsheets/BooleanPreferenceBottomSheet.java @@ -16,9 +16,8 @@ import net.osmand.AndroidUtils; import net.osmand.PlatformUtil; import net.osmand.plus.ApplicationMode; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.BooleanPreference; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.BooleanPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.base.bottomsheetmenu.BaseBottomSheetItem; @@ -57,7 +56,7 @@ public class BooleanPreferenceBottomSheet extends BasePreferenceBottomSheet { String title = switchPreference.getTitle().toString(); items.add(new TitleItem(title)); - final OsmandSettings.BooleanPreference pref = (BooleanPreference) preference; + final BooleanPreference pref = (BooleanPreference) preference; CharSequence summaryOn = switchPreference.getSummaryOn(); CharSequence summaryOff = switchPreference.getSummaryOff(); final String on = summaryOn == null || summaryOn.toString().equals("") diff --git a/OsmAnd/src/net/osmand/plus/settings/bottomsheets/RecalculateRouteInDeviationBottomSheet.java b/OsmAnd/src/net/osmand/plus/settings/bottomsheets/RecalculateRouteInDeviationBottomSheet.java index d016a7fee5..2888603681 100644 --- a/OsmAnd/src/net/osmand/plus/settings/bottomsheets/RecalculateRouteInDeviationBottomSheet.java +++ b/OsmAnd/src/net/osmand/plus/settings/bottomsheets/RecalculateRouteInDeviationBottomSheet.java @@ -17,6 +17,7 @@ import net.osmand.AndroidUtils; import net.osmand.plus.ApplicationMode; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; @@ -43,7 +44,7 @@ public class RecalculateRouteInDeviationBottomSheet extends BooleanPreferenceBot private OsmandApplication app; private OsmandSettings settings; private ApplicationMode appMode; - private OsmandSettings.CommonPreference preference; + private CommonPreference preference; private Slider slider; private TextView tvSliderTitle; diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/BaseSettingsFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/BaseSettingsFragment.java index 1148f23720..3162064aaa 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/BaseSettingsFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/BaseSettingsFragment.java @@ -54,8 +54,9 @@ import net.osmand.PlatformUtil; import net.osmand.access.AccessibilitySettingsFragment; import net.osmand.plus.ApplicationMode; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.MapActivity; @@ -833,11 +834,11 @@ public abstract class BaseSettingsFragment extends PreferenceFragmentCompat impl return icon; } - public SwitchPreferenceCompat createSwitchPreference(OsmandSettings.OsmandPreference b, int title, int summary, int layoutId) { + public SwitchPreferenceCompat createSwitchPreference(OsmandPreference b, int title, int summary, int layoutId) { return createSwitchPreference(b, getString(title), getString(summary), layoutId); } - public SwitchPreferenceCompat createSwitchPreference(OsmandSettings.OsmandPreference b, String title, String summary, int layoutId) { + public SwitchPreferenceCompat createSwitchPreference(OsmandPreference b, String title, String summary, int layoutId) { SwitchPreferenceCompat p = new SwitchPreferenceCompat(getContext()); p.setTitle(title); p.setKey(b.getId()); diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/ConfigureMenuItemsFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/ConfigureMenuItemsFragment.java index c668564a6d..302b7f5a39 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/ConfigureMenuItemsFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/ConfigureMenuItemsFragment.java @@ -28,7 +28,9 @@ import net.osmand.plus.ApplicationMode; import net.osmand.plus.ContextMenuAdapter; import net.osmand.plus.ContextMenuItem; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.ContextMenuItemsPreference; +import net.osmand.plus.settings.backend.ContextMenuItemsSettings; +import net.osmand.plus.settings.backend.MainContextMenuItemsSettings; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.MapActivity; @@ -163,9 +165,9 @@ public class ConfigureMenuItemsFragment extends BaseOsmAndFragment private void initMainActionsIds(ApplicationMode appMode) { List defItems = getCustomizableDefaultItems(contextMenuAdapter.getDefaultItems()); - OsmandSettings.ContextMenuItemsSettings pref = getSettingForScreen(app, screenType).getModeValue(appMode); - if (pref instanceof OsmandSettings.MainContextMenuItemsSettings) { - mainActionItems = new ArrayList<>(((OsmandSettings.MainContextMenuItemsSettings) pref).getMainIds()); + ContextMenuItemsSettings pref = getSettingForScreen(app, screenType).getModeValue(appMode); + if (pref instanceof MainContextMenuItemsSettings) { + mainActionItems = new ArrayList<>(((MainContextMenuItemsSettings) pref).getMainIds()); if (mainActionItems.isEmpty()) { for (int i = 0; i < MAIN_BUTTONS_QUANTITY; i++) { mainActionItems.add(defItems.get(i).getId()); @@ -255,11 +257,11 @@ public class ConfigureMenuItemsFragment extends BaseOsmAndFragment } } FragmentManager fm = getFragmentManager(); - final OsmandSettings.ContextMenuItemsSettings prefToSave; + final ContextMenuItemsSettings prefToSave; if (screenType == ScreenType.CONTEXT_MENU_ACTIONS) { - prefToSave = new OsmandSettings.MainContextMenuItemsSettings(mainActionItems, hiddenMenuItems, ids); + prefToSave = new MainContextMenuItemsSettings(mainActionItems, hiddenMenuItems, ids); } else { - prefToSave = new OsmandSettings.ContextMenuItemsSettings(hiddenMenuItems, ids); + prefToSave = new ContextMenuItemsSettings(hiddenMenuItems, ids); } if (fm != null) { ChangeGeneralProfilesPrefBottomSheet.showInstance(fm, @@ -523,7 +525,7 @@ public class ConfigureMenuItemsFragment extends BaseOsmAndFragment } } - public static OsmandSettings.ContextMenuItemsPreference getSettingForScreen(OsmandApplication app, ScreenType screenType) throws IllegalArgumentException { + public static ContextMenuItemsPreference getSettingForScreen(OsmandApplication app, ScreenType screenType) throws IllegalArgumentException { switch (screenType) { case DRAWER: return app.getSettings().DRAWER_ITEMS; diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java index 10cfd2adcc..d15e0f644f 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java @@ -25,8 +25,9 @@ import net.osmand.StateChangedListener; import net.osmand.plus.ApplicationMode; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.BooleanPreference; +import net.osmand.plus.settings.backend.CommonPreference; +import net.osmand.plus.settings.backend.OsmandPreference; +import net.osmand.plus.settings.backend.BooleanPreference; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.SettingsBaseActivity; @@ -218,7 +219,7 @@ public class RouteParametersFragment extends BaseSettingsFragment implements OnP String description = SettingsBaseActivity.getRoutingStringPropertyDescription(app, p.getId(), p.getDescription()); if (p.getType() == RoutingParameterType.BOOLEAN) { - OsmandSettings.OsmandPreference pref = settings.getCustomRoutingBooleanProperty(p.getId(), p.getDefaultBoolean()); + OsmandPreference pref = settings.getCustomRoutingBooleanProperty(p.getId(), p.getDefaultBoolean()); SwitchPreferenceEx switchPreferenceEx = (SwitchPreferenceEx) createSwitchPreferenceEx(pref.getId(), title, description, R.layout.preference_with_descr_dialog_and_switch); switchPreferenceEx.setDescription(description); @@ -234,7 +235,7 @@ public class RouteParametersFragment extends BaseSettingsFragment implements OnP for (Object o : vls) { svlss[i++] = o.toString(); } - OsmandSettings.OsmandPreference pref = settings.getCustomRoutingProperty(p.getId(), p.getType() == RoutingParameterType.NUMERIC ? "0.0" : "-"); + OsmandPreference pref = settings.getCustomRoutingProperty(p.getId(), p.getType() == RoutingParameterType.NUMERIC ? "0.0" : "-"); ListPreferenceEx listPreferenceEx = (ListPreferenceEx) createListPreferenceEx(pref.getId(), p.getPossibleValueDescriptions(), svlss, title, R.layout.preference_with_descr); listPreferenceEx.setDescription(description); @@ -381,10 +382,10 @@ public class RouteParametersFragment extends BaseSettingsFragment implements OnP for (RoutingParameter parameter : otherRoutingParameters) { if (parameter.getType() == RoutingParameterType.BOOLEAN) { - OsmandSettings.CommonPreference pref = settings.getCustomRoutingBooleanProperty(parameter.getId(), parameter.getDefaultBoolean()); + CommonPreference pref = settings.getCustomRoutingBooleanProperty(parameter.getId(), parameter.getDefaultBoolean()); pref.addListener(booleanRoutingPrefListener); } else { - OsmandSettings.CommonPreference pref = settings.getCustomRoutingProperty(parameter.getId(), parameter.getType() == RoutingParameterType.NUMERIC ? "0.0" : "-"); + CommonPreference pref = settings.getCustomRoutingProperty(parameter.getId(), parameter.getType() == RoutingParameterType.NUMERIC ? "0.0" : "-"); pref.addListener(customRoutingPrefListener); } } @@ -396,10 +397,10 @@ public class RouteParametersFragment extends BaseSettingsFragment implements OnP for (RoutingParameter parameter : otherRoutingParameters) { if (parameter.getType() == RoutingParameterType.BOOLEAN) { - OsmandSettings.CommonPreference pref = settings.getCustomRoutingBooleanProperty(parameter.getId(), parameter.getDefaultBoolean()); + CommonPreference pref = settings.getCustomRoutingBooleanProperty(parameter.getId(), parameter.getDefaultBoolean()); pref.removeListener(booleanRoutingPrefListener); } else { - OsmandSettings.CommonPreference pref = settings.getCustomRoutingProperty(parameter.getId(), parameter.getType() == RoutingParameterType.NUMERIC ? "0.0" : "-"); + CommonPreference pref = settings.getCustomRoutingProperty(parameter.getId(), parameter.getType() == RoutingParameterType.NUMERIC ? "0.0" : "-"); pref.removeListener(customRoutingPrefListener); } } diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/VehicleParametersFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/VehicleParametersFragment.java index b38fffa8e1..9a8c8dcd3d 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/VehicleParametersFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/VehicleParametersFragment.java @@ -9,11 +9,11 @@ import androidx.preference.PreferenceViewHolder; import net.osmand.plus.ApplicationMode; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.activities.SettingsBaseActivity; import net.osmand.plus.routing.RouteProvider.RouteService; import net.osmand.plus.routing.RoutingHelper; +import net.osmand.plus.settings.backend.StringPreference; import net.osmand.plus.settings.preferences.ListPreferenceEx; import net.osmand.router.GeneralRouter; @@ -77,7 +77,7 @@ public class VehicleParametersFragment extends BaseSettingsFragment implements O String description = SettingsBaseActivity.getRoutingStringPropertyDescription(app, parameterId, parameter.getDescription()); String defValue = parameter.getType() == GeneralRouter.RoutingParameterType.NUMERIC ? ROUTING_PARAMETER_NUMERIC_DEFAULT : ROUTING_PARAMETER_SYMBOLIC_DEFAULT; - OsmandSettings.StringPreference pref = (OsmandSettings.StringPreference) app.getSettings().getCustomRoutingProperty(parameterId, defValue); + StringPreference pref = (StringPreference) app.getSettings().getCustomRoutingProperty(parameterId, defValue); Object[] values = parameter.getPossibleValues(); String[] valuesStr = new String[values.length]; diff --git a/OsmAnd/src/net/osmand/plus/settings/preferences/ListPreferenceEx.java b/OsmAnd/src/net/osmand/plus/settings/preferences/ListPreferenceEx.java index e6bdd34f07..60511eadb4 100644 --- a/OsmAnd/src/net/osmand/plus/settings/preferences/ListPreferenceEx.java +++ b/OsmAnd/src/net/osmand/plus/settings/preferences/ListPreferenceEx.java @@ -8,7 +8,7 @@ import androidx.preference.DialogPreference; import androidx.preference.PreferenceDataStore; import net.osmand.plus.ApplicationMode; -import net.osmand.plus.settings.backend.OsmandSettings.PreferencesDataStore; +import net.osmand.plus.settings.backend.OsmAndPreferencesDataStore; public class ListPreferenceEx extends DialogPreference { @@ -126,8 +126,8 @@ public class ListPreferenceEx extends DialogPreference { private Object getPersistedValue(Object defaultValue) { PreferenceDataStore dataStore = getPreferenceDataStore(); - if (dataStore instanceof PreferencesDataStore) { - Object value = ((PreferencesDataStore) dataStore).getValue(getKey(), defaultValue); + if (dataStore instanceof OsmAndPreferencesDataStore) { + Object value = ((OsmAndPreferencesDataStore) dataStore).getValue(getKey(), defaultValue); if (value instanceof Enum) { return ((Enum) value).ordinal(); } else if (value instanceof ApplicationMode) { @@ -144,8 +144,8 @@ public class ListPreferenceEx extends DialogPreference { return; } PreferenceDataStore dataStore = getPreferenceDataStore(); - if (dataStore instanceof PreferencesDataStore) { - ((PreferencesDataStore) dataStore).putValue(getKey(), value); + if (dataStore instanceof OsmAndPreferencesDataStore) { + ((OsmAndPreferencesDataStore) dataStore).putValue(getKey(), value); } } } \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/settings/preferences/MultiSelectBooleanPreference.java b/OsmAnd/src/net/osmand/plus/settings/preferences/MultiSelectBooleanPreference.java index 896e1864d1..1f69cd0989 100644 --- a/OsmAnd/src/net/osmand/plus/settings/preferences/MultiSelectBooleanPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/preferences/MultiSelectBooleanPreference.java @@ -6,7 +6,7 @@ import android.util.AttributeSet; import androidx.preference.MultiSelectListPreference; import androidx.preference.PreferenceDataStore; -import net.osmand.plus.settings.backend.OsmandSettings.PreferencesDataStore; +import net.osmand.plus.settings.backend.OsmAndPreferencesDataStore; import java.util.HashSet; import java.util.Set; @@ -79,8 +79,8 @@ public class MultiSelectBooleanPreference extends MultiSelectListPreference { return; } PreferenceDataStore dataStore = getPreferenceDataStore(); - if (dataStore instanceof PreferencesDataStore) { - PreferencesDataStore preferencesDataStore = (PreferencesDataStore) dataStore; + if (dataStore instanceof OsmAndPreferencesDataStore) { + OsmAndPreferencesDataStore preferencesDataStore = (OsmAndPreferencesDataStore) dataStore; for (String prefId : getPrefsIds()) { preferencesDataStore.putBoolean(prefId, getValues().contains(prefId)); @@ -96,8 +96,8 @@ public class MultiSelectBooleanPreference extends MultiSelectListPreference { Set enabledPrefs = new HashSet<>(); PreferenceDataStore dataStore = getPreferenceDataStore(); - if (dataStore instanceof PreferencesDataStore && getEntryValues() != null) { - PreferencesDataStore preferencesDataStore = (PreferencesDataStore) dataStore; + if (dataStore instanceof OsmAndPreferencesDataStore && getEntryValues() != null) { + OsmAndPreferencesDataStore preferencesDataStore = (OsmAndPreferencesDataStore) dataStore; for (String prefId : getPrefsIds()) { boolean enabled = preferencesDataStore.getBoolean(prefId, false); diff --git a/OsmAnd/src/net/osmand/plus/srtmplugin/ContourLinesAction.java b/OsmAnd/src/net/osmand/plus/srtmplugin/ContourLinesAction.java index 9c4ae901f7..bcbd80ff92 100644 --- a/OsmAnd/src/net/osmand/plus/srtmplugin/ContourLinesAction.java +++ b/OsmAnd/src/net/osmand/plus/srtmplugin/ContourLinesAction.java @@ -8,7 +8,7 @@ import android.widget.TextView; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.quickaction.QuickAction; @@ -46,7 +46,7 @@ public class ContourLinesAction extends QuickAction { OsmandApplication app = activity.getMyApplication(); RenderingRuleProperty contourLinesProp = app.getRendererRegistry().getCustomRenderingRuleProperty(CONTOUR_LINES_ATTR); if (contourLinesProp != null) { - final OsmandSettings.CommonPreference pref = app.getSettings().getCustomRenderProperty(contourLinesProp.getAttrName()); + final CommonPreference pref = app.getSettings().getCustomRenderProperty(contourLinesProp.getAttrName()); boolean selected = !pref.get().equals(CONTOUR_LINES_DISABLED_VALUE); if (selected && !plugin.isActive() && !plugin.needsInstallation()) { diff --git a/OsmAnd/src/net/osmand/plus/srtmplugin/ContourLinesMenu.java b/OsmAnd/src/net/osmand/plus/srtmplugin/ContourLinesMenu.java index 94a33cf6a8..be2631dc04 100644 --- a/OsmAnd/src/net/osmand/plus/srtmplugin/ContourLinesMenu.java +++ b/OsmAnd/src/net/osmand/plus/srtmplugin/ContourLinesMenu.java @@ -7,6 +7,7 @@ import net.osmand.plus.ContextMenuAdapter; import net.osmand.plus.ContextMenuItem; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; @@ -61,8 +62,8 @@ public class ContourLinesMenu { final String contourWidthName; final String contourDensityName; - final OsmandSettings.CommonPreference widthPref; - final OsmandSettings.CommonPreference densityPref; + final CommonPreference widthPref; + final CommonPreference densityPref; final RenderingRuleProperty contourWidthProp = app.getRendererRegistry().getCustomRenderingRuleProperty(CONTOUR_WIDTH_ATTR); if (contourWidthProp != null) { contourWidthName = SettingsActivity.getStringPropertyName(app, contourWidthProp.getAttrName(), @@ -82,8 +83,8 @@ public class ContourLinesMenu { densityPref = null; } - final OsmandSettings.CommonPreference pref = settings.getCustomRenderProperty(contourLinesProp.getAttrName()); - final OsmandSettings.CommonPreference colorPref = settings.getCustomRenderProperty(colorSchemeProp.getAttrName()); + final CommonPreference pref = settings.getCustomRenderProperty(contourLinesProp.getAttrName()); + final CommonPreference colorPref = settings.getCustomRenderProperty(colorSchemeProp.getAttrName()); final boolean selected = !pref.get().equals(CONTOUR_LINES_DISABLED_VALUE); final int toggleActionStringId = selected ? R.string.shared_string_on : R.string.shared_string_off; diff --git a/OsmAnd/src/net/osmand/plus/srtmplugin/SRTMPlugin.java b/OsmAnd/src/net/osmand/plus/srtmplugin/SRTMPlugin.java index 00ce824d6e..715d86443c 100644 --- a/OsmAnd/src/net/osmand/plus/srtmplugin/SRTMPlugin.java +++ b/OsmAnd/src/net/osmand/plus/srtmplugin/SRTMPlugin.java @@ -22,7 +22,7 @@ import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.OsmandSettings.TerrainMode; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.SettingsActivity; @@ -234,7 +234,7 @@ public class SRTMPlugin extends OsmandPlugin { RenderingRuleProperty contourLinesProp = app.getRendererRegistry().getCustomRenderingRuleProperty(CONTOUR_LINES_ATTR); if (contourLinesProp != null) { - final OsmandSettings.CommonPreference pref = app.getSettings().getCustomRenderProperty(contourLinesProp.getAttrName()); + final CommonPreference pref = app.getSettings().getCustomRenderProperty(contourLinesProp.getAttrName()); if (!Algorithms.isEmpty(pref.get())) { contourLinesEnabled = !pref.get().equals(CONTOUR_LINES_DISABLED_VALUE); } else { @@ -291,7 +291,7 @@ public class SRTMPlugin extends OsmandPlugin { public void run() { RenderingRuleProperty contourLinesProp = app.getRendererRegistry().getCustomRenderingRuleProperty(CONTOUR_LINES_ATTR); if (contourLinesProp != null) { - final OsmandSettings.CommonPreference pref = settings.getCustomRenderProperty(contourLinesProp.getAttrName()); + final CommonPreference pref = settings.getCustomRenderProperty(contourLinesProp.getAttrName()); boolean selected = !pref.get().equals(CONTOUR_LINES_DISABLED_VALUE); SRTMPlugin plugin = OsmandPlugin.getPlugin(SRTMPlugin.class); @@ -338,7 +338,7 @@ public class SRTMPlugin extends OsmandPlugin { RenderingRuleProperty contourLinesProp = app.getRendererRegistry().getCustomRenderingRuleProperty(CONTOUR_LINES_ATTR); if (contourLinesProp != null) { - final OsmandSettings.CommonPreference pref = settings.getCustomRenderProperty(contourLinesProp.getAttrName()); + final CommonPreference pref = settings.getCustomRenderProperty(contourLinesProp.getAttrName()); boolean contourLinesSelected = isContourLinesLayerEnabled(app); String descr = getPrefDescription(app, contourLinesProp, pref); adapter.addItem(new ContextMenuItem.ItemBuilder() @@ -407,7 +407,7 @@ public class SRTMPlugin extends OsmandPlugin { final Runnable callback) { RenderingRuleProperty contourLinesProp = app.getRendererRegistry().getCustomRenderingRuleProperty(CONTOUR_LINES_ATTR); if (contourLinesProp != null) { - final OsmandSettings.CommonPreference pref = settings.getCustomRenderProperty(contourLinesProp.getAttrName()); + final CommonPreference pref = settings.getCustomRenderProperty(contourLinesProp.getAttrName()); CommonPreference zoomSetting = settings.CONTOUR_LINES_ZOOM; if (!isChecked) { zoomSetting.set(pref.get()); @@ -435,7 +435,7 @@ public class SRTMPlugin extends OsmandPlugin { } } - public String getPrefDescription(final Context ctx, final RenderingRuleProperty p, final OsmandSettings.CommonPreference pref) { + public String getPrefDescription(final Context ctx, final RenderingRuleProperty p, final CommonPreference pref) { if (!Algorithms.isEmpty(pref.get())) { return SettingsActivity.getStringPropertyValue(ctx, pref.get()); } else { @@ -445,7 +445,7 @@ public class SRTMPlugin extends OsmandPlugin { public void selectPropertyValue(final MapActivity activity, final RenderingRuleProperty p, - final OsmandSettings.CommonPreference pref, + final CommonPreference pref, final Runnable callback) { final String propertyDescr = SettingsActivity.getStringPropertyDescription(activity, p.getAttrName(), p.getName()); diff --git a/OsmAnd/src/net/osmand/plus/transport/TransportLinesMenu.java b/OsmAnd/src/net/osmand/plus/transport/TransportLinesMenu.java index 76d3969e1d..4d304979ac 100644 --- a/OsmAnd/src/net/osmand/plus/transport/TransportLinesMenu.java +++ b/OsmAnd/src/net/osmand/plus/transport/TransportLinesMenu.java @@ -20,7 +20,7 @@ import net.osmand.CallbackWithObject; import net.osmand.plus.ApplicationMode; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.MapActivity; diff --git a/OsmAnd/src/net/osmand/plus/views/AidlMapLayer.java b/OsmAnd/src/net/osmand/plus/views/AidlMapLayer.java index 58a38d40b0..b0ccde211a 100644 --- a/OsmAnd/src/net/osmand/plus/views/AidlMapLayer.java +++ b/OsmAnd/src/net/osmand/plus/views/AidlMapLayer.java @@ -24,7 +24,7 @@ import net.osmand.data.LatLon; import net.osmand.data.PointDescription; import net.osmand.data.RotatedTileBox; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.mapcontextmenu.MapContextMenu; diff --git a/OsmAnd/src/net/osmand/plus/views/GPXLayer.java b/OsmAnd/src/net/osmand/plus/views/GPXLayer.java index cb9dfbf04b..0431e3a4cf 100644 --- a/OsmAnd/src/net/osmand/plus/views/GPXLayer.java +++ b/OsmAnd/src/net/osmand/plus/views/GPXLayer.java @@ -41,7 +41,7 @@ import net.osmand.plus.MapMarkersHelper; import net.osmand.plus.MapMarkersHelper.MapMarker; import net.osmand.plus.MapMarkersHelper.MapMarkersGroup; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.base.FavoriteImageDrawable; import net.osmand.plus.mapcontextmenu.other.TrackDetailsMenu.TrackChartPoints; diff --git a/OsmAnd/src/net/osmand/plus/views/MapControlsLayer.java b/OsmAnd/src/net/osmand/plus/views/MapControlsLayer.java index f6643e7902..84c0af503f 100644 --- a/OsmAnd/src/net/osmand/plus/views/MapControlsLayer.java +++ b/OsmAnd/src/net/osmand/plus/views/MapControlsLayer.java @@ -43,8 +43,9 @@ import net.osmand.plus.OsmAndLocationProvider; import net.osmand.plus.OsmAndLocationSimulation; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings.LayerTransparencySeekbarMode; import net.osmand.plus.R; import net.osmand.plus.TargetPointsHelper; @@ -1225,7 +1226,7 @@ public class MapControlsLayer extends OsmandMapLayer { @Override public boolean onLongClick(View notUseCouldBeNull) { - final OsmandSettings.OsmandPreference mapDensity = view.getSettings().MAP_DENSITY; + final OsmandPreference mapDensity = view.getSettings().MAP_DENSITY; final AlertDialog.Builder bld = new AlertDialog.Builder(view.getContext()); int p = (int) (mapDensity.get() * 100); final TIntArrayList tlist = new TIntArrayList(new int[]{25, 33, 50, 75, 100, 125, 150, 200, 300, 400}); diff --git a/OsmAnd/src/net/osmand/plus/views/RulerControlLayer.java b/OsmAnd/src/net/osmand/plus/views/RulerControlLayer.java index 43131febe2..f733cc972b 100644 --- a/OsmAnd/src/net/osmand/plus/views/RulerControlLayer.java +++ b/OsmAnd/src/net/osmand/plus/views/RulerControlLayer.java @@ -29,6 +29,7 @@ import net.osmand.data.QuadPoint; import net.osmand.data.RotatedTileBox; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.OsmandSettings.AngularConstants; import net.osmand.plus.settings.backend.OsmandSettings.RulerMode; @@ -67,7 +68,7 @@ public class RulerControlLayer extends OsmandMapLayer { private QuadPoint cacheCenter; private float cacheMapDensity; - private OsmandSettings.OsmandPreference mapDensity; + private OsmandPreference mapDensity; private OsmandSettings.MetricsConstants cacheMetricSystem; private int cacheIntZoom; private LatLon cacheCenterLatLon; diff --git a/OsmAnd/src/net/osmand/plus/views/TransportStopsLayer.java b/OsmAnd/src/net/osmand/plus/views/TransportStopsLayer.java index 4160328bcd..a5ba754002 100644 --- a/OsmAnd/src/net/osmand/plus/views/TransportStopsLayer.java +++ b/OsmAnd/src/net/osmand/plus/views/TransportStopsLayer.java @@ -25,6 +25,7 @@ import net.osmand.data.RotatedTileBox; import net.osmand.data.TransportStop; import net.osmand.osm.edit.Node; import net.osmand.osm.edit.Way; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; @@ -60,7 +61,7 @@ public class TransportStopsLayer extends OsmandMapLayer implements ContextMenuLa private MapLayerData> data; private TransportStopRoute stopRoute = null; - private OsmandSettings.CommonPreference showTransportStops; + private CommonPreference showTransportStops; private Path path; private float backgroundIconHalfWidth; diff --git a/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapInfoWidgetsFactory.java b/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapInfoWidgetsFactory.java index 61fffdb814..6350e957ac 100644 --- a/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapInfoWidgetsFactory.java +++ b/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapInfoWidgetsFactory.java @@ -48,6 +48,7 @@ import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmAndLocationProvider; import net.osmand.plus.OsmAndLocationProvider.GPSInfo; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.OsmandSettings.RulerMode; import net.osmand.plus.R; @@ -167,7 +168,7 @@ public class MapInfoWidgetsFactory { public static final int COMPASS_CONTROL_WIDGET_STATE_SHOW = R.id.compass_ruler_control_widget_state_show; public static final int COMPASS_CONTROL_WIDGET_STATE_HIDE = R.id.compass_ruler_control_widget_state_hide; - private final OsmandSettings.OsmandPreference showCompass; + private final OsmandPreference showCompass; public CompassRulerControlWidgetState(OsmandApplication ctx) { super(ctx); diff --git a/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapWidgetRegistry.java b/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapWidgetRegistry.java index e5fa0daca8..0e91dcfe6c 100644 --- a/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapWidgetRegistry.java +++ b/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapWidgetRegistry.java @@ -17,7 +17,7 @@ import net.osmand.plus.ContextMenuAdapter; import net.osmand.plus.ContextMenuItem; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.MapActivity; diff --git a/OsmAnd/src/net/osmand/plus/views/mapwidgets/RouteInfoWidgetsFactory.java b/OsmAnd/src/net/osmand/plus/views/mapwidgets/RouteInfoWidgetsFactory.java index aa9a8d09cc..5eb78bd2b4 100644 --- a/OsmAnd/src/net/osmand/plus/views/mapwidgets/RouteInfoWidgetsFactory.java +++ b/OsmAnd/src/net/osmand/plus/views/mapwidgets/RouteInfoWidgetsFactory.java @@ -35,7 +35,7 @@ import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmAndLocationProvider; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.TargetPointsHelper; import net.osmand.plus.TargetPointsHelper.TargetPoint; @@ -1178,7 +1178,7 @@ public class RouteInfoWidgetsFactory { private String cacheRulerText; private int maxWidth; private float cacheMapDensity; - private OsmandSettings.OsmandPreference mapDensity; + private OsmandPreference mapDensity; private int cacheRulerZoom; private double cacheRulerTileX; private double cacheRulerTileY; diff --git a/OsmAnd/src/net/osmand/plus/voice/MediaCommandPlayerImpl.java b/OsmAnd/src/net/osmand/plus/voice/MediaCommandPlayerImpl.java index f3c9734a82..368dc2dc4a 100644 --- a/OsmAnd/src/net/osmand/plus/voice/MediaCommandPlayerImpl.java +++ b/OsmAnd/src/net/osmand/plus/voice/MediaCommandPlayerImpl.java @@ -8,7 +8,7 @@ import android.os.Build; import net.osmand.PlatformUtil; import net.osmand.plus.ApplicationMode; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.routing.VoiceRouter; import org.apache.commons.logging.Log; @@ -91,7 +91,7 @@ public class MediaCommandPlayerImpl extends AbstractPrologCommandPlayer implemen // Delay first prompt of each batch to allow BT SCO link being established, or when VOICE_PROMPT_DELAY is set >0 for the other stream types if (ctx != null) { Integer stream = ctx.getSettings().AUDIO_MANAGER_STREAM.getModeValue(getApplicationMode()); - OsmandSettings.OsmandPreference pref = ctx.getSettings().VOICE_PROMPT_DELAY[stream]; + OsmandPreference pref = ctx.getSettings().VOICE_PROMPT_DELAY[stream]; if (pref.getModeValue(getApplicationMode()) > 0) { try { Thread.sleep(pref.getModeValue(getApplicationMode())); diff --git a/OsmAnd/src/net/osmand/plus/voice/TTSCommandPlayerImpl.java b/OsmAnd/src/net/osmand/plus/voice/TTSCommandPlayerImpl.java index 4c2559dbf3..2e3340d859 100644 --- a/OsmAnd/src/net/osmand/plus/voice/TTSCommandPlayerImpl.java +++ b/OsmAnd/src/net/osmand/plus/voice/TTSCommandPlayerImpl.java @@ -17,7 +17,7 @@ import androidx.appcompat.app.AlertDialog; import net.osmand.PlatformUtil; import net.osmand.plus.ApplicationMode; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.activities.SettingsActivity; import net.osmand.plus.routing.VoiceRouter; @@ -127,7 +127,7 @@ public class TTSCommandPlayerImpl extends AbstractPrologCommandPlayer { // Delay first prompt of each batch to allow BT SCO link being established, or when VOICE_PROMPT_DELAY is set >0 for the other stream types if (ctx != null) { Integer streamModeValue = ctx.getSettings().AUDIO_MANAGER_STREAM.getModeValue(getApplicationMode()); - OsmandSettings.OsmandPreference pref = ctx.getSettings().VOICE_PROMPT_DELAY[streamModeValue]; + OsmandPreference pref = ctx.getSettings().VOICE_PROMPT_DELAY[streamModeValue]; int vpd = pref == null ? 0 : pref.getModeValue(getApplicationMode()); if (vpd > 0) { ttsRequests++; diff --git a/OsmAnd/src/net/osmand/plus/wikipedia/WikipediaOptionsBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/wikipedia/WikipediaOptionsBottomSheetDialogFragment.java index 41edcb0a02..f05bb9273f 100644 --- a/OsmAnd/src/net/osmand/plus/wikipedia/WikipediaOptionsBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/wikipedia/WikipediaOptionsBottomSheetDialogFragment.java @@ -9,7 +9,7 @@ import androidx.appcompat.widget.PopupMenu; import androidx.fragment.app.Fragment; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings.WikiArticleShowImages; import net.osmand.plus.R; import net.osmand.plus.base.MenuBottomSheetDialogFragment; @@ -28,7 +28,7 @@ public class WikipediaOptionsBottomSheetDialogFragment extends MenuBottomSheetDi @Override public void createMenuItems(Bundle savedInstanceState) { final OsmandApplication app = getMyApplication(); - final OsmandSettings.CommonPreference showImagesPref = app.getSettings().WIKI_ARTICLE_SHOW_IMAGES; + final CommonPreference showImagesPref = app.getSettings().WIKI_ARTICLE_SHOW_IMAGES; items.add(new TitleItem(getString(R.string.shared_string_options))); diff --git a/OsmAnd/src/net/osmand/plus/wikivoyage/explore/WikivoyageOptionsBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/wikivoyage/explore/WikivoyageOptionsBottomSheetDialogFragment.java index 3b67249cf7..ea09a79314 100644 --- a/OsmAnd/src/net/osmand/plus/wikivoyage/explore/WikivoyageOptionsBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/wikivoyage/explore/WikivoyageOptionsBottomSheetDialogFragment.java @@ -15,7 +15,7 @@ import androidx.appcompat.widget.PopupMenu; import net.osmand.PicassoUtils; import net.osmand.plus.OnDialogFragmentResultListener; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings.WikiArticleShowImages; import net.osmand.plus.R; import net.osmand.plus.base.MenuBottomSheetDialogFragment; @@ -44,7 +44,7 @@ public class WikivoyageOptionsBottomSheetDialogFragment extends MenuBottomSheetD if (app == null) { return; } - final OsmandSettings.CommonPreference showImagesPref = app.getSettings().WIKI_ARTICLE_SHOW_IMAGES; + final CommonPreference showImagesPref = app.getSettings().WIKI_ARTICLE_SHOW_IMAGES; final TravelDbHelper dbHelper = app.getTravelDbHelper(); items.add(new TitleItem(getString(R.string.shared_string_options))); From c8ed464125104a7f5e1f06f20d1d730aa85bda25 Mon Sep 17 00:00:00 2001 From: Victor Shcherb Date: Tue, 19 May 2020 15:26:29 +0200 Subject: [PATCH 02/95] Add todos --- .../src/net/osmand/plus/settings/backend/OsmandSettings.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java b/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java index 93705e3c69..523caf7866 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java @@ -186,10 +186,12 @@ public class OsmandSettings { + // TODO doesn't look correct package visibility public Object getProfilePreferences(ApplicationMode mode) { return settingsAPI.getPreferenceObject(getSharedPreferencesName(mode)); } + // TODO doesn't look correct package visibility public Object getProfilePreferences(String modeKey) { return settingsAPI.getPreferenceObject(getSharedPreferencesNameForKey(modeKey)); } @@ -198,16 +200,19 @@ public class OsmandSettings { return registeredPreferences.get(key); } + // TODO doesn't look correct public void setPreferenceForAllModes(String key, Object value) { for (ApplicationMode mode : ApplicationMode.allPossibleValues()) { setPreference(key, value, mode); } } + // TODO doesn't look correct public boolean setPreference(String key, Object value) { return setPreference(key, value, APPLICATION_MODE.get()); } + // TODO doesn't look correct @SuppressWarnings("unchecked") public boolean setPreference(String key, Object value, ApplicationMode mode) { OsmandPreference preference = registeredPreferences.get(key); From cc107157fcc72062930dc41db77f10587093a708 Mon Sep 17 00:00:00 2001 From: simon Date: Wed, 30 Sep 2020 14:34:14 +0300 Subject: [PATCH 03/95] oauth authtoken saved --- OsmAnd/AndroidManifest.xml | 19 ++- OsmAnd/build.gradle | 7 ++ .../osmedit/SettingsOsmEditingActivity.java | 47 +++++++- .../oauth/OsmOAuthAuthorizationClient.java | 114 ++++++++++++++++++ .../plus/settings/backend/OsmandSettings.java | 6 + 5 files changed, 184 insertions(+), 9 deletions(-) create mode 100644 OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationClient.java diff --git a/OsmAnd/AndroidManifest.xml b/OsmAnd/AndroidManifest.xml index 2c6d6b6463..4e5395a04a 100644 --- a/OsmAnd/AndroidManifest.xml +++ b/OsmAnd/AndroidManifest.xml @@ -7,7 +7,7 @@ - + @@ -52,7 +52,7 @@ @@ -65,7 +65,7 @@ - + - + + + + + + + + @@ -1025,7 +1034,7 @@ callback) { + if (accessToken == null) { + throw new IllegalStateException("Access token is null"); + } + OAuthRequest req = new OAuthRequest(Verb.GET, url); + service.signRequest(accessToken, req); + service.execute(req, callback); + } + + public void startOAuth(ViewGroup rootLayout) { + try { + requestToken = service.getRequestToken(); + loadWebView(rootLayout, service.getAuthorizationUrl(requestToken)); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } + } + + public void authorize(String oauthVerifier) { + try { + accessToken = service.getAccessToken(requestToken, oauthVerifier); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } + saveToken(); + } + + public boolean isValidToken(){ + return !(accessToken == null); + } + + public void restoreToken() { + String token = application.getSettings().USER_ACCESS_TOKEN.get(); + String tokenSecret = application.getSettings().USER_ACCESS_TOKEN_SECRET.get(); + accessToken = new OAuth1AccessToken(token, tokenSecret); + } + + private void saveToken() { + application.getSettings().USER_ACCESS_TOKEN.set(accessToken.getToken()); + application.getSettings().USER_ACCESS_TOKEN_SECRET.set(accessToken.getTokenSecret()); + } + + private void loadWebView(ViewGroup root, String url) { + WebView webView = new WebView(root.getContext()); + webView.requestFocus(View.FOCUS_DOWN); + webView.loadUrl(url); + root.addView(webView); + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java b/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java index e41c7d58df..a3e5876a0b 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java @@ -2023,6 +2023,12 @@ public class OsmandSettings { public final OsmandPreference USER_PASSWORD = new StringPreference("user_password", "").makeGlobal(); + public final OsmandPreference USER_ACCESS_TOKEN = + new StringPreference("user_access_token", "").makeGlobal(); + + public final OsmandPreference USER_ACCESS_TOKEN_SECRET = + new StringPreference("user_access_token_secret", "").makeGlobal(); + // this value boolean is synchronized with settings_pref.xml preference offline POI/Bugs edition public final OsmandPreference OFFLINE_EDITION = new BooleanPreference("offline_osm_editing", true).makeGlobal(); From 6d0e76095fa72cc2efd0e97797448eeae43f85c8 Mon Sep 17 00:00:00 2001 From: simon Date: Wed, 30 Sep 2020 17:00:02 +0300 Subject: [PATCH 04/95] saving state --- .../plus/osmedit/EditPOIMenuController.java | 14 ++++- .../plus/osmedit/OpenstreetmapRemoteUtil.java | 11 +++- .../plus/osmedit/OsmBugsRemoteUtil.java | 11 +++- .../osmedit/SettingsOsmEditingActivity.java | 63 +++++++++++++++---- .../UploadOpenstreetmapPointAsyncTask.java | 4 ++ .../oauth/OsmOAuthAuthorizationClient.java | 5 ++ 6 files changed, 90 insertions(+), 18 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/osmedit/EditPOIMenuController.java b/OsmAnd/src/net/osmand/plus/osmedit/EditPOIMenuController.java index 47c2eb5200..b94ac7cc1c 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/EditPOIMenuController.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/EditPOIMenuController.java @@ -14,6 +14,7 @@ import net.osmand.plus.activities.MapActivity; import net.osmand.plus.mapcontextmenu.MenuController; import net.osmand.plus.osmedit.OsmPoint.Action; import net.osmand.plus.osmedit.dialogs.SendPoiDialogFragment; +import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationClient; import net.osmand.plus.render.RenderingIcons; import net.osmand.util.Algorithms; @@ -39,9 +40,16 @@ public class EditPOIMenuController extends MenuController { public void buttonPressed() { MapActivity activity = getMapActivity(); if (plugin != null && activity != null) { - SendPoiDialogFragment sendPoiDialogFragment = - SendPoiDialogFragment.createInstance(new OsmPoint[]{getOsmPoint()}, SendPoiDialogFragment.PoiUploaderType.SIMPLE); - sendPoiDialogFragment.show(activity.getSupportFragmentManager(), SendPoiDialogFragment.TAG); + OsmOAuthAuthorizationClient client = new OsmOAuthAuthorizationClient(activity.getMyApplication()); + if (client.isValidToken()){ + new SendPoiDialogFragment.SimpleProgressDialogPoiUploader(activity). + showProgressDialog(new OsmPoint[] { getOsmPoint() }, false, false); + } + else { + SendPoiDialogFragment sendPoiDialogFragment = + SendPoiDialogFragment.createInstance(new OsmPoint[]{getOsmPoint()}, SendPoiDialogFragment.PoiUploaderType.SIMPLE); + sendPoiDialogFragment.show(activity.getSupportFragmentManager(), SendPoiDialogFragment.TAG); + } } } }; diff --git a/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java b/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java index 3577987a8b..c8bf73e423 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java @@ -21,6 +21,7 @@ import net.osmand.osm.io.Base64; import net.osmand.osm.io.NetworkUtils; import net.osmand.osm.io.OsmBaseStorage; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationClient; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.Version; @@ -119,8 +120,14 @@ public class OpenstreetmapRemoteUtil implements OpenstreetmapUtil { connection.setRequestProperty("User-Agent", Version.getFullVersion(ctx)); //$NON-NLS-1$ StringBuilder responseBody = new StringBuilder(); if (doAuthenticate) { - String token = settings.USER_NAME.get() + ":" + settings.USER_PASSWORD.get(); //$NON-NLS-1$ - connection.addRequestProperty("Authorization", "Basic " + Base64.encode(token.getBytes("UTF-8"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + OsmOAuthAuthorizationClient client = new OsmOAuthAuthorizationClient(ctx); + if (client.isValidToken()){ + connection.addRequestProperty("Authorization", "OAuth " + client.getAccessToken()); + } + else { + String token = settings.USER_NAME.get() + ":" + settings.USER_PASSWORD.get(); //$NON-NLS-1$ + connection.addRequestProperty("Authorization", "Basic " + Base64.encode(token.getBytes("UTF-8"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } } connection.setDoInput(true); if (requestMethod.equals("PUT") || requestMethod.equals("POST") || requestMethod.equals("DELETE")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ diff --git a/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java b/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java index 8d1238e324..581206fb98 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java @@ -5,6 +5,7 @@ import net.osmand.PlatformUtil; import net.osmand.osm.io.Base64; import net.osmand.osm.io.NetworkUtils; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationClient; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.Version; @@ -109,6 +110,7 @@ public class OsmBugsRemoteUtil implements OsmBugsUtil { private OsmBugResult editingPOI(String url, String requestMethod, String userOperation, boolean anonymous) { + OsmOAuthAuthorizationClient client = new OsmOAuthAuthorizationClient(this.app); OsmBugResult r = new OsmBugResult(); try { HttpURLConnection connection = NetworkUtils.getHttpURLConnection(url); @@ -118,8 +120,13 @@ public class OsmBugsRemoteUtil implements OsmBugsUtil { connection.setRequestProperty("User-Agent", Version.getFullVersion(app)); //$NON-NLS-1$ if (!anonymous) { - String token = settings.USER_NAME.get() + ":" + settings.USER_PASSWORD.get(); //$NON-NLS-1$ - connection.addRequestProperty("Authorization", "Basic " + Base64.encode(token.getBytes("UTF-8"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (client.isValidToken()){ + connection.addRequestProperty("Authorization", "OAuth " + client.getAccessToken()); + } + else { + String token = settings.USER_NAME.get() + ":" + settings.USER_PASSWORD.get(); //$NON-NLS-1$ + connection.addRequestProperty("Authorization", "Basic " + Base64.encode(token.getBytes("UTF-8"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } } connection.setDoInput(true); diff --git a/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java b/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java index d2cd35e82b..c0262e436f 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java @@ -18,6 +18,8 @@ import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; +import com.github.scribejava.core.model.OAuthAsyncRequestCallback; +import com.github.scribejava.core.model.Response; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationClient; import net.osmand.plus.OsmandApplication; @@ -25,6 +27,8 @@ import net.osmand.plus.R; import net.osmand.plus.activities.SettingsBaseActivity; import net.osmand.plus.settings.backend.OsmAndAppCustomization; +import java.io.IOException; + public class SettingsOsmEditingActivity extends SettingsBaseActivity { OsmOAuthAuthorizationClient client; @@ -72,17 +76,54 @@ public class SettingsOsmEditingActivity extends SettingsBaseActivity { grp.addPreference(pref); final Preference prefOAuth = new Preference(this); - prefOAuth.setTitle(R.string.osb_author_dialog_password); - prefOAuth.setSummary(R.string.osb_author_dialog_password); - prefOAuth.setKey("local_openstreetmap_points"); - prefOAuth.setOnPreferenceClickListener(new OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - ViewGroup preferenceView = (ViewGroup)getListView().getChildAt(preference.getOrder()); - client.startOAuth(preferenceView); - return true; - } - }); + if (client.isValidToken()){ + prefOAuth.setTitle(R.string.osm_authorization_success); + prefOAuth.setSummary(R.string.osm_authorization_success); + prefOAuth.setKey("local_openstreetmap_token"); + + final Preference prefTestUser = new Preference(this); + prefTestUser.setTitle("Test user request"); + prefTestUser.setSummary("Test user request"); + prefTestUser.setKey("local_openstreetmap_token"); + prefTestUser.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + String url = "https://api.openstreetmap.org/api/0.6/user/details"; + client.performGetRequest(url, new OAuthAsyncRequestCallback() { + @Override + public void onCompleted(Response response) { + try { + Toast.makeText(SettingsOsmEditingActivity.this, + "DATA RETRIEVED: " + response.getBody().toString(),Toast.LENGTH_SHORT).show(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public void onThrowable(Throwable t) { + Toast.makeText(SettingsOsmEditingActivity.this, + "ERROR happened",Toast.LENGTH_SHORT).show(); + } + }); + return true; + } + }); + grp.addPreference(prefTestUser); + } + else { + prefOAuth.setTitle(R.string.osb_author_dialog_password); + prefOAuth.setSummary(R.string.osb_author_dialog_password); + prefOAuth.setKey("local_openstreetmap_token"); + prefOAuth.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + ViewGroup preferenceView = (ViewGroup)getListView().getChildAt(preference.getOrder()); + client.startOAuth(preferenceView); + return true; + } + }); + } grp.addPreference(prefOAuth); } diff --git a/OsmAnd/src/net/osmand/plus/osmedit/UploadOpenstreetmapPointAsyncTask.java b/OsmAnd/src/net/osmand/plus/osmedit/UploadOpenstreetmapPointAsyncTask.java index 1d99aee0c0..3824d060c7 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/UploadOpenstreetmapPointAsyncTask.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/UploadOpenstreetmapPointAsyncTask.java @@ -1,6 +1,7 @@ package net.osmand.plus.osmedit; import android.content.DialogInterface; +import android.net.TrafficStats; import android.os.AsyncTask; import net.osmand.osm.edit.Entity; @@ -43,6 +44,9 @@ public class UploadOpenstreetmapPointAsyncTask @Override protected Map doInBackground(OsmPoint... points) { + final int THREAD_ID = 10102; + TrafficStats.setThreadStatsTag(THREAD_ID); + Map loadErrorsMap = new HashMap<>(); boolean uploaded = false; diff --git a/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationClient.java b/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationClient.java index 95819b8e5d..1e53c48628 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationClient.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationClient.java @@ -53,6 +53,11 @@ public class OsmOAuthAuthorizationClient { final int THREAD_ID = 10101; TrafficStats.setThreadStatsTag(THREAD_ID); this.application = application; + restoreToken(); + } + + public String getAccessToken() { + return this.accessToken.getToken(); } public void performGetRequest(String url,OAuthAsyncRequestCallback callback) { From 48dbb64d09610243ef6956678e1920db7d9cab2b Mon Sep 17 00:00:00 2001 From: Vitaliy Date: Mon, 1 Jun 2020 15:47:01 +0300 Subject: [PATCH 05/95] Fix kmz file import --- .../net/osmand/plus/helpers/ImportHelper.java | 38 ++++++++++++------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java b/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java index c57f53a0fa..a8d621f9ed 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java +++ b/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java @@ -71,6 +71,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; +import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import static android.app.Activity.RESULT_OK; @@ -314,13 +315,17 @@ public class ImportHelper { } else if (fileName != null && fileName.endsWith(KMZ_SUFFIX)) { try { zis = new ZipInputStream(is); - zis.getNextEntry(); - final String result = Kml2Gpx.toGpx(zis); - if (result != null) { - try { - return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - return null; + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + if (entry.getName().endsWith(KML_SUFFIX)) { + final String result = Kml2Gpx.toGpx(zis); + if (result != null) { + try { + return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8"))); + } catch (UnsupportedEncodingException e) { + return null; + } + } } } } catch (Exception e) { @@ -418,13 +423,18 @@ public class ImportHelper { is = app.getContentResolver().openInputStream(kmzFile); if (is != null) { zis = new ZipInputStream(is); - zis.getNextEntry(); - final String result = Kml2Gpx.toGpx(zis); - if (result != null) { - try { - return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - return null; + + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + if (entry.getName().endsWith(KML_SUFFIX)) { + final String result = Kml2Gpx.toGpx(zis); + if (result != null) { + try { + return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8"))); + } catch (UnsupportedEncodingException e) { + return null; + } + } } } } From 38ba94ee1c9b9bb4a9d994bceee44266c2ef0b16 Mon Sep 17 00:00:00 2001 From: Vitaliy Date: Fri, 2 Oct 2020 11:56:07 +0300 Subject: [PATCH 06/95] Add base import task --- .../net/osmand/plus/helpers/ImportHelper.java | 258 ++++++------------ 1 file changed, 89 insertions(+), 169 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java b/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java index a8d621f9ed..febffa73bf 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java +++ b/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java @@ -75,13 +75,13 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import static android.app.Activity.RESULT_OK; -import static net.osmand.IndexConstants.WPT_CHART_FILE_EXT; import static net.osmand.IndexConstants.GPX_FILE_EXT; import static net.osmand.IndexConstants.OSMAND_SETTINGS_FILE_EXT; import static net.osmand.IndexConstants.RENDERER_INDEX_EXT; import static net.osmand.IndexConstants.ROUTING_FILE_EXT; import static net.osmand.IndexConstants.SQLITE_CHART_FILE_EXT; import static net.osmand.IndexConstants.SQLITE_EXT; +import static net.osmand.IndexConstants.WPT_CHART_FILE_EXT; import static net.osmand.data.FavouritePoint.DEFAULT_BACKGROUND_TYPE; import static net.osmand.plus.AppInitializer.loadRoutingFiles; import static net.osmand.plus.myplaces.FavoritesActivity.FAV_TAB; @@ -92,17 +92,20 @@ import static net.osmand.plus.myplaces.FavoritesActivity.TAB_ID; * @author Koen Rabaey */ public class ImportHelper { - public final static Log log = PlatformUtil.getLog(ImportHelper.class); + + public static final Log log = PlatformUtil.getLog(ImportHelper.class); + public static final String KML_SUFFIX = ".kml"; public static final String KMZ_SUFFIX = ".kmz"; - private final AppCompatActivity activity; + public static final int IMPORT_FILE_REQUEST = 1006; + private final OsmandApplication app; private final OsmandMapTileView mapView; + private final AppCompatActivity activity; + private OnGpxImportCompleteListener gpxImportCompleteListener; - public final static int IMPORT_FILE_REQUEST = 1006; - public enum ImportType { SETTINGS(OSMAND_SETTINGS_FILE_EXT), ROUTING(ROUTING_FILE_EXT), @@ -189,20 +192,19 @@ public class ImportHelper { } public void handleFileImport(Uri intentUri, String fileName, Bundle extras, boolean useImportDir) { - final boolean isFileIntent = "file".equals(intentUri.getScheme()); - final boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(intentUri.getPath())); - - final boolean saveFile = !isFileIntent || !isOsmandSubdir; + boolean isFileIntent = "file".equals(intentUri.getScheme()); + boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(intentUri.getPath())); + boolean saveFile = !isFileIntent || !isOsmandSubdir; if (fileName == null) { handleGpxOrFavouritesImport(intentUri, fileName, saveFile, useImportDir, false, false); - } else if (fileName.endsWith(KML_SUFFIX)) { + } else if (fileName.endsWith(KML_SUFFIX)) { handleKmlImport(intentUri, fileName, saveFile, useImportDir); } else if (fileName.endsWith(KMZ_SUFFIX)) { handleKmzImport(intentUri, fileName, saveFile, useImportDir); } else if (fileName.endsWith(IndexConstants.BINARY_MAP_INDEX_EXT)) { handleObfImport(intentUri, fileName); - } else if (fileName.endsWith(IndexConstants.SQLITE_EXT)) { + } else if (fileName.endsWith(SQLITE_EXT)) { handleSqliteTileImport(intentUri, fileName); } else if (fileName.endsWith(OSMAND_SETTINGS_FILE_EXT)) { handleOsmAndSettingsImport(intentUri, fileName, extras, null); @@ -220,7 +222,8 @@ public class ImportHelper { public static String getNameFromContentUri(OsmandApplication app, Uri contentUri) { try { final String name; - final Cursor returnCursor = app.getContentResolver().query(contentUri, new String[]{OpenableColumns.DISPLAY_NAME}, null, null, null); + final Cursor returnCursor = app.getContentResolver().query(contentUri, + new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null); if (returnCursor != null && returnCursor.moveToFirst()) { int columnIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); if (columnIndex != -1) { @@ -239,19 +242,12 @@ public class ImportHelper { log.error(e.getMessage(), e); return null; } - } @SuppressLint("StaticFieldLeak") private void handleGpxImport(final Uri gpxFile, final String fileName, final boolean save, final boolean useImportDir, final boolean showInDetailsActivity) { - new AsyncTask() { - ProgressDialog progress = null; - - @Override - protected void onPreExecute() { - progress = ProgressDialog.show(activity, app.getString(R.string.loading_smth, ""), app.getString(R.string.loading_data)); - } + AsyncTask gpxImportTask = new BaseImportAsyncTask() { @Override protected GPXFile doInBackground(Void... nothing) { @@ -266,35 +262,25 @@ public class ImportHelper { } catch (SecurityException e) { log.error(e.getMessage(), e); } finally { - if (is != null) try { - is.close(); - } catch (IOException ignore) { - } + Algorithms.closeStream(is); } return null; } @Override protected void onPostExecute(GPXFile result) { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } + hideProgress(); handleResult(result, fileName, save, useImportDir, false, showInDetailsActivity); } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + }; + executeImportTask(gpxImportTask); } @SuppressLint("StaticFieldLeak") private void handleGpxOrFavouritesImport(final Uri fileUri, final String fileName, final boolean save, - final boolean useImportDir, final boolean forceImportFavourites, - final boolean forceImportGpx) { - new AsyncTask() { - ProgressDialog progress = null; - - @Override - protected void onPreExecute() { - progress = ProgressDialog.show(activity, app.getString(R.string.loading_smth, ""), app.getString(R.string.loading_data)); - } + final boolean useImportDir, final boolean forceImportFavourites, + final boolean forceImportGpx) { + AsyncTask gpxOrFavouritesImportTask = new BaseImportAsyncTask() { @Override protected GPXFile doInBackground(Void... nothing) { @@ -340,40 +326,24 @@ public class ImportHelper { } catch (SecurityException e) { log.error(e.getMessage(), e); } finally { - if (is != null) try { - is.close(); - } catch (IOException ignore) { - } - if (zis != null) try { - zis.close(); - } catch (IOException ignore) { - } + Algorithms.closeStream(is); + Algorithms.closeStream(zis); } return null; } @Override protected void onPostExecute(final GPXFile result) { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } + hideProgress(); importGpxOrFavourites(result, fileName, save, useImportDir, forceImportFavourites, forceImportGpx); } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + }; + executeImportTask(gpxOrFavouritesImportTask); } @SuppressLint("StaticFieldLeak") private void importFavoritesImpl(final GPXFile gpxFile, final String fileName, final boolean forceImportFavourites) { - final AsyncTask favoritesImportTask = new AsyncTask() { - ProgressDialog progress = null; - - @Override - protected void onPreExecute() { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress = ProgressDialog.show(activity, app.getString(R.string.loading_smth, ""), - app.getString(R.string.loading_data)); - } - } + AsyncTask favoritesImportTask = new BaseImportAsyncTask() { @Override protected GPXFile doInBackground(Void... nothing) { @@ -391,9 +361,7 @@ public class ImportHelper { @Override protected void onPostExecute(GPXFile result) { - if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } + hideProgress(); Toast.makeText(activity, R.string.fav_imported_sucessfully, Toast.LENGTH_LONG).show(); final Intent newIntent = new Intent(activity, app.getAppCustomization().getFavoritesActivity()); @@ -407,13 +375,7 @@ public class ImportHelper { @SuppressLint("StaticFieldLeak") private void handleKmzImport(final Uri kmzFile, final String name, final boolean save, final boolean useImportDir) { - new AsyncTask() { - ProgressDialog progress = null; - - @Override - protected void onPreExecute() { - progress = ProgressDialog.show(activity, app.getString(R.string.loading_smth, ""), app.getString(R.string.loading_data)); - } + AsyncTask kmzImportTask = new BaseImportAsyncTask() { @Override protected GPXFile doInBackground(Void... voids) { @@ -441,39 +403,25 @@ public class ImportHelper { } catch (Exception e) { log.error(e.getMessage(), e); } finally { - try { - if (is != null) { - is.close(); - } - if (zis != null) { - zis.close(); - } - } catch (IOException ignore) { - } + Algorithms.closeStream(is); + Algorithms.closeStream(zis); } return null; } @Override protected void onPostExecute(GPXFile result) { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } + hideProgress(); handleResult(result, name, save, useImportDir, false); } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + }; + executeImportTask(kmzImportTask); } @SuppressLint("StaticFieldLeak") private void handleKmlImport(final Uri kmlFile, final String name, final boolean save, final boolean useImportDir) { - new AsyncTask() { - ProgressDialog progress = null; - - @Override - protected void onPreExecute() { - progress = ProgressDialog.show(activity, app.getString(R.string.loading_smth, ""), app.getString(R.string.loading_data)); - } + AsyncTask kmlImportTask = new BaseImportAsyncTask() { @Override protected GPXFile doInBackground(Void... nothing) { @@ -495,34 +443,23 @@ public class ImportHelper { } catch (SecurityException e) { log.error(e.getMessage(), e); } finally { - if (is != null) try { - is.close(); - } catch (IOException ignore) { - } + Algorithms.closeStream(is); } return null; } @Override protected void onPostExecute(GPXFile result) { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } + hideProgress(); handleResult(result, name, save, useImportDir, false); } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + }; + executeImportTask(kmlImportTask); } @SuppressLint("StaticFieldLeak") private void handleObfImport(final Uri obfFile, final String name) { - new AsyncTask() { - - ProgressDialog progress; - - @Override - protected void onPreExecute() { - progress = ProgressDialog.show(activity, app.getString(R.string.loading_smth, ""), app.getString(R.string.loading_data)); - } + AsyncTask obfImportTask = new BaseImportAsyncTask() { @Override protected String doInBackground(Void... voids) { @@ -537,12 +474,11 @@ public class ImportHelper { @Override protected void onPostExecute(String message) { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } - Toast.makeText(app, message, Toast.LENGTH_SHORT).show(); + hideProgress(); + app.showShortToastMessage(message); } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + }; + executeImportTask(obfImportTask); } @NonNull @@ -583,7 +519,7 @@ public class ImportHelper { } catch (SecurityException e) { e.printStackTrace(); error = e.getMessage(); - } finally { + } finally { if (in != null) { try { in.close(); @@ -604,14 +540,7 @@ public class ImportHelper { @SuppressLint("StaticFieldLeak") private void handleSqliteTileImport(final Uri uri, final String name) { - new AsyncTask() { - - ProgressDialog progress; - - @Override - protected void onPreExecute() { - progress = ProgressDialog.show(activity, app.getString(R.string.loading_smth, ""), app.getString(R.string.loading_data)); - } + AsyncTask sqliteTileImportTask = new BaseImportAsyncTask() { @Override protected String doInBackground(Void... voids) { @@ -620,9 +549,7 @@ public class ImportHelper { @Override protected void onPostExecute(String error) { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } + hideProgress(); if (error == null) { OsmandRasterMapsPlugin plugin = OsmandPlugin.getPlugin(OsmandRasterMapsPlugin.class); if (plugin != null && !plugin.isActive() && !plugin.needsInstallation()) { @@ -637,7 +564,8 @@ public class ImportHelper { Toast.makeText(app, app.getString(R.string.map_import_error) + ": " + error, Toast.LENGTH_SHORT).show(); } } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + }; + executeImportTask(sqliteTileImportTask); } public void chooseFileToImport(final ImportType importType, final CallbackWithObject callback) { @@ -667,21 +595,21 @@ public class ImportHelper { } else if ("content".equals(scheme)) { fileName = getNameFromContentUri(app, data); } - + if (fileName.endsWith(importType.getExtension())) { if (importType.equals(ImportType.SETTINGS)) { handleOsmAndSettingsImport(data, fileName, resultData.getExtras(), callback); - } else if (importType.equals(ImportType.ROUTING)){ + } else if (importType.equals(ImportType.ROUTING)) { handleXmlFileImport(data, fileName, callback); } } else { - app.showToastMessage(app.getString(R.string.not_support_file_type_with_ext, + app.showToastMessage(app.getString(R.string.not_support_file_type_with_ext, importType.getExtension().replaceAll("\\.", "").toUpperCase())); } } } }); - + mapActivity.registerActivityResultListener(listener); mapActivity.startActivityForResult(intent, IMPORT_FILE_REQUEST); } @@ -712,16 +640,7 @@ public class ImportHelper { @SuppressLint("StaticFieldLeak") private void handleOsmAndSettingsImport(final Uri uri, final String name, final String latestChanges, final int version, final CallbackWithObject> callback) { - final AsyncTask settingsImportTask = new AsyncTask() { - - ProgressDialog progress; - - @Override - protected void onPreExecute() { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress = ProgressDialog.show(activity, app.getString(R.string.loading_smth, ""), app.getString(R.string.loading_data)); - } - } + AsyncTask settingsImportTask = new BaseImportAsyncTask() { @Override protected String doInBackground(Void... voids) { @@ -741,9 +660,7 @@ public class ImportHelper { app.getSettingsHelper().collectSettings(file, latestChanges, version, new SettingsCollectListener() { @Override public void onSettingsCollectFinished(boolean succeed, boolean empty, @NonNull List items) { - if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } + hideProgress(); if (succeed) { List pluginIndependentItems = new ArrayList<>(); List pluginSettingsItems = new ArrayList<>(); @@ -767,9 +684,7 @@ public class ImportHelper { } }); } else { - if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } + hideProgress(); app.showShortToastMessage(app.getString(R.string.file_import_error, name, error)); } } @@ -835,17 +750,14 @@ public class ImportHelper { @SuppressLint("StaticFieldLeak") private void handleXmlFileImport(final Uri intentUri, final String fileName, final CallbackWithObject routingCallback) { - final AsyncTask renderingImportTask = new AsyncTask() { + AsyncTask renderingImportTask = new BaseImportAsyncTask() { private String destFileName; private ImportType importType; - private ProgressDialog progress; @Override protected void onPreExecute() { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress = ProgressDialog.show(activity, app.getString(R.string.loading_smth, ""), app.getString(R.string.loading_data)); - } + showProgress(); destFileName = fileName; } @@ -893,12 +805,6 @@ public class ImportHelper { } } - private void hideProgress() { - if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } - } - private File getDestinationDir() { if (importType == ImportType.ROUTING) { return app.getAppPath(IndexConstants.ROUTING_PROFILES_DIR); @@ -947,11 +853,7 @@ public class ImportHelper { break; } } - try { - is.close(); - } catch (IOException e) { - log.error(e); - } + Algorithms.closeStream(is); } } catch (FileNotFoundException | XmlPullParserException e) { log.error(e); @@ -960,11 +862,7 @@ public class ImportHelper { } catch (SecurityException e) { log.error(e.getMessage(), e); } finally { - if (is != null) try { - is.close(); - } catch (IOException e) { - log.error(e); - } + Algorithms.closeStream(is); } } }; @@ -986,9 +884,8 @@ public class ImportHelper { } } else { if (save) { - new SaveAsyncTask(result, name, useImportDir, showInDetailsActivity) - .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } else if (showInDetailsActivity) { + executeImportTask(new SaveAsyncTask(result, name, useImportDir, showInDetailsActivity)); + } else { showGpxInDetailsActivity(result); } if (gpxImportCompleteListener != null) { @@ -1162,8 +1059,8 @@ public class ImportHelper { } private void importGpxOrFavourites(final GPXFile gpxFile, final String fileName, final boolean save, - final boolean useImportDir, final boolean forceImportFavourites, - final boolean forceImportGpx) { + final boolean useImportDir, final boolean forceImportFavourites, + final boolean forceImportGpx) { if (gpxFile == null || gpxFile.isPointsEmpty()) { if (forceImportFavourites) { final DialogInterface.OnClickListener importAsTrackListener = new DialogInterface.OnClickListener() { @@ -1258,4 +1155,27 @@ public class ImportHelper { importTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, requests); } } + + protected abstract class BaseImportAsyncTask extends AsyncTask { + + protected ProgressDialog progress; + + @Override + protected void onPreExecute() { + showProgress(); + } + + protected void showProgress() { + if (AndroidUtils.isActivityNotDestroyed(activity)) { + String title = app.getString(R.string.loading_smth, ""); + progress = ProgressDialog.show(activity, title, app.getString(R.string.loading_data)); + } + } + + protected void hideProgress() { + if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { + progress.dismiss(); + } + } + } } \ No newline at end of file From 689ebf5b75598182772139cbef7a71eb8544065d Mon Sep 17 00:00:00 2001 From: simon Date: Fri, 2 Oct 2020 14:59:10 +0300 Subject: [PATCH 07/95] oauth finished --- OsmAnd-java/build.gradle | 5 +- .../java/net/osmand/osm/io/NetworkUtils.java | 142 ++++++++++-------- .../oauth/OsmOAuthAuthorizationClient.java | 134 +++++++++++++++++ OsmAnd/build.gradle | 2 +- .../plus/download/DownloadIndexesThread.java | 3 + .../plus/osmedit/EditPOIMenuController.java | 6 +- .../plus/osmedit/OpenstreetmapRemoteUtil.java | 108 +++++-------- .../plus/osmedit/OsmBugsRemoteUtil.java | 9 +- .../osmand/plus/osmedit/OsmEditingPlugin.java | 22 +-- .../osmedit/SettingsOsmEditingActivity.java | 9 +- .../oauth/OsmOAuthAuthorizationAdapter.java | 79 ++++++++++ .../oauth/OsmOAuthAuthorizationClient.java | 119 --------------- 12 files changed, 353 insertions(+), 285 deletions(-) create mode 100644 OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java create mode 100644 OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java delete mode 100644 OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationClient.java diff --git a/OsmAnd-java/build.gradle b/OsmAnd-java/build.gradle index 4385f9d0b0..0d0a3c265d 100644 --- a/OsmAnd-java/build.gradle +++ b/OsmAnd-java/build.gradle @@ -1,6 +1,6 @@ apply plugin: 'java' apply plugin: 'maven-publish' - + configurations { android } @@ -104,6 +104,9 @@ dependencies { implementation 'com.moparisthebest:junidecode:0.1.1' implementation 'com.vividsolutions:jts-core:1.14.0' implementation 'com.google.openlocationcode:openlocationcode:1.0.4' + implementation('com.github.scribejava:scribejava-apis:7.1.1'){ + exclude group: "com.fasterxml.jackson.core" + } // turn off for now //implementation 'com.atilika.kuromoji:kuromoji-ipadic:0.9.0' implementation 'net.sf.kxml:kxml2:2.1.8' diff --git a/OsmAnd-java/src/main/java/net/osmand/osm/io/NetworkUtils.java b/OsmAnd-java/src/main/java/net/osmand/osm/io/NetworkUtils.java index 282d6addbd..bdf5b6a70e 100644 --- a/OsmAnd-java/src/main/java/net/osmand/osm/io/NetworkUtils.java +++ b/OsmAnd-java/src/main/java/net/osmand/osm/io/NetworkUtils.java @@ -1,27 +1,19 @@ package net.osmand.osm.io; -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.InetSocketAddress; -import java.net.MalformedURLException; -import java.net.Proxy; -import java.net.URL; -import java.net.URLEncoder; -import java.util.Map; -import java.util.zip.GZIPOutputStream; - +import com.github.scribejava.core.model.OAuthRequest; +import com.github.scribejava.core.model.Response; +import com.github.scribejava.core.model.Verb; import net.osmand.PlatformUtil; +import net.osmand.osm.oauth.OsmOAuthAuthorizationClient; import net.osmand.util.Algorithms; - import org.apache.commons.logging.Log; +import java.io.*; +import java.net.*; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.zip.GZIPOutputStream; + public class NetworkUtils { private static final Log log = PlatformUtil.getLog(NetworkUtils.class); @@ -55,7 +47,6 @@ public class NetworkUtils { responseBody.append("\n"); //$NON-NLS-1$ } responseBody.append(s); - } is.close(); } @@ -65,9 +56,10 @@ public class NetworkUtils { return e.getMessage(); } } - private static final String BOUNDARY = "CowMooCowMooCowCowCow"; //$NON-NLS-1$ - public static String uploadFile(String urlText, File fileToUpload, String userNamePassword, String formName, boolean gzip, Map additionalMapData){ + public static String uploadFile(String urlText, File fileToUpload, String userNamePassword, + OsmOAuthAuthorizationClient client, + String formName, boolean gzip, Map additionalMapData){ URL url; try { boolean firstPrm =!urlText.contains("?"); @@ -77,47 +69,38 @@ public class NetworkUtils { } log.info("Start uploading file to " + urlText + " " +fileToUpload.getName()); url = new URL(urlText); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setDoInput(true); - conn.setDoOutput(true); - conn.setRequestMethod("POST"); - if(userNamePassword != null) { - conn.setRequestProperty("Authorization", "Basic " + Base64.encode(userNamePassword)); //$NON-NLS-1$ //$NON-NLS-2$ + HttpURLConnection conn; + if (client != null && client.isValidToken()){ + OAuthRequest req = new OAuthRequest(Verb.POST, urlText); + req.setPayload(prepareStream(formName,fileToUpload,gzip)); + client.getService().signRequest(client.getAccessToken(), req); + req.addHeader("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); + try { + Response r = client.getService().execute(req); + if(r.getCode() != 200){ + return r.getBody(); + } + return null; + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } + return null; + } + else { + conn = (HttpURLConnection) url.openConnection(); + conn.setDoInput(true); + conn.setDoOutput(true); + conn.setRequestMethod("POST"); + if(userNamePassword != null) { + conn.setRequestProperty("Authorization", "Basic " + Base64.encode(userNamePassword)); //$NON-NLS-1$ //$NON-NLS-2$ + } } - conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); //$NON-NLS-1$ //$NON-NLS-2$ conn.setRequestProperty("User-Agent", "OsmAnd"); //$NON-NLS-1$ //$NON-NLS-2$ - OutputStream ous = conn.getOutputStream(); -// for (String key : additionalMapData.keySet()) { -// ous.write(("--" + BOUNDARY + "\r\n").getBytes()); -// ous.write(("content-disposition: form-data; name=\"" + key + "\"\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$ -// ous.write((additionalMapData.get(key) + "\r\n").getBytes()); -// } - ous.write(("--" + BOUNDARY+"\r\n").getBytes()); - String filename = fileToUpload.getName(); - if(gzip){ - filename+=".gz"; - } - ous.write(("content-disposition: form-data; name=\""+formName+"\"; filename=\"" + filename + "\"\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$ - ous.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes()); //$NON-NLS-1$ - InputStream fis = new FileInputStream(fileToUpload); - BufferedInputStream bis = new BufferedInputStream(fis, 20 * 1024); - ous.flush(); - if(gzip){ - GZIPOutputStream gous = new GZIPOutputStream(ous, 1024); - Algorithms.streamCopy(bis, gous); - gous.flush(); - gous.finish(); - } else { - Algorithms.streamCopy(bis, ous); - } - - ous.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$ - ous.flush(); - Algorithms.closeStream(bis); - Algorithms.closeStream(ous); - + ous.write(prepareStream(formName,fileToUpload,gzip)); log.info("Finish uploading file " + fileToUpload.getName()); log.info("Response code and message : " + conn.getResponseCode() + " " + conn.getResponseMessage()); if(conn.getResponseCode() != 200){ @@ -136,7 +119,6 @@ public class NetworkUtils { responseBody.append("\n"); //$NON-NLS-1$ } responseBody.append(s); - } is.close(); } @@ -149,6 +131,46 @@ public class NetworkUtils { } } + private static byte[] prepareStream(String formName, File fileToUpload, boolean gzip) { + try { + ByteArrayOutputStream ous = new ByteArrayOutputStream(); +// for (String key : additionalMapData.keySet()) { +// ous.write(("--" + BOUNDARY + "\r\n").getBytes()); +// ous.write(("content-disposition: form-data; name=\"" + key + "\"\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$ +// ous.write((additionalMapData.get(key) + "\r\n").getBytes()); +// } + ous.write(("--" + BOUNDARY + "\r\n").getBytes()); + + String filename = fileToUpload.getName(); + if (gzip) { + filename += ".gz"; + } + ous.write(("content-disposition: form-data; name=\"" + formName + "\"; filename=\"" + filename + "\"\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$ + ous.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes()); //$NON-NLS-1$ + InputStream fis = new FileInputStream(fileToUpload); + BufferedInputStream bis = new BufferedInputStream(fis, 20 * 1024); + ous.flush(); + if (gzip) { + GZIPOutputStream gous = new GZIPOutputStream(ous, 1024); + Algorithms.streamCopy(bis, gous); + gous.flush(); + gous.finish(); + gous.close(); + } else { + Algorithms.streamCopy(bis, ous); + } + + ous.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$ + ous.flush(); + Algorithms.closeStream(bis); + Algorithms.closeStream(ous); + return ous.toByteArray(); + } catch (IOException e) { + e.printStackTrace(); + } + return new byte[0]; + } + public static void setProxy(String host, int port) { if(host != null && port > 0) { InetSocketAddress isa = new InetSocketAddress(host, port); @@ -157,7 +179,7 @@ public class NetworkUtils { proxy = null; } } - + public static Proxy getProxy() { return proxy; } diff --git a/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java b/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java new file mode 100644 index 0000000000..bef043e1ce --- /dev/null +++ b/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java @@ -0,0 +1,134 @@ +// License: GPL. For details, see LICENSE file. +package net.osmand.osm.oauth; + +import com.github.scribejava.core.builder.ServiceBuilder; +import com.github.scribejava.core.builder.api.DefaultApi10a; +import com.github.scribejava.core.builder.api.OAuth1SignatureType; +import com.github.scribejava.core.model.*; +import com.github.scribejava.core.oauth.OAuth10aService; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +/** + * An OAuth 1.0 authorization client. + * + * @since 2746 + */ +public class OsmOAuthAuthorizationClient { + OAuth10aService service; + OAuth1RequestToken requestToken; + OAuth1AccessToken accessToken; + + public OsmOAuthAuthorizationClient(String key, String secret){ + service = new ServiceBuilder(key) + .apiSecret(secret) + .callback("osmand-oauth://example.com/oauth") + .build(new OsmApi()); + } + + static class OsmApi extends DefaultApi10a { + @Override + public OAuth1SignatureType getSignatureType() { + return OAuth1SignatureType.QUERY_STRING; + } + + @Override + public String getRequestTokenEndpoint() { + return "https://www.openstreetmap.org/oauth/request_token"; + } + + @Override + public String getAccessTokenEndpoint() { + return "https://www.openstreetmap.org/oauth/access_token"; + } + + @Override + protected String getAuthorizationBaseUrl() { + return "https://www.openstreetmap.org/oauth/authorize"; + } + } + + public OAuth10aService getService() { + return service; + } + + public void setAccessToken(OAuth1AccessToken accessToken) { this.accessToken = accessToken; } + + public OAuth1AccessToken getAccessToken() { return this.accessToken; } + + public Response performRequestWithoutAuth(String url, String requestMethod, String requestBody) + throws InterruptedException, ExecutionException, IOException { + Verb verb = parseRequestMethod(requestMethod); + OAuthRequest req = new OAuthRequest(verb, url); + req.setPayload(requestBody); + return service.execute(req); + } + + public void performGetRequest(String url, OAuthAsyncRequestCallback callback) { + if (accessToken == null) { + throw new IllegalStateException("Access token is null"); + } + OAuthRequest req = new OAuthRequest(Verb.GET, url); + service.signRequest(accessToken, req); + service.execute(req, callback); + } + + public Response performRequest(String url, String method, String body) + throws InterruptedException, ExecutionException, IOException { + service.getApi().getSignatureType(); + if (accessToken == null) { + throw new IllegalStateException("Access token is null"); + } + Verb verbMethod = parseRequestMethod(method); + OAuthRequest req = new OAuthRequest(verbMethod, url); + req.setPayload(body); + service.signRequest(accessToken, req); + req.addHeader("Content-Type", "application/xml"); + return service.execute(req); + } + + private Verb parseRequestMethod(String method) { + Verb m = Verb.GET; + if (method.equals("POST")) { + m = Verb.POST; + } + if (method.equals("PUT")) { + m = Verb.PUT; + } + if (method.equals("DELETE")) { + m = Verb.DELETE; + } + return m; + } + + public OAuth1RequestToken startOAuth() { + try { + requestToken = service.getRequestToken(); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } + return requestToken; + } + + public OAuth1AccessToken authorize(String oauthVerifier) { + try { + setAccessToken(service.getAccessToken(requestToken, oauthVerifier)); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } + return accessToken; + } + + public boolean isValidToken() { + return !(accessToken == null); + } +} diff --git a/OsmAnd/build.gradle b/OsmAnd/build.gradle index 58803bac25..e18cb21e76 100644 --- a/OsmAnd/build.gradle +++ b/OsmAnd/build.gradle @@ -567,10 +567,10 @@ dependencies { implementation ("com.github.HITGIF:TextFieldBoxes:1.4.5"){ exclude group: 'com.android.support' } - implementation 'com.jaredrummler:colorpicker:1.1.0' implementation('com.github.scribejava:scribejava-apis:7.1.1'){ exclude group: "com.fasterxml.jackson.core" } + implementation 'com.jaredrummler:colorpicker:1.1.0' huaweiImplementation files('libs/huawei-android-drm_v2.5.2.300.jar') freehuaweiImplementation files('libs/huawei-android-drm_v2.5.2.300.jar') diff --git a/OsmAnd/src/net/osmand/plus/download/DownloadIndexesThread.java b/OsmAnd/src/net/osmand/plus/download/DownloadIndexesThread.java index 4b0dd632aa..8f826e76b1 100644 --- a/OsmAnd/src/net/osmand/plus/download/DownloadIndexesThread.java +++ b/OsmAnd/src/net/osmand/plus/download/DownloadIndexesThread.java @@ -5,6 +5,7 @@ import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; +import android.net.TrafficStats; import android.net.Uri; import android.os.AsyncTask; import android.os.AsyncTask.Status; @@ -336,6 +337,8 @@ public class DownloadIndexesThread { @Override protected DownloadResources doInBackground(Void... params) { + final int THREAD_ID = 10103; + TrafficStats.setThreadStatsTag(THREAD_ID); DownloadResources result = null; DownloadOsmandIndexesHelper.IndexFileList indexFileList = DownloadOsmandIndexesHelper.getIndexesList(ctx); if (indexFileList != null) { diff --git a/OsmAnd/src/net/osmand/plus/osmedit/EditPOIMenuController.java b/OsmAnd/src/net/osmand/plus/osmedit/EditPOIMenuController.java index b94ac7cc1c..7d04c73252 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/EditPOIMenuController.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/EditPOIMenuController.java @@ -2,10 +2,8 @@ package net.osmand.plus.osmedit; import android.content.DialogInterface; import android.graphics.drawable.Drawable; - import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; - import net.osmand.data.PointDescription; import net.osmand.osm.PoiType; import net.osmand.plus.OsmandPlugin; @@ -14,7 +12,7 @@ import net.osmand.plus.activities.MapActivity; import net.osmand.plus.mapcontextmenu.MenuController; import net.osmand.plus.osmedit.OsmPoint.Action; import net.osmand.plus.osmedit.dialogs.SendPoiDialogFragment; -import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationClient; +import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationAdapter; import net.osmand.plus.render.RenderingIcons; import net.osmand.util.Algorithms; @@ -40,7 +38,7 @@ public class EditPOIMenuController extends MenuController { public void buttonPressed() { MapActivity activity = getMapActivity(); if (plugin != null && activity != null) { - OsmOAuthAuthorizationClient client = new OsmOAuthAuthorizationClient(activity.getMyApplication()); + OsmOAuthAuthorizationAdapter client = new OsmOAuthAuthorizationAdapter(activity.getMyApplication()); if (client.isValidToken()){ new SendPoiDialogFragment.SimpleProgressDialogPoiUploader(activity). showProgressDialog(new OsmPoint[] { getOsmPoint() }, false, false); diff --git a/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java b/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java index c8bf73e423..e550d25d73 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java @@ -2,7 +2,8 @@ package net.osmand.plus.osmedit; import android.util.Xml; import android.widget.Toast; - +import com.github.scribejava.core.model.Response; +import gnu.trove.list.array.TLongArrayList; import net.osmand.NativeLibrary; import net.osmand.PlatformUtil; import net.osmand.data.Amenity; @@ -17,39 +18,29 @@ import net.osmand.osm.edit.Entity.EntityType; import net.osmand.osm.edit.EntityInfo; import net.osmand.osm.edit.Node; import net.osmand.osm.edit.Way; -import net.osmand.osm.io.Base64; import net.osmand.osm.io.NetworkUtils; import net.osmand.osm.io.OsmBaseStorage; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationClient; -import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.Version; +import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationAdapter; +import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.util.MapUtils; - import org.apache.commons.logging.Log; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; -import java.io.BufferedReader; -import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; import java.io.StringWriter; -import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.text.MessageFormat; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; - -import gnu.trove.list.array.TLongArrayList; +import java.util.concurrent.ExecutionException; public class OpenstreetmapRemoteUtil implements OpenstreetmapUtil { @@ -100,12 +91,16 @@ public class OpenstreetmapRemoteUtil implements OpenstreetmapUtil { private final static String URL_TO_UPLOAD_GPX = getSiteApi() + "api/0.6/gpx/create"; public String uploadGPXFile(String tagstring, String description, String visibility, File f) { + OsmOAuthAuthorizationAdapter adapter = new OsmOAuthAuthorizationAdapter(ctx); String url = URL_TO_UPLOAD_GPX; Map additionalData = new LinkedHashMap(); additionalData.put("description", description); additionalData.put("tags", tagstring); additionalData.put("visibility", visibility); - return NetworkUtils.uploadFile(url, f, settings.USER_NAME.get() + ":" + settings.USER_PASSWORD.get(), "file", + return NetworkUtils.uploadFile(url, f, + settings.USER_NAME.get() + ":" + settings.USER_PASSWORD.get(), + adapter.getClient(), + "file", true, additionalData); } @@ -113,59 +108,14 @@ public class OpenstreetmapRemoteUtil implements OpenstreetmapUtil { boolean doAuthenticate) { log.info("Sending request " + url); //$NON-NLS-1$ try { - HttpURLConnection connection = NetworkUtils.getHttpURLConnection(url); - - connection.setConnectTimeout(15000); - connection.setRequestMethod(requestMethod); - connection.setRequestProperty("User-Agent", Version.getFullVersion(ctx)); //$NON-NLS-1$ - StringBuilder responseBody = new StringBuilder(); - if (doAuthenticate) { - OsmOAuthAuthorizationClient client = new OsmOAuthAuthorizationClient(ctx); - if (client.isValidToken()){ - connection.addRequestProperty("Authorization", "OAuth " + client.getAccessToken()); - } - else { - String token = settings.USER_NAME.get() + ":" + settings.USER_PASSWORD.get(); //$NON-NLS-1$ - connection.addRequestProperty("Authorization", "Basic " + Base64.encode(token.getBytes("UTF-8"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } + if (doAuthenticate){ + OsmOAuthAuthorizationAdapter client = new OsmOAuthAuthorizationAdapter(ctx); + Response response = client.performRequest(url,requestMethod,requestBody); + return response.getBody(); } - connection.setDoInput(true); - if (requestMethod.equals("PUT") || requestMethod.equals("POST") || requestMethod.equals("DELETE")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - connection.setDoOutput(true); - connection.setRequestProperty("Content-type", "text/xml"); //$NON-NLS-1$ //$NON-NLS-2$ - OutputStream out = connection.getOutputStream(); - if (requestBody != null) { - BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"), 1024); //$NON-NLS-1$ - bwr.write(requestBody); - bwr.flush(); - } - out.close(); - } - connection.connect(); - if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { - String msg = userOperation - + " " + ctx.getString(R.string.failed_op) + " : " + connection.getResponseMessage(); //$NON-NLS-1$//$NON-NLS-2$ - log.error(msg); - showWarning(msg); - } else { - log.info("Response : " + connection.getResponseMessage()); //$NON-NLS-1$ - // populate return fields. - responseBody.setLength(0); - InputStream i = connection.getInputStream(); - if (i != null) { - BufferedReader in = new BufferedReader(new InputStreamReader(i, "UTF-8"), 256); //$NON-NLS-1$ - String s; - boolean f = true; - while ((s = in.readLine()) != null) { - if (!f) { - responseBody.append("\n"); //$NON-NLS-1$ - } else { - f = false; - } - responseBody.append(s); - } - } - return responseBody.toString(); + else { + OsmOAuthAuthorizationAdapter client = new OsmOAuthAuthorizationAdapter(ctx); + client.performRequestWithoutAuth(url,requestMethod,requestBody); } } catch (NullPointerException e) { // that's tricky case why NPE is thrown to fix that problem httpClient could be used @@ -180,6 +130,14 @@ public class OpenstreetmapRemoteUtil implements OpenstreetmapUtil { log.error(userOperation + " " + ctx.getString(R.string.failed_op), e); //$NON-NLS-1$ showWarning(MessageFormat.format(ctx.getResources().getString(R.string.shared_string_action_template) + ": " + ctx.getResources().getString(R.string.shared_string_io_error), userOperation)); + } catch (InterruptedException e) { + log.error(userOperation + " " + ctx.getString(R.string.failed_op), e); //$NON-NLS-1$ + showWarning(MessageFormat.format(ctx.getResources().getString(R.string.shared_string_action_template) + + ": " + ctx.getResources().getString(R.string.shared_string_unexpected_error), userOperation)); + } catch (ExecutionException e) { + log.error(userOperation + " " + ctx.getString(R.string.failed_op), e); //$NON-NLS-1$ + showWarning(MessageFormat.format(ctx.getResources().getString(R.string.shared_string_action_template) + + ": " + ctx.getResources().getString(R.string.shared_string_unexpected_error), userOperation)); } return null; @@ -213,12 +171,16 @@ public class OpenstreetmapRemoteUtil implements OpenstreetmapUtil { } catch (IOException e) { log.error("Unhandled exception", e); //$NON-NLS-1$ } - String response = sendRequest( - getSiteApi() + "api/0.6/changeset/create/", "PUT", writer.getBuffer().toString(), ctx.getString(R.string.opening_changeset), true); //$NON-NLS-1$ //$NON-NLS-2$ - if (response != null && response.length() > 0) { - id = Long.parseLong(response); - } - + String response = sendRequest( + getSiteApi() + "api/0.6/changeset/create/", "PUT", writer.getBuffer().toString(), ctx.getString(R.string.opening_changeset), true); //$NON-NLS-1$ //$NON-NLS-2$ + try { + if (response != null && response.length() > 0) { + log.debug(response); + id = Long.parseLong(response); + } + } catch (Exception e) { + e.printStackTrace(); + } return id; } diff --git a/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java b/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java index 581206fb98..75b226eb3f 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java @@ -5,13 +5,12 @@ import net.osmand.PlatformUtil; import net.osmand.osm.io.Base64; import net.osmand.osm.io.NetworkUtils; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationClient; -import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.Version; import net.osmand.plus.osmedit.OsmPoint.Action; +import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationAdapter; +import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.util.Algorithms; - import org.apache.commons.logging.Log; import java.io.FileNotFoundException; @@ -110,7 +109,7 @@ public class OsmBugsRemoteUtil implements OsmBugsUtil { private OsmBugResult editingPOI(String url, String requestMethod, String userOperation, boolean anonymous) { - OsmOAuthAuthorizationClient client = new OsmOAuthAuthorizationClient(this.app); + OsmOAuthAuthorizationAdapter client = new OsmOAuthAuthorizationAdapter(this.app); OsmBugResult r = new OsmBugResult(); try { HttpURLConnection connection = NetworkUtils.getHttpURLConnection(url); @@ -121,7 +120,7 @@ public class OsmBugsRemoteUtil implements OsmBugsUtil { if (!anonymous) { if (client.isValidToken()){ - connection.addRequestProperty("Authorization", "OAuth " + client.getAccessToken()); + connection.addRequestProperty("Authorization", "OAuth " + client.getClient().getAccessToken().getToken()); } else { String token = settings.USER_NAME.get() + ":" + settings.USER_PASSWORD.get(); //$NON-NLS-1$ diff --git a/OsmAnd/src/net/osmand/plus/osmedit/OsmEditingPlugin.java b/OsmAnd/src/net/osmand/plus/osmedit/OsmEditingPlugin.java index 427831de54..f1b33b8f79 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/OsmEditingPlugin.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/OsmEditingPlugin.java @@ -13,11 +13,9 @@ import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; - import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; - import net.osmand.AndroidUtils; import net.osmand.PlatformUtil; import net.osmand.data.Amenity; @@ -25,13 +23,8 @@ import net.osmand.data.MapObject; import net.osmand.data.TransportStop; import net.osmand.osm.PoiType; import net.osmand.osm.edit.Entity; -import net.osmand.plus.ContextMenuAdapter; +import net.osmand.plus.*; import net.osmand.plus.ContextMenuAdapter.ItemClickListener; -import net.osmand.plus.ContextMenuItem; -import net.osmand.plus.OsmandApplication; -import net.osmand.plus.OsmandPlugin; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.R; import net.osmand.plus.activities.EnumAdapter; import net.osmand.plus.activities.EnumAdapter.IEnumWithResource; import net.osmand.plus.activities.MapActivity; @@ -43,22 +36,16 @@ import net.osmand.plus.myplaces.AvailableGPXFragment.GpxInfo; import net.osmand.plus.myplaces.FavoritesActivity; import net.osmand.plus.osmedit.OsmPoint.Action; import net.osmand.plus.quickaction.QuickActionType; +import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.fragments.BaseSettingsFragment; import net.osmand.plus.views.OsmandMapTileView; import net.osmand.util.Algorithms; - import org.apache.commons.logging.Log; import java.util.ArrayList; import java.util.List; -import static net.osmand.aidlapi.OsmAndCustomizationConstants.MAP_CONTEXT_MENU_CREATE_POI; -import static net.osmand.aidlapi.OsmAndCustomizationConstants.MAP_CONTEXT_MENU_MODIFY_OSM_CHANGE; -import static net.osmand.aidlapi.OsmAndCustomizationConstants.MAP_CONTEXT_MENU_MODIFY_OSM_NOTE; -import static net.osmand.aidlapi.OsmAndCustomizationConstants.MAP_CONTEXT_MENU_MODIFY_POI; -import static net.osmand.aidlapi.OsmAndCustomizationConstants.MAP_CONTEXT_MENU_OPEN_OSM_NOTE; -import static net.osmand.aidlapi.OsmAndCustomizationConstants.OSM_EDITS; -import static net.osmand.aidlapi.OsmAndCustomizationConstants.OSM_NOTES; +import static net.osmand.aidlapi.OsmAndCustomizationConstants.*; import static net.osmand.plus.ContextMenuAdapter.makeDeleteAction; @@ -464,7 +451,8 @@ public class OsmEditingPlugin extends OsmandPlugin { public boolean sendGPXFiles(final Activity la, AvailableGPXFragment f, final GpxInfo... info) { String name = settings.USER_NAME.get(); String pwd = settings.USER_PASSWORD.get(); - if (Algorithms.isEmpty(name) || Algorithms.isEmpty(pwd)) { + String authToken = settings.USER_ACCESS_TOKEN.get(); + if ((Algorithms.isEmpty(name) || Algorithms.isEmpty(pwd)) && Algorithms.isEmpty(authToken)) { Toast.makeText(la, R.string.validate_gpx_upload_name_pwd, Toast.LENGTH_LONG).show(); return false; } diff --git a/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java b/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java index c0262e436f..651fc7ff07 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java @@ -17,20 +17,19 @@ import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; - import com.github.scribejava.core.model.OAuthAsyncRequestCallback; import com.github.scribejava.core.model.Response; -import net.osmand.plus.OsmandPlugin; -import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationClient; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.OsmandPlugin; import net.osmand.plus.R; import net.osmand.plus.activities.SettingsBaseActivity; +import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationAdapter; import net.osmand.plus.settings.backend.OsmAndAppCustomization; import java.io.IOException; public class SettingsOsmEditingActivity extends SettingsBaseActivity { - OsmOAuthAuthorizationClient client; + OsmOAuthAuthorizationAdapter client; @Override public void onCreate(Bundle savedInstanceState) { @@ -44,7 +43,7 @@ public class SettingsOsmEditingActivity extends SettingsBaseActivity { ((OsmandApplication) getApplication()).applyTheme(this); super.onCreate(savedInstanceState); - client = new OsmOAuthAuthorizationClient(this.getMyApplication()); + client = new OsmOAuthAuthorizationAdapter(this.getMyApplication()); getToolbar().setTitle(R.string.osm_settings); @SuppressWarnings("deprecation") diff --git a/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java b/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java new file mode 100644 index 0000000000..5d2313c078 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java @@ -0,0 +1,79 @@ +package net.osmand.plus.osmedit.oauth; + +import android.net.TrafficStats; +import android.view.View; +import android.view.ViewGroup; +import android.webkit.WebView; +import com.github.scribejava.core.model.OAuth1AccessToken; +import com.github.scribejava.core.model.OAuth1RequestToken; +import com.github.scribejava.core.model.OAuthAsyncRequestCallback; +import com.github.scribejava.core.model.Response; +import net.osmand.osm.oauth.OsmOAuthAuthorizationClient; +import net.osmand.plus.BuildConfig; +import net.osmand.plus.OsmandApplication; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class OsmOAuthAuthorizationAdapter { + OsmandApplication application; + OsmOAuthAuthorizationClient client = new OsmOAuthAuthorizationClient(BuildConfig.CONSUMER_KEY, BuildConfig.CONSUMER_SECRET); + + public OsmOAuthAuthorizationAdapter(OsmandApplication application) { + final int THREAD_ID = 10101; + TrafficStats.setThreadStatsTag(THREAD_ID); + this.application = application; + restoreToken(); + } + + public OsmOAuthAuthorizationClient getClient() { + return client; + } + + public boolean isValidToken() { + return client.isValidToken(); + } + + public void restoreToken() { + String token = application.getSettings().USER_ACCESS_TOKEN.get(); + String tokenSecret = application.getSettings().USER_ACCESS_TOKEN_SECRET.get(); + client.setAccessToken(new OAuth1AccessToken(token, tokenSecret)); + } + + public void startOAuth(ViewGroup rootLayout) { + OAuth1RequestToken requestToken = client.startOAuth(); + loadWebView(rootLayout, client.getService().getAuthorizationUrl(requestToken)); + } + + private void saveToken() { + OAuth1AccessToken accessToken = client.getAccessToken(); + application.getSettings().USER_ACCESS_TOKEN.set(accessToken.getToken()); + application.getSettings().USER_ACCESS_TOKEN_SECRET.set(accessToken.getTokenSecret()); + } + + private void loadWebView(ViewGroup root, String url) { + WebView webView = new WebView(root.getContext()); + webView.requestFocus(View.FOCUS_DOWN); + webView.loadUrl(url); + root.addView(webView); + } + + public void performGetRequest(String url, OAuthAsyncRequestCallback callback) { + client.performGetRequest(url, callback); + } + + public Response performRequest(String url, String method, String body) + throws InterruptedException, ExecutionException, IOException { + return client.performRequest(url, method, body); + } + + public Response performRequestWithoutAuth(String url, String method, String body) + throws InterruptedException, ExecutionException, IOException { + return client.performRequestWithoutAuth(url, method, body); + } + + public void authorize(String oauthVerifier) { + client.authorize(oauthVerifier); + saveToken(); + } +} diff --git a/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationClient.java b/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationClient.java deleted file mode 100644 index 1e53c48628..0000000000 --- a/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationClient.java +++ /dev/null @@ -1,119 +0,0 @@ -// License: GPL. For details, see LICENSE file. -package net.osmand.plus.osmedit.oauth; - - -import android.net.TrafficStats; -import android.view.View; -import android.view.ViewGroup; -import android.webkit.WebView; -import com.github.scribejava.core.builder.ServiceBuilder; -import com.github.scribejava.core.builder.api.DefaultApi10a; -import com.github.scribejava.core.model.*; -import com.github.scribejava.core.oauth.OAuth10aService; -import net.osmand.plus.BuildConfig; -import net.osmand.plus.OsmandApplication; - -import java.io.IOException; -import java.util.concurrent.ExecutionException; - -/** - * An OAuth 1.0 authorization client. - * - * @since 2746 - */ -public class OsmOAuthAuthorizationClient { - - OAuth10aService service = new ServiceBuilder(BuildConfig.CONSUMER_KEY) - .apiSecret(BuildConfig.CONSUMER_SECRET) - .debug() - .callback("osmand-oauth://example.com/oauth") - .build(new OsmApi()); - - OAuth1RequestToken requestToken; - OAuth1AccessToken accessToken; - OsmandApplication application; - - static class OsmApi extends DefaultApi10a { - - @Override - public String getRequestTokenEndpoint() { return "https://www.openstreetmap.org/oauth/request_token"; } - - @Override - public String getAccessTokenEndpoint() { - return "https://www.openstreetmap.org/oauth/access_token"; - } - - @Override - protected String getAuthorizationBaseUrl() { - return "https://www.openstreetmap.org/oauth/authorize"; - } - } - - public OsmOAuthAuthorizationClient(OsmandApplication application) { - final int THREAD_ID = 10101; - TrafficStats.setThreadStatsTag(THREAD_ID); - this.application = application; - restoreToken(); - } - - public String getAccessToken() { - return this.accessToken.getToken(); - } - - public void performGetRequest(String url,OAuthAsyncRequestCallback callback) { - if (accessToken == null) { - throw new IllegalStateException("Access token is null"); - } - OAuthRequest req = new OAuthRequest(Verb.GET, url); - service.signRequest(accessToken, req); - service.execute(req, callback); - } - - public void startOAuth(ViewGroup rootLayout) { - try { - requestToken = service.getRequestToken(); - loadWebView(rootLayout, service.getAuthorizationUrl(requestToken)); - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } - } - - public void authorize(String oauthVerifier) { - try { - accessToken = service.getAccessToken(requestToken, oauthVerifier); - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } - saveToken(); - } - - public boolean isValidToken(){ - return !(accessToken == null); - } - - public void restoreToken() { - String token = application.getSettings().USER_ACCESS_TOKEN.get(); - String tokenSecret = application.getSettings().USER_ACCESS_TOKEN_SECRET.get(); - accessToken = new OAuth1AccessToken(token, tokenSecret); - } - - private void saveToken() { - application.getSettings().USER_ACCESS_TOKEN.set(accessToken.getToken()); - application.getSettings().USER_ACCESS_TOKEN_SECRET.set(accessToken.getTokenSecret()); - } - - private void loadWebView(ViewGroup root, String url) { - WebView webView = new WebView(root.getContext()); - webView.requestFocus(View.FOCUS_DOWN); - webView.loadUrl(url); - root.addView(webView); - } -} From 33f933e89d2bc56a0d9740da88464ae8bbe39542 Mon Sep 17 00:00:00 2001 From: simon Date: Fri, 2 Oct 2020 16:00:03 +0300 Subject: [PATCH 08/95] logout added --- .../oauth/OsmOAuthAuthorizationClient.java | 40 ++++++++++--------- OsmAnd/res/values/strings.xml | 6 +++ .../osmedit/SettingsOsmEditingActivity.java | 31 ++++++++++---- .../oauth/OsmOAuthAuthorizationAdapter.java | 10 ++++- 4 files changed, 61 insertions(+), 26 deletions(-) diff --git a/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java b/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java index bef043e1ce..ed2854bb02 100644 --- a/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java +++ b/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java @@ -20,7 +20,7 @@ public class OsmOAuthAuthorizationClient { OAuth1RequestToken requestToken; OAuth1AccessToken accessToken; - public OsmOAuthAuthorizationClient(String key, String secret){ + public OsmOAuthAuthorizationClient(String key, String secret) { service = new ServiceBuilder(key) .apiSecret(secret) .callback("osmand-oauth://example.com/oauth") @@ -53,9 +53,13 @@ public class OsmOAuthAuthorizationClient { return service; } - public void setAccessToken(OAuth1AccessToken accessToken) { this.accessToken = accessToken; } - - public OAuth1AccessToken getAccessToken() { return this.accessToken; } + public void setAccessToken(OAuth1AccessToken accessToken) { + this.accessToken = accessToken; + } + + public OAuth1AccessToken getAccessToken() { + return this.accessToken; + } public Response performRequestWithoutAuth(String url, String requestMethod, String requestBody) throws InterruptedException, ExecutionException, IOException { @@ -88,20 +92,6 @@ public class OsmOAuthAuthorizationClient { return service.execute(req); } - private Verb parseRequestMethod(String method) { - Verb m = Verb.GET; - if (method.equals("POST")) { - m = Verb.POST; - } - if (method.equals("PUT")) { - m = Verb.PUT; - } - if (method.equals("DELETE")) { - m = Verb.DELETE; - } - return m; - } - public OAuth1RequestToken startOAuth() { try { requestToken = service.getRequestToken(); @@ -131,4 +121,18 @@ public class OsmOAuthAuthorizationClient { public boolean isValidToken() { return !(accessToken == null); } + + private Verb parseRequestMethod(String method) { + Verb m = Verb.GET; + if (method.equals("POST")) { + m = Verb.POST; + } + if (method.equals("PUT")) { + m = Verb.PUT; + } + if (method.equals("DELETE")) { + m = Verb.DELETE; + } + return m; + } } diff --git a/OsmAnd/res/values/strings.xml b/OsmAnd/res/values/strings.xml index 14e08c0176..915e2a0f6d 100644 --- a/OsmAnd/res/values/strings.xml +++ b/OsmAnd/res/values/strings.xml @@ -11,6 +11,12 @@ Thx - Hardy --> + Logout successful + Clear OpenStreetMap OAuth token + Test user request + Retrieve current user info + Log in via OAuth + Perform an OAuth Login to use osmedit features Name: A – Z Name: Z – A Last modified diff --git a/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java b/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java index 651fc7ff07..c4c8cb8d38 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java @@ -81,8 +81,8 @@ public class SettingsOsmEditingActivity extends SettingsBaseActivity { prefOAuth.setKey("local_openstreetmap_token"); final Preference prefTestUser = new Preference(this); - prefTestUser.setTitle("Test user request"); - prefTestUser.setSummary("Test user request"); + prefTestUser.setTitle(R.string.test_user_request); + prefTestUser.setSummary(R.string.test_user_request_description); prefTestUser.setKey("local_openstreetmap_token"); prefTestUser.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override @@ -92,8 +92,7 @@ public class SettingsOsmEditingActivity extends SettingsBaseActivity { @Override public void onCompleted(Response response) { try { - Toast.makeText(SettingsOsmEditingActivity.this, - "DATA RETRIEVED: " + response.getBody().toString(),Toast.LENGTH_SHORT).show(); + Toast.makeText(SettingsOsmEditingActivity.this,response.getBody(),Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } @@ -108,11 +107,27 @@ public class SettingsOsmEditingActivity extends SettingsBaseActivity { return true; } }); - grp.addPreference(prefTestUser); + final Preference prefClearToken = new Preference(this); + prefClearToken.setTitle(R.string.shared_string_logoff); + prefClearToken.setSummary(R.string.clear_osm_token); + prefClearToken.setKey("local_openstreetmap_token"); + prefClearToken.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + settings.USER_ACCESS_TOKEN.set(""); + settings.USER_ACCESS_TOKEN_SECRET.set(""); + client.resetToken(); + Toast.makeText(SettingsOsmEditingActivity.this, R.string.osm_edit_logout_success, Toast.LENGTH_SHORT).show(); + finish(); + startActivity(getIntent()); + return true; + } + }); + grp.addPreference(prefClearToken); } else { - prefOAuth.setTitle(R.string.osb_author_dialog_password); - prefOAuth.setSummary(R.string.osb_author_dialog_password); + prefOAuth.setTitle(R.string.perform_oauth_authorization); + prefOAuth.setSummary(R.string.perform_oauth_authorization_description); prefOAuth.setKey("local_openstreetmap_token"); prefOAuth.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override @@ -193,6 +208,8 @@ public class SettingsOsmEditingActivity extends SettingsBaseActivity { if (uri != null && uri.toString().startsWith("osmand-oauth")) { String oauthVerifier = uri.getQueryParameter("oauth_verifier"); client.authorize(oauthVerifier); + finish(); + startActivity(getIntent()); } } } \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java b/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java index 5d2313c078..47757317f7 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java @@ -34,10 +34,18 @@ public class OsmOAuthAuthorizationAdapter { return client.isValidToken(); } + public void resetToken() { + client.setAccessToken(null); + } + public void restoreToken() { String token = application.getSettings().USER_ACCESS_TOKEN.get(); String tokenSecret = application.getSettings().USER_ACCESS_TOKEN_SECRET.get(); - client.setAccessToken(new OAuth1AccessToken(token, tokenSecret)); + if (!(token.isEmpty() || tokenSecret.isEmpty())) { + client.setAccessToken(new OAuth1AccessToken(token, tokenSecret)); + } else { + client.setAccessToken(null); + } } public void startOAuth(ViewGroup rootLayout) { From dba64d631747bf90a125d8f8540f17f88abceb66 Mon Sep 17 00:00:00 2001 From: simon Date: Fri, 2 Oct 2020 16:49:03 +0300 Subject: [PATCH 09/95] bug fix --- .../src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java b/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java index e550d25d73..74eb48c1b4 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java @@ -115,7 +115,8 @@ public class OpenstreetmapRemoteUtil implements OpenstreetmapUtil { } else { OsmOAuthAuthorizationAdapter client = new OsmOAuthAuthorizationAdapter(ctx); - client.performRequestWithoutAuth(url,requestMethod,requestBody); + Response response = client.performRequestWithoutAuth(url,requestMethod,requestBody); + return response.getBody(); } } catch (NullPointerException e) { // that's tricky case why NPE is thrown to fix that problem httpClient could be used From 0948476bf8bcb8f945c1834390f18217807d7ac1 Mon Sep 17 00:00:00 2001 From: simon Date: Mon, 5 Oct 2020 09:54:25 +0300 Subject: [PATCH 10/95] style issues fixed --- .../java/net/osmand/osm/io/NetworkUtils.java | 6 ++--- .../oauth/OsmOAuthAuthorizationClient.java | 23 +++++++++++-------- .../plus/download/DownloadIndexesThread.java | 3 +-- .../plus/osmedit/OpenstreetmapRemoteUtil.java | 2 +- .../plus/osmedit/OsmBugsRemoteUtil.java | 2 +- .../osmedit/SettingsOsmEditingActivity.java | 17 ++++++++------ .../UploadOpenstreetmapPointAsyncTask.java | 2 +- .../oauth/OsmOAuthAuthorizationAdapter.java | 6 ++--- 8 files changed, 33 insertions(+), 28 deletions(-) diff --git a/OsmAnd-java/src/main/java/net/osmand/osm/io/NetworkUtils.java b/OsmAnd-java/src/main/java/net/osmand/osm/io/NetworkUtils.java index bdf5b6a70e..8880184f96 100644 --- a/OsmAnd-java/src/main/java/net/osmand/osm/io/NetworkUtils.java +++ b/OsmAnd-java/src/main/java/net/osmand/osm/io/NetworkUtils.java @@ -82,9 +82,9 @@ public class NetworkUtils { } return null; } catch (InterruptedException e) { - e.printStackTrace(); + log.error(e); } catch (ExecutionException e) { - e.printStackTrace(); + log.error(e); } return null; } @@ -166,7 +166,7 @@ public class NetworkUtils { Algorithms.closeStream(ous); return ous.toByteArray(); } catch (IOException e) { - e.printStackTrace(); + log.error(e); } return new byte[0]; } diff --git a/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java b/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java index ed2854bb02..5726855f72 100644 --- a/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java +++ b/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java @@ -6,6 +6,8 @@ import com.github.scribejava.core.builder.api.DefaultApi10a; import com.github.scribejava.core.builder.api.OAuth1SignatureType; import com.github.scribejava.core.model.*; import com.github.scribejava.core.oauth.OAuth10aService; +import net.osmand.PlatformUtil; +import org.apache.commons.logging.Log; import java.io.IOException; import java.util.concurrent.ExecutionException; @@ -16,9 +18,10 @@ import java.util.concurrent.ExecutionException; * @since 2746 */ public class OsmOAuthAuthorizationClient { - OAuth10aService service; - OAuth1RequestToken requestToken; - OAuth1AccessToken accessToken; + private OAuth1RequestToken requestToken; + private OAuth1AccessToken accessToken; + private final OAuth10aService service; + public final static Log log = PlatformUtil.getLog(OsmOAuthAuthorizationClient.class); public OsmOAuthAuthorizationClient(String key, String secret) { service = new ServiceBuilder(key) @@ -58,7 +61,7 @@ public class OsmOAuthAuthorizationClient { } public OAuth1AccessToken getAccessToken() { - return this.accessToken; + return accessToken; } public Response performRequestWithoutAuth(String url, String requestMethod, String requestBody) @@ -96,11 +99,11 @@ public class OsmOAuthAuthorizationClient { try { requestToken = service.getRequestToken(); } catch (IOException e) { - e.printStackTrace(); + log.error(e); } catch (InterruptedException e) { - e.printStackTrace(); + log.error(e); } catch (ExecutionException e) { - e.printStackTrace(); + log.error(e); } return requestToken; } @@ -109,11 +112,11 @@ public class OsmOAuthAuthorizationClient { try { setAccessToken(service.getAccessToken(requestToken, oauthVerifier)); } catch (IOException e) { - e.printStackTrace(); + log.error(e); } catch (InterruptedException e) { - e.printStackTrace(); + log.error(e); } catch (ExecutionException e) { - e.printStackTrace(); + log.error(e); } return accessToken; } diff --git a/OsmAnd/src/net/osmand/plus/download/DownloadIndexesThread.java b/OsmAnd/src/net/osmand/plus/download/DownloadIndexesThread.java index 8f826e76b1..450d7e4b0d 100644 --- a/OsmAnd/src/net/osmand/plus/download/DownloadIndexesThread.java +++ b/OsmAnd/src/net/osmand/plus/download/DownloadIndexesThread.java @@ -59,8 +59,8 @@ public class DownloadIndexesThread { private ConcurrentLinkedQueue indexItemDownloading = new ConcurrentLinkedQueue(); private IndexItem currentDownloadingItem = null; private int currentDownloadingItemProgress = 0; - private DownloadResources indexes; + private static final int THREAD_ID = 10103; public interface DownloadEvents { @@ -337,7 +337,6 @@ public class DownloadIndexesThread { @Override protected DownloadResources doInBackground(Void... params) { - final int THREAD_ID = 10103; TrafficStats.setThreadStatsTag(THREAD_ID); DownloadResources result = null; DownloadOsmandIndexesHelper.IndexFileList indexFileList = DownloadOsmandIndexesHelper.getIndexesList(ctx); diff --git a/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java b/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java index 74eb48c1b4..e978c3841b 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java @@ -180,7 +180,7 @@ public class OpenstreetmapRemoteUtil implements OpenstreetmapUtil { id = Long.parseLong(response); } } catch (Exception e) { - e.printStackTrace(); + log.error(e); } return id; } diff --git a/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java b/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java index 75b226eb3f..724f798bf7 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java @@ -109,7 +109,7 @@ public class OsmBugsRemoteUtil implements OsmBugsUtil { private OsmBugResult editingPOI(String url, String requestMethod, String userOperation, boolean anonymous) { - OsmOAuthAuthorizationAdapter client = new OsmOAuthAuthorizationAdapter(this.app); + OsmOAuthAuthorizationAdapter client = new OsmOAuthAuthorizationAdapter(app); OsmBugResult r = new OsmBugResult(); try { HttpURLConnection connection = NetworkUtils.getHttpURLConnection(url); diff --git a/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java b/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java index c4c8cb8d38..6be8066553 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java @@ -19,17 +19,20 @@ import android.widget.TextView; import android.widget.Toast; import com.github.scribejava.core.model.OAuthAsyncRequestCallback; import com.github.scribejava.core.model.Response; +import net.osmand.PlatformUtil; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.R; import net.osmand.plus.activities.SettingsBaseActivity; import net.osmand.plus.osmedit.oauth.OsmOAuthAuthorizationAdapter; import net.osmand.plus.settings.backend.OsmAndAppCustomization; +import org.apache.commons.logging.Log; import java.io.IOException; public class SettingsOsmEditingActivity extends SettingsBaseActivity { - OsmOAuthAuthorizationAdapter client; + private OsmOAuthAuthorizationAdapter client; + private static final Log log = PlatformUtil.getLog(SettingsOsmEditingActivity.class); @Override public void onCreate(Bundle savedInstanceState) { @@ -43,7 +46,7 @@ public class SettingsOsmEditingActivity extends SettingsBaseActivity { ((OsmandApplication) getApplication()).applyTheme(this); super.onCreate(savedInstanceState); - client = new OsmOAuthAuthorizationAdapter(this.getMyApplication()); + client = new OsmOAuthAuthorizationAdapter(getMyApplication()); getToolbar().setTitle(R.string.osm_settings); @SuppressWarnings("deprecation") @@ -78,12 +81,12 @@ public class SettingsOsmEditingActivity extends SettingsBaseActivity { if (client.isValidToken()){ prefOAuth.setTitle(R.string.osm_authorization_success); prefOAuth.setSummary(R.string.osm_authorization_success); - prefOAuth.setKey("local_openstreetmap_token"); + prefOAuth.setKey("local_openstreetmap_oauth_success"); final Preference prefTestUser = new Preference(this); prefTestUser.setTitle(R.string.test_user_request); prefTestUser.setSummary(R.string.test_user_request_description); - prefTestUser.setKey("local_openstreetmap_token"); + prefTestUser.setKey("local_openstreetmap_oauth_user"); prefTestUser.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { @@ -94,7 +97,7 @@ public class SettingsOsmEditingActivity extends SettingsBaseActivity { try { Toast.makeText(SettingsOsmEditingActivity.this,response.getBody(),Toast.LENGTH_SHORT).show(); } catch (IOException e) { - e.printStackTrace(); + log.error(e); } } @@ -110,7 +113,7 @@ public class SettingsOsmEditingActivity extends SettingsBaseActivity { final Preference prefClearToken = new Preference(this); prefClearToken.setTitle(R.string.shared_string_logoff); prefClearToken.setSummary(R.string.clear_osm_token); - prefClearToken.setKey("local_openstreetmap_token"); + prefClearToken.setKey("local_openstreetmap_oauth_clear"); prefClearToken.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { @@ -128,7 +131,7 @@ public class SettingsOsmEditingActivity extends SettingsBaseActivity { else { prefOAuth.setTitle(R.string.perform_oauth_authorization); prefOAuth.setSummary(R.string.perform_oauth_authorization_description); - prefOAuth.setKey("local_openstreetmap_token"); + prefOAuth.setKey("local_openstreetmap_oauth_login"); prefOAuth.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { diff --git a/OsmAnd/src/net/osmand/plus/osmedit/UploadOpenstreetmapPointAsyncTask.java b/OsmAnd/src/net/osmand/plus/osmedit/UploadOpenstreetmapPointAsyncTask.java index 3824d060c7..285c359656 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/UploadOpenstreetmapPointAsyncTask.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/UploadOpenstreetmapPointAsyncTask.java @@ -25,6 +25,7 @@ public class UploadOpenstreetmapPointAsyncTask private OsmEditingPlugin plugin; private final boolean closeChangeSet; private final boolean loadAnonymous; + private static final int THREAD_ID = 10102; public UploadOpenstreetmapPointAsyncTask(ProgressDialogFragment progress, OsmEditsUploadListener listener, @@ -44,7 +45,6 @@ public class UploadOpenstreetmapPointAsyncTask @Override protected Map doInBackground(OsmPoint... points) { - final int THREAD_ID = 10102; TrafficStats.setThreadStatsTag(THREAD_ID); Map loadErrorsMap = new HashMap<>(); diff --git a/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java b/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java index 47757317f7..09a3dba0c4 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java @@ -16,11 +16,11 @@ import java.io.IOException; import java.util.concurrent.ExecutionException; public class OsmOAuthAuthorizationAdapter { - OsmandApplication application; - OsmOAuthAuthorizationClient client = new OsmOAuthAuthorizationClient(BuildConfig.CONSUMER_KEY, BuildConfig.CONSUMER_SECRET); + private OsmandApplication application; + private OsmOAuthAuthorizationClient client = new OsmOAuthAuthorizationClient(BuildConfig.CONSUMER_KEY, BuildConfig.CONSUMER_SECRET); + private static final int THREAD_ID = 10101; public OsmOAuthAuthorizationAdapter(OsmandApplication application) { - final int THREAD_ID = 10101; TrafficStats.setThreadStatsTag(THREAD_ID); this.application = application; restoreToken(); From 6f5019f03f835827f0e491bcbd1fc4bf2ae016c8 Mon Sep 17 00:00:00 2001 From: simon Date: Tue, 6 Oct 2020 09:59:03 +0300 Subject: [PATCH 11/95] style issues and cleanup --- OsmAnd/build.gradle | 8 +++--- OsmAnd/res/values/strings.xml | 2 -- .../plus/osmedit/OpenstreetmapRemoteUtil.java | 16 +++++------ .../plus/osmedit/OsmBugsRemoteUtil.java | 5 ++-- .../osmedit/SettingsOsmEditingActivity.java | 28 ------------------- .../oauth/OsmOAuthAuthorizationAdapter.java | 3 +- 6 files changed, 16 insertions(+), 46 deletions(-) diff --git a/OsmAnd/build.gradle b/OsmAnd/build.gradle index e18cb21e76..ddac6aee41 100644 --- a/OsmAnd/build.gradle +++ b/OsmAnd/build.gradle @@ -216,13 +216,13 @@ android { buildTypes { debug { - buildConfigField "String", "CONSUMER_KEY", "\"Ti2qq3fo4i4Wmuox3SiWRIGq3obZisBHnxmcM05y\"" - buildConfigField "String", "CONSUMER_SECRET", "\"lxulb3HYoMmd2cC4xxNe1dyfRMAY8dS0eNihJ0DM\"" + buildConfigField "String", "OSM_OAUTH_CONSUMER_KEY", "\"Ti2qq3fo4i4Wmuox3SiWRIGq3obZisBHnxmcM05y\"" + buildConfigField "String", "OSM_OAUTH_CONSUMER_SECRET", "\"lxulb3HYoMmd2cC4xxNe1dyfRMAY8dS0eNihJ0DM\"" signingConfig signingConfigs.development } release { - buildConfigField "String", "CONSUMER_KEY", "\"Ti2qq3fo4i4Wmuox3SiWRIGq3obZisBHnxmcM05y\"" - buildConfigField "String", "CONSUMER_SECRET", "\"lxulb3HYoMmd2cC4xxNe1dyfRMAY8dS0eNihJ0DM\"" + buildConfigField "String", "OSM_OAUTH_CONSUMER_KEY", "\"Ti2qq3fo4i4Wmuox3SiWRIGq3obZisBHnxmcM05y\"" + buildConfigField "String", "OSM_OAUTH_CONSUMER_SECRET", "\"lxulb3HYoMmd2cC4xxNe1dyfRMAY8dS0eNihJ0DM\"" signingConfig signingConfigs.publishing } } diff --git a/OsmAnd/res/values/strings.xml b/OsmAnd/res/values/strings.xml index 915e2a0f6d..a8b3d34fbe 100644 --- a/OsmAnd/res/values/strings.xml +++ b/OsmAnd/res/values/strings.xml @@ -13,8 +13,6 @@ --> Logout successful Clear OpenStreetMap OAuth token - Test user request - Retrieve current user info Log in via OAuth Perform an OAuth Login to use osmedit features Name: A – Z diff --git a/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java b/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java index e978c3841b..393dd7d965 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/OpenstreetmapRemoteUtil.java @@ -174,14 +174,14 @@ public class OpenstreetmapRemoteUtil implements OpenstreetmapUtil { } String response = sendRequest( getSiteApi() + "api/0.6/changeset/create/", "PUT", writer.getBuffer().toString(), ctx.getString(R.string.opening_changeset), true); //$NON-NLS-1$ //$NON-NLS-2$ - try { - if (response != null && response.length() > 0) { - log.debug(response); - id = Long.parseLong(response); - } - } catch (Exception e) { - log.error(e); - } + try { + if (response != null && response.length() > 0) { + log.debug(response); + id = Long.parseLong(response); + } + } catch (Exception e) { + log.error(e); + } return id; } diff --git a/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java b/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java index 724f798bf7..a6e2dd5ca8 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/OsmBugsRemoteUtil.java @@ -119,10 +119,9 @@ public class OsmBugsRemoteUtil implements OsmBugsUtil { connection.setRequestProperty("User-Agent", Version.getFullVersion(app)); //$NON-NLS-1$ if (!anonymous) { - if (client.isValidToken()){ + if (client.isValidToken()) { connection.addRequestProperty("Authorization", "OAuth " + client.getClient().getAccessToken().getToken()); - } - else { + } else { String token = settings.USER_NAME.get() + ":" + settings.USER_PASSWORD.get(); //$NON-NLS-1$ connection.addRequestProperty("Authorization", "Basic " + Base64.encode(token.getBytes("UTF-8"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } diff --git a/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java b/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java index 6be8066553..4f1410dc4c 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/SettingsOsmEditingActivity.java @@ -82,34 +82,6 @@ public class SettingsOsmEditingActivity extends SettingsBaseActivity { prefOAuth.setTitle(R.string.osm_authorization_success); prefOAuth.setSummary(R.string.osm_authorization_success); prefOAuth.setKey("local_openstreetmap_oauth_success"); - - final Preference prefTestUser = new Preference(this); - prefTestUser.setTitle(R.string.test_user_request); - prefTestUser.setSummary(R.string.test_user_request_description); - prefTestUser.setKey("local_openstreetmap_oauth_user"); - prefTestUser.setOnPreferenceClickListener(new OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - String url = "https://api.openstreetmap.org/api/0.6/user/details"; - client.performGetRequest(url, new OAuthAsyncRequestCallback() { - @Override - public void onCompleted(Response response) { - try { - Toast.makeText(SettingsOsmEditingActivity.this,response.getBody(),Toast.LENGTH_SHORT).show(); - } catch (IOException e) { - log.error(e); - } - } - - @Override - public void onThrowable(Throwable t) { - Toast.makeText(SettingsOsmEditingActivity.this, - "ERROR happened",Toast.LENGTH_SHORT).show(); - } - }); - return true; - } - }); final Preference prefClearToken = new Preference(this); prefClearToken.setTitle(R.string.shared_string_logoff); prefClearToken.setSummary(R.string.clear_osm_token); diff --git a/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java b/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java index 09a3dba0c4..8d687f9604 100644 --- a/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java +++ b/OsmAnd/src/net/osmand/plus/osmedit/oauth/OsmOAuthAuthorizationAdapter.java @@ -17,7 +17,8 @@ import java.util.concurrent.ExecutionException; public class OsmOAuthAuthorizationAdapter { private OsmandApplication application; - private OsmOAuthAuthorizationClient client = new OsmOAuthAuthorizationClient(BuildConfig.CONSUMER_KEY, BuildConfig.CONSUMER_SECRET); + private OsmOAuthAuthorizationClient client = + new OsmOAuthAuthorizationClient(BuildConfig.OSM_OAUTH_CONSUMER_KEY, BuildConfig.OSM_OAUTH_CONSUMER_SECRET); private static final int THREAD_ID = 10101; public OsmOAuthAuthorizationAdapter(OsmandApplication application) { From a5776ae07a527c64ffc8936a42e8f31d65c0b1e4 Mon Sep 17 00:00:00 2001 From: simon Date: Tue, 6 Oct 2020 10:30:10 +0300 Subject: [PATCH 12/95] cleanup --- OsmAnd-java/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OsmAnd-java/build.gradle b/OsmAnd-java/build.gradle index 0d0a3c265d..2c5415a84f 100644 --- a/OsmAnd-java/build.gradle +++ b/OsmAnd-java/build.gradle @@ -104,7 +104,7 @@ dependencies { implementation 'com.moparisthebest:junidecode:0.1.1' implementation 'com.vividsolutions:jts-core:1.14.0' implementation 'com.google.openlocationcode:openlocationcode:1.0.4' - implementation('com.github.scribejava:scribejava-apis:7.1.1'){ + implementation ('com.github.scribejava:scribejava-apis:7.1.1') { exclude group: "com.fasterxml.jackson.core" } // turn off for now From ba5b407cea5efff921390779ec525e9cbd76819c Mon Sep 17 00:00:00 2001 From: sergosm Date: Tue, 6 Oct 2020 16:51:45 +0300 Subject: [PATCH 13/95] Move development settings Preview --- OsmAnd/res/values/strings.xml | 10 ++- OsmAnd/res/xml/development_settings.xml | 35 --------- .../DevelopmentSettingsFragment.java | 54 +++---------- .../SettingsDevelopmentActivity.java | 37 +++------ .../plus/settings/backend/OsmandSettings.java | 10 +-- .../fragments/RouteParametersFragment.java | 76 ++++++++++++++++++- 6 files changed, 111 insertions(+), 111 deletions(-) diff --git a/OsmAnd/res/values/strings.xml b/OsmAnd/res/values/strings.xml index 086a7470d5..b01a0ef58c 100644 --- a/OsmAnd/res/values/strings.xml +++ b/OsmAnd/res/values/strings.xml @@ -11,6 +11,14 @@ Thx - Hardy --> + Switch to Java (safe) Public Transport routing calculation + Native Public Transport development + Recalculates only the initial part of the route. Can be used for long trips. + Two-phase routing for car navigation. + Complex routing + OsmAnd Live data + OsmAnd Live data + Development Start/finish icons Name: A – Z Name: Z – A @@ -2463,7 +2471,6 @@ Specify the speech rate for text-to-speech. Speech Rate Fast route calculation failed (%s), fallback to slow calculation. - Disable two-phase routing for car navigation. Disable complex routing Seamark Select shown profiles. @@ -3657,7 +3664,6 @@ You need to be online to install this plugin. Get Smart route recalculation - For long trips, only recalculate the initial part of the route. Do you like OsmAnd? Your opinion and feedback is valued. Rate this app diff --git a/OsmAnd/res/xml/development_settings.xml b/OsmAnd/res/xml/development_settings.xml index d01a1f169d..231bd469bc 100644 --- a/OsmAnd/res/xml/development_settings.xml +++ b/OsmAnd/res/xml/development_settings.xml @@ -25,46 +25,11 @@ android:summaryOn="@string/shared_string_enabled" android:title="@string/safe_mode" /> - - - - - - - - - - MAPILLARY_FILTER_TO_DATE = new LongPreference("mapillary_filter_to_date", 0).makeGlobal(); public final CommonPreference MAPILLARY_FILTER_PANO = new BooleanPreference("mapillary_filter_pano", false).makeGlobal(); - public final CommonPreference USE_FAST_RECALCULATION = new BooleanPreference("use_fast_recalculation", true).makeGlobal().cache(); + public final CommonPreference USE_FAST_RECALCULATION = new BooleanPreference("use_fast_recalculation", true).makeProfile().cache(); public final CommonPreference FORCE_PRIVATE_ACCESS_ROUTING_ASKED = new BooleanPreference("force_private_access_routing", false).makeProfile().cache(); public final CommonPreference SHOW_CARD_TO_CHOOSE_DRAWER = new BooleanPreference("show_card_to_choose_drawer", false).makeGlobal(); @@ -2117,7 +2117,7 @@ public class OsmandSettings { // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference FAST_ROUTE_MODE = new BooleanPreference("fast_route_mode", true).makeProfile(); // dev version - public final CommonPreference DISABLE_COMPLEX_ROUTING = new BooleanPreference("disable_complex_routing", false).makeGlobal(); + public final CommonPreference DISABLE_COMPLEX_ROUTING = new BooleanPreference("disable_complex_routing", false).makeProfile(); public final CommonPreference ENABLE_TIME_CONDITIONAL_ROUTING = new BooleanPreference("enable_time_conditional_routing", true).makeProfile(); public boolean simulateNavigation = false; @@ -3852,9 +3852,9 @@ public class OsmandSettings { public final CommonPreference ROUTE_RECALCULATION_DISTANCE = new FloatPreference("routing_recalc_distance", 0.f).makeProfile(); public final CommonPreference ROUTE_STRAIGHT_ANGLE = new FloatPreference("routing_straight_angle", 30.f).makeProfile(); - public final OsmandPreference USE_OSM_LIVE_FOR_ROUTING = new BooleanPreference("enable_osmc_routing", true).makeGlobal(); + public final OsmandPreference USE_OSM_LIVE_FOR_ROUTING = new BooleanPreference("enable_osmc_routing", true).makeProfile(); - public final OsmandPreference USE_OSM_LIVE_FOR_PUBLIC_TRANSPORT = new BooleanPreference("enable_osmc_public_transport", false).makeGlobal(); + public final OsmandPreference USE_OSM_LIVE_FOR_PUBLIC_TRANSPORT = new BooleanPreference("enable_osmc_public_transport", false).makeProfile(); public final OsmandPreference VOICE_MUTE = new BooleanPreference("voice_mute", false).makeProfile().cache(); @@ -3863,7 +3863,7 @@ public class OsmandSettings { // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference SAFE_MODE = new BooleanPreference("safe_mode", false).makeGlobal(); - public final OsmandPreference PT_SAFE_MODE = new BooleanPreference("pt_safe_mode", false).makeGlobal(); + public final OsmandPreference PT_SAFE_MODE = new BooleanPreference("pt_safe_mode", false).makeProfile(); public final OsmandPreference NATIVE_RENDERING_FAILED = new BooleanPreference("native_rendering_failed_init", false).makeGlobal(); public final OsmandPreference USE_OPENGL_RENDER = new BooleanPreference("use_opengl_render", diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java index 198e6e13eb..70dc81c23e 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java @@ -6,6 +6,7 @@ import android.content.DialogInterface; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; +import android.preference.CheckBoxPreference; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -25,6 +26,7 @@ import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.slider.Slider; import net.osmand.StateChangedListener; +import net.osmand.plus.Version; import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; @@ -155,6 +157,60 @@ public class RouteParametersFragment extends BaseSettingsFragment implements OnP getPreferenceScreen().addPreference(timeConditionalRouting); } + private void setupOsmLiveForPublicTransportPref() { + SwitchPreferenceEx useOsmLiveForPublicTransport = createSwitchPreferenceEx(settings.USE_OSM_LIVE_FOR_PUBLIC_TRANSPORT.getId(), + R.string.use_live_public_transport, R.layout.preference_with_descr_dialog_and_switch); + useOsmLiveForPublicTransport.setDescription(getString(R.string.use_osm_live_public_transport_description)); + useOsmLiveForPublicTransport.setSummaryOn(R.string.shared_string_enabled); + useOsmLiveForPublicTransport.setSummaryOff(R.string.shared_string_disabled); + useOsmLiveForPublicTransport.setIconSpaceReserved(true); + getPreferenceScreen().addPreference(useOsmLiveForPublicTransport); + } + + private void setupNativePublicTransport() { + SwitchPreferenceEx setupNativePublicTransport = createSwitchPreferenceEx(settings.PT_SAFE_MODE.getId(), + R.string.use_native_pt, R.layout.preference_with_descr_dialog_and_switch); + if (!Version.isBlackberry(app)) { + setupNativePublicTransport.setDescription(getString(R.string.use_native_pt_desc)); + setupNativePublicTransport.setSummaryOn(R.string.shared_string_enabled); + setupNativePublicTransport.setSummaryOff(R.string.shared_string_disabled); + setupNativePublicTransport.setIconSpaceReserved(true); + getPreferenceScreen().addPreference(setupNativePublicTransport); + } else { + setupNativePublicTransport.setVisible(false); + } + } + + private void setupOsmLiveForRoutingPref() { + SwitchPreferenceEx useOsmLiveForRouting = createSwitchPreferenceEx(settings.USE_OSM_LIVE_FOR_ROUTING.getId(), + R.string.use_live_routing, R.layout.preference_with_descr_dialog_and_switch); + useOsmLiveForRouting.setDescription(getString(R.string.use_osm_live_routing_description)); + useOsmLiveForRouting.setSummaryOn(R.string.shared_string_enabled); + useOsmLiveForRouting.setSummaryOff(R.string.shared_string_disabled); + useOsmLiveForRouting.setIconSpaceReserved(true); + getPreferenceScreen().addPreference(useOsmLiveForRouting); + } + + private void setupDisableComplexRoutingPref() { + SwitchPreferenceEx disableComplexRouting = createSwitchPreferenceEx(settings.DISABLE_COMPLEX_ROUTING.getId(), + R.string.use_complex_routing, R.layout.preference_with_descr_dialog_and_switch); + disableComplexRouting.setDescription(getString(R.string.disable_complex_routing_descr)); + disableComplexRouting.setSummaryOn(R.string.shared_string_enabled); + disableComplexRouting.setSummaryOff(R.string.shared_string_disabled); + disableComplexRouting.setIconSpaceReserved(true); + getPreferenceScreen().addPreference(disableComplexRouting); + } + + private void setupFastRecalculationPref() { + SwitchPreferenceEx useFastRecalculation = createSwitchPreferenceEx(settings.USE_FAST_RECALCULATION.getId(), + R.string.use_fast_recalculation, R.layout.preference_with_descr_dialog_and_switch); + useFastRecalculation.setDescription(getString(R.string.use_fast_recalculation_desc)); + useFastRecalculation.setSummaryOn(R.string.shared_string_enabled); + useFastRecalculation.setSummaryOff(R.string.shared_string_disabled); + useFastRecalculation.setIconSpaceReserved(true); + getPreferenceScreen().addPreference(useFastRecalculation); + } + private void setupRoutingPrefs() { OsmandApplication app = getMyApplication(); if (app == null) { @@ -170,7 +226,7 @@ public class RouteParametersFragment extends BaseSettingsFragment implements OnP fastRoute.setSummaryOn(R.string.shared_string_on); fastRoute.setSummaryOff(R.string.shared_string_off); - if (am.getRouteService() == RouteProvider.RouteService.OSMAND){ + if (am.getRouteService() == RouteProvider.RouteService.OSMAND) { GeneralRouter router = app.getRouter(am); clearParameters(); if (router != null) { @@ -273,6 +329,17 @@ public class RouteParametersFragment extends BaseSettingsFragment implements OnP setupRouteRecalcHeader(screen); setupSelectRouteRecalcDistance(screen); setupReverseDirectionRecalculation(screen); + addDivider(screen); + setupDevelopmentcategoryHeader(screen); + if (am.isDerivedRoutingFrom(ApplicationMode.PUBLIC_TRANSPORT)) { + setupOsmLiveForPublicTransportPref(); + setupNativePublicTransport(); + } + if (am.isDerivedRoutingFrom(ApplicationMode.CAR)) { + setupOsmLiveForRoutingPref(); + setupDisableComplexRoutingPref(); + } + setupFastRecalculationPref(); } private void addDivider(PreferenceScreen screen) { @@ -300,6 +367,13 @@ public class RouteParametersFragment extends BaseSettingsFragment implements OnP screen.addPreference(routingCategory); } + private void setupDevelopmentcategoryHeader (PreferenceScreen screen) { + PreferenceCategory developmentCategory = new PreferenceCategory(requireContext()); + developmentCategory.setLayoutResource(R.layout.preference_category_with_descr); + developmentCategory.setTitle(R.string.development); + screen.addPreference(developmentCategory); + } + @Override public boolean onPreferenceClick(Preference preference) { if (preference.getKey().equals(settings.ROUTE_STRAIGHT_ANGLE.getId())) { From 4774382258c4d89dce9dd36f02a940b43ab5e95d Mon Sep 17 00:00:00 2001 From: Vitaliy Date: Tue, 6 Oct 2020 19:48:33 +0300 Subject: [PATCH 14/95] Move import async tasks and ImportHelper to separate package --- .../osmand/plus/activities/MapActivity.java | 2 +- .../ImportGpxBottomSheetDialogFragment.java | 2 +- .../plus/importfiles/BaseImportAsyncTask.java | 45 ++ .../plus/importfiles/FavoritesImportTask.java | 59 ++ .../plus/importfiles/GpxImportTask.java | 59 ++ .../GpxOrFavouritesImportTask.java | 83 +++ .../ImportHelper.java | 625 ++---------------- .../plus/importfiles/KmlImportTask.java | 71 ++ .../plus/importfiles/KmzImportTask.java | 67 ++ .../plus/importfiles/ObfImportTask.java | 52 ++ .../plus/importfiles/SettingsImportTask.java | 158 +++++ .../importfiles/SqliteTileImportTask.java | 50 ++ .../plus/importfiles/XmlImportTask.java | 149 +++++ .../StartPlanRouteBottomSheet.java | 4 +- .../plus/myplaces/FavoritesActivity.java | 4 +- ...electProfileBottomSheetDialogFragment.java | 2 +- .../FollowTrackFragment.java | 4 +- .../backend/OsmAndAppCustomization.java | 2 +- .../fragments/MainSettingsFragment.java | 2 +- 19 files changed, 858 insertions(+), 582 deletions(-) create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/BaseImportAsyncTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/FavoritesImportTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/GpxImportTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/GpxOrFavouritesImportTask.java rename OsmAnd/src/net/osmand/plus/{helpers => importfiles}/ImportHelper.java (50%) create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/KmlImportTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/KmzImportTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/ObfImportTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/SettingsImportTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/SqliteTileImportTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/XmlImportTask.java diff --git a/OsmAnd/src/net/osmand/plus/activities/MapActivity.java b/OsmAnd/src/net/osmand/plus/activities/MapActivity.java index 2816e7d5b0..2e840f8b64 100644 --- a/OsmAnd/src/net/osmand/plus/activities/MapActivity.java +++ b/OsmAnd/src/net/osmand/plus/activities/MapActivity.java @@ -99,7 +99,7 @@ import net.osmand.plus.firstusage.FirstUsageWelcomeFragment; import net.osmand.plus.firstusage.FirstUsageWizardFragment; import net.osmand.plus.helpers.AndroidUiHelper; import net.osmand.plus.helpers.DiscountHelper; -import net.osmand.plus.helpers.ImportHelper; +import net.osmand.plus.importfiles.ImportHelper; import net.osmand.plus.helpers.IntentHelper; import net.osmand.plus.helpers.LockHelper; import net.osmand.plus.helpers.LockHelper.LockUIAdapter; diff --git a/OsmAnd/src/net/osmand/plus/dialogs/ImportGpxBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/dialogs/ImportGpxBottomSheetDialogFragment.java index cf371f006e..4bc4e1589a 100644 --- a/OsmAnd/src/net/osmand/plus/dialogs/ImportGpxBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/dialogs/ImportGpxBottomSheetDialogFragment.java @@ -13,7 +13,7 @@ import net.osmand.plus.base.bottomsheetmenu.SimpleBottomSheetItem; import net.osmand.plus.base.bottomsheetmenu.simpleitems.DividerHalfItem; import net.osmand.plus.base.bottomsheetmenu.simpleitems.ShortDescriptionItem; import net.osmand.plus.base.bottomsheetmenu.simpleitems.TitleItem; -import net.osmand.plus.helpers.ImportHelper; +import net.osmand.plus.importfiles.ImportHelper; public class ImportGpxBottomSheetDialogFragment extends MenuBottomSheetDialogFragment { diff --git a/OsmAnd/src/net/osmand/plus/importfiles/BaseImportAsyncTask.java b/OsmAnd/src/net/osmand/plus/importfiles/BaseImportAsyncTask.java new file mode 100644 index 0000000000..4ebafcb8cc --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/BaseImportAsyncTask.java @@ -0,0 +1,45 @@ +package net.osmand.plus.importfiles; + +import android.app.ProgressDialog; +import android.os.AsyncTask; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.AndroidUtils; +import net.osmand.plus.OsmandApplication; +import net.osmand.plus.R; + +import java.lang.ref.WeakReference; + +abstract class BaseImportAsyncTask extends AsyncTask { + + protected OsmandApplication app; + protected WeakReference activityRef; + protected ProgressDialog progress; + + public BaseImportAsyncTask(@NonNull FragmentActivity activity) { + app = (OsmandApplication) activity.getApplicationContext(); + activityRef = new WeakReference<>(activity); + } + + @Override + protected void onPreExecute() { + showProgress(); + } + + protected void showProgress() { + FragmentActivity activity = activityRef.get(); + if (AndroidUtils.isActivityNotDestroyed(activity)) { + String title = app.getString(R.string.loading_smth, ""); + progress = ProgressDialog.show(activity, title, app.getString(R.string.loading_data)); + } + } + + protected void hideProgress() { + FragmentActivity activity = activityRef.get(); + if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { + progress.dismiss(); + } + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/FavoritesImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/FavoritesImportTask.java new file mode 100644 index 0000000000..2793e1e0ab --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/FavoritesImportTask.java @@ -0,0 +1,59 @@ +package net.osmand.plus.importfiles; + +import android.content.Intent; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.GPXUtilities; +import net.osmand.GPXUtilities.GPXFile; +import net.osmand.data.FavouritePoint; +import net.osmand.plus.FavouritesDbHelper; +import net.osmand.plus.R; + +import java.util.List; + +import static net.osmand.plus.importfiles.ImportHelper.asFavourites; +import static net.osmand.plus.myplaces.FavoritesActivity.FAV_TAB; +import static net.osmand.plus.myplaces.FavoritesActivity.TAB_ID; + +class FavoritesImportTask extends BaseImportAsyncTask { + + private GPXFile gpxFile; + private String fileName; + private boolean forceImportFavourites; + + public FavoritesImportTask(@NonNull FragmentActivity activity, @NonNull GPXFile gpxFile, + @NonNull String fileName, boolean forceImportFavourites) { + super(activity); + this.gpxFile = gpxFile; + this.fileName = fileName; + this.forceImportFavourites = forceImportFavourites; + } + + @Override + protected GPXFile doInBackground(Void... nothing) { + List favourites = asFavourites(app, gpxFile.getPoints(), fileName, forceImportFavourites); + FavouritesDbHelper favoritesHelper = app.getFavorites(); + for (FavouritePoint favourite : favourites) { + favoritesHelper.deleteFavourite(favourite, false); + favoritesHelper.addFavourite(favourite, false); + } + favoritesHelper.sortAll(); + favoritesHelper.saveCurrentPointsIntoFile(); + return null; + } + + @Override + protected void onPostExecute(GPXUtilities.GPXFile result) { + hideProgress(); + FragmentActivity activity = activityRef.get(); + if (activity != null) { + app.showToastMessage(R.string.fav_imported_sucessfully); + Intent newIntent = new Intent(activity, app.getAppCustomization().getFavoritesActivity()); + newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + newIntent.putExtra(TAB_ID, FAV_TAB); + activity.startActivity(newIntent); + } + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/GpxImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/GpxImportTask.java new file mode 100644 index 0000000000..1e76f15a26 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/GpxImportTask.java @@ -0,0 +1,59 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.GPXUtilities; +import net.osmand.GPXUtilities.GPXFile; +import net.osmand.util.Algorithms; + +import java.io.FileNotFoundException; +import java.io.InputStream; + +class GpxImportTask extends BaseImportAsyncTask { + + private ImportHelper importHelper; + private Uri gpxFile; + private String fileName; + private boolean save; + private boolean useImportDir; + private boolean showInDetailsActivity; + + public GpxImportTask(@NonNull ImportHelper importHelper, @NonNull FragmentActivity activity, + @NonNull Uri gpxFile, @NonNull String fileName, boolean save, boolean useImportDir, + boolean showInDetailsActivity) { + super(activity); + this.importHelper = importHelper; + this.gpxFile = gpxFile; + this.fileName = fileName; + this.save = save; + this.useImportDir = useImportDir; + this.showInDetailsActivity = showInDetailsActivity; + } + + @Override + protected GPXFile doInBackground(Void... nothing) { + InputStream is = null; + try { + is = app.getContentResolver().openInputStream(gpxFile); + if (is != null) { + return GPXUtilities.loadGPXFile(is); + } + } catch (FileNotFoundException e) { + // + } catch (SecurityException e) { + ImportHelper.log.error(e.getMessage(), e); + } finally { + Algorithms.closeStream(is); + } + return null; + } + + @Override + protected void onPostExecute(GPXUtilities.GPXFile result) { + hideProgress(); + importHelper.handleResult(result, fileName, save, useImportDir, false, showInDetailsActivity); + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/GpxOrFavouritesImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/GpxOrFavouritesImportTask.java new file mode 100644 index 0000000000..48eadfb5b1 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/GpxOrFavouritesImportTask.java @@ -0,0 +1,83 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.GPXUtilities; +import net.osmand.GPXUtilities.GPXFile; +import net.osmand.util.Algorithms; + +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import static net.osmand.plus.importfiles.KmlImportTask.loadGpxFromKml; + +class GpxOrFavouritesImportTask extends BaseImportAsyncTask { + + private ImportHelper importHelper; + private Uri fileUri; + private String fileName; + private boolean save; + private boolean useImportDir; + private boolean forceImportFavourites; + private boolean forceImportGpx; + + public GpxOrFavouritesImportTask(@NonNull ImportHelper importHelper, @NonNull FragmentActivity activity, + @NonNull Uri fileUri, String fileName, boolean save, boolean useImportDir, + boolean forceImportFavourites, boolean forceImportGpx) { + super(activity); + this.importHelper = importHelper; + this.fileUri = fileUri; + this.fileName = fileName; + this.save = save; + this.useImportDir = useImportDir; + this.forceImportFavourites = forceImportFavourites; + this.forceImportGpx = forceImportGpx; + } + + @Override + protected GPXFile doInBackground(Void... nothing) { + InputStream is = null; + ZipInputStream zis = null; + try { + is = app.getContentResolver().openInputStream(fileUri); + if (is != null) { + if (fileName != null && fileName.endsWith(ImportHelper.KML_SUFFIX)) { + return loadGpxFromKml(is); + } else if (fileName != null && fileName.endsWith(ImportHelper.KMZ_SUFFIX)) { + try { + zis = new ZipInputStream(is); + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + if (entry.getName().endsWith(ImportHelper.KML_SUFFIX)) { + return loadGpxFromKml(zis); + } + } + } catch (Exception e) { + return null; + } + } else { + return GPXUtilities.loadGPXFile(is); + } + } + } catch (FileNotFoundException e) { + // + } catch (SecurityException e) { + ImportHelper.log.error(e.getMessage(), e); + } finally { + Algorithms.closeStream(is); + Algorithms.closeStream(zis); + } + return null; + } + + @Override + protected void onPostExecute(final GPXUtilities.GPXFile result) { + hideProgress(); + importHelper.importGpxOrFavourites(result, fileName, save, useImportDir, forceImportFavourites, forceImportGpx); + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java b/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java similarity index 50% rename from OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java rename to OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java index febffa73bf..f5b47604ac 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java +++ b/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java @@ -1,7 +1,5 @@ -package net.osmand.plus.helpers; +package net.osmand.plus.importfiles; -import android.annotation.SuppressLint; -import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; @@ -17,65 +15,47 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; -import androidx.fragment.app.FragmentManager; -import net.osmand.AndroidUtils; import net.osmand.CallbackWithObject; import net.osmand.GPXUtilities; import net.osmand.GPXUtilities.GPXFile; import net.osmand.GPXUtilities.WptPt; -import net.osmand.IProgress; import net.osmand.IndexConstants; import net.osmand.PlatformUtil; import net.osmand.data.FavouritePoint; import net.osmand.data.FavouritePoint.BackgroundType; import net.osmand.plus.AppInitializer; -import net.osmand.plus.CustomOsmandPlugin; -import net.osmand.plus.FavouritesDbHelper; import net.osmand.plus.GPXDatabase.GpxDataItem; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.OsmandPlugin; import net.osmand.plus.R; import net.osmand.plus.activities.ActivityResultListener; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.TrackActivity; import net.osmand.plus.dialogs.ImportGpxBottomSheetDialogFragment; import net.osmand.plus.measurementtool.MeasurementToolFragment; -import net.osmand.plus.rastermaps.OsmandRasterMapsPlugin; import net.osmand.plus.settings.backend.SettingsHelper; -import net.osmand.plus.settings.backend.SettingsHelper.CheckDuplicatesListener; -import net.osmand.plus.settings.backend.SettingsHelper.PluginSettingsItem; -import net.osmand.plus.settings.backend.SettingsHelper.ProfileSettingsItem; -import net.osmand.plus.settings.backend.SettingsHelper.SettingsCollectListener; -import net.osmand.plus.settings.backend.SettingsHelper.SettingsImportListener; import net.osmand.plus.settings.backend.SettingsHelper.SettingsItem; -import net.osmand.plus.settings.fragments.ImportSettingsFragment; import net.osmand.plus.views.OsmandMapTileView; -import net.osmand.router.RoutingConfiguration; import net.osmand.util.Algorithms; import org.apache.commons.logging.Log; -import org.xmlpull.v1.XmlPullParser; -import org.xmlpull.v1.XmlPullParserException; -import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; import static android.app.Activity.RESULT_OK; +import static net.osmand.IndexConstants.BINARY_MAP_INDEX_EXT; import static net.osmand.IndexConstants.GPX_FILE_EXT; +import static net.osmand.IndexConstants.GPX_INDEX_DIR; import static net.osmand.IndexConstants.OSMAND_SETTINGS_FILE_EXT; import static net.osmand.IndexConstants.RENDERER_INDEX_EXT; import static net.osmand.IndexConstants.ROUTING_FILE_EXT; @@ -83,8 +63,6 @@ import static net.osmand.IndexConstants.SQLITE_CHART_FILE_EXT; import static net.osmand.IndexConstants.SQLITE_EXT; import static net.osmand.IndexConstants.WPT_CHART_FILE_EXT; import static net.osmand.data.FavouritePoint.DEFAULT_BACKGROUND_TYPE; -import static net.osmand.plus.AppInitializer.loadRoutingFiles; -import static net.osmand.plus.myplaces.FavoritesActivity.FAV_TAB; import static net.osmand.plus.myplaces.FavoritesActivity.GPX_TAB; import static net.osmand.plus.myplaces.FavoritesActivity.TAB_ID; @@ -124,6 +102,7 @@ public class ImportHelper { public interface OnGpxImportCompleteListener { void onImportComplete(boolean success); + void onSaveComplete(boolean success, GPXFile result); } @@ -138,7 +117,7 @@ public class ImportHelper { } public void handleContentImport(final Uri contentUri, Bundle extras, final boolean useImportDir) { - final String name = getNameFromContentUri(app, contentUri); + String name = getNameFromContentUri(app, contentUri); handleFileImport(contentUri, name, extras, useImportDir); } @@ -156,7 +135,7 @@ public class ImportHelper { public boolean handleGpxImport(final Uri contentUri, final boolean useImportDir, boolean showInDetailsActivity) { String name = getNameFromContentUri(app, contentUri); - boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(contentUri.getPath())); + boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(GPX_INDEX_DIR), new File(contentUri.getPath())); if (!isOsmandSubdir && name != null) { String nameLC = name.toLowerCase(); if (nameLC.endsWith(GPX_FILE_EXT)) { @@ -180,7 +159,7 @@ public class ImportHelper { String scheme = uri.getScheme(); boolean isFileIntent = "file".equals(scheme); boolean isContentIntent = "content".equals(scheme); - boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(uri.getPath())); + boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(GPX_INDEX_DIR), new File(uri.getPath())); final boolean saveFile = !isFileIntent || !isOsmandSubdir; String fileName = ""; if (isFileIntent) { @@ -193,7 +172,7 @@ public class ImportHelper { public void handleFileImport(Uri intentUri, String fileName, Bundle extras, boolean useImportDir) { boolean isFileIntent = "file".equals(intentUri.getScheme()); - boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(intentUri.getPath())); + boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(GPX_INDEX_DIR), new File(intentUri.getPath())); boolean saveFile = !isFileIntent || !isOsmandSubdir; if (fileName == null) { @@ -202,7 +181,7 @@ public class ImportHelper { handleKmlImport(intentUri, fileName, saveFile, useImportDir); } else if (fileName.endsWith(KMZ_SUFFIX)) { handleKmzImport(intentUri, fileName, saveFile, useImportDir); - } else if (fileName.endsWith(IndexConstants.BINARY_MAP_INDEX_EXT)) { + } else if (fileName.endsWith(BINARY_MAP_INDEX_EXT)) { handleObfImport(intentUri, fileName); } else if (fileName.endsWith(SQLITE_EXT)) { handleSqliteTileImport(intentUri, fileName); @@ -221,9 +200,8 @@ public class ImportHelper { public static String getNameFromContentUri(OsmandApplication app, Uri contentUri) { try { - final String name; - final Cursor returnCursor = app.getContentResolver().query(contentUri, - new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null); + String name; + Cursor returnCursor = app.getContentResolver().query(contentUri, new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null); if (returnCursor != null && returnCursor.moveToFirst()) { int columnIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); if (columnIndex != -1) { @@ -244,251 +222,52 @@ public class ImportHelper { } } - @SuppressLint("StaticFieldLeak") - private void handleGpxImport(final Uri gpxFile, final String fileName, final boolean save, final boolean useImportDir, - final boolean showInDetailsActivity) { - AsyncTask gpxImportTask = new BaseImportAsyncTask() { - - @Override - protected GPXFile doInBackground(Void... nothing) { - InputStream is = null; - try { - is = app.getContentResolver().openInputStream(gpxFile); - if (is != null) { - return GPXUtilities.loadGPXFile(is); - } - } catch (FileNotFoundException e) { - // - } catch (SecurityException e) { - log.error(e.getMessage(), e); - } finally { - Algorithms.closeStream(is); - } - return null; - } - - @Override - protected void onPostExecute(GPXFile result) { - hideProgress(); - handleResult(result, fileName, save, useImportDir, false, showInDetailsActivity); - } - }; - executeImportTask(gpxImportTask); + private void handleGpxImport(Uri gpxFile, String fileName, boolean save, boolean useImportDir, boolean showInDetailsActivity) { + executeImportTask(new GpxImportTask(this, activity, gpxFile, fileName, save, useImportDir, showInDetailsActivity)); } - @SuppressLint("StaticFieldLeak") - private void handleGpxOrFavouritesImport(final Uri fileUri, final String fileName, final boolean save, - final boolean useImportDir, final boolean forceImportFavourites, - final boolean forceImportGpx) { - AsyncTask gpxOrFavouritesImportTask = new BaseImportAsyncTask() { - - @Override - protected GPXFile doInBackground(Void... nothing) { - InputStream is = null; - ZipInputStream zis = null; - try { - is = app.getContentResolver().openInputStream(fileUri); - if (is != null) { - if (fileName != null && fileName.endsWith(KML_SUFFIX)) { - final String result = Kml2Gpx.toGpx(is); - if (result != null) { - try { - return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - return null; - } - } - } else if (fileName != null && fileName.endsWith(KMZ_SUFFIX)) { - try { - zis = new ZipInputStream(is); - ZipEntry entry; - while ((entry = zis.getNextEntry()) != null) { - if (entry.getName().endsWith(KML_SUFFIX)) { - final String result = Kml2Gpx.toGpx(zis); - if (result != null) { - try { - return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - return null; - } - } - } - } - } catch (Exception e) { - return null; - } - } else { - return GPXUtilities.loadGPXFile(is); - } - } - } catch (FileNotFoundException e) { - // - } catch (SecurityException e) { - log.error(e.getMessage(), e); - } finally { - Algorithms.closeStream(is); - Algorithms.closeStream(zis); - } - return null; - } - - @Override - protected void onPostExecute(final GPXFile result) { - hideProgress(); - importGpxOrFavourites(result, fileName, save, useImportDir, forceImportFavourites, forceImportGpx); - } - }; - executeImportTask(gpxOrFavouritesImportTask); + private void handleGpxOrFavouritesImport(Uri fileUri, String fileName, boolean save, boolean useImportDir, + boolean forceImportFavourites, boolean forceImportGpx) { + executeImportTask(new GpxOrFavouritesImportTask(this, activity, fileUri, fileName, save, useImportDir, forceImportFavourites, forceImportGpx)); } - @SuppressLint("StaticFieldLeak") - private void importFavoritesImpl(final GPXFile gpxFile, final String fileName, final boolean forceImportFavourites) { - AsyncTask favoritesImportTask = new BaseImportAsyncTask() { - - @Override - protected GPXFile doInBackground(Void... nothing) { - final List favourites = asFavourites(gpxFile.getPoints(), - fileName, forceImportFavourites); - final FavouritesDbHelper favoritesHelper = app.getFavorites(); - for (final FavouritePoint favourite : favourites) { - favoritesHelper.deleteFavourite(favourite, false); - favoritesHelper.addFavourite(favourite, false); - } - favoritesHelper.sortAll(); - favoritesHelper.saveCurrentPointsIntoFile(); - return null; - } - - @Override - protected void onPostExecute(GPXFile result) { - hideProgress(); - Toast.makeText(activity, R.string.fav_imported_sucessfully, Toast.LENGTH_LONG).show(); - final Intent newIntent = new Intent(activity, - app.getAppCustomization().getFavoritesActivity()); - newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - newIntent.putExtra(TAB_ID, FAV_TAB); - activity.startActivity(newIntent); - } - }; - executeImportTask(favoritesImportTask); + private void importFavoritesImpl(GPXFile gpxFile, String fileName, boolean forceImportFavourites) { + executeImportTask(new FavoritesImportTask(activity, gpxFile, fileName, forceImportFavourites)); } - @SuppressLint("StaticFieldLeak") - private void handleKmzImport(final Uri kmzFile, final String name, final boolean save, final boolean useImportDir) { - AsyncTask kmzImportTask = new BaseImportAsyncTask() { - - @Override - protected GPXFile doInBackground(Void... voids) { - InputStream is = null; - ZipInputStream zis = null; - try { - is = app.getContentResolver().openInputStream(kmzFile); - if (is != null) { - zis = new ZipInputStream(is); - - ZipEntry entry; - while ((entry = zis.getNextEntry()) != null) { - if (entry.getName().endsWith(KML_SUFFIX)) { - final String result = Kml2Gpx.toGpx(zis); - if (result != null) { - try { - return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - return null; - } - } - } - } - } - } catch (Exception e) { - log.error(e.getMessage(), e); - } finally { - Algorithms.closeStream(is); - Algorithms.closeStream(zis); - } - return null; - } - - @Override - protected void onPostExecute(GPXFile result) { - hideProgress(); - handleResult(result, name, save, useImportDir, false); - } - - }; - executeImportTask(kmzImportTask); + private void handleKmzImport(Uri kmzFile, String name, boolean save, boolean useImportDir) { + executeImportTask(new KmzImportTask(this, activity, kmzFile, name, save, useImportDir)); } - @SuppressLint("StaticFieldLeak") - private void handleKmlImport(final Uri kmlFile, final String name, final boolean save, final boolean useImportDir) { - AsyncTask kmlImportTask = new BaseImportAsyncTask() { - - @Override - protected GPXFile doInBackground(Void... nothing) { - InputStream is = null; - try { - is = app.getContentResolver().openInputStream(kmlFile); - if (is != null) { - final String result = Kml2Gpx.toGpx(is); - if (result != null) { - try { - return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - return null; - } - } - } - } catch (FileNotFoundException e) { - // - } catch (SecurityException e) { - log.error(e.getMessage(), e); - } finally { - Algorithms.closeStream(is); - } - return null; - } - - @Override - protected void onPostExecute(GPXFile result) { - hideProgress(); - handleResult(result, name, save, useImportDir, false); - } - }; - executeImportTask(kmlImportTask); + private void handleKmlImport(Uri kmlFile, String name, boolean save, boolean useImportDir) { + executeImportTask(new KmlImportTask(this, activity, kmlFile, name, save, useImportDir)); } - @SuppressLint("StaticFieldLeak") - private void handleObfImport(final Uri obfFile, final String name) { - AsyncTask obfImportTask = new BaseImportAsyncTask() { - - @Override - protected String doInBackground(Void... voids) { - String error = copyFile(app, getObfDestFile(name), obfFile, false); - if (error == null) { - app.getResourceManager().reloadIndexes(IProgress.EMPTY_PROGRESS, new ArrayList()); - app.getDownloadThread().updateLoadedFiles(); - return app.getString(R.string.map_imported_successfully); - } - return app.getString(R.string.map_import_error) + ": " + error; - } - - @Override - protected void onPostExecute(String message) { - hideProgress(); - app.showShortToastMessage(message); - } - }; - executeImportTask(obfImportTask); + private void handleObfImport(Uri obfFile, String name) { + executeImportTask(new ObfImportTask(activity, obfFile, name)); } - @NonNull - private File getObfDestFile(@NonNull String name) { - if (name.endsWith(IndexConstants.BINARY_ROAD_MAP_INDEX_EXT)) { - return app.getAppPath(IndexConstants.ROADS_INDEX_DIR + name); - } else if (name.endsWith(IndexConstants.BINARY_WIKI_MAP_INDEX_EXT)) { - return app.getAppPath(IndexConstants.WIKI_INDEX_DIR + name); + private void handleSqliteTileImport(Uri uri, String name) { + executeImportTask(new SqliteTileImportTask(activity, uri, name)); + } + + private void handleOsmAndSettingsImport(Uri intentUri, String fileName, Bundle extras, CallbackWithObject> callback) { + if (extras != null && extras.containsKey(SettingsHelper.SETTINGS_VERSION_KEY) && extras.containsKey(SettingsHelper.SETTINGS_LATEST_CHANGES_KEY)) { + int version = extras.getInt(SettingsHelper.SETTINGS_VERSION_KEY, -1); + String latestChanges = extras.getString(SettingsHelper.SETTINGS_LATEST_CHANGES_KEY); + handleOsmAndSettingsImport(intentUri, fileName, latestChanges, version, callback); + } else { + handleOsmAndSettingsImport(intentUri, fileName, null, -1, callback); } - return app.getAppPath(name); + } + + private void handleOsmAndSettingsImport(Uri uri, String name, String latestChanges, int version, + CallbackWithObject> callback) { + executeImportTask(new SettingsImportTask(activity, uri, name, latestChanges, version, callback)); + } + + private void handleXmlFileImport(Uri intentUri, String fileName, CallbackWithObject routingCallback) { + executeImportTask(new XmlImportTask(activity, intentUri, fileName, routingCallback)); } @Nullable @@ -538,36 +317,6 @@ public class ImportHelper { return error; } - @SuppressLint("StaticFieldLeak") - private void handleSqliteTileImport(final Uri uri, final String name) { - AsyncTask sqliteTileImportTask = new BaseImportAsyncTask() { - - @Override - protected String doInBackground(Void... voids) { - return copyFile(app, app.getAppPath(IndexConstants.TILES_INDEX_DIR + name), uri, false); - } - - @Override - protected void onPostExecute(String error) { - hideProgress(); - if (error == null) { - OsmandRasterMapsPlugin plugin = OsmandPlugin.getPlugin(OsmandRasterMapsPlugin.class); - if (plugin != null && !plugin.isActive() && !plugin.needsInstallation()) { - OsmandPlugin.enablePlugin(getMapActivity(), app, plugin, true); - } - MapActivity mapActivity = getMapActivity(); - if (mapActivity != null) { - mapActivity.getMapLayers().selectMapLayer(mapActivity.getMapView(), null, null); - } - Toast.makeText(app, app.getString(R.string.map_imported_successfully), Toast.LENGTH_SHORT).show(); - } else { - Toast.makeText(app, app.getString(R.string.map_import_error) + ": " + error, Toast.LENGTH_SHORT).show(); - } - } - }; - executeImportTask(sqliteTileImportTask); - } - public void chooseFileToImport(final ImportType importType, final CallbackWithObject callback) { final MapActivity mapActivity = getMapActivity(); if (mapActivity == null) { @@ -627,255 +376,13 @@ public class ImportHelper { return intent; } - private void handleOsmAndSettingsImport(Uri intentUri, String fileName, Bundle extras, CallbackWithObject> callback) { - if (extras != null && extras.containsKey(SettingsHelper.SETTINGS_VERSION_KEY) && extras.containsKey(SettingsHelper.SETTINGS_LATEST_CHANGES_KEY)) { - int version = extras.getInt(SettingsHelper.SETTINGS_VERSION_KEY, -1); - String latestChanges = extras.getString(SettingsHelper.SETTINGS_LATEST_CHANGES_KEY); - handleOsmAndSettingsImport(intentUri, fileName, latestChanges, version, callback); - } else { - handleOsmAndSettingsImport(intentUri, fileName, null, -1, callback); - } - } - - @SuppressLint("StaticFieldLeak") - private void handleOsmAndSettingsImport(final Uri uri, final String name, final String latestChanges, final int version, - final CallbackWithObject> callback) { - AsyncTask settingsImportTask = new BaseImportAsyncTask() { - - @Override - protected String doInBackground(Void... voids) { - File tempDir = app.getAppPath(IndexConstants.TEMP_DIR); - if (!tempDir.exists()) { - tempDir.mkdirs(); - } - File dest = new File(tempDir, name); - return copyFile(app, dest, uri, true); - } - - @Override - protected void onPostExecute(String error) { - File tempDir = app.getAppPath(IndexConstants.TEMP_DIR); - final File file = new File(tempDir, name); - if (error == null && file.exists()) { - app.getSettingsHelper().collectSettings(file, latestChanges, version, new SettingsCollectListener() { - @Override - public void onSettingsCollectFinished(boolean succeed, boolean empty, @NonNull List items) { - hideProgress(); - if (succeed) { - List pluginIndependentItems = new ArrayList<>(); - List pluginSettingsItems = new ArrayList<>(); - for (SettingsItem item : items) { - if (item instanceof PluginSettingsItem) { - pluginSettingsItems.add((PluginSettingsItem) item); - } else if (Algorithms.isEmpty(item.getPluginId())) { - pluginIndependentItems.add(item); - } - } - for (PluginSettingsItem pluginItem : pluginSettingsItems) { - handlePluginImport(pluginItem, file); - } - if (!pluginIndependentItems.isEmpty()) { - FragmentManager fragmentManager = activity.getSupportFragmentManager(); - ImportSettingsFragment.showInstance(fragmentManager, pluginIndependentItems, file); - } - } else if (empty) { - app.showShortToastMessage(app.getString(R.string.file_import_error, name, app.getString(R.string.shared_string_unexpected_error))); - } - } - }); - } else { - hideProgress(); - app.showShortToastMessage(app.getString(R.string.file_import_error, name, error)); - } - } - }; - executeImportTask(settingsImportTask); - } - - private void handlePluginImport(final PluginSettingsItem pluginItem, final File file) { - final ProgressDialog progress = new ProgressDialog(activity); - progress.setTitle(app.getString(R.string.loading_smth, "")); - progress.setMessage(app.getString(R.string.importing_from, pluginItem.getPublicName(app))); - progress.setIndeterminate(true); - progress.setCancelable(false); - - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress.show(); - } - - final SettingsImportListener importListener = new SettingsImportListener() { - @Override - public void onSettingsImportFinished(boolean succeed, @NonNull List items) { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } - CustomOsmandPlugin plugin = pluginItem.getPlugin(); - plugin.loadResources(); - - for (SettingsItem item : items) { - if (item instanceof ProfileSettingsItem) { - ((ProfileSettingsItem) item).applyAdditionalPrefs(); - } - } - if (!Algorithms.isEmpty(plugin.getDownloadMaps())) { - app.getDownloadThread().runReloadIndexFilesSilent(); - } - if (!Algorithms.isEmpty(plugin.getRendererNames())) { - app.getRendererRegistry().updateExternalRenderers(); - } - if (!Algorithms.isEmpty(plugin.getRouterNames())) { - loadRoutingFiles(app, null); - } - if (activity != null) { - plugin.onInstall(app, activity); - } - String pluginId = pluginItem.getPluginId(); - File pluginDir = new File(app.getAppPath(null), IndexConstants.PLUGINS_DIR + pluginId); - app.getSettingsHelper().exportSettings(pluginDir, "items", null, items, false); - } - }; - List pluginItems = new ArrayList<>(pluginItem.getPluginDependentItems()); - pluginItems.add(0, pluginItem); - app.getSettingsHelper().checkDuplicates(file, pluginItems, pluginItems, new CheckDuplicatesListener() { - @Override - public void onDuplicatesChecked(@NonNull List duplicates, List items) { - for (SettingsItem item : items) { - item.setShouldReplace(true); - } - app.getSettingsHelper().importSettings(file, items, "", 1, importListener); - } - }); - } - - @SuppressLint("StaticFieldLeak") - private void handleXmlFileImport(final Uri intentUri, final String fileName, - final CallbackWithObject routingCallback) { - AsyncTask renderingImportTask = new BaseImportAsyncTask() { - - private String destFileName; - private ImportType importType; - - @Override - protected void onPreExecute() { - showProgress(); - destFileName = fileName; - } - - @Override - protected String doInBackground(Void... voids) { - checkImportType(); - if (importType != null) { - File dest = getDestinationFile(); - if (dest != null) { - return copyFile(app, dest, intentUri, true); - } - } - return app.getString(R.string.file_import_error, destFileName, app.getString(R.string.unsupported_type_error)); - } - - @Override - protected void onPostExecute(String error) { - File destDir = getDestinationDir(); - File file = new File(destDir, destFileName); - if (error == null && file.exists()) { - if (importType == ImportType.RENDERING) { - app.getRendererRegistry().updateExternalRenderers(); - app.showShortToastMessage(app.getString(R.string.file_imported_successfully, destFileName)); - hideProgress(); - } else if (importType == ImportType.ROUTING) { - loadRoutingFiles(app, new AppInitializer.LoadRoutingFilesCallback() { - @Override - public void onRoutingFilesLoaded() { - hideProgress(); - RoutingConfiguration.Builder builder = app.getCustomRoutingConfig(destFileName); - if (builder != null) { - if (routingCallback != null) { - routingCallback.processResult(builder); - } - app.showShortToastMessage(app.getString(R.string.file_imported_successfully, destFileName)); - } else { - app.showToastMessage(app.getString(R.string.file_does_not_contain_routing_rules, destFileName)); - } - } - }); - } - } else { - hideProgress(); - app.showShortToastMessage(app.getString(R.string.file_import_error, destFileName, error)); - } - } - - private File getDestinationDir() { - if (importType == ImportType.ROUTING) { - return app.getAppPath(IndexConstants.ROUTING_PROFILES_DIR); - } else if (importType == ImportType.RENDERING) { - return app.getAppPath(IndexConstants.RENDERERS_DIR); - } - return null; - } - - private File getDestinationFile() { - File destDir = getDestinationDir(); - if (destDir != null) { - if (!destDir.exists()) { - destDir.mkdirs(); - } - if (importType == ImportType.RENDERING && !destFileName.endsWith(RENDERER_INDEX_EXT)) { - String fileName = Algorithms.getFileNameWithoutExtension(destFileName); - destFileName = fileName + RENDERER_INDEX_EXT; - } - File destFile = new File(destDir, destFileName); - while (destFile.exists()) { - destFileName = AndroidUtils.createNewFileName(destFileName); - destFile = new File(destDir, destFileName); - } - return destFile; - } - return null; - } - - private void checkImportType() { - InputStream is = null; - try { - is = app.getContentResolver().openInputStream(intentUri); - if (is != null) { - XmlPullParser parser = PlatformUtil.newXMLPullParser(); - parser.setInput(is, "UTF-8"); - int tok; - while ((tok = parser.next()) != XmlPullParser.END_DOCUMENT) { - if (tok == XmlPullParser.START_TAG) { - String name = parser.getName(); - if ("osmand_routing_config".equals(name)) { - importType = ImportType.ROUTING; - } else if ("renderingStyle".equals(name)) { - importType = ImportType.RENDERING; - } - break; - } - } - Algorithms.closeStream(is); - } - } catch (FileNotFoundException | XmlPullParserException e) { - log.error(e); - } catch (IOException e) { - log.error(e); - } catch (SecurityException e) { - log.error(e.getMessage(), e); - } finally { - Algorithms.closeStream(is); - } - } - }; - executeImportTask(renderingImportTask); - } - - private void handleResult(GPXFile result, String name, boolean save, - boolean useImportDir, boolean forceImportFavourites) { + protected void handleResult(GPXFile result, String name, boolean save, + boolean useImportDir, boolean forceImportFavourites) { handleResult(result, name, save, useImportDir, forceImportFavourites, true); } - private void handleResult(final GPXFile result, final String name, final boolean save, - final boolean useImportDir, boolean forceImportFavourites, boolean showInDetailsActivity) { + protected void handleResult(final GPXFile result, final String name, final boolean save, + final boolean useImportDir, boolean forceImportFavourites, boolean showInDetailsActivity) { if (result != null) { if (result.error != null) { Toast.makeText(activity, result.error.getMessage(), Toast.LENGTH_LONG).show(); @@ -937,7 +444,7 @@ public class ImportHelper { if (useImportDir) { importDir = app.getAppPath(IndexConstants.GPX_IMPORT_DIR); } else { - importDir = app.getAppPath(IndexConstants.GPX_INDEX_DIR); + importDir = app.getAppPath(GPX_INDEX_DIR); } //noinspection ResultOfMethodCallIgnored importDir.mkdirs(); @@ -1058,9 +565,9 @@ public class ImportHelper { } } - private void importGpxOrFavourites(final GPXFile gpxFile, final String fileName, final boolean save, - final boolean useImportDir, final boolean forceImportFavourites, - final boolean forceImportGpx) { + protected void importGpxOrFavourites(final GPXFile gpxFile, final String fileName, final boolean save, + final boolean useImportDir, final boolean forceImportFavourites, + final boolean forceImportGpx) { if (gpxFile == null || gpxFile.isPointsEmpty()) { if (forceImportFavourites) { final DialogInterface.OnClickListener importAsTrackListener = new DialogInterface.OnClickListener() { @@ -1083,11 +590,10 @@ public class ImportHelper { .setPositiveButton(R.string.shared_string_import, importAsTrackListener) .setNegativeButton(R.string.shared_string_cancel, importAsTrackListener) .show(); - return; } else { handleResult(gpxFile, fileName, save, useImportDir, false); - return; } + return; } if (forceImportFavourites) { @@ -1110,7 +616,7 @@ public class ImportHelper { } } - private List asFavourites(final List wptPts, String fileName, boolean forceImportFavourites) { + protected static List asFavourites(OsmandApplication app, List wptPts, String fileName, boolean forceImportFavourites) { final List favourites = new ArrayList<>(); for (WptPt p : wptPts) { if (p.name != null) { @@ -1155,27 +661,4 @@ public class ImportHelper { importTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, requests); } } - - protected abstract class BaseImportAsyncTask extends AsyncTask { - - protected ProgressDialog progress; - - @Override - protected void onPreExecute() { - showProgress(); - } - - protected void showProgress() { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - String title = app.getString(R.string.loading_smth, ""); - progress = ProgressDialog.show(activity, title, app.getString(R.string.loading_data)); - } - } - - protected void hideProgress() { - if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } - } - } } \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/KmlImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/KmlImportTask.java new file mode 100644 index 0000000000..38c557e8c7 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/KmlImportTask.java @@ -0,0 +1,71 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.GPXUtilities; +import net.osmand.GPXUtilities.GPXFile; +import net.osmand.plus.helpers.Kml2Gpx; +import net.osmand.util.Algorithms; + +import java.io.ByteArrayInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; + +class KmlImportTask extends BaseImportAsyncTask { + + private ImportHelper importHelper; + private Uri uri; + private String name; + private boolean save; + private boolean useImportDir; + + public KmlImportTask(@NonNull ImportHelper importHelper, @NonNull FragmentActivity activity, + @NonNull Uri uri, String name, boolean save, boolean useImportDir) { + super(activity); + this.importHelper = importHelper; + this.uri = uri; + this.name = name; + this.save = save; + this.useImportDir = useImportDir; + } + + @Override + protected GPXFile doInBackground(Void... nothing) { + InputStream is = null; + try { + is = app.getContentResolver().openInputStream(uri); + if (is != null) { + return loadGpxFromKml(is); + } + } catch (FileNotFoundException e) { + // + } catch (SecurityException e) { + ImportHelper.log.error(e.getMessage(), e); + } finally { + Algorithms.closeStream(is); + } + return null; + } + + @Override + protected void onPostExecute(GPXFile result) { + hideProgress(); + importHelper.handleResult(result, name, save, useImportDir, false); + } + + protected static GPXFile loadGpxFromKml(@NonNull InputStream is) { + String result = Kml2Gpx.toGpx(is); + if (result != null) { + try { + return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8"))); + } catch (UnsupportedEncodingException e) { + return null; + } + } + return null; + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/KmzImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/KmzImportTask.java new file mode 100644 index 0000000000..420f4feff4 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/KmzImportTask.java @@ -0,0 +1,67 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.GPXUtilities; +import net.osmand.GPXUtilities.GPXFile; +import net.osmand.util.Algorithms; + +import java.io.InputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import static net.osmand.plus.importfiles.ImportHelper.KML_SUFFIX; +import static net.osmand.plus.importfiles.KmlImportTask.loadGpxFromKml; + +class KmzImportTask extends BaseImportAsyncTask { + + private ImportHelper importHelper; + private Uri uri; + private String name; + private boolean save; + private boolean useImportDir; + + public KmzImportTask(@NonNull ImportHelper importHelper, @NonNull FragmentActivity activity, + @NonNull Uri uri, @NonNull String name, boolean save, boolean useImportDir) { + super(activity); + this.importHelper = importHelper; + this.uri = uri; + this.name = name; + this.save = save; + this.useImportDir = useImportDir; + } + + @Override + protected GPXFile doInBackground(Void... voids) { + InputStream is = null; + ZipInputStream zis = null; + try { + is = app.getContentResolver().openInputStream(uri); + if (is != null) { + zis = new ZipInputStream(is); + + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + if (entry.getName().endsWith(KML_SUFFIX)) { + return loadGpxFromKml(is); + } + } + } + } catch (Exception e) { + ImportHelper.log.error(e.getMessage(), e); + } finally { + Algorithms.closeStream(is); + Algorithms.closeStream(zis); + } + return null; + } + + @Override + protected void onPostExecute(GPXUtilities.GPXFile result) { + hideProgress(); + importHelper.handleResult(result, name, save, useImportDir, false); + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/ObfImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/ObfImportTask.java new file mode 100644 index 0000000000..e4a82faff9 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/ObfImportTask.java @@ -0,0 +1,52 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.IProgress; +import net.osmand.IndexConstants; +import net.osmand.plus.R; + +import java.io.File; +import java.util.ArrayList; + +class ObfImportTask extends BaseImportAsyncTask { + + private Uri uri; + private String name; + + public ObfImportTask(@NonNull FragmentActivity activity, @NonNull Uri uri, String name) { + super(activity); + this.uri = uri; + this.name = name; + } + + @Override + protected String doInBackground(Void... voids) { + String error = ImportHelper.copyFile(app, getObfDestFile(name), uri, false); + if (error == null) { + app.getResourceManager().reloadIndexes(IProgress.EMPTY_PROGRESS, new ArrayList()); + app.getDownloadThread().updateLoadedFiles(); + return app.getString(R.string.map_imported_successfully); + } + return app.getString(R.string.map_import_error) + ": " + error; + } + + @Override + protected void onPostExecute(String message) { + hideProgress(); + app.showShortToastMessage(message); + } + + @NonNull + private File getObfDestFile(@NonNull String name) { + if (name.endsWith(IndexConstants.BINARY_ROAD_MAP_INDEX_EXT)) { + return app.getAppPath(IndexConstants.ROADS_INDEX_DIR + name); + } else if (name.endsWith(IndexConstants.BINARY_WIKI_MAP_INDEX_EXT)) { + return app.getAppPath(IndexConstants.WIKI_INDEX_DIR + name); + } + return app.getAppPath(name); + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/SettingsImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/SettingsImportTask.java new file mode 100644 index 0000000000..7800714610 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/SettingsImportTask.java @@ -0,0 +1,158 @@ +package net.osmand.plus.importfiles; + +import android.app.ProgressDialog; +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; +import androidx.fragment.app.FragmentManager; + +import net.osmand.AndroidUtils; +import net.osmand.CallbackWithObject; +import net.osmand.IndexConstants; +import net.osmand.plus.CustomOsmandPlugin; +import net.osmand.plus.R; +import net.osmand.plus.settings.backend.SettingsHelper.CheckDuplicatesListener; +import net.osmand.plus.settings.backend.SettingsHelper.PluginSettingsItem; +import net.osmand.plus.settings.backend.SettingsHelper.ProfileSettingsItem; +import net.osmand.plus.settings.backend.SettingsHelper.SettingsCollectListener; +import net.osmand.plus.settings.backend.SettingsHelper.SettingsImportListener; +import net.osmand.plus.settings.backend.SettingsHelper.SettingsItem; +import net.osmand.plus.settings.fragments.ImportSettingsFragment; +import net.osmand.util.Algorithms; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import static net.osmand.IndexConstants.TEMP_DIR; +import static net.osmand.plus.AppInitializer.loadRoutingFiles; + +class SettingsImportTask extends BaseImportAsyncTask { + + private Uri uri; + private String name; + private String latestChanges; + private int version; + private CallbackWithObject> callback; + + public SettingsImportTask(@NonNull FragmentActivity activity, @NonNull Uri uri, + @NonNull String name, String latestChanges, int version, + CallbackWithObject> callback) { + super(activity); + this.uri = uri; + this.name = name; + this.latestChanges = latestChanges; + this.version = version; + this.callback = callback; + } + + @Override + protected String doInBackground(Void... voids) { + File tempDir = app.getAppPath(TEMP_DIR); + if (!tempDir.exists()) { + tempDir.mkdirs(); + } + File dest = new File(tempDir, name); + return ImportHelper.copyFile(app, dest, uri, true); + } + + @Override + protected void onPostExecute(String error) { + File tempDir = app.getAppPath(TEMP_DIR); + final File file = new File(tempDir, name); + if (error == null && file.exists()) { + app.getSettingsHelper().collectSettings(file, latestChanges, version, new SettingsCollectListener() { + @Override + public void onSettingsCollectFinished(boolean succeed, boolean empty, @NonNull List items) { + hideProgress(); + if (succeed) { + List pluginIndependentItems = new ArrayList<>(); + List pluginSettingsItems = new ArrayList<>(); + for (SettingsItem item : items) { + if (item instanceof PluginSettingsItem) { + pluginSettingsItems.add((PluginSettingsItem) item); + } else if (Algorithms.isEmpty(item.getPluginId())) { + pluginIndependentItems.add(item); + } + } + for (PluginSettingsItem pluginItem : pluginSettingsItems) { + handlePluginImport(pluginItem, file); + } + if (!pluginIndependentItems.isEmpty()) { + FragmentActivity activity = activityRef.get(); + if (activity != null) { + FragmentManager fragmentManager = activity.getSupportFragmentManager(); + ImportSettingsFragment.showInstance(fragmentManager, pluginIndependentItems, file); + } + } + } else if (empty) { + app.showShortToastMessage(app.getString(R.string.file_import_error, name, app.getString(R.string.shared_string_unexpected_error))); + } + } + }); + } else { + hideProgress(); + app.showShortToastMessage(app.getString(R.string.file_import_error, name, error)); + } + } + + private void handlePluginImport(final PluginSettingsItem pluginItem, final File file) { + FragmentActivity activity = activityRef.get(); + final ProgressDialog progress; + if (AndroidUtils.isActivityNotDestroyed(activity)) { + progress = new ProgressDialog(activity); + progress.setTitle(app.getString(R.string.loading_smth, "")); + progress.setMessage(app.getString(R.string.importing_from, pluginItem.getPublicName(app))); + progress.setIndeterminate(true); + progress.setCancelable(false); + progress.show(); + } else { + progress = null; + } + + final SettingsImportListener importListener = new SettingsImportListener() { + @Override + public void onSettingsImportFinished(boolean succeed, @NonNull List items) { + FragmentActivity activity = activityRef.get(); + if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { + progress.dismiss(); + } + CustomOsmandPlugin plugin = pluginItem.getPlugin(); + plugin.loadResources(); + + for (SettingsItem item : items) { + if (item instanceof ProfileSettingsItem) { + ((ProfileSettingsItem) item).applyAdditionalPrefs(); + } + } + if (!Algorithms.isEmpty(plugin.getDownloadMaps())) { + app.getDownloadThread().runReloadIndexFilesSilent(); + } + if (!Algorithms.isEmpty(plugin.getRendererNames())) { + app.getRendererRegistry().updateExternalRenderers(); + } + if (!Algorithms.isEmpty(plugin.getRouterNames())) { + loadRoutingFiles(app, null); + } + if (activity != null) { + plugin.onInstall(app, activity); + } + String pluginId = pluginItem.getPluginId(); + File pluginDir = new File(app.getAppPath(null), IndexConstants.PLUGINS_DIR + pluginId); + app.getSettingsHelper().exportSettings(pluginDir, "items", null, items, false); + } + }; + List pluginItems = new ArrayList<>(pluginItem.getPluginDependentItems()); + pluginItems.add(0, pluginItem); + app.getSettingsHelper().checkDuplicates(file, pluginItems, pluginItems, new CheckDuplicatesListener() { + @Override + public void onDuplicatesChecked(@NonNull List duplicates, List items) { + for (SettingsItem item : items) { + item.setShouldReplace(true); + } + app.getSettingsHelper().importSettings(file, items, "", 1, importListener); + } + }); + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/SqliteTileImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/SqliteTileImportTask.java new file mode 100644 index 0000000000..d9a177a016 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/SqliteTileImportTask.java @@ -0,0 +1,50 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.plus.OsmandPlugin; +import net.osmand.plus.R; +import net.osmand.plus.activities.MapActivity; +import net.osmand.plus.rastermaps.OsmandRasterMapsPlugin; + +import static net.osmand.IndexConstants.TILES_INDEX_DIR; + +class SqliteTileImportTask extends BaseImportAsyncTask { + + private Uri uri; + private String name; + + public SqliteTileImportTask(@NonNull FragmentActivity activity, @NonNull Uri uri, @NonNull String name) { + super(activity); + this.uri = uri; + this.name = name; + } + + @Override + protected String doInBackground(Void... voids) { + return ImportHelper.copyFile(app, app.getAppPath(TILES_INDEX_DIR + name), uri, false); + } + + @Override + protected void onPostExecute(String error) { + hideProgress(); + if (error == null) { + FragmentActivity activity = activityRef.get(); + OsmandRasterMapsPlugin plugin = OsmandPlugin.getPlugin(OsmandRasterMapsPlugin.class); + if (plugin != null && !plugin.isActive() && !plugin.needsInstallation()) { + OsmandPlugin.enablePlugin(activity, app, plugin, true); + } + if (activity instanceof MapActivity) { + MapActivity mapActivity = (MapActivity) activity; + mapActivity.getMapLayers().selectMapLayer(mapActivity.getMapView(), null, null); + } + Toast.makeText(app, app.getString(R.string.map_imported_successfully), Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(app, app.getString(R.string.map_import_error) + ": " + error, Toast.LENGTH_SHORT).show(); + } + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/XmlImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/XmlImportTask.java new file mode 100644 index 0000000000..bc66d77a76 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/XmlImportTask.java @@ -0,0 +1,149 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.AndroidUtils; +import net.osmand.CallbackWithObject; +import net.osmand.IndexConstants; +import net.osmand.PlatformUtil; +import net.osmand.plus.AppInitializer.LoadRoutingFilesCallback; +import net.osmand.plus.R; +import net.osmand.plus.importfiles.ImportHelper.ImportType; +import net.osmand.router.RoutingConfiguration.Builder; +import net.osmand.util.Algorithms; + +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import static net.osmand.IndexConstants.RENDERER_INDEX_EXT; +import static net.osmand.plus.AppInitializer.loadRoutingFiles; + +class XmlImportTask extends BaseImportAsyncTask { + + private Uri intentUri; + private String destFileName; + private ImportType importType; + private CallbackWithObject routingCallback; + + public XmlImportTask(@NonNull FragmentActivity activity, @NonNull Uri intentUri, + @NonNull String fileName, @Nullable CallbackWithObject routingCallback) { + super(activity); + this.intentUri = intentUri; + this.destFileName = fileName; + this.routingCallback = routingCallback; + } + + @Override + protected String doInBackground(Void... voids) { + checkImportType(); + if (importType != null) { + File dest = getDestinationFile(); + if (dest != null) { + return ImportHelper.copyFile(app, dest, intentUri, true); + } + } + return app.getString(R.string.file_import_error, destFileName, app.getString(R.string.unsupported_type_error)); + } + + @Override + protected void onPostExecute(String error) { + File destDir = getDestinationDir(); + File file = new File(destDir, destFileName); + if (error == null && file.exists()) { + if (importType == ImportType.RENDERING) { + app.getRendererRegistry().updateExternalRenderers(); + app.showShortToastMessage(app.getString(R.string.file_imported_successfully, destFileName)); + hideProgress(); + } else if (importType == ImportType.ROUTING) { + loadRoutingFiles(app, new LoadRoutingFilesCallback() { + @Override + public void onRoutingFilesLoaded() { + hideProgress(); + Builder builder = app.getCustomRoutingConfig(destFileName); + if (builder != null) { + if (routingCallback != null) { + routingCallback.processResult(builder); + } + app.showShortToastMessage(app.getString(R.string.file_imported_successfully, destFileName)); + } else { + app.showToastMessage(app.getString(R.string.file_does_not_contain_routing_rules, destFileName)); + } + } + }); + } + } else { + hideProgress(); + app.showShortToastMessage(app.getString(R.string.file_import_error, destFileName, error)); + } + } + + private File getDestinationDir() { + if (importType == ImportType.ROUTING) { + return app.getAppPath(IndexConstants.ROUTING_PROFILES_DIR); + } else if (importType == ImportType.RENDERING) { + return app.getAppPath(IndexConstants.RENDERERS_DIR); + } + return null; + } + + private File getDestinationFile() { + File destDir = getDestinationDir(); + if (destDir != null) { + if (!destDir.exists()) { + destDir.mkdirs(); + } + if (importType == ImportType.RENDERING && !destFileName.endsWith(RENDERER_INDEX_EXT)) { + String fileName = Algorithms.getFileNameWithoutExtension(destFileName); + destFileName = fileName + RENDERER_INDEX_EXT; + } + File destFile = new File(destDir, destFileName); + while (destFile.exists()) { + destFileName = AndroidUtils.createNewFileName(destFileName); + destFile = new File(destDir, destFileName); + } + return destFile; + } + return null; + } + + private void checkImportType() { + InputStream is = null; + try { + is = app.getContentResolver().openInputStream(intentUri); + if (is != null) { + XmlPullParser parser = PlatformUtil.newXMLPullParser(); + parser.setInput(is, "UTF-8"); + int tok; + while ((tok = parser.next()) != XmlPullParser.END_DOCUMENT) { + if (tok == XmlPullParser.START_TAG) { + String name = parser.getName(); + if ("osmand_routing_config".equals(name)) { + importType = ImportType.ROUTING; + } else if ("renderingStyle".equals(name)) { + importType = ImportType.RENDERING; + } + break; + } + } + Algorithms.closeStream(is); + } + } catch (FileNotFoundException | XmlPullParserException e) { + ImportHelper.log.error(e); + } catch (IOException e) { + ImportHelper.log.error(e); + } catch (SecurityException e) { + ImportHelper.log.error(e.getMessage(), e); + } finally { + Algorithms.closeStream(is); + } + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/measurementtool/StartPlanRouteBottomSheet.java b/OsmAnd/src/net/osmand/plus/measurementtool/StartPlanRouteBottomSheet.java index b81b015f32..fe02db28b8 100644 --- a/OsmAnd/src/net/osmand/plus/measurementtool/StartPlanRouteBottomSheet.java +++ b/OsmAnd/src/net/osmand/plus/measurementtool/StartPlanRouteBottomSheet.java @@ -28,8 +28,8 @@ import net.osmand.plus.base.bottomsheetmenu.simpleitems.DividerItem; import net.osmand.plus.base.bottomsheetmenu.simpleitems.TitleItem; import net.osmand.plus.helpers.GpxTrackAdapter; import net.osmand.plus.helpers.GpxUiHelper.GPXInfo; -import net.osmand.plus.helpers.ImportHelper; -import net.osmand.plus.helpers.ImportHelper.OnGpxImportCompleteListener; +import net.osmand.plus.importfiles.ImportHelper; +import net.osmand.plus.importfiles.ImportHelper.OnGpxImportCompleteListener; import org.apache.commons.logging.Log; diff --git a/OsmAnd/src/net/osmand/plus/myplaces/FavoritesActivity.java b/OsmAnd/src/net/osmand/plus/myplaces/FavoritesActivity.java index f310802c44..c77cfbfc0d 100644 --- a/OsmAnd/src/net/osmand/plus/myplaces/FavoritesActivity.java +++ b/OsmAnd/src/net/osmand/plus/myplaces/FavoritesActivity.java @@ -30,8 +30,8 @@ import net.osmand.plus.R; import net.osmand.plus.activities.FavoritesTreeFragment; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.TabActivity; -import net.osmand.plus.helpers.ImportHelper; -import net.osmand.plus.helpers.ImportHelper.OnGpxImportCompleteListener; +import net.osmand.plus.importfiles.ImportHelper; +import net.osmand.plus.importfiles.ImportHelper.OnGpxImportCompleteListener; import net.osmand.plus.settings.backend.OsmAndAppCustomization; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.views.controls.PagerSlidingTabStrip; diff --git a/OsmAnd/src/net/osmand/plus/profiles/SelectProfileBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/profiles/SelectProfileBottomSheetDialogFragment.java index c7d7ec843c..743c9897ad 100644 --- a/OsmAnd/src/net/osmand/plus/profiles/SelectProfileBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/profiles/SelectProfileBottomSheetDialogFragment.java @@ -40,7 +40,7 @@ import org.apache.commons.logging.Log; import java.util.ArrayList; import java.util.List; -import static net.osmand.plus.helpers.ImportHelper.ImportType.ROUTING; +import static net.osmand.plus.importfiles.ImportHelper.ImportType.ROUTING; public class SelectProfileBottomSheetDialogFragment extends BasePreferenceBottomSheet { diff --git a/OsmAnd/src/net/osmand/plus/routepreparationmenu/FollowTrackFragment.java b/OsmAnd/src/net/osmand/plus/routepreparationmenu/FollowTrackFragment.java index ee2bf6b38e..48eba555cb 100644 --- a/OsmAnd/src/net/osmand/plus/routepreparationmenu/FollowTrackFragment.java +++ b/OsmAnd/src/net/osmand/plus/routepreparationmenu/FollowTrackFragment.java @@ -40,8 +40,8 @@ import net.osmand.plus.base.ContextMenuScrollFragment; import net.osmand.plus.helpers.AndroidUiHelper; import net.osmand.plus.helpers.GpxUiHelper; import net.osmand.plus.helpers.GpxUiHelper.GPXInfo; -import net.osmand.plus.helpers.ImportHelper; -import net.osmand.plus.helpers.ImportHelper.OnGpxImportCompleteListener; +import net.osmand.plus.importfiles.ImportHelper; +import net.osmand.plus.importfiles.ImportHelper.OnGpxImportCompleteListener; import net.osmand.plus.measurementtool.GpxData; import net.osmand.plus.measurementtool.GpxData.ActionType; import net.osmand.plus.measurementtool.MeasurementEditingContext; diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndAppCustomization.java b/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndAppCustomization.java index b23edbbea1..c8025bc2d5 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndAppCustomization.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndAppCustomization.java @@ -31,7 +31,7 @@ import net.osmand.plus.activities.PluginsActivity; import net.osmand.plus.activities.SettingsActivity; import net.osmand.plus.activities.TrackActivity; import net.osmand.plus.download.DownloadActivity; -import net.osmand.plus.helpers.ImportHelper; +import net.osmand.plus.importfiles.ImportHelper; import net.osmand.plus.helpers.WaypointHelper; import net.osmand.plus.myplaces.FavoritesActivity; import net.osmand.plus.routing.RouteCalculationResult; diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/MainSettingsFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/MainSettingsFragment.java index 6aac50bc9c..2428290517 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/MainSettingsFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/MainSettingsFragment.java @@ -31,7 +31,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import static net.osmand.plus.helpers.ImportHelper.ImportType.SETTINGS; +import static net.osmand.plus.importfiles.ImportHelper.ImportType.SETTINGS; import static net.osmand.plus.profiles.SelectProfileBottomSheetDialogFragment.DIALOG_TYPE; import static net.osmand.plus.profiles.SelectProfileBottomSheetDialogFragment.IS_PROFILE_IMPORTED_ARG; import static net.osmand.plus.profiles.SelectProfileBottomSheetDialogFragment.PROFILE_KEY_ARG; From 27b235cb39399c855e61f258f608335dff455232 Mon Sep 17 00:00:00 2001 From: Vitaliy Date: Wed, 7 Oct 2020 03:17:16 +0300 Subject: [PATCH 15/95] Add import with file signature check --- .../main/java/net/osmand/IndexConstants.java | 5 +- .../main/java/net/osmand/util/Algorithms.java | 9 +- .../plus/importfiles/FavoritesImportTask.java | 3 +- .../plus/importfiles/GpxImportTask.java | 2 +- .../GpxOrFavouritesImportTask.java | 2 +- .../osmand/plus/importfiles/ImportHelper.java | 16 ++- .../plus/importfiles/KmlImportTask.java | 2 +- .../plus/importfiles/KmzImportTask.java | 5 +- .../plus/importfiles/ObfImportTask.java | 2 +- .../plus/importfiles/UriImportTask.java | 129 ++++++++++++++++++ 10 files changed, 156 insertions(+), 19 deletions(-) create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/UriImportTask.java diff --git a/OsmAnd-java/src/main/java/net/osmand/IndexConstants.java b/OsmAnd-java/src/main/java/net/osmand/IndexConstants.java index 93569dfddd..c8ffd2d96b 100644 --- a/OsmAnd-java/src/main/java/net/osmand/IndexConstants.java +++ b/OsmAnd-java/src/main/java/net/osmand/IndexConstants.java @@ -14,7 +14,8 @@ public class IndexConstants { public static final String TEMP_SOURCE_TO_LOAD = "temp"; public static final String POI_INDEX_EXT = ".poi.odb"; //$NON-NLS-1$ - + + public static final String ZIP_EXT = ".zip"; //$NON-NLS-1$ public static final String BINARY_MAP_INDEX_EXT = ".obf"; //$NON-NLS-1$ public static final String BINARY_MAP_INDEX_EXT_ZIP = ".obf.zip"; //$NON-NLS-1$ @@ -71,7 +72,7 @@ public class IndexConstants { public static final String FONT_INDEX_DIR = "fonts/"; //$NON-NLS-1$ public static final String VOICE_INDEX_DIR = "voice/"; //$NON-NLS-1$ public static final String RENDERERS_DIR = "rendering/"; //$NON-NLS-1$ - public static final String ROUTING_XML_FILE= "routing.xml"; + public static final String ROUTING_XML_FILE = "routing.xml"; public static final String SETTINGS_DIR = "settings/"; //$NON-NLS-1$ public static final String TEMP_DIR = "temp/"; public static final String ROUTING_PROFILES_DIR = "routing/"; diff --git a/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java b/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java index ea2869aaa3..d890d5edea 100644 --- a/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java +++ b/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java @@ -49,6 +49,11 @@ public class Algorithms { private static char[] CHARS_TO_NORMALIZE_KEY = new char['’']; private static char[] CHARS_TO_NORMALIZE_VALUE = new char['\'']; + public static final int ZIP_FILE_SIGNATURE = 0x504b0304; + public static final int XML_FILE_SIGNATURE = 0x3c3f786d; + public static final int OBF_FILE_SIGNATURE = 0x08029001; + public static final int SQLITE_FILE_SIGNATURE = 0x53514C69; + public static String normalizeSearchText(String s) { boolean norm = false; for (int i = 0; i < s.length() && !norm; i++) { @@ -293,7 +298,7 @@ public class Algorithms { FileInputStream in = new FileInputStream(file); int test = readInt(in); in.close(); - return test == 0x504b0304; + return test == ZIP_FILE_SIGNATURE; } /** @@ -322,7 +327,7 @@ public class Algorithms { return false; } - private static int readInt(InputStream in) throws IOException { + public static int readInt(InputStream in) throws IOException { int ch1 = in.read(); int ch2 = in.read(); int ch3 = in.read(); diff --git a/OsmAnd/src/net/osmand/plus/importfiles/FavoritesImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/FavoritesImportTask.java index 2793e1e0ab..9047baeb59 100644 --- a/OsmAnd/src/net/osmand/plus/importfiles/FavoritesImportTask.java +++ b/OsmAnd/src/net/osmand/plus/importfiles/FavoritesImportTask.java @@ -5,7 +5,6 @@ import android.content.Intent; import androidx.annotation.NonNull; import androidx.fragment.app.FragmentActivity; -import net.osmand.GPXUtilities; import net.osmand.GPXUtilities.GPXFile; import net.osmand.data.FavouritePoint; import net.osmand.plus.FavouritesDbHelper; @@ -45,7 +44,7 @@ class FavoritesImportTask extends BaseImportAsyncTask { } @Override - protected void onPostExecute(GPXUtilities.GPXFile result) { + protected void onPostExecute(GPXFile result) { hideProgress(); FragmentActivity activity = activityRef.get(); if (activity != null) { diff --git a/OsmAnd/src/net/osmand/plus/importfiles/GpxImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/GpxImportTask.java index 1e76f15a26..4a410172a7 100644 --- a/OsmAnd/src/net/osmand/plus/importfiles/GpxImportTask.java +++ b/OsmAnd/src/net/osmand/plus/importfiles/GpxImportTask.java @@ -52,7 +52,7 @@ class GpxImportTask extends BaseImportAsyncTask { } @Override - protected void onPostExecute(GPXUtilities.GPXFile result) { + protected void onPostExecute(GPXFile result) { hideProgress(); importHelper.handleResult(result, fileName, save, useImportDir, false, showInDetailsActivity); } diff --git a/OsmAnd/src/net/osmand/plus/importfiles/GpxOrFavouritesImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/GpxOrFavouritesImportTask.java index 48eadfb5b1..ed1a16c3b1 100644 --- a/OsmAnd/src/net/osmand/plus/importfiles/GpxOrFavouritesImportTask.java +++ b/OsmAnd/src/net/osmand/plus/importfiles/GpxOrFavouritesImportTask.java @@ -76,7 +76,7 @@ class GpxOrFavouritesImportTask extends BaseImportAsyncTask } @Override - protected void onPostExecute(final GPXUtilities.GPXFile result) { + protected void onPostExecute(GPXFile result) { hideProgress(); importHelper.importGpxOrFavourites(result, fileName, save, useImportDir, forceImportFavourites, forceImportGpx); } diff --git a/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java b/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java index f5b47604ac..d8bca201b4 100644 --- a/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java +++ b/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java @@ -20,7 +20,6 @@ import net.osmand.CallbackWithObject; import net.osmand.GPXUtilities; import net.osmand.GPXUtilities.GPXFile; import net.osmand.GPXUtilities.WptPt; -import net.osmand.IndexConstants; import net.osmand.PlatformUtil; import net.osmand.data.FavouritePoint; import net.osmand.data.FavouritePoint.BackgroundType; @@ -55,6 +54,7 @@ import java.util.Locale; import static android.app.Activity.RESULT_OK; import static net.osmand.IndexConstants.BINARY_MAP_INDEX_EXT; import static net.osmand.IndexConstants.GPX_FILE_EXT; +import static net.osmand.IndexConstants.GPX_IMPORT_DIR; import static net.osmand.IndexConstants.GPX_INDEX_DIR; import static net.osmand.IndexConstants.OSMAND_SETTINGS_FILE_EXT; import static net.osmand.IndexConstants.RENDERER_INDEX_EXT; @@ -176,7 +176,7 @@ public class ImportHelper { boolean saveFile = !isFileIntent || !isOsmandSubdir; if (fileName == null) { - handleGpxOrFavouritesImport(intentUri, fileName, saveFile, useImportDir, false, false); + handleUriImport(intentUri, saveFile, useImportDir); } else if (fileName.endsWith(KML_SUFFIX)) { handleKmlImport(intentUri, fileName, saveFile, useImportDir); } else if (fileName.endsWith(KMZ_SUFFIX)) { @@ -243,11 +243,11 @@ public class ImportHelper { executeImportTask(new KmlImportTask(this, activity, kmlFile, name, save, useImportDir)); } - private void handleObfImport(Uri obfFile, String name) { + protected void handleObfImport(Uri obfFile, String name) { executeImportTask(new ObfImportTask(activity, obfFile, name)); } - private void handleSqliteTileImport(Uri uri, String name) { + protected void handleSqliteTileImport(Uri uri, String name) { executeImportTask(new SqliteTileImportTask(activity, uri, name)); } @@ -266,10 +266,14 @@ public class ImportHelper { executeImportTask(new SettingsImportTask(activity, uri, name, latestChanges, version, callback)); } - private void handleXmlFileImport(Uri intentUri, String fileName, CallbackWithObject routingCallback) { + protected void handleXmlFileImport(Uri intentUri, String fileName, CallbackWithObject routingCallback) { executeImportTask(new XmlImportTask(activity, intentUri, fileName, routingCallback)); } + private void handleUriImport(Uri uri, boolean save, boolean useImportDir) { + executeImportTask(new UriImportTask(this, activity, uri, save, useImportDir)); + } + @Nullable public static String copyFile(OsmandApplication app, @NonNull File dest, @NonNull Uri uri, boolean overwrite) { if (dest.exists() && !overwrite) { @@ -442,7 +446,7 @@ public class ImportHelper { } else { final File importDir; if (useImportDir) { - importDir = app.getAppPath(IndexConstants.GPX_IMPORT_DIR); + importDir = app.getAppPath(GPX_IMPORT_DIR); } else { importDir = app.getAppPath(GPX_INDEX_DIR); } diff --git a/OsmAnd/src/net/osmand/plus/importfiles/KmlImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/KmlImportTask.java index 38c557e8c7..8d48485b33 100644 --- a/OsmAnd/src/net/osmand/plus/importfiles/KmlImportTask.java +++ b/OsmAnd/src/net/osmand/plus/importfiles/KmlImportTask.java @@ -15,7 +15,7 @@ import java.io.FileNotFoundException; import java.io.InputStream; import java.io.UnsupportedEncodingException; -class KmlImportTask extends BaseImportAsyncTask { +class KmlImportTask extends BaseImportAsyncTask { private ImportHelper importHelper; private Uri uri; diff --git a/OsmAnd/src/net/osmand/plus/importfiles/KmzImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/KmzImportTask.java index 420f4feff4..41d01be264 100644 --- a/OsmAnd/src/net/osmand/plus/importfiles/KmzImportTask.java +++ b/OsmAnd/src/net/osmand/plus/importfiles/KmzImportTask.java @@ -5,7 +5,6 @@ import android.net.Uri; import androidx.annotation.NonNull; import androidx.fragment.app.FragmentActivity; -import net.osmand.GPXUtilities; import net.osmand.GPXUtilities.GPXFile; import net.osmand.util.Algorithms; @@ -16,7 +15,7 @@ import java.util.zip.ZipInputStream; import static net.osmand.plus.importfiles.ImportHelper.KML_SUFFIX; import static net.osmand.plus.importfiles.KmlImportTask.loadGpxFromKml; -class KmzImportTask extends BaseImportAsyncTask { +class KmzImportTask extends BaseImportAsyncTask { private ImportHelper importHelper; private Uri uri; @@ -60,7 +59,7 @@ class KmzImportTask extends BaseImportAsyncTask { private Uri uri; private String name; - public ObfImportTask(@NonNull FragmentActivity activity, @NonNull Uri uri, String name) { + public ObfImportTask(@NonNull FragmentActivity activity, @NonNull Uri uri, @NonNull String name) { super(activity); this.uri = uri; this.name = name; diff --git a/OsmAnd/src/net/osmand/plus/importfiles/UriImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/UriImportTask.java new file mode 100644 index 0000000000..0bc9909643 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/UriImportTask.java @@ -0,0 +1,129 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.AndroidUtils; +import net.osmand.plus.R; +import net.osmand.util.Algorithms; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import static net.osmand.FileUtils.createUniqueFileName; +import static net.osmand.IndexConstants.BINARY_MAP_INDEX_EXT; +import static net.osmand.IndexConstants.MAPS_PATH; +import static net.osmand.IndexConstants.ROUTING_FILE_EXT; +import static net.osmand.IndexConstants.SQLITE_EXT; +import static net.osmand.IndexConstants.TEMP_DIR; +import static net.osmand.IndexConstants.TILES_INDEX_DIR; +import static net.osmand.IndexConstants.ZIP_EXT; +import static net.osmand.util.Algorithms.OBF_FILE_SIGNATURE; +import static net.osmand.util.Algorithms.SQLITE_FILE_SIGNATURE; +import static net.osmand.util.Algorithms.XML_FILE_SIGNATURE; +import static net.osmand.util.Algorithms.ZIP_FILE_SIGNATURE; + +class UriImportTask extends BaseImportAsyncTask { + + private ImportHelper importHelper; + private Uri uri; + private String tempFileName; + + private int fileSignature; + + private boolean save; + private boolean useImportDir; + + public UriImportTask(@NonNull ImportHelper importHelper, @NonNull FragmentActivity activity, + @NonNull Uri uri, boolean save, boolean useImportDir) { + super(activity); + this.importHelper = importHelper; + this.uri = uri; + this.save = save; + this.useImportDir = useImportDir; + } + + @Override + protected String doInBackground(Void... nothing) { + String error = null; + InputStream is = null; + OutputStream out = null; + try { + is = app.getContentResolver().openInputStream(uri); + if (is != null) { + fileSignature = Algorithms.readInt(is); + if (isSupportedFileSignature()) { + File tempDir = app.getAppPath(TEMP_DIR); + if (!tempDir.exists()) { + tempDir.mkdirs(); + } + tempFileName = getTempFileName(); + File dest = new File(tempDir, tempFileName); + + out = new FileOutputStream(dest); + Algorithms.writeInt(out, Integer.reverseBytes(fileSignature)); + Algorithms.streamCopy(is, out); + } + } + } catch (FileNotFoundException e) { + ImportHelper.log.error(e); + error = e.getMessage(); + } catch (SecurityException e) { + ImportHelper.log.error(e); + error = e.getMessage(); + } catch (IOException e) { + ImportHelper.log.error(e); + error = e.getMessage(); + } finally { + Algorithms.closeStream(is); + Algorithms.closeStream(out); + } + return error; + } + + private boolean isSupportedFileSignature() { + return fileSignature == XML_FILE_SIGNATURE || fileSignature == OBF_FILE_SIGNATURE + || fileSignature == ZIP_FILE_SIGNATURE || fileSignature == SQLITE_FILE_SIGNATURE; + } + + @Override + protected void onPostExecute(String error) { + hideProgress(); + File file = app.getAppPath(TEMP_DIR + tempFileName); + if (error == null && file.exists()) { + Uri tempUri = AndroidUtils.getUriForFile(app, file); + if (XML_FILE_SIGNATURE == fileSignature) { + importHelper.handleXmlFileImport(tempUri, null, null); + } else if (OBF_FILE_SIGNATURE == fileSignature) { + String name = createUniqueFileName(app, "map", MAPS_PATH, BINARY_MAP_INDEX_EXT); + importHelper.handleObfImport(tempUri, name); + } else if (ZIP_FILE_SIGNATURE == fileSignature) { +// importHelper.handleKmzImport(tempUri, null, save, useImportDir); + } else if (SQLITE_FILE_SIGNATURE == fileSignature) { + String name = createUniqueFileName(app, "online_map", TILES_INDEX_DIR, SQLITE_EXT); + importHelper.handleSqliteTileImport(tempUri, name); + } + } else { + app.showShortToastMessage(app.getString(R.string.file_import_error, tempFileName, error)); + } + } + + private String getTempFileName() { + if (XML_FILE_SIGNATURE == fileSignature) { + return createUniqueFileName(app, "xml_file", TEMP_DIR, ROUTING_FILE_EXT); + } else if (OBF_FILE_SIGNATURE == fileSignature) { + return createUniqueFileName(app, "map", TEMP_DIR, BINARY_MAP_INDEX_EXT); + } else if (ZIP_FILE_SIGNATURE == fileSignature) { + return createUniqueFileName(app, "zip_file", TEMP_DIR, ZIP_EXT); + } else if (SQLITE_FILE_SIGNATURE == fileSignature) { + return createUniqueFileName(app, "online_map", TEMP_DIR, SQLITE_EXT); + } + return ""; + } +} \ No newline at end of file From fea6b424ca3b4ede41e432fe45848c13d3659699 Mon Sep 17 00:00:00 2001 From: Vitaliy Date: Wed, 7 Oct 2020 04:06:52 +0300 Subject: [PATCH 16/95] Add xml files import after check for file signature --- .../osmand/plus/importfiles/ImportHelper.java | 8 ++++--- .../plus/importfiles/UriImportTask.java | 10 +++++++- .../plus/importfiles/XmlImportTask.java | 23 ++++++++++++------- 3 files changed, 29 insertions(+), 12 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java b/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java index d8bca201b4..62e0f1dbd0 100644 --- a/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java +++ b/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java @@ -87,7 +87,9 @@ public class ImportHelper { public enum ImportType { SETTINGS(OSMAND_SETTINGS_FILE_EXT), ROUTING(ROUTING_FILE_EXT), - RENDERING(RENDERER_INDEX_EXT); + RENDERING(RENDERER_INDEX_EXT), + GPX(GPX_FILE_EXT), + KML(KML_SUFFIX); ImportType(String extension) { this.extension = extension; @@ -226,8 +228,8 @@ public class ImportHelper { executeImportTask(new GpxImportTask(this, activity, gpxFile, fileName, save, useImportDir, showInDetailsActivity)); } - private void handleGpxOrFavouritesImport(Uri fileUri, String fileName, boolean save, boolean useImportDir, - boolean forceImportFavourites, boolean forceImportGpx) { + protected void handleGpxOrFavouritesImport(Uri fileUri, String fileName, boolean save, boolean useImportDir, + boolean forceImportFavourites, boolean forceImportGpx) { executeImportTask(new GpxOrFavouritesImportTask(this, activity, fileUri, fileName, save, useImportDir, forceImportFavourites, forceImportGpx)); } diff --git a/OsmAnd/src/net/osmand/plus/importfiles/UriImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/UriImportTask.java index 0bc9909643..27b4a0fa73 100644 --- a/OsmAnd/src/net/osmand/plus/importfiles/UriImportTask.java +++ b/OsmAnd/src/net/osmand/plus/importfiles/UriImportTask.java @@ -7,6 +7,7 @@ import androidx.fragment.app.FragmentActivity; import net.osmand.AndroidUtils; import net.osmand.plus.R; +import net.osmand.plus.importfiles.ImportHelper.ImportType; import net.osmand.util.Algorithms; import java.io.File; @@ -19,6 +20,7 @@ import java.io.OutputStream; import static net.osmand.FileUtils.createUniqueFileName; import static net.osmand.IndexConstants.BINARY_MAP_INDEX_EXT; import static net.osmand.IndexConstants.MAPS_PATH; +import static net.osmand.IndexConstants.RENDERER_INDEX_EXT; import static net.osmand.IndexConstants.ROUTING_FILE_EXT; import static net.osmand.IndexConstants.SQLITE_EXT; import static net.osmand.IndexConstants.TEMP_DIR; @@ -99,7 +101,13 @@ class UriImportTask extends BaseImportAsyncTask { if (error == null && file.exists()) { Uri tempUri = AndroidUtils.getUriForFile(app, file); if (XML_FILE_SIGNATURE == fileSignature) { - importHelper.handleXmlFileImport(tempUri, null, null); + ImportType importType = XmlImportTask.checkImportType(app, tempUri); + if (importType == ImportType.RENDERING || importType == ImportType.ROUTING) { + String name = importType == ImportType.RENDERING ? "renderer" + RENDERER_INDEX_EXT : "router" + ROUTING_FILE_EXT; + importHelper.handleXmlFileImport(tempUri, name, null); + } else if (importType == ImportType.GPX || importType == ImportType.KML) { + importHelper.handleGpxOrFavouritesImport(tempUri, tempFileName, save, useImportDir, false, false); + } } else if (OBF_FILE_SIGNATURE == fileSignature) { String name = createUniqueFileName(app, "map", MAPS_PATH, BINARY_MAP_INDEX_EXT); importHelper.handleObfImport(tempUri, name); diff --git a/OsmAnd/src/net/osmand/plus/importfiles/XmlImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/XmlImportTask.java index bc66d77a76..6d45466bab 100644 --- a/OsmAnd/src/net/osmand/plus/importfiles/XmlImportTask.java +++ b/OsmAnd/src/net/osmand/plus/importfiles/XmlImportTask.java @@ -11,6 +11,7 @@ import net.osmand.CallbackWithObject; import net.osmand.IndexConstants; import net.osmand.PlatformUtil; import net.osmand.plus.AppInitializer.LoadRoutingFilesCallback; +import net.osmand.plus.OsmandApplication; import net.osmand.plus.R; import net.osmand.plus.importfiles.ImportHelper.ImportType; import net.osmand.router.RoutingConfiguration.Builder; @@ -29,26 +30,26 @@ import static net.osmand.plus.AppInitializer.loadRoutingFiles; class XmlImportTask extends BaseImportAsyncTask { - private Uri intentUri; + private Uri uri; private String destFileName; private ImportType importType; private CallbackWithObject routingCallback; - public XmlImportTask(@NonNull FragmentActivity activity, @NonNull Uri intentUri, - @NonNull String fileName, @Nullable CallbackWithObject routingCallback) { + public XmlImportTask(@NonNull FragmentActivity activity, @NonNull Uri uri, + @NonNull String fileName, @Nullable CallbackWithObject routingCallback) { super(activity); - this.intentUri = intentUri; + this.uri = uri; this.destFileName = fileName; this.routingCallback = routingCallback; } @Override protected String doInBackground(Void... voids) { - checkImportType(); + importType = checkImportType(app, uri); if (importType != null) { File dest = getDestinationFile(); if (dest != null) { - return ImportHelper.copyFile(app, dest, intentUri, true); + return ImportHelper.copyFile(app, dest, uri, true); } } return app.getString(R.string.file_import_error, destFileName, app.getString(R.string.unsupported_type_error)); @@ -115,10 +116,11 @@ class XmlImportTask extends BaseImportAsyncTask { return null; } - private void checkImportType() { + protected static ImportType checkImportType(OsmandApplication app, Uri uri) { + ImportType importType = null; InputStream is = null; try { - is = app.getContentResolver().openInputStream(intentUri); + is = app.getContentResolver().openInputStream(uri); if (is != null) { XmlPullParser parser = PlatformUtil.newXMLPullParser(); parser.setInput(is, "UTF-8"); @@ -130,6 +132,10 @@ class XmlImportTask extends BaseImportAsyncTask { importType = ImportType.ROUTING; } else if ("renderingStyle".equals(name)) { importType = ImportType.RENDERING; + } else if ("gpx".equals(name)) { + importType = ImportType.GPX; + } else if ("kml".equals(name)) { + importType = ImportType.KML; } break; } @@ -145,5 +151,6 @@ class XmlImportTask extends BaseImportAsyncTask { } finally { Algorithms.closeStream(is); } + return importType; } } \ No newline at end of file From 62c119731978546079d97595b3de7ddf78ebcbd5 Mon Sep 17 00:00:00 2001 From: Vitaliy Date: Wed, 7 Oct 2020 05:23:02 +0300 Subject: [PATCH 17/95] Add zip files import with check for file signature --- .../osmand/plus/importfiles/ImportHelper.java | 13 ++- .../plus/importfiles/UriImportTask.java | 14 +-- .../plus/importfiles/ZipImportTask.java | 90 +++++++++++++++++++ 3 files changed, 106 insertions(+), 11 deletions(-) create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/ZipImportTask.java diff --git a/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java b/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java index 62e0f1dbd0..c67ae8834e 100644 --- a/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java +++ b/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java @@ -89,7 +89,8 @@ public class ImportHelper { ROUTING(ROUTING_FILE_EXT), RENDERING(RENDERER_INDEX_EXT), GPX(GPX_FILE_EXT), - KML(KML_SUFFIX); + KML(KML_SUFFIX), + KMZ(KMZ_SUFFIX); ImportType(String extension) { this.extension = extension; @@ -237,7 +238,7 @@ public class ImportHelper { executeImportTask(new FavoritesImportTask(activity, gpxFile, fileName, forceImportFavourites)); } - private void handleKmzImport(Uri kmzFile, String name, boolean save, boolean useImportDir) { + protected void handleKmzImport(Uri kmzFile, String name, boolean save, boolean useImportDir) { executeImportTask(new KmzImportTask(this, activity, kmzFile, name, save, useImportDir)); } @@ -263,8 +264,8 @@ public class ImportHelper { } } - private void handleOsmAndSettingsImport(Uri uri, String name, String latestChanges, int version, - CallbackWithObject> callback) { + protected void handleOsmAndSettingsImport(Uri uri, String name, String latestChanges, int version, + CallbackWithObject> callback) { executeImportTask(new SettingsImportTask(activity, uri, name, latestChanges, version, callback)); } @@ -276,6 +277,10 @@ public class ImportHelper { executeImportTask(new UriImportTask(this, activity, uri, save, useImportDir)); } + protected void handleZipImport(Uri uri, boolean save, boolean useImportDir) { + executeImportTask(new ZipImportTask(this, activity, uri, save, useImportDir)); + } + @Nullable public static String copyFile(OsmandApplication app, @NonNull File dest, @NonNull Uri uri, boolean overwrite) { if (dest.exists() && !overwrite) { diff --git a/OsmAnd/src/net/osmand/plus/importfiles/UriImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/UriImportTask.java index 27b4a0fa73..c2de2d072f 100644 --- a/OsmAnd/src/net/osmand/plus/importfiles/UriImportTask.java +++ b/OsmAnd/src/net/osmand/plus/importfiles/UriImportTask.java @@ -110,12 +110,12 @@ class UriImportTask extends BaseImportAsyncTask { } } else if (OBF_FILE_SIGNATURE == fileSignature) { String name = createUniqueFileName(app, "map", MAPS_PATH, BINARY_MAP_INDEX_EXT); - importHelper.handleObfImport(tempUri, name); + importHelper.handleObfImport(tempUri, name + BINARY_MAP_INDEX_EXT); } else if (ZIP_FILE_SIGNATURE == fileSignature) { -// importHelper.handleKmzImport(tempUri, null, save, useImportDir); + importHelper.handleZipImport(tempUri, save, useImportDir); } else if (SQLITE_FILE_SIGNATURE == fileSignature) { String name = createUniqueFileName(app, "online_map", TILES_INDEX_DIR, SQLITE_EXT); - importHelper.handleSqliteTileImport(tempUri, name); + importHelper.handleSqliteTileImport(tempUri, name + SQLITE_EXT); } } else { app.showShortToastMessage(app.getString(R.string.file_import_error, tempFileName, error)); @@ -124,13 +124,13 @@ class UriImportTask extends BaseImportAsyncTask { private String getTempFileName() { if (XML_FILE_SIGNATURE == fileSignature) { - return createUniqueFileName(app, "xml_file", TEMP_DIR, ROUTING_FILE_EXT); + return createUniqueFileName(app, "xml_file", TEMP_DIR, ROUTING_FILE_EXT) + ROUTING_FILE_EXT; } else if (OBF_FILE_SIGNATURE == fileSignature) { - return createUniqueFileName(app, "map", TEMP_DIR, BINARY_MAP_INDEX_EXT); + return createUniqueFileName(app, "map", TEMP_DIR, BINARY_MAP_INDEX_EXT) + BINARY_MAP_INDEX_EXT; } else if (ZIP_FILE_SIGNATURE == fileSignature) { - return createUniqueFileName(app, "zip_file", TEMP_DIR, ZIP_EXT); + return createUniqueFileName(app, "zip_file", TEMP_DIR, ZIP_EXT) + ZIP_EXT; } else if (SQLITE_FILE_SIGNATURE == fileSignature) { - return createUniqueFileName(app, "online_map", TEMP_DIR, SQLITE_EXT); + return createUniqueFileName(app, "online_map", TEMP_DIR, SQLITE_EXT) + SQLITE_EXT; } return ""; } diff --git a/OsmAnd/src/net/osmand/plus/importfiles/ZipImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/ZipImportTask.java new file mode 100644 index 0000000000..3704f2192b --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/ZipImportTask.java @@ -0,0 +1,90 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.plus.importfiles.ImportHelper.ImportType; +import net.osmand.util.Algorithms; + +import java.io.InputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import static net.osmand.FileUtils.createUniqueFileName; +import static net.osmand.IndexConstants.GPX_FILE_EXT; +import static net.osmand.IndexConstants.GPX_IMPORT_DIR; +import static net.osmand.IndexConstants.GPX_INDEX_DIR; +import static net.osmand.IndexConstants.OSMAND_SETTINGS_FILE_EXT; +import static net.osmand.IndexConstants.TEMP_DIR; +import static net.osmand.plus.importfiles.ImportHelper.KML_SUFFIX; + +public class ZipImportTask extends BaseImportAsyncTask { + + private ImportHelper importHelper; + private Uri uri; + private boolean save; + private boolean useImportDir; + + public ZipImportTask(@NonNull ImportHelper importHelper, @NonNull FragmentActivity activity, + @NonNull Uri uri, boolean save, boolean useImportDir) { + super(activity); + this.importHelper = importHelper; + this.uri = uri; + this.save = save; + this.useImportDir = useImportDir; + } + + @Override + protected ImportType doInBackground(Void... voids) { + ImportType importType = null; + InputStream is = null; + ZipInputStream zis = null; + try { + is = app.getContentResolver().openInputStream(uri); + if (is != null) { + zis = new ZipInputStream(is); + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + String fileName = checkEntryName(entry.getName()); + if (fileName.endsWith(KML_SUFFIX)) { + importType = ImportType.KMZ; + break; + } else if (fileName.equals("items.json")) { + importType = ImportType.SETTINGS; + break; + } + } + } + } catch (Exception e) { + ImportHelper.log.error(e.getMessage(), e); + } finally { + Algorithms.closeStream(is); + Algorithms.closeStream(zis); + } + return importType; + } + + private String checkEntryName(String entryName) { + String fileExt = OSMAND_SETTINGS_FILE_EXT + "/"; + int index = entryName.indexOf(fileExt); + if (index != -1) { + entryName = entryName.substring(index + fileExt.length()); + } + return entryName; + } + + @Override + protected void onPostExecute(ImportType importType) { + hideProgress(); + if (importType == ImportType.KMZ) { + String dir = useImportDir ? GPX_IMPORT_DIR : GPX_INDEX_DIR; + String name = createUniqueFileName(app, "track", dir, GPX_FILE_EXT); + importHelper.handleKmzImport(uri, name + GPX_FILE_EXT, save, useImportDir); + } else if (importType == ImportType.SETTINGS) { + String name = createUniqueFileName(app, "settings", TEMP_DIR, OSMAND_SETTINGS_FILE_EXT); + importHelper.handleOsmAndSettingsImport(uri, name + OSMAND_SETTINGS_FILE_EXT, null, -1, null); + } + } +} \ No newline at end of file From 02dbacf4fe09d48d719c56ed42a0fd524d0044ff Mon Sep 17 00:00:00 2001 From: simon Date: Wed, 7 Oct 2020 12:10:59 +0300 Subject: [PATCH 18/95] amenity id --- .../builders/cards/ImageCard.java | 137 ++++++++++++------ .../plus/views/layers/ContextMenuLayer.java | 6 +- .../osmand/plus/views/layers/POIMapLayer.java | 2 +- 3 files changed, 95 insertions(+), 50 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java index c7cf92df0f..84a63cb72a 100644 --- a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java +++ b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java @@ -2,6 +2,7 @@ package net.osmand.plus.mapcontextmenu.builders.cards; import android.content.res.ColorStateList; import android.graphics.Bitmap; +import android.graphics.PointF; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.view.View; @@ -16,9 +17,13 @@ import androidx.appcompat.widget.AppCompatButton; import net.osmand.AndroidNetworkUtils; import net.osmand.AndroidUtils; +import net.osmand.GPXUtilities; import net.osmand.Location; import net.osmand.data.Amenity; +import net.osmand.data.FavouritePoint; import net.osmand.data.LatLon; +import net.osmand.data.RotatedTileBox; +import net.osmand.osm.PoiType; import net.osmand.plus.OsmandApplication; import net.osmand.plus.R; import net.osmand.plus.Version; @@ -26,6 +31,8 @@ import net.osmand.plus.activities.MapActivity; import net.osmand.plus.mapcontextmenu.MenuBuilder; import net.osmand.plus.mapillary.MapillaryContributeCard; import net.osmand.plus.mapillary.MapillaryImageCard; +import net.osmand.plus.osmedit.OsmBugsLayer; +import net.osmand.plus.views.layers.ContextMenuLayer; import net.osmand.plus.wikimedia.WikiImageHelper; import net.osmand.util.Algorithms; @@ -43,6 +50,8 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import static net.osmand.data.FavouritePoint.DEFAULT_BACKGROUND_TYPE; + public abstract class ImageCard extends AbstractCard { public static String TYPE_MAPILLARY_PHOTO = "mapillary-photo"; @@ -411,7 +420,7 @@ public abstract class ImageCard extends AbstractCard { } public GetImageCardsTask(@NonNull MapActivity mapActivity, LatLon latLon, - @Nullable Map params, GetImageCardsListener listener) { + @Nullable Map params, GetImageCardsListener listener) { this.mapActivity = mapActivity; this.app = mapActivity.getMyApplication(); this.latLon = latLon; @@ -422,64 +431,100 @@ public abstract class ImageCard extends AbstractCard { @Override protected List doInBackground(Void... params) { List result = new ArrayList<>(); - try { + RotatedTileBox rtb = mapActivity.getMapView().getCurrentRotatedTileBox(); + Object o = mapActivity.getMapLayers().getContextMenuLayer().getSelectedObject(); + if (this.params != null) { + String wikidataId = this.params.get(Amenity.WIKIDATA); + if (wikidataId != null) { + this.params.remove(Amenity.WIKIDATA); + WikiImageHelper.addWikidataImageCards(mapActivity, wikidataId, result); + } + String wikimediaContent = this.params.get(Amenity.WIKIMEDIA_COMMONS); + if (wikimediaContent != null) { + this.params.remove(Amenity.WIKIMEDIA_COMMONS); + WikiImageHelper.addWikimediaImageCards(mapActivity, wikimediaContent, result); + } + } + if (o instanceof Amenity) { + Amenity am = (Amenity) o; + System.out.println("POINT OSM ID: " + am.getId() + " " + am.getType().ordinal()); final Map pms = new LinkedHashMap<>(); - pms.put("lat", "" + (float) latLon.getLatitude()); - pms.put("lon", "" + (float) latLon.getLongitude()); - Location myLocation = app.getLocationProvider().getLastKnownLocation(); - if (myLocation != null) { - pms.put("mloc", "" + (float) myLocation.getLatitude() + "," + (float) myLocation.getLongitude()); - } - pms.put("app", Version.isPaidVersion(app) ? "paid" : "free"); - String preferredLang = app.getSettings().MAP_PREFERRED_LOCALE.get(); - if (Algorithms.isEmpty(preferredLang)) { - preferredLang = app.getLanguage(); - } - if (!Algorithms.isEmpty(preferredLang)) { - pms.put("lang", preferredLang); - } - if (this.params != null) { - String wikidataId = this.params.get(Amenity.WIKIDATA); - if (wikidataId != null) { - this.params.remove(Amenity.WIKIDATA); - WikiImageHelper.addWikidataImageCards(mapActivity, wikidataId, result); - } - String wikimediaContent = this.params.get(Amenity.WIKIMEDIA_COMMONS); - if (wikimediaContent != null) { - this.params.remove(Amenity.WIKIMEDIA_COMMONS); - WikiImageHelper.addWikimediaImageCards(mapActivity, wikimediaContent, result); - } - pms.putAll(this.params); - } + pms.put("osmid", "" + am.getId()); String response = AndroidNetworkUtils.sendRequest(app, "https://osmand.net/api/cm_place", pms, "Requesting location images...", false, false); if (!Algorithms.isEmpty(response)) { - JSONObject obj = new JSONObject(response); - JSONArray images = obj.getJSONArray("features"); - if (images.length() > 0) { - for (int i = 0; i < images.length(); i++) { - try { - JSONObject imageObject = (JSONObject) images.get(i); - if (imageObject != JSONObject.NULL) { - ImageCard imageCard = ImageCard.createCard(mapActivity, imageObject); - if (imageCard != null) { - result.add(imageCard); + JSONObject obj = null; + try { + obj = new JSONObject(response); + JSONArray images = null; + images = obj.getJSONArray("features"); + if (images.length() > 0) { + for (int i = 0; i < images.length(); i++) { + try { + JSONObject imageObject = (JSONObject) images.get(i); + if (imageObject != JSONObject.NULL) { + ImageCard imageCard = ImageCard.createCard(mapActivity, imageObject); + if (imageCard != null) { + result.add(imageCard); + } } + } catch (JSONException e) { + e.printStackTrace(); } - } catch (JSONException e) { - e.printStackTrace(); } } + } catch (JSONException e) { + e.printStackTrace(); } } - } catch (Exception e) { - e.printStackTrace(); - } - if (listener != null) { - listener.onPostProcess(result); } return result; +// try { +// final Map pms = new LinkedHashMap<>(); +// pms.put("lat", "" + (float) latLon.getLatitude()); +// pms.put("lon", "" + (float) latLon.getLongitude()); +// Location myLocation = app.getLocationProvider().getLastKnownLocation(); +// if (myLocation != null) { +// pms.put("mloc", "" + (float) myLocation.getLatitude() + "," + (float) myLocation.getLongitude()); +// } +// pms.put("app", Version.isPaidVersion(app) ? "paid" : "free"); +// String preferredLang = app.getSettings().MAP_PREFERRED_LOCALE.get(); +// if (Algorithms.isEmpty(preferredLang)) { +// preferredLang = app.getLanguage(); +// } +// if (!Algorithms.isEmpty(preferredLang)) { +// pms.put("lang", preferredLang); +// } +// String response = AndroidNetworkUtils.sendRequest(app, "https://osmand.net/api/cm_place", pms, +// "Requesting location images...", false, false); +// +// if (!Algorithms.isEmpty(response)) { +// JSONObject obj = new JSONObject(response); +// JSONArray images = obj.getJSONArray("features"); +// if (images.length() > 0) { +// for (int i = 0; i < images.length(); i++) { +// try { +// JSONObject imageObject = (JSONObject) images.get(i); +// if (imageObject != JSONObject.NULL) { +// ImageCard imageCard = ImageCard.createCard(mapActivity, imageObject); +// if (imageCard != null) { +// result.add(imageCard); +// } +// } +// } catch (JSONException e) { +// e.printStackTrace(); +// } +// } +// } +// } +// } catch (Exception e) { +// e.printStackTrace(); +// } +// if (listener != null) { +// listener.onPostProcess(result); +// } +// return result; } @Override diff --git a/OsmAnd/src/net/osmand/plus/views/layers/ContextMenuLayer.java b/OsmAnd/src/net/osmand/plus/views/layers/ContextMenuLayer.java index 7a8690fe2d..2902794ee8 100644 --- a/OsmAnd/src/net/osmand/plus/views/layers/ContextMenuLayer.java +++ b/OsmAnd/src/net/osmand/plus/views/layers/ContextMenuLayer.java @@ -907,9 +907,9 @@ public class ContextMenuLayer extends OsmandMapLayer { } @NonNull - private Map selectObjectsForContextMenu(RotatedTileBox tileBox, - PointF point, boolean acquireObjLatLon, - boolean unknownLocation) { + public Map selectObjectsForContextMenu(RotatedTileBox tileBox, + PointF point, boolean acquireObjLatLon, + boolean unknownLocation) { Map pressedLatLonFull = new HashMap<>(); Map pressedLatLonSmall = new HashMap<>(); Map selectedObjects = new HashMap<>(); diff --git a/OsmAnd/src/net/osmand/plus/views/layers/POIMapLayer.java b/OsmAnd/src/net/osmand/plus/views/layers/POIMapLayer.java index ed0f2cc45d..d01ec310a9 100644 --- a/OsmAnd/src/net/osmand/plus/views/layers/POIMapLayer.java +++ b/OsmAnd/src/net/osmand/plus/views/layers/POIMapLayer.java @@ -66,7 +66,7 @@ public class POIMapLayer extends OsmandMapLayer implements ContextMenuLayer.ICon /// cache for displayed POI // Work with cache (for map copied from AmenityIndexRepositoryOdb) - private MapLayerData> data; + public MapLayerData> data; private OsmandApplication app; From b201f147aca39dccdfdbaa9561f5afdd3c23fa16 Mon Sep 17 00:00:00 2001 From: Alexander Sytnyk Date: Wed, 7 Oct 2020 14:23:34 +0300 Subject: [PATCH 19/95] #9621 Add validation for the online tracking link --- .../main/java/net/osmand/util/Algorithms.java | 16 ++++++++++++++ .../plus/monitoring/LiveMonitoringHelper.java | 16 +++++++++----- .../SettingsMonitoringActivity.java | 21 ++++++++++++++++--- 3 files changed, 45 insertions(+), 8 deletions(-) diff --git a/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java b/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java index ea2869aaa3..a1e721ac21 100644 --- a/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java +++ b/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java @@ -942,4 +942,20 @@ public class Algorithms { } return res; } + + public static boolean isValidMessageFormat(CharSequence sequence) { + if (!isEmpty(sequence)) { + int counter = 0; + for (int i = 0; i < sequence.length(); i++) { + char ch = sequence.charAt(i); + if (ch == '{') { + counter++; + } else if (ch == '}') { + counter--; + } + } + return counter == 0; + } + return false; + } } \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/monitoring/LiveMonitoringHelper.java b/OsmAnd/src/net/osmand/plus/monitoring/LiveMonitoringHelper.java index 169507b35a..9ec8a3081c 100644 --- a/OsmAnd/src/net/osmand/plus/monitoring/LiveMonitoringHelper.java +++ b/OsmAnd/src/net/osmand/plus/monitoring/LiveMonitoringHelper.java @@ -131,7 +131,14 @@ public class LiveMonitoringHelper { } public void sendData(LiveMonitoringData data) { - String urlStr = getLiveUrl(data); + String baseUrl = app.getSettings().LIVE_MONITORING_URL.get(); + String urlStr; + try { + urlStr = getLiveUrl(baseUrl, data); + } catch (IllegalArgumentException e) { + log.error("Could not construct live url from base url: " + baseUrl, e); + return; + } try { // Parse the URL and let the URI constructor handle proper encoding of special characters such as spaces URL url = new URL(urlStr); @@ -172,12 +179,11 @@ public class LiveMonitoringHelper { } } - private String getLiveUrl(LiveMonitoringData data) { - String st = app.getSettings().LIVE_MONITORING_URL.get(); + private String getLiveUrl(String baseUrl, LiveMonitoringData data) { List prm = new ArrayList(); int maxLen = 0; for (int i = 0; i < 7; i++) { - boolean b = st.contains("{"+i+"}"); + boolean b = baseUrl.contains("{"+i+"}"); if(b) { maxLen = i; } @@ -210,6 +216,6 @@ public class LiveMonitoringHelper { break; } } - return MessageFormat.format(st, prm.toArray()); + return MessageFormat.format(baseUrl, prm.toArray()); } } diff --git a/OsmAnd/src/net/osmand/plus/monitoring/SettingsMonitoringActivity.java b/OsmAnd/src/net/osmand/plus/monitoring/SettingsMonitoringActivity.java index d048bbedd5..7ace6377ad 100644 --- a/OsmAnd/src/net/osmand/plus/monitoring/SettingsMonitoringActivity.java +++ b/OsmAnd/src/net/osmand/plus/monitoring/SettingsMonitoringActivity.java @@ -8,6 +8,7 @@ import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.preference.CheckBoxPreference; +import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; @@ -23,11 +24,11 @@ import android.view.Window; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; +import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; -import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmAndTaskManager.OsmAndTaskRunnable; import net.osmand.plus.OsmandApplication; @@ -35,6 +36,8 @@ import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.SavingTrackHelper; import net.osmand.plus.activities.SettingsBaseActivity; +import net.osmand.plus.settings.backend.ApplicationMode; +import net.osmand.util.Algorithms; import java.util.Map; @@ -172,8 +175,20 @@ public class SettingsMonitoringActivity extends SettingsBaseActivity { cat.setTitle(R.string.live_monitoring_m); grp.addPreference(cat); - cat.addPreference(createEditTextPreference(settings.LIVE_MONITORING_URL, R.string.live_monitoring_url, - R.string.live_monitoring_url_descr)); + EditTextPreference urlPreference = createEditTextPreference(settings.LIVE_MONITORING_URL, R.string.live_monitoring_url, + R.string.live_monitoring_url_descr); + urlPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + if (Algorithms.isValidMessageFormat((String) newValue)) { + return SettingsMonitoringActivity.super.onPreferenceChange(preference, newValue); + } else { + Toast.makeText(SettingsMonitoringActivity.this, R.string.wrong_format, Toast.LENGTH_SHORT).show(); + return false; + } + } + }); + cat.addPreference(urlPreference); final CheckBoxPreference liveMonitoring = createCheckBoxPreference(settings.LIVE_MONITORING, R.string.live_monitoring_m, R.string.live_monitoring_m_descr); cat.addPreference(liveMonitoring); From 9472f6306d7342976f30746fd194ff758491a3c2 Mon Sep 17 00:00:00 2001 From: Dima-1 Date: Wed, 7 Oct 2020 15:25:14 +0300 Subject: [PATCH 20/95] refactor fix build --- OsmAnd/res/xml/configure_profile.xml | 4 +- OsmAnd/res/xml/general_profile_settings.xml | 2 +- OsmAnd/res/xml/global_settings.xml | 4 +- OsmAnd/res/xml/navigation_settings_new.xml | 6 +- OsmAnd/res/xml/settings_main_screen.xml | 6 +- .../osmand/plus/AppVersionUpgradeOnInit.java | 100 +++++++----------- .../BooleanAccessibilityPreference.java | 13 +-- .../settings/backend/BooleanPreference.java | 6 +- .../settings/backend/CommonPreference.java | 17 ++- .../backend/ContextMenuItemsPreference.java | 10 +- .../backend/ContextMenuItemsSettings.java | 9 +- .../backend/EnumStringPreference.java | 16 +-- .../settings/backend/FloatPreference.java | 12 +-- .../backend/ImpassableRoadsStorage.java | 11 +- .../plus/settings/backend/IntPreference.java | 12 +-- .../backend/IntermediatePointsStorage.java | 6 +- .../backend/ListStringPreference.java | 16 ++- .../plus/settings/backend/LongPreference.java | 12 +-- .../backend/OsmAndPreferencesDataStore.java | 20 ++-- .../plus/settings/backend/OsmandSettings.java | 86 +++++++++++---- .../plus/settings/backend/SettingsHelper.java | 14 +-- .../backend/SettingsMapPointsStorage.java | 23 ++-- .../settings/backend/StringPreference.java | 11 +- 23 files changed, 216 insertions(+), 200 deletions(-) diff --git a/OsmAnd/res/xml/configure_profile.xml b/OsmAnd/res/xml/configure_profile.xml index d86a80620f..9fb131486e 100644 --- a/OsmAnd/res/xml/configure_profile.xml +++ b/OsmAnd/res/xml/configure_profile.xml @@ -16,7 +16,7 @@ android:persistent="false" android:summary="@string/general_settings_profile_descr" android:title="@string/general_settings_2" - app:fragment="net.osmand.plus.settings.GeneralProfileSettingsFragment" + app:fragment="net.osmand.plus.settings.fragments.GeneralProfileSettingsFragment" tools:icon="@drawable/ic_action_settings" /> + app:fragment="net.osmand.plus.settings.fragments.CoordinatesFormatFragment" /> + app:fragment="net.osmand.plus.settings.fragments.MapDuringNavigationFragment" /> globalPrefsMap = globalSharedPreferences.getAll(); for (String key : globalPrefsMap.keySet()) { - OsmandPreference pref = getPreference(key); + OsmandPreference pref = settings.getPreference(key); if (pref instanceof CommonPreference) { - CommonPreference commonPreference = (CommonPreference) pref; - if (!commonPreference.global) { + CommonPreference commonPreference = (CommonPreference) pref; + if (!commonPreference.isGlobal()) { for (ApplicationMode mode : ApplicationMode.allPossibleValues()) { if (!commonPreference.isSetForMode(mode) && !commonPreference.hasDefaultValueForMode(mode)) { - setPreference(key, globalPrefsMap.get(key), mode); + settings.setPreference(key, globalPrefsMap.get(key), mode); } } } } } - SharedPreferences defaultProfilePreferences = (SharedPreferences) getProfilePreferences(ApplicationMode.DEFAULT); + SharedPreferences defaultProfilePreferences = (SharedPreferences) settings.getProfilePreferences(ApplicationMode.DEFAULT); Map defaultPrefsMap = defaultProfilePreferences.getAll(); for (String key : defaultPrefsMap.keySet()) { - OsmandPreference pref = getPreference(key); + OsmandPreference pref = settings.getPreference(key); if (pref instanceof CommonPreference) { - CommonPreference commonPreference = (CommonPreference) pref; - if (commonPreference.global && !commonPreference.isSet()) { - setPreference(key, defaultPrefsMap.get(key)); + CommonPreference commonPreference = (CommonPreference) pref; + if (commonPreference.isGlobal() && !commonPreference.isSet()) { + settings.setPreference(key, defaultPrefsMap.get(key)); } } } - for (OsmandPreference pref : generalPrefs) { + for (OsmandPreference pref : settings.getGeneralPrefs()) { if (pref instanceof CommonPreference) { - CommonPreference commonPref = (CommonPreference) pref; + CommonPreference commonPref = (CommonPreference) pref; Object defaultVal = commonPref.getModeValue(ApplicationMode.DEFAULT); for (ApplicationMode mode : ApplicationMode.allPossibleValues()) { if (!commonPref.isSetForMode(mode) && !commonPref.hasDefaultValueForMode(mode)) { - setPreference(commonPref.getId(), defaultVal, mode); + settings.setPreference(commonPref.getId(), defaultVal, mode); } } } } - String json = settingsAPI.getString(globalPreferences, "custom_app_profiles", ""); + String json = settings.getSettingsAPI().getString(settings.getGlobalPreferences(), "custom_app_profiles", ""); if (!Algorithms.isEmpty(json)) { Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); Type t = new TypeToken>() { @@ -252,22 +226,22 @@ class AppVersionUpgradeOnInit { List customProfiles = gson.fromJson(json, t); if (!Algorithms.isEmpty(customProfiles)) { for (ApplicationMode.ApplicationModeBean modeBean : customProfiles) { - ApplicationMode.ApplicationModeBuilder builder = ApplicationMode.fromModeBean(ctx, modeBean); - ApplicationMode.saveProfile(builder, ctx); + ApplicationMode.ApplicationModeBuilder builder = ApplicationMode.fromModeBean(app, modeBean); + ApplicationMode.saveProfile(builder, app); } } } } public void migrateEnumPreferences() { - for (OsmandPreference pref : registeredPreferences.values()) { + for (OsmandPreference pref : settings.getRegisteredPreferences().values()) { if (pref instanceof EnumStringPreference) { EnumStringPreference enumPref = (EnumStringPreference) pref; if (enumPref.isGlobal()) { - migrateEnumPref(enumPref, (SharedPreferences) globalPreferences); + migrateEnumPref(enumPref, (SharedPreferences) settings.getGlobalPreferences()); } else { for (ApplicationMode mode : ApplicationMode.allPossibleValues()) { - migrateEnumPref(enumPref, (SharedPreferences) getProfilePreferences(mode)); + migrateEnumPref(enumPref, (SharedPreferences) settings.getProfilePreferences(mode)); } } } @@ -278,15 +252,17 @@ class AppVersionUpgradeOnInit { Object value = sharedPreferences.getAll().get(enumPref.getId()); if (value instanceof Integer) { int enumIndex = (int) value; - if (enumIndex >= 0 && enumIndex < enumPref.values.length) { - Enum savedValue = enumPref.values[enumIndex]; + if (enumIndex >= 0 && enumIndex < enumPref.getValues().length) { + Enum savedValue = enumPref.getValues()[enumIndex]; enumPref.setValue(sharedPreferences, savedValue); } } } public void migrateHomeWorkParkingToFavorites() { - FavouritesDbHelper favorites = ctx.getFavorites(); + FavouritesDbHelper favorites = app.getFavorites(); + SettingsAPI settingsAPI = settings.getSettingsAPI(); + Object globalPreferences= settings.getGlobalPreferences(); LatLon homePoint = null; float lat = settingsAPI.getFloat(globalPreferences, "home_point_lat", 0); diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/BooleanAccessibilityPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanAccessibilityPreference.java index 7a796b6a6a..c376b6a99a 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/BooleanAccessibilityPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanAccessibilityPreference.java @@ -4,30 +4,27 @@ import net.osmand.plus.ApplicationMode; class BooleanAccessibilityPreference extends BooleanPreference { - private OsmandSettings osmandSettings; - BooleanAccessibilityPreference(OsmandSettings osmandSettings, String id, boolean defaultValue) { - super(id, defaultValue); - this.osmandSettings = osmandSettings; + super(osmandSettings, id, defaultValue); } @Override public Boolean get() { - return osmandSettings.ctx.accessibilityEnabled() ? super.get() : getDefaultValue(); + return getContext().accessibilityEnabled() ? super.get() : getDefaultValue(); } @Override public Boolean getModeValue(ApplicationMode mode) { - return osmandSettings.ctx.accessibilityEnabledForMode(mode) ? super.getModeValue(mode) : getDefaultValue(); + return getContext().accessibilityEnabledForMode(mode) ? super.getModeValue(mode) : getDefaultValue(); } @Override public boolean set(Boolean obj) { - return osmandSettings.ctx.accessibilityEnabled() && super.set(obj); + return getContext().accessibilityEnabled() && super.set(obj); } @Override public boolean setModeValue(ApplicationMode mode, Boolean obj) { - return osmandSettings.ctx.accessibilityEnabledForMode(mode) && super.setModeValue(mode, obj); + return getContext().accessibilityEnabledForMode(mode) && super.setModeValue(mode, obj); } } diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/BooleanPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanPreference.java index 3a1c0cd363..9a0c2a2391 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/BooleanPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanPreference.java @@ -7,13 +7,13 @@ public class BooleanPreference extends CommonPreference { } @Override - protected Boolean getValue(Object prefs, Boolean defaultValue) { - return osmandSettings.settingsAPI.getBoolean(prefs, getId(), defaultValue); + public Boolean getValue(Object prefs, Boolean defaultValue) { + return getSettingsAPI().getBoolean(prefs, getId(), defaultValue); } @Override protected boolean setValue(Object prefs, Boolean val) { - return osmandSettings.settingsAPI.edit(prefs).putBoolean(getId(), val).commit(); + return getSettingsAPI().edit(prefs).putBoolean(getId(), val).commit(); } @Override diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java index 4e1e69f1b4..0a53139dc1 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java @@ -1,6 +1,8 @@ package net.osmand.plus.settings.backend; import net.osmand.plus.ApplicationMode; +import net.osmand.plus.OsmandApplication; +import net.osmand.plus.api.SettingsAPI; import org.json.JSONException; import org.json.JSONObject; @@ -27,16 +29,27 @@ public abstract class CommonPreference extends PreferenceWithListener { } // Methods to possibly override - protected abstract T getValue(Object prefs, T defaultValue); + public abstract T getValue(Object prefs, T defaultValue); protected abstract boolean setValue(Object prefs, T val); public abstract T parseString(String s); protected String toString(T o) { - return o == null ? null : o.toString(); + return o == null ? null : o.toString(); } + protected SettingsAPI getSettingsAPI() { + return osmandSettings.getSettingsAPI(); + } + + protected ApplicationMode getApplicationMode() { + return osmandSettings.getApplicationMode(); + } + + protected OsmandApplication getContext() { + return osmandSettings.getContext(); + } // common methods diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsPreference.java index a671d6141b..4e562f1aca 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsPreference.java @@ -3,25 +3,23 @@ package net.osmand.plus.settings.backend; import androidx.annotation.NonNull; public class ContextMenuItemsPreference extends CommonPreference { - private OsmandSettings osmandSettings; @NonNull private String idScheme; ContextMenuItemsPreference(OsmandSettings osmandSettings, String id, @NonNull String idScheme, @NonNull ContextMenuItemsSettings defValue) { - super(id, defValue); - this.osmandSettings = osmandSettings; + super(osmandSettings, id, defValue); this.idScheme = idScheme; } @Override - protected ContextMenuItemsSettings getValue(Object prefs, ContextMenuItemsSettings defaultValue) { - String s = osmandSettings.settingsAPI.getString(prefs, getId(), ""); + public ContextMenuItemsSettings getValue(Object prefs, ContextMenuItemsSettings defaultValue) { + String s = getSettingsAPI().getString(prefs, getId(), ""); return readValue(s); } @Override protected boolean setValue(Object prefs, ContextMenuItemsSettings val) { - return osmandSettings.settingsAPI.edit(prefs).putString(getId(), val.writeToJsonString(idScheme)).commit(); + return getSettingsAPI().edit(prefs).putString(getId(), val.writeToJsonString(idScheme)).commit(); } diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsSettings.java b/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsSettings.java index 85046ba00a..822840a60e 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsSettings.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsSettings.java @@ -1,7 +1,9 @@ package net.osmand.plus.settings.backend; +import net.osmand.PlatformUtil; import net.osmand.util.Algorithms; +import org.apache.commons.logging.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -14,6 +16,9 @@ import java.util.List; import androidx.annotation.NonNull; public class ContextMenuItemsSettings implements Serializable { + + private static final Log LOG = PlatformUtil.getLog(ContextMenuItemsSettings.class.getName()); + private static final String HIDDEN = "hidden"; private static final String ORDER = "order"; private List hiddenIds = new ArrayList<>(); @@ -40,7 +45,7 @@ public class ContextMenuItemsSettings implements Serializable { JSONObject json = new JSONObject(jsonString); readFromJson(json, idScheme); } catch (JSONException e) { - OsmandSettings.LOG.error("Error converting to json string: " + e); + LOG.error("Error converting to json string: " + e); } } @@ -66,7 +71,7 @@ public class ContextMenuItemsSettings implements Serializable { writeToJson(json, idScheme); return json.toString(); } catch (JSONException e) { - OsmandSettings.LOG.error("Error converting to json string: " + e); + LOG.error("Error converting to json string: " + e); } return ""; } diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/EnumStringPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/EnumStringPreference.java index d8d01e4091..5d03d3e556 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/EnumStringPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/EnumStringPreference.java @@ -2,19 +2,17 @@ package net.osmand.plus.settings.backend; public class EnumStringPreference> extends CommonPreference { - private OsmandSettings osmandSettings; private final E[] values; EnumStringPreference(OsmandSettings osmandSettings, String id, E defaultValue, E[] values) { - super(id, defaultValue); - this.osmandSettings = osmandSettings; + super(osmandSettings, id, defaultValue); this.values = values; } @Override - protected E getValue(Object prefs, E defaultValue) { + public E getValue(Object prefs, E defaultValue) { try { - String name = osmandSettings.settingsAPI.getString(prefs, getId(), defaultValue.name()); + String name = getSettingsAPI().getString(prefs, getId(), defaultValue.name()); E value = parseString(name); return value != null ? value : defaultValue; } catch (ClassCastException ex) { @@ -24,8 +22,8 @@ public class EnumStringPreference> extends CommonPreference } @Override - protected boolean setValue(Object prefs, E val) { - return osmandSettings.settingsAPI.edit(prefs).putString(getId(), val.name()).commit(); + public boolean setValue(Object prefs, E val) { + return getSettingsAPI().edit(prefs).putString(getId(), val.name()).commit(); } @Override @@ -42,4 +40,8 @@ public class EnumStringPreference> extends CommonPreference } return null; } + + public E[] getValues() { + return values; + } } diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/FloatPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/FloatPreference.java index 9c10a314f9..47ee4a24bd 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/FloatPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/FloatPreference.java @@ -2,22 +2,18 @@ package net.osmand.plus.settings.backend; public class FloatPreference extends CommonPreference { - - private OsmandSettings osmandSettings; - FloatPreference(OsmandSettings osmandSettings, String id, float defaultValue) { - super(id, defaultValue); - this.osmandSettings = osmandSettings; + super(osmandSettings, id, defaultValue); } @Override - protected Float getValue(Object prefs, Float defaultValue) { - return osmandSettings.settingsAPI.getFloat(prefs, getId(), defaultValue); + public Float getValue(Object prefs, Float defaultValue) { + return getSettingsAPI().getFloat(prefs, getId(), defaultValue); } @Override protected boolean setValue(Object prefs, Float val) { - return osmandSettings.settingsAPI.edit(prefs).putFloat(getId(), val).commit(); + return getSettingsAPI().edit(prefs).putFloat(getId(), val).commit(); } @Override diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/ImpassableRoadsStorage.java b/OsmAnd/src/net/osmand/plus/settings/backend/ImpassableRoadsStorage.java index dacadbf149..1f890766c2 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/ImpassableRoadsStorage.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/ImpassableRoadsStorage.java @@ -11,12 +11,11 @@ import java.util.StringTokenizer; class ImpassableRoadsStorage extends SettingsMapPointsStorage { - private OsmandSettings osmandSettings; protected String roadsIdsKey; protected String appModeKey; public ImpassableRoadsStorage(OsmandSettings osmandSettings) { - this.osmandSettings = osmandSettings; + super(osmandSettings); pointsKey = OsmandSettings.IMPASSABLE_ROAD_POINTS; descriptionsKey = OsmandSettings.IMPASSABLE_ROADS_DESCRIPTIONS; roadsIdsKey = OsmandSettings.IMPASSABLE_ROADS_IDS; @@ -25,7 +24,7 @@ class ImpassableRoadsStorage extends SettingsMapPointsStorage { public List getRoadIds(int size) { List list = new ArrayList<>(); - String roadIds = osmandSettings.settingsAPI.getString(osmandSettings.globalPreferences, roadsIdsKey, ""); + String roadIds = getSettingsAPI().getString(getOsmandSettings().globalPreferences, roadsIdsKey, ""); if (roadIds.trim().length() > 0) { StringTokenizer tok = new StringTokenizer(roadIds, ","); while (tok.hasMoreTokens() && list.size() <= size) { @@ -40,7 +39,7 @@ class ImpassableRoadsStorage extends SettingsMapPointsStorage { public List getAppModeKeys(int size) { List list = new ArrayList<>(); - String roadIds = osmandSettings.settingsAPI.getString(osmandSettings.globalPreferences, appModeKey, ""); + String roadIds = getSettingsAPI().getString(getOsmandSettings().globalPreferences, appModeKey, ""); if (roadIds.trim().length() > 0) { StringTokenizer tok = new StringTokenizer(roadIds, ","); while (tok.hasMoreTokens() && list.size() <= size) { @@ -173,7 +172,7 @@ class ImpassableRoadsStorage extends SettingsMapPointsStorage { stringBuilder.append(","); } } - return osmandSettings.settingsAPI.edit(osmandSettings.globalPreferences) + return getSettingsAPI().edit(getOsmandSettings().globalPreferences) .putString(roadsIdsKey, stringBuilder.toString()) .commit(); } @@ -187,7 +186,7 @@ class ImpassableRoadsStorage extends SettingsMapPointsStorage { stringBuilder.append(","); } } - return osmandSettings.settingsAPI.edit(osmandSettings.globalPreferences) + return getSettingsAPI().edit(getOsmandSettings().globalPreferences) .putString(appModeKey, stringBuilder.toString()) .commit(); } diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/IntPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/IntPreference.java index 3c040821b9..92e0b9071c 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/IntPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/IntPreference.java @@ -2,22 +2,18 @@ package net.osmand.plus.settings.backend; class IntPreference extends CommonPreference { - - private OsmandSettings osmandSettings; - IntPreference(OsmandSettings osmandSettings, String id, int defaultValue) { - super(id, defaultValue); - this.osmandSettings = osmandSettings; + super(osmandSettings, id, defaultValue); } @Override - protected Integer getValue(Object prefs, Integer defaultValue) { - return osmandSettings.settingsAPI.getInt(prefs, getId(), defaultValue); + public Integer getValue(Object prefs, Integer defaultValue) { + return getSettingsAPI().getInt(prefs, getId(), defaultValue); } @Override protected boolean setValue(Object prefs, Integer val) { - return osmandSettings.settingsAPI.edit(prefs).putInt(getId(), val).commit(); + return getSettingsAPI().edit(prefs).putInt(getId(), val).commit(); } @Override diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/IntermediatePointsStorage.java b/OsmAnd/src/net/osmand/plus/settings/backend/IntermediatePointsStorage.java index aaf90f0efd..c420036da0 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/IntermediatePointsStorage.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/IntermediatePointsStorage.java @@ -6,10 +6,8 @@ import java.util.List; class IntermediatePointsStorage extends SettingsMapPointsStorage { - private OsmandSettings osmandSettings; - public IntermediatePointsStorage(OsmandSettings osmandSettings) { - this.osmandSettings = osmandSettings; + super(osmandSettings); pointsKey = OsmandSettings.INTERMEDIATE_POINTS; descriptionsKey = OsmandSettings.INTERMEDIATE_POINTS_DESCRIPTION; } @@ -17,7 +15,7 @@ class IntermediatePointsStorage extends SettingsMapPointsStorage { @Override public boolean savePoints(List ps, List ds) { boolean res = super.savePoints(ps, ds); - osmandSettings.backupTargetPoints(); + getOsmandSettings().backupTargetPoints(); return res; } } diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/ListStringPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/ListStringPreference.java index 81b7a01f60..ff611593cc 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/ListStringPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/ListStringPreference.java @@ -8,17 +8,15 @@ import java.util.List; public class ListStringPreference extends StringPreference { - private OsmandSettings osmandSettings; private String delimiter; ListStringPreference(OsmandSettings osmandSettings, String id, String defaultValue, String delimiter) { - super(id, defaultValue); - this.osmandSettings = osmandSettings; + super(osmandSettings, id, defaultValue); this.delimiter = delimiter; } public boolean addValue(String res) { - return addModeValue(osmandSettings.getApplicationMode(), res); + return addModeValue(getApplicationMode(), res); } public boolean addModeValue(ApplicationMode appMode, String res) { @@ -33,7 +31,7 @@ public class ListStringPreference extends StringPreference { } public void clearAll() { - clearAllForProfile(osmandSettings.getApplicationMode()); + clearAllForProfile(getApplicationMode()); } public void clearAllForProfile(ApplicationMode appMode) { @@ -41,7 +39,7 @@ public class ListStringPreference extends StringPreference { } public boolean containsValue(String res) { - return containsValue(osmandSettings.getApplicationMode(), res); + return containsValue(getApplicationMode(), res); } public boolean containsValue(ApplicationMode appMode, String res) { @@ -51,7 +49,7 @@ public class ListStringPreference extends StringPreference { } public boolean removeValue(String res) { - return removeValueForProfile(osmandSettings.getApplicationMode(), res); + return removeValueForProfile(getApplicationMode(), res); } public boolean removeValueForProfile(ApplicationMode appMode, String res) { @@ -75,7 +73,7 @@ public class ListStringPreference extends StringPreference { } public List getStringsList() { - return getStringsListForProfile(osmandSettings.getApplicationMode()); + return getStringsListForProfile(getApplicationMode()); } public List getStringsListForProfile(ApplicationMode appMode) { @@ -93,7 +91,7 @@ public class ListStringPreference extends StringPreference { } public void setStringsList(List values) { - setStringsListForProfile(osmandSettings.getApplicationMode(), values); + setStringsListForProfile(getApplicationMode(), values); } public void setStringsListForProfile(ApplicationMode appMode, List values) { diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/LongPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/LongPreference.java index 8993919e23..f36d8368a3 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/LongPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/LongPreference.java @@ -2,22 +2,18 @@ package net.osmand.plus.settings.backend; class LongPreference extends CommonPreference { - - private OsmandSettings osmandSettings; - LongPreference(OsmandSettings osmandSettings, String id, long defaultValue) { - super(id, defaultValue); - this.osmandSettings = osmandSettings; + super(osmandSettings, id, defaultValue); } @Override - protected Long getValue(Object prefs, Long defaultValue) { - return osmandSettings.settingsAPI.getLong(prefs, getId(), defaultValue); + public Long getValue(Object prefs, Long defaultValue) { + return getSettingsAPI().getLong(prefs, getId(), defaultValue); } @Override protected boolean setValue(Object prefs, Long val) { - return osmandSettings.settingsAPI.edit(prefs).putLong(getId(), val).commit(); + return getSettingsAPI().edit(prefs).putLong(getId(), val).commit(); } @Override diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndPreferencesDataStore.java b/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndPreferencesDataStore.java index 0a6f464b77..d4eaf070f2 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndPreferencesDataStore.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndPreferencesDataStore.java @@ -55,7 +55,7 @@ public class OsmAndPreferencesDataStore extends PreferenceDataStore { @Nullable @Override public String getString(String key, @Nullable String defValue) { - OsmandPreference preference = osmandSettings.getPreference(key); + OsmandPreference preference = osmandSettings.getPreference(key); if (preference instanceof StringPreference) { return ((StringPreference) preference).getModeValue(appMode); } else { @@ -75,25 +75,25 @@ public class OsmAndPreferencesDataStore extends PreferenceDataStore { @Override public int getInt(String key, int defValue) { - OsmandPreference preference = osmandSettings.getPreference(key); - if (preference instanceof OsmandSettings.IntPreference) { - return ((OsmandSettings.IntPreference) preference).getModeValue(appMode); + OsmandPreference preference = osmandSettings.getPreference(key); + if (preference instanceof IntPreference) { + return ((IntPreference) preference).getModeValue(appMode); } return defValue; } @Override public long getLong(String key, long defValue) { - OsmandPreference preference = osmandSettings.getPreference(key); - if (preference instanceof OsmandSettings.LongPreference) { - return ((OsmandSettings.LongPreference) preference).getModeValue(appMode); + OsmandPreference preference = osmandSettings.getPreference(key); + if (preference instanceof LongPreference) { + return ((LongPreference) preference).getModeValue(appMode); } return defValue; } @Override public float getFloat(String key, float defValue) { - OsmandPreference preference = osmandSettings.getPreference(key); + OsmandPreference preference = osmandSettings.getPreference(key); if (preference instanceof FloatPreference) { return ((FloatPreference) preference).getModeValue(appMode); } @@ -102,7 +102,7 @@ public class OsmAndPreferencesDataStore extends PreferenceDataStore { @Override public boolean getBoolean(String key, boolean defValue) { - OsmandPreference preference = osmandSettings.getPreference(key); + OsmandPreference preference = osmandSettings.getPreference(key); if (preference instanceof BooleanPreference) { return ((BooleanPreference) preference).getModeValue(appMode); } @@ -111,7 +111,7 @@ public class OsmAndPreferencesDataStore extends PreferenceDataStore { @Nullable public Object getValue(String key, Object defValue) { - OsmandPreference preference = osmandSettings.getPreference(key); + OsmandPreference preference = osmandSettings.getPreference(key); if (preference != null) { return preference.getModeValue(appMode); } diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java b/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java index 523caf7866..3a9cd36219 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java @@ -113,14 +113,13 @@ public class OsmandSettings { private boolean editObjectToShow; private String searchRequestToShow; - - protected OsmandSettings(OsmandApplication clientContext, SettingsAPI settinsAPI) { + public OsmandSettings(OsmandApplication clientContext, SettingsAPI settinsAPI) { ctx = clientContext; this.settingsAPI = settinsAPI; initPrefs(); } - protected OsmandSettings(OsmandApplication clientContext, SettingsAPI settinsAPI, String sharedPreferencesName) { + public OsmandSettings(OsmandApplication clientContext, SettingsAPI settinsAPI, String sharedPreferencesName) { ctx = clientContext; this.settingsAPI = settinsAPI; CUSTOM_SHARED_PREFERENCES_NAME = CUSTOM_SHARED_PREFERENCES_PREFIX + sharedPreferencesName; @@ -196,7 +195,7 @@ public class OsmandSettings { return settingsAPI.getPreferenceObject(getSharedPreferencesNameForKey(modeKey)); } - public OsmandPreference getPreference(String key) { + public OsmandPreference getPreference(String key) { return registeredPreferences.get(key); } @@ -301,7 +300,7 @@ public class OsmandSettings { } else if (preference instanceof EnumStringPreference) { EnumStringPreference enumPref = (EnumStringPreference) preference; if (value instanceof String) { - Enum enumValue = enumPref.parseString((String) value); + Enum enumValue = enumPref.parseString((String) value); if (enumValue != null) { return enumPref.setModeValue(mode, enumValue); } @@ -310,8 +309,8 @@ public class OsmandSettings { return enumPref.setModeValue(mode, value); } else if (value instanceof Integer) { int newVal = (Integer) value; - if (enumPref.values.length > newVal) { - Enum enumValue = enumPref.values[newVal]; + if (enumPref.getValues().length > newVal) { + Enum enumValue = enumPref.getValues()[newVal]; return enumPref.setModeValue(mode, enumValue); } return false; @@ -358,7 +357,7 @@ public class OsmandSettings { } private boolean prefCanBeCopiedOrReset(OsmandPreference pref) { - return pref instanceof CommonPreference && !((CommonPreference) pref).global + return pref instanceof CommonPreference && !((CommonPreference) pref).isGlobal() && !APP_MODE_ORDER.getId().equals(pref.getId()); } @@ -412,7 +411,7 @@ public class OsmandSettings { OsmandAidlApi aidlApi = ctx.getAidlApi(); if (aidlApi != null) { - ctx.poiFilters.loadSelectedPoiFilters(); + ctx.getPoiFilters().loadSelectedPoiFilters(); } fireEvent(oldMode); @@ -728,13 +727,13 @@ public class OsmandSettings { public final OsmandPreference DEFAULT_APPLICATION_MODE = new CommonPreference(this, "default_application_mode_string", ApplicationMode.DEFAULT) { @Override - protected ApplicationMode getValue(Object prefs, ApplicationMode defaultValue) { + public ApplicationMode getValue(Object prefs, ApplicationMode defaultValue) { String key = settingsAPI.getString(prefs, getId(), defaultValue.getStringKey()); return ApplicationMode.valueOfStringKey(key, defaultValue); } @Override - protected boolean setValue(Object prefs, ApplicationMode val) { + public boolean setValue(Object prefs, ApplicationMode val) { boolean valueSaved = settingsAPI.edit(prefs).putString(getId(), val.getStringKey()).commit(); if (valueSaved) { APPLICATION_MODE.set(val); @@ -774,13 +773,13 @@ public class OsmandSettings { public final OsmandPreference LAST_ROUTE_APPLICATION_MODE = new CommonPreference(this, "last_route_application_mode_backup_string", ApplicationMode.DEFAULT) { @Override - protected ApplicationMode getValue(Object prefs, ApplicationMode defaultValue) { + public ApplicationMode getValue(Object prefs, ApplicationMode defaultValue) { String key = settingsAPI.getString(prefs, getId(), defaultValue.getStringKey()); return ApplicationMode.valueOfStringKey(key, defaultValue); } @Override - protected boolean setValue(Object prefs, ApplicationMode val) { + public boolean setValue(Object prefs, ApplicationMode val) { return settingsAPI.edit(prefs).putString(getId(), val.getStringKey()).commit(); } @@ -818,7 +817,7 @@ public class OsmandSettings { public final CommonPreference DRIVING_REGION_AUTOMATIC = new BooleanPreference(this, "driving_region_automatic", true).makeProfile().cache(); public final OsmandPreference DRIVING_REGION = new EnumStringPreference(this, "default_driving_region", DrivingRegion.EUROPE_ASIA, DrivingRegion.values()) { - protected boolean setValue(Object prefs, DrivingRegion val) { + public boolean setValue(Object prefs, DrivingRegion val) { if (val != null) { METRIC_SYSTEM.set(val.defMetrics); } @@ -2067,10 +2066,10 @@ public class OsmandSettings { public final static String MY_LOC_POINT_LON = "my_loc_point_lon"; public final static String MY_LOC_POINT_DESCRIPTION = "my_loc_point_description"; - private static final String IMPASSABLE_ROAD_POINTS = "impassable_road_points"; - private static final String IMPASSABLE_ROADS_DESCRIPTIONS = "impassable_roads_descriptions"; - private static final String IMPASSABLE_ROADS_IDS = "impassable_roads_ids"; - private static final String IMPASSABLE_ROADS_APP_MODE_KEYS = "impassable_roads_app_mode_keys"; + public static final String IMPASSABLE_ROAD_POINTS = "impassable_road_points"; + public static final String IMPASSABLE_ROADS_DESCRIPTIONS = "impassable_roads_descriptions"; + public static final String IMPASSABLE_ROADS_IDS = "impassable_roads_ids"; + public static final String IMPASSABLE_ROADS_APP_MODE_KEYS = "impassable_roads_app_mode_keys"; public void backupPointToStart() { settingsAPI.edit(globalPreferences) @@ -2509,7 +2508,7 @@ public class OsmandSettings { @Nullable public ContextMenuItemsPreference getContextMenuItemsPreference(@NonNull String id) { for (ContextMenuItemsPreference preference : CONTEXT_MENU_ITEMS_PREFERENCES) { - if (id.startsWith(preference.idScheme)) { + if (id.startsWith(preference.getIdScheme())) { return preference; } } @@ -2745,6 +2744,55 @@ public class OsmandSettings { return res; } + public String[] getAppModeBeanPrefsIds() { + return new String[]{ + ICON_COLOR.getId(), + ICON_RES_NAME.getId(), + PARENT_APP_MODE.getId(), + ROUTING_PROFILE.getId(), + ROUTE_SERVICE.getId(), + USER_PROFILE_NAME.getId(), + LOCATION_ICON.getId(), + NAVIGATION_ICON.getId(), + APP_MODE_ORDER.getId() + }; + } + + public OsmandPreference[] getGeneralPrefs() { + return new OsmandPreference[]{ + EXTERNAL_INPUT_DEVICE, + CENTER_POSITION_ON_MAP, + ROTATE_MAP, + MAP_SCREEN_ORIENTATION, + LIVE_MONITORING_URL, + LIVE_MONITORING_MAX_INTERVAL_TO_SEND, + LIVE_MONITORING_INTERVAL, + LIVE_MONITORING, + SHOW_TRIP_REC_NOTIFICATION, + AUTO_SPLIT_RECORDING, + SAVE_TRACK_MIN_SPEED, + SAVE_TRACK_PRECISION, + SAVE_TRACK_MIN_DISTANCE, + SAVE_TRACK_INTERVAL, + TRACK_STORAGE_DIRECTORY, + SAVE_HEADING_TO_GPX, + DISABLE_RECORDING_ONCE_APP_KILLED, + SAVE_TRACK_TO_GPX, + SAVE_GLOBAL_TRACK_REMEMBER, + SAVE_GLOBAL_TRACK_INTERVAL, + MAP_EMPTY_STATE_ALLOWED, + DO_NOT_USE_ANIMATIONS, + USE_KALMAN_FILTER_FOR_COMPASS, + USE_MAGNETIC_FIELD_SENSOR_COMPASS, + USE_TRACKBALL_FOR_MOVEMENTS, + SPEED_SYSTEM, + ANGULAR_UNITS, + METRIC_SYSTEM, + DRIVING_REGION, + DRIVING_REGION_AUTOMATIC + }; + } + public enum DayNightMode { AUTO(R.string.daynight_mode_auto, R.drawable.ic_action_map_sunset), DAY(R.string.daynight_mode_day, R.drawable.ic_action_map_day), diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/SettingsHelper.java b/OsmAnd/src/net/osmand/plus/settings/backend/SettingsHelper.java index 50ee1c028e..1c6c003021 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/SettingsHelper.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/SettingsHelper.java @@ -906,18 +906,6 @@ public class SettingsHelper { } } - String[] - appModeBeanPrefsIds = new String[] { - ICON_COLOR.getId(), - ICON_RES_NAME.getId(), - PARENT_APP_MODE.getId(), - ROUTING_PROFILE.getId(), - ROUTE_SERVICE.getId(), - USER_PROFILE_NAME.getId(), - LOCATION_ICON.getId(), - NAVIGATION_ICON.getId(), - APP_MODE_ORDER.getId() - }; public static class ProfileSettingsItem extends OsmandSettingsItem { @@ -947,7 +935,7 @@ public class SettingsHelper { @Override protected void init() { super.init(); - appModeBeanPrefsIds = new HashSet<>(Arrays.asList(app.getSettings().appModeBeanPrefsIds)); + appModeBeanPrefsIds = new HashSet<>(Arrays.asList(app.getSettings().getAppModeBeanPrefsIds())); } @NonNull diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/SettingsMapPointsStorage.java b/OsmAnd/src/net/osmand/plus/settings/backend/SettingsMapPointsStorage.java index cdb923ed23..46c5bc1f3d 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/SettingsMapPointsStorage.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/SettingsMapPointsStorage.java @@ -2,6 +2,7 @@ package net.osmand.plus.settings.backend; import net.osmand.data.LatLon; import net.osmand.data.PointDescription; +import net.osmand.plus.api.SettingsAPI; import net.osmand.plus.helpers.SearchHistoryHelper; import java.util.ArrayList; @@ -19,9 +20,17 @@ abstract class SettingsMapPointsStorage { this.osmandSettings = osmandSettings; } + protected SettingsAPI getSettingsAPI() { + return osmandSettings.getSettingsAPI(); + } + + protected OsmandSettings getOsmandSettings() { + return osmandSettings; + } + public List getPointDescriptions(int sz) { List list = new ArrayList<>(); - String ip = osmandSettings.settingsAPI.getString(osmandSettings.globalPreferences, descriptionsKey, ""); + String ip = getSettingsAPI().getString(osmandSettings.globalPreferences, descriptionsKey, ""); if (ip.trim().length() > 0) { list.addAll(Arrays.asList(ip.split("--"))); } @@ -36,7 +45,7 @@ abstract class SettingsMapPointsStorage { public List getPoints() { List list = new ArrayList<>(); - String ip = osmandSettings.settingsAPI.getString(osmandSettings.globalPreferences, pointsKey, ""); + String ip = getSettingsAPI().getString(osmandSettings.globalPreferences, pointsKey, ""); if (ip.trim().length() > 0) { StringTokenizer tok = new StringTokenizer(ip, ","); while (tok.hasMoreTokens()) { @@ -56,8 +65,8 @@ abstract class SettingsMapPointsStorage { List ds = getPointDescriptions(ps.size()); ps.add(index, new LatLon(latitude, longitude)); ds.add(index, PointDescription.serializeToString(historyDescription)); - if (historyDescription != null && !historyDescription.isSearchingAddress(osmandSettings.ctx)) { - SearchHistoryHelper.getInstance(osmandSettings.ctx).addNewItemToHistory(latitude, longitude, historyDescription); + if (historyDescription != null && !historyDescription.isSearchingAddress(osmandSettings.getContext())) { + SearchHistoryHelper.getInstance(osmandSettings.getContext()).addNewItemToHistory(latitude, longitude, historyDescription); } return savePoints(ps, ds); } @@ -68,8 +77,8 @@ abstract class SettingsMapPointsStorage { int i = ps.indexOf(new LatLon(latitude, longitude)); if (i != -1) { ds.set(i, PointDescription.serializeToString(historyDescription)); - if (historyDescription != null && !historyDescription.isSearchingAddress(osmandSettings.ctx)) { - SearchHistoryHelper.getInstance(osmandSettings.ctx).addNewItemToHistory(latitude, longitude, historyDescription); + if (historyDescription != null && !historyDescription.isSearchingAddress(osmandSettings.getContext())) { + SearchHistoryHelper.getInstance(osmandSettings.getContext()).addNewItemToHistory(latitude, longitude, historyDescription); } return savePoints(ps, ds); } else { @@ -121,7 +130,7 @@ abstract class SettingsMapPointsStorage { tb.append(ds.get(i)); } } - return osmandSettings.settingsAPI.edit(osmandSettings.globalPreferences) + return getSettingsAPI().edit(osmandSettings.globalPreferences) .putString(pointsKey, sb.toString()) .putString(descriptionsKey, tb.toString()) .commit(); diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/StringPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/StringPreference.java index 3ee07b43bd..e0c98404be 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/StringPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/StringPreference.java @@ -2,21 +2,18 @@ package net.osmand.plus.settings.backend; public class StringPreference extends CommonPreference { - private OsmandSettings osmandSettings; - StringPreference(OsmandSettings osmandSettings, String id, String defaultValue) { - super(id, defaultValue); - this.osmandSettings = osmandSettings; + super(osmandSettings, id, defaultValue); } @Override - protected String getValue(Object prefs, String defaultValue) { - return osmandSettings.settingsAPI.getString(prefs, getId(), defaultValue); + public String getValue(Object prefs, String defaultValue) { + return getSettingsAPI().getString(prefs, getId(), defaultValue); } @Override protected boolean setValue(Object prefs, String val) { - return osmandSettings.settingsAPI.edit(prefs).putString(getId(), (val != null) ? val.trim() : val).commit(); + return getSettingsAPI().edit(prefs).putString(getId(), (val != null) ? val.trim() : val).commit(); } @Override From 878129ce93c17b688fc516530ef3806d10d59cb9 Mon Sep 17 00:00:00 2001 From: simon Date: Wed, 7 Oct 2020 17:01:51 +0300 Subject: [PATCH 21/95] photos added --- .../builders/cards/IPFSImageCard.java | 47 +++++ .../builders/cards/ImageCard.java | 183 +++++++++--------- 2 files changed, 143 insertions(+), 87 deletions(-) create mode 100644 OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/IPFSImageCard.java diff --git a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/IPFSImageCard.java b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/IPFSImageCard.java new file mode 100644 index 0000000000..b029c7cdfc --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/IPFSImageCard.java @@ -0,0 +1,47 @@ +package net.osmand.plus.mapcontextmenu.builders.cards; + +import android.view.View; +import net.osmand.plus.activities.MapActivity; +import net.osmand.util.Algorithms; +import org.json.JSONException; +import org.json.JSONObject; + +public class IPFSImageCard extends ImageCard { + private static final String BASE_URL = "https://test.openplacereviews.org/api/ipfs/image-ipfs?cid="; + + public IPFSImageCard(MapActivity mapActivity, JSONObject imageObject) { + super(mapActivity, imageObject); + try { + this.url = BASE_URL + imageObject.get("cid"); + this.imageHiresUrl = BASE_URL + imageObject.get("cid"); + this.imageUrl = BASE_URL + imageObject.get("cid"); + } catch (JSONException e) { + e.printStackTrace(); + } + if (!Algorithms.isEmpty(getSuitableUrl())) { + View.OnClickListener onClickListener = new View.OnClickListener() { + @Override + public void onClick(View v) { + openUrl(getMapActivity(), getMyApplication(), getTitle(), getSuitableUrl(), + isExternalLink() || Algorithms.isEmpty(getImageHiresUrl()), + !Algorithms.isEmpty(getImageHiresUrl())); + } + }; + if (!Algorithms.isEmpty(buttonText)) { + this.onButtonClickListener = onClickListener; + } else { + this.onClickListener = onClickListener; + } + } + } + + private String getSuitableUrl() { + final String url; + if (Algorithms.isEmpty(getImageHiresUrl())) { + url = getUrl(); + } else { + url = getImageHiresUrl(); + } + return url; + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java index 84a63cb72a..667b234956 100644 --- a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java +++ b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java @@ -4,6 +4,7 @@ import android.content.res.ColorStateList; import android.graphics.Bitmap; import android.graphics.PointF; import android.graphics.drawable.Drawable; +import android.net.TrafficStats; import android.os.AsyncTask; import android.view.View; import android.view.View.OnClickListener; @@ -15,10 +16,9 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatButton; -import net.osmand.AndroidNetworkUtils; -import net.osmand.AndroidUtils; -import net.osmand.GPXUtilities; -import net.osmand.Location; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import net.osmand.*; import net.osmand.data.Amenity; import net.osmand.data.FavouritePoint; import net.osmand.data.LatLon; @@ -28,6 +28,7 @@ import net.osmand.plus.OsmandApplication; import net.osmand.plus.R; import net.osmand.plus.Version; import net.osmand.plus.activities.MapActivity; +import net.osmand.plus.activities.SettingsBaseActivity; import net.osmand.plus.mapcontextmenu.MenuBuilder; import net.osmand.plus.mapillary.MapillaryContributeCard; import net.osmand.plus.mapillary.MapillaryImageCard; @@ -36,6 +37,7 @@ import net.osmand.plus.views.layers.ContextMenuLayer; import net.osmand.plus.wikimedia.WikiImageHelper; import net.osmand.util.Algorithms; +import org.apache.commons.logging.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -43,12 +45,7 @@ import org.json.JSONObject; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; +import java.util.*; import static net.osmand.data.FavouritePoint.DEFAULT_BACKGROUND_TYPE; @@ -57,6 +54,7 @@ public abstract class ImageCard extends AbstractCard { public static String TYPE_MAPILLARY_PHOTO = "mapillary-photo"; public static String TYPE_MAPILLARY_CONTRIBUTE = "mapillary-contribute"; + private static final Log LOG = PlatformUtil.getLog(ImageCard.class); protected String type; // Image location protected LatLon location; @@ -200,6 +198,14 @@ public abstract class ImageCard extends AbstractCard { return imageCard; } + private static ImageCard createCardOpr(MapActivity mapActivity, JSONObject imageObject) { + ImageCard imageCard = null; + if (imageObject.has("cid")) { + imageCard = new IPFSImageCard(mapActivity, imageObject); + } + return imageCard; + } + public double getCa() { return ca; } @@ -430,101 +436,104 @@ public abstract class ImageCard extends AbstractCard { @Override protected List doInBackground(Void... params) { + final int THREAD_ID = 10104; + TrafficStats.setThreadStatsTag(THREAD_ID); List result = new ArrayList<>(); RotatedTileBox rtb = mapActivity.getMapView().getCurrentRotatedTileBox(); Object o = mapActivity.getMapLayers().getContextMenuLayer().getSelectedObject(); - if (this.params != null) { - String wikidataId = this.params.get(Amenity.WIKIDATA); - if (wikidataId != null) { - this.params.remove(Amenity.WIKIDATA); - WikiImageHelper.addWikidataImageCards(mapActivity, wikidataId, result); - } - String wikimediaContent = this.params.get(Amenity.WIKIMEDIA_COMMONS); - if (wikimediaContent != null) { - this.params.remove(Amenity.WIKIMEDIA_COMMONS); - WikiImageHelper.addWikimediaImageCards(mapActivity, wikimediaContent, result); - } - } if (o instanceof Amenity) { Amenity am = (Amenity) o; - System.out.println("POINT OSM ID: " + am.getId() + " " + am.getType().ordinal()); + long amenityId = (am.getId() >> 1); + getPicturesForPlace(result, amenityId); + } + try { final Map pms = new LinkedHashMap<>(); - pms.put("osmid", "" + am.getId()); + pms.put("lat", "" + (float) latLon.getLatitude()); + pms.put("lon", "" + (float) latLon.getLongitude()); + Location myLocation = app.getLocationProvider().getLastKnownLocation(); + if (myLocation != null) { + pms.put("mloc", "" + (float) myLocation.getLatitude() + "," + (float) myLocation.getLongitude()); + } + pms.put("app", Version.isPaidVersion(app) ? "paid" : "free"); + String preferredLang = app.getSettings().MAP_PREFERRED_LOCALE.get(); + if (Algorithms.isEmpty(preferredLang)) { + preferredLang = app.getLanguage(); + } + if (!Algorithms.isEmpty(preferredLang)) { + pms.put("lang", preferredLang); + } + if (this.params != null) { + String wikidataId = this.params.get(Amenity.WIKIDATA); + if (wikidataId != null) { + this.params.remove(Amenity.WIKIDATA); + WikiImageHelper.addWikidataImageCards(mapActivity, wikidataId, result); + } + String wikimediaContent = this.params.get(Amenity.WIKIMEDIA_COMMONS); + if (wikimediaContent != null) { + this.params.remove(Amenity.WIKIMEDIA_COMMONS); + WikiImageHelper.addWikimediaImageCards(mapActivity, wikimediaContent, result); + } + pms.putAll(this.params); + } String response = AndroidNetworkUtils.sendRequest(app, "https://osmand.net/api/cm_place", pms, "Requesting location images...", false, false); if (!Algorithms.isEmpty(response)) { - JSONObject obj = null; - try { - obj = new JSONObject(response); - JSONArray images = null; - images = obj.getJSONArray("features"); - if (images.length() > 0) { - for (int i = 0; i < images.length(); i++) { - try { - JSONObject imageObject = (JSONObject) images.get(i); - if (imageObject != JSONObject.NULL) { - ImageCard imageCard = ImageCard.createCard(mapActivity, imageObject); - if (imageCard != null) { - result.add(imageCard); - } + JSONObject obj = new JSONObject(response); + JSONArray images = obj.getJSONArray("features"); + if (images.length() > 0) { + for (int i = 0; i < images.length(); i++) { + try { + JSONObject imageObject = (JSONObject) images.get(i); + if (imageObject != JSONObject.NULL) { + ImageCard imageCard = ImageCard.createCard(mapActivity, imageObject); + if (imageCard != null) { + result.add(imageCard); } - } catch (JSONException e) { - e.printStackTrace(); } + } catch (JSONException e) { + e.printStackTrace(); } } - } catch (JSONException e) { - e.printStackTrace(); } } + } catch (Exception e) { + e.printStackTrace(); + } + if (listener != null) { + listener.onPostProcess(result); } return result; -// try { -// final Map pms = new LinkedHashMap<>(); -// pms.put("lat", "" + (float) latLon.getLatitude()); -// pms.put("lon", "" + (float) latLon.getLongitude()); -// Location myLocation = app.getLocationProvider().getLastKnownLocation(); -// if (myLocation != null) { -// pms.put("mloc", "" + (float) myLocation.getLatitude() + "," + (float) myLocation.getLongitude()); -// } -// pms.put("app", Version.isPaidVersion(app) ? "paid" : "free"); -// String preferredLang = app.getSettings().MAP_PREFERRED_LOCALE.get(); -// if (Algorithms.isEmpty(preferredLang)) { -// preferredLang = app.getLanguage(); -// } -// if (!Algorithms.isEmpty(preferredLang)) { -// pms.put("lang", preferredLang); -// } -// String response = AndroidNetworkUtils.sendRequest(app, "https://osmand.net/api/cm_place", pms, -// "Requesting location images...", false, false); -// -// if (!Algorithms.isEmpty(response)) { -// JSONObject obj = new JSONObject(response); -// JSONArray images = obj.getJSONArray("features"); -// if (images.length() > 0) { -// for (int i = 0; i < images.length(); i++) { -// try { -// JSONObject imageObject = (JSONObject) images.get(i); -// if (imageObject != JSONObject.NULL) { -// ImageCard imageCard = ImageCard.createCard(mapActivity, imageObject); -// if (imageCard != null) { -// result.add(imageCard); -// } -// } -// } catch (JSONException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// if (listener != null) { -// listener.onPostProcess(result); -// } -// return result; + } + + private void getPicturesForPlace(List result, long l) { + String url = "https://test.openplacereviews.org/api/objects-by-index?type=opr.place&index=osmid&limit=1&key=" + l; + String response = AndroidNetworkUtils.sendRequest(app, url, Collections.emptyMap(), + "Requesting location images...", false, false); + + try { + if (!Algorithms.isEmpty(response)) { + JSONArray obj = new JSONObject(response).getJSONArray("objects"); + JSONArray images = ((JSONObject) ((JSONObject) obj.get(0)).get("images")).getJSONArray("outdoor"); + if (images.length() > 0) { + for (int i = 0; i < images.length(); i++) { + try { + JSONObject imageObject = (JSONObject) images.get(i); + if (imageObject != JSONObject.NULL) { + ImageCard imageCard = ImageCard.createCardOpr(mapActivity, imageObject); + if (imageCard != null) { + result.add(imageCard); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + } + } catch (Exception e) { + LOG.error(e); + } } @Override From 2867736814b406309807724440bd6af34654ad37 Mon Sep 17 00:00:00 2001 From: Dima-1 Date: Wed, 7 Oct 2020 23:08:57 +0300 Subject: [PATCH 22/95] refactor OsmandSettings remove Enum --- .../plus/inapp/InAppPurchaseHelperImpl.java | 3 +- .../plus/inapp/InAppPurchaseHelperImpl.java | 2 +- OsmAnd/src/net/osmand/FileUtils.java | 13 + OsmAnd/src/net/osmand/aidl/ConnectedApp.java | 1 - .../src/net/osmand/plus/AppInitializer.java | 2 +- .../osmand/plus/AppVersionUpgradeOnInit.java | 19 +- .../net/osmand/plus/ContextMenuAdapter.java | 3 - .../net/osmand/plus/GpxSelectionHelper.java | 2 +- .../src/net/osmand/plus/OsmAndFormatter.java | 6 +- .../net/osmand/plus/OsmandApplication.java | 19 +- .../osmand/plus/activities/MapActivity.java | 2 +- .../plus/activities/SettingsBaseActivity.java | 3 - .../activities/SettingsGeneralActivity.java | 6 +- .../SettingsNavigationActivity.java | 11 +- .../osmand/plus/audionotes/NotesFragment.java | 1 - .../plus/audionotes/NotesSortByMode.java | 14 + .../SortByMenuBottomSheetDialogFragment.java | 1 - .../dashboard/DashChooseAppDirFragment.java | 5 +- .../plus/development/TestVoiceActivity.java | 2 +- .../osmand/plus/dialogs/ConfigureMapMenu.java | 12 +- .../plus/dialogs/DetailsBottomSheet.java | 2 +- .../osmand/plus/dialogs/RasterMapMenu.java | 6 +- .../ui/DataStoragePlaceDialogFragment.java | 5 +- .../DayNightHelper.java | 4 +- .../net/osmand/plus/helpers/GpxUiHelper.java | 43 +- .../osmand/plus/helpers/WaypointHelper.java | 13 +- .../plus/helpers/enums/AngularConstants.java | 28 + .../plus/helpers/enums/AutoZoomMap.java | 19 + .../plus/helpers/enums/DayNightMode.java | 62 ++ .../plus/helpers/enums/DrivingRegion.java | 62 ++ .../plus/helpers/enums/MetricsConstants.java | 30 + .../plus/helpers/enums/SpeedConstants.java | 33 + .../plus/helpers/enums/TracksSortByMode.java | 38 ++ .../plus/liveupdates/LiveUpdatesFragment.java | 2 +- .../MapContextMenuFragment.java | 3 +- .../builders/AmenityMenuBuilder.java | 9 +- .../DirectionIndicationDialogFragment.java | 1 - .../plus/mapmarkers/MapMarkersMode.java | 37 ++ .../OptionsBottomSheetDialogFragment.java | 3 +- .../SelectFileBottomSheet.java | 2 +- .../plus/myplaces/AvailableGPXFragment.java | 2 +- .../TrackActivityFragmentAdapter.java | 2 - .../parkingpoint/ParkingPositionPlugin.java | 6 - .../actions/DayNightModeAction.java | 7 +- .../LayerTransparencySeekbarMode.java | 22 + .../plus/rastermaps/MapOverlayAction.java | 3 +- .../plus/rastermaps/MapUnderlayAction.java | 1 - .../rastermaps/OsmandRasterMapsPlugin.java | 10 +- .../MapRouteInfoMenu.java | 3 - .../osmand/plus/routing/RouteProvider.java | 3 - .../osmand/plus/routing/RoutingHelper.java | 5 +- .../BooleanAccessibilityPreference.java | 2 - .../backend/BooleanStringPreference.java | 25 + .../settings/backend/CommonPreference.java | 1 - .../backend/ListStringPreference.java | 2 - .../backend/OsmAndPreferencesDataStore.java | 2 - .../settings/backend/OsmandPreference.java | 1 - .../plus/settings/backend/OsmandSettings.java | 583 ++++-------------- .../ChangeDataStorageBottomSheet.java | 4 +- ...ecalculateRouteInDeviationBottomSheet.java | 5 +- .../fragments/DataStorageFragment.java | 3 +- .../GeneralProfileSettingsFragment.java | 31 +- .../MapDuringNavigationFragment.java | 8 +- .../fragments/RouteParametersFragment.java | 1 - .../fragments/VehicleParametersFragment.java | 4 +- .../fragments/VoiceAnnouncesFragment.java | 3 +- .../preferences/ListPreferenceEx.java | 1 - .../osmand/plus/srtmplugin/SRTMPlugin.java | 1 - .../plus/srtmplugin/TerrainFragment.java | 5 +- .../osmand/plus/srtmplugin/TerrainLayer.java | 3 +- .../osmand/plus/srtmplugin/TerrainMode.java | 6 + .../plus/track/ShowStartFinishCard.java | 3 +- .../plus/track/TrackAppearanceFragment.java | 4 +- .../osmand/plus/views/layers/GPXLayer.java | 2 +- .../plus/views/layers/MapControlsLayer.java | 5 +- .../plus/views/layers/RulerControlLayer.java | 9 +- .../osmand/plus/views/layers/RulerMode.java | 7 + .../mapwidgets/MapInfoWidgetsFactory.java | 5 +- .../mapwidgets/RouteInfoWidgetsFactory.java | 2 - .../views/mapwidgets/widgets/AlarmWidget.java | 7 +- .../views/mapwidgets/widgets/RulerWidget.java | 2 +- .../widgetstates/BearingWidgetState.java | 4 +- .../widgetstates/CompassRulerWidgetState.java | 2 +- .../widgetstates/TimeWidgetState.java | 2 +- .../voice/AbstractPrologCommandPlayer.java | 2 +- .../WikiArticleBaseDialogFragment.java | 3 +- .../plus/wikipedia/WikiArticleShowImages.java | 15 + ...pediaOptionsBottomSheetDialogFragment.java | 1 - .../WikivoyageShowPicturesDialogFragment.java | 2 +- .../WikivoyageArticleDialogFragment.java | 2 +- ...oyageOptionsBottomSheetDialogFragment.java | 2 +- 91 files changed, 703 insertions(+), 662 deletions(-) create mode 100644 OsmAnd/src/net/osmand/plus/audionotes/NotesSortByMode.java rename OsmAnd/src/net/osmand/plus/{activities => helpers}/DayNightHelper.java (98%) create mode 100644 OsmAnd/src/net/osmand/plus/helpers/enums/AngularConstants.java create mode 100644 OsmAnd/src/net/osmand/plus/helpers/enums/AutoZoomMap.java create mode 100644 OsmAnd/src/net/osmand/plus/helpers/enums/DayNightMode.java create mode 100644 OsmAnd/src/net/osmand/plus/helpers/enums/DrivingRegion.java create mode 100644 OsmAnd/src/net/osmand/plus/helpers/enums/MetricsConstants.java create mode 100644 OsmAnd/src/net/osmand/plus/helpers/enums/SpeedConstants.java create mode 100644 OsmAnd/src/net/osmand/plus/helpers/enums/TracksSortByMode.java create mode 100644 OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersMode.java create mode 100644 OsmAnd/src/net/osmand/plus/rastermaps/LayerTransparencySeekbarMode.java create mode 100644 OsmAnd/src/net/osmand/plus/settings/backend/BooleanStringPreference.java create mode 100644 OsmAnd/src/net/osmand/plus/srtmplugin/TerrainMode.java create mode 100644 OsmAnd/src/net/osmand/plus/views/layers/RulerMode.java create mode 100644 OsmAnd/src/net/osmand/plus/wikipedia/WikiArticleShowImages.java diff --git a/OsmAnd/src-google/net/osmand/plus/inapp/InAppPurchaseHelperImpl.java b/OsmAnd/src-google/net/osmand/plus/inapp/InAppPurchaseHelperImpl.java index c6925a5e63..5bd9f2cb23 100644 --- a/OsmAnd/src-google/net/osmand/plus/inapp/InAppPurchaseHelperImpl.java +++ b/OsmAnd/src-google/net/osmand/plus/inapp/InAppPurchaseHelperImpl.java @@ -23,6 +23,7 @@ import net.osmand.plus.inapp.InAppPurchases.InAppPurchase; import net.osmand.plus.inapp.InAppPurchases.InAppSubscription; import net.osmand.plus.inapp.InAppPurchasesImpl.InAppPurchaseLiveUpdatesOldSubscription; import net.osmand.plus.inapp.util.BillingManager; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.srtmplugin.SRTMPlugin; import net.osmand.util.Algorithms; @@ -407,7 +408,7 @@ public class InAppPurchaseHelperImpl extends InAppPurchaseHelper { } } } - OsmandSettings.OsmandPreference subscriptionCancelledTime = ctx.getSettings().LIVE_UPDATES_PURCHASE_CANCELLED_TIME; + OsmandPreference subscriptionCancelledTime = ctx.getSettings().LIVE_UPDATES_PURCHASE_CANCELLED_TIME; if (!subscribedToLiveUpdates && ctx.getSettings().LIVE_UPDATES_PURCHASED.get()) { if (subscriptionCancelledTime.get() == 0) { subscriptionCancelledTime.set(System.currentTimeMillis()); diff --git a/OsmAnd/src-huawei/net/osmand/plus/inapp/InAppPurchaseHelperImpl.java b/OsmAnd/src-huawei/net/osmand/plus/inapp/InAppPurchaseHelperImpl.java index c3d6fc193c..0f3536e5d0 100644 --- a/OsmAnd/src-huawei/net/osmand/plus/inapp/InAppPurchaseHelperImpl.java +++ b/OsmAnd/src-huawei/net/osmand/plus/inapp/InAppPurchaseHelperImpl.java @@ -31,7 +31,7 @@ import net.osmand.plus.inapp.InAppPurchases.InAppSubscription; import net.osmand.plus.inapp.InAppPurchases.InAppSubscriptionIntroductoryInfo; import net.osmand.plus.inapp.InAppPurchasesImpl.InAppPurchaseLiveUpdatesOldSubscription; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.util.Algorithms; import java.lang.ref.WeakReference; diff --git a/OsmAnd/src/net/osmand/FileUtils.java b/OsmAnd/src/net/osmand/FileUtils.java index 65ea676356..1f9a755be5 100644 --- a/OsmAnd/src/net/osmand/FileUtils.java +++ b/OsmAnd/src/net/osmand/FileUtils.java @@ -223,6 +223,19 @@ public class FileUtils { return tempDir; } + public static boolean isWritable(File dirToTest) { + boolean isWriteable; + try { + dirToTest.mkdirs(); + File writeTestFile = File.createTempFile("osmand_", ".tmp", dirToTest); + isWriteable = writeTestFile.exists(); + writeTestFile.delete(); + } catch (IOException e) { + isWriteable = false; + } + return isWriteable; + } + public interface RenameCallback { void renamedTo(File file); } diff --git a/OsmAnd/src/net/osmand/aidl/ConnectedApp.java b/OsmAnd/src/net/osmand/aidl/ConnectedApp.java index 0d4c9bc36b..be25ab931d 100644 --- a/OsmAnd/src/net/osmand/aidl/ConnectedApp.java +++ b/OsmAnd/src/net/osmand/aidl/ConnectedApp.java @@ -22,7 +22,6 @@ import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.settings.backend.ApplicationMode; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; import net.osmand.plus.views.OsmandMapLayer; import net.osmand.plus.views.layers.AidlMapLayer; import net.osmand.plus.views.layers.MapInfoLayer; diff --git a/OsmAnd/src/net/osmand/plus/AppInitializer.java b/OsmAnd/src/net/osmand/plus/AppInitializer.java index 0ae24b7c5f..78364460a7 100644 --- a/OsmAnd/src/net/osmand/plus/AppInitializer.java +++ b/OsmAnd/src/net/osmand/plus/AppInitializer.java @@ -28,7 +28,7 @@ import net.osmand.map.OsmandRegions.RegionTranslation; import net.osmand.map.WorldRegion; import net.osmand.osm.AbstractPoiType; import net.osmand.osm.MapPoiTypes; -import net.osmand.plus.activities.DayNightHelper; +import net.osmand.plus.helpers.DayNightHelper; import net.osmand.plus.activities.LocalIndexHelper; import net.osmand.plus.activities.LocalIndexInfo; import net.osmand.plus.activities.SavingTrackHelper; diff --git a/OsmAnd/src/net/osmand/plus/AppVersionUpgradeOnInit.java b/OsmAnd/src/net/osmand/plus/AppVersionUpgradeOnInit.java index 0ab61f725a..49e354ea8b 100644 --- a/OsmAnd/src/net/osmand/plus/AppVersionUpgradeOnInit.java +++ b/OsmAnd/src/net/osmand/plus/AppVersionUpgradeOnInit.java @@ -10,6 +10,7 @@ import com.google.gson.reflect.TypeToken; import net.osmand.data.FavouritePoint; import net.osmand.data.LatLon; import net.osmand.plus.api.SettingsAPI; +import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.EnumStringPreference; import net.osmand.plus.settings.backend.OsmandPreference; @@ -18,6 +19,7 @@ import net.osmand.util.Algorithms; import java.lang.reflect.Type; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -133,7 +135,7 @@ class AppVersionUpgradeOnInit { startPrefs.edit().putInt(VERSION_INSTALLED_NUMBER, VERSION_3_7_01).commit(); } if (prevAppVersion < VERSION_3_8_00) { - app.getSettings().migrateQuickActionStates(); + migrateQuickActionStates(); startPrefs.edit().putInt(VERSION_INSTALLED_NUMBER, VERSION_3_8_00).commit(); } startPrefs.edit().putInt(VERSION_INSTALLED_NUMBER, lastVersion).commit(); @@ -253,6 +255,21 @@ class AppVersionUpgradeOnInit { } } + public void migrateQuickActionStates() { + String quickActionsJson = settings.getSettingsAPI().getString(settings.getGlobalPreferences(), "quick_action_new", ""); + if (!Algorithms.isEmpty(quickActionsJson)) { + Gson gson = new GsonBuilder().create(); + Type type = new TypeToken>() { + }.getType(); + HashMap quickActions = gson.fromJson(quickActionsJson, type); + if (!Algorithms.isEmpty(quickActions)) { + for (ApplicationMode mode : ApplicationMode.allPossibleValues()) { + settings.setQuickActions(quickActions, mode); + } + } + } + } + private void migrateEnumPref(EnumStringPreference enumPref, SharedPreferences sharedPreferences) { Object value = sharedPreferences.getAll().get(enumPref.getId()); if (value instanceof Integer) { diff --git a/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java b/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java index c076f75ee2..c6226d6615 100644 --- a/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java +++ b/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java @@ -38,9 +38,6 @@ import net.osmand.plus.dialogs.HelpArticleDialogFragment; import net.osmand.plus.helpers.AndroidUiHelper; import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.settings.backend.OsmAndAppCustomization; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.ContextMenuItemsPreference; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; import net.osmand.plus.settings.backend.ContextMenuItemsPreference; import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.util.Algorithms; diff --git a/OsmAnd/src/net/osmand/plus/GpxSelectionHelper.java b/OsmAnd/src/net/osmand/plus/GpxSelectionHelper.java index 7217e8af5f..923bbe646a 100644 --- a/OsmAnd/src/net/osmand/plus/GpxSelectionHelper.java +++ b/OsmAnd/src/net/osmand/plus/GpxSelectionHelper.java @@ -29,7 +29,7 @@ import net.osmand.plus.helpers.GpxUiHelper; import net.osmand.plus.helpers.GpxUiHelper.GPXDataSetAxisType; import net.osmand.plus.helpers.GpxUiHelper.GPXDataSetType; import net.osmand.plus.routing.RouteProvider; -import net.osmand.plus.settings.backend.OsmandSettings.MetricsConstants; +import net.osmand.plus.helpers.enums.MetricsConstants; import net.osmand.plus.track.GpxSplitType; import net.osmand.plus.track.GradientScaleType; import net.osmand.util.Algorithms; diff --git a/OsmAnd/src/net/osmand/plus/OsmAndFormatter.java b/OsmAnd/src/net/osmand/plus/OsmAndFormatter.java index 2ac142d06a..b58b3eba5e 100644 --- a/OsmAnd/src/net/osmand/plus/OsmAndFormatter.java +++ b/OsmAnd/src/net/osmand/plus/OsmAndFormatter.java @@ -15,9 +15,9 @@ import net.osmand.osm.PoiCategory; import net.osmand.osm.PoiType; import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.AngularConstants; -import net.osmand.plus.settings.backend.OsmandSettings.MetricsConstants; -import net.osmand.plus.settings.backend.OsmandSettings.SpeedConstants; +import net.osmand.plus.helpers.enums.AngularConstants; +import net.osmand.plus.helpers.enums.MetricsConstants; +import net.osmand.plus.helpers.enums.SpeedConstants; import net.osmand.util.Algorithms; import java.text.DateFormatSymbols; diff --git a/OsmAnd/src/net/osmand/plus/OsmandApplication.java b/OsmAnd/src/net/osmand/plus/OsmandApplication.java index 43c3a17f09..1a48650a4d 100644 --- a/OsmAnd/src/net/osmand/plus/OsmandApplication.java +++ b/OsmAnd/src/net/osmand/plus/OsmandApplication.java @@ -30,6 +30,7 @@ import androidx.multidex.MultiDex; import androidx.multidex.MultiDexApplication; import net.osmand.AndroidUtils; +import net.osmand.FileUtils; import net.osmand.IndexConstants; import net.osmand.PlatformUtil; import net.osmand.access.AccessibilityPlugin; @@ -42,7 +43,7 @@ import net.osmand.osm.MapPoiTypes; import net.osmand.osm.io.NetworkUtils; import net.osmand.plus.AppInitializer.AppInitializeListener; import net.osmand.plus.access.AccessibilityMode; -import net.osmand.plus.activities.DayNightHelper; +import net.osmand.plus.helpers.DayNightHelper; import net.osmand.plus.activities.ExitActivity; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.SavingTrackHelper; @@ -56,7 +57,9 @@ import net.osmand.plus.download.DownloadIndexesThread; import net.osmand.plus.download.DownloadService; import net.osmand.plus.download.IndexItem; import net.osmand.plus.helpers.AvoidSpecificRoads; +import net.osmand.plus.helpers.enums.DrivingRegion; import net.osmand.plus.helpers.LockHelper; +import net.osmand.plus.helpers.enums.MetricsConstants; import net.osmand.plus.helpers.WaypointHelper; import net.osmand.plus.inapp.InAppPurchaseHelper; import net.osmand.plus.mapmarkers.MapMarkersDbHelper; @@ -189,7 +192,7 @@ public class OsmandApplication extends MultiDexApplication { osmandSettings.initExternalStorageDirectory(); } externalStorageDirectory = osmandSettings.getExternalStorageDirectory(); - if (!OsmandSettings.isWritable(externalStorageDirectory)) { + if (!FileUtils.isWritable(externalStorageDirectory)) { externalStorageDirectoryReadOnly = true; externalStorageDirectory = osmandSettings.getInternalAppPath(); } @@ -983,15 +986,15 @@ public class OsmandApplication extends MultiDexApplication { } public void setupDrivingRegion(WorldRegion reg) { - OsmandSettings.DrivingRegion drg = null; + DrivingRegion drg = null; WorldRegion.RegionParams params = reg.getParams(); // boolean americanSigns = "american".equals(params.getRegionRoadSigns()); boolean leftHand = "yes".equals(params.getRegionLeftHandDriving()); - OsmandSettings.MetricsConstants mc1 = "miles".equals(params.getRegionMetric()) ? - OsmandSettings.MetricsConstants.MILES_AND_FEET : OsmandSettings.MetricsConstants.KILOMETERS_AND_METERS; - OsmandSettings.MetricsConstants mc2 = "miles".equals(params.getRegionMetric()) ? - OsmandSettings.MetricsConstants.MILES_AND_METERS : OsmandSettings.MetricsConstants.KILOMETERS_AND_METERS; - for (OsmandSettings.DrivingRegion r : OsmandSettings.DrivingRegion.values()) { + MetricsConstants mc1 = "miles".equals(params.getRegionMetric()) ? + MetricsConstants.MILES_AND_FEET : MetricsConstants.KILOMETERS_AND_METERS; + MetricsConstants mc2 = "miles".equals(params.getRegionMetric()) ? + MetricsConstants.MILES_AND_METERS : MetricsConstants.KILOMETERS_AND_METERS; + for (DrivingRegion r : DrivingRegion.values()) { if (r.leftHandDriving == leftHand && (r.defMetrics == mc1 || r.defMetrics == mc2)) { drg = r; break; diff --git a/OsmAnd/src/net/osmand/plus/activities/MapActivity.java b/OsmAnd/src/net/osmand/plus/activities/MapActivity.java index 8533c9c463..083c95d279 100644 --- a/OsmAnd/src/net/osmand/plus/activities/MapActivity.java +++ b/OsmAnd/src/net/osmand/plus/activities/MapActivity.java @@ -74,6 +74,7 @@ import net.osmand.plus.OsmAndConstants; import net.osmand.plus.OsmAndLocationSimulation; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; +import net.osmand.plus.helpers.DayNightHelper; import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; @@ -132,7 +133,6 @@ import net.osmand.plus.search.QuickSearchDialogFragment.QuickSearchTab; import net.osmand.plus.search.QuickSearchDialogFragment.QuickSearchType; import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.settings.backend.OsmAndAppCustomization.OsmAndAppCustomizationListener; -import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.fragments.BaseSettingsFragment; import net.osmand.plus.settings.fragments.BaseSettingsFragment.SettingsScreenType; import net.osmand.plus.settings.fragments.ConfigureProfileFragment; diff --git a/OsmAnd/src/net/osmand/plus/activities/SettingsBaseActivity.java b/OsmAnd/src/net/osmand/plus/activities/SettingsBaseActivity.java index 58f0b57029..316de777b0 100644 --- a/OsmAnd/src/net/osmand/plus/activities/SettingsBaseActivity.java +++ b/OsmAnd/src/net/osmand/plus/activities/SettingsBaseActivity.java @@ -32,9 +32,6 @@ import net.osmand.plus.R; import net.osmand.plus.profiles.AppProfileArrayAdapter; import net.osmand.plus.profiles.ProfileDataObject; import net.osmand.plus.settings.backend.ApplicationMode; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; import org.apache.commons.logging.Log; diff --git a/OsmAnd/src/net/osmand/plus/activities/SettingsGeneralActivity.java b/OsmAnd/src/net/osmand/plus/activities/SettingsGeneralActivity.java index aaf206ca06..225384349c 100644 --- a/OsmAnd/src/net/osmand/plus/activities/SettingsGeneralActivity.java +++ b/OsmAnd/src/net/osmand/plus/activities/SettingsGeneralActivity.java @@ -42,9 +42,9 @@ import net.osmand.osm.io.NetworkUtils; import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.AngularConstants; -import net.osmand.plus.settings.backend.OsmandSettings.DrivingRegion; -import net.osmand.plus.settings.backend.OsmandSettings.MetricsConstants; +import net.osmand.plus.helpers.enums.AngularConstants; +import net.osmand.plus.helpers.enums.DrivingRegion; +import net.osmand.plus.helpers.enums.MetricsConstants; import net.osmand.plus.R; import net.osmand.plus.Version; import net.osmand.plus.base.MapViewTrackingUtilities; diff --git a/OsmAnd/src/net/osmand/plus/activities/SettingsNavigationActivity.java b/OsmAnd/src/net/osmand/plus/activities/SettingsNavigationActivity.java index 89c0806d0a..a0a5c74992 100644 --- a/OsmAnd/src/net/osmand/plus/activities/SettingsNavigationActivity.java +++ b/OsmAnd/src/net/osmand/plus/activities/SettingsNavigationActivity.java @@ -34,11 +34,12 @@ import net.osmand.plus.ContextMenuAdapter; import net.osmand.plus.ContextMenuItem; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.helpers.enums.MetricsConstants; import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.AutoZoomMap; +import net.osmand.plus.helpers.enums.AutoZoomMap; import net.osmand.plus.settings.backend.OsmandPreference; -import net.osmand.plus.settings.backend.OsmandSettings.SpeedConstants; +import net.osmand.plus.helpers.enums.SpeedConstants; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.Version; @@ -49,10 +50,6 @@ import net.osmand.plus.routepreparationmenu.RoutingOptionsHelper; import net.osmand.plus.routing.RouteProvider.RouteService; import net.osmand.plus.routing.RoutingHelper; import net.osmand.plus.settings.backend.ApplicationMode; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.AutoZoomMap; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; -import net.osmand.plus.settings.backend.OsmandSettings.SpeedConstants; import net.osmand.plus.voice.CommandPlayer; import net.osmand.router.GeneralRouter; import net.osmand.router.GeneralRouter.GeneralRouterProfile; @@ -176,7 +173,7 @@ public class SettingsNavigationActivity extends SettingsBaseActivity { //array size must be equal! Float[] speedLimitsKmhPos = new Float[]{0f, 5f, 7f, 10f, 15f, 20f}; Float[] speedLimitsMphPos = new Float[]{0f, 3f, 5f, 7f, 10f, 15f}; - if (settings.METRIC_SYSTEM.get() == OsmandSettings.MetricsConstants.KILOMETERS_AND_METERS) { + if (settings.METRIC_SYSTEM.get() == MetricsConstants.KILOMETERS_AND_METERS) { String[] speedNames = new String[speedLimitsKmh.length]; String[] speedNamesPos = new String[speedLimitsKmhPos.length]; for (int i = 0; i < speedLimitsKmh.length; i++) { diff --git a/OsmAnd/src/net/osmand/plus/audionotes/NotesFragment.java b/OsmAnd/src/net/osmand/plus/audionotes/NotesFragment.java index 09acdca8d8..8e911b04fc 100644 --- a/OsmAnd/src/net/osmand/plus/audionotes/NotesFragment.java +++ b/OsmAnd/src/net/osmand/plus/audionotes/NotesFragment.java @@ -38,7 +38,6 @@ import net.osmand.PlatformUtil; import net.osmand.data.PointDescription; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; -import net.osmand.plus.settings.backend.OsmandSettings.NotesSortByMode; import net.osmand.plus.R; import net.osmand.plus.Version; import net.osmand.plus.activities.ActionBarProgressActivity; diff --git a/OsmAnd/src/net/osmand/plus/audionotes/NotesSortByMode.java b/OsmAnd/src/net/osmand/plus/audionotes/NotesSortByMode.java new file mode 100644 index 0000000000..cf791dbf26 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/audionotes/NotesSortByMode.java @@ -0,0 +1,14 @@ +package net.osmand.plus.audionotes; + +public enum NotesSortByMode { + BY_TYPE, + BY_DATE; + + public boolean isByType() { + return this == BY_TYPE; + } + + public boolean isByDate() { + return this == BY_DATE; + } +} diff --git a/OsmAnd/src/net/osmand/plus/audionotes/SortByMenuBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/audionotes/SortByMenuBottomSheetDialogFragment.java index 2e228874b0..06fa83f6ca 100644 --- a/OsmAnd/src/net/osmand/plus/audionotes/SortByMenuBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/audionotes/SortByMenuBottomSheetDialogFragment.java @@ -4,7 +4,6 @@ import android.os.Bundle; import android.view.View; import net.osmand.plus.settings.backend.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.NotesSortByMode; import net.osmand.plus.R; import net.osmand.plus.base.MenuBottomSheetDialogFragment; import net.osmand.plus.base.bottomsheetmenu.BaseBottomSheetItem; diff --git a/OsmAnd/src/net/osmand/plus/dashboard/DashChooseAppDirFragment.java b/OsmAnd/src/net/osmand/plus/dashboard/DashChooseAppDirFragment.java index 9f37cd1b41..883010ea46 100644 --- a/OsmAnd/src/net/osmand/plus/dashboard/DashChooseAppDirFragment.java +++ b/OsmAnd/src/net/osmand/plus/dashboard/DashChooseAppDirFragment.java @@ -30,6 +30,7 @@ import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import net.osmand.AndroidUtils; +import net.osmand.FileUtils; import net.osmand.ValueHolder; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; @@ -113,7 +114,7 @@ public class DashChooseAppDirFragment { boolean copyFiles = !currentAppFile.getAbsolutePath().equals(selectedFile.getAbsolutePath()) && !mapsCopied; warningReadonly.setVisibility(copyFiles ? View.VISIBLE : View.GONE); if (copyFiles) { - if (!OsmandSettings.isWritable(currentAppFile)) { + if (!FileUtils.isWritable(currentAppFile)) { warningReadonly.setText(activity.getString(R.string.android_19_location_disabled, currentAppFile.getAbsolutePath())); } else { @@ -385,7 +386,7 @@ public class DashChooseAppDirFragment { @Override public void onClick(View v) { - boolean wr = OsmandSettings.isWritable(selectedFile); + boolean wr = FileUtils.isWritable(selectedFile); if (wr) { boolean changed = !currentAppFile.getAbsolutePath().equals(selectedFile.getAbsolutePath()); getMyApplication().setExternalStorageDirectory(type, selectedFile.getAbsolutePath()); diff --git a/OsmAnd/src/net/osmand/plus/development/TestVoiceActivity.java b/OsmAnd/src/net/osmand/plus/development/TestVoiceActivity.java index 2e4dfc3dfb..a9a0ba563e 100644 --- a/OsmAnd/src/net/osmand/plus/development/TestVoiceActivity.java +++ b/OsmAnd/src/net/osmand/plus/development/TestVoiceActivity.java @@ -151,7 +151,7 @@ public class TestVoiceActivity extends OsmandActionBarActivity { v += "\n \u25CF BT SCO: The current app profile is not set to use 'Phone call audio'."; } - //OsmandSettings.OsmandPreference pref = ((OsmandApplication) getApplication()).getSettings().VOICE_PROMPT_DELAY[stream]; + //OsmandPreference pref = ((OsmandApplication) getApplication()).getSettings().VOICE_PROMPT_DELAY[stream]; //if(pref != null) { // v += "\n \u25CF Voice prompt delay for selected output: " + pref.get() + "\u00A0ms"; //} diff --git a/OsmAnd/src/net/osmand/plus/dialogs/ConfigureMapMenu.java b/OsmAnd/src/net/osmand/plus/dialogs/ConfigureMapMenu.java index 97534b5bdf..1c01808be8 100644 --- a/OsmAnd/src/net/osmand/plus/dialogs/ConfigureMapMenu.java +++ b/OsmAnd/src/net/osmand/plus/dialogs/ConfigureMapMenu.java @@ -33,6 +33,7 @@ import net.osmand.plus.ContextMenuItem; import net.osmand.plus.DialogListItemAdapter; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; +import net.osmand.plus.helpers.enums.DayNightMode; import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.CommonPreference; @@ -44,9 +45,6 @@ import net.osmand.plus.activities.SettingsActivity; import net.osmand.plus.inapp.InAppPurchaseHelper; import net.osmand.plus.poi.PoiUIFilter; import net.osmand.plus.render.RendererRegistry; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.ListStringPreference; import net.osmand.plus.srtmplugin.SRTMPlugin; import net.osmand.plus.transport.TransportLinesMenu; import net.osmand.plus.views.OsmandMapTileView; @@ -311,7 +309,7 @@ public class ConfigureMapMenu { DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT); String sunriseTime = dateFormat.format(sunriseSunset.getSunrise()); String sunsetTime = dateFormat.format(sunriseSunset.getSunset()); - OsmandSettings.DayNightMode dayNightMode = activity.getMyApplication().getSettings().DAYNIGHT_MODE.get(); + DayNightMode dayNightMode = activity.getMyApplication().getSettings().DAYNIGHT_MODE.get(); if (dayNightMode.isDay() || dayNightMode.isNight()) { if (sunriseSunset.isDaytime()) { description = String.format(app.getString(R.string.sunset_at), sunsetTime); @@ -338,9 +336,9 @@ public class ConfigureMapMenu { final OsmandMapTileView view = activity.getMapView(); AlertDialog.Builder bld = new AlertDialog.Builder(new ContextThemeWrapper(view.getContext(), themeRes)); bld.setTitle(R.string.daynight); - final String[] items = new String[OsmandSettings.DayNightMode.values().length]; + final String[] items = new String[DayNightMode.values().length]; for (int i = 0; i < items.length; i++) { - items[i] = OsmandSettings.DayNightMode.values()[i].toHumanString(app); + items[i] = DayNightMode.values()[i].toHumanString(app); } int i = view.getSettings().DAYNIGHT_MODE.get().ordinal(); bld.setNegativeButton(R.string.shared_string_dismiss, null); @@ -349,7 +347,7 @@ public class ConfigureMapMenu { @Override public void onClick(View v) { int which = (int) v.getTag(); - view.getSettings().DAYNIGHT_MODE.set(OsmandSettings.DayNightMode.values()[which]); + view.getSettings().DAYNIGHT_MODE.set(DayNightMode.values()[which]); refreshMapComplete(activity); activity.getDashboard().refreshContent(true); // adapter.getItem(pos).setDescription(s, getDayNightDescr(activity)); diff --git a/OsmAnd/src/net/osmand/plus/dialogs/DetailsBottomSheet.java b/OsmAnd/src/net/osmand/plus/dialogs/DetailsBottomSheet.java index 4e8febb56e..ecb8f04b86 100644 --- a/OsmAnd/src/net/osmand/plus/dialogs/DetailsBottomSheet.java +++ b/OsmAnd/src/net/osmand/plus/dialogs/DetailsBottomSheet.java @@ -27,7 +27,7 @@ import net.osmand.plus.base.bottomsheetmenu.BottomSheetItemTwoChoicesButton.OnBo import net.osmand.plus.base.bottomsheetmenu.BottomSheetItemWithCompoundButton; import net.osmand.plus.base.bottomsheetmenu.simpleitems.DividerItem; import net.osmand.plus.helpers.FontCache; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.bottomsheets.BasePreferenceBottomSheet; import net.osmand.render.RenderingRuleProperty; import net.osmand.render.RenderingRuleStorageProperties; diff --git a/OsmAnd/src/net/osmand/plus/dialogs/RasterMapMenu.java b/OsmAnd/src/net/osmand/plus/dialogs/RasterMapMenu.java index e5414bd0b4..8219cc5a23 100644 --- a/OsmAnd/src/net/osmand/plus/dialogs/RasterMapMenu.java +++ b/OsmAnd/src/net/osmand/plus/dialogs/RasterMapMenu.java @@ -12,7 +12,7 @@ import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.LayerTransparencySeekbarMode; +import net.osmand.plus.rastermaps.LayerTransparencySeekbarMode; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.MapActivityLayers; @@ -182,8 +182,8 @@ public class RasterMapMenu { @NonNull public static Boolean isSeekbarVisible(OsmandApplication app, RasterMapType type) { - final OsmandSettings.LayerTransparencySeekbarMode currentMapTypeSeekbarMode = - type == RasterMapType.OVERLAY ? OsmandSettings.LayerTransparencySeekbarMode.OVERLAY : OsmandSettings.LayerTransparencySeekbarMode.UNDERLAY; + final LayerTransparencySeekbarMode currentMapTypeSeekbarMode = + type == RasterMapType.OVERLAY ? LayerTransparencySeekbarMode.OVERLAY : LayerTransparencySeekbarMode.UNDERLAY; LayerTransparencySeekbarMode seekbarMode = app.getSettings().LAYER_TRANSPARENCY_SEEKBAR_MODE.get(); return seekbarMode == LayerTransparencySeekbarMode.UNDEFINED || seekbarMode == currentMapTypeSeekbarMode; } diff --git a/OsmAnd/src/net/osmand/plus/download/ui/DataStoragePlaceDialogFragment.java b/OsmAnd/src/net/osmand/plus/download/ui/DataStoragePlaceDialogFragment.java index dceeac1862..f97784cb36 100644 --- a/OsmAnd/src/net/osmand/plus/download/ui/DataStoragePlaceDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/download/ui/DataStoragePlaceDialogFragment.java @@ -21,6 +21,7 @@ import androidx.annotation.NonNull; import androidx.fragment.app.FragmentManager; import net.osmand.AndroidUtils; +import net.osmand.FileUtils; import net.osmand.IProgress; import net.osmand.plus.OnDismissDialogFragmentListener; import net.osmand.plus.OsmandApplication; @@ -71,7 +72,7 @@ public class DataStoragePlaceDialogFragment extends BottomSheetDialogFragment { File internalStorage = getInternalStorageDirectory(activity); File external1Storage = getExternal1StorageDirectory(activity); - if (external1Storage != null && external1Storage.exists() && OsmandSettings.isWritable(external1Storage)) { + if (external1Storage != null && external1Storage.exists() && FileUtils.isWritable(external1Storage)) { deviceStorage = external1Storage; deviceStorageType = OsmandSettings.EXTERNAL_STORAGE_TYPE_EXTERNAL_FILE; deviceStorageName = getString(R.string.storage_directory_external); @@ -246,7 +247,7 @@ public class DataStoragePlaceDialogFragment extends BottomSheetDialogFragment { }; public boolean saveFilesLocation(int type, File selectedFile, Activity context) { - boolean wr = OsmandSettings.isWritable(selectedFile); + boolean wr = FileUtils.isWritable(selectedFile); if (wr) { ((OsmandApplication) context.getApplication()) .setExternalStorageDirectory(type, selectedFile.getAbsolutePath()); diff --git a/OsmAnd/src/net/osmand/plus/activities/DayNightHelper.java b/OsmAnd/src/net/osmand/plus/helpers/DayNightHelper.java similarity index 98% rename from OsmAnd/src/net/osmand/plus/activities/DayNightHelper.java rename to OsmAnd/src/net/osmand/plus/helpers/DayNightHelper.java index f9ca2afca4..ea4f6a1ae7 100644 --- a/OsmAnd/src/net/osmand/plus/activities/DayNightHelper.java +++ b/OsmAnd/src/net/osmand/plus/helpers/DayNightHelper.java @@ -1,4 +1,4 @@ -package net.osmand.plus.activities; +package net.osmand.plus.helpers; import java.util.Date; @@ -8,9 +8,9 @@ import java.util.TimeZone; import net.osmand.Location; import net.osmand.PlatformUtil; import net.osmand.StateChangedListener; +import net.osmand.plus.helpers.enums.DayNightMode; import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings.DayNightMode; import net.osmand.util.SunriseSunset; import org.apache.commons.logging.Log; diff --git a/OsmAnd/src/net/osmand/plus/helpers/GpxUiHelper.java b/OsmAnd/src/net/osmand/plus/helpers/GpxUiHelper.java index 2305d1beec..47650dc2ec 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/GpxUiHelper.java +++ b/OsmAnd/src/net/osmand/plus/helpers/GpxUiHelper.java @@ -80,6 +80,8 @@ import net.osmand.plus.OsmAndConstants; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; +import net.osmand.plus.helpers.enums.MetricsConstants; +import net.osmand.plus.helpers.enums.SpeedConstants; import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; @@ -95,7 +97,6 @@ import net.osmand.plus.dialogs.GpxAppearanceAdapter; import net.osmand.plus.dialogs.GpxAppearanceAdapter.AppearanceListItem; import net.osmand.plus.monitoring.OsmandMonitoringPlugin; import net.osmand.plus.routing.RouteCalculationResult; -import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.render.RenderingRuleProperty; import net.osmand.render.RenderingRulesStorage; import net.osmand.router.RouteStatisticsHelper; @@ -1041,7 +1042,7 @@ public class GpxUiHelper { private static float setupAxisDistance(OsmandApplication ctx, AxisBase axisBase, float meters) { OsmandSettings settings = ctx.getSettings(); - OsmandSettings.MetricsConstants mc = settings.METRIC_SYSTEM.get(); + MetricsConstants mc = settings.METRIC_SYSTEM.get(); float divX; String format1 = "{0,number,0.#} "; @@ -1050,10 +1051,10 @@ public class GpxUiHelper { float granularity = 1f; int mainUnitStr; float mainUnitInMeters; - if (mc == OsmandSettings.MetricsConstants.KILOMETERS_AND_METERS) { + if (mc == MetricsConstants.KILOMETERS_AND_METERS) { mainUnitStr = R.string.km; mainUnitInMeters = METERS_IN_KILOMETER; - } else if (mc == OsmandSettings.MetricsConstants.NAUTICAL_MILES) { + } else if (mc == MetricsConstants.NAUTICAL_MILES) { mainUnitStr = R.string.nm; mainUnitInMeters = METERS_IN_ONE_NAUTICALMILE; } else { @@ -1067,10 +1068,10 @@ public class GpxUiHelper { if (meters >= 100 * mainUnitInMeters || meters > 9.99f * mainUnitInMeters || meters > 0.999f * mainUnitInMeters || - mc == OsmandSettings.MetricsConstants.MILES_AND_FEET && meters > 0.249f * mainUnitInMeters || - mc == OsmandSettings.MetricsConstants.MILES_AND_METERS && meters > 0.249f * mainUnitInMeters || - mc == OsmandSettings.MetricsConstants.MILES_AND_YARDS && meters > 0.249f * mainUnitInMeters || - mc == OsmandSettings.MetricsConstants.NAUTICAL_MILES && meters > 0.99f * mainUnitInMeters) { + mc == MetricsConstants.MILES_AND_FEET && meters > 0.249f * mainUnitInMeters || + mc == MetricsConstants.MILES_AND_METERS && meters > 0.249f * mainUnitInMeters || + mc == MetricsConstants.MILES_AND_YARDS && meters > 0.249f * mainUnitInMeters || + mc == MetricsConstants.NAUTICAL_MILES && meters > 0.99f * mainUnitInMeters) { divX = mainUnitInMeters; if (fmt == null) { @@ -1080,13 +1081,13 @@ public class GpxUiHelper { } else { fmt = null; granularity = 1f; - if (mc == OsmandSettings.MetricsConstants.KILOMETERS_AND_METERS || mc == OsmandSettings.MetricsConstants.MILES_AND_METERS) { + if (mc == MetricsConstants.KILOMETERS_AND_METERS || mc == MetricsConstants.MILES_AND_METERS) { divX = 1f; mainUnitStr = R.string.m; - } else if (mc == OsmandSettings.MetricsConstants.MILES_AND_FEET) { + } else if (mc == MetricsConstants.MILES_AND_FEET) { divX = 1f / FEET_IN_ONE_METER; mainUnitStr = R.string.foot; - } else if (mc == OsmandSettings.MetricsConstants.MILES_AND_YARDS) { + } else if (mc == MetricsConstants.MILES_AND_YARDS) { divX = 1f / YARDS_IN_ONE_METER; mainUnitStr = R.string.yard; } else { @@ -1308,8 +1309,8 @@ public class GpxUiHelper { boolean drawFilled, boolean calcWithoutGaps) { OsmandSettings settings = ctx.getSettings(); - OsmandSettings.MetricsConstants mc = settings.METRIC_SYSTEM.get(); - boolean useFeet = (mc == OsmandSettings.MetricsConstants.MILES_AND_FEET) || (mc == OsmandSettings.MetricsConstants.MILES_AND_YARDS); + MetricsConstants mc = settings.METRIC_SYSTEM.get(); + boolean useFeet = (mc == MetricsConstants.MILES_AND_FEET) || (mc == MetricsConstants.MILES_AND_YARDS); boolean light = settings.isLightContent(); final float convEle = useFeet ? 3.28084f : 1.0f; @@ -1410,19 +1411,19 @@ public class GpxUiHelper { divX = setupAxisDistance(ctx, xAxis, calcWithoutGaps ? analysis.totalDistanceWithoutGaps : analysis.totalDistance); } - OsmandSettings.SpeedConstants sps = settings.SPEED_SYSTEM.get(); + SpeedConstants sps = settings.SPEED_SYSTEM.get(); float mulSpeed = Float.NaN; float divSpeed = Float.NaN; final String mainUnitY = sps.toShortString(ctx); - if (sps == OsmandSettings.SpeedConstants.KILOMETERS_PER_HOUR) { + if (sps == SpeedConstants.KILOMETERS_PER_HOUR) { mulSpeed = 3.6f; - } else if (sps == OsmandSettings.SpeedConstants.MILES_PER_HOUR) { + } else if (sps == SpeedConstants.MILES_PER_HOUR) { mulSpeed = 3.6f * METERS_IN_KILOMETER / METERS_IN_ONE_MILE; - } else if (sps == OsmandSettings.SpeedConstants.NAUTICALMILES_PER_HOUR) { + } else if (sps == SpeedConstants.NAUTICALMILES_PER_HOUR) { mulSpeed = 3.6f * METERS_IN_KILOMETER / METERS_IN_ONE_NAUTICALMILE; - } else if (sps == OsmandSettings.SpeedConstants.MINUTES_PER_KILOMETER) { + } else if (sps == SpeedConstants.MINUTES_PER_KILOMETER) { divSpeed = METERS_IN_KILOMETER / 60; - } else if (sps == OsmandSettings.SpeedConstants.MINUTES_PER_MILE) { + } else if (sps == SpeedConstants.MINUTES_PER_MILE) { divSpeed = METERS_IN_ONE_MILE / 60; } else { mulSpeed = 1f; @@ -1573,8 +1574,8 @@ public class GpxUiHelper { } OsmandSettings settings = ctx.getSettings(); boolean light = settings.isLightContent(); - OsmandSettings.MetricsConstants mc = settings.METRIC_SYSTEM.get(); - boolean useFeet = (mc == OsmandSettings.MetricsConstants.MILES_AND_FEET) || (mc == OsmandSettings.MetricsConstants.MILES_AND_YARDS); + MetricsConstants mc = settings.METRIC_SYSTEM.get(); + boolean useFeet = (mc == MetricsConstants.MILES_AND_FEET) || (mc == MetricsConstants.MILES_AND_YARDS); final float convEle = useFeet ? 3.28084f : 1.0f; final float totalDistance = calcWithoutGaps ? analysis.totalDistanceWithoutGaps : analysis.totalDistance; diff --git a/OsmAnd/src/net/osmand/plus/helpers/WaypointHelper.java b/OsmAnd/src/net/osmand/plus/helpers/WaypointHelper.java index b143653754..7f20de3e60 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/WaypointHelper.java +++ b/OsmAnd/src/net/osmand/plus/helpers/WaypointHelper.java @@ -24,6 +24,9 @@ import net.osmand.plus.TargetPointsHelper.TargetPoint; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.IntermediatePointsDialog; import net.osmand.plus.base.PointImageDrawable; +import net.osmand.plus.helpers.enums.DrivingRegion; +import net.osmand.plus.helpers.enums.MetricsConstants; +import net.osmand.plus.helpers.enums.SpeedConstants; import net.osmand.plus.poi.PoiUIFilter; import net.osmand.plus.render.RenderingIcons; import net.osmand.plus.routing.AlarmInfo; @@ -31,8 +34,6 @@ import net.osmand.plus.routing.AlarmInfo.AlarmInfoType; import net.osmand.plus.routing.RouteCalculationResult; import net.osmand.plus.routing.VoiceRouter; import net.osmand.plus.settings.backend.ApplicationMode; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.MetricsConstants; import net.osmand.util.MapUtils; import java.util.ArrayList; @@ -193,7 +194,7 @@ public class WaypointHelper { return found; } - public AlarmInfo getMostImportantAlarm(OsmandSettings.SpeedConstants sc, boolean showCameras) { + public AlarmInfo getMostImportantAlarm(SpeedConstants sc, boolean showCameras) { Location lastProjection = app.getRoutingHelper().getLastProjection(); float mxspeed = route.getCurrentMaxSpeed(); float delta = app.getSettings().SPEED_LIMIT_EXCEED_KMH.get() / 3.6f; @@ -291,7 +292,7 @@ public class WaypointHelper { } public AlarmInfo calculateMostImportantAlarm(RouteDataObject ro, Location loc, MetricsConstants mc, - OsmandSettings.SpeedConstants sc, boolean showCameras) { + SpeedConstants sc, boolean showCameras) { float mxspeed = ro.getMaximumSpeed(ro.bearingVsRouteDirection(loc)); float delta = app.getSettings().SPEED_LIMIT_EXCEED_KMH.get() / 3.6f; AlarmInfo speedAlarm = createSpeedAlarm(sc, mxspeed, loc, delta); @@ -331,7 +332,7 @@ public class WaypointHelper { return null; } - private static AlarmInfo createSpeedAlarm(OsmandSettings.SpeedConstants sc, float mxspeed, Location loc, float delta) { + private static AlarmInfo createSpeedAlarm(SpeedConstants sc, float mxspeed, Location loc, float delta) { AlarmInfo speedAlarm = null; if (mxspeed != 0 && loc != null && loc.hasSpeed() && mxspeed != RouteDataObject.NONE_MAX_SPEED) { if (loc.getSpeed() > mxspeed + delta) { @@ -790,7 +791,7 @@ public class WaypointHelper { } else if (type == ALARMS) { //assign alarm list icons manually for now String typeString = ((AlarmInfo) point).getType().toString(); - OsmandSettings.DrivingRegion region = app.getSettings().DRIVING_REGION.get(); + DrivingRegion region = app.getSettings().DRIVING_REGION.get(); if (typeString.equals("SPEED_CAMERA")) { return AppCompatResources.getDrawable(uiCtx, R.drawable.mx_highway_speed_camera); } else if (typeString.equals("BORDER_CONTROL")) { diff --git a/OsmAnd/src/net/osmand/plus/helpers/enums/AngularConstants.java b/OsmAnd/src/net/osmand/plus/helpers/enums/AngularConstants.java new file mode 100644 index 0000000000..9962144fa4 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/helpers/enums/AngularConstants.java @@ -0,0 +1,28 @@ +package net.osmand.plus.helpers.enums; + +import android.content.Context; + +import net.osmand.plus.R; + +public enum AngularConstants { + DEGREES(R.string.shared_string_degrees, "°"), + DEGREES360(R.string.shared_string_degrees, "°"), + MILLIRADS(R.string.shared_string_milliradians, "mil"); + + private final int key; + private final String unit; + + AngularConstants(int key, String unit) { + this.key = key; + this.unit = unit; + } + + public String toHumanString(Context ctx) { + return ctx.getString(key); + } + + public String getUnitSymbol() { + return unit; + } + +} diff --git a/OsmAnd/src/net/osmand/plus/helpers/enums/AutoZoomMap.java b/OsmAnd/src/net/osmand/plus/helpers/enums/AutoZoomMap.java new file mode 100644 index 0000000000..f092c19be7 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/helpers/enums/AutoZoomMap.java @@ -0,0 +1,19 @@ +package net.osmand.plus.helpers.enums; + +import net.osmand.plus.R; + +public enum AutoZoomMap { + FARTHEST(R.string.auto_zoom_farthest, 1f, 15.5f), + FAR(R.string.auto_zoom_far, 1.4f, 17f), + CLOSE(R.string.auto_zoom_close, 2f, 19f); + public final float coefficient; + public final int name; + public final float maxZoom; + + AutoZoomMap(int name, float coefficient, float maxZoom) { + this.name = name; + this.coefficient = coefficient; + this.maxZoom = maxZoom; + + } +} diff --git a/OsmAnd/src/net/osmand/plus/helpers/enums/DayNightMode.java b/OsmAnd/src/net/osmand/plus/helpers/enums/DayNightMode.java new file mode 100644 index 0000000000..9c8865e877 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/helpers/enums/DayNightMode.java @@ -0,0 +1,62 @@ +package net.osmand.plus.helpers.enums; + +import android.content.Context; +import android.hardware.Sensor; +import android.hardware.SensorManager; + +import androidx.annotation.DrawableRes; +import androidx.annotation.StringRes; + +import net.osmand.plus.R; + +public enum DayNightMode { + AUTO(R.string.daynight_mode_auto, R.drawable.ic_action_map_sunset), + DAY(R.string.daynight_mode_day, R.drawable.ic_action_map_day), + NIGHT(R.string.daynight_mode_night, R.drawable.ic_action_map_night), + SENSOR(R.string.daynight_mode_sensor, R.drawable.ic_action_map_light_sensor); + + private final int key; + @DrawableRes + private final int drawableRes; + + DayNightMode(@StringRes int key, @DrawableRes int drawableRes) { + this.key = key; + this.drawableRes = drawableRes; + } + + public String toHumanString(Context ctx) { + return ctx.getString(key); + } + + @DrawableRes + public int getIconRes() { + return drawableRes; + } + + public boolean isSensor() { + return this == SENSOR; + } + + public boolean isAuto() { + return this == AUTO; + } + + public boolean isDay() { + return this == DAY; + } + + public boolean isNight() { + return this == NIGHT; + } + + public static DayNightMode[] possibleValues(Context context) { + SensorManager mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); + Sensor mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); + boolean isLightSensorEnabled = mLight != null; + if (isLightSensorEnabled) { + return DayNightMode.values(); + } else { + return new DayNightMode[]{AUTO, DAY, NIGHT}; + } + } +} diff --git a/OsmAnd/src/net/osmand/plus/helpers/enums/DrivingRegion.java b/OsmAnd/src/net/osmand/plus/helpers/enums/DrivingRegion.java new file mode 100644 index 0000000000..70c825926e --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/helpers/enums/DrivingRegion.java @@ -0,0 +1,62 @@ +package net.osmand.plus.helpers.enums; + +import android.content.Context; + +import net.osmand.plus.R; + +import java.util.Locale; + +/** + * Class represents specific for driving region + * Signs, leftHandDriving + */ +public enum DrivingRegion { + + EUROPE_ASIA(R.string.driving_region_europe_asia, MetricsConstants.KILOMETERS_AND_METERS, false), + US(R.string.driving_region_us, MetricsConstants.MILES_AND_FEET, false), + CANADA(R.string.driving_region_canada, MetricsConstants.KILOMETERS_AND_METERS, false), + UK_AND_OTHERS(R.string.driving_region_uk, MetricsConstants.MILES_AND_METERS, true), + JAPAN(R.string.driving_region_japan, MetricsConstants.KILOMETERS_AND_METERS, true), + AUSTRALIA(R.string.driving_region_australia, MetricsConstants.KILOMETERS_AND_METERS, true); + + public final boolean leftHandDriving; + public final MetricsConstants defMetrics; + public final int name; + + DrivingRegion(int name, MetricsConstants def, boolean leftHandDriving) { + this.name = name; + defMetrics = def; + this.leftHandDriving = leftHandDriving; + } + + public boolean isAmericanTypeSigns() { + return this == DrivingRegion.AUSTRALIA || + this == DrivingRegion.US || + this == DrivingRegion.CANADA; + } + + public String getDescription(Context ctx) { + return ctx.getString(leftHandDriving ? R.string.left_side_navigation : R.string.right_side_navigation) + + ", " + + defMetrics.toHumanString(ctx).toLowerCase(); + } + + public static DrivingRegion getDrivingRegionByLocale() { + Locale df = Locale.getDefault(); + if (df == null) { + return DrivingRegion.EUROPE_ASIA; + } + if (df.getCountry().equalsIgnoreCase(Locale.US.getCountry())) { + return DrivingRegion.US; + } else if (df.getCountry().equalsIgnoreCase(Locale.CANADA.getCountry())) { + return DrivingRegion.CANADA; + } else if (df.getCountry().equalsIgnoreCase(Locale.JAPAN.getCountry())) { + return DrivingRegion.JAPAN; + } else if (df.getCountry().equalsIgnoreCase("au")) { + return DrivingRegion.AUSTRALIA; + } else if(df.getCountry().equalsIgnoreCase(Locale.UK.getCountry())) { + return DrivingRegion.UK_AND_OTHERS; + } + return DrivingRegion.EUROPE_ASIA; + } +} diff --git a/OsmAnd/src/net/osmand/plus/helpers/enums/MetricsConstants.java b/OsmAnd/src/net/osmand/plus/helpers/enums/MetricsConstants.java new file mode 100644 index 0000000000..23034b5277 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/helpers/enums/MetricsConstants.java @@ -0,0 +1,30 @@ +package net.osmand.plus.helpers.enums; + +import android.content.Context; + +import net.osmand.plus.R; + +public enum MetricsConstants { + KILOMETERS_AND_METERS(R.string.si_km_m, "km-m"), + MILES_AND_FEET(R.string.si_mi_feet, "mi-f"), + MILES_AND_METERS(R.string.si_mi_meters, "mi-m"), + MILES_AND_YARDS(R.string.si_mi_yard, "mi-y"), + NAUTICAL_MILES(R.string.si_nm, "nm"); + + private final int key; + private final String ttsString; + + MetricsConstants(int key, String ttsString) { + this.key = key; + this.ttsString = ttsString; + } + + public String toHumanString(Context ctx) { + return ctx.getString(key); + } + + public String toTTSString() { + return ttsString; + } + +} diff --git a/OsmAnd/src/net/osmand/plus/helpers/enums/SpeedConstants.java b/OsmAnd/src/net/osmand/plus/helpers/enums/SpeedConstants.java new file mode 100644 index 0000000000..15a54513eb --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/helpers/enums/SpeedConstants.java @@ -0,0 +1,33 @@ +package net.osmand.plus.helpers.enums; + +import android.content.Context; + +import net.osmand.plus.R; + +public enum SpeedConstants { + KILOMETERS_PER_HOUR(R.string.km_h, R.string.si_kmh, false), + MILES_PER_HOUR(R.string.mile_per_hour, R.string.si_mph, true), + METERS_PER_SECOND(R.string.m_s, R.string.si_m_s, false), + MINUTES_PER_MILE(R.string.min_mile, R.string.si_min_m, true), + MINUTES_PER_KILOMETER(R.string.min_km, R.string.si_min_km, false), + NAUTICALMILES_PER_HOUR(R.string.nm_h, R.string.si_nm_h, true); + + public final int key; + public final int descr; + public final boolean imperial; + + SpeedConstants(int key, int descr, boolean imperial) { + this.key = key; + this.descr = descr; + this.imperial = imperial; + } + + public String toHumanString(Context ctx) { + return ctx.getString(descr); + } + + public String toShortString(Context ctx) { + return ctx.getString(key); + } + +} diff --git a/OsmAnd/src/net/osmand/plus/helpers/enums/TracksSortByMode.java b/OsmAnd/src/net/osmand/plus/helpers/enums/TracksSortByMode.java new file mode 100644 index 0000000000..6b4177c701 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/helpers/enums/TracksSortByMode.java @@ -0,0 +1,38 @@ +package net.osmand.plus.helpers.enums; + +import androidx.annotation.DrawableRes; +import androidx.annotation.StringRes; + +import net.osmand.plus.R; + +public enum TracksSortByMode { + BY_DATE(R.string.sort_last_modified, R.drawable.ic_action_time_start), + BY_NAME_ASCENDING(R.string.sort_name_ascending, R.drawable.ic_action_sort_by_name_ascending), + BY_NAME_DESCENDING(R.string.sort_name_descending, R.drawable.ic_action_sort_by_name_descending); + + private final int iconId; + private final int nameId; + + TracksSortByMode(int nameId, int iconId) { + this.nameId = nameId; + this.iconId = iconId; + } + + public boolean isByName() { + return this == BY_NAME_ASCENDING || this == BY_NAME_DESCENDING; + } + + public boolean isByDate() { + return this == BY_DATE; + } + + @StringRes + public int getNameId() { + return nameId; + } + + @DrawableRes + public int getIconId() { + return iconId; + } +} diff --git a/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesFragment.java b/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesFragment.java index f7c5f8bc59..c503162910 100644 --- a/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesFragment.java +++ b/OsmAnd/src/net/osmand/plus/liveupdates/LiveUpdatesFragment.java @@ -314,7 +314,7 @@ public class LiveUpdatesFragment extends BaseOsmAndFragment implements InAppPurc public void add(LocalIndexInfo info) { CommonPreference preference = preferenceLiveUpdatesOn( - info.getFileName(), getSettings()); + info.getFileName(), app.getSettings()); if (preference.get()) { dataShouldUpdate.add(info); } else { diff --git a/OsmAnd/src/net/osmand/plus/mapcontextmenu/MapContextMenuFragment.java b/OsmAnd/src/net/osmand/plus/mapcontextmenu/MapContextMenuFragment.java index 27dd2c89c3..7977a9ddc6 100644 --- a/OsmAnd/src/net/osmand/plus/mapcontextmenu/MapContextMenuFragment.java +++ b/OsmAnd/src/net/osmand/plus/mapcontextmenu/MapContextMenuFragment.java @@ -76,7 +76,6 @@ import net.osmand.plus.mapcontextmenu.MenuController.TitleProgressController; import net.osmand.plus.mapcontextmenu.controllers.TransportStopController; import net.osmand.plus.routepreparationmenu.ChooseRouteFragment; import net.osmand.plus.routepreparationmenu.MapRouteInfoMenu; -import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.transport.TransportStopRoute; import net.osmand.plus.views.AnimateDraggingMapThread; import net.osmand.plus.views.OsmandMapTileView; @@ -644,7 +643,7 @@ public class MapContextMenuFragment extends BaseOsmAndFragment implements Downlo // Action buttons ContextMenuAdapter adapter = menu.getActionsContextMenuAdapter(false); List items = adapter.getVisibleItems(); - List mainIds = ((OsmandSettings.MainContextMenuItemsSettings) mapActivity.getMyApplication() + List mainIds = ((MainContextMenuItemsSettings) mapActivity.getMyApplication() .getSettings().CONTEXT_MENU_ACTIONS_ITEMS.get()).getMainIds(); ContextMenuAdapter mainAdapter = new ContextMenuAdapter(requireMyApplication()); ContextMenuAdapter additionalAdapter = new ContextMenuAdapter(requireMyApplication()); diff --git a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/AmenityMenuBuilder.java b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/AmenityMenuBuilder.java index 5a4618ca4f..f0d33b68dd 100644 --- a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/AmenityMenuBuilder.java +++ b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/AmenityMenuBuilder.java @@ -36,8 +36,7 @@ import net.osmand.plus.mapcontextmenu.CollapsableView; import net.osmand.plus.mapcontextmenu.MenuBuilder; import net.osmand.plus.osmedit.OsmEditingPlugin; import net.osmand.plus.poi.PoiUIFilter; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.MetricsConstants; +import net.osmand.plus.helpers.enums.MetricsConstants; import net.osmand.plus.views.layers.POIMapLayer; import net.osmand.plus.widgets.TextViewEx; import net.osmand.plus.widgets.tools.ClickableSpanTouchListener; @@ -70,7 +69,7 @@ public class AmenityMenuBuilder extends MenuBuilder { private static final String WIKI_LINK = ".wikipedia.org/w"; public final static Log LOG = PlatformUtil.getLog(AmenityMenuBuilder.class); private final static DecimalFormat DF = new DecimalFormat("#.##"); - private OsmandSettings.MetricsConstants metricSystem; + private MetricsConstants metricSystem; private final Amenity amenity; @@ -714,10 +713,10 @@ public class AmenityMenuBuilder extends MenuBuilder { case "seamark_height": if (Algorithms.isFloat(value)) { double valueAsDouble = Double.valueOf(value); - if (metricSystem == OsmandSettings.MetricsConstants.MILES_AND_FEET) { + if (metricSystem == MetricsConstants.MILES_AND_FEET) { formattedValue = String.valueOf(DF.format(valueAsDouble * OsmAndFormatter.FEET_IN_ONE_METER)) + " " + mapActivity.getResources().getString(R.string.foot); - } else if (metricSystem == OsmandSettings.MetricsConstants.MILES_AND_YARDS) { + } else if (metricSystem == MetricsConstants.MILES_AND_YARDS) { formattedValue = String.valueOf(DF.format(valueAsDouble * OsmAndFormatter.YARDS_IN_ONE_METER)) + " " + mapActivity.getResources().getString(R.string.yard); } else { diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/DirectionIndicationDialogFragment.java b/OsmAnd/src/net/osmand/plus/mapmarkers/DirectionIndicationDialogFragment.java index c82230a464..d624ec7947 100644 --- a/OsmAnd/src/net/osmand/plus/mapmarkers/DirectionIndicationDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/DirectionIndicationDialogFragment.java @@ -32,7 +32,6 @@ import com.github.ksoichiro.android.observablescrollview.ScrollState; import net.osmand.AndroidUtils; import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.MapMarkersMode; import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersMode.java b/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersMode.java new file mode 100644 index 0000000000..840da1ad92 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersMode.java @@ -0,0 +1,37 @@ +package net.osmand.plus.mapmarkers; + +import android.content.Context; + +import net.osmand.plus.R; + +public enum MapMarkersMode { + TOOLBAR(R.string.shared_string_topbar), + WIDGETS(R.string.shared_string_widgets), + NONE(R.string.shared_string_none); + + private final int key; + + MapMarkersMode(int key) { + this.key = key; + } + + public String toHumanString(Context ctx) { + return ctx.getString(key); + } + + public boolean isToolbar() { + return this == TOOLBAR; + } + + public boolean isWidgets() { + return this == WIDGETS; + } + + public boolean isNone() { + return this == NONE; + } + + public static MapMarkersMode[] possibleValues(Context context) { + return new MapMarkersMode[]{TOOLBAR, WIDGETS, NONE}; + } +} diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/OptionsBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/mapmarkers/OptionsBottomSheetDialogFragment.java index 487ee2073c..4627ed764b 100644 --- a/OsmAnd/src/net/osmand/plus/mapmarkers/OptionsBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/OptionsBottomSheetDialogFragment.java @@ -14,7 +14,6 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import net.osmand.AndroidUtils; -import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.base.BottomSheetDialogFragment; import net.osmand.plus.helpers.AndroidUiHelper; @@ -63,7 +62,7 @@ public class OptionsBottomSheetDialogFragment extends BottomSheetDialogFragment } ((ImageView) mainView.findViewById(R.id.sort_by_icon)).setImageDrawable(getContentIcon(R.drawable.ic_sort_waypoint_dark)); - OsmandSettings.MapMarkersMode mode = getMyApplication().getSettings().MAP_MARKERS_MODE.get(); + MapMarkersMode mode = getMyApplication().getSettings().MAP_MARKERS_MODE.get(); int displayedCount = getMyApplication().getSettings().DISPLAYED_MARKERS_WIDGETS_COUNT.get(); ImageView showDirectionIcon = (ImageView) mainView.findViewById(R.id.show_direction_icon); int imageResId = 0; diff --git a/OsmAnd/src/net/osmand/plus/measurementtool/SelectFileBottomSheet.java b/OsmAnd/src/net/osmand/plus/measurementtool/SelectFileBottomSheet.java index 24d3ec8282..c155ec493c 100644 --- a/OsmAnd/src/net/osmand/plus/measurementtool/SelectFileBottomSheet.java +++ b/OsmAnd/src/net/osmand/plus/measurementtool/SelectFileBottomSheet.java @@ -25,6 +25,7 @@ import net.osmand.plus.base.bottomsheetmenu.BaseBottomSheetItem; import net.osmand.plus.helpers.GpxTrackAdapter; import net.osmand.plus.helpers.GpxTrackAdapter.OnItemClickListener; import net.osmand.plus.helpers.GpxUiHelper.GPXInfo; +import net.osmand.plus.helpers.enums.TracksSortByMode; import net.osmand.plus.mapcontextmenu.other.HorizontalSelectionAdapter; import net.osmand.plus.mapcontextmenu.other.HorizontalSelectionAdapter.HorizontalSelectionAdapterListener; @@ -38,7 +39,6 @@ import java.util.Map; import static net.osmand.plus.SimplePopUpMenuItemAdapter.*; import static net.osmand.plus.helpers.GpxUiHelper.getSortedGPXFilesInfo; -import static net.osmand.plus.settings.backend.OsmandSettings.*; import static net.osmand.util.Algorithms.collectDirs; public class SelectFileBottomSheet extends BottomSheetBehaviourDialogFragment { diff --git a/OsmAnd/src/net/osmand/plus/myplaces/AvailableGPXFragment.java b/OsmAnd/src/net/osmand/plus/myplaces/AvailableGPXFragment.java index fae190ea01..31cb5375fe 100644 --- a/OsmAnd/src/net/osmand/plus/myplaces/AvailableGPXFragment.java +++ b/OsmAnd/src/net/osmand/plus/myplaces/AvailableGPXFragment.java @@ -84,7 +84,7 @@ import net.osmand.plus.mapmarkers.CoordinateInputDialogFragment; import net.osmand.plus.monitoring.OsmandMonitoringPlugin; import net.osmand.plus.osmedit.OsmEditingPlugin; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.TracksSortByMode; +import net.osmand.plus.helpers.enums.TracksSortByMode; import java.io.File; import java.text.DateFormat; diff --git a/OsmAnd/src/net/osmand/plus/myplaces/TrackActivityFragmentAdapter.java b/OsmAnd/src/net/osmand/plus/myplaces/TrackActivityFragmentAdapter.java index f99046de4d..4451354fc8 100644 --- a/OsmAnd/src/net/osmand/plus/myplaces/TrackActivityFragmentAdapter.java +++ b/OsmAnd/src/net/osmand/plus/myplaces/TrackActivityFragmentAdapter.java @@ -58,8 +58,6 @@ import net.osmand.plus.activities.TrackActivity; import net.osmand.plus.dialogs.GpxAppearanceAdapter; import net.osmand.plus.measurementtool.GpxData; import net.osmand.plus.myplaces.TrackBitmapDrawer.TrackBitmapDrawerListener; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; import net.osmand.plus.track.GpxSplitType; import net.osmand.plus.track.SplitTrackAsyncTask; import net.osmand.plus.track.SplitTrackAsyncTask.SplitTrackListener; diff --git a/OsmAnd/src/net/osmand/plus/parkingpoint/ParkingPositionPlugin.java b/OsmAnd/src/net/osmand/plus/parkingpoint/ParkingPositionPlugin.java index bc0ff794c5..d131721376 100644 --- a/OsmAnd/src/net/osmand/plus/parkingpoint/ParkingPositionPlugin.java +++ b/OsmAnd/src/net/osmand/plus/parkingpoint/ParkingPositionPlugin.java @@ -7,7 +7,6 @@ import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.format.DateFormat; -import android.text.format.Time; import android.view.View; import android.widget.ArrayAdapter; import android.widget.CheckBox; @@ -36,20 +35,15 @@ import net.osmand.plus.dashboard.tools.DashFragmentData; import net.osmand.plus.mapcontextmenu.MapContextMenu; import net.osmand.plus.quickaction.QuickActionType; import net.osmand.plus.settings.backend.ApplicationMode; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; import net.osmand.plus.views.AnimateDraggingMapThread; import net.osmand.plus.views.layers.MapInfoLayer; import net.osmand.plus.views.OsmandMapLayer.DrawSettings; import net.osmand.plus.views.OsmandMapTileView; import net.osmand.plus.views.mapwidgets.widgets.TextInfoWidget; -import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; -import java.util.Date; import java.util.List; -import java.util.Locale; import static net.osmand.aidlapi.OsmAndCustomizationConstants.MAP_CONTEXT_MENU_MARK_AS_PARKING_LOC; diff --git a/OsmAnd/src/net/osmand/plus/quickaction/actions/DayNightModeAction.java b/OsmAnd/src/net/osmand/plus/quickaction/actions/DayNightModeAction.java index 0be5c0f715..8314341371 100644 --- a/OsmAnd/src/net/osmand/plus/quickaction/actions/DayNightModeAction.java +++ b/OsmAnd/src/net/osmand/plus/quickaction/actions/DayNightModeAction.java @@ -6,8 +6,7 @@ import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.DayNightMode; +import net.osmand.plus.helpers.enums.DayNightMode; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.quickaction.QuickAction; @@ -27,9 +26,9 @@ public class DayNightModeAction extends QuickAction { @Override public void execute(MapActivity activity) { if (activity.getMyApplication().getDaynightHelper().isNightMode()) { - activity.getMyApplication().getSettings().DAYNIGHT_MODE.set(OsmandSettings.DayNightMode.DAY); + activity.getMyApplication().getSettings().DAYNIGHT_MODE.set(DayNightMode.DAY); } else { - activity.getMyApplication().getSettings().DAYNIGHT_MODE.set(OsmandSettings.DayNightMode.NIGHT); + activity.getMyApplication().getSettings().DAYNIGHT_MODE.set(DayNightMode.NIGHT); } } diff --git a/OsmAnd/src/net/osmand/plus/rastermaps/LayerTransparencySeekbarMode.java b/OsmAnd/src/net/osmand/plus/rastermaps/LayerTransparencySeekbarMode.java new file mode 100644 index 0000000000..1fd8b2f91d --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/rastermaps/LayerTransparencySeekbarMode.java @@ -0,0 +1,22 @@ +package net.osmand.plus.rastermaps; + +import android.content.Context; + +import net.osmand.plus.R; + +public enum LayerTransparencySeekbarMode { + OVERLAY(R.string.overlay_transparency), + UNDERLAY(R.string.map_transparency), + OFF(R.string.shared_string_off), + UNDEFINED(R.string.shared_string_none); + + private final int key; + + LayerTransparencySeekbarMode(int key) { + this.key = key; + } + + public String toHumanString(Context ctx) { + return ctx.getString(key); + } +} diff --git a/OsmAnd/src/net/osmand/plus/rastermaps/MapOverlayAction.java b/OsmAnd/src/net/osmand/plus/rastermaps/MapOverlayAction.java index 575196f8a2..7972b264aa 100644 --- a/OsmAnd/src/net/osmand/plus/rastermaps/MapOverlayAction.java +++ b/OsmAnd/src/net/osmand/plus/rastermaps/MapOverlayAction.java @@ -16,7 +16,6 @@ import com.google.gson.reflect.TypeToken; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.LayerTransparencySeekbarMode; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.MapActivity; @@ -137,7 +136,7 @@ public class MapOverlayAction extends SwitchableAction> { if (settings.LAYER_TRANSPARENCY_SEEKBAR_MODE.get() == LayerTransparencySeekbarMode.UNDEFINED) { settings.LAYER_TRANSPARENCY_SEEKBAR_MODE.set(LayerTransparencySeekbarMode.OVERLAY); } - if (settings.LAYER_TRANSPARENCY_SEEKBAR_MODE.get() == OsmandSettings.LayerTransparencySeekbarMode.OVERLAY) { + if (settings.LAYER_TRANSPARENCY_SEEKBAR_MODE.get() == LayerTransparencySeekbarMode.OVERLAY) { activity.getMapLayers().getMapControlsLayer().showTransparencyBar(settings.MAP_OVERLAY_TRANSPARENCY, true); } } else { diff --git a/OsmAnd/src/net/osmand/plus/rastermaps/MapUnderlayAction.java b/OsmAnd/src/net/osmand/plus/rastermaps/MapUnderlayAction.java index d938174c1f..ca79cb4895 100644 --- a/OsmAnd/src/net/osmand/plus/rastermaps/MapUnderlayAction.java +++ b/OsmAnd/src/net/osmand/plus/rastermaps/MapUnderlayAction.java @@ -17,7 +17,6 @@ import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.LayerTransparencySeekbarMode; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.MapActivity; diff --git a/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java b/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java index 5d79637b1a..942a34cbf1 100644 --- a/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java +++ b/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java @@ -31,7 +31,6 @@ import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.LayerTransparencySeekbarMode; import net.osmand.plus.R; import net.osmand.plus.Version; import net.osmand.plus.activities.DownloadTilesDialog; @@ -41,9 +40,6 @@ import net.osmand.plus.activities.MapActivityLayers; import net.osmand.plus.dashboard.DashboardOnMap.DashboardType; import net.osmand.plus.dialogs.RasterMapMenu; import net.osmand.plus.quickaction.QuickActionType; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.LayerTransparencySeekbarMode; import net.osmand.plus.views.MapTileLayer; import net.osmand.plus.views.OsmandMapTileView; import net.osmand.util.Algorithms; @@ -562,10 +558,10 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { } MapActivityLayers mapLayers = mapActivity.getMapLayers(); ITileSource map = layer.getMap(); - final OsmandSettings.LayerTransparencySeekbarMode currentMapTypeSeekbarMode = type == + final LayerTransparencySeekbarMode currentMapTypeSeekbarMode = type == OsmandRasterMapsPlugin.RasterMapType.OVERLAY - ? OsmandSettings.LayerTransparencySeekbarMode.OVERLAY - : OsmandSettings.LayerTransparencySeekbarMode.UNDERLAY; + ? LayerTransparencySeekbarMode.OVERLAY + : LayerTransparencySeekbarMode.UNDERLAY; if (map != null) { mapTypePreference.set(null); if (callback != null) { diff --git a/OsmAnd/src/net/osmand/plus/routepreparationmenu/MapRouteInfoMenu.java b/OsmAnd/src/net/osmand/plus/routepreparationmenu/MapRouteInfoMenu.java index 7c8238e7a1..927a085c8c 100644 --- a/OsmAnd/src/net/osmand/plus/routepreparationmenu/MapRouteInfoMenu.java +++ b/OsmAnd/src/net/osmand/plus/routepreparationmenu/MapRouteInfoMenu.java @@ -105,9 +105,6 @@ import net.osmand.plus.routing.RoutingHelper; import net.osmand.plus.routing.TransportRoutingHelper; import net.osmand.plus.search.QuickSearchHelper; import net.osmand.plus.settings.backend.ApplicationMode; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; import net.osmand.plus.widgets.TextViewExProgress; import net.osmand.router.GeneralRouter; import net.osmand.router.GeneralRouter.RoutingParameter; diff --git a/OsmAnd/src/net/osmand/plus/routing/RouteProvider.java b/OsmAnd/src/net/osmand/plus/routing/RouteProvider.java index 6a5599fa1a..a21b8898e6 100644 --- a/OsmAnd/src/net/osmand/plus/routing/RouteProvider.java +++ b/OsmAnd/src/net/osmand/plus/routing/RouteProvider.java @@ -30,13 +30,10 @@ import net.osmand.plus.TargetPointsHelper.TargetPoint; import net.osmand.plus.Version; import net.osmand.plus.render.NativeOsmandLibrary; import net.osmand.plus.settings.backend.ApplicationMode; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; import net.osmand.router.GeneralRouter; import net.osmand.router.GeneralRouter.RoutingParameter; import net.osmand.router.GeneralRouter.RoutingParameterType; import net.osmand.router.PrecalculatedRouteDirection; -import net.osmand.router.RouteCalculationProgress; import net.osmand.router.RouteExporter; import net.osmand.router.RouteImporter; import net.osmand.router.RoutePlannerFrontEnd; diff --git a/OsmAnd/src/net/osmand/plus/routing/RoutingHelper.java b/OsmAnd/src/net/osmand/plus/routing/RoutingHelper.java index 4fd5b1dd65..e92c8c0504 100644 --- a/OsmAnd/src/net/osmand/plus/routing/RoutingHelper.java +++ b/OsmAnd/src/net/osmand/plus/routing/RoutingHelper.java @@ -21,6 +21,7 @@ import net.osmand.plus.OsmandPlugin; import net.osmand.plus.R; import net.osmand.plus.TargetPointsHelper; import net.osmand.plus.TargetPointsHelper.TargetPoint; +import net.osmand.plus.helpers.enums.MetricsConstants; import net.osmand.plus.notifications.OsmandNotification.NotificationType; import net.osmand.plus.routing.RouteCalculationResult.NextDirectionInfo; import net.osmand.plus.routing.RouteProvider.GPXRouteParamsBuilder; @@ -408,8 +409,8 @@ public class RoutingHelper { } else if (mode.getRouteService() == RouteService.DIRECT_TO) { return -1.0f; } else if (mode.getRouteService() == RouteService.STRAIGHT) { - OsmandSettings.MetricsConstants mc = settings.METRIC_SYSTEM.getModeValue(mode); - if (mc == OsmandSettings.MetricsConstants.KILOMETERS_AND_METERS || mc == OsmandSettings.MetricsConstants.MILES_AND_METERS) { + MetricsConstants mc = settings.METRIC_SYSTEM.getModeValue(mode); + if (mc == MetricsConstants.KILOMETERS_AND_METERS || mc == MetricsConstants.MILES_AND_METERS) { return 500.f; } else { // 1/4 mile diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/BooleanAccessibilityPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanAccessibilityPreference.java index c376b6a99a..145a566b77 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/BooleanAccessibilityPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanAccessibilityPreference.java @@ -1,7 +1,5 @@ package net.osmand.plus.settings.backend; -import net.osmand.plus.ApplicationMode; - class BooleanAccessibilityPreference extends BooleanPreference { BooleanAccessibilityPreference(OsmandSettings osmandSettings, String id, boolean defaultValue) { diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/BooleanStringPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanStringPreference.java new file mode 100644 index 0000000000..8ca99f8521 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanStringPreference.java @@ -0,0 +1,25 @@ +package net.osmand.plus.settings.backend; + +public class BooleanStringPreference extends BooleanPreference { + + public BooleanStringPreference(OsmandSettings osmandSettings, String id, boolean defaultValue) { + super(osmandSettings, id, defaultValue); + } + + @Override + public Boolean getValue(Object prefs, Boolean defaultValue) { + Boolean value; + try { + value = parseString(getSettingsAPI().getString(prefs, getId(), defaultValue.toString())); + } catch (ClassCastException e) { + value = getSettingsAPI().getBoolean(prefs, getId(), defaultValue); + setValue(prefs, value); + } + return value; + } + + @Override + protected boolean setValue(Object prefs, Boolean val) { + return getSettingsAPI().edit(prefs).putString(getId(), val != null ? val.toString() : null).commit(); + } +} diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java index 0a53139dc1..ea1c251375 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java @@ -1,6 +1,5 @@ package net.osmand.plus.settings.backend; -import net.osmand.plus.ApplicationMode; import net.osmand.plus.OsmandApplication; import net.osmand.plus.api.SettingsAPI; diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/ListStringPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/ListStringPreference.java index ff611593cc..661a42341a 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/ListStringPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/ListStringPreference.java @@ -1,7 +1,5 @@ package net.osmand.plus.settings.backend; -import net.osmand.plus.ApplicationMode; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndPreferencesDataStore.java b/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndPreferencesDataStore.java index d4eaf070f2..135055c234 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndPreferencesDataStore.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndPreferencesDataStore.java @@ -1,7 +1,5 @@ package net.osmand.plus.settings.backend; -import net.osmand.plus.ApplicationMode; - import java.util.Set; import androidx.annotation.NonNull; diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/OsmandPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/OsmandPreference.java index ae9a3f5e3a..897f9c22b0 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/OsmandPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/OsmandPreference.java @@ -1,7 +1,6 @@ package net.osmand.plus.settings.backend; import net.osmand.StateChangedListener; -import net.osmand.plus.ApplicationMode; import org.json.JSONException; import org.json.JSONObject; diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java b/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java index 6a00a9f5a3..f66f81de57 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/OsmandSettings.java @@ -6,29 +6,19 @@ import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; -import android.hardware.Sensor; -import android.hardware.SensorManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.Environment; -import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; -import androidx.annotation.StringRes; import androidx.core.util.Pair; -import androidx.preference.PreferenceDataStore; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; +import net.osmand.FileUtils; import net.osmand.IndexConstants; import net.osmand.PlatformUtil; import net.osmand.ValueHolder; -import net.osmand.data.FavouritePoint; -import net.osmand.aidl.OsmandAidlApi; import net.osmand.data.LatLon; import net.osmand.data.PointDescription; import net.osmand.map.ITileSource; @@ -36,8 +26,6 @@ import net.osmand.map.TileSourceManager; import net.osmand.map.TileSourceManager.TileSourceTemplate; import net.osmand.osm.MapPoiTypes; import net.osmand.osm.io.NetworkUtils; -import net.osmand.plus.ApplicationMode; -import net.osmand.plus.FavouritesDbHelper; import net.osmand.plus.OsmandApplication; import net.osmand.plus.R; import net.osmand.plus.SQLiteTileSource; @@ -46,19 +34,30 @@ import net.osmand.plus.access.RelativeDirectionStyle; import net.osmand.plus.api.SettingsAPI; import net.osmand.plus.api.SettingsAPI.SettingsEditor; import net.osmand.plus.api.SettingsAPIImpl; +import net.osmand.plus.audionotes.NotesSortByMode; import net.osmand.plus.dialogs.RateUsBottomSheetDialogFragment.RateUsState; +import net.osmand.plus.helpers.enums.AngularConstants; +import net.osmand.plus.helpers.enums.AutoZoomMap; import net.osmand.plus.helpers.AvoidSpecificRoads.AvoidRoadInfo; +import net.osmand.plus.helpers.enums.DayNightMode; +import net.osmand.plus.helpers.enums.DrivingRegion; +import net.osmand.plus.helpers.enums.MetricsConstants; import net.osmand.plus.helpers.SearchHistoryHelper; +import net.osmand.plus.helpers.enums.SpeedConstants; +import net.osmand.plus.helpers.enums.TracksSortByMode; import net.osmand.plus.mapillary.MapillaryPlugin; import net.osmand.plus.mapmarkers.CoordinateInputFormats.Format; +import net.osmand.plus.mapmarkers.MapMarkersMode; import net.osmand.plus.profiles.LocationIcon; import net.osmand.plus.profiles.NavigationIcon; import net.osmand.plus.profiles.ProfileIconColors; +import net.osmand.plus.rastermaps.LayerTransparencySeekbarMode; import net.osmand.plus.render.RendererRegistry; import net.osmand.plus.routing.RouteProvider.RouteService; -import net.osmand.plus.settings.backend.ApplicationMode.ApplicationModeBean; -import net.osmand.plus.settings.backend.ApplicationMode.ApplicationModeBuilder; +import net.osmand.plus.srtmplugin.TerrainMode; +import net.osmand.plus.views.layers.RulerMode; import net.osmand.plus.voice.CommandPlayer; +import net.osmand.plus.wikipedia.WikiArticleShowImages; import net.osmand.render.RenderingRulesStorage; import net.osmand.util.Algorithms; @@ -78,7 +77,6 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; @@ -213,7 +211,7 @@ public class OsmandSettings { } // TODO doesn't look correct package visibility - public Object getProfilePreferences(String modeKey) { + Object getProfilePreferences(String modeKey) { return settingsAPI.getPreferenceObject(getSharedPreferencesNameForKey(modeKey)); } @@ -693,51 +691,47 @@ public class OsmandSettings { return false; } - public final CommonPreference RULER_MODE = new EnumStringPreference<>("ruler_mode", RulerMode.FIRST, RulerMode.values()).makeGlobal(); + public final CommonPreference RULER_MODE = new EnumStringPreference<>(this, "ruler_mode", RulerMode.FIRST, RulerMode.values()).makeGlobal(); - public final OsmandPreference SHOW_COMPASS_CONTROL_RULER = new BooleanPreference("show_compass_ruler", true).makeGlobal(); + public final OsmandPreference SHOW_COMPASS_CONTROL_RULER = new BooleanPreference(this, "show_compass_ruler", true).makeGlobal(); - public final CommonPreference SHOW_LINES_TO_FIRST_MARKERS = new BooleanPreference("show_lines_to_first_markers", false).makeProfile(); - public final CommonPreference SHOW_ARROWS_TO_FIRST_MARKERS = new BooleanPreference("show_arrows_to_first_markers", false).makeProfile(); + public final CommonPreference SHOW_LINES_TO_FIRST_MARKERS = new BooleanPreference(this, "show_lines_to_first_markers", false).makeProfile(); + public final CommonPreference SHOW_ARROWS_TO_FIRST_MARKERS = new BooleanPreference(this, "show_arrows_to_first_markers", false).makeProfile(); - public final CommonPreference WIKI_ARTICLE_SHOW_IMAGES_ASKED = new BooleanPreference("wikivoyage_show_images_asked", false).makeGlobal(); - public final CommonPreference WIKI_ARTICLE_SHOW_IMAGES = new EnumStringPreference<>("wikivoyage_show_imgs", WikiArticleShowImages.OFF, WikiArticleShowImages.values()).makeGlobal(); - public final CommonPreference GLOBAL_WIKIPEDIA_POI_ENABLED = new BooleanPreference("global_wikipedia_poi_enabled", false).makeProfile(); - public final ListStringPreference WIKIPEDIA_POI_ENABLED_LANGUAGES = (ListStringPreference) new ListStringPreference("wikipedia_poi_enabled_languages", null, ",").makeProfile().cache(); + public final CommonPreference WIKI_ARTICLE_SHOW_IMAGES_ASKED = new BooleanPreference(this, "wikivoyage_show_images_asked", false).makeGlobal(); + public final CommonPreference WIKI_ARTICLE_SHOW_IMAGES = new EnumStringPreference<>(this, "wikivoyage_show_imgs", WikiArticleShowImages.OFF, WikiArticleShowImages.values()).makeGlobal(); + public final CommonPreference GLOBAL_WIKIPEDIA_POI_ENABLED = new BooleanPreference(this, "global_wikipedia_poi_enabled", false).makeProfile(); + public final ListStringPreference WIKIPEDIA_POI_ENABLED_LANGUAGES = (ListStringPreference) new ListStringPreference(this, "wikipedia_poi_enabled_languages", null, ",").makeProfile().cache(); - public final CommonPreference SELECT_MARKER_ON_SINGLE_TAP = new BooleanPreference("select_marker_on_single_tap", false).makeProfile(); - public final CommonPreference KEEP_PASSED_MARKERS_ON_MAP = new BooleanPreference("keep_passed_markers_on_map", true).makeProfile(); + public final CommonPreference SELECT_MARKER_ON_SINGLE_TAP = new BooleanPreference(this, "select_marker_on_single_tap", false).makeProfile(); + public final CommonPreference KEEP_PASSED_MARKERS_ON_MAP = new BooleanPreference(this, "keep_passed_markers_on_map", true).makeProfile(); - public final CommonPreference COORDS_INPUT_USE_RIGHT_SIDE = new BooleanPreference("coords_input_use_right_side", true).makeGlobal(); - public final OsmandPreference COORDS_INPUT_FORMAT = new EnumStringPreference<>("coords_input_format", Format.DD_MM_MMM, Format.values()).makeGlobal(); - public final CommonPreference COORDS_INPUT_USE_OSMAND_KEYBOARD = new BooleanPreference("coords_input_use_osmand_keyboard", Build.VERSION.SDK_INT >= 16).makeGlobal(); - public final CommonPreference COORDS_INPUT_TWO_DIGITS_LONGTITUDE = new BooleanPreference("coords_input_two_digits_longitude", false).makeGlobal(); + public final CommonPreference COORDS_INPUT_USE_RIGHT_SIDE = new BooleanPreference(this, "coords_input_use_right_side", true).makeGlobal(); + public final OsmandPreference COORDS_INPUT_FORMAT = new EnumStringPreference<>(this, "coords_input_format", Format.DD_MM_MMM, Format.values()).makeGlobal(); + public final CommonPreference COORDS_INPUT_USE_OSMAND_KEYBOARD = new BooleanPreference(this, "coords_input_use_osmand_keyboard", Build.VERSION.SDK_INT >= 16).makeGlobal(); + public final CommonPreference COORDS_INPUT_TWO_DIGITS_LONGTITUDE = new BooleanPreference(this, "coords_input_two_digits_longitude", false).makeGlobal(); - public final CommonPreference USE_MAPILLARY_FILTER = new BooleanPreference("use_mapillary_filters", false).makeGlobal(); - public final CommonPreference MAPILLARY_FILTER_USER_KEY = new StringPreference("mapillary_filter_user_key", "").makeGlobal(); - public final CommonPreference MAPILLARY_FILTER_USERNAME = new StringPreference("mapillary_filter_username", "").makeGlobal(); - public final CommonPreference MAPILLARY_FILTER_FROM_DATE = new LongPreference("mapillary_filter_from_date", 0).makeGlobal(); - public final CommonPreference MAPILLARY_FILTER_TO_DATE = new LongPreference("mapillary_filter_to_date", 0).makeGlobal(); - public final CommonPreference MAPILLARY_FILTER_PANO = new BooleanPreference("mapillary_filter_pano", false).makeGlobal(); + public final CommonPreference USE_MAPILLARY_FILTER = new BooleanPreference(this, "use_mapillary_filters", false).makeGlobal(); + public final CommonPreference MAPILLARY_FILTER_USER_KEY = new StringPreference(this, "mapillary_filter_user_key", "").makeGlobal(); + public final CommonPreference MAPILLARY_FILTER_USERNAME = new StringPreference(this, "mapillary_filter_username", "").makeGlobal(); + public final CommonPreference MAPILLARY_FILTER_FROM_DATE = new LongPreference(this, "mapillary_filter_from_date", 0).makeGlobal(); + public final CommonPreference MAPILLARY_FILTER_TO_DATE = new LongPreference(this, "mapillary_filter_to_date", 0).makeGlobal(); + public final CommonPreference MAPILLARY_FILTER_PANO = new BooleanPreference(this, "mapillary_filter_pano", false).makeGlobal(); - public final CommonPreference USE_FAST_RECALCULATION = new BooleanPreference("use_fast_recalculation", true).makeGlobal().cache(); - public final CommonPreference FORCE_PRIVATE_ACCESS_ROUTING_ASKED = new BooleanPreference("force_private_access_routing", false).makeProfile().cache(); + public final CommonPreference USE_FAST_RECALCULATION = new BooleanPreference(this, "use_fast_recalculation", true).makeGlobal().cache(); + public final CommonPreference FORCE_PRIVATE_ACCESS_ROUTING_ASKED = new BooleanPreference(this, "force_private_access_routing", false).makeProfile().cache(); - public final CommonPreference SHOW_CARD_TO_CHOOSE_DRAWER = new BooleanPreference("show_card_to_choose_drawer", false).makeGlobal(); - public final CommonPreference SHOW_DASHBOARD_ON_START = new BooleanPreference("should_show_dashboard_on_start", false).makeGlobal(); - public final CommonPreference SHOW_DASHBOARD_ON_MAP_SCREEN = new BooleanPreference("show_dashboard_on_map_screen", false).makeGlobal(); - public final CommonPreference SHOW_OSMAND_WELCOME_SCREEN = new BooleanPreference("show_osmand_welcome_screen", true).makeGlobal(); + public final CommonPreference SHOW_CARD_TO_CHOOSE_DRAWER = new BooleanPreference(this, "show_card_to_choose_drawer", false).makeGlobal(); + public final CommonPreference SHOW_DASHBOARD_ON_START = new BooleanPreference(this, "should_show_dashboard_on_start", false).makeGlobal(); + public final CommonPreference SHOW_DASHBOARD_ON_MAP_SCREEN = new BooleanPreference(this, "show_dashboard_on_map_screen", false).makeGlobal(); + public final CommonPreference SHOW_OSMAND_WELCOME_SCREEN = new BooleanPreference(this, "show_osmand_welcome_screen", true).makeGlobal(); - public final CommonPreference API_NAV_DRAWER_ITEMS_JSON = new StringPreference("api_nav_drawer_items_json", "{}").makeGlobal(); - public final CommonPreference API_CONNECTED_APPS_JSON = new StringPreference("api_connected_apps_json", "[]").makeGlobal(); - public final CommonPreference NAV_DRAWER_LOGO = new StringPreference("drawer_logo", "").makeProfile(); - public final CommonPreference NAV_DRAWER_URL = new StringPreference("drawer_url", "").makeProfile(); + public final CommonPreference API_NAV_DRAWER_ITEMS_JSON = new StringPreference(this, "api_nav_drawer_items_json", "{}").makeGlobal(); + public final CommonPreference API_CONNECTED_APPS_JSON = new StringPreference(this, "api_connected_apps_json", "[]").makeGlobal(); + public final CommonPreference NAV_DRAWER_LOGO = new StringPreference(this, "drawer_logo", "").makeProfile(); + public final CommonPreference NAV_DRAWER_URL = new StringPreference(this, "drawer_url", "").makeProfile(); - public final CommonPreference NUMBER_OF_STARTS_FIRST_XMAS_SHOWN = new IntPreference("number_of_starts_first_xmas_shown", 0).makeGlobal(); - - public final OsmandPreference AVAILABLE_APP_MODES = new StringPreference("available_application_modes", "car,bicycle,pedestrian,public_transport,").makeGlobal().cache(); - - public final OsmandPreference LAST_FAV_CATEGORY_ENTERED = new StringPreference("last_fav_category", "").makeGlobal(); + public final CommonPreference NUMBER_OF_STARTS_FIRST_XMAS_SHOWN = new IntPreference(this, "number_of_starts_first_xmas_shown", 0).makeGlobal(); public final OsmandPreference AVAILABLE_APP_MODES = new StringPreference(this, "available_application_modes", "car,bicycle,pedestrian,public_transport,").makeGlobal().cache(); @@ -844,22 +838,7 @@ public class OsmandSettings { } protected DrivingRegion getDefaultValue() { - Locale df = Locale.getDefault(); - if (df == null) { - return DrivingRegion.EUROPE_ASIA; - } - if (df.getCountry().equalsIgnoreCase(Locale.US.getCountry())) { - return DrivingRegion.US; - } else if (df.getCountry().equalsIgnoreCase(Locale.CANADA.getCountry())) { - return DrivingRegion.CANADA; - } else if (df.getCountry().equalsIgnoreCase(Locale.JAPAN.getCountry())) { - return DrivingRegion.JAPAN; - } else if (df.getCountry().equalsIgnoreCase("au")) { - return DrivingRegion.AUSTRALIA; - } else if(df.getCountry().equalsIgnoreCase(Locale.UK.getCountry())) { - return DrivingRegion.UK_AND_OTHERS; - } - return DrivingRegion.EUROPE_ASIA; + return DrivingRegion.getDrivingRegionByLocale(); } }.makeProfile().cache(); @@ -1040,31 +1019,31 @@ public class OsmandSettings { // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference ACCESSIBILITY_SMART_AUTOANNOUNCE = new BooleanAccessibilityPreference(this, "accessibility_smart_autoannounce", true).makeProfile(); - + // this value string is synchronized with settings_pref.xml preference name // cache of metrics constants as they are used very often public final OsmandPreference ACCESSIBILITY_AUTOANNOUNCE_PERIOD = new IntPreference(this, "accessibility_autoannounce_period", 10000).makeProfile().cache(); // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference DISABLE_OFFROUTE_RECALC = - new BooleanPreference(this,"disable_offroute_recalc", false).makeProfile(); + new BooleanPreference(this, "disable_offroute_recalc", false).makeProfile(); // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference DISABLE_WRONG_DIRECTION_RECALC = - new BooleanPreference("disable_wrong_direction_recalc", false).makeProfile(); - + new BooleanPreference(this, "disable_wrong_direction_recalc", false).makeProfile(); + // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference DIRECTION_AUDIO_FEEDBACK = - new BooleanAccessibilityPreference(this, "direction_audio_feedback", false).makeProfile(); - + new BooleanAccessibilityPreference(this, "direction_audio_feedback", false).makeProfile(); + // this value string is synchronized with settings_pref.xml preference name public final OsmandPreference DIRECTION_HAPTIC_FEEDBACK = - new BooleanAccessibilityPreference(this, "direction_haptic_feedback", false).makeProfile(); + new BooleanAccessibilityPreference(this, "direction_haptic_feedback", false).makeProfile(); // magnetic field doesn'torkmost of the time on some phones - public final OsmandPreference USE_MAGNETIC_FIELD_SENSOR_COMPASS = new BooleanPreference("use_magnetic_field_sensor_compass", false).makeProfile().cache(); - public final OsmandPreference USE_KALMAN_FILTER_FOR_COMPASS = new BooleanPreference("use_kalman_filter_compass", true).makeProfile().cache(); - public final OsmandPreference USE_VOLUME_BUTTONS_AS_ZOOM = new BooleanPreference("use_volume_buttons_as_zoom", false).makeProfile().cache(); + public final OsmandPreference USE_MAGNETIC_FIELD_SENSOR_COMPASS = new BooleanPreference(this, "use_magnetic_field_sensor_compass", false).makeProfile().cache(); + public final OsmandPreference USE_KALMAN_FILTER_FOR_COMPASS = new BooleanPreference(this, "use_kalman_filter_compass", true).makeProfile().cache(); + public final OsmandPreference USE_VOLUME_BUTTONS_AS_ZOOM = new BooleanPreference(this, "use_volume_buttons_as_zoom", false).makeProfile().cache(); public final OsmandPreference DO_NOT_SHOW_STARTUP_MESSAGES = new BooleanPreference(this, "do_not_show_startup_messages", false).makeGlobal().cache(); public final OsmandPreference SHOW_DOWNLOAD_MAP_DIALOG = new BooleanPreference(this, "show_download_map_dialog", true).makeGlobal().cache(); @@ -1117,23 +1096,23 @@ public class OsmandSettings { public final OsmandPreference INAPPS_READ = new BooleanPreference(this, "inapps_read", false).makeGlobal(); - public final OsmandPreference BILLING_USER_ID = new StringPreference("billing_user_id", "").makeGlobal(); - public final OsmandPreference BILLING_USER_TOKEN = new StringPreference("billing_user_token", "").makeGlobal(); - public final OsmandPreference BILLING_USER_NAME = new StringPreference("billing_user_name", "").makeGlobal(); - public final OsmandPreference BILLING_USER_EMAIL = new StringPreference("billing_user_email", "").makeGlobal(); - public final OsmandPreference BILLING_USER_COUNTRY = new StringPreference("billing_user_country", "").makeGlobal(); - public final OsmandPreference BILLING_USER_COUNTRY_DOWNLOAD_NAME = new StringPreference("billing_user_country_download_name", BILLING_USER_DONATION_NONE_PARAMETER).makeGlobal(); - public final OsmandPreference BILLING_HIDE_USER_NAME = new BooleanPreference("billing_hide_user_name", false).makeGlobal(); - public final OsmandPreference BILLING_PURCHASE_TOKEN_SENT = new BooleanPreference("billing_purchase_token_sent", false).makeGlobal(); - public final OsmandPreference BILLING_PURCHASE_TOKENS_SENT = new StringPreference("billing_purchase_tokens_sent", "").makeGlobal(); - public final OsmandPreference LIVE_UPDATES_PURCHASED = new BooleanPreference("billing_live_updates_purchased", false).makeGlobal(); - public final OsmandPreference LIVE_UPDATES_PURCHASE_CANCELLED_TIME = new LongPreference("live_updates_purchase_cancelled_time", 0).makeGlobal(); - public final OsmandPreference LIVE_UPDATES_PURCHASE_CANCELLED_FIRST_DLG_SHOWN = new BooleanPreference("live_updates_purchase_cancelled_first_dlg_shown", false).makeGlobal(); - public final OsmandPreference LIVE_UPDATES_PURCHASE_CANCELLED_SECOND_DLG_SHOWN = new BooleanPreference("live_updates_purchase_cancelled_second_dlg_shown", false).makeGlobal(); - public final OsmandPreference FULL_VERSION_PURCHASED = new BooleanPreference("billing_full_version_purchased", false).makeGlobal(); - public final OsmandPreference DEPTH_CONTOURS_PURCHASED = new BooleanPreference("billing_sea_depth_purchased", false).makeGlobal(); - public final OsmandPreference CONTOUR_LINES_PURCHASED = new BooleanPreference("billing_srtm_purchased", false).makeGlobal(); - public final OsmandPreference EMAIL_SUBSCRIBED = new BooleanPreference("email_subscribed", false).makeGlobal(); + public final OsmandPreference BILLING_USER_ID = new StringPreference(this, "billing_user_id", "").makeGlobal(); + public final OsmandPreference BILLING_USER_TOKEN = new StringPreference(this, "billing_user_token", "").makeGlobal(); + public final OsmandPreference BILLING_USER_NAME = new StringPreference(this, "billing_user_name", "").makeGlobal(); + public final OsmandPreference BILLING_USER_EMAIL = new StringPreference(this, "billing_user_email", "").makeGlobal(); + public final OsmandPreference BILLING_USER_COUNTRY = new StringPreference(this, "billing_user_country", "").makeGlobal(); + public final OsmandPreference BILLING_USER_COUNTRY_DOWNLOAD_NAME = new StringPreference(this, "billing_user_country_download_name", BILLING_USER_DONATION_NONE_PARAMETER).makeGlobal(); + public final OsmandPreference BILLING_HIDE_USER_NAME = new BooleanPreference(this, "billing_hide_user_name", false).makeGlobal(); + public final OsmandPreference BILLING_PURCHASE_TOKEN_SENT = new BooleanPreference(this, "billing_purchase_token_sent", false).makeGlobal(); + public final OsmandPreference BILLING_PURCHASE_TOKENS_SENT = new StringPreference(this, "billing_purchase_tokens_sent", "").makeGlobal(); + public final OsmandPreference LIVE_UPDATES_PURCHASED = new BooleanPreference(this, "billing_live_updates_purchased", false).makeGlobal(); + public final OsmandPreference LIVE_UPDATES_PURCHASE_CANCELLED_TIME = new LongPreference(this, "live_updates_purchase_cancelled_time", 0).makeGlobal(); + public final OsmandPreference LIVE_UPDATES_PURCHASE_CANCELLED_FIRST_DLG_SHOWN = new BooleanPreference(this, "live_updates_purchase_cancelled_first_dlg_shown", false).makeGlobal(); + public final OsmandPreference LIVE_UPDATES_PURCHASE_CANCELLED_SECOND_DLG_SHOWN = new BooleanPreference(this, "live_updates_purchase_cancelled_second_dlg_shown", false).makeGlobal(); + public final OsmandPreference FULL_VERSION_PURCHASED = new BooleanPreference(this, "billing_full_version_purchased", false).makeGlobal(); + public final OsmandPreference DEPTH_CONTOURS_PURCHASED = new BooleanPreference(this, "billing_sea_depth_purchased", false).makeGlobal(); + public final OsmandPreference CONTOUR_LINES_PURCHASED = new BooleanPreference(this, "billing_srtm_purchased", false).makeGlobal(); + public final OsmandPreference EMAIL_SUBSCRIBED = new BooleanPreference(this, "email_subscribed", false).makeGlobal(); public final OsmandPreference DISCOUNT_ID = new IntPreference(this, "discount_id", 0).makeGlobal(); public final OsmandPreference DISCOUNT_SHOW_NUMBER_OF_STARTS = new IntPreference(this, "number_of_starts_on_discount_show", 0).makeGlobal(); @@ -1284,17 +1263,19 @@ public class OsmandSettings { { SPEAK_TRAFFIC_WARNINGS.setModeDefaultValue(ApplicationMode.CAR, true); } + public final CommonPreference SPEAK_PEDESTRIAN = new BooleanPreference(this, "speak_pedestrian", false).makeProfile().cache(); + { SPEAK_PEDESTRIAN.setModeDefaultValue(ApplicationMode.CAR, true); } + public final OsmandPreference SPEAK_SPEED_LIMIT = new BooleanPreference(this, "speak_speed_limit", false).makeProfile().cache(); public final OsmandPreference SPEAK_SPEED_CAMERA = new BooleanPreference(this, "speak_cameras", false).makeProfile().cache(); public final OsmandPreference SPEAK_TUNNELS = new BooleanPreference(this, "speak_tunnels", false).makeProfile().cache(); - public final OsmandPreference ANNOUNCE_WPT = new BooleanPreference(this, "announce_wpt", true) { - public final OsmandPreference SPEED_CAMERAS_UNINSTALLED = new BooleanPreference("speed_cameras_uninstalled", false).makeGlobal(); - public final OsmandPreference SPEED_CAMERAS_ALERT_SHOWED = new BooleanPreference("speed_cameras_alert_showed", false).makeGlobal(); + public final OsmandPreference SPEED_CAMERAS_UNINSTALLED = new BooleanPreference(this, "speed_cameras_uninstalled", false).makeGlobal(); + public final OsmandPreference SPEED_CAMERAS_ALERT_SHOWED = new BooleanPreference(this, "speed_cameras_alert_showed", false).makeGlobal(); public Set getForbiddenTypes() { Set typeNames = new HashSet<>(); @@ -1304,7 +1285,7 @@ public class OsmandSettings { return typeNames; } - public final OsmandPreference ANNOUNCE_WPT = new BooleanPreference("announce_wpt", true) { + public final OsmandPreference ANNOUNCE_WPT = new BooleanPreference(this, "announce_wpt", true) { @Override protected boolean setValue(Object prefs, Boolean val) { boolean valueSaved = super.setValue(prefs, val); @@ -1343,11 +1324,7 @@ public class OsmandSettings { public final OsmandPreference GPX_ROUTE_CALC_OSMAND_PARTS = new BooleanPreference(this, "gpx_routing_calculate_osmand_route", true).makeGlobal().cache(); public final OsmandPreference GPX_CALCULATE_RTEPT = new BooleanPreference(this, "gpx_routing_calculate_rtept", true).makeGlobal().cache(); public final OsmandPreference GPX_ROUTE_CALC = new BooleanPreference(this, "calc_gpx_route", false).makeGlobal().cache(); - public final OsmandPreference SHOW_START_FINISH_ICONS = new BooleanPreference("show_start_finish_icons", true).makeGlobal().cache(); - - public final OsmandPreference GPX_ROUTE_CALC_OSMAND_PARTS = new BooleanPreference("gpx_routing_calculate_osmand_route", true).makeGlobal().cache(); -// public final OsmandPreference GPX_CALCULATE_RTEPT = new BooleanPreference("gpx_routing_calculate_rtept", true).makeGlobal().cache(); - public final OsmandPreference GPX_ROUTE_CALC = new BooleanPreference("calc_gpx_route", false).makeGlobal().cache(); + public final OsmandPreference SHOW_START_FINISH_ICONS = new BooleanPreference(this, "show_start_finish_icons", true).makeGlobal().cache(); public final OsmandPreference AVOID_TOLL_ROADS = new BooleanPreference(this, "avoid_toll_roads", false).makeProfile().cache(); public final OsmandPreference AVOID_MOTORWAY = new BooleanPreference(this, "avoid_motorway", false).makeProfile().cache(); @@ -1358,11 +1335,11 @@ public class OsmandSettings { public final OsmandPreference LAST_UPDATES_CARD_REFRESH = new LongPreference(this, "last_updates_card_refresh", 0).makeGlobal(); - public final CommonPreference CURRENT_TRACK_COLOR = new IntPreference("current_track_color", 0).makeGlobal().cache(); - public final CommonPreference CURRENT_TRACK_WIDTH = new StringPreference("current_track_width", "").makeGlobal().cache(); - public final CommonPreference CURRENT_TRACK_SHOW_ARROWS = new BooleanPreference("current_track_show_arrows", false).makeGlobal().cache(); - public final CommonPreference CURRENT_TRACK_SHOW_START_FINISH = new BooleanPreference("current_track_show_start_finish", true).makeGlobal().cache(); - public final ListStringPreference CUSTOM_TRACK_COLORS = (ListStringPreference) new ListStringPreference("custom_track_colors", null, ",").makeGlobal(); + public final CommonPreference CURRENT_TRACK_COLOR = new IntPreference(this, "current_track_color", 0).makeGlobal().cache(); + public final CommonPreference CURRENT_TRACK_WIDTH = new StringPreference(this, "current_track_width", "").makeGlobal().cache(); + public final CommonPreference CURRENT_TRACK_SHOW_ARROWS = new BooleanPreference(this, "current_track_show_arrows", false).makeGlobal().cache(); + public final CommonPreference CURRENT_TRACK_SHOW_START_FINISH = new BooleanPreference(this, "current_track_show_start_finish", true).makeGlobal().cache(); + public final ListStringPreference CUSTOM_TRACK_COLORS = (ListStringPreference) new ListStringPreference(this, "custom_track_colors", null, ",").makeGlobal(); // this value string is synchronized with settings_pref.xml preference name public final CommonPreference SAVE_TRACK_INTERVAL = new IntPreference(this, "save_track_interval", 5000).makeProfile(); @@ -1372,7 +1349,7 @@ public class OsmandSettings { SAVE_TRACK_INTERVAL.setModeDefaultValue(ApplicationMode.BICYCLE, 5000); SAVE_TRACK_INTERVAL.setModeDefaultValue(ApplicationMode.PEDESTRIAN, 10000); } - + // Please note that SAVE_TRACK_MIN_DISTANCE, SAVE_TRACK_PRECISION, SAVE_TRACK_MIN_SPEED should all be "0" for the default profile, as we have no interface to change them public final CommonPreference SAVE_TRACK_MIN_DISTANCE = new FloatPreference(this, "save_track_min_distance", 0).makeProfile(); //{ @@ -1420,6 +1397,7 @@ public class OsmandSettings { public final CommonPreference SHOW_OSM_BUGS_MIN_ZOOM = new IntPreference(this, "show_osm_bugs_min_zoom", 8).makeProfile().cache(); public final CommonPreference MAP_INFO_CONTROLS = new StringPreference(this, "map_info_controls", "").makeProfile(); + { for (ApplicationMode mode : ApplicationMode.allPossibleValues()) { MAP_INFO_CONTROLS.setModeDefaultValue(mode, ""); @@ -1474,7 +1452,7 @@ public class OsmandSettings { KEEP_INFORMING.setModeDefaultValue(ApplicationMode.PEDESTRIAN, 0); } - public final CommonPreference USE_SYSTEM_SCREEN_TIMEOUT = new BooleanPreference("use_system_screen_timeout", false).makeProfile(); + public final CommonPreference USE_SYSTEM_SCREEN_TIMEOUT = new BooleanPreference(this, "use_system_screen_timeout", false).makeProfile(); public final CommonPreference TURN_SCREEN_ON_TIME_INT = new IntPreference(this, "turn_screen_on_time_int", 0).makeProfile(); @@ -1485,16 +1463,16 @@ public class OsmandSettings { } public final CommonPreference TURN_SCREEN_ON_SENSOR = new BooleanPreference(this, "turn_screen_on_sensor", false).makeProfile(); - + { TURN_SCREEN_ON_SENSOR.setModeDefaultValue(ApplicationMode.CAR, false); TURN_SCREEN_ON_SENSOR.setModeDefaultValue(ApplicationMode.BICYCLE, false); TURN_SCREEN_ON_SENSOR.setModeDefaultValue(ApplicationMode.PEDESTRIAN, false); } - public final CommonPreference TURN_SCREEN_ON_NAVIGATION_INSTRUCTIONS = new BooleanPreference("turn_screen_on_navigation_instructions", false).makeProfile(); + public final CommonPreference TURN_SCREEN_ON_NAVIGATION_INSTRUCTIONS = new BooleanPreference(this, "turn_screen_on_navigation_instructions", false).makeProfile(); - public final CommonPreference TURN_SCREEN_ON_POWER_BUTTON = new BooleanPreference("turn_screen_on_power_button", false).makeProfile(); + public final CommonPreference TURN_SCREEN_ON_POWER_BUTTON = new BooleanPreference(this, "turn_screen_on_power_button", false).makeProfile(); // this value string is synchronized with settings_pref.xml preference name // try without AUTO_FOLLOW_ROUTE_NAV (see forum discussion 'Simplify our navigation preference menu') @@ -1567,7 +1545,8 @@ public class OsmandSettings { VOICE_PROMPT_DELAY[3] = new IntPreference(this, "voice_prompt_delay_3", 0).makeGlobal().cache(); /*AudioManager.STREAM_MUSIC*/ VOICE_PROMPT_DELAY[5] = new IntPreference(this, "voice_prompt_delay_5", 0).makeGlobal().cache(); /*AudioManager.STREAM_NOTIFICATION*/ } - public final OsmandPreference DISPLAY_TTS_UTTERANCE = new BooleanPreference("display_tts_utterance", false).makeGlobal(); + + public final OsmandPreference DISPLAY_TTS_UTTERANCE = new BooleanPreference(this, "display_tts_utterance", false).makeGlobal(); // this value string is synchronized with settings_pref.xml preference name public final CommonPreference MAP_ONLINE_DATA = new BooleanPreference(this, "map_online_data", false).makeProfile(); @@ -1636,8 +1615,8 @@ public class OsmandSettings { public final OsmandPreference SHOW_COORDINATES_WIDGET = new BooleanPreference(this, "show_coordinates_widget", false).makeProfile().cache(); - public final CommonPreference NOTES_SORT_BY_MODE = new EnumStringPreference<>("notes_sort_by_mode", NotesSortByMode.BY_DATE, NotesSortByMode.values()); - public final CommonPreference TRACKS_SORT_BY_MODE = new EnumStringPreference<>("tracks_sort_by_mode", TracksSortByMode.BY_DATE, TracksSortByMode.values()); + public final CommonPreference NOTES_SORT_BY_MODE = new EnumStringPreference<>(this, "notes_sort_by_mode", NotesSortByMode.BY_DATE, NotesSortByMode.values()); + public final CommonPreference TRACKS_SORT_BY_MODE = new EnumStringPreference<>(this, "tracks_sort_by_mode", TracksSortByMode.BY_DATE, TracksSortByMode.values()); public final OsmandPreference ANIMATE_MY_LOCATION = new BooleanPreference(this, "animate_my_location", true).makeProfile().cache(); @@ -1791,7 +1770,7 @@ public class OsmandSettings { setExternalStorageDirectoryPre19(getInternalAppPath().getAbsolutePath()); } else { File externalStorage = getExternal1AppPath(); - if (externalStorage != null && OsmandSettings.isWritable(externalStorage)) { + if (externalStorage != null && FileUtils.isWritable(externalStorage)) { setExternalStorageDirectoryV19(EXTERNAL_STORAGE_TYPE_EXTERNAL_FILE, getExternal1AppPath().getAbsolutePath()); } else { @@ -1843,7 +1822,7 @@ public class OsmandSettings { int type = settingsAPI.getInt(globalPreferences, EXTERNAL_STORAGE_DIR_TYPE_V19, -1); File location = getDefaultLocationV19(); if (type == -1) { - if (isWritable(location)) { + if (FileUtils.isWritable(location)) { if (tp != null) { tp.value = settingsAPI.contains(globalPreferences, EXTERNAL_STORAGE_DIR_V19) ? EXTERNAL_STORAGE_TYPE_SPECIFIED : @@ -1881,20 +1860,6 @@ public class OsmandSettings { return new File(location); } - - public static boolean isWritable(File dirToTest) { - boolean isWriteable = false; - try { - dirToTest.mkdirs(); - File writeTestFile = File.createTempFile("osmand_", ".tmp", dirToTest); - isWriteable = writeTestFile.exists(); - writeTestFile.delete(); - } catch (IOException e) { - isWriteable = false; - } - return isWriteable; - } - public boolean isExternalStorageDirectoryTypeSpecifiedV19() { return settingsAPI.contains(globalPreferences, EXTERNAL_STORAGE_DIR_TYPE_V19); } @@ -2008,10 +1973,6 @@ public class OsmandSettings { } } - private Object objectToShow; - private boolean editObjectToShow; - private String searchRequestToShow; - public void setSearchRequestToShow(String request) { this.searchRequestToShow = request; } @@ -2039,7 +2000,7 @@ public class OsmandSettings { } public void setMapLocationToShow(double latitude, double longitude, int zoom, PointDescription pointDescription, - boolean addToHistory, Object toShow) { + boolean addToHistory, Object toShow) { SettingsEditor edit = settingsAPI.edit(globalPreferences); edit.putFloat(MAP_LAT_TO_SHOW, (float) latitude); edit.putFloat(MAP_LON_TO_SHOW, (float) longitude); @@ -2103,7 +2064,6 @@ public class OsmandSettings { public final static String INTERMEDIATE_POINTS = "intermediate_points"; //$NON-NLS-1$ public final static String INTERMEDIATE_POINTS_DESCRIPTION = "intermediate_points_description"; //$NON-NLS-1$ - private IntermediatePointsStorage intermediatePointsStorage = new IntermediatePointsStorage(); public final static String POINT_NAVIGATE_LAT_BACKUP = "point_navigate_lat_backup"; //$NON-NLS-1$ public final static String POINT_NAVIGATE_LON_BACKUP = "point_navigate_lon_backup"; //$NON-NLS-1$ @@ -2363,7 +2323,7 @@ public class OsmandSettings { public static final String QUICK_FAB_MARGIN_X_LANDSCAPE_MARGIN = "quick_fab_margin_x_landscape_margin"; public static final String QUICK_FAB_MARGIN_Y_LANDSCAPE_MARGIN = "quick_fab_margin_y_landscape_margin"; - public final CommonPreference QUICK_ACTION = new BooleanPreference("quick_action_state", false).makeProfile(); + public final CommonPreference QUICK_ACTION = new BooleanPreference(this, "quick_action_state", false).makeProfile(); public final CommonPreference QUICK_ACTION_LIST = new StringPreference(this, "quick_action_list", "").makeGlobal(); @@ -2538,7 +2498,7 @@ public class OsmandSettings { public final ListStringPreference POI_FILTERS_ORDER = (ListStringPreference) new ListStringPreference(this, "poi_filters_order", null, ",,").makeProfile().cache(); - + public final ListStringPreference INACTIVE_POI_FILTERS = (ListStringPreference) new ListStringPreference(this, "inactive_poi_filters", null, ",,").makeProfile().cache(); @@ -2609,11 +2569,9 @@ public class OsmandSettings { RENDERER.setModeDefaultValue(ApplicationMode.SKI, RendererRegistry.WINTER_SKI_RENDER); } - Map> customRendersProps = new LinkedHashMap>(); - public CommonPreference getCustomRenderProperty(String attrName) { if (!customRendersProps.containsKey(attrName)) { - customRendersProps.put(attrName, new StringPreference(RENDERER_PREFERENCE_PREFIX + attrName, "").makeProfile()); + customRendersProps.put(attrName, new StringPreference(this, RENDERER_PREFERENCE_PREFIX + attrName, "").makeProfile()); } return customRendersProps.get(attrName); } @@ -2623,29 +2581,24 @@ public class OsmandSettings { getCustomRenderProperty("defAppMode"); } - Map> customBooleanRendersProps = new LinkedHashMap>(); - public CommonPreference getCustomRenderBooleanProperty(String attrName) { if (!customBooleanRendersProps.containsKey(attrName)) { - customBooleanRendersProps.put(attrName, new BooleanPreference(RENDERER_PREFERENCE_PREFIX + attrName, false).makeProfile()); + customBooleanRendersProps.put(attrName, new BooleanPreference(this, RENDERER_PREFERENCE_PREFIX + attrName, false).makeProfile()); } return customBooleanRendersProps.get(attrName); } - Map> customRoutingProps = new LinkedHashMap<>(); - public CommonPreference getCustomRoutingProperty(String attrName, String defValue) { if (!customRoutingProps.containsKey(attrName)) { - customRoutingProps.put(attrName, new StringPreference(ROUTING_PREFERENCE_PREFIX + attrName, defValue).makeProfile()); + customRoutingProps.put(attrName, new StringPreference(this, ROUTING_PREFERENCE_PREFIX + attrName, defValue).makeProfile()); } return customRoutingProps.get(attrName); } - Map> customBooleanRoutingProps = new LinkedHashMap<>(); public CommonPreference getCustomRoutingBooleanProperty(String attrName, boolean defaulfValue) { if (!customBooleanRoutingProps.containsKey(attrName)) { - customBooleanRoutingProps.put(attrName, new BooleanStringPreference(ROUTING_PREFERENCE_PREFIX + attrName, defaulfValue).makeProfile()); + customBooleanRoutingProps.put(attrName, new BooleanStringPreference(this, ROUTING_PREFERENCE_PREFIX + attrName, defaulfValue).makeProfile()); } return customBooleanRoutingProps.get(attrName); } @@ -2663,9 +2616,9 @@ public class OsmandSettings { public final OsmandPreference MAP_ACTIVITY_ENABLED = new BooleanPreference(this, "map_activity_enabled", false).makeGlobal(); // this value string is synchronized with settings_pref.xml preference name - public final OsmandPreference SAFE_MODE = new BooleanPreference("safe_mode", false).makeGlobal(); - public final OsmandPreference PT_SAFE_MODE = new BooleanPreference("pt_safe_mode", false).makeGlobal(); - public final OsmandPreference NATIVE_RENDERING_FAILED = new BooleanPreference("native_rendering_failed_init", false).makeGlobal(); + public final OsmandPreference SAFE_MODE = new BooleanPreference(this, "safe_mode", false).makeGlobal(); + public final OsmandPreference PT_SAFE_MODE = new BooleanPreference(this, "pt_safe_mode", false).makeGlobal(); + public final OsmandPreference NATIVE_RENDERING_FAILED = new BooleanPreference(this, "native_rendering_failed_init", false).makeGlobal(); public final OsmandPreference USE_OPENGL_RENDER = new BooleanPreference(this, "use_opengl_render", false /*Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH*/ @@ -2681,12 +2634,12 @@ public class OsmandSettings { public final OsmandPreference FOLLOW_THE_ROUTE = new BooleanPreference(this, "follow_to_route", false).makeGlobal(); public final OsmandPreference FOLLOW_THE_GPX_ROUTE = new StringPreference(this, "follow_gpx", null).makeGlobal(); - + public final OsmandPreference SELECTED_TRAVEL_BOOK = new StringPreference(this, "selected_travel_book", "").makeGlobal(); public final ListStringPreference DISPLAYED_TRANSPORT_SETTINGS = (ListStringPreference) new ListStringPreference(this, "displayed_transport_settings", null, ",").makeProfile(); - + public final OsmandPreference SHOW_ARRIVAL_TIME_OTHERWISE_EXPECTED_TIME = new BooleanPreference(this, "show_arrival_time", true).makeProfile(); @@ -2741,7 +2694,7 @@ public class OsmandSettings { new IntPreference(this, "FAVORITES_TAB", 0).makeGlobal().cache(); public final CommonPreference OSMAND_THEME = - new IntPreference("osmand_theme", OSMAND_LIGHT_THEME) { + new IntPreference(this, "osmand_theme", OSMAND_LIGHT_THEME) { @Override public void readFromJson(JSONObject json, ApplicationMode appMode) throws JSONException { Integer theme = parseString(json.getString(getId())); @@ -2792,7 +2745,6 @@ public class OsmandSettings { new BooleanPreference(this, "fluorescent_overlays", false).makeGlobal().cache(); - // public final OsmandPreference NUMBER_OF_FREE_DOWNLOADS_V2 = new IntPreference("free_downloads_v2", 0).makeGlobal(); public final OsmandPreference NUMBER_OF_FREE_DOWNLOADS = new IntPreference(this, NUMBER_OF_FREE_DOWNLOADS_ID, 0).makeGlobal(); @@ -2811,7 +2763,7 @@ public class OsmandSettings { new EnumStringPreference<>(this, "rate_us_state", RateUsState.INITIAL_STATE, RateUsState.values()).makeGlobal(); public final CommonPreference CUSTOM_APP_MODES_KEYS = - new StringPreference(this, "custom_app_modes_keys", "").makeGlobal().cache(); + new StringPreference(this, "custom_app_modes_keys", "").makeGlobal().cache(); public Set getCustomAppModesKeys() { String appModesKeys = CUSTOM_APP_MODES_KEYS.get(); @@ -2823,6 +2775,16 @@ public class OsmandSettings { return res; } + public void setQuickActions(HashMap quickActions, ApplicationMode mode) { + if (!QUICK_ACTION.isSetForMode(mode)) { + Boolean actionState = quickActions.get(mode.getStringKey()); + if (actionState == null) { + actionState = QUICK_ACTION.getDefaultValue(); + } + setPreference(QUICK_ACTION.getId(), actionState, mode); + } + } + public String[] getAppModeBeanPrefsIds() { return new String[]{ ICON_COLOR.getId(), @@ -2871,305 +2833,4 @@ public class OsmandSettings { DRIVING_REGION_AUTOMATIC }; } - - public enum DayNightMode { - AUTO(R.string.daynight_mode_auto, R.drawable.ic_action_map_sunset), - DAY(R.string.daynight_mode_day, R.drawable.ic_action_map_day), - NIGHT(R.string.daynight_mode_night, R.drawable.ic_action_map_night), - SENSOR(R.string.daynight_mode_sensor, R.drawable.ic_action_map_light_sensor); - - private final int key; - @DrawableRes - private final int drawableRes; - - DayNightMode(@StringRes int key, @DrawableRes int drawableRes) { - this.key = key; - this.drawableRes = drawableRes; - } - - public String toHumanString(Context ctx) { - return ctx.getString(key); - } - - @DrawableRes - public int getIconRes() { - return drawableRes; - } - - public boolean isSensor() { - return this == SENSOR; - } - - public boolean isAuto() { - return this == AUTO; - } - - public boolean isDay() { - return this == DAY; - } - - public boolean isNight() { - return this == NIGHT; - } - - public static DayNightMode[] possibleValues(Context context) { - SensorManager mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); - Sensor mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); - boolean isLightSensorEnabled = mLight != null; - if (isLightSensorEnabled) { - return DayNightMode.values(); - } else { - return new DayNightMode[]{AUTO, DAY, NIGHT}; - } - } - } - - - public enum LayerTransparencySeekbarMode { - OVERLAY(R.string.overlay_transparency), - UNDERLAY(R.string.map_transparency), - OFF(R.string.shared_string_off), - UNDEFINED(R.string.shared_string_none); - - private final int key; - - LayerTransparencySeekbarMode(int key) { - this.key = key; - } - - public String toHumanString(Context ctx) { - return ctx.getString(key); - } - } - - public enum NotesSortByMode { - BY_TYPE, - BY_DATE; - - public boolean isByType() { - return this == BY_TYPE; - } - - public boolean isByDate() { - return this == BY_DATE; - } - } - - public enum TracksSortByMode { - BY_DATE(R.string.sort_last_modified, R.drawable.ic_action_time_start), - BY_NAME_ASCENDING(R.string.sort_name_ascending, R.drawable.ic_action_sort_by_name_ascending), - BY_NAME_DESCENDING(R.string.sort_name_descending, R.drawable.ic_action_sort_by_name_descending); - - private final int iconId; - private final int nameId; - - TracksSortByMode(int nameId, int iconId) { - this.nameId = nameId; - this.iconId = iconId; - } - - public boolean isByName() { - return this == BY_NAME_ASCENDING || this == BY_NAME_DESCENDING; - } - - public boolean isByDate() { - return this == BY_DATE; - } - - @StringRes - public int getNameId() { - return nameId; - } - - @DrawableRes - public int getIconId() { - return iconId; - } - } - - public enum MapMarkersMode { - TOOLBAR(R.string.shared_string_topbar), - WIDGETS(R.string.shared_string_widgets), - NONE(R.string.shared_string_none); - - private final int key; - - MapMarkersMode(int key) { - this.key = key; - } - - public String toHumanString(Context ctx) { - return ctx.getString(key); - } - - public boolean isToolbar() { - return this == TOOLBAR; - } - - public boolean isWidgets() { - return this == WIDGETS; - } - - public boolean isNone() { - return this == NONE; - } - - public static MapMarkersMode[] possibleValues(Context context) { - return new MapMarkersMode[]{TOOLBAR, WIDGETS, NONE}; - } - } - - public enum SpeedConstants { - KILOMETERS_PER_HOUR(R.string.km_h, R.string.si_kmh, false), - MILES_PER_HOUR(R.string.mile_per_hour, R.string.si_mph, true), - METERS_PER_SECOND(R.string.m_s, R.string.si_m_s, false), - MINUTES_PER_MILE(R.string.min_mile, R.string.si_min_m, true), - MINUTES_PER_KILOMETER(R.string.min_km, R.string.si_min_km, false), - NAUTICALMILES_PER_HOUR(R.string.nm_h, R.string.si_nm_h, true); - - public final int key; - public final int descr; - public final boolean imperial; - - SpeedConstants(int key, int descr, boolean imperial) { - this.key = key; - this.descr = descr; - this.imperial = imperial; - } - - - - public String toHumanString(Context ctx) { - return ctx.getString(descr); - } - - public String toShortString(Context ctx) { - return ctx.getString(key); - } - - - } - - public enum MetricsConstants { - KILOMETERS_AND_METERS(R.string.si_km_m, "km-m"), - MILES_AND_FEET(R.string.si_mi_feet, "mi-f"), - MILES_AND_METERS(R.string.si_mi_meters, "mi-m"), - MILES_AND_YARDS(R.string.si_mi_yard, "mi-y"), - NAUTICAL_MILES(R.string.si_nm, "nm"); - - private final int key; - private final String ttsString; - - MetricsConstants(int key, String ttsString) { - this.key = key; - this.ttsString = ttsString; - } - - public String toHumanString(Context ctx) { - return ctx.getString(key); - } - - public String toTTSString() { - return ttsString; - } - - } - - public enum AngularConstants { - DEGREES(R.string.shared_string_degrees, "°"), - DEGREES360(R.string.shared_string_degrees, "°"), - MILLIRADS(R.string.shared_string_milliradians, "mil"); - - private final int key; - private final String unit; - - AngularConstants(int key, String unit) { - this.key = key; - this.unit = unit; - } - - public String toHumanString(Context ctx) { - return ctx.getString(key); - } - public String getUnitSymbol() { - return unit; - } - - } - - public enum AutoZoomMap { - FARTHEST(R.string.auto_zoom_farthest, 1f, 15.5f), - FAR(R.string.auto_zoom_far, 1.4f, 17f), - CLOSE(R.string.auto_zoom_close, 2f, 19f); - public final float coefficient; - public final int name; - public final float maxZoom; - - AutoZoomMap(int name, float coefficient, float maxZoom) { - this.name = name; - this.coefficient = coefficient; - this.maxZoom = maxZoom; - - } - } - - /** - * Class represents specific for driving region - * Signs, leftHandDriving - */ - public enum DrivingRegion { - - EUROPE_ASIA(R.string.driving_region_europe_asia, MetricsConstants.KILOMETERS_AND_METERS, false), - US(R.string.driving_region_us, MetricsConstants.MILES_AND_FEET, false), - CANADA(R.string.driving_region_canada, MetricsConstants.KILOMETERS_AND_METERS, false), - UK_AND_OTHERS(R.string.driving_region_uk, MetricsConstants.MILES_AND_METERS, true), - JAPAN(R.string.driving_region_japan, MetricsConstants.KILOMETERS_AND_METERS, true), - AUSTRALIA(R.string.driving_region_australia, MetricsConstants.KILOMETERS_AND_METERS, true); - - public final boolean leftHandDriving; - public final MetricsConstants defMetrics; - public final int name; - - DrivingRegion(int name, MetricsConstants def, boolean leftHandDriving) { - this.name = name; - defMetrics = def; - this.leftHandDriving = leftHandDriving; - } - - public boolean isAmericanTypeSigns() { - return this == OsmandSettings.DrivingRegion.AUSTRALIA || - this == OsmandSettings.DrivingRegion.US || - this == OsmandSettings.DrivingRegion.CANADA; - } - - public String getDescription(Context ctx) { - return ctx.getString(leftHandDriving ? R.string.left_side_navigation : R.string.right_side_navigation) + - ", " + - defMetrics.toHumanString(ctx).toLowerCase(); - } - } - - public enum RulerMode { - FIRST, - SECOND, - EMPTY - } - - public enum WikiArticleShowImages { - ON(R.string.shared_string_on), - OFF(R.string.shared_string_off), - WIFI(R.string.shared_string_wifi_only); - - public final int name; - - WikiArticleShowImages(int name) { - this.name = name; - } - } - - public enum TerrainMode { - HILLSHADE, - SLOPE - } - } diff --git a/OsmAnd/src/net/osmand/plus/settings/bottomsheets/ChangeDataStorageBottomSheet.java b/OsmAnd/src/net/osmand/plus/settings/bottomsheets/ChangeDataStorageBottomSheet.java index 334cc42aa8..e61faafe16 100644 --- a/OsmAnd/src/net/osmand/plus/settings/bottomsheets/ChangeDataStorageBottomSheet.java +++ b/OsmAnd/src/net/osmand/plus/settings/bottomsheets/ChangeDataStorageBottomSheet.java @@ -11,8 +11,8 @@ import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; +import net.osmand.FileUtils; import net.osmand.PlatformUtil; -import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.base.bottomsheetmenu.BaseBottomSheetItem; @@ -63,7 +63,7 @@ public class ChangeDataStorageBottomSheet extends BasePreferenceBottomSheet { CharSequence desc = null; File currentStorageFile = new File(currentDirectory.getDirectory()); - if ((!OsmandSettings.isWritable(currentStorageFile))) { + if ((!FileUtils.isWritable(currentStorageFile))) { desc = String.format(getString(R.string.android_19_location_disabled), currentStorageFile.getAbsoluteFile()); } else { String from = currentDirectory.getKey().equals(MANUALLY_SPECIFIED) ? currentDirectory.getDirectory() : currentDirectory.getTitle(); diff --git a/OsmAnd/src/net/osmand/plus/settings/bottomsheets/RecalculateRouteInDeviationBottomSheet.java b/OsmAnd/src/net/osmand/plus/settings/bottomsheets/RecalculateRouteInDeviationBottomSheet.java index 5d37d40b3b..d2679564a8 100644 --- a/OsmAnd/src/net/osmand/plus/settings/bottomsheets/RecalculateRouteInDeviationBottomSheet.java +++ b/OsmAnd/src/net/osmand/plus/settings/bottomsheets/RecalculateRouteInDeviationBottomSheet.java @@ -14,6 +14,7 @@ import androidx.fragment.app.FragmentManager; import com.google.android.material.slider.Slider; import net.osmand.AndroidUtils; +import net.osmand.plus.helpers.enums.MetricsConstants; import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; @@ -76,8 +77,8 @@ public class RecalculateRouteInDeviationBottomSheet extends BooleanPreferenceBot int contentPaddingSmall = app.getResources().getDimensionPixelSize(R.dimen.content_padding_small); int contentPadding = app.getResources().getDimensionPixelSize(R.dimen.content_padding); - OsmandSettings.MetricsConstants mc = settings.METRIC_SYSTEM.get(); - if (mc == OsmandSettings.MetricsConstants.KILOMETERS_AND_METERS) { + MetricsConstants mc = settings.METRIC_SYSTEM.get(); + if (mc == MetricsConstants.KILOMETERS_AND_METERS) { entryValues = new Float[]{10.f, 20.0f, 30.0f, 50.0f, 100.0f, 200.0f, 500.0f, 1000.0f, 1500.0f}; } else { entryValues = new Float[]{9.1f, 18.3f, 30.5f, 45.7f, 91.5f, 183.0f, 482.0f, 965.0f, 1609.0f}; diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/DataStorageFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/DataStorageFragment.java index 93719a83ab..842b53e2fa 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/DataStorageFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/DataStorageFragment.java @@ -23,6 +23,7 @@ import androidx.preference.PreferenceScreen; import androidx.preference.PreferenceViewHolder; import net.osmand.AndroidUtils; +import net.osmand.FileUtils; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.ProgressImplementation; @@ -408,7 +409,7 @@ public class DataStorageFragment extends BaseSettingsFragment implements DataSto String newDirectory = newStorageDirectory.getDirectory(); int type = newStorageDirectory.getType(); File newDirectoryFile = new File(newDirectory); - boolean wr = OsmandSettings.isWritable(newDirectoryFile); + boolean wr = FileUtils.isWritable(newDirectoryFile); if (wr) { app.setExternalStorageDirectory(type, newDirectory); reloadData(); diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/GeneralProfileSettingsFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/GeneralProfileSettingsFragment.java index 0cd1e628bb..3a81548285 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/GeneralProfileSettingsFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/GeneralProfileSettingsFragment.java @@ -22,9 +22,12 @@ import androidx.preference.PreferenceViewHolder; import androidx.preference.SwitchPreferenceCompat; import net.osmand.data.PointDescription; +import net.osmand.plus.helpers.enums.AngularConstants; +import net.osmand.plus.helpers.enums.MetricsConstants; +import net.osmand.plus.helpers.enums.SpeedConstants; import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.DrivingRegion; +import net.osmand.plus.helpers.enums.DrivingRegion; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.Version; @@ -186,7 +189,7 @@ public class GeneralProfileSettingsFragment extends BaseSettingsFragment impleme } private void setupUnitsOfLengthPref() { - OsmandSettings.MetricsConstants[] metricsConstants = OsmandSettings.MetricsConstants.values(); + MetricsConstants[] metricsConstants = MetricsConstants.values(); String[] entries = new String[metricsConstants.length]; Integer[] entryValues = new Integer[metricsConstants.length]; @@ -208,20 +211,20 @@ public class GeneralProfileSettingsFragment extends BaseSettingsFragment impleme } private void setupAngularUnitsPref() { - OsmandSettings.AngularConstants[] ac = OsmandSettings.AngularConstants.values(); + AngularConstants[] ac = AngularConstants.values(); String[] entries = new String[ac.length]; Integer[] entryValues = new Integer[ac.length]; for (int i = 0; i < entries.length; i++) { - if (ac[i] == OsmandSettings.AngularConstants.DEGREES) { - entries[i] = OsmandSettings.AngularConstants.DEGREES.toHumanString(app) + " 180"; - entryValues[i] = OsmandSettings.AngularConstants.DEGREES.ordinal(); - } else if (ac[i] == OsmandSettings.AngularConstants.DEGREES360) { - entries[i] = OsmandSettings.AngularConstants.DEGREES.toHumanString(app) + " 360"; - entryValues[i] = OsmandSettings.AngularConstants.DEGREES360.ordinal(); + if (ac[i] == AngularConstants.DEGREES) { + entries[i] = AngularConstants.DEGREES.toHumanString(app) + " 180"; + entryValues[i] = AngularConstants.DEGREES.ordinal(); + } else if (ac[i] == AngularConstants.DEGREES360) { + entries[i] = AngularConstants.DEGREES.toHumanString(app) + " 360"; + entryValues[i] = AngularConstants.DEGREES360.ordinal(); } else { entries[i] = ac[i].toHumanString(app); - entryValues[i] = OsmandSettings.AngularConstants.MILLIRADS.ordinal(); + entryValues[i] = AngularConstants.MILLIRADS.ordinal(); } } @@ -232,7 +235,7 @@ public class GeneralProfileSettingsFragment extends BaseSettingsFragment impleme } private void setupSpeedSystemPref() { - OsmandSettings.SpeedConstants[] speedConstants = OsmandSettings.SpeedConstants.values(); + SpeedConstants[] speedConstants = SpeedConstants.values(); String[] entries = new String[speedConstants.length]; Integer[] entryValues = new Integer[speedConstants.length]; @@ -377,14 +380,14 @@ public class GeneralProfileSettingsFragment extends BaseSettingsFragment impleme if (mapViewTrackingUtilities != null) { mapViewTrackingUtilities.resetDrivingRegionUpdate(); } - } else if (newValue instanceof OsmandSettings.DrivingRegion) { + } else if (newValue instanceof DrivingRegion) { applyPreference(settings.DRIVING_REGION_AUTOMATIC.getId(), applyToAllProfiles, false); if (applyToAllProfiles) { for (ApplicationMode appMode : ApplicationMode.allPossibleValues()) { - settings.DRIVING_REGION.setModeValue(appMode, (OsmandSettings.DrivingRegion) newValue); + settings.DRIVING_REGION.setModeValue(appMode, (DrivingRegion) newValue); } } else { - settings.DRIVING_REGION.setModeValue(selectedMode, (OsmandSettings.DrivingRegion) newValue); + settings.DRIVING_REGION.setModeValue(selectedMode, (DrivingRegion) newValue); } } updateAllSettings(); diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/MapDuringNavigationFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/MapDuringNavigationFragment.java index 06aa0c4c08..0fe5a6d6a3 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/MapDuringNavigationFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/MapDuringNavigationFragment.java @@ -2,8 +2,8 @@ package net.osmand.plus.settings.fragments; import androidx.preference.Preference; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.AutoZoomMap; +import net.osmand.plus.helpers.enums.MetricsConstants; +import net.osmand.plus.helpers.enums.AutoZoomMap; import net.osmand.plus.R; import net.osmand.plus.settings.preferences.ListPreferenceEx; import net.osmand.plus.settings.preferences.SwitchPreferenceEx; @@ -78,7 +78,7 @@ public class MapDuringNavigationFragment extends BaseSettingsFragment { Float[] valuesKmh = new Float[]{0f, 5f, 7f, 10f, 15f, 20f}; Float[] valuesMph = new Float[]{0f, 3f, 5f, 7f, 10f, 15f}; String[] names; - if (settings.METRIC_SYSTEM.getModeValue(getSelectedAppMode()) == OsmandSettings.MetricsConstants.KILOMETERS_AND_METERS) { + if (settings.METRIC_SYSTEM.getModeValue(getSelectedAppMode()) == MetricsConstants.KILOMETERS_AND_METERS) { names = new String[valuesKmh.length]; for (int i = 0; i < names.length; i++) { names[i] = valuesKmh[i].intValue() + " " + getString(R.string.km_h); @@ -113,7 +113,7 @@ public class MapDuringNavigationFragment extends BaseSettingsFragment { } else { applyPreference(settings.AUTO_ZOOM_MAP.getId(), applyToAllProfiles, true); applyPreference(settings.AUTO_ZOOM_MAP_SCALE.getId(), - applyToAllProfiles, OsmandSettings.AutoZoomMap.values()[position - 1]); + applyToAllProfiles, AutoZoomMap.values()[position - 1]); } } } else { diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java index 00ec37480a..12e1fba73c 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java @@ -37,7 +37,6 @@ import net.osmand.plus.activities.SettingsBaseActivity; import net.osmand.plus.activities.SettingsNavigationActivity; import net.osmand.plus.routing.RouteProvider; import net.osmand.plus.routing.RoutingHelper; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; import net.osmand.plus.settings.bottomsheets.RecalculateRouteInDeviationBottomSheet; import net.osmand.plus.settings.preferences.ListPreferenceEx; import net.osmand.plus.settings.preferences.MultiSelectBooleanPreference; diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/VehicleParametersFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/VehicleParametersFragment.java index df1af1a693..dfed2c5930 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/VehicleParametersFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/VehicleParametersFragment.java @@ -14,7 +14,7 @@ import net.osmand.plus.activities.SettingsBaseActivity; import net.osmand.plus.routing.RouteProvider.RouteService; import net.osmand.plus.routing.RoutingHelper; import net.osmand.plus.settings.backend.ApplicationMode; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.StringPreference; import net.osmand.plus.settings.bottomsheets.VehicleParametersBottomSheet; import net.osmand.plus.settings.bottomsheets.VehicleSizeAssets; import net.osmand.plus.settings.preferences.ListPreferenceEx; @@ -72,7 +72,7 @@ public class VehicleParametersFragment extends BaseSettingsFragment implements O parameter.getDescription()); String defValue = parameter.getType() == RoutingParameterType.NUMERIC ? ROUTING_PARAMETER_NUMERIC_DEFAULT : ROUTING_PARAMETER_SYMBOLIC_DEFAULT; - OsmandSettings.StringPreference pref = (OsmandSettings.StringPreference) app.getSettings() + StringPreference pref = (StringPreference) app.getSettings() .getCustomRoutingProperty(parameterId, defValue); VehicleSizeAssets assets = VehicleSizeAssets.getAssets(parameterId, routerProfile); Object[] values = parameter.getPossibleValues(); diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/VoiceAnnouncesFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/VoiceAnnouncesFragment.java index 4ff8f3262d..8013baeb63 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/VoiceAnnouncesFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/VoiceAnnouncesFragment.java @@ -18,6 +18,7 @@ import androidx.preference.SwitchPreferenceCompat; import net.osmand.AndroidUtils; import net.osmand.plus.dialogs.SpeedCamerasBottomSheet; +import net.osmand.plus.helpers.enums.MetricsConstants; import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; @@ -107,7 +108,7 @@ public class VoiceAnnouncesFragment extends BaseSettingsFragment implements OnPr Float[] valuesKmh = new Float[]{-10f, -7f, -5f, 0f, 5f, 7f, 10f, 15f, 20f}; Float[] valuesMph = new Float[]{-7f, -5f, -3f, 0f, 3f, 5f, 7f, 10f, 15f}; String[] names; - if (settings.METRIC_SYSTEM.getModeValue(getSelectedAppMode()) == OsmandSettings.MetricsConstants.KILOMETERS_AND_METERS) { + if (settings.METRIC_SYSTEM.getModeValue(getSelectedAppMode()) == MetricsConstants.KILOMETERS_AND_METERS) { names = new String[valuesKmh.length]; for (int i = 0; i < names.length; i++) { names[i] = valuesKmh[i].intValue() + " " + getString(R.string.km_h); diff --git a/OsmAnd/src/net/osmand/plus/settings/preferences/ListPreferenceEx.java b/OsmAnd/src/net/osmand/plus/settings/preferences/ListPreferenceEx.java index b1ea56806d..07e5d088b9 100644 --- a/OsmAnd/src/net/osmand/plus/settings/preferences/ListPreferenceEx.java +++ b/OsmAnd/src/net/osmand/plus/settings/preferences/ListPreferenceEx.java @@ -8,7 +8,6 @@ import androidx.preference.DialogPreference; import androidx.preference.PreferenceDataStore; import net.osmand.plus.settings.backend.ApplicationMode; -import net.osmand.plus.settings.backend.OsmandSettings.PreferencesDataStore; import net.osmand.plus.settings.backend.OsmAndPreferencesDataStore; public class ListPreferenceEx extends DialogPreference { diff --git a/OsmAnd/src/net/osmand/plus/srtmplugin/SRTMPlugin.java b/OsmAnd/src/net/osmand/plus/srtmplugin/SRTMPlugin.java index 7b477176a4..5a186e75d0 100644 --- a/OsmAnd/src/net/osmand/plus/srtmplugin/SRTMPlugin.java +++ b/OsmAnd/src/net/osmand/plus/srtmplugin/SRTMPlugin.java @@ -21,7 +21,6 @@ import net.osmand.plus.DialogListItemAdapter; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.TerrainMode; import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; diff --git a/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainFragment.java b/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainFragment.java index b613d2ba13..3635aafe89 100644 --- a/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainFragment.java +++ b/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainFragment.java @@ -43,7 +43,6 @@ import net.osmand.plus.download.DownloadValidationManager; import net.osmand.plus.download.IndexItem; import net.osmand.plus.helpers.FontCache; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.TerrainMode; import net.osmand.plus.widgets.style.CustomTypefaceSpan; import org.apache.commons.logging.Log; @@ -55,8 +54,8 @@ import java.util.List; import static net.osmand.plus.UiUtilities.CustomRadioButtonType.*; import static net.osmand.plus.download.DownloadActivityType.HILLSHADE_FILE; import static net.osmand.plus.download.DownloadActivityType.SLOPE_FILE; -import static net.osmand.plus.settings.backend.OsmandSettings.TerrainMode.HILLSHADE; -import static net.osmand.plus.settings.backend.OsmandSettings.TerrainMode.SLOPE; +import static net.osmand.plus.srtmplugin.TerrainMode.HILLSHADE; +import static net.osmand.plus.srtmplugin.TerrainMode.SLOPE; import static net.osmand.plus.srtmplugin.SRTMPlugin.TERRAIN_MAX_ZOOM; import static net.osmand.plus.srtmplugin.SRTMPlugin.TERRAIN_MIN_ZOOM; diff --git a/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainLayer.java b/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainLayer.java index 8f75c68259..79e47de648 100644 --- a/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainLayer.java +++ b/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainLayer.java @@ -18,7 +18,6 @@ import net.osmand.plus.OsmandApplication; import net.osmand.plus.SQLiteTileSource; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.api.SQLiteAPI.SQLiteConnection; -import net.osmand.plus.settings.backend.OsmandSettings.TerrainMode; import net.osmand.plus.views.MapTileLayer; import net.osmand.util.Algorithms; @@ -31,7 +30,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import static net.osmand.plus.settings.backend.OsmandSettings.TerrainMode.HILLSHADE; +import static net.osmand.plus.srtmplugin.TerrainMode.HILLSHADE; public class TerrainLayer extends MapTileLayer { diff --git a/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainMode.java b/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainMode.java new file mode 100644 index 0000000000..e9f3d20d9f --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainMode.java @@ -0,0 +1,6 @@ +package net.osmand.plus.srtmplugin; + +public enum TerrainMode { + HILLSHADE, + SLOPE +} diff --git a/OsmAnd/src/net/osmand/plus/track/ShowStartFinishCard.java b/OsmAnd/src/net/osmand/plus/track/ShowStartFinishCard.java index 3941bdbb15..eaf145379c 100644 --- a/OsmAnd/src/net/osmand/plus/track/ShowStartFinishCard.java +++ b/OsmAnd/src/net/osmand/plus/track/ShowStartFinishCard.java @@ -10,8 +10,7 @@ import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.helpers.AndroidUiHelper; import net.osmand.plus.routepreparationmenu.cards.BaseCard; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; class ShowStartFinishCard extends BaseCard { diff --git a/OsmAnd/src/net/osmand/plus/track/TrackAppearanceFragment.java b/OsmAnd/src/net/osmand/plus/track/TrackAppearanceFragment.java index 81a43da20f..2276d57cd2 100644 --- a/OsmAnd/src/net/osmand/plus/track/TrackAppearanceFragment.java +++ b/OsmAnd/src/net/osmand/plus/track/TrackAppearanceFragment.java @@ -41,7 +41,7 @@ import net.osmand.plus.dialogs.GpxAppearanceAdapter; import net.osmand.plus.helpers.AndroidUiHelper; import net.osmand.plus.routepreparationmenu.cards.BaseCard; import net.osmand.plus.routepreparationmenu.cards.BaseCard.CardListener; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.track.CustomColorBottomSheet.ColorPickerListener; import net.osmand.plus.track.SplitTrackAsyncTask.SplitTrackListener; import net.osmand.render.RenderingRulesStorage; @@ -185,7 +185,7 @@ public class TrackAppearanceFragment extends ContextMenuScrollFragment implement } if (color == 0) { RenderingRulesStorage renderer = app.getRendererRegistry().getCurrentSelectedRenderer(); - OsmandSettings.CommonPreference prefColor = app.getSettings().getCustomRenderProperty(CURRENT_TRACK_COLOR_ATTR); + CommonPreference prefColor = app.getSettings().getCustomRenderProperty(CURRENT_TRACK_COLOR_ATTR); color = GpxAppearanceAdapter.parseTrackColor(renderer, prefColor.get()); } trackDrawInfo.setColor(color); diff --git a/OsmAnd/src/net/osmand/plus/views/layers/GPXLayer.java b/OsmAnd/src/net/osmand/plus/views/layers/GPXLayer.java index 641944ce21..46d51bca33 100644 --- a/OsmAnd/src/net/osmand/plus/views/layers/GPXLayer.java +++ b/OsmAnd/src/net/osmand/plus/views/layers/GPXLayer.java @@ -50,7 +50,7 @@ import net.osmand.plus.mapcontextmenu.other.TrackChartPoints; import net.osmand.plus.render.OsmandRenderer; import net.osmand.plus.render.OsmandRenderer.RenderingContext; import net.osmand.plus.routepreparationmenu.MapRouteInfoMenu; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; +import net.osmand.plus.settings.backend.CommonPreference; import net.osmand.plus.track.SaveGpxAsyncTask; import net.osmand.plus.track.TrackDrawInfo; import net.osmand.plus.views.OsmandMapLayer; diff --git a/OsmAnd/src/net/osmand/plus/views/layers/MapControlsLayer.java b/OsmAnd/src/net/osmand/plus/views/layers/MapControlsLayer.java index 2d813e0bd9..6a4cf344c7 100644 --- a/OsmAnd/src/net/osmand/plus/views/layers/MapControlsLayer.java +++ b/OsmAnd/src/net/osmand/plus/views/layers/MapControlsLayer.java @@ -47,7 +47,7 @@ import net.osmand.plus.OsmandPlugin; import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.LayerTransparencySeekbarMode; +import net.osmand.plus.rastermaps.LayerTransparencySeekbarMode; import net.osmand.plus.R; import net.osmand.plus.TargetPointsHelper; import net.osmand.plus.TargetPointsHelper.TargetPoint; @@ -67,9 +67,6 @@ import net.osmand.plus.routing.RoutingHelper; import net.osmand.plus.search.QuickSearchDialogFragment.QuickSearchType; import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.settings.backend.OsmAndAppCustomization; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.LayerTransparencySeekbarMode; import net.osmand.plus.views.OsmandMapLayer; import net.osmand.plus.views.OsmandMapTileView; import net.osmand.plus.views.corenative.NativeCoreContext; diff --git a/OsmAnd/src/net/osmand/plus/views/layers/RulerControlLayer.java b/OsmAnd/src/net/osmand/plus/views/layers/RulerControlLayer.java index 7847b6e7c3..e6f864af3d 100644 --- a/OsmAnd/src/net/osmand/plus/views/layers/RulerControlLayer.java +++ b/OsmAnd/src/net/osmand/plus/views/layers/RulerControlLayer.java @@ -29,10 +29,9 @@ import net.osmand.data.QuadPoint; import net.osmand.data.RotatedTileBox; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; +import net.osmand.plus.helpers.enums.MetricsConstants; import net.osmand.plus.settings.backend.OsmandPreference; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.AngularConstants; -import net.osmand.plus.settings.backend.OsmandSettings.RulerMode; +import net.osmand.plus.helpers.enums.AngularConstants; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.views.OsmandMapLayer; @@ -72,7 +71,7 @@ public class RulerControlLayer extends OsmandMapLayer { private QuadPoint cacheCenter; private float cacheMapDensity; private OsmandPreference mapDensity; - private OsmandSettings.MetricsConstants cacheMetricSystem; + private MetricsConstants cacheMetricSystem; private int cacheIntZoom; private LatLon cacheCenterLatLon; private long cacheMultiTouchEndTime; @@ -452,7 +451,7 @@ public class RulerControlLayer extends OsmandMapLayer { updateCenter(tb, center); } - OsmandSettings.MetricsConstants currentMetricSystem = app.getSettings().METRIC_SYSTEM.get(); + MetricsConstants currentMetricSystem = app.getSettings().METRIC_SYSTEM.get(); boolean updateCache = tb.getZoom() != cacheIntZoom || !tb.getCenterLatLon().equals(cacheCenterLatLon) || mapDensity.get() != cacheMapDensity || cacheMetricSystem != currentMetricSystem; diff --git a/OsmAnd/src/net/osmand/plus/views/layers/RulerMode.java b/OsmAnd/src/net/osmand/plus/views/layers/RulerMode.java new file mode 100644 index 0000000000..db5d6d8e61 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/views/layers/RulerMode.java @@ -0,0 +1,7 @@ +package net.osmand.plus.views.layers; + +public enum RulerMode { + FIRST, + SECOND, + EMPTY +} diff --git a/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapInfoWidgetsFactory.java b/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapInfoWidgetsFactory.java index bf75a64bac..4aafc1b2af 100644 --- a/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapInfoWidgetsFactory.java +++ b/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapInfoWidgetsFactory.java @@ -48,9 +48,8 @@ import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmAndLocationProvider; import net.osmand.plus.OsmAndLocationProvider.GPSInfo; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.RulerMode; +import net.osmand.plus.views.layers.RulerMode; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; import net.osmand.plus.activities.MapActivity; @@ -66,8 +65,6 @@ import net.osmand.plus.routepreparationmenu.ShowAlongTheRouteBottomSheet; import net.osmand.plus.routing.RouteCalculationResult; import net.osmand.plus.routing.RouteDirectionInfo; import net.osmand.plus.routing.RoutingHelper; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.RulerMode; import net.osmand.plus.views.OsmandMapLayer.DrawSettings; import net.osmand.plus.views.OsmandMapTileView; import net.osmand.plus.views.layers.RulerControlLayer; diff --git a/OsmAnd/src/net/osmand/plus/views/mapwidgets/RouteInfoWidgetsFactory.java b/OsmAnd/src/net/osmand/plus/views/mapwidgets/RouteInfoWidgetsFactory.java index 782dc4c04f..f77bc27f36 100644 --- a/OsmAnd/src/net/osmand/plus/views/mapwidgets/RouteInfoWidgetsFactory.java +++ b/OsmAnd/src/net/osmand/plus/views/mapwidgets/RouteInfoWidgetsFactory.java @@ -25,8 +25,6 @@ import net.osmand.plus.activities.MapActivity; import net.osmand.plus.base.MapViewTrackingUtilities; import net.osmand.plus.routing.RouteCalculationResult.NextDirectionInfo; import net.osmand.plus.routing.RoutingHelper; -import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; import net.osmand.plus.views.OsmandMapLayer.DrawSettings; import net.osmand.plus.views.OsmandMapTileView; import net.osmand.plus.views.mapwidgets.widgets.AlarmWidget; diff --git a/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgets/AlarmWidget.java b/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgets/AlarmWidget.java index a75422967d..2dc092139e 100644 --- a/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgets/AlarmWidget.java +++ b/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgets/AlarmWidget.java @@ -16,6 +16,7 @@ import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.base.MapViewTrackingUtilities; import net.osmand.plus.helpers.AndroidUiHelper; +import net.osmand.plus.helpers.enums.DrivingRegion; import net.osmand.plus.helpers.WaypointHelper; import net.osmand.plus.routing.AlarmInfo; import net.osmand.plus.routing.RoutingHelper; @@ -40,7 +41,7 @@ public class AlarmWidget { private int imgId; private String cachedText; private String cachedBottomText; - private OsmandSettings.DrivingRegion cachedRegion; + private DrivingRegion cachedRegion; public AlarmWidget(final OsmandApplication app, MapActivity ma) { layout = ma.findViewById(R.id.map_alarm_warning); @@ -81,9 +82,9 @@ public class AlarmWidget { int locimgId = R.drawable.warnings_limit; String text = ""; String bottomText = ""; - OsmandSettings.DrivingRegion region = settings.DRIVING_REGION.get(); + DrivingRegion region = settings.DRIVING_REGION.get(); boolean americanType = region.isAmericanTypeSigns(); - boolean isCanadianRegion = region == OsmandSettings.DrivingRegion.CANADA; + boolean isCanadianRegion = region == DrivingRegion.CANADA; if (alarm.getType() == AlarmInfo.AlarmInfoType.SPEED_LIMIT) { if (isCanadianRegion) { locimgId = R.drawable.warnings_speed_limit_ca; diff --git a/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgets/RulerWidget.java b/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgets/RulerWidget.java index 8d576c72cf..636ef0af5a 100644 --- a/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgets/RulerWidget.java +++ b/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgets/RulerWidget.java @@ -10,7 +10,7 @@ import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.helpers.AndroidUiHelper; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; import net.osmand.plus.views.OsmandMapLayer.DrawSettings; import net.osmand.plus.views.OsmandMapTileView; diff --git a/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgetstates/BearingWidgetState.java b/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgetstates/BearingWidgetState.java index ce4761eab1..d3fc793ee1 100644 --- a/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgetstates/BearingWidgetState.java +++ b/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgetstates/BearingWidgetState.java @@ -2,14 +2,14 @@ package net.osmand.plus.views.mapwidgets.widgetstates; import net.osmand.plus.OsmandApplication; import net.osmand.plus.R; -import net.osmand.plus.settings.backend.OsmandSettings; +import net.osmand.plus.settings.backend.OsmandPreference; public class BearingWidgetState extends WidgetState { public static final int BEARING_WIDGET_STATE_RELATIVE_BEARING = R.id.bearing_widget_state_relative_bearing; public static final int BEARING_WIDGET_STATE_MAGNETIC_BEARING = R.id.bearing_widget_state_magnetic_bearing; - private final OsmandSettings.OsmandPreference showRelativeBearing; + private final OsmandPreference showRelativeBearing; public BearingWidgetState(OsmandApplication ctx) { super(ctx); diff --git a/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgetstates/CompassRulerWidgetState.java b/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgetstates/CompassRulerWidgetState.java index eb77043746..39de1d653c 100644 --- a/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgetstates/CompassRulerWidgetState.java +++ b/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgetstates/CompassRulerWidgetState.java @@ -2,7 +2,7 @@ package net.osmand.plus.views.mapwidgets.widgetstates; import net.osmand.plus.OsmandApplication; import net.osmand.plus.R; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; public class CompassRulerWidgetState extends WidgetState { diff --git a/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgetstates/TimeWidgetState.java b/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgetstates/TimeWidgetState.java index 3274245a0c..b42d5a970d 100644 --- a/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgetstates/TimeWidgetState.java +++ b/OsmAnd/src/net/osmand/plus/views/mapwidgets/widgetstates/TimeWidgetState.java @@ -2,7 +2,7 @@ package net.osmand.plus.views.mapwidgets.widgetstates; import net.osmand.plus.OsmandApplication; import net.osmand.plus.R; -import net.osmand.plus.settings.backend.OsmandSettings.OsmandPreference; +import net.osmand.plus.settings.backend.OsmandPreference; public class TimeWidgetState extends WidgetState { diff --git a/OsmAnd/src/net/osmand/plus/voice/AbstractPrologCommandPlayer.java b/OsmAnd/src/net/osmand/plus/voice/AbstractPrologCommandPlayer.java index 74c0de1508..44f301945f 100644 --- a/OsmAnd/src/net/osmand/plus/voice/AbstractPrologCommandPlayer.java +++ b/OsmAnd/src/net/osmand/plus/voice/AbstractPrologCommandPlayer.java @@ -12,7 +12,7 @@ import net.osmand.StateChangedListener; import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.OsmandSettings; -import net.osmand.plus.settings.backend.OsmandSettings.MetricsConstants; +import net.osmand.plus.helpers.enums.MetricsConstants; import net.osmand.plus.R; import net.osmand.plus.api.AudioFocusHelper; diff --git a/OsmAnd/src/net/osmand/plus/wikipedia/WikiArticleBaseDialogFragment.java b/OsmAnd/src/net/osmand/plus/wikipedia/WikiArticleBaseDialogFragment.java index 302140ba03..0e15c2b4a9 100644 --- a/OsmAnd/src/net/osmand/plus/wikipedia/WikiArticleBaseDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/wikipedia/WikiArticleBaseDialogFragment.java @@ -13,7 +13,6 @@ import androidx.annotation.NonNull; import net.osmand.AndroidUtils; import net.osmand.IndexConstants; -import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.wikivoyage.WikiBaseDialogFragment; @@ -94,7 +93,7 @@ public abstract class WikiArticleBaseDialogFragment extends WikiBaseDialogFragme protected void updateWebSettings() { - OsmandSettings.WikiArticleShowImages showImages = getSettings().WIKI_ARTICLE_SHOW_IMAGES.get(); + WikiArticleShowImages showImages = getSettings().WIKI_ARTICLE_SHOW_IMAGES.get(); WebSettings webSettings = contentWebView.getSettings(); switch (showImages) { case ON: diff --git a/OsmAnd/src/net/osmand/plus/wikipedia/WikiArticleShowImages.java b/OsmAnd/src/net/osmand/plus/wikipedia/WikiArticleShowImages.java new file mode 100644 index 0000000000..ea3d8a925b --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/wikipedia/WikiArticleShowImages.java @@ -0,0 +1,15 @@ +package net.osmand.plus.wikipedia; + +import net.osmand.plus.R; + +public enum WikiArticleShowImages { + ON(R.string.shared_string_on), + OFF(R.string.shared_string_off), + WIFI(R.string.shared_string_wifi_only); + + public final int name; + + WikiArticleShowImages(int name) { + this.name = name; + } +} diff --git a/OsmAnd/src/net/osmand/plus/wikipedia/WikipediaOptionsBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/wikipedia/WikipediaOptionsBottomSheetDialogFragment.java index f05bb9273f..7c2b23867e 100644 --- a/OsmAnd/src/net/osmand/plus/wikipedia/WikipediaOptionsBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/wikipedia/WikipediaOptionsBottomSheetDialogFragment.java @@ -10,7 +10,6 @@ import androidx.fragment.app.Fragment; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.WikiArticleShowImages; import net.osmand.plus.R; import net.osmand.plus.base.MenuBottomSheetDialogFragment; import net.osmand.plus.base.bottomsheetmenu.BaseBottomSheetItem; diff --git a/OsmAnd/src/net/osmand/plus/wikivoyage/WikivoyageShowPicturesDialogFragment.java b/OsmAnd/src/net/osmand/plus/wikivoyage/WikivoyageShowPicturesDialogFragment.java index 07c748cd28..824a2e9e49 100644 --- a/OsmAnd/src/net/osmand/plus/wikivoyage/WikivoyageShowPicturesDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/wikivoyage/WikivoyageShowPicturesDialogFragment.java @@ -18,7 +18,7 @@ import androidx.fragment.app.Fragment; import net.osmand.AndroidUtils; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings.WikiArticleShowImages; +import net.osmand.plus.wikipedia.WikiArticleShowImages; import net.osmand.plus.R; import net.osmand.plus.base.BottomSheetDialogFragment; import net.osmand.plus.helpers.AndroidUiHelper; diff --git a/OsmAnd/src/net/osmand/plus/wikivoyage/article/WikivoyageArticleDialogFragment.java b/OsmAnd/src/net/osmand/plus/wikivoyage/article/WikivoyageArticleDialogFragment.java index be9d3f2e58..fa704688a0 100644 --- a/OsmAnd/src/net/osmand/plus/wikivoyage/article/WikivoyageArticleDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/wikivoyage/article/WikivoyageArticleDialogFragment.java @@ -50,7 +50,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; -import static net.osmand.plus.settings.backend.OsmandSettings.WikiArticleShowImages.OFF; +import static net.osmand.plus.wikipedia.WikiArticleShowImages.OFF; public class WikivoyageArticleDialogFragment extends WikiArticleBaseDialogFragment { diff --git a/OsmAnd/src/net/osmand/plus/wikivoyage/explore/WikivoyageOptionsBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/wikivoyage/explore/WikivoyageOptionsBottomSheetDialogFragment.java index ea09a79314..988598c359 100644 --- a/OsmAnd/src/net/osmand/plus/wikivoyage/explore/WikivoyageOptionsBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/wikivoyage/explore/WikivoyageOptionsBottomSheetDialogFragment.java @@ -16,7 +16,7 @@ import net.osmand.PicassoUtils; import net.osmand.plus.OnDialogFragmentResultListener; import net.osmand.plus.OsmandApplication; import net.osmand.plus.settings.backend.CommonPreference; -import net.osmand.plus.settings.backend.OsmandSettings.WikiArticleShowImages; +import net.osmand.plus.wikipedia.WikiArticleShowImages; import net.osmand.plus.R; import net.osmand.plus.base.MenuBottomSheetDialogFragment; import net.osmand.plus.base.bottomsheetmenu.BaseBottomSheetItem; From 4e3526e742fb0f02e1e8bf426f6608c808928821 Mon Sep 17 00:00:00 2001 From: sergosm Date: Wed, 7 Oct 2020 23:15:45 +0300 Subject: [PATCH 23/95] We have a few issues with text and icon colors. --- .../plus/wikivoyage/search/SearchRecyclerViewAdapter.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/OsmAnd/src/net/osmand/plus/wikivoyage/search/SearchRecyclerViewAdapter.java b/OsmAnd/src/net/osmand/plus/wikivoyage/search/SearchRecyclerViewAdapter.java index 902b883e3d..e4c310c866 100644 --- a/OsmAnd/src/net/osmand/plus/wikivoyage/search/SearchRecyclerViewAdapter.java +++ b/OsmAnd/src/net/osmand/plus/wikivoyage/search/SearchRecyclerViewAdapter.java @@ -135,6 +135,7 @@ public class SearchRecyclerViewAdapter extends RecyclerView.Adapter Date: Thu, 8 Oct 2020 09:19:18 +0300 Subject: [PATCH 24/95] Increase waiting telegram library time for fixing widget fake error state --- OsmAnd-telegram/src/net/osmand/telegram/TelegramSettings.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OsmAnd-telegram/src/net/osmand/telegram/TelegramSettings.kt b/OsmAnd-telegram/src/net/osmand/telegram/TelegramSettings.kt index 042fb03d11..d9ec335a0e 100644 --- a/OsmAnd-telegram/src/net/osmand/telegram/TelegramSettings.kt +++ b/OsmAnd-telegram/src/net/osmand/telegram/TelegramSettings.kt @@ -110,7 +110,7 @@ private const val PROXY_ENABLED = "proxy_enabled" private const val PROXY_PREFERENCES_KEY = "proxy_preferences" private const val SHARING_INITIALIZATION_TIME = 60 * 2L // 2 minutes -private const val WAITING_TDLIB_TIME = 3 // 3 seconds +private const val WAITING_TDLIB_TIME = 7 // 7 seconds private const val GPS_UPDATE_EXPIRED_TIME = 60 * 3L // 3 minutes From 0fdc58960a989544cb03f09fe35fb75fbddb7a78 Mon Sep 17 00:00:00 2001 From: simon Date: Thu, 8 Oct 2020 09:58:44 +0300 Subject: [PATCH 25/95] cleanup --- .../builders/cards/IPFSImageCard.java | 30 ++++++++----------- .../builders/cards/ImageCard.java | 8 ++--- .../osmand/plus/views/layers/POIMapLayer.java | 2 +- 3 files changed, 17 insertions(+), 23 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/IPFSImageCard.java b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/IPFSImageCard.java index b029c7cdfc..682cfe8abd 100644 --- a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/IPFSImageCard.java +++ b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/IPFSImageCard.java @@ -1,28 +1,34 @@ package net.osmand.plus.mapcontextmenu.builders.cards; import android.view.View; +import net.osmand.AndroidNetworkUtils; +import net.osmand.PlatformUtil; import net.osmand.plus.activities.MapActivity; import net.osmand.util.Algorithms; +import org.apache.commons.logging.Log; import org.json.JSONException; import org.json.JSONObject; public class IPFSImageCard extends ImageCard { private static final String BASE_URL = "https://test.openplacereviews.org/api/ipfs/image-ipfs?cid="; + private static final Log LOG = PlatformUtil.getLog(IPFSImageCard.class); public IPFSImageCard(MapActivity mapActivity, JSONObject imageObject) { super(mapActivity, imageObject); + String cid = ""; try { - this.url = BASE_URL + imageObject.get("cid"); - this.imageHiresUrl = BASE_URL + imageObject.get("cid"); - this.imageUrl = BASE_URL + imageObject.get("cid"); + cid = (String) imageObject.get("cid"); } catch (JSONException e) { - e.printStackTrace(); + LOG.error(e); } - if (!Algorithms.isEmpty(getSuitableUrl())) { + this.url = BASE_URL + cid; + this.imageHiresUrl = BASE_URL + cid; + this.imageUrl = BASE_URL + cid; + if (!Algorithms.isEmpty(getUrl())) { View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { - openUrl(getMapActivity(), getMyApplication(), getTitle(), getSuitableUrl(), + openUrl(getMapActivity(), getMyApplication(), getTitle(), getUrl(), isExternalLink() || Algorithms.isEmpty(getImageHiresUrl()), !Algorithms.isEmpty(getImageHiresUrl())); } @@ -34,14 +40,4 @@ public class IPFSImageCard extends ImageCard { } } } - - private String getSuitableUrl() { - final String url; - if (Algorithms.isEmpty(getImageHiresUrl())) { - url = getUrl(); - } else { - url = getImageHiresUrl(); - } - return url; - } -} \ No newline at end of file +} diff --git a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java index 667b234956..9a4486b8a5 100644 --- a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java +++ b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java @@ -418,6 +418,7 @@ public abstract class ImageCard extends AbstractCard { private Map params; private GetImageCardsListener listener; private List result; + private static final int GET_IMAGE_CARD_THREAD_ID = 10104; public interface GetImageCardsListener { void onPostProcess(List cardList); @@ -436,10 +437,8 @@ public abstract class ImageCard extends AbstractCard { @Override protected List doInBackground(Void... params) { - final int THREAD_ID = 10104; - TrafficStats.setThreadStatsTag(THREAD_ID); + TrafficStats.setThreadStatsTag(GET_IMAGE_CARD_THREAD_ID); List result = new ArrayList<>(); - RotatedTileBox rtb = mapActivity.getMapView().getCurrentRotatedTileBox(); Object o = mapActivity.getMapLayers().getContextMenuLayer().getSelectedObject(); if (o instanceof Amenity) { Amenity am = (Amenity) o; @@ -510,7 +509,6 @@ public abstract class ImageCard extends AbstractCard { String url = "https://test.openplacereviews.org/api/objects-by-index?type=opr.place&index=osmid&limit=1&key=" + l; String response = AndroidNetworkUtils.sendRequest(app, url, Collections.emptyMap(), "Requesting location images...", false, false); - try { if (!Algorithms.isEmpty(response)) { JSONArray obj = new JSONObject(response).getJSONArray("objects"); @@ -526,7 +524,7 @@ public abstract class ImageCard extends AbstractCard { } } } catch (JSONException e) { - e.printStackTrace(); + LOG.error(e); } } } diff --git a/OsmAnd/src/net/osmand/plus/views/layers/POIMapLayer.java b/OsmAnd/src/net/osmand/plus/views/layers/POIMapLayer.java index d01ec310a9..ed0f2cc45d 100644 --- a/OsmAnd/src/net/osmand/plus/views/layers/POIMapLayer.java +++ b/OsmAnd/src/net/osmand/plus/views/layers/POIMapLayer.java @@ -66,7 +66,7 @@ public class POIMapLayer extends OsmandMapLayer implements ContextMenuLayer.ICon /// cache for displayed POI // Work with cache (for map copied from AmenityIndexRepositoryOdb) - public MapLayerData> data; + private MapLayerData> data; private OsmandApplication app; From 4eae0ee60a2494693e9523f49085ac9a3e241b3c Mon Sep 17 00:00:00 2001 From: simon Date: Thu, 8 Oct 2020 10:03:58 +0300 Subject: [PATCH 26/95] cleanup --- .../plus/mapcontextmenu/builders/cards/IPFSImageCard.java | 8 ++++---- .../plus/mapcontextmenu/builders/cards/ImageCard.java | 2 +- .../net/osmand/plus/views/layers/ContextMenuLayer.java | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/IPFSImageCard.java b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/IPFSImageCard.java index 682cfe8abd..45495ca8d0 100644 --- a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/IPFSImageCard.java +++ b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/IPFSImageCard.java @@ -21,9 +21,9 @@ public class IPFSImageCard extends ImageCard { } catch (JSONException e) { LOG.error(e); } - this.url = BASE_URL + cid; - this.imageHiresUrl = BASE_URL + cid; - this.imageUrl = BASE_URL + cid; + url = BASE_URL + cid; + imageHiresUrl = BASE_URL + cid; + imageUrl = BASE_URL + cid; if (!Algorithms.isEmpty(getUrl())) { View.OnClickListener onClickListener = new View.OnClickListener() { @Override @@ -34,7 +34,7 @@ public class IPFSImageCard extends ImageCard { } }; if (!Algorithms.isEmpty(buttonText)) { - this.onButtonClickListener = onClickListener; + onButtonClickListener = onClickListener; } else { this.onClickListener = onClickListener; } diff --git a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java index 9a4486b8a5..1afb883231 100644 --- a/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java +++ b/OsmAnd/src/net/osmand/plus/mapcontextmenu/builders/cards/ImageCard.java @@ -442,7 +442,7 @@ public abstract class ImageCard extends AbstractCard { Object o = mapActivity.getMapLayers().getContextMenuLayer().getSelectedObject(); if (o instanceof Amenity) { Amenity am = (Amenity) o; - long amenityId = (am.getId() >> 1); + long amenityId = am.getId() >> 1; getPicturesForPlace(result, amenityId); } try { diff --git a/OsmAnd/src/net/osmand/plus/views/layers/ContextMenuLayer.java b/OsmAnd/src/net/osmand/plus/views/layers/ContextMenuLayer.java index 2902794ee8..7a8690fe2d 100644 --- a/OsmAnd/src/net/osmand/plus/views/layers/ContextMenuLayer.java +++ b/OsmAnd/src/net/osmand/plus/views/layers/ContextMenuLayer.java @@ -907,9 +907,9 @@ public class ContextMenuLayer extends OsmandMapLayer { } @NonNull - public Map selectObjectsForContextMenu(RotatedTileBox tileBox, - PointF point, boolean acquireObjLatLon, - boolean unknownLocation) { + private Map selectObjectsForContextMenu(RotatedTileBox tileBox, + PointF point, boolean acquireObjLatLon, + boolean unknownLocation) { Map pressedLatLonFull = new HashMap<>(); Map pressedLatLonSmall = new HashMap<>(); Map selectedObjects = new HashMap<>(); From 0cd8cd049f67f80853d3bc05d6837a0c2b673316 Mon Sep 17 00:00:00 2001 From: sergosm Date: Thu, 8 Oct 2020 11:53:45 +0300 Subject: [PATCH 27/95] update --- .../plus/wikivoyage/search/SearchRecyclerViewAdapter.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/wikivoyage/search/SearchRecyclerViewAdapter.java b/OsmAnd/src/net/osmand/plus/wikivoyage/search/SearchRecyclerViewAdapter.java index e4c310c866..de9793d267 100644 --- a/OsmAnd/src/net/osmand/plus/wikivoyage/search/SearchRecyclerViewAdapter.java +++ b/OsmAnd/src/net/osmand/plus/wikivoyage/search/SearchRecyclerViewAdapter.java @@ -135,7 +135,7 @@ public class SearchRecyclerViewAdapter extends RecyclerView.Adapter Date: Thu, 8 Oct 2020 12:08:31 +0300 Subject: [PATCH 28/95] #9621 Add validation for the online tracking link to the new settings screen --- .../fragments/LiveMonitoringFragment.java | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/LiveMonitoringFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/LiveMonitoringFragment.java index e664953662..6a426e654c 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/LiveMonitoringFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/LiveMonitoringFragment.java @@ -5,6 +5,7 @@ import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; +import android.widget.Toast; import androidx.appcompat.widget.SwitchCompat; import androidx.core.content.ContextCompat; @@ -12,11 +13,12 @@ import androidx.preference.Preference; import net.osmand.AndroidUtils; import net.osmand.plus.OsmAndFormatter; -import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.R; import net.osmand.plus.UiUtilities; +import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.settings.preferences.EditTextPreferenceEx; import net.osmand.plus.settings.preferences.ListPreferenceEx; +import net.osmand.util.Algorithms; import static net.osmand.plus.UiUtilities.CompoundButtonType.TOOLBAR; import static net.osmand.plus.monitoring.OsmandMonitoringPlugin.MAX_INTERVAL_TO_SEND_MINUTES; @@ -60,6 +62,19 @@ public class LiveMonitoringFragment extends BaseSettingsFragment { updateToolbarSwitch(); } + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + if (preference.getKey().equals(settings.LIVE_MONITORING_URL.getId())) { + if (Algorithms.isValidMessageFormat((String) newValue)) { + return super.onPreferenceChange(preference, newValue); + } else { + Toast.makeText(app, R.string.wrong_format, Toast.LENGTH_SHORT).show(); + return false; + } + } + return super.onPreferenceChange(preference, newValue); + } + private void updateToolbarSwitch() { View view = getView(); if (view == null) { From e083c3958df2762f0f3601dd0d24298983533cd3 Mon Sep 17 00:00:00 2001 From: Dima-1 Date: Thu, 8 Oct 2020 12:50:33 +0300 Subject: [PATCH 29/95] Fix wrong place of configure profile --- OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java | 12 ++++++++++++ .../fragments/ConfigureMenuItemsFragment.java | 6 +++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java b/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java index 7263f119bd..26e173d568 100644 --- a/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java +++ b/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java @@ -53,6 +53,9 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import static net.osmand.aidlapi.OsmAndCustomizationConstants.DRAWER_CONFIGURE_PROFILE_ID; +import static net.osmand.aidlapi.OsmAndCustomizationConstants.DRAWER_SWITCH_PROFILE_ID; + public class ContextMenuAdapter { private static final Log LOG = PlatformUtil.getLog(ContextMenuAdapter.class); @@ -134,6 +137,15 @@ public class ContextMenuAdapter { Collections.sort(items, new Comparator() { @Override public int compare(ContextMenuItem item1, ContextMenuItem item2) { + if (DRAWER_SWITCH_PROFILE_ID.equals(item1.getId())) { + return -1; + } + if (DRAWER_CONFIGURE_PROFILE_ID.equals(item1.getId()) && DRAWER_SWITCH_PROFILE_ID.equals(item2.getId())) { + return 1; + } + if (DRAWER_CONFIGURE_PROFILE_ID.equals(item1.getId())) { + return -1; + } int order1 = item1.getOrder(); int order2 = item2.getOrder(); if (order1 < order2) { diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/ConfigureMenuItemsFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/ConfigureMenuItemsFragment.java index 44fb4bf7f6..4d2309af82 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/ConfigureMenuItemsFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/ConfigureMenuItemsFragment.java @@ -51,6 +51,8 @@ import java.util.HashMap; import java.util.List; import static net.osmand.aidlapi.OsmAndCustomizationConstants.APP_PROFILES_ID; +import static net.osmand.aidlapi.OsmAndCustomizationConstants.DRAWER_CONFIGURE_PROFILE_ID; +import static net.osmand.aidlapi.OsmAndCustomizationConstants.DRAWER_SWITCH_PROFILE_ID; import static net.osmand.aidlapi.OsmAndCustomizationConstants.MAP_CONTEXT_MENU_MORE_ID; import static net.osmand.plus.settings.fragments.RearrangeMenuItemsAdapter.AdapterItemType.BUTTON; import static net.osmand.plus.settings.fragments.RearrangeMenuItemsAdapter.AdapterItemType.DESCRIPTION; @@ -183,7 +185,9 @@ public class ConfigureMenuItemsFragment extends BaseOsmAndFragment public static List getCustomizableDefaultItems(List defItems) { List items = new ArrayList<>(); for (ContextMenuItem item : defItems) { - if (!APP_PROFILES_ID.equals(item.getId())) { + if (!APP_PROFILES_ID.equals(item.getId()) + && !DRAWER_CONFIGURE_PROFILE_ID.equals(item.getId()) + && !DRAWER_SWITCH_PROFILE_ID.equals(item.getId())) { items.add(item); } } From bde5ae822b5a8172761a329bcf43ed04816d70bb Mon Sep 17 00:00:00 2001 From: simon Date: Thu, 8 Oct 2020 15:43:57 +0300 Subject: [PATCH 30/95] stream improvements --- .../java/net/osmand/osm/io/NetworkUtils.java | 71 ++--- .../osm/oauth/IInputStreamHttpClient.java | 7 + .../osmand/osm/oauth/OsmAndJDKHttpClient.java | 260 ++++++++++++++++++ .../oauth/OsmOAuthAuthorizationClient.java | 3 + 4 files changed, 297 insertions(+), 44 deletions(-) create mode 100644 OsmAnd-java/src/main/java/net/osmand/osm/oauth/IInputStreamHttpClient.java create mode 100644 OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmAndJDKHttpClient.java diff --git a/OsmAnd-java/src/main/java/net/osmand/osm/io/NetworkUtils.java b/OsmAnd-java/src/main/java/net/osmand/osm/io/NetworkUtils.java index 8880184f96..d684b148a4 100644 --- a/OsmAnd-java/src/main/java/net/osmand/osm/io/NetworkUtils.java +++ b/OsmAnd-java/src/main/java/net/osmand/osm/io/NetworkUtils.java @@ -4,6 +4,7 @@ import com.github.scribejava.core.model.OAuthRequest; import com.github.scribejava.core.model.Response; import com.github.scribejava.core.model.Verb; import net.osmand.PlatformUtil; +import net.osmand.osm.oauth.IInputStreamHttpClient; import net.osmand.osm.oauth.OsmOAuthAuthorizationClient; import net.osmand.util.Algorithms; import org.apache.commons.logging.Log; @@ -72,12 +73,13 @@ public class NetworkUtils { HttpURLConnection conn; if (client != null && client.isValidToken()){ OAuthRequest req = new OAuthRequest(Verb.POST, urlText); - req.setPayload(prepareStream(formName,fileToUpload,gzip)); client.getService().signRequest(client.getAccessToken(), req); req.addHeader("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); try { + IInputStreamHttpClient service = (IInputStreamHttpClient) client.getService(); + service.execute(service.getUserAgent(), req.getHeaders(), req.getVerb(), req.getCompleteUrl(), fileToUpload); Response r = client.getService().execute(req); - if(r.getCode() != 200){ + if (r.getCode() != 200) { return r.getBody(); } return null; @@ -100,7 +102,29 @@ public class NetworkUtils { conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); //$NON-NLS-1$ //$NON-NLS-2$ conn.setRequestProperty("User-Agent", "OsmAnd"); //$NON-NLS-1$ //$NON-NLS-2$ OutputStream ous = conn.getOutputStream(); - ous.write(prepareStream(formName,fileToUpload,gzip)); + ous.write(("--" + BOUNDARY + "\r\n").getBytes()); + String filename = fileToUpload.getName(); + if (gzip) { + filename += ".gz"; + } + ous.write(("content-disposition: form-data; name=\"" + formName + "\"; filename=\"" + filename + "\"\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$ + ous.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes()); //$NON-NLS-1$ + InputStream fis = new FileInputStream(fileToUpload); + BufferedInputStream bis = new BufferedInputStream(fis, 20 * 1024); + ous.flush(); + if (gzip) { + GZIPOutputStream gous = new GZIPOutputStream(ous, 1024); + Algorithms.streamCopy(bis, gous); + gous.flush(); + gous.finish(); + } else { + Algorithms.streamCopy(bis, ous); + } + ous.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$ + ous.flush(); + Algorithms.closeStream(bis); + Algorithms.closeStream(ous); + log.info("Finish uploading file " + fileToUpload.getName()); log.info("Response code and message : " + conn.getResponseCode() + " " + conn.getResponseMessage()); if(conn.getResponseCode() != 200){ @@ -131,46 +155,6 @@ public class NetworkUtils { } } - private static byte[] prepareStream(String formName, File fileToUpload, boolean gzip) { - try { - ByteArrayOutputStream ous = new ByteArrayOutputStream(); -// for (String key : additionalMapData.keySet()) { -// ous.write(("--" + BOUNDARY + "\r\n").getBytes()); -// ous.write(("content-disposition: form-data; name=\"" + key + "\"\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$ -// ous.write((additionalMapData.get(key) + "\r\n").getBytes()); -// } - ous.write(("--" + BOUNDARY + "\r\n").getBytes()); - - String filename = fileToUpload.getName(); - if (gzip) { - filename += ".gz"; - } - ous.write(("content-disposition: form-data; name=\"" + formName + "\"; filename=\"" + filename + "\"\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$ - ous.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes()); //$NON-NLS-1$ - InputStream fis = new FileInputStream(fileToUpload); - BufferedInputStream bis = new BufferedInputStream(fis, 20 * 1024); - ous.flush(); - if (gzip) { - GZIPOutputStream gous = new GZIPOutputStream(ous, 1024); - Algorithms.streamCopy(bis, gous); - gous.flush(); - gous.finish(); - gous.close(); - } else { - Algorithms.streamCopy(bis, ous); - } - - ous.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$ - ous.flush(); - Algorithms.closeStream(bis); - Algorithms.closeStream(ous); - return ous.toByteArray(); - } catch (IOException e) { - log.error(e); - } - return new byte[0]; - } - public static void setProxy(String host, int port) { if(host != null && port > 0) { InetSocketAddress isa = new InetSocketAddress(host, port); @@ -179,7 +163,6 @@ public class NetworkUtils { proxy = null; } } - public static Proxy getProxy() { return proxy; } diff --git a/OsmAnd-java/src/main/java/net/osmand/osm/oauth/IInputStreamHttpClient.java b/OsmAnd-java/src/main/java/net/osmand/osm/oauth/IInputStreamHttpClient.java new file mode 100644 index 0000000000..c42182fdd7 --- /dev/null +++ b/OsmAnd-java/src/main/java/net/osmand/osm/oauth/IInputStreamHttpClient.java @@ -0,0 +1,7 @@ +package net.osmand.osm.oauth; + +import com.github.scribejava.core.httpclient.HttpClient; + +public interface IInputStreamHttpClient extends HttpClient { + String getUserAgent(); +} diff --git a/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmAndJDKHttpClient.java b/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmAndJDKHttpClient.java new file mode 100644 index 0000000000..c7d8f88446 --- /dev/null +++ b/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmAndJDKHttpClient.java @@ -0,0 +1,260 @@ +package net.osmand.osm.oauth; + +import com.github.scribejava.core.exceptions.OAuthException; +import com.github.scribejava.core.httpclient.HttpClient; +import com.github.scribejava.core.httpclient.jdk.JDKHttpClientConfig; +import com.github.scribejava.core.httpclient.jdk.JDKHttpFuture; +import com.github.scribejava.core.httpclient.multipart.MultipartPayload; +import com.github.scribejava.core.httpclient.multipart.MultipartUtils; +import com.github.scribejava.core.model.*; +import net.osmand.util.Algorithms; + +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.UnknownHostException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +public class OsmAndJDKHttpClient implements IInputStreamHttpClient { + private static final String BOUNDARY = "CowMooCowMooCowCowCow"; + private final JDKHttpClientConfig config; + + public OsmAndJDKHttpClient() { + this(JDKHttpClientConfig.defaultConfig()); + } + + public OsmAndJDKHttpClient(JDKHttpClientConfig clientConfig) { + config = clientConfig; + } + + @Override + public void close() { + } + + @Override + public Future executeAsync(String userAgent, Map headers, Verb httpVerb, String completeUrl, + byte[] bodyContents, OAuthAsyncRequestCallback callback, OAuthRequest.ResponseConverter converter) { + + return doExecuteAsync(userAgent, headers, httpVerb, completeUrl, BodyType.BYTE_ARRAY, bodyContents, callback, + converter); + } + + @Override + public Future executeAsync(String userAgent, Map headers, Verb httpVerb, String completeUrl, + MultipartPayload bodyContents, OAuthAsyncRequestCallback callback, + OAuthRequest.ResponseConverter converter) { + + return doExecuteAsync(userAgent, headers, httpVerb, completeUrl, BodyType.MULTIPART, bodyContents, callback, + converter); + } + + @Override + public Future executeAsync(String userAgent, Map headers, Verb httpVerb, String completeUrl, + String bodyContents, OAuthAsyncRequestCallback callback, OAuthRequest.ResponseConverter converter) { + + return doExecuteAsync(userAgent, headers, httpVerb, completeUrl, BodyType.STRING, bodyContents, callback, + converter); + } + + @Override + public Future executeAsync(String userAgent, Map headers, Verb httpVerb, String completeUrl, + File bodyContents, OAuthAsyncRequestCallback callback, OAuthRequest.ResponseConverter converter) { + return doExecuteAsync(userAgent, headers, httpVerb, completeUrl, BodyType.STREAM, bodyContents, callback, + converter); + } + + private Future doExecuteAsync(String userAgent, Map headers, Verb httpVerb, + String completeUrl, BodyType bodyType, Object bodyContents, OAuthAsyncRequestCallback callback, + OAuthRequest.ResponseConverter converter) { + try { + final Response response = doExecute(userAgent, headers, httpVerb, completeUrl, bodyType, bodyContents); + @SuppressWarnings("unchecked") + final T t = converter == null ? (T) response : converter.convert(response); + if (callback != null) { + callback.onCompleted(t); + } + return new JDKHttpFuture<>(t); + } catch (IOException | RuntimeException e) { + if (callback != null) { + callback.onThrowable(e); + } + return new JDKHttpFuture<>(e); + } + } + + @Override + public Response execute(String userAgent, Map headers, Verb httpVerb, String completeUrl, + byte[] bodyContents) throws InterruptedException, ExecutionException, IOException { + return doExecute(userAgent, headers, httpVerb, completeUrl, BodyType.BYTE_ARRAY, bodyContents); + } + + @Override + public Response execute(String userAgent, Map headers, Verb httpVerb, String completeUrl, + MultipartPayload multipartPayloads) throws InterruptedException, ExecutionException, IOException { + return doExecute(userAgent, headers, httpVerb, completeUrl, BodyType.MULTIPART, multipartPayloads); + } + + @Override + public Response execute(String userAgent, Map headers, Verb httpVerb, String completeUrl, + String bodyContents) throws InterruptedException, ExecutionException, IOException { + return doExecute(userAgent, headers, httpVerb, completeUrl, BodyType.STRING, bodyContents); + } + + @Override + public Response execute(String userAgent, Map headers, Verb httpVerb, String completeUrl, + File bodyContents) throws InterruptedException, ExecutionException, IOException { + return doExecute(userAgent, headers, httpVerb, completeUrl, BodyType.STREAM, bodyContents); + } + + private Response doExecute(String userAgent, Map headers, Verb httpVerb, String completeUrl, + BodyType bodyType, Object bodyContents) throws IOException { + final URL url = new URL(completeUrl); + final HttpURLConnection connection; + if (config.getProxy() == null) { + connection = (HttpURLConnection) url.openConnection(); + } else { + connection = (HttpURLConnection) url.openConnection(config.getProxy()); + } + connection.setInstanceFollowRedirects(config.isFollowRedirects()); + connection.setRequestMethod(httpVerb.name()); + if (config.getConnectTimeout() != null) { + connection.setConnectTimeout(config.getConnectTimeout()); + } + if (config.getReadTimeout() != null) { + connection.setReadTimeout(config.getReadTimeout()); + } + addHeaders(connection, headers, userAgent); + if (httpVerb.isPermitBody()) { + bodyType.setBody(connection, bodyContents, httpVerb.isRequiresBody()); + } + + try { + connection.connect(); + final int responseCode = connection.getResponseCode(); + return new Response(responseCode, connection.getResponseMessage(), parseHeaders(connection), + responseCode >= 200 && responseCode < 400 ? connection.getInputStream() + : connection.getErrorStream()); + } catch (UnknownHostException e) { + throw new OAuthException("The IP address of a host could not be determined.", e); + } + } + + @Override + public String getUserAgent() { + return "OsmandUserAgent"; + } + + private enum BodyType { + BYTE_ARRAY { + @Override + void setBody(HttpURLConnection connection, Object bodyContents, boolean requiresBody) throws IOException { + addBody(connection, (byte[]) bodyContents, requiresBody); + } + }, + STREAM { + @Override + void setBody(HttpURLConnection connection, Object bodyContents, boolean requiresBody) throws IOException { + addBody(connection, (File) bodyContents, requiresBody); + } + }, + MULTIPART { + @Override + void setBody(HttpURLConnection connection, Object bodyContents, boolean requiresBody) throws IOException { + addBody(connection, (MultipartPayload) bodyContents, requiresBody); + } + }, + STRING { + @Override + void setBody(HttpURLConnection connection, Object bodyContents, boolean requiresBody) throws IOException { + addBody(connection, ((String) bodyContents).getBytes(), requiresBody); + } + }; + abstract void setBody(HttpURLConnection connection, Object bodyContents, boolean requiresBody) + throws IOException; + } + + private static Map parseHeaders(HttpURLConnection conn) { + final Map headers = new HashMap<>(); + + for (Map.Entry> headerField : conn.getHeaderFields().entrySet()) { + final String key = headerField.getKey(); + final String value = headerField.getValue().get(0); + if ("Content-Encoding".equalsIgnoreCase(key)) { + headers.put("Content-Encoding", value); + } else { + headers.put(key, value); + } + } + return headers; + } + + private static void addHeaders(HttpURLConnection connection, Map headers, String userAgent) { + for (Map.Entry header : headers.entrySet()) { + connection.setRequestProperty(header.getKey(), header.getValue()); + } + + if (userAgent != null) { + connection.setRequestProperty(OAuthConstants.USER_AGENT_HEADER_NAME, userAgent); + } + } + + private static void addBody(HttpURLConnection connection, File file, boolean requiresBody) throws IOException { + if (requiresBody) { + String filename = file.getName(); + String formName = "file"; + final OutputStream ous = prepareConnectionForBodyAndGetOutputStream(connection, 20 * 1024); + ous.write(("--" + BOUNDARY+"\r\n").getBytes()); + InputStream stream = new FileInputStream(file); + ous.write(("content-disposition: form-data; name=\""+formName+"\"; filename=\"" + filename + "\"\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$ + ous.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes()); //$NON-NLS-1$ + BufferedInputStream bis = new BufferedInputStream(stream, 20 * 1024); + ous.flush(); + Algorithms.streamCopy(bis, ous); + ous.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$ + ous.flush(); + Algorithms.closeStream(bis); + Algorithms.closeStream(ous); + } + } + + private static void addBody(HttpURLConnection connection, byte[] content, boolean requiresBody) throws IOException { + final int contentLength = content.length; + if (requiresBody || contentLength > 0) { + final OutputStream outputStream = prepareConnectionForBodyAndGetOutputStream(connection, contentLength); + if (contentLength > 0) { + outputStream.write(content); + } + } + } + + private static void addBody(HttpURLConnection connection, MultipartPayload multipartPayload, boolean requiresBody) + throws IOException { + + for (Map.Entry header : multipartPayload.getHeaders().entrySet()) { + connection.setRequestProperty(header.getKey(), header.getValue()); + } + + if (requiresBody) { + final ByteArrayOutputStream os = MultipartUtils.getPayload(multipartPayload); + final int contentLength = os.size(); + final OutputStream outputStream = prepareConnectionForBodyAndGetOutputStream(connection, contentLength); + if (contentLength > 0) { + os.writeTo(outputStream); + } + } + } + + private static OutputStream prepareConnectionForBodyAndGetOutputStream(HttpURLConnection connection, + int contentLength) throws IOException { + connection.setRequestProperty(CONTENT_LENGTH, String.valueOf(contentLength)); + if (connection.getRequestProperty(CONTENT_TYPE) == null) { + connection.setRequestProperty(CONTENT_TYPE, DEFAULT_CONTENT_TYPE); + } + connection.setDoOutput(true); + return connection.getOutputStream(); + } +} \ No newline at end of file diff --git a/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java b/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java index 5726855f72..709dbaa275 100644 --- a/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java +++ b/OsmAnd-java/src/main/java/net/osmand/osm/oauth/OsmOAuthAuthorizationClient.java @@ -4,6 +4,8 @@ package net.osmand.osm.oauth; import com.github.scribejava.core.builder.ServiceBuilder; import com.github.scribejava.core.builder.api.DefaultApi10a; import com.github.scribejava.core.builder.api.OAuth1SignatureType; +import com.github.scribejava.core.httpclient.jdk.JDKHttpClient; +import com.github.scribejava.core.httpclient.jdk.JDKHttpClientConfig; import com.github.scribejava.core.model.*; import com.github.scribejava.core.oauth.OAuth10aService; import net.osmand.PlatformUtil; @@ -26,6 +28,7 @@ public class OsmOAuthAuthorizationClient { public OsmOAuthAuthorizationClient(String key, String secret) { service = new ServiceBuilder(key) .apiSecret(secret) + .httpClient(new OsmAndJDKHttpClient(JDKHttpClientConfig.defaultConfig())) .callback("osmand-oauth://example.com/oauth") .build(new OsmApi()); } From dd220b193213ee6a8f1833611b1cf2ae4525884c Mon Sep 17 00:00:00 2001 From: Alexander Sytnyk Date: Thu, 8 Oct 2020 16:10:31 +0300 Subject: [PATCH 31/95] #9984 Fix overlapping text --- ...bottom_sheet_item_slider_with_two_text.xml | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/OsmAnd/res/layout/bottom_sheet_item_slider_with_two_text.xml b/OsmAnd/res/layout/bottom_sheet_item_slider_with_two_text.xml index b5cb11cf49..f386e8c59f 100644 --- a/OsmAnd/res/layout/bottom_sheet_item_slider_with_two_text.xml +++ b/OsmAnd/res/layout/bottom_sheet_item_slider_with_two_text.xml @@ -6,33 +6,37 @@ android:layout_width="match_parent" android:layout_height="match_parent"> - + osmand:typeface="@string/font_roboto_regular" + tools:text="Some very long title to check overlapped texts" /> + + + osmand:typeface="@string/font_roboto_medium" + tools:text="summary" /> - + Date: Thu, 8 Oct 2020 16:12:07 +0300 Subject: [PATCH 32/95] update OpenGL Check Invert Disable Setting --- OsmAnd/src/net/osmand/plus/Version.java | 27 ++++++++++++++++--- .../SettingsDevelopmentActivity.java | 13 +++------ .../fragments/RouteParametersFragment.java | 12 ++++----- 3 files changed, 33 insertions(+), 19 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/Version.java b/OsmAnd/src/net/osmand/plus/Version.java index 14ed68b100..4a13b98783 100644 --- a/OsmAnd/src/net/osmand/plus/Version.java +++ b/OsmAnd/src/net/osmand/plus/Version.java @@ -1,13 +1,15 @@ package net.osmand.plus; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; +import android.content.pm.PackageManager; import net.osmand.plus.inapp.InAppPurchaseHelper; +import java.io.File; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; + public class Version { private final String appVersion; @@ -149,4 +151,21 @@ public class Version { return v; } -} + public static boolean isOpenGlAvailable(OsmandApplication app) { + if ("qnx".equals(System.getProperty("os.name"))) { + return false; + } + File nativeLibraryDir = new File(app.getApplicationInfo().nativeLibraryDir); + if (nativeLibraryDir.exists() && nativeLibraryDir.canRead()) { + File[] files = nativeLibraryDir.listFiles(); + if (files != null) { + for (File file : files) { + if ("libOsmAndCoreWithJNI.so".equals(file.getName())) { + return true; + } + } + } + } + return false; + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/development/SettingsDevelopmentActivity.java b/OsmAnd/src/net/osmand/plus/development/SettingsDevelopmentActivity.java index 3f95829762..f7e1fa064f 100644 --- a/OsmAnd/src/net/osmand/plus/development/SettingsDevelopmentActivity.java +++ b/OsmAnd/src/net/osmand/plus/development/SettingsDevelopmentActivity.java @@ -14,12 +14,11 @@ import android.preference.PreferenceScreen; import net.osmand.plus.OsmAndLocationSimulation; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.R; import net.osmand.plus.Version; import net.osmand.plus.activities.SettingsBaseActivity; import net.osmand.plus.render.NativeOsmandLibrary; -import net.osmand.plus.views.corenative.NativeCoreContext; +import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.util.SunriseSunset; import java.text.SimpleDateFormat; @@ -38,9 +37,9 @@ public class SettingsDevelopmentActivity extends SettingsBaseActivity { PreferenceScreen category = getPreferenceScreen(); Preference pref; - if (app.getSettings().USE_OPENGL_RENDER.get() && NativeCoreContext.isInit()) { - CheckBoxPreference useOpenglRender = createCheckBoxPreference(settings.USE_OPENGL_RENDER, R.string.use_opengl_render, R.string.use_opengl_render_descr); - category.addPreference(useOpenglRender); + if (Version.isOpenGlAvailable(app)) { + category.addPreference(createCheckBoxPreference(settings.USE_OPENGL_RENDER, + R.string.use_opengl_render, R.string.use_opengl_render_descr)); } if (!Version.isBlackberry(app)) { @@ -113,10 +112,6 @@ public class SettingsDevelopmentActivity extends SettingsBaseActivity { R.string.show_free_version_banner, R.string.show_free_version_banner_description)); - - - - pref = new Preference(this); pref.setTitle(R.string.test_voice_prompts); pref.setSummary(R.string.play_commands_of_currently_selected_voice); diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java index 70dc81c23e..ae82028971 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/RouteParametersFragment.java @@ -168,16 +168,14 @@ public class RouteParametersFragment extends BaseSettingsFragment implements OnP } private void setupNativePublicTransport() { - SwitchPreferenceEx setupNativePublicTransport = createSwitchPreferenceEx(settings.PT_SAFE_MODE.getId(), - R.string.use_native_pt, R.layout.preference_with_descr_dialog_and_switch); if (!Version.isBlackberry(app)) { + SwitchPreferenceEx setupNativePublicTransport = createSwitchPreferenceEx(settings.PT_SAFE_MODE.getId(), + R.string.use_native_pt, R.layout.preference_with_descr_dialog_and_switch); setupNativePublicTransport.setDescription(getString(R.string.use_native_pt_desc)); setupNativePublicTransport.setSummaryOn(R.string.shared_string_enabled); setupNativePublicTransport.setSummaryOff(R.string.shared_string_disabled); setupNativePublicTransport.setIconSpaceReserved(true); getPreferenceScreen().addPreference(setupNativePublicTransport); - } else { - setupNativePublicTransport.setVisible(false); } } @@ -192,12 +190,14 @@ public class RouteParametersFragment extends BaseSettingsFragment implements OnP } private void setupDisableComplexRoutingPref() { + boolean enabled = !settings.DISABLE_COMPLEX_ROUTING.get(); // pref ui was inverted SwitchPreferenceEx disableComplexRouting = createSwitchPreferenceEx(settings.DISABLE_COMPLEX_ROUTING.getId(), R.string.use_complex_routing, R.layout.preference_with_descr_dialog_and_switch); disableComplexRouting.setDescription(getString(R.string.disable_complex_routing_descr)); disableComplexRouting.setSummaryOn(R.string.shared_string_enabled); disableComplexRouting.setSummaryOff(R.string.shared_string_disabled); disableComplexRouting.setIconSpaceReserved(true); + disableComplexRouting.setChecked(enabled); getPreferenceScreen().addPreference(disableComplexRouting); } @@ -330,7 +330,7 @@ public class RouteParametersFragment extends BaseSettingsFragment implements OnP setupSelectRouteRecalcDistance(screen); setupReverseDirectionRecalculation(screen); addDivider(screen); - setupDevelopmentcategoryHeader(screen); + setupDevelopmentCategoryHeader(screen); if (am.isDerivedRoutingFrom(ApplicationMode.PUBLIC_TRANSPORT)) { setupOsmLiveForPublicTransportPref(); setupNativePublicTransport(); @@ -367,7 +367,7 @@ public class RouteParametersFragment extends BaseSettingsFragment implements OnP screen.addPreference(routingCategory); } - private void setupDevelopmentcategoryHeader (PreferenceScreen screen) { + private void setupDevelopmentCategoryHeader (PreferenceScreen screen) { PreferenceCategory developmentCategory = new PreferenceCategory(requireContext()); developmentCategory.setLayoutResource(R.layout.preference_category_with_descr); developmentCategory.setTitle(R.string.development); From faf565b205f3c279309e4a90a7c3c60184ee3a1b Mon Sep 17 00:00:00 2001 From: Dmitry Date: Thu, 8 Oct 2020 16:41:46 +0300 Subject: [PATCH 33/95] Added logo for OpenPlaceReview --- .../res/drawable/ic_logo_openplacereview.xml | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 OsmAnd/res/drawable/ic_logo_openplacereview.xml diff --git a/OsmAnd/res/drawable/ic_logo_openplacereview.xml b/OsmAnd/res/drawable/ic_logo_openplacereview.xml new file mode 100644 index 0000000000..fc5b26cbf3 --- /dev/null +++ b/OsmAnd/res/drawable/ic_logo_openplacereview.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + From 8d271c08ed58dcdac4b56638a4e452b3fe1bc656 Mon Sep 17 00:00:00 2001 From: Artem Date: Thu, 8 Oct 2020 13:28:35 +0000 Subject: [PATCH 34/95] Translated using Weblate (Russian) Currently translated at 100.0% (3493 of 3493 strings) --- OsmAnd/res/values-ru/strings.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/OsmAnd/res/values-ru/strings.xml b/OsmAnd/res/values-ru/strings.xml index b6dd46c4e9..2088db1fe7 100644 --- a/OsmAnd/res/values-ru/strings.xml +++ b/OsmAnd/res/values-ru/strings.xml @@ -3904,4 +3904,6 @@ Имя: А - Я Значки старта и финиша Спасибо за покупку \'Контурных линий\' + Избегать пешеходных дорожек + Избегать пешеходных дорожек \ No newline at end of file From 76eeec305aa47c93999f9793946cb883820d7f1b Mon Sep 17 00:00:00 2001 From: Nikita Epifanov Date: Thu, 8 Oct 2020 12:37:33 +0000 Subject: [PATCH 35/95] Translated using Weblate (Russian) Currently translated at 100.0% (3493 of 3493 strings) --- OsmAnd/res/values-ru/strings.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/OsmAnd/res/values-ru/strings.xml b/OsmAnd/res/values-ru/strings.xml index 2088db1fe7..90e1c50349 100644 --- a/OsmAnd/res/values-ru/strings.xml +++ b/OsmAnd/res/values-ru/strings.xml @@ -3906,4 +3906,10 @@ Спасибо за покупку \'Контурных линий\' Избегать пешеходных дорожек Избегать пешеходных дорожек + Подписка взимается за выбранный период. Отмените её в AppGallery в любое время. + Оплата будет снята с вашей учетной записи AppGallery при подтверждении покупки. +\n +\nПодписка продлевается автоматически, если она не будет отменена до даты продления. С вашего счета будет взиматься плата за период продления (месяц/три месяца/год) только в дату продления. +\n +\nВы можете управлять своими подписками и отменять их, перейдя в настройки AppGallery. \ No newline at end of file From dda863700c78832a7cae93d014e427c23253ede3 Mon Sep 17 00:00:00 2001 From: Deelite <556xxy@gmail.com> Date: Thu, 8 Oct 2020 00:50:47 +0000 Subject: [PATCH 36/95] Translated using Weblate (Russian) Currently translated at 100.0% (3493 of 3493 strings) --- OsmAnd/res/values-ru/strings.xml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/OsmAnd/res/values-ru/strings.xml b/OsmAnd/res/values-ru/strings.xml index 90e1c50349..17452f3328 100644 --- a/OsmAnd/res/values-ru/strings.xml +++ b/OsmAnd/res/values-ru/strings.xml @@ -73,7 +73,7 @@ Поиск почтового индекса Запись аудио⁣ Записать видео - Фотозаметка + Сделать фото OSM-заметка Функции парковки Благодарим вас за покупку платной версии OsmAnd. @@ -1813,7 +1813,7 @@ Хранилище карт Копировать Переместить файлы данных Osmand в новое место назначения\? - Напечатайте для поиска + Любой текст для поиска Номера домов Избегать пересечения границ Предельная высота @@ -3580,8 +3580,7 @@ Примечание: проверка скорости > 0: большинство модулей GPS сообщают значение скорости только в том случае, если алгоритм определяет, что вы движетесь, и ничего, если вы не перемещаетесь. Следовательно, использование параметра > 0 в этом фильтре в некотором смысле приводит к обнаружению факта перемещения модуля GPS. Но даже если мы не производим данную фильтрацию во время записи, то всё равно эта функция используется при анализе GPX для определения скорректированного расстояния, то есть значение, отображаемое в этом поле, является расстоянием, записанным во время движения. Разделение записи Укажите веб-адрес со следующими параметрами: lat={0}, lon={1}, timestamp={2}, hdop={3}, altitude={4}, speed={5}, bearing={6}. - "Будут записываться только точки, отвечающие -\n в минимальной точностью (в метрах/футах —зависит от настроек системы). Точность — это близость измерений к истинному положению, и она не связана напрямую с точностью, которая представляет собой разброс повторных измерений." + "Будут записываться только точки, отвечающие по показателю минимальной точности (в метрах или футах — зависит от настроек системы). Точность — это близость измерений к истинному положению, и она не связана напрямую с точностью, которая представляет собой разброс повторных измерений." Рекомендация: попробуйте сначала воспользоваться детектором движения через фильтр минимального смещения (B), что может дать лучшие результаты и вы потеряете меньше данных. Если треки остаются шумными на низких скоростях, попробуйте использовать ненулевые значения. Обратите внимание, что некоторые измерения могут вообще не указывать значения скорости (некоторые сетевые методы), и в этом случае ничего не будет записываться. Для визуализации крутизны рельефа используются цвета. Подробнее об уклонах можно прочитать в %1$s. From 81f114afe92da53e3dd66bd1902d2d3caa310da2 Mon Sep 17 00:00:00 2001 From: Ldm Public Date: Wed, 7 Oct 2020 21:22:40 +0000 Subject: [PATCH 37/95] Translated using Weblate (French) Currently translated at 99.9% (3492 of 3493 strings) --- OsmAnd/res/values-fr/strings.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/OsmAnd/res/values-fr/strings.xml b/OsmAnd/res/values-fr/strings.xml index 41007cc7eb..401664b66e 100644 --- a/OsmAnd/res/values-fr/strings.xml +++ b/OsmAnd/res/values-fr/strings.xml @@ -3885,4 +3885,7 @@ Nom : A – Z Icônes de départ / arrivée Merci pour votre achat de \'Courbes de niveaux\' + Abonnement facturé pour chaque période sélectionnée. Annulation possible à tout moment sur AppGallery. + Éviter les trottoirs + Éviter les trottoirs \ No newline at end of file From ad9b88354e6bb76e61a4a9cfdb234b149fc2b93d Mon Sep 17 00:00:00 2001 From: Jan-Hendrik Spieth Date: Thu, 8 Oct 2020 05:17:50 +0000 Subject: [PATCH 38/95] Translated using Weblate (German) Currently translated at 100.0% (3493 of 3493 strings) --- OsmAnd/res/values-de/strings.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OsmAnd/res/values-de/strings.xml b/OsmAnd/res/values-de/strings.xml index 1fcf32f445..281ac9f4d2 100644 --- a/OsmAnd/res/values-de/strings.xml +++ b/OsmAnd/res/values-de/strings.xml @@ -3826,7 +3826,7 @@ Wählen Sie eine Trackdatei zum Öffnen aus. Fertig Track überschreiben - Schwellenwert-Distanz + Maximaler Abstand Als neuen Track speichern Route umkehren Der gesamte Track wird mit dem ausgewählten Profil neu berechnet. From d42bb5d72ea96b8cf129553f0f03a0cc6bf93b8c Mon Sep 17 00:00:00 2001 From: nautilusx Date: Thu, 8 Oct 2020 05:15:04 +0000 Subject: [PATCH 39/95] Translated using Weblate (German) Currently translated at 100.0% (3493 of 3493 strings) --- OsmAnd/res/values-de/strings.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/OsmAnd/res/values-de/strings.xml b/OsmAnd/res/values-de/strings.xml index 281ac9f4d2..fcfcca7c77 100644 --- a/OsmAnd/res/values-de/strings.xml +++ b/OsmAnd/res/values-de/strings.xml @@ -3910,4 +3910,12 @@ Name: A – Z Start-/Ziel-Symbole Vielen Dank für den Kauf von \'Höhenlinien\' + Das Abonnement wird pro ausgewähltem Zeitraum berechnet. Sie können das Abonnement jederzeit über die AppGallery kündigen. + Die Bezahlung wird Ihrem AppGallery-Konto bei der Bestätigung des Kaufs belastet. +\n +\n Das Abonnement verlängert sich automatisch, sofern es nicht vor dem Verlängerungsdatum gekündigt wird. Ihr Konto wird für den Verlängerungszeitraum (Monat / drei Monate / Jahr) nur am Verlängerungsdatum belastet. +\n +\n Sie können Ihre Abonnements verwalten und kündigen, indem Sie zu Ihren AppGallery-Einstellungen gehen. + Vermeidet Fußwege + Keine Fußwege \ No newline at end of file From 968931a4bed9f8094f23188305083120b6dd0e4f Mon Sep 17 00:00:00 2001 From: Dmitriy Prodchenko Date: Thu, 8 Oct 2020 13:49:03 +0000 Subject: [PATCH 40/95] Translated using Weblate (Russian) Currently translated at 100.0% (3493 of 3493 strings) --- OsmAnd/res/values-ru/strings.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OsmAnd/res/values-ru/strings.xml b/OsmAnd/res/values-ru/strings.xml index 17452f3328..1f3bd7185a 100644 --- a/OsmAnd/res/values-ru/strings.xml +++ b/OsmAnd/res/values-ru/strings.xml @@ -1813,7 +1813,7 @@ Хранилище карт Копировать Переместить файлы данных Osmand в новое место назначения\? - Любой текст для поиска + Напечатайте для поиска Номера домов Избегать пересечения границ Предельная высота From 62f0d4b74029e84f609120dbd67b18eeda02e4c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?O=C4=9Fuz=20Ersen?= Date: Wed, 7 Oct 2020 22:02:49 +0000 Subject: [PATCH 41/95] Translated using Weblate (Turkish) Currently translated at 100.0% (3493 of 3493 strings) --- OsmAnd/res/values-tr/strings.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/OsmAnd/res/values-tr/strings.xml b/OsmAnd/res/values-tr/strings.xml index 50a41c8562..071ecab230 100644 --- a/OsmAnd/res/values-tr/strings.xml +++ b/OsmAnd/res/values-tr/strings.xml @@ -3861,4 +3861,12 @@ İsim: A – Z Başlangıç/bitiş simgeleri \'Eş yükselti eğrileri\'ni satın aldığınız için teşekkürler + Abonelik seçilen dönem başına ücretlendirilir. İstediğiniz zaman AppGallery\'den iptal edin. + Ödeme, satın alma onaylandığında AppGallery hesabınızdan alınacaktır. +\n +\nYenileme tarihinden önce iptal edilmedikçe abonelik otomatik olarak yenilenir. Hesabınızdan yenileme süresi (ay/üç ay/yıl) için yalnızca yenileme tarihinde ücret alınacaktır. +\n +\n AppGallery ayarlarınıza giderek aboneliklerinizi yönetebilir ve iptal edebilirsiniz. + Yaya yollarından kaçın + Yaya yollarından kaçın \ No newline at end of file From d3fa589a0f07279a2b73b5cba8d4c54c60470b9b Mon Sep 17 00:00:00 2001 From: Yaron Shahrabani Date: Thu, 8 Oct 2020 06:34:32 +0000 Subject: [PATCH 42/95] Translated using Weblate (Hebrew) Currently translated at 99.9% (3491 of 3493 strings) --- OsmAnd/res/values-iw/strings.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/OsmAnd/res/values-iw/strings.xml b/OsmAnd/res/values-iw/strings.xml index 42a840fa87..54343e43d2 100644 --- a/OsmAnd/res/values-iw/strings.xml +++ b/OsmAnd/res/values-iw/strings.xml @@ -3911,4 +3911,6 @@ שם: א – ת סמלי התחלה/סיום תודה לך על רכישת ‚קווי מתאר’ + הימנעות משבילי הולכי רגל + הימנעות משבילי הולכי רגל \ No newline at end of file From 12aeebf6d32329cd1eca2589f6e22159bead16d4 Mon Sep 17 00:00:00 2001 From: Ahmad Alfrhood Date: Thu, 8 Oct 2020 07:02:23 +0000 Subject: [PATCH 43/95] Translated using Weblate (Arabic) Currently translated at 100.0% (3493 of 3493 strings) --- OsmAnd/res/values-ar/strings.xml | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/OsmAnd/res/values-ar/strings.xml b/OsmAnd/res/values-ar/strings.xml index c1426b8483..c695a1c813 100644 --- a/OsmAnd/res/values-ar/strings.xml +++ b/OsmAnd/res/values-ar/strings.xml @@ -1074,7 +1074,7 @@ المسارات الرياضية وسائل المواصلات سمات أخرى للخريطة - العناصر الاخرى + العناصر الأخرى شريط المعلومات العدادات على اليمين العدادات على اليسار @@ -3413,7 +3413,7 @@ سترى الأيقونة فقط أثناء الملاحة أو أثناء التحرك. قيم تظهر أيقونة الخريطة فقط على الخريطة ، وتتغير أثناء التنقل إلى أيقونة التنقل. - تحقق وتبادل سجلات مفصلة من التطبيق + التحقق من السجلات التفصيلية للتطبيق ومشاركتها تعذر تحليل الهدف الجغرافي \'%s\'. الإذن مطلوب لاستخدام هذا الخيار. اعراض جانبية: سيفقد المسار الخاص بك جميع الأقسام التي لم يتحقق فيها معيار الحد الأدنى للسرعة (على سبيل المثال ، حيث تدفع دراجتك أعلى تل شديد الانحدار). أيضا ، لن تكون هناك معلومات حول فترات الراحة ، مثل الاستراحات. هذا له تأثيرات على أي تحليل أو مرحلة ما بعد المعالجة ، مثل عند محاولة تحديد المدة الإجمالية لرحلتك ، أو وقت الحركة ، أو متوسط سرعتك. @@ -3893,4 +3893,12 @@ الاسم: أ – ي رموز البدء/الانتهاء شكرا لشرائك \"خطوط الكنتور\" + رسوم الاشتراك ستفرض كل شهر. يمكنك إلغاء اشتراكك متى أردت عبر Google play. + سيتم تحصيل المبلغ على حساب AppGallery الخاص بك عند تأكيد الشراء. +\n +\nيتم تجديد الاشتراك تلقائيًا ما لم يتم إلغاؤه قبل تاريخ التجديد. سيتم خصم حسابك على فترة التجديد (شهر/ثلاثة أشهر/سنة) فقط في تاريخ التجديد. +\n +\nيمكنك إدارة وإلغاء الاشتراكات الخاصة بك عن طريق الانتقال إلى إعدادات AppGallery. + تجنب الممرات + تجنب الممرات \ No newline at end of file From 324fb1e58a620407bb51d350b7cedf150ebbd880 Mon Sep 17 00:00:00 2001 From: Ajeje Brazorf Date: Wed, 7 Oct 2020 21:36:29 +0000 Subject: [PATCH 44/95] Translated using Weblate (Sardinian) Currently translated at 99.7% (3483 of 3493 strings) --- OsmAnd/res/values-sc/strings.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/OsmAnd/res/values-sc/strings.xml b/OsmAnd/res/values-sc/strings.xml index 57221ff561..06484d1e32 100644 --- a/OsmAnd/res/values-sc/strings.xml +++ b/OsmAnd/res/values-sc/strings.xml @@ -3905,4 +3905,12 @@ Nùmene: A – Z Iconas de incumintzu/fine Gràtzias pro àere comporadu \'Curvas de livellu\' + Costu periòdicu de s\'abbonamentu. Lu podes anullare in AppGallery cando boles. + Su pagamentu at a èssere addebitadu a su contu tuo de AppGallery cando sa còmpora at a èssere cunfirmada. +\n +\nS\'abbonamentu si rinnovat a sa sola automaticamente, francu chi siat istadu annulladu in antis de sa die de su rinnovu. Su contu tuo at a bènnere addebitadu pro su perìodu de rinnovu (mese/tres meses/annu) in sa die de rinnovu ebbia. +\n +\nPodes amministrare e annullare sos abbonamentos tuos intrende in sas impostatziones de AppGallery tuas. + Èvita sos martzapiedis + Èvita sos martzapiedis \ No newline at end of file From 7e88d639a06e9cc66c2d076478a5014277859088 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Priit=20J=C3=B5er=C3=BC=C3=BCt?= Date: Thu, 8 Oct 2020 06:27:37 +0000 Subject: [PATCH 45/95] Translated using Weblate (Estonian) Currently translated at 99.4% (3473 of 3493 strings) --- OsmAnd/res/values-et/strings.xml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/OsmAnd/res/values-et/strings.xml b/OsmAnd/res/values-et/strings.xml index 8e58fdad52..fe5cbbfa20 100644 --- a/OsmAnd/res/values-et/strings.xml +++ b/OsmAnd/res/values-et/strings.xml @@ -3764,4 +3764,13 @@ Nimi: A – Z Ekraani väljalülitamine Ratastool edasi + Väldi jalgteid + Väldi jalgteid + Täname „Kõrgusjoonte“ ostu eest + Ostukinnituse saabumisel arveldame tellimuse eest sinu AppGallery konto alusel. +\n +\nKui sa ei tühista tellimust enne uue perioodi algust, siis tellimus pikeneb automaatselt ning arveldame järgmise ajavahemiku eest (kuu/kvartal/aasta) selle alguses. +\n +\nTellimust saad hallata ja tühistada AppGallery seadistustest. + Arveldame tellimuse eest valitud ajavahemiku alusel. Seda saad sa vabalt valitud ajal tühistada AppGallery\'s. \ No newline at end of file From b9fd31aa90e53d67608f0e343051d6b01fe758d2 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 8 Oct 2020 06:40:25 +0000 Subject: [PATCH 46/95] Translated using Weblate (Chinese (Traditional)) Currently translated at 100.0% (3493 of 3493 strings) --- OsmAnd/res/values-zh-rTW/strings.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/OsmAnd/res/values-zh-rTW/strings.xml b/OsmAnd/res/values-zh-rTW/strings.xml index cf0cc3fd99..1d6615754e 100644 --- a/OsmAnd/res/values-zh-rTW/strings.xml +++ b/OsmAnd/res/values-zh-rTW/strings.xml @@ -3901,4 +3901,12 @@ 名稱:A – Z 開始/結束圖示 感謝您購買 \'Contour lines\' + 按選定週期收取訂閱費用。隨時在 AppGallery 上取消。 + 確認購買後將會從您的 AppGallery 帳號中付款。 +\n +\n除非在續訂日期前取消,否則就會自動續訂。您的帳號將只會在續訂日期收取訂閱週期(一個月/三個月/一年)的費用。 +\n +\n您可以在您的 AppGallery 設定中管理與取消您的訂閱。 + 避免人行道 + 避免人行道 \ No newline at end of file From fbdd3db40e014d3e840be57a5f4e4d6b3f567891 Mon Sep 17 00:00:00 2001 From: Ahmad Alfrhood Date: Thu, 8 Oct 2020 06:10:21 +0000 Subject: [PATCH 47/95] Translated using Weblate (Arabic) Currently translated at 100.0% (271 of 271 strings) Translation: OsmAnd/Telegram Translate-URL: https://hosted.weblate.org/projects/osmand/telegram/ar/ --- OsmAnd-telegram/res/values-ar/strings.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/OsmAnd-telegram/res/values-ar/strings.xml b/OsmAnd-telegram/res/values-ar/strings.xml index 1fb4149e0b..45b5d99ce7 100644 --- a/OsmAnd-telegram/res/values-ar/strings.xml +++ b/OsmAnd-telegram/res/values-ar/strings.xml @@ -267,4 +267,8 @@ تتبع حالة أوسماند العودة إلى OsmAnd %1$s منذ + إرسال التقرير + تصدير + سجل الاستخدام + التحقق من السجلات التفصيلية للتطبيق ومشاركتها \ No newline at end of file From e6c8d5e7500841f3f2bea33569f165680aa3aac5 Mon Sep 17 00:00:00 2001 From: yogiks Date: Thu, 8 Oct 2020 19:31:02 +0530 Subject: [PATCH 48/95] Add Kannada --- OsmAnd-java/src/main/java/net/osmand/osm/MapRenderingTypes.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OsmAnd-java/src/main/java/net/osmand/osm/MapRenderingTypes.java b/OsmAnd-java/src/main/java/net/osmand/osm/MapRenderingTypes.java index 34e5048930..d996678e44 100644 --- a/OsmAnd-java/src/main/java/net/osmand/osm/MapRenderingTypes.java +++ b/OsmAnd-java/src/main/java/net/osmand/osm/MapRenderingTypes.java @@ -27,7 +27,7 @@ public abstract class MapRenderingTypes { private static final Log log = PlatformUtil.getLog(MapRenderingTypes.class); public static final String[] langs = new String[] { "af", "als", "ar", "az", "be", "bg", "bn", "bpy", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "eo", "es", "et", "eu", "fa", "fi", "fr", "fy", "ga", "gl", "he", "hi", "hsb", - "hr", "ht", "hu", "hy", "id", "is", "it", "ja", "ka", "ko", "ku", "la", "lb", "lo", "lt", "lv", "mk", "ml", "mr", "ms", "nds", "new", "nl", "nn", "no", "nv", "os", "pl", "pms", "pt", "ro", "ru", "sc", "sh", "sk", "sl", "sq", "sr", "sv", "sw", "ta", "te", "th", "tl", "tr", "uk", "vi", "vo", "zh", "zh-hans", "zh-hant", }; + "hr", "ht", "hu", "hy", "id", "is", "it", "ja", "ka", "kn", "ko", "ku", "la", "lb", "lo", "lt", "lv", "mk", "ml", "mr", "ms", "nds", "new", "nl", "nn", "no", "nv", "os", "pl", "pms", "pt", "ro", "ru", "sc", "sh", "sk", "sl", "sq", "sr", "sv", "sw", "ta", "te", "th", "tl", "tr", "uk", "vi", "vo", "zh", "zh-hans", "zh-hant", }; public final static byte RESTRICTION_NO_RIGHT_TURN = 1; From 4faf931d2011f5e146e89905ad308baf6b7fca2e Mon Sep 17 00:00:00 2001 From: sergosm Date: Thu, 8 Oct 2020 17:01:38 +0300 Subject: [PATCH 49/95] OpenGL verification --- .../osmand/plus/development/DevelopmentSettingsFragment.java | 2 +- .../osmand/plus/development/SettingsDevelopmentActivity.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/development/DevelopmentSettingsFragment.java b/OsmAnd/src/net/osmand/plus/development/DevelopmentSettingsFragment.java index 97e6bd12cd..774e5f47f2 100644 --- a/OsmAnd/src/net/osmand/plus/development/DevelopmentSettingsFragment.java +++ b/OsmAnd/src/net/osmand/plus/development/DevelopmentSettingsFragment.java @@ -59,7 +59,7 @@ public class DevelopmentSettingsFragment extends BaseSettingsFragment { private void setupOpenglRenderPref() { SwitchPreferenceEx useOpenglRender = findPreference(settings.USE_OPENGL_RENDER.getId()); - if (app.getSettings().USE_OPENGL_RENDER.get() && NativeCoreContext.isInit()) { + if (Version.isOpenGlAvailable(app)) { assert useOpenglRender != null; useOpenglRender.setDescription(getString(R.string.use_opengl_render_descr)); useOpenglRender.setIconSpaceReserved(false); diff --git a/OsmAnd/src/net/osmand/plus/development/SettingsDevelopmentActivity.java b/OsmAnd/src/net/osmand/plus/development/SettingsDevelopmentActivity.java index f7e1fa064f..c500a28254 100644 --- a/OsmAnd/src/net/osmand/plus/development/SettingsDevelopmentActivity.java +++ b/OsmAnd/src/net/osmand/plus/development/SettingsDevelopmentActivity.java @@ -111,7 +111,7 @@ public class SettingsDevelopmentActivity extends SettingsBaseActivity { debug.addPreference(createCheckBoxPreference(settings.SHOULD_SHOW_FREE_VERSION_BANNER, R.string.show_free_version_banner, R.string.show_free_version_banner_description)); - + pref = new Preference(this); pref.setTitle(R.string.test_voice_prompts); pref.setSummary(R.string.play_commands_of_currently_selected_voice); From 800ffe1819b69bad5dd1394715f7371a4f99aa80 Mon Sep 17 00:00:00 2001 From: Dima-1 Date: Thu, 8 Oct 2020 20:35:53 +0300 Subject: [PATCH 50/95] Fix import profile by AIDL --- .../src/net/osmand/plus/settings/backend/SettingsHelper.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/SettingsHelper.java b/OsmAnd/src/net/osmand/plus/settings/backend/SettingsHelper.java index 0172531139..9831206962 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/SettingsHelper.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/SettingsHelper.java @@ -2937,6 +2937,11 @@ public class SettingsHelper { for (ExportSettingsType settingsType : settingsTypes) { List settingsDataObjects = additionalData.get(settingsType); if (settingsDataObjects != null) { + for (Object object : settingsDataObjects) { + if (object instanceof ApplicationModeBean) { + settingsItems.add(new ProfileSettingsItem(app, null, (ApplicationModeBean) object)); + } + } settingsItems.addAll(prepareAdditionalSettingsItems(new ArrayList<>(settingsDataObjects))); } } From 674423b0581c31e059c9ed293b7d41718fc26ab5 Mon Sep 17 00:00:00 2001 From: Dima-1 Date: Thu, 8 Oct 2020 20:36:19 +0300 Subject: [PATCH 51/95] Fix sorting menu items --- .../src/net/osmand/plus/ContextMenuAdapter.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java b/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java index 26e173d568..102234a3cf 100644 --- a/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java +++ b/OsmAnd/src/net/osmand/plus/ContextMenuAdapter.java @@ -137,14 +137,18 @@ public class ContextMenuAdapter { Collections.sort(items, new Comparator() { @Override public int compare(ContextMenuItem item1, ContextMenuItem item2) { - if (DRAWER_SWITCH_PROFILE_ID.equals(item1.getId())) { - return -1; - } - if (DRAWER_CONFIGURE_PROFILE_ID.equals(item1.getId()) && DRAWER_SWITCH_PROFILE_ID.equals(item2.getId())) { + if (DRAWER_CONFIGURE_PROFILE_ID.equals(item1.getId()) + && DRAWER_SWITCH_PROFILE_ID.equals(item2.getId())) { return 1; - } - if (DRAWER_CONFIGURE_PROFILE_ID.equals(item1.getId())) { + } else if (DRAWER_SWITCH_PROFILE_ID.equals(item1.getId()) + && DRAWER_CONFIGURE_PROFILE_ID.equals(item2.getId())) { return -1; + } else if (DRAWER_SWITCH_PROFILE_ID.equals(item1.getId()) + || DRAWER_CONFIGURE_PROFILE_ID.equals(item1.getId())) { + return -1; + } else if (DRAWER_SWITCH_PROFILE_ID.equals(item2.getId()) + || DRAWER_CONFIGURE_PROFILE_ID.equals(item2.getId())) { + return 1; } int order1 = item1.getOrder(); int order2 = item2.getOrder(); From dc55878c922803a47ff6f534d5fde0dd9b8e312e Mon Sep 17 00:00:00 2001 From: Vitaliy Date: Thu, 8 Oct 2020 22:45:39 +0300 Subject: [PATCH 52/95] Fix version upgrade and remove unnecessary changes --- .../osmand/plus/AppVersionUpgradeOnInit.java | 80 +++++++++---- .../osmand/plus/helpers/DayNightHelper.java | 28 ++--- .../plus/helpers/enums/AngularConstants.java | 3 +- .../plus/helpers/enums/AutoZoomMap.java | 4 +- .../plus/helpers/enums/DayNightMode.java | 2 +- .../plus/helpers/enums/DrivingRegion.java | 4 +- .../plus/helpers/enums/MetricsConstants.java | 3 +- .../plus/helpers/enums/SpeedConstants.java | 3 +- .../plus/mapmarkers/MapMarkersMode.java | 2 +- .../settings/backend/BooleanPreference.java | 8 +- .../backend/BooleanStringPreference.java | 4 +- .../settings/backend/CommonPreference.java | 53 +++++---- .../backend/ContextMenuItemsPreference.java | 8 +- .../backend/ContextMenuItemsSettings.java | 5 +- .../backend/EnumStringPreference.java | 8 +- .../settings/backend/FloatPreference.java | 8 +- .../backend/ImpassableRoadsStorage.java | 22 ++-- .../plus/settings/backend/IntPreference.java | 10 +- .../backend/IntermediatePointsStorage.java | 2 +- .../backend/ListStringPreference.java | 20 ++-- .../plus/settings/backend/LongPreference.java | 10 +- .../backend/MainContextMenuItemsSettings.java | 8 +- .../backend/OsmAndPreferencesDataStore.java | 10 +- .../settings/backend/OsmandPreference.java | 2 +- .../plus/settings/backend/OsmandSettings.java | 107 +++++------------- .../backend/PreferenceWithListener.java | 2 +- .../plus/settings/backend/SettingsHelper.java | 22 +++- .../backend/SettingsMapPointsStorage.java | 8 +- .../settings/backend/StringPreference.java | 8 +- .../src/net/osmand/plus/views/GPXLayer.java | 0 .../plus/views/layers/RulerControlLayer.java | 6 + .../osmand/plus/views/layers/RulerMode.java | 7 -- .../mapwidgets/MapInfoWidgetsFactory.java | 2 +- 33 files changed, 237 insertions(+), 232 deletions(-) delete mode 100644 OsmAnd/src/net/osmand/plus/views/GPXLayer.java delete mode 100644 OsmAnd/src/net/osmand/plus/views/layers/RulerMode.java diff --git a/OsmAnd/src/net/osmand/plus/AppVersionUpgradeOnInit.java b/OsmAnd/src/net/osmand/plus/AppVersionUpgradeOnInit.java index 49e354ea8b..9eeec4542b 100644 --- a/OsmAnd/src/net/osmand/plus/AppVersionUpgradeOnInit.java +++ b/OsmAnd/src/net/osmand/plus/AppVersionUpgradeOnInit.java @@ -7,8 +7,10 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; -import net.osmand.data.FavouritePoint; +import net.osmand.data.FavouritePoint.SpecialPointType; import net.osmand.data.LatLon; +import net.osmand.plus.AppInitializer.AppInitializeListener; +import net.osmand.plus.AppInitializer.InitEvents; import net.osmand.plus.api.SettingsAPI; import net.osmand.plus.settings.backend.ApplicationMode; import net.osmand.plus.settings.backend.CommonPreference; @@ -24,6 +26,7 @@ import java.util.List; import java.util.Map; class AppVersionUpgradeOnInit { + public static final String FIRST_TIME_APP_RUN = "FIRST_TIME_APP_RUN"; //$NON-NLS-1$ public static final String VERSION_INSTALLED_NUMBER = "VERSION_INSTALLED_NUMBER"; //$NON-NLS-1$ public static final String NUMBER_OF_STARTS = "NUMBER_OF_STARTS"; //$NON-NLS-1$ @@ -56,16 +59,14 @@ class AppVersionUpgradeOnInit { private int prevAppVersion; private boolean appVersionChanged; private boolean firstTime; - private OsmandSettings settings; AppVersionUpgradeOnInit(OsmandApplication app) { this.app = app; - settings = app.getSettings(); } @SuppressLint("ApplySharedPref") void upgradeVersion(SharedPreferences startPrefs, int lastVersion) { - if(!startPrefs.contains(NUMBER_OF_STARTS)) { + if (!startPrefs.contains(NUMBER_OF_STARTS)) { startPrefs.edit().putInt(NUMBER_OF_STARTS, 1).commit(); } else { startPrefs.edit().putInt(NUMBER_OF_STARTS, startPrefs.getInt(NUMBER_OF_STARTS, 0) + 1).commit(); @@ -81,7 +82,7 @@ class AppVersionUpgradeOnInit { } else { prevAppVersion = startPrefs.getInt(VERSION_INSTALLED_NUMBER, 0); if (needsUpgrade(startPrefs, lastVersion)) { - + OsmandSettings settings = app.getSettings(); if (prevAppVersion < VERSION_2_2) { settings.SHOW_DASHBOARD_ON_START.set(true); settings.SHOW_DASHBOARD_ON_MAP_SCREEN.set(true); @@ -121,13 +122,14 @@ class AppVersionUpgradeOnInit { startPrefs.edit().putInt(VERSION_INSTALLED_NUMBER, VERSION_3_7).commit(); } if (prevAppVersion < VERSION_3_7_01) { - app.getAppInitializer().addListener(new AppInitializer.AppInitializeListener() { + app.getAppInitializer().addListener(new AppInitializeListener() { @Override public void onProgress(AppInitializer init, AppInitializer.InitEvents event) { - if (event.equals(AppInitializer.InitEvents.FAVORITES_INITIALIZED)) { + if (event.equals(InitEvents.FAVORITES_INITIALIZED)) { app.getFavorites().fixBlackBackground(); } } + @Override public void onFinish(AppInitializer init) { } @@ -158,20 +160,20 @@ class AppVersionUpgradeOnInit { } public void resetFirstTimeRun(SharedPreferences startPrefs) { - if(startPrefs != null) { + if (startPrefs != null) { startPrefs.edit().remove(FIRST_TIME_APP_RUN).commit(); } } public int getNumberOfStarts(SharedPreferences startPrefs) { - if(startPrefs == null) { + if (startPrefs == null) { return 0; } return startPrefs.getInt(NUMBER_OF_STARTS, 1); } public long getFirstInstalledDays(SharedPreferences startPrefs) { - if(startPrefs == null) { + if (startPrefs == null) { return 0; } long nd = startPrefs.getLong(FIRST_INSTALLED, 0); @@ -183,9 +185,8 @@ class AppVersionUpgradeOnInit { return firstTime; } - - public void migratePreferences() { + OsmandSettings settings = app.getSettings(); migrateEnumPreferences(); SharedPreferences globalSharedPreferences = (SharedPreferences) settings.getGlobalPreferences(); Map globalPrefsMap = globalSharedPreferences.getAll(); @@ -213,7 +214,7 @@ class AppVersionUpgradeOnInit { } } } - for (OsmandPreference pref : settings.getGeneralPrefs()) { + for (OsmandPreference pref : getGeneralPrefs()) { if (pref instanceof CommonPreference) { CommonPreference commonPref = (CommonPreference) pref; Object defaultVal = commonPref.getModeValue(ApplicationMode.DEFAULT); @@ -224,7 +225,6 @@ class AppVersionUpgradeOnInit { } } } - String json = settings.getSettingsAPI().getString(settings.getGlobalPreferences(), "custom_app_profiles", ""); if (!Algorithms.isEmpty(json)) { Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); @@ -241,9 +241,10 @@ class AppVersionUpgradeOnInit { } public void migrateEnumPreferences() { - for (OsmandPreference pref : settings.getRegisteredPreferences().values()) { + OsmandSettings settings = app.getSettings(); + for (OsmandPreference pref : settings.getRegisteredPreferences().values()) { if (pref instanceof EnumStringPreference) { - EnumStringPreference enumPref = (EnumStringPreference) pref; + EnumStringPreference enumPref = (EnumStringPreference) pref; if (enumPref.isGlobal()) { migrateEnumPref(enumPref, (SharedPreferences) settings.getGlobalPreferences()); } else { @@ -256,6 +257,7 @@ class AppVersionUpgradeOnInit { } public void migrateQuickActionStates() { + OsmandSettings settings = app.getSettings(); String quickActionsJson = settings.getSettingsAPI().getString(settings.getGlobalPreferences(), "quick_action_new", ""); if (!Algorithms.isEmpty(quickActionsJson)) { Gson gson = new GsonBuilder().create(); @@ -282,9 +284,10 @@ class AppVersionUpgradeOnInit { } public void migrateHomeWorkParkingToFavorites() { + OsmandSettings settings = app.getSettings(); FavouritesDbHelper favorites = app.getFavorites(); SettingsAPI settingsAPI = settings.getSettingsAPI(); - Object globalPreferences= settings.getGlobalPreferences(); + Object globalPreferences = settings.getGlobalPreferences(); LatLon homePoint = null; float lat = settingsAPI.getFloat(globalPreferences, "home_point_lat", 0); @@ -299,10 +302,47 @@ class AppVersionUpgradeOnInit { workPoint = new LatLon(lat, lon); } if (homePoint != null) { - favorites.setSpecialPoint(homePoint, FavouritePoint.SpecialPointType.HOME, null); + favorites.setSpecialPoint(homePoint, SpecialPointType.HOME, null); } if (workPoint != null) { - favorites.setSpecialPoint(workPoint, FavouritePoint.SpecialPointType.WORK, null); + favorites.setSpecialPoint(workPoint, SpecialPointType.WORK, null); } } -} + + + public OsmandPreference[] getGeneralPrefs() { + OsmandSettings settings = app.getSettings(); + return new OsmandPreference[] { + settings.EXTERNAL_INPUT_DEVICE, + settings.CENTER_POSITION_ON_MAP, + settings.ROTATE_MAP, + settings.MAP_SCREEN_ORIENTATION, + settings.LIVE_MONITORING_URL, + settings.LIVE_MONITORING_MAX_INTERVAL_TO_SEND, + settings.LIVE_MONITORING_INTERVAL, + settings.LIVE_MONITORING, + settings.SHOW_TRIP_REC_NOTIFICATION, + settings.AUTO_SPLIT_RECORDING, + settings.SAVE_TRACK_MIN_SPEED, + settings.SAVE_TRACK_PRECISION, + settings.SAVE_TRACK_MIN_DISTANCE, + settings.SAVE_TRACK_INTERVAL, + settings.TRACK_STORAGE_DIRECTORY, + settings.SAVE_HEADING_TO_GPX, + settings.DISABLE_RECORDING_ONCE_APP_KILLED, + settings.SAVE_TRACK_TO_GPX, + settings.SAVE_GLOBAL_TRACK_REMEMBER, + settings.SAVE_GLOBAL_TRACK_INTERVAL, + settings.MAP_EMPTY_STATE_ALLOWED, + settings.DO_NOT_USE_ANIMATIONS, + settings.USE_KALMAN_FILTER_FOR_COMPASS, + settings.USE_MAGNETIC_FIELD_SENSOR_COMPASS, + settings.USE_TRACKBALL_FOR_MOVEMENTS, + settings.SPEED_SYSTEM, + settings.ANGULAR_UNITS, + settings.METRIC_SYSTEM, + settings.DRIVING_REGION, + settings.DRIVING_REGION_AUTOMATIC + }; + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/helpers/DayNightHelper.java b/OsmAnd/src/net/osmand/plus/helpers/DayNightHelper.java index ea4f6a1ae7..d3ebe9d6ae 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/DayNightHelper.java +++ b/OsmAnd/src/net/osmand/plus/helpers/DayNightHelper.java @@ -1,20 +1,6 @@ package net.osmand.plus.helpers; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import net.osmand.Location; -import net.osmand.PlatformUtil; -import net.osmand.StateChangedListener; -import net.osmand.plus.helpers.enums.DayNightMode; -import net.osmand.plus.settings.backend.ApplicationMode; -import net.osmand.plus.OsmandApplication; -import net.osmand.util.SunriseSunset; - -import org.apache.commons.logging.Log; - import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; @@ -22,6 +8,20 @@ import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.LocationManager; +import net.osmand.Location; +import net.osmand.PlatformUtil; +import net.osmand.StateChangedListener; +import net.osmand.plus.OsmandApplication; +import net.osmand.plus.helpers.enums.DayNightMode; +import net.osmand.plus.settings.backend.ApplicationMode; +import net.osmand.util.SunriseSunset; + +import org.apache.commons.logging.Log; + +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + /** * Class to help determine if we want to render day or night map - it uses the * DayNightMode enumeration for its behavior
diff --git a/OsmAnd/src/net/osmand/plus/helpers/enums/AngularConstants.java b/OsmAnd/src/net/osmand/plus/helpers/enums/AngularConstants.java index 9962144fa4..4041380fe1 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/enums/AngularConstants.java +++ b/OsmAnd/src/net/osmand/plus/helpers/enums/AngularConstants.java @@ -24,5 +24,4 @@ public enum AngularConstants { public String getUnitSymbol() { return unit; } - -} +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/helpers/enums/AutoZoomMap.java b/OsmAnd/src/net/osmand/plus/helpers/enums/AutoZoomMap.java index f092c19be7..ad09424924 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/enums/AutoZoomMap.java +++ b/OsmAnd/src/net/osmand/plus/helpers/enums/AutoZoomMap.java @@ -6,6 +6,7 @@ public enum AutoZoomMap { FARTHEST(R.string.auto_zoom_farthest, 1f, 15.5f), FAR(R.string.auto_zoom_far, 1.4f, 17f), CLOSE(R.string.auto_zoom_close, 2f, 19f); + public final float coefficient; public final int name; public final float maxZoom; @@ -14,6 +15,5 @@ public enum AutoZoomMap { this.name = name; this.coefficient = coefficient; this.maxZoom = maxZoom; - } -} +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/helpers/enums/DayNightMode.java b/OsmAnd/src/net/osmand/plus/helpers/enums/DayNightMode.java index 9c8865e877..77f0eb8876 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/enums/DayNightMode.java +++ b/OsmAnd/src/net/osmand/plus/helpers/enums/DayNightMode.java @@ -59,4 +59,4 @@ public enum DayNightMode { return new DayNightMode[]{AUTO, DAY, NIGHT}; } } -} +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/helpers/enums/DrivingRegion.java b/OsmAnd/src/net/osmand/plus/helpers/enums/DrivingRegion.java index 70c825926e..60902c46b5 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/enums/DrivingRegion.java +++ b/OsmAnd/src/net/osmand/plus/helpers/enums/DrivingRegion.java @@ -54,9 +54,9 @@ public enum DrivingRegion { return DrivingRegion.JAPAN; } else if (df.getCountry().equalsIgnoreCase("au")) { return DrivingRegion.AUSTRALIA; - } else if(df.getCountry().equalsIgnoreCase(Locale.UK.getCountry())) { + } else if (df.getCountry().equalsIgnoreCase(Locale.UK.getCountry())) { return DrivingRegion.UK_AND_OTHERS; } return DrivingRegion.EUROPE_ASIA; } -} +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/helpers/enums/MetricsConstants.java b/OsmAnd/src/net/osmand/plus/helpers/enums/MetricsConstants.java index 23034b5277..20f3804a6a 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/enums/MetricsConstants.java +++ b/OsmAnd/src/net/osmand/plus/helpers/enums/MetricsConstants.java @@ -26,5 +26,4 @@ public enum MetricsConstants { public String toTTSString() { return ttsString; } - -} +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/helpers/enums/SpeedConstants.java b/OsmAnd/src/net/osmand/plus/helpers/enums/SpeedConstants.java index 15a54513eb..1a4c512b8c 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/enums/SpeedConstants.java +++ b/OsmAnd/src/net/osmand/plus/helpers/enums/SpeedConstants.java @@ -29,5 +29,4 @@ public enum SpeedConstants { public String toShortString(Context ctx) { return ctx.getString(key); } - -} +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersMode.java b/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersMode.java index 840da1ad92..a9cf23ea75 100644 --- a/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersMode.java +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersMode.java @@ -34,4 +34,4 @@ public enum MapMarkersMode { public static MapMarkersMode[] possibleValues(Context context) { return new MapMarkersMode[]{TOOLBAR, WIDGETS, NONE}; } -} +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/BooleanPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanPreference.java index 9a0c2a2391..9ff4d3069d 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/BooleanPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanPreference.java @@ -2,12 +2,12 @@ package net.osmand.plus.settings.backend; public class BooleanPreference extends CommonPreference { - BooleanPreference(OsmandSettings osmandSettings, String id, boolean defaultValue) { - super(osmandSettings, id, defaultValue); + BooleanPreference(OsmandSettings settings, String id, boolean defaultValue) { + super(settings, id, defaultValue); } @Override - public Boolean getValue(Object prefs, Boolean defaultValue) { + protected Boolean getValue(Object prefs, Boolean defaultValue) { return getSettingsAPI().getBoolean(prefs, getId(), defaultValue); } @@ -20,4 +20,4 @@ public class BooleanPreference extends CommonPreference { public Boolean parseString(String s) { return Boolean.parseBoolean(s); } -} +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/BooleanStringPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanStringPreference.java index 8ca99f8521..1928fa60a7 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/BooleanStringPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/BooleanStringPreference.java @@ -7,7 +7,7 @@ public class BooleanStringPreference extends BooleanPreference { } @Override - public Boolean getValue(Object prefs, Boolean defaultValue) { + protected Boolean getValue(Object prefs, Boolean defaultValue) { Boolean value; try { value = parseString(getSettingsAPI().getString(prefs, getId(), defaultValue.toString())); @@ -22,4 +22,4 @@ public class BooleanStringPreference extends BooleanPreference { protected boolean setValue(Object prefs, Boolean val) { return getSettingsAPI().edit(prefs).putString(getId(), val != null ? val.toString() : null).commit(); } -} +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java index ea1c251375..62ce3a2450 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/CommonPreference.java @@ -10,25 +10,29 @@ import java.util.LinkedHashMap; import java.util.Map; public abstract class CommonPreference extends PreferenceWithListener { - private OsmandSettings osmandSettings; - private final String id; - private boolean global; - private T cachedValue; + + private OsmandSettings settings; private Object cachedPreference; - private boolean cache; - private Map defaultValues; + + private final String id; + + private T cachedValue; private T defaultValue; + private Map defaultValues; + + private boolean cache; + private boolean global; - public CommonPreference(OsmandSettings osmandSettings, String id, T defaultValue) { - this.osmandSettings = osmandSettings; + public CommonPreference(OsmandSettings settings, String id, T defaultValue) { + this.settings = settings; this.id = id; this.defaultValue = defaultValue; - osmandSettings.registerInternalPreference(id, this); + settings.registerInternalPreference(id, this); } // Methods to possibly override - public abstract T getValue(Object prefs, T defaultValue); + protected abstract T getValue(Object prefs, T defaultValue); protected abstract boolean setValue(Object prefs, T val); @@ -39,15 +43,15 @@ public abstract class CommonPreference extends PreferenceWithListener { } protected SettingsAPI getSettingsAPI() { - return osmandSettings.getSettingsAPI(); + return settings.getSettingsAPI(); } protected ApplicationMode getApplicationMode() { - return osmandSettings.getApplicationMode(); + return settings.getApplicationMode(); } protected OsmandApplication getContext() { - return osmandSettings.getContext(); + return settings.getContext(); } // common methods @@ -68,7 +72,7 @@ public abstract class CommonPreference extends PreferenceWithListener { } protected final Object getPreferences() { - return osmandSettings.getPreferences(global); + return settings.getPreferences(global); } @@ -86,7 +90,7 @@ public abstract class CommonPreference extends PreferenceWithListener { return set(obj); } - Object profilePrefs = osmandSettings.getProfilePreferences(mode); + Object profilePrefs = settings.getProfilePreferences(mode); boolean valueSaved = setValue(profilePrefs, obj); if (valueSaved && cache && cachedPreference == profilePrefs) { cachedValue = obj; @@ -121,7 +125,7 @@ public abstract class CommonPreference extends PreferenceWithListener { // TODO final protected T getDefaultValue() { - return getProfileDefaultValue(osmandSettings.currentMode); + return getProfileDefaultValue(settings.APPLICATION_MODE.get()); } @Override @@ -129,8 +133,6 @@ public abstract class CommonPreference extends PreferenceWithListener { this.defaultValue = newDefaultValue; } - - // TODO final @Override public T getModeValue(ApplicationMode mode) { @@ -138,7 +140,7 @@ public abstract class CommonPreference extends PreferenceWithListener { return get(); } T defaultV = getProfileDefaultValue(mode); - return getValue(osmandSettings.getProfilePreferences(mode), defaultV); + return getValue(settings.getProfilePreferences(mode), defaultV); } // TODO final @@ -148,7 +150,7 @@ public abstract class CommonPreference extends PreferenceWithListener { return cachedValue; } cachedPreference = getPreferences(); - cachedValue = getValue(cachedPreference, getProfileDefaultValue(osmandSettings.currentMode)); + cachedValue = getValue(cachedPreference, getProfileDefaultValue(settings.APPLICATION_MODE.get())); return cachedValue; } @@ -159,7 +161,7 @@ public abstract class CommonPreference extends PreferenceWithListener { @Override public final void resetToDefault() { - T o = getProfileDefaultValue(osmandSettings.currentMode); + T o = getProfileDefaultValue(settings.APPLICATION_MODE.get()); set(o); } @@ -186,12 +188,12 @@ public abstract class CommonPreference extends PreferenceWithListener { return false; } - public final boolean isSet() { - return osmandSettings.isSet(global, getId()); + public final boolean isSet() { + return settings.isSet(global, getId()); } public boolean isSetForMode(ApplicationMode mode) { - return osmandSettings.isSet(mode, getId()); + return settings.isSet(mode, getId()); } public final boolean isGlobal() { @@ -218,6 +220,7 @@ public abstract class CommonPreference extends PreferenceWithListener { } return false; } + // TODO final @Override public void readFromJson(JSONObject json, ApplicationMode appMode) throws JSONException { @@ -243,4 +246,4 @@ public abstract class CommonPreference extends PreferenceWithListener { T v = getModeValue(m); return toString(v); } -} +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsPreference.java b/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsPreference.java index 4e562f1aca..12a83ea229 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsPreference.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/ContextMenuItemsPreference.java @@ -6,13 +6,13 @@ public class ContextMenuItemsPreference extends CommonPreference