001// License: GPL. For details, see Readme.txt file.
002package org.openstreetmap.gui.jmapviewer;
003
004import java.io.File;
005import java.io.IOException;
006import org.openstreetmap.gui.jmapviewer.interfaces.TileJob;
007import org.openstreetmap.gui.jmapviewer.interfaces.TileLoaderListener;
008import org.openstreetmap.gui.jmapviewer.interfaces.TileSource;
009
010/**
011 * Reworked version of the OsmFileCacheTileLoader.
012 *
013 * When class OsmFileCacheTileLoader is no longer needed, it can be integrated
014 * here and removed.
015 */
016public class TMSFileCacheTileLoader extends OsmFileCacheTileLoader {
017
018    public TMSFileCacheTileLoader(TileLoaderListener map, File cacheDir) throws IOException {
019        super(map, cacheDir);
020    }
021
022    @Override
023    public TileJob createTileLoaderJob(final Tile tile) {
024        return new TMSFileLoadJob(tile);
025    }
026
027    protected class TMSFileLoadJob extends FileLoadJob {
028
029        public TMSFileLoadJob(Tile tile) {
030            super(tile);
031        }
032
033        @Override
034        protected File getTileFile() {
035            return getDataFile(tile.getSource().getTileType());
036        }
037
038        @Override
039        protected File getTagsFile() {
040            return getDataFile(TAGS_FILE_EXT);
041        }
042
043        protected File getDataFile(String ext) {
044            int nDigits = (int) Math.ceil(Math.log10(1 << tile.getZoom()));
045            String x = String.format("%0" + nDigits + "d", tile.getXtile());
046            String y = String.format("%0" + nDigits + "d", tile.getYtile());
047            File path = new File(tileCacheDir, "z" + tile.getZoom());
048            for (int i=0; i<nDigits; i++) {
049                String component = "x" + x.substring(i, i+1) + "y" + y.substring(i, i+1);
050                if (i == nDigits -1 ) {
051                    component += "." + ext;
052                }
053                path = new File(path, component);
054            }
055            return path;
056        }
057    }
058
059    @Override
060    protected File getSourceCacheDir(TileSource source) {
061        File dir = sourceCacheDirMap.get(source);
062        if (dir == null) {
063            String id = source.getId();
064            if (id != null) {
065                dir = new File(cacheDirBase, id);
066            } else {
067                dir = new File(cacheDirBase, source.getName().replaceAll("[\\\\/:*?\"<>|]", "_"));
068            }
069            if (!dir.exists()) {
070                dir.mkdirs();
071            }
072        }
073        return dir;
074    }
075
076}