aboutsummaryrefslogtreecommitdiff
path: root/libs/map/framework.hpp
blob: 8369f20593bb48056e470d7572ddb99f0a8663d7 (plain) (blame)
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
#pragma once

#include "map/api_mark_point.hpp"
#include "map/bookmark.hpp"
#include "map/bookmark_manager.hpp"
#include "map/features_fetcher.hpp"
#include "map/isolines_manager.hpp"
#include "map/mwm_url.hpp"
#include "map/place_page_info.hpp"
#include "map/position_provider.hpp"
#include "map/power_management/power_management_schemas.hpp"
#include "map/power_management/power_manager.hpp"
#include "map/routing_manager.hpp"
#include "map/routing_mark.hpp"
#include "map/search_api.hpp"
#include "map/search_mark.hpp"
#include "map/selection_processor.hpp"
#include "map/track.hpp"
#include "map/track_statistics.hpp"
#include "map/traffic_manager.hpp"
#include "map/transit/transit_reader.hpp"

#include "drape_frontend/drape_api.hpp"
#include "drape_frontend/drape_engine.hpp"
#include "drape_frontend/gui/skin.hpp"
#include "drape_frontend/user_event_stream.hpp"

#include "drape/drape_global.hpp"
#include "drape/graphics_context_factory.hpp"

#include "kml/type_utils.hpp"

#include "editor/new_feature_categories.hpp"
#include "editor/osm_editor.hpp"

#include "indexer/data_source.hpp"
#include "indexer/data_source_helpers.hpp"
#include "indexer/map_object.hpp"
#include "indexer/map_style.hpp"

#include "search/displayed_categories.hpp"
#include "search/result.hpp"
#include "search/reverse_geocoder.hpp"

#include "storage/downloading_policy.hpp"
#include "storage/storage.hpp"

#include "platform/distance.hpp"
#include "platform/location.hpp"
#include "platform/placement_settings.hpp"
#include "platform/platform.hpp"
#include "platform/products.hpp"

#include "geometry/rect2d.hpp"
#include "geometry/screenbase.hpp"

#include "base/macros.hpp"
#include "base/strings_bundle.hpp"

#include "std/target_os.hpp"

#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <vector>

namespace osm
{
class EditableMapObject;
}

namespace storage
{
class CountryInfoReader;
}  // namespace storage

namespace descriptions
{
class Loader;
}

/// Uncomment line to make fixed position settings and
/// build version for screenshots.
// #define FIXED_LOCATION

class RasterTileProvider;

struct FrameworkParams
{
  bool m_enableDiffs = true;
  size_t m_numSearchAPIThreads = 1;

  FrameworkParams() = default;
  FrameworkParams(bool enableDiffs) : m_enableDiffs(enableDiffs) {}
};

