diff --git a/OsmAnd/res/layout/fragment_map_markers_dialog.xml b/OsmAnd/res/layout/fragment_map_markers_dialog.xml index 08e4bcd12d..eb8ebecc96 100644 --- a/OsmAnd/res/layout/fragment_map_markers_dialog.xml +++ b/OsmAnd/res/layout/fragment_map_markers_dialog.xml @@ -30,16 +30,34 @@ app:contentInsetLeft="54dp" app:contentInsetStart="54dp"> - + + + + + + + + diff --git a/OsmAnd/res/values/strings.xml b/OsmAnd/res/values/strings.xml index e2926e4430..cd52e1afbc 100644 --- a/OsmAnd/res/values/strings.xml +++ b/OsmAnd/res/values/strings.xml @@ -9,6 +9,8 @@ 3. All your modified/created strings are in the top of the file (to make easier find what\'s translated). PLEASE: Have a look at http://code.google.com/p/osmand/wiki/UIConsistency, it may really improve your and our work :-) Thx - Hardy --> + You can add all of the track\'s waypoints, or select separate categories. + Total Clear all intermediate points Group deleted Whitewater sports diff --git a/OsmAnd/src/net/osmand/plus/AppInitializer.java b/OsmAnd/src/net/osmand/plus/AppInitializer.java index d591287c2f..2c9515ce09 100644 --- a/OsmAnd/src/net/osmand/plus/AppInitializer.java +++ b/OsmAnd/src/net/osmand/plus/AppInitializer.java @@ -603,7 +603,6 @@ public class AppInitializer implements IProgress { notifyEvent(InitEvents.LOAD_GPX_TRACKS); saveGPXTracks(); notifyEvent(InitEvents.SAVE_GPX_TRACKS); - app.mapMarkersHelper.syncAllGroupsAsync(); // restore backuped favorites to normal file restoreBackupForFavoritesFiles(); notifyEvent(InitEvents.RESTORE_BACKUPS); diff --git a/OsmAnd/src/net/osmand/plus/FavouritesDbHelper.java b/OsmAnd/src/net/osmand/plus/FavouritesDbHelper.java index fd8d7c9b74..87a95eb7cc 100644 --- a/OsmAnd/src/net/osmand/plus/FavouritesDbHelper.java +++ b/OsmAnd/src/net/osmand/plus/FavouritesDbHelper.java @@ -10,7 +10,6 @@ import net.osmand.data.FavouritePoint; import net.osmand.data.LatLon; import net.osmand.plus.GPXUtilities.GPXFile; import net.osmand.plus.GPXUtilities.WptPt; -import net.osmand.plus.MapMarkersHelper.MarkersSyncGroup; import net.osmand.plus.api.SQLiteAPI.SQLiteConnection; import net.osmand.plus.api.SQLiteAPI.SQLiteCursor; import net.osmand.util.Algorithms; @@ -110,6 +109,20 @@ public class FavouritesDbHelper { return changed; } + private void runSyncWithMarkers(FavoriteGroup favGroup) { + MapMarkersHelper helper = context.getMapMarkersHelper(); + helper.runSynchronization(helper.getOrCreateGroup(favGroup)); + } + + private void removeFromMarkers(FavoriteGroup favGroup) { + MapMarkersHelper helper = context.getMapMarkersHelper(); + helper.removeMarkersGroup(helper.getOrCreateGroup(favGroup)); + } + + private void addToMarkers(FavoriteGroup favGroup) { + MapMarkersHelper helper = context.getMapMarkersHelper(); + helper.syncWithMarkers(helper.getOrCreateGroup(favGroup)); + } private File getInternalFile() { return context.getFileStreamPath(FILE_TO_BACKUP); @@ -127,7 +140,7 @@ public class FavouritesDbHelper { cachedFavoritePoints.remove(p); } for (FavoriteGroup gr : groupsToSync) { - context.getMapMarkersHelper().syncGroupAsync(new MarkersSyncGroup(gr.name, gr.name, MarkersSyncGroup.FAVORITES_TYPE)); + runSyncWithMarkers(gr); } } if (groupsToDelete != null) { @@ -135,7 +148,7 @@ public class FavouritesDbHelper { flatGroups.remove(g.name); favoriteGroups.remove(g); cachedFavoritePoints.removeAll(g.points); - context.getMapMarkersHelper().removeMarkersSyncGroup(g.name); + removeFromMarkers(g); } } saveCurrentPointsIntoFile(); @@ -150,7 +163,7 @@ public class FavouritesDbHelper { FavoriteGroup group = flatGroups.get(p.getCategory()); if (group != null) { group.points.remove(p); - context.getMapMarkersHelper().syncGroupAsync(new MarkersSyncGroup(group.name, group.name, MarkersSyncGroup.FAVORITES_TYPE)); + runSyncWithMarkers(group); } cachedFavoritePoints.remove(p); } @@ -180,7 +193,7 @@ public class FavouritesDbHelper { sortAll(); saveCurrentPointsIntoFile(); } - context.getMapMarkersHelper().syncGroupAsync(new MarkersSyncGroup(group.name, group.name, MarkersSyncGroup.FAVORITES_TYPE, group.color)); + runSyncWithMarkers(group); return true; } @@ -275,7 +288,7 @@ public class FavouritesDbHelper { } sortAll(); saveCurrentPointsIntoFile(); - context.getMapMarkersHelper().syncGroupAsync(new MarkersSyncGroup(category, category, MarkersSyncGroup.FAVORITES_TYPE, p.getColor())); + runSyncWithMarkers(getOrCreateGroup(p, 0)); return true; } @@ -283,7 +296,7 @@ public class FavouritesDbHelper { p.setLatitude(lat); p.setLongitude(lon); saveCurrentPointsIntoFile(); - context.getMapMarkersHelper().syncGroupAsync(new MarkersSyncGroup(p.getCategory(), p.getCategory(), MarkersSyncGroup.FAVORITES_TYPE, p.getColor())); + runSyncWithMarkers(getOrCreateGroup(p, 0)); return true; } @@ -352,7 +365,7 @@ public class FavouritesDbHelper { if (remove) { flatGroups.remove(group.name); saveCurrentPointsIntoFile(); - context.getMapMarkersHelper().removeMarkersSyncGroup(group.name); + removeFromMarkers(group); return true; } return false; @@ -603,14 +616,13 @@ public class FavouritesDbHelper { } public void editFavouriteGroup(FavoriteGroup group, String newName, int color, boolean visible) { - MapMarkersHelper markersHelper = context.getMapMarkersHelper(); if (color != 0 && group.color != color) { FavoriteGroup gr = flatGroups.get(group.name); group.color = color; for (FavouritePoint p : gr.points) { p.setColor(color); } - markersHelper.syncGroupAsync(new MarkersSyncGroup(gr.name, gr.name, MarkersSyncGroup.FAVORITES_TYPE, color)); + runSyncWithMarkers(gr); } if (group.visible != visible) { FavoriteGroup gr = flatGroups.get(group.name); @@ -618,11 +630,11 @@ public class FavouritesDbHelper { for (FavouritePoint p : gr.points) { p.setVisible(visible); } - markersHelper.syncGroupAsync(new MarkersSyncGroup(gr.name, gr.name, MarkersSyncGroup.FAVORITES_TYPE, group.color)); + runSyncWithMarkers(gr); } if (!group.name.equals(newName)) { FavoriteGroup gr = flatGroups.remove(group.name); - markersHelper.removeMarkersSyncGroup(group.name); + removeFromMarkers(gr); gr.name = newName; FavoriteGroup renamedGroup = flatGroups.get(gr.name); boolean existing = renamedGroup != null; @@ -638,9 +650,7 @@ public class FavouritesDbHelper { renamedGroup.points.add(p); } } - MarkersSyncGroup syncGroup = new MarkersSyncGroup(renamedGroup.name, renamedGroup.name, MarkersSyncGroup.FAVORITES_TYPE, group.color); - markersHelper.addMarkersSyncGroup(syncGroup); - markersHelper.syncGroupAsync(syncGroup); + addToMarkers(renamedGroup); } saveCurrentPointsIntoFile(); } diff --git a/OsmAnd/src/net/osmand/plus/GpxSelectionHelper.java b/OsmAnd/src/net/osmand/plus/GpxSelectionHelper.java index 0dc42d50a9..2022567095 100644 --- a/OsmAnd/src/net/osmand/plus/GpxSelectionHelper.java +++ b/OsmAnd/src/net/osmand/plus/GpxSelectionHelper.java @@ -6,7 +6,6 @@ import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; -import net.osmand.AndroidUtils; import net.osmand.IProgress; import net.osmand.data.LatLon; import net.osmand.plus.GPXDatabase.GpxDataItem; @@ -16,8 +15,6 @@ import net.osmand.plus.GPXUtilities.Route; import net.osmand.plus.GPXUtilities.Track; import net.osmand.plus.GPXUtilities.TrkSegment; import net.osmand.plus.GPXUtilities.WptPt; -import net.osmand.plus.MapMarkersHelper.MarkersSyncGroup; -import net.osmand.plus.MapMarkersHelper.OnGroupSyncedListener; import net.osmand.plus.OsmandSettings.MetricsConstants; import net.osmand.plus.activities.SavingTrackHelper; import net.osmand.plus.helpers.GpxUiHelper; @@ -502,7 +499,7 @@ public class GpxSelectionHelper { } } if (syncGroup) { - syncGpx(gpx, true, null); + syncGpx(gpx); } return sf; } @@ -539,25 +536,10 @@ public class GpxSelectionHelper { } private void syncGpx(GPXFile gpxFile) { - syncGpx(gpxFile, false, null); - } - - public void syncGpx(GPXFile gpxFile, boolean createOrDeleteGroup, @Nullable OnGroupSyncedListener callback) { File gpx = new File(gpxFile.path); if (gpx.exists()) { MapMarkersHelper mapMarkersHelper = app.getMapMarkersHelper(); - MarkersSyncGroup syncGroup = new MarkersSyncGroup(gpx.getAbsolutePath(), AndroidUtils.trimExtension(gpx.getName()), MarkersSyncGroup.GPX_TYPE); - boolean enabled = true; - if (createOrDeleteGroup) { - boolean show = getSelectedFileByPath(gpx.getAbsolutePath()) != null; - enabled = mapMarkersHelper.isGroupSynced(gpx.getAbsolutePath()); - if (show && !enabled) { - mapMarkersHelper.addMarkersSyncGroup(syncGroup); - } else if (!show && mapMarkersHelper.isGroupDisabled(gpx.getAbsolutePath())) { - mapMarkersHelper.removeMarkersSyncGroup(gpx.getAbsolutePath()); - } - } - mapMarkersHelper.syncGroupAsync(syncGroup, enabled, callback); + mapMarkersHelper.runSynchronization(mapMarkersHelper.getOrCreateGroup(gpx)); } } diff --git a/OsmAnd/src/net/osmand/plus/MapMarkersHelper.java b/OsmAnd/src/net/osmand/plus/MapMarkersHelper.java index 54dea59630..52ab9f268b 100644 --- a/OsmAnd/src/net/osmand/plus/MapMarkersHelper.java +++ b/OsmAnd/src/net/osmand/plus/MapMarkersHelper.java @@ -7,6 +7,7 @@ import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; +import net.osmand.AndroidUtils; import net.osmand.IndexConstants; import net.osmand.data.FavouritePoint; import net.osmand.data.LatLon; @@ -15,6 +16,7 @@ import net.osmand.data.PointDescription; import net.osmand.plus.FavouritesDbHelper.FavoriteGroup; import net.osmand.plus.GPXUtilities.GPXFile; import net.osmand.plus.GPXUtilities.WptPt; +import net.osmand.plus.GeocodingLookupService.AddressLookupRequest; import net.osmand.plus.GpxSelectionHelper.SelectedGpxFile; import net.osmand.plus.mapmarkers.MapMarkersDbHelper; import net.osmand.plus.mapmarkers.MarkersPlanRouteContext; @@ -27,9 +29,11 @@ import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; -import java.util.LinkedHashMap; +import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -61,11 +65,947 @@ public class MapMarkersHelper { private List mapMarkersGroups = new ArrayList<>(); private List listeners = new ArrayList<>(); + private Set syncListeners = new HashSet<>(); private boolean startFromMyLocation; private MarkersPlanRouteContext planRouteContext; + public List getMapMarkers() { + return mapMarkers; + } + + public List getMapMarkersHistory() { + return mapMarkersHistory; + } + + public List getMapMarkersGroups() { + return mapMarkersGroups; + } + + public boolean isStartFromMyLocation() { + return startFromMyLocation; + } + + public void setStartFromMyLocation(boolean startFromMyLocation) { + this.startFromMyLocation = startFromMyLocation; + settings.ROUTE_MAP_MARKERS_START_MY_LOC.set(startFromMyLocation); + } + + public MarkersPlanRouteContext getPlanRouteContext() { + return planRouteContext; + } + + public MapMarkersHelper(OsmandApplication ctx) { + this.ctx = ctx; + settings = ctx.getSettings(); + markersDbHelper = ctx.getMapMarkersDbHelper(); + planRouteContext = new MarkersPlanRouteContext(ctx); + startFromMyLocation = settings.ROUTE_MAP_MARKERS_START_MY_LOC.get(); + markersDbHelper.removeDisabledGroups(); + loadMarkers(); + loadGroups(); + } + + private void loadMarkers() { + mapMarkers = new ArrayList<>(); + mapMarkersHistory = new ArrayList<>(); + + addToMapMarkersList(markersDbHelper.getActiveMarkers()); + reorderActiveMarkersIfNeeded(); + + List markersHistory = markersDbHelper.getMarkersHistory(); + sortMarkers(markersHistory, true, BY_DATE_ADDED_DESC); + addToMapMarkersHistoryList(markersHistory); + + if (!ctx.isApplicationInitializing()) { + lookupAddressAll(); + } + } + + private void loadGroups() { + Map groupsMap = markersDbHelper.getAllGroupsMap(); + List allMarkers = new ArrayList<>(mapMarkers); + allMarkers.addAll(mapMarkersHistory); + + MapMarkersGroup noGroup = null; + + for (MapMarker marker : allMarkers) { + MapMarkersGroup group = groupsMap.get(marker.groupKey); + if (group == null) { + if (noGroup == null) { + noGroup = new MapMarkersGroup(); + noGroup.creationDate = Long.MAX_VALUE; + } + noGroup.getMarkers().add(marker); + } else { + if (marker.creationDate < group.creationDate) { + group.creationDate = marker.creationDate; + } + group.getMarkers().add(marker); + } + } + + mapMarkersGroups = new ArrayList<>(groupsMap.values()); + if (noGroup != null) { + sortMarkers(noGroup.getMarkers(), false, BY_DATE_ADDED_DESC); + addToGroupsList(noGroup); + } + + sortGroups(); + + for (MapMarkersGroup group : mapMarkersGroups) { + updateGroup(group); + } + + syncAllGroupsAsync(); + } + + private void syncAllGroupsAsync() { + for (MapMarkersGroup gr : mapMarkersGroups) { + if (gr.getId() != null && gr.getName() != null) { + runSynchronization(gr); + } + } + } + + public void lookupAddressAll() { + for (MapMarker mapMarker : mapMarkers) { + lookupAddress(mapMarker); + } + for (MapMarker mapMarker : mapMarkersHistory) { + lookupAddress(mapMarker); + } + } + + private void lookupAddress(final MapMarker mapMarker) { + if (mapMarker != null && mapMarker.pointDescription.isSearchingAddress(ctx)) { + cancelPointAddressRequests(mapMarker.point); + AddressLookupRequest lookupRequest = new AddressLookupRequest(mapMarker.point, + new GeocodingLookupService.OnAddressLookupResult() { + @Override + public void geocodingDone(String address) { + if (Algorithms.isEmpty(address)) { + mapMarker.pointDescription.setName(PointDescription.getAddressNotFoundStr(ctx)); + } else { + mapMarker.pointDescription.setName(address); + } + markersDbHelper.updateMarker(mapMarker); + refreshMarker(mapMarker); + } + }, null); + ctx.getGeocodingLookupService().lookupAddress(lookupRequest); + } + } + + private void cancelAddressRequests() { + List markers = new ArrayList<>(mapMarkers); + for (MapMarker m : markers) { + cancelPointAddressRequests(m.point); + } + markers = new ArrayList<>(mapMarkersHistory); + for (MapMarker m : markers) { + cancelPointAddressRequests(m.point); + } + } + + private void cancelPointAddressRequests(LatLon latLon) { + if (latLon != null) { + ctx.getGeocodingLookupService().cancel(latLon); + } + } + + public void reorderActiveMarkersIfNeeded() { + if (!mapMarkers.isEmpty()) { + if (mapMarkers.size() > 1) { + for (int i = 0; i < mapMarkers.size() - 1; i++) { + MapMarker first = mapMarkers.get(i); + MapMarker second = mapMarkers.get(i + 1); + if (!first.nextKey.equals(second.id)) { + markersDbHelper.changeActiveMarkerPosition(first, second); + first.nextKey = second.id; + } + } + } + + MapMarker tail = mapMarkers.get(mapMarkers.size() - 1); + if (!tail.nextKey.equals(MapMarkersDbHelper.TAIL_NEXT_VALUE)) { + markersDbHelper.changeActiveMarkerPosition(tail, null); + } + } + } + + public void sortMarkers(final @MapMarkersSortByDef int sortByMode, LatLon location) { + sortMarkers(getMapMarkers(), false, sortByMode, location); + reorderActiveMarkersIfNeeded(); + } + + private void sortMarkers(List markers, final boolean visited, final @MapMarkersSortByDef int sortByMode) { + sortMarkers(markers, visited, sortByMode, null); + } + + private void sortMarkers(List markers, + final boolean visited, + final @MapMarkersSortByDef int sortByMode, + @Nullable final LatLon location) { + Collections.sort(markers, new Comparator() { + @Override + public int compare(MapMarker mapMarker1, MapMarker mapMarker2) { + if (sortByMode == BY_DATE_ADDED_DESC || sortByMode == BY_DATE_ADDED_ASC) { + long t1 = visited ? mapMarker1.visitedDate : mapMarker1.creationDate; + long t2 = visited ? mapMarker2.visitedDate : mapMarker2.creationDate; + if (t1 > t2) { + return sortByMode == BY_DATE_ADDED_DESC ? -1 : 1; + } else if (t1 == t2) { + return 0; + } else { + return sortByMode == BY_DATE_ADDED_DESC ? 1 : -1; + } + } else if (location != null && (sortByMode == BY_DISTANCE_DESC || sortByMode == BY_DISTANCE_ASC)) { + int d1 = (int) MapUtils.getDistance(location, mapMarker1.getLatitude(), mapMarker1.getLongitude()); + int d2 = (int) MapUtils.getDistance(location, mapMarker2.getLatitude(), mapMarker2.getLongitude()); + if (d1 > d2) { + return sortByMode == BY_DISTANCE_DESC ? -1 : 1; + } else if (d1 == d2) { + return 0; + } else { + return sortByMode == BY_DISTANCE_DESC ? 1 : -1; + } + } else { + String n1 = mapMarker1.getName(ctx); + String n2 = mapMarker2.getName(ctx); + return n1.compareToIgnoreCase(n2); + } + } + }); + } + + public boolean isGroupSynced(String id) { + return getMapMarkerGroupById(id) != null; + } + + public void runSynchronization(@NonNull final MapMarkersGroup group) { + ctx.runInUIThread(new Runnable() { + @Override + public void run() { + new SyncGroupTask(group).executeOnExecutor(executorService); + } + }); + } + + public boolean isSynced(SelectedGpxFile gpxFile) { + List gpxPoints = gpxFile.getGpxFile().getPoints(); + for (WptPt wptPt : gpxPoints) { + if (getMapMarker(wptPt) != null) { + return true; + } + } + return false; + } + + public boolean isSynced(FavouritePoint favouritePoint) { + return getMapMarker(favouritePoint) != null; + } + + public void syncWithMarkers(@NonNull MapMarkersGroup group) { + if (!isGroupSynced(group.getId())) { + markersDbHelper.addGroup(group); + addToGroupsList(group); + } else if (group.wptCategories != null) { + markersDbHelper.updateGroupCategories(group.getId(), group.getWptCategoriesString()); + } + runSynchronization(group); + } + + public void removeMarkersGroup(MapMarkersGroup group) { + if (group != null) { + markersDbHelper.removeMarkersGroup(group.getId()); + removeGroupActiveMarkers(group, false); + removeFromGroupsList(group); + } + } + + public void updateGroupDisabled(@NonNull MapMarkersGroup group, boolean disabled) { + String id = group.getId(); + if (id != null) { + markersDbHelper.updateGroupDisabled(id, disabled); + group.disabled = disabled; + } + } + + private void removeGroupActiveMarkers(MapMarkersGroup group, boolean updateGroup) { + if (group != null) { + markersDbHelper.removeActiveMarkersFromGroup(group.getId()); + removeFromMapMarkersList(group.getActiveMarkers()); + if (updateGroup) { + group.markers = group.getHistoryMarkers(); + updateGroup(group); + } + reorderActiveMarkersIfNeeded(); + refresh(); + } + } + + public void updateGroups() { + for (MapMarkersGroup group : mapMarkersGroups) { + updateGroup(group); + } + } + + public void updateGroup(MapMarkersGroup mapMarkersGroup) { + if (mapMarkersGroup.getId() == null || mapMarkersGroup.getName() == null) { + return; + } + createHeaderInGroup(mapMarkersGroup); + int historyMarkersCount = mapMarkersGroup.getHistoryMarkers().size(); + ShowHideHistoryButton showHideHistoryButton = mapMarkersGroup.getShowHideHistoryButton(); + if (showHideHistoryButton != null) { + if (historyMarkersCount == 0) { + mapMarkersGroup.showHideHistoryButton = null; + } + } else if (historyMarkersCount > 0) { + showHideHistoryButton = new ShowHideHistoryButton(); + showHideHistoryButton.showHistory = false; + mapMarkersGroup.showHideHistoryButton = showHideHistoryButton; + } + } + + private void addMarkersToGroups(@NonNull List markers) { + for (MapMarker marker : markers) { + addMarkerToGroup(marker); + } + } + + private void addMarkerToGroup(MapMarker marker) { + if (marker != null) { + MapMarkersGroup mapMarkersGroup = getMapMarkerGroupById(marker.groupKey); + if (mapMarkersGroup != null) { + mapMarkersGroup.getMarkers().add(marker); + updateGroup(mapMarkersGroup); + if (mapMarkersGroup.getName() == null) { + sortMarkers(mapMarkersGroup.getMarkers(), false, BY_DATE_ADDED_DESC); + } + } else { + mapMarkersGroup = new MapMarkersGroup(); + mapMarkersGroup.id = marker.groupKey; + mapMarkersGroup.name = marker.groupName; + mapMarkersGroup.creationDate = Long.MAX_VALUE; + mapMarkersGroup.getMarkers().add(marker); + addToGroupsList(mapMarkersGroup); + sortGroups(); + updateGroup(mapMarkersGroup); + } + } + } + + private void createHeaderInGroup(@NonNull MapMarkersGroup group) { + GroupHeader header = new GroupHeader(); + int type = group.getType(); + if (type != -1) { + header.iconRes = type == MapMarkersGroup.FAVORITES_TYPE + ? R.drawable.ic_action_fav_dark : R.drawable.ic_action_polygom_dark; + } + header.group = group; + group.header = header; + } + + private void removeMarkerFromGroup(MapMarker marker) { + if (marker != null) { + MapMarkersGroup mapMarkersGroup = getMapMarkerGroupById(marker.groupKey); + if (mapMarkersGroup != null) { + mapMarkersGroup.getMarkers().remove(marker); + updateGroup(mapMarkersGroup); + } + } + } + + private void sortGroups() { + if (mapMarkersGroups.size() > 0) { + Collections.sort(mapMarkersGroups, new Comparator() { + @Override + public int compare(MapMarkersGroup group1, MapMarkersGroup group2) { + long t1 = group1.creationDate; + long t2 = group2.creationDate; + return (t1 > t2) ? -1 : ((t1 == t2) ? 0 : 1); + } + }); + } + } + + @Nullable + public MapMarkersGroup getMapMarkerGroupById(String id) { + for (MapMarkersGroup group : mapMarkersGroups) { + if ((id == null && group.getId() == null) + || (group.getId() != null && group.getId().equals(id))) { + return group; + } + } + return null; + } + + public MapMarkersGroup getOrCreateGroup(@NonNull FavoriteGroup favGroup) { + MapMarkersGroup group = getMapMarkerGroupById(favGroup.name); + if (group == null) { + group = new MapMarkersGroup(favGroup.name, favGroup.name, MapMarkersGroup.FAVORITES_TYPE); + } + return group; + } + + public MapMarkersGroup getOrCreateGroup(@NonNull File gpx) { + MapMarkersGroup group = getMapMarkerGroupById(gpx.getAbsolutePath()); + if (group == null) { + group = new MapMarkersGroup(gpx.getAbsolutePath(), + AndroidUtils.trimExtension(gpx.getName()), + MapMarkersGroup.GPX_TYPE); + } + return group; + } + + @NonNull + public List getGroupsForDisplayedGpx() { + List res = new ArrayList<>(); + List selectedGpxFiles = ctx.getSelectedGpxHelper().getSelectedGPXFiles(); + for (SelectedGpxFile selected : selectedGpxFiles) { + MapMarkersGroup group = getOrCreateGroup(new File(selected.getGpxFile().path)); + if (!isGroupSynced(group.getId())) { + group.disabled = true; + createHeaderInGroup(group); + res.add(group); + } + } + return res; + } + + @Nullable + public MapMarker getMapMarker(WptPt wptPt) { + for (MapMarker marker : mapMarkers) { + if (marker.wptPt == wptPt) { + return marker; + } + } + return null; + } + + @Nullable + public MapMarker getMapMarker(FavouritePoint favouritePoint) { + for (MapMarker marker : mapMarkers) { + if (marker.favouritePoint == favouritePoint) { + return marker; + } + } + return null; + } + + @Nullable + public MapMarker getMapMarker(@NonNull LatLon latLon) { + for (MapMarker marker : mapMarkers) { + if (marker.point != null && marker.point.equals(latLon)) { + return marker; + } + } + return null; + } + + @Nullable + public MapMarker getMapMarker(@NonNull String mapObjectName, @NonNull LatLon latLon) { + for (MapMarker marker : mapMarkers) { + if (marker.mapObjectName != null + && marker.point != null + && marker.mapObjectName.equals(mapObjectName) + && MapUtils.getDistance(latLon, marker.point) < 15) { + return marker; + } + } + return null; + } + + private void addNewMarkerIfNeeded(@NonNull MapMarkersGroup group, + @NonNull List groupMarkers, + @NonNull LatLon latLon, + @NonNull String name, + @Nullable FavouritePoint favouritePoint, + @Nullable WptPt wptPt) { + boolean exists = false; + + Iterator iterator = groupMarkers.iterator(); + while (iterator.hasNext()) { + MapMarker marker = iterator.next(); + if (marker.id.equals(group.getId() + name)) { + exists = true; + marker.favouritePoint = favouritePoint; + marker.wptPt = wptPt; + if (!marker.history && !marker.point.equals(latLon)) { + marker.point = latLon; + updateMapMarker(marker, true); + } + iterator.remove(); + break; + } + } + + if (!exists) { + // TODO create method add1Marker + addMarkers(Collections.singletonList(latLon), + Collections.singletonList(new PointDescription(POINT_TYPE_MAP_MARKER, name)), + group, + Collections.singletonList(favouritePoint), + Collections.singletonList(wptPt), + null); + } + } + + private void removeOldMarkersIfPresent(List markers) { + if (!markers.isEmpty()) { + boolean needRefresh = false; + for (MapMarker marker : markers) { + if (!marker.history) { + removeMarker(marker, false); + needRefresh = true; + } + } + if (needRefresh) { + reorderActiveMarkersIfNeeded(); + refresh(); + } + } + } + + public void moveMapMarkerToHistory(MapMarker marker) { + if (marker != null) { + cancelPointAddressRequests(marker.point); + markersDbHelper.moveMarkerToHistory(marker); + removeFromMapMarkersList(marker); + marker.history = true; + marker.nextKey = MapMarkersDbHelper.HISTORY_NEXT_VALUE; + addToMapMarkersHistoryList(marker); + reorderActiveMarkersIfNeeded(); + sortMarkers(mapMarkersHistory, true, BY_DATE_ADDED_DESC); + refresh(); + } + } + + public void addMarkers(List markers) { + if (markers != null) { + markersDbHelper.addMarkers(markers); + addToMapMarkersList(markers); + reorderActiveMarkersIfNeeded(); + addMarkersToGroups(markers); + refresh(); + } + } + + public void addMarker(MapMarker marker) { + if (marker != null) { + markersDbHelper.addMarker(marker); + if (marker.history) { + addToMapMarkersHistoryList(marker); + sortMarkers(mapMarkersHistory, true, BY_DATE_ADDED_DESC); + } else { + addToMapMarkersList(marker); + reorderActiveMarkersIfNeeded(); + } + addMarkerToGroup(marker); + refresh(); + } + } + + public void restoreMarkerFromHistory(MapMarker marker, int position) { + if (marker != null) { + markersDbHelper.restoreMapMarkerFromHistory(marker); + removeFromMapMarkersHistoryList(marker); + marker.history = false; + addToMapMarkersList(position, marker); + reorderActiveMarkersIfNeeded(); + sortMarkers(mapMarkersHistory, true, BY_DATE_ADDED_DESC); + refresh(); + } + } + + public void restoreMarkersFromHistory(List markers) { + if (markers != null) { + for (MapMarker marker : markers) { + markersDbHelper.restoreMapMarkerFromHistory(marker); + marker.history = false; + } + removeFromMapMarkersHistoryList(markers); + addToMapMarkersList(markers); + reorderActiveMarkersIfNeeded(); + sortMarkers(mapMarkersHistory, true, BY_DATE_ADDED_DESC); + updateGroups(); + refresh(); + } + } + + public void removeMarker(MapMarker marker) { + removeMarker(marker, true); + } + + private void removeMarker(MapMarker marker, boolean refresh) { + if (marker != null) { + markersDbHelper.removeMarker(marker); + if (marker.history) { + removeFromMapMarkersHistoryList(marker); + } else { + removeFromMapMarkersList(marker); + } + removeMarkerFromGroup(marker); + if (refresh) { + refresh(); + } + } + } + + @Nullable + public MapMarker getFirstMapMarker() { + return mapMarkers.size() > 0 ? mapMarkers.get(0) : null; + } + + public void deselectAllActiveMarkers() { + for (MapMarker m : mapMarkers) { + if (m.selected) { + m.selected = false; + markersDbHelper.updateMarker(m); + } + } + } + + public void selectAllActiveMarkers() { + for (MapMarker m : mapMarkers) { + if (!m.selected) { + m.selected = true; + markersDbHelper.updateMarker(m); + } + } + } + + public List getSelectedMarkers() { + List list = new ArrayList<>(); + for (MapMarker m : mapMarkers) { + if (m.selected) { + list.add(m); + } + } + return list; + } + + public int getSelectedMarkersCount() { + int res = 0; + for (MapMarker m : mapMarkers) { + if (m.selected) { + res++; + } + } + return res; + } + + public void addSelectedMarkersToTop(@NonNull List markers) { + List markersToRemove = new ArrayList<>(); + for (MapMarker m : mapMarkers) { + if (m.selected) { + if (!markers.contains(m)) { + return; + } + markersToRemove.add(m); + } + } + if (markersToRemove.size() != markers.size()) { + return; + } + + removeFromMapMarkersList(markersToRemove); + addToMapMarkersList(0, markers); + reorderActiveMarkersIfNeeded(); + } + + public List getSelectedMarkersLatLon() { + List list = new ArrayList<>(); + for (MapMarker m : this.mapMarkers) { + if (m.selected) { + list.add(m.point); + } + } + return list; + } + + public void reverseActiveMarkersOrder() { + cancelAddressRequests(); + Collections.reverse(mapMarkers); + reorderActiveMarkersIfNeeded(); + } + + public void moveAllActiveMarkersToHistory() { + cancelAddressRequests(); + long timestamp = System.currentTimeMillis(); + markersDbHelper.moveAllActiveMarkersToHistory(timestamp); + for (MapMarker marker : mapMarkers) { + marker.visitedDate = timestamp; + marker.history = true; + marker.nextKey = MapMarkersDbHelper.HISTORY_NEXT_VALUE; + } + addToMapMarkersHistoryList(mapMarkers); + mapMarkers = new ArrayList<>(); + sortMarkers(mapMarkersHistory, true, BY_DATE_ADDED_DESC); + updateGroups(); + refresh(); + } + + public void addMapMarker(@NonNull LatLon point, @Nullable PointDescription historyName) { + addMapMarkers(Collections.singletonList(point), Collections.singletonList(historyName), null); + } + + public void addMapMarker(@NonNull LatLon point, + @Nullable PointDescription historyName, + @Nullable String mapObjectName) { + addMarkers(Collections.singletonList(point), + Collections.singletonList(historyName), + null, + null, + null, + Collections.singletonList(mapObjectName)); + } + + public void addMapMarkers(@NonNull List points, + @NonNull List historyNames, + @Nullable MapMarkersGroup group) { + addMarkers(points, historyNames, group, null, null, null); + } + + private void addMarkers(@NonNull List points, + @NonNull List historyNames, + @Nullable MapMarkersGroup group, + @Nullable List favouritePoints, + @Nullable List wptPts, + @Nullable List mapObjNames) { + if (points.size() > 0) { + int colorIndex = -1; + List addedMarkers = new ArrayList<>(); + for (int i = 0; i < points.size(); i++) { + LatLon point = points.get(i); + PointDescription historyName = historyNames.get(i); + FavouritePoint favouritePoint = favouritePoints == null ? null : favouritePoints.get(i); + WptPt wptPt = wptPts == null ? null : wptPts.get(i); + String mapObjName = mapObjNames == null ? null : mapObjNames.get(i); + final PointDescription pointDescription; + if (historyName == null) { + pointDescription = new PointDescription(PointDescription.POINT_TYPE_LOCATION, ""); + } else { + pointDescription = historyName; + } + if (pointDescription.isLocation() && Algorithms.isEmpty(pointDescription.getName())) { + pointDescription.setName(PointDescription.getSearchAddressStr(ctx)); + } + if (colorIndex == -1) { + if (mapMarkers.size() > 0) { + colorIndex = (mapMarkers.get(0).colorIndex + 1) % MAP_MARKERS_COLORS_COUNT; + } else { + colorIndex = 0; + } + } else { + colorIndex = (colorIndex + 1) % MAP_MARKERS_COLORS_COUNT; + } + + MapMarker marker = new MapMarker(point, pointDescription, colorIndex, false, 0); + if (group != null) { + marker.id = group.getId() + marker.getName(ctx); + // TODO ??????? + if (markersDbHelper.getMarker(marker.id) != null) { + continue; + } + marker.groupName = group.getName(); + marker.groupKey = group.getId(); + } + marker.history = false; + marker.nextKey = MapMarkersDbHelper.TAIL_NEXT_VALUE; + marker.favouritePoint = favouritePoint; + marker.wptPt = wptPt; + marker.mapObjectName = mapObjName; + markersDbHelper.addMarker(marker); + addToMapMarkersList(0, marker); + addedMarkers.add(marker); + reorderActiveMarkersIfNeeded(); + lookupAddress(marker); + } + addMarkersToGroups(addedMarkers); + } + } + + public void updateMapMarker(MapMarker marker, boolean refresh) { + if (marker != null) { + markersDbHelper.updateMarker(marker); + if (refresh) { + refresh(); + } + } + } + + public void moveMarkerToTop(MapMarker marker) { + int i = mapMarkers.indexOf(marker); + if (i != -1 && mapMarkers.size() > 1) { + removeFromMapMarkersList(marker); + addToMapMarkersList(0, marker); + reorderActiveMarkersIfNeeded(); + refresh(); + } + } + + public void moveMapMarker(MapMarker marker, LatLon latLon) { + if (marker != null) { + LatLon point = new LatLon(latLon.getLatitude(), latLon.getLongitude()); + int index = mapMarkers.indexOf(marker); + if (index != -1) { + mapMarkers.get(index).point = point; + } + marker.point = point; + markersDbHelper.updateMarker(marker); + reorderActiveMarkersIfNeeded(); + refresh(); + lookupAddress(marker); + } + } + + public void addSyncListener(OnGroupSyncedListener listener) { + syncListeners.add(listener); + } + + public void removeSyncListener(OnGroupSyncedListener listener) { + syncListeners.remove(listener); + } + + public void addListener(MapMarkerChangedListener l) { + if (!listeners.contains(l)) { + listeners.add(l); + } + } + + public void removeListener(MapMarkerChangedListener l) { + listeners.remove(l); + } + + private void refreshMarker(final MapMarker marker) { + ctx.runInUIThread(new Runnable() { + @Override + public void run() { + for (MapMarkerChangedListener l : listeners) { + l.onMapMarkerChanged(marker); + } + } + }); + } + + private void refresh() { + ctx.runInUIThread(new Runnable() { + @Override + public void run() { + for (MapMarkerChangedListener l : listeners) { + l.onMapMarkersChanged(); + } + } + }); + } + + public String generateGpx(String fileName) { + final File dir = ctx.getAppPath(IndexConstants.GPX_INDEX_DIR + "/map markers"); + if (!dir.exists()) { + dir.mkdirs(); + } + File fout = new File(dir, fileName + ".gpx"); + int ind = 1; + while (fout.exists()) { + fout = new File(dir, fileName + "_" + (++ind) + ".gpx"); + } + GPXFile file = new GPXFile(); + for (MapMarker marker : mapMarkers) { + WptPt wpt = new WptPt(); + wpt.lat = marker.getLatitude(); + wpt.lon = marker.getLongitude(); + wpt.setColor(ctx.getResources().getColor(MapMarker.getColorId(marker.colorIndex))); + wpt.name = marker.getOnlyName(); + file.addPoint(wpt); + } + GPXUtilities.writeGpxFile(fout, file, ctx); + return fout.getAbsolutePath(); + } + + // --------------------------------------------------------------------------------------------- + + // accessors to active markers: + + private void addToMapMarkersList(MapMarker marker) { + addToMapMarkersList(mapMarkers.size(), marker); + } + + private void addToMapMarkersList(int position, MapMarker marker) { + List copyList = new ArrayList<>(mapMarkers); + copyList.add(position, marker); + mapMarkers = copyList; + } + + private void addToMapMarkersList(List markers) { + addToMapMarkersList(mapMarkers.size(), markers); + } + + private void addToMapMarkersList(int position, List markers) { + List copyList = new ArrayList<>(mapMarkers); + copyList.addAll(position, markers); + mapMarkers = copyList; + } + + private void removeFromMapMarkersList(MapMarker marker) { + List copyList = new ArrayList<>(mapMarkers); + copyList.remove(marker); + mapMarkers = copyList; + } + + private void removeFromMapMarkersList(List markers) { + List copyList = new ArrayList<>(mapMarkers); + copyList.removeAll(markers); + mapMarkers = copyList; + } + + // accessors to history markers: + + private void addToMapMarkersHistoryList(MapMarker marker) { + List copyList = new ArrayList<>(mapMarkersHistory); + copyList.add(marker); + mapMarkersHistory = copyList; + } + + private void addToMapMarkersHistoryList(List markers) { + List copyList = new ArrayList<>(mapMarkersHistory); + copyList.addAll(markers); + mapMarkersHistory = copyList; + } + + private void removeFromMapMarkersHistoryList(MapMarker marker) { + List copyList = new ArrayList<>(mapMarkersHistory); + copyList.remove(marker); + mapMarkersHistory = copyList; + } + + private void removeFromMapMarkersHistoryList(List markers) { + List copyList = new ArrayList<>(mapMarkersHistory); + copyList.removeAll(markers); + mapMarkersHistory = copyList; + } + + // accessors to markers groups: + + private void addToGroupsList(MapMarkersGroup group) { + List copyList = new ArrayList<>(mapMarkersGroups); + copyList.add(group); + mapMarkersGroups = copyList; + } + + private void removeFromGroupsList(MapMarkersGroup group) { + List copyList = new ArrayList<>(mapMarkersGroups); + copyList.remove(group); + mapMarkersGroups = copyList; + } + + // --------------------------------------------------------------------------------------------- + + // classes and interfaces: + public interface MapMarkerChangedListener { void onMapMarkerChanged(MapMarker mapMarker); @@ -73,9 +1013,223 @@ public class MapMarkersHelper { } public interface OnGroupSyncedListener { + + void onSyncStarted(); + void onSyncDone(); } + private class SyncGroupTask extends AsyncTask { + + private MapMarkersGroup group; + + SyncGroupTask(MapMarkersGroup group) { + this.group = group; + } + + @Override + protected void onPreExecute() { + if (!syncListeners.isEmpty()) { + ctx.runInUIThread(new Runnable() { + @Override + public void run() { + for (OnGroupSyncedListener listener : syncListeners) { + listener.onSyncStarted(); + } + } + }); + } + } + + @Override + protected Void doInBackground(Void... voids) { + runGroupSynchronization(); + return null; + } + + // TODO extract method from Asynctask to Helper directly + private void runGroupSynchronization() { + if (!isGroupSynced(group.getId())) { + return; + } + + List groupMarkers = new ArrayList<>(group.getMarkers()); + + if (group.getType() == MapMarkersGroup.FAVORITES_TYPE) { + FavoriteGroup favGroup = ctx.getFavorites().getGroup(group.getName()); + if (favGroup == null) { + return; + } + group.visible = favGroup.visible; + if (!group.isVisible() || group.isDisabled()) { + removeGroupActiveMarkers(group, true); + return; + } + + for (FavouritePoint fp : favGroup.points) { + addNewMarkerIfNeeded(group, groupMarkers, new LatLon(fp.getLatitude(), fp.getLongitude()), fp.getName(), fp, null); + } + + + } else if (group.getType() == MapMarkersGroup.GPX_TYPE) { + GpxSelectionHelper gpxHelper = ctx.getSelectedGpxHelper(); + File file = new File(group.getId()); + if (!file.exists()) { + return; + } + + SelectedGpxFile selectedGpxFile = gpxHelper.getSelectedFileByPath(group.getId()); + GPXFile gpx = selectedGpxFile == null ? null : selectedGpxFile.getGpxFile(); + group.visible = gpx != null; + if (!group.isVisible() || group.isDisabled()) { + removeGroupActiveMarkers(group, true); + return; + } + + boolean addAll = group.wptCategories == null || group.wptCategories.isEmpty(); + List gpxPoints = new ArrayList<>(gpx.getPoints()); + for (WptPt pt : gpxPoints) { + if (addAll || group.wptCategories.contains(pt.category) + || (pt.category == null && group.wptCategories.contains(""))) { + addNewMarkerIfNeeded(group, groupMarkers, new LatLon(pt.lat, pt.lon), pt.name, null, pt); + } + } + } + + removeOldMarkersIfPresent(groupMarkers); + } + + @Override + protected void onPostExecute(Void aVoid) { + if (!syncListeners.isEmpty()) { + ctx.runInUIThread(new Runnable() { + @Override + public void run() { + for (OnGroupSyncedListener listener : syncListeners) { + listener.onSyncDone(); + } + } + }); + } + } + } + + public static class MapMarkersGroup { + + public static final int FAVORITES_TYPE = 0; + public static final int GPX_TYPE = 1; + + public static final String MARKERS_SYNC_GROUP_ID = "markers_sync_group_id"; + + private String id; + private String name; + private int type = -1; + private Set wptCategories; + private long creationDate; + private boolean disabled; + private boolean visible = true; + private List markers = new ArrayList<>(); + // TODO should be removed from this class: + private GroupHeader header; + private ShowHideHistoryButton showHideHistoryButton; + + public MapMarkersGroup() { + + } + + public MapMarkersGroup(@NonNull String id, @NonNull String name, int type) { + this.id = id; + this.name = name; + this.type = type; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public int getType() { + return type; + } + + public void setWptCategories(Set wptCategories) { + this.wptCategories = wptCategories; + } + + public boolean isDisabled() { + return disabled; + } + + public void setDisabled(boolean disabled) { + this.disabled = disabled; + } + + public boolean isVisible() { + return visible; + } + + public List getMarkers() { + return markers; + } + + public GroupHeader getGroupHeader() { + return header; + } + + public ShowHideHistoryButton getShowHideHistoryButton() { + return showHideHistoryButton; + } + + @Nullable + public String getWptCategoriesString() { + if (wptCategories != null) { + return Algorithms.encodeStringSet(wptCategories); + } + return null; + } + + public List getActiveMarkers() { + List markers = new ArrayList<>(this.markers); + List activeMarkers = new ArrayList<>(markers.size()); + for (MapMarker marker : markers) { + if (!marker.history) { + activeMarkers.add(marker); + } + } + return activeMarkers; + } + + public List getHistoryMarkers() { + List historyMarkers = new ArrayList<>(); + for (MapMarker marker : markers) { + if (marker.history) { + historyMarkers.add(marker); + } + } + return historyMarkers; + } + } + + public static class ShowHideHistoryButton { + public boolean showHistory; + } + + public static class GroupHeader { + private int iconRes; + private MapMarkersGroup group; + + public int getIconRes() { + return iconRes; + } + + public MapMarkersGroup getGroup() { + return group; + } + } + public static class MapMarker implements LocationPoint { private static int[] colors; @@ -96,8 +1250,7 @@ public class MapMarkersHelper { public FavouritePoint favouritePoint; public String mapObjectName; - public MapMarker(LatLon point, PointDescription name, int colorIndex, - boolean selected, int index) { + public MapMarker(LatLon point, PointDescription name, int colorIndex, boolean selected, int index) { this.point = point; this.pointDescription = name; this.colorIndex = colorIndex; @@ -106,8 +1259,7 @@ public class MapMarkersHelper { } public PointDescription getPointDescription(Context ctx) { - return new PointDescription(POINT_TYPE_MAP_MARKER, ctx.getString(R.string.map_marker), - getOnlyName()); + return new PointDescription(POINT_TYPE_MAP_MARKER, ctx.getString(R.string.map_marker), getOnlyName()); } public String getName(Context ctx) { @@ -158,9 +1310,7 @@ public class MapMarkersHelper { MapMarker mapMarker = (MapMarker) o; - if (colorIndex != mapMarker.colorIndex) return false; - return point.equals(mapMarker.point); - + return colorIndex == mapMarker.colorIndex && point.equals(mapMarker.point); } @Override @@ -195,1336 +1345,4 @@ public class MapMarkersHelper { return (colorIndex >= 0 && colorIndex < colorsIds.length) ? colorsIds[colorIndex] : colorsIds[0]; } } - - @Nullable - public MarkersSyncGroup getGroup(String id) { - return markersDbHelper.getGroup(id); - } - - public static class MarkersSyncGroup { - - public static final int FAVORITES_TYPE = 0; - public static final int GPX_TYPE = 1; - - public static final String MARKERS_SYNC_GROUP_ID = "markers_sync_group_id"; - - private String id; - private String name; - private int type; - private int color; - - public MarkersSyncGroup(@NonNull String id, @NonNull String name, int type, int color) { - this.id = id; - this.name = name; - this.type = type; - this.color = color; - } - - public MarkersSyncGroup(@NonNull String id, @NonNull String name, int type) { - this.id = id; - this.name = name; - this.type = type; - this.color = -1; - } - - public String getId() { - return id; - } - - public String getName() { - return name; - } - - public int getType() { - return type; - } - - public int getColor() { - return color; - } - - public void setColor(int color) { - this.color = color; - } - } - - public MapMarkersHelper(OsmandApplication ctx) { - this.ctx = ctx; - settings = ctx.getSettings(); - markersDbHelper = ctx.getMapMarkersDbHelper(); - planRouteContext = new MarkersPlanRouteContext(ctx); - startFromMyLocation = settings.ROUTE_MAP_MARKERS_START_MY_LOC.get(); - removeDisabledGroups(); - loadMarkers(); - createMapMarkersGroups(); - } - - public MarkersPlanRouteContext getPlanRouteContext() { - return planRouteContext; - } - - public boolean isStartFromMyLocation() { - return startFromMyLocation; - } - - public void setStartFromMyLocation(boolean startFromMyLocation) { - this.startFromMyLocation = startFromMyLocation; - settings.ROUTE_MAP_MARKERS_START_MY_LOC.set(startFromMyLocation); - } - - public void lookupAddressAll() { - for (MapMarker mapMarker : mapMarkers) { - lookupAddress(mapMarker); - } - for (MapMarker mapMarker : mapMarkersHistory) { - lookupAddress(mapMarker); - } - } - - private void loadMarkers() { - mapMarkers = new ArrayList<>(); - mapMarkersHistory = new ArrayList<>(); - - List activeMarkers = markersDbHelper.getActiveMarkers(); - addToMapMarkersList(activeMarkers); - reorderActiveMarkersIfNeeded(); - - List markersHistory = markersDbHelper.getMarkersHistory(); - sortMarkers(markersHistory, true, BY_DATE_ADDED_DESC); - addToMapMarkersHistoryList(markersHistory); - - if (!ctx.isApplicationInitializing()) { - lookupAddressAll(); - } - } - - private void removeFromMapMarkersList(List markers) { - List copyList = new ArrayList<>(mapMarkers); - copyList.removeAll(markers); - mapMarkers = copyList; - } - - private void removeFromMapMarkersList(MapMarker marker) { - List copyList = new ArrayList<>(mapMarkers); - copyList.remove(marker); - mapMarkers = copyList; - } - - private void addToMapMarkersList(MapMarker marker) { - addToMapMarkersList(mapMarkers.size(), marker); - } - - private void addToMapMarkersList(int position, MapMarker marker) { - List copyList = new ArrayList<>(mapMarkers); - copyList.add(position, marker); - mapMarkers = copyList; - } - - private void addToMapMarkersList(List markers) { - addToMapMarkersList(mapMarkers.size(), markers); - } - - private void addToMapMarkersList(int position, List markers) { - List copyList = new ArrayList<>(mapMarkers); - copyList.addAll(position, markers); - mapMarkers = copyList; - } - - private void removeFromMapMarkersHistoryList(MapMarker marker) { - List copyList = new ArrayList<>(mapMarkersHistory); - copyList.remove(marker); - mapMarkersHistory = copyList; - } - - private void addToMapMarkersHistoryList(MapMarker marker) { - addToMapMarkersHistoryList(mapMarkersHistory.size(), marker); - } - - private void addToMapMarkersHistoryList(int position, MapMarker marker) { - List copyList = new ArrayList<>(mapMarkersHistory); - copyList.add(position, marker); - mapMarkersHistory = copyList; - } - - private void addToMapMarkersHistoryList(int position, List markers) { - List copyList = new ArrayList<>(mapMarkersHistory); - copyList.addAll(position, markers); - mapMarkersHistory = copyList; - } - - private void addToMapMarkersHistoryList(List markers) { - addToMapMarkersHistoryList(mapMarkersHistory.size(), markers); - } - - private void removeFromGroupsList(MapMarkersGroup group) { - List copyList = new ArrayList<>(mapMarkersGroups); - copyList.remove(group); - mapMarkersGroups = copyList; - } - - private void addToGroupsList(int position, MapMarkersGroup group) { - List copyList = new ArrayList<>(mapMarkersGroups); - copyList.add(position, group); - mapMarkersGroups = copyList; - } - - private void addToGroupsList(MapMarkersGroup group) { - addToGroupsList(mapMarkersGroups.size(), group); - } - - public void reorderActiveMarkersIfNeeded() { - if (!mapMarkers.isEmpty()) { - if (mapMarkers.size() > 1) { - for (int i = 0; i < mapMarkers.size() - 1; i++) { - MapMarker first = mapMarkers.get(i); - MapMarker second = mapMarkers.get(i + 1); - if (!first.nextKey.equals(second.id)) { - markersDbHelper.changeActiveMarkerPosition(first, second); - first.nextKey = second.id; - } - } - } - - MapMarker tail = mapMarkers.get(mapMarkers.size() - 1); - if (!tail.nextKey.equals(MapMarkersDbHelper.TAIL_NEXT_VALUE)) { - markersDbHelper.changeActiveMarkerPosition(tail, null); - } - } - } - - private void sortMarkers(List markers, final boolean visited, final @MapMarkersSortByDef int sortByMode) { - sortMarkers(markers, visited, sortByMode, null); - } - - private void sortMarkers(List markers, final boolean visited, - final @MapMarkersSortByDef int sortByMode, @Nullable final LatLon location) { - Collections.sort(markers, new Comparator() { - @Override - public int compare(MapMarker mapMarker1, MapMarker mapMarker2) { - if (sortByMode == BY_DATE_ADDED_DESC || sortByMode == BY_DATE_ADDED_ASC) { - long t1 = visited ? mapMarker1.visitedDate : mapMarker1.creationDate; - long t2 = visited ? mapMarker2.visitedDate : mapMarker2.creationDate; - if (t1 > t2) { - return sortByMode == BY_DATE_ADDED_DESC ? -1 : 1; - } else if (t1 == t2) { - return 0; - } else { - return sortByMode == BY_DATE_ADDED_DESC ? 1 : -1; - } - } else if (location != null && (sortByMode == BY_DISTANCE_DESC || sortByMode == BY_DISTANCE_ASC)) { - int d1 = (int) MapUtils.getDistance(location, mapMarker1.getLatitude(), mapMarker1.getLongitude()); - int d2 = (int) MapUtils.getDistance(location, mapMarker2.getLatitude(), mapMarker2.getLongitude()); - if (d1 > d2) { - return sortByMode == BY_DISTANCE_DESC ? -1 : 1; - } else if (d1 == d2) { - return 0; - } else { - return sortByMode == BY_DISTANCE_DESC ? 1 : -1; - } - } else { - String n1 = mapMarker1.getName(ctx); - String n2 = mapMarker2.getName(ctx); - return n1.compareToIgnoreCase(n2); - } - } - }); - } - - public void sortMarkers(final @MapMarkersSortByDef int sortByMode, LatLon location) { - sortMarkers(getMapMarkers(), false, sortByMode, location); - reorderActiveMarkersIfNeeded(); - } - - private void lookupAddress(final MapMarker mapMarker) { - if (mapMarker != null && mapMarker.pointDescription.isSearchingAddress(ctx)) { - cancelPointAddressRequests(mapMarker.point); - GeocodingLookupService.AddressLookupRequest lookupRequest = - new GeocodingLookupService.AddressLookupRequest(mapMarker.point, new GeocodingLookupService.OnAddressLookupResult() { - @Override - public void geocodingDone(String address) { - if (Algorithms.isEmpty(address)) { - mapMarker.pointDescription.setName(PointDescription.getAddressNotFoundStr(ctx)); - } else { - mapMarker.pointDescription.setName(address); - } - markersDbHelper.updateMarker(mapMarker); - refreshMarker(mapMarker); - } - }, null); - ctx.getGeocodingLookupService().lookupAddress(lookupRequest); - } - } - - public boolean isGroupSynced(String id) { - return markersDbHelper.getGroup(id) != null; - } - - public boolean isGroupDisabled(String id) { - return markersDbHelper.isGroupDisabled(id); - } - - public void syncAllGroupsAsync() { - List groups = markersDbHelper.getAllGroups(); - for (MarkersSyncGroup gr : groups) { - syncGroupAsync(gr); - } - } - - public void syncGroupAsync(@NonNull MarkersSyncGroup group) { - syncGroupAsync(group, true, null); - } - - public void syncGroupAsync(@NonNull MarkersSyncGroup group, boolean enabled) { - syncGroupAsync(group, enabled, null); - } - - public void syncGroupAsync(@NonNull MarkersSyncGroup group, @Nullable OnGroupSyncedListener groupSyncedListener) { - syncGroupAsync(group, true, groupSyncedListener); - } - - public void syncGroupAsync(@NonNull final MarkersSyncGroup group, final boolean enabled, @Nullable final OnGroupSyncedListener groupSyncedListener) { - ctx.runInUIThread(new Runnable() { - @Override - public void run() { - SyncGroupTask syncGroupTask = new SyncGroupTask(group, enabled, groupSyncedListener); - syncGroupTask.executeOnExecutor(executorService); - } - }); - } - - private class SyncGroupTask extends AsyncTask { - - private MarkersSyncGroup group; - private boolean enabled; - private OnGroupSyncedListener listener; - - SyncGroupTask(MarkersSyncGroup group, boolean enabled, OnGroupSyncedListener listener) { - this.group = group; - this.enabled = enabled; - this.listener = listener; - } - - @Override - protected Void doInBackground(Void... voids) { - runGroupSynchronization(); - return null; - } - - private void runGroupSynchronization() { - if (!isGroupSynced(group.getId())) { - return; - } - - List dbMarkers = markersDbHelper.getMarkersFromGroup(group); - - if (group.getType() == MarkersSyncGroup.FAVORITES_TYPE) { - FavoriteGroup favGroup = ctx.getFavorites().getGroup(group.getName()); - if (favGroup == null) { - return; - } - if (!favGroup.visible) { - removeActiveMarkersFromSyncGroup(group.getId()); - removeActiveMarkersFromGroup(group.getId()); - return; - } - if (group.getColor() == -1) { - group.setColor(favGroup.color); - } - - for (FavouritePoint fp : favGroup.points) { - addNewMarkerIfNeeded(group, dbMarkers, new LatLon(fp.getLatitude(), fp.getLongitude()), fp.getName(), enabled, fp, null); - } - - removeOldMarkersIfNeeded(dbMarkers); - } else if (group.getType() == MarkersSyncGroup.GPX_TYPE) { - GpxSelectionHelper gpxHelper = ctx.getSelectedGpxHelper(); - File file = new File(group.getId()); - if (!file.exists()) { - return; - } - - SelectedGpxFile selectedGpxFile = gpxHelper.getSelectedFileByPath(group.getId()); - GPXFile gpx = selectedGpxFile == null ? null : selectedGpxFile.getGpxFile(); - if (gpx == null) { - removeActiveMarkersFromSyncGroup(group.getId()); - removeActiveMarkersFromGroup(group.getId()); - return; - } - - List gpxPoints = new ArrayList<>(gpx.getPoints()); - int defColor = ContextCompat.getColor(ctx, R.color.marker_red); - for (WptPt pt : gpxPoints) { - group.setColor(pt.getColor(defColor)); - addNewMarkerIfNeeded(group, dbMarkers, new LatLon(pt.lat, pt.lon), pt.name, enabled, null, pt); - } - - removeOldMarkersIfNeeded(dbMarkers); - } - } - - @Override - protected void onPostExecute(Void aVoid) { - if (listener != null) { - ctx.runInUIThread(new Runnable() { - @Override - public void run() { - listener.onSyncDone(); - } - }); - } - } - } - - public boolean isSynced(SelectedGpxFile gpxFile) { - GPXFile gpx = gpxFile.getGpxFile(); - List gpxPoints = gpx.getPoints(); - for (WptPt wptPt : gpxPoints) { - MapMarker mapMarker = getMapMarker(wptPt); - if (mapMarker != null) { - return true; - } - } - return false; - } - - public boolean isSynced(FavouritePoint favouritePoint) { - MapMarker mapMarker = getMapMarker(favouritePoint); - return mapMarker != null; - } - - public MapMarker getMapMarker(WptPt wptPt) { - for (MapMarker marker : mapMarkers) { - if (marker.wptPt == wptPt) { - return marker; - } - } - return null; - } - - public MapMarker getMapMarker(FavouritePoint favouritePoint) { - for (MapMarker marker : mapMarkers) { - if (marker.favouritePoint == favouritePoint) { - return marker; - } - } - return null; - } - - @Nullable - public MapMarker getMapMarker(@NonNull LatLon latLon) { - for (MapMarker marker : mapMarkers) { - if (marker.point != null && marker.point.equals(latLon)) { - return marker; - } - } - return null; - } - - @Nullable - public MapMarker getMapMarker(@NonNull String mapObjectName, @NonNull LatLon latLon) { - for (MapMarker marker : mapMarkers) { - if (marker.mapObjectName != null && marker.mapObjectName.equals(mapObjectName) && marker.point != null) { - if (MapUtils.getDistance(latLon, marker.point) < 15) { - return marker; - } - } - } - return null; - } - - private void addNewMarkerIfNeeded(@NonNull MarkersSyncGroup group, - @NonNull List markers, - @NonNull LatLon latLon, - @NonNull String name, - boolean enabled, - @Nullable FavouritePoint favouritePoint, - @Nullable WptPt wptPt) { - boolean exists = false; - - for (MapMarker marker : markers) { - if (marker.id.equals(group.getId() + name)) { - exists = true; - for (MapMarker m : mapMarkers) { - if (m.id.equals(marker.id)) { - m.favouritePoint = favouritePoint; - m.wptPt = wptPt; - if (!marker.history && !marker.point.equals(latLon)) { - m.point = latLon; - updateMapMarker(m, true); - } - break; - } - } - markers.remove(marker); - break; - } - } - - if (!exists) { - addMarkers(Collections.singletonList(latLon), - Collections.singletonList(new PointDescription(POINT_TYPE_MAP_MARKER, name)), - group, enabled, Collections.singletonList(favouritePoint), Collections.singletonList(wptPt), null); - } - } - - private void removeOldMarkersIfNeeded(List markers) { - if (!markers.isEmpty()) { - boolean needRefresh = false; - for (MapMarker marker : markers) { - if (!marker.history) { - markersDbHelper.removeMarker(marker, false); - removeFromMapMarkersList(marker); - removeMarkerFromGroup(marker); - needRefresh = true; - } - } - if (needRefresh) { - reorderActiveMarkersIfNeeded(); - refresh(); - } - } - } - - public void moveMapMarkerToHistory(MapMarker marker) { - if (marker != null) { - cancelPointAddressRequests(marker.point); - markersDbHelper.moveMarkerToHistory(marker); - removeFromMapMarkersList(marker); - marker.history = true; - marker.nextKey = MapMarkersDbHelper.HISTORY_NEXT_VALUE; - addToMapMarkersHistoryList(marker); - reorderActiveMarkersIfNeeded(); - sortMarkers(mapMarkersHistory, true, BY_DATE_ADDED_DESC); - refresh(); - } - } - - public void addMarkers(List markers) { - if (markers != null) { - markersDbHelper.addMarkers(markers); - addToMapMarkersList(markers); - reorderActiveMarkersIfNeeded(); - addMarkersToGroups(markers, true); - refresh(); - } - } - - public void addMarker(MapMarker marker) { - if (marker != null) { - markersDbHelper.addMarker(marker); - if (marker.history) { - addToMapMarkersHistoryList(marker); - sortMarkers(mapMarkersHistory, true, BY_DATE_ADDED_DESC); - } else { - addToMapMarkersList(marker); - reorderActiveMarkersIfNeeded(); - } - addMarkerToGroup(marker); - refresh(); - } - } - - public void restoreMarkerFromHistory(MapMarker marker, int position) { - if (marker != null) { - markersDbHelper.restoreMapMarkerFromHistory(marker); - removeFromMapMarkersHistoryList(marker); - marker.history = false; - addToMapMarkersList(position, marker); - reorderActiveMarkersIfNeeded(); - sortMarkers(mapMarkersHistory, true, BY_DATE_ADDED_DESC); - refresh(); - } - } - - public void restoreMarkersFromHistory(List markers) { - if (markers != null) { - for (MapMarker marker : markers) { - markersDbHelper.restoreMapMarkerFromHistory(marker); - removeFromMapMarkersHistoryList(marker); - marker.history = false; - addToMapMarkersList(marker); - } - reorderActiveMarkersIfNeeded(); - sortMarkers(mapMarkersHistory, true, BY_DATE_ADDED_DESC); - updateGroups(); - refresh(); - } - } - - public void removeMarker(MapMarker marker) { - if (marker != null) { - boolean history = marker.history; - markersDbHelper.removeMarker(marker, history); - if (history) { - removeFromMapMarkersHistoryList(marker); - } else { - removeFromMapMarkersList(marker); - } - removeMarkerFromGroup(marker); - refresh(); - } - } - - public List getMapMarkers() { - return mapMarkers; - } - - public MapMarker getFirstMapMarker() { - if (mapMarkers.size() > 0) { - return mapMarkers.get(0); - } else { - return null; - } - } - - public List getMapMarkersHistory() { - return mapMarkersHistory; - } - - public void deselectAllActiveMarkers() { - for (MapMarker m : mapMarkers) { - if (m.selected) { - m.selected = false; - markersDbHelper.updateMarker(m); - } - } - } - - public void selectAllActiveMarkers() { - for (MapMarker m : mapMarkers) { - if (!m.selected) { - m.selected = true; - markersDbHelper.updateMarker(m); - } - } - } - - public List getSelectedMarkers() { - List list = new ArrayList<>(); - for (MapMarker m : this.mapMarkers) { - if (m.selected) { - list.add(m); - } - } - return list; - } - - public int getSelectedMarkersCount() { - int res = 0; - for (MapMarker m : this.mapMarkers) { - if (m.selected) { - res++; - } - } - return res; - } - - public void addSelectedMarkersToTop(@NonNull List markers) { - List markersToRemove = new ArrayList<>(); - for (MapMarker m : mapMarkers) { - if (m.selected) { - if (!markers.contains(m)) { - return; - } - markersToRemove.add(m); - } - } - if (markersToRemove.size() != markers.size()) { - return; - } - - removeFromMapMarkersList(markersToRemove); - addToMapMarkersList(0, markers); - reorderActiveMarkersIfNeeded(); - } - - public List getActiveMarkersLatLon() { - List list = new ArrayList<>(); - for (MapMarker m : this.mapMarkers) { - list.add(m.point); - } - return list; - } - - public List getSelectedMarkersLatLon() { - List list = new ArrayList<>(); - for (MapMarker m : this.mapMarkers) { - if (m.selected) { - list.add(m.point); - } - } - return list; - } - - public List getMarkersHistoryLatLon() { - List list = new ArrayList<>(); - for (MapMarker m : this.mapMarkersHistory) { - list.add(m.point); - } - return list; - } - - public void reverseActiveMarkersOrder() { - cancelAddressRequests(); - Collections.reverse(mapMarkers); - reorderActiveMarkersIfNeeded(); - } - - public void moveAllActiveMarkersToHistory() { - cancelAddressRequests(); - long timestamp = System.currentTimeMillis(); - markersDbHelper.moveAllActiveMarkersToHistory(timestamp); - for (MapMarker marker : mapMarkers) { - marker.visitedDate = timestamp; - marker.history = true; - marker.nextKey = MapMarkersDbHelper.HISTORY_NEXT_VALUE; - } - addToMapMarkersHistoryList(mapMarkers); - mapMarkers = new ArrayList<>(); - sortMarkers(mapMarkersHistory, true, BY_DATE_ADDED_DESC); - updateGroups(); - refresh(); - } - - public void removeMarkersHistory() { - cancelAddressRequests(); - markersDbHelper.clearAllMarkersHistory(); - mapMarkersHistory = new ArrayList<>(); - refresh(); - removeHistoryMarkersFromGroups(); - } - - public void addMarkersSyncGroup(MarkersSyncGroup group) { - if (group != null) { - if (markersDbHelper.getGroup(group.getId()) == null) { - markersDbHelper.addGroup(group.getId(), group.getName(), group.getType()); - } - } - } - - public void removeMarkersSyncGroup(String id) { - if (id != null) { - markersDbHelper.removeMarkersSyncGroup(id); - removeActiveMarkersFromSyncGroup(id); - MapMarkersGroup group = getMapMarkerGroupByKey(id); - if (group != null) { - removeFromGroupsList(group); - } - } - } - - public void removeDisabledGroups() { - markersDbHelper.removeDisabledGroups(); - } - - public void updateGroupDisabled(@NonNull MapMarkersGroup group, boolean disabled) { - String id = group.getGroupKey(); - if (id != null) { - markersDbHelper.updateSyncGroupDisabled(id, disabled); - updateSyncGroupDisabled(group, disabled); - } - } - - private void updateSyncGroupDisabled(@NonNull MapMarkersGroup group, boolean disabled) { - List groupMarkers = new ArrayList<>(group.getMarkers()); - for (MapMarker marker : groupMarkers) { - if (marker.history) { - if (disabled) { - removeFromMapMarkersHistoryList(marker); - } else { - addToMapMarkersHistoryList(marker); - } - } else { - if (disabled) { - removeFromMapMarkersList(marker); - } else { - addToMapMarkersList(marker); - } - } - } - reorderActiveMarkersIfNeeded(); - sortMarkers(mapMarkersHistory, true, BY_DATE_ADDED_DESC); - refresh(); - } - - public void removeActiveMarkersFromSyncGroup(String syncGroupId) { - if (syncGroupId != null) { - markersDbHelper.removeActiveMarkersFromSyncGroup(syncGroupId); - List copyList = new ArrayList<>(mapMarkers); - for (int i = 0; i < copyList.size(); i++) { - MapMarker marker = copyList.get(i); - String groupKey = marker.groupKey; - if (groupKey != null && groupKey.equals(syncGroupId)) { - removeFromMapMarkersList(marker); - } - } - reorderActiveMarkersIfNeeded(); - refresh(); - } - } - - public void addMapMarker(@NonNull LatLon point, @Nullable PointDescription historyName) { - addMarkers(Collections.singletonList(point), Collections.singletonList(historyName), null, true); - } - - public void addMapMarker(@NonNull LatLon point, @Nullable PointDescription historyName, @Nullable String mapObjectName) { - addMarkers(Collections.singletonList(point), Collections.singletonList(historyName), null, - true, null, null, Collections.singletonList(mapObjectName)); - } - - public void addMapMarkers(@NonNull List points, @NonNull List historyNames, @Nullable MarkersSyncGroup group) { - addMarkers(points, historyNames, group, true); - } - - private void addMarkers(@NonNull List points, @NonNull List historyNames, @Nullable MarkersSyncGroup group, boolean enabled) { - addMarkers(points, historyNames, group, enabled, null, null, null); - } - - private void addMarkers(@NonNull List points, @NonNull List historyNames, @Nullable MarkersSyncGroup group, - boolean enabled, @Nullable List favouritePoints, @Nullable List wptPts, @Nullable List mapObjNames) { - if (points.size() > 0) { - int colorIndex = -1; - List addedMarkers = new ArrayList<>(); - for (int i = 0; i < points.size(); i++) { - LatLon point = points.get(i); - PointDescription historyName = historyNames.get(i); - FavouritePoint favouritePoint = favouritePoints == null ? null : favouritePoints.get(i); - WptPt wptPt = wptPts == null ? null : wptPts.get(i); - String mapObjName = mapObjNames == null ? null : mapObjNames.get(i); - final PointDescription pointDescription; - if (historyName == null) { - pointDescription = new PointDescription(PointDescription.POINT_TYPE_LOCATION, ""); - } else { - pointDescription = historyName; - } - if (pointDescription.isLocation() && Algorithms.isEmpty(pointDescription.getName())) { - pointDescription.setName(PointDescription.getSearchAddressStr(ctx)); - } - if (colorIndex == -1) { - if (mapMarkers.size() > 0) { - colorIndex = (mapMarkers.get(0).colorIndex + 1) % MAP_MARKERS_COLORS_COUNT; - } else { - colorIndex = 0; - } - } else { - colorIndex = (colorIndex + 1) % MAP_MARKERS_COLORS_COUNT; - } - - MapMarker marker = new MapMarker(point, pointDescription, colorIndex, false, 0); - if (group != null) { - marker.id = group.getId() + marker.getName(ctx); - if (markersDbHelper.getMarker(marker.id) != null) { - continue; - } - marker.groupName = group.getName(); - marker.groupKey = group.getId(); - } - marker.history = false; - marker.nextKey = MapMarkersDbHelper.TAIL_NEXT_VALUE; - marker.favouritePoint = favouritePoint; - marker.wptPt = wptPt; - marker.mapObjectName = mapObjName; - markersDbHelper.addMarker(marker); - if (enabled) { - addToMapMarkersList(0, marker); - } - addedMarkers.add(marker); - reorderActiveMarkersIfNeeded(); - lookupAddress(marker); - } - addMarkersToGroups(addedMarkers, enabled); - } - } - - public void updateMapMarker(MapMarker marker, boolean refresh) { - if (marker != null) { - markersDbHelper.updateMarker(marker); - if (refresh) { - refresh(); - } - } - } - - public void moveMarkerToTop(MapMarker marker) { - int i = mapMarkers.indexOf(marker); - if (i != -1 && mapMarkers.size() > 1) { - removeFromMapMarkersList(marker); - addToMapMarkersList(0, marker); - reorderActiveMarkersIfNeeded(); - refresh(); - } - } - - public void moveMapMarker(MapMarker marker, LatLon latLon) { - if (marker != null) { - LatLon point = new LatLon(latLon.getLatitude(), latLon.getLongitude()); - int index = mapMarkers.indexOf(marker); - if (index != -1) { - mapMarkers.get(index).point = point; - } - marker.point = point; - markersDbHelper.updateMarker(marker); - reorderActiveMarkersIfNeeded(); - refresh(); - lookupAddress(marker); - } - } - - public void addListener(MapMarkerChangedListener l) { - if (!listeners.contains(l)) { - listeners.add(l); - } - } - - public void removeListener(MapMarkerChangedListener l) { - listeners.remove(l); - } - - private void refreshMarker(final MapMarker marker) { - ctx.runInUIThread(new Runnable() { - @Override - public void run() { - for (MapMarkerChangedListener l : listeners) { - l.onMapMarkerChanged(marker); - } - } - }); - } - - private void refreshMarkers() { - ctx.runInUIThread(new Runnable() { - @Override - public void run() { - for (MapMarkerChangedListener l : listeners) { - l.onMapMarkersChanged(); - } - } - }); - } - - public void refresh() { - refreshMarkers(); - } - - private void cancelAddressRequests() { - List list = getActiveMarkersLatLon(); - for (LatLon latLon : list) { - cancelPointAddressRequests(latLon); - } - list = getMarkersHistoryLatLon(); - for (LatLon latLon : list) { - cancelPointAddressRequests(latLon); - } - } - - private void cancelPointAddressRequests(LatLon latLon) { - if (latLon != null) { - ctx.getGeocodingLookupService().cancel(latLon); - } - } - - public String generateGpx(String fileName) { - final File dir = ctx.getAppPath(IndexConstants.GPX_INDEX_DIR + "/map markers"); - if (!dir.exists()) { - dir.mkdirs(); - } - File fout = new File(dir, fileName + ".gpx"); - int ind = 1; - while (fout.exists()) { - fout = new File(dir, fileName + "_" + (++ind) + ".gpx"); - } - GPXFile file = new GPXFile(); - for (MapMarker marker : mapMarkers) { - WptPt wpt = new WptPt(); - wpt.lat = marker.getLatitude(); - wpt.lon = marker.getLongitude(); - wpt.setColor(ctx.getResources().getColor(MapMarker.getColorId(marker.colorIndex))); - wpt.name = marker.getOnlyName(); - file.addPoint(wpt); - } - GPXUtilities.writeGpxFile(fout, file, ctx); - return fout.getAbsolutePath(); - } - - private void removeHistoryMarkersFromGroups() { - for (MapMarkersGroup markersGroup : mapMarkersGroups) { - List activeMarkers = new ArrayList<>(); - for (MapMarker marker : markersGroup.getMarkers()) { - if (!marker.history) { - activeMarkers.add(marker); - } - } - markersGroup.setMarkers(activeMarkers); - updateGroup(markersGroup); - } - } - - private void removeActiveMarkersFromGroup(String groupId) { - MapMarkersGroup group = getMapMarkerGroupByKey(groupId); - if (group != null) { - List markers = group.getMarkers(); - List historyMarkers = new ArrayList<>(); - for (MapMarker marker : markers) { - if (marker.history) { - historyMarkers.add(marker); - } - } - group.setMarkers(historyMarkers); - updateGroup(group); - } - } - - public void updateGroups() { - for (MapMarkersGroup group : mapMarkersGroups) { - updateGroup(group); - } - } - - public void updateGroup(MapMarkersGroup mapMarkersGroup) { - if (mapMarkersGroup.getMarkers().size() == 0) { - removeFromGroupsList(mapMarkersGroup); - return; - } - int historyMarkersCount = mapMarkersGroup.getHistoryMarkers().size(); - ShowHideHistoryButton showHideHistoryButton = mapMarkersGroup.getShowHideHistoryButton(); - if (showHideHistoryButton != null) { - if (historyMarkersCount == 0) { - mapMarkersGroup.setShowHideHistoryButton(null); - } - } else if (historyMarkersCount > 0) { - showHideHistoryButton = new ShowHideHistoryButton(); - showHideHistoryButton.setShowHistory(false); - showHideHistoryButton.setMarkerGroup(mapMarkersGroup); - mapMarkersGroup.setShowHideHistoryButton(showHideHistoryButton); - } - } - - private void addMarkersToGroups(@NonNull List markers, boolean enabled) { - List groups = new ArrayList<>(); - for (int i = 0; i < markers.size(); i++) { - MapMarkersGroup group = addMarkerToGroup(markers.get(i)); - if (group != null && !groups.contains(group)) { - groups.add(group); - } - } - if (!enabled) { - for (MapMarkersGroup mapMarkersGroup : groups) { - mapMarkersGroup.setDisabled(true); - updateGroupDisabled(mapMarkersGroup, true); - } - } - } - - private MapMarkersGroup addMarkerToGroup(MapMarker marker) { - if (marker != null) { - MapMarkersGroup mapMarkersGroup = getMapMarkerGroupByName(marker.groupName); - if (mapMarkersGroup != null) { - mapMarkersGroup.getMarkers().add(marker); - updateGroup(mapMarkersGroup); - if (mapMarkersGroup.getName() == null) { - sortMarkers(mapMarkersGroup.getMarkers(), false, BY_DATE_ADDED_DESC); - } - } else { - mapMarkersGroup = createMapMarkerGroup(marker); - mapMarkersGroup.getMarkers().add(marker); - createHeaderAndHistoryButtonInGroup(mapMarkersGroup); - } - return mapMarkersGroup; - } - return null; - } - - private MapMarkersGroup createMapMarkerGroup(@NonNull MapMarker marker) { - MapMarkersGroup group = new MapMarkersGroup(); - if (marker.groupName != null) { - group.setName(marker.groupName); - group.setGroupKey(marker.groupKey); - MapMarkersHelper.MarkersSyncGroup syncGroup = getGroup(marker.groupKey); - if (syncGroup != null) { - group.setType(syncGroup.getType()); - } else { - group.setType(MarkersSyncGroup.FAVORITES_TYPE); - } - group.setColor(MapMarker.getColorId(marker.colorIndex)); - } - group.setCreationDate(marker.creationDate); - addToGroupsList(group); - sortGroups(); - return group; - } - - private void createHeaderAndHistoryButtonInGroup(@NonNull MapMarkersGroup group) { - if (group.getName() != null) { - GroupHeader header = new GroupHeader(); - int type = group.getType(); - if (type != -1) { - header.setIconRes(type == MapMarkersHelper.MarkersSyncGroup.FAVORITES_TYPE ? R.drawable.ic_action_fav_dark : R.drawable.ic_action_polygom_dark); - } - header.setGroup(group); - group.setGroupHeader(header); - updateGroup(group); - } - } - - private void removeMarkerFromGroup(MapMarker marker) { - if (marker != null) { - MapMarkersGroup mapMarkersGroup = getMapMarkerGroupByName(marker.groupName); - if (mapMarkersGroup != null) { - mapMarkersGroup.getMarkers().remove(marker); - updateGroup(mapMarkersGroup); - } - } - } - - public List getMapMarkersGroups() { - return mapMarkersGroups; - } - - private void createMapMarkersGroups() { - List markers = new ArrayList<>(); - markers.addAll(mapMarkers); - markers.addAll(mapMarkersHistory); - - Map groupsMap = new LinkedHashMap<>(); - MapMarkersGroup noGroup = null; - for (MapMarker marker : markers) { - String groupName = marker.groupName; - if (groupName == null) { - if (noGroup == null) { - noGroup = new MapMarkersGroup(); - noGroup.setCreationDate(marker.creationDate); - } - noGroup.getMarkers().add(marker); - } else { - MapMarkersGroup group = groupsMap.get(groupName); - if (group == null) { - group = new MapMarkersGroup(); - group.setName(marker.groupName); - group.setGroupKey(marker.groupKey); - MapMarkersHelper.MarkersSyncGroup syncGroup = getGroup(marker.groupKey); - if (syncGroup != null) { - group.setType(syncGroup.getType()); - } else { - group.setType(MarkersSyncGroup.FAVORITES_TYPE); - } - group.setColor(MapMarker.getColorId(marker.colorIndex)); - group.setCreationDate(marker.creationDate); - groupsMap.put(groupName, group); - } else { - long markerCreationDate = marker.creationDate; - if (markerCreationDate < group.getCreationDate()) { - group.setCreationDate(markerCreationDate); - } - } - group.getMarkers().add(marker); - } - } - mapMarkersGroups = new ArrayList<>(groupsMap.values()); - if (noGroup != null) { - addToGroupsList(noGroup); - } - sortGroups(); - - for (MapMarkersGroup group : mapMarkersGroups) { - createHeaderAndHistoryButtonInGroup(group); - } - } - - private void sortGroups() { - if (mapMarkersGroups.size() > 0) { - MapMarkersGroup noGroup = null; - for (int i = 0; i < mapMarkersGroups.size(); i++) { - MapMarkersGroup group = mapMarkersGroups.get(i); - if (group.getName() == null) { - sortMarkers(group.getMarkers(), false, BY_DATE_ADDED_DESC); - removeFromGroupsList(group); - noGroup = group; - } - } - Collections.sort(mapMarkersGroups, new Comparator() { - @Override - public int compare(MapMarkersGroup group1, MapMarkersGroup group2) { - long t1 = group1.getCreationDate(); - long t2 = group2.getCreationDate(); - if (t1 > t2) { - return -1; - } else if (t1 == t2) { - return 0; - } else { - return 1; - } - } - }); - if (noGroup != null) { - addToGroupsList(0, noGroup); - } - } - } - - public MapMarkersGroup getMapMarkerGroupByName(String name) { - for (MapMarkersGroup group : mapMarkersGroups) { - if ((name == null && group.getName() == null) - || (group.getName() != null && group.getName().equals(name))) { - return group; - } - } - return null; - } - - public MapMarkersGroup getMapMarkerGroupByKey(String key) { - for (MapMarkersGroup group : mapMarkersGroups) { - if ((key == null && group.getGroupKey() == null) - || (group.getGroupKey() != null && group.getGroupKey().equals(key))) { - return group; - } - } - return null; - } - - public static class MapMarkersGroup { - private String name; - private String groupKey; - private GroupHeader header; - private int type = -1; - private List markers = new ArrayList<>(); - private long creationDate; - private ShowHideHistoryButton showHideHistoryButton; - private int color; - private boolean disabled; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getGroupKey() { - return groupKey; - } - - public void setGroupKey(String groupKey) { - this.groupKey = groupKey; - } - - public GroupHeader getGroupHeader() { - return header; - } - - public void setGroupHeader(GroupHeader header) { - this.header = header; - } - - public int getType() { - return type; - } - - public void setType(int type) { - this.type = type; - } - - public List getActiveMarkers() { - List markers = new ArrayList<>(this.markers); - List activeMarkers = new ArrayList<>(markers.size()); - for (MapMarker marker : markers) { - if (!marker.history) { - activeMarkers.add(marker); - } - } - return activeMarkers; - } - - public List getHistoryMarkers() { - List historyMarkers = new ArrayList<>(); - for (MapMarker marker : markers) { - if (marker.history) { - historyMarkers.add(marker); - } - } - return historyMarkers; - } - - public List getMarkers() { - return markers; - } - - public void setMarkers(List markers) { - this.markers = markers; - } - - public long getCreationDate() { - return creationDate; - } - - public void setCreationDate(long creationDate) { - this.creationDate = creationDate; - } - - public ShowHideHistoryButton getShowHideHistoryButton() { - return showHideHistoryButton; - } - - public void setShowHideHistoryButton(ShowHideHistoryButton showHideHistoryButton) { - this.showHideHistoryButton = showHideHistoryButton; - } - - public int getColor() { - return color; - } - - public void setColor(int color) { - this.color = color; - } - - public boolean isDisabled() { - return disabled; - } - - public void setDisabled(boolean disabled) { - this.disabled = disabled; - } - } - - public static class ShowHideHistoryButton { - private boolean showHistory; - private MapMarkersGroup group; - - public boolean isShowHistory() { - return showHistory; - } - - public void setShowHistory(boolean showHistory) { - this.showHistory = showHistory; - } - - public MapMarkersGroup getMapMarkerGroup() { - return group; - } - - public void setMarkerGroup(MapMarkersGroup group) { - this.group = group; - } - } - - public static class GroupHeader { - private int iconRes; - private MapMarkersGroup group; - - public int getIconRes() { - return iconRes; - } - - public void setIconRes(int iconRes) { - this.iconRes = iconRes; - } - - public MapMarkersGroup getGroup() { - return group; - } - - public void setGroup(MapMarkersGroup group) { - this.group = group; - } - } } diff --git a/OsmAnd/src/net/osmand/plus/activities/EditFavoriteGroupDialogFragment.java b/OsmAnd/src/net/osmand/plus/activities/EditFavoriteGroupDialogFragment.java index 435d360211..bf55a108d1 100644 --- a/OsmAnd/src/net/osmand/plus/activities/EditFavoriteGroupDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/activities/EditFavoriteGroupDialogFragment.java @@ -23,7 +23,7 @@ import net.osmand.AndroidUtils; import net.osmand.plus.FavouritesDbHelper; import net.osmand.plus.FavouritesDbHelper.FavoriteGroup; import net.osmand.plus.MapMarkersHelper; -import net.osmand.plus.MapMarkersHelper.MarkersSyncGroup; +import net.osmand.plus.MapMarkersHelper.MapMarkersGroup; import net.osmand.plus.OsmandApplication; import net.osmand.plus.R; import net.osmand.plus.base.MenuBottomSheetDialogFragment; @@ -156,49 +156,30 @@ public class EditFavoriteGroupDialogFragment extends MenuBottomSheetDialogFragme if (group.points.size() > 0) { items.add(new DividerHalfItem(getContext())); - } - final MapMarkersHelper markersHelper = app.getMapMarkersHelper(); - final MarkersSyncGroup syncGroup = - new MarkersSyncGroup(group.name, group.name, MarkersSyncGroup.FAVORITES_TYPE, group.color); - boolean groupSyncedWithMarkers = markersHelper.isGroupSynced(syncGroup.getId()); + final MapMarkersHelper markersHelper = app.getMapMarkersHelper(); + final MapMarkersGroup markersGr = markersHelper.getOrCreateGroup(this.group); + final boolean synced = markersHelper.isGroupSynced(markersGr.getId()); - if (app.getSettings().USE_MAP_MARKERS.get() && group.points.size() > 0 && !groupSyncedWithMarkers) { - BaseBottomSheetItem addToMarkersItem = new SimpleBottomSheetItem.Builder() - .setIcon(getContentIcon(R.drawable.ic_action_flag_dark)) - .setTitle(getString(R.string.shared_string_add_to_map_markers)) - .setLayoutId(R.layout.bottom_sheet_item_simple) - .setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - markersHelper.addMarkersSyncGroup(syncGroup); - markersHelper.syncGroupAsync(syncGroup); - dismiss(); - MapActivity.launchMapActivityMoveToTop(getActivity()); - } - }) - .create(); - items.add(addToMarkersItem); - } - - if (app.getSettings().USE_MAP_MARKERS.get() && groupSyncedWithMarkers) { - BaseBottomSheetItem removeFromMarkersItem = new SimpleBottomSheetItem.Builder() - .setIcon(getContentIcon(R.drawable.ic_action_delete_dark)) - .setTitle(getString(R.string.remove_from_map_markers)) + BaseBottomSheetItem markersGroupItem = new SimpleBottomSheetItem.Builder() + .setIcon(getContentIcon(synced ? R.drawable.ic_action_delete_dark : R.drawable.ic_action_flag_dark)) + .setTitle(getString(synced ? R.string.remove_from_map_markers : R.string.shared_string_add_to_map_markers)) .setLayoutId(R.layout.bottom_sheet_item_simple) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - markersHelper.removeMarkersSyncGroup(syncGroup.getId()); + if (synced) { + markersHelper.removeMarkersGroup(markersGr); + } else { + markersHelper.syncWithMarkers(markersGr); + } dismiss(); MapActivity.launchMapActivityMoveToTop(getActivity()); } }) .create(); - items.add(removeFromMarkersItem); - } + items.add(markersGroupItem); - if (group.points.size() > 0) { BaseBottomSheetItem shareItem = new SimpleBottomSheetItem.Builder() .setIcon(getContentIcon(R.drawable.ic_action_gshare_dark)) .setTitle(getString(R.string.shared_string_share)) @@ -208,7 +189,7 @@ public class EditFavoriteGroupDialogFragment extends MenuBottomSheetDialogFragme public void onClick(View view) { FavoritesTreeFragment fragment = getFavoritesTreeFragment(); if (fragment != null) { - fragment.shareFavorites(group); + fragment.shareFavorites(EditFavoriteGroupDialogFragment.this.group); } dismiss(); } diff --git a/OsmAnd/src/net/osmand/plus/activities/FavoritesTreeFragment.java b/OsmAnd/src/net/osmand/plus/activities/FavoritesTreeFragment.java index b54979ac83..1f0d11b19d 100644 --- a/OsmAnd/src/net/osmand/plus/activities/FavoritesTreeFragment.java +++ b/OsmAnd/src/net/osmand/plus/activities/FavoritesTreeFragment.java @@ -36,12 +36,11 @@ import net.osmand.data.PointDescription; import net.osmand.plus.FavouritesDbHelper; import net.osmand.plus.FavouritesDbHelper.FavoriteGroup; import net.osmand.plus.MapMarkersHelper; -import net.osmand.plus.MapMarkersHelper.MarkersSyncGroup; +import net.osmand.plus.MapMarkersHelper.MapMarkersGroup; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandSettings; import net.osmand.plus.R; -import net.osmand.plus.TargetPointsHelper; import net.osmand.plus.base.FavoriteImageDrawable; import net.osmand.plus.base.OsmandExpandableListFragment; import net.osmand.plus.helpers.AndroidUiHelper; @@ -58,7 +57,6 @@ import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; -import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; @@ -347,13 +345,8 @@ public class FavoritesTreeFragment extends OsmandExpandableListFragment { R.drawable.ic_action_plus, MenuItemCompat.SHOW_AS_ACTION_ALWAYS); createMenuItem(menu, SHARE_ID, R.string.shared_string_share, R.drawable.ic_action_gshare_dark, R.drawable.ic_action_gshare_dark, MenuItemCompat.SHOW_AS_ACTION_ALWAYS); - if (getSettings().USE_MAP_MARKERS.get()) { - createMenuItem(menu, SELECT_MAP_MARKERS_ID, R.string.select_map_markers, R.drawable.ic_action_flag_dark, - R.drawable.ic_action_flag_dark, MenuItemCompat.SHOW_AS_ACTION_ALWAYS); - } else { - createMenuItem(menu, SELECT_MAP_MARKERS_ID, R.string.select_destination_and_intermediate_points, R.drawable.ic_action_intermediate, - R.drawable.ic_action_intermediate, MenuItemCompat.SHOW_AS_ACTION_ALWAYS); - } + createMenuItem(menu, SELECT_MAP_MARKERS_ID, R.string.select_map_markers, R.drawable.ic_action_flag_dark, + R.drawable.ic_action_flag_dark, MenuItemCompat.SHOW_AS_ACTION_ALWAYS); createMenuItem(menu, DELETE_ID, R.string.shared_string_delete, R.drawable.ic_action_delete_dark, R.drawable.ic_action_delete_dark, MenuItemCompat.SHOW_AS_ACTION_ALWAYS); // createMenuItem(menu, EXPORT_ID, R.string.shared_string_export, R.drawable.ic_action_gsave_light, @@ -383,15 +376,9 @@ public class FavoritesTreeFragment extends OsmandExpandableListFragment { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { enableSelectionMode(true); - if (getSettings().USE_MAP_MARKERS.get()) { - createMenuItem(menu, SELECT_MAP_MARKERS_ACTION_MODE_ID, R.string.select_map_markers, - R.drawable.ic_action_flag_dark, R.drawable.ic_action_flag_dark, - MenuItemCompat.SHOW_AS_ACTION_IF_ROOM); - } else { - createMenuItem(menu, SELECT_MAP_MARKERS_ACTION_MODE_ID, R.string.select_destination_and_intermediate_points, - R.drawable.ic_action_intermediate, R.drawable.ic_action_intermediate, - MenuItemCompat.SHOW_AS_ACTION_IF_ROOM); - } + createMenuItem(menu, SELECT_MAP_MARKERS_ACTION_MODE_ID, R.string.select_map_markers, + R.drawable.ic_action_flag_dark, R.drawable.ic_action_flag_dark, + MenuItemCompat.SHOW_AS_ACTION_IF_ROOM); favoritesSelected.clear(); groupsToDelete.clear(); favouritesAdapter.notifyDataSetInvalidated(); @@ -424,40 +411,25 @@ public class FavoritesTreeFragment extends OsmandExpandableListFragment { private void selectMapMarkersImpl() { if (getSelectedFavoritesCount() > 0) { - if (getSettings().USE_MAP_MARKERS.get()) { - MapMarkersHelper markersHelper = getMyApplication().getMapMarkersHelper(); - List points = new LinkedList<>(); - List names = new LinkedList<>(); - for (Map.Entry> entry : favoritesSelected.entrySet()) { - FavoriteGroup favGr = helper.getGroup(entry.getKey()); - MarkersSyncGroup syncGr = - new MarkersSyncGroup(favGr.name, favGr.name, MarkersSyncGroup.FAVORITES_TYPE, favGr.color); - if (entry.getValue().size() == favGr.points.size()) { - markersHelper.addMarkersSyncGroup(syncGr); - markersHelper.syncGroupAsync(syncGr); - } else { - for (FavouritePoint fp : entry.getValue()) { - points.add(new LatLon(fp.getLatitude(), fp.getLongitude())); - names.add(new PointDescription(PointDescription.POINT_TYPE_MAP_MARKER, fp.getName())); - } - markersHelper.addMapMarkers(points, names, syncGr); - points.clear(); - names.clear(); + MapMarkersHelper markersHelper = getMyApplication().getMapMarkersHelper(); + List points = new ArrayList<>(); + List names = new ArrayList<>(); + for (Map.Entry> entry : favoritesSelected.entrySet()) { + FavoriteGroup favGr = helper.getGroup(entry.getKey()); + MapMarkersGroup markersGr = markersHelper.getOrCreateGroup(favGr); + if (entry.getValue().size() == favGr.points.size()) { + markersHelper.syncWithMarkers(markersGr); + } else { + for (FavouritePoint fp : entry.getValue()) { + points.add(new LatLon(fp.getLatitude(), fp.getLongitude())); + names.add(new PointDescription(PointDescription.POINT_TYPE_MAP_MARKER, fp.getName())); } + markersHelper.addMapMarkers(points, names, markersGr); + points.clear(); + names.clear(); } - MapActivity.launchMapActivityMoveToTop(getActivity()); - } else { - final TargetPointsHelper targetPointsHelper = getMyApplication().getTargetPointsHelper(); - for (FavouritePoint fp : getSelectedFavorites()) { - targetPointsHelper.navigateToPoint(new LatLon(fp.getLatitude(), fp.getLongitude()), false, - targetPointsHelper.getIntermediatePoints().size() + 1, - new PointDescription(PointDescription.POINT_TYPE_FAVORITE, fp.getName())); - } - if (getMyApplication().getRoutingHelper().isRouteCalculated()) { - targetPointsHelper.updateRouteAndRefresh(true); - } - IntermediatePointsDialog.openIntermediatePointsDialog(getActivity(), getMyApplication(), true); } + MapActivity.launchMapActivityMoveToTop(getActivity()); } } diff --git a/OsmAnd/src/net/osmand/plus/activities/MapActivity.java b/OsmAnd/src/net/osmand/plus/activities/MapActivity.java index 8bad7a1d68..5f4dbdd064 100644 --- a/OsmAnd/src/net/osmand/plus/activities/MapActivity.java +++ b/OsmAnd/src/net/osmand/plus/activities/MapActivity.java @@ -719,7 +719,7 @@ public class MapActivity extends OsmandActionBarActivity implements DownloadEven if (intent.hasExtra(MapMarkersDialogFragment.OPEN_MAP_MARKERS_GROUPS)) { Bundle openMapMarkersGroupsExtra = intent.getBundleExtra(MapMarkersDialogFragment.OPEN_MAP_MARKERS_GROUPS); if (openMapMarkersGroupsExtra != null) { - MapMarkersDialogFragment.showInstance(this, openMapMarkersGroupsExtra.getString(MapMarkersHelper.MarkersSyncGroup.MARKERS_SYNC_GROUP_ID)); + MapMarkersDialogFragment.showInstance(this, openMapMarkersGroupsExtra.getString(MapMarkersHelper.MapMarkersGroup.MARKERS_SYNC_GROUP_ID)); } setIntent(null); } diff --git a/OsmAnd/src/net/osmand/plus/base/bottomsheetmenu/BaseBottomSheetItem.java b/OsmAnd/src/net/osmand/plus/base/bottomsheetmenu/BaseBottomSheetItem.java index ace5f0dfd2..8917d22975 100644 --- a/OsmAnd/src/net/osmand/plus/base/bottomsheetmenu/BaseBottomSheetItem.java +++ b/OsmAnd/src/net/osmand/plus/base/bottomsheetmenu/BaseBottomSheetItem.java @@ -26,6 +26,10 @@ public class BaseBottomSheetItem { return view; } + public Object getTag() { + return tag; + } + public BaseBottomSheetItem(View view, @LayoutRes int layoutId, Object tag, diff --git a/OsmAnd/src/net/osmand/plus/base/bottomsheetmenu/BottomSheetItemWithCompoundButton.java b/OsmAnd/src/net/osmand/plus/base/bottomsheetmenu/BottomSheetItemWithCompoundButton.java index ab4835b8bf..07bcb93895 100644 --- a/OsmAnd/src/net/osmand/plus/base/bottomsheetmenu/BottomSheetItemWithCompoundButton.java +++ b/OsmAnd/src/net/osmand/plus/base/bottomsheetmenu/BottomSheetItemWithCompoundButton.java @@ -8,6 +8,7 @@ import android.support.v4.widget.CompoundButtonCompat; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; import net.osmand.plus.OsmandApplication; import net.osmand.plus.R; @@ -16,9 +17,14 @@ public class BottomSheetItemWithCompoundButton extends BottomSheetItemWithDescri private boolean checked; private ColorStateList buttonTintList; + private OnCheckedChangeListener onCheckedChangeListener; private CompoundButton compoundButton; + public boolean isChecked() { + return checked; + } + public BottomSheetItemWithCompoundButton(View customView, @LayoutRes int layoutId, Object tag, @@ -31,7 +37,8 @@ public class BottomSheetItemWithCompoundButton extends BottomSheetItemWithDescri CharSequence description, @ColorRes int descriptionColorId, boolean checked, - ColorStateList buttonTintList) { + ColorStateList buttonTintList, + OnCheckedChangeListener onCheckedChangeListener) { super(customView, layoutId, tag, @@ -45,6 +52,7 @@ public class BottomSheetItemWithCompoundButton extends BottomSheetItemWithDescri descriptionColorId); this.checked = checked; this.buttonTintList = buttonTintList; + this.onCheckedChangeListener = onCheckedChangeListener; } public void setChecked(boolean checked) { @@ -58,12 +66,14 @@ public class BottomSheetItemWithCompoundButton extends BottomSheetItemWithDescri compoundButton = (CompoundButton) view.findViewById(R.id.compound_button); compoundButton.setChecked(checked); CompoundButtonCompat.setButtonTintList(compoundButton, buttonTintList); + compoundButton.setOnCheckedChangeListener(onCheckedChangeListener); } public static class Builder extends BottomSheetItemWithDescription.Builder { protected boolean checked; protected ColorStateList buttonTintList; + protected OnCheckedChangeListener onCheckedChangeListener; public Builder setChecked(boolean checked) { this.checked = checked; @@ -75,6 +85,11 @@ public class BottomSheetItemWithCompoundButton extends BottomSheetItemWithDescri return this; } + public Builder setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) { + this.onCheckedChangeListener = onCheckedChangeListener; + return this; + } + public BottomSheetItemWithCompoundButton create() { return new BottomSheetItemWithCompoundButton(customView, layoutId, @@ -88,7 +103,8 @@ public class BottomSheetItemWithCompoundButton extends BottomSheetItemWithDescri description, descriptionColorId, checked, - buttonTintList); + buttonTintList, + onCheckedChangeListener); } } } diff --git a/OsmAnd/src/net/osmand/plus/helpers/MapMarkerDialogHelper.java b/OsmAnd/src/net/osmand/plus/helpers/MapMarkerDialogHelper.java index 4d7360b6a1..2d7efeef18 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/MapMarkerDialogHelper.java +++ b/OsmAnd/src/net/osmand/plus/helpers/MapMarkerDialogHelper.java @@ -1,473 +1,35 @@ package net.osmand.plus.helpers; import android.content.Context; -import android.content.DialogInterface; import android.graphics.drawable.Drawable; -import android.graphics.drawable.ShapeDrawable; -import android.graphics.drawable.shapes.Shape; -import android.support.v7.app.AlertDialog; -import android.support.v7.widget.PopupMenu; -import android.text.format.DateFormat; -import android.view.MenuItem; import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.Button; import android.widget.CheckBox; -import android.widget.ImageButton; import android.widget.ImageView; -import android.widget.ListView; import android.widget.TextView; import net.osmand.AndroidUtils; -import net.osmand.IndexConstants; import net.osmand.Location; import net.osmand.data.LatLon; -import net.osmand.data.PointDescription; -import net.osmand.plus.ApplicationMode; -import net.osmand.plus.GPXUtilities; -import net.osmand.plus.GPXUtilities.GPXFile; -import net.osmand.plus.GPXUtilities.WptPt; -import net.osmand.plus.IconsCache; -import net.osmand.plus.MapMarkersHelper; import net.osmand.plus.MapMarkersHelper.MapMarker; import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmandApplication; import net.osmand.plus.R; -import net.osmand.plus.activities.MapActivity; -import net.osmand.plus.dashboard.DashLocationFragment; -import net.osmand.plus.dashboard.DashboardOnMap; -import net.osmand.plus.dialogs.DirectionsDialogs; import net.osmand.plus.views.DirectionDrawable; -import net.osmand.plus.views.controls.DynamicListView; -import net.osmand.plus.views.controls.ListDividerShape; -import net.osmand.plus.views.controls.StableArrayAdapter; -import net.osmand.util.MapUtils; -import java.io.File; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; import java.util.Date; -import java.util.List; import java.util.Locale; public class MapMarkerDialogHelper { - public static final int ACTIVE_MARKERS = 0; - public static final int MY_LOCATION = 10; - public static final int MARKERS_HISTORY = 100; - private MapActivity mapActivity; - private OsmandApplication app; - private MapMarkersHelper markersHelper; - private MapMarkersDialogHelperCallbacks helperCallbacks; - private boolean sorted; - private boolean nightMode; - private boolean selectionMode; - - private boolean useCenter; - private LatLon myLoc; - private LatLon loc; - private Float heading; - private int screenOrientation; - private boolean reloading; - private long lastUpdateTime; - private boolean allSelected; - - public interface MapMarkersDialogHelperCallbacks { - void reloadAdapter(); - - void deleteMapMarker(int position); - - void showMarkersRouteOnMap(); - } - - public MapMarkerDialogHelper(MapActivity mapActivity) { - this.mapActivity = mapActivity; - app = mapActivity.getMyApplication(); - markersHelper = app.getMapMarkersHelper(); - } - - public void setHelperCallbacks(MapMarkersDialogHelperCallbacks helperCallbacks) { - this.helperCallbacks = helperCallbacks; - } - - public boolean isInSelectionMode() { - return selectionMode; - } - - public boolean hasActiveMarkers() { - return markersHelper.getMapMarkers().size() > 0; - } - - public void setSelectionMode(boolean selectionMode) { - this.selectionMode = selectionMode; - } - - public boolean isNightMode() { - return nightMode; - } - - public void setNightMode(boolean nightMode) { - this.nightMode = nightMode; - } - - public boolean isSorted() { - return sorted; - } - - public void setSorted(boolean sorted) { - this.sorted = sorted; - } - - public AdapterView.OnItemClickListener getItemClickListener(final ArrayAdapter listAdapter) { - return new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int item, long l) { - Object obj = listAdapter.getItem(item); - if (obj instanceof MapMarker) { - MapMarker marker = (MapMarker) obj; - if (selectionMode) { - CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox); - checkBox.setChecked(!checkBox.isChecked()); - marker.selected = checkBox.isChecked(); - markersHelper.updateMapMarker(marker, false); - if (helperCallbacks != null) { - helperCallbacks.showMarkersRouteOnMap(); - } - } else { - if (!marker.history) { - showMarkerOnMap(mapActivity, marker); - } else { - showHistoryOnMap(marker); - } - } - } else if (obj instanceof Integer && (Integer) obj == MY_LOCATION && selectionMode) { - CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox); - checkBox.setChecked(!checkBox.isChecked()); - markersHelper.setStartFromMyLocation(checkBox.isChecked()); - if (helperCallbacks != null) { - helperCallbacks.showMarkersRouteOnMap(); - } - } - } - }; - } - - public StableArrayAdapter getMapMarkersListAdapter() { - - screenOrientation = DashLocationFragment.getScreenOrientation(mapActivity); - calculateLocationParams(); - - final List objects = getListObjects(); - List activeObjects = getActiveObjects(objects); - - allSelected = true; - List activeMarkers = new ArrayList<>(markersHelper.getMapMarkers()); - for (MapMarker m : activeMarkers) { - if (!m.selected) { - allSelected = false; - break; - } - } - - return new StableArrayAdapter(mapActivity, - R.layout.map_marker_item, R.id.title, objects, activeObjects) { - - @Override - public void buildDividers() { - dividers = getCustomDividers(getObjects()); - } - - @Override - public boolean isEnabled(int position) { - Object obj = getItem(position); - return obj instanceof MapMarker - || (obj instanceof Integer && (Integer) obj == MY_LOCATION); - } - - @Override - public View getView(final int position, View convertView, ViewGroup parent) { - // User super class to create the View - View v = convertView; - Object obj = getItem(position); - boolean labelView = (obj instanceof Integer); - boolean topDividerView = (obj instanceof Boolean) && ((Boolean) obj); - boolean bottomDividerView = (obj instanceof Boolean) && !((Boolean) obj); - if (labelView) { - if ((Integer) obj == MY_LOCATION) { - v = updateMyLocationView(v); - } else { - v = createItemForCategory(this, (Integer) obj); - } - AndroidUtils.setListItemBackground(mapActivity, v, nightMode); - } else if (topDividerView) { - v = mapActivity.getLayoutInflater().inflate(R.layout.card_top_divider, null); - AndroidUtils.setListBackground(mapActivity, v, nightMode); - } else if (bottomDividerView) { - v = mapActivity.getLayoutInflater().inflate(R.layout.card_bottom_divider, null); - AndroidUtils.setListBackground(mapActivity, v, nightMode); - } else if (obj instanceof MapMarker) { - MapMarker marker = (MapMarker) obj; - v = updateMapMarkerItemView(this, v, marker); - AndroidUtils.setListItemBackground(mapActivity, v, nightMode); - } - return v; - } - }; - } - - private List getCustomDividers(List points) { - int color; - if (nightMode) { - color = mapActivity.getResources().getColor(R.color.dashboard_divider_dark); - } else { - color = mapActivity.getResources().getColor(R.color.dashboard_divider_light); - } - - Shape fullDividerShape = new ListDividerShape(color, 0); - Shape halfDividerShape = new ListDividerShape(color, AndroidUtils.dpToPx(mapActivity, 56f)); - - final ShapeDrawable fullDivider = new ShapeDrawable(fullDividerShape); - final ShapeDrawable halfDivider = new ShapeDrawable(halfDividerShape); - - int divHeight = AndroidUtils.dpToPx(mapActivity, 1f); - fullDivider.setIntrinsicHeight(divHeight); - halfDivider.setIntrinsicHeight(divHeight); - - List res = new ArrayList<>(); - for (int i = 0; i < points.size(); i++) { - Object obj = points.get(i); - Object objNext = i + 1 < points.size() ? points.get(i + 1) : null; - - if (objNext == null) { - break; - } - - boolean bottomDividerViewNext = (objNext instanceof Boolean) && !((Boolean) objNext); - - boolean mapMarker = (obj instanceof MapMarker); - boolean mapMarkerNext = (objNext instanceof MapMarker); - - Drawable d = null; - - if (mapMarkerNext) { - if (mapMarker) { - d = halfDivider; - } else { - d = fullDivider; - } - } else if (mapMarker && !bottomDividerViewNext) { - d = fullDivider; - } - - res.add(d); - } - return res; - } - - protected View createItemForCategory(final ArrayAdapter listAdapter, final int type) { - View v = mapActivity.getLayoutInflater().inflate(R.layout.waypoint_header, null); - v.findViewById(R.id.toggle_item).setVisibility(View.GONE); - v.findViewById(R.id.ProgressBar).setVisibility(View.GONE); - - if (type == MARKERS_HISTORY) { - final Button btn = (Button) v.findViewById(R.id.header_button); - btn.setTextColor(!nightMode ? mapActivity.getResources().getColor(R.color.map_widget_blue) - : mapActivity.getResources().getColor(R.color.osmand_orange)); - btn.setText(mapActivity.getString(R.string.shared_string_clear)); - btn.setVisibility(View.VISIBLE); - btn.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - AlertDialog.Builder builder = new AlertDialog.Builder(mapActivity); - builder.setMessage(mapActivity.getString(R.string.clear_markers_history_q)) - .setPositiveButton(R.string.shared_string_yes, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - listAdapter.notifyDataSetInvalidated(); - markersHelper.removeMarkersHistory(); - if (markersHelper.getMapMarkers().size() == 0) { - mapActivity.getDashboard().hideDashboard(); - } else if (helperCallbacks != null) { - helperCallbacks.reloadAdapter(); - } else { - reloadListAdapter(listAdapter); - } - } - }) - .setNegativeButton(R.string.shared_string_no, null) - .show(); - } - }); - - } else if (type == ACTIVE_MARKERS) { - if (selectionMode) { - final Button btn = (Button) v.findViewById(R.id.header_button); - btn.setTextColor(!nightMode ? mapActivity.getResources().getColor(R.color.map_widget_blue) - : mapActivity.getResources().getColor(R.color.osmand_orange)); - if (allSelected) { - btn.setText(mapActivity.getString(R.string.shared_string_deselect_all)); - } else { - btn.setText(mapActivity.getString(R.string.shared_string_select_all)); - } - btn.setVisibility(View.VISIBLE); - btn.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - List markers = markersHelper.getMapMarkers(); - for (MapMarker marker : markers) { - marker.selected = !allSelected; - } - markersHelper.setStartFromMyLocation(!allSelected); - allSelected = !allSelected; - if (helperCallbacks != null) { - helperCallbacks.reloadAdapter(); - } else { - reloadListAdapter(listAdapter); - } - } - }); - - } else { - final ImageButton btn = (ImageButton) v.findViewById(R.id.image_button); - btn.setImageDrawable(app.getIconsCache().getIcon(R.drawable.ic_overflow_menu_white, !nightMode)); - btn.setVisibility(View.VISIBLE); - btn.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - - IconsCache iconsCache = app.getIconsCache(); - final PopupMenu optionsMenu = new PopupMenu(mapActivity, v); - DirectionsDialogs.setupPopUpMenuIcon(optionsMenu); - MenuItem item; - item = optionsMenu.getMenu().add(R.string.shared_string_clear) - .setIcon(iconsCache.getThemedIcon(R.drawable.ic_action_delete_dark)); - item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { - @Override - public boolean onMenuItemClick(MenuItem item) { - AlertDialog.Builder builder = new AlertDialog.Builder(mapActivity); - builder.setMessage(mapActivity.getString(R.string.clear_active_markers_q)) - .setPositiveButton(R.string.shared_string_yes, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - listAdapter.notifyDataSetInvalidated(); - markersHelper.moveAllActiveMarkersToHistory(); - if (markersHelper.getMapMarkersHistory().size() == 0) { - mapActivity.getDashboard().hideDashboard(); - } else if (helperCallbacks != null) { - helperCallbacks.reloadAdapter(); - } else { - reloadListAdapter(listAdapter); - } - } - }) - .setNegativeButton(R.string.shared_string_no, null) - .show(); - return true; - } - }); - - if (!sorted && markersHelper.getMapMarkers().size() > 1) { - item = optionsMenu.getMenu().add(R.string.shared_string_reverse_order).setIcon( - iconsCache.getThemedIcon(R.drawable.ic_action_undo_dark)); - item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { - @Override - public boolean onMenuItemClick(MenuItem item) { - markersHelper.reverseActiveMarkersOrder(); - if (helperCallbacks != null) { - helperCallbacks.reloadAdapter(); - } else { - reloadListAdapter(listAdapter); - } - return true; - } - }); - } - - item = optionsMenu.getMenu().add(R.string.shared_string_save_as_gpx).setIcon( - iconsCache.getThemedIcon(R.drawable.ic_action_save)); - item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { - @Override - public boolean onMenuItemClick(MenuItem item) { - generateGPX(markersHelper.getMapMarkers()); - return true; - } - }); - - optionsMenu.show(); - } - }); - } - } - - TextView tv = (TextView) v.findViewById(R.id.header_text); - AndroidUtils.setTextPrimaryColor(mapActivity, tv, nightMode); - tv.setText(getHeader(type)); - return v; - } - - protected View updateMapMarkerItemView(final StableArrayAdapter adapter, View v, final MapMarker marker) { - if (v == null || v.findViewById(R.id.info_close) == null) { - v = mapActivity.getLayoutInflater().inflate(R.layout.map_marker_item, null); - } - updateMapMarkerInfo(mapActivity, v, loc, heading, useCenter, nightMode, screenOrientation, - selectionMode, helperCallbacks, marker, false); - final View more = v.findViewById(R.id.all_points); - final View move = v.findViewById(R.id.info_move); - final View remove = v.findViewById(R.id.info_close); - remove.setVisibility(View.GONE); - more.setVisibility(View.GONE); - if (!marker.history && !sorted) { - move.setVisibility(View.VISIBLE); - ((ImageView) move).setImageDrawable(app.getIconsCache().getIcon( - R.drawable.ic_action_reorder, !nightMode)); - if (app.accessibilityEnabled()) { - move.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - ((DynamicListView.DragIcon)view.getTag()).onClick(); - } - }); - } - move.setTag(new DynamicListView.DragIcon() { - @Override - public void onClick() { - final PopupMenu optionsMenu = new PopupMenu(mapActivity, move); - DirectionsDialogs.setupPopUpMenuIcon(optionsMenu); - MenuItem item; - item = optionsMenu.getMenu().add( - R.string.shared_string_remove).setIcon(app.getIconsCache(). - getThemedIcon(R.drawable.ic_action_remove_dark)); - item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { - @Override - public boolean onMenuItemClick(MenuItem item) { - if (helperCallbacks != null) { - int pos = adapter.getPosition(marker); - if (pos != -1) { - helperCallbacks.deleteMapMarker(pos); - } - } - return true; - } - }); - optionsMenu.show(); - } - }); - } else { - move.setVisibility(View.GONE); - move.setTag(null); - } - return v; - } - - public static void updateMapMarkerInfo(final Context ctx, View localView, LatLon loc, - Float heading, boolean useCenter, boolean nightMode, - int screenOrientation, boolean selectionMode, - final MapMarkersDialogHelperCallbacks helperCallbacks, - final MapMarker marker, boolean showDateAndGroup) { + public static void updateMapMarkerInfo(final Context ctx, + View localView, + LatLon loc, + Float heading, + boolean useCenter, + boolean nightMode, + int screenOrientation, + final MapMarker marker) { TextView text = (TextView) localView.findViewById(R.id.waypoint_text); TextView textShadow = (TextView) localView.findViewById(R.id.waypoint_text_shadow); TextView textDist = (TextView) localView.findViewById(R.id.waypoint_dist); @@ -539,360 +101,29 @@ public class MapMarkerDialogHelper { descText.setVisibility(View.GONE); - if (showDateAndGroup) { - Date date = new Date(marker.creationDate); - String month = new SimpleDateFormat("MMM", Locale.getDefault()).format(date); - if (month.length() > 1) { - month = Character.toUpperCase(month.charAt(0)) + month.substring(1); + Date date = new Date(marker.creationDate); + String month = new SimpleDateFormat("MMM", Locale.getDefault()).format(date); + if (month.length() > 1) { + month = Character.toUpperCase(month.charAt(0)) + month.substring(1); + } + month = month.replaceAll("\\.", ""); + String day = new SimpleDateFormat("d", Locale.getDefault()).format(date); + String desc = month + " " + day; + String markerGroupName = marker.groupName; + if (markerGroupName != null) { + if (markerGroupName.equals("")) { + markerGroupName = app.getString(R.string.shared_string_favorites); } - month = month.replaceAll("\\.", ""); - String day = new SimpleDateFormat("d", Locale.getDefault()).format(date); - String desc = month + " " + day; - String markerGroupName = marker.groupName; - if (markerGroupName != null) { - if (markerGroupName.equals("")) { - markerGroupName = app.getString(R.string.shared_string_favorites); - } - desc += " • " + markerGroupName; - } - dateGroupText.setVisibility(View.VISIBLE); - dateGroupText.setText(desc); + desc += " • " + markerGroupName; } + dateGroupText.setVisibility(View.VISIBLE); + dateGroupText.setText(desc); - if (selectionMode) { - checkBox.setChecked(marker.selected); - checkBox.setVisibility(View.VISIBLE); - checkBox.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - marker.selected = checkBox.isChecked(); - app.getMapMarkersHelper().updateMapMarker(marker, false); - if (helperCallbacks != null) { - helperCallbacks.showMarkersRouteOnMap(); - } else if (ctx instanceof MapActivity) { - ((MapActivity) ctx).refreshMap(); - } - } - }); - } else { - checkBox.setVisibility(View.GONE); - checkBox.setOnClickListener(null); - } - - /* - String pointDescription = ""; - if (descText != null) { - AndroidUtils.setTextSecondaryColor(this, descText, nightMode); - pointDescription = marker.getPointDescription(this).getTypeName(); - } - - if (descr.equals(pointDescription)) { - pointDescription = ""; - } - if (dist > 0 && !Algorithms.isEmpty(pointDescription)) { - pointDescription = " • " + pointDescription; - } - if (descText != null) { - descText.setText(pointDescription); - } - */ - } - - protected void updateMapMarkerArrowDistanceView(View localView, final MapMarker marker) { - TextView textDist = (TextView) localView.findViewById(R.id.waypoint_dist); - ImageView arrow = (ImageView) localView.findViewById(R.id.direction); - if (textDist == null || arrow == null) { - return; - } - float[] mes = new float[2]; - if (loc != null && marker.point != null) { - Location.distanceBetween(marker.getLatitude(), marker.getLongitude(), loc.getLatitude(), loc.getLongitude(), mes); - } - boolean newImage = false; - int arrowResId = R.drawable.ic_direction_arrow; - DirectionDrawable dd; - if (!(arrow.getDrawable() instanceof DirectionDrawable)) { - newImage = true; - dd = new DirectionDrawable(mapActivity, arrow.getWidth(), arrow.getHeight()); - } else { - dd = (DirectionDrawable) arrow.getDrawable(); - } - if (!marker.history) { - dd.setImage(arrowResId, useCenter ? R.color.color_distance : R.color.color_myloc_distance); - } else { - dd.setImage(arrowResId, nightMode ? R.color.secondary_text_dark : R.color.secondary_text_light); - } - if (loc == null || heading == null || marker.point == null) { - dd.setAngle(0); - } else { - dd.setAngle(mes[1] - heading + 180 + screenOrientation); - } - if (newImage) { - arrow.setImageDrawable(dd); - } - arrow.invalidate(); - - int dist = (int) mes[0]; - textDist.setText(OsmAndFormatter.getFormattedDistance(dist, app)); - } - - protected View updateMyLocationView(View v) { - if (v == null || v.findViewById(R.id.info_close) == null) { - v = mapActivity.getLayoutInflater().inflate(R.layout.map_marker_item, null); - } - updateMyLocationInfo(mapActivity, v, nightMode, selectionMode, helperCallbacks); - final View more = v.findViewById(R.id.all_points); - final View move = v.findViewById(R.id.info_move); - final View remove = v.findViewById(R.id.info_close); - remove.setVisibility(View.GONE); - more.setVisibility(View.GONE); - move.setVisibility(View.GONE); - move.setTag(null); - return v; - } - - public static void updateMyLocationInfo(final Context ctx, View localView, boolean nightMode, - boolean selectionMode, - final MapMarkersDialogHelperCallbacks helperCallbacks) { - TextView text = (TextView) localView.findViewById(R.id.waypoint_text); - TextView textDist = (TextView) localView.findViewById(R.id.waypoint_dist); - ImageView arrow = (ImageView) localView.findViewById(R.id.direction); - ImageView waypointIcon = (ImageView) localView.findViewById(R.id.waypoint_icon); - TextView waypointDeviation = (TextView) localView.findViewById(R.id.waypoint_deviation); - TextView descText = (TextView) localView.findViewById(R.id.waypoint_desc_text); - final CheckBox checkBox = (CheckBox) localView.findViewById(R.id.checkbox); - - if (text == null || textDist == null || arrow == null || waypointIcon == null - || waypointDeviation == null || descText == null) { - return; - } - - arrow.setVisibility(View.GONE); - textDist.setVisibility(View.GONE); - waypointDeviation.setVisibility(View.GONE); - - final OsmandApplication app = (OsmandApplication) ctx.getApplicationContext(); - - ApplicationMode appMode = app.getSettings().getApplicationMode(); - waypointIcon.setImageDrawable(ctx.getResources().getDrawable(appMode.getResourceLocationDay())); - - text.setText(ctx.getString(R.string.shared_string_my_location)); - descText.setText(ctx.getResources().getString(R.string.starting_point)); - descText.setVisibility(View.VISIBLE); - - AndroidUtils.setTextPrimaryColor(ctx, text, nightMode); - AndroidUtils.setTextSecondaryColor(ctx, descText, nightMode); - - if (selectionMode) { - checkBox.setChecked(app.getMapMarkersHelper().isStartFromMyLocation()); - checkBox.setVisibility(View.VISIBLE); - checkBox.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - app.getMapMarkersHelper().setStartFromMyLocation(checkBox.isChecked()); - if (helperCallbacks != null) { - helperCallbacks.showMarkersRouteOnMap(); - } else if (ctx instanceof MapActivity) { - ((MapActivity) ctx).refreshMap(); - } - } - }); - } else { - checkBox.setVisibility(View.GONE); - checkBox.setOnClickListener(null); - } - } - - public static void showMarkerOnMap(MapActivity mapActivity, MapMarker marker) { - mapActivity.getMyApplication().getSettings().setMapLocationToShow(marker.getLatitude(), marker.getLongitude(), - 15, marker.getPointDescription(mapActivity), true, marker); - MapActivity.launchMapActivityMoveToTop(mapActivity); - } - - public void showHistoryOnMap(MapMarker marker) { - app.getSettings().setMapLocationToShow(marker.getLatitude(), marker.getLongitude(), - 15, new PointDescription(PointDescription.POINT_TYPE_LOCATION, - marker.getPointDescription(mapActivity).getName()), - false, null); - MapActivity.launchMapActivityMoveToTop(mapActivity); - } - - protected String getHeader(int type) { - String str = mapActivity.getString(R.string.map_markers); - switch (type) { - case ACTIVE_MARKERS: - str = mapActivity.getString(R.string.active_markers); - break; - case MARKERS_HISTORY: - str = mapActivity.getString(R.string.shared_string_history); - break; - } - return str; - } - - public void reloadListAdapter(ArrayAdapter listAdapter) { - reloading = true; - listAdapter.setNotifyOnChange(false); - listAdapter.clear(); - List objects = getListObjects(); - for (Object point : objects) { - listAdapter.add(point); - } - if (listAdapter instanceof StableArrayAdapter) { - ((StableArrayAdapter) listAdapter).updateObjects(objects, getActiveObjects(objects)); - } - listAdapter.notifyDataSetChanged(); - reloading = false; - } - - public void calcDistance(LatLon anchor, List markers) { - for (MapMarker m : markers) { - m.dist = (int) (MapUtils.getDistance(m.getLatitude(), m.getLongitude(), - anchor.getLatitude(), anchor.getLongitude())); - } - } - - protected List getListObjects() { - final List objects = new ArrayList<>(); - - LatLon mapLocation = - new LatLon(mapActivity.getMapView().getLatitude(), mapActivity.getMapView().getLongitude()); - - List activeMarkers = new ArrayList<>(markersHelper.getMapMarkers()); - calcDistance(mapLocation, activeMarkers); - if (sorted) { - Collections.sort(activeMarkers, new Comparator() { - @Override - public int compare(MapMarker lhs, MapMarker rhs) { - return lhs.dist < rhs.dist ? -1 : (lhs.dist == rhs.dist ? 0 : 1); - } - }); - } - if (activeMarkers.size() > 0) { - objects.add(ACTIVE_MARKERS); - if (selectionMode) { - objects.add(MY_LOCATION); - } - objects.addAll(activeMarkers); - objects.add(false); - } - - if (!selectionMode) { - List markersHistory = new ArrayList<>(markersHelper.getMapMarkersHistory()); - calcDistance(mapLocation, markersHistory); - if (markersHistory.size() > 0) { - if (activeMarkers.size() > 0) { - objects.add(true); - } - objects.add(MARKERS_HISTORY); - objects.addAll(markersHistory); - objects.add(false); - } - } - - return objects; - } - - private List getActiveObjects(List objects) { - List activeObjects = new ArrayList<>(); - for (Object obj : objects) { - if (obj instanceof MapMarker) { - activeObjects.add(obj); - } - } - return activeObjects; + checkBox.setVisibility(View.GONE); + checkBox.setOnClickListener(null); } public static Drawable getMapMarkerIcon(OsmandApplication app, int colorIndex) { return app.getIconsCache().getIcon(R.drawable.ic_action_flag_dark, MapMarker.getColorId(colorIndex)); } - - public void updateLocation(ListView listView, boolean compassChanged) { - if ((compassChanged && !mapActivity.getDashboard().isMapLinkedToLocation()) - || reloading || System.currentTimeMillis() - lastUpdateTime < 100) { - return; - } - - lastUpdateTime = System.currentTimeMillis(); - - try { - LatLon prevMyLoc = myLoc; - calculateLocationParams(); - - for (int i = listView.getFirstVisiblePosition(); i <= listView.getLastVisiblePosition(); i++) { - Object obj = listView.getItemAtPosition(i); - View v = listView.getChildAt(i - listView.getFirstVisiblePosition()); - if (obj instanceof MapMarker && v != null) { - updateMapMarkerArrowDistanceView(v, (MapMarker) obj); - } - } - - if (selectionMode && markersHelper.isStartFromMyLocation() && prevMyLoc == null && myLoc != null) { - if (helperCallbacks != null) { - helperCallbacks.showMarkersRouteOnMap(); - } else { - mapActivity.refreshMap(); - } - } - } catch (Exception e) { - } - } - - public void updateMarkerView(ListView listView, MapMarker marker) { - try { - for (int i = listView.getFirstVisiblePosition(); i <= listView.getLastVisiblePosition(); i++) { - Object obj = listView.getItemAtPosition(i); - View v = listView.getChildAt(i - listView.getFirstVisiblePosition()); - if (obj == marker) { - updateMapMarkerInfo(mapActivity, v, loc, heading, useCenter, nightMode, - screenOrientation, selectionMode, helperCallbacks, marker, false); - } - } - } catch (Exception e) { - } - } - - private void calculateLocationParams() { - DashboardOnMap d = mapActivity.getDashboard(); - if (d == null) { - return; - } - - float head = d.getHeading(); - float mapRotation = d.getMapRotation(); - LatLon mw = d.getMapViewLocation(); - Location l = d.getMyLocation(); - boolean mapLinked = d.isMapLinkedToLocation() && l != null; - myLoc = l == null ? null : new LatLon(l.getLatitude(), l.getLongitude()); - useCenter = !mapLinked; - loc = (useCenter ? mw : myLoc); - heading = useCenter ? -mapRotation : head; - } - - private void generateGPX(List markers) { - final File dir = app.getAppPath(IndexConstants.GPX_INDEX_DIR + "/map markers"); - if (!dir.exists()) { - dir.mkdirs(); - } - Date date = new Date(); - String fileName = DateFormat.format("yyyy-MM-dd", date).toString() + "_" + new SimpleDateFormat("HH-mm_EEE", Locale.US).format(date); - File fout = new File(dir, fileName + ".gpx"); - int ind = 1; - while (fout.exists()) { - fout = new File(dir, fileName + "_" + (++ind) + ".gpx"); - } - GPXFile file = new GPXFile(); - for (MapMarker marker : markersHelper.getMapMarkers()) { - WptPt wpt = new WptPt(); - wpt.lat = marker.getLatitude(); - wpt.lon = marker.getLongitude(); - wpt.setColor(mapActivity.getResources().getColor(MapMarker.getColorId(marker.colorIndex))); - wpt.name = marker.getOnlyName(); - //wpt.link = r.getFileName(); - //wpt.time = r.getFile().lastModified(); - //wpt.category = r.getSearchHistoryType(); - file.addPoint(wpt); - } - GPXUtilities.writeGpxFile(fout, file, app); - } } diff --git a/OsmAnd/src/net/osmand/plus/mapcontextmenu/MapContextMenu.java b/OsmAnd/src/net/osmand/plus/mapcontextmenu/MapContextMenu.java index a1788d050b..cb03d0aa3c 100644 --- a/OsmAnd/src/net/osmand/plus/mapcontextmenu/MapContextMenu.java +++ b/OsmAnd/src/net/osmand/plus/mapcontextmenu/MapContextMenu.java @@ -836,23 +836,18 @@ public class MapContextMenu extends MenuTitleController implements StateChangedL if (marker != null) { RenameMarkerBottomSheetDialogFragment .showInstance(mapActivity.getSupportFragmentManager(), marker); - } else if (settings.USE_MAP_MARKERS.get()) { - if (pointDescription.isMapMarker()) { - hide(); - MapActivity.clearPrevActivityIntent(); - MapMarkersDialogFragment.showInstance(mapActivity); - } else { - String mapObjectName = null; - if (object instanceof Amenity) { - Amenity amenity = (Amenity) object; - mapObjectName = amenity.getName() + "_" + amenity.getType().getKeyName(); - } - mapActivity.getMapActions().addMapMarker(latLon.getLatitude(), latLon.getLongitude(), - getPointDescriptionForMarker(), mapObjectName); - } + } else if (pointDescription.isMapMarker()) { + hide(); + MapActivity.clearPrevActivityIntent(); + MapMarkersDialogFragment.showInstance(mapActivity); } else { - mapActivity.getMapActions().addAsTarget(latLon.getLatitude(), latLon.getLongitude(), - getPointDescriptionForTarget()); + String mapObjectName = null; + if (object instanceof Amenity) { + Amenity amenity = (Amenity) object; + mapObjectName = amenity.getName() + "_" + amenity.getType().getKeyName(); + } + mapActivity.getMapActions().addMapMarker(latLon.getLatitude(), latLon.getLongitude(), + getPointDescriptionForMarker(), mapObjectName); } close(); } diff --git a/OsmAnd/src/net/osmand/plus/mapcontextmenu/editors/WptPtEditorFragment.java b/OsmAnd/src/net/osmand/plus/mapcontextmenu/editors/WptPtEditorFragment.java index 8b01132b2f..221584b3ed 100644 --- a/OsmAnd/src/net/osmand/plus/mapcontextmenu/editors/WptPtEditorFragment.java +++ b/OsmAnd/src/net/osmand/plus/mapcontextmenu/editors/WptPtEditorFragment.java @@ -10,14 +10,13 @@ import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.view.View; -import net.osmand.AndroidUtils; import net.osmand.data.LatLon; import net.osmand.plus.FavouritesDbHelper.FavoriteGroup; import net.osmand.plus.GPXUtilities; import net.osmand.plus.GPXUtilities.GPXFile; import net.osmand.plus.GPXUtilities.WptPt; import net.osmand.plus.GpxSelectionHelper; -import net.osmand.plus.MapMarkersHelper.MarkersSyncGroup; +import net.osmand.plus.MapMarkersHelper; import net.osmand.plus.OsmandApplication; import net.osmand.plus.R; import net.osmand.plus.activities.MapActivity; @@ -180,8 +179,8 @@ public class WptPtEditorFragment extends PointEditorFragment { private void syncGpx(GPXFile gpxFile) { File gpx = new File(gpxFile.path); if (gpx.exists()) { - getMyApplication().getMapMarkersHelper().syncGroupAsync(new MarkersSyncGroup(gpx.getAbsolutePath(), - AndroidUtils.trimExtension(gpx.getName()), MarkersSyncGroup.GPX_TYPE)); + MapMarkersHelper helper = getMyApplication().getMapMarkersHelper(); + helper.runSynchronization(helper.getOrCreateGroup(gpx)); } } diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/AddFavouritesGroupBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/mapmarkers/AddFavouritesGroupBottomSheetDialogFragment.java index a609a61ac3..0866a3245e 100644 --- a/OsmAnd/src/net/osmand/plus/mapmarkers/AddFavouritesGroupBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/AddFavouritesGroupBottomSheetDialogFragment.java @@ -4,8 +4,8 @@ import android.os.Bundle; import net.osmand.plus.FavouritesDbHelper; import net.osmand.plus.FavouritesDbHelper.FavoriteGroup; -import net.osmand.plus.MapMarkersHelper.MarkersSyncGroup; import net.osmand.plus.mapmarkers.adapters.FavouritesGroupsAdapter; +import net.osmand.plus.mapmarkers.adapters.GroupsAdapter; public class AddFavouritesGroupBottomSheetDialogFragment extends AddGroupBottomSheetDialogFragment { @@ -18,16 +18,16 @@ public class AddFavouritesGroupBottomSheetDialogFragment extends AddGroupBottomS } @Override - public MarkersSyncGroup createMapMarkersSyncGroup(int position) { + public GroupsAdapter createAdapter() { + return new FavouritesGroupsAdapter(getContext(), favouritesDbHelper.getFavoriteGroups()); + } + + @Override + protected void onItemClick(int position) { FavoriteGroup group = favouritesDbHelper.getFavoriteGroups().get(position - 1); if (!group.visible) { favouritesDbHelper.editFavouriteGroup(group, group.name, group.color, true); } - return new MarkersSyncGroup(group.name, group.name, MarkersSyncGroup.FAVORITES_TYPE, group.color); - } - - @Override - public void createAdapter() { - adapter = new FavouritesGroupsAdapter(getContext(), favouritesDbHelper.getFavoriteGroups()); + addAndSyncGroup(getMyApplication().getMapMarkersHelper().getOrCreateGroup(group)); } } diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/AddGroupBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/mapmarkers/AddGroupBottomSheetDialogFragment.java index 2c37c532c2..1c777213ab 100644 --- a/OsmAnd/src/net/osmand/plus/mapmarkers/AddGroupBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/AddGroupBottomSheetDialogFragment.java @@ -7,8 +7,7 @@ import android.support.v7.widget.RecyclerView; import android.view.ContextThemeWrapper; import android.view.View; -import net.osmand.plus.MapMarkersHelper; -import net.osmand.plus.MapMarkersHelper.MarkersSyncGroup; +import net.osmand.plus.MapMarkersHelper.MapMarkersGroup; import net.osmand.plus.R; import net.osmand.plus.base.MenuBottomSheetDialogFragment; import net.osmand.plus.base.bottomsheetmenu.BaseBottomSheetItem; @@ -18,20 +17,8 @@ public abstract class AddGroupBottomSheetDialogFragment extends MenuBottomSheetD public static final String TAG = "AddGroupBottomSheetDialogFragment"; - private AddGroupListener listener; protected View mainView; protected GroupsAdapter adapter; - protected MapMarkersHelper mapMarkersHelper; - - public void setListener(AddGroupListener listener) { - this.listener = listener; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - mapMarkersHelper = getMyApplication().getMapMarkersHelper(); - } @Override public void createMenuItems(Bundle savedInstanceState) { @@ -41,26 +28,14 @@ public abstract class AddGroupBottomSheetDialogFragment extends MenuBottomSheetD final RecyclerView recyclerView = mainView.findViewById(R.id.groups_recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); - createAdapter(); + adapter = createAdapter(); adapter.setAdapterListener(new GroupsAdapter.GroupsAdapterListener() { @Override public void onItemClick(View view) { int position = recyclerView.getChildAdapterPosition(view); - if (position == RecyclerView.NO_POSITION) { - return; + if (position != RecyclerView.NO_POSITION) { + AddGroupBottomSheetDialogFragment.this.onItemClick(position); } - showProgressBar(); - MarkersSyncGroup group = createMapMarkersSyncGroup(position); - mapMarkersHelper.addMarkersSyncGroup(group); - mapMarkersHelper.syncGroupAsync(group, new MapMarkersHelper.OnGroupSyncedListener() { - @Override - public void onSyncDone() { - if (listener != null) { - listener.onGroupAdded(); - } - dismiss(); - } - }); } }); recyclerView.setAdapter(adapter); @@ -82,16 +57,12 @@ public abstract class AddGroupBottomSheetDialogFragment extends MenuBottomSheetD return false; } - private void showProgressBar() { - mainView.findViewById(R.id.groups_recycler_view).setVisibility(View.GONE); - mainView.findViewById(R.id.progress_bar).setVisibility(View.VISIBLE); + protected void addAndSyncGroup(MapMarkersGroup group) { + getMyApplication().getMapMarkersHelper().syncWithMarkers(group); + dismiss(); } - protected abstract void createAdapter(); + protected abstract GroupsAdapter createAdapter(); - protected abstract MarkersSyncGroup createMapMarkersSyncGroup(int position); - - public interface AddGroupListener { - void onGroupAdded(); - } + protected abstract void onItemClick(int position); } diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/AddTracksGroupBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/mapmarkers/AddTracksGroupBottomSheetDialogFragment.java index 639f243c10..2c6789a74e 100644 --- a/OsmAnd/src/net/osmand/plus/mapmarkers/AddTracksGroupBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/AddTracksGroupBottomSheetDialogFragment.java @@ -1,5 +1,6 @@ package net.osmand.plus.mapmarkers; +import android.annotation.SuppressLint; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; @@ -8,7 +9,6 @@ import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; -import net.osmand.AndroidUtils; import net.osmand.IndexConstants; import net.osmand.plus.GPXDatabase; import net.osmand.plus.GPXDatabase.GpxDataItem; @@ -17,9 +17,10 @@ import net.osmand.plus.GPXUtilities.GPXFile; import net.osmand.plus.GPXUtilities.GPXTrackAnalysis; import net.osmand.plus.GpxSelectionHelper; import net.osmand.plus.GpxSelectionHelper.SelectedGpxFile; -import net.osmand.plus.MapMarkersHelper.MarkersSyncGroup; +import net.osmand.plus.MapMarkersHelper.MapMarkersGroup; import net.osmand.plus.OsmandApplication; import net.osmand.plus.R; +import net.osmand.plus.mapmarkers.adapters.GroupsAdapter; import net.osmand.plus.mapmarkers.adapters.TracksGroupsAdapter; import java.io.File; @@ -33,13 +34,6 @@ public class AddTracksGroupBottomSheetDialogFragment extends AddGroupBottomSheet private ProcessGpxTask asyncProcessor; private List gpxList; - private GpxSelectionHelper gpxSelectionHelper; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - gpxSelectionHelper = getMyApplication().getSelectedGpxHelper(); - } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { @@ -48,24 +42,6 @@ public class AddTracksGroupBottomSheetDialogFragment extends AddGroupBottomSheet asyncProcessor.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - @Override - public void createAdapter() { - gpxList = new ArrayList<>(); - adapter = new TracksGroupsAdapter(getContext(), gpxList); - } - - @Override - public MarkersSyncGroup createMapMarkersSyncGroup(int position) { - GpxDataItem gpxDataItem = gpxList.get(position - 1); - File gpx = gpxDataItem.getFile(); - SelectedGpxFile selectedGpxFile = gpxSelectionHelper.getSelectedFileByPath(gpx.getAbsolutePath()); - if (selectedGpxFile == null) { - GPXFile res = GPXUtilities.loadGPXFile(getContext(), gpx); - gpxSelectionHelper.selectGpxFile(res, true, false, false); - } - return new MarkersSyncGroup(gpx.getAbsolutePath(), AndroidUtils.trimExtension(gpx.getName()), MarkersSyncGroup.GPX_TYPE); - } - @Override public void onDestroyView() { super.onDestroyView(); @@ -75,12 +51,47 @@ public class AddTracksGroupBottomSheetDialogFragment extends AddGroupBottomSheet } } + @Override + public GroupsAdapter createAdapter() { + gpxList = new ArrayList<>(); + return new TracksGroupsAdapter(getContext(), gpxList); + } + + @Override + protected void onItemClick(int position) { + GpxDataItem dataItem = gpxList.get(position - 1); + if (dataItem.getAnalysis().wptCategoryNames != null && dataItem.getAnalysis().wptCategoryNames.size() > 1) { + Bundle args = new Bundle(); + args.putString(SelectWptCategoriesBottomSheetDialogFragment.GPX_FILE_PATH_KEY, dataItem.getFile().getAbsolutePath()); + + SelectWptCategoriesBottomSheetDialogFragment fragment = new SelectWptCategoriesBottomSheetDialogFragment(); + fragment.setArguments(args); + fragment.setUsedOnMap(false); + fragment.show(getParentFragment().getChildFragmentManager(), SelectWptCategoriesBottomSheetDialogFragment.TAG); + dismiss(); + } else { + addAndSyncGroup(createMapMarkersSyncGroup(getMyApplication(), dataItem)); + } + } + + private MapMarkersGroup createMapMarkersSyncGroup(OsmandApplication app, GpxDataItem gpxDataItem) { + GpxSelectionHelper gpxSelectionHelper = app.getSelectedGpxHelper(); + File gpx = gpxDataItem.getFile(); + SelectedGpxFile selectedGpxFile = gpxSelectionHelper.getSelectedFileByPath(gpx.getAbsolutePath()); + if (selectedGpxFile == null) { + GPXFile res = GPXUtilities.loadGPXFile(app, gpx); + gpxSelectionHelper.selectGpxFile(res, true, false); + } + return getMyApplication().getMapMarkersHelper().getOrCreateGroup(gpx); + } + + @SuppressLint("StaticFieldLeak") public class ProcessGpxTask extends AsyncTask { private OsmandApplication app = getMyApplication(); private Map processedDataFiles = new HashMap<>(); private GPXDatabase db = app.getGpxDatabase(); - private ProgressBar progressBar = (ProgressBar) mainView.findViewById(R.id.progress_bar);; + private ProgressBar progressBar = (ProgressBar) mainView.findViewById(R.id.progress_bar); private RecyclerView recyclerView = (RecyclerView) mainView.findViewById(R.id.groups_recycler_view); private TextView lookingForTracksText = (TextView) mainView.findViewById(R.id.looking_for_tracks_text); diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkerSelectionFragment.java b/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkerSelectionFragment.java index b04a26ba93..71f1f4d8d6 100644 --- a/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkerSelectionFragment.java +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkerSelectionFragment.java @@ -135,7 +135,7 @@ public class MapMarkerSelectionFragment extends BaseOsmAndDialogFragment { convertView = getMapActivity().getLayoutInflater().inflate(R.layout.map_marker_item, null); } MapMarkerDialogHelper.updateMapMarkerInfo(getContext(), convertView, loc, heading, - useCenter, nightMode, screenOrientation, false, null, marker, true); + useCenter, nightMode, screenOrientation, marker); final View remove = convertView.findViewById(R.id.info_close); remove.setVisibility(View.GONE); AndroidUtils.setListItemBackground(getMapActivity(), convertView, nightMode); diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersDbHelper.java b/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersDbHelper.java index 84e67317fd..7219c5f73f 100644 --- a/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersDbHelper.java +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersDbHelper.java @@ -5,19 +5,19 @@ import android.support.annotation.Nullable; import net.osmand.data.LatLon; import net.osmand.data.PointDescription; import net.osmand.plus.MapMarkersHelper.MapMarker; -import net.osmand.plus.MapMarkersHelper.MarkersSyncGroup; +import net.osmand.plus.MapMarkersHelper.MapMarkersGroup; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandSettings; import net.osmand.plus.api.SQLiteAPI.SQLiteConnection; import net.osmand.plus.api.SQLiteAPI.SQLiteCursor; import net.osmand.plus.helpers.SearchHistoryHelper; +import net.osmand.util.Algorithms; import java.util.ArrayList; import java.util.Calendar; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; -import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; @@ -25,7 +25,7 @@ import java.util.Set; public class MapMarkersDbHelper { - private static final int DB_VERSION = 12; + private static final int DB_VERSION = 13; public static final String DB_NAME = "map_markers_db"; private static final String MARKERS_TABLE_NAME = "map_markers"; @@ -83,19 +83,22 @@ public class MapMarkersDbHelper { private static final String GROUPS_COL_NAME = "group_name"; private static final String GROUPS_COL_TYPE = "group_type"; private static final String GROUPS_COL_DISABLED = "group_disabled"; + private static final String GROUPS_COL_CATEGORIES = "group_categories"; private static final String GROUPS_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " + GROUPS_TABLE_NAME + " (" + GROUPS_COL_ID + " TEXT PRIMARY KEY, " + GROUPS_COL_NAME + " TEXT, " + GROUPS_COL_TYPE + " int, " + - GROUPS_COL_DISABLED + " int);"; // 1 = true, 0 = false + GROUPS_COL_DISABLED + " int, " + // 1 = true, 0 = false + GROUPS_COL_CATEGORIES + " TEXT);"; private static final String GROUPS_TABLE_SELECT = "SELECT " + GROUPS_COL_ID + ", " + GROUPS_COL_NAME + ", " + GROUPS_COL_TYPE + ", " + - GROUPS_COL_DISABLED + + GROUPS_COL_DISABLED + ", " + + GROUPS_COL_CATEGORIES + " FROM " + GROUPS_TABLE_NAME; public static final String TAIL_NEXT_VALUE = "tail_next"; @@ -156,6 +159,9 @@ public class MapMarkersDbHelper { if (oldVersion < 12) { db.execSQL("ALTER TABLE " + MARKERS_TABLE_NAME + " ADD " + MARKERS_COL_MAP_OBJECT_NAME + " TEXT"); } + if (oldVersion < 13) { + db.execSQL("ALTER TABLE " + GROUPS_TABLE_NAME + " ADD " + GROUPS_COL_CATEGORIES + " TEXT"); + } } private void saveExistingMarkersToDb() { @@ -189,26 +195,28 @@ public class MapMarkersDbHelper { } } - public void addGroup(String id, String name, int type) { + public void addGroup(MapMarkersGroup group) { SQLiteConnection db = openConnection(false); if (db != null) { try { - db.execSQL("INSERT INTO " + GROUPS_TABLE_NAME + " VALUES (?, ?, ?, ?)", new Object[]{id, name, type, 0}); + db.execSQL("INSERT INTO " + GROUPS_TABLE_NAME + " VALUES (?, ?, ?, ?, ?)", + new Object[]{group.getId(), group.getName(), group.getType(), group.isDisabled(), group.getWptCategoriesString()}); } finally { db.close(); } } } - public List getAllGroups() { - List res = new LinkedList<>(); + public Map getAllGroupsMap() { + Map res = new LinkedHashMap<>(); SQLiteConnection db = openConnection(true); if (db != null) { try { SQLiteCursor query = db.rawQuery(GROUPS_TABLE_SELECT, null); if (query.moveToFirst()) { do { - res.add(readSyncGroup(query)); + MapMarkersGroup group = readGroup(query); + res.put(group.getId(), group); } while (query.moveToNext()); } query.close(); @@ -219,33 +227,21 @@ public class MapMarkersDbHelper { return res; } - @Nullable - public MarkersSyncGroup getGroup(String id) { - MarkersSyncGroup res = null; - SQLiteConnection db = openConnection(true); - if (db != null) { - try { - SQLiteCursor query = db.rawQuery(GROUPS_TABLE_SELECT + " WHERE " + GROUPS_COL_ID + " = ?", new String[]{id}); - if (query.moveToFirst()) { - res = readSyncGroup(query); - } - query.close(); - } finally { - db.close(); - } - } - return res; - } - - private MarkersSyncGroup readSyncGroup(SQLiteCursor query) { + private MapMarkersGroup readGroup(SQLiteCursor query) { String id = query.getString(0); String name = query.getString(1); int type = query.getInt(2); + boolean disabled = query.getInt(3) == 1; + String categories = query.getString(4); - return new MarkersSyncGroup(id, name, type); + MapMarkersGroup res = new MapMarkersGroup(id, name, type); + res.setDisabled(disabled); + res.setWptCategories(categories == null ? null : Algorithms.decodeStringSet(categories)); + + return res; } - public void removeMarkersSyncGroup(String id) { + public void removeMarkersGroup(String id) { SQLiteConnection db = openConnection(true); if (db != null) { try { @@ -256,21 +252,21 @@ public class MapMarkersDbHelper { } } - public void removeActiveMarkersFromSyncGroup(String syncGroupId) { + public void removeActiveMarkersFromGroup(String groupId) { SQLiteConnection db = openConnection(true); if (db != null) { try { db.execSQL("DELETE FROM " + MARKERS_TABLE_NAME + " WHERE " + MARKERS_COL_GROUP_KEY + " = ?" + " AND " + MARKERS_COL_ACTIVE + " = ?", - new Object[]{syncGroupId, 1}); + new Object[]{groupId, 1}); } finally { db.close(); } } } - public void updateSyncGroupDisabled(String id, boolean disabled) { + public void updateGroupDisabled(String id, boolean disabled) { SQLiteConnection db = openConnection(false); if (db != null) { try { @@ -286,21 +282,17 @@ public class MapMarkersDbHelper { } } - public boolean isGroupDisabled(String id) { - boolean disabled = false; - SQLiteConnection db = openConnection(true); + public void updateGroupCategories(String id, String categories) { + SQLiteConnection db = openConnection(false); if (db != null) { try { - SQLiteCursor query = db.rawQuery(GROUPS_TABLE_SELECT + " WHERE " + GROUPS_COL_ID + " = ?", new String[]{id}); - if (query.moveToFirst()) { - disabled = query.getInt(3) == 1; - } - query.close(); + db.execSQL("UPDATE " + GROUPS_TABLE_NAME + + " SET " + GROUPS_COL_CATEGORIES + " = ? " + + "WHERE " + GROUPS_COL_ID + " = ?", new Object[]{categories, id}); } finally { db.close(); } } - return disabled; } public void removeDisabledGroups() { @@ -385,33 +377,13 @@ public class MapMarkersDbHelper { MARKERS_COL_NEXT_KEY + ", " + MARKERS_COL_DISABLED + ", " + MARKERS_COL_SELECTED + ", " + - MARKERS_COL_MAP_OBJECT_NAME + ") " + + MARKERS_COL_MAP_OBJECT_NAME + ") " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", new Object[]{marker.id, marker.getLatitude(), marker.getLongitude(), descr, active, currentTime, visited, marker.groupName, marker.groupKey, marker.colorIndex, marker.history ? HISTORY_NEXT_VALUE : TAIL_NEXT_VALUE, 0, 0, marker.mapObjectName}); } - public List getMarkersFromGroup(MarkersSyncGroup group) { - List res = new LinkedList<>(); - SQLiteConnection db = openConnection(true); - if (db != null) { - try { - SQLiteCursor query = db.rawQuery(MARKERS_TABLE_SELECT + " WHERE " + MARKERS_COL_GROUP_KEY + " = ?", - new String[]{group.getId()}); - if (query.moveToFirst()) { - do { - res.add(readItem(query)); - } while (query.moveToNext()); - } - query.close(); - } finally { - db.close(); - } - } - return res; - } - @Nullable public MapMarker getMarker(String id) { MapMarker res = null; @@ -591,7 +563,7 @@ public class MapMarkersDbHelper { } public List getMarkersHistory() { - List markers = new LinkedList<>(); + List markers = new ArrayList<>(); SQLiteConnection db = openConnection(true); if (db != null) { try { @@ -610,26 +582,14 @@ public class MapMarkersDbHelper { return markers; } - public void removeMarker(MapMarker marker, boolean history) { + public void removeMarker(MapMarker marker) { SQLiteConnection db = openConnection(true); if (db != null) { try { db.execSQL("DELETE FROM " + MARKERS_TABLE_NAME + " WHERE " + MARKERS_COL_ID + " = ?" + " AND " + MARKERS_COL_ACTIVE + " = ?", - new Object[]{marker.id, history ? 0 : 1}); - } finally { - db.close(); - } - } - } - - public void clearAllMarkersHistory() { - SQLiteConnection db = openConnection(true); - if (db != null) { - try { - db.execSQL("DELETE FROM " + MARKERS_TABLE_NAME + " WHERE " + MARKERS_COL_ACTIVE + " = ?", - new Object[]{0}); + new Object[]{marker.id, marker.history ? 0 : 1}); } finally { db.close(); } diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersDialogFragment.java b/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersDialogFragment.java index d1e7ab2d44..9bcf0354e2 100644 --- a/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersDialogFragment.java @@ -18,6 +18,7 @@ import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; +import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; @@ -26,6 +27,7 @@ import net.osmand.data.LatLon; import net.osmand.plus.LockableViewPager; import net.osmand.plus.MapMarkersHelper; import net.osmand.plus.MapMarkersHelper.MapMarkersSortByDef; +import net.osmand.plus.MapMarkersHelper.OnGroupSyncedListener; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandSettings; import net.osmand.plus.R; @@ -45,7 +47,7 @@ import java.util.List; import static net.osmand.plus.mapmarkers.OptionsBottomSheetDialogFragment.GROUPS_MARKERS_MENU; import static net.osmand.plus.mapmarkers.OptionsBottomSheetDialogFragment.HISTORY_MARKERS_MENU; -public class MapMarkersDialogFragment extends android.support.v4.app.DialogFragment { +public class MapMarkersDialogFragment extends android.support.v4.app.DialogFragment implements OnGroupSyncedListener { public static final String TAG = "MapMarkersDialogFragment"; @@ -62,6 +64,7 @@ public class MapMarkersDialogFragment extends android.support.v4.app.DialogFragm private Snackbar snackbar; private LockableViewPager viewPager; private BottomNavigationView bottomNav; + private ProgressBar progressBar; private boolean lightTheme; private String groupIdToOpen; @@ -158,6 +161,8 @@ public class MapMarkersDialogFragment extends android.support.v4.app.DialogFragm final MapMarkersViewPagerAdapter adapter = new MapMarkersViewPagerAdapter(getChildFragmentManager()); viewPager.setAdapter(adapter); + progressBar = (ProgressBar) mainView.findViewById(R.id.progress_bar); + bottomNav = mainView.findViewById(R.id.map_markers_bottom_navigation); BottomNavigationViewHelper.disableShiftMode(bottomNav); if (!lightTheme) { @@ -206,6 +211,35 @@ public class MapMarkersDialogFragment extends android.support.v4.app.DialogFragm return mainView; } + @Override + public void onResume() { + super.onResume(); + getMyApplication().getMapMarkersHelper().addSyncListener(this); + } + + @Override + public void onPause() { + super.onPause(); + getMyApplication().getMapMarkersHelper().removeSyncListener(this); + } + + @Override + public void onSyncStarted() { + switchProgressbarVisibility(true); + } + + @Override + public void onSyncDone() { + updateAdapters(); + switchProgressbarVisibility(false); + } + + private void switchProgressbarVisibility(boolean visible) { + if (progressBar != null) { + progressBar.setVisibility(visible ? View.VISIBLE : View.GONE); + } + } + private void setupLocationUpdate(boolean activeFr, boolean groupsFr) { if (activeFr) { activeFragment.startLocationUpdate(); diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersGroupsFragment.java b/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersGroupsFragment.java index def0aad3e6..8362f02805 100644 --- a/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersGroupsFragment.java +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/MapMarkersGroupsFragment.java @@ -69,10 +69,6 @@ public class MapMarkersGroupsFragment extends Fragment implements OsmAndCompassL if (selectionMarkersGroupFragment != null) { ((SelectionMarkersGroupBottomSheetDialogFragment) selectionMarkersGroupFragment).setListener(createAddMarkersGroupFragmentListener()); } - Fragment addGroupFragment = getChildFragmentManager().findFragmentByTag(AddGroupBottomSheetDialogFragment.TAG); - if (addGroupFragment != null) { - ((AddGroupBottomSheetDialogFragment) addGroupFragment).setListener(createAddGroupListener()); - } Fragment historyMarkerMenuFragment = getChildFragmentManager().findFragmentByTag(HistoryMarkerMenuBottomSheetDialogFragment.TAG); if (historyMarkerMenuFragment != null) { ((HistoryMarkerMenuBottomSheetDialogFragment) historyMarkerMenuFragment).setListener(createHistoryMarkerMenuListener()); @@ -373,33 +369,21 @@ public class MapMarkersGroupsFragment extends Fragment implements OsmAndCompassL } private void openAddGroupMenu(AddGroupBottomSheetDialogFragment fragment) { - fragment.setListener(createAddGroupListener()); fragment.setUsedOnMap(false); fragment.setRetainInstance(true); fragment.show(getChildFragmentManager(), AddGroupBottomSheetDialogFragment.TAG); } - private AddGroupBottomSheetDialogFragment.AddGroupListener createAddGroupListener() { - return new AddGroupBottomSheetDialogFragment.AddGroupListener() { - @Override - public void onGroupAdded() { - updateAdapter(); - } - }; - } - private AddMarkersGroupFragmentListener createAddMarkersGroupFragmentListener() { return new AddMarkersGroupFragmentListener() { @Override public void favouritesOnClick() { - AddFavouritesGroupBottomSheetDialogFragment fragment = new AddFavouritesGroupBottomSheetDialogFragment(); - openAddGroupMenu(fragment); + openAddGroupMenu(new AddFavouritesGroupBottomSheetDialogFragment()); } @Override public void waypointsOnClick() { - AddTracksGroupBottomSheetDialogFragment fragment = new AddTracksGroupBottomSheetDialogFragment(); - openAddGroupMenu(fragment); + openAddGroupMenu(new AddTracksGroupBottomSheetDialogFragment()); } }; } diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/SelectWptCategoriesBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/mapmarkers/SelectWptCategoriesBottomSheetDialogFragment.java new file mode 100644 index 0000000000..626a37b348 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/SelectWptCategoriesBottomSheetDialogFragment.java @@ -0,0 +1,159 @@ +package net.osmand.plus.mapmarkers; + +import android.os.Bundle; +import android.support.annotation.Nullable; +import android.view.View; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; + +import net.osmand.plus.GPXUtilities; +import net.osmand.plus.GPXUtilities.GPXFile; +import net.osmand.plus.GPXUtilities.WptPt; +import net.osmand.plus.GpxSelectionHelper; +import net.osmand.plus.GpxSelectionHelper.SelectedGpxFile; +import net.osmand.plus.MapMarkersHelper; +import net.osmand.plus.MapMarkersHelper.MapMarkersGroup; +import net.osmand.plus.OsmandApplication; +import net.osmand.plus.R; +import net.osmand.plus.base.MenuBottomSheetDialogFragment; +import net.osmand.plus.base.bottomsheetmenu.BottomSheetItemWithCompoundButton; +import net.osmand.plus.base.bottomsheetmenu.simpleitems.DescriptionItem; +import net.osmand.plus.base.bottomsheetmenu.simpleitems.DividerItem; +import net.osmand.plus.base.bottomsheetmenu.simpleitems.TitleItem; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class SelectWptCategoriesBottomSheetDialogFragment extends MenuBottomSheetDialogFragment { + + public static final String TAG = "SelectWptCategoriesBottomSheetDialogFragment"; + public static final String GPX_FILE_PATH_KEY = "gpx_file_path"; + + private GPXFile gpxFile; + + private Set selectedCategories = new HashSet<>(); + private List categoryItems = new ArrayList<>(); + + @Override + public void createMenuItems(Bundle savedInstanceState) { + gpxFile = getGpxFile(); + if (gpxFile == null) { + return; + } + + items.add(new TitleItem(getGpxName(gpxFile))); + + items.add(new DescriptionItem(getString(R.string.select_waypoints_category_description))); + + final BottomSheetItemWithCompoundButton[] selectAllItem = new BottomSheetItemWithCompoundButton[1]; + selectAllItem[0] = (BottomSheetItemWithCompoundButton) new BottomSheetItemWithCompoundButton.Builder() + .setDescription(getString(R.string.shared_string_total) + ": " + gpxFile.getPoints().size()) + .setIcon(getContentIcon(R.drawable.ic_action_group_select_all)) + .setTitle(getString(R.string.shared_string_select_all)) + .setLayoutId(R.layout.bottom_sheet_item_with_descr_and_checkbox_56dp) + .setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + boolean checked = !selectAllItem[0].isChecked(); + selectAllItem[0].setChecked(checked); + for (BottomSheetItemWithCompoundButton item : categoryItems) { + item.setChecked(checked); + } + } + }) + .create(); + items.add(selectAllItem[0]); + + items.add(new DividerItem(getContext())); + + Map> pointsByCategories = gpxFile.getPointsByCategories(); + + for (String category : pointsByCategories.keySet()) { + final BottomSheetItemWithCompoundButton[] categoryItem = new BottomSheetItemWithCompoundButton[1]; + categoryItem[0] = (BottomSheetItemWithCompoundButton) new BottomSheetItemWithCompoundButton.Builder() + .setOnCheckedChangeListener(new OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + if (isChecked) { + selectedCategories.add((String) categoryItem[0].getTag()); + } else { + selectedCategories.remove((String) categoryItem[0].getTag()); + } + } + }) + .setDescription(String.valueOf(pointsByCategories.get(category).size())) + .setIcon(getContentIcon(R.drawable.ic_action_folder)) + .setTitle(category.equals("") ? getString(R.string.waypoints) : category) + .setLayoutId(R.layout.bottom_sheet_item_with_descr_and_checkbox_56dp) + .setTag(category) + .setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + categoryItem[0].setChecked(!categoryItem[0].isChecked()); + selectAllItem[0].setChecked(isAllChecked()); + } + }) + .create(); + items.add(categoryItem[0]); + categoryItems.add(categoryItem[0]); + } + } + + @Override + protected int getRightBottomButtonTextId() { + return R.string.shared_string_import; + } + + @Override + protected void onRightBottomButtonClick() { + OsmandApplication app = getMyApplication(); + GpxSelectionHelper gpxSelectionHelper = app.getSelectedGpxHelper(); + MapMarkersHelper mapMarkersHelper = app.getMapMarkersHelper(); + + SelectedGpxFile selectedGpxFile = gpxSelectionHelper.getSelectedFileByPath(gpxFile.path); + if (selectedGpxFile == null) { + gpxSelectionHelper.selectGpxFile(gpxFile, true, false); + } + + MapMarkersGroup markersGr = mapMarkersHelper.getOrCreateGroup(new File(gpxFile.path)); + markersGr.setWptCategories(selectedCategories); + + mapMarkersHelper.syncWithMarkers(markersGr); + + dismiss(); + } + + private boolean isAllChecked() { + for (BottomSheetItemWithCompoundButton item : categoryItems) { + if (!item.isChecked()) { + return false; + } + } + return true; + } + + private String getGpxName(GPXFile gpxFile) { + return new File(gpxFile.path).getName() + .replace(".gpx", "") + .replace("/", " ") + .replace("_", " "); + } + + @Nullable + private GPXFile getGpxFile() { + String filePath = getArguments().getString(GPX_FILE_PATH_KEY); + if (filePath != null) { + OsmandApplication app = getMyApplication(); + SelectedGpxFile selectedGpx = app.getSelectedGpxHelper().getSelectedFileByPath(filePath); + if (selectedGpx != null && selectedGpx.getGpxFile() != null) { + return selectedGpx.getGpxFile(); + } + return GPXUtilities.loadGPXFile(app, new File(filePath)); + } + return null; + } +} diff --git a/OsmAnd/src/net/osmand/plus/mapmarkers/adapters/MapMarkersActiveAdapter.java b/OsmAnd/src/net/osmand/plus/mapmarkers/adapters/MapMarkersActiveAdapter.java index 92c995bdd9..3d4789ba55 100644 --- a/OsmAnd/src/net/osmand/plus/mapmarkers/adapters/MapMarkersActiveAdapter.java +++ b/OsmAnd/src/net/osmand/plus/mapmarkers/adapters/MapMarkersActiveAdapter.java @@ -237,7 +237,7 @@ public class MapMarkersActiveAdapter extends RecyclerView.Adapter(); - app.getMapMarkersHelper().updateGroups(); - List groups = app.getMapMarkersHelper().getMapMarkersGroups(); + MapMarkersHelper helper = app.getMapMarkersHelper(); + helper.updateGroups(); + List groups = new ArrayList<>(helper.getMapMarkersGroups()); + groups.addAll(helper.getGroupsForDisplayedGpx()); for (int i = 0; i < groups.size(); i++) { MapMarkersGroup group = groups.get(i); + if (!group.isVisible()) { + continue; + } String markerGroupName = group.getName(); if (markerGroupName == null) { int previousDateHeader = -1; @@ -148,7 +153,7 @@ public class MapMarkersGroupsAdapter extends RecyclerView.Adapter objectsToAdd = new ArrayList<>(); - if (showHideHistoryButton != null && showHideHistoryButton.isShowHistory()) { + if (showHideHistoryButton != null && showHideHistoryButton.showHistory) { objectsToAdd.addAll(group.getMarkers()); } else { objectsToAdd.addAll(group.getActiveMarkers()); @@ -168,7 +173,7 @@ public class MapMarkersGroupsAdapter extends RecyclerView.Adapter 0) { - if (getSettings().USE_MAP_MARKERS.get()) { - MapMarkersHelper markersHelper = app.getMapMarkersHelper(); - List points = new LinkedList<>(); - List names = new LinkedList<>(); - for (Map.Entry> entry : selectedItems.entrySet()) { - if (entry.getKey() != GpxDisplayItemType.TRACK_POINTS) { - for (GpxDisplayItem i : entry.getValue()) { - if (i.locationStart != null) { - points.add(new LatLon(i.locationStart.lat, i.locationStart.lon)); - names.add(new PointDescription(PointDescription.POINT_TYPE_MAP_MARKER, i.name)); - } - } - markersHelper.addMapMarkers(points, names, null); - } - } - MapActivity.launchMapActivityMoveToTop(getActivity()); - } else { - final TargetPointsHelper targetPointsHelper = getMyApplication().getTargetPointsHelper(); - for (GpxDisplayItem i : getSelectedItems()) { - if (i.locationStart != null) { - targetPointsHelper.navigateToPoint(new LatLon(i.locationStart.lat, i.locationStart.lon), false, - targetPointsHelper.getIntermediatePoints().size() + 1, - new PointDescription(PointDescription.POINT_TYPE_FAVORITE, i.name)); - } - } - if (getMyApplication().getRoutingHelper().isRouteCalculated()) { - targetPointsHelper.updateRouteAndRefresh(true); - } - IntermediatePointsDialog.openIntermediatePointsDialog(getActivity(), getMyApplication(), true); - } - } - } - private void enterFavoritesMode() { actionMode = getActionBarActivity().startSupportActionMode(new ActionMode.Callback() { diff --git a/OsmAnd/src/net/osmand/plus/views/GPXLayer.java b/OsmAnd/src/net/osmand/plus/views/GPXLayer.java index 48a77d8ecf..1b90115db1 100644 --- a/OsmAnd/src/net/osmand/plus/views/GPXLayer.java +++ b/OsmAnd/src/net/osmand/plus/views/GPXLayer.java @@ -20,7 +20,6 @@ import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; -import net.osmand.AndroidUtils; import net.osmand.data.LatLon; import net.osmand.data.PointDescription; import net.osmand.data.QuadRect; @@ -36,7 +35,6 @@ import net.osmand.plus.GpxSelectionHelper.GpxDisplayGroup; import net.osmand.plus.GpxSelectionHelper.GpxDisplayItem; import net.osmand.plus.GpxSelectionHelper.SelectedGpxFile; import net.osmand.plus.MapMarkersHelper; -import net.osmand.plus.MapMarkersHelper.MarkersSyncGroup; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandSettings.CommonPreference; import net.osmand.plus.R; @@ -666,8 +664,7 @@ public class GPXLayer extends OsmandMapLayer implements ContextMenuLayer.IContex private void syncGpx(GPXFile gpxFile) { File gpx = new File(gpxFile.path); if (gpx.exists()) { - mapMarkersHelper.syncGroupAsync(new MarkersSyncGroup(gpx.getAbsolutePath(), - AndroidUtils.trimExtension(gpx.getName()), MarkersSyncGroup.GPX_TYPE)); + mapMarkersHelper.runSynchronization(view.getApplication().getMapMarkersHelper().getOrCreateGroup(gpx)); } } diff --git a/OsmAnd/src/net/osmand/plus/views/MapMarkersLayer.java b/OsmAnd/src/net/osmand/plus/views/MapMarkersLayer.java index b9298bc8d9..155b034161 100644 --- a/OsmAnd/src/net/osmand/plus/views/MapMarkersLayer.java +++ b/OsmAnd/src/net/osmand/plus/views/MapMarkersLayer.java @@ -319,7 +319,7 @@ public class MapMarkersLayer extends OsmandMapLayer implements IContextMenuProvi widgetsFactory.updateInfo(useFingerLocation ? fingerLocation : null, tileBox.getZoom()); OsmandSettings settings = map.getMyApplication().getSettings(); - if (tileBox.getZoom() < 3 || !settings.USE_MAP_MARKERS.get()) { + if (tileBox.getZoom() < 3) { return; } @@ -514,7 +514,7 @@ public class MapMarkersLayer extends OsmandMapLayer implements IContextMenuProvi @Override public void collectObjectsFromPoint(PointF point, RotatedTileBox tileBox, List o, boolean unknownLocation) { - if (tileBox.getZoom() < 3 || !map.getMyApplication().getSettings().USE_MAP_MARKERS.get()) { + if (tileBox.getZoom() < 3) { return; } amenities.clear(); diff --git a/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapMarkersWidgetsFactory.java b/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapMarkersWidgetsFactory.java index c14ab304cb..33c2120da7 100644 --- a/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapMarkersWidgetsFactory.java +++ b/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapMarkersWidgetsFactory.java @@ -185,10 +185,6 @@ public class MapMarkersWidgetsFactory { } public void updateInfo(LatLon customLocation, int zoom) { - if (!map.getMyApplication().getSettings().USE_MAP_MARKERS.get()) { - return; - } - if (customLocation != null) { loc = customLocation; } else { diff --git a/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapWidgetRegistry.java b/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapWidgetRegistry.java index d3e66e0994..961a75d1dd 100644 --- a/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapWidgetRegistry.java +++ b/OsmAnd/src/net/osmand/plus/views/mapwidgets/MapWidgetRegistry.java @@ -321,26 +321,24 @@ public class MapWidgetRegistry { if (mode != ApplicationMode.DEFAULT) { addControlId(map, cm, R.string.map_widget_top_text, settings.SHOW_STREET_NAME); } - if (settings.USE_MAP_MARKERS.get()) { - cm.addItem(new ContextMenuItem.ItemBuilder().setTitleId(R.string.map_markers, map) - .setDescription(settings.MAP_MARKERS_MODE.get().toHumanString(map)) - .setListener(new ContextMenuAdapter.ItemClickListener() { - @Override - public boolean onContextMenuClick(final ArrayAdapter adapter, int itemId, final int position, boolean isChecked, int[] viewCoordinates) { - DirectionIndicationDialogFragment fragment = new DirectionIndicationDialogFragment(); - fragment.setListener(new DirectionIndicationDialogFragment.DirectionIndicationFragmentListener() { - @Override - public void onMapMarkersModeChanged(boolean showDirectionEnabled) { - updateMapMarkersMode(map); - cm.getItem(position).setDescription(settings.MAP_MARKERS_MODE.get().toHumanString(map)); - adapter.notifyDataSetChanged(); - } - }); - fragment.show(map.getSupportFragmentManager(), DirectionIndicationDialogFragment.TAG); - return false; - } - }).setLayout(R.layout.list_item_text_button).createItem()); - } + cm.addItem(new ContextMenuItem.ItemBuilder().setTitleId(R.string.map_markers, map) + .setDescription(settings.MAP_MARKERS_MODE.get().toHumanString(map)) + .setListener(new ContextMenuAdapter.ItemClickListener() { + @Override + public boolean onContextMenuClick(final ArrayAdapter adapter, int itemId, final int position, boolean isChecked, int[] viewCoordinates) { + DirectionIndicationDialogFragment fragment = new DirectionIndicationDialogFragment(); + fragment.setListener(new DirectionIndicationDialogFragment.DirectionIndicationFragmentListener() { + @Override + public void onMapMarkersModeChanged(boolean showDirectionEnabled) { + updateMapMarkersMode(map); + cm.getItem(position).setDescription(settings.MAP_MARKERS_MODE.get().toHumanString(map)); + adapter.notifyDataSetChanged(); + } + }); + fragment.show(map.getSupportFragmentManager(), DirectionIndicationDialogFragment.TAG); + return false; + } + }).setLayout(R.layout.list_item_text_button).createItem()); } public void updateMapMarkersMode(MapActivity mapActivity) {