forked from commons-app/apps-android-commons
/
NearbyParentFragment.java
2193 lines (2017 loc) · 88.5 KB
/
NearbyParentFragment.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package fr.free.nrw.commons.nearby.fragments;
import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.CUSTOM_QUERY;
import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.LOCATION_SIGNIFICANTLY_CHANGED;
import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.LOCATION_SLIGHTLY_CHANGED;
import static fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType.MAP_UPDATED;
import static fr.free.nrw.commons.wikidata.WikidataConstants.PLACE_OBJECT;
import android.Manifest;
import android.Manifest.permission;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.SearchView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding3.appcompat.RxSearchView;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.CommonsApplication.BaseLogoutListener;
import fr.free.nrw.commons.MapController.NearbyPlacesInfo;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.Utils;
import fr.free.nrw.commons.bookmarks.locations.BookmarkLocationsDao;
import fr.free.nrw.commons.contributions.ContributionController;
import fr.free.nrw.commons.contributions.MainActivity;
import fr.free.nrw.commons.contributions.MainActivity.ActiveFragment;
import fr.free.nrw.commons.di.CommonsDaggerSupportFragment;
import fr.free.nrw.commons.kvstore.JsonKvStore;
import fr.free.nrw.commons.location.LocationServiceManager;
import fr.free.nrw.commons.location.LocationUpdateListener;
import fr.free.nrw.commons.nearby.CheckBoxTriStates;
import fr.free.nrw.commons.nearby.Label;
import fr.free.nrw.commons.nearby.MarkerPlaceGroup;
import fr.free.nrw.commons.nearby.NearbyBaseMarker;
import fr.free.nrw.commons.nearby.NearbyController;
import fr.free.nrw.commons.nearby.NearbyFilterSearchRecyclerViewAdapter;
import fr.free.nrw.commons.nearby.NearbyFilterState;
import fr.free.nrw.commons.nearby.NearbyMarker;
import fr.free.nrw.commons.nearby.Place;
import fr.free.nrw.commons.nearby.contract.NearbyParentFragmentContract;
import fr.free.nrw.commons.nearby.fragments.AdvanceQueryFragment.Callback;
import fr.free.nrw.commons.nearby.presenter.NearbyParentFragmentPresenter;
import fr.free.nrw.commons.upload.FileUtils;
import fr.free.nrw.commons.utils.DialogUtil;
import fr.free.nrw.commons.utils.ExecutorUtils;
import fr.free.nrw.commons.utils.LayoutUtils;
import fr.free.nrw.commons.utils.LocationUtils;
import fr.free.nrw.commons.utils.NearbyFABUtils;
import fr.free.nrw.commons.utils.NetworkUtils;
import fr.free.nrw.commons.utils.PermissionUtils;
import fr.free.nrw.commons.utils.SystemThemeUtils;
import fr.free.nrw.commons.utils.ViewUtil;
import fr.free.nrw.commons.wikidata.WikidataEditListener;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Named;
import kotlin.Unit;
import org.jetbrains.annotations.NotNull;
import org.osmdroid.events.MapEventsReceiver;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.util.constants.GeoConstants;
import org.osmdroid.views.CustomZoomButtonsController;
import org.osmdroid.views.overlay.ItemizedIconOverlay.OnItemGestureListener;
import org.osmdroid.views.overlay.ItemizedOverlayWithFocus;
import org.osmdroid.views.overlay.MapEventsOverlay;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;
import org.osmdroid.views.overlay.ScaleBarOverlay;
import org.osmdroid.views.overlay.ScaleDiskOverlay;
import org.osmdroid.views.overlay.TilesOverlay;
import timber.log.Timber;
public class NearbyParentFragment extends CommonsDaggerSupportFragment
implements NearbyParentFragmentContract.View,
WikidataEditListener.WikidataP18EditListener, LocationUpdateListener {
@BindView(R.id.bottom_sheet)
RelativeLayout rlBottomSheet;
@BindView(R.id.bottom_sheet_details)
View bottomSheetDetails;
@BindView(R.id.transparentView)
View transparentView;
@BindView(R.id.directionsButtonText)
TextView directionsButtonText;
@BindView(R.id.wikipediaButtonText)
TextView wikipediaButtonText;
@BindView(R.id.wikidataButtonText)
TextView wikidataButtonText;
@BindView(R.id.commonsButtonText)
TextView commonsButtonText;
@BindView(R.id.fab_plus)
FloatingActionButton fabPlus;
@BindView(R.id.fab_camera)
FloatingActionButton fabCamera;
@BindView(R.id.fab_gallery)
FloatingActionButton fabGallery;
@BindView(R.id.fab_recenter)
FloatingActionButton fabRecenter;
@BindView(R.id.bookmarkButtonImage)
ImageView bookmarkButtonImage;
@BindView(R.id.bookmarkButton)
LinearLayout bookmarkButton;
@BindView(R.id.wikipediaButton)
LinearLayout wikipediaButton;
@BindView(R.id.wikidataButton)
LinearLayout wikidataButton;
@BindView(R.id.directionsButton)
LinearLayout directionsButton;
@BindView(R.id.commonsButton)
LinearLayout commonsButton;
@BindView(R.id.description)
TextView description;
@BindView(R.id.title)
TextView title;
@BindView(R.id.category)
TextView distance;
@BindView(R.id.icon)
ImageView icon;
@BindView(R.id.search_this_area_button)
Button searchThisAreaButton;
@BindView(R.id.map_progress_bar)
ProgressBar progressBar;
@BindView(R.id.choice_chip_exists)
Chip chipExists;
@BindView(R.id.choice_chip_wlm)
Chip chipWlm;
@BindView(R.id.choice_chip_needs_photo)
Chip chipNeedsPhoto;
@BindView(R.id.choice_chip_group)
ChipGroup choiceChipGroup;
@BindView(R.id.search_view)
SearchView searchView;
@BindView(R.id.search_list_view)
RecyclerView recyclerView;
@BindView(R.id.nearby_filter_list)
View nearbyFilterList;
@BindView(R.id.checkbox_tri_states)
CheckBoxTriStates checkBoxTriStates;
@BindView(R.id.map)
org.osmdroid.views.MapView mapView;
@BindView(R.id.rv_nearby_list)
RecyclerView rvNearbyList;
@BindView(R.id.no_results_message)
TextView noResultsView;
@BindView(R.id.tv_attribution)
AppCompatTextView tvAttribution;
@BindView(R.id.rl_container_wlm_month_message)
RelativeLayout rlContainerWLMMonthMessage;
@BindView(R.id.tv_learn_more)
AppCompatTextView tvLearnMore;
@BindView(R.id.iv_toggle_chips)
AppCompatImageView ivToggleChips;
@BindView(R.id.chip_view)
View llContainerChips;
@BindView(R.id.btn_advanced_options)
AppCompatButton btnAdvancedOptions;
@BindView(R.id.fl_container_nearby_children)
FrameLayout flConainerNearbyChildren;
@Inject
LocationServiceManager locationManager;
@Inject
NearbyController nearbyController;
@Inject
@Named("default_preferences")
JsonKvStore applicationKvStore;
@Inject
BookmarkLocationsDao bookmarkLocationDao;
@Inject
ContributionController controller;
@Inject
WikidataEditListener wikidataEditListener;
@Inject
SystemThemeUtils systemThemeUtils;
@Inject
CommonPlaceClickActions commonPlaceClickActions;
private NearbyFilterSearchRecyclerViewAdapter nearbyFilterSearchRecyclerViewAdapter;
private BottomSheetBehavior bottomSheetListBehavior;
private BottomSheetBehavior bottomSheetDetailsBehavior;
private Animation rotate_backward;
private Animation fab_close;
private Animation fab_open;
private Animation rotate_forward;
private static final float ZOOM_LEVEL = 14f;
private final String NETWORK_INTENT_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
private BroadcastReceiver broadcastReceiver;
private boolean isNetworkErrorOccurred;
private Snackbar snackbar;
private View view;
private NearbyParentFragmentPresenter presenter;
private boolean isDarkTheme;
private boolean isFABsExpanded;
private Marker selectedMarker;
private Place selectedPlace;
private Place clickedMarkerPlace;
private boolean isClickedMarkerBookmarked;
private final double CAMERA_TARGET_SHIFT_FACTOR_PORTRAIT = 0.005;
private final double CAMERA_TARGET_SHIFT_FACTOR_LANDSCAPE = 0.004;
private boolean isPermissionDenied;
private boolean recenterToUserLocation;
private GeoPoint mapCenter;
IntentFilter intentFilter = new IntentFilter(NETWORK_INTENT_ACTION);
private Marker currentLocationMarker;
private Place lastPlaceToCenter;
private fr.free.nrw.commons.location.LatLng lastKnownLocation;
private boolean isVisibleToUser;
private fr.free.nrw.commons.location.LatLng lastFocusLocation;
private LatLngBounds latLngBounds;
private PlaceAdapter adapter;
private GeoPoint lastMapFocus;
private NearbyParentFragmentInstanceReadyCallback nearbyParentFragmentInstanceReadyCallback;
private boolean isAdvancedQueryFragmentVisible = false;
private Place nearestPlace;
private ActivityResultLauncher<String[]> inAppCameraLocationPermissionLauncher = registerForActivityResult(
new ActivityResultContracts.RequestMultiplePermissions(),
new ActivityResultCallback<Map<String, Boolean>>() {
@Override
public void onActivityResult(Map<String, Boolean> result) {
boolean areAllGranted = true;
for (final boolean b : result.values()) {
areAllGranted = areAllGranted && b;
}
if (areAllGranted) {
controller.locationPermissionCallback.onLocationPermissionGranted();
} else {
if (shouldShowRequestPermissionRationale(permission.ACCESS_FINE_LOCATION)) {
controller.handleShowRationaleFlowCameraLocation(getActivity());
} else {
controller.locationPermissionCallback.onLocationPermissionDenied(
getActivity().getString(
R.string.in_app_camera_location_permission_denied));
}
}
}
});
private ActivityResultLauncher<String> locationPermissionLauncher = registerForActivityResult(
new ActivityResultContracts.RequestPermission(), isGranted -> {
if (isGranted) {
locationPermissionGranted();
} else {
if (shouldShowRequestPermissionRationale(permission.ACCESS_FINE_LOCATION)) {
DialogUtil.showAlertDialog(getActivity(),
getActivity().getString(R.string.location_permission_title),
getActivity().getString(R.string.location_permission_rationale_nearby),
getActivity().getString(android.R.string.ok),
getActivity().getString(android.R.string.cancel),
() -> {
if (!(locationManager.isNetworkProviderEnabled()
|| locationManager.isGPSProviderEnabled())) {
showLocationOffDialog();
}
},
() -> isPermissionDenied = true,
null,
false);
} else {
isPermissionDenied = true;
}
}
});
/**
* WLM URL
*/
public static final String WLM_URL = "https://commons.wikimedia.org/wiki/Commons:Mobile_app/Contributing_to_WLM_using_the_app";
/**
* Saves response of list of places for the first time
*/
private List<Place> places = new ArrayList<>();
@NonNull
public static NearbyParentFragment newInstance() {
NearbyParentFragment fragment = new NearbyParentFragment();
fragment.setRetainInstance(true);
return fragment;
}
@Override
public View onCreateView(@NonNull final LayoutInflater inflater, final ViewGroup container,
final Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_nearby_parent, container, false);
ButterKnife.bind(this, view);
initNetworkBroadCastReceiver();
presenter = new NearbyParentFragmentPresenter(bookmarkLocationDao);
setHasOptionsMenu(true);
// Inflate the layout for this fragment
return view;
}
@Override
public void onCreateOptionsMenu(@NonNull final Menu menu,
@NonNull final MenuInflater inflater) {
inflater.inflate(R.menu.nearby_fragment_menu, menu);
MenuItem listMenu = menu.findItem(R.id.list_sheet);
listMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
listOptionMenuItemClicked();
return false;
}
});
}
@Override
public void onViewCreated(@NonNull final View view, @Nullable final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
isDarkTheme = systemThemeUtils.isDeviceInNightMode();
if (Utils.isMonumentsEnabled(new Date())) {
rlContainerWLMMonthMessage.setVisibility(View.VISIBLE);
} else {
rlContainerWLMMonthMessage.setVisibility(View.GONE);
}
presenter.attachView(this);
isPermissionDenied = false;
recenterToUserLocation = false;
initThemePreferences();
initViews();
presenter.setActionListeners(applicationKvStore);
org.osmdroid.config.Configuration.getInstance().load(this.getContext(),
PreferenceManager.getDefaultSharedPreferences(this.getContext()));
// Use the Wikimedia tile server, rather than OpenStreetMap (Mapnik) which has various
// restrictions that we do not satisfy.
mapView.setTileSource(TileSourceFactory.WIKIMEDIA);
mapView.setTilesScaledToDpi(true);
// Add referer HTTP header because the Wikimedia tile server requires it.
// This was suggested by Dmitry Brant within an email thread between us and WMF.
org.osmdroid.config.Configuration.getInstance().getAdditionalHttpRequestProperties().put(
"Referer", "http://maps.wikimedia.org/"
);
if (applicationKvStore.getString("LastLocation")
!= null) { // Checking for last searched location
String[] locationLatLng = applicationKvStore.getString("LastLocation").split(",");
lastMapFocus = new GeoPoint(Double.valueOf(locationLatLng[0]),
Double.valueOf(locationLatLng[1]));
} else {
lastMapFocus = new GeoPoint(51.50550, -0.07520);
}
ScaleBarOverlay scaleBarOverlay = new ScaleBarOverlay(mapView);
scaleBarOverlay.setScaleBarOffset(15, 25);
Paint barPaint = new Paint();
barPaint.setARGB(200, 255, 250, 250);
scaleBarOverlay.setBackgroundPaint(barPaint);
scaleBarOverlay.enableScaleBar();
mapView.getOverlays().add(scaleBarOverlay);
mapView.getZoomController().setVisibility(CustomZoomButtonsController.Visibility.NEVER);
mapView.getController().setZoom(ZOOM_LEVEL);
mapView.getOverlays().add(new MapEventsOverlay(new MapEventsReceiver() {
@Override
public boolean singleTapConfirmedHelper(GeoPoint p) {
if (clickedMarkerPlace != null){
removeMarker(clickedMarkerPlace);
addMarkerToMap(clickedMarkerPlace,isClickedMarkerBookmarked);
}else {
Timber.e("CLICKED MARKER IS NULL");
}
if (isListBottomSheetExpanded()) {
// Back should first hide the bottom sheet if it is expanded
hideBottomSheet();
} else if (isDetailsBottomSheetVisible()) {
hideBottomDetailsSheet();
}
return true;
}
@Override
public boolean longPressHelper(GeoPoint p) {
return false;
}
}));
mapView.addMapListener(new MapListener() {
@Override
public boolean onScroll(ScrollEvent event) {
if (lastMapFocus != null) {
Location mylocation = new Location("");
Location dest_location = new Location("");
dest_location.setLatitude(mapView.getMapCenter().getLatitude());
dest_location.setLongitude(mapView.getMapCenter().getLongitude());
mylocation.setLatitude(lastMapFocus.getLatitude());
mylocation.setLongitude(lastMapFocus.getLongitude());
Float distance = mylocation.distanceTo(dest_location);//in meters
if (lastMapFocus != null) {
if (isNetworkConnectionEstablished() && (event.getX() > 0
|| event.getY() > 0)) {
if (distance > 2000.0) {
setSearchThisAreaButtonVisibility(true);
} else {
setSearchThisAreaButtonVisibility(false);
}
}
} else {
setSearchThisAreaButtonVisibility(false);
}
}
return true;
}
@Override
public boolean onZoom(ZoomEvent event) {
return false;
}
});
mapView.setMultiTouchControls(true);
if (nearbyParentFragmentInstanceReadyCallback != null) {
nearbyParentFragmentInstanceReadyCallback.onReady();
}
initNearbyFilter();
addCheckBoxCallback();
performMapReadyActions();
moveCameraToPosition(lastMapFocus);
initRvNearbyList();
onResume();
tvAttribution.setText(Html.fromHtml(getString(R.string.map_attribution)));
tvAttribution.setMovementMethod(LinkMovementMethod.getInstance());
btnAdvancedOptions.setOnClickListener(v -> {
searchView.clearFocus();
showHideAdvancedQueryFragment(true);
final AdvanceQueryFragment fragment = new AdvanceQueryFragment();
final Bundle bundle = new Bundle();
try {
bundle.putString("query", FileUtils.readFromResource("/queries/nearby_query.rq"));
} catch (IOException e) {
Timber.e(e);
}
fragment.setArguments(bundle);
fragment.callback = new Callback() {
@Override
public void close() {
showHideAdvancedQueryFragment(false);
}
@Override
public void reset() {
presenter.setAdvancedQuery(null);
presenter.updateMapAndList(LOCATION_SIGNIFICANTLY_CHANGED);
showHideAdvancedQueryFragment(false);
}
@Override
public void apply(@NotNull final String query) {
presenter.setAdvancedQuery(query);
presenter.updateMapAndList(CUSTOM_QUERY);
showHideAdvancedQueryFragment(false);
}
};
getChildFragmentManager().beginTransaction()
.replace(R.id.fl_container_nearby_children, fragment)
.commit();
});
}
/**
* Initialise background based on theme, this should be doe ideally via styles, that would need
* another refactor
*/
private void initThemePreferences() {
if (isDarkTheme) {
rvNearbyList.setBackgroundColor(
getContext().getResources().getColor(R.color.contributionListDarkBackground));
checkBoxTriStates.setTextColor(
getContext().getResources().getColor(android.R.color.white));
checkBoxTriStates.setTextColor(
getContext().getResources().getColor(android.R.color.white));
nearbyFilterList.setBackgroundColor(
getContext().getResources().getColor(R.color.contributionListDarkBackground));
mapView.getOverlayManager().getTilesOverlay()
.setColorFilter(TilesOverlay.INVERT_COLORS);
} else {
rvNearbyList.setBackgroundColor(
getContext().getResources().getColor(android.R.color.white));
checkBoxTriStates.setTextColor(
getContext().getResources().getColor(R.color.contributionListDarkBackground));
nearbyFilterList.setBackgroundColor(
getContext().getResources().getColor(android.R.color.white));
nearbyFilterList.setBackgroundColor(
getContext().getResources().getColor(android.R.color.white));
}
}
private void initRvNearbyList() {
rvNearbyList.setLayoutManager(new LinearLayoutManager(getContext()));
adapter = new PlaceAdapter(bookmarkLocationDao,
place -> {
moveCameraToPosition(new GeoPoint(place.location.getLatitude(),place.location.getLongitude()));
return Unit.INSTANCE;
},
(place, isBookmarked) -> {
updateMarker(isBookmarked, place, null);
mapView.invalidate();
return Unit.INSTANCE;
},
commonPlaceClickActions,
inAppCameraLocationPermissionLauncher
);
rvNearbyList.setAdapter(adapter);
}
private void addCheckBoxCallback() {
checkBoxTriStates.setCallback(
(o, state, b, b1) -> presenter.filterByMarkerType(o, state, b, b1));
}
private void performMapReadyActions() {
if (((MainActivity) getActivity()).activeFragment == ActiveFragment.NEARBY) {
if (!applicationKvStore.getBoolean("doNotAskForLocationPermission", false) ||
PermissionUtils.hasPermission(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION})) {
checkPermissionsAndPerformAction();
} else {
isPermissionDenied = true;
}
}
}
private void locationPermissionGranted() {
isPermissionDenied = false;
applicationKvStore.putBoolean("doNotAskForLocationPermission", false);
lastKnownLocation = locationManager.getLastLocation();
fr.free.nrw.commons.location.LatLng target = lastKnownLocation;
if (lastKnownLocation != null) {
GeoPoint targetP = new GeoPoint(target.getLatitude(), target.getLongitude());
mapCenter = targetP;
mapView.getController().setCenter(targetP);
recenterMarkerToPosition(targetP);
moveCameraToPosition(targetP);
} else if (locationManager.isGPSProviderEnabled()
|| locationManager.isNetworkProviderEnabled()) {
locationManager.requestLocationUpdatesFromProvider(LocationManager.NETWORK_PROVIDER);
locationManager.requestLocationUpdatesFromProvider(LocationManager.GPS_PROVIDER);
setProgressBarVisibility(true);
} else {
Toast.makeText(getContext(), getString(R.string.nearby_location_not_available),
Toast.LENGTH_LONG).show();
}
presenter.onMapReady();
registerUnregisterLocationListener(false);
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
presenter.attachView(this);
registerNetworkReceiver();
if (isResumed() && ((MainActivity) getActivity()).activeFragment == ActiveFragment.NEARBY) {
if (!isPermissionDenied && !applicationKvStore.getBoolean(
"doNotAskForLocationPermission", false)) {
if (!locationManager.isGPSProviderEnabled()) {
startMapWithCondition("Without GPS");
} else {
startTheMap();
}
} else {
startMapWithCondition("Without Permission");
}
}
}
/**
* Starts the map without GPS and without permission By default it points to 51.50550,-0.07520
* coordinates, other than that it points to the last known location which can be get by the key
* "LastLocation" from applicationKvStore
*
* @param condition : for which condition the map should start
*/
private void startMapWithCondition(final String condition) {
if (condition.equals("Without Permission")) {
applicationKvStore.putBoolean("doNotAskForLocationPermission", true);
}
if (applicationKvStore.getString("LastLocation") != null) {
final String[] locationLatLng
= applicationKvStore.getString("LastLocation").split(",");
lastKnownLocation
= new fr.free.nrw.commons.location.LatLng(Double.parseDouble(locationLatLng[0]),
Double.parseDouble(locationLatLng[1]), 1f);
} else {
lastKnownLocation = new fr.free.nrw.commons.location.LatLng(51.50550,
-0.07520, 1f);
}
if (mapView != null) {
recenterMap(lastKnownLocation);
}
}
private void registerNetworkReceiver() {
if (getActivity() != null) {
getActivity().registerReceiver(broadcastReceiver, intentFilter);
}
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
compositeDisposable.clear();
presenter.detachView();
registerUnregisterLocationListener(true);
try {
if (broadcastReceiver != null && getActivity() != null) {
getContext().unregisterReceiver(broadcastReceiver);
}
if (locationManager != null && presenter != null) {
locationManager.removeLocationListener(presenter);
locationManager.unregisterLocationManager();
}
} catch (final Exception e) {
Timber.e(e);
//Broadcast receivers should always be unregistered inside catch, you never know if they were already registered or not
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
presenter.removeNearbyPreferences(applicationKvStore);
}
private void initViews() {
Timber.d("init views called");
initBottomSheets();
loadAnimations();
setBottomSheetCallbacks();
decideButtonVisibilities();
addActionToTitle();
if (!Utils.isMonumentsEnabled(new Date())) {
chipWlm.setVisibility(View.GONE);
}
}
/**
* a) Creates bottom sheet behaviours from bottom sheets, sets initial states and visibility b)
* Gets the touch event on the map to perform following actions: if fab is open then close fab.
* if bottom sheet details are expanded then collapse bottom sheet details. if bottom sheet
* details are collapsed then hide the bottom sheet details. if listBottomSheet is open then
* hide the list bottom sheet.
*/
@SuppressLint("ClickableViewAccessibility")
private void initBottomSheets() {
bottomSheetListBehavior = BottomSheetBehavior.from(rlBottomSheet);
bottomSheetDetailsBehavior = BottomSheetBehavior.from(bottomSheetDetails);
bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
bottomSheetDetails.setVisibility(View.VISIBLE);
bottomSheetListBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
}
public void initNearbyFilter() {
nearbyFilterList.setVisibility(View.GONE);
hideBottomSheet();
searchView.setOnQueryTextFocusChangeListener((v, hasFocus) -> {
LayoutUtils.setLayoutHeightAllignedToWidth(1.25, nearbyFilterList);
if (hasFocus) {
nearbyFilterList.setVisibility(View.VISIBLE);
presenter.searchViewGainedFocus();
} else {
nearbyFilterList.setVisibility(View.GONE);
}
});
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
DividerItemDecoration.VERTICAL));
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
nearbyFilterSearchRecyclerViewAdapter = new NearbyFilterSearchRecyclerViewAdapter(
getContext(), new ArrayList<>(Label.valuesAsList()), recyclerView);
nearbyFilterSearchRecyclerViewAdapter.setCallback(
new NearbyFilterSearchRecyclerViewAdapter.Callback() {
@Override
public void setCheckboxUnknown() {
presenter.setCheckboxUnknown();
}
@Override
public void filterByMarkerType(final ArrayList<Label> selectedLabels, final int i,
final boolean b, final boolean b1) {
presenter.filterByMarkerType(selectedLabels, i, b, b1);
}
@Override
public boolean isDarkTheme() {
return isDarkTheme;
}
});
nearbyFilterList.getLayoutParams().width = (int) LayoutUtils.getScreenWidth(getActivity(),
0.75);
recyclerView.setAdapter(nearbyFilterSearchRecyclerViewAdapter);
LayoutUtils.setLayoutHeightAllignedToWidth(1.25, nearbyFilterList);
compositeDisposable.add(RxSearchView.queryTextChanges(searchView)
.takeUntil(RxView.detaches(searchView))
.debounce(500, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(query -> {
((NearbyFilterSearchRecyclerViewAdapter) recyclerView.getAdapter()).getFilter()
.filter(query.toString());
}));
initFilterChips();
}
@Override
public void setCheckBoxAction() {
checkBoxTriStates.addAction();
checkBoxTriStates.setState(CheckBoxTriStates.UNKNOWN);
}
@Override
public void setCheckBoxState(final int state) {
checkBoxTriStates.setState(state);
}
@Override
public void setFilterState() {
chipNeedsPhoto.setChecked(NearbyFilterState.getInstance().isNeedPhotoSelected());
chipExists.setChecked(NearbyFilterState.getInstance().isExistsSelected());
chipWlm.setChecked(NearbyFilterState.getInstance().isWlmSelected());
if (NearbyController.currentLocation != null) {
presenter.filterByMarkerType(nearbyFilterSearchRecyclerViewAdapter.selectedLabels,
checkBoxTriStates.getState(), true, false);
}
}
private void initFilterChips() {
chipNeedsPhoto.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (NearbyController.currentLocation != null) {
checkBoxTriStates.setState(CheckBoxTriStates.CHECKED);
NearbyFilterState.setNeedPhotoSelected(isChecked);
presenter.filterByMarkerType(nearbyFilterSearchRecyclerViewAdapter.selectedLabels,
checkBoxTriStates.getState(), true, true);
updatePlaceList(chipNeedsPhoto.isChecked(),
chipExists.isChecked(), chipWlm.isChecked());
} else {
chipNeedsPhoto.setChecked(!isChecked);
}
});
chipExists.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (NearbyController.currentLocation != null) {
checkBoxTriStates.setState(CheckBoxTriStates.CHECKED);
NearbyFilterState.setExistsSelected(isChecked);
presenter.filterByMarkerType(nearbyFilterSearchRecyclerViewAdapter.selectedLabels,
checkBoxTriStates.getState(), true, true);
updatePlaceList(chipNeedsPhoto.isChecked(),
chipExists.isChecked(), chipWlm.isChecked());
} else {
chipExists.setChecked(!isChecked);
}
});
chipWlm.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (NearbyController.currentLocation != null) {
checkBoxTriStates.setState(CheckBoxTriStates.CHECKED);
NearbyFilterState.setWlmSelected(isChecked);
presenter.filterByMarkerType(nearbyFilterSearchRecyclerViewAdapter.selectedLabels,
checkBoxTriStates.getState(), true, true);
updatePlaceList(chipNeedsPhoto.isChecked(),
chipExists.isChecked(), chipWlm.isChecked());
} else {
chipWlm.setChecked(!isChecked);
}
});
}
/**
* Updates Nearby place list according to available chip states
*
* @param needsPhoto is chipNeedsPhoto checked
* @param exists is chipExists checked
* @param isWlm is chipWlm checked
*/
private void updatePlaceList(final boolean needsPhoto, final boolean exists,
final boolean isWlm) {
final List<Place> updatedPlaces = new ArrayList<>();
if (needsPhoto) {
for (final Place place :
places) {
if (place.pic.trim().isEmpty() && !updatedPlaces.contains(place)) {
updatedPlaces.add(place);
}
}
} else {
updatedPlaces.addAll(places);
}
if (exists) {
for (final Iterator<Place> placeIterator = updatedPlaces.iterator();
placeIterator.hasNext(); ) {
final Place place = placeIterator.next();
if (!place.exists) {
placeIterator.remove();
}
}
}
if (!isWlm) {
for (final Place place :
places) {
if (place.isMonument() && updatedPlaces.contains(place)) {
updatedPlaces.remove(place);
}
}
} else {
for (final Place place :
places) {
if (place.isMonument() && !updatedPlaces.contains(place)) {
updatedPlaces.add(place);
}
}
}
adapter.setItems(updatedPlaces);
noResultsView.setVisibility(updatedPlaces.isEmpty() ? View.VISIBLE : View.GONE);
}
/**
* Defines how bottom sheets will act on click
*/
private void setBottomSheetCallbacks() {
bottomSheetDetailsBehavior.setBottomSheetCallback(new BottomSheetBehavior
.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull final View bottomSheet, final int newState) {
prepareViewsForSheetPosition(newState);
}
@Override
public void onSlide(@NonNull final View bottomSheet, final float slideOffset) {
}
});
bottomSheetDetails.setOnClickListener(v -> {
if (bottomSheetDetailsBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
} else if (bottomSheetDetailsBehavior.getState()
== BottomSheetBehavior.STATE_EXPANDED) {
bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
});
rlBottomSheet.getLayoutParams().height = getActivity().getWindowManager()
.getDefaultDisplay().getHeight() / 16 * 9;
bottomSheetListBehavior = BottomSheetBehavior.from(rlBottomSheet);
bottomSheetListBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
bottomSheetListBehavior.setBottomSheetCallback(new BottomSheetBehavior
.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull final View bottomSheet, final int newState) {
if (newState == BottomSheetBehavior.STATE_EXPANDED) {
bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
}
}
@Override
public void onSlide(@NonNull final View bottomSheet, final float slideOffset) {
}
});
}
/**
* Loads animations will be used for FABs
*/
private void loadAnimations() {
fab_open = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_open);
fab_close = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_close);
rotate_forward = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_forward);
rotate_backward = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_backward);
}
/**
* Fits buttons according to our layout
*/
private void decideButtonVisibilities() {
// Remove button text if they exceed 1 line or if internal layout has not been built
// Only need to check for directions button because it is the longest
if (directionsButtonText.getLineCount() > 1 || directionsButtonText.getLineCount() == 0) {
wikipediaButtonText.setVisibility(View.GONE);
wikidataButtonText.setVisibility(View.GONE);
commonsButtonText.setVisibility(View.GONE);
directionsButtonText.setVisibility(View.GONE);
}
}
/**
*
*/
private void addActionToTitle() {
title.setOnLongClickListener(view -> {
Utils.copy("place", title.getText().toString(), getContext());
Toast.makeText(getContext(), R.string.text_copy, Toast.LENGTH_SHORT).show();
return true;
});
title.setOnClickListener(view -> {
bottomSheetListBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
if (bottomSheetDetailsBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
} else {
bottomSheetDetailsBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
});
}
/**
* Centers the map in nearby fragment to a given place and updates nearestPlace
*
* @param place is new center of the map
*/
@Override
public void centerMapToPlace(@Nullable final Place place) {
Timber.d("Map is centered to place");
final double cameraShift;
if (null != place) {
lastPlaceToCenter = place;
nearestPlace = place;
}
if (null != lastPlaceToCenter) {
final Configuration configuration = getActivity().getResources().getConfiguration();
if (configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {