-
Notifications
You must be signed in to change notification settings - Fork 0
/
AbstractTileSourceLayer.java
2014 lines (1806 loc) · 78 KB
/
AbstractTileSourceLayer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.gui.layer;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Shape;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.Timer;
import org.openstreetmap.gui.jmapviewer.AttributionSupport;
import org.openstreetmap.gui.jmapviewer.MemoryTileCache;
import org.openstreetmap.gui.jmapviewer.OsmTileLoader;
import org.openstreetmap.gui.jmapviewer.Tile;
import org.openstreetmap.gui.jmapviewer.TileRange;
import org.openstreetmap.gui.jmapviewer.TileXY;
import org.openstreetmap.gui.jmapviewer.interfaces.CachedTileLoader;
import org.openstreetmap.gui.jmapviewer.interfaces.ICoordinate;
import org.openstreetmap.gui.jmapviewer.interfaces.IProjected;
import org.openstreetmap.gui.jmapviewer.interfaces.TemplatedTileSource;
import org.openstreetmap.gui.jmapviewer.interfaces.TileCache;
import org.openstreetmap.gui.jmapviewer.interfaces.TileLoader;
import org.openstreetmap.gui.jmapviewer.interfaces.TileLoaderListener;
import org.openstreetmap.gui.jmapviewer.interfaces.TileSource;
import org.openstreetmap.gui.jmapviewer.tilesources.AbstractTMSTileSource;
import org.openstreetmap.josm.actions.ExpertToggleAction;
import org.openstreetmap.josm.actions.ImageryAdjustAction;
import org.openstreetmap.josm.actions.RenameLayerAction;
import org.openstreetmap.josm.actions.SaveActionBase;
import org.openstreetmap.josm.data.Bounds;
import org.openstreetmap.josm.data.ProjectionBounds;
import org.openstreetmap.josm.data.coor.EastNorth;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.data.imagery.CoordinateConversion;
import org.openstreetmap.josm.data.imagery.ImageryInfo;
import org.openstreetmap.josm.data.imagery.OffsetBookmark;
import org.openstreetmap.josm.data.imagery.TMSCachedTileLoader;
import org.openstreetmap.josm.data.imagery.TileLoaderFactory;
import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
import org.openstreetmap.josm.data.preferences.IntegerProperty;
import org.openstreetmap.josm.data.projection.Projection;
import org.openstreetmap.josm.data.projection.ProjectionRegistry;
import org.openstreetmap.josm.data.projection.Projections;
import org.openstreetmap.josm.gui.ExtendedDialog;
import org.openstreetmap.josm.gui.MainApplication;
import org.openstreetmap.josm.gui.MapView;
import org.openstreetmap.josm.gui.NavigatableComponent;
import org.openstreetmap.josm.gui.NavigatableComponent.ZoomChangeListener;
import org.openstreetmap.josm.gui.Notification;
import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
import org.openstreetmap.josm.gui.io.importexport.WMSLayerImporter;
import org.openstreetmap.josm.gui.layer.imagery.AutoLoadTilesAction;
import org.openstreetmap.josm.gui.layer.imagery.AutoZoomAction;
import org.openstreetmap.josm.gui.layer.imagery.DecreaseZoomAction;
import org.openstreetmap.josm.gui.layer.imagery.FlushTileCacheAction;
import org.openstreetmap.josm.gui.layer.imagery.ImageryFilterSettings.FilterChangeListener;
import org.openstreetmap.josm.gui.layer.imagery.IncreaseZoomAction;
import org.openstreetmap.josm.gui.layer.imagery.LoadAllTilesAction;
import org.openstreetmap.josm.gui.layer.imagery.LoadErroneousTilesAction;
import org.openstreetmap.josm.gui.layer.imagery.ReprojectionTile;
import org.openstreetmap.josm.gui.layer.imagery.ShowErrorsAction;
import org.openstreetmap.josm.gui.layer.imagery.TileAnchor;
import org.openstreetmap.josm.gui.layer.imagery.TileCoordinateConverter;
import org.openstreetmap.josm.gui.layer.imagery.TilePosition;
import org.openstreetmap.josm.gui.layer.imagery.TileSourceDisplaySettings;
import org.openstreetmap.josm.gui.layer.imagery.TileSourceDisplaySettings.DisplaySettingsChangeEvent;
import org.openstreetmap.josm.gui.layer.imagery.TileSourceDisplaySettings.DisplaySettingsChangeListener;
import org.openstreetmap.josm.gui.layer.imagery.ZoomToBestAction;
import org.openstreetmap.josm.gui.layer.imagery.ZoomToNativeLevelAction;
import org.openstreetmap.josm.gui.progress.ProgressMonitor;
import org.openstreetmap.josm.gui.util.GuiHelper;
import org.openstreetmap.josm.tools.GBC;
import org.openstreetmap.josm.tools.HttpClient;
import org.openstreetmap.josm.tools.Logging;
import org.openstreetmap.josm.tools.MemoryManager;
import org.openstreetmap.josm.tools.MemoryManager.MemoryHandle;
import org.openstreetmap.josm.tools.MemoryManager.NotEnoughMemoryException;
import org.openstreetmap.josm.tools.PlatformManager;
import org.openstreetmap.josm.tools.Utils;
import org.openstreetmap.josm.tools.bugreport.BugReport;
/**
* Base abstract class that supports displaying images provided by TileSource. It might be TMS source, WMS or WMTS
* It implements all standard functions of tilesource based layers: autozoom, tile reloads, layer saving, loading,etc.
*
* @author Upliner
* @author Wiktor Niesiobędzki
* @param <T> Tile Source class used for this layer
* @since 3715
* @since 8526 (copied from TMSLayer)
*/
public abstract class AbstractTileSourceLayer<T extends AbstractTMSTileSource> extends ImageryLayer
implements ImageObserver, TileLoaderListener, ZoomChangeListener, FilterChangeListener, DisplaySettingsChangeListener {
private static final String PREFERENCE_PREFIX = "imagery.generic";
static { // Registers all setting properties
new TileSourceDisplaySettings();
}
/** maximum zoom level supported */
public static final int MAX_ZOOM = 30;
/** minimum zoom level supported */
public static final int MIN_ZOOM = 2;
private static final Font InfoFont = new Font("sansserif", Font.BOLD, 13);
/** additional layer menu actions */
private static List<MenuAddition> menuAdditions = new LinkedList<>();
/** minimum zoom level to show to user */
public static final IntegerProperty PROP_MIN_ZOOM_LVL = new IntegerProperty(PREFERENCE_PREFIX + ".min_zoom_lvl", 2);
/** maximum zoom level to show to user */
public static final IntegerProperty PROP_MAX_ZOOM_LVL = new IntegerProperty(PREFERENCE_PREFIX + ".max_zoom_lvl", 20);
//public static final BooleanProperty PROP_DRAW_DEBUG = new BooleanProperty(PREFERENCE_PREFIX + ".draw_debug", false);
/** Zoomlevel at which tiles is currently downloaded. Initial zoom lvl is set to bestZoom */
private int currentZoomLevel;
private final AttributionSupport attribution = new AttributionSupport();
/**
* Offset between calculated zoom level and zoom level used to download and show tiles. Negative values will result in
* lower resolution of imagery useful in "retina" displays, positive values will result in higher resolution
*/
public static final IntegerProperty ZOOM_OFFSET = new IntegerProperty(PREFERENCE_PREFIX + ".zoom_offset",
PlatformManager.getPlatform().isHighDpiDisplay() ? 2 : 0);
/*
* use MemoryTileCache instead of tileLoader JCS cache, as tileLoader caches only content (byte[] of image)
* and MemoryTileCache caches whole Tile. This gives huge performance improvement when a lot of tiles are visible
* in MapView (for example - when limiting min zoom in imagery)
*
* Use per-layer tileCache instance, as the more layers there are, the more tiles needs to be cached
*/
protected TileCache tileCache; // initialized together with tileSource
protected T tileSource;
protected TileLoader tileLoader;
/** A timer that is used to delay invalidation events if required. */
private final Timer invalidateLaterTimer = new Timer(100, e -> this.invalidate());
private final MouseAdapter adapter = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (!isVisible()) return;
if (e.getButton() == MouseEvent.BUTTON3) {
Component component = e.getComponent();
if (component.isShowing()) {
new TileSourceLayerPopup(e.getX(), e.getY()).show(component, e.getX(), e.getY());
}
} else if (e.getButton() == MouseEvent.BUTTON1) {
attribution.handleAttribution(e.getPoint(), true);
}
}
};
private final TileSourceDisplaySettings displaySettings = createDisplaySettings();
private final ImageryAdjustAction adjustAction = new ImageryAdjustAction(this);
// prepared to be moved to the painter
protected TileCoordinateConverter coordinateConverter;
private final long minimumTileExpire;
/**
* Creates Tile Source based Imagery Layer based on Imagery Info
* @param info imagery info
*/
public AbstractTileSourceLayer(ImageryInfo info) {
super(info);
setBackgroundLayer(true);
this.setVisible(true);
getFilterSettings().addFilterChangeListener(this);
getDisplaySettings().addSettingsChangeListener(this);
this.minimumTileExpire = info.getMinimumTileExpire();
}
/**
* This method creates the {@link TileSourceDisplaySettings} object. Subclasses may implement it to e.g. change the prefix.
* @return The object.
* @since 10568
*/
protected TileSourceDisplaySettings createDisplaySettings() {
return new TileSourceDisplaySettings();
}
/**
* Gets the {@link TileSourceDisplaySettings} instance associated with this tile source.
* @return The tile source display settings
* @since 10568
*/
public TileSourceDisplaySettings getDisplaySettings() {
return displaySettings;
}
@Override
public void filterChanged() {
invalidate();
}
protected abstract TileLoaderFactory getTileLoaderFactory();
/**
* Get projections this imagery layer supports natively.
*
* For example projection of tiles that are downloaded from a server. Layer
* may support even more projections (by reprojecting the tiles), but with a
* certain loss in image quality and performance.
* @return projections this imagery layer supports natively; null if layer is projection agnostic.
*/
public abstract Collection<String> getNativeProjections();
/**
* Creates and returns a new {@link TileSource} instance depending on {@link #info} specified in the constructor.
*
* @return TileSource for specified ImageryInfo
* @throws IllegalArgumentException when Imagery is not supported by layer
*/
protected abstract T getTileSource();
protected Map<String, String> getHeaders(T tileSource) {
if (tileSource instanceof TemplatedTileSource) {
return ((TemplatedTileSource) tileSource).getHeaders();
}
return null;
}
protected void initTileSource(T tileSource) {
coordinateConverter = new TileCoordinateConverter(MainApplication.getMap().mapView, tileSource, getDisplaySettings());
attribution.initialize(tileSource);
currentZoomLevel = getBestZoom();
Map<String, String> headers = getHeaders(tileSource);
tileLoader = getTileLoaderFactory().makeTileLoader(this, headers, minimumTileExpire);
try {
if ("file".equalsIgnoreCase(new URL(tileSource.getBaseUrl()).getProtocol())) {
tileLoader = new OsmTileLoader(this);
}
} catch (MalformedURLException e) {
// ignore, assume that this is not a file
Logging.log(Logging.LEVEL_DEBUG, e);
}
if (tileLoader == null)
tileLoader = new OsmTileLoader(this, headers);
tileCache = new MemoryTileCache(estimateTileCacheSize());
}
@Override
public synchronized void tileLoadingFinished(Tile tile, boolean success) {
if (tile.hasError()) {
success = false;
tile.setImage(null);
}
invalidateLater();
Logging.debug("tileLoadingFinished() tile: {0} success: {1}", tile, success);
}
/**
* Clears the tile cache.
*/
public void clearTileCache() {
if (tileLoader instanceof CachedTileLoader) {
((CachedTileLoader) tileLoader).clearCache(tileSource);
}
tileCache.clear();
}
@Override
public Object getInfoComponent() {
JPanel panel = (JPanel) super.getInfoComponent();
List<List<String>> content = new ArrayList<>();
Collection<String> nativeProjections = getNativeProjections();
if (nativeProjections != null) {
content.add(Arrays.asList(tr("Native projections"), String.join(", ", getNativeProjections())));
}
EastNorth offset = getDisplaySettings().getDisplacement();
if (offset.distanceSq(0, 0) > 1e-10) {
content.add(Arrays.asList(tr("Offset"), offset.east() + ";" + offset.north()));
}
if (coordinateConverter.requiresReprojection()) {
content.add(Arrays.asList(tr("Tile download projection"), tileSource.getServerCRS()));
content.add(Arrays.asList(tr("Tile display projection"), ProjectionRegistry.getProjection().toCode()));
}
content.add(Arrays.asList(tr("Current zoom"), Integer.toString(currentZoomLevel)));
for (List<String> entry: content) {
panel.add(new JLabel(entry.get(0) + ':'), GBC.std());
panel.add(GBC.glue(5, 0), GBC.std());
panel.add(createTextField(entry.get(1)), GBC.eol().fill(GBC.HORIZONTAL));
}
return panel;
}
@Override
protected Action getAdjustAction() {
return adjustAction;
}
/**
* Returns average number of screen pixels per tile pixel for current mapview
* @param zoom zoom level
* @return average number of screen pixels per tile pixel
*/
public double getScaleFactor(int zoom) {
if (coordinateConverter != null) {
return coordinateConverter.getScaleFactor(zoom);
} else {
return 1;
}
}
/**
* Returns best zoom level.
* @return best zoom level
*/
public int getBestZoom() {
double factor = getScaleFactor(1); // check the ratio between area of tilesize at zoom 1 to current view
double result = Math.log(factor)/Math.log(2)/2;
/*
* Math.log(factor)/Math.log(2) - gives log base 2 of factor
* We divide result by 2, as factor contains ratio between areas. We could do Math.sqrt before log, or just divide log by 2
*
* ZOOM_OFFSET controls, whether we work with overzoomed or underzoomed tiles. Positive ZOOM_OFFSET
* is for working with underzoomed tiles (higher quality when working with aerial imagery), negative ZOOM_OFFSET
* is for working with overzoomed tiles (big, pixelated), which is good when working with high-dpi screens and/or
* maps as a imagery layer
*/
int intResult = (int) Math.round(result + 1 + ZOOM_OFFSET.get() / 1.9);
int minZoom = getMinZoomLvl();
int maxZoom = getMaxZoomLvl();
if (minZoom <= maxZoom) {
intResult = Utils.clamp(intResult, minZoom, maxZoom);
} else if (intResult > maxZoom) {
intResult = maxZoom;
}
return intResult;
}
/**
* Default implementation of {@link org.openstreetmap.josm.gui.layer.Layer.LayerAction#supportLayers(List)}.
* @param layers layers
* @return {@code true} is layers contains only a {@code TMSLayer}
*/
public static boolean actionSupportLayers(List<Layer> layers) {
return layers.size() == 1 && layers.get(0) instanceof TMSLayer;
}
private abstract static class AbstractTileAction extends AbstractAction {
protected final AbstractTileSourceLayer<?> layer;
protected final Tile tile;
AbstractTileAction(String name, AbstractTileSourceLayer<?> layer, Tile tile) {
super(name);
this.layer = layer;
this.tile = tile;
}
}
private static final class ShowTileInfoAction extends AbstractTileAction {
private ShowTileInfoAction(AbstractTileSourceLayer<?> layer, Tile tile) {
super(tr("Show tile info"), layer, tile);
setEnabled(tile != null);
}
private static String getSizeString(int size) {
return new StringBuilder().append(size).append('x').append(size).toString();
}
@Override
public void actionPerformed(ActionEvent ae) {
if (tile != null) {
ExtendedDialog ed = new ExtendedDialog(MainApplication.getMainFrame(), tr("Tile Info"), tr("OK"));
JPanel panel = new JPanel(new GridBagLayout());
Rectangle2D displaySize = layer.coordinateConverter.getRectangleForTile(tile);
String url = "";
try {
url = tile.getUrl();
} catch (IOException e) {
// silence exceptions
Logging.trace(e);
}
List<List<String>> content = new ArrayList<>();
content.add(Arrays.asList(tr("Tile name"), tile.getKey()));
content.add(Arrays.asList(tr("Tile URL"), url));
if (tile.getTileSource() instanceof TemplatedTileSource) {
Map<String, String> headers = ((TemplatedTileSource) tile.getTileSource()).getHeaders();
for (String key: new TreeSet<>(headers.keySet())) {
// iterate over sorted keys
content.add(Arrays.asList(tr("Custom header: {0}", key), headers.get(key)));
}
}
content.add(Arrays.asList(tr("Tile size"),
getSizeString(tile.getTileSource().getTileSize())));
content.add(Arrays.asList(tr("Tile display size"),
new StringBuilder().append(displaySize.getWidth())
.append('x')
.append(displaySize.getHeight()).toString()));
if (layer.coordinateConverter.requiresReprojection()) {
content.add(Arrays.asList(tr("Reprojection"),
tile.getTileSource().getServerCRS() +
" -> " + ProjectionRegistry.getProjection().toCode()));
BufferedImage img = tile.getImage();
if (img != null) {
content.add(Arrays.asList(tr("Reprojected tile size"),
img.getWidth() + "x" + img.getHeight()));
}
}
content.add(Arrays.asList(tr("Status"), tr(tile.getStatus())));
content.add(Arrays.asList(tr("Loaded"), tr(Boolean.toString(tile.isLoaded()))));
content.add(Arrays.asList(tr("Loading"), tr(Boolean.toString(tile.isLoading()))));
content.add(Arrays.asList(tr("Error"), tr(Boolean.toString(tile.hasError()))));
for (List<String> entry: content) {
panel.add(new JLabel(entry.get(0) + ':'), GBC.std());
panel.add(GBC.glue(5, 0), GBC.std());
panel.add(layer.createTextField(entry.get(1)), GBC.eol().fill(GBC.HORIZONTAL));
}
for (Entry<String, String> e: tile.getMetadata().entrySet()) {
panel.add(new JLabel(tr("Metadata ") + tr(e.getKey()) + ':'), GBC.std());
panel.add(GBC.glue(5, 0), GBC.std());
String value = e.getValue();
if ("lastModification".equals(e.getKey()) || "expirationTime".equals(e.getKey())) {
value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(value)));
}
panel.add(layer.createTextField(value), GBC.eol().fill(GBC.HORIZONTAL));
}
ed.setIcon(JOptionPane.INFORMATION_MESSAGE);
ed.setContent(panel);
ed.showDialog();
}
}
}
private static final class LoadTileAction extends AbstractTileAction {
private LoadTileAction(AbstractTileSourceLayer<?> layer, Tile tile) {
super(tr("Load tile"), layer, tile);
setEnabled(tile != null);
}
@Override
public void actionPerformed(ActionEvent ae) {
if (tile != null) {
layer.loadTile(tile, true);
layer.invalidate();
}
}
}
private static void sendOsmTileRequest(Tile tile, String request) {
if (tile != null) {
try {
new Notification(HttpClient.create(new URL(tile.getUrl() + '/' + request))
.connect().fetchContent()).show();
} catch (IOException ex) {
Logging.error(ex);
}
}
}
private static final class GetOsmTileStatusAction extends AbstractTileAction {
private GetOsmTileStatusAction(AbstractTileSourceLayer<?> layer, Tile tile) {
super(tr("Get tile status"), layer, tile);
setEnabled(tile != null);
}
@Override
public void actionPerformed(ActionEvent e) {
sendOsmTileRequest(tile, "status");
}
}
private static final class MarkOsmTileDirtyAction extends AbstractTileAction {
private MarkOsmTileDirtyAction(AbstractTileSourceLayer<?> layer, Tile tile) {
super(tr("Force tile rendering"), layer, tile);
setEnabled(tile != null);
}
@Override
public void actionPerformed(ActionEvent e) {
sendOsmTileRequest(tile, "dirty");
}
}
/**
* Creates popup menu items and binds to mouse actions
*/
@Override
public void hookUpMapView() {
// this needs to be here and not in constructor to allow empty TileSource class construction using SessionWriter
initializeIfRequired();
super.hookUpMapView();
}
@Override
public LayerPainter attachToMapView(MapViewEvent event) {
initializeIfRequired();
event.getMapView().addMouseListener(adapter);
MapView.addZoomChangeListener(this);
if (this instanceof NativeScaleLayer && NavigatableComponent.PROP_ZOOM_SCALE_FOLLOW_NATIVE_RES_AT_LOAD.get()) {
event.getMapView().setNativeScaleLayer((NativeScaleLayer) this);
}
// FIXME: why do we need this? Without this, if you add a WMS layer and do not move the mouse, sometimes, tiles do not start loading.
// FIXME: Check if this is still required.
event.getMapView().repaint(500);
return super.attachToMapView(event);
}
private void initializeIfRequired() {
if (tileSource == null) {
tileSource = getTileSource();
if (tileSource == null) {
throw new IllegalArgumentException(tr("Failed to create tile source"));
}
// check if projection is supported
projectionChanged(null, ProjectionRegistry.getProjection());
initTileSource(this.tileSource);
}
}
@Override
protected LayerPainter createMapViewPainter(MapViewEvent event) {
return new TileSourcePainter();
}
/**
* Tile source layer popup menu.
*/
public class TileSourceLayerPopup extends JPopupMenu {
/**
* Constructs a new {@code TileSourceLayerPopup}.
* @param x horizontal dimension where user clicked
* @param y vertical dimension where user clicked
*/
public TileSourceLayerPopup(int x, int y) {
List<JMenu> submenus = new ArrayList<>();
MainApplication.getLayerManager().getVisibleLayersInZOrder().stream()
.filter(AbstractTileSourceLayer.class::isInstance)
.map(AbstractTileSourceLayer.class::cast)
.forEachOrdered(layer -> {
JMenu submenu = new JMenu(layer.getName());
for (Action a : layer.getCommonEntries()) {
if (a instanceof LayerAction) {
submenu.add(((LayerAction) a).createMenuComponent());
} else {
submenu.add(new JMenuItem(a));
}
}
submenu.add(new JSeparator());
Tile tile = layer.getTileForPixelpos(x, y);
submenu.add(new JMenuItem(new LoadTileAction(layer, tile)));
submenu.add(new JMenuItem(new ShowTileInfoAction(layer, tile)));
if (ExpertToggleAction.isExpert() && tileSource != null && tileSource.isModTileFeatures()) {
submenu.add(new JMenuItem(new GetOsmTileStatusAction(layer, tile)));
submenu.add(new JMenuItem(new MarkOsmTileDirtyAction(layer, tile)));
}
submenus.add(submenu);
});
if (submenus.size() == 1) {
JMenu menu = submenus.get(0);
Arrays.stream(menu.getMenuComponents()).forEachOrdered(this::add);
} else if (submenus.size() > 1) {
submenus.stream().forEachOrdered(this::add);
}
}
}
protected int estimateTileCacheSize() {
Dimension screenSize = GuiHelper.getMaximumScreenSize();
int height = screenSize.height;
int width = screenSize.width;
int tileSize = 256; // default tile size
if (tileSource != null) {
tileSize = tileSource.getTileSize();
}
// as we can see part of the tile at the top and at the bottom, use Math.ceil(...) + 1 to accommodate for that
int visibileTiles = (int) (Math.ceil((double) height / tileSize + 1) * Math.ceil((double) width / tileSize + 1));
// add 10% for tiles from different zoom levels
int ret = (int) Math.ceil(
Math.pow(2d, ZOOM_OFFSET.get()) * visibileTiles // use offset to decide, how many tiles are visible
* 4);
Logging.info("AbstractTileSourceLayer: estimated visible tiles: {0}, estimated cache size: {1}", visibileTiles, ret);
return ret;
}
@Override
public void displaySettingsChanged(DisplaySettingsChangeEvent e) {
if (tileSource == null) {
return;
}
switch (e.getChangedSetting()) {
case TileSourceDisplaySettings.AUTO_ZOOM:
if (getDisplaySettings().isAutoZoom() && getBestZoom() != currentZoomLevel) {
setZoomLevel(getBestZoom());
invalidate();
}
break;
case TileSourceDisplaySettings.AUTO_LOAD:
if (getDisplaySettings().isAutoLoad()) {
invalidate();
}
break;
default:
// e.g. displacement
// trigger a redraw in every case
invalidate();
}
}
/**
* Checks zoom level against settings
* @param maxZoomLvl zoom level to check
* @param ts tile source to crosscheck with
* @return maximum zoom level, not higher than supported by tilesource nor set by the user
*/
public static int checkMaxZoomLvl(int maxZoomLvl, TileSource ts) {
if (maxZoomLvl > MAX_ZOOM) {
maxZoomLvl = MAX_ZOOM;
}
if (maxZoomLvl < PROP_MIN_ZOOM_LVL.get()) {
maxZoomLvl = PROP_MIN_ZOOM_LVL.get();
}
if (ts != null && ts.getMaxZoom() != 0 && ts.getMaxZoom() < maxZoomLvl) {
maxZoomLvl = ts.getMaxZoom();
}
return maxZoomLvl;
}
/**
* Checks zoom level against settings
* @param minZoomLvl zoom level to check
* @param ts tile source to crosscheck with
* @return minimum zoom level, not higher than supported by tilesource nor set by the user
*/
public static int checkMinZoomLvl(int minZoomLvl, TileSource ts) {
if (minZoomLvl < MIN_ZOOM) {
minZoomLvl = MIN_ZOOM;
}
if (minZoomLvl > PROP_MAX_ZOOM_LVL.get()) {
minZoomLvl = getMaxZoomLvl(ts);
}
if (ts != null && ts.getMinZoom() > minZoomLvl) {
minZoomLvl = ts.getMinZoom();
}
return minZoomLvl;
}
/**
* @param ts TileSource for which we want to know maximum zoom level
* @return maximum max zoom level, that will be shown on layer
*/
public static int getMaxZoomLvl(TileSource ts) {
return checkMaxZoomLvl(PROP_MAX_ZOOM_LVL.get(), ts);
}
/**
* @param ts TileSource for which we want to know minimum zoom level
* @return minimum zoom level, that will be shown on layer
*/
public static int getMinZoomLvl(TileSource ts) {
return checkMinZoomLvl(PROP_MIN_ZOOM_LVL.get(), ts);
}
/**
* Sets maximum zoom level, that layer will attempt show
* @param maxZoomLvl maximum zoom level
*/
public static void setMaxZoomLvl(int maxZoomLvl) {
PROP_MAX_ZOOM_LVL.put(checkMaxZoomLvl(maxZoomLvl, null));
}
/**
* Sets minimum zoom level, that layer will attempt show
* @param minZoomLvl minimum zoom level
*/
public static void setMinZoomLvl(int minZoomLvl) {
PROP_MIN_ZOOM_LVL.put(checkMinZoomLvl(minZoomLvl, null));
}
/**
* This fires every time the user changes the zoom, but also (due to ZoomChangeListener) - on all
* changes to visible map (panning/zooming)
*/
@Override
public void zoomChanged() {
zoomChanged(true);
}
private void zoomChanged(boolean invalidate) {
Logging.debug("zoomChanged(): {0}", currentZoomLevel);
if (tileLoader instanceof TMSCachedTileLoader) {
((TMSCachedTileLoader) tileLoader).cancelOutstandingTasks();
}
if (invalidate) {
invalidate();
}
}
protected int getMaxZoomLvl() {
if (info.getMaxZoom() != 0)
return checkMaxZoomLvl(info.getMaxZoom(), tileSource);
else
return getMaxZoomLvl(tileSource);
}
protected int getMinZoomLvl() {
if (info.getMinZoom() != 0)
return checkMinZoomLvl(info.getMinZoom(), tileSource);
else
return getMinZoomLvl(tileSource);
}
/**
*
* @return if its allowed to zoom in
*/
public boolean zoomIncreaseAllowed() {
boolean zia = currentZoomLevel < this.getMaxZoomLvl();
Logging.debug("zoomIncreaseAllowed(): {0} {1} vs. {2}", zia, currentZoomLevel, this.getMaxZoomLvl());
return zia;
}
/**
* Zoom in, go closer to map.
*
* @return true, if zoom increasing was successful, false otherwise
*/
public boolean increaseZoomLevel() {
if (zoomIncreaseAllowed()) {
currentZoomLevel++;
Logging.debug("increasing zoom level to: {0}", currentZoomLevel);
zoomChanged();
} else {
Logging.warn("Current zoom level ("+currentZoomLevel+") could not be increased. "+
"Max.zZoom Level "+this.getMaxZoomLvl()+" reached.");
return false;
}
return true;
}
/**
* Get the current zoom level of the layer
* @return the current zoom level
* @since 12603
*/
public int getZoomLevel() {
return currentZoomLevel;
}
/**
* Sets the zoom level of the layer
* @param zoom zoom level
* @return true, when zoom has changed to desired value, false if it was outside supported zoom levels
*/
public boolean setZoomLevel(int zoom) {
return setZoomLevel(zoom, true);
}
private boolean setZoomLevel(int zoom, boolean invalidate) {
if (zoom == currentZoomLevel) return true;
if (zoom > this.getMaxZoomLvl()) return false;
if (zoom < this.getMinZoomLvl()) return false;
currentZoomLevel = zoom;
zoomChanged(invalidate);
return true;
}
/**
* Check if zooming out is allowed
*
* @return true, if zooming out is allowed (currentZoomLevel > minZoomLevel)
*/
public boolean zoomDecreaseAllowed() {
boolean zda = currentZoomLevel > this.getMinZoomLvl();
Logging.debug("zoomDecreaseAllowed(): {0} {1} vs. {2}", zda, currentZoomLevel, this.getMinZoomLvl());
return zda;
}
/**
* Zoom out from map.
*
* @return true, if zoom increasing was successful, false othervise
*/
public boolean decreaseZoomLevel() {
if (zoomDecreaseAllowed()) {
Logging.debug("decreasing zoom level to: {0}", currentZoomLevel);
currentZoomLevel--;
zoomChanged();
} else {
return false;
}
return true;
}
private Tile getOrCreateTile(TilePosition tilePosition) {
return getOrCreateTile(tilePosition.getX(), tilePosition.getY(), tilePosition.getZoom());
}
private Tile getOrCreateTile(int x, int y, int zoom) {
Tile tile = getTile(x, y, zoom);
if (tile == null) {
if (coordinateConverter.requiresReprojection()) {
tile = new ReprojectionTile(tileSource, x, y, zoom);
} else {
tile = new Tile(tileSource, x, y, zoom);
}
tileCache.addTile(tile);
}
return tile;
}
private Tile getTile(TilePosition tilePosition) {
return getTile(tilePosition.getX(), tilePosition.getY(), tilePosition.getZoom());
}
/**
* Returns tile at given position.
* This can and will return null for tiles that are not already in the cache.
* @param x tile number on the x axis of the tile to be retrieved
* @param y tile number on the y axis of the tile to be retrieved
* @param zoom zoom level of the tile to be retrieved
* @return tile at given position
*/
private Tile getTile(int x, int y, int zoom) {
if (x < tileSource.getTileXMin(zoom) || x > tileSource.getTileXMax(zoom)
|| y < tileSource.getTileYMin(zoom) || y > tileSource.getTileYMax(zoom))
return null;
return tileCache.getTile(tileSource, x, y, zoom);
}
private boolean loadTile(Tile tile, boolean force) {
if (tile == null)
return false;
if (!force && tile.isLoaded())
return false;
if (tile.isLoading())
return false;
tileLoader.createTileLoaderJob(tile).submit(force);
return true;
}
private TileSet getVisibleTileSet() {
if (!MainApplication.isDisplayingMapView())
return new TileSet();
ProjectionBounds bounds = MainApplication.getMap().mapView.getProjectionBounds();
return getTileSet(bounds, currentZoomLevel);
}
/**
* Load all visible tiles.
* @param force {@code true} to force loading if auto-load is disabled
* @since 11950
*/
public void loadAllTiles(boolean force) {
TileSet ts = getVisibleTileSet();
// if there is more than 18 tiles on screen in any direction, do not load all tiles!
if (ts.tooLarge()) {
Logging.warn("Not downloading all tiles because there is more than 18 tiles on an axis!");
return;
}
ts.loadAllTiles(force);
invalidate();
}
/**
* Load all visible tiles in error.
* @param force {@code true} to force loading if auto-load is disabled
* @since 11950
*/
public void loadAllErrorTiles(boolean force) {
TileSet ts = getVisibleTileSet();
ts.loadAllErrorTiles(force);
invalidate();
}
@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
boolean done = (infoflags & (ERROR | FRAMEBITS | ALLBITS)) != 0;
Logging.debug("imageUpdate() done: {0} calling repaint", done);
if (done) {
invalidate();
} else {
invalidateLater();
}
return !done;
}
/**
* Invalidate the layer at a time in the future so that the user still sees the interface responsive.
*/
private void invalidateLater() {
GuiHelper.runInEDT(() -> {
if (!invalidateLaterTimer.isRunning()) {
invalidateLaterTimer.setRepeats(false);
invalidateLaterTimer.start();
}
});
}
private boolean imageLoaded(Image i) {
if (i == null)
return false;
int status = Toolkit.getDefaultToolkit().checkImage(i, -1, -1, this);
return (status & ALLBITS) != 0;
}
/**
* Returns the image for the given tile image is loaded.
* Otherwise returns null.
*
* @param tile the Tile for which the image should be returned
* @return the image of the tile or null.
*/
private BufferedImage getLoadedTileImage(Tile tile) {
BufferedImage img = tile.getImage();
if (!imageLoaded(img))
return null;
return img;
}
/**
* Draw a tile image on screen.
* @param g the Graphics2D
* @param toDrawImg tile image
* @param anchorImage tile anchor in image coordinates
* @param anchorScreen tile anchor in screen coordinates
* @param clip clipping region in screen coordinates (can be null)
*/
private void drawImageInside(Graphics2D g, BufferedImage toDrawImg, TileAnchor anchorImage, TileAnchor anchorScreen, Shape clip) {
AffineTransform imageToScreen = anchorImage.convert(anchorScreen);
Point2D screen0 = imageToScreen.transform(new Point2D.Double(0, 0), null);
Point2D screen1 = imageToScreen.transform(new Point2D.Double(
toDrawImg.getWidth(), toDrawImg.getHeight()), null);
Shape oldClip = null;
if (clip != null) {