From 1f8dbb7694dda48caf6c7607b3eb357279654014 Mon Sep 17 00:00:00 2001 From: simon Date: Thu, 3 Sep 2020 16:53:38 +0300 Subject: [PATCH] code cleanup --- .../java/net/osmand/data/RotatedTileBox.java | 51 ----- .../osmand/plus/activities/MapActivity.java | 85 ++------ .../plus/activities/ServerActivity.java | 5 +- .../src/net/osmand/plus/server/ApiRouter.java | 181 ++++-------------- .../plus/server/ServerSessionHandler.java | 8 +- .../plus/server/endpoints/TileEndpoint.java | 103 ++++++++++ .../osmand/plus/views/OsmandMapTileView.java | 19 -- 7 files changed, 157 insertions(+), 295 deletions(-) create mode 100644 OsmAnd/src/net/osmand/plus/server/endpoints/TileEndpoint.java diff --git a/OsmAnd-java/src/main/java/net/osmand/data/RotatedTileBox.java b/OsmAnd-java/src/main/java/net/osmand/data/RotatedTileBox.java index 2219a0a6d6..477f985e1a 100644 --- a/OsmAnd-java/src/main/java/net/osmand/data/RotatedTileBox.java +++ b/OsmAnd-java/src/main/java/net/osmand/data/RotatedTileBox.java @@ -71,57 +71,6 @@ public class RotatedTileBox { } } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - RotatedTileBox tileBox = (RotatedTileBox) o; - return this.compare(tileBox.lat, lat) && - this.compare(tileBox.lon, lon) && - this.compare(tileBox.rotate, rotate) && - this.compare(tileBox.density, density) && - zoom == tileBox.zoom && - this.compare(tileBox.mapDensity, mapDensity) && - this.compare(tileBox.zoomAnimation, zoomAnimation) && - this.compare(tileBox.zoomFloatPart, zoomFloatPart) && - cx == tileBox.cx && - cy == tileBox.cy && - pixWidth == tileBox.pixWidth && - pixHeight == tileBox.pixHeight && - this.compare(tileBox.zoomFactor, zoomFactor) && - this.compare(tileBox.rotateCos, rotateCos) && - this.compare(tileBox.rotateSin, rotateSin) && - this.compare(tileBox.oxTile, oxTile) && - this.compare(tileBox.oyTile, oyTile); - } - - private double E = 0.0001; - - private boolean compare(float lon, float lon1) { - return Math.abs(lon1-lon) < E; - } - - private boolean compare(double lon, double lon1) { - return Math.abs(lon1-lon) < E; - } - - @Override - public int hashCode() { - int result = 1 + (int)lat + - 3* (int)(lon*1/E) + - 5* (int)(rotate*1/E) + - 7* (int)(density*1/E) + - 11* zoom + - 13* (int)(mapDensity*1/E) + - 17* (int)(zoomAnimation*1/E) + - 19* (int)(zoomFloatPart*1/E) + - 23* cx + - 29* cy + - 31* pixWidth + - 37* pixHeight; - return result; - } - public void calculateDerivedFields() { zoomFactor = Math.pow(2, zoomAnimation + zoomFloatPart) * 256 * mapDensity; double rad = Math.toRadians(this.rotate); diff --git a/OsmAnd/src/net/osmand/plus/activities/MapActivity.java b/OsmAnd/src/net/osmand/plus/activities/MapActivity.java index f58acb8591..776e74c4cc 100644 --- a/OsmAnd/src/net/osmand/plus/activities/MapActivity.java +++ b/OsmAnd/src/net/osmand/plus/activities/MapActivity.java @@ -5,11 +5,7 @@ import android.app.Activity; import android.app.AlarmManager; import android.app.Dialog; import android.app.PendingIntent; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.IntentFilter; +import android.content.*; import android.content.pm.PackageManager; import android.media.AudioManager; import android.net.Uri; @@ -18,18 +14,10 @@ import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.util.DisplayMetrics; -import android.view.Gravity; -import android.view.KeyEvent; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.ViewStub; -import android.view.Window; -import android.view.WindowManager; +import android.view.*; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; - import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; @@ -44,41 +32,22 @@ import androidx.fragment.app.FragmentManager.BackStackEntry; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import androidx.preference.PreferenceFragmentCompat.OnPreferenceStartFragmentCallback; - -import net.osmand.AndroidUtils; +import net.osmand.*; import net.osmand.GPXUtilities.GPXFile; -import net.osmand.Location; -import net.osmand.PlatformUtil; -import net.osmand.SecondSplashScreenFragment; -import net.osmand.StateChangedListener; -import net.osmand.ValueHolder; import net.osmand.access.MapAccessibilityActions; import net.osmand.aidl.AidlMapPointWrapper; import net.osmand.aidl.OsmandAidlApi.AMapPointUpdateListener; import net.osmand.core.android.AtlasMapRendererView; -import net.osmand.data.LatLon; -import net.osmand.data.PointDescription; -import net.osmand.data.QuadPoint; -import net.osmand.data.QuadRect; -import net.osmand.data.RotatedTileBox; +import net.osmand.data.*; import net.osmand.map.MapTileDownloader.DownloadRequest; import net.osmand.map.MapTileDownloader.IMapDownloaderCallback; -import net.osmand.plus.AppInitializer; +import net.osmand.plus.*; import net.osmand.plus.AppInitializer.AppInitializeListener; import net.osmand.plus.AppInitializer.InitEvents; import net.osmand.plus.GpxSelectionHelper.GpxDisplayItem; -import net.osmand.plus.HuaweiDrmHelper; import net.osmand.plus.MapMarkersHelper.MapMarker; import net.osmand.plus.MapMarkersHelper.MapMarkerChangedListener; -import net.osmand.plus.OnDismissDialogFragmentListener; -import net.osmand.plus.OsmAndConstants; -import net.osmand.plus.OsmAndLocationSimulation; -import net.osmand.plus.OsmandApplication; -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.Version; import net.osmand.plus.activities.search.SearchActivity; import net.osmand.plus.base.BaseOsmAndFragment; import net.osmand.plus.base.ContextMenuFragment; @@ -87,24 +56,14 @@ import net.osmand.plus.base.MapViewTrackingUtilities; import net.osmand.plus.chooseplan.OsmLiveCancelledDialog; import net.osmand.plus.dashboard.DashboardOnMap; import net.osmand.plus.dashboard.DashboardOnMap.DashboardType; -import net.osmand.plus.dialogs.CrashBottomSheetDialogFragment; -import net.osmand.plus.dialogs.ImportGpxBottomSheetDialogFragment; -import net.osmand.plus.dialogs.RateUsBottomSheetDialogFragment; -import net.osmand.plus.dialogs.SendAnalyticsBottomSheetDialogFragment; -import net.osmand.plus.dialogs.WhatsNewDialogFragment; -import net.osmand.plus.dialogs.XMasDialogFragment; +import net.osmand.plus.dialogs.*; import net.osmand.plus.download.DownloadActivity; import net.osmand.plus.download.DownloadIndexesThread.DownloadEvents; import net.osmand.plus.download.ui.DataStoragePlaceDialogFragment; 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.helpers.IntentHelper; -import net.osmand.plus.helpers.LockHelper; +import net.osmand.plus.helpers.*; import net.osmand.plus.helpers.LockHelper.LockUIAdapter; -import net.osmand.plus.helpers.ScrollHelper; import net.osmand.plus.helpers.ScrollHelper.OnScrollEventListener; import net.osmand.plus.mapcontextmenu.AdditionalActionsBottomSheetDialogFragment; import net.osmand.plus.mapcontextmenu.MapContextMenu; @@ -118,11 +77,7 @@ import net.osmand.plus.mapcontextmenu.other.DestinationReachedMenu; import net.osmand.plus.mapcontextmenu.other.TrackDetailsMenu; import net.osmand.plus.mapmarkers.MapMarkersDialogFragment; import net.osmand.plus.mapmarkers.PlanRouteFragment; -import net.osmand.plus.measurementtool.GpxApproximationFragment; -import net.osmand.plus.measurementtool.GpxData; -import net.osmand.plus.measurementtool.MeasurementEditingContext; -import net.osmand.plus.measurementtool.MeasurementToolFragment; -import net.osmand.plus.measurementtool.SnapTrackWarningBottomSheet; +import net.osmand.plus.measurementtool.*; import net.osmand.plus.quickaction.QuickActionListFragment; import net.osmand.plus.render.RendererRegistry; import net.osmand.plus.resources.ResourceManager; @@ -136,25 +91,14 @@ import net.osmand.plus.routing.TransportRoutingHelper.TransportRouteCalculationP import net.osmand.plus.search.QuickSearchDialogFragment; import net.osmand.plus.search.QuickSearchDialogFragment.QuickSearchTab; import net.osmand.plus.search.QuickSearchDialogFragment.QuickSearchType; -import net.osmand.plus.server.ApiRouter; 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.*; import net.osmand.plus.settings.fragments.BaseSettingsFragment.SettingsScreenType; -import net.osmand.plus.settings.fragments.ConfigureMenuItemsFragment; -import net.osmand.plus.settings.fragments.ConfigureProfileFragment; -import net.osmand.plus.settings.fragments.DataStorageFragment; -import net.osmand.plus.settings.fragments.ImportCompleteFragment; -import net.osmand.plus.settings.fragments.ImportSettingsFragment; -import net.osmand.plus.settings.fragments.ProfileAppearanceFragment; import net.osmand.plus.track.TrackAppearanceFragment; import net.osmand.plus.views.AddGpxPointBottomSheetHelper.NewGpxPoint; -import net.osmand.plus.views.AnimateDraggingMapThread; -import net.osmand.plus.views.OsmAndMapLayersView; -import net.osmand.plus.views.OsmAndMapSurfaceView; -import net.osmand.plus.views.OsmandMapLayer; -import net.osmand.plus.views.OsmandMapTileView; +import net.osmand.plus.views.*; import net.osmand.plus.views.OsmandMapTileView.OnDrawMapListener; import net.osmand.plus.views.corenative.NativeCoreContext; import net.osmand.plus.views.layers.MapControlsLayer; @@ -165,16 +109,10 @@ import net.osmand.plus.views.mapwidgets.MapInfoWidgetsFactory.TopToolbarControll import net.osmand.render.RenderingRulesStorage; import net.osmand.router.GeneralRouter; import net.osmand.util.Algorithms; - import org.apache.commons.logging.Log; import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; +import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -310,7 +248,6 @@ public class MapActivity extends OsmandActionBarActivity implements DownloadEven int h = dm.heightPixels - statusBarHeight; mapView = new OsmandMapTileView(this, w, h); - ApiRouter.mapActivity = this; if (app.getAppInitializer().checkAppVersionChanged() && WhatsNewDialogFragment.SHOW) { SecondSplashScreenFragment.SHOW = false; WhatsNewDialogFragment.SHOW = false; diff --git a/OsmAnd/src/net/osmand/plus/activities/ServerActivity.java b/OsmAnd/src/net/osmand/plus/activities/ServerActivity.java index eda412c599..6630cb20c0 100644 --- a/OsmAnd/src/net/osmand/plus/activities/ServerActivity.java +++ b/OsmAnd/src/net/osmand/plus/activities/ServerActivity.java @@ -73,7 +73,7 @@ public class ServerActivity extends AppCompatActivity { OsmAndHttpServer.HOSTNAME = getDeviceAddress(); try { server = new OsmAndHttpServer(); - server.setAndroidApplication((OsmandApplication)this.getApplication()); + server.setAndroidApplication((OsmandApplication) this.getApplication()); initialized = true; updateTextView("Server started at: http://" + getDeviceAddress() + ":" + OsmAndHttpServer.PORT); } catch (IOException e) { @@ -91,11 +91,12 @@ public class ServerActivity extends AppCompatActivity { } private void deInitServer() { - if (server != null){ + if (server != null) { server.closeAllConnections(); server.stop(); } initialized = false; + finish(); } @Override diff --git a/OsmAnd/src/net/osmand/plus/server/ApiRouter.java b/OsmAnd/src/net/osmand/plus/server/ApiRouter.java index a8e5ddc86d..cdb056771c 100644 --- a/OsmAnd/src/net/osmand/plus/server/ApiRouter.java +++ b/OsmAnd/src/net/osmand/plus/server/ApiRouter.java @@ -1,128 +1,45 @@ package net.osmand.plus.server; -import android.graphics.Bitmap; import android.util.Log; -import android.util.Pair; import android.webkit.MimeTypeMap; -import com.google.gson.Gson; import fi.iki.elonen.NanoHTTPD; -import net.osmand.data.FavouritePoint; -import net.osmand.data.RotatedTileBox; +import net.osmand.PlatformUtil; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.activities.MapActivity; -import net.osmand.plus.views.OsmandMapLayer; -import net.osmand.plus.views.OsmandMapTileView; +import net.osmand.plus.server.endpoints.TileEndpoint; -import java.io.*; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.nio.charset.Charset; -import java.util.*; -import java.util.concurrent.*; +import java.util.HashMap; +import java.util.Map; import static fi.iki.elonen.NanoHTTPD.newFixedLengthResponse; -public class ApiRouter implements OsmandMapTileView.IMapImageDrawListener { - private OsmandApplication androidContext; - - public OsmandApplication getAndroidContext() { - return androidContext; - } - +public class ApiRouter { + private OsmandApplication application; private final String FOLDER_NAME = "server"; - private Gson gson = new Gson(); - private Map endpoints = new HashMap<>(); - //change to weakreference - public static MapActivity mapActivity; + private final Map endpoints = new HashMap<>(); + private static final org.apache.commons.logging.Log LOG = PlatformUtil.getLog(ApiRouter.class); public ApiRouter() { initRoutes(); } + public OsmandApplication getApplication() { + return application; + } + + final TileEndpoint tileEndpoint = new TileEndpoint(application); + private void initRoutes() { - ApiEndpoint favorites = new ApiEndpoint(); - favorites.uri = "/favorites"; - favorites.apiCall = new ApiEndpoint.ApiCall() { - @Override - public NanoHTTPD.Response call(NanoHTTPD.IHTTPSession session) { - return newFixedLengthResponse(getFavoritesJson()); - } - }; - endpoints.put(favorites.uri, favorites); - - final ApiEndpoint tile = new ApiEndpoint(); - tile.uri = "/tile"; - tile.apiCall = new ApiEndpoint.ApiCall() { - @Override - public NanoHTTPD.Response call(NanoHTTPD.IHTTPSession session) { - try { - return tileApiCall(session); - } catch (Exception e) { - e.printStackTrace(); - } - return ErrorResponses.response500; - } - }; - endpoints.put(tile.uri, tile); + endpoints.put(tileEndpoint.uri, tileEndpoint); } - ExecutorService executor = Executors.newFixedThreadPool(3); - - Map hashMap = new HashMap<>(); - Map map = Collections.synchronizedMap(hashMap); - - private synchronized NanoHTTPD.Response tileApiCall(NanoHTTPD.IHTTPSession session) { - int zoom = 0; - double lat = 0;//50.901430; - double lon = 0;//34.801775; - try { - String fullUri = session.getUri().replace("/tile/", ""); - Scanner s = new Scanner(fullUri).useDelimiter("/"); - zoom = s.nextInt(); - lat = s.nextDouble(); - lon = s.nextDouble(); - } catch (Exception e) { - e.printStackTrace(); - return ErrorResponses.response500; - } - mapActivity.getMapView().setMapImageDrawListener(this); - Future> future; - final RotatedTileBox rotatedTileBox = new RotatedTileBox.RotatedTileBoxBuilder() - .setLocation(lat, lon) - .setZoom(zoom) - .setPixelDimensions(512, 512, 0.5f, 0.5f).build(); - future = executor.submit(new Callable>() { - @Override - public Pair call() throws Exception { - Bitmap bmp; - while ((bmp = map.get(rotatedTileBox)) == null) { - Thread.sleep(1000); - } - return Pair.create(rotatedTileBox, bmp); - } - }); - mapActivity.getMapView().setCurrentRotatedTileBox(rotatedTileBox); - try { - Pair pair = future.get(); - Bitmap bitmap = pair.second;// mapActivity.getMapView().currentCanvas; - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); - byte[] byteArray = stream.toByteArray(); - ByteArrayInputStream str = new ByteArrayInputStream(byteArray); - return newFixedLengthResponse( - NanoHTTPD.Response.Status.OK, - "image/png", - str, - str.available()); - } catch (ExecutionException e) { - e.printStackTrace(); - return ErrorResponses.response500; - } catch (InterruptedException e) { - e.printStackTrace(); - return ErrorResponses.response500; - } - } - - public void setAndroidContext(OsmandApplication androidContext) { - this.androidContext = androidContext; + public void setApplication(OsmandApplication application) { + this.application = application; + tileEndpoint.setApplication(application); } public NanoHTTPD.Response route(NanoHTTPD.IHTTPSession session) { @@ -144,9 +61,9 @@ public class ApiRouter implements OsmandMapTileView.IMapImageDrawListener { private NanoHTTPD.Response routeApi(NanoHTTPD.IHTTPSession session) { String uri = session.getUri(); - //TODO rewrite - if (uri.contains("tile")) { - return endpoints.get("/tile").apiCall.call(session); + int pathEnd = uri.indexOf("/", 1); + if (pathEnd != -1) { + uri = uri.substring(0, pathEnd); } ApiEndpoint endpoint = endpoints.get(uri); if (endpoint != null) { @@ -157,8 +74,11 @@ public class ApiRouter implements OsmandMapTileView.IMapImageDrawListener { private boolean isApiUrl(String uri) { for (String endpoint : endpoints.keySet()) { - //TODO rewrite contains - if (endpoint.equals(uri) || uri.contains("tile")) return true; + int stringLength = endpoint.length(); + if (uri.startsWith(endpoint) && + (uri.length() == endpoint.length() || uri.charAt(stringLength) == '/')) { + return true; + } } return false; } @@ -175,11 +95,11 @@ public class ApiRouter implements OsmandMapTileView.IMapImageDrawListener { } public NanoHTTPD.Response getStatic(String uri) { - InputStream is = null; + InputStream is; String mimeType = parseMimeType(uri); - if (androidContext != null) { + if (application != null) { try { - is = androidContext.getAssets().open(FOLDER_NAME + uri); + is = application.getAssets().open(FOLDER_NAME + uri); if (is.available() == 0) { return ErrorResponses.response404; } @@ -208,7 +128,7 @@ public class ApiRouter implements OsmandMapTileView.IMapImageDrawListener { private String readHTMLFromFile(String filename) { StringBuilder sb = new StringBuilder(); try { - InputStream is = androidContext.getAssets().open(FOLDER_NAME + filename); + InputStream is = application.getAssets().open(FOLDER_NAME + filename); BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String str; @@ -217,7 +137,7 @@ public class ApiRouter implements OsmandMapTileView.IMapImageDrawListener { } br.close(); } catch (IOException e) { - e.printStackTrace(); + LOG.error("IOException", e); return null; } return sb.toString(); @@ -225,41 +145,18 @@ public class ApiRouter implements OsmandMapTileView.IMapImageDrawListener { public String getHtmlPage(String name) { String responseText = ""; - if (androidContext != null) { + if (application != null) { responseText = readHTMLFromFile(name); } - if (responseText == null) { - return null; - } return responseText; } - private String getFavoritesJson() { - List points = androidContext.getFavorites().getFavouritePoints(); - StringBuilder text = new StringBuilder(); - for (FavouritePoint p : points) { - String json = jsonFromFavorite(p); - text.append(json); - text.append(","); - } - return "[" + text.substring(0, text.length() - 1) + "]"; - } - - private String jsonFromFavorite(FavouritePoint favouritePoint) { - return gson.toJson(favouritePoint); - } - - @Override - public void onDraw(RotatedTileBox viewport, Bitmap bmp) { - this.map.put(viewport, bmp); - } - - static class ErrorResponses { - static NanoHTTPD.Response response404 = + public static class ErrorResponses { + public static NanoHTTPD.Response response404 = newFixedLengthResponse(NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "404 Not Found"); - static NanoHTTPD.Response response500 = + public static NanoHTTPD.Response response500 = newFixedLengthResponse(NanoHTTPD.Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "500 Internal Server Error"); } diff --git a/OsmAnd/src/net/osmand/plus/server/ServerSessionHandler.java b/OsmAnd/src/net/osmand/plus/server/ServerSessionHandler.java index 13d54fcab8..ba4b8c6419 100644 --- a/OsmAnd/src/net/osmand/plus/server/ServerSessionHandler.java +++ b/OsmAnd/src/net/osmand/plus/server/ServerSessionHandler.java @@ -3,7 +3,6 @@ package net.osmand.plus.server; import net.osmand.plus.OsmandApplication; import fi.iki.elonen.NanoHTTPD; -import net.osmand.plus.activities.MapActivity; public class ServerSessionHandler { private OsmandApplication androidApplication; @@ -16,12 +15,7 @@ public class ServerSessionHandler { public void setAndroidApplication(OsmandApplication androidApplication) { this.androidApplication = androidApplication; - router.setAndroidContext(androidApplication); - } - - public void setMapActivity(MapActivity activity) { - //todo - router.mapActivity = activity; + router.setApplication(androidApplication); } public NanoHTTPD.Response handle(NanoHTTPD.IHTTPSession session) { diff --git a/OsmAnd/src/net/osmand/plus/server/endpoints/TileEndpoint.java b/OsmAnd/src/net/osmand/plus/server/endpoints/TileEndpoint.java new file mode 100644 index 0000000000..9ffd2f2752 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/server/endpoints/TileEndpoint.java @@ -0,0 +1,103 @@ +package net.osmand.plus.server.endpoints; + +import android.graphics.Bitmap; +import android.util.Pair; +import fi.iki.elonen.NanoHTTPD; +import net.osmand.PlatformUtil; +import net.osmand.data.RotatedTileBox; +import net.osmand.plus.OsmandApplication; +import net.osmand.plus.render.MapRenderRepositories; +import net.osmand.plus.resources.AsyncLoadingThread; +import net.osmand.plus.server.ApiEndpoint; +import net.osmand.plus.server.ApiRouter; +import org.apache.commons.logging.Log; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; +import java.util.concurrent.*; + +import static fi.iki.elonen.NanoHTTPD.newFixedLengthResponse; + +public class TileEndpoint extends ApiEndpoint { + ExecutorService executor = Executors.newFixedThreadPool(3); + Map hashMap = new HashMap<>(); + Map map = Collections.synchronizedMap(hashMap); + OsmandApplication application; + private static final Log LOG = PlatformUtil.getLog(TileEndpoint.class); + + public TileEndpoint(OsmandApplication application) { + this.application = application; + this.uri = "/tile"; + this.apiCall = new ApiEndpoint.ApiCall() { + @Override + public NanoHTTPD.Response call(NanoHTTPD.IHTTPSession session) { + try { + return tileApiCall(session); + } catch (Exception e) { + LOG.error("Exception", e); + } + return ApiRouter.ErrorResponses.response500; + } + }; + } + + private synchronized NanoHTTPD.Response tileApiCall(NanoHTTPD.IHTTPSession session) { + int zoom; + double lat; + double lon; + String fullUri = session.getUri().replace("/tile/", ""); + Scanner s = new Scanner(fullUri).useDelimiter("/"); + zoom = s.nextInt(); + lat = s.nextDouble(); + lon = s.nextDouble(); + Future> future; + final RotatedTileBox rotatedTileBox = new RotatedTileBox.RotatedTileBoxBuilder() + .setLocation(lat, lon) + .setZoom(zoom) + .setPixelDimensions(512, 512, 0.5f, 0.5f).build(); + final MapRenderRepositories renderer = application.getResourceManager().getRenderer(); + future = executor.submit(new Callable>() { + @Override + public Pair call() throws Exception { + Bitmap bmp; + while ((bmp = map.get(rotatedTileBox)) == null) { + Thread.sleep(500); + } + return Pair.create(rotatedTileBox, bmp); + } + }); + application.getResourceManager().updateRendererMap(rotatedTileBox, new AsyncLoadingThread.OnMapLoadedListener() { + @Override + public void onMapLoaded(boolean interrupted) { + map.put(rotatedTileBox, renderer.getBitmap()); + } + }); + try { + Pair pair = future.get(); + Bitmap bitmap = pair.second; + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); + byte[] byteArray = stream.toByteArray(); + ByteArrayInputStream str = new ByteArrayInputStream(byteArray); + return newFixedLengthResponse( + NanoHTTPD.Response.Status.OK, + "image/png", + str, + str.available()); + } catch (ExecutionException e) { + LOG.error("Execution exception", e); + return ApiRouter.ErrorResponses.response500; + } catch (InterruptedException e) { + LOG.error("Interrupted exception", e); + return ApiRouter.ErrorResponses.response500; + } + } + + public void setApplication(OsmandApplication application) { + this.application = application; + } +} diff --git a/OsmAnd/src/net/osmand/plus/views/OsmandMapTileView.java b/OsmAnd/src/net/osmand/plus/views/OsmandMapTileView.java index 4ecc092cd7..62e05fd82c 100644 --- a/OsmAnd/src/net/osmand/plus/views/OsmandMapTileView.java +++ b/OsmAnd/src/net/osmand/plus/views/OsmandMapTileView.java @@ -77,7 +77,6 @@ public class OsmandMapTileView implements IMapDownloaderCallback { protected OsmandSettings settings = null; private CanvasColors canvasColors = null; private Boolean nightMode = null; - public Bitmap currentCanvas = null; private class CanvasColors { int colorDay = MAP_DEFAULT_COLOR; @@ -121,10 +120,6 @@ public class OsmandMapTileView implements IMapDownloaderCallback { public void onDrawOverMap(); } - public interface IMapImageDrawListener { - public void onDraw(RotatedTileBox viewport,Bitmap bmp); - } - protected static final Log LOG = PlatformUtil.getLog(OsmandMapTileView.class); @@ -148,8 +143,6 @@ public class OsmandMapTileView implements IMapDownloaderCallback { private OnTrackBallListener trackBallDelegate; - private IMapImageDrawListener iMapImageDrawListener; - private AccessibilityActionsProvider accessibilityActions; private List layers = new ArrayList<>(); @@ -372,14 +365,6 @@ public class OsmandMapTileView implements IMapDownloaderCallback { return wasZoomInMultiTouch; } - public IMapImageDrawListener getMapImageDrawListener() { - return iMapImageDrawListener; - } - - public void setMapImageDrawListener(IMapImageDrawListener iMapImageDrawListener) { - this.iMapImageDrawListener = iMapImageDrawListener; - } - public boolean mapGestureAllowed(OsmandMapLayer.MapGestureType type) { for (OsmandMapLayer layer : layers) { if (!layer.isMapGestureAllowed(type)) { @@ -588,7 +573,6 @@ public class OsmandMapTileView implements IMapDownloaderCallback { if (!bufferBitmap.isRecycled()) { RectF rct = new RectF(x1, y1, x2, y2); canvas.drawBitmap(bufferBitmap, null, rct, paintImg); - currentCanvas = bufferBitmap; } canvas.rotate(-rot, currentViewport.getCenterPixelX(), currentViewport.getCenterPixelY()); } @@ -629,9 +613,6 @@ public class OsmandMapTileView implements IMapDownloaderCallback { } long end = SystemClock.elapsedRealtime(); additional.calculateFPS(start, end); - if (iMapImageDrawListener != null){ - iMapImageDrawListener.onDraw(tileBox,bufferBitmap); - } } public void refreshMapInternal(DrawSettings drawSettings) {