#include "map/framework.hpp" #include "base/assert.hpp" #include "map/benchmark_tools.hpp" #include "map/gps_tracker.hpp" #include "map/place_page_info.hpp" #include "map/raster_tile_provider.hpp" #include "map/relation_track.hpp" #include "map/track_mark.hpp" #include "map/user_mark.hpp" #include "ge0/url_generator.hpp" #include "routing/route.hpp" #include "routing/speed_camera_prohibition.hpp" #include "search/editor_delegate.hpp" #include "search/engine.hpp" #include "search/locality_finder.hpp" #include "storage/country_info_getter.hpp" #include "storage/routing_helpers.hpp" #include "storage/storage.hpp" #include "storage/storage_helpers.hpp" #include "drape_frontend/color_constants.hpp" #include "drape_frontend/gps_track_point.hpp" #include "drape_frontend/relations_draw_info.hpp" #include "drape_frontend/tile_key.hpp" #include "drape_frontend/visual_params.hpp" #include "drape/drape_global.hpp" #include "descriptions/loader.hpp" #include "indexer/categories_holder.hpp" #include "indexer/classificator.hpp" #include "indexer/classificator_loader.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/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 "base/logging.hpp" #include "base/math.hpp" #include "base/string_utils.hpp" #include "std/target_os.hpp" #include using namespace location; using namespace routing; using namespace storage; using namespace std::placeholders; 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 { std::string_view constexpr kMapStyleKey = "MapStyleKeyV1"; std::string_view constexpr kBgTilesEnabledKey = "BgTilesEnabled"; // custom raster tiles layer on/off std::string_view constexpr kBgTilesUrlKey = "BgTilesUrl"; // custom raster tiles URL template std::string_view constexpr kBgTilesCacheSizeMBKey = "BgTilesCacheMB"; // custom raster tiles disk cache cap std::string_view constexpr kBgTilesAreaOpacityKey = "BgTilesAreaOpacity"; // area-fill opacity over satellite tiles, % uint32_t constexpr kDefaultBgTilesCacheSizeMB = 50; uint32_t constexpr kDefaultBgTilesAreaOpacityPct = 50; // half-transparent area fills by default in Satellite mode std::string_view constexpr kAllow3dKey = "Allow3d"; std::string_view constexpr kAllow3dBuildingsKey = "Buildings3d"; std::string_view constexpr kAllowAutoZoom = "AutoZoom"; std::string_view constexpr kTrafficEnabledKey = "TrafficEnabled"; std::string_view constexpr kTransitSchemeEnabledKey = "TransitSchemeEnabled"; std::string_view constexpr kIsolinesEnabledKey = "IsolinesEnabled"; std::string_view constexpr kOutdoorsEnabledKey = "OutdoorsEnabled"; std::string_view constexpr kTrafficSimplifiedColorsKey = "TrafficSimplifiedColors"; std::string_view constexpr kLargeFontsSize = "LargeFontsSize"; std::string_view constexpr kTranslitMode = "TransliterationMode"; std::string_view constexpr kPreferredGraphicsAPI = "PreferredGraphicsAPI"; std::string_view constexpr kShowDebugInfo = "DebugInfo"; std::string_view constexpr kShowDownloadedRegions = "DownloadedRegions"; std::string_view constexpr kScreenViewport = "ScreenClipRect"; std::string_view constexpr kPlacePageProductsPopupCloseTime = "PlacePageProductsPopupCloseTime"; std::string_view constexpr kPlacePageProductsPopupCloseReason = "PlacePageProductsPopupCloseReason"; std::string_view constexpr kPlacePageSelectedProduct = "PlacePageSelectedProduct"; std::string_view constexpr kProductsPopupCloseReasonCloseStr = "close"; std::string_view constexpr kProductsPopupCloseReasonRemindLaterStr = "remind_later"; std::string_view constexpr kProductsPopupCloseReasonAlreadyDonatedStr = "already_donated"; std::string_view constexpr kProductsPopupCloseReasonSelectProductStr = "select_product"; std::string_view constexpr kFirstAskedForRateUsTimeKey = "FirstAskedForRateUsTime"; std::string_view constexpr kLastAskedForRateUsTimeKey = "LastAskedForRateUsTime"; std::string_view constexpr kDonationTapTimeKey = "DonationTapTime"; std::string_view constexpr kDonationTapCountKey = "DonationTapCount"; // The gift box is shown from 00:00 UTC of the start date until 00:00 UTC of the end date, // i.e. the end date is the first day without it. Update both dates to run the next campaign. auto const kCrowdfundingStartTime = base::YYMMDDToSecondsSinceEpoch(251220); auto const kCrowdfundingEndTime = base::YYMMDDToSecondsSinceEpoch(260120); auto constexpr kLargeFontsScaleFactor = 1.6; size_t constexpr kMaxTrafficCacheSizeBytes = 64 /* Mb */ * 1024 * 1024; // 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(std::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 == std::string::npos) return false; std::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; } void EmitDebugCommandResult(search::SearchParams const & params, std::string const & message) { if (!params.m_onResults) return; search::Results results; results.AddResultNoChecks(search::Result(message, std::string(params.m_query))); params.m_onResults(results); results.SetEndMarker(false /* isCancelled */); params.m_onResults(results); } void UpdateTrackSelectionColor(dp::Color & color) { if (color == feature::RouteRelationBase::kEmptyColor) color = dp::Color::Purple(); // Default purple. // Adjust colors to the current theme for readability. bool const isLightTheme = !MapStyleIsDark(GetStyleReader().GetCurrentStyle()); dp::HSL hsl = dp::Color2HSL(color); if (hsl.AdjustLightness(isLightTheme)) color = dp::HSL2Color(hsl); } bool HasHigherTrackSelectionPriority(Track::TrackSelectionInfo const & lhs, Track::TrackSelectionInfo const & rhs) { if (lhs.IsRelation() != rhs.IsRelation()) return !lhs.IsRelation(); // non-relation tracks has higher priority return lhs.m_squareDist < rhs.m_squareDist; } } // namespace std::pair 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, std::vector const & features) { return m_featuresFetcher.ReadFeatures(fn, features); }, std::bind(&Framework::GetMwmsByRect, this, _1, false /* rough */)) , m_isolinesManager(m_featuresFetcher.GetDataSource(), std::bind(&Framework::GetMwmsByRect, this, _1, false /* rough */)) , m_routingManager(RoutingManager::Callbacks([this]() -> DataSource & { return m_featuresFetcher.GetDataSource(); }, [this]() -> storage::CountryInfoGetter const & { return GetCountryInfoGetter(); }, [this](std::string const & id) -> std::string { return m_storage.GetParentIdFor(id); }, [this]() -> StringsBundle const & { return m_stringsBundle; }, [this]() -> power_management::PowerManager const & { return m_powerManager; }), static_cast(*this)) , m_trafficManager(std::bind(&Framework::GetMwmsByRect, this, _1, false /* rough */), kMaxTrafficCacheSizeBytes, m_routingManager.RoutingSession()) , m_lastReportedCountry(kInvalidCountryId) , m_descriptionsLoader(std::make_unique(m_featuresFetcher.GetDataSource())) , m_selectionProcessor(*this) { // 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; std::string mapStyleStr; if (settings::Get(kMapStyleKey, mapStyleStr)) mapStyle = MapStyleFromSettings(mapStyleStr); GetStyleReader().SetCurrentStyle(mapStyle); df::LoadTransitColors(); // 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", "Map Point"); 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(std::bind(&Framework::OnMapDeregistered, this, _1)); LOG(LDEBUG, ("Classificator initialized")); m_displayedCategories = std::make_unique(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 = std::make_unique(BookmarkManager::Callbacks( [this]() -> StringsBundle const & { return m_stringsBundle; }, [this]() -> SearchAPI & { return GetSearchAPI(); }, [this](std::vector const & marks) { GetSearchAPI().OnBookmarksCreated(marks); }, [this](std::vector const & marks) { GetSearchAPI().OnBookmarksUpdated(marks); }, [this](std::vector const & marks) { GetSearchAPI().OnBookmarksDeleted(marks); }, [this](std::vector const & marks) { GetSearchAPI().OnBookmarksAttached(marks); }, [this](std::vector 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(std::bind(&Framework::OnCountryFileDownloaded, this, _1, _2), std::bind(&Framework::OnCountryFileDelete, this, _1, _2)); m_storage.SetDownloadingPolicy(&m_storageDownloadingPolicy); m_storage.SetStartDownloadingCallback([this]() { // Don't call UpdatePlacePageInfoForCurrentSelection -> BuildPlacePageInfo, just need to update UI. if (m_currentPlacePageInfo && m_onPlacePageUpdate) m_onPlacePageUpdate(); }); UpdateMinBuildingsTapZoom(); LOG(LINFO, ("System languages:", languages::GetPreferred())); editor.SetDelegate(std::make_unique(m_featuresFetcher.GetDataSource())); editor.SetInvalidateFn([this]() { Invalidate(); }); /// @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(); if (m_infoGetter->HasRegionTriangles()) { m_showDownloadedRegions = true; UNUSED_VALUE(settings::Get(kShowDownloadedRegions, m_showDownloadedRegions)); } } 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); /// @todo A bit controversial, why clear when adding a new map :) 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_descriptionsLoader->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")); InitRouting(); GetStorage().RestoreDownloadQueue(); } // Small copy-paste with LoadMapsSync, but I don't have a better solution. void Framework::LoadMapsAsync(std::function && callback) { threads::SimpleThread([this, callback = std::move(callback)]() { 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")); GetPlatform().RunTask(Platform::Thread::Gui, [this, callback = std::move(callback)]() { /// @todo Investigate if we can call it async after "Editor initialized". InitRouting(); callback(); }); LOG(LINFO, ("Finished async loading")); }).detach(); } void Framework::RegisterAllMaps() { m_storage.RegisterAllLocalMaps(m_enabledDiffs); std::vector> maps; m_storage.GetLocalMaps(maps); for (auto const & localFile : maps) { if (RegisterMap(*localFile).second != MwmSet::RegResult::Success) { /// @todo Should call something like Storage::DeleteCountryFiles (DeleteCustomCountryVersion ??). /// Storage::DeleteCountry makes ->Framework callbacks, but Framework <-> Storage /// logic is tangled-complicated enough to realize. // Otherwise we have blank map view instead of countries, without Download button. } } } void Framework::DeregisterAllMaps() { m_transitManager.Clear(); m_isolinesManager.Clear(); m_trafficManager.Clear(); m_descriptionsLoader->Clear(); GetSearchAPI().ClearCaches(); m_featuresFetcher.Clear(); m_storage.Clear(); } void Framework::LoadBookmarks() { GetBookmarkManager().LoadBookmarks(); } kml::MarkGroupId Framework::AddCategory(std::string const & categoryName) { return GetBookmarkManager().CreateBookmarkCategory(categoryName); } void Framework::FillPointInfoForBookmark(Bookmark const & bmk, place_page::Info & info) const { feature::TypesHolder bmTypes; auto const & srcTypes = bmk.GetData().m_featureTypes; for (size_t i = 0; i < std::min(feature::kMaxTypesCount, srcTypes.size()); ++i) bmTypes.Add(srcTypes[i]); bmTypes.SortToCompare(); GetSelectionProcessor().FillPointInfo(info, bmk.GetPivot(), {} /* customTitle */, [&bmTypes](FeatureType & ft) { if (bmTypes.Empty()) return false; feature::TypesHolder fTypes(ft); fTypes.SortToCompare(); return bmTypes.EqualUsefulSorted(fTypes); }); } bool Framework::FillUserMarkInfo(UserMark const * mark, place_page::Info & outInfo) { outInfo.SetSelectedObject(df::SelectionShape::OBJECT_USER_MARK); switch (mark->GetMarkType()) { case UserMark::Type::API: FillApiMarkInfo(*static_cast(mark), outInfo); break; case UserMark::Type::BOOKMARK: FillBookmarkInfo(*static_cast(mark), outInfo); break; case UserMark::Type::SEARCH: FillSearchResultInfo(*static_cast(mark), outInfo); break; case UserMark::Type::ROUTING: FillRouteMarkInfo(*static_cast(mark), outInfo); break; case UserMark::Type::ROAD_WARNING: FillRoadTypeMarkInfo(*static_cast(mark), outInfo); break; case UserMark::Type::TRACK_INFO: { auto const & infoMark = *static_cast(mark); return BuildTrackPlacePage(GetBookmarkManager().GetTrackSelectionInfo(infoMark.GetTrackId()), outInfo); } case UserMark::Type::TRACK_SELECTION: { auto const & selMark = *static_cast(mark); return BuildTrackPlacePage(GetBookmarkManager().GetTrackSelectionInfo(selMark.GetTrackId()), outInfo); } case UserMark::Type::TRANSIT: { FillTransitMarkInfo(*static_cast(mark), outInfo); break; } case UserMark::Type::SPEED_CAM: { FillSpeedCameraMarkInfo(*static_cast(mark), outInfo); break; } default: CHECK(false, ("Unexpected user mark type", mark->GetMarkType())); } GetSelectionProcessor().SetPlacePageLocation(outInfo); return true; } 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, Track::TrackSelectionInfo const & trackSelectionInfo, place_page::Info & info) const { info.SetTrackId(track.GetId()); info.SetTrackRelationId(trackSelectionInfo.m_relationId); auto const groupId = track.GetGroupId(); info.SetBookmarkCategoryId(groupId); if (groupId != kml::kInvalidMarkGroupId) info.SetBookmarkCategoryName(GetBookmarkManager().GetCategoryName(groupId)); info.SetMercator(trackSelectionInfo.m_trackPoint); info.SetTitlesForTrack(track); } search::ReverseGeocoder::Address Framework::GetAddressAtPoint(m2::PointD const & pt) const { search::ReverseGeocoder const coder(m_featuresFetcher.GetDataSource()); search::ReverseGeocoder::Address addr; coder.GetNearbyAddress(pt, 0.5 /* maxDistanceM */, addr, true /* placeAsStreet */); return addr; } std::vector Framework::FindRelationTracksInTapPosition( std::vector> const & lineCandidates, m2::PointD const & mercator) { std::vector candidates; df::RelationsDrawSettings sett; sett.Load(); if (sett.IsEmpty()) return candidates; for (auto const & [_, fid] : lineCandidates) { if (!fid.IsValid()) continue; // No problem with multiple instances here - ctor is fast. auto const currSize = candidates.size(); RelationTrackBuilder builder(m_featuresFetcher.GetDataSource(), fid, m_infoGetter.get()); builder.ForEachMetadata([&](RelationTrackBuilder::Metadata && metadata) { // Filter duplicates from previous lineCandidates Features. for (size_t i = 0; i < currSize; ++i) if (metadata.m_relationId == candidates[i].m_relationId) return; Track::TrackSelectionInfo trackSelInfo; trackSelInfo.m_trackId = kml::kTempRelationTrackId; trackSelInfo.m_trackPoint = mercator; trackSelInfo.m_relationId = std::move(metadata.m_relationId); trackSelInfo.m_title = std::move(metadata.m_name); trackSelInfo.m_color = metadata.m_color; UpdateTrackSelectionColor(trackSelInfo.m_color); ASSERT(trackSelInfo.IsValid(), ()); candidates.push_back(std::move(trackSelInfo)); }, sett); } return candidates; } std::optional Framework::TryBuildRelationTrack(Track::TrackSelectionInfo const & trackSelectionInfo) { auto const relationId = trackSelectionInfo.m_relationId; CHECK(trackSelectionInfo.IsRelation(), ()); RelationTrackBuilder builder(m_featuresFetcher.GetDataSource(), trackSelectionInfo.m_relationId, m_infoGetter.get()); auto trackData = builder.Build(relationId); if (!trackData) { LOG(LERROR, ("Failed to build relation track data for relationId", relationId)); return std::nullopt; } kml::TrackData kmlTrack; for (auto & line : trackData->m_lines) { kmlTrack.m_geometry.m_lines.push_back(std::move(line.m_points)); kmlTrack.m_geometry.m_timestamps.emplace_back(); } kml::SetDefaultStr(kmlTrack.m_name, std::move(trackData->m_name)); kml::TrackLayer layer; UpdateTrackSelectionColor(trackData->m_color); layer.m_color.m_rgba = trackData->m_color.GetRGBA(); kmlTrack.m_layers.push_back(layer); kmlTrack.m_id = kml::kTempRelationTrackId; return kmlTrack; } void Framework::FillApiMarkInfo(ApiMarkPoint const & api, place_page::Info & info) const { GetSelectionProcessor().FillPointInfo(info, api.GetPivot()); std::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()) GetSelectionProcessor().FillFeatureInfo(smp.GetFeatureID(), info); else GetSelectionProcessor().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")); info.SetCanEditOrAdd(GetSelectionProcessor().CanEditMapForPosition(*position)); UserMark const * mark = FindUserMarkInTapPosition(buildInfo); if (mark != nullptr && mark->GetMarkType() == UserMark::Type::ROUTING) { auto routingMark = static_cast(mark); info.SetIsRoutePoint(); info.SetRouteMarkType(routingMark->GetRoutePointType()); info.SetIntermediateIndex(routingMark->GetIntermediateIndex()); } } void Framework::FillRouteMarkInfo(RouteMarkPoint const & rmp, place_page::Info & info) const { GetSelectionProcessor().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 { GetSelectionProcessor().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) { GetSelectionProcessor().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); if (mark) ShowBookmark(mark); else ASSERT(false, ("ShowBookmark was called with invalid id", id)); } void Framework::ShowBookmark(Bookmark const * mark) { StopLocationFollow(); place_page::BuildInfo info; info.m_mercator = mark->GetPivot(); info.m_userMarkId = mark->GetId(); m_currentPlacePageInfo = BuildPlacePageInfo(info); auto scale = static_cast(mark->GetScale()); if (scale == 0) scale = scales::GetUpperComfortScale(); auto es = GetBookmarkManager().GetEditSession(); es.SetIsVisible(mark->GetGroupId(), true /* visible */); SetViewportCenter(mark->GetPivot(), scale, true /* isAnim */, true /* trackVisibleViewport */); ActivateMapSelection(); } void Framework::ShowTrack(kml::TrackId trackId) { auto & bm = GetBookmarkManager(); auto const track = bm.GetTrack(trackId); StopLocationFollow(); auto rect = track->GetLimitRect(); ExpandRectForPreview(rect); place_page::BuildInfo info; info.m_trackId = trackId; info.m_mercator = rect.Center(); m_currentPlacePageInfo = BuildPlacePageInfo(info); auto es = bm.GetEditSession(); es.SetIsVisible(track->GetGroupId(), true /* visible */); // Also unhide the individual track so imported tracks with m_visible=false // become visible when navigated to from the bookmark list. es.SetTrackVisibility(trackId, true /* visible */); ShowRect(rect, true /* isAnim */, true /* useVisibleViewport */); ActivateMapSelection(); } void Framework::SetTrackVisibility(kml::TrackId trackId, bool visible) { { auto es = GetBookmarkManager().GetEditSession(); es.SetTrackVisibility(trackId, visible); } // Hiding the track shown in the Place Page must reset the selection so nothing // stays selected on an invisible track. if (!visible && m_currentPlacePageInfo && m_currentPlacePageInfo->GetTrackId() == trackId) DeactivateMapSelection(); } void Framework::DeleteTrack(kml::TrackId trackId) { // Close the Place Page first (while the track still exists) so nothing stays selected on a // deleted track; otherwise the selection would be rebuilt for a track that is already gone. if (m_currentPlacePageInfo && m_currentPlacePageInfo->GetTrackId() == trackId) DeactivateMapSelection(); GetBookmarkManager().GetEditSession().DeleteTrack(trackId); } void Framework::DeleteBookmarksAndTracks(kml::MarkIdCollection const & bookmarkIds, kml::TrackIdCollection const & trackIds) { // Same reason as in DeleteTrack(), extended to bookmarks: a batch deletion has no undo, so a Place Page left // on one of its items could not be restored. The invalid ids a non-bookmark/non-track selection reports are // never in the collections. if (m_currentPlacePageInfo && (base::IsExist(bookmarkIds, m_currentPlacePageInfo->GetBookmarkId()) || base::IsExist(trackIds, m_currentPlacePageInfo->GetTrackId()))) DeactivateMapSelection(); GetBookmarkManager().GetEditSession().DeleteBookmarksAndTracks(bookmarkIds, trackIds); } void Framework::SelectTrackCandidate(kml::TrackId trackId, RelationID const & relationId) { CHECK(m_currentPlacePageInfo, ()); auto const & candidates = m_currentPlacePageInfo->GetTrackCandidates(); auto const isRelationTrack = trackId == kml::kTempRelationTrackId; auto const candidate = std::find_if(candidates.begin(), candidates.end(), [&trackId, &relationId, isRelationTrack](auto const & candidate) { return isRelationTrack ? candidate.m_relationId == relationId : candidate.m_trackId == trackId; }); CHECK(candidate != candidates.end(), ()); CHECK(candidate->IsValid(), ()); if (!BuildTrackPlacePage(*candidate, m_currentPlacePageInfo.value())) return; GetBookmarkManager().UpdateElevationMyPosition(trackId, true /* ignoreLocationCache */); ActivateMapSelection(); } 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, animation); auto es = bm.GetEditSession(); es.SetIsVisible(categoryId, true /* visible */); } 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(std::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(kScreenViewport, rect); } void Framework::LoadViewport() { m2::AnyRectD rect; if (settings::Get(kScreenViewport, 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) 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, bool animation, bool useVisibleViewport) { if (m_drapeEngine) m_drapeEngine->SetModelViewRect(rect, true /* applyRotation */, -1 /* zoom */, animation, useVisibleViewport); } void Framework::ShowRect(m2::AnyRectD const & rect, bool animation, bool useVisibleViewport) { if (m_drapeEngine) m_drapeEngine->SetModelViewAnyRect(rect, animation, useVisibleViewport); } void Framework::SetViewportListener(TViewportChangedFn const & fn) { m_viewportChangedFn = fn; } #if defined(OMIM_OS_DESKTOP) void Framework::NotifyGraphicsReady(TGraphicsReadyFn const & fn, bool needInvalidate) { if (m_drapeEngine != nullptr) m_drapeEngine->NotifyGraphicsReady(fn, needInvalidate); } #endif void Framework::StopLocationFollow() { if (m_drapeEngine != nullptr) m_drapeEngine->StopLocationFollow(); } void Framework::OnSize(int w, int h) { if (m_drapeEngine != nullptr) m_drapeEngine->Resize(std::max(w, 2), std::max(h, 2)); /// @todo Expected that DrapeEngine::Resize does all the work, but nope .. /// - Strange, but seems like iOS works fine without it. /// - Test Android screen orientation and position mark in map and navigation modes. SetVisibleViewport(m2::RectD(0, 0, w, h)); } namespace { double ScaleModeToFactor(Framework::EScaleMode mode) { switch (mode) { using enum Framework::EScaleMode; case SCALE_MAG: return 2.0; case SCALE_MAG_LIGHT: return 1.5; case SCALE_MIN: return 0.5; case SCALE_MIN_LIGHT: return 0.67; } UNREACHABLE(); } } // namespace void Framework::Scale(EScaleMode mode, bool isAnim) { Scale(ScaleModeToFactor(mode), isAnim); } void Framework::Scale(Framework::EScaleMode mode, m2::PointD const & pxPoint, bool isAnim) { Scale(ScaleModeToFactor(mode), pxPoint, isAnim); } void Framework::Scale(double factor, bool isAnim) { Scale(factor, GetVisiblePixelCenter(), isAnim); } void Framework::Scale(double factor, m2::PointD const & pxPoint, bool isAnim) { if (m_drapeEngine != nullptr) m_drapeEngine->Scale(factor, pxPoint, isAnim); } void Framework::Move(double factorX, double factorY, bool isAnim) { if (m_drapeEngine != nullptr) m_drapeEngine->Move(factorX, factorY, isAnim); } void Framework::Scroll(double distanceX, double distanceY) { if (m_drapeEngine != nullptr) m_drapeEngine->Scroll(distanceX, distanceY); } void Framework::Rotate(double azimuth, bool isAnim) { if (m_drapeEngine != nullptr) m_drapeEngine->Rotate(azimuth, isAnim); } void Framework::TouchEvent(df::TouchEvent const & touch) { if (m_drapeEngine != nullptr) m_drapeEngine->AddTouchEvent(touch); } void Framework::MakeFrameActive() { if (m_drapeEngine != nullptr) m_drapeEngine->MakeFrameActive(); } int Framework::GetDrawScale() const { if (m_drapeEngine != nullptr) return df::GetDrawTileScale(m_currentModelView); return 0; } void Framework::RunFirstLaunchAnimation() { if (m_drapeEngine != nullptr) m_drapeEngine->RunFirstLaunchAnimation(); } bool Framework::IsCountryLoadedByName(std::string_view name) const { return m_featuresFetcher.IsLoaded(name); } void Framework::InvalidateRect(m2::RectD const & rect) { if (m_drapeEngine != nullptr) m_drapeEngine->InvalidateRect(rect); } void Framework::ClearAllCaches() { m_featuresFetcher.ClearCaches(); m_infoGetter->ClearCaches(); GetSearchAPI().ClearCaches(); } void Framework::OnUpdateCurrentCountry(m2::PointD const & pt, int zoomLevel) { storage::CountryId newCountryId = kInvalidCountryId; if (zoomLevel > scales::GetUpperWorldScale()) newCountryId = m_infoGetter->GetRegionCountryId(pt); if (newCountryId == m_lastReportedCountry) return; m_lastReportedCountry = newCountryId; /// @todo Looks logical to add if (m_currentCountryChanged) before RunTask, /// but possible races with read/write of m_currentCountryChanged. GetPlatform().RunTask(Platform::Thread::Gui, [this, newCountryId]() { if (m_currentCountryChanged) m_currentCountryChanged(newCountryId); }); } void Framework::SetCurrentCountryChangedListener(TCurrentCountryChanged listener) { m_currentCountryChanged = std::move(listener); m_lastReportedCountry = kInvalidCountryId; } void Framework::MemoryWarning() { LOG(LINFO, ("MemoryWarning")); ClearAllCaches(); SharedBufferManager::Instance().ClearReserved(); } void Framework::EnterBackground() { m_usageStats.EnterBackground(); if (m_drapeEngine) m_drapeEngine->OnEnterBackground(); SaveViewport(); m_trafficManager.OnEnterBackground(); ClearAllCaches(); } void Framework::EnterForeground() { m_usageStats.EnterForeground(); if (m_drapeEngine) m_drapeEngine->OnEnterForeground(); m_trafficManager.OnEnterForeground(); } void Framework::InitCountryInfoGetter() { ASSERT(!m_infoGetter, ()); auto const & platform = GetPlatform(); m_infoGetter = CountryInfoReader::CreateCountryInfoReader(platform); // Storage::GetAffiliations() pointer never changed. m_infoGetter->SetAffiliations(m_storage.GetAffiliations()); } void Framework::InitSearchAPI(size_t numThreads) { ASSERT(!m_searchAPI, ()); ASSERT(m_infoGetter, ()); try { m_searchAPI = std::make_unique(m_featuresFetcher.GetDataSource(), m_storage, *m_infoGetter, numThreads, static_cast(*this)); } catch (RootException const & e) { LOG(LCRITICAL, ("Can't load needed resources for SearchAPI:", e.Msg())); } } void Framework::InitTransliteration() { InitTransliterationInstanceWithDefaultDirs(); if (!LoadTransliteration()) Transliteration::Instance().SetMode(Transliteration::Mode::Disabled); } int64_t Framework::GetMwmVersion(m2::PointD const & pt) const { auto name = m_infoGetter->GetRegionCountryId(pt); return IsCountryIdValid(name) ? m_featuresFetcher.GetMwmVersion(std::move(name)) : 0; } bool Framework::NeedUpdateForRoutes() const { auto const version = GetMwmVersion(GetViewportCenter()); return version > 0 && version < 250801; } /* Framework::DoAfterUpdate Framework::ToDoAfterUpdate() const { auto const connectionStatus = Platform::ConnectionStatus(); if (connectionStatus == Platform::EConnectionType::CONNECTION_NONE) return DoAfterUpdate::Nothing; auto const & s = GetStorage(); auto const & rootId = s.GetRootId(); if (!IsEnoughSpaceForUpdate(rootId, s)) return DoAfterUpdate::Nothing; NodeAttrs attrs; s.GetNodeAttrs(rootId, attrs); MwmSize const countrySizeInBytes = attrs.m_localMwmSize; if (countrySizeInBytes == 0 || attrs.m_status != NodeStatus::OnDiskOutOfDate) return DoAfterUpdate::Nothing; if (s.IsPossibleToAutoupdate() && connectionStatus == Platform::EConnectionType::CONNECTION_WIFI) return DoAfterUpdate::AutoupdateMaps; return DoAfterUpdate::AskForUpdateMaps; } */ SearchAPI & Framework::GetSearchAPI() { ASSERT(m_searchAPI, ()); return *m_searchAPI; } search::DisplayedCategories const & Framework::GetDisplayedCategories() { ASSERT(m_displayedCategories, ()); return *m_displayedCategories; } void Framework::SelectSearchResult(search::Result const & result, bool animation) { using namespace search; place_page::BuildInfo info; info.m_source = place_page::BuildInfo::Source::Search; info.m_needAnimationOnSelection = false; int scale = -1; switch (result.GetResultType()) { case Result::Type::Feature: info.m_mercator = result.GetFeatureCenter(); info.m_match = place_page::BuildInfo::Match::Nothing; info.m_featureId = result.GetFeatureID(); info.m_isGeometrySelectionAllowed = true; break; case Result::Type::LatLon: info.m_mercator = result.GetFeatureCenter(); info.m_match = place_page::BuildInfo::Match::Nothing; scale = scales::GetUpperComfortScale(); break; case Result::Type::Postcode: info.m_mercator = result.GetFeatureCenter(); info.m_match = place_page::BuildInfo::Match::Nothing; scale = scales::GetUpperComfortScale(); break; case Result::Type::SuggestFromFeature: case Result::Type::PureSuggest: m_currentPlacePageInfo = {}; ASSERT(false, ("Suggests should not be here.")); return; } m_currentPlacePageInfo = BuildPlacePageInfo(info); if (result.GetResultType() == Result::Type::Postcode) m_currentPlacePageInfo->SetCustomNames(result.GetString(), m_stringsBundle.GetString("postal_code")); if (m_drapeEngine) { if (scale < 0) scale = GetFeatureViewportScale(m_currentPlacePageInfo->GetID(), m_currentPlacePageInfo->GetTypes()); m2::PointD const center = m_currentPlacePageInfo->GetMercator(); m_drapeEngine->SetModelViewCenter(center, scale, animation, true /* trackVisibleViewport */); } ActivateMapSelection(); } void Framework::ShowSearchResult(search::Result const & res, bool animation) { GetSearchAPI().CancelAllSearches(); StopLocationFollow(); SelectSearchResult(res, animation); } void Framework::SelectRoute(uint32_t relID) { if (!m_drapeEngine || !HasPlacePageInfo()) return; auto const & fid = m_currentPlacePageInfo->GetID(); if (!fid.IsValid()) return; RelationTrackBuilder builder(m_featuresFetcher.GetDataSource(), fid); auto info = builder.BuildSelectionInfo(relID); if (!info) return; UpdateTrackSelectionColor(info->m_color); m_drapeEngine->SetSelectionLines(std::move(*info)); } void Framework::ShowRouteTransit(uint32_t relID) { if (!m_drapeEngine || !HasPlacePageInfo()) return; auto const & fid = m_currentPlacePageInfo->GetID(); if (!fid.IsValid()) return; RelationTrackBuilder builder(m_featuresFetcher.GetDataSource(), fid, m_infoGetter.get()); auto info = builder.BuildTransitInfo(relID); if (!info) return; if (!m_routeTransitSelection || m_routeTransitSelection->m_featureId != fid) { if (m_currentModelView.isPerspective()) m_currentModelView.ResetPerspective(); m_routeTransitSelection.emplace(fid, relID); } else m_routeTransitSelection->m_relID = relID; // Fit the viewport to the route before pushing data — same UX as the old selection-line path. m2::RectD bbox; for (auto const & route : info->m_routes) for (auto const & p : route.m_polyline) bbox.Add(p); for (auto const & stop : info->m_stops) bbox.Add(stop.m_pos); if (bbox.IsValid()) { bbox.Scale(1.2); /// @todo Set for RouteRelationBase::Type::Train only, keep default otherwise? int const zoom = df::GetDrawTileScale(bbox); if (zoom < df::kTransitSchemeMinZoomLevel) info->m_minZoomLevel = std::max(df::kTransitSchemeMinZoomFloor, zoom); ShowRect(bbox, true /* animation */, true /* useVisibleViewport */); } UpdateTrackSelectionColor(info->m_color); m_drapeEngine->EnableTransitScheme(true); m_drapeEngine->ShowRouteTransit(std::move(*info)); } std::string Framework::GetActiveTransitRouteRef() const { if (!m_routeTransitSelection || !HasPlacePageInfo()) return {}; uint32_t const relID = m_routeTransitSelection->m_relID; for (auto const & r : GetCurrentPlacePageInfo().GetRoutes()) if (r.m_relID == relID) return r.m_ref; return {}; } void Framework::HideRouteTransitIfNeeded() { if (!m_routeTransitSelection) return; m_routeTransitSelection = {}; if (!m_drapeEngine) return; m_drapeEngine->HideRouteTransit(); // Keep the user's subway/transit-scheme layer visible after previewing a route. The layer // returns on its own: the render gate stays enabled and the real-MwmId scheme data was never // wiped (the route lives under the sentinel MwmId{}), so the frontend re-collects the scheme // overlays once the route data is gone. Disabling here would clear the builder instead; // Invalidate() is only a safety refresh in case the viewport's MWMs changed during the preview. if (m_transitManager.IsSchemeMode()) m_transitManager.Invalidate(); else m_drapeEngine->EnableTransitScheme(false); } void Framework::UpdateViewport(search::Results const & results) { // Setup viewport according to results. m2::AnyRectD viewport = m_currentModelView.GlobalRect(); m2::PointD const center = viewport.Center(); double minDistance = std::numeric_limits::max(); search::Result const * res = nullptr; for (auto const & r : results) { if (r.HasPoint()) { double const dist = center.SquaredLength(r.GetFeatureCenter()); if (dist < minDistance) { minDistance = dist; res = &r; } } } if (res) { m2::PointD const pt = res->GetFeatureCenter(); if (!viewport.IsPointInside(pt)) { viewport.SetSizesToIncludePoint(pt); double constexpr factor = 0.05; viewport.Inflate(viewport.GetLocalRect().SizeX() * factor, viewport.GetLocalRect().SizeY() * factor); StopLocationFollow(); ShowRect(viewport); } } } void Framework::FillSearchResultsMarks(bool clear, search::Results const & results) { FillSearchResultsMarks(results.begin(), results.end(), clear); } void Framework::FillSearchResultsMarks(SearchResultsIterT beg, SearchResultsIterT end, bool clear) { auto editSession = GetBookmarkManager().GetEditSession(); if (clear) editSession.ClearGroup(UserMark::Type::SEARCH); editSession.SetIsVisible(UserMark::Type::SEARCH, true); for (auto it = beg; it != end; ++it) { auto const & r = *it; if (!r.HasPoint()) continue; auto * mark = editSession.CreateUserMark(r.GetFeatureCenter()); mark->SetMatchedName(r.GetString()); if (r.GetResultType() == search::Result::Type::Feature) { auto const fID = r.GetFeatureID(); mark->SetFoundFeature(fID); mark->SetFromType(r.GetFeatureType()); mark->SetVisited(m_searchMarks.IsVisited(fID)); mark->SetSelected(m_searchMarks.IsSelected(fID)); } } } bool Framework::GetDistanceAndAzimut(m2::PointD const & point, double lat, double lon, double north, platform::Distance & distance, double & azimut) { #ifdef FIXED_LOCATION m_fixedPos.GetLat(lat); m_fixedPos.GetLon(lon); m_fixedPos.GetNorth(north); #endif double const d = ms::DistanceOnEarth(lat, lon, mercator::YToLat(point.y), mercator::XToLon(point.x)); // Distance may be less than 1.0 distance = platform::Distance::CreateFormatted(d); // We calculate azimuth even when distance is very short (d ~ 0), // because return value has 2 states (near me or far from me). azimut = ang::Azimuth(mercator::FromLatLon(lat, lon), point, north); double const pi2 = 2.0 * math::pi; if (azimut < 0.0) azimut += pi2; else if (azimut > pi2) azimut -= pi2; // This constant and return value is using for arrow/flag choice. return (d < 25000.0); } m2::PointD Framework::PtoG(m2::PointD const & p) const { auto pt = m_currentModelView.PtoG(p); pt.x = mercator::WrapX(pt.x); return pt; } m2::PointD Framework::P3dtoG(m2::PointD const & p) const { auto pt = m_currentModelView.PtoG(m_currentModelView.P3dtoP(p)); pt.x = mercator::WrapX(pt.x); return pt; } void Framework::CreateDrapeEngine(ref_ptr contextFactory, DrapeCreationParams && params) { auto idReadFn = [this](auto const & fn, m2::RectD const & r, int scale) { m_featuresFetcher.ForEachFeatureID(r, fn, scale); if (m_showDownloadedRegions && scale <= 7) { auto names = m_featuresFetcher.GetDataSource().GetLoadedCountryNames(r); ASSERT(base::IsSortedAndUnique(names), ()); m_infoGetter->ForEachRegionId(names, [&fn](size_t id) { fn(FeatureID({}, id)); }); } }; uint32_t const borderType = classif().GetTypeByPath({"organicapp", "mwm_border"}); auto featureReadFn = [this, borderType](auto const & fn, std::vector const & ids) { m_featuresFetcher.ReadFeatures(fn, ids); for (auto const & id : ids) if (id.m_mwmId.IsNull()) { FeatureType ft(id, borderType); m_infoGetter->GetTriangles(id.m_index, ft); fn(ft); } else break; }; // Custom raster background tiles come from a user-configured XYZ source (Settings -> Map tiles), // persisted via kBgTilesEnabledKey / kBgTilesUrlKey / kBgTilesCacheSizeMBKey. The layer is active // only when enabled AND a URL is set. std::string bgTilesUrl; settings::TryGet(kBgTilesUrlKey, bgTilesUrl); bool bgTilesEnabled = false; settings::TryGet(kBgTilesEnabledKey, bgTilesEnabled); bool const bgTilesActive = bgTilesEnabled && !bgTilesUrl.empty(); if (bgTilesActive && !m_rasterTileProvider) CreateBackgroundTilesProvider(bgTilesUrl, GetBackgroundTilesCacheSize()); auto tileBackgroundReadFn = [this](df::TileKey const & tileKey, dp::BackgroundMode mode) -> bool { if (m_rasterTileProvider) return m_rasterTileProvider->RequestTile(tileKey, mode); return false; }; auto cancelTileBackgroundReadingFn = [this](df::TileKey const & tileKey, dp::BackgroundMode mode) -> void { if (m_rasterTileProvider) m_rasterTileProvider->CancelTile(tileKey, mode); }; auto myPositionModeChangedFn = [this](location::EMyPositionMode mode, bool routingActive) { GetPlatform().RunTask(Platform::Thread::Gui, [this, mode, routingActive]() { // Deactivate selection (and hide place page) if we return to routing in F&R mode. if (routingActive && mode == location::FollowAndRotate) DeactivateMapSelection(); if (m_myPositionListener != nullptr) m_myPositionListener(mode, routingActive); }); }; auto overlaysShowStatsFn = [](std::list &&) {}; auto onGraphicsContextInitialized = [this]() { GetPlatform().RunTask(Platform::Thread::Gui, [this]() { if (m_onGraphicsContextInitialized) m_onGraphicsContextInitialized(); }); }; auto isCountryLoadedByNameFn = std::bind(&Framework::IsCountryLoadedByName, this, _1); auto updateCurrentCountryFn = std::bind(&Framework::OnUpdateCurrentCountry, this, _1, _2); bool allow3d; bool allow3dBuildings; Load3dMode(allow3d, allow3dBuildings); auto const isAutozoomEnabled = LoadAutoZoom(); auto const trafficEnabled = m_trafficManager.IsEnabled(); auto const isolinesEnabled = m_isolinesManager.IsEnabled(); auto const simplifiedTrafficColors = m_trafficManager.HasSimplifiedColorScheme(); auto const fontsScaleFactor = (LoadLargeFontsSize() ? kLargeFontsScaleFactor : 1.0) * m_fontScaleFactor; // Enable the raster background layer iff the custom tile source is enabled and configured. auto const tileBackgroundMode = bgTilesActive ? dp::BackgroundMode::Satellite : dp::BackgroundMode::Default; float const satelliteAreaOpacity = GetBackgroundTilesAreaOpacity() / 100.0f; df::DrapeEngine::Params p( params.m_apiVersion, contextFactory, dp::Viewport(0, 0, params.m_surfaceWidth, params.m_surfaceHeight), df::MapDataProvider(std::move(idReadFn), std::move(featureReadFn), std::move(isCountryLoadedByNameFn), std::move(updateCurrentCountryFn), std::move(tileBackgroundReadFn), std::move(cancelTileBackgroundReadingFn)), params.m_hints, params.m_visualScale, fontsScaleFactor, std::move(params.m_widgetsInitInfo), std::move(myPositionModeChangedFn), allow3dBuildings, trafficEnabled, isolinesEnabled, params.m_isChoosePositionMode, params.m_isChoosePositionMode, GetSelectedFeatureTriangles(), m_routingManager.IsRoutingActive() && m_routingManager.IsRoutingFollowing(), isAutozoomEnabled, simplifiedTrafficColors, tileBackgroundMode, satelliteAreaOpacity, std::nullopt /* arrow3dCustomDecl */, std::move(overlaysShowStatsFn), std::move(onGraphicsContextInitialized), std::move(params.m_renderInjectionHandler)); m_drapeEngine = make_unique_dp(std::move(p)); m_drapeEngine->SetModelViewListener([this](ScreenBase const & screen) { GetPlatform().RunTask(Platform::Thread::Gui, [this, screen]() { OnViewportChanged(screen); }); }); m_drapeEngine->SetTapEventInfoListener([this](df::TapInfo const & tapInfo) { GetPlatform().RunTask(Platform::Thread::Gui, [this, tapInfo]() { OnTapEvent(place_page::BuildInfo(tapInfo)); }); }); m_drapeEngine->SetUserPositionListener([this](m2::PointD const & position, bool hasPosition) { GetPlatform().RunTask(Platform::Thread::Gui, [this, position, hasPosition]() { OnUserPositionChanged(position, hasPosition); }); }); OnSize(params.m_surfaceWidth, params.m_surfaceHeight); Allow3dMode(allow3d, allow3dBuildings); ApplyMapLanguageCode(GetMapLanguageCode()); LoadViewport(); { auto & tracker = GpsTracker::Instance(); if (tracker.IsEnabled()) tracker.Connect(std::bind(&Framework::OnUpdateGpsTrackPointsCallback, this, _1, _2, _3)); } GetBookmarkManager().SetDrapeEngine(make_ref(m_drapeEngine)); m_drapeApi.SetDrapeEngine(make_ref(m_drapeEngine)); m_routingManager.SetDrapeEngine(make_ref(m_drapeEngine), allow3d); m_trafficManager.SetDrapeEngine(make_ref(m_drapeEngine)); m_transitManager.SetDrapeEngine(make_ref(m_drapeEngine)); m_isolinesManager.SetDrapeEngine(make_ref(m_drapeEngine)); m_searchMarks.SetDrapeEngine(make_ref(m_drapeEngine)); InvalidateUserMarks(); auto const transitSchemeEnabled = LoadTransitSchemeEnabled(); m_transitManager.EnableTransitSchemeMode(transitSchemeEnabled); // Show debug info if it's enabled in the config. bool showDebugInfo = false; UNUSED_VALUE(settings::Get(kShowDebugInfo, showDebugInfo)); if (showDebugInfo) m_drapeEngine->ShowDebugInfo(showDebugInfo); benchmark::RunGraphicsBenchmark(this); } void Framework::OnRecoverSurface(int width, int height, bool recreateContextDependentResources) { if (m_drapeEngine) { m_drapeEngine->RecoverSurface(width, height, recreateContextDependentResources); InvalidateUserMarks(); m_drapeApi.Invalidate(); } m_trafficManager.OnRecoverSurface(); m_transitManager.Invalidate(); m_isolinesManager.Invalidate(); } void Framework::OnDestroySurface() { m_trafficManager.OnDestroySurface(); } void Framework::UpdateVisualScale(double vs) { if (m_drapeEngine != nullptr) m_drapeEngine->UpdateVisualScale(vs, m_isRenderingEnabled); } void Framework::UpdateMyPositionRoutingOffset(bool useDefault, int offsetY) { if (m_drapeEngine != nullptr) m_drapeEngine->UpdateMyPositionRoutingOffset(useDefault, offsetY); } ref_ptr Framework::GetDrapeEngine() { return make_ref(m_drapeEngine); } void Framework::DestroyDrapeEngine() { if (m_drapeEngine != nullptr) { m_drapeApi.SetDrapeEngine(nullptr); m_routingManager.SetDrapeEngine(nullptr, false); m_trafficManager.SetDrapeEngine(nullptr); m_transitManager.SetDrapeEngine(nullptr); m_isolinesManager.SetDrapeEngine(nullptr); m_searchMarks.SetDrapeEngine(nullptr); GetBookmarkManager().SetDrapeEngine(nullptr); m_trafficManager.Teardown(); GpsTracker::Instance().Disconnect(); m_drapeEngine.reset(); } } void Framework::SetRenderingEnabled(ref_ptr contextFactory) { m_isRenderingEnabled = true; if (m_drapeEngine) m_drapeEngine->SetRenderingEnabled(contextFactory); } void Framework::SetRenderingDisabled(bool destroySurface) { m_isRenderingEnabled = false; if (m_drapeEngine) m_drapeEngine->SetRenderingDisabled(destroySurface); } void Framework::SetGraphicsContextInitializationHandler(df::OnGraphicsContextInitialized && handler) { m_onGraphicsContextInitialized = std::move(handler); } void Framework::EnableDebugRectRendering(bool enabled) { if (m_drapeEngine) m_drapeEngine->EnableDebugRectRendering(enabled); } void Framework::StartTrackRecording() { auto & tracker = GpsTracker::Instance(); tracker.SetEnabled(true); if (m_drapeEngine) { m_drapeEngine->ClearGpsTrackPoints(); tracker.Connect(std::bind(&Framework::OnUpdateGpsTrackPointsCallback, this, _1, _2, _3)); } } void Framework::SetTrackRecordingUpdateHandler(TrackRecordingUpdateHandler && trackRecordingDidUpdate) { m_trackRecordingUpdateHandler = std::move(trackRecordingDidUpdate); if (m_trackRecordingUpdateHandler) m_trackRecordingUpdateHandler(GpsTracker::Instance().GetTrackStatistics()); } ElevationInfo const & Framework::GetTrackRecordingElevationInfo() { return GpsTracker::Instance().GetElevationInfo(); } void Framework::StopTrackRecording() { auto & tracker = GpsTracker::Instance(); tracker.Disconnect(); tracker.SetEnabled(false); if (m_drapeEngine) m_drapeEngine->ClearGpsTrackPoints(); } void Framework::SaveTrackRecordingWithName(std::string const & name) { auto const trackId = GetBookmarkManager().SaveTrackRecording(name); if (m_drapeEngine) m_drapeEngine->ClearGpsTrackPoints(); ShowTrack(trackId); GpsTracker::Instance().Clear(); } bool Framework::IsTrackRecordingEmpty() const { return GpsTracker::Instance().IsEmpty(); } bool Framework::IsTrackRecordingEnabled() const { return GpsTracker::Instance().IsEnabled(); } void Framework::SaveRoute() { auto const trackId = m_routingManager.SaveRoute(); if (trackId != kml::kInvalidTrackId) ShowTrack(trackId); } void Framework::OnUpdateGpsTrackPointsCallback(std::vector> && toAdd, std::pair const & toRemove, TrackStatistics const & trackStatistics) { ASSERT(m_drapeEngine, ()); std::vector pointsAdd; pointsAdd.reserve(toAdd.size()); for (auto const & ip : toAdd) { df::GpsTrackPoint pt; ASSERT_LESS(ip.first, static_cast(std::numeric_limits::max()), ()); pt.m_id = static_cast(ip.first); pt.m_speedMPS = ip.second.m_speed; pt.m_timestamp = ip.second.m_timestamp; pt.m_point = mercator::FromLatLon(ip.second.m_latitude, ip.second.m_longitude); pointsAdd.emplace_back(pt); } std::vector indicesRemove; if (toRemove.first != GpsTrack::kInvalidId) { ASSERT_LESS_OR_EQUAL(toRemove.first, toRemove.second, ()); indicesRemove.reserve(toRemove.second - toRemove.first + 1); for (size_t i = toRemove.first; i <= toRemove.second; ++i) indicesRemove.emplace_back(i); } m_drapeEngine->UpdateGpsTrackPoints(std::move(pointsAdd), std::move(indicesRemove)); if (m_trackRecordingUpdateHandler) m_trackRecordingUpdateHandler(trackStatistics); } void Framework::MarkMapStyle(MapStyle mapStyle) { ASSERT_NOT_EQUAL(mapStyle, MapStyle::MapStyleMerged, ()); // Store current map style before classificator reloading std::string mapStyleStr = MapStyleToString(mapStyle); if (mapStyleStr.empty()) { mapStyle = kDefaultMapStyle; mapStyleStr = MapStyleToString(mapStyle); } settings::Set(kMapStyleKey, mapStyleStr); // Make sure the new style's family is resident before switching (a no-op once it is loaded, so // light<->dark stays zero-IO); drape worker threads observe the switch only via UpdateMapStyle. classificator::EnsureStyleLoaded(mapStyle); GetStyleReader().SetCurrentStyle(mapStyle); } void Framework::SetMapStyle(MapStyle mapStyle) { MarkMapStyle(mapStyle); if (m_drapeEngine != nullptr) m_drapeEngine->UpdateMapStyle(); InvalidateUserMarks(); UpdateBookmarksTextPlacement(); UpdateMinBuildingsTapZoom(); } MapStyle Framework::GetMapStyle() const { return GetStyleReader().GetCurrentStyle(); } void Framework::SetupMeasurementSystem() { GetPlatform().SetupMeasurementSystem(); m_routingManager.SetTurnNotificationsUnits(measurement_utils::GetMeasurementUnits()); } void Framework::SetWidgetLayout(gui::TWidgetsLayoutInfo && layout) { ASSERT(m_drapeEngine, ()); m_drapeEngine->SetWidgetLayout(std::move(layout)); } Framework::ParsedRoutingData Framework::GetParsedRoutingData() const { return Framework::ParsedRoutingData(m_parsedMapApi.GetRoutePoints(), routing::FromString(m_parsedMapApi.GetRoutingType())); } url_scheme::SearchRequest Framework::GetParsedSearchRequest() const { return m_parsedMapApi.GetSearchRequest(); } std::string Framework::GetParsedOAuth2Code() const { return m_parsedMapApi.GetOAuth2Code(); } std::string const & Framework::GetParsedAppName() const { return m_parsedMapApi.GetAppName(); } std::string const & Framework::GetParsedBackUrl() const { return m_parsedMapApi.GetGlobalBackUrl(); } ms::LatLon Framework::GetParsedCenterLatLon() const { return m_parsedMapApi.GetCenterLatLon(); } url_scheme::InAppFeatureHighlightRequest Framework::GetInAppFeatureHighlightRequest() const { return m_parsedMapApi.GetInAppFeatureHighlightRequest(); } FeatureID Framework::GetFeatureAtPoint(m2::PointD const & mercator) const { return GetSelectionProcessor().GetFeatureAtPoint(mercator); } osm::MapObject Framework::GetMapObjectByID(FeatureID const & fid) const { osm::MapObject res; ASSERT(fid.IsValid(), ()); FeaturesLoaderGuard guard(m_featuresFetcher.GetDataSource(), fid.m_mwmId); auto ft = guard.GetFeatureByIndex(fid.m_index); if (ft) res.SetFromFeatureType(*ft); return res; } BookmarkManager & Framework::GetBookmarkManager() { ASSERT(m_bmManager, ()); return *m_bmManager; } BookmarkManager const & Framework::GetBookmarkManager() const { ASSERT(m_bmManager, ()); return *m_bmManager; } void Framework::SetPlacePageListeners(PlacePageEvent::OnOpen onOpen, PlacePageEvent::OnClose onClose, PlacePageEvent::OnUpdate onUpdate, PlacePageEvent::OnSwitchFullScreen onSwitchFullScreen) { m_onPlacePageOpen = std::move(onOpen); m_onPlacePageClose = std::move(onClose); m_onPlacePageUpdate = std::move(onUpdate); m_onSwitchFullScreen = std::move(onSwitchFullScreen); #ifdef OMIM_OS_ANDROID // A click on the Search result from the search activity in Android calls // ShowSearchResult/SelectSearchResult, but SetPlacePageListeners is set later, // when MWMActivity::onStart is called. So PP is displayed here if its info was set previously. // TODO: A better approach is to use an intent with params to pass the search result into MWMActivity, // like it is done when selected bookmark is displayed on the map. if (m_onPlacePageOpen && HasPlacePageInfo()) m_onPlacePageOpen(); #endif // OMIM_OS_ANDROID } place_page::Info const & Framework::GetCurrentPlacePageInfo() const { CHECK(HasPlacePageInfo(), ()); return *m_currentPlacePageInfo; } place_page::Info & Framework::GetCurrentPlacePageInfo() { CHECK(HasPlacePageInfo(), ()); return *m_currentPlacePageInfo; } void Framework::UpdateBookmarksTextPlacement() { m_bmManager->UpdateBookmarksTextPlacement(); } void Framework::ActivateMapSelection() { if (!m_currentPlacePageInfo) return; auto & bm = GetBookmarkManager(); bm.ResetRecentlyDeletedBookmark(); if (m_currentPlacePageInfo->GetSelectedObject() == df::SelectionShape::OBJECT_TRACK) bm.OnTrackSelected(m_currentPlacePageInfo->GetTrackId()); else bm.OnTrackDeselected(); auto const & featureId = m_currentPlacePageInfo->GetID(); m_searchMarks.SetSelected(featureId); auto const selObj = m_currentPlacePageInfo->GetSelectedObject(); CHECK_NOT_EQUAL(selObj, df::SelectionShape::OBJECT_EMPTY, ("Empty selections are impossible.")); if (m_drapeEngine) { auto const & bi = m_currentPlacePageInfo->GetBuildInfo(); m_drapeEngine->SelectObject(selObj, m_currentPlacePageInfo->GetMercator(), featureId, bi.m_needAnimationOnSelection, bi.m_isGeometrySelectionAllowed, true); } /// @todo Current android logic is strange (see SetPlacePageListeners comments), so skip assert. // ASSERT(m_onPlacePageOpen, ()); if (m_onPlacePageOpen) m_onPlacePageOpen(); } bool Framework::DeactivateMapSelection() { if (m_routingManager.IsRoutingActive() || m_routingManager.GetRoutePointsCount() > 0) HideRouteTransitIfNeeded(); bool const recoverRouteTransitSession = m_currentPlacePageInfo && m_routeTransitSelection && m_currentPlacePageInfo->GetID() != m_routeTransitSelection->m_featureId; if (recoverRouteTransitSession) { DeactivateHotelSearchMark(); auto & bm = GetBookmarkManager(); bm.OnTrackDeselected(); bm.ClearTempRelationTrack(); bm.ResetRecentlyDeletedBookmark(); place_page::BuildInfo info; info.m_featureId = m_routeTransitSelection->m_featureId; info.m_match = place_page::BuildInfo::Match::FeatureOnly; m_currentPlacePageInfo = BuildPlacePageInfo(info); ActivateMapSelection(); return true; } if (m_onPlacePageClose) m_onPlacePageClose(); if (m_currentPlacePageInfo) { HideRouteTransitIfNeeded(); DeactivateHotelSearchMark(); auto & bm = GetBookmarkManager(); bm.OnTrackDeselected(); bm.ClearTempRelationTrack(); bm.ResetRecentlyDeletedBookmark(); m_currentPlacePageInfo = {}; if (m_drapeEngine != nullptr) m_drapeEngine->DeselectObject(false /* restoreViewport */); } return false; } void Framework::DeactivateMapSelectionCircle(bool restoreViewport) { if (m_drapeEngine) m_drapeEngine->DeselectObject(restoreViewport); } void Framework::SwitchFullScreen() { if (m_onSwitchFullScreen) m_onSwitchFullScreen(); } void Framework::InvalidateUserMarks() { // Actual invalidation call happens in EditSession dtor. GetBookmarkManager().GetEditSession(); } void Framework::DeactivateHotelSearchMark() { if (!m_currentPlacePageInfo) return; m_searchMarks.SetSelected({}); if (m_currentPlacePageInfo->IsHotel()) { auto const & featureId = m_currentPlacePageInfo->GetID(); if (m_searchMarks.IsThereSearchMarkForFeature(featureId)) { m_searchMarks.SetVisited(featureId); m_searchMarks.OnDeactivate(featureId); } if (!GetSearchAPI().IsViewportSearchActive()) GetBookmarkManager().GetEditSession().ClearGroup(UserMark::Type::SEARCH); } } void Framework::OnTapEvent(place_page::BuildInfo const & buildInfo) { // Intercept taps on alternative-route ETA balloons before BuildPlacePageInfo: swap the active // variant and return. Always return — even when SwapActiveAlternative declines (tap on the // already-active balloon) — because FillUserMarkInfo has no ROUTE_ALT handler and would CHECK-fail. if (!buildInfo.m_isLongTap && buildInfo.m_userMarkId != kml::kInvalidMarkId && UserMark::GetMarkType(buildInfo.m_userMarkId) == UserMark::Type::ROUTE_ALT) { if (auto const * mark = static_cast(GetBookmarkManager().GetUserMark(buildInfo.m_userMarkId))) m_routingManager.SwapActiveAlternative(mark->GetRouteIdx()); return; } // Same swap when the tap lands on an alternative route's polyline rather than its balloon. if (!buildInfo.m_isLongTap && m_routingManager.TryTapOnAlternativeRoute(buildInfo.m_mercator, m_currentModelView.GetScale())) { return; } auto placePageInfo = BuildPlacePageInfo(buildInfo); bool isRoutePoint = placePageInfo.IsRoutePoint(); if (m_routingManager.IsRoutingActive() && m_routingManager.GetCurrentRouterType() == routing::RouterType::Ruler && !buildInfo.m_isLongTap && !isRoutePoint) { DeactivateMapSelection(); // This re-check guards against any synchronous callback that tears down routing mid-handler. if (!m_routingManager.IsRoutingActive()) return; // Continue route to the point RouteMarkData data; data.m_title = placePageInfo.GetTitle(); data.m_subTitle = std::string(); data.m_pointType = RouteMarkType::Finish; data.m_intermediateIndex = m_routingManager.GetRoutePointsCount() - 1; data.m_isMyPosition = false; if (placePageInfo.IsBookmark()) // Continue route to exact bookmark position. data.m_position = placePageInfo.GetBookmarkData().m_point; else data.m_position = buildInfo.m_mercator; if (!m_routingManager.ContinueRouteToPoint(std::move(data))) return; // Refresh route m_routingManager.RemoveRoute(false /* deactivateFollowing */); m_routingManager.BuildRoute(); return; } if (buildInfo.m_isLongTap) { SwitchFullScreen(); } else { auto const prevTrackId = m_currentPlacePageInfo ? m_currentPlacePageInfo->GetTrackId() : kml::kInvalidTrackId; DeactivateHotelSearchMark(); m_currentPlacePageInfo = placePageInfo; auto const newTrackId = m_currentPlacePageInfo->GetTrackId(); if (newTrackId != kml::kInvalidTrackId) { // For user tracks: tapping the same track at a different point just moves the selection circle. // Temp relation tracks always reuse the same ID, so always update the PlacePage for them. if (newTrackId == prevTrackId && newTrackId != kml::kTempRelationTrackId) { if (m_drapeEngine) { m_drapeEngine->SelectObject(df::SelectionShape::ESelectedObject::OBJECT_TRACK, m_currentPlacePageInfo->GetMercator(), FeatureID(), false /* isAnim */, false /* isGeometrySelectionAllowed */, true /* isSelectionShapeVisible */); } return; } GetBookmarkManager().UpdateElevationMyPosition(newTrackId, true /* ignoreLocationCache */); } ActivateMapSelection(); } } void Framework::InvalidateRendering() { if (m_drapeEngine) m_drapeEngine->Invalidate(); } void Framework::UpdateMinBuildingsTapZoom() { constexpr int kMinTapZoom = 16; m_minBuildingsTapZoom = std::max(kMinTapZoom, feature::GetDrawableScaleRange(classif().GetTypeByPath({"building"})).first); } FeatureID Framework::FindBuildingAtPoint(m2::PointD const & mercator) const { FeatureID featureId; if (GetDrawScale() >= m_minBuildingsTapZoom) { constexpr int kScale = scales::GetUpperScale(); constexpr double kSelectRectWidthInMeters = 1.1; m2::RectD const rect = mercator::RectByCenterXYAndSizeInMeters(mercator, kSelectRectWidthInMeters); m_featuresFetcher.ForEachFeature(rect, [&](FeatureType & ft) { if (!featureId.IsValid() && ft.GetGeomType() == feature::GeomType::Area && ftypes::IsBuildingChecker::Instance()(ft) && ft.GetLimitRect(kScale).IsPointInside(mercator) && feature::GetMinDistanceMeters(ft, mercator) == 0.0) { featureId = ft.GetID(); } }, kScale); } return featureId; } bool Framework::BuildTrackPlacePage(Track::TrackSelectionInfo const & trackSelectionInfo, place_page::Info & info) { auto & bm = GetBookmarkManager(); Track::TrackSelectionInfo selectedInfo = trackSelectionInfo; if (selectedInfo.IsRelation()) { auto trackData = TryBuildRelationTrack(selectedInfo); if (!trackData) return false; bm.SetTempRelationTrack(std::move(trackData.value())); auto const tapPoint = selectedInfo.m_trackPoint; // Copy tap point before mutation. bm.GetTrack(kml::kTempRelationTrackId)->UpdateSelectionInfo(tapPoint, selectedInfo); } else if (selectedInfo.m_trackId != kml::kTempRelationTrackId) { // Never drop the temporary track when it is the selected one: it can't be rebuilt without the // relation metadata that this selection is missing. bm.ClearTempRelationTrack(); } // Can be null for a stale selection mark, left over from an already deleted track. auto const * track = bm.GetTrack(selectedInfo.m_trackId); if (track == nullptr) return false; info.SetSelectedObject(df::SelectionShape::OBJECT_TRACK); FillTrackInfo(*track, selectedInfo, info); bm.SetTrackSelectionInfo(selectedInfo, true /* notifyListeners */); return true; } place_page::Info Framework::BuildPlacePageInfo(place_page::BuildInfo const & buildInfo) { place_page::Info outInfo; outInfo.SetBuildInfo(buildInfo); // 1. User Bookmarks. if (buildInfo.IsUserMarkMatchingEnabled()) { UserMark const * mark = nullptr; if (buildInfo.m_userMarkId != kml::kInvalidMarkId) { auto const & bm = GetBookmarkManager(); mark = bm.IsBookmark(buildInfo.m_userMarkId) ? bm.GetBookmark(buildInfo.m_userMarkId) : bm.GetUserMark(buildInfo.m_userMarkId); ASSERT(mark, ("There is no user mark with id", buildInfo.m_userMarkId)); } if (!mark) mark = FindUserMarkInTapPosition(buildInfo); if (mark) { if (FillUserMarkInfo(mark, outInfo)) return outInfo; // Stale track mark: drop the partially filled info and continue with the regular matching. outInfo = {}; outInfo.SetBuildInfo(buildInfo); } } auto const & sp = GetSelectionProcessor(); // 2. My position. if (buildInfo.m_isMyPosition) { outInfo.SetSelectedObject(df::SelectionShape::OBJECT_MY_POSITION); FillMyPositionInfo(outInfo, buildInfo); sp.SetPlacePageLocation(outInfo); return outInfo; } auto const isFeatureMatchingEnabled = buildInfo.IsFeatureMatchingEnabled(); // 3. Feature explicitly set (drape overlay tap or search result) -> possible fallback to Bookmark. if (buildInfo.m_featureId.IsValid()) { sp.FillFeatureInfo(buildInfo.m_featureId, outInfo); if (buildInfo.IsUserMarkMatchingEnabled() && !outInfo.IsBookmark()) { double constexpr kEps = 1e-7; auto const rect = df::TapInfo::GetPreciseTapRect(outInfo.GetMercator(), kEps); UserMark const * mark = GetBookmarkManager().FindNearestUserMark([&rect](UserMark::Type) { return rect; }, [](UserMark::Type) { return true; }); // On a stale track mark keep the feature info filled above and fall back to the POI selection. if (mark && FillUserMarkInfo(mark, outInfo)) { sp.SetPlacePageLocation(outInfo); return outInfo; } } outInfo.SetSelectedObject(df::SelectionShape::OBJECT_POI); GetBookmarkManager().SelectionMark().SetPtOrg(outInfo.GetMercator()); sp.SetPlacePageLocation(outInfo); return outInfo; } // 4. User Tracks. Using VisualParams inside FindTracksInTapPosition/GetDefaultTapRect requires drapeEngine. if (m_drapeEngine != nullptr && buildInfo.IsTrackMatchingEnabled()) { Track::TrackSelectionInfo trackToSelect; std::vector trackSelectionCandidates; if (buildInfo.m_trackId != kml::kInvalidTrackId) { // Known track: find the closest point to the track's bounding-rect center, no distance limit. auto const * track = GetBookmarkManager().GetTrack(buildInfo.m_trackId); if (track == nullptr) return outInfo; track->UpdateSelectionInfo(track->GetLimitRect().Center(), trackToSelect); ASSERT(trackToSelect.IsValid(), ()); trackSelectionCandidates.push_back(trackToSelect); } else { trackSelectionCandidates = FindTracksInTapPosition(buildInfo); if (!trackSelectionCandidates.empty() && isFeatureMatchingEnabled) { auto const searchRect = df::TapInfo::GetDefaultTapRect(buildInfo.m_mercator, m_currentModelView).GetGlobalRect(); auto relationTrackCandidates = FindRelationTracksInTapPosition( sp.FindFeaturesInRect(buildInfo.m_mercator, searchRect).m_lineCandidates, buildInfo.m_mercator); trackSelectionCandidates.insert(trackSelectionCandidates.end(), relationTrackCandidates.begin(), relationTrackCandidates.end()); std::sort(trackSelectionCandidates.begin(), trackSelectionCandidates.end(), HasHigherTrackSelectionPriority); } if (!trackSelectionCandidates.empty()) trackToSelect = trackSelectionCandidates.front(); } if (trackToSelect.IsValid() && BuildTrackPlacePage(trackToSelect, outInfo)) { outInfo.SetTrackCandidates(std::move(trackSelectionCandidates)); return outInfo; } } // 5. Find and classify features in tap rect. if (isFeatureMatchingEnabled) { m2::RectD searchRect; if (m_drapeEngine != nullptr) { // No problem if it is bigger with rotation. searchRect = df::TapInfo::GetDefaultTapRect(buildInfo.m_mercator, m_currentModelView).GetGlobalRect(); } else { // Fallback when drape engine is not available (e.g. search result selection). constexpr double kFallbackRadiusM = 20.0; searchRect = mercator::RectByCenterXYAndSizeInMeters(buildInfo.m_mercator, kFallbackRadiusM); } auto const tap = sp.FindFeaturesInRect(buildInfo.m_mercator, searchRect); // POIs (tap.m_poi) are intentionally not used here — visible POIs are always // selected through drape's OverlayTree (step 3). We must not select displaced or // invisible POIs via ForEachInRect. // Priority: Building > Route relation track > Line > Area. if (tap.m_building.IsValid() && GetDrawScale() >= m_minBuildingsTapZoom) { sp.FillFeatureInfo(tap.m_building, outInfo); outInfo.SetMercator(buildInfo.m_mercator); // Move selection circle to the tap position inside a building. } else { Track::TrackSelectionInfo trackToSelect; auto trackSelectionCandidates = FindRelationTracksInTapPosition(tap.m_lineCandidates, buildInfo.m_mercator); std::sort(trackSelectionCandidates.begin(), trackSelectionCandidates.end(), HasHigherTrackSelectionPriority); if (!trackSelectionCandidates.empty()) trackToSelect = trackSelectionCandidates.front(); // Set first track as selected to display. if (trackToSelect.IsValid()) { outInfo.SetSelectedObject(df::SelectionShape::OBJECT_TRACK); sp.SetPlacePageLocation(outInfo); if (BuildTrackPlacePage(trackToSelect, outInfo)) { outInfo.SetTrackCandidates(std::move(trackSelectionCandidates)); return outInfo; } } auto const bestFeature = tap.m_line.IsValid() ? tap.m_line : tap.m_area; if (bestFeature.IsValid()) { sp.FillFeatureInfo(bestFeature, outInfo); outInfo.SetMercator(buildInfo.m_mercator); } else { sp.FillNotMatchedPlaceInfo(outInfo, buildInfo.m_mercator, {}); } } } else { sp.FillNotMatchedPlaceInfo(outInfo, buildInfo.m_mercator, {}); } // 6. Empty place / final POI setup. outInfo.SetSelectedObject(df::SelectionShape::OBJECT_POI); GetBookmarkManager().SelectionMark().SetPtOrg(outInfo.GetMercator()); sp.SetPlacePageLocation(outInfo); return outInfo; } void Framework::UpdatePlacePageInfoForCurrentSelection(std::optional const & overrideInfo) { if (!m_currentPlacePageInfo) return; m_currentPlacePageInfo = BuildPlacePageInfo(overrideInfo ? *overrideInfo : m_currentPlacePageInfo->GetBuildInfo()); if (m_onPlacePageUpdate) m_onPlacePageUpdate(); } std::vector Framework::FindTracksInTapPosition(place_page::BuildInfo const & buildInfo) const { auto const & bm = GetBookmarkManager(); if (buildInfo.m_trackId != kml::kInvalidTrackId) { if (bm.GetTrack(buildInfo.m_trackId) == nullptr) return {}; auto const selection = bm.GetTrackSelectionInfo(buildInfo.m_trackId); CHECK(selection.IsValid(), ()); return {selection}; } auto const touchRect = df::TapInfo::GetDefaultTapRect(buildInfo.m_mercator, m_currentModelView).GetGlobalRect(); return bm.FindTracksInRect(touchRect); } UserMark const * Framework::FindUserMarkInTapPosition(place_page::BuildInfo const & buildInfo) const { UserMark const * mark = GetBookmarkManager().FindNearestUserMark([this, &buildInfo](UserMark::Type type) { double constexpr kEps = 1e-7; if (buildInfo.m_source != place_page::BuildInfo::Source::User) return df::TapInfo::GetPreciseTapRect(buildInfo.m_mercator, kEps); if (type == UserMark::Type::BOOKMARK || type == UserMark::Type::TRACK_INFO) return df::TapInfo::GetBookmarkTapRect(buildInfo.m_mercator, m_currentModelView); if (type == UserMark::Type::ROUTING || type == UserMark::Type::ROAD_WARNING) return df::TapInfo::GetRoutingPointTapRect(buildInfo.m_mercator, m_currentModelView); return df::TapInfo::GetDefaultTapRect(buildInfo.m_mercator, m_currentModelView); }, [](UserMark::Type type) { return type == UserMark::Type::TRACK_INFO || type == UserMark::Type::TRACK_SELECTION; }); return mark; } void Framework::PredictLocation(double & lat, double & lon, double accuracy, double bearing, double speed, double elapsedSeconds) { double offsetInM = speed * elapsedSeconds; double angle = math::DegToRad(90.0 - bearing); m2::PointD mercatorPt = mercator::MetersToXY(lon, lat, accuracy).Center(); mercatorPt = mercator::GetSmPoint(mercatorPt, offsetInM * cos(angle), offsetInM * sin(angle)); // GetSmPoint may return extended coordinates past the antimeridian. // Wrap back to [-180, 180] so callers (e.g. iOS CLLocation) get valid longitude. lon = mercator::XToLon(mercator::WrapX(mercatorPt.x)); lat = mercator::YToLat(mercatorPt.y); } StringsBundle const & Framework::GetStringsBundle() { return m_stringsBundle; } // static std::string Framework::CodeGe0url(Bookmark const * bmk, bool addName) { double lat = mercator::YToLat(bmk->GetPivot().y); double lon = mercator::XToLon(bmk->GetPivot().x); return ge0::GenerateShortShowMapUrl(lat, lon, bmk->GetScale(), addName ? bmk->GetPreferredName() : ""); } // static std::string Framework::CodeGe0url(double lat, double lon, double zoomLevel, std::string const & name) { return ge0::GenerateShortShowMapUrl(lat, lon, zoomLevel, name); } std::string Framework::GenerateApiBackUrl(ApiMarkPoint const & point) const { std::string res = m_parsedMapApi.GetGlobalBackUrl(); if (!res.empty()) { ms::LatLon const ll = point.GetLatLon(); res += "pin?ll=" + strings::to_string(ll.m_lat) + "," + strings::to_string(ll.m_lon); if (!point.GetName().empty()) res += "&n=" + url::UrlEncode(point.GetName()); if (!point.GetApiID().empty()) res += "&id=" + url::UrlEncode(point.GetApiID()); } return res; } /* bool Framework::IsDataVersionUpdated() { int64_t storedVersion; if (settings::Get("DataVersion", storedVersion)) { return storedVersion < m_storage.GetCurrentDataVersion(); } // no key in the settings, assume new version return true; } void Framework::UpdateSavedDataVersion() { settings::Set("DataVersion", m_storage.GetCurrentDataVersion()); } */ int64_t Framework::GetCurrentDataVersion() const { return m_storage.GetCurrentDataVersion(); } dp::ApiVersion Framework::LoadPreferredGraphicsAPI() { std::string apiStr; if (settings::Get(kPreferredGraphicsAPI, apiStr)) return dp::ApiVersionFromString(apiStr); return dp::ApiVersionFromString({}); } void Framework::SavePreferredGraphicsAPI(dp::ApiVersion apiVersion) { settings::Set(kPreferredGraphicsAPI, DebugPrint(apiVersion)); } void Framework::AllowTransliteration(bool allowTranslit) { Transliteration::Instance().SetMode(allowTranslit ? Transliteration::Mode::Enabled : Transliteration::Mode::Disabled); Invalidate(); } bool Framework::LoadTransliteration() { Transliteration::Mode mode; if (settings::Get(kTranslitMode, mode)) return mode == Transliteration::Mode::Enabled; return true; } void Framework::SaveTransliteration(bool allowTranslit) { settings::Set(kTranslitMode, allowTranslit ? Transliteration::Mode::Enabled : Transliteration::Mode::Disabled); } std::string Framework::GetMapLanguageCode() { return languages::GetCurrentMapLanguage(); } void Framework::SetMapLanguageCode(std::string const & langCode) { settings::Set(settings::kMapLanguageCode, langCode); if (m_drapeEngine) ApplyMapLanguageCode(langCode); if (m_searchAPI) m_searchAPI->SetLocale(langCode); } void Framework::CreateBackgroundTilesProvider(std::string const & url, uint32_t cacheSizeMB) { RasterTileProvider::Params rp; rp.m_urlTemplate = url; rp.m_cacheSubdir = "bg_tiles"; rp.m_maxZoom = 19; // standard web-mercator detail; deeper OM tiles reuse the ancestor sub-rect. rp.m_maxCacheBytes = static_cast(cacheSizeMB) * 1024 * 1024; // Global coverage (whole world) — min zoom and the lat/lon box keep their defaults. m_rasterTileProvider = std::make_unique( std::move(rp), [this](df::TileKey const & tileKey, dp::BackgroundMode mode, std::string const & imageUid, uint32_t width, uint32_t height, m2::RectF const & rect, std::vector && rgba) { // Invoked on a background thread; AddTileBackgroundImage/SetTileBackgroundData only post // messages, so they are safe to call from any thread. if (m_drapeEngine) { m_drapeEngine->AddTileBackgroundImage(imageUid, width, height, dp::TextureFormat::RGBA8, mode, std::move(rgba)); m_drapeEngine->SetTileBackgroundData(tileKey, imageUid, rect); } }); } void Framework::SetBackgroundTiles(bool enabled, std::string url, uint32_t cacheSizeMB, uint32_t areaOpacityPct) { // Single entry point for the settings UI: persist all values and apply them at once. We only persist // the URL/cache/opacity when enabling — when disabled, keep the previously stored values untouched and // just flip the off-flag. Otherwise editing the URL while the layer is off would persist it and then // resurface as a stale RasterTileProvider on the next enable (enable -> edit -> disable -> close). if (!enabled) { SetBackgroundTilesEnabled(false); return; } cacheSizeMB = math::Clamp(cacheSizeMB, kBackgroundTilesMinCacheSizeMB, kBackgroundTilesMaxCacheSizeMB); areaOpacityPct = math::Clamp(areaOpacityPct, kBackgroundTilesMinAreaOpacityPct, kBackgroundTilesMaxAreaOpacityPct); settings::Set(kBgTilesEnabledKey, enabled); settings::Set(kBgTilesUrlKey, url); settings::Set(kBgTilesCacheSizeMBKey, cacheSizeMB); settings::Set(kBgTilesAreaOpacityKey, areaOpacityPct); bool const active = !url.empty(); if (active) { auto const cacheBytes = static_cast(cacheSizeMB) * 1024 * 1024; if (m_rasterTileProvider) m_rasterTileProvider->Reconfigure(url, cacheBytes); // clears the cache if the URL changed else CreateBackgroundTilesProvider(url, cacheSizeMB); } if (m_drapeEngine) m_drapeEngine->SetTileBackgroundMode(active ? dp::BackgroundMode::Satellite : dp::BackgroundMode::Default, areaOpacityPct / 100.0f); } uint32_t Framework::GetBackgroundTilesCacheSize() { uint32_t res; if (!settings::Get(kBgTilesCacheSizeMBKey, res) || res < kBackgroundTilesMinCacheSizeMB || res > kBackgroundTilesMaxCacheSizeMB) res = kDefaultBgTilesCacheSizeMB; return res; } void Framework::SetBackgroundTilesEnabled(bool enabled) { // Toggle the layer on/off without touching the persisted URL / cache size / area opacity. settings::Set(kBgTilesEnabledKey, enabled); std::string url; settings::TryGet(kBgTilesUrlKey, url); bool const active = enabled && !url.empty(); // The provider is created lazily at startup only when the layer was already on; create it here on // the first enable so SetTileBackgroundMode(Satellite) has tiles to render. if (active && !m_rasterTileProvider) CreateBackgroundTilesProvider(url, GetBackgroundTilesCacheSize()); if (m_drapeEngine) m_drapeEngine->SetTileBackgroundMode(active ? dp::BackgroundMode::Satellite : dp::BackgroundMode::Default, GetBackgroundTilesAreaOpacity() / 100.0f); } std::string Framework::GetBackgroundTilesURL() { std::string url; settings::TryGet(kBgTilesUrlKey, url); return url; } bool Framework::IsBackgroundTilesEnabled() { bool enabled = false; settings::TryGet(kBgTilesEnabledKey, enabled); return enabled; } uint32_t Framework::GetBackgroundTilesAreaOpacity() { uint32_t opacityPct; if (!settings::Get(kBgTilesAreaOpacityKey, opacityPct) || opacityPct > kBackgroundTilesMaxAreaOpacityPct) opacityPct = kDefaultBgTilesAreaOpacityPct; return opacityPct; } bool Framework::IsWellFormedBackgroundTilesURL(std::string const & url) { // Require an http(s):// scheme. size_t hostStart; if (url.starts_with("https://")) hostStart = 8; else if (url.starts_with("http://")) hostStart = 7; else return false; // Require a non-empty host (everything up to the first '/' after the scheme). size_t const slash = url.find('/', hostStart); size_t const hostLen = (slash == std::string::npos ? url.size() : slash) - hostStart; if (hostLen == 0) return false; // Require all three placeholders present literally (braces must not be percent-encoded). return url.find("{z}") != std::string::npos && url.find("{x}") != std::string::npos && url.find("{y}") != std::string::npos; } void Framework::ApplyMapLanguageCode(std::string const & langCode) { int8_t langIndex = StringUtf8Multilang::GetLangIndex(langCode); ASSERT(langIndex != StringUtf8Multilang::kUnsupportedLanguageCode, ()); if (langIndex == StringUtf8Multilang::kUnsupportedLanguageCode) langIndex = StringUtf8Multilang::kDefaultCode; m_drapeEngine->SetMapLangIndex(langIndex); } void Framework::Allow3dMode(bool allow3d, bool allow3dBuildings) { if (m_drapeEngine == nullptr) return; if (!m_powerManager.IsFacilityEnabled(power_management::Facility::PerspectiveView)) allow3d = false; if (!m_powerManager.IsFacilityEnabled(power_management::Facility::Buildings3d)) allow3dBuildings = false; m_drapeEngine->Allow3dMode(allow3d, allow3dBuildings); } void Framework::Save3dMode(bool allow3d, bool allow3dBuildings) { settings::Set(kAllow3dKey, allow3d); settings::Set(kAllow3dBuildingsKey, allow3dBuildings); } void Framework::Load3dMode(bool & allow3d, bool & allow3dBuildings) { if (!settings::Get(kAllow3dKey, allow3d)) allow3d = true; if (!settings::Get(kAllow3dBuildingsKey, allow3dBuildings)) allow3dBuildings = true; } bool Framework::LoadLargeFontsSize() { bool isLargeSize = false; return settings::Get(kLargeFontsSize, isLargeSize) && isLargeSize; } void Framework::SetLargeFontsSize(bool isLargeSize) { settings::Set(kLargeFontsSize, isLargeSize); double const resultScaleFactor = (isLargeSize ? kLargeFontsScaleFactor : 1.0) * m_fontScaleFactor; if (!m_drapeEngine) return; m_drapeEngine->SetFontScaleFactor(resultScaleFactor); Invalidate(); } void Framework::SetFontScaleFactor(double scaleFactor) { if (m_fontScaleFactor == scaleFactor) return; m_fontScaleFactor = scaleFactor; if (!m_drapeEngine) return; bool isLargeSize = false; UNUSED_VALUE(settings::Get(kLargeFontsSize, isLargeSize)); auto const resultScaleFactor = (isLargeSize ? kLargeFontsScaleFactor : 1.0) * m_fontScaleFactor; m_drapeEngine->SetFontScaleFactor(resultScaleFactor); Invalidate(); } bool Framework::LoadTrafficEnabled() { bool enabled; return settings::Get(kTrafficEnabledKey, enabled) && enabled; } void Framework::SaveTrafficEnabled(bool trafficEnabled) { settings::Set(kTrafficEnabledKey, trafficEnabled); } bool Framework::LoadTrafficSimplifiedColors() { bool simplified; if (!settings::Get(kTrafficSimplifiedColorsKey, simplified)) simplified = true; return simplified; } void Framework::SaveTrafficSimplifiedColors(bool simplified) { settings::Set(kTrafficSimplifiedColorsKey, simplified); } bool Framework::LoadAutoZoom() { bool allowAutoZoom; if (!settings::Get(kAllowAutoZoom, allowAutoZoom)) allowAutoZoom = true; return allowAutoZoom; } void Framework::AllowAutoZoom(bool allowAutoZoom) { routing::RouterType const type = m_routingManager.GetRouter(); bool const isPedestrianRoute = type == RouterType::Pedestrian; if (m_drapeEngine != nullptr) m_drapeEngine->AllowAutoZoom(allowAutoZoom && !isPedestrianRoute); } void Framework::SaveAutoZoom(bool allowAutoZoom) { settings::Set(kAllowAutoZoom, allowAutoZoom); } settings::Placement Framework::GetBookmarksTextPlacement() { using namespace settings; auto setting = kDefaultBookmarksTextPlacement; TryGet(kBookmarksTextPlacement, setting); return setting; } void Framework::SetBookmarksTextPlacement(settings::Placement setting) { settings::Set(settings::kBookmarksTextPlacement, setting); UpdateBookmarksTextPlacement(); } bool Framework::IsShowDownloadedRegions() { bool showDownloadedRegions; if (!settings::Get(kShowDownloadedRegions, showDownloadedRegions)) showDownloadedRegions = true; return showDownloadedRegions; } void Framework::SetShowDownloadedRegions(bool isEnabled) { if (isEnabled && !m_infoGetter->HasRegionTriangles()) return; m_showDownloadedRegions = isEnabled; settings::Set(kShowDownloadedRegions, isEnabled); Invalidate(); } bool Framework::LoadTransitSchemeEnabled() { bool enabled; return settings::Get(kTransitSchemeEnabledKey, enabled) && enabled; } void Framework::SaveTransitSchemeEnabled(bool enabled) { settings::Set(kTransitSchemeEnabledKey, enabled); } bool Framework::LoadIsolinesEnabled() { bool enabled; return settings::Get(kIsolinesEnabledKey, enabled) && enabled; } void Framework::SaveIsolinesEnabled(bool enabled) { settings::Set(kIsolinesEnabledKey, enabled); } bool Framework::LoadOutdoorsEnabled() { bool enabled; return settings::Get(kOutdoorsEnabledKey, enabled) && enabled; } void Framework::SaveOutdoorsEnabled(bool enabled) { settings::Set(kOutdoorsEnabledKey, enabled); } bool Framework::IsHikingEnabled() { bool enabled; return settings::Get(df::RelationsDrawSettings::kHikingEnabledKey, enabled) && enabled; } void Framework::SetHikingEnabled(bool enabled) { settings::Set(df::RelationsDrawSettings::kHikingEnabledKey, enabled); Invalidate(); } bool Framework::IsCyclingEnabled() { bool enabled; return settings::Get(df::RelationsDrawSettings::kCyclingEnabledKey, enabled) && enabled; } void Framework::SetCyclingEnabled(bool enabled) { settings::Set(df::RelationsDrawSettings::kCyclingEnabledKey, enabled); Invalidate(); } void Framework::EnableChoosePositionMode(bool enable, bool enableBounds, m2::PointD const * optionalPosition) { if (m_drapeEngine != nullptr) { m_drapeEngine->EnableChoosePositionMode( enable, enableBounds ? GetSelectedFeatureTriangles() : std::vector(), optionalPosition); } } std::vector Framework::GetSelectedFeatureTriangles() const { std::vector triangles; if (!m_currentPlacePageInfo || !m_currentPlacePageInfo->GetID().IsValid()) return triangles; FeaturesLoaderGuard const guard(m_featuresFetcher.GetDataSource(), m_currentPlacePageInfo->GetID().m_mwmId); auto ft = guard.GetFeatureByIndex(m_currentPlacePageInfo->GetID().m_index); if (!ft) return triangles; if (ftypes::IsBuildingChecker::Instance()(feature::TypesHolder(*ft))) { triangles.reserve(10); ft->ForEachTriangle([&](m2::PointD const & p1, m2::PointD const & p2, m2::PointD const & p3) { triangles.emplace_back(p1, p2, p3); }, scales::GetUpperScale()); } return triangles; } void Framework::BlockTapEvents(bool block) { if (m_drapeEngine != nullptr) m_drapeEngine->BlockTapEvents(block); } bool Framework::ParseDrapeDebugCommand(std::string const & query) { MapStyle desiredStyle = MapStyleCount; if (query == "?dark" || query == "mapstyle:dark") desiredStyle = MapStyleDefaultDark; else if (query == "?light" || query == "mapstyle:light") desiredStyle = MapStyleDefaultLight; else if (query == "?vlight" || query == "mapstyle:vehicle_light") desiredStyle = MapStyleVehicleLight; else if (query == "?vdark" || query == "mapstyle:vehicle_dark") desiredStyle = MapStyleVehicleDark; else if (query == "?olight" || query == "mapstyle:outdoors_light") desiredStyle = MapStyleOutdoorsLight; else if (query == "?odark" || query == "mapstyle:outdoors_dark") desiredStyle = MapStyleOutdoorsDark; if (desiredStyle != MapStyleCount) { #if defined(OMIM_OS_ANDROID) if (m_drapeEngine->GetApiVersion() == dp::ApiVersion::Vulkan) { // See comment in android/jni/app/organicmaps/Framework.cpp Framework::MarkMapStyle(). SetMapStyle(desiredStyle); } else MarkMapStyle(desiredStyle); #else SetMapStyle(desiredStyle); #endif return true; } if (query == "?aa" || query == "effect:antialiasing") { m_drapeEngine->SetPosteffectEnabled(df::PostprocessRenderer::Antialiasing, true /* enabled */); return true; } if (query == "?no-aa" || query == "effect:no-antialiasing") { m_drapeEngine->SetPosteffectEnabled(df::PostprocessRenderer::Antialiasing, false /* enabled */); return true; } if (query == "?scheme") { m_transitManager.EnableTransitSchemeMode(true /* enable */); return true; } if (query == "?no-scheme") { m_transitManager.EnableTransitSchemeMode(false /* enable */); return true; } if (query == "?isolines") { m_isolinesManager.SetEnabled(true /* enable */); return true; } if (query == "?no-isolines") { m_isolinesManager.SetEnabled(false /* enable */); return true; } if (query == "?debug-info") { m_drapeEngine->ShowDebugInfo(true /* shown */); return true; } if (query == "?debug-info-always") { m_drapeEngine->ShowDebugInfo(true /* shown */); settings::Set(kShowDebugInfo, true); return true; } if (query == "?no-debug-info") { m_drapeEngine->ShowDebugInfo(false /* shown */); settings::Set(kShowDebugInfo, false); return true; } if (query == "?debug-rect") { m_drapeEngine->EnableDebugRectRendering(true /* shown */); return true; } if (query == "?no-debug-rect") { m_drapeEngine->EnableDebugRectRendering(false /* shown */); return true; } if (query == "?show-downloaded") { SetShowDownloadedRegions(true); return true; } if (query == "?no-show-downloaded") { SetShowDownloadedRegions(false); return true; } if (query == "?satellite") { m_drapeEngine->SetTileBackgroundMode(dp::BackgroundMode::Satellite, GetBackgroundTilesAreaOpacity() / 100.0f); return true; } if (query == "?no-satellite") { m_drapeEngine->SetTileBackgroundMode(dp::BackgroundMode::Default, GetBackgroundTilesAreaOpacity() / 100.0f); return true; } #if defined(OMIM_METAL_AVAILABLE) if (query == "?metal") { SavePreferredGraphicsAPI(dp::ApiVersion::Metal); return true; } #endif #if defined(OMIM_OS_ANDROID) if (query == "?vulkan") { SavePreferredGraphicsAPI(dp::ApiVersion::Vulkan); return true; } if (query == "?gl") { SavePreferredGraphicsAPI(dp::ApiVersion::OpenGLES3); return true; } #endif return false; } bool Framework::ParseEditorDebugCommand(search::SearchParams const & params) { if (params.m_query == "?edits") { osm::Editor::Stats stats = osm::Editor::Instance().GetStats(); search::Results results; results.AddResultNoChecks(search::Result("Uploaded: " + strings::to_string(stats.m_uploadedCount), "?edits")); for (auto & edit : stats.m_edits) { FeatureID const & fid = edit.first; FeaturesLoaderGuard 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 true; } search::Result res(feature::GetCenter(*ft), std::string(ft->GetReadableName())); res.SetAddress(std::move(edit.second)); res.FromFeature(fid, feature::TypesHolder(*ft).GetBestType(), 0, {}); results.AddResultNoChecks(std::move(res)); } params.m_onResults(results); results.SetEndMarker(false /* isCancelled */); params.m_onResults(results); return true; } else if (params.m_query == "?eclear") { osm::Editor::Instance().ClearAllLocalEdits(); return true; } return false; } bool Framework::ParseRoutingDebugCommand(search::SearchParams const & params) { if (params.m_query == "?debug-cam") { settings::Set(kDebugSpeedCamSetting, true); return true; } else if (params.m_query == "?no-debug-cam") { settings::Set(kDebugSpeedCamSetting, false); return true; } return false; } bool Framework::ParseDownloaderDebugCommand(search::SearchParams const & params) { char const kSetCommand[] = "?map-download-server:"; char const kStatusCommand[] = "?map-download-server"; char const kResetCommand[] = "?no-map-download-server"; if (params.m_query == kStatusCommand) { std::string serverUrl; if (m_storage.GetDebugMapDownloadServer(serverUrl)) EmitDebugCommandResult(params, "Map download server: " + serverUrl); else EmitDebugCommandResult(params, "Map download server: default"); return true; } bool const reset = params.m_query == kResetCommand; if (!reset && !params.m_query.starts_with(kSetCommand)) return false; // Both setting and resetting the server affect ongoing downloads. if (m_storage.IsDownloadInProgress()) { EmitDebugCommandResult(params, "Cancel active map downloads before changing the map download server."); return true; } if (reset) { m_storage.ResetDebugMapDownloadServer(); EmitDebugCommandResult(params, "Map download server reset to default."); } else { std::string normalizedUrl; if (m_storage.SetDebugMapDownloadServer(params.m_query.substr(sizeof(kSetCommand) - 1), normalizedUrl)) EmitDebugCommandResult(params, "Map download server: " + normalizedUrl); else EmitDebugCommandResult(params, "Invalid map download server URL. Use http:// or https:// without query."); } return true; } bool Framework::ParseAllTypesDebugCommand(search::SearchParams const & params) { if (params.m_query == "?all-types") { settings::Set(place_page::kDebugAllTypesSetting, true); return true; } else if (params.m_query == "?no-all-types") { settings::Set(place_page::kDebugAllTypesSetting, false); return true; } return false; } // Editable map object helper functions. namespace { bool LocalizeStreet(DataSource const & dataSource, FeatureID const & fid, osm::LocalizedStreet & result) { FeaturesLoaderGuard g(dataSource, fid.m_mwmId); auto ft = g.GetFeatureByIndex(fid.m_index); if (!ft) return false; result.m_defaultName = ft->GetDefaultName(); result.m_localizedName = ft->GetReadableName(); if (result.m_localizedName == result.m_defaultName) result.m_localizedName.clear(); return true; } std::vector TakeSomeStreetsAndLocalize( std::vector const & streets, DataSource const & dataSource) { std::vector results; // Exact feature street always goes first in Editor UI street list. // Reasonable number of different nearby street names to display in UI. constexpr size_t kMaxNumberOfNearbyStreetsToDisplay = 8; for (auto const & street : streets) { auto const isDuplicate = std::find_if(std::begin(results), std::end(results), [&street](osm::LocalizedStreet const & s) { return s.m_defaultName == street.m_name || s.m_localizedName == street.m_name; }) != results.end(); if (isDuplicate) continue; osm::LocalizedStreet ls; if (!LocalizeStreet(dataSource, street.m_id, ls)) continue; results.emplace_back(std::move(ls)); if (results.size() >= kMaxNumberOfNearbyStreetsToDisplay) break; } return results; } void SetStreet(search::ReverseGeocoder const & coder, DataSource const & dataSource, FeatureType & ft, osm::EditableMapObject & emo) { // Get exact feature's street address (if any) from mwm, // together with all nearby streets. auto const streets = coder.GetNearbyStreets(ft); std::string street = coder.GetFeatureStreetName(ft); auto localizedStreets = TakeSomeStreetsAndLocalize(streets, dataSource); if (!street.empty()) { auto it = std::find_if(std::begin(streets), std::end(streets), [&street](search::ReverseGeocoder::Street const & s) { return s.m_name == street; }); if (it != std::end(streets)) { osm::LocalizedStreet ls; if (!LocalizeStreet(dataSource, it->m_id, ls)) ls.m_defaultName = street; emo.SetStreet(ls); // A street that a feature belongs to should always be in the first place in the list. auto it = std::find_if(std::begin(localizedStreets), std::end(localizedStreets), [&ls](osm::LocalizedStreet const & rs) { return ls.m_defaultName == rs.m_defaultName; }); if (it != std::end(localizedStreets)) iter_swap(it, std::begin(localizedStreets)); else localizedStreets.insert(std::begin(localizedStreets), ls); } else { emo.SetStreet({street, ""}); } } else { emo.SetStreet({}); } emo.SetNearbyStreets(std::move(localizedStreets)); } void SetHostingBuildingAddress(FeatureID const & hostingBuildingFid, DataSource const & dataSource, search::ReverseGeocoder const & coder, osm::EditableMapObject & emo) { if (!hostingBuildingFid.IsValid()) return; FeaturesLoaderGuard g(dataSource, hostingBuildingFid.m_mwmId); auto hostingBuildingFeature = g.GetFeatureByIndex(hostingBuildingFid.m_index); if (!hostingBuildingFeature) return; search::ReverseGeocoder::Address address; if (coder.GetExactAddress(*hostingBuildingFeature, address)) { if (emo.GetHouseNumber().empty()) emo.SetHouseNumber(address.GetHouseNumber()); if (emo.GetStreet().m_defaultName.empty()) emo.SetStreet({std::string(address.GetStreetName()), std::string(address.m_street.m_name)}); } } } // namespace bool Framework::CanEditMapForPosition(m2::PointD const & position) const { return GetSelectionProcessor().CanEditMapForPosition(position); } bool Framework::CreateMapObject(m2::PointD const & mercator, uint32_t const featureType, osm::EditableMapObject & emo) const { emo = {}; auto const & dataSource = m_featuresFetcher.GetDataSource(); MwmSet::MwmId const mwmId = dataSource.GetMwmIdByCountryFile(platform::CountryFile(m_infoGetter->GetRegionCountryId(mercator))); if (!mwmId.IsAlive()) return false; search::ReverseGeocoder const coder(m_featuresFetcher.GetDataSource()); auto const streets = coder.GetNearbyStreets(mwmId, mercator); emo.SetNearbyStreets(TakeSomeStreetsAndLocalize(streets, m_featuresFetcher.GetDataSource())); // TODO(mgsergio): Check emo is a poi. For now it is the only option. SetHostingBuildingAddress(FindBuildingAtPoint(mercator), dataSource, coder, emo); return osm::Editor::Instance().CreatePoint(featureType, mercator, mwmId, emo); } bool Framework::GetEditableMapObject(FeatureID const & fid, osm::EditableMapObject & emo) const { if (!fid.IsValid()) return false; FeaturesLoaderGuard guard(m_featuresFetcher.GetDataSource(), fid.m_mwmId); auto ft = guard.GetFeatureByIndex(fid.m_index); if (!ft) return false; emo = {}; emo.SetFromFeatureType(*ft); if (HasPlacePageInfo()) { auto const & info = GetCurrentPlacePageInfo(); auto const & buildInfo = info.GetBuildInfo(); // In explicit feature selections (for example, tapping a road label), the place page keeps the // feature center. The original user tap is still the location that the note should report. if (info.GetID() == fid && buildInfo.m_source == place_page::BuildInfo::Source::User && info.GetGeomType() != feature::GeomType::Point) { emo.SetSelectionPoint(buildInfo.m_mercator); } } auto const & editor = osm::Editor::Instance(); emo.SetEditableProperties(editor.GetEditableProperties(*ft)); auto const & dataSource = m_featuresFetcher.GetDataSource(); search::ReverseGeocoder const coder(dataSource); SetStreet(coder, dataSource, *ft, emo); if (!ftypes::IsBuildingChecker::Instance()(*ft) && (emo.GetHouseNumber().empty() || emo.GetStreet().m_defaultName.empty())) { SetHostingBuildingAddress(FindBuildingAtPoint(feature::GetCenter(*ft)), dataSource, coder, emo); } auto optJournal = editor.GetEditedFeatureJournal(fid); if (optJournal) emo.SetJournal(std::move(*optJournal)); return true; } osm::Editor::SaveResult Framework::SaveEditedMapObject(osm::EditableMapObject emo) { auto & editor = osm::Editor::Instance(); // Update EditJournal osm::EditableMapObject unedited_emo; if (emo.GetEditingLifecycle() == osm::EditingLifecycle::CREATED && emo.GetJournal().GetJournal().size() == 1) unedited_emo = {}; else CHECK(GetEditableMapObject(emo.GetID(), unedited_emo), ("Loading unedited EditableMapObject failed.")); emo.LogDiffInJournal(unedited_emo); ms::LatLon issueLatLon; auto shouldNotify = false; // Notify if a poi address and it's hosting building address differ. do { auto const isCreatedFeature = editor.IsCreatedFeature(emo.GetID()); FeaturesLoaderGuard g(m_featuresFetcher.GetDataSource(), emo.GetID().m_mwmId); std::unique_ptr originalFeature; if (!isCreatedFeature) { originalFeature = g.GetOriginalFeatureByIndex(emo.GetID().m_index); if (!originalFeature) return osm::Editor::SaveResult::NoUnderlyingMapError; } else { originalFeature = FeatureType::CreateFromMapObject(emo); } // Handle only pois. if (ftypes::IsBuildingChecker::Instance()(*originalFeature)) break; auto const hostingBuildingFid = FindBuildingAtPoint(feature::GetCenter(*originalFeature)); // The is no building to take address from. Fallback to simple saving. if (!hostingBuildingFid.IsValid()) break; auto hostingBuildingFeature = g.GetFeatureByIndex(hostingBuildingFid.m_index); if (!hostingBuildingFeature) break; issueLatLon = mercator::ToLatLon(feature::GetCenter(*hostingBuildingFeature)); search::ReverseGeocoder::Address hostingBuildingAddress; search::ReverseGeocoder const coder(m_featuresFetcher.GetDataSource()); // The is no address to take from a hosting building. Fallback to simple saving. if (!coder.GetExactAddress(*hostingBuildingFeature, hostingBuildingAddress)) break; std::string originalFeatureStreet; if (!isCreatedFeature) originalFeatureStreet = coder.GetOriginalFeatureStreetName(originalFeature->GetID()); else originalFeatureStreet = emo.GetStreet().m_defaultName; auto isStreetOverridden = false; if (!hostingBuildingAddress.GetStreetName().empty() && emo.GetStreet().m_defaultName != hostingBuildingAddress.GetStreetName()) { isStreetOverridden = true; shouldNotify = true; } auto isHouseNumberOverridden = false; if (!hostingBuildingAddress.GetHouseNumber().empty() && emo.GetHouseNumber() != hostingBuildingAddress.GetHouseNumber()) { isHouseNumberOverridden = true; shouldNotify = true; } // TODO(mgsergio): Consider this: // User changed a feature that had no original address and the address he entered // is different from the one on the hosting building. He saved it and the changes // were uploaded to OSM. Then he set the address from the hosting building back // to the feature. As a result this address won't be merged in OSM because emo.SetStreet({}) // and emo.SetHouseNumber("") will be called in the following code. So OSM ends up // with incorrect data. // There is (almost) always a street and/or house number set in emo. We must keep them from // saving to editor and pushing to OSM if they ware not overidden. To be saved to editor // emo is first converted to FeatureType and FeatureType is then saved to a file and editor. // To keep street and house number from penetrating to FeatureType we set them to be empty. // Do not save street if it was taken from hosting building. if ((originalFeatureStreet.empty() || isCreatedFeature) && !isStreetOverridden) emo.SetStreet({}); // Do not save house number if it was taken from hosting building. if ((originalFeature->GetHouseNumber().empty() || isCreatedFeature) && !isHouseNumberOverridden) emo.SetHouseNumber(""); if (!isStreetOverridden && !isHouseNumberOverridden) { // Address was taken from the hosting building of a feature. Nothing to note. shouldNotify = false; break; } if (shouldNotify) { auto editedFeature = editor.GetEditedFeature(emo.GetID()); std::string editedFeatureStreet; // Such a notification have been already sent. I.e at least one of // street of house number should differ in emo and editor. shouldNotify = !isCreatedFeature && ((editedFeature && !editedFeature->GetHouseNumber().empty() && editedFeature->GetHouseNumber() != emo.GetHouseNumber()) || (editor.GetEditedFeatureStreet(emo.GetID(), editedFeatureStreet) && !editedFeatureStreet.empty() && editedFeatureStreet != emo.GetStreet().m_defaultName)); } } while (0); if (shouldNotify) { // TODO @mgsergio fill with correct NoteProblemType editor.CreateNote(emo.GetLatLon(), emo.GetID(), emo.GetTypes(), emo.GetDefaultName(), osm::Editor::NoteProblemType::General, "The address on this POI is different from the building address." " It is either a user's mistake, or an issue in the data. Please" " check this and fix if needed. (This note was created automatically" " without a user's input. Feel free to close it if it's wrong)."); } auto const result = osm::Editor::Instance().SaveEditedFeature(emo); place_page::BuildInfo info; info.m_mercator = emo.GetMercator(); info.m_featureId = emo.GetID(); m_currentPlacePageInfo = BuildPlacePageInfo(info); ActivateMapSelection(); return result; } void Framework::DeleteFeature(FeatureID const & fid) { osm::Editor::Instance().DeleteFeature(fid); UpdatePlacePageInfoForCurrentSelection(); } osm::NewFeatureCategories Framework::GetEditorCategories() const { return osm::Editor::Instance().GetNewFeatureCategories(); } bool Framework::RollBackChanges(FeatureID const & fid) { auto & editor = osm::Editor::Instance(); auto const status = editor.GetFeatureStatus(fid); auto const rolledBack = editor.RollBackChanges(fid); if (rolledBack) { if (status == FeatureStatus::Created) DeactivateMapSelection(); else UpdatePlacePageInfoForCurrentSelection(); } return rolledBack; } void Framework::CreateNote(osm::EditableMapObject const & mapObject, osm::Editor::NoteProblemType const type, std::string const & note) { auto const & selection = mapObject.GetSelectionPoint(); auto const noteLatLon = selection ? mercator::ToLatLon(*selection) : mapObject.GetLatLon(); osm::Editor::Instance().CreateNote(noteLatLon, mapObject.GetID(), mapObject.GetTypes(), mapObject.GetDefaultName(), type, note); if (type == osm::Editor::NoteProblemType::PlaceDoesNotExist) DeactivateMapSelection(); } void Framework::RunUITask(std::function fn) { GetPlatform().RunTask(Platform::Thread::Gui, std::move(fn)); } void Framework::ShowViewportSearchResults(SearchResultsIterT begin, SearchResultsIterT end, bool clear) { FillSearchResultsMarks(begin, end, clear); } void Framework::ClearViewportSearchResults() { m_searchMarks.ClearTrackedProperties(); GetBookmarkManager().GetEditSession().ClearGroup(UserMark::Type::SEARCH); } std::optional Framework::GetCurrentPosition() const { auto const & myPosMark = GetBookmarkManager().MyPositionMark(); if (!myPosMark.HasPosition()) return {}; return myPosMark.GetPivot(); } bool Framework::ParseSearchQueryCommand(search::SearchParams const & params) { if (ParseDrapeDebugCommand(params.m_query)) return true; if (ParseSetGpsTrackMinAccuracyCommand(params.m_query)) return true; if (ParseEditorDebugCommand(params)) return true; if (ParseRoutingDebugCommand(params)) return true; if (ParseDownloaderDebugCommand(params)) return true; if (ParseAllTypesDebugCommand(params)) return true; return false; } m2::PointD Framework::GetMinDistanceBetweenResults() const { return m_searchMarks.GetMaxDimension(m_currentModelView); } std::vector Framework::GetRegionsCountryIdByRect(m2::RectD const & rect, bool rough) const { return m_infoGetter->GetRegionsCountryIdByRect(rect, rough); } std::vector Framework::GetMwmsByRect(m2::RectD const & rect, bool rough) const { std::vector result; if (!m_infoGetter) return result; auto const & dataSource = m_featuresFetcher.GetDataSource(); auto countryIds = GetRegionsCountryIdByRect(rect, rough); for (auto & id : countryIds) result.push_back(dataSource.GetMwmIdByCountryFile(platform::CountryFile(std::move(id)))); return result; } // RoutingManager::Delegate void Framework::OnRouteFollow(routing::RouterType type) { bool const isPedestrianRoute = type == RouterType::Pedestrian; bool const enableAutoZoom = isPedestrianRoute ? false : LoadAutoZoom(); int const scale = isPedestrianRoute ? scales::GetPedestrianNavigationScale() : scales::GetNavigationScale(); int scale3d = isPedestrianRoute ? scales::GetPedestrianNavigation3dScale() : scales::GetNavigation3dScale(); if (enableAutoZoom) ++scale3d; bool const isBicycleRoute = type == RouterType::Bicycle; if ((isPedestrianRoute || isBicycleRoute) && LoadTrafficEnabled()) { m_trafficManager.SetEnabled(false /* enabled */); SaveTrafficEnabled(false /* enabled */); } // TODO. We need to sync two enums VehicleType and RouterType to be able to pass // GetRoutingSettings(type).m_matchRoute to the FollowRoute() instead of |isPedestrianRoute|. // |isArrowGlued| parameter fully corresponds to |m_matchRoute| in RoutingSettings. // For pedestrian and bicycle modes, use compass heading when stopped (isArrowGlued = false). m_drapeEngine->FollowRoute(scale, scale3d, enableAutoZoom, !(isPedestrianRoute || isBicycleRoute) /* isArrowGlued */); } // RoutingManager::Delegate void Framework::InitRouting() { m_routingManager.Init(routing::CreateNumMwmIds(m_storage)); LOG(LDEBUG, ("Routing initialized")); } void Framework::OnPowerFacilityChanged(power_management::Facility const facility, bool enabled) { if (facility == power_management::Facility::PerspectiveView || facility == power_management::Facility::Buildings3d) { bool allow3d = true, allow3dBuildings = true; Load3dMode(allow3d, allow3dBuildings); if (facility == power_management::Facility::PerspectiveView) allow3d = allow3d && enabled; else allow3dBuildings = allow3dBuildings && enabled; Allow3dMode(allow3d, allow3dBuildings); } else if (facility == power_management::Facility::TrafficJams) { auto trafficState = enabled && LoadTrafficEnabled(); if (trafficState == GetTrafficManager().IsEnabled()) return; GetTrafficManager().SetEnabled(trafficState); } } void Framework::OnPowerSchemeChanged(power_management::Scheme const actualScheme) { if (actualScheme == power_management::Scheme::EconomyMaximum && GetTrafficManager().IsEnabled()) GetTrafficManager().SetEnabled(false); } bool Framework::ShouldShowProducts() const { auto const connectionStatus = Platform::ConnectionStatus(); if (connectionStatus == Platform::EConnectionType::CONNECTION_NONE) return false; std::string donateUrl; if (!settings::Get(settings::kDonateUrl, donateUrl)) // donation is disabled return false; if (!m_usageStats.IsLoyalUser()) return false; if (!HasPlacePageInfo()) // happens after the POI is deleted via the editor return false; if (!storage::IsPointCoveredByDownloadedMaps(GetCurrentPlacePageInfo().GetMercator(), m_storage, *m_infoGetter)) return false; uint64_t popupCloseTime; std::string productCloseReason; if (!settings::Get(kPlacePageProductsPopupCloseTime, popupCloseTime) || !settings::Get(kPlacePageProductsPopupCloseReason, productCloseReason)) return true; // The popup was never closed. auto const now = base::SecondsSinceEpoch(); auto const timeout = GetTimeoutForReason(FromString(productCloseReason)); bool const timeoutExpired = popupCloseTime + timeout < now; if (timeoutExpired) return true; return false; } std::optional Framework::GetProductsConfiguration() const { if (!ShouldShowProducts()) return std::nullopt; return products::ProductsSettings::Instance().Get(); } void Framework::DidCloseProductsPopup(ProductsPopupCloseReason reason) const { auto const now = base::SecondsSinceEpoch(); settings::Set(kPlacePageProductsPopupCloseTime, now); settings::Set(kPlacePageProductsPopupCloseReason, ToString(reason)); // Users who say they have already donated shouldn't see the crowdfunding promo either. if (reason == ProductsPopupCloseReason::AlreadyDonated) settings::Set(kDonationTapTimeKey, now); } void Framework::DidSelectProduct(products::ProductsConfig::Product const & product) const { settings::Set(kPlacePageSelectedProduct, product.title); // Selecting a product opens the donation page, update the stats used by the crowdfunding promo. DidShowDonationPage(); } uint32_t Framework::GetTimeoutForReason(ProductsPopupCloseReason reason) { #ifdef DEBUG uint32_t constexpr kPopupCloseTimeout = 10; uint32_t constexpr kProductSelectTimeout = 20; uint32_t constexpr kRemindMeLaterTimeout = 5; #else uint32_t constexpr kPopupCloseTimeout = 60 * 60 * 24 * 30; // 30 days uint32_t constexpr kProductSelectTimeout = 60 * 60 * 24 * 180; // 180 days uint32_t constexpr kRemindMeLaterTimeout = 60 * 60 * 24 * 3; // 3 days #endif switch (reason) { case ProductsPopupCloseReason::Close: return kPopupCloseTimeout; case ProductsPopupCloseReason::RemindLater: return kRemindMeLaterTimeout; case ProductsPopupCloseReason::AlreadyDonated: return kProductSelectTimeout; case ProductsPopupCloseReason::SelectProduct: return kProductSelectTimeout; } ASSERT(false, ("Unknown reason")); return kPopupCloseTimeout; } std::string_view Framework::ToString(ProductsPopupCloseReason reason) { switch (reason) { case ProductsPopupCloseReason::Close: return kProductsPopupCloseReasonCloseStr; case ProductsPopupCloseReason::RemindLater: return kProductsPopupCloseReasonRemindLaterStr; case ProductsPopupCloseReason::AlreadyDonated: return kProductsPopupCloseReasonAlreadyDonatedStr; case ProductsPopupCloseReason::SelectProduct: return kProductsPopupCloseReasonSelectProductStr; } ASSERT(false, ("Unknown reason")); return kProductsPopupCloseReasonCloseStr; } Framework::ProductsPopupCloseReason Framework::FromString(std::string_view str) { if (str == kProductsPopupCloseReasonCloseStr) return ProductsPopupCloseReason::Close; if (str == kProductsPopupCloseReasonRemindLaterStr) return ProductsPopupCloseReason::RemindLater; if (str == kProductsPopupCloseReasonAlreadyDonatedStr) return ProductsPopupCloseReason::AlreadyDonated; if (str == kProductsPopupCloseReasonSelectProductStr) return ProductsPopupCloseReason::SelectProduct; ASSERT(false, ("Incorrect reason string:", str)); return ProductsPopupCloseReason::Close; } bool Framework::CanShowRateUsRequest() const { if (m_routingManager.IsRoutingActive()) return false; if (Platform::ConnectionStatus() == Platform::EConnectionType::CONNECTION_NONE) return false; if (!m_usageStats.IsLoyalUser()) return false; uint8_t constexpr kMinBatteryLevelPercent = 15; if (Platform::GetBatteryLevel() < kMinBatteryLevelPercent) return false; uint64_t lastAskedForRateUsTime; if (!settings::Get(kLastAskedForRateUsTimeKey, lastAskedForRateUsTime)) return true; uint32_t constexpr kLastAskedForRateUsTimeout = 60 * 60 * 24 * 90; // 90 days bool const timeoutExpired = lastAskedForRateUsTime + kLastAskedForRateUsTimeout < base::SecondsSinceEpoch(); if (!timeoutExpired) return false; return true; } void Framework::DidShowRateUsRequest() const { auto const now = base::SecondsSinceEpoch(); uint64_t firstAskedForRateUsTime; if (!settings::Get(kFirstAskedForRateUsTimeKey, firstAskedForRateUsTime)) settings::Set(kFirstAskedForRateUsTimeKey, now); settings::Set(kLastAskedForRateUsTimeKey, now); } std::string Framework::GetDonateUrl() const { std::string url; UNUSED_VALUE(settings::Get(settings::kDonateUrl, url)); if (url.ends_with("organicmaps.app/donate/")) return platform::GetLocalizedString("translated_om_site_url") + "donate/"; return url; } bool Framework::CanShowCrowdfundingPromo() const { auto const now = base::SecondsSinceEpoch(); if (now < kCrowdfundingStartTime || now > kCrowdfundingEndTime) return false; // Don't nag users who have already opened the donation page during this campaign. uint64_t lastDonationTapTime = 0; settings::TryGet(kDonationTapTimeKey, lastDonationTapTime); return lastDonationTapTime < kCrowdfundingStartTime; } void Framework::DidShowDonationPage() const { settings::Set(kDonationTapTimeKey, base::SecondsSinceEpoch()); uint32_t tapCount = 0; UNUSED_VALUE(settings::Get(kDonationTapCountKey, tapCount)); settings::Set(kDonationTapCountKey, tapCount + 1); } void Framework::ResetDonations() { LOG(LDEBUG, ("Donations data was reset to initial state.")); settings::Set(kDonationTapTimeKey, 0); settings::Set(kDonationTapCountKey, 0); }