Search in sources :

Example 1 with DownloadRequest

use of net.osmand.map.MapTileDownloader.DownloadRequest in project OsmAnd-tools by osmandapp.

the class MapPanel method getImageFor.

public Image getImageFor(int x, int y, int zoom, boolean loadIfNeeded) throws IOException {
    if (map == null) {
        return null;
    }
    String file = getFileForImage(x, y, zoom, map.getTileFormat());
    if (cache.get(file) == null) {
        File en = new File(tilesLocation, file);
        if (cache.size() > 100) {
            ArrayList<String> list = new ArrayList<String>(cache.keySet());
            for (int i = 0; i < list.size(); i += 2) {
                Image remove = cache.remove(list.get(i));
                remove.flush();
            }
            if (log.isInfoEnabled()) {
                log.info(// $NON-NLS-1$ //$NON-NLS-2$
                "Before running gc on map tiles. Total Memory : " + (Runtime.getRuntime().totalMemory() >> 20) + " Mb. Used memory : " + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + // $NON-NLS-1$
                " Mb");
            }
            System.gc();
            if (log.isInfoEnabled()) {
                log.info(// $NON-NLS-1$ //$NON-NLS-2$
                "After running gc on map tiles. Total Memory : " + (Runtime.getRuntime().totalMemory() >> 20) + " Mb. Used memory : " + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + // $NON-NLS-1$
                " Mb");
            }
        }
        if (!downloader.isFileCurrentlyDownloaded(en)) {
            if (en.exists()) {
                // long time = System.currentTimeMillis();
                try {
                    cache.put(file, ImageIO.read(en));
                // if (log.isDebugEnabled()) {
                // log.debug("Loaded file : " + file + " " + (System.currentTimeMillis() - time) + " ms");
                // }
                } catch (IIOException e) {
                    // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    log.error("Eror reading png " + x + " " + y + " zoom : " + zoom, e);
                }
            }
            if (loadIfNeeded && cache.get(file) == null) {
                String urlToLoad = map.getUrlToLoad(x, y, zoom);
                if (urlToLoad != null) {
                    downloader.requestToDownload(new DownloadRequest(urlToLoad, en, x, y, zoom));
                }
            }
        }
    }
    return cache.get(file);
}
Also used : ArrayList(java.util.ArrayList) DownloadRequest(net.osmand.map.MapTileDownloader.DownloadRequest) IIOException(javax.imageio.IIOException) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) File(java.io.File) Point(java.awt.Point)

Example 2 with DownloadRequest

use of net.osmand.map.MapTileDownloader.DownloadRequest in project OsmAnd-tools by osmandapp.

the class TileBundleDownloadDialog method downloadTiles.

public void downloadTiles() {
    setVisible(false);
    // $NON-NLS-1$
    final ProgressDialog progressDialog = new ProgressDialog(this, Messages.getString("TileBundleDownloadDialog.DOWNLOADING.TILES"));
    int numberTiles = 0;
    final int startZoom = (Integer) startSpinner.getValue();
    final int endZoom = (Integer) endSpinner.getValue();
    for (int zoom = startZoom; zoom <= endZoom; zoom++) {
        int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1());
        int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2());
        int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1());
        int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2());
        numberTiles += (x2 - x1 + 1) * (y2 - y1 + 1);
    }
    final int number = numberTiles;
    final MapTileDownloader instance = MapTileDownloader.getInstance(MapCreatorVersion.APP_MAP_CREATOR_VERSION);
    progressDialog.setRunnable(new Runnable() {

        @Override
        public void run() {
            // $NON-NLS-1$
            progressDialog.startTask(Messages.getString("TileBundleDownloadDialog.LOADING"), number);
            for (int zoom = startZoom; zoom <= endZoom; zoom++) {
                int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1());
                int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2());
                int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1());
                int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2());
                for (int x = x1; x <= x2; x++) {
                    for (int y = y1; y <= y2; y++) {
                        String file = getFileForImage(x, y, zoom, map.getTileFormat());
                        if (new File(tilesLocation, file).exists()) {
                            progressDialog.progress(1);
                        } else {
                            DownloadRequest req = new DownloadRequest(map.getUrlToLoad(x, y, zoom), new File(tilesLocation, file), x, y, zoom);
                            instance.requestToDownload(req);
                        }
                    }
                }
                while (instance.isSomethingBeingDownloaded()) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new IllegalArgumentException(e);
                    }
                }
            }
        }
    });
    ArrayList<IMapDownloaderCallback> previousCallbacks = new ArrayList<IMapDownloaderCallback>(instance.getDownloaderCallbacks());
    instance.getDownloaderCallbacks().clear();
    instance.addDownloaderCallback(new IMapDownloaderCallback() {

        @Override
        public void tileDownloaded(DownloadRequest request) {
            // TODO request could be null if bundle loading?
            progressDialog.progress(1);
        }
    });
    try {
        progressDialog.run();
        instance.refuseAllPreviousRequests();
    } catch (InvocationTargetException e) {
        ExceptionHandler.handle(e.getCause());
    } catch (InterruptedException e) {
        ExceptionHandler.handle(e);
    } finally {
        instance.getDownloaderCallbacks().clear();
        instance.getDownloaderCallbacks().addAll(previousCallbacks);
    }
}
Also used : IMapDownloaderCallback(net.osmand.map.MapTileDownloader.IMapDownloaderCallback) ArrayList(java.util.ArrayList) DownloadRequest(net.osmand.map.MapTileDownloader.DownloadRequest) InvocationTargetException(java.lang.reflect.InvocationTargetException) MapTileDownloader(net.osmand.map.MapTileDownloader) File(java.io.File)

