Merge pull request #864 from deltachat/experimental_async_loading

[WIP] Experimental async loading
This commit is contained in:
björn petersen
2019-04-25 12:47:13 +02:00
committed by GitHub
8 changed files with 428 additions and 310 deletions
@@ -1,27 +1,18 @@
package org.thoughtcrime.securesms.map;
import android.os.AsyncTask;
import android.util.Log;
import com.b44t.messenger.DcArray;
import com.b44t.messenger.DcContext;
import com.google.gson.JsonObject;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.LineString;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
import org.thoughtcrime.securesms.map.model.MapSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;
import static org.thoughtcrime.securesms.map.MapDataManager.ACCURACY;
import static org.thoughtcrime.securesms.map.MapDataManager.CONTACT_ID;
import static org.thoughtcrime.securesms.map.MapDataManager.LAST_LOCATION;
import static org.thoughtcrime.securesms.map.MapDataManager.MARKER_SELECTED;
import static org.thoughtcrime.securesms.map.MapDataManager.MESSAGE_ID;
import static org.thoughtcrime.securesms.map.MapDataManager.TIMESTAMP;
import static org.thoughtcrime.securesms.map.MapDataManager.TIMESTAMP_NOW;
import static org.thoughtcrime.securesms.map.MapDataManager.TIME_FRAME;
@@ -29,86 +20,81 @@ import static org.thoughtcrime.securesms.map.MapDataManager.TIME_FRAME;
* Created by cyberta on 15.04.19.
*/
public class DataCollectionTask extends AsyncTask<Void, DataCollectionTask.DataCollection, DataCollectionTask.DataCollection> {
public class DataCollectionTask extends AsyncTask<Void, Void, Void> {
public class DataCollection {
HashMap<String, ArrayList<Feature>> featureCollections;
public DataCollection(HashMap<String, ArrayList<Feature>> featureCollections) {
this.featureCollections = featureCollections;
}
public interface DataCollectionCallback {
void onDataCollectionFinished();
}
private static final String TAG = DataCollectionTask.class.getSimpleName();
private static final HashSet<DataCollectionTask> instances = new HashSet<>();
private final int chatId;
private final HashMap<Integer, MapSource> contactMapSources;
private final int[] contactIds;
private ConcurrentHashMap<Integer, MapSource> contactMapSources;
private ConcurrentHashMap<String, LinkedList<Feature>> featureCollections;
private ConcurrentHashMap<Integer, Feature> lastPositions;
private final LatLngBounds.Builder boundingBuilder;
private final DcContext dcContext;
private final DataCollectionCallback callback;
public DataCollectionTask(DcContext context, int chatId, HashMap<Integer, MapSource> contactMapSources, LatLngBounds.Builder boundingBuilder) {
public DataCollectionTask(DcContext context,
int chatId,
int[] contactIds,
ConcurrentHashMap<Integer, MapSource> contactMapSources,
ConcurrentHashMap featureCollections,
ConcurrentHashMap<Integer, Feature> lastPositions,
LatLngBounds.Builder boundingBuilder,
DataCollectionCallback callback) {
this.chatId = chatId;
this.contactMapSources = contactMapSources;
this.featureCollections = featureCollections;
this.lastPositions = lastPositions;
this.boundingBuilder = boundingBuilder;
this.dcContext = context;
this.callback = callback;
this.contactIds = contactIds;
instances.add(this);
}
public static void cancelRunningTasks() {
for (DataCollectionTask task : instances) {
task.cancel(true);
}
}
@Override
protected DataCollection doInBackground(Void... voids) {
HashMap<String, ArrayList<Feature>> featureCollections = new HashMap<>();
for (int contactId : contactMapSources.keySet()) {
updateSource(chatId, contactId, System.currentTimeMillis() - TIME_FRAME, TIMESTAMP_NOW, featureCollections, boundingBuilder);
}
return new DataCollection(featureCollections);
}
private void updateSource(int chatId, int contactId, long startTimestamp, long endTimestamp, HashMap<String, ArrayList<Feature>> featureCollections, LatLngBounds.Builder boundingBuilder) {
//long start = System.currentTimeMillis();
DcArray locations = dcContext.getLocations(chatId, contactId, startTimestamp, endTimestamp);
MapSource contactMapMetadata = contactMapSources.get(contactId);
ArrayList<Feature> sortedPointFeatures = new ArrayList<>();
ArrayList<Feature> sortedLineFeatures = new ArrayList<>();
int count = locations.getCnt();
for (int i = sortedPointFeatures.size(); i < count; i++) {
Point point = Point.fromLngLat(locations.getLongitude(i), locations.getLatitude(i));
Feature pointFeature = Feature.fromGeometry(point, new JsonObject(), String.valueOf(locations.getLocationId(i)));
pointFeature.addBooleanProperty(MARKER_SELECTED, false);
pointFeature.addBooleanProperty(LAST_LOCATION, false);
pointFeature.addNumberProperty(CONTACT_ID, contactId);
pointFeature.addNumberProperty(TIMESTAMP, locations.getTimestamp(i));
pointFeature.addNumberProperty(MESSAGE_ID, locations.getMsgId(i));
pointFeature.addNumberProperty(ACCURACY, locations.getAccuracy(i));
sortedPointFeatures.add(pointFeature);
if (i > 0) {
Point lastPoint = (Point) sortedPointFeatures.get(i - 1).geometry();
ArrayList<Point> lineSegmentPoints = new ArrayList<>(3);
lineSegmentPoints.add(lastPoint);
lineSegmentPoints.add(point);
LineString l = LineString.fromLngLats(lineSegmentPoints);
Feature lineFeature = Feature.fromGeometry(l, new JsonObject(), "l_" + pointFeature.id());
lineFeature.addNumberProperty(TIMESTAMP, pointFeature.getNumberProperty(TIMESTAMP));
sortedLineFeatures.add(lineFeature);
}
if (boundingBuilder != null) {
boundingBuilder.include(new LatLng(locations.getLatitude(i), locations.getLongitude(i)));
protected Void doInBackground(Void... voids) {
Log.d(TAG, "performance test - collect Data start");
DataCollector dataCollector = new DataCollector(dcContext,
contactMapSources,
featureCollections,
lastPositions,
boundingBuilder);
for (int contactId : contactIds) {
dataCollector.updateSource(chatId,
contactId,
System.currentTimeMillis() - TIME_FRAME,
TIMESTAMP_NOW);
if (this.isCancelled()) {
break;
}
}
if (sortedPointFeatures.size() > 0) {
sortedPointFeatures.get(0).addBooleanProperty(LAST_LOCATION, true);
}
featureCollections.put(contactMapMetadata.getMarkerFeatureCollection(), sortedPointFeatures);
featureCollections.put(contactMapMetadata.getLineFeatureCollection(), sortedLineFeatures);
//Log.d(TAG, "update Source took " + (System.currentTimeMillis() - start) + " ms");
return null;
}
@Override
protected void onPostExecute(Void value) {
if (!this.isCancelled()) {
callback.onDataCollectionFinished();
}
instances.remove(this);
Log.d(TAG, "performance test - collect Data finished");
}
@Override
protected void onCancelled() {
super.onCancelled();
instances.remove(this);
}
}
@@ -0,0 +1,136 @@
package org.thoughtcrime.securesms.map;
import com.b44t.messenger.DcArray;
import com.b44t.messenger.DcContact;
import com.b44t.messenger.DcContext;
import com.google.gson.JsonObject;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.LineString;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
import org.thoughtcrime.securesms.map.model.MapSource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;
import static org.thoughtcrime.securesms.map.MapDataManager.ACCURACY;
import static org.thoughtcrime.securesms.map.MapDataManager.CONTACT_ID;
import static org.thoughtcrime.securesms.map.MapDataManager.LAST_LOCATION;
import static org.thoughtcrime.securesms.map.MapDataManager.LAST_POSITION_ICON;
import static org.thoughtcrime.securesms.map.MapDataManager.MARKER_CHAR;
import static org.thoughtcrime.securesms.map.MapDataManager.MARKER_ICON;
import static org.thoughtcrime.securesms.map.MapDataManager.MARKER_SELECTED;
import static org.thoughtcrime.securesms.map.MapDataManager.MESSAGE_ID;
import static org.thoughtcrime.securesms.map.MapDataManager.TIMESTAMP;
/**
* Created by cyberta on 18.04.19.
*/
public class DataCollector {
private final DcContext dcContext;
private ConcurrentHashMap<Integer, MapSource> contactMapSources;
private ConcurrentHashMap<String, LinkedList<Feature>> featureCollections;
private ConcurrentHashMap<Integer, Feature> lastPositions;
private LatLngBounds.Builder boundingBuilder;
public DataCollector(DcContext dcContext,
ConcurrentHashMap<Integer, MapSource> contactMapSources,
ConcurrentHashMap<String, LinkedList<Feature>> featureCollections,
ConcurrentHashMap<Integer, Feature> lastPositions,
LatLngBounds.Builder boundingBuilder) {
this.dcContext = dcContext;
this.contactMapSources = contactMapSources;
this.featureCollections = featureCollections;
this.lastPositions = lastPositions;
this.boundingBuilder = boundingBuilder;
}
public void updateSource(int chatId,
int contactId,
long startTimestamp,
long endTimestamp) {
DcArray locations = dcContext.getLocations(chatId, contactId, startTimestamp, endTimestamp);
int count = locations.getCnt();
if (count == 0) {
return;
}
MapSource contactMapMetadata = contactMapSources.get(contactId);
if (contactMapMetadata == null) {
contactMapMetadata = addContactMapSource(contactMapSources, contactId);
}
LinkedList<Feature> sortedPointFeatures = featureCollections.get(contactMapMetadata.getMarkerFeatureCollection());
if (sortedPointFeatures != null && sortedPointFeatures.size() == count) {
return;
} else {
sortedPointFeatures = new LinkedList<>();
}
LinkedList<Feature> sortedLineFeatures = new LinkedList<>();
for (int i = count - 1; i >= 0; i--) {
Point point = Point.fromLngLat(locations.getLongitude(i), locations.getLatitude(i));
String codepointChar =
locations.getMarker(i) != null ?
locations.getMarker(i) :
"";
Feature pointFeature = Feature.fromGeometry(point, new JsonObject(), String.valueOf(locations.getLocationId(i)));
pointFeature.addBooleanProperty(MARKER_SELECTED, false);
pointFeature.addBooleanProperty(LAST_LOCATION, false);
pointFeature.addNumberProperty(CONTACT_ID, contactId);
pointFeature.addNumberProperty(TIMESTAMP, locations.getTimestamp(i));
pointFeature.addNumberProperty(MESSAGE_ID, locations.getMsgId(i));
pointFeature.addNumberProperty(ACCURACY, locations.getAccuracy(i));
pointFeature.addStringProperty(MARKER_CHAR, codepointChar);
pointFeature.addStringProperty(MARKER_ICON, contactMapMetadata.getMarkerIcon());
sortedPointFeatures.addFirst(pointFeature);
if (sortedPointFeatures.size() > 1) {
Point lastPoint = (Point) sortedPointFeatures.get(1).geometry();
ArrayList<Point> lineSegmentPoints = new ArrayList<>(3);
lineSegmentPoints.add(lastPoint);
lineSegmentPoints.add(point);
LineString l = LineString.fromLngLats(lineSegmentPoints);
Feature lineFeature = Feature.fromGeometry(l, new JsonObject(), "l_" + pointFeature.id());
lineFeature.addNumberProperty(TIMESTAMP, pointFeature.getNumberProperty(TIMESTAMP));
sortedLineFeatures.addFirst(lineFeature);
}
if (boundingBuilder != null) {
boundingBuilder.include(new LatLng(locations.getLatitude(i), locations.getLongitude(i)));
}
}
if (sortedPointFeatures.size() > 0) {
Feature lastPostion = sortedPointFeatures.getFirst();
lastPostion.addStringProperty(LAST_POSITION_ICON, contactMapMetadata.getMarkerLastPositon());
lastPostion.removeProperty(MARKER_ICON);
lastPostion.addBooleanProperty(LAST_LOCATION, true);
lastPositions.put(contactId, lastPostion);
}
featureCollections.put(contactMapMetadata.getMarkerFeatureCollection(), sortedPointFeatures);
featureCollections.put(contactMapMetadata.getLineFeatureCollection(), sortedLineFeatures);
}
private MapSource addContactMapSource(ConcurrentHashMap<Integer, MapSource> contactMapSources, int contactId) {
if (contactMapSources.get(contactId) != null) {
return contactMapSources.get(contactId);
}
DcContact contact = dcContext.getContact(contactId);
MapSource contactMapSource = new MapSource(contactId);
contactMapSource.setColor(contact.getColor());
contactMapSources.put(contactId, contactMapSource);
return contactMapSource;
}
}
@@ -1,19 +0,0 @@
package org.thoughtcrime.securesms.map;
import android.content.Context;
import android.graphics.Bitmap;
import java.util.HashMap;
/**
* Created by cyberta on 13.03.19.
*/
public interface GenerateInfoWindowCallback {
Context getContext();
/**
* Invoked when the bitmaps have been generated from a view.
*/
void setInfoWindowResults(Bitmap result);
}
@@ -4,6 +4,7 @@ package org.thoughtcrime.securesms.map;
* Created by cyberta on 13.03.19.
*/
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
@@ -48,6 +49,15 @@ import static org.thoughtcrime.securesms.map.MapDataManager.TIMESTAMP;
*/
class GenerateInfoWindowTask extends AsyncTask<Feature, Bitmap, Bitmap> {
public interface GenerateInfoWindowCallback {
Context getContext();
/**
* Invoked when the bitmaps have been generated from a view.
*/
void setInfoWindowResults(Bitmap result);
}
private static final String TAG = GenerateInfoWindowCallback.class.getName();
private final WeakReference<GenerateInfoWindowCallback> callbackRef;
private final static HashSet<GenerateInfoWindowTask> instances = new HashSet<>();
@@ -28,14 +28,17 @@ import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.components.rangeslider.TimeRangeSlider;
import org.thoughtcrime.securesms.connect.DcHelper;
import org.thoughtcrime.securesms.geolocation.DcLocation;
import org.thoughtcrime.securesms.util.Prefs;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;
import static android.support.design.widget.BottomSheetBehavior.STATE_COLLAPSED;
import static android.support.design.widget.BottomSheetBehavior.STATE_EXPANDED;
import static com.b44t.messenger.DcChat.DC_CHAT_NO_CHAT;
import static com.mapbox.mapboxsdk.constants.MapboxConstants.MINIMUM_ZOOM;
import static org.thoughtcrime.securesms.map.MapDataManager.MARKER_SELECTED;
import static org.thoughtcrime.securesms.map.MapDataManager.MESSAGE_ID;
import static org.thoughtcrime.securesms.map.model.MapSource.INFO_WINDOW_LAYER;
@@ -78,10 +81,26 @@ public class MapActivity extends BaseActivity implements Observer, TimeRangeSlid
mapFragment.getMapAsync(mapboxMap -> mapboxMap.setStyle(Style.MAPBOX_STREETS, style -> {
this.mapboxMap = mapboxMap;
mapboxMap.setCameraPosition(new CameraPosition.Builder()
.target(new LatLng(dcLocation.getLastLocation().getLatitude(), dcLocation.getLastLocation().getLongitude()))
.zoom(9)
.build());
final LatLng lastMapCenter = Prefs.getMapCenter(this.getApplicationContext(), chatId);
if (lastMapCenter != null) {
double lastZoom = Prefs.getMapZoom(this.getApplicationContext(), chatId);
mapboxMap.setCameraPosition(new CameraPosition.Builder()
.target(lastMapCenter)
.zoom(lastZoom)
.build());
} else if (dcLocation.getLastLocation().getProvider().equals("?")) {
double randomLongitude = getRandomLongitude();
mapboxMap.setCameraPosition(new CameraPosition.Builder()
.target(new LatLng(0d, randomLongitude))
.zoom(MINIMUM_ZOOM)
.build());
} else {
mapboxMap.setCameraPosition(new CameraPosition.Builder()
.target(new LatLng(dcLocation.getLastLocation().getLatitude(), dcLocation.getLastLocation().getLongitude()))
.zoom(9)
.build());
}
mapboxMap.getUiSettings().setLogoEnabled(false);
mapboxMap.getUiSettings().setAttributionEnabled(false);
@@ -92,84 +111,86 @@ public class MapActivity extends BaseActivity implements Observer, TimeRangeSlid
mapDataManager = new MapDataManager(this, mapBoxStyle, chatId, (latLngBounds) -> {
Log.d(TAG, "on Data initialized");
mapboxMap.easeCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, 50), 1000);
});
mapboxMap.addOnMapClickListener(point -> {
final PointF pixel = mapboxMap.getProjection().toScreenLocation(point);
Log.d(TAG, "on item clicked.");
List<Feature> features = mapboxMap.queryRenderedFeatures(pixel, mapDataManager.getMarkerLayers());
for (Feature feature : features) {
Log.d(TAG, "found feature: " + feature.toJson());
//show first feature that has meta data infos
if (feature.hasProperty(MARKER_SELECTED)) {
mapDataManager.setMarkerSelected(feature.id());
return true;
}
if (latLngBounds != null && lastMapCenter == null) {
mapboxMap.easeCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, 50), 1000);
}
mapDataManager.unselectMarker();
return false;
});
mapboxMap.addOnMapClickListener(point -> {
final PointF pixel = mapboxMap.getProjection().toScreenLocation(point);
mapboxMap.addOnMapClickListener(point -> {
final PointF pixel = mapboxMap.getProjection().toScreenLocation(point);
Log.d(TAG, "on item clicked.");
List<Feature> features = mapboxMap.queryRenderedFeatures(pixel, INFO_WINDOW_LAYER);
Log.d(TAG, "on info window clicked." + features.size());
for (Feature feature : features) {
Log.d(TAG, "found feature: " + feature.toJson());
int messageId = feature.getNumberProperty(MESSAGE_ID).intValue();
DcMsg dcMsg = ApplicationContext.getInstance(this).dcContext.getMsg(messageId);
int dcMsgChatId = dcMsg.getChatId();
if (dcMsgChatId == DC_CHAT_NO_CHAT) {
continue;
}
int msgs[] = DcHelper.getContext(MapActivity.this).getChatMsgs(dcMsgChatId, 0, 0);
int startingPosition = -1;
for(int i=0; i< msgs.length; i++ ) {
if(msgs[i] == messageId) {
startingPosition = msgs.length-1-i;
break;
List<Feature> features = mapboxMap.queryRenderedFeatures(pixel, mapDataManager.getMarkerLayers());
for (Feature feature : features) {
Log.d(TAG, "found feature: " + feature.toJson());
//show first feature that has meta data infos
if (feature.hasProperty(MARKER_SELECTED)) {
mapDataManager.setMarkerSelected(feature.id());
return true;
}
}
Intent intent = new Intent(MapActivity.this, ConversationActivity.class);
intent.putExtra(ConversationActivity.THREAD_ID_EXTRA, dcMsgChatId);
intent.putExtra(ConversationActivity.LAST_SEEN_EXTRA, 0);
intent.putExtra(ConversationActivity.STARTING_POSITION_EXTRA, startingPosition);
startActivity(intent);
return true;
}
return false;
});
if (BuildConfig.DEBUG) {
mapboxMap.addOnMapLongClickListener(point -> {
new AlertDialog.Builder(MapActivity.this)
.setMessage(getString(R.string.menu_delete_locations))
.setPositiveButton(R.string.yes, (dialog, which) -> {
ApplicationContext.getInstance(MapActivity.this).dcLocationManager.deleteAllLocations();
})
.setNegativeButton(R.string.no, null)
.show();
return true;
mapDataManager.unselectMarker();
return false;
});
}
SwitchCompat switchCompat = this.findViewById(R.id.locationTraceSwitch);
switchCompat.setOnCheckedChangeListener((buttonView, isChecked) -> {
mapDataManager.showTraces(isChecked);
mapboxMap.addOnMapClickListener(point -> {
final PointF pixel = mapboxMap.getProjection().toScreenLocation(point);
List<Feature> features = mapboxMap.queryRenderedFeatures(pixel, INFO_WINDOW_LAYER);
Log.d(TAG, "on info window clicked." + features.size());
for (Feature feature : features) {
Log.d(TAG, "found feature: " + feature.toJson());
int messageId = feature.getNumberProperty(MESSAGE_ID).intValue();
DcMsg dcMsg = ApplicationContext.getInstance(this).dcContext.getMsg(messageId);
int dcMsgChatId = dcMsg.getChatId();
if (dcMsgChatId == DC_CHAT_NO_CHAT) {
continue;
}
int msgs[] = DcHelper.getContext(MapActivity.this).getChatMsgs(dcMsgChatId, 0, 0);
int startingPosition = -1;
for(int i=0; i< msgs.length; i++ ) {
if(msgs[i] == messageId) {
startingPosition = msgs.length-1-i;
break;
}
}
Intent intent = new Intent(MapActivity.this, ConversationActivity.class);
intent.putExtra(ConversationActivity.THREAD_ID_EXTRA, dcMsgChatId);
intent.putExtra(ConversationActivity.LAST_SEEN_EXTRA, 0);
intent.putExtra(ConversationActivity.STARTING_POSITION_EXTRA, startingPosition);
startActivity(intent);
return true;
}
return false;
});
if (BuildConfig.DEBUG) {
mapboxMap.addOnMapLongClickListener(point -> {
new AlertDialog.Builder(MapActivity.this)
.setMessage(getString(R.string.menu_delete_locations))
.setPositiveButton(R.string.yes, (dialog, which) -> {
ApplicationContext.getInstance(MapActivity.this).dcLocationManager.deleteAllLocations();
})
.setNegativeButton(R.string.no, null)
.show();
return true;
});
}
SwitchCompat switchCompat = this.findViewById(R.id.locationTraceSwitch);
switchCompat.setOnCheckedChangeListener((buttonView, isChecked) -> {
mapDataManager.showTraces(isChecked);
});
});
}));
TimeRangeSlider timeRangeSlider = this.findViewById(R.id.timeRangeSlider);
timeRangeSlider.setOnTimestampChangedListener(this);
TimeRangeSlider timeRangeSlider = this.findViewById(R.id.timeRangeSlider);
timeRangeSlider.setOnTimestampChangedListener(this);
}));
View bottomSheet = this.findViewById(R.id.bottom_sheet);
BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet);
@@ -211,6 +232,8 @@ public class MapActivity extends BaseActivity implements Observer, TimeRangeSlid
protected void onDestroy() {
super.onDestroy();
if (mapDataManager != null) {
Prefs.setMapCenter(this.getApplicationContext(), mapDataManager.getChatId(), mapboxMap.getCameraPosition().target);
Prefs.setMapZoom(this.getApplicationContext(), mapDataManager.getChatId(), mapboxMap.getCameraPosition().zoom);
mapDataManager.onDestroy();
}
}
@@ -242,4 +265,12 @@ public class MapActivity extends BaseActivity implements Observer, TimeRangeSlid
}
mapDataManager.filterLastPositions(startTimestamp);
}
double getRandomLongitude() {
double start = -180;
double end = 180;
double random = new Random().nextDouble();
return start + (random * (end - start));
}
}
@@ -13,16 +13,10 @@ import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.b44t.messenger.DcArray;
import com.b44t.messenger.DcContact;
import com.b44t.messenger.DcEventCenter;
import com.google.gson.JsonObject;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.FeatureCollection;
import com.mapbox.geojson.LineString;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.exceptions.InvalidLatLngBoundsException;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.expressions.Expression;
@@ -35,14 +29,17 @@ import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.connect.ApplicationDcContext;
import org.thoughtcrime.securesms.connect.DcHelper;
import org.thoughtcrime.securesms.map.DataCollectionTask.DataCollectionCallback;
import org.thoughtcrime.securesms.map.GenerateInfoWindowTask.GenerateInfoWindowCallback;
import org.thoughtcrime.securesms.map.model.FilterProvider;
import org.thoughtcrime.securesms.map.model.MapSource;
import org.thoughtcrime.securesms.util.Prefs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static com.b44t.messenger.DcContext.DC_EVENT_LOCATION_CHANGED;
import static com.b44t.messenger.DcContext.DC_GCL_ADD_SELF;
@@ -81,7 +78,7 @@ import static org.thoughtcrime.securesms.map.model.MapSource.LINE_FEATURE_LIST;
* Created by cyberta on 07.03.19.
*/
public class MapDataManager implements DcEventCenter.DcEventDelegate, GenerateInfoWindowCallback {
public class MapDataManager implements DcEventCenter.DcEventDelegate, GenerateInfoWindowCallback, DataCollectionCallback {
public static final String MARKER_SELECTED = "MARKER_SELECTED";
public static final String LAST_LOCATION = "LAST_LOCATION";
public static final String CONTACT_ID = "CONTACT_ID";
@@ -95,7 +92,6 @@ public class MapDataManager implements DcEventCenter.DcEventDelegate, GenerateIn
private static final String INFO_WINDOW_SRC = "INFO_WINDOW_SRC";
private static final String LAST_POSITION_LAYER = "LAST_POSITION_LAYER";
private static final String LAST_POSITION_SOURCE = "LAST_POSITION_SRC";
private static final String LAST_POSITION_ICON_ID = "LAST_POSITION_ICN_ID";
public static final int ALL_CHATS_GLOBAL_MAP = 0;
public static final long TIMESTAMP_NOW = 0L;
@@ -104,14 +100,16 @@ public class MapDataManager implements DcEventCenter.DcEventDelegate, GenerateIn
private static final String TAG = MapDataManager.class.getSimpleName();
private Style mapboxStyle;
private HashMap<Integer, MapSource> contactMapSources = new HashMap<>();
private HashMap<String, LinkedList<Feature>> featureCollections = new HashMap<>();
private HashMap<Integer, Feature> lastPositions = new HashMap<>();
private ConcurrentHashMap<Integer, MapSource> contactMapSources = new ConcurrentHashMap<>();
private ConcurrentHashMap<String, LinkedList<Feature>> featureCollections = new ConcurrentHashMap<>();
private ConcurrentHashMap<Integer, Feature> lastPositions = new ConcurrentHashMap<>();
private FilterProvider filterProvider = new FilterProvider();
private Feature selectedFeature;
private int chatId;
private LatLngBounds.Builder boundingBuilder;
private Context context;
private ApplicationDcContext dcContext;
private MapDataState callback;
private boolean isInitial = true;
private boolean showTraces = false;
@@ -120,35 +118,25 @@ public class MapDataManager implements DcEventCenter.DcEventDelegate, GenerateIn
}
public MapDataManager(Context context, @NonNull Style mapboxMapStyle, int chatId, MapDataState updateCallback) {
Log.d(TAG, "performance test - create map manager");
this.mapboxStyle = mapboxMapStyle;
this.context = context;
this.dcContext = DcHelper.getContext(context);
this.chatId = chatId;
LatLngBounds.Builder boundingBuilder = new LatLngBounds.Builder();
boundingBuilder = new LatLngBounds.Builder();
this.callback = updateCallback;
int[] contactIds = getContactIds(chatId);
initInfoWindowLayer();
initLastPositionLayer();
filterProvider.setMessageFilter(true);
filterProvider.setLastPositionFilter(System.currentTimeMillis() - DEFAULT_LAST_POSITION_DELTA);
applyLastPositionFilter();
for (int contactId : contactIds) {
updateSource(chatId, contactId, boundingBuilder);
MapSource source = contactMapSources.get(contactId);
if (source != null) {
applyMarkerFilter(source);
applyLineFilter(source);
}
}
updateSources();
dcContext.eventCenter.addObserver(DC_EVENT_LOCATION_CHANGED, this);
try {
updateCallback.onDataInitialized(boundingBuilder.build());
} catch (InvalidLatLngBoundsException e) {
e.printStackTrace();
}
Log.d(TAG, "performance test - create map manager finished");
}
public void onResume() {
@@ -165,6 +153,8 @@ public class MapDataManager implements DcEventCenter.DcEventDelegate, GenerateIn
public void onDestroy() {
GenerateInfoWindowTask.cancelRunningTasks();
DataCollectionTask.cancelRunningTasks();
Log.d(TAG, "performance test - Map manager destroyed");
}
@Override
@@ -189,7 +179,16 @@ public class MapDataManager implements DcEventCenter.DcEventDelegate, GenerateIn
Log.d(TAG, "updateEvent in MapDataManager called. eventId: " + eventId);
int contactId = ((Long) data1).intValue();
if (contactMapSources.containsKey(contactId)) {
updateSource(chatId, contactId);
DataCollector collector = new DataCollector(dcContext,
contactMapSources,
featureCollections,
lastPositions, null);
collector.updateSource(chatId,
contactId,
System.currentTimeMillis() - TIME_FRAME,
TIMESTAMP_NOW);
refreshSource(contactId);
}
Log.d(TAG, "updateEvent in MapDataManager called. finished: " + eventId);
}
@@ -244,6 +243,27 @@ public class MapDataManager implements DcEventCenter.DcEventDelegate, GenerateIn
infoWindowSource.setGeoJson(selectedFeature);
}
@Override
public void onDataCollectionFinished() {
for (MapSource source : contactMapSources.values()) {
initContactBasedLayers(source);
refreshSource(source.getContactId());
applyMarkerFilter(source);
applyLineFilter(source);
}
if (boundingBuilder != null && callback != null) {
LatLngBounds bound = null;
try {
bound = boundingBuilder.build();
} catch (InvalidLatLngBoundsException e) {
Log.w(TAG, e.getLocalizedMessage());
}
callback.onDataInitialized(bound);
}
}
public void filterRange(long startTimestamp, long endTimestamp) {
int[] contactIds = getContactIds(chatId);
filterProvider.setRangeFilter(startTimestamp, endTimestamp);
@@ -263,6 +283,10 @@ public class MapDataManager implements DcEventCenter.DcEventDelegate, GenerateIn
applyFilters(contactIds);
}
public int getChatId() {
return chatId;
}
private void showLineLayer(MapSource source) {
LineLayer lineLayer = (LineLayer) mapboxStyle.getLayer(source.getLineLayer());
lineLayer.setProperties(visibility(showTraces ? VISIBLE : NONE));
@@ -296,99 +320,6 @@ public class MapDataManager implements DcEventCenter.DcEventDelegate, GenerateIn
lineLayer.setFilter(filterProvider.getTimeFilter());
}
private void updateSource(int chatId, int contactId) {
updateSource(chatId, contactId, null);
}
private void updateSource(int chatId, int contactId, LatLngBounds.Builder boundingBuilder) {
updateSource(chatId, contactId, System.currentTimeMillis() - TIME_FRAME, TIMESTAMP_NOW, boundingBuilder );
}
private void updateSource(int chatId, int contactId, long startTimestamp, long endTimestamp, LatLngBounds.Builder boundingBuilder) {
//long start = System.currentTimeMillis();
DcArray locations = dcContext.getLocations(chatId, contactId, startTimestamp, endTimestamp);
int count = locations.getCnt();
if (count == 0) {
return;
}
MapSource contactMapMetadata = contactMapSources.get(contactId);
if (contactMapMetadata == null) {
contactMapMetadata = addContactMapSource(contactId);
}
LinkedList<Feature> sortedPointFeatures = featureCollections.get(contactMapMetadata.getMarkerFeatureCollection());
if (sortedPointFeatures != null && sortedPointFeatures.size() == count) {
return;
} else {
sortedPointFeatures = new LinkedList<>();
}
LinkedList<Feature> sortedLineFeatures = new LinkedList<>();
for (int i = count - 1; i >= 0; i--) {
Point point = Point.fromLngLat(locations.getLongitude(i), locations.getLatitude(i));
String codepointChar =
locations.getMarker(i) != null ?
locations.getMarker(i) :
"";
Feature pointFeature = Feature.fromGeometry(point, new JsonObject(), String.valueOf(locations.getLocationId(i)));
pointFeature.addBooleanProperty(MARKER_SELECTED, false);
pointFeature.addBooleanProperty(LAST_LOCATION, false);
pointFeature.addNumberProperty(CONTACT_ID, contactId);
pointFeature.addNumberProperty(TIMESTAMP, locations.getTimestamp(i));
pointFeature.addNumberProperty(MESSAGE_ID, locations.getMsgId(i));
pointFeature.addNumberProperty(ACCURACY, locations.getAccuracy(i));
pointFeature.addStringProperty(MARKER_CHAR, codepointChar);
pointFeature.addStringProperty(MARKER_ICON, contactMapMetadata.getMarkerIcon());
sortedPointFeatures.addFirst(pointFeature);
if (sortedPointFeatures.size() > 1) {
Point lastPoint = (Point) sortedPointFeatures.get(1).geometry();
ArrayList<Point> lineSegmentPoints = new ArrayList<>(3);
lineSegmentPoints.add(lastPoint);
lineSegmentPoints.add(point);
LineString l = LineString.fromLngLats(lineSegmentPoints);
Feature lineFeature = Feature.fromGeometry(l, new JsonObject(), "l_" + pointFeature.id());
lineFeature.addNumberProperty(TIMESTAMP, pointFeature.getNumberProperty(TIMESTAMP));
sortedLineFeatures.addFirst(lineFeature);
}
if (boundingBuilder != null) {
boundingBuilder.include(new LatLng(locations.getLatitude(i), locations.getLongitude(i)));
}
}
if (sortedPointFeatures.size() > 0) {
Feature lastPostion = sortedPointFeatures.getFirst();
lastPostion.addStringProperty(LAST_POSITION_ICON, contactMapMetadata.getMarkerLastPositon());
lastPostion.removeProperty(MARKER_ICON);
lastPostion.addBooleanProperty(LAST_LOCATION, true);
lastPositions.put(contactId, lastPostion);
}
featureCollections.put(contactMapMetadata.getMarkerFeatureCollection(), sortedPointFeatures);
featureCollections.put(contactMapMetadata.getLineFeatureCollection(), sortedLineFeatures);
refreshSource(contactId);
//Log.d(TAG, "update Source took " + (System.currentTimeMillis() - start) + " ms");
}
private void initGeoJsonSources(MapSource source) {
GeoJsonSource markerPositionSource = new GeoJsonSource(source.getMarkerSource());
GeoJsonSource linePositionSource = new GeoJsonSource(source.getLineSource());
try {
mapboxStyle.addSource(markerPositionSource);
mapboxStyle.addSource(linePositionSource);
} catch (RuntimeException e) {
//TODO: specify exception more
Log.e(TAG, "Unable to init GeoJsonSources. Already added to mapBoxMap? " + e.getMessage());
}
}
private int[] getContactIds(int chatId) {
if (chatId == ALL_CHATS_GLOBAL_MAP) {
return dcContext.getContacts(DC_GCL_ADD_SELF, "");
@@ -441,6 +372,21 @@ public class MapDataManager implements DcEventCenter.DcEventDelegate, GenerateIn
}
private void initContactBasedLayers(MapSource source) {
if (mapboxStyle.getLayer(source.getMarkerLayer()) != null) {
return;
}
GeoJsonSource markerPositionSource = new GeoJsonSource(source.getMarkerSource());
GeoJsonSource linePositionSource = new GeoJsonSource(source.getLineSource());
try {
mapboxStyle.addSource(markerPositionSource);
mapboxStyle.addSource(linePositionSource);
} catch (RuntimeException e) {
//TODO: specify exception more
Log.e(TAG, "Unable to init GeoJsonSources. Already added to mapBoxMap? " + e.getMessage());
}
mapboxStyle.addImage(source.getMarkerLastPositon(),
generateColoredLastPositionIcon(source.getColorArgb()));
mapboxStyle.addImage(source.getMarkerIcon(),
@@ -482,20 +428,6 @@ public class MapDataManager implements DcEventCenter.DcEventDelegate, GenerateIn
LAST_POSITION_LAYER);
}
private MapSource addContactMapSource(int contactId) {
if (contactMapSources.get(contactId) != null) {
return contactMapSources.get(contactId);
}
DcContact contact = dcContext.getContact(contactId);
MapSource contactMapSource = new MapSource(contactId);
contactMapSource.setColor(contact.getColor());
contactMapSources.put(contactId, contactMapSource);
initGeoJsonSources(contactMapSource);
initContactBasedLayers(contactMapSource);
return contactMapSource;
}
private Bitmap generateColoredLastPositionIcon(int colorFilter) {
return generateColoredBitmap(colorFilter, R.drawable.ic_location_on_white_48dp);
}
@@ -525,10 +457,14 @@ public class MapDataManager implements DcEventCenter.DcEventDelegate, GenerateIn
}
private void updateSources() {
int[] contactIds = getContactIds(chatId);
for (int contactId : contactIds) {
updateSource(chatId, contactId);
}
new DataCollectionTask(dcContext,
chatId,
getContactIds(chatId),
contactMapSources,
featureCollections,
lastPositions,
boundingBuilder,
this).execute();
}
private void replaceSelectedMarker(String featureId) {
@@ -561,11 +497,12 @@ public class MapDataManager implements DcEventCenter.DcEventDelegate, GenerateIn
}
private Feature getFeatureWithId(String id) {
for (String key : featureCollections.keySet()) {
for (Map.Entry<String, LinkedList<Feature>> e : featureCollections.entrySet()) {
String key = e.getKey();
if (key.startsWith(LINE_FEATURE_LIST)) {
continue;
}
LinkedList<Feature> featureCollection = featureCollections.get(key);
LinkedList<Feature> featureCollection = e.getValue();
for (Feature f : featureCollection) {
if (f.id().equals(id)) {
return f;
@@ -30,6 +30,7 @@ public class MapSource {
private int color;
private int colorArgb;
private int contactId;
public MapSource(int contactId) {
markerSource = MARKER_POSITION_SOURCE + "_" + contactId;
@@ -40,6 +41,7 @@ public class MapSource {
markerLastPositon = MARKER_LAST_POSITON + "_" + contactId;
markerFeatureCollection = MARKER_FEATURE_LIST + "_" + contactId;
lineFeatureCollection = LINE_FEATURE_LIST + "_" + contactId;
this.contactId = contactId;
}
public void setColor(int color) {
@@ -83,4 +85,6 @@ public class MapSource {
public String getLineFeatureCollection() { return lineFeatureCollection; }
public int getContactId() { return contactId; }
}
+34 -1
View File
@@ -13,6 +13,8 @@ import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.mapbox.mapboxsdk.geometry.LatLng;
import org.thoughtcrime.securesms.preferences.widgets.NotificationPrivacyPreference;
import java.io.IOException;
@@ -22,6 +24,8 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.mapbox.mapboxsdk.constants.MapboxConstants.MINIMUM_ZOOM;
public class Prefs {
private static final String TAG = Prefs.class.getSimpleName();
@@ -69,6 +73,10 @@ public class Prefs {
private static final String PREF_CONTACT_PHOTO_IDENTIFIERS = "pref_contact_photo_identifiers";
private static final String MAP_CENTER_LATITUDE = "pref_map_center_latitude";
private static final String MAP_CENTER_LONGITUDE = "pref_map_center_longitude";
private static final String MAP_ZOOM = "pref_map_zoom";
public enum VibrateState {
DEFAULT(0), ENABLED(1), DISABLED(2);
private final int id;
@@ -328,6 +336,31 @@ public class Prefs {
return System.currentTimeMillis() <= getChatMutedUntil(context, chatId);
}
// map
public static void setMapCenter(Context context, int chatId, LatLng latLng) {
setLongPreference(context, MAP_CENTER_LATITUDE+chatId, Double.doubleToRawLongBits(latLng.getLatitude()));
setLongPreference(context, MAP_CENTER_LONGITUDE+chatId, Double.doubleToRawLongBits(latLng.getLongitude()));
}
public static void setMapZoom(Context context, int chatId, double zoom) {
setLongPreference(context, MAP_ZOOM+chatId, Double.doubleToRawLongBits(zoom));
}
public static LatLng getMapCenter(Context context, int chatId) {
long latitude = getLongPreference(context, MAP_CENTER_LATITUDE+chatId, Long.MAX_VALUE);
long longitude = getLongPreference(context, MAP_CENTER_LONGITUDE+chatId, Long.MAX_VALUE);
if (latitude == Long.MAX_VALUE || longitude == Long.MAX_VALUE) {
return null;
}
return new LatLng(Double.longBitsToDouble(latitude), Double.longBitsToDouble(longitude));
}
public static double getMapZoom(Context context, int chatId) {
long zoom = getLongPreference(context, MAP_ZOOM+chatId, Double.doubleToLongBits(MINIMUM_ZOOM));
return Double.longBitsToDouble(zoom);
}
// misc.
public static String getBackgroundImagePath(Context context) {
@@ -409,4 +442,4 @@ public class Prefs {
return null;
}
}
}