From 19e5db7b0a6b2b1f687a297aadea1bfa8d16191a Mon Sep 17 00:00:00 2001 From: max-klaus Date: Thu, 11 Jun 2020 15:14:56 +0300 Subject: [PATCH 1/6] Fix raster map menu crash --- .../rastermaps/OsmandRasterMapsPlugin.java | 301 ++++++++++-------- 1 file changed, 174 insertions(+), 127 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java b/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java index 9194949691..58af80e351 100644 --- a/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java +++ b/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java @@ -1,6 +1,7 @@ package net.osmand.plus.rastermaps; import android.app.Activity; +import android.content.Context; import android.content.DialogInterface; import android.graphics.drawable.Drawable; import android.os.AsyncTask; @@ -52,6 +53,7 @@ import net.osmand.plus.views.OsmandMapTileView; import net.osmand.util.Algorithms; import java.io.File; +import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -128,8 +130,6 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { }; // mapView.addLayer(overlayLayer, 0.7f); settings.MAP_OVERLAY_TRANSPARENCY.addListener(overlayLayerListener); - - } @Override @@ -138,8 +138,9 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { } - public void updateMapLayers(OsmandMapTileView mapView, CommonPreference settingsToWarnAboutMap, - final MapActivityLayers layers) { + public void updateMapLayers(OsmandMapTileView mapView, + CommonPreference settingsToWarnAboutMap, + MapActivityLayers layers) { if (overlayLayer == null) { createLayers(); } @@ -169,7 +170,8 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { } public void updateLayer(OsmandMapTileView mapView, OsmandSettings settings, - MapTileLayer layer, CommonPreference preference, float layerOrder, boolean warnWhenSelected) { + MapTileLayer layer, CommonPreference preference, + float layerOrder, boolean warnWhenSelected) { ITileSource overlay = settings.getTileSourceByName(preference.get(), warnWhenSelected); if (!Algorithms.objectEquals(overlay, layer.getMap())) { if (overlay == null) { @@ -186,21 +188,21 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { @NonNull final CommonPreference mapPref, @NonNull final CommonPreference exMapPref, boolean force, - @NonNull final MapActivity activity, + @NonNull final MapActivity mapActivity, @Nullable final OnMapSelectedCallback callback) { - final MapActivityLayers layers = activity.getMapLayers(); + final WeakReference mapActivityRef = new WeakReference<>(mapActivity); if (!force && exMapPref.get() != null) { mapPref.set(exMapPref.get()); if (callback != null) { callback.onMapSelected(false); } - updateMapLayers(mapView, mapPref, layers); + updateMapLayers(mapView, mapPref, mapActivity.getMapLayers()); return; } - final OsmandSettings settings = app.getSettings(); + OsmandSettings settings = app.getSettings(); Map entriesMap = settings.getTileSourceEntries(); final ArrayList keys = new ArrayList<>(entriesMap.keySet()); - AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, getThemeRes(activity, app))); + AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(mapActivity, getThemeRes(mapActivity))); final String[] items = new String[entriesMap.size() + 1]; int i = 0; for (String it : entriesMap.values()) { @@ -211,13 +213,24 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { + MapActivity activity = mapActivityRef.get(); + if (activity == null || activity.isFinishing()) { + return; + } if (which == items.length - 1) { installMapLayers(activity, new ResultMatcher() { TileSourceTemplate template = null; int count = 0; + boolean cancel = false; @Override public boolean publish(TileSourceTemplate object) { + MapActivity mapActivity = mapActivityRef.get(); + if (mapActivity == null || mapActivity.isFinishing()) { + cancel = true; + return false; + } + OsmandMapTileView mapView = mapActivity.getMapView(); if (object == null) { if (count == 1) { mapPref.set(template.getName()); @@ -225,9 +238,9 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { if (callback != null) { callback.onMapSelected(false); } - updateMapLayers(mapView, mapPref, layers); + updateMapLayers(mapView, mapPref, mapActivity.getMapLayers()); } else { - selectMapOverlayLayer(mapView, mapPref, exMapPref, false, activity, null); + selectMapOverlayLayer(mapView, mapPref, exMapPref, false, mapActivity, null); } } else { count++; @@ -238,7 +251,7 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { @Override public boolean isCancelled() { - return false; + return cancel; } }); } else { @@ -247,7 +260,7 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { if (callback != null) { callback.onMapSelected(false); } - updateMapLayers(mapView, mapPref, layers); + updateMapLayers(mapActivity.getMapView(), mapPref, activity.getMapLayers()); } dialog.dismiss(); } @@ -266,43 +279,52 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { } @Override - public void registerLayerContextMenuActions(final OsmandMapTileView mapView, + public void registerLayerContextMenuActions(OsmandMapTileView mapView, ContextMenuAdapter adapter, - final MapActivity mapActivity) { + MapActivity mapActivity) { + final WeakReference mapActivityRef = new WeakReference<>(mapActivity); ContextMenuAdapter.ItemClickListener listener = new ContextMenuAdapter.OnRowItemClick() { @Override public boolean onRowItemClick(ArrayAdapter adapter, View view, int itemId, int position) { - int[] viewCoordinates = AndroidUtils.getCenterViewCoordinates(view); - if (itemId == R.string.layer_overlay) { - mapActivity.getDashboard().setDashboardVisibility(true, DashboardType.OVERLAY_MAP, viewCoordinates); - return false; - } else if (itemId == R.string.layer_underlay) { - mapActivity.getDashboard().setDashboardVisibility(true, DashboardType.UNDERLAY_MAP, viewCoordinates); - return false; + MapActivity mapActivity = mapActivityRef.get(); + if (mapActivity != null && !mapActivity.isFinishing()) { + int[] viewCoordinates = AndroidUtils.getCenterViewCoordinates(view); + if (itemId == R.string.layer_overlay) { + mapActivity.getDashboard().setDashboardVisibility(true, DashboardType.OVERLAY_MAP, viewCoordinates); + return false; + } else if (itemId == R.string.layer_underlay) { + mapActivity.getDashboard().setDashboardVisibility(true, DashboardType.UNDERLAY_MAP, viewCoordinates); + return false; + } } return true; } @Override public boolean onContextMenuClick(final ArrayAdapter adapter, int itemId, final int pos, boolean isChecked, int[] viewCoordinates) { - final OsmandSettings settings = mapActivity.getMyApplication().getSettings(); + MapActivity mapActivity = mapActivityRef.get(); + if (mapActivity == null || mapActivity.isFinishing()) { + return false; + } if (itemId == R.string.layer_overlay) { toggleUnderlayState(mapActivity, RasterMapType.OVERLAY, new OnMapSelectedCallback() { @Override public void onMapSelected(boolean canceled) { - ContextMenuItem item = adapter.getItem(pos); - - String overlayMapDescr = settings.MAP_OVERLAY.get(); - - boolean hasOverlayDescription = overlayMapDescr != null; - overlayMapDescr = hasOverlayDescription ? overlayMapDescr - : mapActivity.getString(R.string.shared_string_none); - - item.setDescription(overlayMapDescr); - item.setSelected(hasOverlayDescription); - item.setColorRes(hasOverlayDescription ? R.color.osmand_orange : ContextMenuItem.INVALID_ID); - adapter.notifyDataSetChanged(); + MapActivity mapActivity = mapActivityRef.get(); + if (mapActivity != null && !mapActivity.isFinishing()) { + ContextMenuItem item = adapter.getItem(pos); + if (item != null) { + String overlayMapDescr = mapActivity.getMyApplication().getSettings().MAP_OVERLAY.get(); + boolean hasOverlayDescription = overlayMapDescr != null; + overlayMapDescr = hasOverlayDescription ? overlayMapDescr + : mapActivity.getString(R.string.shared_string_none); + item.setDescription(overlayMapDescr); + item.setSelected(hasOverlayDescription); + item.setColorRes(hasOverlayDescription ? R.color.osmand_orange : ContextMenuItem.INVALID_ID); + adapter.notifyDataSetChanged(); + } + } } }); return false; @@ -311,24 +333,29 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { new OnMapSelectedCallback() { @Override public void onMapSelected(boolean canceled) { - ContextMenuItem item = adapter.getItem(pos); + MapActivity mapActivity = mapActivityRef.get(); + if (mapActivity != null && !mapActivity.isFinishing()) { + ContextMenuItem item = adapter.getItem(pos); + if (item != null) { + String underlayMapDescr = settings.MAP_UNDERLAY.get(); - String underlayMapDescr = settings.MAP_UNDERLAY.get(); + boolean hasUnderlayDescription = underlayMapDescr != null; + underlayMapDescr = hasUnderlayDescription + ? underlayMapDescr + : mapActivity.getString(R.string.shared_string_none); - boolean hasUnderlayDescription = underlayMapDescr != null; - underlayMapDescr = hasUnderlayDescription ? underlayMapDescr - : mapActivity.getString(R.string.shared_string_none); + item.setDescription(underlayMapDescr); + item.setSelected(hasUnderlayDescription); + item.setColorRes(hasUnderlayDescription ? R.color.osmand_orange : ContextMenuItem.INVALID_ID); - item.setDescription(underlayMapDescr); - item.setSelected(hasUnderlayDescription); - item.setColorRes(hasUnderlayDescription ? R.color.osmand_orange : ContextMenuItem.INVALID_ID); + adapter.notifyDataSetChanged(); - adapter.notifyDataSetChanged(); - - final CommonPreference hidePolygonsPref = - mapActivity.getMyApplication().getSettings().getCustomRenderBooleanProperty("noPolygons"); - hidePolygonsPref.set(hasUnderlayDescription); - RasterMapMenu.refreshMapComplete(mapActivity); + final CommonPreference hidePolygonsPref = + mapActivity.getMyApplication().getSettings().getCustomRenderBooleanProperty("noPolygons"); + hidePolygonsPref.set(hasUnderlayDescription); + RasterMapMenu.refreshMapComplete(mapActivity); + } + } } }); return false; @@ -381,18 +408,23 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { @Override - public void registerMapContextMenuActions(final MapActivity mapActivity, final double latitude, final double longitude, ContextMenuAdapter adapter, - Object selectedObj) { - final OsmandMapTileView mapView = mapActivity.getMapView(); - if (mapView.getMainLayer() instanceof MapTileLayer) { + public void registerMapContextMenuActions(MapActivity mapActivity, + final double latitude, final double longitude, + ContextMenuAdapter adapter, Object selectedObj) { + final WeakReference mapActivityRef = new WeakReference<>(mapActivity); + if (mapActivity.getMapView().getMainLayer() instanceof MapTileLayer) { ItemClickListener listener = new ContextMenuAdapter.ItemClickListener() { @Override public boolean onContextMenuClick(ArrayAdapter adapter, int resId, int pos, boolean isChecked, int[] viewCoordinates) { - if (resId == R.string.context_menu_item_update_map) { - mapActivity.getMapActions().reloadTile(mapView.getZoom(), latitude, longitude); - } else if (resId == R.string.shared_string_download_map) { - DownloadTilesDialog dlg = new DownloadTilesDialog(mapActivity, (OsmandApplication) mapActivity.getApplication(), mapView); - dlg.openDialog(); + MapActivity mapActivity = mapActivityRef.get(); + if (mapActivity != null && !mapActivity.isFinishing()) { + OsmandMapTileView mapView = mapActivity.getMapView(); + if (resId == R.string.context_menu_item_update_map) { + mapActivity.getMapActions().reloadTile(mapView.getZoom(), latitude, longitude); + } else if (resId == R.string.shared_string_download_map) { + DownloadTilesDialog dlg = new DownloadTilesDialog(mapActivity, (OsmandApplication) mapActivity.getApplication(), mapView); + dlg.openDialog(); + } } return true; } @@ -412,10 +444,10 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { } } - public static void installMapLayers(final Activity activity, final ResultMatcher result) { + public static void installMapLayers(Activity activity, final ResultMatcher result) { + final WeakReference activityRef = new WeakReference<>(activity); final OsmandApplication app = (OsmandApplication) activity.getApplication(); - final OsmandSettings settings = app.getSettings(); - final Map entriesMap = settings.getTileSourceEntries(); + OsmandSettings settings = app.getSettings(); if (!settings.isInternetConnectionAvailable(true)) { Toast.makeText(activity, R.string.internet_not_available, Toast.LENGTH_LONG).show(); return; @@ -427,27 +459,36 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { } protected void onPostExecute(final java.util.List downloaded) { + Activity activity = activityRef.get(); + if (activity == null || activity.isFinishing()) { + return; + } + OsmandApplication app = (OsmandApplication) activity.getApplication(); if (downloaded == null || downloaded.isEmpty()) { Toast.makeText(activity, R.string.shared_string_io_error, Toast.LENGTH_SHORT).show(); return; } - AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, getThemeRes(activity, app))); + AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, getThemeRes(activity))); String[] names = new String[downloaded.size()]; for (int i = 0; i < names.length; i++) { names[i] = downloaded.get(i).getName(); } final boolean[] selected = new boolean[downloaded.size()]; - boolean nightMode = isNightMode(activity, app); - int themeResId = getThemeRes(activity, app); + boolean nightMode = isNightMode(activity); + int themeResId = getThemeRes(activity); int selectedProfileColor = ContextCompat.getColor(app, app.getSettings().getApplicationMode().getIconColorInfo().getColor(nightMode)); DialogListItemAdapter dialogAdapter = DialogListItemAdapter.createMultiChoiceAdapter(names, nightMode, selected, app, selectedProfileColor, themeResId, new View.OnClickListener() { @Override public void onClick(View v) { - int which = (int) v.getTag(); - selected[which] = !selected[which]; - if (entriesMap.containsKey(downloaded.get(which).getName()) && selected[which]) { - Toast.makeText(activity, R.string.tile_source_already_installed, Toast.LENGTH_SHORT).show(); + Activity activity = activityRef.get(); + if (activity != null && !activity.isFinishing()) { + Map entriesMap = ((OsmandApplication)activity.getApplication()).getSettings().getTileSourceEntries(); + int which = (int) v.getTag(); + selected[which] = !selected[which]; + if (entriesMap.containsKey(downloaded.get(which).getName()) && selected[which]) { + Toast.makeText(activity, R.string.tile_source_already_installed, Toast.LENGTH_SHORT).show(); + } } } } @@ -458,22 +499,26 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { builder.setPositiveButton(R.string.shared_string_apply, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - List toInstall = new ArrayList<>(); - for (int i = 0; i < selected.length; i++) { - if (selected[i]) { - toInstall.add(downloaded.get(i)); - } - } - for (TileSourceTemplate ts : toInstall) { - if (settings.installTileSource(ts)) { - if (result != null) { - result.publish(ts); + Activity activity = activityRef.get(); + if (activity != null && !activity.isFinishing()) { + OsmandSettings settings = ((OsmandApplication) activity.getApplication()).getSettings(); + List toInstall = new ArrayList<>(); + for (int i = 0; i < selected.length; i++) { + if (selected[i]) { + toInstall.add(downloaded.get(i)); } } - } - // at the end publish null to show end of process - if (!toInstall.isEmpty() && result != null) { - result.publish(null); + for (TileSourceTemplate ts : toInstall) { + if (settings.installTileSource(ts)) { + if (result != null) { + result.publish(ts); + } + } + } + // at the end publish null to show end of process + if (!toInstall.isEmpty() && result != null) { + result.publish(null); + } } } }); @@ -483,19 +528,20 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - public static void defineNewEditLayer(final Activity activity, final ResultMatcher resultMatcher, final String editedLayerName) { - final OsmandApplication app = (OsmandApplication) activity.getApplication(); - final OsmandSettings settings = app.getSettings(); - final Map entriesMap = settings.getTileSourceEntries(true); + public static void defineNewEditLayer(Activity activity, final ResultMatcher resultMatcher, final String editedLayerName) { + final WeakReference activityRef = new WeakReference<>(activity); + OsmandApplication app = (OsmandApplication) activity.getApplication(); + OsmandSettings settings = app.getSettings(); + Map entriesMap = settings.getTileSourceEntries(true); final SQLiteTileSource[] sqLiteTileSource = new SQLiteTileSource[1]; - boolean nightMode = isNightMode(activity, app); + boolean nightMode = isNightMode(activity); final int dp8 = AndroidUtils.dpToPx(app, 8f); int textColorPrimary = ContextCompat.getColor(app, nightMode ? R.color.text_color_primary_dark : R.color.text_color_primary_light); TileSourceTemplate ts = new TileSourceTemplate("NewMapnik", "http://mapnik.osmand.net/{0}/{1}/{2}.png", "png", 17, 5, 256, 16, 32000); final TileSourceTemplate[] result = new TileSourceTemplate[]{ts}; - AlertDialog.Builder bld = new AlertDialog.Builder(new ContextThemeWrapper(activity, getThemeRes(activity, app))); - View view = UiUtilities.getInflater(activity, isNightMode(activity, app)).inflate(R.layout.editing_tile_source, null); + AlertDialog.Builder bld = new AlertDialog.Builder(new ContextThemeWrapper(activity, getThemeRes(activity))); + View view = UiUtilities.getInflater(activity, isNightMode(activity)).inflate(R.layout.editing_tile_source, null); final EditText name = (EditText) view.findViewById(R.id.Name); final Spinner existing = (Spinner) view.findViewById(R.id.TileSourceSpinner); final TextView existingHint = (TextView) view.findViewById(R.id.TileSourceHint); @@ -539,10 +585,8 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { template.setExpirationTimeMinutes(sqLiteTileSource[0].getExpirationTimeMinutes()); template.setEllipticYTile(sqLiteTileSource[0].isEllipticYTile()); } - if (template != null) { - result[0] = template.copy(); - updateTileSourceEditView(result[0], name, urlToLoad, minZoom, maxZoom, expire, elliptic); - } + result[0] = template.copy(); + updateTileSourceEditView(result[0], name, urlToLoad, minZoom, maxZoom, expire, elliptic); existingHint.setVisibility(View.GONE); existing.setVisibility(View.GONE); } @@ -551,13 +595,12 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - if (position > 0) { + Activity activity = activityRef.get(); + if (activity != null && !activity.isFinishing() && position > 0) { File f = ((OsmandApplication) activity.getApplication()).getAppPath(IndexConstants.TILES_INDEX_DIR + templates.get(position)); TileSourceTemplate template = TileSourceManager.createTileSourceTemplate(f); - if (template != null) { - result[0] = template.copy(); - updateTileSourceEditView(result[0], name, urlToLoad, minZoom, maxZoom, expire, elliptic); - } + result[0] = template.copy(); + updateTileSourceEditView(result[0], name, urlToLoad, minZoom, maxZoom, expire, elliptic); } } @@ -571,29 +614,33 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { @Override public void onClick(DialogInterface dialog, int which) { - TileSourceTemplate r = result[0]; - try { - r.setName(name.getText().toString()); - r.setExpirationTimeMinutes(expire.getText().length() == 0 ? -1 : - Integer.parseInt(expire.getText().toString())); - r.setMinZoom(Integer.parseInt(minZoom.getText().toString())); - r.setMaxZoom(Integer.parseInt(maxZoom.getText().toString())); - r.setEllipticYTile(elliptic.isChecked()); - r.setUrlToLoad(urlToLoad.getText().toString().equals("") ? null : urlToLoad.getText().toString().replace("{$x}", "{1}") - .replace("{$y}", "{2}").replace("{$z}", "{0}")); - if (sqLiteTileSource[0] != null) { - sqLiteTileSource[0].updateFromTileSourceTemplate(r); - } else { - if (r.getName().length() > 0) { - if (settings.installTileSource(r)) { - Toast.makeText(activity, activity.getString(R.string.edit_tilesource_successfully, r.getName()), - Toast.LENGTH_SHORT).show(); - resultMatcher.publish(r); + Activity activity = activityRef.get(); + if (activity != null && !activity.isFinishing()) { + OsmandSettings settings = ((OsmandApplication) activity.getApplication()).getSettings(); + TileSourceTemplate r = result[0]; + try { + r.setName(name.getText().toString()); + r.setExpirationTimeMinutes(expire.getText().length() == 0 ? -1 : + Integer.parseInt(expire.getText().toString())); + r.setMinZoom(Integer.parseInt(minZoom.getText().toString())); + r.setMaxZoom(Integer.parseInt(maxZoom.getText().toString())); + r.setEllipticYTile(elliptic.isChecked()); + r.setUrlToLoad(urlToLoad.getText().toString().equals("") ? null : urlToLoad.getText().toString().replace("{$x}", "{1}") + .replace("{$y}", "{2}").replace("{$z}", "{0}")); + if (sqLiteTileSource[0] != null) { + sqLiteTileSource[0].updateFromTileSourceTemplate(r); + } else { + if (r.getName().length() > 0) { + if (settings.installTileSource(r)) { + Toast.makeText(activity, activity.getString(R.string.edit_tilesource_successfully, r.getName()), + Toast.LENGTH_SHORT).show(); + resultMatcher.publish(r); + } } } + } catch (RuntimeException e) { + Toast.makeText(activity, e.getMessage(), Toast.LENGTH_SHORT).show(); } - } catch (RuntimeException e) { - Toast.makeText(activity, e.getMessage(), Toast.LENGTH_SHORT).show(); } } }); @@ -601,8 +648,8 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { bld.show(); } - private static void updateTileSourceEditView(TileSourceTemplate ts, EditText name, final EditText urlToLoad, final EditText minZoom, - final EditText maxZoom, EditText expire, final CheckBox elliptic) { + private static void updateTileSourceEditView(TileSourceTemplate ts, EditText name, EditText urlToLoad, EditText minZoom, + EditText maxZoom, EditText expire, CheckBox elliptic) { minZoom.setText(String.valueOf(ts.getMinimumZoomSupported())); maxZoom.setText(String.valueOf(ts.getMaximumZoomSupported())); name.setText(ts.getName()); @@ -626,7 +673,6 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { OsmandMapTileView mapView = mapActivity.getMapView(); CommonPreference mapTypePreference; CommonPreference exMapTypePreference; - OsmandSettings.CommonPreference mapTransparencyPreference; //boolean isMapSelected; MapTileLayer layer; @@ -663,15 +709,16 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { } } - private static boolean isNightMode(Activity activity, OsmandApplication app) { - if (activity == null || app == null) { + private static boolean isNightMode(Context context) { + if (context == null) { return false; } - return activity instanceof MapActivity ? app.getDaynightHelper().isNightModeForMapControls() : !app.getSettings().isLightContent(); + OsmandApplication app = (OsmandApplication) context.getApplicationContext(); + return context instanceof MapActivity ? app.getDaynightHelper().isNightModeForMapControls() : !app.getSettings().isLightContent(); } - private static int getThemeRes(Activity activity, OsmandApplication app) { - return isNightMode(activity, app) ? R.style.OsmandDarkTheme : R.style.OsmandLightTheme; + private static int getThemeRes(Context context) { + return isNightMode(context) ? R.style.OsmandDarkTheme : R.style.OsmandLightTheme; } public enum RasterMapType { From bd81e430b95d8e834ae3e0f9599f6ee8b5edc3db Mon Sep 17 00:00:00 2001 From: Victor Shcherb Date: Thu, 11 Jun 2020 18:52:30 +0200 Subject: [PATCH 2/6] Fix #5175 --- .../net/osmand/router/BinaryRoutePlanner.java | 7 +++ .../osmand/router/RoutePlannerFrontEnd.java | 63 +++++-------------- .../net/osmand/router/RoutingContext.java | 2 +- 3 files changed, 25 insertions(+), 47 deletions(-) diff --git a/OsmAnd-java/src/main/java/net/osmand/router/BinaryRoutePlanner.java b/OsmAnd-java/src/main/java/net/osmand/router/BinaryRoutePlanner.java index f57a4f1c3d..6bffd147a7 100644 --- a/OsmAnd-java/src/main/java/net/osmand/router/BinaryRoutePlanner.java +++ b/OsmAnd-java/src/main/java/net/osmand/router/BinaryRoutePlanner.java @@ -11,6 +11,7 @@ import java.util.PriorityQueue; import net.osmand.PlatformUtil; import net.osmand.binary.RouteDataObject; +import net.osmand.data.LatLon; import net.osmand.osm.MapRenderingTypes; import net.osmand.util.MapUtils; @@ -859,6 +860,12 @@ public class BinaryRoutePlanner { public int preciseX; public int preciseY; public List others; + + public LatLon getPreciseLatLon() { + return new LatLon(MapUtils.get31LatitudeY(preciseY), MapUtils.get31LongitudeX(preciseX)); + + } + } public static class RouteSegment { diff --git a/OsmAnd-java/src/main/java/net/osmand/router/RoutePlannerFrontEnd.java b/OsmAnd-java/src/main/java/net/osmand/router/RoutePlannerFrontEnd.java index 3df6b65125..e8f2fe3707 100644 --- a/OsmAnd-java/src/main/java/net/osmand/router/RoutePlannerFrontEnd.java +++ b/OsmAnd-java/src/main/java/net/osmand/router/RoutePlannerFrontEnd.java @@ -243,9 +243,7 @@ public class RoutePlannerFrontEnd { return null; } ctx.calculationProgress.nextIteration(); - List res = searchRoute(ctx, points, routeDirection); - // make start and end more precise - makeStartEndPointsPrecise(res, start, end, intermediates); + List res = searchRouteImpl(ctx, points, routeDirection); if (res != null) { new RouteResultPreparation().printResults(ctx, start, end, res); } @@ -256,33 +254,6 @@ public class RoutePlannerFrontEnd { if (res.size() > 0) { updateResult(res.get(0), start, true); updateResult(res.get(res.size() - 1), end, false); - if (intermediates != null) { - int k = 1; - for (int i = 0; i < intermediates.size(); i++) { - LatLon ll = intermediates.get(i); - int px = MapUtils.get31TileNumberX(ll.getLongitude()); - int py = MapUtils.get31TileNumberY(ll.getLatitude()); - for (; k < res.size(); k++) { - double currentsDist = projectDistance(res, k, px, py); - if (currentsDist < 500 * 500) { - for (int k1 = k + 1; k1 < res.size(); k1++) { - double c2 = projectDistance(res, k1, px, py); - if (c2 < currentsDist) { - k = k1; - currentsDist = c2; - } else if (k1 - k > 15) { - break; - } - } - updateResult(res.get(k), ll, false); - if (k < res.size() - 1) { - updateResult(res.get(k + 1), ll, true); - } - break; - } - } - } - } } } @@ -474,13 +445,18 @@ public class RoutePlannerFrontEnd { } - private List searchRoute(final RoutingContext ctx, List points, PrecalculatedRouteDirection routeDirection) + private List searchRouteImpl(final RoutingContext ctx, List points, PrecalculatedRouteDirection routeDirection) throws IOException, InterruptedException { if (points.size() <= 2) { + // simple case 2 points only if (!useSmartRouteRecalculation) { ctx.previouslyCalculatedRoute = null; } - return searchRoute(ctx, points.get(0), points.get(1), routeDirection); + pringGC(ctx, true); + List res = searchRouteInternalPrepare(ctx, points.get(0), points.get(1), routeDirection); + pringGC(ctx, false); + makeStartEndPointsPrecise(res, points.get(0).getPreciseLatLon(), points.get(1).getPreciseLatLon(), null); + return res; } ArrayList firstPartRecalculatedRoute = null; @@ -522,7 +498,7 @@ public class RoutePlannerFrontEnd { local.visitor = ctx.visitor; local.calculationProgress = ctx.calculationProgress; List res = searchRouteInternalPrepare(local, points.get(i), points.get(i + 1), routeDirection); - + makeStartEndPointsPrecise(res, points.get(i).getPreciseLatLon(), points.get(i + 1).getPreciseLatLon(), null); results.addAll(res); ctx.distinctLoadedTiles += local.distinctLoadedTiles; ctx.loadedTiles += local.loadedTiles; @@ -545,27 +521,22 @@ public class RoutePlannerFrontEnd { } - @SuppressWarnings("static-access") - private List searchRoute(final RoutingContext ctx, RouteSegmentPoint start, RouteSegmentPoint end, - PrecalculatedRouteDirection routeDirection) throws IOException, InterruptedException { - if (ctx.SHOW_GC_SIZE) { - long h1 = ctx.runGCUsedMemory(); + private void pringGC(final RoutingContext ctx, boolean before) { + if (RoutingContext.SHOW_GC_SIZE && before) { + long h1 = RoutingContext.runGCUsedMemory(); float mb = (1 << 20); log.warn("Used before routing " + h1 / mb + " actual"); - } - List result = searchRouteInternalPrepare(ctx, start, end, routeDirection); - if (RoutingContext.SHOW_GC_SIZE) { + } else if (RoutingContext.SHOW_GC_SIZE && !before) { int sz = ctx.global.size; log.warn("Subregion size " + ctx.subregionTiles.size() + " " + " tiles " + ctx.indexedSubregions.size()); - ctx.runGCUsedMemory(); - long h1 = ctx.runGCUsedMemory(); + RoutingContext.runGCUsedMemory(); + long h1 = RoutingContext.runGCUsedMemory(); ctx.unloadAllData(); - ctx.runGCUsedMemory(); - long h2 = ctx.runGCUsedMemory(); + RoutingContext.runGCUsedMemory(); + long h2 = RoutingContext.runGCUsedMemory(); float mb = (1 << 20); log.warn("Unload context : estimated " + sz / mb + " ?= " + (h1 - h2) / mb + " actual"); } - return result; } diff --git a/OsmAnd-java/src/main/java/net/osmand/router/RoutingContext.java b/OsmAnd-java/src/main/java/net/osmand/router/RoutingContext.java index 2e657a8c5c..2c44940dff 100644 --- a/OsmAnd-java/src/main/java/net/osmand/router/RoutingContext.java +++ b/OsmAnd-java/src/main/java/net/osmand/router/RoutingContext.java @@ -36,7 +36,7 @@ import net.osmand.router.RoutePlannerFrontEnd.RouteCalculationMode; public class RoutingContext { - public static final boolean SHOW_GC_SIZE = false; + public static boolean SHOW_GC_SIZE = false; private final static Log log = PlatformUtil.getLog(RoutingContext.class); From 45e192b62e98698bc7e52ab6319f3959c41ff3e2 Mon Sep 17 00:00:00 2001 From: max-klaus Date: Thu, 11 Jun 2020 20:19:19 +0300 Subject: [PATCH 3/6] Update material libtrary to beta01 --- OsmAnd/build.gradle | 2 +- OsmAnd/res/layout/fragment_terrain.xml | 2 +- OsmAnd/src/net/osmand/plus/UiUtilities.java | 69 ++++++++++++----- .../plus/srtmplugin/TerrainFragment.java | 75 +++++++------------ 4 files changed, 82 insertions(+), 66 deletions(-) diff --git a/OsmAnd/build.gradle b/OsmAnd/build.gradle index 6bebf5f67b..79c1027c84 100644 --- a/OsmAnd/build.gradle +++ b/OsmAnd/build.gradle @@ -524,7 +524,7 @@ dependencies { implementation 'androidx.gridlayout:gridlayout:1.0.0' implementation 'androidx.cardview:cardview:1.0.0' implementation 'androidx.appcompat:appcompat:1.1.0' - implementation 'com.google.android.material:material:1.2.0-alpha06' + implementation 'com.google.android.material:material:1.2.0-beta01' implementation 'androidx.browser:browser:1.0.0' implementation 'androidx.preference:preference:1.1.0' implementation fileTree(include: ['gnu-trove-osmand.jar', 'icu4j-49_1_patched.jar'], dir: 'libs') diff --git a/OsmAnd/res/layout/fragment_terrain.xml b/OsmAnd/res/layout/fragment_terrain.xml index c077d1a765..11fa1aa1f0 100644 --- a/OsmAnd/res/layout/fragment_terrain.xml +++ b/OsmAnd/res/layout/fragment_terrain.xml @@ -275,7 +275,7 @@ android:textSize="@dimen/default_list_text_size" tools:text="3" /> - listAdapter; + private Slider.OnChangeListener transparencySliderChangeListener = new Slider.OnChangeListener() { + @Override + public void onValueChange(@NonNull Slider slider, float value, boolean fromUser) { + if (fromUser) { + String transparencyStr = (int) value + "%"; + transparencyValueTv.setText(transparencyStr); + srtmPlugin.setTerrainTransparency((int) Math.ceil(value * 2.55), srtmPlugin.getTerrainMode()); + } + } + }; + + private RangeSlider.OnChangeListener zoomSliderChangeListener = new RangeSlider.OnChangeListener() { + @Override + public void onValueChange(@NonNull RangeSlider slider, float value, boolean fromUser) { + List values = slider.getValues(); + if (values.size() > 0) { + minZoomTv.setText(String.valueOf(values.get(0).intValue())); + maxZoomTv.setText(String.valueOf(values.get(1).intValue())); + srtmPlugin.setTerrainZoomValues(values.get(0).intValue(), values.get(1).intValue(), srtmPlugin.getTerrainMode()); + } + } + }; + @Override public void onCreate(@Nullable Bundle savedInstanceState) { app = requireMyApplication(); @@ -175,10 +199,8 @@ public class TerrainFragment extends BaseOsmAndFragment implements View.OnClickL UiUtilities.setupSlider(transparencySlider, nightMode, colorProfile); UiUtilities.setupSlider(zoomSlider, nightMode, colorProfile, true); - transparencySlider.addOnSliderTouchListener(this); - zoomSlider.addOnSliderTouchListener(this); - transparencySlider.addOnChangeListener(this); - zoomSlider.addOnChangeListener(this); + transparencySlider.addOnChangeListener(transparencySliderChangeListener); + zoomSlider.addOnChangeListener(zoomSliderChangeListener); transparencySlider.setValueTo(100); transparencySlider.setValueFrom(0); zoomSlider.setValueTo(TERRAIN_MAX_ZOOM); @@ -207,47 +229,6 @@ public class TerrainFragment extends BaseOsmAndFragment implements View.OnClickL } } - @Override - public void onStartTrackingTouch(@NonNull Slider slider) { - - } - - @Override - public void onStopTrackingTouch(@NonNull Slider slider) { - switch (slider.getId()) { - case R.id.transparency_slider: - double d = slider.getValue() * 2.55; - srtmPlugin.setTerrainTransparency((int) Math.ceil(d), srtmPlugin.getTerrainMode()); - break; - case R.id.zoom_slider: - List values = slider.getValues(); - if (values.size() > 0) { - srtmPlugin.setTerrainZoomValues(values.get(0).intValue(), values.get(1).intValue(), srtmPlugin.getTerrainMode()); - } - break; - } - updateLayers(); - } - - @Override - public void onValueChange(@NonNull Slider slider, float value, boolean fromUser) { - if (fromUser) { - switch (slider.getId()) { - case R.id.transparency_slider: - String transparency = (int) value + "%"; - transparencyValueTv.setText(transparency); - break; - case R.id.zoom_slider: - List values = slider.getValues(); - if (values.size() > 0) { - minZoomTv.setText(String.valueOf(values.get(0).intValue())); - maxZoomTv.setText(String.valueOf(values.get(1).intValue())); - } - break; - } - } - } - private void updateUiMode() { TerrainMode mode = srtmPlugin.getTerrainMode(); if (terrainEnabled) { From f07ae7b3e39a342c5099de7ee4c1f3ec4a41b537 Mon Sep 17 00:00:00 2001 From: max-klaus Date: Thu, 11 Jun 2020 20:32:52 +0300 Subject: [PATCH 4/6] Raster plugin small fixes --- .../rastermaps/OsmandRasterMapsPlugin.java | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java b/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java index 58af80e351..e120743e98 100644 --- a/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java +++ b/OsmAnd/src/net/osmand/plus/rastermaps/OsmandRasterMapsPlugin.java @@ -35,9 +35,6 @@ import net.osmand.plus.ContextMenuItem; 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.LayerTransparencySeekbarMode; import net.osmand.plus.R; import net.osmand.plus.SQLiteTileSource; import net.osmand.plus.UiUtilities; @@ -48,6 +45,9 @@ 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; @@ -184,11 +184,11 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { } } - public void selectMapOverlayLayer(@NonNull final OsmandMapTileView mapView, + public void selectMapOverlayLayer(@NonNull OsmandMapTileView mapView, @NonNull final CommonPreference mapPref, @NonNull final CommonPreference exMapPref, boolean force, - @NonNull final MapActivity mapActivity, + @NonNull MapActivity mapActivity, @Nullable final OnMapSelectedCallback callback) { final WeakReference mapActivityRef = new WeakReference<>(mapActivity); if (!force && exMapPref.get() != null) { @@ -213,12 +213,12 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - MapActivity activity = mapActivityRef.get(); - if (activity == null || activity.isFinishing()) { + MapActivity mapActivity = mapActivityRef.get(); + if (mapActivity == null || mapActivity.isFinishing()) { return; } if (which == items.length - 1) { - installMapLayers(activity, new ResultMatcher() { + installMapLayers(mapActivity, new ResultMatcher() { TileSourceTemplate template = null; int count = 0; boolean cancel = false; @@ -260,11 +260,10 @@ public class OsmandRasterMapsPlugin extends OsmandPlugin { if (callback != null) { callback.onMapSelected(false); } - updateMapLayers(mapActivity.getMapView(), mapPref, activity.getMapLayers()); + updateMapLayers(mapActivity.getMapView(), mapPref, mapActivity.getMapLayers()); } dialog.dismiss(); } - }) .setNegativeButton(R.string.shared_string_cancel, null) .setOnDismissListener(new DialogInterface.OnDismissListener() { From ca99280651f864bc05d98b9c901ee9089dbab03c Mon Sep 17 00:00:00 2001 From: max-klaus Date: Thu, 11 Jun 2020 20:47:06 +0300 Subject: [PATCH 5/6] Fix range slider --- OsmAnd/res/layout/zoom_levels_with_descr.xml | 2 +- .../mapsource/InputZoomLevelsBottomSheet.java | 15 +++++++-------- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/OsmAnd/res/layout/zoom_levels_with_descr.xml b/OsmAnd/res/layout/zoom_levels_with_descr.xml index 98e173140d..d3fcba0da2 100644 --- a/OsmAnd/res/layout/zoom_levels_with_descr.xml +++ b/OsmAnd/res/layout/zoom_levels_with_descr.xml @@ -65,7 +65,7 @@ android:textSize="@dimen/default_list_text_size" tools:text="3" /> - values = slider.getValues(); if (values.size() > 0) { minZoomValue.setText(String.valueOf(values.get(0).intValue())); @@ -114,14 +114,13 @@ public class InputZoomLevelsBottomSheet extends MenuBottomSheetDialogFragment { } } }); - slider.addOnSliderTouchListener(new Slider.OnSliderTouchListener() { + slider.addOnSliderTouchListener(new RangeSlider.OnSliderTouchListener() { @Override - public void onStartTrackingTouch(@NonNull Slider slider) { - + public void onStartTrackingTouch(@NonNull RangeSlider slider) { } @Override - public void onStopTrackingTouch(@NonNull Slider slider) { + public void onStopTrackingTouch(@NonNull RangeSlider slider) { List values = slider.getValues(); if (values.size() > 0) { minZoom = values.get(0).intValue(); From 2912163ca1e77f7d5ee91d6a24eabd1d0a646ca9 Mon Sep 17 00:00:00 2001 From: max-klaus Date: Fri, 12 Jun 2020 11:05:24 +0300 Subject: [PATCH 6/6] Fix terrain transparency slider response --- .../plus/srtmplugin/TerrainFragment.java | 68 ++++++++++++------- 1 file changed, 44 insertions(+), 24 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainFragment.java b/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainFragment.java index 8aa60d902e..9c905bf8e1 100644 --- a/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainFragment.java +++ b/OsmAnd/src/net/osmand/plus/srtmplugin/TerrainFragment.java @@ -52,6 +52,7 @@ import net.osmand.plus.widgets.style.CustomTypefaceSpan; import org.apache.commons.logging.Log; import java.io.IOException; +import java.lang.ref.WeakReference; import java.util.List; import static net.osmand.plus.download.DownloadActivityType.HILLSHADE_FILE; @@ -115,6 +116,7 @@ public class TerrainFragment extends BaseOsmAndFragment implements View.OnClickL String transparencyStr = (int) value + "%"; transparencyValueTv.setText(transparencyStr); srtmPlugin.setTerrainTransparency((int) Math.ceil(value * 2.55), srtmPlugin.getTerrainMode()); + refreshMap(); } } }; @@ -127,10 +129,20 @@ public class TerrainFragment extends BaseOsmAndFragment implements View.OnClickL minZoomTv.setText(String.valueOf(values.get(0).intValue())); maxZoomTv.setText(String.valueOf(values.get(1).intValue())); srtmPlugin.setTerrainZoomValues(values.get(0).intValue(), values.get(1).intValue(), srtmPlugin.getTerrainMode()); + refreshMap(); } } }; + @Nullable + private MapActivity getMapActivity() { + Activity activity = getActivity(); + if (activity instanceof MapActivity && !activity.isFinishing()) { + return (MapActivity) activity; + } + return null; + } + @Override public void onCreate(@Nullable Bundle savedInstanceState) { app = requireMyApplication(); @@ -365,13 +377,17 @@ public class TerrainFragment extends BaseOsmAndFragment implements View.OnClickL } } + private void refreshMap() { + MapActivity mapActivity = getMapActivity(); + if (mapActivity != null) { + mapActivity.getMapView().refreshMap(); + } + } + private void updateLayers() { - Activity activity = getActivity(); - if (activity instanceof MapActivity) { - srtmPlugin.updateLayers( - ((MapActivity) activity).getMapView(), - (MapActivity) activity - ); + MapActivity mapActivity = getMapActivity(); + if (mapActivity != null) { + srtmPlugin.updateLayers(mapActivity.getMapView(), mapActivity); } } @@ -381,10 +397,11 @@ public class TerrainFragment extends BaseOsmAndFragment implements View.OnClickL adapter.setProfileDependent(true); adapter.setNightMode(nightMode); - final Activity mapActivity = getActivity(); - if (!(mapActivity instanceof MapActivity)) { + MapActivity mapActivity = getMapActivity(); + if (mapActivity == null) { return; } + final WeakReference mapActivityRef = new WeakReference<>(mapActivity); final DownloadIndexesThread downloadThread = app.getDownloadThread(); if (!downloadThread.getIndexes().isDownloadedFromInternet) { @@ -425,22 +442,25 @@ public class TerrainFragment extends BaseOsmAndFragment implements View.OnClickL .setListener(new ContextMenuAdapter.ItemClickListener() { @Override public boolean onContextMenuClick(ArrayAdapter adapter, int itemId, int position, boolean isChecked, int[] viewCoordinates) { - ContextMenuItem item = adapter.getItem(position); - if (downloadThread.isDownloading(indexItem)) { - downloadThread.cancelDownload(indexItem); - if (item != null) { - item.setProgress(ContextMenuItem.INVALID_ID); - item.setLoading(false); - item.setSecondaryIcon(R.drawable.ic_action_import); - adapter.notifyDataSetChanged(); - } - } else { - new DownloadValidationManager(app).startDownload((MapActivity) mapActivity, indexItem); - if (item != null) { - item.setProgress(ContextMenuItem.INVALID_ID); - item.setLoading(true); - item.setSecondaryIcon(R.drawable.ic_action_remove_dark); - adapter.notifyDataSetChanged(); + MapActivity mapActivity = mapActivityRef.get(); + if (mapActivity != null && !mapActivity.isFinishing()) { + ContextMenuItem item = adapter.getItem(position); + if (downloadThread.isDownloading(indexItem)) { + downloadThread.cancelDownload(indexItem); + if (item != null) { + item.setProgress(ContextMenuItem.INVALID_ID); + item.setLoading(false); + item.setSecondaryIcon(R.drawable.ic_action_import); + adapter.notifyDataSetChanged(); + } + } else { + new DownloadValidationManager(app).startDownload(mapActivity, indexItem); + if (item != null) { + item.setProgress(ContextMenuItem.INVALID_ID); + item.setLoading(true); + item.setSecondaryIcon(R.drawable.ic_action_remove_dark); + adapter.notifyDataSetChanged(); + } } } return false;