forked from organicmaps/organicmaps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathframework.cpp
3249 lines (2721 loc) · 98.5 KB
/
framework.cpp
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
#include "map/framework.hpp"
#include "map/benchmark_tools.hpp"
#include "map/gps_tracker.hpp"
#include "map/user_mark.hpp"
#include "map/track_mark.hpp"
#include "ge0/url_generator.hpp"
#include "routing/route.hpp"
#include "routing/speed_camera_prohibition.hpp"
#include "routing_common/num_mwm_id.hpp"
#include "search/editor_delegate.hpp"
#include "search/engine.hpp"
#include "search/locality_finder.hpp"
#include "storage/country_info_getter.hpp"
#include "storage/storage_helpers.hpp"
#include "drape_frontend/color_constants.hpp"
#include "drape_frontend/gps_track_point.hpp"
#include "drape_frontend/visual_params.hpp"
#include "descriptions/loader.hpp"
#include "indexer/categories_holder.hpp"
#include "indexer/classificator.hpp"
#include "indexer/drawing_rules.hpp"
#include "indexer/editable_map_object.hpp"
#include "indexer/feature.hpp"
#include "indexer/feature_algo.hpp"
#include "indexer/feature_source.hpp"
#include "indexer/feature_utils.hpp"
#include "indexer/feature_visibility.hpp"
#include "indexer/map_style_reader.hpp"
#include "indexer/scales.hpp"
#include "indexer/transliteration_loader.hpp"
#include "platform/localization.hpp"
#include "platform/measurement_utils.hpp"
#include "platform/mwm_version.hpp"
#include "platform/platform.hpp"
#include "platform/preferred_languages.hpp"
#include "platform/settings.hpp"
#include "coding/point_coding.hpp"
#include "coding/string_utf8_multilang.hpp"
#include "coding/transliteration.hpp"
#include "coding/url.hpp"
#include "geometry/angles.hpp"
#include "geometry/any_rect2d.hpp"
#include "geometry/distance_on_sphere.hpp"
#include "geometry/latlon.hpp"
#include "geometry/mercator.hpp"
#include "geometry/rect2d.hpp"
#include "geometry/triangle2d.hpp"
#include "base/logging.hpp"
#include "base/math.hpp"
#include "base/string_utils.hpp"
#include "std/target_os.hpp"
#include "defines.hpp"
#include <algorithm>
using namespace location;
using namespace routing;
using namespace storage;
using namespace std::placeholders;
using namespace std;
using platform::CountryFile;
using platform::LocalCountryFile;
#ifdef FIXED_LOCATION
Framework::FixedPosition::FixedPosition()
{
m_fixedLatLon = Settings::Get("FixPosition", m_latlon);
m_fixedDir = Settings::Get("FixDirection", m_dirFromNorth);
}
#endif
namespace
{
char const kMapStyleKey[] = "MapStyleKeyV1";
char const kAllow3dKey[] = "Allow3d";
char const kAllow3dBuildingsKey[] = "Buildings3d";
char const kAllowAutoZoom[] = "AutoZoom";
char const kTrafficEnabledKey[] = "TrafficEnabled";
char const kTransitSchemeEnabledKey[] = "TransitSchemeEnabled";
char const kIsolinesEnabledKey[] = "IsolinesEnabled";
char const kOutdoorsEnabledKey[] = "OutdoorsEnabled";
char const kTrafficSimplifiedColorsKey[] = "TrafficSimplifiedColors";
char const kLargeFontsSize[] = "LargeFontsSize";
char const kTranslitMode[] = "TransliterationMode";
char const kPreferredGraphicsAPI[] = "PreferredGraphicsAPI";
char const kShowDebugInfo[] = "DebugInfo";
auto constexpr kLargeFontsScaleFactor = 1.6;
size_t constexpr kMaxTrafficCacheSizeBytes = 64 /* Mb */ * 1024 * 1024;
auto constexpr kBuildingCentroidThreshold = 10.0;
// TODO!
// To adjust GpsTrackFilter was added secret command "?gpstrackaccuracy:xxx;"
// where xxx is a new value for horizontal accuracy.
// This is temporary solution while we don't have a good filter.
bool ParseSetGpsTrackMinAccuracyCommand(string const & query)
{
char const kGpsAccuracy[] = "?gpstrackaccuracy:";
if (!query.starts_with(kGpsAccuracy))
return false;
size_t const end = query.find(';', sizeof(kGpsAccuracy) - 1);
if (end == string::npos)
return false;
string s(query.begin() + sizeof(kGpsAccuracy) - 1, query.begin() + end);
double value;
if (!strings::to_double(s, value))
return false;
GpsTrackFilter::StoreMinHorizontalAccuracy(value);
return true;
}
} // namespace
pair<MwmSet::MwmId, MwmSet::RegResult> Framework::RegisterMap(LocalCountryFile const & file)
{
auto res = m_featuresFetcher.RegisterMap(file);
if (res.second == MwmSet::RegResult::Success)
{
auto const & id = res.first;
ASSERT(id.IsAlive(), ());
LOG(LINFO, ("Loaded", file.GetCountryName(), "map, of version", id.GetInfo()->GetVersion()));
}
return res;
}
void Framework::OnLocationError(TLocationError /*error*/)
{
m_trafficManager.UpdateMyPosition(TrafficManager::MyPosition());
if (m_drapeEngine != nullptr)
m_drapeEngine->LoseLocation();
}
void Framework::OnLocationUpdate(GpsInfo const & info)
{
#ifdef FIXED_LOCATION
GpsInfo rInfo(info);
// get fixed coordinates
m_fixedPos.GetLon(rInfo.m_longitude);
m_fixedPos.GetLat(rInfo.m_latitude);
// pretend like GPS position
rInfo.m_horizontalAccuracy = 5.0;
if (m_fixedPos.HasNorth())
{
// pass compass value (for devices without compass)
CompassInfo compass;
m_fixedPos.GetNorth(compass.m_bearing);
OnCompassUpdate(compass);
}
#else
GpsInfo const & rInfo = info;
#endif
m_routingManager.OnLocationUpdate(rInfo);
}
void Framework::OnCompassUpdate(CompassInfo const & info)
{
#ifdef FIXED_LOCATION
CompassInfo rInfo(info);
m_fixedPos.GetNorth(rInfo.m_bearing);
#else
CompassInfo const & rInfo = info;
#endif
if (m_drapeEngine != nullptr)
m_drapeEngine->SetCompassInfo(rInfo);
}
void Framework::SwitchMyPositionNextMode()
{
if (m_drapeEngine != nullptr)
m_drapeEngine->SwitchMyPositionNextMode();
}
void Framework::SetMyPositionModeListener(TMyPositionModeChanged && fn)
{
m_myPositionListener = std::move(fn);
}
EMyPositionMode Framework::GetMyPositionMode() const
{
return m_drapeEngine ? m_drapeEngine->GetMyPositionMode() : PendingPosition;
}
TrafficManager & Framework::GetTrafficManager()
{
return m_trafficManager;
}
TransitReadManager & Framework::GetTransitManager()
{
return m_transitManager;
}
IsolinesManager & Framework::GetIsolinesManager()
{
return m_isolinesManager;
}
IsolinesManager const & Framework::GetIsolinesManager() const
{
return m_isolinesManager;
}
void Framework::OnUserPositionChanged(m2::PointD const & position, bool hasPosition)
{
GetBookmarkManager().MyPositionMark().SetUserPosition(position, hasPosition);
if (m_currentPlacePageInfo && m_currentPlacePageInfo->GetTrackId() != kml::kInvalidTrackId)
GetBookmarkManager().UpdateElevationMyPosition(m_currentPlacePageInfo->GetTrackId());
m_routingManager.SetUserCurrentPosition(position);
m_trafficManager.UpdateMyPosition(TrafficManager::MyPosition(position));
}
void Framework::OnViewportChanged(ScreenBase const & screen)
{
// Drape engine may spuriously call OnViewportChanged. Filter out the calls that
// change the viewport from the drape engine's point of view but leave it almost
// the same from the point of view of the framework and all its subsystems such as search api.
// Additional filtering may be done by each subsystem.
auto const isSameViewport = m2::IsEqual(screen.ClipRect(), m_currentModelView.ClipRect(),
kMwmPointAccuracy, kMwmPointAccuracy);
if (isSameViewport)
return;
m_currentModelView = screen;
GetSearchAPI().OnViewportChanged(GetCurrentViewport());
GetBookmarkManager().UpdateViewport(m_currentModelView);
m_trafficManager.UpdateViewport(m_currentModelView);
m_transitManager.UpdateViewport(m_currentModelView);
m_isolinesManager.UpdateViewport(m_currentModelView);
if (m_viewportChangedFn != nullptr)
m_viewportChangedFn(screen);
}
Framework::Framework(FrameworkParams const & params, bool loadMaps)
: m_enabledDiffs(params.m_enableDiffs)
, m_isRenderingEnabled(true)
, m_transitManager(m_featuresFetcher.GetDataSource(),
[this](FeatureCallback const & fn, vector<FeatureID> const & features) {
return m_featuresFetcher.ReadFeatures(fn, features);
},
bind(&Framework::GetMwmsByRect, this, _1, false /* rough */))
, m_isolinesManager(m_featuresFetcher.GetDataSource(),
bind(&Framework::GetMwmsByRect, this, _1, false /* rough */))
, m_routingManager(
RoutingManager::Callbacks(
[this]() -> DataSource & { return m_featuresFetcher.GetDataSource(); },
[this]() -> storage::CountryInfoGetter const & { return GetCountryInfoGetter(); },
[this](string const & id) -> string { return m_storage.GetParentIdFor(id); },
[this]() -> StringsBundle const & { return m_stringsBundle; },
[this]() -> power_management::PowerManager const & { return m_powerManager; }),
static_cast<RoutingManager::Delegate &>(*this))
, m_trafficManager(bind(&Framework::GetMwmsByRect, this, _1, false /* rough */),
kMaxTrafficCacheSizeBytes, m_routingManager.RoutingSession())
, m_lastReportedCountry(kInvalidCountryId)
, m_popularityLoader(m_featuresFetcher.GetDataSource(), POPULARITY_RANKS_FILE_TAG)
, m_descriptionsLoader(std::make_unique<descriptions::Loader>(m_featuresFetcher.GetDataSource()))
{
// Editor should be initialized from the main thread to set its ThreadChecker.
// However, search calls editor upon initialization thus setting the lazy editor's ThreadChecker
// to a wrong thread. So editor should be initialiazed before serach.
osm::Editor & editor = osm::Editor::Instance();
// Restore map style before classificator loading
MapStyle mapStyle = kDefaultMapStyle;
string mapStyleStr;
if (settings::Get(kMapStyleKey, mapStyleStr))
mapStyle = MapStyleFromSettings(mapStyleStr);
GetStyleReader().SetCurrentStyle(mapStyle);
df::LoadTransitColors();
m_connectToGpsTrack = GpsTracker::Instance().IsEnabled();
// Init strings bundle.
// @TODO. There are hardcoded strings below which are defined in strings.txt as well.
// It's better to use strings from strings.txt instead of hardcoding them here.
m_stringsBundle.SetDefaultString("core_entrance", "Entrance");
m_stringsBundle.SetDefaultString("core_exit", "Exit");
m_stringsBundle.SetDefaultString("core_placepage_unknown_place", "Unknown Place");
m_stringsBundle.SetDefaultString("core_my_places", "My Places");
m_stringsBundle.SetDefaultString("core_my_position", "My Position");
m_stringsBundle.SetDefaultString("postal_code", "Postal Code");
m_featuresFetcher.InitClassificator();
m_featuresFetcher.SetOnMapDeregisteredCallback(bind(&Framework::OnMapDeregistered, this, _1));
LOG(LDEBUG, ("Classificator initialized"));
m_displayedCategories = make_unique<search::DisplayedCategories>(GetDefaultCategories());
// To avoid possible races - init country info getter in constructor.
InitCountryInfoGetter();
LOG(LDEBUG, ("Country info getter initialized"));
InitSearchAPI(params.m_numSearchAPIThreads);
LOG(LDEBUG, ("Search API initialized, part 1"));
m_bmManager = make_unique<BookmarkManager>(BookmarkManager::Callbacks(
[this]() -> StringsBundle const & { return m_stringsBundle; },
[this]() -> SearchAPI & { return GetSearchAPI(); },
[this](vector<BookmarkInfo> const & marks) { GetSearchAPI().OnBookmarksCreated(marks); },
[this](vector<BookmarkInfo> const & marks) { GetSearchAPI().OnBookmarksUpdated(marks); },
[this](vector<kml::MarkId> const & marks) { GetSearchAPI().OnBookmarksDeleted(marks); },
[this](vector<BookmarkGroupInfo> const & marks) { GetSearchAPI().OnBookmarksAttached(marks); },
[this](vector<BookmarkGroupInfo> const & marks) { GetSearchAPI().OnBookmarksDetached(marks); }));
m_bmManager->InitRegionAddressGetter(m_featuresFetcher.GetDataSource(), *m_infoGetter);
m_routingManager.SetBookmarkManager(m_bmManager.get());
m_searchMarks.SetBookmarkManager(m_bmManager.get());
m_routingManager.SetTransitManager(&m_transitManager);
// Init storage with needed callback.
m_storage.Init(bind(&Framework::OnCountryFileDownloaded, this, _1, _2),
bind(&Framework::OnCountryFileDelete, this, _1, _2));
m_storage.SetDownloadingPolicy(&m_storageDownloadingPolicy);
m_storage.SetStartDownloadingCallback([this]() { UpdatePlacePageInfoForCurrentSelection(); });
m_routingManager.SetRouterImpl(RouterType::Vehicle);
UpdateMinBuildingsTapZoom();
LOG(LINFO, ("System languages:", languages::GetPreferred()));
editor.SetDelegate(make_unique<search::EditorDelegate>(m_featuresFetcher.GetDataSource()));
editor.SetInvalidateFn([this](){ InvalidateRect(GetCurrentViewport()); });
/// @todo Uncomment when we will integrate a traffic provider.
// m_trafficManager.SetCurrentDataVersion(m_storage.GetCurrentDataVersion());
// m_trafficManager.SetSimplifiedColorScheme(LoadTrafficSimplifiedColors());
// m_trafficManager.SetEnabled(LoadTrafficEnabled());
m_isolinesManager.SetEnabled(LoadIsolinesEnabled());
InitTransliteration();
LOG(LDEBUG, ("Transliterators initialized"));
/// @todo No any real config loading here for now.
GetPowerManager().Subscribe(this);
GetPowerManager().Load();
if (loadMaps)
LoadMapsSync();
}
Framework::~Framework()
{
GetPowerManager().UnsubscribeAll();
m_threadRunner.reset();
osm::Editor & editor = osm::Editor::Instance();
editor.SetDelegate({});
editor.SetInvalidateFn({});
GetBookmarkManager().Teardown();
m_trafficManager.Teardown();
DestroyDrapeEngine();
m_featuresFetcher.SetOnMapDeregisteredCallback(nullptr);
}
void Framework::ShowNode(storage::CountryId const & countryId)
{
StopLocationFollow();
ShowRect(CalcLimitRect(countryId, GetStorage(), GetCountryInfoGetter()));
}
void Framework::OnCountryFileDownloaded(storage::CountryId const &,
storage::LocalFilePtr const localFile)
{
// Soft reset to signal that mwm file may be out of date in routing caches.
m_routingManager.ResetRoutingSession();
m2::RectD rect = mercator::Bounds::FullRect();
if (localFile && localFile->OnDisk(MapFileType::Map))
{
auto const res = RegisterMap(*localFile);
MwmSet::MwmId const & id = res.first;
if (id.IsAlive())
rect = id.GetInfo()->m_bordersRect;
}
m_trafficManager.Invalidate();
m_transitManager.Invalidate();
m_isolinesManager.Invalidate();
InvalidateRect(rect);
GetSearchAPI().ClearCaches();
}
bool Framework::OnCountryFileDelete(storage::CountryId const & countryId,
storage::LocalFilePtr const localFile)
{
// Soft reset to signal that mwm file may be out of date in routing caches.
m_routingManager.ResetRoutingSession();
if (countryId == m_lastReportedCountry)
m_lastReportedCountry = kInvalidCountryId;
GetSearchAPI().CancelAllSearches();
m2::RectD rect = mercator::Bounds::FullRect();
bool deferredDelete = false;
if (localFile)
{
rect = m_infoGetter->GetLimitRectForLeaf(countryId);
m_featuresFetcher.DeregisterMap(platform::CountryFile(countryId));
deferredDelete = true;
}
InvalidateRect(rect);
GetSearchAPI().ClearCaches();
return deferredDelete;
}
void Framework::OnMapDeregistered(platform::LocalCountryFile const & localFile)
{
auto action = [this, localFile]
{
m_transitManager.OnMwmDeregistered(localFile);
m_isolinesManager.OnMwmDeregistered(localFile);
m_trafficManager.OnMwmDeregistered(localFile);
m_popularityLoader.OnMwmDeregistered(localFile);
m_storage.DeleteCustomCountryVersion(localFile);
};
// Call action on thread in which the framework was created
// For more information look at comment for Observer class in mwm_set.hpp
if (m_storage.GetThreadChecker().CalledOnOriginalThread())
action();
else
GetPlatform().RunTask(Platform::Thread::Gui, action);
}
bool Framework::HasUnsavedEdits(storage::CountryId const & countryId)
{
bool hasUnsavedChanges = false;
auto const forEachInSubtree = [&hasUnsavedChanges, this](storage::CountryId const & fileName,
bool groupNode) {
if (groupNode)
return;
hasUnsavedChanges |= osm::Editor::Instance().HaveMapEditsToUpload(
m_featuresFetcher.GetDataSource().GetMwmIdByCountryFile(platform::CountryFile(fileName)));
};
GetStorage().ForEachInSubtree(countryId, forEachInSubtree);
return hasUnsavedChanges;
}
// Small copy-paste with LoadMapsAsync, but I don't have a better solution.
void Framework::LoadMapsSync()
{
RegisterAllMaps();
LOG(LDEBUG, ("Maps initialized"));
GetSearchAPI().InitAfterWorldLoaded();
LOG(LDEBUG, ("Search API initialized, part 2, after World was loaded"));
osm::Editor & editor = osm::Editor::Instance();
editor.LoadEdits();
m_featuresFetcher.GetDataSource().AddObserver(editor);
LOG(LDEBUG, ("Editor initialized"));
GetStorage().RestoreDownloadQueue();
}
// Small copy-paste with LoadMapsSync, but I don't have a better solution.
void Framework::LoadMapsAsync(std::function<void()> && callback)
{
osm::Editor & editor = osm::Editor::Instance();
threads::SimpleThread([this, &editor, callback = std::move(callback)]()
{
RegisterAllMaps();
LOG(LDEBUG, ("Maps initialized"));
GetSearchAPI().InitAfterWorldLoaded();
LOG(LDEBUG, ("Search API initialized, part 2, after World was loaded"));
GetPlatform().RunTask(Platform::Thread::Gui, [this, &editor, callback = std::move(callback)]()
{
editor.LoadEdits();
m_featuresFetcher.GetDataSource().AddObserver(editor);
LOG(LDEBUG, ("Editor initialized"));
GetStorage().RestoreDownloadQueue();
callback();
});
}).detach();
}
void Framework::RegisterAllMaps()
{
m_storage.RegisterAllLocalMaps(m_enabledDiffs);
vector<shared_ptr<LocalCountryFile>> maps;
m_storage.GetLocalMaps(maps);
for (auto const & localFile : maps)
UNUSED_VALUE(RegisterMap(*localFile));
}
void Framework::DeregisterAllMaps()
{
m_featuresFetcher.Clear();
m_storage.Clear();
}
void Framework::LoadBookmarks()
{
GetBookmarkManager().LoadBookmarks();
}
kml::MarkGroupId Framework::AddCategory(string const & categoryName)
{
return GetBookmarkManager().CreateBookmarkCategory(categoryName);
}
void Framework::FillPointInfoForBookmark(Bookmark const & bmk, place_page::Info & info) const
{
// Convert indices to sorted classifier types.
Classificator const & cl = classif();
buffer_vector<uint8_t, 8> types;
for (uint32_t i : bmk.GetData().m_featureTypes)
types.push_back(cl.GetTypeForIndex(i));
std::sort(types.begin(), types.end());
FillPointInfo(info, bmk.GetPivot(), {} /* customTitle */, [&types](FeatureType & ft)
{
if (types.empty() || ft.GetTypesCount() != types.size())
return false;
// Strict equal types.
feature::TypesHolder fTypes(ft);
std::sort(fTypes.begin(), fTypes.end());
return std::equal(types.begin(), types.end(), fTypes.begin(), fTypes.end());
});
}
void Framework::FillBookmarkInfo(Bookmark const & bmk, place_page::Info & info) const
{
info.SetBookmarkCategoryName(GetBookmarkManager().GetCategoryName(bmk.GetGroupId()));
info.SetBookmarkData(bmk.GetData());
info.SetBookmarkId(bmk.GetId());
info.SetBookmarkCategoryId(bmk.GetGroupId());
auto const description = GetPreferredBookmarkStr(info.GetBookmarkData().m_description);
auto const openingMode = m_routingManager.IsRoutingActive() || description.empty()
? place_page::OpeningMode::Preview
: place_page::OpeningMode::PreviewPlus;
info.SetOpeningMode(openingMode);
if (bmk.CanFillPlacePageMetadata())
{
info.SetMercator(bmk.GetPivot());
info.SetTitlesForBookmark();
info.SetCanEditOrAdd(false);
info.SetFromBookmarkProperties(bmk.GetData().m_properties);
}
else
{
FillPointInfoForBookmark(bmk, info);
}
}
void Framework::FillTrackInfo(Track const & track, m2::PointD const & trackPoint,
place_page::Info & info) const
{
info.SetTrackId(track.GetId());
info.SetBookmarkCategoryId(track.GetGroupId());
info.SetMercator(trackPoint);
}
search::ReverseGeocoder::Address Framework::GetAddressAtPoint(m2::PointD const & pt) const
{
search::ReverseGeocoder const coder(m_featuresFetcher.GetDataSource());
search::ReverseGeocoder::Address addr;
/// @todo Call exact address manually here?
coder.GetNearbyAddress(pt, 0.5 /* maxDistanceM */, addr, true /* placeAsStreet */);
return addr;
}
void Framework::FillFeatureInfo(FeatureID const & fid, place_page::Info & info) const
{
if (!fid.IsValid())
{
LOG(LERROR, ("FeatureID is invalid:", fid));
return;
}
FeaturesLoaderGuard const guard(m_featuresFetcher.GetDataSource(), fid.m_mwmId);
auto ft = guard.GetFeatureByIndex(fid.m_index);
if (!ft)
{
LOG(LERROR, ("Feature can't be loaded:", fid));
return;
}
FillInfoFromFeatureType(*ft, info);
}
void Framework::FillPointInfo(place_page::Info & info, m2::PointD const & mercator,
string const & customTitle /* = {} */,
FeatureMatcher && matcher /* = nullptr */) const
{
auto const fid = GetFeatureAtPoint(mercator, std::move(matcher));
if (fid.IsValid())
{
m_featuresFetcher.GetDataSource().ReadFeature(
[&](FeatureType & ft) { FillInfoFromFeatureType(ft, info); }, fid);
// This line overwrites mercator center from area feature which can be far away.
info.SetMercator(mercator);
}
else
{
FillNotMatchedPlaceInfo(info, mercator, customTitle);
}
}
void Framework::FillNotMatchedPlaceInfo(place_page::Info & info, m2::PointD const & mercator,
std::string const & customTitle /* = {} */) const
{
if (customTitle.empty())
info.SetCustomNameWithCoordinates(mercator, m_stringsBundle.GetString("core_placepage_unknown_place"));
else
info.SetCustomName(customTitle);
info.SetCanEditOrAdd(CanEditMap());
info.SetMercator(mercator);
}
void Framework::FillPostcodeInfo(string const & postcode, m2::PointD const & mercator,
place_page::Info & info) const
{
info.SetCustomNames(postcode, m_stringsBundle.GetString("postal_code"));
info.SetMercator(mercator);
}
void Framework::FillInfoFromFeatureType(FeatureType & ft, place_page::Info & info) const
{
auto const featureStatus = osm::Editor::Instance().GetFeatureStatus(ft.GetID());
ASSERT_NOT_EQUAL(featureStatus, FeatureStatus::Deleted,
("Deleted features cannot be selected from UI."));
info.SetFeatureStatus(featureStatus);
if (ftypes::IsAddressObjectChecker::Instance()(ft))
info.SetAddress(GetAddressAtPoint(feature::GetCenter(ft)).FormatAddress());
info.SetFromFeatureType(ft);
FillDescription(ft, info);
auto const mwmInfo = ft.GetID().m_mwmId.GetInfo();
bool const isMapVersionEditable = mwmInfo && mwmInfo->m_version.IsEditableMap();
bool const canEditOrAdd = featureStatus != FeatureStatus::Obsolete && CanEditMap() &&
isMapVersionEditable;
info.SetCanEditOrAdd(canEditOrAdd);
//info.SetPopularity(m_popularityLoader.Get(ft.GetID()));
// Fill countryId for place page info
auto const & types = info.GetTypes();
bool const isState = ftypes::IsStateChecker::Instance()(types);
if (isState || ftypes::IsCountryChecker::Instance()(types))
{
size_t const level = isState ? 1 : 0;
CountriesVec countries;
CountryId countryId = m_infoGetter->GetRegionCountryId(info.GetMercator());
GetStorage().GetTopmostNodesFor(countryId, countries, level);
if (countries.size() == 1)
countryId = countries.front();
info.SetCountryId(countryId);
info.SetTopmostCountryIds(std::move(countries));
}
}
void Framework::FillApiMarkInfo(ApiMarkPoint const & api, place_page::Info & info) const
{
FillPointInfo(info, api.GetPivot());
string const & name = api.GetName();
if (!name.empty())
info.SetCustomName(name);
info.SetApiId(api.GetApiID());
info.SetApiUrl(GenerateApiBackUrl(api));
}
void Framework::FillSearchResultInfo(SearchMarkPoint const & smp, place_page::Info & info) const
{
if (smp.GetFeatureID().IsValid())
FillFeatureInfo(smp.GetFeatureID(), info);
else
FillPointInfo(info, smp.GetPivot(), smp.GetMatchedName());
}
void Framework::FillMyPositionInfo(place_page::Info & info, place_page::BuildInfo const & buildInfo) const
{
auto const position = GetCurrentPosition();
CHECK(position, ());
info.SetMercator(*position);
info.SetCustomName(m_stringsBundle.GetString("core_my_position"));
UserMark const * mark = FindUserMarkInTapPosition(buildInfo);
if (mark != nullptr && mark->GetMarkType() == UserMark::Type::ROUTING)
{
auto routingMark = static_cast<RouteMarkPoint const *>(mark);
info.SetIsRoutePoint();
info.SetRouteMarkType(routingMark->GetRoutePointType());
info.SetIntermediateIndex(routingMark->GetIntermediateIndex());
}
}
void Framework::FillRouteMarkInfo(RouteMarkPoint const & rmp, place_page::Info & info) const
{
FillPointInfo(info, rmp.GetPivot());
info.SetIsRoutePoint();
info.SetRouteMarkType(rmp.GetRoutePointType());
info.SetIntermediateIndex(rmp.GetIntermediateIndex());
}
void Framework::FillSpeedCameraMarkInfo(SpeedCameraMark const & speedCameraMark, place_page::Info & info) const
{
info.SetCanEditOrAdd(false);
info.SetMercator(speedCameraMark.GetPivot());
// Title is a speed limit, if any.
auto title = speedCameraMark.GetTitle();
if (!title.empty())
title = title + " " + platform::GetLocalizedSpeedUnits(measurement_utils::GetMeasurementUnits());
info.SetCustomNames(title, platform::GetLocalizedTypeName("highway-speed_camera"));
}
void Framework::FillTransitMarkInfo(TransitMark const & transitMark, place_page::Info & info) const
{
FillFeatureInfo(transitMark.GetFeatureID(), info);
/// @todo Add useful info in PP for TransitMark (public transport).
}
void Framework::FillRoadTypeMarkInfo(RoadWarningMark const & roadTypeMark, place_page::Info & info) const
{
if (roadTypeMark.GetFeatureID().IsValid())
{
FeaturesLoaderGuard const guard(m_featuresFetcher.GetDataSource(), roadTypeMark.GetFeatureID().m_mwmId);
auto ft = guard.GetFeatureByIndex(roadTypeMark.GetFeatureID().m_index);
if (ft)
{
FillInfoFromFeatureType(*ft, info);
info.SetRoadType(*ft, roadTypeMark.GetRoadWarningType(),
RoadWarningMark::GetLocalizedRoadWarningType(roadTypeMark.GetRoadWarningType()),
roadTypeMark.GetDistance());
info.SetMercator(roadTypeMark.GetPivot());
return;
}
else
{
LOG(LERROR, ("Feature can't be loaded:", roadTypeMark.GetFeatureID()));
}
}
info.SetRoadType(roadTypeMark.GetRoadWarningType(),
RoadWarningMark::GetLocalizedRoadWarningType(roadTypeMark.GetRoadWarningType()),
roadTypeMark.GetDistance());
info.SetMercator(roadTypeMark.GetPivot());
}
void Framework::ShowBookmark(kml::MarkId id)
{
auto const * mark = m_bmManager->GetBookmark(id);
ShowBookmark(mark);
}
void Framework::ShowBookmark(Bookmark const * mark)
{
if (mark == nullptr)
return;
StopLocationFollow();
place_page::BuildInfo info;
info.m_mercator = mark->GetPivot();
info.m_userMarkId = mark->GetId();
m_currentPlacePageInfo = BuildPlacePageInfo(info);
auto scale = static_cast<int>(mark->GetScale());
if (scale == 0)
scale = scales::GetUpperComfortScale();
auto es = GetBookmarkManager().GetEditSession();
es.SetIsVisible(mark->GetGroupId(), true /* visible */);
if (m_drapeEngine != nullptr)
{
m_drapeEngine->SetModelViewCenter(mark->GetPivot(), scale, true /* isAnim */,
true /* trackVisibleViewport */);
}
ActivateMapSelection();
}
void Framework::ShowTrack(kml::TrackId trackId)
{
auto & bm = GetBookmarkManager();
auto const track = bm.GetTrack(trackId);
if (track == nullptr)
return;
auto rect = track->GetLimitRect();
ExpandRectForPreview(rect);
StopLocationFollow();
ShowRect(rect);
auto es = GetBookmarkManager().GetEditSession();
es.SetIsVisible(track->GetGroupId(), true /* visible */);
if (track->IsInteractive())
bm.SetDefaultTrackSelection(trackId, true /* showInfoSign */);
}
void Framework::ShowBookmarkCategory(kml::MarkGroupId categoryId, bool animation)
{
auto & bm = GetBookmarkManager();
auto rect = bm.GetCategoryRect(categoryId, true /* addIconsSize */);
if (!rect.IsValid())
return;
ExpandRectForPreview(rect);
StopLocationFollow();
ShowRect(rect, -1 /* maxScale */, animation);
auto es = bm.GetEditSession();
es.SetIsVisible(categoryId, true /* visible */);
auto const trackIds = bm.GetTrackIds(categoryId);
for (auto trackId : trackIds)
{
if (!bm.GetTrack(trackId)->IsInteractive())
continue;
bm.SetDefaultTrackSelection(trackId, true /* showInfoSign */);
break;
}
}
void Framework::ShowFeature(FeatureID const & featureId)
{
StopLocationFollow();
place_page::BuildInfo info;
info.m_featureId = featureId;
info.m_match = place_page::BuildInfo::Match::FeatureOnly;
m_currentPlacePageInfo = BuildPlacePageInfo(info);
if (m_drapeEngine != nullptr)
{
auto const pt = m_currentPlacePageInfo->GetMercator();
auto const scale = scales::GetUpperComfortScale();
m_drapeEngine->SetModelViewCenter(pt, scale, true /* isAnim */, true /* trackVisibleViewport */);
}
ActivateMapSelection();
}
void Framework::AddBookmarksFile(string const & filePath, bool isTemporaryFile)
{
GetBookmarkManager().LoadBookmark(filePath, isTemporaryFile);
}
void Framework::PrepareToShutdown()
{
DestroyDrapeEngine();
}
void Framework::SaveViewport()
{
m2::AnyRectD rect;
if (m_currentModelView.isPerspective())
{
ScreenBase modelView = m_currentModelView;
modelView.ResetPerspective();
rect = modelView.GlobalRect();
}
else
{
rect = m_currentModelView.GlobalRect();
}
settings::Set("ScreenClipRect", rect);
}
void Framework::LoadViewport()
{
m2::AnyRectD rect;
if (settings::Get("ScreenClipRect", rect) && df::GetWorldRect().IsRectInside(rect.GetGlobalRect()))
{
if (m_drapeEngine != nullptr)
m_drapeEngine->SetModelViewAnyRect(rect, false /* isAnim */, false /* useVisibleViewport */);
}
else
{
ShowAll();
}
}
void Framework::ShowAll()
{
if (m_drapeEngine == nullptr)
return;
m_drapeEngine->SetModelViewAnyRect(m2::AnyRectD(m_featuresFetcher.GetWorldRect()), false /* isAnim */,
false /* useVisibleViewport */);
}
m2::PointD Framework::GetVisiblePixelCenter() const
{
return m_visibleViewport.Center();
}
m2::PointD const & Framework::GetViewportCenter() const
{
return m_currentModelView.GetOrg();
}
void Framework::SetViewportCenter(m2::PointD const & pt, int zoomLevel /* = -1 */, bool isAnim /* = true */,
bool trackVisibleViewport /* = false */)
{
if (m_drapeEngine != nullptr)
m_drapeEngine->SetModelViewCenter(pt, zoomLevel, isAnim, trackVisibleViewport);
}
m2::RectD Framework::GetCurrentViewport() const
{
return m_currentModelView.ClipRect();
}
void Framework::SetVisibleViewport(m2::RectD const & rect)
{
if (m_drapeEngine == nullptr)
return;
double constexpr kEps = 0.5;
if (m2::IsEqual(m_visibleViewport, rect, kEps, kEps))
return;
double constexpr kMinSize = 100.0;
if (rect.SizeX() < kMinSize || rect.SizeY() < kMinSize)
return;
m_visibleViewport = rect;
m_drapeEngine->SetVisibleViewport(rect);
}
void Framework::ShowRect(m2::RectD const & rect, int maxScale, bool animation, bool useVisibleViewport)
{
if (m_drapeEngine == nullptr)
return;
m_drapeEngine->SetModelViewRect(rect, true /* applyRotation */, maxScale /* zoom */, animation,
useVisibleViewport);
}
void Framework::ShowRect(m2::AnyRectD const & rect, bool animation, bool useVisibleViewport)
{
if (m_drapeEngine != nullptr)
m_drapeEngine->SetModelViewAnyRect(rect, animation, useVisibleViewport);
}
void Framework::GetTouchRect(m2::PointD const & center, uint32_t pxRadius, m2::AnyRectD & rect)
{
m_currentModelView.GetTouchRect(center, static_cast<double>(pxRadius), rect);
}
void Framework::SetViewportListener(TViewportChangedFn const & fn)
{