Example 3 with DownloadRequest

use of net.osmand.map.MapTileDownloader.DownloadRequest in project Osmand by osmandapp.

the class MapActivity method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    setRequestedOrientation(AndroidUiHelper.getScreenOrientation(this));
    long tm = System.currentTimeMillis();
    app = getMyApplication();
    settings = app.getSettings();
    app.applyTheme(this);
    supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
    boolean portraitMode = AndroidUiHelper.isOrientationPortrait(this);
    boolean largeDevice = AndroidUiHelper.isXLargeDevice(this);
    landscapeLayout = !portraitMode && !largeDevice;
    mapContextMenu.setMapActivity(this);
    super.onCreate(savedInstanceState);
    // Full screen is not used here
    // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.main);
    if (Build.VERSION.SDK_INT >= 21) {
        enterToFullScreen();
        // Navigation Drawer:
        AndroidUtils.addStatusBarPadding21v(this, findViewById(R.id.menuItems));
    }
    int statusBarHeight = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        statusBarHeight = getResources().getDimensionPixelSize(resourceId);
    }
    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    int w = dm.widthPixels;
    int h = dm.heightPixels - statusBarHeight;
    mapView = new OsmandMapTileView(this, w, h);
    if (app.getAppInitializer().checkAppVersionChanged() && WhatsNewDialogFragment.SHOW) {
        SecondSplashScreenFragment.SHOW = false;
        WhatsNewDialogFragment.SHOW = false;
        new WhatsNewDialogFragment().show(getSupportFragmentManager(), null);
    }
    mapActions = new MapActivityActions(this);
    mapLayers = new MapActivityLayers(this);
    if (mapViewTrackingUtilities == null) {
        mapViewTrackingUtilities = new MapViewTrackingUtilities(app);
    }
    dashboardOnMap.createDashboardView();
    checkAppInitialization();
    parseLaunchIntentLocation();
    mapView.setTrackBallDelegate(new OsmandMapTileView.OnTrackBallListener() {

        @Override
        public boolean onTrackBallEvent(MotionEvent e) {
            showAndHideMapPosition();
            return MapActivity.this.onTrackballEvent(e);
        }
    });
    mapView.setAccessibilityActions(new MapAccessibilityActions(this));
    mapViewTrackingUtilities.setMapView(mapView);
    // to not let it gc
    downloaderCallback = new IMapDownloaderCallback() {

        @Override
        public void tileDownloaded(DownloadRequest request) {
            if (request != null && !request.error && request.fileToSave != null) {
                ResourceManager mgr = app.getResourceManager();
                mgr.tileDownloaded(request);
            }
            if (request == null || !request.error) {
                mapView.tileDownloaded(request);
            }
        }
    };
    app.getResourceManager().getMapTileDownloader().addDownloaderCallback(downloaderCallback);
    createProgressBarForRouting();
    mapLayers.createLayers(mapView);
    updateStatusBarColor();
    // it tries to continue the last route
    if (settings.FOLLOW_THE_ROUTE.get() && !app.getRoutingHelper().isRouteCalculated() && !app.getRoutingHelper().isRouteBeingCalculated()) {
        FailSafeFuntions.restoreRoutingMode(this);
    } else if (!app.getRoutingHelper().isRoutePlanningMode() && !settings.FOLLOW_THE_ROUTE.get() && app.getTargetPointsHelper().getAllPoints().size() > 0) {
        app.getRoutingHelper().clearCurrentRoute(null, new ArrayList<LatLon>());
        app.getTargetPointsHelper().removeAllWayPoints(false, false);
    }
    if (!settings.isLastKnownMapLocation()) {
        // show first time when application ran
        net.osmand.Location location = app.getLocationProvider().getFirstTimeRunDefaultLocation();
        mapViewTrackingUtilities.setMapLinkedToLocation(true);
        if (location != null) {
            mapView.setLatLon(location.getLatitude(), location.getLongitude());
            mapView.setIntZoom(14);
        }
    }
    addDialogProvider(mapActions);
    OsmandPlugin.onMapActivityCreate(this);
    importHelper = new ImportHelper(this, getMyApplication(), getMapView());
    wakeLockHelper = new WakeLockHelper(getMyApplication());
    if (System.currentTimeMillis() - tm > 50) {
        System.err.println("OnCreate for MapActivity took " + (System.currentTimeMillis() - tm) + " ms");
    }
    mapView.refreshMap(true);
    mapActions.updateDrawerMenu();
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
    screenOffReceiver = new ScreenOffReceiver();
    registerReceiver(screenOffReceiver, filter);
    app.getAidlApi().onCreateMapActivity(this);
    mIsDestroyed = false;
}
Also used : IntentFilter(android.content.IntentFilter) IMapDownloaderCallback(net.osmand.map.MapTileDownloader.IMapDownloaderCallback) MapViewTrackingUtilities(net.osmand.plus.base.MapViewTrackingUtilities) ArrayList(java.util.ArrayList) DownloadRequest(net.osmand.map.MapTileDownloader.DownloadRequest) WhatsNewDialogFragment(net.osmand.plus.dialogs.WhatsNewDialogFragment) ResourceManager(net.osmand.plus.resources.ResourceManager) DisplayMetrics(android.util.DisplayMetrics) TargetPoint(net.osmand.plus.TargetPointsHelper.TargetPoint) QuadPoint(net.osmand.data.QuadPoint) NewGpxPoint(net.osmand.plus.views.AddGpxPointBottomSheetHelper.NewGpxPoint) MapAccessibilityActions(net.osmand.access.MapAccessibilityActions) MotionEvent(android.view.MotionEvent) OsmandMapTileView(net.osmand.plus.views.OsmandMapTileView) WakeLockHelper(net.osmand.plus.helpers.WakeLockHelper) ImportHelper(net.osmand.plus.helpers.ImportHelper) Location(net.osmand.Location)

Example 4 with DownloadRequest

use of net.osmand.map.MapTileDownloader.DownloadRequest in project Osmand by osmandapp.

the class DownloadTilesDialog method run.

public void run(final int zoom, final int progress, final QuadRect latlonRect, final ITileSource map) {
    cancel = false;
    int numberTiles = 0;
    for (int z = zoom; z <= progress + zoom; z++) {
        int x1 = (int) MapUtils.getTileNumberX(z, latlonRect.left);
        int x2 = (int) MapUtils.getTileNumberX(z, latlonRect.right);
        int y1 = (int) MapUtils.getTileNumberY(z, latlonRect.top);
        int y2 = (int) MapUtils.getTileNumberY(z, latlonRect.bottom);
        numberTiles += (x2 - x1 + 1) * (y2 - y1 + 1);
    }
    final ProgressDialog progressDlg = new ProgressDialog(ctx);
    progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDlg.setMessage(ctx.getString(R.string.shared_string_downloading) + ctx.getString(R.string.shared_string_ellipsis));
    progressDlg.setCancelable(true);
    progressDlg.setMax(numberTiles);
    progressDlg.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            cancel = true;
        }
    });
    final MapTileDownloader instance = MapTileDownloader.getInstance(Version.getFullVersion(app));
    final List<IMapDownloaderCallback> previousCallbacks = instance.getDownloaderCallbacks();
    instance.clearCallbacks();
    callback = new IMapDownloaderCallback() {

        @Override
        public void tileDownloaded(DownloadRequest request) {
            if (request != null) {
                progressDlg.setProgress(progressDlg.getProgress() + 1);
            }
        }
    };
    instance.addDownloaderCallback(callback);
    Runnable r = new Runnable() {

        @Override
        public void run() {
            int requests = 0;
            int limitRequests = 50;
            try {
                ResourceManager rm = app.getResourceManager();
                for (int z = zoom; z <= zoom + progress && !cancel; z++) {
                    int x1 = (int) MapUtils.getTileNumberX(z, latlonRect.left);
                    int x2 = (int) MapUtils.getTileNumberX(z, latlonRect.right);
                    int y1 = (int) MapUtils.getTileNumberY(z, latlonRect.top);
                    int y2 = (int) MapUtils.getTileNumberY(z, latlonRect.bottom);
                    for (int x = x1; x <= x2 && !cancel; x++) {
                        for (int y = y1; y <= y2 && !cancel; y++) {
                            String tileId = rm.calculateTileId(map, x, y, z);
                            if (rm.tileExistOnFileSystem(tileId, map, x, y, z)) {
                                progressDlg.setProgress(progressDlg.getProgress() + 1);
                            } else {
                                rm.hasTileForMapSync(tileId, map, x, y, z, true);
                                requests++;
                            }
                            if (!cancel) {
                                if (requests >= limitRequests) {
                                    requests = 0;
                                    while (instance.isSomethingBeingDownloaded()) {
                                        try {
                                            Thread.sleep(500);
                                        } catch (InterruptedException e) {
                                            throw new IllegalArgumentException(e);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (cancel) {
                    instance.refuseAllPreviousRequests();
                } else {
                    while (instance.isSomethingBeingDownloaded()) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }
                }
                mapView.refreshMap();
                callback = null;
            } catch (Exception e) {
                // $NON-NLS-1$
                log.error("Exception while downloading tiles ", e);
                instance.refuseAllPreviousRequests();
            } finally {
                instance.clearCallbacks();
                for (IMapDownloaderCallback cbck : previousCallbacks) {
                    instance.addDownloaderCallback(cbck);
                }
                app.getResourceManager().reloadTilesFromFS();
            }
            progressDlg.dismiss();
        }
    };
    // $NON-NLS-1$
    new Thread(r, "Downloading tiles").start();
    progressDlg.show();
}
Also used : IMapDownloaderCallback(net.osmand.map.MapTileDownloader.IMapDownloaderCallback) DialogInterface(android.content.DialogInterface) DownloadRequest(net.osmand.map.MapTileDownloader.DownloadRequest) ResourceManager(net.osmand.plus.resources.ResourceManager) ProgressDialog(android.app.ProgressDialog) MapTileDownloader(net.osmand.map.MapTileDownloader)

Aggregations

DownloadRequest (net.osmand.map.MapTileDownloader.DownloadRequest)4 ArrayList (java.util.ArrayList)3 IMapDownloaderCallback (net.osmand.map.MapTileDownloader.IMapDownloaderCallback)3 File (java.io.File)2 MapTileDownloader (net.osmand.map.MapTileDownloader)2 ResourceManager (net.osmand.plus.resources.ResourceManager)2 ProgressDialog (android.app.ProgressDialog)1 DialogInterface (android.content.DialogInterface)1 IntentFilter (android.content.IntentFilter)1 DisplayMetrics (android.util.DisplayMetrics)1 MotionEvent (android.view.MotionEvent)1 Image (java.awt.Image)1 Point (java.awt.Point)1 BufferedImage (java.awt.image.BufferedImage)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 IIOException (javax.imageio.IIOException)1 Location (net.osmand.Location)1 MapAccessibilityActions (net.osmand.access.MapAccessibilityActions)1 QuadPoint (net.osmand.data.QuadPoint)1 TargetPoint (net.osmand.plus.TargetPointsHelper.TargetPoint)1