class Framework
  : public PositionProvider
  , public SearchAPI::Delegate
  , public RoutingManager::Delegate
  , private power_management::PowerManager::Subscriber
{
  DISALLOW_COPY(Framework);
  friend class SelectionProcessor;

#ifdef FIXED_LOCATION
  class FixedPosition
  {
    std::pair<double, double> m_latlon;
    double m_dirFromNorth;
    bool m_fixedLatLon, m_fixedDir;

  public:
    FixedPosition();

    void GetLat(double & l) const
    {
      if (m_fixedLatLon)
        l = m_latlon.first;
    }
    void GetLon(double & l) const
    {
      if (m_fixedLatLon)
        l = m_latlon.second;
    }

    void GetNorth(double & n) const
    {
      if (m_fixedDir)
        n = m_dirFromNorth;
    }
    bool HasNorth() const { return m_fixedDir; }

  } m_fixedPos;
#endif

private:
  // Must be first member in Framework and must be destroyed first in Framework destructor.
  std::unique_ptr<Platform::ThreadRunner> m_threadRunner = std::make_unique<Platform::ThreadRunner>();

protected:
  using TDrapeFunction = std::function<void(df::DrapeEngine *)>;

  StringsBundle m_stringsBundle;

  FeaturesFetcher m_featuresFetcher;

  // The order matters here: DisplayedCategories may be used only
  // after classificator is loaded by |m_featuresFetcher|.
  std::unique_ptr<search::DisplayedCategories> m_displayedCategories;

  // The order matters here: storage::CountryInfoGetter and
  // m_FeaturesFetcher must be initialized before
  // search::Engine and, therefore, destroyed after search::Engine.
  std::unique_ptr<storage::CountryInfoReader> m_infoGetter;

  std::unique_ptr<SearchAPI> m_searchAPI;

  ScreenBase m_currentModelView;
  m2::RectD m_visibleViewport;

  using TViewportChangedFn = df::DrapeEngine::ModelViewChangedHandler;
  TViewportChangedFn m_viewportChangedFn;

  drape_ptr<df::DrapeEngine> m_drapeEngine;
  double m_fontScaleFactor = 1.0;

  // POC source of raster background tiles (see tileBackgroundReadFn in CreateDrapeEngine).
  std::unique_ptr<RasterTileProvider> m_rasterTileProvider;

  StorageDownloadingPolicy m_storageDownloadingPolicy;
  storage::Storage m_storage;
  bool m_enabledDiffs;

  location::TMyPositionModeChanged m_myPositionListener;

  std::unique_ptr<BookmarkManager> m_bmManager;

  SearchMarks m_searchMarks;

  df::DrapeApi m_drapeApi;

  bool m_isRenderingEnabled;

  // Note. |m_powerManager| should be declared before |m_routingManager|
  power_management::PowerManager m_powerManager;

  TransitReadManager m_transitManager;
  IsolinesManager m_isolinesManager;

  // Note. |m_routingManager| should be declared before |m_trafficManager|
  RoutingManager m_routingManager;

  TrafficManager m_trafficManager;

  /// This function will be called by m_storage when latest local files
  /// is downloaded.
  void OnCountryFileDownloaded(storage::CountryId const & countryId, storage::LocalFilePtr const localFile);

  /// This function will be called by m_storage before latest local files
  /// is deleted.
  bool OnCountryFileDelete(storage::CountryId const & countryId, storage::LocalFilePtr const localFile);

  /// This function is called by m_featuresFetcher when the map file is deregistered.
  void OnMapDeregistered(platform::LocalCountryFile const & localFile);

  void ClearAllCaches();

  void OnViewportChanged(ScreenBase const & screen);

  void InitTransliteration();

  // Builds m_rasterTileProvider for the given XYZ source and the "bg_tiles" disk cache.
  void CreateBackgroundTilesProvider(std::string const & url, uint32_t cacheSizeMB);

public:
  explicit Framework(FrameworkParams const & params = {}, bool loadMaps = true);
  virtual ~Framework() override;

  df::DrapeApi & GetDrapeApi() { return m_drapeApi; }

  /// \returns true if there're unsaved changes in map with |countryId| and false otherwise.
  /// \note It works for group and leaf node.
  bool HasUnsavedEdits(storage::CountryId const & countryId);

  void LoadMapsSync();
  void LoadMapsAsync(std::function<void()> && callback);

  /// Registers all local map files in internal indexes.
  void RegisterAllMaps();

  /// Deregisters all registered map files.
  void DeregisterAllMaps();

  /// Registers a local map file in internal indexes.
  std::pair<MwmSet::MwmId, MwmSet::RegResult> RegisterMap(platform::LocalCountryFile const & localFile);

  /// Shows group or leaf mwm on the map.
  void ShowNode(storage::CountryId const & countryId);

  /// Checks, whether the country is loaded.
  bool IsCountryLoadedByName(std::string_view name) const;

  void InvalidateRect(m2::RectD const & rect);
  void Invalidate() { InvalidateRect(GetCurrentViewport()); }

  /// @return 0 if there is no country under point or country is not loaded.
  int64_t GetMwmVersion(m2::PointD const & pt) const;
  bool NeedUpdateForRoutes() const;

  enum class DoAfterUpdate
  {
    Nothing,
    AutoupdateMaps,
    AskForUpdateMaps,
    Migrate
  };
  //  DoAfterUpdate ToDoAfterUpdate() const;

  storage::Storage & GetStorage() { return m_storage; }
  storage::Storage const & GetStorage() const { return m_storage; }
  search::DisplayedCategories const & GetDisplayedCategories();
  storage::CountryInfoReader const & GetCountryInfoGetter() { return *m_infoGetter; }
  StorageDownloadingPolicy & GetDownloadingPolicy() { return m_storageDownloadingPolicy; }

  DataSource const & GetDataSource() const { return m_featuresFetcher.GetDataSource(); }

  SearchAPI & GetSearchAPI();

  /// @name Bookmarks, Tracks and other UserMarks
  /// Scans and loads all kml files with bookmarks in WritableDir.
  void LoadBookmarks();

  /// @return Created bookmark category id.
  kml::MarkGroupId AddCategory(std::string const & categoryName);

  kml::MarkGroupId LastEditedBMCategory() { return GetBookmarkManager().LastEditedBMCategory(); }
  kml::ColorData LastEditedBMColor() const { return GetBookmarkManager().LastEditedBMColor(); }

  void ShowBookmark(kml::MarkId id);
  void ShowBookmark(Bookmark const * bookmark);
  void ShowTrack(kml::TrackId trackId);
  // Sets individual track visibility. Hiding the track that is currently shown in the
  // Place Page also resets the selection so nothing stays selected on an invisible track.
  void SetTrackVisibility(kml::TrackId trackId, bool visible);
  // Deletes the track, closing the Place Page first if it currently shows this track.
  void DeleteTrack(kml::TrackId trackId);
  // Same for a whole multi-select batch. Call this rather than the EditSession method it wraps, so that the
  // Place Page cleanup does not have to be repeated per platform.
  void DeleteBookmarksAndTracks(kml::MarkIdCollection const & bookmarkIds, kml::TrackIdCollection const & trackIds);
  void ShowFeature(FeatureID const & featureId);
  void ShowBookmarkCategory(kml::MarkGroupId categoryId, bool animation = true);

  void SelectTrackCandidate(kml::TrackId trackId, RelationID const & relationId);

  void AddBookmarksFile(std::string const & filePath, bool isTemporaryFile);

  BookmarkManager & GetBookmarkManager();
  BookmarkManager const & GetBookmarkManager() const;

  /// @name Visualize utilities, used in desktop only. Implemented in framework_visualize.cpp
  /// @{
  void VisualizeRoadsInRect(m2::RectD const & rect);
  void VisualizeCityBoundariesInRect(m2::RectD const & rect);
  void VisualizeCityRoadsInRect(m2::RectD const & rect);
  void VisualizeCrossMwmTransitionsInRect(m2::RectD const & rect);
  /// @}

public:
  // SearchAPI::Delegate overrides:
  void RunUITask(std::function<void()> fn) override;
  using SearchResultsIterT = SearchAPI::Delegate::ResultsIterT;
  void ShowViewportSearchResults(SearchResultsIterT begin, SearchResultsIterT end, bool clear) override;
  void ClearViewportSearchResults() override;
  // PositionProvider, SearchApi::Delegate and TipsApi::Delegate override.
  std::optional<m2::PointD> GetCurrentPosition() const override;
  bool ParseSearchQueryCommand(search::SearchParams const & params) override;
  m2::PointD GetMinDistanceBetweenResults() const override;

private:
  void UpdateBookmarksTextPlacement();

  void ActivateMapSelection();
  void InvalidateUserMarks();

  void DeactivateHotelSearchMark();

public:
  /// @return true if a transit route selection was recovered (PP re-activated).
  bool DeactivateMapSelection();
  void DeactivateMapSelectionCircle(bool restoreViewport);
  void SwitchFullScreen();
  /// Used to "refresh" UI in some cases (e.g. feature editing).
  void UpdatePlacePageInfoForCurrentSelection(std::optional<place_page::BuildInfo> const & overrideInfo = {});

  struct PlacePageEvent
  {
    /// Called to notify UI that object on a map was selected (UI should show Place Page, for example).
    using OnOpen = std::function<void()>;
    /// Called to notify UI that object on a map was deselected (UI should hide Place Page).
    /// If switchFullScreenMode is true, ui can [optionally] enter or exit full screen mode.
    using OnClose = std::function<void()>;
    using OnUpdate = std::function<void()>;
    using OnSwitchFullScreen = std::function<void()>;
  };

  void SetPlacePageListeners(PlacePageEvent::OnOpen onOpen, PlacePageEvent::OnClose onClose,
                             PlacePageEvent::OnUpdate onUpdate, PlacePageEvent::OnSwitchFullScreen onSwitchFullScreen);
  bool HasPlacePageInfo() const { return m_currentPlacePageInfo.has_value(); }
  place_page::Info const & GetCurrentPlacePageInfo() const;
  place_page::Info & GetCurrentPlacePageInfo();
  void BuildAndSetPlacePageInfo(place_page::BuildInfo const & buildInfo) { OnTapEvent(buildInfo); }

  void InvalidateRendering();
  void EnableDebugRectRendering(bool enabled);

  void EnableChoosePositionMode(bool enable, bool enableBounds, m2::PointD const * optionalPosition);
  void BlockTapEvents(bool block);

  using TCurrentCountryChanged = std::function<void(storage::CountryId const &)>;
  storage::CountryId const & GetLastReportedCountry() { return m_lastReportedCountry; }
  /// Guarantees that listener is called in the main thread context.
  void SetCurrentCountryChangedListener(TCurrentCountryChanged listener);

  std::vector<std::string> GetRegionsCountryIdByRect(m2::RectD const & rect, bool rough) const;
  std::vector<MwmSet::MwmId> GetMwmsByRect(m2::RectD const & rect, bool rough) const;

private:
  std::optional<place_page::Info> m_currentPlacePageInfo;

  void OnTapEvent(place_page::BuildInfo const & buildInfo);
  place_page::Info BuildPlacePageInfo(place_page::BuildInfo const & buildInfo);
  std::optional<kml::TrackData> TryBuildRelationTrack(Track::TrackSelectionInfo const & candidateInfo);
  bool BuildTrackPlacePage(Track::TrackSelectionInfo const & trackSelectionInfo, place_page::Info & info);
  std::vector<Track::TrackSelectionInfo> FindTracksInTapPosition(place_page::BuildInfo const & buildInfo) const;
  /// Builds temporary track candidates for route relations associated with tapped line features.
  std::vector<Track::TrackSelectionInfo> FindRelationTracksInTapPosition(
      std::vector<std::pair<double, FeatureID>> const & lineCandidates, m2::PointD const & mercator);
  UserMark const * FindUserMarkInTapPosition(place_page::BuildInfo const & buildInfo) const;
  FeatureID FindBuildingAtPoint(m2::PointD const & mercator) const;

  void UpdateMinBuildingsTapZoom();

  int m_minBuildingsTapZoom;

  PlacePageEvent::OnOpen m_onPlacePageOpen;
  PlacePageEvent::OnClose m_onPlacePageClose;
  PlacePageEvent::OnUpdate m_onPlacePageUpdate;
  PlacePageEvent::OnSwitchFullScreen m_onSwitchFullScreen;

private:
  std::vector<m2::TriangleD> GetSelectedFeatureTriangles() const;

public:
  /// @name GPS location updates routine.
  void OnLocationError(location::TLocationError error);
  void OnLocationUpdate(location::GpsInfo const & info);
  void OnCompassUpdate(location::CompassInfo const & info);
  void SwitchMyPositionNextMode();
  /// Should be set before Drape initialization. Guarantees that fn is called in main thread context.
  void SetMyPositionModeListener(location::TMyPositionModeChanged && fn);

  location::EMyPositionMode GetMyPositionMode() const;

private:
  void OnUserPositionChanged(m2::PointD const & position, bool hasPosition);

public:
  struct DrapeCreationParams
  {
    dp::ApiVersion m_apiVersion = dp::ApiVersion::OpenGLES3;
    double m_visualScale = 1.0;
    int m_surfaceWidth = 0;
    int m_surfaceHeight = 0;
    gui::TWidgetsInitInfo m_widgetsInitInfo;

    bool m_isChoosePositionMode = false;
    df::Hints m_hints;
    dp::RenderInjectionHandler m_renderInjectionHandler;
  };

  void CreateDrapeEngine(ref_ptr<dp::GraphicsContextFactory> contextFactory, DrapeCreationParams && params);
  ref_ptr<df::DrapeEngine> GetDrapeEngine();
  bool IsDrapeEngineCreated() const { return m_drapeEngine != nullptr; }
  void DestroyDrapeEngine();
  /// Called when graphics engine should be temporarily paused and then resumed.
  void SetRenderingEnabled(ref_ptr<dp::GraphicsContextFactory> contextFactory = nullptr);
  void SetRenderingDisabled(bool destroySurface);

  void SetGraphicsContextInitializationHandler(df::OnGraphicsContextInitialized && handler);

  void OnRecoverSurface(int width, int height, bool recreateContextDependentResources);
  void OnDestroySurface();

  void UpdateVisualScale(double vs);

  /// Sets the distance between the bottom edge of the arrow and the bottom edge of the visible viewport
  /// in follow routing mode or resets it to the default value.
  void UpdateMyPositionRoutingOffset(bool useDefault, int offsetY);

private:
  /// Depends on initialized Drape engine.
  void SaveViewport();
  /// Depends on initialized Drape engine.
  void LoadViewport();

  df::OnGraphicsContextInitialized m_onGraphicsContextInitialized;

public:
  using TrackRecordingUpdateHandler = platform::SafeCallback<void(TrackStatistics const & trackStatistics)>;
  void StartTrackRecording();
  void SetTrackRecordingUpdateHandler(TrackRecordingUpdateHandler && trackRecordingDidUpdate);
  void StopTrackRecording();
  void SaveTrackRecordingWithName(std::string const & name);
  bool IsTrackRecordingEmpty() const;
  bool IsTrackRecordingEnabled() const;

  void SaveRoute();
  /// Returns the elevation profile data of the currently recorded track.
  /// To get the data on the every track recording state update, this function should be called after receiving the
  /// callback from the `SetTrackRecordingUpdateHandler`.
  static ElevationInfo const & GetTrackRecordingElevationInfo();

  void SetMapStyle(MapStyle mapStyle);
  void MarkMapStyle(MapStyle mapStyle);
  MapStyle GetMapStyle() const;

  void SetupMeasurementSystem();

  void SetWidgetLayout(gui::TWidgetsLayoutInfo && layout);

  void PrepareToShutdown();

private:
  void InitCountryInfoGetter();
  void InitSearchAPI(size_t numThreads);

  void OnUpdateCurrentCountry(m2::PointD const & pt, int zoomLevel);

  storage::CountryId m_lastReportedCountry;
  TCurrentCountryChanged m_currentCountryChanged;

  void OnUpdateGpsTrackPointsCallback(std::vector<std::pair<size_t, location::GpsInfo>> && toAdd,
                                      std::pair<size_t, size_t> const & toRemove,
                                      TrackStatistics const & trackStatistics);

  TrackRecordingUpdateHandler m_trackRecordingUpdateHandler;

  std::unique_ptr<descriptions::Loader> m_descriptionsLoader;
  SelectionProcessor m_selectionProcessor;

  struct RouteTransitSelection
  {
    FeatureID m_featureId;
    uint32_t m_relID = 0;
  };

  std::optional<RouteTransitSelection> m_routeTransitSelection;

public:
  // Moves viewport to the search result and taps on it.
  void SelectSearchResult(search::Result const & res, bool animation);

  // Highlights a public-transport route line on the map, using the current place page's feature
  // to locate the relation. The current place page (stop) remains open.
  void SelectRoute(uint32_t relID);

  // Builds a TransitInfo (lines + stops) for @p relID relative to the current place page's feature
  // and shows it on the transit scheme layer (with the usual map dim).
  void ShowRouteTransit(uint32_t relID);
  // Returns the ref string of the currently selected transit route, or empty if none.
  std::string GetActiveTransitRouteRef() const;
  // Is called on PT PP close. Clears drape's transit scheme if ShowRouteTransit above was called before.
  void HideRouteTransitIfNeeded();

  // Cancels all searches, stops location follow and then selects
  // search result.
  void ShowSearchResult(search::Result const & res, bool animation = true);

  void UpdateViewport(search::Results const & results);

  void FillSearchResultsMarks(bool clear, search::Results const & results);
  void FillSearchResultsMarks(SearchResultsIterT beg, SearchResultsIterT end, bool clear);

  /// Calculate distance and direction to POI for the given position.
  /// @param[in]  point             POI's position;
  /// @param[in]  lat, lon, north   Current position and heading from north;
  /// @param[out] distance          Distance to point from (lat, lon);
  /// @param[out] azimut            Azimut to point from (lat, lon);
  /// @return true  If the POI is near the current position (distance < 25 km);
  bool GetDistanceAndAzimut(m2::PointD const & point, double lat, double lon, double north,
                            platform::Distance & distance, double & azimut);

  /// @name For Desktop only.
  /// @{
  m2::PointD PtoG(m2::PointD const & p) const;
  m2::PointD P3dtoG(m2::PointD const & p) const;
  /// @}

  /// Show all model by it's world rect.
  void ShowAll();

  m2::PointD GetVisiblePixelCenter() const;

  m2::PointD const & GetViewportCenter() const;
  void SetViewportCenter(m2::PointD const & pt, int zoomLevel = -1, bool isAnim = true,
                         bool trackVisibleViewport = false);

  m2::RectD GetCurrentViewport() const;
  void SetVisibleViewport(m2::RectD const & rect);

  void ShowRect(m2::RectD const & rect, bool animation = true, bool useVisibleViewport = false);
  void ShowRect(m2::AnyRectD const & rect, bool animation = true, bool useVisibleViewport = false);

  void SetViewportListener(TViewportChangedFn const & fn);

#if defined(OMIM_OS_DESKTOP)
  using TGraphicsReadyFn = df::DrapeEngine::GraphicsReadyHandler;
  void NotifyGraphicsReady(TGraphicsReadyFn const & fn, bool needInvalidate);
#endif

  void StopLocationFollow();

  /// Resize event from window.
  void OnSize(int w, int h);

  enum EScaleMode
  {
    SCALE_MAG,
    SCALE_MAG_LIGHT,
    SCALE_MIN,
    SCALE_MIN_LIGHT
  };

  void Scale(EScaleMode mode, bool isAnim);
  void Scale(EScaleMode mode, m2::PointD const & pxPoint, bool isAnim);
  void Scale(double factor, bool isAnim);
  void Scale(double factor, m2::PointD const & pxPoint, bool isAnim);

  /// Moves the viewport a distance of factorX * viewportWidth and factorY * viewportHeight.
  /// E.g. factorX == 1.0 moves the map one screen size to the right, factorX == -0.5 moves the map
  /// half screen size to the left, factorY == -2.0 moves the map two sizes down,
  /// factorY = 1.5 moves the map one and a half size up.
  void Move(double factorX, double factorY, bool isAnim);

  void Scroll(double distanceX, double distanceY);

  void Rotate(double azimuth, bool isAnim);

  void TouchEvent(df::TouchEvent const & touch);

  void MakeFrameActive();

  int GetDrawScale() const;

  void RunFirstLaunchAnimation();

  /// Set correct viewport, parse API, show balloon.
  void ExecuteMapApiRequest() { m_parsedMapApi.ExecuteMapApiRequest(*this); }

  url_scheme::ParsedMapApi::UrlType ParseAndSetApiURL(std::string const & url)
  {
    return m_parsedMapApi.SetUrlAndParse(url);
  }

  struct ParsedRoutingData
  {
    ParsedRoutingData(std::vector<url_scheme::RoutePoint> const & points, routing::RouterType type)
      : m_points(points)
      , m_type(type)
    {}
    std::vector<url_scheme::RoutePoint> m_points;
    routing::RouterType m_type;
  };

  ParsedRoutingData GetParsedRoutingData() const;
  url_scheme::SearchRequest GetParsedSearchRequest() const;
  std::string GetParsedOAuth2Code() const;
  std::string const & GetParsedAppName() const;
  std::string const & GetParsedBackUrl() const;
  ms::LatLon GetParsedCenterLatLon() const;
  url_scheme::InAppFeatureHighlightRequest GetInAppFeatureHighlightRequest() const;

private:
  /// @returns true if command was handled by editor.
  bool ParseEditorDebugCommand(search::SearchParams const & params);

  /// @returns true if command was handled by drape.
  bool ParseDrapeDebugCommand(std::string const & query);

  /// This function can be used for enabling some experimental features for routing.
  bool ParseRoutingDebugCommand(search::SearchParams const & params);

  /// @returns true if command was handled by downloader debug commands.
  bool ParseDownloaderDebugCommand(search::SearchParams const & params);

  static bool ParseAllTypesDebugCommand(search::SearchParams const & params);

  /// @return false if @a outInfo was not filled (e.g. a stale track mark), so the caller should fall
  /// back to the regular tap matching instead of activating an empty selection.
  bool FillUserMarkInfo(UserMark const * mark, place_page::Info & outInfo);
  void FillApiMarkInfo(ApiMarkPoint const & api, place_page::Info & info) const;
  void FillSearchResultInfo(SearchMarkPoint const & smp, place_page::Info & info) const;
  void FillMyPositionInfo(place_page::Info & info, place_page::BuildInfo const & buildInfo) const;
  void FillRouteMarkInfo(RouteMarkPoint const & rmp, place_page::Info & info) const;
  void FillSpeedCameraMarkInfo(SpeedCameraMark const & speedCameraMark, place_page::Info & info) const;
  void FillTransitMarkInfo(TransitMark const & transitMark, place_page::Info & info) const;
  void FillRoadTypeMarkInfo(RoadWarningMark const & roadTypeMark, place_page::Info & info) const;
  void FillPointInfoForBookmark(Bookmark const & bmk, place_page::Info & info) const;
  void FillBookmarkInfo(Bookmark const & bmk, place_page::Info & info) const;
  void FillTrackInfo(Track const & track, Track::TrackSelectionInfo const & trackSelectionInfo,
                     place_page::Info & info) const;

  SelectionProcessor const & GetSelectionProcessor() const { return m_selectionProcessor; }

public:
  search::ReverseGeocoder::Address GetAddressAtPoint(m2::PointD const & pt) const;

  /// Delegates to SelectionProcessor::GetFeatureAtPoint.
  FeatureID GetFeatureAtPoint(m2::PointD const & mercator) const;

  /// @param[in] scale Pass GetUpperScale (for countries) or GetUpperWorldScale (for World map).
  template <typename TFn>
  void ForEachFeatureAtPoint(TFn && fn, m2::PointD const & mercator, int scale) const
  {
    indexer::ForEachFeatureAtPoint(m_featuresFetcher.GetDataSource(), fn, mercator, scale);
  }

  osm::MapObject GetMapObjectByID(FeatureID const & fid) const;

  void MemoryWarning();
  void EnterBackground();
  void EnterForeground();

  /// Set the localized strings bundle
  void AddString(std::string const & name, std::string const & value) { m_stringsBundle.SetString(name, value); }

  StringsBundle const & GetStringsBundle();

  /// [in] lat, lon - last known location
  /// [out] lat, lon - predicted location
  static void PredictLocation(double & lat, double & lon, double accuracy, double bearing, double speed,
                              double elapsedSeconds);

public:
  static std::string CodeGe0url(Bookmark const * bmk, bool addName);
  static std::string CodeGe0url(double lat, double lon, double zoomLevel, std::string const & name);

  /// @name Api
  std::string GenerateApiBackUrl(ApiMarkPoint const & point) const;
  url_scheme::ParsedMapApi const & GetApiDataHolder() const { return m_parsedMapApi; }

private:
  url_scheme::ParsedMapApi m_parsedMapApi;

public:
  /// @name Data versions
  // bool IsDataVersionUpdated();
  // void UpdateSavedDataVersion();
  int64_t GetCurrentDataVersion() const;

public:
  void AllowTransliteration(bool allowTranslit);
  static bool LoadTransliteration();
  static void SaveTransliteration(bool allowTranslit);

  void Allow3dMode(bool allow3d, bool allow3dBuildings);
  static void Save3dMode(bool allow3d, bool allow3dBuildings);
  static void Load3dMode(bool & allow3d, bool & allow3dBuildings);

private:
  void ApplyMapLanguageCode(std::string const & langCode);

public:
  static std::string GetMapLanguageCode();
  void SetMapLanguageCode(std::string const & langCode);

  // Custom raster background tiles (user-provided XYZ {z}/{x}/{y} source). SetBackgroundTiles is the
  // single apply entry point for the settings UI (call it when the tiles settings are committed):
  // it persists all values (kept even while disabled) and applies them. cacheSizeMB and
  // areaOpacityPct are clamped to the limits below. areaOpacityPct is the opacity of vector area
  // fills drawn over the imagery (0 hides them). The layer renders only when enabled AND a non-empty
  // URL is set.
  static uint32_t constexpr kBackgroundTilesMinCacheSizeMB = 1;
  static uint32_t constexpr kBackgroundTilesMaxCacheSizeMB = 1000;
  static uint32_t constexpr kBackgroundTilesMinAreaOpacityPct = 0;
  static uint32_t constexpr kBackgroundTilesMaxAreaOpacityPct = 100;

  void SetBackgroundTiles(bool enabled, std::string url, uint32_t cacheSizeMB, uint32_t areaOpacityPct);
  // Flips only the on/off flag, keeping the configured URL / cache size / area opacity. Lighter than
  // SetBackgroundTiles: it just switches the rendered mode (creating the provider on first enable).
  void SetBackgroundTilesEnabled(bool enabled);
  static std::string GetBackgroundTilesURL();
  static bool IsBackgroundTilesEnabled();
  static uint32_t GetBackgroundTilesCacheSize();
  static uint32_t GetBackgroundTilesAreaOpacity();
  // Basic sanity check for a user-entered XYZ template: requires an http(s):// scheme, a non-empty host,
  // and all three {z}/{x}/{y} placeholders present literally (the braces must not be percent-encoded).
  // The settings UI calls this before committing and refuses to close on an enabled, malformed URL.
  static bool IsWellFormedBackgroundTilesURL(std::string const & url);

  void SetLargeFontsSize(bool isLargeSize);
  // Multiplied on top of the SetLargeFontsSize (Large Fonts) factor.
  void SetFontScaleFactor(double scaleFactor);
  bool LoadLargeFontsSize();

  bool LoadAutoZoom();
  void AllowAutoZoom(bool allowAutoZoom);
  void SaveAutoZoom(bool allowAutoZoom);

  static settings::Placement GetBookmarksTextPlacement();
  void SetBookmarksTextPlacement(settings::Placement setting);

  bool IsShowDownloadedRegions();
  void SetShowDownloadedRegions(bool isEnabled);

  TrafficManager & GetTrafficManager();

  TransitReadManager & GetTransitManager();

  IsolinesManager & GetIsolinesManager();
  IsolinesManager const & GetIsolinesManager() const;

  static bool LoadTrafficEnabled();
  static void SaveTrafficEnabled(bool trafficEnabled);

  static bool LoadTrafficSimplifiedColors();
  static void SaveTrafficSimplifiedColors(bool simplified);

  static bool LoadTransitSchemeEnabled();
  static void SaveTransitSchemeEnabled(bool enabled);

  static bool LoadIsolinesEnabled();
  static void SaveIsolinesEnabled(bool enabled);

  static bool LoadOutdoorsEnabled();
  static void SaveOutdoorsEnabled(bool enabled);

  static bool IsHikingEnabled();
  void SetHikingEnabled(bool enabled);

  static bool IsCyclingEnabled();
  void SetCyclingEnabled(bool enabled);

  static dp::ApiVersion LoadPreferredGraphicsAPI();
  static void SavePreferredGraphicsAPI(dp::ApiVersion apiVersion);

public:
  /// Routing Manager
  RoutingManager & GetRoutingManager() { return m_routingManager; }
  RoutingManager const & GetRoutingManager() const { return m_routingManager; }

protected:
  /// RoutingManager::Delegate
  void OnRouteFollow(routing::RouterType type) override;
  void InitRouting();

public:
  /// @returns false in case when coordinate is in the ocean or mwm is not downloaded.
  bool CanEditMapForPosition(m2::PointD const & position) const;

  bool CreateMapObject(m2::PointD const & mercator, uint32_t const featureType, osm::EditableMapObject & emo) const;
  /// @returns false if feature is invalid or can't be edited.
  bool GetEditableMapObject(FeatureID const & fid, osm::EditableMapObject & emo) const;
  osm::Editor::SaveResult SaveEditedMapObject(osm::EditableMapObject emo);
  void DeleteFeature(FeatureID const & fid);
  osm::NewFeatureCategories GetEditorCategories() const;
  bool RollBackChanges(FeatureID const & fid);
  void CreateNote(osm::EditableMapObject const & mapObject, osm::Editor::NoteProblemType const type,
                  std::string const & note);

private:
  settings::UsageStats m_usageStats;

  bool m_showDownloadedRegions = false;

public:
  power_management::PowerManager & GetPowerManager() { return m_powerManager; }

  // PowerManager::Subscriber override.
  void OnPowerFacilityChanged(power_management::Facility const facility, bool enabled) override;
  void OnPowerSchemeChanged(power_management::Scheme const actualScheme) override;

public:
  std::optional<products::ProductsConfig> GetProductsConfiguration() const;

  enum class ProductsPopupCloseReason
  {
    Close,
    SelectProduct,
    AlreadyDonated,
    RemindLater
  };

  void DidCloseProductsPopup(ProductsPopupCloseReason reason) const;
  void DidSelectProduct(products::ProductsConfig::Product const & product) const;

  bool ShouldShowProducts() const;
  static ProductsPopupCloseReason FromString(std::string_view str);

  bool CanShowRateUsRequest() const;
  void DidShowRateUsRequest() const;

  std::string GetDonateUrl() const;
  bool CanShowCrowdfundingPromo() const;
  void DidShowDonationPage() const;
  // Only for testing purposes.
  void ResetDonations();

private:
  static uint32_t GetTimeoutForReason(ProductsPopupCloseReason reason);
  static std::string_view ToString(ProductsPopupCloseReason reason);
};