From d12292fedcaf51b8c2ad005979c71284f5c01e8e Mon Sep 17 00:00:00 2001 From: dbf Date: Sun, 17 Apr 2022 21:07:31 +0300 Subject: [PATCH 01/21] Add ru-RU translation for Google play/F-droid Signed-off-by: dbf --- .../play/listings/ru-RU/full-description.txt | 51 +++++++++++++++++++ .../play/listings/ru-RU/short-description.txt | 1 + .../src/fdroid/play/listings/ru-RU/title.txt | 1 + 3 files changed, 53 insertions(+) create mode 100644 android/src/fdroid/play/listings/ru-RU/full-description.txt create mode 100644 android/src/fdroid/play/listings/ru-RU/short-description.txt create mode 100644 android/src/fdroid/play/listings/ru-RU/title.txt diff --git a/android/src/fdroid/play/listings/ru-RU/full-description.txt b/android/src/fdroid/play/listings/ru-RU/full-description.txt new file mode 100644 index 0000000000..c7ef689c07 --- /dev/null +++ b/android/src/fdroid/play/listings/ru-RU/full-description.txt @@ -0,0 +1,51 @@ +‣ Наше бесплатное приложение не отслеживает вас и не показывает рекламу. +‣ Оно постоянно улучшается нашей маленькой командой в наше свободное время, на наши собственные деньги и с помощью пожертвований/вклада наших пользователей +‣ Если на карте что-то отсутствует или есть ошибка, то исправьте это в OpenStreetMap и изменение появится в Organic Maps сл следующим обновлением. +‣ Если поиск или навигатор не работают, пожалуйста, напишите нам. Мы отвечаем на КАЖДОЕ письмо, и исправим проблему как можно скорее! + +Ваш отзыв и оценка в 5 звёзд — лучшая поддержка для нас! + +Основные функции: +• Бесплатно, с открытым исходным кодом, без слежки и рекламы +• Подробные оффлайн карты, во многих местах превосходящие Google maps, созданные сообществом OpenStreetMap +• Маршруты для велосипедистов, туристов и прогулок +• Профили высоты, вершины и склоны +• Turn-by-turn навигатор для прогулок, велосипедов и ЭКСПЕРИМЕНТАЛЬНАЯ навигация для машин с голосовыми подсказками +• Быстрый поиск без использования сети +• Поддержка закладок в формате KML/KMZ (GPX будут скоро добавлен) +• Тёмная тема, чтобы глазам было комфортнее + +У нас пока нет поддержки Android Auto, общественного транспорта, спутниковых снимков, и многих других функций. Но с вашей помощью, мы будем улучшать мир шаг за шагом. + +Organic Maps полностью органические, сделанные с любовью: + +• Невероятно быстро работают без использования сети +• С уважением относится к вашей конфиденциальности +• Сохраняют батарею +• Без неожиданных расходов на сотовую связь +• Простые в использовании, в наличие только самое необходимое + +Без отслеживания и подобных плохих вещей: + +• Без рекламы +• Без отслеживания +• Без сбора данных +• Без передачи данных разработчикам +• Без раздражающих регистраций +• Без обязательных самоучителей +• Без назойливого спама +• Без пуш-уведомлений +• Б̶е̶з̶ ̶п̶е̶с̶т̶и̶ц̶и̶д̶о̶в̶ полностью органические + +В Organic Maps мы верим, что конфиденциальность - это право каждого: + +• Organic Maps — это независимый проект с открытым исходным кодом, разрабатываемый сообществом +• Мы защищаем конфиденциальность от корпораций +• Будьте в безопасности, где бы вы ни были + +Отсутствие трекеров и минимальный набор разрешений, согласно Exodus Privacy Report. + +Посетите наш сайт organicmaps.app за дополнительной информацией или свяжитесь с нами в канале @OrganicMapsApp в Telegram. + +Сопротивляйтесь слежке — отстаивайте ваше свободу. +Попробуйте Organic Maps! \ No newline at end of file diff --git a/android/src/fdroid/play/listings/ru-RU/short-description.txt b/android/src/fdroid/play/listings/ru-RU/short-description.txt new file mode 100644 index 0000000000..8ff479b2a9 --- /dev/null +++ b/android/src/fdroid/play/listings/ru-RU/short-description.txt @@ -0,0 +1 @@ +Открытые, созданные сообществом, карты для путешественников, туристов и велосипедистов \ No newline at end of file diff --git a/android/src/fdroid/play/listings/ru-RU/title.txt b/android/src/fdroid/play/listings/ru-RU/title.txt new file mode 100644 index 0000000000..3cc6d8955d --- /dev/null +++ b/android/src/fdroid/play/listings/ru-RU/title.txt @@ -0,0 +1 @@ +Organic Maps — оффлайн карты \ No newline at end of file -- 2.45.3 From 03e4c1b9835ccf04a972a6cd5db8d271ecbb587d Mon Sep 17 00:00:00 2001 From: dbf Date: Sun, 17 Apr 2022 21:11:40 +0300 Subject: [PATCH 02/21] Add ru-RU translation for Google play/F-droid Signed-off-by: dbf --- android/src/fdroid/play/listings/ru-RU/full-description.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/src/fdroid/play/listings/ru-RU/full-description.txt b/android/src/fdroid/play/listings/ru-RU/full-description.txt index c7ef689c07..5f2da5d83e 100644 --- a/android/src/fdroid/play/listings/ru-RU/full-description.txt +++ b/android/src/fdroid/play/listings/ru-RU/full-description.txt @@ -1,6 +1,6 @@ ‣ Наше бесплатное приложение не отслеживает вас и не показывает рекламу. ‣ Оно постоянно улучшается нашей маленькой командой в наше свободное время, на наши собственные деньги и с помощью пожертвований/вклада наших пользователей -‣ Если на карте что-то отсутствует или есть ошибка, то исправьте это в OpenStreetMap и изменение появится в Organic Maps сл следующим обновлением. +‣ Если на карте что-то отсутствует или есть ошибка, то исправьте это в OpenStreetMap и изменение появится в Organic Maps со следующим обновлением. ‣ Если поиск или навигатор не работают, пожалуйста, напишите нам. Мы отвечаем на КАЖДОЕ письмо, и исправим проблему как можно скорее! Ваш отзыв и оценка в 5 звёзд — лучшая поддержка для нас! -- 2.45.3 From 2dc3b35183037a9bb3bf2d0b4065847369a5dd94 Mon Sep 17 00:00:00 2001 From: dbf Date: Sun, 17 Apr 2022 21:17:44 +0300 Subject: [PATCH 03/21] Add ru-RU translation for Google play/F-droid - fix typo Signed-off-by: dbf --- .../play/listings/ru-RU/full-description.txt | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/android/src/fdroid/play/listings/ru-RU/full-description.txt b/android/src/fdroid/play/listings/ru-RU/full-description.txt index 5f2da5d83e..e872d31a9e 100644 --- a/android/src/fdroid/play/listings/ru-RU/full-description.txt +++ b/android/src/fdroid/play/listings/ru-RU/full-description.txt @@ -1,7 +1,7 @@ ‣ Наше бесплатное приложение не отслеживает вас и не показывает рекламу. ‣ Оно постоянно улучшается нашей маленькой командой в наше свободное время, на наши собственные деньги и с помощью пожертвований/вклада наших пользователей -‣ Если на карте что-то отсутствует или есть ошибка, то исправьте это в OpenStreetMap и изменение появится в Organic Maps со следующим обновлением. -‣ Если поиск или навигатор не работают, пожалуйста, напишите нам. Мы отвечаем на КАЖДОЕ письмо, и исправим проблему как можно скорее! +‣ Если на карте что-то отсутствует или есть ошибка, то исправьте это в OpenStreetMap и изменение появится в Organic Maps со следующим обновлением +‣ Если поиск или навигатор работают неправильно, пожалуйста, напишите нам. Мы отвечаем на КАЖДОЕ письмо и исправим проблему как можно скорее! Ваш отзыв и оценка в 5 звёзд — лучшая поддержка для нас! @@ -12,32 +12,32 @@ • Профили высоты, вершины и склоны • Turn-by-turn навигатор для прогулок, велосипедов и ЭКСПЕРИМЕНТАЛЬНАЯ навигация для машин с голосовыми подсказками • Быстрый поиск без использования сети -• Поддержка закладок в формате KML/KMZ (GPX будут скоро добавлен) +• Поддержка закладок в формате KML/KMZ (GPX будет скоро добавлен) • Тёмная тема, чтобы глазам было комфортнее -У нас пока нет поддержки Android Auto, общественного транспорта, спутниковых снимков, и многих других функций. Но с вашей помощью, мы будем улучшать мир шаг за шагом. +У нас пока нет поддержки Android Auto, общественного транспорта, спутниковых снимков и многих других функций. Но с вашей помощью мы будем улучшать мир шаг за шагом. -Organic Maps полностью органические, сделанные с любовью: +Organic Maps — полностью органические, сделанные с любовью: • Невероятно быстро работают без использования сети -• С уважением относится к вашей конфиденциальности -• Сохраняют батарею -• Без неожиданных расходов на сотовую связь +• С уважением относятся к вашей конфиденциальности +• Экономят заряд батареи +• Без непредвиденных расходов на сотовую связь • Простые в использовании, в наличие только самое необходимое -Без отслеживания и подобных плохих вещей: +Без отслеживания и подобных недостатков: • Без рекламы • Без отслеживания • Без сбора данных • Без передачи данных разработчикам • Без раздражающих регистраций -• Без обязательных самоучителей +• Без обязательного инструктажа • Без назойливого спама • Без пуш-уведомлений • Б̶е̶з̶ ̶п̶е̶с̶т̶и̶ц̶и̶д̶о̶в̶ полностью органические -В Organic Maps мы верим, что конфиденциальность - это право каждого: +В Organic Maps мы верим, что конфиденциальность — это право каждого: • Organic Maps — это независимый проект с открытым исходным кодом, разрабатываемый сообществом • Мы защищаем конфиденциальность от корпораций @@ -47,5 +47,5 @@ Organic Maps полностью органические, сделанные Посетите наш сайт organicmaps.app за дополнительной информацией или свяжитесь с нами в канале @OrganicMapsApp в Telegram. -Сопротивляйтесь слежке — отстаивайте ваше свободу. +Сопротивляйтесь слежке — отстаивайте вашу свободу. Попробуйте Organic Maps! \ No newline at end of file -- 2.45.3 From f6fd827aeb61647d2b1c725ddd36368769deec99 Mon Sep 17 00:00:00 2001 From: dbf Date: Sun, 17 Apr 2022 21:22:21 +0300 Subject: [PATCH 04/21] Add ru-RU translation for Google play/F-droid - fix metadata Signed-off-by: dbf --- android/src/fdroid/play/listings/ru-RU/full-description.txt | 2 +- android/src/fdroid/play/listings/ru-RU/short-description.txt | 2 +- android/src/fdroid/play/listings/ru-RU/title.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/android/src/fdroid/play/listings/ru-RU/full-description.txt b/android/src/fdroid/play/listings/ru-RU/full-description.txt index e872d31a9e..73edf8288b 100644 --- a/android/src/fdroid/play/listings/ru-RU/full-description.txt +++ b/android/src/fdroid/play/listings/ru-RU/full-description.txt @@ -48,4 +48,4 @@ Organic Maps — полностью органические, сделанн Посетите наш сайт organicmaps.app за дополнительной информацией или свяжитесь с нами в канале @OrganicMapsApp в Telegram. Сопротивляйтесь слежке — отстаивайте вашу свободу. -Попробуйте Organic Maps! \ No newline at end of file +Попробуйте Organic Maps! diff --git a/android/src/fdroid/play/listings/ru-RU/short-description.txt b/android/src/fdroid/play/listings/ru-RU/short-description.txt index 8ff479b2a9..ea5c44dd1b 100644 --- a/android/src/fdroid/play/listings/ru-RU/short-description.txt +++ b/android/src/fdroid/play/listings/ru-RU/short-description.txt @@ -1 +1 @@ -Открытые, созданные сообществом, карты для путешественников, туристов и велосипедистов \ No newline at end of file +Открытые карты от сообщества для путешественников, туристов и велосипедистов diff --git a/android/src/fdroid/play/listings/ru-RU/title.txt b/android/src/fdroid/play/listings/ru-RU/title.txt index 3cc6d8955d..9c7f02a907 100644 --- a/android/src/fdroid/play/listings/ru-RU/title.txt +++ b/android/src/fdroid/play/listings/ru-RU/title.txt @@ -1 +1 @@ -Organic Maps — оффлайн карты \ No newline at end of file +Organic Maps — оффлайн карты -- 2.45.3 From a91a8a06f75a6936a922d475d881ec02ef6954b1 Mon Sep 17 00:00:00 2001 From: Alexander Borsuk Date: Fri, 15 Apr 2022 12:32:52 +0200 Subject: [PATCH 05/21] Replaced WARN_UNUSED_RESULT macro with [[nodiscard]] C++11 attribute Signed-off-by: Alexander Borsuk --- base/macros.hpp | 6 ----- base/string_utils.hpp | 49 +++++++++++++++++------------------ coding/map_uint32_to_val.hpp | 4 +-- indexer/centers_table.hpp | 2 +- indexer/metadata_serdes.hpp | 4 +-- indexer/postcodes.hpp | 2 +- map/framework.cpp | 2 +- platform/platform.hpp | 7 +++-- platform/settings.hpp | 4 +-- search/geocoder.cpp | 2 +- search/geocoder.hpp | 3 +-- search/lazy_centers_table.hpp | 2 +- search/mwm_context.hpp | 2 +- 13 files changed, 40 insertions(+), 49 deletions(-) diff --git a/base/macros.hpp b/base/macros.hpp index 7fc946a0c5..7f51813381 100644 --- a/base/macros.hpp +++ b/base/macros.hpp @@ -79,9 +79,3 @@ inline void ForceUseValue(T const & t) #define UINT64_HI(x) (static_cast(x >> 32)) #define NOTIMPLEMENTED() ASSERT(false, ("Function", __func__, "is not implemented!")); - -#if defined(__GNUC__) -#define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) -#else -#define WARN_UNUSED_RESULT -#endif // defined(__GNUC__) diff --git a/base/string_utils.hpp b/base/string_utils.hpp index 66d09c4674..f1ac4fb325 100644 --- a/base/string_utils.hpp +++ b/base/string_utils.hpp @@ -2,7 +2,6 @@ #include "base/buffer_vector.hpp" #include "base/checked_cast.hpp" -#include "base/macros.hpp" #include "base/stl_helpers.hpp" #include @@ -414,12 +413,12 @@ bool ToInteger(char const * start, T & result, int base = 10) } } // namespace internal -WARN_UNUSED_RESULT inline bool to_int(char const * s, int & i, int base = 10) +[[nodiscard]] inline bool to_int(char const * s, int & i, int base = 10) { return internal::ToInteger(s, i, base); } -WARN_UNUSED_RESULT inline bool to_uint(char const * s, unsigned int & i, int base = 10) +[[nodiscard]] inline bool to_uint(char const * s, unsigned int & i, int base = 10) { return internal::ToInteger(s, i, base); } @@ -433,12 +432,12 @@ WARN_UNUSED_RESULT inline bool to_uint(char const * s, unsigned int & i, int bas // negative std::numeric_limits::max() converts to 1. // Values lower than negative std::numeric_limits::max() // are not convertible (method returns false). -WARN_UNUSED_RESULT inline bool to_uint64(char const * s, uint64_t & i, int base = 10) +[[nodiscard]] inline bool to_uint64(char const * s, uint64_t & i, int base = 10) { return internal::ToInteger(s, i, base); } -WARN_UNUSED_RESULT inline bool to_int64(char const * s, int64_t & i) +[[nodiscard]] inline bool to_int64(char const * s, int64_t & i) { return internal::ToInteger(s, i); } @@ -449,64 +448,64 @@ WARN_UNUSED_RESULT inline bool to_int64(char const * s, int64_t & i) // conversions may differ between platforms. // Converting strings representing negative numbers to unsigned integers looks like a bad // idea anyway and it's not worth changing the implementation solely for this reason. -WARN_UNUSED_RESULT inline bool to_uint32(char const * s, uint32_t & i, int base = 10) +[[nodiscard]] inline bool to_uint32(char const * s, uint32_t & i, int base = 10) { return internal::ToInteger(s, i, base); } -WARN_UNUSED_RESULT inline bool to_int32(char const * s, int32_t & i) +[[nodiscard]] inline bool to_int32(char const * s, int32_t & i) { return internal::ToInteger(s, i); } -WARN_UNUSED_RESULT bool to_size_t(char const * s, size_t & i, int base = 10); +[[nodiscard]] bool to_size_t(char const * s, size_t & i, int base = 10); // Both functions return false for INF, NAN, numbers like "1." and "0.4 ". -WARN_UNUSED_RESULT bool to_float(char const * s, float & f); -WARN_UNUSED_RESULT bool to_double(char const * s, double & d); -WARN_UNUSED_RESULT bool is_finite(double d); +[[nodiscard]] bool to_float(char const * s, float & f); +[[nodiscard]] bool to_double(char const * s, double & d); +[[nodiscard]] bool is_finite(double d); -WARN_UNUSED_RESULT inline bool is_number(std::string const & s) +[[nodiscard]] inline bool is_number(std::string const & s) { uint64_t dummy; return to_uint64(s.c_str(), dummy); } -WARN_UNUSED_RESULT inline bool to_int(std::string const & s, int & i, int base = 10) +[[nodiscard]] inline bool to_int(std::string const & s, int & i, int base = 10) { return to_int(s.c_str(), i, base); } -WARN_UNUSED_RESULT inline bool to_uint(std::string const & s, unsigned int & i, int base = 10) +[[nodiscard]] inline bool to_uint(std::string const & s, unsigned int & i, int base = 10) { return to_uint(s.c_str(), i, base); } // Note: negative values will be converted too. // For ex. "-1" converts to uint64_t max value. -WARN_UNUSED_RESULT inline bool to_uint64(std::string const & s, uint64_t & i, int base = 10) +[[nodiscard]] inline bool to_uint64(std::string const & s, uint64_t & i, int base = 10) { return to_uint64(s.c_str(), i, base); } -WARN_UNUSED_RESULT inline bool to_int64(std::string const & s, int64_t & i) +[[nodiscard]] inline bool to_int64(std::string const & s, int64_t & i) { return to_int64(s.c_str(), i); } -WARN_UNUSED_RESULT inline bool to_uint32(std::string const & s, uint32_t & i, int base = 10) +[[nodiscard]] inline bool to_uint32(std::string const & s, uint32_t & i, int base = 10) { return to_uint32(s.c_str(), i, base); } -WARN_UNUSED_RESULT inline bool to_int32(std::string const & s, int32_t & i) +[[nodiscard]] inline bool to_int32(std::string const & s, int32_t & i) { return to_int32(s.c_str(), i); } -WARN_UNUSED_RESULT inline bool to_size_t(std::string const & s, size_t & i) +[[nodiscard]] inline bool to_size_t(std::string const & s, size_t & i) { return to_size_t(s.c_str(), i); } -WARN_UNUSED_RESULT inline bool to_float(std::string const & s, float & f) +[[nodiscard]] inline bool to_float(std::string const & s, float & f) { return to_float(s.c_str(), f); } -WARN_UNUSED_RESULT inline bool to_double(std::string const & s, double & d) +[[nodiscard]] inline bool to_double(std::string const & s, double & d) { return to_double(s.c_str(), d); } @@ -555,14 +554,14 @@ std::string to_string(T t) } template ::value>> -WARN_UNUSED_RESULT inline bool to_any(std::string const & s, T & i) +[[nodiscard]] inline bool to_any(std::string const & s, T & i) { return internal::ToInteger(s.c_str(), i); } -WARN_UNUSED_RESULT inline bool to_any(std::string const & s, float & f) { return to_float(s, f); } -WARN_UNUSED_RESULT inline bool to_any(std::string const & s, double & d) { return to_double(s, d); } -WARN_UNUSED_RESULT inline bool to_any(std::string const & s, std::string & result) +[[nodiscard]] inline bool to_any(std::string const & s, float & f) { return to_float(s, f); } +[[nodiscard]] inline bool to_any(std::string const & s, double & d) { return to_double(s, d); } +[[nodiscard]] inline bool to_any(std::string const & s, std::string & result) { result = s; return true; diff --git a/coding/map_uint32_to_val.hpp b/coding/map_uint32_to_val.hpp index c89d817dca..960290d452 100644 --- a/coding/map_uint32_to_val.hpp +++ b/coding/map_uint32_to_val.hpp @@ -154,7 +154,7 @@ public: // Tries to get |value| for key identified by |id|. Returns // false if table does not have entry for this id. - WARN_UNUSED_RESULT bool Get(uint32_t id, Value & value) + [[nodiscard]] bool Get(uint32_t id, Value & value) { if (id >= m_ids.size() || !m_ids[id]) return false; @@ -173,7 +173,7 @@ public: // Tries to get |value| for key identified by |id|. Returns // false if table does not have entry for this id. - WARN_UNUSED_RESULT bool GetThreadsafe(uint32_t id, Value & value) const + [[nodiscard]] bool GetThreadsafe(uint32_t id, Value & value) const { if (id >= m_ids.size() || !m_ids[id]) return false; diff --git a/indexer/centers_table.hpp b/indexer/centers_table.hpp index b69c8f04a4..841d99ff62 100644 --- a/indexer/centers_table.hpp +++ b/indexer/centers_table.hpp @@ -52,7 +52,7 @@ public: // Tries to get |center| of the feature identified by |id|. Returns // false if table does not have entry for the feature. - WARN_UNUSED_RESULT bool Get(uint32_t id, m2::PointD & center); + [[nodiscard]] bool Get(uint32_t id, m2::PointD & center); uint64_t Count() const { return m_map->Count(); }; diff --git a/indexer/metadata_serdes.hpp b/indexer/metadata_serdes.hpp index 3cef262b44..e8aa07bd90 100644 --- a/indexer/metadata_serdes.hpp +++ b/indexer/metadata_serdes.hpp @@ -64,12 +64,12 @@ public: // Tries to get metadata of the feature with id |featureId|. Returns false if table // does not have entry for the feature. // This method is threadsafe. - WARN_UNUSED_RESULT bool Get(uint32_t featureId, feature::MetadataBase & meta); + [[nodiscard]] bool Get(uint32_t featureId, feature::MetadataBase & meta); // Tries to get string ids for metagata of the feature with id |featureId|. Returns false // if table does not have entry for the feature. // This method is threadsafe. - WARN_UNUSED_RESULT bool GetIds(uint32_t featureId, MetaIds & metaIds) const; + [[nodiscard]] bool GetIds(uint32_t featureId, MetaIds & metaIds) const; // Gets single metadata string from text storage. This method is threadsafe. std::string GetMetaById(uint32_t id); diff --git a/indexer/postcodes.hpp b/indexer/postcodes.hpp index 5c078ceaf3..993f043c3b 100644 --- a/indexer/postcodes.hpp +++ b/indexer/postcodes.hpp @@ -41,7 +41,7 @@ public: // Tries to get |postcode| of the feature with id |featureId|. Returns false if table // does not have entry for the feature. - WARN_UNUSED_RESULT bool Get(uint32_t featureId, std::string & postcode); + [[nodiscard]] bool Get(uint32_t featureId, std::string & postcode); private: using Map = MapUint32ToValue; diff --git a/map/framework.cpp b/map/framework.cpp index 6d16763cb6..763b2ccf61 100644 --- a/map/framework.cpp +++ b/map/framework.cpp @@ -2755,7 +2755,7 @@ bool Framework::ParseRoutingDebugCommand(search::SearchParams const & params) namespace { -WARN_UNUSED_RESULT bool LocalizeStreet(DataSource const & dataSource, FeatureID const & fid, +[[nodiscard]] bool LocalizeStreet(DataSource const & dataSource, FeatureID const & fid, osm::LocalizedStreet & result) { FeaturesLoaderGuard g(dataSource, fid.m_mwmId); diff --git a/platform/platform.hpp b/platform/platform.hpp index b4af4d0a00..8afb79efa4 100644 --- a/platform/platform.hpp +++ b/platform/platform.hpp @@ -9,7 +9,6 @@ #include "base/assert.hpp" #include "base/exception.hpp" -#include "base/macros.hpp" #include "base/task_loop.hpp" #include "base/thread_pool_delayed.hpp" @@ -155,11 +154,11 @@ public: void SetResourceDir(std::string const & path); /// Creates the directory in the filesystem. - WARN_UNUSED_RESULT static EError MkDir(std::string const & dirName); + [[nodiscard]] static EError MkDir(std::string const & dirName); /// Creates the directory. Returns true on success. /// Returns false and logs the reason on failure. - WARN_UNUSED_RESULT static bool MkDirChecked(std::string const & dirName); + [[nodiscard]] static bool MkDirChecked(std::string const & dirName); // Creates the directory path dirName. // The function will create all parent directories necessary to create the directory. @@ -167,7 +166,7 @@ public: // If the path already exists when this function is called, it will return true. // If it was possible to create only a part of the directories, the function will returns false // and will not restore the previous state of the file system. - WARN_UNUSED_RESULT static bool MkDirRecursively(std::string const & dirName); + [[nodiscard]] static bool MkDirRecursively(std::string const & dirName); /// Removes empty directory from the filesystem. static EError RmDir(std::string const & dirName); diff --git a/platform/settings.hpp b/platform/settings.hpp index 42ca00da0c..2ff9a6c10a 100644 --- a/platform/settings.hpp +++ b/platform/settings.hpp @@ -31,7 +31,7 @@ private: /// Retrieve setting /// @return false if setting is absent template -WARN_UNUSED_RESULT bool Get(std::string const & key, Value & outValue) +[[nodiscard]] bool Get(std::string const & key, Value & outValue) { std::string strVal; return StringStorage::Instance().GetValue(key, strVal) && FromString(strVal, outValue); @@ -71,7 +71,7 @@ public: } template - WARN_UNUSED_RESULT static bool Get(std::string const & key, Value & outValue) + [[nodiscard]] static bool Get(std::string const & key, Value & outValue) { std::string strVal; return Instance().GetValue(key, strVal) && settings::FromString(strVal, outValue); diff --git a/search/geocoder.cpp b/search/geocoder.cpp index d8d47803e5..31f691ffe1 100644 --- a/search/geocoder.cpp +++ b/search/geocoder.cpp @@ -233,7 +233,7 @@ void JoinQueryTokens(QueryParams const & params, TokenRange const & range, UniSt } /// @todo Can't change on string_view now, because of unordered_map Affiliations. -WARN_UNUSED_RESULT bool GetAffiliationName(FeatureType & ft, string & affiliation) +[[nodiscard]] bool GetAffiliationName(FeatureType & ft, string & affiliation) { string_view name = ft.GetName(StringUtf8Multilang::kDefaultCode); if (name.empty()) diff --git a/search/geocoder.hpp b/search/geocoder.hpp index 4cebc67e1e..fb88d6b09a 100644 --- a/search/geocoder.hpp +++ b/search/geocoder.hpp @@ -35,7 +35,6 @@ #include "base/cancellable.hpp" #include "base/dfa_helpers.hpp" #include "base/levenshtein_dfa.hpp" -#include "base/macros.hpp" #include "base/string_utils.hpp" #include @@ -291,7 +290,7 @@ private: // This is a faster wrapper around SearchModel::GetSearchType(), as // it uses pre-loaded lists of streets and villages. - WARN_UNUSED_RESULT bool GetTypeInGeocoding(BaseContext const & ctx, uint32_t featureId, + [[nodiscard]] bool GetTypeInGeocoding(BaseContext const & ctx, uint32_t featureId, Model::Type & type); ExtendedMwmInfos::ExtendedMwmInfo GetExtendedMwmInfo( diff --git a/search/lazy_centers_table.hpp b/search/lazy_centers_table.hpp index 53dffbeb95..ee79f34ffe 100644 --- a/search/lazy_centers_table.hpp +++ b/search/lazy_centers_table.hpp @@ -29,7 +29,7 @@ public: void EnsureTableLoaded(); - WARN_UNUSED_RESULT bool Get(uint32_t id, m2::PointD & center); + [[nodiscard]] bool Get(uint32_t id, m2::PointD & center); private: MwmValue const & m_value; diff --git a/search/mwm_context.hpp b/search/mwm_context.hpp index bbc85a5ea4..fdcc6a1450 100644 --- a/search/mwm_context.hpp +++ b/search/mwm_context.hpp @@ -98,7 +98,7 @@ public: // Returns false if feature was deleted by user. std::unique_ptr GetFeature(uint32_t index) const; - WARN_UNUSED_RESULT inline bool GetCenter(uint32_t index, m2::PointD & center) + [[nodiscard]] inline bool GetCenter(uint32_t index, m2::PointD & center) { return m_centers.Get(index, center); } -- 2.45.3 From 6fba6e4b0fb16ff2fdac8383e5f08e14ff5253f5 Mon Sep 17 00:00:00 2001 From: Alexander Borsuk Date: Sat, 16 Apr 2022 21:48:34 +0200 Subject: [PATCH 06/21] Minor fixes Signed-off-by: Alexander Borsuk --- base/base_tests/fifo_cache_test.cpp | 7 +++++++ base/fifo_cache.hpp | 7 +++++++ drape/overlay_tree.cpp | 3 +-- editor/feature_matcher.cpp | 2 +- editor/osm_editor.cpp | 7 ++++--- .../cross_mwm_osm_ways_collector_tests.cpp | 8 ++++++-- generator/intermediate_data.cpp | 2 +- iphone/Maps/Core/Editor/MWMEditorHelper.mm | 2 +- testing/testing.hpp | 2 +- tracking/archive.hpp | 7 +++++++ tracking/connection.hpp | 7 +++++++ tracking/protocol.hpp | 7 +++++++ tracking/reporter.hpp | 7 +++++++ traffic/traffic_tests/traffic_info_test.cpp | 2 +- 14 files changed, 58 insertions(+), 12 deletions(-) diff --git a/base/base_tests/fifo_cache_test.cpp b/base/base_tests/fifo_cache_test.cpp index 554e4e9b8a..b8747af6fd 100644 --- a/base/base_tests/fifo_cache_test.cpp +++ b/base/base_tests/fifo_cache_test.cpp @@ -6,7 +6,14 @@ #include #include +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-copy" +#endif #include +#ifdef __clang__ +#pragma clang diagnostic pop +#endif using namespace std; diff --git a/base/fifo_cache.hpp b/base/fifo_cache.hpp index 3ebfe48a81..b89fd5dc06 100644 --- a/base/fifo_cache.hpp +++ b/base/fifo_cache.hpp @@ -6,7 +6,14 @@ #include #include +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-copy" +#endif #include +#ifdef __clang__ +#pragma clang diagnostic pop +#endif template> class FifoCache diff --git a/drape/overlay_tree.cpp b/drape/overlay_tree.cpp index f5f87264da..a14d1a9f61 100644 --- a/drape/overlay_tree.cpp +++ b/drape/overlay_tree.cpp @@ -500,8 +500,7 @@ void OverlayTree::Select(m2::RectD const & rect, TOverlayContainer & result) con ScreenBase screen = GetModelView(); ForEachInRect(rect, [&](ref_ptr const & h) { - auto const & overlayId = h->GetOverlayID(); - ASSERT(overlayId.IsValid(), ()); + ASSERT(h->GetOverlayID().IsValid(), ()); if (!h->HasLinearFeatureShape() && h->IsVisible()) { diff --git a/editor/feature_matcher.cpp b/editor/feature_matcher.cpp index 990a9237b8..cc37be65aa 100644 --- a/editor/feature_matcher.cpp +++ b/editor/feature_matcher.cpp @@ -306,6 +306,6 @@ double ScoreTriangulatedGeometriesByPoints(vector const & lhs, return p1 < p2 && !p1.EqualDxDy(p2, mercator::kPointEqualityEps); }).GetCount(); - return static_cast(matched) / lhs.size(); + return static_cast(matched) / static_cast(lhs.size()); } } // namespace matcher diff --git a/editor/osm_editor.cpp b/editor/osm_editor.cpp index 97824173f2..e95a1d3a35 100644 --- a/editor/osm_editor.cpp +++ b/editor/osm_editor.cpp @@ -307,7 +307,7 @@ void Editor::ClearAllLocalEdits() Invalidate(); } -void Editor::OnMapRegistered(platform::LocalCountryFile const & localFile) +void Editor::OnMapRegistered(platform::LocalCountryFile const &) { // todo(@a, @m) Reloading edits only for |localFile| should be enough. LoadEdits(); @@ -670,10 +670,11 @@ void Editor::UploadChanges(string const & key, string const & secret, ChangesetT try { auto const center = fti.m_object.GetMercator(); - + // Throws, see catch below. XMLFeature osmFeature = changeset.GetMatchingNodeFeatureFromOSM(center); + // If we are here, it means that object already exists at the given point. - // To avoid nodes duplication, merge and apply changes to it instead of creating an new one. + // To avoid nodes duplication, merge and apply changes to it instead of creating a new one. XMLFeature const osmFeatureCopy = osmFeature; osmFeature.ApplyPatch(feature); // Check to avoid uploading duplicates into OSM. diff --git a/generator/generator_tests/cross_mwm_osm_ways_collector_tests.cpp b/generator/generator_tests/cross_mwm_osm_ways_collector_tests.cpp index d4b5f80dd8..9a09856661 100644 --- a/generator/generator_tests/cross_mwm_osm_ways_collector_tests.cpp +++ b/generator/generator_tests/cross_mwm_osm_ways_collector_tests.cpp @@ -14,7 +14,6 @@ #include "geometry/mercator.hpp" #include "base/assert.hpp" -#include "base/macros.hpp" #include "base/scope_guard.hpp" #include @@ -48,7 +47,12 @@ public: m_targetDir = GetPlatform().WritableDir(); auto const & intermediateDir = base::JoinPath(m_targetDir, kTmpDirName); - UNUSED_VALUE(Platform::MkDir(intermediateDir)); + if (auto const ret = Platform::MkDir(intermediateDir); + ret != Platform::EError::ERR_OK && + ret != Platform::EError::ERR_FILE_ALREADY_EXISTS) + { + MYTHROW(FileSystemException, ("Can't create intermediateDir", intermediateDir)); + } m_intermediateDir = intermediateDir; } diff --git a/generator/intermediate_data.cpp b/generator/intermediate_data.cpp index 19db5f1977..96b11ffca4 100644 --- a/generator/intermediate_data.cpp +++ b/generator/intermediate_data.cpp @@ -157,7 +157,7 @@ public: { } - ~RawMemPointStorageWriter() + ~RawMemPointStorageWriter() override { m_fileWriter.Write(m_data.data(), m_data.size() * sizeof(LatLon)); } diff --git a/iphone/Maps/Core/Editor/MWMEditorHelper.mm b/iphone/Maps/Core/Editor/MWMEditorHelper.mm index 29fa71700d..e49bd47467 100644 --- a/iphone/Maps/Core/Editor/MWMEditorHelper.mm +++ b/iphone/Maps/Core/Editor/MWMEditorHelper.mm @@ -33,7 +33,7 @@ osm::Editor::Instance().UploadChanges( keySecret.first, keySecret.second, {{"created_by", - std::string("OMaps " OMIM_OS_NAME " ") + AppInfo.sharedInfo.bundleVersion.UTF8String}, + std::string("Organic Maps " OMIM_OS_NAME " ") + AppInfo.sharedInfo.bundleVersion.UTF8String}, {"bundle_id", NSBundle.mainBundle.bundleIdentifier.UTF8String}}, lambda); } diff --git a/testing/testing.hpp b/testing/testing.hpp index dd7265f6f8..1674568225 100644 --- a/testing/testing.hpp +++ b/testing/testing.hpp @@ -31,7 +31,7 @@ DECLARE_EXCEPTION(TestFailureException, RootException); namespace base { -inline void OnTestFailed(SrcPoint const & srcPoint, std::string const & msg) +[[noreturn]] inline void OnTestFailed(SrcPoint const & srcPoint, std::string const & msg) { LOG(LINFO, ("FAILED")); LOG(LINFO, (::DebugPrint(srcPoint.FileName()) + ":" + ::DebugPrint(srcPoint.Line()), msg)); diff --git a/tracking/archive.hpp b/tracking/archive.hpp index fe3b82b31c..3d59665e34 100644 --- a/tracking/archive.hpp +++ b/tracking/archive.hpp @@ -22,7 +22,14 @@ #include #include +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-copy" +#endif #include +#ifdef __clang__ +#pragma clang diagnostic pop +#endif namespace { diff --git a/tracking/connection.hpp b/tracking/connection.hpp index 2dbf559831..e1e1ac2378 100644 --- a/tracking/connection.hpp +++ b/tracking/connection.hpp @@ -6,7 +6,14 @@ #include #include +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-copy" +#endif #include +#ifdef __clang__ +#pragma clang diagnostic pop +#endif namespace platform { class Socket; } diff --git a/tracking/protocol.hpp b/tracking/protocol.hpp index 0389d3c1ab..0f159db76b 100644 --- a/tracking/protocol.hpp +++ b/tracking/protocol.hpp @@ -7,7 +7,14 @@ #include #include +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-copy" +#endif #include +#ifdef __clang__ +#pragma clang diagnostic pop +#endif namespace tracking { diff --git a/tracking/reporter.hpp b/tracking/reporter.hpp index ec88b119e2..3c10931cd3 100644 --- a/tracking/reporter.hpp +++ b/tracking/reporter.hpp @@ -16,7 +16,14 @@ #include #include +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-copy" +#endif #include +#ifdef __clang__ +#pragma clang diagnostic pop +#endif namespace location { diff --git a/traffic/traffic_tests/traffic_info_test.cpp b/traffic/traffic_tests/traffic_info_test.cpp index 2a58df8126..14b2305826 100644 --- a/traffic/traffic_tests/traffic_info_test.cpp +++ b/traffic/traffic_tests/traffic_info_test.cpp @@ -26,7 +26,7 @@ class TestMwmSet : public MwmSet { protected: // MwmSet overrides: - unique_ptr CreateInfo(platform::LocalCountryFile const & localFile) const override + unique_ptr CreateInfo(platform::LocalCountryFile const &) const override { unique_ptr info(new MwmInfo()); info->m_version.SetFormat(version::Format::lastFormat); -- 2.45.3 From 76c3cc9b5f9848825623f5c1d075f5a6482a22b1 Mon Sep 17 00:00:00 2001 From: Alexander Borsuk Date: Sat, 16 Apr 2022 23:54:08 +0200 Subject: [PATCH 07/21] Fixed QtCreator warning Signed-off-by: Alexander Borsuk --- testing/testing.hpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/testing/testing.hpp b/testing/testing.hpp index 1674568225..b0c0edf24a 100644 --- a/testing/testing.hpp +++ b/testing/testing.hpp @@ -9,9 +9,12 @@ #include +// TestRegister is static to avoid this warning: +// No previous extern declaration for non-static variable 'g_testRegister_TESTNAME' +// note: declare 'static' if the variable is not intended to be used outside of this translation unit #define UNIT_TEST(name) \ void UnitTest_##name(); \ - TestRegister g_testRegister_##name(#name, __FILE__, &UnitTest_##name); \ + static TestRegister g_testRegister_##name(#name, __FILE__, &UnitTest_##name); \ void UnitTest_##name() #define UNIT_CLASS_TEST(CLASS, NAME) \ -- 2.45.3 From 0a97d70be42d956c9eda4468a983610f7733106d Mon Sep 17 00:00:00 2001 From: Alexander Borsuk Date: Sat, 16 Apr 2022 23:54:27 +0200 Subject: [PATCH 08/21] Fixed unnecessary semicolon warning Signed-off-by: Alexander Borsuk --- base/scope_guard.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/base/scope_guard.hpp b/base/scope_guard.hpp index df907096f4..aff3675445 100644 --- a/base/scope_guard.hpp +++ b/base/scope_guard.hpp @@ -61,4 +61,4 @@ impl::GuardImpl make_scope_guard(TFunctor const & F) #define SCOPE_GUARD(name, func) \ ::base::scope_guard name = base::make_scope_guard(func); \ - static_cast(name); + static_cast(name) -- 2.45.3 From d2868c34e4c5f3d1d1f40ff3b8094ca40b1f95a3 Mon Sep 17 00:00:00 2001 From: Alexander Borsuk Date: Sat, 16 Apr 2022 21:49:19 +0200 Subject: [PATCH 09/21] [generator] std::optional for intermediate elements Signed-off-by: Alexander Borsuk --- .../restriction_collector_test.cpp | 4 +- .../source_to_element_test.cpp | 16 ++--- generator/holes.cpp | 5 +- generator/intermediate_data.cpp | 4 +- generator/intermediate_elements.hpp | 58 +++++++------------ generator/osm_element.hpp | 2 + generator/osm_source.cpp | 33 ++++++----- generator/osm_source.hpp | 4 +- generator/relation_tags.cpp | 20 +++---- generator/relation_tags.hpp | 2 +- .../world_roads_builder.cpp | 12 ++-- .../world_roads_builder.hpp | 5 +- 12 files changed, 75 insertions(+), 90 deletions(-) diff --git a/generator/generator_tests/restriction_collector_test.cpp b/generator/generator_tests/restriction_collector_test.cpp index a742868918..def97a79ba 100644 --- a/generator/generator_tests/restriction_collector_test.cpp +++ b/generator/generator_tests/restriction_collector_test.cpp @@ -108,7 +108,7 @@ std::string const kosmIdsToFeatureIdsContentForTwoCubeGraph = RelationElement MakeRelationElement(std::vector const & nodes, std::vector const & ways, - std::map const & tags) + std::map> const & tags) { RelationElement r; r.m_nodes = nodes; @@ -229,7 +229,7 @@ UNIT_TEST(RestrictionWriter_Merge) auto c1 = std::make_shared(filename, nullptr /* cache */); auto c2 = c1->Clone(); - std::map const tags = {{"type", "restriction"}, + std::map> const tags = {{"type", "restriction"}, {"restriction", "no_right_turn"}}; c1->CollectRelation(MakeRelationElement({} /* nodes */, {{1, "via"}, {11, "from"}, {21, "to"}} /* ways */, tags /* tags */)); c2->CollectRelation(MakeRelationElement({} /* nodes */, {{2, "via"}, {12, "from"}, {22, "to"}} /* ways */, tags /* tags */)); diff --git a/generator/generator_tests/source_to_element_test.cpp b/generator/generator_tests/source_to_element_test.cpp index 85f93031e5..301273e3a8 100644 --- a/generator/generator_tests/source_to_element_test.cpp +++ b/generator/generator_tests/source_to_element_test.cpp @@ -21,9 +21,9 @@ UNIT_TEST(Source_To_Element_create_from_xml_test) SourceReader reader(ss); std::vector elements; - ProcessOsmElementsFromXML(reader, [&elements](OsmElement * e) + ProcessOsmElementsFromXML(reader, [&elements](OsmElement && e) { - elements.push_back(*e); + elements.push_back(std::move(e)); }); TEST_EQUAL(elements.size(), 10, (elements)); @@ -36,9 +36,9 @@ UNIT_TEST(Source_To_Element_create_from_o5m_test) SourceReader reader(ss); std::vector elements; - ProcessOsmElementsFromO5M(reader, [&elements](OsmElement * e) + ProcessOsmElementsFromO5M(reader, [&elements](OsmElement && e) { - elements.push_back(*e); + elements.push_back(std::move(e)); }); TEST_EQUAL(elements.size(), 11, (elements)); @@ -51,9 +51,9 @@ UNIT_TEST(Source_To_Element_check_equivalence) SourceReader readerXML(ss1); std::vector elementsXML; - ProcessOsmElementsFromXML(readerXML, [&elementsXML](OsmElement * e) + ProcessOsmElementsFromXML(readerXML, [&elementsXML](OsmElement && e) { - elementsXML.push_back(*e); + elementsXML.push_back(std::move(e)); }); std::string src(std::begin(relation_o5m_data), std::end(relation_o5m_data)); @@ -61,9 +61,9 @@ UNIT_TEST(Source_To_Element_check_equivalence) SourceReader readerO5M(ss2); std::vector elementsO5M; - ProcessOsmElementsFromO5M(readerO5M, [&elementsO5M](OsmElement * e) + ProcessOsmElementsFromO5M(readerO5M, [&elementsO5M](OsmElement && e) { - elementsO5M.push_back(*e); + elementsO5M.push_back(std::move(e)); }); TEST_EQUAL(elementsXML.size(), elementsO5M.size(), ()); diff --git a/generator/holes.cpp b/generator/holes.cpp index 324626a663..07e378bbd4 100644 --- a/generator/holes.cpp +++ b/generator/holes.cpp @@ -34,12 +34,11 @@ HolesProcessor::HolesProcessor( base::ControlFlow HolesProcessor::operator() (uint64_t /* id */, RelationElement const & e) { - std::string const type = e.GetType(); + auto const type = e.GetType(); if (!(type == "multipolygon" || type == "boundary")) return base::ControlFlow::Continue; - std::string role; - if (e.FindWay(m_id, role) && role == "outer") + if (auto const role = e.GetWayRole(m_id); role == "outer") { e.ForEachWay(*this); // Stop processing. Assume that "outer way" exists in one relation only. diff --git a/generator/intermediate_data.cpp b/generator/intermediate_data.cpp index 96b11ffca4..211ddc2a68 100644 --- a/generator/intermediate_data.cpp +++ b/generator/intermediate_data.cpp @@ -399,9 +399,9 @@ IntermediateDataWriter::IntermediateDataWriter(PointStorageWriterInterface & nod void IntermediateDataWriter::AddRelation(Key id, RelationElement const & e) { - static set const types = {"multipolygon", "route", "boundary", + static set const types = {"multipolygon", "route", "boundary", "associatedStreet", "building", "restriction"}; - string const & relationType = e.GetType(); + auto const relationType = e.GetType(); if (!types.count(relationType)) return; diff --git a/generator/intermediate_elements.hpp b/generator/intermediate_elements.hpp index b41414b129..66361ecde2 100644 --- a/generator/intermediate_elements.hpp +++ b/generator/intermediate_elements.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -96,20 +97,24 @@ public: std::vector m_nodes; std::vector m_ways; std::vector m_relations; - std::map m_tags; + // std::less<> is for transparent find using string_view. + std::map> m_tags; bool IsValid() const { return !(m_nodes.empty() && m_ways.empty() && m_relations.empty()); } - std::string GetTagValue(std::string const & key) const + std::string_view GetTagValue(std::string_view key) const { - auto it = m_tags.find(key); - return ((it != m_tags.end()) ? it->second : std::string()); + auto const it = m_tags.find(key); + return it == m_tags.end() ? std::string_view() : it->second; } - std::string GetType() const { return GetTagValue("type"); } - bool FindWay(uint64_t id, std::string & role) const { return FindRoleImpl(m_ways, id, role); } - bool FindNode(uint64_t id, std::string & role) const { return FindRoleImpl(m_nodes, id, role); } - bool FindRelation(uint64_t id, std::string & role) const { return FindRoleImpl(m_relations, id, role); } + std::string_view GetType() const { return GetTagValue("type"); } + /// @returns (empty if absent) role for the way with given id. + std::string_view GetWayRole(uint64_t id) const { return FindRoleImpl(m_ways, id); } + /// @returns (empty if absent) role for the node with given id. + std::string_view GetNodeRole(uint64_t id) const { return FindRoleImpl(m_nodes, id); } + /// @returns (empty if absent) role for the relation with given id. + std::string_view GetRelationRole(uint64_t id) const { return FindRoleImpl(m_relations, id); } template void ForEachWay(ToDo & toDo) const @@ -118,27 +123,6 @@ public: toDo(m_ways[i].first, m_ways[i].second); } - std::string GetNodeRole(uint64_t const id) const - { - std::string role; - UNUSED_VALUE(FindNode(id, role)); - return role; - } - - std::string GetWayRole(uint64_t const id) const - { - std::string role; - UNUSED_VALUE(FindWay(id, role)); - return role; - } - - std::string GetRelationRole(uint64_t const id) const - { - std::string role; - UNUSED_VALUE(FindRelation(id, role)); - return role; - } - void Swap(RelationElement & rhs) { m_nodes.swap(rhs.m_nodes); @@ -192,7 +176,7 @@ public: { ReaderSource r(reader); - auto StringReader = [&r](std::string & str) + auto const StringReader = [&r](std::string & str) { uint16_t sz = 0; r.Read(&sz, sizeof(sz)); @@ -200,7 +184,7 @@ public: r.Read(&str[0], sz); }; - auto MembersReader = [&r, &StringReader](std::vector & members) + auto const MembersReader = [&r, &StringReader](std::vector & members) { uint64_t count = ReadVarUint(r); members.resize(count); @@ -219,7 +203,7 @@ public: // decode m_tags m_tags.clear(); - uint64_t count = ReadVarUint(r); + uint64_t const count = ReadVarUint(r); for (uint64_t i = 0; i < count; ++i) { std::pair kv; @@ -251,16 +235,14 @@ public: } protected: - bool FindRoleImpl(std::vector const & container, uint64_t id, std::string & role) const + std::string_view FindRoleImpl(std::vector const & container, uint64_t id) const { for (auto const & e : container) { if (e.first == id) - { - role = e.second; - return true; - } + return e.second; } - return false; + + return {}; } }; diff --git a/generator/osm_element.hpp b/generator/osm_element.hpp index 77090104a3..bd6ae79139 100644 --- a/generator/osm_element.hpp +++ b/generator/osm_element.hpp @@ -97,7 +97,9 @@ struct OsmElement std::vector const & Nodes() const { return m_nodes; } std::vector const & Members() const { return m_members; } + std::vector & Members() { return m_members; } std::vector const & Tags() const { return m_tags; } + std::vector & Tags() { return m_tags; } bool IsNode() const { return m_type == EntityType::Node; } bool IsWay() const { return m_type == EntityType::Way; } diff --git a/generator/osm_source.cpp b/generator/osm_source.cpp index 9e16df4aa6..01c5679621 100644 --- a/generator/osm_source.cpp +++ b/generator/osm_source.cpp @@ -53,7 +53,7 @@ uint64_t SourceReader::Read(char * buffer, uint64_t bufferSize) } // Functions --------------------------------------------------------------------------------------- -void AddElementToCache(cache::IntermediateDataWriter & cache, OsmElement & element) +void AddElementToCache(cache::IntermediateDataWriter & cache, OsmElement && element) { switch (element.m_type) { @@ -78,25 +78,26 @@ void AddElementToCache(cache::IntermediateDataWriter & cache, OsmElement & eleme { // store relation RelationElement relation; - for (auto const & member : element.Members()) + for (auto & member : element.Members()) { - switch (member.m_type) { + switch (member.m_type) + { case OsmElement::EntityType::Node: - relation.m_nodes.emplace_back(member.m_ref, string(member.m_role)); + relation.m_nodes.emplace_back(member.m_ref, std::move(member.m_role)); break; case OsmElement::EntityType::Way: - relation.m_ways.emplace_back(member.m_ref, string(member.m_role)); + relation.m_ways.emplace_back(member.m_ref, std::move(member.m_role)); break; case OsmElement::EntityType::Relation: - relation.m_relations.emplace_back(member.m_ref, string(member.m_role)); + relation.m_relations.emplace_back(member.m_ref, std::move(member.m_role)); break; default: break; } } - for (auto const & tag : element.Tags()) - relation.m_tags.emplace(tag.m_key, tag.m_value); + for (auto & tag : element.Tags()) + relation.m_tags.emplace(std::move(tag.m_key), std::move(tag.m_value)); if (relation.IsValid()) cache.AddRelation(element.m_id, relation); @@ -116,17 +117,17 @@ void BuildIntermediateDataFromXML(SourceReader & stream, cache::IntermediateData while (processorOsmElementsFromXml.TryRead(element)) { towns.CheckElement(element); - AddElementToCache(cache, element); + AddElementToCache(cache, std::move(element)); } } -void ProcessOsmElementsFromXML(SourceReader & stream, function processor) +void ProcessOsmElementsFromXML(SourceReader & stream, function processor) { ProcessorOsmElementsFromXml processorOsmElementsFromXml(stream); OsmElement element; while (processorOsmElementsFromXml.TryRead(element)) { - processor(&element); + processor(std::move(element)); element.Clear(); } } @@ -134,9 +135,9 @@ void ProcessOsmElementsFromXML(SourceReader & stream, function processor) +void ProcessOsmElementsFromO5M(SourceReader & stream, function processor) { ProcessorOsmElementsFromO5M processorOsmElementsFromO5M(stream); OsmElement element; while (processorOsmElementsFromO5M.TryRead(element)) { - processor(&element); + processor(std::move(element)); element.Clear(); } } diff --git a/generator/osm_source.hpp b/generator/osm_source.hpp index 40ca97b6be..c1bd01111b 100644 --- a/generator/osm_source.hpp +++ b/generator/osm_source.hpp @@ -47,8 +47,8 @@ public: bool GenerateIntermediateData(feature::GenerateInfo & info); -void ProcessOsmElementsFromO5M(SourceReader & stream, std::function processor); -void ProcessOsmElementsFromXML(SourceReader & stream, std::function processor); +void ProcessOsmElementsFromO5M(SourceReader & stream, std::function processor); +void ProcessOsmElementsFromXML(SourceReader & stream, std::function processor); class ProcessorOsmElementsInterface { diff --git a/generator/relation_tags.cpp b/generator/relation_tags.cpp index 5488a8fc2e..55aad0b42d 100644 --- a/generator/relation_tags.cpp +++ b/generator/relation_tags.cpp @@ -14,7 +14,7 @@ void RelationTagsBase::Reset(uint64_t fID, OsmElement * p) m_current = p; } -bool RelationTagsBase::IsSkipRelation(std::string const & type) +bool RelationTagsBase::IsSkipRelation(std::string_view type) { /// @todo Skip special relation types. return type == "multipolygon" || type == "bridge"; @@ -33,7 +33,7 @@ void RelationTagsBase::AddCustomTag(std::pair const & void RelationTagsNode::Process(RelationElement const & e) { - std::string const & type = e.GetType(); + auto const type = e.GetType(); if (Base::IsSkipRelation(type)) return; @@ -60,8 +60,8 @@ void RelationTagsNode::Process(RelationElement const & e) bool RelationTagsWay::IsAcceptBoundary(RelationElement const & e) const { - std::string role; - CHECK(e.FindWay(Base::m_featureID, role), (Base::m_featureID)); + auto const role = e.GetWayRole(Base::m_featureID); + CHECK(!role.empty(), ("Relation does not have a way", Base::m_featureID)); // Do not accumulate boundary types (boundary=administrative) for inner polygons. // Example: Minsk city border (admin_level=8) is inner for Minsk area border (admin_level=4). @@ -72,7 +72,7 @@ void RelationTagsWay::Process(RelationElement const & e) { /// @todo Review route relations in future. /// Actually, now they give a lot of dummy tags. - std::string const & type = e.GetType(); + auto const type = e.GetType(); if (Base::IsSkipRelation(type)) return; @@ -81,16 +81,16 @@ void RelationTagsWay::Process(RelationElement const & e) if (e.GetTagValue("route") == "road") { // Append "network/ref" to the feature ref tag. - std::string ref = e.GetTagValue("ref"); + std::string ref(e.GetTagValue("ref")); if (!ref.empty()) { - std::string const & network = e.GetTagValue("network"); + auto const network = e.GetTagValue("network"); // Not processing networks with more than 15 chars (see road_shields_parser.cpp). if (!network.empty() && network.find('/') == std::string::npos && network.size() < 15) - ref = network + '/' + ref; - std::string const & refBase = m_current->GetTag("ref"); + ref.assign(network).append(1, '/').append(ref); + auto const refBase = m_current->GetTag("ref"); if (!refBase.empty()) - ref = refBase + ';' + ref; + ref.assign(refBase).append(1, ';').append(ref); Base::AddCustomTag({"ref", std::move(ref)}); } } diff --git a/generator/relation_tags.hpp b/generator/relation_tags.hpp index 12b90a71ce..c139cc1088 100644 --- a/generator/relation_tags.hpp +++ b/generator/relation_tags.hpp @@ -38,7 +38,7 @@ public: } protected: - static bool IsSkipRelation(std::string const & type); + static bool IsSkipRelation(std::string_view type); bool IsKeyTagExists(std::string const & key) const; void AddCustomTag(std::pair const & p); virtual void Process(RelationElement const & e) = 0; diff --git a/generator/world_roads_builder/world_roads_builder.cpp b/generator/world_roads_builder/world_roads_builder.cpp index b30ca20772..bf3b6ee577 100644 --- a/generator/world_roads_builder/world_roads_builder.cpp +++ b/generator/world_roads_builder/world_roads_builder.cpp @@ -64,17 +64,17 @@ RoadsFromOsm GetRoadsFromOsm(generator::SourceReader & reader, { RoadsFromOsm roadsFromOsm; - ProcessOsmElementsFromO5M(reader, [&roadsFromOsm, &highways](OsmElement * e) { - if (e->IsWay()) + ProcessOsmElementsFromO5M(reader, [&roadsFromOsm, &highways](OsmElement && e) { + if (e.IsWay()) { - std::string const & highway = e->GetTag("highway"); + std::string const & highway = e.GetTag("highway"); if (!highway.empty() && base::IsExist(highways, highway)) - roadsFromOsm.m_ways[highway].emplace(e->m_id, RoadData({}, *e)); + roadsFromOsm.m_ways[highway].emplace(e.m_id, RoadData({}, std::move(e))); } - else if (e->IsNode()) + else if (e.IsNode()) { - roadsFromOsm.m_nodes.emplace(e->m_id, ms::LatLon(e->m_lat, e->m_lon)); + roadsFromOsm.m_nodes.emplace(e.m_id, ms::LatLon(e.m_lat, e.m_lon)); } }); diff --git a/generator/world_roads_builder/world_roads_builder.hpp b/generator/world_roads_builder/world_roads_builder.hpp index fb6327d73e..434f4da53b 100644 --- a/generator/world_roads_builder/world_roads_builder.hpp +++ b/generator/world_roads_builder/world_roads_builder.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #include namespace routing @@ -26,8 +27,8 @@ struct RoadData { RoadData() = default; - RoadData(std::set const & regions, OsmElement const & way) - : m_regions(regions), m_way(way) + RoadData(std::set regions, OsmElement && way) + : m_regions(std::move(regions)), m_way(std::move(way)) { } -- 2.45.3 From c4192887444df3d490f03a3292276e095fcea8b6 Mon Sep 17 00:00:00 2001 From: Alexander Borsuk Date: Sat, 16 Apr 2022 08:48:45 +0200 Subject: [PATCH 10/21] Get phone from "mobile" OSM tag Signed-off-by: Alexander Borsuk --- data/editor.config | 1 + editor/xml_feature.cpp | 2 +- indexer/feature_meta.cpp | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/data/editor.config b/data/editor.config index daafe22cf7..e0cd8a9f6d 100644 --- a/data/editor.config +++ b/data/editor.config @@ -41,6 +41,7 @@ + diff --git a/editor/xml_feature.cpp b/editor/xml_feature.cpp index 7b727762e5..8c59732029 100644 --- a/editor/xml_feature.cpp +++ b/editor/xml_feature.cpp @@ -170,7 +170,7 @@ void XMLFeature::ApplyPatch(XMLFeature const & featureWithChanges) { // TODO(mgsergio): Get these alt tags from the config. base::StringIL const alternativeTags[] = { - {"phone", "contact:phone", "contact:mobile"}, + {"phone", "contact:phone", "contact:mobile", "mobile"}, {"website", "contact:website", "url"}, {"fax", "contact:fax"}, {"email", "contact:email"} diff --git a/indexer/feature_meta.cpp b/indexer/feature_meta.cpp index eb8b14b505..8b7c4709d7 100644 --- a/indexer/feature_meta.cpp +++ b/indexer/feature_meta.cpp @@ -46,7 +46,7 @@ bool Metadata::TypeFromString(string const & k, Metadata::EType & outType) { if (k == "opening_hours") outType = Metadata::FMD_OPEN_HOURS; - else if (k == "phone" || k == "contact:phone" || k == "contact:mobile") + else if (k == "phone" || k == "contact:phone" || k == "contact:mobile" || k == "mobile") outType = Metadata::FMD_PHONE_NUMBER; else if (k == "fax" || k == "contact:fax") outType = Metadata::EType::FMD_FAX_NUMBER; -- 2.45.3 From 9fa706ee1473ea1ec416347fb2aa682eafc2fe57 Mon Sep 17 00:00:00 2001 From: vng Date: Thu, 13 May 2021 15:58:55 +0300 Subject: [PATCH 11/21] [storage] Fixed countries.txt order lookup. Signed-off-by: vng --- storage/country_tree.cpp | 59 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 3 deletions(-) diff --git a/storage/country_tree.cpp b/storage/country_tree.cpp index 6dad35a14b..d9b5e196d3 100644 --- a/storage/country_tree.cpp +++ b/storage/country_tree.cpp @@ -443,6 +443,21 @@ int64_t LoadCountriesFromBuffer(string const & jsonBuffer, CountryTree & countri return version; } +namespace +{ +unique_ptr GetReaderImpl(Platform & pl, string const & file, string const & scope) +{ + try + { + return pl.GetReader(file, scope); + } + catch (RootException const &) + { + } + return nullptr; +} +} // namespace + int64_t LoadCountriesFromFile(string const & path, CountryTree & countries, Affiliations & affiliations, CountryNameSynonyms & countryNameSynonyms, @@ -450,9 +465,47 @@ int64_t LoadCountriesFromFile(string const & path, CountryTree & countries, MwmTopCountryGeoIds & mwmTopCountryGeoIds) { string json; - ReaderPtr(GetPlatform().GetReader(path)).ReadAsString(json); - return LoadCountriesFromBuffer(json, countries, affiliations, countryNameSynonyms, - mwmTopCityGeoIds, mwmTopCountryGeoIds); + int64_t version = -1; + + // Choose the latest version from "resource" or "writable": + // w > r in case of autoupdates + // r > w in case of a new countries file with an updated app + + auto & pl = GetPlatform(); + auto reader = GetReaderImpl(pl, path, "fr"); + if (reader) + { + reader->ReadAsString(json); + version = LoadCountriesFromBuffer(json, countries, affiliations, countryNameSynonyms, + mwmTopCityGeoIds, mwmTopCountryGeoIds); + } + + reader = GetReaderImpl(pl, path, "w"); + if (reader) + { + CountryTree newCountries; + Affiliations newAffs; + CountryNameSynonyms newSyms; + MwmTopCityGeoIds newCityIds; + MwmTopCountryGeoIds newCountryIds; + + reader->ReadAsString(json); + int64_t const newVersion = LoadCountriesFromBuffer(json, newCountries, newAffs, newSyms, + newCityIds, newCountryIds); + + if (newVersion > version) + { + version = newVersion; + + countries = std::move(newCountries); + affiliations = std::move(newAffs); + countryNameSynonyms = std::move(newSyms); + mwmTopCityGeoIds = std::move(newCityIds); + mwmTopCountryGeoIds = std::move(newCountryIds); + } + } + + return version; } void LoadCountryFile2CountryInfo(string const & jsonBuffer, map & id2info) -- 2.45.3 From ba2308607d21ebe231589ca10386816536009c58 Mon Sep 17 00:00:00 2001 From: vng Date: Fri, 14 May 2021 10:33:42 +0300 Subject: [PATCH 12/21] [storage] Do not apply affiliations and synonyms when updating countries.txt Signed-off-by: vng --- feature_list/feature_list.cpp | 2 +- map/framework.cpp | 4 ++- storage/country_info_getter.cpp | 4 ++- storage/storage.cpp | 38 +++++++++++++++++++------ storage/storage.hpp | 29 ++++++++++++------- storage/storage_tests/storage_tests.cpp | 6 ++-- 6 files changed, 58 insertions(+), 25 deletions(-) diff --git a/feature_list/feature_list.cpp b/feature_list/feature_list.cpp index b58ff63663..847dcfb5ee 100644 --- a/feature_list/feature_list.cpp +++ b/feature_list/feature_list.cpp @@ -340,7 +340,7 @@ int main(int argc, char ** argv) storage::Storage storage(countriesFile, argv[1]); storage.Init(&DidDownload, &WillDelete); auto infoGetter = storage::CountryInfoReader::CreateCountryInfoGetter(pl); - infoGetter->SetAffiliations(&storage.GetAffiliations()); + infoGetter->SetAffiliations(storage.GetAffiliations()); GetStyleReader().SetCurrentStyle(MapStyleMerged); classificator::Load(); diff --git a/map/framework.cpp b/map/framework.cpp index 763b2ccf61..e50b607746 100644 --- a/map/framework.cpp +++ b/map/framework.cpp @@ -1198,7 +1198,9 @@ void Framework::InitCountryInfoGetter() auto const & platform = GetPlatform(); m_infoGetter = CountryInfoReader::CreateCountryInfoGetter(platform); - m_infoGetter->SetAffiliations(&m_storage.GetAffiliations()); + + // Storage::GetAffiliations() pointer never changed. + m_infoGetter->SetAffiliations(m_storage.GetAffiliations()); } void Framework::InitSearchAPI(size_t numThreads) diff --git a/storage/country_info_getter.cpp b/storage/country_info_getter.cpp index eea766ea29..a72adaeff4 100644 --- a/storage/country_info_getter.cpp +++ b/storage/country_info_getter.cpp @@ -156,7 +156,9 @@ m2::RectD CountryInfoGetter::GetLimitRectForLeaf(CountryId const & leafCountryId void CountryInfoGetter::GetMatchedRegions(std::string const & affiliation, RegionIdVec & regions) const { - CHECK(m_affiliations, ()); + // Once set, m_affiliations ptr is never changed (same as the content). + ASSERT(m_affiliations, ()); + auto it = m_affiliations->find(affiliation); if (it == m_affiliations->end()) return; diff --git a/storage/storage.cpp b/storage/storage.cpp index 1e6d637c4f..047d797e8a 100644 --- a/storage/storage.cpp +++ b/storage/storage.cpp @@ -1058,10 +1058,14 @@ void Storage::ApplyCountries(std::string const & countriesBuffer, Storage & stor m_downloader->SetDataVersion(m_currentVersion); m_countries = std::move(storage.m_countries); - m_affiliations = std::move(storage.m_affiliations); - m_countryNameSynonyms = std::move(storage.m_countryNameSynonyms); - m_mwmTopCityGeoIds = std::move(storage.m_mwmTopCityGeoIds); - m_mwmTopCountryGeoIds = std::move(storage.m_mwmTopCountryGeoIds); + + /// @todo The best way is to restart the app after ApplyCountries. + // Do not to update this information containers to avoid possible races. + // Affiliations, synonyms, etc can be updated with the app update. + //m_affiliations = std::move(storage.m_affiliations); + //m_countryNameSynonyms = std::move(storage.m_countryNameSynonyms); + //m_mwmTopCityGeoIds = std::move(storage.m_mwmTopCityGeoIds); + //m_mwmTopCountryGeoIds = std::move(storage.m_mwmTopCountryGeoIds); LOG(LDEBUG, ("Version", m_currentVersion, "is applied")); @@ -1750,20 +1754,38 @@ bool Storage::GetUpdateInfo(CountryId const & countryId, UpdateInfo & updateInfo return true; } +/// @note No need to call CHECK_THREAD_CHECKER(m_threadChecker, ()) here and below, because +/// we don't change all this containers during update. Consider checking, otherwise. +/// @{ +Affiliations const * Storage::GetAffiliations() const +{ + return &m_affiliations; +} + +CountryNameSynonyms const & Storage::GetCountryNameSynonyms() const +{ + return m_countryNameSynonyms; +} + +MwmTopCityGeoIds const & Storage::GetMwmTopCityGeoIds() const +{ + return m_mwmTopCityGeoIds; +} + std::vector Storage::GetTopCountryGeoIds(CountryId const & countryId) const { std::vector result; - auto const collector = [this, &result](CountryId const & id, CountryTree::Node const &) { + ForEachAncestorExceptForTheRoot(countryId, [this, &result](CountryId const & id, CountryTree::Node const &) + { auto const it = m_mwmTopCountryGeoIds.find(id); if (it != m_mwmTopCountryGeoIds.cend()) result.insert(result.end(), it->second.cbegin(), it->second.cend()); - }; - - ForEachAncestorExceptForTheRoot(countryId, collector); + }); return result; } +/// @} void Storage::GetQueuedChildren(CountryId const & parent, CountriesVec & queuedChildren) const { diff --git a/storage/storage.hpp b/storage/storage.hpp index 00bd9a3f54..f7215456c0 100644 --- a/storage/storage.hpp +++ b/storage/storage.hpp @@ -230,16 +230,21 @@ private: CountryNameGetter m_countryNameGetter; - // |m_affiliations| is a mapping from countryId to the list of names of - // geographical objects (such as countries) that encompass this countryId. - // Note. Affiliations is inherited from ancestors of the countryId in country tree. - // |m_affiliations| is filled during Storage initialization or during migration process. - // It is filled with data of countries.txt (field "affiliations"). - // Once filled |m_affiliations| is not changed. + /** + * @brief Mapping from countryId to the list of names of + * geographical objects (such as countries) that encompass this countryId. + * @note Affiliations are inherited from ancestors of the countryId in country tree. + * Initialized with data of countries.txt (field "affiliations"). + * Once filled, they are not changed. + */ Affiliations m_affiliations; CountryNameSynonyms m_countryNameSynonyms; + + /// @todo This containers are empty for now, but probably will be used in future. + /// @{ MwmTopCityGeoIds m_mwmTopCityGeoIds; MwmTopCountryGeoIds m_mwmTopCountryGeoIds; + /// @} MwmSize m_maxMwmSizeBytes = 0; @@ -432,12 +437,14 @@ public: /// \return true if updateInfo is filled correctly and false otherwise. bool GetUpdateInfo(CountryId const & countryId, UpdateInfo & updateInfo) const; - Affiliations const & GetAffiliations() const { return m_affiliations; } - - CountryNameSynonyms const & GetCountryNameSynonyms() const { return m_countryNameSynonyms; } - - MwmTopCityGeoIds const & GetMwmTopCityGeoIds() const { return m_mwmTopCityGeoIds; } + /// @name This functions should be called from 'main' thread only to avoid races. + /// @{ + /// @return Pointer that will be stored for later use. + Affiliations const * GetAffiliations() const; + CountryNameSynonyms const & GetCountryNameSynonyms() const; + MwmTopCityGeoIds const & GetMwmTopCityGeoIds() const; std::vector GetTopCountryGeoIds(CountryId const & countryId) const; + /// @} /// \brief Calls |toDo| for each node for subtree with |root|. /// For example ForEachInSubtree(GetRootId()) calls |toDo| for every node including diff --git a/storage/storage_tests/storage_tests.cpp b/storage/storage_tests/storage_tests.cpp index 1bdfa0c68f..99ca767fa0 100644 --- a/storage/storage_tests/storage_tests.cpp +++ b/storage/storage_tests/storage_tests.cpp @@ -747,16 +747,16 @@ UNIT_TEST(StorageTest_GetAffiliations) vector const abkhaziaId = {"Abkhazia"}; for (auto const & s : {"Georgia", "Russia", "Europe"}) - TEST_EQUAL(storage.GetAffiliations().at(s), abkhaziaId, ()); + TEST_EQUAL(storage.GetAffiliations()->at(s), abkhaziaId, ()); // Affiliation inheritance. vector const disputableId = {"Disputable Territory"}; for (auto const & s : {"Stepchild Land1", "Stepchild Land2"}) - TEST_EQUAL(storage.GetAffiliations().at(s), disputableId, ()); + TEST_EQUAL(storage.GetAffiliations()->at(s), disputableId, ()); vector const indisputableId = {"Indisputable Territory Of Country1"}; for (auto const & s : {"Child Land1"}) - TEST_EQUAL(storage.GetAffiliations().at(s), indisputableId, ()); + TEST_EQUAL(storage.GetAffiliations()->at(s), indisputableId, ()); } UNIT_TEST(StorageTest_HasCountryId) -- 2.45.3 From f97d862dd5c21ea6f94ac898e3f5c85be879b4c7 Mon Sep 17 00:00:00 2001 From: Viktor Govako Date: Thu, 9 Dec 2021 13:36:50 +0300 Subject: [PATCH 13/21] Replace std::vector(m2::PointD) code bloat with value initialization. Signed-off-by: Viktor Govako --- .../processor_test.cpp | 653 ++++++++---------- 1 file changed, 280 insertions(+), 373 deletions(-) diff --git a/search/search_integration_tests/processor_test.cpp b/search/search_integration_tests/processor_test.cpp index 98bb26d698..740a9e020b 100644 --- a/search/search_integration_tests/processor_test.cpp +++ b/search/search_integration_tests/processor_test.cpp @@ -117,51 +117,40 @@ class ProcessorTest : public SearchTest UNIT_CLASS_TEST(ProcessorTest, Smoke) { string const countryName = "Wonderland"; - TestCountry wonderlandCountry(m2::PointD(10, 10), countryName, "en"); + TestCountry wonderlandCountry({10, 10}, countryName, "en"); - TestCity losAlamosCity(m2::PointD(10, 10), "Los Alamos", "en", 100 /* rank */); - TestCity mskCity(m2::PointD(0, 0), "Moscow", "en", 100 /* rank */); - TestCity torontoCity(m2::PointD(-10, -10), "Toronto", "en", 100 /* rank */); + TestCity losAlamosCity({10, 10}, "Los Alamos", "en", 100 /* rank */); + TestCity mskCity({0, 0}, "Moscow", "en", 100 /* rank */); + TestCity torontoCity({-10, -10}, "Toronto", "en", 100 /* rank */); - TestVillage longPondVillage(m2::PointD(15, 15), "Long Pond Village", "en", 10 /* rank */); - TestStreet feynmanStreet( - vector{m2::PointD(9.999, 9.999), m2::PointD(10, 10), m2::PointD(10.001, 10.001)}, - "Feynman street", "en"); - TestStreet bohrStreet1( - vector{m2::PointD(9.999, 10.001), m2::PointD(10, 10), m2::PointD(10.001, 9.999)}, - "Bohr street", "en"); - TestStreet bohrStreet2(vector{m2::PointD(10.001, 9.999), m2::PointD(10.002, 9.998)}, - "Bohr street", "en"); - TestStreet bohrStreet3(vector{m2::PointD(10.002, 9.998), m2::PointD(10.003, 9.997)}, - "Bohr street", "en"); - TestStreet firstAprilStreet(vector{m2::PointD(14.998, 15), m2::PointD(15.002, 15)}, - "1st April street", "en"); + TestVillage longPondVillage({15, 15}, "Long Pond Village", "en", 10 /* rank */); + TestStreet feynmanStreet({{9.999, 9.999}, {10, 10}, {10.001, 10.001}}, "Feynman street", "en"); + TestStreet bohrStreet1({{9.999, 10.001}, {10, 10}, {10.001, 9.999}}, "Bohr street", "en"); + TestStreet bohrStreet2({{10.001, 9.999}, {10.002, 9.998}}, "Bohr street", "en"); + TestStreet bohrStreet3({{10.002, 9.998}, {10.003, 9.997}}, "Bohr street", "en"); + TestStreet firstAprilStreet({{14.998, 15}, {15.002, 15}}, "1st April street", "en"); - TestBuilding feynmanHouse(m2::PointD(10, 10), "Feynman house", "1 unit 1", feynmanStreet.GetName("en"), "en"); - TestBuilding bohrHouse(m2::PointD(10, 10), "Bohr house", "1 unit 1", bohrStreet1.GetName("en"), "en"); - TestBuilding hilbertHouse( - vector{ - {10.0005, 10.0005}, {10.0006, 10.0005}, {10.0006, 10.0006}, {10.0005, 10.0006}}, + TestBuilding feynmanHouse({10, 10}, "Feynman house", "1 unit 1", feynmanStreet.GetName("en"), "en"); + TestBuilding bohrHouse({10, 10}, "Bohr house", "1 unit 1", bohrStreet1.GetName("en"), "en"); + TestBuilding hilbertHouse({{10.0005, 10.0005}, {10.0006, 10.0005}, {10.0006, 10.0006}, {10.0005, 10.0006}}, "Hilbert house", "1 unit 2", bohrStreet1.GetName("en"), "en"); - TestBuilding descartesHouse(m2::PointD(10, 10), "Descartes house", "2", "en"); - TestBuilding bornHouse(m2::PointD(14.999, 15), "Born house", "8", firstAprilStreet.GetName("en"), "en"); + TestBuilding descartesHouse({10, 10}, "Descartes house", "2", "en"); + TestBuilding bornHouse({14.999, 15}, "Born house", "8", firstAprilStreet.GetName("en"), "en"); - TestPOI busStop(m2::PointD(0, 0), "Central bus stop", "en"); - TestPOI tramStop(m2::PointD(0.0001, 0.0001), "Tram stop", "en"); - TestPOI quantumTeleport1(m2::PointD(0.0002, 0.0002), "Quantum teleport 1", "en"); + TestPOI busStop({0, 0}, "Central bus stop", "en"); + TestPOI tramStop({0.0001, 0.0001}, "Tram stop", "en"); + TestPOI quantumTeleport1({0.0002, 0.0002}, "Quantum teleport 1", "en"); - TestPOI quantumTeleport2(m2::PointD(10, 10), "Quantum teleport 2", "en"); + TestPOI quantumTeleport2({10, 10}, "Quantum teleport 2", "en"); quantumTeleport2.SetHouseNumber("3"); quantumTeleport2.SetStreetName(feynmanStreet.GetName("en")); - TestPOI quantumCafe(m2::PointD(-0.0002, -0.0002), "Quantum cafe", "en"); - TestPOI lantern1(m2::PointD(10.0005, 10.0005), "lantern 1", "en"); - TestPOI lantern2(m2::PointD(10.0006, 10.0005), "lantern 2", "en"); + TestPOI quantumCafe({-0.0002, -0.0002}, "Quantum cafe", "en"); + TestPOI lantern1({10.0005, 10.0005}, "lantern 1", "en"); + TestPOI lantern2({10.0006, 10.0005}, "lantern 2", "en"); - TestStreet stradaDrive(vector{m2::PointD(-10.001, -10.001), m2::PointD(-10, -10), - m2::PointD(-9.999, -9.999)}, - "Strada drive", "en"); - TestBuilding terranceHouse(m2::PointD(-10, -10), "", "155", stradaDrive.GetName("en"), "en"); + TestStreet stradaDrive({{-10.001, -10.001}, {-10, -10}, {-9.999, -9.999}}, "Strada drive", "en"); + TestBuilding terranceHouse({-10, -10}, "", "155", stradaDrive.GetName("en"), "en"); auto const worldId = BuildWorld([&](TestMwmBuilder & builder) { builder.Add(wonderlandCountry); @@ -199,7 +188,7 @@ UNIT_CLASS_TEST(ProcessorTest, Smoke) builder.Add(terranceHouse); }); - SetViewport(m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0))); + SetViewport(m2::RectD(-1.0, -1.0, 1.0, 1.0)); { Rules rules = {}; TEST(ResultsMatch("", rules), ()); @@ -285,17 +274,17 @@ UNIT_CLASS_TEST(ProcessorTest, Smoke) UNIT_CLASS_TEST(ProcessorTest, SearchInWorld) { string const countryName = "Wonderland"; - TestCountry wonderland(m2::PointD(0, 0), countryName, "en"); - TestCity losAlamos(m2::PointD(0, 0), "Los Alamos", "en", 100 /* rank */); + TestCountry wonderland({0, 0}, countryName, "en"); + TestCity losAlamos({0, 0}, "Los Alamos", "en", 100 /* rank */); auto testWorldId = BuildWorld([&](TestMwmBuilder & builder) { builder.Add(wonderland); builder.Add(losAlamos); }); - RegisterCountry(countryName, m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0))); + RegisterCountry(countryName, m2::RectD(-1.0, -1.0, 1.0, 1.0)); - SetViewport(m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(-0.5, -0.5))); + SetViewport(m2::RectD(-1.0, -1.0, -0.5, -0.5)); { Rules rules = {ExactMatch(testWorldId, losAlamos)}; TEST(ResultsMatch("Los Alamos", rules), ()); @@ -313,11 +302,9 @@ UNIT_CLASS_TEST(ProcessorTest, SearchInWorld) UNIT_CLASS_TEST(ProcessorTest, SearchByName) { string const countryName = "Wonderland"; - TestCity london(m2::PointD(1, 1), "London", "en", 100 /* rank */); - TestPark hydePark(vector{m2::PointD(0.5, 0.5), m2::PointD(1.5, 0.5), - m2::PointD(1.5, 1.5), m2::PointD(0.5, 1.5)}, - "Hyde Park", "en"); - TestPOI cafe(m2::PointD(1.0, 1.0), "London Cafe", "en"); + TestCity london({1, 1}, "London", "en", 100 /* rank */); + TestPark hydePark({{0.5, 0.5}, {1.5, 0.5}, {1.5, 1.5}, {0.5, 1.5}}, "Hyde Park", "en"); + TestPOI cafe({1.0, 1.0}, "London Cafe", "en"); auto worldId = BuildWorld([&](TestMwmBuilder & builder) { @@ -329,7 +316,7 @@ UNIT_CLASS_TEST(ProcessorTest, SearchByName) builder.Add(cafe); }); - SetViewport(m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(-0.9, -0.9))); + SetViewport(m2::RectD(-1.0, -1.0, -0.9, -0.9)); { Rules rules = {ExactMatch(wonderlandId, hydePark)}; TEST(ResultsMatch("hyde park", rules), ()); @@ -340,7 +327,7 @@ UNIT_CLASS_TEST(ProcessorTest, SearchByName) TEST(ResultsMatch("hyde london park", rules), ()); } - SetViewport(m2::RectD(m2::PointD(0.5, 0.5), m2::PointD(1.5, 1.5))); + SetViewport(m2::RectD(0.5, 0.5, 1.5, 1.5)); { Rules rules = {ExactMatch(worldId, london)}; TEST(ResultsMatch("london", Mode::Downloader, rules), ()); @@ -353,8 +340,8 @@ UNIT_CLASS_TEST(ProcessorTest, SearchByName) UNIT_CLASS_TEST(ProcessorTest, DisableSuggests) { - TestCity london1(m2::PointD(1, 1), "London", "en", 100 /* rank */); - TestCity london2(m2::PointD(-1, -1), "London", "en", 100 /* rank */); + TestCity london1({1, 1}, "London", "en", 100 /* rank */); + TestCity london2({-1, -1}, "London", "en", 100 /* rank */); auto worldId = BuildWorld([&](TestMwmBuilder & builder) { @@ -366,7 +353,7 @@ UNIT_CLASS_TEST(ProcessorTest, DisableSuggests) SearchParams params; params.m_query = "londo"; params.m_inputLocale = "en"; - params.m_viewport = m2::RectD(m2::PointD(0.5, 0.5), m2::PointD(1.5, 1.5)); + params.m_viewport = m2::RectD(0.5, 0.5, 1.5, 1.5); params.m_mode = Mode::Downloader; params.m_suggestsEnabled = false; @@ -382,34 +369,32 @@ UNIT_CLASS_TEST(ProcessorTest, TestRankingInfo) { string const countryName = "Wonderland"; - TestCity sanFrancisco(m2::PointD(1, 1), "San Francisco", "en", 100 /* rank */); + TestCity sanFrancisco({1, 1}, "San Francisco", "en", 100 /* rank */); // Golden Gate Bridge-bridge is located in this test on the Golden // Gate Bridge-street. Therefore, there are several valid parses of // the query "Golden Gate Bridge", and search engine must return // both features (street and bridge) as they were matched by full // name. - TestStreet goldenGateStreet( - vector{m2::PointD(-0.5, -0.5), m2::PointD(0, 0), m2::PointD(0.5, 0.5)}, - "Golden Gate Bridge", "en"); + TestStreet goldenGateStreet({{-0.5, -0.5}, {0, 0}, {0.5, 0.5}}, "Golden Gate Bridge", "en"); - TestPOI goldenGateBridge(m2::PointD(0, 0), "Golden Gate Bridge", "en"); + TestPOI goldenGateBridge({0, 0}, "Golden Gate Bridge", "en"); - TestPOI waterfall(m2::PointD(0.5, 0.5), "", "en"); + TestPOI waterfall({0.5, 0.5}, "", "en"); waterfall.SetTypes({{"waterway", "waterfall"}}); - TestPOI lermontov(m2::PointD(1, 1), "Лермонтовъ", "en"); + TestPOI lermontov({1, 1}, "Лермонтовъ", "en"); lermontov.SetTypes({{"amenity", "cafe"}}); // A low-rank city with two noname cafes. - TestCity lermontovo(m2::PointD(-1, -1), "Лермонтово", "en", 0 /* rank */); - TestPOI cafe1(m2::PointD(-1.01, -1.01), "", "en"); + TestCity lermontovo({-1, -1}, "Лермонтово", "en", 0 /* rank */); + TestPOI cafe1({-1.01, -1.01}, "", "en"); cafe1.SetTypes({{"amenity", "cafe"}}); - TestPOI cafe2(m2::PointD(-0.99, -0.99), "", "en"); + TestPOI cafe2({-0.99, -0.99}, "", "en"); cafe2.SetTypes({{"amenity", "cafe"}}); // A low-rank village with a single noname cafe. - TestVillage pushkino(m2::PointD(-10, -10), "Pushkino", "en", 0 /* rank */); - TestPOI cafe3(m2::PointD(-10.01, -10.01), "", "en"); + TestVillage pushkino({-10, -10}, "Pushkino", "en", 0 /* rank */); + TestPOI cafe3({-10.01, -10.01}, "", "en"); cafe3.SetTypes({{"amenity", "cafe"}}); auto worldId = BuildWorld([&](TestMwmBuilder & builder) @@ -429,7 +414,7 @@ UNIT_CLASS_TEST(ProcessorTest, TestRankingInfo) builder.Add(waterfall); }); - SetViewport(m2::RectD(m2::PointD(-0.5, -0.5), m2::PointD(0.5, 0.5))); + SetViewport(m2::RectD(-0.5, -0.5, 0.5, 0.5)); { auto request = MakeRequest("golden gate bridge "); @@ -465,7 +450,7 @@ UNIT_CLASS_TEST(ProcessorTest, TestRankingInfo) TEST(ResultsMatch("waterfall", rules), ()); } - SetViewport(m2::RectD(m2::PointD(-10.5, -10.5), m2::PointD(-9.5, -9.5))); + SetViewport(m2::RectD(-10.5, -10.5, -9.5, -9.5)); { Rules rules{ExactMatch(wonderlandId, cafe3)}; TEST(ResultsMatch("cafe pushkino ", rules), ()); @@ -476,21 +461,13 @@ UNIT_CLASS_TEST(ProcessorTest, TestRankingInfo_ErrorsMade) { string const countryName = "Wonderland"; - TestCity chekhov(m2::PointD(0, 0), "Чеховъ Антонъ Павловичъ", "ru", 100 /* rank */); + TestCity chekhov({0, 0}, "Чеховъ Антонъ Павловичъ", "ru", 100 /* rank */); - TestStreet yesenina( - vector{m2::PointD(0.5, -0.5), m2::PointD(0, 0), m2::PointD(-0.5, 0.5)}, - "Yesenina street", "en"); + TestStreet yesenina({{0.5, -0.5}, {0, 0}, {-0.5, 0.5}}, "Yesenina street", "en"); + TestStreet pushkinskaya({{-0.5, -0.5}, {0, 0}, {0.5, 0.5}}, "Улица Пушкинская", "ru"); + TestStreet ostrovskogo({{-0.5, 0.0}, {0, 0}, {0.5, 0.0}}, "улица Островского", "ru"); - TestStreet pushkinskaya( - vector{m2::PointD(-0.5, -0.5), m2::PointD(0, 0), m2::PointD(0.5, 0.5)}, - "Улица Пушкинская", "ru"); - - TestStreet ostrovskogo( - vector{m2::PointD(-0.5, 0.0), m2::PointD(0, 0), m2::PointD(0.5, 0.0)}, - "улица Островского", "ru"); - - TestPOI lermontov(m2::PointD(0, 0), "Трактиръ Лермонтовъ", "ru"); + TestPOI lermontov({0, 0}, "Трактиръ Лермонтовъ", "ru"); lermontov.SetTypes({{"amenity", "cafe"}}); auto worldId = BuildWorld([&](TestMwmBuilder & builder) { builder.Add(chekhov); }); @@ -558,17 +535,15 @@ UNIT_CLASS_TEST(ProcessorTest, TestHouseNumbers) { string const countryName = "HouseNumberLand"; - TestCity greenCity(m2::PointD(0, 0), "Зеленоград", "ru", 100 /* rank */); + TestCity greenCity({0, 0}, "Зеленоград", "ru", 100 /* rank */); - TestStreet street( - vector{m2::PointD(-5.0, -5.0), m2::PointD(0, 0), m2::PointD(5.0, 5.0)}, - "Генерала Генералова", "ru"); + TestStreet street({{-5.0, -5.0}, {0, 0}, {5.0, 5.0}}, "Генерала Генералова", "ru"); - TestBuilding building100(m2::PointD(2.0, 2.0), "", "100", "en"); - TestBuilding building200(m2::PointD(3.0, 3.0), "", "к200", "ru"); - TestBuilding building300(m2::PointD(4.0, 4.0), "", "300 строение 400", "ru"); - TestBuilding building115(m2::PointD(1.0, 1.0), "", "115", "en"); - TestBuilding building115k1(m2::PointD(-1.0, -1.0), "", "115к1", "en"); + TestBuilding building100({2.0, 2.0}, "", "100", "en"); + TestBuilding building200({3.0, 3.0}, "", "к200", "ru"); + TestBuilding building300({4.0, 4.0}, "", "300 строение 400", "ru"); + TestBuilding building115({1.0, 1.0}, "", "115", "en"); + TestBuilding building115k1({-1.0, -1.0}, "", "115к1", "en"); BuildWorld([&](TestMwmBuilder & builder) { builder.Add(greenCity); }); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { @@ -580,7 +555,7 @@ UNIT_CLASS_TEST(ProcessorTest, TestHouseNumbers) builder.Add(building115k1); }); - SetViewport(m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0))); + SetViewport(m2::RectD(-1.0, -1.0, 1.0, 1.0)); { Rules rules{ExactMatch(countryId, building100), ExactMatch(countryId, street)}; @@ -640,29 +615,27 @@ UNIT_CLASS_TEST(ProcessorTest, TestPostcodes) { string const countryName = "Russia"; - TestCity dolgoprudny(m2::PointD(0, 0), "Долгопрудный", "ru", 100 /* rank */); - TestCity london(m2::PointD(10, 10), "London", "en", 100 /* rank */); + TestCity dolgoprudny({0, 0}, "Долгопрудный", "ru", 100 /* rank */); + TestCity london({10, 10}, "London", "en", 100 /* rank */); - TestStreet street( - vector{m2::PointD(-0.5, 0.0), m2::PointD(0, 0), m2::PointD(0.5, 0.0)}, - "Первомайская", "ru"); + TestStreet street({{-0.5, 0.0}, {0, 0}, {0.5, 0.0}}, "Первомайская", "ru"); street.SetPostcode("141701"); - TestBuilding building28(m2::PointD(0.0, 0.00001), "", "28а", street.GetName("ru"), "ru"); + TestBuilding building28({0.0, 0.00001}, "", "28а", street.GetName("ru"), "ru"); building28.SetPostcode("141701"); - TestBuilding building29(m2::PointD(0.0, -0.00001), "", "29", street.GetName("ru"), "ru"); + TestBuilding building29({0.0, -0.00001}, "", "29", street.GetName("ru"), "ru"); building29.SetPostcode("141701"); - TestPOI building30(m2::PointD(0.00002, 0.00002), "", "en"); + TestPOI building30({0.00002, 0.00002}, "", "en"); building30.SetHouseNumber("30"); building30.SetPostcode("141701"); building30.SetTypes({{"building", "address"}}); - TestBuilding building31(m2::PointD(0.00001, 0.00001), "", "31", street.GetName("ru"), "ru"); + TestBuilding building31({0.00001, 0.00001}, "", "31", street.GetName("ru"), "ru"); building31.SetPostcode("141702"); - TestBuilding building1(m2::PointD(10, 10), "", "1", "en"); + TestBuilding building1({10, 10}, "", "1", "en"); building1.SetPostcode("WC2H 7BX"); BuildWorld([&](TestMwmBuilder & builder) @@ -748,30 +721,30 @@ UNIT_CLASS_TEST(ProcessorTest, TestCategories) { string const countryName = "Wonderland"; - TestCity sanFrancisco(m2::PointD(0, 0), "San Francisco", "en", 100 /* rank */); + TestCity sanFrancisco({0, 0}, "San Francisco", "en", 100 /* rank */); - TestPOI nonameBeach(m2::PointD(0, 0), "", "ru"); + TestPOI nonameBeach({0, 0}, "", "ru"); nonameBeach.SetTypes({{"leisure", "beach_resort"}}); - TestPOI namedBeach(m2::PointD(0.2, 0.2), "San Francisco beach", "en"); + TestPOI namedBeach({0.2, 0.2}, "San Francisco beach", "en"); namedBeach.SetTypes({{"natural", "beach"}}); - TestPOI nonameAtm(m2::PointD(0, 0), "", "en"); + TestPOI nonameAtm({0, 0}, "", "en"); nonameAtm.SetTypes({{"amenity", "atm"}}); - TestPOI namedAtm(m2::PointD(0.03, 0.03), "ATM", "en"); + TestPOI namedAtm({0.03, 0.03}, "ATM", "en"); namedAtm.SetTypes({{"amenity", "atm"}}); - TestPOI busStop(m2::PointD(0.00005, 0.0005), "ATM Bus Stop", "en"); + TestPOI busStop({0.00005, 0.0005}, "ATM Bus Stop", "en"); busStop.SetTypes({{"highway", "bus_stop"}}); - TestPOI cafe(m2::PointD(0.0001, 0.0001), "Cafe", "en"); + TestPOI cafe({0.0001, 0.0001}, "Cafe", "en"); cafe.SetTypes({{"amenity", "cafe"}, {"internet_access", "wlan"}}); - TestPOI toi(m2::PointD(0.0001, 0.0001), "", "en"); + TestPOI toi({0.0001, 0.0001}, "", "en"); toi.SetTypes({{"amenity", "toilets"}}); - TestPOI namedResidential(m2::PointD(0.04, 0.04), "Residential", "en"); + TestPOI namedResidential({0.04, 0.04}, "Residential", "en"); namedResidential.SetTypes({{"landuse", "residential"}}); BuildWorld([&](TestMwmBuilder & builder) @@ -790,7 +763,7 @@ UNIT_CLASS_TEST(ProcessorTest, TestCategories) builder.Add(namedResidential); }); - SetViewport(m2::RectD(m2::PointD(-0.5, -0.5), m2::PointD(0.5, 0.5))); + SetViewport(m2::RectD(-0.5, -0.5, 0.5, 0.5)); { Rules const rules = {ExactMatch(wonderlandId, nonameAtm), ExactMatch(wonderlandId, namedAtm), @@ -835,27 +808,27 @@ UNIT_CLASS_TEST(ProcessorTest, TestCategorialSearch) { string const countryName = "Wonderland"; - TestCity sanDiego(m2::PointD(0, 0), "San Diego", "en", 100 /* rank */); - TestCity homel(m2::PointD(10, 10), "Homel", "en", 100 /* rank */); + TestCity sanDiego({0, 0}, "San Diego", "en", 100 /* rank */); + TestCity homel({10, 10}, "Homel", "en", 100 /* rank */); // No need in TestHotel here, TestPOI is enough. - TestPOI hotel1(m2::PointD(0, 0.01), "", "ru"); + TestPOI hotel1({0, 0.01}, "", "ru"); hotel1.SetTypes({{"tourism", "hotel"}}); - TestPOI hotel2(m2::PointD(0, 0.02), "Hotel San Diego, California", "en"); + TestPOI hotel2({0, 0.02}, "Hotel San Diego, California", "en"); hotel2.SetTypes({{"tourism", "hotel"}}); - TestPOI hotelCafe(m2::PointD(0, 0.03), "Hotel", "en"); + TestPOI hotelCafe({0, 0.03}, "Hotel", "en"); hotelCafe.SetTypes({{"amenity", "cafe"}}); - TestPOI hotelDeVille(m2::PointD(0, 0.04), "Hôtel De Ville", "en"); + TestPOI hotelDeVille({0, 0.04}, "Hôtel De Ville", "en"); hotelDeVille.SetTypes({{"amenity", "townhall"}}); - TestPOI nightclub(m2::PointD(0, 0.05), "Moulin Rouge", "fr"); + TestPOI nightclub({0, 0.05}, "Moulin Rouge", "fr"); nightclub.SetTypes({{"amenity", "nightclub"}}); // A POI with that matches "entertainment" only by name. - TestPOI laundry(m2::PointD(0, 0.06), "Entertainment 720", "en"); + TestPOI laundry({0, 0.06}, "Entertainment 720", "en"); laundry.SetTypes({{"shop", "laundry"}}); auto const testWorldId = BuildWorld([&](TestMwmBuilder & builder) { @@ -871,7 +844,7 @@ UNIT_CLASS_TEST(ProcessorTest, TestCategorialSearch) builder.Add(laundry); }); - SetViewport(m2::RectD(m2::PointD(-0.5, -0.5), m2::PointD(0.5, 0.5))); + SetViewport(m2::RectD(-0.5, -0.5, 0.5, 0.5)); { Rules const rules = {ExactMatch(wonderlandId, hotel1), ExactMatch(wonderlandId, hotel2)}; @@ -951,11 +924,11 @@ UNIT_CLASS_TEST(ProcessorTest, SearchDebug) { string const countryName = "Wonderland"; - TestCity debugville(m2::PointD(0, 0), "Debugville", "en", 100 /* rank */); + TestCity debugville({0, 0}, "Debugville", "en", 100 /* rank */); - TestCafe cafe(m2::PointD(0.01, 0), "", "ru"); + TestCafe cafe({0.01, 0}, "", "ru"); - TestPOI hotel(m2::PointD(0, 0.01), "", "ru"); + TestPOI hotel({0, 0.01}, "", "ru"); hotel.SetTypes({{"tourism", "hotel"}}); auto const testWorldId = BuildWorld([&](TestMwmBuilder & builder) { @@ -965,7 +938,7 @@ UNIT_CLASS_TEST(ProcessorTest, SearchDebug) builder.Add(hotel); builder.Add(cafe); }); - RegisterCountry(countryName, m2::RectD(m2::PointD(-100.0, -100.0), m2::PointD(100.0, 100.0))); + RegisterCountry(countryName, m2::RectD(-100.0, -100.0, 100.0, 100.0)); auto const ruleCity = ExactMatch(testWorldId, debugville); auto const ruleCafe = ExactMatch(wonderlandId, cafe); @@ -1039,15 +1012,14 @@ UNIT_CLASS_TEST(ProcessorTest, SearchCoordinates) UNIT_CLASS_TEST(ProcessorTest, FuzzyMatch) { string const countryName = "Wonderland"; - TestCountry country(m2::PointD(10, 10), countryName, "en"); + TestCountry country({10, 10}, countryName, "en"); - TestCity city(m2::PointD(0, 0), "Москва", "ru", 100 /* rank */); - TestStreet street(vector{m2::PointD(-0.001, -0.001), m2::PointD(0.001, 0.001)}, - "Ленинградский", "ru"); - TestPOI bar(m2::PointD(0, 0), "Черчилль", "ru"); + TestCity city({0, 0}, "Москва", "ru", 100 /* rank */); + TestStreet street({{-0.001, -0.001}, {0.001, 0.001}}, "Ленинградский", "ru"); + TestPOI bar({0, 0}, "Черчилль", "ru"); bar.SetTypes({{"amenity", "pub"}}); - TestPOI metro(m2::PointD(5.0, 5.0), "Liceu", "es"); + TestPOI metro({5.0, 5.0}, "Liceu", "es"); metro.SetTypes({{"railway", "subway_entrance"}}); BuildWorld([&](TestMwmBuilder & builder) { @@ -1061,7 +1033,7 @@ UNIT_CLASS_TEST(ProcessorTest, FuzzyMatch) builder.Add(metro); }); - SetViewport(m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0))); + SetViewport(m2::RectD(-1.0, -1.0, 1.0, 1.0)); { Rules rulesWithoutStreet = {ExactMatch(id, bar)}; Rules rules = {ExactMatch(id, bar), ExactMatch(id, street)}; @@ -1093,10 +1065,10 @@ UNIT_CLASS_TEST(ProcessorTest, FuzzyMatch) UNIT_CLASS_TEST(ProcessorTest, SpacesInCategories) { string const countryName = "Wonderland"; - TestCountry country(m2::PointD(10, 10), countryName, "en"); + TestCountry country({10, 10}, countryName, "en"); - TestCity city(m2::PointD(5.0, 5.0), "Москва", "ru", 100 /* rank */); - TestPOI nightclub(m2::PointD(5.0, 5.0), "Crasy daizy", "ru"); + TestCity city({5.0, 5.0}, "Москва", "ru", 100 /* rank */); + TestPOI nightclub({5.0, 5.0}, "Crasy daizy", "ru"); nightclub.SetTypes({{"amenity", "nightclub"}}); BuildWorld([&](TestMwmBuilder & builder) { @@ -1117,13 +1089,11 @@ UNIT_CLASS_TEST(ProcessorTest, SpacesInCategories) UNIT_CLASS_TEST(ProcessorTest, StopWords) { - TestCountry country(m2::PointD(0, 0), "France", "en"); - TestCity city(m2::PointD(0, 0), "Paris", "en", 100 /* rank */); - TestStreet street( - vector{m2::PointD(-0.001, -0.001), m2::PointD(0, 0), m2::PointD(0.001, 0.001)}, - "Rue de la Paix", "en"); + TestCountry country({0, 0}, "France", "en"); + TestCity city({0, 0}, "Paris", "en", 100 /* rank */); + TestStreet street({{-0.001, -0.001}, {0, 0}, {0.001, 0.001}}, "Rue de la Paix", "en"); - TestPOI bakery(m2::PointD(0.0, 0.0), "" /* name */, "en"); + TestPOI bakery({0.0, 0.0}, "" /* name */, "en"); bakery.SetTypes({{"shop", "bakery"}}); BuildWorld([&](TestMwmBuilder & builder) { @@ -1163,13 +1133,13 @@ UNIT_CLASS_TEST(ProcessorTest, StopWords) UNIT_CLASS_TEST(ProcessorTest, Numerals) { - TestCountry country(m2::PointD(0, 0), "Беларусь", "ru"); - TestPOI school(m2::PointD(0, 0), "СШ №61", "ru"); + TestCountry country({0, 0}, "Беларусь", "ru"); + TestPOI school({0, 0}, "СШ №61", "ru"); school.SetTypes({{"amenity", "school"}}); auto id = BuildCountry(country.GetName("ru"), [&](TestMwmBuilder & builder) { builder.Add(school); }); - SetViewport(m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0))); + SetViewport(m2::RectD(-1.0, -1.0, 1.0, 1.0)); { Rules rules{ExactMatch(id, school)}; TEST(ResultsMatch("Школа 61", "ru", rules), ()); @@ -1184,16 +1154,15 @@ UNIT_CLASS_TEST(ProcessorTest, TestWeirdTypes) { string const countryName = "Area51"; - TestCity tokyo(m2::PointD(0, 0), "東京", "ja", 100 /* rank */); + TestCity tokyo({0, 0}, "東京", "ja", 100 /* rank */); - TestStreet street(vector{m2::PointD(-8.0, 0.0), m2::PointD(8.0, 0.0)}, "竹下通り", - "ja"); + TestStreet street({{-8.0, 0.0}, {8.0, 0.0}}, "竹下通り", "ja"); - TestPOI defibrillator1(m2::PointD(0.0, 0.0), "" /* name */, "en"); + TestPOI defibrillator1({0.0, 0.0}, "" /* name */, "en"); defibrillator1.SetTypes({{"emergency", "defibrillator"}}); - TestPOI defibrillator2(m2::PointD(-5.0, 0.0), "" /* name */, "ja"); + TestPOI defibrillator2({-5.0, 0.0}, "" /* name */, "ja"); defibrillator2.SetTypes({{"emergency", "defibrillator"}}); - TestPOI fireHydrant(m2::PointD(2.0, 0.0), "" /* name */, "en"); + TestPOI fireHydrant({2.0, 0.0}, "" /* name */, "en"); fireHydrant.SetTypes({{"emergency", "fire_hydrant"}}); BuildWorld([&](TestMwmBuilder & builder) { builder.Add(tokyo); }); @@ -1232,12 +1201,10 @@ UNIT_CLASS_TEST(ProcessorTest, TestWeirdTypes) UNIT_CLASS_TEST(ProcessorTest, CityBoundaryLoad) { - TestCity city(vector({m2::PointD(0, 0), m2::PointD(0.5, 0), m2::PointD(0.5, 0.5), - m2::PointD(0, 0.5)}), - "moscow", "en", 100 /* rank */); + TestCity city({{0, 0}, {0.5, 0}, {0.5, 0.5}, {0, 0.5}}, "moscow", "en", 100 /* rank */); auto const id = BuildWorld([&](TestMwmBuilder & builder) { builder.Add(city); }); - SetViewport(m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0))); + SetViewport(m2::RectD(-1.0, -1.0, 1.0, 1.0)); { Rules const rules{ExactMatch(id, city)}; TEST(ResultsMatch("moscow", "en", rules), ()); @@ -1250,29 +1217,25 @@ UNIT_CLASS_TEST(ProcessorTest, CityBoundaryLoad) CitiesBoundariesTable::Boundaries boundaries; TEST(table.Get(0 /* fid */, boundaries), ()); - TEST(boundaries.HasPoint(m2::PointD(0, 0)), ()); - TEST(boundaries.HasPoint(m2::PointD(0.5, 0)), ()); - TEST(boundaries.HasPoint(m2::PointD(0.5, 0.5)), ()); - TEST(boundaries.HasPoint(m2::PointD(0, 0.5)), ()); - TEST(boundaries.HasPoint(m2::PointD(0.25, 0.25)), ()); + TEST(boundaries.HasPoint({0, 0}), ()); + TEST(boundaries.HasPoint({0.5, 0}), ()); + TEST(boundaries.HasPoint({0.5, 0.5}), ()); + TEST(boundaries.HasPoint({0, 0.5}), ()); + TEST(boundaries.HasPoint({0.25, 0.25}), ()); - TEST(!boundaries.HasPoint(m2::PointD(0.6, 0.6)), ()); - TEST(!boundaries.HasPoint(m2::PointD(-1, 0.5)), ()); + TEST(!boundaries.HasPoint({0.6, 0.6}), ()); + TEST(!boundaries.HasPoint({-1, 0.5}), ()); } UNIT_CLASS_TEST(ProcessorTest, CityBoundarySmoke) { - TestCity moscow(vector({m2::PointD(0, 0), m2::PointD(0.5, 0), m2::PointD(0.5, 0.5), - m2::PointD(0, 0.5)}), - "Москва", "ru", 100 /* rank */); - TestCity khimki(vector({m2::PointD(0.25, 0.5), m2::PointD(0.5, 0.5), - m2::PointD(0.5, 0.75), m2::PointD(0.25, 0.75)}), - "Химки", "ru", 50 /* rank */); + TestCity moscow({{0, 0}, {0.5, 0}, {0.5, 0.5}, {0, 0.5}}, "Москва", "ru", 100 /* rank */); + TestCity khimki({{0.25, 0.5}, {0.5, 0.5}, {0.5, 0.75}, {0.25, 0.75}}, "Химки", "ru", 50 /* rank */); - TestPOI cafeMoscow(m2::PointD(0.49, 0.49), "Москвичка", "ru"); + TestPOI cafeMoscow({0.49, 0.49}, "Москвичка", "ru"); cafeMoscow.SetTypes({{"amenity", "cafe"}, {"internet_access", "wlan"}}); - TestPOI cafeKhimki(m2::PointD(0.49, 0.51), "Химичка", "ru"); + TestPOI cafeKhimki({0.49, 0.51}, "Химичка", "ru"); cafeKhimki.SetTypes({{"amenity", "cafe"}, {"internet_access", "wlan"}}); BuildWorld([&](TestMwmBuilder & builder) { @@ -1285,7 +1248,7 @@ UNIT_CLASS_TEST(ProcessorTest, CityBoundarySmoke) builder.Add(cafeKhimki); }); - SetViewport(m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0))); + SetViewport(m2::RectD(-1.0, -1.0, 1.0, 1.0)); { auto request = MakeRequest("кафе", "ru"); @@ -1316,23 +1279,22 @@ UNIT_CLASS_TEST(ProcessorTest, CityBoundarySmoke) UNIT_CLASS_TEST(ProcessorTest, RelaxedRetrieval) { string const countryName = "Wonderland"; - TestCountry country(m2::PointD(10.0, 10.0), countryName, "en"); + TestCountry country({10.0, 10.0}, countryName, "en"); TestCity city({{-10.0, -10.0}, {10.0, -10.0}, {10.0, 10.0}, {-10.0, 10.0}} /* boundary */, "Sick City", "en", 255 /* rank */); - TestStreet street(vector{m2::PointD(-1.0, 0.0), m2::PointD(1.0, 0.0)}, "Queer Street", - "en"); - TestBuilding building0(m2::PointD(-1.0, 0.0), "" /* name */, "0", street.GetName("en"), "en"); - TestBuilding building1(m2::PointD(1.0, 0.0), "", "1", street.GetName("en"), "en"); - TestBuilding building2(m2::PointD(2.0, 0.0), "named building", "" /* house number */, "en"); - TestBuilding building3(m2::PointD(3.0, 0.0), "named building", "", "en"); + TestStreet street({{-1.0, 0.0}, {1.0, 0.0}}, "Queer Street", "en"); + TestBuilding building0({-1.0, 0.0}, "" /* name */, "0", street.GetName("en"), "en"); + TestBuilding building1({1.0, 0.0}, "", "1", street.GetName("en"), "en"); + TestBuilding building2({2.0, 0.0}, "named building", "" /* house number */, "en"); + TestBuilding building3({3.0, 0.0}, "named building", "", "en"); - TestPOI poi0(m2::PointD(-1.0, 0.0), "Farmacia de guardia", "en"); + TestPOI poi0({-1.0, 0.0}, "Farmacia de guardia", "en"); poi0.SetTypes({{"amenity", "pharmacy"}}); // A poi inside building2. - TestPOI poi2(m2::PointD(2.0, 0.0), "Post box", "en"); + TestPOI poi2({2.0, 0.0}, "Post box", "en"); poi2.SetTypes({{"amenity", "post_box"}}); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { @@ -1341,7 +1303,7 @@ UNIT_CLASS_TEST(ProcessorTest, RelaxedRetrieval) builder.Add(building1); builder.Add(poi0); }); - RegisterCountry(countryName, m2::RectD(m2::PointD(-10.0, -10.0), m2::PointD(10.0, 10.0))); + RegisterCountry(countryName, m2::RectD(-10.0, -10.0, 10.0, 10.0)); auto worldId = BuildWorld([&](TestMwmBuilder & builder) { builder.Add(country); @@ -1402,31 +1364,28 @@ UNIT_CLASS_TEST(ProcessorTest, PathsThroughLayers) { string const countryName = "Science Country"; - TestCountry scienceCountry(m2::PointD(0.0, 0.0), countryName, "en"); + TestCountry scienceCountry({0.0, 0.0}, countryName, "en"); - TestCity mathTown(vector({m2::PointD(-100.0, -100.0), m2::PointD(100.0, -100.0), - m2::PointD(100.0, 100.0), m2::PointD(-100.0, 100.0)}), + TestCity mathTown({{-100.0, -100.0}, {100.0, -100.0}, {100.0, 100.0}, {-100.0, 100.0}}, "Math Town", "en", 100 /* rank */); - TestStreet computingStreet( - vector{m2::PointD{-16.0, -16.0}, m2::PointD(0.0, 0.0), m2::PointD(16.0, 16.0)}, - "Computing street", "en"); + TestStreet computingStreet({{-16.0, -16.0}, {0.0, 0.0}, {16.0, 16.0}}, "Computing street", "en"); - TestBuilding statisticalLearningBuilding(m2::PointD(8.0, 8.0), + TestBuilding statisticalLearningBuilding({8.0, 8.0}, "Statistical Learning Buisiness Center", "0", computingStreet.GetName("en"), "en"); - TestPOI supervisedOffice(m2::PointD(8.0, 8.0), "Supervised, Inc.", "en"); + TestPOI supervisedOffice({8.0, 8.0}, "Supervised, Inc.", "en"); supervisedOffice.SetTypes({{"office", "company"}}); - TestPOI svmCafe(m2::PointD(8.0, 8.0), "Trattoria SVM", "en"); + TestPOI svmCafe({8.0, 8.0}, "Trattoria SVM", "en"); svmCafe.SetTypes({{"amenity", "cafe"}}); BuildWorld([&](TestMwmBuilder & builder) { builder.Add(scienceCountry); builder.Add(mathTown); }); - RegisterCountry(countryName, m2::RectD(m2::PointD(-100.0, -100.0), m2::PointD(100.0, 100.0))); + RegisterCountry(countryName, m2::RectD(-100.0, -100.0, 100.0, 100.0)); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(computingStreet); @@ -1435,7 +1394,7 @@ UNIT_CLASS_TEST(ProcessorTest, PathsThroughLayers) builder.Add(svmCafe); }); - SetViewport(m2::RectD(m2::PointD(-100.0, -100.0), m2::PointD(100.0, 100.0))); + SetViewport(m2::RectD(-100.0, -100.0, 100.0, 100.0)); for (auto const mode : {FeaturesLayerPathFinder::MODE_AUTO, FeaturesLayerPathFinder::MODE_TOP_DOWN, @@ -1504,7 +1463,7 @@ UNIT_CLASS_TEST(ProcessorTest, SelectProperName) }; TestMultilingualPOI cafe( - m2::PointD(0.0, 0.0), "Default", + {0.0, 0.0}, "Default", {{"es", "Spanish"}, {"int_name", "International"}, {"fr", "French"}, {"ru", "Russian"}}); cafe.SetTypes({{"amenity", "cafe"}}); @@ -1552,10 +1511,10 @@ UNIT_CLASS_TEST(ProcessorTest, CuisineTest) { string const countryName = "Wonderland"; - TestPOI vegan(m2::PointD(1.0, 1.0), "Useless name", "en"); + TestPOI vegan({1.0, 1.0}, "Useless name", "en"); vegan.SetTypes({{"amenity", "cafe"}, {"cuisine", "vegan"}}); - TestPOI pizza(m2::PointD(1.0, 1.0), "Useless name", "en"); + TestPOI pizza({1.0, 1.0}, "Useless name", "en"); pizza.SetTypes({{"amenity", "bar"}, {"cuisine", "pizza"}}); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { @@ -1641,8 +1600,8 @@ UNIT_CLASS_TEST(ProcessorTest, AirportTest) { string const countryName = "Wonderland"; - TestAirport vko(m2::PointD(1.0, 1.0), "Useless name", "en", "VKO"); - TestAirport svo(m2::PointD(1.0, 1.0), "Useless name", "en", "SVO"); + TestAirport vko({1.0, 1.0}, "Useless name", "en", "VKO"); + TestAirport svo({1.0, 1.0}, "Useless name", "en", "SVO"); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(vko); @@ -1666,8 +1625,8 @@ UNIT_CLASS_TEST(ProcessorTest, OperatorTest) { string const countryName = "Wonderland"; - TestATM sber(m2::PointD(1.0, 1.0), "Sberbank", "en"); - TestATM alfa(m2::PointD(1.0, 1.0), "Alfa bank", "en"); + TestATM sber({1.0, 1.0}, "Sberbank", "en"); + TestATM alfa({1.0, 1.0}, "Alfa bank", "en"); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(sber); @@ -1697,8 +1656,8 @@ UNIT_CLASS_TEST(ProcessorTest, BrandTest) { string const countryName = "Wonderland"; - TestBrandFeature mac(m2::PointD(1.0, 1.0), "mcdonalds", "en"); - TestBrandFeature sw(m2::PointD(1.0, 1.0), "subway", "en"); + TestBrandFeature mac({1.0, 1.0}, "mcdonalds", "en"); + TestBrandFeature sw({1.0, 1.0}, "subway", "en"); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(mac); @@ -1730,7 +1689,7 @@ UNIT_CLASS_TEST(ProcessorTest, SquareAsStreetTest) TestSquare square(m2::RectD(0.0, 0.0, 1.0, 1.0), "revolution square", "en"); - TestPOI nonameHouse(m2::PointD(1.0, 1.0), "", "en"); + TestPOI nonameHouse({1.0, 1.0}, "", "en"); nonameHouse.SetHouseNumber("3"); nonameHouse.SetStreetName(square.GetName("en")); @@ -1740,7 +1699,7 @@ UNIT_CLASS_TEST(ProcessorTest, SquareAsStreetTest) builder.Add(nonameHouse); }); - SetViewport(m2::RectD(m2::PointD(0.0, 0.0), m2::PointD(1.0, 2.0))); + SetViewport(m2::RectD(0.0, 0.0, 1.0, 2.0)); { Rules rules = {ExactMatch(countryId, nonameHouse)}; TEST(ResultsMatch("revolution square 3", rules), ()); @@ -1749,8 +1708,8 @@ UNIT_CLASS_TEST(ProcessorTest, SquareAsStreetTest) UNIT_CLASS_TEST(ProcessorTest, CountrySynonymsTest) { - TestCountry usa(m2::PointD(0.5, 0.5), "United States of America", "en"); - TestPOI alabama(m2::PointD(0.5, 0.5), "Alabama", "en"); + TestCountry usa({0.5, 0.5}, "United States of America", "en"); + TestPOI alabama({0.5, 0.5}, "Alabama", "en"); alabama.SetTypes({{"place", "state"}}); auto worldId = BuildWorld([&](TestMwmBuilder & builder) @@ -1759,7 +1718,7 @@ UNIT_CLASS_TEST(ProcessorTest, CountrySynonymsTest) builder.Add(alabama); }); - SetViewport(m2::RectD(m2::PointD(0.0, 0.0), m2::PointD(1.0, 1.0))); + SetViewport(m2::RectD(0.0, 0.0, 1.0, 1.0)); { Rules rules = {ExactMatch(worldId, usa)}; TEST(ResultsMatch("United States of America", rules), ()); @@ -1778,16 +1737,11 @@ UNIT_CLASS_TEST(ProcessorTest, SynonymsTest) { string const countryName = "Wonderland"; - TestStreet streetEn( - vector{m2::PointD(0.5, -0.5), m2::PointD(0.0, 0.0), m2::PointD(-0.5, 0.5)}, - "Southwest street", "en"); + TestStreet streetEn({{0.5, -0.5}, {0.0, 0.0}, {-0.5, 0.5}}, "Southwest street", "en"); + TestStreet streetRu({{-0.5, -0.5}, {0.0, 0.0}, {0.5, 0.5}}, "большая свято-покровская улица", "ru"); - TestStreet streetRu( - vector{m2::PointD(-0.5, -0.5), m2::PointD(0.0, 0.0), m2::PointD(0.5, 0.5)}, - "большая свято-покровская улица", "ru"); - - TestPOI stPeterEn(m2::PointD(2.0, 2.0), "saint peter basilica", "en"); - TestPOI stPeterRu(m2::PointD(-2.0, -2.0), "собор святого петра", "ru"); + TestPOI stPeterEn({2.0, 2.0}, "saint peter basilica", "en"); + TestPOI stPeterRu({-2.0, -2.0}, "собор святого петра", "ru"); auto wonderlandId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(streetEn); @@ -1838,17 +1792,9 @@ UNIT_CLASS_TEST(ProcessorTest, PreprocessBeforeTokenizationTest) { string const countryName = "Wonderland"; - TestStreet prt( - vector{m2::PointD(0.5, -0.5), m2::PointD(0.0, 0.0), m2::PointD(-0.5, 0.5)}, - "Октябрьский проспект", "ru"); - - TestStreet prd( - vector{m2::PointD(-0.5, -0.5), m2::PointD(0.0, 0.0), m2::PointD(0.5, 0.5)}, - "Жуков проезд", "ru"); - - TestStreet nabya( - vector{m2::PointD(0.0, -0.5), m2::PointD(0.0, 0.0), m2::PointD(0.0, 0.5)}, - "Москворецкая набережная", "ru"); + TestStreet prt({{0.5, -0.5}, {0.0, 0.0}, {-0.5, 0.5}}, "Октябрьский проспект", "ru"); + TestStreet prd({{-0.5, -0.5}, {0.0, 0.0}, {0.5, 0.5}}, "Жуков проезд", "ru"); + TestStreet nabya({{0.0, -0.5}, {0.0, 0.0}, {0.0, 0.5}}, "Москворецкая набережная", "ru"); auto wonderlandId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(prt); @@ -1885,11 +1831,9 @@ UNIT_CLASS_TEST(ProcessorTest, StreetNameLocaleTest) streetName.AddString("default", "default"); streetName.AddString("en", "english"); streetName.AddString("ja", "japanese"); - TestStreet street( - vector{m2::PointD(0.0, -0.5), m2::PointD(0.0, 0.0), m2::PointD(0.0, 0.5)}, - streetName); + TestStreet street({{0.0, -0.5}, {0.0, 0.0}, {0.0, 0.5}}, streetName); - TestPOI nonameHouse(m2::PointD(0.0, 0.0), "", "en"); + TestPOI nonameHouse({0.0, 0.0}, "", "en"); nonameHouse.SetHouseNumber("3"); nonameHouse.SetStreetName(street.GetName("ja")); @@ -1898,7 +1842,7 @@ UNIT_CLASS_TEST(ProcessorTest, StreetNameLocaleTest) builder.Add(nonameHouse); }); - SetViewport(m2::RectD(m2::PointD(0.0, 0.0), m2::PointD(1.0, 1.0))); + SetViewport(m2::RectD(0.0, 0.0, 1.0, 1.0)); { Rules rules = {ExactMatch(countryId, nonameHouse)}; TEST(ResultsMatch("default 3", rules), ()); @@ -1911,11 +1855,9 @@ UNIT_CLASS_TEST(ProcessorTest, RemoveDuplicatingStreets) string const streetName = "Октябрьский проспект"; // Distance between centers should be less than 5km. - TestStreet street1(vector{m2::PointD(0.0, 0.0), m2::PointD(0.0, 0.01)}, - streetName, "ru"); + TestStreet street1({{0.0, 0.0}, {0.0, 0.01}}, streetName, "ru"); street1.SetHighwayType("primary"); - TestStreet street2(vector{m2::PointD(0.0, 0.01), m2::PointD(0.0, 0.02)}, - streetName, "ru"); + TestStreet street2({{0.0, 0.01}, {0.0, 0.02}}, streetName, "ru"); street1.SetHighwayType("secondary"); auto wonderlandId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { @@ -1933,10 +1875,9 @@ UNIT_CLASS_TEST(ProcessorTest, ExactMatchTest) { string const countryName = "Wonderland"; - TestCafe lermontov(m2::PointD(1, 1), "Лермонтовъ", "ru"); - - TestCity lermontovo(m2::PointD(-1, -1), "Лермонтово", "ru", 0 /* rank */); - TestCafe cafe(m2::PointD(-1.01, -1.01), "", "ru"); + TestCafe lermontov({1, 1}, "Лермонтовъ", "ru"); + TestCity lermontovo({-1, -1}, "Лермонтово", "ru", 0 /* rank */); + TestCafe cafe({-1.01, -1.01}, "", "ru"); auto worldId = BuildWorld([&](TestMwmBuilder & builder) { builder.Add(lermontovo); }); auto wonderlandId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { @@ -2016,10 +1957,9 @@ UNIT_CLASS_TEST(ProcessorTest, StreetSynonymPrefix) string const countryName = "Wonderland"; // Est is a prefix of "estrada". - TestStreet street(vector{m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0)}, - "Boulevard Maloney Est", "en"); + TestStreet street({{-1.0, -1.0}, {1.0, 1.0}}, "Boulevard Maloney Est", "en"); - TestPOI house(m2::PointD(1.0, 1.0), "", "en"); + TestPOI house({1.0, 1.0}, "", "en"); house.SetHouseNumber("3"); house.SetStreetName(street.GetName("en")); @@ -2028,7 +1968,7 @@ UNIT_CLASS_TEST(ProcessorTest, StreetSynonymPrefix) builder.Add(house); }); - SetViewport(m2::RectD(m2::PointD(0.0, 0.0), m2::PointD(1.0, 2.0))); + SetViewport(m2::RectD(0.0, 0.0, 1.0, 2.0)); { Rules rules = {ExactMatch(countryId, house), ExactMatch(countryId, street)}; TEST(ResultsMatch("3 Boulevard Maloney Est", rules), ()); @@ -2039,10 +1979,8 @@ UNIT_CLASS_TEST(ProcessorTest, Strasse) { string const countryName = "Wonderland"; - TestStreet s1(vector{m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0)}, "abcdstraße", - "en"); - TestStreet s2(vector{m2::PointD(1.0, -1.0), m2::PointD(-1.0, 1.0)}, "xyz strasse", - "en"); + TestStreet s1({{-1.0, -1.0},{1.0, 1.0}}, "abcdstraße", "en"); + TestStreet s2({{1.0, -1.0}, {-1.0, 1.0}}, "xyz strasse", "en"); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(s1); @@ -2060,7 +1998,7 @@ UNIT_CLASS_TEST(ProcessorTest, Strasse) TEST(nameScore == NAME_SCORE_FULL_MATCH || nameScore == NAME_SCORE_PREFIX, (query)); }; - SetViewport(m2::RectD(m2::PointD(0.0, 0.0), m2::PointD(1.0, 2.0))); + SetViewport(m2::RectD(0.0, 0.0, 1.0, 2.0)); { Rules rules = {ExactMatch(countryId, s1)}; checkNoErrors("abcdstrasse ", rules); @@ -2097,12 +2035,9 @@ UNIT_CLASS_TEST(ProcessorTest, StreetSynonymsWithMisprints) { string const countryName = "Wonderland"; - TestStreet leninsky(vector{m2::PointD(0.0, -1.0), m2::PointD(0.0, 1.0)}, - "Ленинский проспект", "ru"); - TestStreet nabrezhnaya(vector{m2::PointD(1.0, -1.0), m2::PointD(1.0, 1.0)}, - "улица набрежная", "ru"); - TestStreet naberezhnaya(vector{m2::PointD(2.0, -1.0), m2::PointD(2.0, 1.0)}, - "улица набережная", "ru"); + TestStreet leninsky({{0.0, -1.0}, {0.0, 1.0}}, "Ленинский проспект", "ru"); + TestStreet nabrezhnaya({{1.0, -1.0}, {1.0, 1.0}}, "улица набрежная", "ru"); + TestStreet naberezhnaya({{2.0, -1.0}, {2.0, 1.0}}, "улица набережная", "ru"); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(leninsky); @@ -2110,7 +2045,7 @@ UNIT_CLASS_TEST(ProcessorTest, StreetSynonymsWithMisprints) builder.Add(naberezhnaya); }); - SetViewport(m2::RectD(m2::PointD(0.0, -1.0), m2::PointD(2.0, 1.0))); + SetViewport(m2::RectD(0.0, -1.0, 2.0, 1.0)); { Rules rules = {ExactMatch(countryId, leninsky)}; TEST(ResultsMatch("ленинский проспект", rules), ()); @@ -2132,22 +2067,19 @@ UNIT_CLASS_TEST(ProcessorTest, HouseOnStreetSynonymsWithMisprints) { string const countryName = "Wonderland"; - TestStreet tverskoi(vector{m2::PointD(1.0, -1.0), m2::PointD(1.0, 1.0)}, - "Tverskoi Boulevard", "en"); - TestStreet leninsky(vector{m2::PointD(0.0, -1.0), m2::PointD(0.0, 1.0)}, - "Leninsky Avenue", "en"); - TestStreet mira(vector{m2::PointD(-1.0, -1.0), m2::PointD(-1.0, 1.0)}, - "Проспект Мира", "ru"); + TestStreet tverskoi({{1.0, -1.0}, {1.0, 1.0}}, "Tverskoi Boulevard", "en"); + TestStreet leninsky({{0.0, -1.0}, {0.0, 1.0}}, "Leninsky Avenue", "en"); + TestStreet mira({{-1.0, -1.0}, {-1.0, 1.0}}, "Проспект Мира", "ru"); - TestPOI houseTverskoi(m2::PointD(1.0, 0.0), "", "en"); + TestPOI houseTverskoi({1.0, 0.0}, "", "en"); houseTverskoi.SetHouseNumber("3"); houseTverskoi.SetStreetName(tverskoi.GetName("en")); - TestPOI houseLeninsky(m2::PointD(0.0, 0.0), "", "en"); + TestPOI houseLeninsky({0.0, 0.0}, "", "en"); houseLeninsky.SetHouseNumber("5"); houseLeninsky.SetStreetName(leninsky.GetName("en")); - TestPOI houseMira(m2::PointD(-1.0, 0.0), "", "en"); + TestPOI houseMira({-1.0, 0.0}, "", "en"); houseMira.SetHouseNumber("7"); houseMira.SetStreetName(mira.GetName("ru")); @@ -2160,7 +2092,7 @@ UNIT_CLASS_TEST(ProcessorTest, HouseOnStreetSynonymsWithMisprints) builder.Add(houseMira); }); - SetViewport(m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0))); + SetViewport(m2::RectD(-1.0, -1.0, 1.0, 1.0)); { Rules rules = {ExactMatch(countryId, houseTverskoi)}; Rules rulesWithStreet = {ExactMatch(countryId, houseTverskoi), ExactMatch(countryId, tverskoi)}; @@ -2196,11 +2128,9 @@ UNIT_CLASS_TEST(ProcessorTest, StreetSynonymPrefixMatch) { string const countryName = "Wonderland"; - TestStreet yesenina( - vector{m2::PointD(0.5, -0.5), m2::PointD(0, 0), m2::PointD(-0.5, 0.5)}, - "Yesenina street", "en"); + TestStreet yesenina({{0.5, -0.5}, {0, 0}, {-0.5, 0.5}}, "Yesenina street", "en"); - TestPOI cafe(m2::PointD(0, 0), "", "en"); + TestPOI cafe({0, 0}, "", "en"); cafe.SetTypes({{"amenity", "cafe"}}); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { @@ -2227,10 +2157,10 @@ UNIT_CLASS_TEST(ProcessorTest, SynonymMisprintsTest) { string const countryName = "Wonderland"; - TestStreet bolshaya({m2::PointD(0.5, -0.5), m2::PointD(-0.5, 0.5)}, "большая дмитровка", "ru"); - TestCafe bolnaya(m2::PointD(0.0, 0.0), "больная дмитровка", "ru"); - TestStreet sw({m2::PointD(0.5, -0.5), m2::PointD(0.5, 0.5)}, "southwest street", "en"); - TestStreet se({m2::PointD(-0.5, -0.5), m2::PointD(-0.5, 0.5)}, "southeast street", "en"); + TestStreet bolshaya({{0.5, -0.5}, {-0.5, 0.5}}, "большая дмитровка", "ru"); + TestCafe bolnaya({0.0, 0.0}, "больная дмитровка", "ru"); + TestStreet sw({{0.5, -0.5}, {0.5, 0.5}}, "southwest street", "en"); + TestStreet se({{-0.5, -0.5}, {-0.5, 0.5}}, "southeast street", "en"); auto wonderlandId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(bolshaya); @@ -2271,15 +2201,13 @@ UNIT_CLASS_TEST(ProcessorTest, VillagePostcodes) { string const countryName = "France"; - TestVillage marckolsheim(m2::PointD(0, 0), "Marckolsheim", "en", 10 /* rank */); + TestVillage marckolsheim({0, 0}, "Marckolsheim", "en", 10 /* rank */); marckolsheim.SetPostcode("67390"); - TestStreet street( - vector{m2::PointD(-0.5, 0.0), m2::PointD(0, 0), m2::PointD(0.5, 0.0)}, - "Rue des Serpents", "en"); + TestStreet street({{-0.5, 0.0}, {0, 0}, {0.5, 0.0}}, "Rue des Serpents", "en"); - TestBuilding building4(m2::PointD(0.0, 0.00001), "", "4", street.GetName("en"), "en"); - TestPOI poi(m2::PointD(0.0, -0.00001), "Carrefour", "en"); + TestBuilding building4({0.0, 0.00001}, "", "4", street.GetName("en"), "en"); + TestPOI poi({0.0, -0.00001}, "Carrefour", "en"); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(marckolsheim); @@ -2317,12 +2245,10 @@ UNIT_CLASS_TEST(ProcessorTest, StreetPostcodes) { string const countryName = "France"; - TestStreet street( - vector{m2::PointD(-0.5, 0.0), m2::PointD(0, 0), m2::PointD(0.5, 0.0)}, - "Rue des Serpents", "en"); + TestStreet street({{-0.5, 0.0}, {0, 0}, {0.5, 0.0}}, "Rue des Serpents", "en"); street.SetPostcode("67390"); - TestBuilding building4(m2::PointD(0.0, 0.00001), "", "4", street.GetName("en"), "en"); + TestBuilding building4({0.0, 0.00001}, "", "4", street.GetName("en"), "en"); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(street); @@ -2346,14 +2272,12 @@ UNIT_CLASS_TEST(ProcessorTest, CityPostcodes) { string const countryName = "Russia"; - TestCity moscow(m2::PointD(0, 0), "Moscow", "en", 100 /* rank */); + TestCity moscow({0, 0}, "Moscow", "en", 100 /* rank */); moscow.SetPostcode("123456"); - TestStreet street( - vector{m2::PointD(-0.5, 0.0), m2::PointD(0, 0), m2::PointD(0.5, 0.0)}, - "Tverskaya", "en"); + TestStreet street({{-0.5, 0.0}, {0, 0}, {0.5, 0.0}}, "Tverskaya", "en"); - TestBuilding building(m2::PointD(0.0, 0.00001), "", "4", street.GetName("en"), "en"); + TestBuilding building({0.0, 0.00001}, "", "4", street.GetName("en"), "en"); auto const worldId = BuildWorld([&](TestMwmBuilder & builder) { builder.Add(moscow); @@ -2377,15 +2301,14 @@ UNIT_CLASS_TEST(ProcessorTest, StreetNumber) { string const countryName = "Wonderland"; - TestStreet street(vector{m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0)}, - "Симферопольское шоссе", "ru"); + TestStreet street({{-1.0, -1.0}, {1.0, 1.0}}, "Симферопольское шоссе", "ru"); street.SetRoadNumber("M2"); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(street); }); - SetViewport(m2::RectD(m2::PointD(0.0, 0.0), m2::PointD(1.0, 2.0))); + SetViewport(m2::RectD(0.0, 0.0, 1.0, 2.0)); { Rules rules = {ExactMatch(countryId, street)}; TEST(ResultsMatch("M2 ", rules), ()); @@ -2396,19 +2319,19 @@ UNIT_CLASS_TEST(ProcessorTest, StreetNumberEnriched) { string const countryName = "Wonderland"; - TestStreet street(vector{m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0)}, "Нева", "ru"); + TestStreet street({{-1.0, -1.0}, {1.0, 1.0}}, "Нева", "ru"); street.SetRoadNumber("M-11;ru:national/M-11"); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(street); }); - SetViewport(m2::RectD(m2::PointD(0.0, 0.0), m2::PointD(1.0, 2.0))); + SetViewport(m2::RectD(0.0, 0.0, 1.0, 2.0)); { Rules rules = {ExactMatch(countryId, street)}; TEST(ResultsMatch("M-11 ", rules), ()); } - SetViewport(m2::RectD(m2::PointD(0.0, 0.0), m2::PointD(1.0, 2.0))); + SetViewport(m2::RectD(0.0, 0.0, 1.0, 2.0)); { Rules rules = {}; TEST(ResultsMatch("ru ", rules), ()); @@ -2420,14 +2343,14 @@ UNIT_CLASS_TEST(ProcessorTest, Postbox) { string const countryName = "Wonderland"; - TestPOI postbox(m2::PointD(0.0, 0.0), "127001", "default"); + TestPOI postbox({0.0, 0.0}, "127001", "default"); postbox.SetTypes({{"amenity", "post_box"}}); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(postbox); }); - SetViewport(m2::RectD(m2::PointD(0.0, 0.0), m2::PointD(1.0, 1.0))); + SetViewport(m2::RectD(0.0, 0.0, 1.0, 1.0)); { Rules rules = {ExactMatch(countryId, postbox)}; TEST(ResultsMatch("127001", rules), ()); @@ -2443,16 +2366,14 @@ UNIT_CLASS_TEST(ProcessorTest, OrderCountries) { string const cafeLandName = "CafeLand"; string const UkCountryName = "UK"; - TestCity london(m2::PointD(1.0, 1.0), "London", "en", 100 /* rank */); - TestStreet piccadilly(vector{m2::PointD(0.5, 0.5), m2::PointD(1.5, 1.5)}, - "Piccadilly Circus", "en"); - TestVillage cambridge(m2::PointD(3.0, 3.0), "Cambridge", "en", 5 /* rank */); - TestStreet wheeling(vector{m2::PointD(2.5, 2.5), m2::PointD(3.5, 3.5)}, - "Wheeling Avenue", "en"); + TestCity london({1.0, 1.0}, "London", "en", 100 /* rank */); + TestStreet piccadilly({{0.5, 0.5}, {1.5, 1.5}}, "Piccadilly Circus", "en"); + TestVillage cambridge({3.0, 3.0}, "Cambridge", "en", 5 /* rank */); + TestStreet wheeling({{2.5, 2.5}, {3.5, 3.5}}, "Wheeling Avenue", "en"); - TestPOI dummyPoi(m2::PointD(0.0, 4.0), "dummy", "en"); - TestCafe londonCafe(m2::PointD(-10.01, 14.0), "London Piccadilly cafe", "en"); - TestCafe cambridgeCafe(m2::PointD(-10.02, 14.01), "Cambridge Wheeling cafe", "en"); + TestPOI dummyPoi({0.0, 4.0}, "dummy", "en"); + TestCafe londonCafe({-10.01, 14.0}, "London Piccadilly cafe", "en"); + TestCafe cambridgeCafe({-10.02, 14.01}, "Cambridge Wheeling cafe", "en"); auto worldId = BuildWorld([&](TestMwmBuilder & builder) { builder.Add(london); }); auto UkId = BuildCountry(UkCountryName, [&](TestMwmBuilder & builder) { @@ -2461,7 +2382,7 @@ UNIT_CLASS_TEST(ProcessorTest, OrderCountries) builder.Add(cambridge); builder.Add(wheeling); }); - auto const UkCountryRect = m2::RectD(m2::PointD(0.5, 0.5), m2::PointD(3.5, 3.5)); + auto const UkCountryRect = m2::RectD(0.5, 0.5, 3.5, 3.5); RegisterCountry(UkCountryName, UkCountryRect); auto cafeLandId = BuildCountry(cafeLandName, [&](TestMwmBuilder & builder) { @@ -2470,10 +2391,10 @@ UNIT_CLASS_TEST(ProcessorTest, OrderCountries) builder.Add(cambridgeCafe); }); - auto const cafeLandRect = m2::RectD(m2::PointD(-10.5, 4.0), m2::PointD(0.0, 14.5)); + auto const cafeLandRect = m2::RectD(-10.5, 4.0, 0.0, 14.5); RegisterCountry(cafeLandName, cafeLandRect); - auto const viewportRect = m2::RectD(m2::PointD(-1.0, 5.0), m2::PointD(0.0, 4.0)); + auto const viewportRect = m2::RectD(-1.0, 4.0, 0.0, 5.0); SetViewport(viewportRect); CHECK(!viewportRect.IsIntersect(UkCountryRect), ()); CHECK(viewportRect.IsIntersect(cafeLandRect), ()); @@ -2504,18 +2425,16 @@ UNIT_CLASS_TEST(ProcessorTest, Suburbs) { string const countryName = "Wonderland"; - TestPOI suburb(m2::PointD(0, 0), "Bloomsbury", "en"); + TestPOI suburb({0, 0}, "Bloomsbury", "en"); suburb.SetTypes({{"place", "suburb"}}); - TestStreet street( - vector{m2::PointD(-0.5, -0.5), m2::PointD(0, 0), m2::PointD(0.5, 0.5)}, - "Malet place", "en"); + TestStreet street({{-0.5, -0.5}, {0, 0}, {0.5, 0.5}}, "Malet place", "en"); - TestPOI house(m2::PointD(0.5, 0.5), "", "en"); + TestPOI house({0.5, 0.5}, "", "en"); house.SetHouseNumber("3"); house.SetStreetName(street.GetName("en")); - TestCafe cafe(m2::PointD(0.01, 0.01), "", "en"); + TestCafe cafe({0.01, 0.01}, "", "en"); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(suburb); @@ -2548,8 +2467,8 @@ UNIT_CLASS_TEST(ProcessorTest, Suburbs) UNIT_CLASS_TEST(ProcessorTest, ViewportFilter) { - TestStreet street23({m2::PointD(0.5, -1.0), m2::PointD(0.5, 1.0)}, "23rd February street", "en"); - TestStreet street8({m2::PointD(0.0, -1.0), m2::PointD(0.0, 1.0)}, "8th March street", "en"); + TestStreet street23({{0.5, -1.0}, {0.5, 1.0}}, "23rd February street", "en"); + TestStreet street8({{0.0, -1.0}, {0.0, 1.0}}, "8th March street", "en"); auto const countryId = BuildCountry("Wounderland", [&](TestMwmBuilder & builder) { builder.Add(street23); @@ -2560,7 +2479,7 @@ UNIT_CLASS_TEST(ProcessorTest, ViewportFilter) SearchParams params; params.m_query = "8th March street 23"; params.m_inputLocale = "en"; - params.m_viewport = m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0)); + params.m_viewport = m2::RectD(-1.0, -1.0, 1.0, 1.0); params.m_mode = Mode::Viewport; // |street23| should not appear in viewport search because it has 2 unmatched tokens. @@ -2576,7 +2495,7 @@ UNIT_CLASS_TEST(ProcessorTest, ViewportFilter) SearchParams params; params.m_query = "8th March street 23"; params.m_inputLocale = "en"; - params.m_viewport = m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0)); + params.m_viewport = m2::RectD(-1.0, -1.0, 1.0, 1.0); params.m_mode = Mode::Everywhere; // |street23| should be in everywhere search results because everywhere search mode does not @@ -2591,12 +2510,12 @@ UNIT_CLASS_TEST(ProcessorTest, ViewportFilter) UNIT_CLASS_TEST(ProcessorTest, FilterStreetPredictions) { - TestCity smallCity(m2::PointD(3.0, 0.0), "SmallCity", "en", 1 /* rank */); + TestCity smallCity({3.0, 0.0}, "SmallCity", "en", 1 /* rank */); - TestStreet lenina0({m2::PointD(0.0, -1.0), m2::PointD(0.0, 1.0)}, "Lenina", "en"); - TestStreet lenina1({m2::PointD(1.0, -1.0), m2::PointD(1.0, 1.0)}, "Lenina", "en"); - TestStreet lenina2({m2::PointD(2.0, -1.0), m2::PointD(2.0, 1.0)}, "Lenina", "en"); - TestStreet lenina3({m2::PointD(3.0, -1.0), m2::PointD(3.0, 1.0)}, "Lenina", "en"); + TestStreet lenina0({{0.0, -1.0}, {0.0, 1.0}}, "Lenina", "en"); + TestStreet lenina1({{1.0, -1.0}, {1.0, 1.0}}, "Lenina", "en"); + TestStreet lenina2({{2.0, -1.0}, {2.0, 1.0}}, "Lenina", "en"); + TestStreet lenina3({{3.0, -1.0}, {3.0, 1.0}}, "Lenina", "en"); auto const countryId = BuildCountry("Wounderland", [&](TestMwmBuilder & builder) { builder.Add(lenina0); @@ -2610,7 +2529,7 @@ UNIT_CLASS_TEST(ProcessorTest, FilterStreetPredictions) SearchParams defaultParams; defaultParams.m_query = "Lenina"; defaultParams.m_inputLocale = "en"; - defaultParams.m_viewport = m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0)); + defaultParams.m_viewport = m2::RectD(-1.0, -1.0, 1.0, 1.0); defaultParams.m_mode = Mode::Everywhere; defaultParams.m_streetSearchRadiusM = TestSearchRequest::kDefaultTestStreetSearchRadiusM; @@ -2629,7 +2548,7 @@ UNIT_CLASS_TEST(ProcessorTest, FilterStreetPredictions) auto params = defaultParams; params.m_streetSearchRadiusM = - mercator::DistanceOnEarth(params.m_viewport.Center(), m2::PointD(3.0, 0.0)) - 1.0; + mercator::DistanceOnEarth(params.m_viewport.Center(), {3.0, 0.0}) - 1.0; TestSearchRequest request(m_engine, params); request.Run(); @@ -2641,7 +2560,7 @@ UNIT_CLASS_TEST(ProcessorTest, FilterStreetPredictions) auto params = defaultParams; params.m_streetSearchRadiusM = - mercator::DistanceOnEarth(params.m_viewport.Center(), m2::PointD(2.0, 0.0)) - 1.0; + mercator::DistanceOnEarth(params.m_viewport.Center(), {2.0, 0.0}) - 1.0; TestSearchRequest request(m_engine, params); request.Run(); @@ -2653,7 +2572,7 @@ UNIT_CLASS_TEST(ProcessorTest, FilterStreetPredictions) auto params = defaultParams; params.m_streetSearchRadiusM = - mercator::DistanceOnEarth(params.m_viewport.Center(), m2::PointD(1.0, 0.0)) - 1.0; + mercator::DistanceOnEarth(params.m_viewport.Center(), {1.0, 0.0}) - 1.0; TestSearchRequest request(m_engine, params); request.Run(); @@ -2665,8 +2584,8 @@ UNIT_CLASS_TEST(ProcessorTest, FilterStreetPredictions) auto params = defaultParams; params.m_streetSearchRadiusM = - mercator::DistanceOnEarth(params.m_viewport.Center(), m2::PointD(1.0, 0.0)) - 1.0; - params.m_position = m2::PointD(3.0, 0.0); + mercator::DistanceOnEarth(params.m_viewport.Center(), {1.0, 0.0}) - 1.0; + params.m_position = {3.0, 0.0}; TestSearchRequest request(m_engine, params); request.Run(); @@ -2678,7 +2597,7 @@ UNIT_CLASS_TEST(ProcessorTest, FilterStreetPredictions) auto params = defaultParams; params.m_streetSearchRadiusM = - mercator::DistanceOnEarth(params.m_viewport.Center(), m2::PointD(1.0, 0.0)) - 1.0; + mercator::DistanceOnEarth(params.m_viewport.Center(), {1.0, 0.0}) - 1.0; params.m_query = "SmallCity Lenina"; TestSearchRequest request(m_engine, params); @@ -2689,14 +2608,14 @@ UNIT_CLASS_TEST(ProcessorTest, FilterStreetPredictions) UNIT_CLASS_TEST(ProcessorTest, FilterVillages) { - TestState moscowRegion(m2::PointD(10.0, 10.0), "Moscow Region", "en"); + TestState moscowRegion({10.0, 10.0}, "Moscow Region", "en"); // |moscowRegion| feature should belong to MoscowRegion with some margin due to mwmPointAccuracy. - TestPOI dummy(m2::PointD(9.99, 9.99), "", "en"); - TestVillage petrovskoeMoscow(m2::PointD(10.5, 10.5), "Petrovskoe", "en", 5 /* rank */); + TestPOI dummy({9.99, 9.99}, "", "en"); + TestVillage petrovskoeMoscow({10.5, 10.5}, "Petrovskoe", "en", 5 /* rank */); - TestVillage petrovskoe0(m2::PointD(0.0, 0.0), "Petrovskoe", "en", 5 /* rank */); - TestVillage petrovskoe1(m2::PointD(1.0, 1.0), "Petrovskoe", "en", 5 /* rank */); - TestVillage petrovskoe2(m2::PointD(2.0, 2.0), "Petrovskoe", "en", 5 /* rank */); + TestVillage petrovskoe0({0.0, 0.0}, "Petrovskoe", "en", 5 /* rank */); + TestVillage petrovskoe1({1.0, 1.0}, "Petrovskoe", "en", 5 /* rank */); + TestVillage petrovskoe2({2.0, 2.0}, "Petrovskoe", "en", 5 /* rank */); auto const moscowId = BuildCountry("MoscowRegion", [&](TestMwmBuilder & builder) { builder.Add(petrovskoeMoscow); @@ -2714,7 +2633,7 @@ UNIT_CLASS_TEST(ProcessorTest, FilterVillages) SearchParams defaultParams; defaultParams.m_query = "Petrovskoe"; defaultParams.m_inputLocale = "en"; - defaultParams.m_viewport = m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0)); + defaultParams.m_viewport = m2::RectD(-1.0, -1.0, 1.0, 1.0); defaultParams.m_mode = Mode::Everywhere; defaultParams.m_villageSearchRadiusM = TestSearchRequest::kDefaultTestVillageSearchRadiusM; @@ -2768,7 +2687,7 @@ UNIT_CLASS_TEST(ProcessorTest, FilterVillages) Rules const rules = {ExactMatch(otherId, petrovskoe0), ExactMatch(otherId, petrovskoe2)}; auto params = defaultParams; - params.m_position = m2::PointD(2.0, 2.0); + params.m_position = {2.0, 2.0}; params.m_villageSearchRadiusM = min(mercator::DistanceOnEarth(params.m_viewport.Center(), petrovskoe1.GetCenter()), mercator::DistanceOnEarth(*params.m_position, petrovskoe1.GetCenter())); @@ -2798,10 +2717,8 @@ UNIT_CLASS_TEST(ProcessorTest, MatchedFraction) string const countryName = "Wonderland"; string const streetName = "Октябрьский проспaект"; - TestStreet street1(vector{m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0)}, - "Первомайская", "ru"); - TestStreet street2(vector{m2::PointD(-1.0, 1.0), m2::PointD(1.0, -1.0)}, - "8 марта", "ru"); + TestStreet street1({{-1.0, -1.0}, {1.0, 1.0}}, "Первомайская", "ru"); + TestStreet street2({{-1.0, 1.0}, {1.0, -1.0}}, "8 марта", "ru"); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(street1); @@ -2824,22 +2741,22 @@ UNIT_CLASS_TEST(ProcessorTest, AvoidMatchAroundPivotInMwmWithCity) { string const minskCountryName = "Minsk"; - TestCity minsk(m2::PointD(-10.0, -10.0), "Minsk", "en", 10 /* rank */); + TestCity minsk({-10.0, -10.0}, "Minsk", "en", 10 /* rank */); // World.mwm should intersect viewport. - TestPOI dummy(m2::PointD(10.0, 10.0), "", "en"); + TestPOI dummy({10.0, 10.0}, "", "en"); auto worldId = BuildWorld([&](TestMwmBuilder & builder) { builder.Add(minsk); builder.Add(dummy); }); - TestCafe minskCafe(m2::PointD(-9.99, -9.99), "Minsk cafe", "en"); + TestCafe minskCafe({-9.99, -9.99}, "Minsk cafe", "en"); auto minskId = BuildCountry(minskCountryName, [&](TestMwmBuilder & builder) { builder.Add(minsk); builder.Add(minskCafe); }); - SetViewport(m2::RectD(m2::PointD(-1.0, -1.0), m2::PointD(1.0, 1.0))); + SetViewport(m2::RectD(-1.0, -1.0, 1.0, 1.0)); { // Minsk cafe should not appear here because we have (worldId, minsk) result with all tokens // used. @@ -2857,13 +2774,13 @@ UNIT_CLASS_TEST(ProcessorTest, AvoidMatchAroundPivotInMwmWithCity) UNIT_CLASS_TEST(ProcessorTest, LocalityScorer) { - TestCity sp0(m2::PointD(0.0, 0.0), "San Pedro", "en", 50 /* rank */); - TestCity sp1(m2::PointD(1.0, 1.0), "San Pedro", "en", 50 /* rank */); - TestCity sp2(m2::PointD(2.0, 2.0), "San Pedro", "en", 50 /* rank */); - TestCity sp3(m2::PointD(3.0, 3.0), "San Pedro", "en", 50 /* rank */); - TestCity sp4(m2::PointD(4.0, 4.0), "San Pedro", "en", 50 /* rank */); - TestCity spAtacama(m2::PointD(5.5, 5.5), "San Pedro de Atacama", "en", 100 /* rank */); - TestCity spAlcantara(m2::PointD(6.5, 6.5), "San Pedro de Alcantara", "en", 40 /* rank */); + TestCity sp0({0.0, 0.0}, "San Pedro", "en", 50 /* rank */); + TestCity sp1({1.0, 1.0}, "San Pedro", "en", 50 /* rank */); + TestCity sp2({2.0, 2.0}, "San Pedro", "en", 50 /* rank */); + TestCity sp3({3.0, 3.0}, "San Pedro", "en", 50 /* rank */); + TestCity sp4({4.0, 4.0}, "San Pedro", "en", 50 /* rank */); + TestCity spAtacama({5.5, 5.5}, "San Pedro de Atacama", "en", 100 /* rank */); + TestCity spAlcantara({6.5, 6.5}, "San Pedro de Alcantara", "en", 40 /* rank */); auto worldId = BuildWorld([&](TestMwmBuilder & builder) { builder.Add(sp0); @@ -2875,7 +2792,7 @@ UNIT_CLASS_TEST(ProcessorTest, LocalityScorer) builder.Add(spAlcantara); }); - SetViewport(m2::RectD(m2::PointD(0.0, 0.0), m2::PointD(2.0, 2.0))); + SetViewport(m2::RectD(0.0, 0.0, 2.0, 2.0)); { Rules rules = {ExactMatch(worldId, spAtacama)}; TEST(ResultsMatch("San Pedro de Atacama ", rules), ()); @@ -2892,21 +2809,13 @@ UNIT_CLASS_TEST(ProcessorTest, StreetWithNumber) { string const countryName = "Wonderland"; - TestStreet street1( - vector{m2::PointD(-0.5, 1.0), m2::PointD(0.0, 1.0), m2::PointD(0.5, 1.0)}, - "1-я Тверская-Ямская", "ru"); + TestStreet street1({{-0.5, 1.0}, {0.0, 1.0}, {0.5, 1.0}}, "1-я Тверская-Ямская", "ru"); + TestStreet street8({{-0.5, 1.0}, {0.0, 0.0}, {0.5, 0.0}}, "8 Марта", "ru"); + TestStreet street11({{-0.5, -1.0}, {0.0, -1.0}, {0.5, -1.0}}, "11-я Магистральная", "ru"); - TestStreet street8( - vector{m2::PointD(-0.5, 1.0), m2::PointD(0.0, 0.0), m2::PointD(0.5, 0.0)}, - "8 Марта", "ru"); - - TestStreet street11( - vector{m2::PointD(-0.5, -1.0), m2::PointD(0.0, -1.0), m2::PointD(0.5, -1.0)}, - "11-я Магистральная", "ru"); - - TestBuilding building1(m2::PointD(0.0, 1.00001), "", "1", street1.GetName("ru"), "en"); - TestBuilding building8(m2::PointD(0.0, 0.00001), "", "8", street8.GetName("ru"), "en"); - TestBuilding building11(m2::PointD(0.0, -1.00001), "", "11", street11.GetName("ru"), "en"); + TestBuilding building1({0.0, 1.00001}, "", "1", street1.GetName("ru"), "en"); + TestBuilding building8({0.0, 0.00001}, "", "8", street8.GetName("ru"), "en"); + TestBuilding building11({0.0, -1.00001}, "", "11", street11.GetName("ru"), "en"); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(street1); @@ -2942,7 +2851,7 @@ UNIT_CLASS_TEST(ProcessorTest, SimilarLanguage) TEST_EQUAL(results.size(), expectedRes ? 1 : 0, (results, language, searchString, expectedRes)); }; - TestMultilingualPOI poi(m2::PointD(0.0, 0.0), "default", + TestMultilingualPOI poi({0.0, 0.0}, "default", {{"en", "Jiyugaoka Station"}, {"int_name", "international"}, {"ja", "自由が丘"}, @@ -2977,7 +2886,7 @@ UNIT_CLASS_TEST(ProcessorTest, AltAndOldName) { string const countryName = "Wonderland"; - TestMultilingualPOI poi(m2::PointD(0.0, 0.0), "default", + TestMultilingualPOI poi({0.0, 0.0}, "default", {{"en", "english"}, {"alt_name", "alternative"}, {"old_name", "old"}}); auto wonderlandId = @@ -3001,17 +2910,15 @@ UNIT_CLASS_TEST(ProcessorTest, TestRankingInfo_IsAltOrOldName) cityName.AddString("default", "Санкт-Петербург"); cityName.AddString("alt_name", "Питер"); cityName.AddString("old_name", "Ленинград"); - TestCity city(m2::PointD(0.0, 0.0), cityName, 100 /* rank */); + TestCity city({0.0, 0.0}, cityName, 100 /* rank */); StringUtf8Multilang streetName; streetName.AddString("default", "Большой проспект Васильевского Острова"); streetName.AddString("alt_name", "Большой проспект В. О."); streetName.AddString("old_name", "проспект Пролетарской Победы"); - TestStreet street( - vector{m2::PointD(0.0, -0.5), m2::PointD(0.0, 0.0), m2::PointD(0.0, 0.5)}, - streetName); + TestStreet street({{0.0, -0.5}, {0.0, 0.0}, {0.0, 0.5}}, streetName); - TestMultilingualPOI poi(m2::PointD(0.0, 0.0), "KFC", + TestMultilingualPOI poi({0.0, 0.0}, "KFC", {{"alt_name", "Kentucky Fried Chicken"}, {"old_name", "Ростикс"}}); auto worldId = BuildWorld([&](TestMwmBuilder & builder) { builder.Add(city); }); @@ -3077,15 +2984,15 @@ UNIT_CLASS_TEST(ProcessorTest, JaKanaNormalizationTest) { string const countryName = "Wonderland"; - TestPOI poiHiragana(m2::PointD(0.0, 0.0), "とうきょうと", "default"); - TestPOI poiKatakana(m2::PointD(1.0, 1.0), "トウキョウト", "default"); + TestPOI poiHiragana({0.0, 0.0}, "とうきょうと", "default"); + TestPOI poiKatakana({1.0, 1.0}, "トウキョウト", "default"); auto countryId = BuildCountry(countryName, [&](TestMwmBuilder & builder) { builder.Add(poiHiragana); builder.Add(poiKatakana); }); - SetViewport(m2::RectD(m2::PointD(0.0, 0.0), m2::PointD(1.0, 1.0))); + SetViewport(m2::RectD(0.0, 0.0, 1.0, 1.0)); { Rules rules = {ExactMatch(countryId, poiHiragana), ExactMatch(countryId, poiKatakana)}; TEST(ResultsMatch("とうきょうと", rules), ()); @@ -3100,7 +3007,7 @@ UNIT_CLASS_TEST(ProcessorTest, TestRankingInfo_MultipleOldNames) StringUtf8Multilang cityName; cityName.AddString("default", "Санкт-Петербург"); cityName.AddString("old_name", "Ленинград;Петроград"); - TestCity city(m2::PointD(0.0, 0.0), cityName, 100 /* rank */); + TestCity city({0.0, 0.0}, cityName, 100 /* rank */); auto worldId = BuildWorld([&](TestMwmBuilder & builder) { builder.Add(city); }); -- 2.45.3 From c7fad20b0f5407a11b1fc865f8cbe3b6cd9289a4 Mon Sep 17 00:00:00 2001 From: Viktor Govako Date: Fri, 10 Dec 2021 16:31:12 +0300 Subject: [PATCH 14/21] Removed obsolete Framework::m_cityFinder. Signed-off-by: Viktor Govako --- map/framework.cpp | 35 ----------------------------------- map/framework.hpp | 6 ------ 2 files changed, 41 deletions(-) diff --git a/map/framework.cpp b/map/framework.cpp index e50b607746..9e84aafa51 100644 --- a/map/framework.cpp +++ b/map/framework.cpp @@ -159,23 +159,6 @@ bool ParseSetGpsTrackMinAccuracyCommand(string const & query) GpsTrackFilter::StoreMinHorizontalAccuracy(value); return true; } -/* -string MakeSearchBookingUrl(booking::Api const & bookingApi, search::CityFinder & cityFinder, - FeatureType & ft) -{ - string name; - auto const & info = ft.GetID().m_mwmId.GetInfo(); - ASSERT(info, ()); - - int8_t lang = feature::GetNameForSearchOnBooking(info->GetRegionData(), ft.GetNames(), name); - - if (lang == StringUtf8Multilang::kUnsupportedLanguageCode) - return {}; - - string city = cityFinder.GetCityName(feature::GetCenter(ft), lang); - - return bookingApi.GetSearchUrl(city, name); -}*/ } // namespace pair Framework::RegisterMap(LocalCountryFile const & localFile) @@ -383,8 +366,6 @@ Framework::Framework(FrameworkParams const & params) m_routingManager.SetTransitManager(&m_transitManager); - InitCityFinder(); - // Init storage with needed callback. m_storage.Init(bind(&Framework::OnCountryFileDownloaded, this, _1, _2), bind(&Framework::OnCountryFileDelete, this, _1, _2)); @@ -3111,15 +3092,6 @@ void Framework::CreateNote(osm::MapObject const & mapObject, DeactivateMapSelection(true /* notifyUI */); } -storage::CountriesVec Framework::GetTopmostCountries(ms::LatLon const & latlon) const -{ - m2::PointD const point = mercator::FromLatLon(latlon); - auto const countryId = m_infoGetter->GetRegionCountryId(point); - storage::CountriesVec topmostCountryIds; - GetStorage().GetTopmostNodesFor(countryId, topmostCountryIds); - return topmostCountryIds; -} - void Framework::RunUITask(function fn) { GetPlatform().RunTask(Platform::Thread::Gui, move(fn)); @@ -3218,13 +3190,6 @@ void Framework::RegisterCountryFilesOnRoute(shared_ptr ptr) [&ptr](platform::CountryFile const & file) { ptr->RegisterFile(file); }); } -void Framework::InitCityFinder() -{ - ASSERT(!m_cityFinder, ()); - - m_cityFinder = make_unique(m_featuresFetcher.GetDataSource()); -} - void Framework::SetPlacePageLocation(place_page::Info & info) { ASSERT(m_infoGetter, ()); diff --git a/map/framework.hpp b/map/framework.hpp index 82a35bca22..f2c64bfdd7 100644 --- a/map/framework.hpp +++ b/map/framework.hpp @@ -736,15 +736,9 @@ public: void CreateNote(osm::MapObject const & mapObject, osm::Editor::NoteProblemType const type, std::string const & note); -public: - storage::CountriesVec GetTopmostCountries(ms::LatLon const & latlon) const; - private: - std::unique_ptr m_cityFinder; CachingAddressGetter m_addressGetter; - void InitCityFinder(); - public: // TipsApi::Delegate override. bool HaveTransit(m2::PointD const & pt) const; -- 2.45.3 From 05a4fcfb5e37a269c0beeb374072a30774c87285 Mon Sep 17 00:00:00 2001 From: Viktor Govako Date: Sat, 11 Dec 2021 20:18:56 +0300 Subject: [PATCH 15/21] [storage] Use std::move semantics. Signed-off-by: Viktor Govako --- platform/country_file.cpp | 12 +++------ platform/country_file.hpp | 10 +++----- platform/local_country_file_utils.cpp | 2 ++ .../platform_tests/country_file_tests.cpp | 24 +++++++++++------- .../local_country_file_tests.cpp | 7 ++---- storage/country.hpp | 6 ++--- storage/country_tree.cpp | 25 ++++++++----------- storage/country_tree.hpp | 8 +++--- 8 files changed, 42 insertions(+), 52 deletions(-) diff --git a/platform/country_file.cpp b/platform/country_file.cpp index e68777cb79..6ff6e77eab 100644 --- a/platform/country_file.cpp +++ b/platform/country_file.cpp @@ -32,18 +32,14 @@ namespace platform { CountryFile::CountryFile() : m_mapSize(0) {} -CountryFile::CountryFile(string name) : m_name(std::move(name)), m_mapSize(0) {} - -string const & CountryFile::GetName() const { return m_name; } - -void CountryFile::SetRemoteSize(MwmSize mapSize) +CountryFile::CountryFile(std::string name) +: m_name(std::move(name)), m_mapSize(0) { - m_mapSize = mapSize; } -MwmSize CountryFile::GetRemoteSize() const +CountryFile::CountryFile(std::string name, MwmSize size, std::string sha1) +: m_name(std::move(name)), m_mapSize(size), m_sha1(sha1) { - return m_mapSize; } string GetFileName(string const & countryFile, MapFileType type) diff --git a/platform/country_file.hpp b/platform/country_file.hpp index 5799310bc6..01f0521896 100644 --- a/platform/country_file.hpp +++ b/platform/country_file.hpp @@ -17,18 +17,14 @@ class CountryFile public: CountryFile(); explicit CountryFile(std::string name); + CountryFile(std::string name, MwmSize size, std::string sha1); /// \returns Empty (invalid) CountryFile. bool IsEmpty() const { return m_name.empty(); } /// \returns file name without extensions. - std::string const & GetName() const; - - /// \note Remote size is size of mwm in bytes. - void SetRemoteSize(MwmSize mapSize); - MwmSize GetRemoteSize() const; - - void SetSha1(std::string const & base64Sha1) { m_sha1 = base64Sha1; } + std::string const & GetName() const { return m_name; } + MwmSize GetRemoteSize() const { return m_mapSize; } std::string const & GetSha1() const { return m_sha1; } inline bool operator<(const CountryFile & rhs) const { return m_name < rhs.m_name; } diff --git a/platform/local_country_file_utils.cpp b/platform/local_country_file_utils.cpp index 32cf860620..0d57d87341 100644 --- a/platform/local_country_file_utils.cpp +++ b/platform/local_country_file_utils.cpp @@ -222,6 +222,8 @@ void FindAllLocalMapsAndCleanup(int64_t latestVersion, string const & dataDir, vector & localFiles) { string const dir = GetDataDirFullPath(dataDir); + + /// @todo Should we search for files in root data folder, except minsk-pass tests? FindAllLocalMapsInDirectoryAndCleanup(dir, 0 /* version */, latestVersion, localFiles); Platform::TFilesWithType fwts; diff --git a/platform/platform_tests/country_file_tests.cpp b/platform/platform_tests/country_file_tests.cpp index 0e0a009120..f3b313b491 100644 --- a/platform/platform_tests/country_file_tests.cpp +++ b/platform/platform_tests/country_file_tests.cpp @@ -13,17 +13,23 @@ namespace platform { UNIT_TEST(CountryFile_Smoke) { - CountryFile countryFile("TestCountryOneComponent"); - TEST_EQUAL("TestCountryOneComponent", countryFile.GetName(), ()); - string const mapFileName = - GetFileName(countryFile.GetName(), MapFileType::Map); + { + CountryFile cf("One"); + TEST_EQUAL("One", cf.GetName(), ()); + string const mapFileName = GetFileName(cf.GetName(), MapFileType::Map); - TEST_EQUAL("TestCountryOneComponent" DATA_FILE_EXTENSION, mapFileName, ()); + TEST_EQUAL("One" DATA_FILE_EXTENSION, mapFileName, ()); + TEST_EQUAL(0, cf.GetRemoteSize(), ()); + } - TEST_EQUAL(0, countryFile.GetRemoteSize(), ()); + { + CountryFile cf("Three", 666, "xxxSHAxxx"); + TEST_EQUAL("Three", cf.GetName(), ()); + string const mapFileName = GetFileName(cf.GetName(), MapFileType::Map); - countryFile.SetRemoteSize(3 /* mapSize */); - - TEST_EQUAL(3, countryFile.GetRemoteSize(), ()); + TEST_EQUAL("Three" DATA_FILE_EXTENSION, mapFileName, ()); + TEST_EQUAL(666, cf.GetRemoteSize(), ()); + TEST_EQUAL("xxxSHAxxx", cf.GetSha1(), ()); + } } } // namespace platform diff --git a/platform/platform_tests/local_country_file_tests.cpp b/platform/platform_tests/local_country_file_tests.cpp index 58e5ad4c68..f0d58df4ef 100644 --- a/platform/platform_tests/local_country_file_tests.cpp +++ b/platform/platform_tests/local_country_file_tests.cpp @@ -59,9 +59,7 @@ UNIT_TEST(LocalCountryFile_ParseVersion) // Checks basic functionality of LocalCountryFile. UNIT_TEST(LocalCountryFile_Smoke) { - CountryFile countryFile("TestCountry"); - countryFile.SetRemoteSize(1 /* mapSize */); - + CountryFile countryFile("TestCountry", 1 /* size */, "sha1"); LocalCountryFile localFile("/test-dir", countryFile, 150309); TEST_EQUAL("/test-dir/TestCountry" DATA_FILE_EXTENSION, localFile.GetPath(MapFileType::Map), ()); @@ -85,8 +83,7 @@ UNIT_TEST(LocalCountryFile_DiskFiles) { Platform & platform = GetPlatform(); - CountryFile countryFile("TestCountry"); - countryFile.SetRemoteSize(1 /* mapSize */); + CountryFile countryFile("TestCountry", 1 /* size */, "sha1"); for (int64_t version : {1, 150312}) { diff --git a/storage/country.hpp b/storage/country.hpp index d59c933baf..3e832b1351 100644 --- a/storage/country.hpp +++ b/storage/country.hpp @@ -38,7 +38,7 @@ public: { } - void SetFile(platform::CountryFile const & file) { m_file = file; } + void SetFile(platform::CountryFile && file) { m_file = std::move(file); } void SetSubtreeAttrs(MwmCounter subtreeMwmNumber, MwmSize subtreeMwmSizeBytes) { m_subtreeMwmNumber = subtreeMwmNumber; @@ -46,12 +46,10 @@ public: } MwmCounter GetSubtreeMwmCounter() const { return m_subtreeMwmNumber; } MwmSize GetSubtreeMwmSizeBytes() const { return m_subtreeMwmSizeBytes; } - CountryId GetParent() const { return m_parent; } - /// This function valid for current logic - one file for one country (region). - /// If the logic will be changed, replace GetFile with ForEachFile. platform::CountryFile const & GetFile() const { return m_file; } CountryId const & Name() const { return m_name; } + CountryId const & GetParent() const { return m_parent; } private: /// Name in the country node tree. In single mwm case it's a country id. diff --git a/storage/country_tree.cpp b/storage/country_tree.cpp index d9b5e196d3..556ed1f6cd 100644 --- a/storage/country_tree.cpp +++ b/storage/country_tree.cpp @@ -77,13 +77,8 @@ public: { Country country(id, parent); if (mapSize) - { - CountryFile countryFile(id); - countryFile.SetRemoteSize(mapSize); - countryFile.SetSha1(mapSha1); - country.SetFile(countryFile); - } - return &m_countries.AddAtDepth(depth, country); + country.SetFile(CountryFile{id, mapSize, mapSha1}); + return &m_countries.AddAtDepth(depth, std::move(country)); } void InsertOldMwmMapping(CountryId const & newId, CountryId const & oldId) override @@ -171,13 +166,13 @@ public: // CountryTree::Node ------------------------------------------------------------------------------- -CountryTree::Node * CountryTree::Node::AddAtDepth(size_t level, Country const & value) +CountryTree::Node * CountryTree::Node::AddAtDepth(size_t level, Country && value) { Node * node = this; while (--level > 0 && !node->m_children.empty()) node = node->m_children.back().get(); ASSERT_EQUAL(level, 0, ()); - return node->Add(value); + return node->Add(std::move(value)); } CountryTree::Node const & CountryTree::Node::Parent() const @@ -253,9 +248,9 @@ void CountryTree::Node::ForEachAncestorExceptForTheRoot( m_parent->ForEachAncestorExceptForTheRoot(f); } -CountryTree::Node * CountryTree::Node::Add(Country const & value) +CountryTree::Node * CountryTree::Node::Add(Country && value) { - m_children.emplace_back(std::make_unique(value, this)); + m_children.emplace_back(std::make_unique(std::move(value), this)); return m_children.back().get(); } @@ -273,22 +268,22 @@ CountryTree::Node & CountryTree::GetRoot() return *m_countryTree; } -Country & CountryTree::AddAtDepth(size_t level, Country const & value) +Country & CountryTree::AddAtDepth(size_t level, Country && value) { Node * added = nullptr; if (level == 0) { ASSERT(IsEmpty(), ()); - m_countryTree = std::make_unique(value, nullptr); // Creating the root node. + m_countryTree = std::make_unique(std::move(value), nullptr); // Creating the root node. added = m_countryTree.get(); } else { - added = m_countryTree->AddAtDepth(level, value); + added = m_countryTree->AddAtDepth(level, std::move(value)); } ASSERT(added, ()); - m_countryTreeMap.insert(make_pair(value.Name(), added)); + m_countryTreeMap.insert(make_pair(added->Value().Name(), added)); return added->Value(); } diff --git a/storage/country_tree.hpp b/storage/country_tree.hpp index 9e6c91a42a..87e43b8db6 100644 --- a/storage/country_tree.hpp +++ b/storage/country_tree.hpp @@ -29,7 +29,7 @@ public: public: using NodeCallback = std::function; - Node(Country const & value, Node * parent) : m_value(value), m_parent(parent) {} + Node(Country && value, Node * parent) : m_value(std::move(value)), m_parent(parent) {} Country const & Value() const { return m_value; } Country & Value() { return m_value; } @@ -43,7 +43,7 @@ public: /// \param value is a value of node which will be added. /// \note This method does not let to add a node to an arbitrary place in the tree. /// It's posible to add children only from "right side". - Node * AddAtDepth(size_t level, Country const & value); + Node * AddAtDepth(size_t level, Country && value); bool HasParent() const { return m_parent != nullptr; } @@ -74,7 +74,7 @@ public: void ForEachAncestorExceptForTheRoot(NodeCallback const & f) const; private: - Node * Add(Country const & value); + Node * Add(Country && value); Country m_value; @@ -91,7 +91,7 @@ public: Node & GetRoot(); - Country & AddAtDepth(size_t level, Country const & value); + Country & AddAtDepth(size_t level, Country && value); /// Deletes all children and makes tree empty void Clear(); -- 2.45.3 From b09d4280f97c4b47c7a2c87d4cae2d6b30c759cc Mon Sep 17 00:00:00 2001 From: Viktor Govako Date: Sun, 26 Dec 2021 21:29:59 +0300 Subject: [PATCH 16/21] [storage] Comment old diff scheme logic until refactoring. Signed-off-by: Viktor Govako --- android/jni/com/mapswithme/maps/Framework.cpp | 6 ++ android/jni/com/mapswithme/maps/Framework.hpp | 4 +- .../src/com/mapswithme/maps/Framework.java | 28 ++++----- defines.hpp | 9 +-- indexer/data_source.hpp | 2 - indexer/features_offsets_table.cpp | 1 + iphone/Maps/Classes/MapViewController.mm | 27 ++++---- map/framework.cpp | 38 ++++++------ map/framework.hpp | 3 +- platform/constants.hpp | 4 +- platform/local_country_file.cpp | 28 ++++----- platform/local_country_file.hpp | 29 ++++----- platform/local_country_file_utils.cpp | 18 +++--- platform/local_country_file_utils.hpp | 6 +- .../local_country_file_tests.cpp | 5 +- routing/mwm_hierarchy_handler.cpp | 2 +- routing/routing_tests/mwm_hierarchy_test.cpp | 13 +--- storage/routing_helpers.cpp | 17 +++-- storage/routing_helpers.hpp | 7 ++- storage/storage.cpp | 62 +++++++++++-------- storage/storage.hpp | 38 ++++++------ .../country_info_getter_tests.cpp | 6 +- storage/storage_tests/storage_tests.cpp | 42 +++++++------ 23 files changed, 198 insertions(+), 197 deletions(-) diff --git a/android/jni/com/mapswithme/maps/Framework.cpp b/android/jni/com/mapswithme/maps/Framework.cpp index d6afd8a2b2..88106faeec 100644 --- a/android/jni/com/mapswithme/maps/Framework.cpp +++ b/android/jni/com/mapswithme/maps/Framework.cpp @@ -574,6 +574,7 @@ void Framework::DeactivatePopup() m_work.DeactivateMapSelection(false); } +/* string Framework::GetOutdatedCountriesString() { vector countries; @@ -595,6 +596,7 @@ string Framework::GetOutdatedCountriesString() return res; } +*/ void Framework::SetTrafficStateListener(TrafficManager::TrafficStateChangedFn const & fn) { @@ -702,10 +704,12 @@ void Framework::EnableDownloadOn3g() m_work.GetDownloadingPolicy().EnableCellularDownload(true); } +/* int Framework::ToDoAfterUpdate() const { return (int) m_work.ToDoAfterUpdate(); } +*/ void Framework::OnPowerFacilityChanged(power_management::Facility const facility, bool enabled) { @@ -946,6 +950,7 @@ Java_com_mapswithme_maps_Framework_nativeFormatSpeed(JNIEnv * env, jclass, jdoub return jni::ToJavaString(env, measurement_utils::FormatSpeed(speed)); } +/* JNIEXPORT jobject JNICALL Java_com_mapswithme_maps_Framework_nativeGetOutdatedCountriesString(JNIEnv * env, jclass) { @@ -983,6 +988,7 @@ Java_com_mapswithme_maps_Framework_nativeUpdateSavedDataVersion(JNIEnv * env, jc { frm()->UpdateSavedDataVersion(); } +*/ JNIEXPORT jlong JNICALL Java_com_mapswithme_maps_Framework_nativeGetDataVersion(JNIEnv * env, jclass) diff --git a/android/jni/com/mapswithme/maps/Framework.hpp b/android/jni/com/mapswithme/maps/Framework.hpp index be4f72c742..3950059149 100644 --- a/android/jni/com/mapswithme/maps/Framework.hpp +++ b/android/jni/com/mapswithme/maps/Framework.hpp @@ -156,7 +156,7 @@ namespace android void DeactivatePopup(); - std::string GetOutdatedCountriesString(); +// std::string GetOutdatedCountriesString(); void SetMyPositionModeListener(location::TMyPositionModeChanged const & fn); location::EMyPositionMode GetMyPositionMode(); @@ -188,7 +188,7 @@ namespace android bool IsDownloadOn3gEnabled(); void EnableDownloadOn3g(); - int ToDoAfterUpdate() const; +// int ToDoAfterUpdate() const; // PowerManager::Subscriber overrides: void OnPowerFacilityChanged(power_management::Facility const facility, bool enabled) override; diff --git a/android/src/com/mapswithme/maps/Framework.java b/android/src/com/mapswithme/maps/Framework.java index 9f7ddd4a53..06e77c4989 100644 --- a/android/src/com/mapswithme/maps/Framework.java +++ b/android/src/com/mapswithme/maps/Framework.java @@ -186,20 +186,20 @@ public class Framework public static native void nativeRemovePlacePageActivationListener(); - @UiThread - public static native String nativeGetOutdatedCountriesString(); - - @UiThread - @NonNull - public static native String[] nativeGetOutdatedCountries(); - - @UiThread - @DoAfterUpdate - public static native int nativeToDoAfterUpdate(); - - public static native boolean nativeIsDataVersionChanged(); - - public static native void nativeUpdateSavedDataVersion(); +// @UiThread +// public static native String nativeGetOutdatedCountriesString(); +// +// @UiThread +// @NonNull +// public static native String[] nativeGetOutdatedCountries(); +// +// @UiThread +// @DoAfterUpdate +// public static native int nativeToDoAfterUpdate(); +// +// public static native boolean nativeIsDataVersionChanged(); +// +// public static native void nativeUpdateSavedDataVersion(); public static native long nativeGetDataVersion(); diff --git a/defines.hpp b/defines.hpp index 3479010277..5aed2bbf7f 100644 --- a/defines.hpp +++ b/defines.hpp @@ -10,8 +10,6 @@ #define OSM2FEATURE_FILE_EXTENSION ".osm2ft" #define EXTENSION_TMP ".tmp" #define RAW_GEOM_FILE_EXTENSION ".rawgeom" -#define LOC_IDX_FILE_EXTENSION ".locidx" -#define LOC_DATA_FILE_EXTENSION ".locdata" #define OSM_DATA_FILE_EXTENSION ".osm" #define ARCHIVE_TRACKS_FILE_EXTENSION ".track" #define ARCHIVE_TRACKS_ZIPPED_FILE_EXTENSION ".track.zip" @@ -67,15 +65,10 @@ #define TRANSIT_FILE_EXTENSION ".transit.json" #define GEOM_INDEX_TMP_EXT ".geomidx.tmp" -#define CELL2FEATURE_SORTED_EXT ".c2f.sorted" -#define CELL2FEATURE_TMP_EXT ".c2f.tmp" - -#define LOCALITY_INDEX_TMP_EXT ".locidx.tmp" -#define CELL2LOCALITY_SORTED_EXT ".c2l.sorted" -#define CELL2LOCALITY_TMP_EXT ".c2l.tmp" #define COUNTRIES_FILE "countries.txt" #define SERVER_DATAVERSION_FILE "data_version.json" +#define COUNTRIES_ROOT "Countries" #define COUNTRIES_META_FILE "countries_meta.txt" #define LEAP_SPEEDS_FILE "leap_speeds.json" diff --git a/indexer/data_source.hpp b/indexer/data_source.hpp index 9464b34448..d88eecbec0 100644 --- a/indexer/data_source.hpp +++ b/indexer/data_source.hpp @@ -29,8 +29,6 @@ public: using FeatureIdCallback = std::function; using StopSearchCallback = std::function; - ~DataSource() override = default; - /// Registers a new map. std::pair RegisterMap(platform::LocalCountryFile const & localFile); diff --git a/indexer/features_offsets_table.cpp b/indexer/features_offsets_table.cpp index 32e853ef82..636d28ff74 100644 --- a/indexer/features_offsets_table.cpp +++ b/indexer/features_offsets_table.cpp @@ -72,6 +72,7 @@ namespace feature table->m_file.Open(cont.GetFileName()); auto p = cont.GetAbsoluteOffsetAndSize(FEATURE_OFFSETS_FILE_TAG); + ASSERT(p.first % 4 == 0, (p.first)); // will get troubles in succinct otherwise table->m_handle.Assign(table->m_file.Map(p.first, p.second, FEATURE_OFFSETS_FILE_TAG)); succinct::mapper::map(table->m_table, table->m_handle.GetData()); diff --git a/iphone/Maps/Classes/MapViewController.mm b/iphone/Maps/Classes/MapViewController.mm index 0e32541f8e..8c3abaa9e6 100644 --- a/iphone/Maps/Classes/MapViewController.mm +++ b/iphone/Maps/Classes/MapViewController.mm @@ -339,18 +339,21 @@ NSString *const kPP2BookmarkEditingSegue = @"PP2BookmarkEditing"; if (isLaunchedByDeeplink) (void)[DeepLinkHandler.shared handleDeepLink]; - else { - // TODO(vng): Uncomment update dialog when we're ready to handle more traffic. -// auto const todo = GetFramework().ToDoAfterUpdate(); -// switch (todo) { -// case Framework::DoAfterUpdate::Migrate: -// case Framework::DoAfterUpdate::Nothing: -// break; -// case Framework::DoAfterUpdate::AutoupdateMaps: -// case Framework::DoAfterUpdate::AskForUpdateMaps: -// [self presentViewController:[MWMAutoupdateController instanceWithPurpose:todo] animated:YES completion:nil]; -// break; -// } + else + { + /// @todo: Uncomment update dialog when will be ready to handle big traffic bursts. + /* + auto const todo = GetFramework().ToDoAfterUpdate(); + switch (todo) { + case Framework::DoAfterUpdate::Migrate: + case Framework::DoAfterUpdate::Nothing: + break; + case Framework::DoAfterUpdate::AutoupdateMaps: + case Framework::DoAfterUpdate::AskForUpdateMaps: + [self presentViewController:[MWMAutoupdateController instanceWithPurpose:todo] animated:YES completion:nil]; + break; + } + */ } } diff --git a/map/framework.cpp b/map/framework.cpp index 9e84aafa51..19ee7f653b 100644 --- a/map/framework.cpp +++ b/map/framework.cpp @@ -161,9 +161,17 @@ bool ParseSetGpsTrackMinAccuracyCommand(string const & query) } } // namespace -pair Framework::RegisterMap(LocalCountryFile const & localFile) +pair Framework::RegisterMap(LocalCountryFile const & file) { - return m_featuresFetcher.RegisterMap(localFile); + auto const 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*/) @@ -433,7 +441,7 @@ void Framework::ShowNode(storage::CountryId const & countryId) ShowRect(CalcLimitRect(countryId, GetStorage(), GetCountryInfoGetter())); } -void Framework::OnCountryFileDownloaded(storage::CountryId const & countryId, +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. @@ -443,9 +451,8 @@ void Framework::OnCountryFileDownloaded(storage::CountryId const & countryId, if (localFile && localFile->OnDisk(MapFileType::Map)) { - // Add downloaded map. - auto p = m_featuresFetcher.RegisterMap(*localFile); - MwmSet::MwmId const & id = p.first; + auto const res = RegisterMap(*localFile); + MwmSet::MwmId const & id = res.first; if (id.IsAlive()) rect = id.GetInfo()->m_bordersRect; } @@ -529,16 +536,7 @@ void Framework::RegisterAllMaps() vector> maps; m_storage.GetLocalMaps(maps); for (auto const & localFile : maps) - { - auto p = RegisterMap(*localFile); - if (p.second != MwmSet::RegResult::Success) - continue; - - MwmSet::MwmId const & id = p.first; - ASSERT(id.IsAlive(), ()); - - LOG(LINFO, ("Loaded", localFile->GetCountryName(), "map, of version", id.GetInfo()->GetVersion())); - } + UNUSED_VALUE(RegisterMap(*localFile)); } void Framework::DeregisterAllMaps() @@ -1220,6 +1218,7 @@ string Framework::GetCountryName(m2::PointD const & pt) const return info.m_name; } +/* Framework::DoAfterUpdate Framework::ToDoAfterUpdate() const { auto const connectionStatus = Platform::ConnectionStatus(); @@ -1243,6 +1242,7 @@ Framework::DoAfterUpdate Framework::ToDoAfterUpdate() const return DoAfterUpdate::AskForUpdateMaps; } +*/ SearchAPI & Framework::GetSearchAPI() { @@ -3186,8 +3186,10 @@ void Framework::OnRouteFollow(routing::RouterType type) // RoutingManager::Delegate void Framework::RegisterCountryFilesOnRoute(shared_ptr ptr) const { - m_storage.ForEachCountryFile( - [&ptr](platform::CountryFile const & file) { ptr->RegisterFile(file); }); + m_storage.ForEachCountry([&ptr](storage::Country const & country) + { + ptr->RegisterFile(country.GetFile()); + }); } void Framework::SetPlacePageLocation(place_page::Info & info) diff --git a/map/framework.hpp b/map/framework.hpp index f2c64bfdd7..9ea0ca7b0c 100644 --- a/map/framework.hpp +++ b/map/framework.hpp @@ -269,8 +269,7 @@ public: AskForUpdateMaps, Migrate }; - - DoAfterUpdate ToDoAfterUpdate() const; +// DoAfterUpdate ToDoAfterUpdate() const; storage::Storage & GetStorage() { return m_storage; } storage::Storage const & GetStorage() const { return m_storage; } diff --git a/platform/constants.hpp b/platform/constants.hpp index d465b5aed3..9ce6b7cdbb 100644 --- a/platform/constants.hpp +++ b/platform/constants.hpp @@ -2,5 +2,5 @@ #include -static const uint32_t READER_CHUNK_LOG_SIZE = 10; -static const uint32_t READER_CHUNK_LOG_COUNT = 12; +constexpr uint32_t READER_CHUNK_LOG_SIZE = 10; +constexpr uint32_t READER_CHUNK_LOG_COUNT = 12; diff --git a/platform/local_country_file.cpp b/platform/local_country_file.cpp index 68f833580f..0d7bab1729 100644 --- a/platform/local_country_file.cpp +++ b/platform/local_country_file.cpp @@ -36,13 +36,15 @@ void LocalCountryFile::SyncWithDisk() uint64_t size = 0; // Now we are not working with several files at the same time and diffs have greater priority. + Platform & platform = GetPlatform(); for (MapFileType type : {MapFileType::Diff, MapFileType::Map}) { - ASSERT_LESS(base::Underlying(type), m_files.size(), ()); + auto const ut = base::Underlying(type); + ASSERT_LESS(ut, m_files.size(), ()); - if (GetPlatform().GetFileSizeByFullPath(GetPath(type), size)) + if (platform.GetFileSizeByFullPath(GetPath(type), size)) { - m_files[base::Underlying(type)] = size; + m_files[ut] = size; break; } } @@ -52,10 +54,7 @@ void LocalCountryFile::DeleteFromDisk(MapFileType type) const { ASSERT_LESS(base::Underlying(type), m_files.size(), ()); - if (!OnDisk(type)) - return; - - if (!base::DeleteFileX(GetPath(type))) + if (OnDisk(type) && !base::DeleteFileX(GetPath(type))) LOG(LERROR, (type, "from", *this, "wasn't deleted from disk.")); } @@ -74,7 +73,7 @@ uint64_t LocalCountryFile::GetSize(MapFileType type) const bool LocalCountryFile::HasFiles() const { return std::any_of(m_files.cbegin(), m_files.cend(), - [](auto value) { return value.has_value(); }); + [](auto const & value) { return value.has_value(); }); } bool LocalCountryFile::OnDisk(MapFileType type) const @@ -131,22 +130,21 @@ LocalCountryFile LocalCountryFile::MakeTemporary(string const & fullPath) string DebugPrint(LocalCountryFile const & file) { - ostringstream filesStream; - filesStream << "["; + ostringstream os; + os << "LocalCountryFile [" << file.m_directory << ", " + << DebugPrint(file.m_countryFile) << ", " << file.m_version << ", ["; + bool fileAdded = false; for (auto const & mapFile : file.m_files) { if (mapFile) { - filesStream << (fileAdded ? ", " : "") << *mapFile; + os << (fileAdded ? ", " : "") << *mapFile; fileAdded = true; } } - filesStream << "]"; - ostringstream os; - os << "LocalCountryFile [" << file.m_directory << ", " << DebugPrint(file.m_countryFile) << ", " - << file.m_version << ", " << filesStream.str() << "]"; + os << "]]"; return os.str(); } } // namespace platform diff --git a/platform/local_country_file.hpp b/platform/local_country_file.hpp index f1e1091237..a0b023a818 100644 --- a/platform/local_country_file.hpp +++ b/platform/local_country_file.hpp @@ -22,15 +22,11 @@ namespace platform // SyncWithDisk()/DeleteFromDisk()/GetPath()/GetSize() will return // incorrect results. // -// TODO (@gorshenin): fix this hack somehow -// (https://trello.com/c/qcveFw3M/27-world-worldcoasts-mwm-localcountryfile) -// // In any case, when you're going to read a file LocalCountryFile points to, -// use GetCountryReader(). +// use platform::GetCountryReader(). class LocalCountryFile { public: - // Creates empty instance. LocalCountryFile(); // Creates an instance holding a path to countryFile's in a @@ -49,27 +45,26 @@ public: // it was found by a previous SyncWithDisk() call. void DeleteFromDisk(MapFileType type) const; - // Returns path to a file. Return value may be empty until - // SyncWithDisk() is called. + // Returns path to a file. + // Return value may be empty until SyncWithDisk() is called. std::string GetPath(MapFileType type) const; - // Returns size of a file. Return value may be zero until - // SyncWithDisk() is called. + // Returns size of a file. + // Return value may be zero until SyncWithDisk() is called. uint64_t GetSize(MapFileType type) const; // Returns true when some files are found during SyncWithDisk. // Return value is false until SyncWithDisk() is called. bool HasFiles() const; - // Checks whether files specified in filesMask are on disk. Return - // value will be false until SyncWithDisk() is called. + // Checks whether files specified in filesMask are on disk. + // Return value will be false until SyncWithDisk() is called. bool OnDisk(MapFileType type) const; std::string const & GetDirectory() const { return m_directory; } std::string const & GetCountryName() const { return m_countryFile.GetName(); } int64_t GetVersion() const { return m_version; } CountryFile const & GetCountryFile() const { return m_countryFile; } - CountryFile & GetCountryFile() { return m_countryFile; } bool operator<(LocalCountryFile const & rhs) const; bool operator==(LocalCountryFile const & rhs) const; @@ -78,18 +73,16 @@ public: bool ValidateIntegrity() const; // Creates LocalCountryFile for test purposes, for a country region - // with countryFileName (without any extensions). Automatically - // performs sync with disk. + // with countryFileName (without any extensions). Automatically performs sync with disk. static LocalCountryFile MakeForTesting(std::string const & countryFileName, int64_t version = 0); - /// @todo The easiest solution for now. Need to be removed in future. - /// @param fullPath Full path to the mwm file. + // Used in generator only to simplify getting instance from path. static LocalCountryFile MakeTemporary(std::string const & fullPath); private: friend std::string DebugPrint(LocalCountryFile const &); - friend void FindAllLocalMapsAndCleanup(int64_t latestVersion, - std::string const & dataDir, std::vector & localFiles); + friend void FindAllLocalMapsAndCleanup(int64_t latestVersion, std::string const & dataDir, + std::vector & localFiles); /// @note! If directory is empty, the file is stored in resources. /// In this case, the only valid params are m_countryFile and m_version. diff --git a/platform/local_country_file_utils.cpp b/platform/local_country_file_utils.cpp index 0d57d87341..0e907a5644 100644 --- a/platform/local_country_file_utils.cpp +++ b/platform/local_country_file_utils.cpp @@ -57,8 +57,8 @@ bool IsDiffFile(string const & name) bool DirectoryHasIndexesOnly(string const & directory) { Platform::TFilesWithType fwts; - Platform::GetFilesByType(directory, Platform::FILE_TYPE_REGULAR | Platform::FILE_TYPE_DIRECTORY, - fwts); + Platform::GetFilesByType(directory, Platform::FILE_TYPE_REGULAR | Platform::FILE_TYPE_DIRECTORY, fwts); + for (auto const & fwt : fwts) { auto const & name = fwt.first; @@ -67,11 +67,11 @@ bool DirectoryHasIndexesOnly(string const & directory) { if (!IsSpecialName(name)) return false; - continue; } - if (!CountryIndexes::IsIndexFile(name)) + else if (!CountryIndexes::IsIndexFile(name)) return false; } + return true; } @@ -187,14 +187,13 @@ void FindAllLocalMapsInDirectoryAndCleanup(string const & directory, int64_t ver if (fwt.second != Platform::FILE_TYPE_DIRECTORY) continue; - string name = fwt.first; + string const & name = fwt.first; if (IsSpecialName(name)) continue; if (names.count(name) == 0 && DirectoryHasIndexesOnly(base::JoinPath(directory, name))) { - // Directory which looks like a directory with indexes for absent country. It's OK to remove - // it. + // Directory which looks like a directory with indexes for absent country. It's OK to remove it. LocalCountryFile absentCountry(directory, CountryFile(name), version); CountryIndexes::DeleteFromDisk(absentCountry); } @@ -276,7 +275,7 @@ void FindAllLocalMapsAndCleanup(int64_t latestVersion, string const & dataDir, { if (i == localFiles.end()) { - // This warning is possible on android devices without pre-downloaded Worlds/fonts files. + // This warning is possible on android devices without bundled Worlds. LOG(LWARNING, ("Can't find any:", file, "Reason:", ex.Msg())); } } @@ -291,7 +290,8 @@ void CleanupMapsDirectory(int64_t latestVersion) bool ParseVersion(string const & s, int64_t & version) { - if (s.empty() || s.size() > kMaxTimestampLength) + // Folder version format is 211122. Unit tests use simple "1", "2" versions. + if (s.empty() || s.size() > 6) return false; int64_t v = 0; diff --git a/platform/local_country_file_utils.hpp b/platform/local_country_file_utils.hpp index 3ba8b3147a..c1c2169296 100644 --- a/platform/local_country_file_utils.hpp +++ b/platform/local_country_file_utils.hpp @@ -87,7 +87,8 @@ inline std::string GetFileDownloadPath(int64_t version, std::string const & mwmN std::unique_ptr GetCountryReader(LocalCountryFile const & file, MapFileType type); -// An API for managing country indexes. +/// An API for managing country indexes. +/// Not used now (except tests), but will be usefull for the Terrain index in future. class CountryIndexes { public: @@ -98,8 +99,7 @@ public: Offsets }; - /// Prepares (if necessary) directory for country indexes. Local file - /// should point to existing local country files. + /// Prepares (if necessary) directory for country indexes. /// @throw FileSystemException if any file system error occured. static void PreparePlaceOnDisk(LocalCountryFile const & localFile); diff --git a/platform/platform_tests/local_country_file_tests.cpp b/platform/platform_tests/local_country_file_tests.cpp index f0d58df4ef..8886ea742c 100644 --- a/platform/platform_tests/local_country_file_tests.cpp +++ b/platform/platform_tests/local_country_file_tests.cpp @@ -43,10 +43,7 @@ UNIT_TEST(LocalCountryFile_ParseVersion) TEST(ParseVersion("150309", version), ()); TEST_EQUAL(version, 150309, ()); - TEST(ParseVersion("999999999999999999", version), ()); - TEST_EQUAL(version, 999999999999999999, ()); - - TEST(!ParseVersion("1000000000000000000", version), ()); + TEST(!ParseVersion("2111225", version), ()); // too many digits TEST(!ParseVersion("00000000000000000000000000000000123", version), ()); TEST(!ParseVersion("", version), ()); diff --git a/routing/mwm_hierarchy_handler.cpp b/routing/mwm_hierarchy_handler.cpp index 3680c32b52..82277f4caf 100644 --- a/routing/mwm_hierarchy_handler.cpp +++ b/routing/mwm_hierarchy_handler.cpp @@ -34,7 +34,7 @@ std::string GetCountryByMwmName(std::string const & mwmName, CountryParentNameGe break; auto parent = fn(country); - if (parent == "Countries") + if (parent == COUNTRIES_ROOT) break; else country = std::move(parent); diff --git a/routing/routing_tests/mwm_hierarchy_test.cpp b/routing/routing_tests/mwm_hierarchy_test.cpp index d2519bd7f1..ad6c766698 100644 --- a/routing/routing_tests/mwm_hierarchy_test.cpp +++ b/routing/routing_tests/mwm_hierarchy_test.cpp @@ -1,8 +1,9 @@ #include "testing/testing.hpp" #include "routing/mwm_hierarchy_handler.hpp" -#include "storage/country_parent_getter.hpp" +#include "storage/country_parent_getter.hpp" +#include "storage/routing_helpers.hpp" using namespace routing; @@ -17,14 +18,6 @@ UNIT_TEST(CountryParentGetter_Smoke) namespace { -std::shared_ptr CreateNumMwmIds(storage::CountryParentGetter const & getter) -{ - auto mwmIDs = std::make_shared(); - getter.GetStorageForTesting().ForEachCountryFile( - [&mwmIDs](platform::CountryFile const & file) { mwmIDs->RegisterFile(file); }); - return mwmIDs; -} - uint16_t GetCountryID(std::shared_ptr mwmIDs, std::string const & mwmName) { return mwmIDs->GetId(platform::CountryFile(mwmName)); @@ -35,7 +28,7 @@ uint16_t GetCountryID(std::shared_ptr mwmIDs, std::string const & mwm UNIT_TEST(MwmHierarchyHandler_Smoke) { storage::CountryParentGetter getter; - auto mwmIDs = CreateNumMwmIds(getter); + auto mwmIDs = CreateNumMwmIds(getter.GetStorageForTesting()); routing::MwmHierarchyHandler handler(mwmIDs, getter); TEST(!handler.HasCrossBorderPenalty(GetCountryID(mwmIDs, "Belarus_Maglieu Region"), diff --git a/storage/routing_helpers.cpp b/storage/routing_helpers.cpp index 5abde81ba8..abcfb8098f 100644 --- a/storage/routing_helpers.cpp +++ b/storage/routing_helpers.cpp @@ -1,13 +1,14 @@ #include "storage/routing_helpers.hpp" -#include +namespace routing +{ std::unique_ptr> MakeNumMwmTree( - routing::NumMwmIds const & numMwmIds, storage::CountryInfoGetter const & countryInfoGetter) + NumMwmIds const & numMwmIds, storage::CountryInfoGetter const & countryInfoGetter) { - auto tree = std::make_unique>(); + auto tree = std::make_unique>(); - numMwmIds.ForEachId([&](routing::NumMwmId numMwmId) { + numMwmIds.ForEachId([&](NumMwmId numMwmId) { auto const & countryName = numMwmIds.GetFile(numMwmId).GetName(); tree->Add(numMwmId, countryInfoGetter.GetLimitRectForLeaf(countryName)); }); @@ -18,7 +19,11 @@ std::unique_ptr> MakeNumMwmTree( std::shared_ptr CreateNumMwmIds(storage::Storage const & storage) { auto numMwmIds = std::make_shared(); - storage.ForEachCountryFile( - [&](platform::CountryFile const & file) { numMwmIds->RegisterFile(file); }); + storage.ForEachCountry([&](storage::Country const & country) + { + numMwmIds->RegisterFile(country.GetFile()); + }); return numMwmIds; } + +} // namespace routing diff --git a/storage/routing_helpers.hpp b/storage/routing_helpers.hpp index 22714ad707..378ccc6a3b 100644 --- a/storage/routing_helpers.hpp +++ b/storage/routing_helpers.hpp @@ -9,6 +9,9 @@ #include +namespace routing +{ std::unique_ptr> MakeNumMwmTree( - routing::NumMwmIds const & numMwmIds, storage::CountryInfoGetter const & countryInfoGetter); -std::shared_ptr CreateNumMwmIds(storage::Storage const & storage); + NumMwmIds const & numMwmIds, storage::CountryInfoGetter const & countryInfoGetter); +std::shared_ptr CreateNumMwmIds(storage::Storage const & storage); +} // namespace routing diff --git a/storage/storage.cpp b/storage/storage.cpp index 047d797e8a..ab5edab1eb 100644 --- a/storage/storage.cpp +++ b/storage/storage.cpp @@ -245,9 +245,9 @@ void Storage::RegisterAllLocalMaps(bool enableDiffs) LocalCountryFile const & localFile = *i; string const & name = localFile.GetCountryName(); - CountryId countryId = FindCountryIdByFile(name); + CountryId const countryId = FindCountryIdByFile(name); if (IsLeaf(countryId)) - RegisterCountryFiles(countryId, localFile.GetDirectory(), localFile.GetVersion()); + RegisterCountryFiles(countryId, localFile); else RegisterFakeCountryFiles(localFile); // Also called for Worlds from resources. @@ -257,8 +257,9 @@ void Storage::RegisterAllLocalMaps(bool enableDiffs) } FindAllDiffs(m_dataDir, m_notAppliedDiffs); - if (enableDiffs) - LoadDiffScheme(); + //if (enableDiffs) + // LoadDiffScheme(); + // Note: call order is important, diffs loading must be called first. // Since diffs info downloading and servers list downloading // are working on network thread, consecutive executing is guaranteed. @@ -731,6 +732,7 @@ void Storage::RegisterDownloadedFiles(CountryId const & countryId, MapFileType t ApplyDiff(countryId, fn); return; } + ASSERT_EQUAL(type, MapFileType::Map, ()); CountryFile const countryFile = GetCountryFile(countryId); LocalFilePtr localFile = GetLocalFile(countryId, GetCurrentDataVersion()); @@ -738,15 +740,15 @@ void Storage::RegisterDownloadedFiles(CountryId const & countryId, MapFileType t localFile = PreparePlaceForCountryFiles(GetCurrentDataVersion(), m_dataDir, countryFile); if (!localFile) { - LOG(LERROR, ("Local file data structure can't be prepared for downloaded file(", countryFile, - type, ").")); - fn(false /* isSuccess */); + LOG(LERROR, ("Can't prepare LocalCountryFile for", countryFile, "in folder", m_dataDir)); + fn(false); return; } string const path = GetFileDownloadPath(countryId, type); if (!base::RenameFileX(path, localFile->GetPath(type))) { + /// @todo If localFile already exists (valid), remove it from disk and return false? localFile->DeleteFromDisk(type); fn(false); return; @@ -794,6 +796,7 @@ CountriesVec Storage::FindAllIndexesByFile(CountryId const & name) const return result; } +/* void Storage::GetOutdatedCountries(vector & countries) const { for (auto const & p : m_localFiles) @@ -808,6 +811,7 @@ void Storage::GetOutdatedCountries(vector & countries) const } } } +*/ bool Storage::IsCountryInQueue(CountryId const & countryId) const { @@ -882,23 +886,21 @@ void Storage::RegisterCountryFiles(LocalFilePtr localFile) } } -void Storage::RegisterCountryFiles(CountryId const & countryId, string const & directory, - int64_t version) +void Storage::RegisterCountryFiles(CountryId const & countryId, LocalCountryFile const & localFile) { - LocalFilePtr localFile = GetLocalFile(countryId, version); - if (localFile) - return; - - CountryFile const & countryFile = GetCountryFile(countryId); - localFile = make_shared(directory, countryFile, version); - RegisterCountryFiles(localFile); + LocalFilePtr p = GetLocalFile(countryId, localFile.GetVersion()); + if (!p) + { + p = make_shared(localFile); + RegisterCountryFiles(p); + } } -void Storage::RegisterFakeCountryFiles(platform::LocalCountryFile const & localFile) +void Storage::RegisterFakeCountryFiles(LocalCountryFile const & localFile) { - LocalFilePtr fakeCountryLocalFile = make_shared(localFile); - fakeCountryLocalFile->SyncWithDisk(); - m_localFilesForFakeCountries[fakeCountryLocalFile->GetCountryFile()] = fakeCountryLocalFile; + LocalFilePtr p = make_shared(localFile); + p->SyncWithDisk(); + m_localFilesForFakeCountries[p->GetCountryFile()] = p; } void Storage::DeleteCountryFiles(CountryId const & countryId, MapFileType type, bool deferredDelete) @@ -1069,7 +1071,7 @@ void Storage::ApplyCountries(std::string const & countriesBuffer, Storage & stor LOG(LDEBUG, ("Version", m_currentVersion, "is applied")); - LoadDiffScheme(); + //LoadDiffScheme(); /// @todo Start World and WorldCoasts download ?! } @@ -1097,6 +1099,7 @@ void Storage::GetChildren(CountryId const & parent, CountriesVec & childIds) con childIds.emplace_back(parentNode->Child(i).Value().Name()); } +/* void Storage::GetLocalRealMaps(CountriesVec & localMaps) const { CHECK_THREAD_CHECKER(m_threadChecker, ()); @@ -1107,6 +1110,7 @@ void Storage::GetLocalRealMaps(CountriesVec & localMaps) const for (auto const & keyValue : m_localFiles) localMaps.push_back(keyValue.first); } +*/ void Storage::GetChildrenInGroups(CountryId const & parent, CountriesVec & downloadedChildren, CountriesVec & availChildren, bool keepAvailableChildren) const @@ -1278,6 +1282,7 @@ void Storage::CalcMaxMwmSizeBytes() }); } +/* void Storage::LoadDiffScheme() { CHECK_THREAD_CHECKER(m_threadChecker, ()); @@ -1307,6 +1312,7 @@ void Storage::LoadDiffScheme() OnDiffStatusReceived(move(diffs)); }); } +*/ void Storage::ApplyDiff(CountryId const & countryId, function const & fn) { @@ -1338,9 +1344,9 @@ void Storage::ApplyDiff(CountryId const & countryId, functionsecond, - [this, fn, countryId, diffFile](DiffApplicationResult result) { + [this, fn, countryId, diffFile](DiffApplicationResult result) + { CHECK_THREAD_CHECKER(m_threadChecker, ()); - static string const kSourceKey = "diff"; if (result == DiffApplicationResult::Ok && m_integrityValidationEnabled && !diffFile->ValidateIntegrity()) { @@ -1402,6 +1408,7 @@ void Storage::AbortDiffScheme() m_diffsDataSource->AbortDiffScheme(); } +/* bool Storage::IsPossibleToAutoupdate() const { CHECK_THREAD_CHECKER(m_threadChecker, ()); @@ -1424,6 +1431,7 @@ bool Storage::IsPossibleToAutoupdate() const return true; } +*/ void Storage::SetStartDownloadingCallback(StartDownloadingCallback const & cb) { @@ -1567,11 +1575,11 @@ void Storage::GetNodeAttrs(CountryId const & countryId, NodeAttrs & nodeAttrs) c nodeAttrs.m_downloadingMwmCounter = 0; nodeAttrs.m_downloadingMwmSize = 0; CountriesSet visitedLocalNodes; - node->ForEachInSubtree([this, &nodeAttrs, &visitedLocalNodes](CountryTree::Node const & d) { - CountryId const countryId = d.Value().Name(); - if (visitedLocalNodes.count(countryId) != 0) + node->ForEachInSubtree([this, &nodeAttrs, &visitedLocalNodes](CountryTree::Node const & d) + { + CountryId const & countryId = d.Value().Name(); + if (!visitedLocalNodes.insert(countryId).second) return; - visitedLocalNodes.insert(countryId); // Downloading mwm information. StatusAndError const statusAndErr = GetNodeStatus(d); diff --git a/storage/storage.hpp b/storage/storage.hpp index f7215456c0..eaeac11431 100644 --- a/storage/storage.hpp +++ b/storage/storage.hpp @@ -174,10 +174,11 @@ private: /// stores countries whose download has failed recently CountriesSet m_failedCountries; + /// @todo Do we really store a list of local files here (of different versions)? + /// I suspect that only one at a time, old versions are deleted automatically. std::map> m_localFiles; - // Our World.mwm and WorldCoasts.mwm are fake countries, together with any custom mwm in data - // folder. + // World and WorldCoasts are fake countries, together with any custom mwm in data folder. std::map m_localFilesForFakeCountries; // Since the diffs applying runs on a different thread, the result @@ -446,15 +447,14 @@ public: std::vector GetTopCountryGeoIds(CountryId const & countryId) const; /// @} - /// \brief Calls |toDo| for each node for subtree with |root|. - /// For example ForEachInSubtree(GetRootId()) calls |toDo| for every node including - /// the result of GetRootId() call. + /// For each node with \a root subtree (including). template void ForEachInSubtree(CountryId const & root, ToDo && toDo) const; template void ForEachAncestorExceptForTheRoot(CountryId const & childId, ToDo && toDo) const; template - void ForEachCountryFile(ToDo && toDo) const; + /// For each leaf country excluding Worlds. + void ForEachCountry(ToDo && toDo) const; /// \brief Sets callback which will be called in case of a click on download map button on the map. void SetCallbackForClickOnDownloadMap(DownloadFn & downloadFn); @@ -468,7 +468,7 @@ public: /// \returns real (not fake) local maps contained in countries.txt. /// So this method does not return custom user local maps and World and WorldCoasts country id. - void GetLocalRealMaps(CountriesVec & localMaps) const; + //void GetLocalRealMaps(CountriesVec & localMaps) const; /// Do we have downloaded countries bool HaveDownloadedCountries() const; @@ -508,7 +508,7 @@ public: // Returns true iff |countryId| exists as a node in the tree. bool IsNode(CountryId const & countryId) const; - // Returns true iff |countryId| is a leaf of the tree. + /// @return true iff \a countryId is a leaf of the tree. bool IsLeaf(CountryId const & countryId) const; // Returns true iff |countryId| is an inner node of the tree. @@ -539,7 +539,7 @@ public: bool IsDownloadInProgress() const; /// @param[out] res Populated with oudated countries. - void GetOutdatedCountries(std::vector & countries) const; + //void GetOutdatedCountries(std::vector & countries) const; /// Sets and gets locale, which is used to get localized counries names void SetLocale(std::string const & locale) { m_countryNameGetter.SetLocale(locale); } @@ -554,9 +554,8 @@ public: void SetDownloadingServersForTesting(std::vector const & downloadingUrls); void SetLocaleForTesting(std::string const & jsonBuffer, std::string const & locale); - /// Returns true if the diff scheme is available and all local outdated maps can be updated via - /// diffs. - bool IsPossibleToAutoupdate() const; + /// Returns true if the diff scheme is available and all local outdated maps can be updated via diffs. + //bool IsPossibleToAutoupdate() const; void SetStartDownloadingCallback(StartDownloadingCallback const & cb); @@ -587,8 +586,7 @@ private: // Registers disk files for a country. This method must be used only // for real (listed in countries.txt) countries. - void RegisterCountryFiles(CountryId const & countryId, std::string const & directory, - int64_t version); + void RegisterCountryFiles(CountryId const & countryId, platform::LocalCountryFile const & localFile); // Registers disk files for a country. This method must be used only // for custom (made by user) map files. @@ -609,6 +607,7 @@ private: /// Returns status for a node (group node or not). StatusAndError GetNodeStatus(CountryTree::Node const & node) const; + /// Returns status for a node (group node or not). /// Fills |disputedTeritories| with all disputed teritories in subtree with the root == |node|. StatusAndError GetNodeStatusInfo( @@ -631,14 +630,14 @@ private: void ForEachAncestorExceptForTheRoot(std::vector const & nodes, ToDo && toDo) const; - /// Returns true if |node.Value().Name()| is a disputed territory and false otherwise. + /// @return true if |node.Value().Name()| is a disputed territory and false otherwise. bool IsDisputed(CountryTree::Node const & node) const; void CalcMaxMwmSizeBytes(); void OnMapDownloadFailed(CountryId const & countryId); - void LoadDiffScheme(); + //void LoadDiffScheme(); void ApplyDiff(CountryId const & countryId, std::function const & fn); using IsDiffAbsentForCountry = std::function; @@ -709,11 +708,12 @@ void Storage::ForEachAncestorExceptForTheRoot(std::vector -void Storage::ForEachCountryFile(ToDo && toDo) const +void Storage::ForEachCountry(ToDo && toDo) const { - m_countries.GetRoot().ForEachInSubtree([&](CountryTree::Node const & node) { + m_countries.GetRoot().ForEachInSubtree([&](CountryTree::Node const & node) + { if (node.ChildrenCount() == 0) - toDo(node.Value().GetFile()); + toDo(node.Value()); }); } } // namespace storage diff --git a/storage/storage_tests/country_info_getter_tests.cpp b/storage/storage_tests/country_info_getter_tests.cpp index 34339dac2d..93a75129a1 100644 --- a/storage/storage_tests/country_info_getter_tests.cpp +++ b/storage/storage_tests/country_info_getter_tests.cpp @@ -243,9 +243,9 @@ UNIT_TEST(CountryInfoGetter_Countries_And_Polygons) // Set is used here because disputed territories may occur as leaves several times. set storageLeaves; - storage.ForEachInSubtree(storage.GetRootId(), [&](CountryId const & countryId, bool groupNode) { - if (!groupNode) - storageLeaves.insert(countryId); + storage.ForEachCountry([&](Country const & country) + { + storageLeaves.insert(country.Name()); }); TEST_EQUAL(countries.size(), storageLeaves.size(), ()); diff --git a/storage/storage_tests/storage_tests.cpp b/storage/storage_tests/storage_tests.cpp index 99ca767fa0..3d683d0786 100644 --- a/storage/storage_tests/storage_tests.cpp +++ b/storage/storage_tests/storage_tests.cpp @@ -715,7 +715,7 @@ UNIT_TEST(StorageTest_GetRootId) })"), make_unique()); // The name of the root is the same for courntries.txt version 1 and version 2. - TEST_EQUAL(storage.GetRootId(), "Countries", ()); + TEST_EQUAL(storage.GetRootId(), COUNTRIES_ROOT, ()); } UNIT_TEST(StorageTest_GetChildren) @@ -723,7 +723,7 @@ UNIT_TEST(StorageTest_GetChildren) Storage storage(kCountriesTxt, make_unique()); CountryId const world = storage.GetRootId(); - TEST_EQUAL(world, "Countries", ()); + TEST_EQUAL(world, COUNTRIES_ROOT, ()); CountriesVec countriesList; storage.GetChildren(world, countriesList); @@ -798,19 +798,21 @@ UNIT_CLASS_TEST(StorageTest, DownloadedMap) } // Storage::GetLocalRealMaps() test. + /* CountriesVec localRealMaps; storage.GetLocalRealMaps(localRealMaps); - sort(localRealMaps.begin(), localRealMaps.end()); + TEST_EQUAL(localRealMaps.size(), 4, ()); TEST(storage.IsNodeDownloaded("Algeria_Central"), ()); TEST(storage.IsNodeDownloaded("Algeria_Coast"), ()); TEST(!storage.IsNodeDownloaded("Algeria_Coast.mwm"), ()); - TEST(!storage.IsNodeDownloaded("World"), ()); - TEST(!storage.IsNodeDownloaded("World"), ()); + TEST(!storage.IsNodeDownloaded(WORLD_FILE_NAME), ()); + TEST(!storage.IsNodeDownloaded(WORLD_COASTS_FILE_NAME), ()); + */ // Storage::GetChildrenInGroups test when at least Algeria_Central and Algeria_Coast have been downloaded. CountryId const rootCountryId = storage.GetRootId(); - TEST_EQUAL(rootCountryId, "Countries", ()); + TEST_EQUAL(rootCountryId, COUNTRIES_ROOT, ()); CountriesVec downloaded, available; CountriesVec downloadedWithKeep, availableWithKeep; @@ -910,10 +912,10 @@ UNIT_TEST(StorageTest_ParentSingleMwm) { Storage storage(kCountriesTxt, make_unique()); - TEST(ParentOf(storage, "Countries", "Abkhazia"), ()); + TEST(ParentOf(storage, COUNTRIES_ROOT, "Abkhazia"), ()); TEST(ParentOf(storage, "Algeria", "Algeria_Central"), ()); - TEST(ParentOf(storage, "Countries", "South Korea_South"), ()); - TEST(ParentOf(storage, kInvalidCountryId, "Countries"), ()); + TEST(ParentOf(storage, COUNTRIES_ROOT, "South Korea_South"), ()); + TEST(ParentOf(storage, kInvalidCountryId, COUNTRIES_ROOT), ()); } UNIT_TEST(StorageTest_GetNodeStatusesSingleMwm) @@ -943,7 +945,7 @@ UNIT_TEST(StorageTest_GetNodeAttrsSingleMwm) TEST_EQUAL(nodeAttrs.m_status, NodeStatus::NotDownloaded, ()); TEST_EQUAL(nodeAttrs.m_error, NodeErrorCode::NoError, ()); TEST_EQUAL(nodeAttrs.m_parentInfo.size(), 1, ()); - TEST_EQUAL(nodeAttrs.m_parentInfo[0].m_id, "Countries", ()); + TEST_EQUAL(nodeAttrs.m_parentInfo[0].m_id, COUNTRIES_ROOT, ()); TEST_EQUAL(nodeAttrs.m_downloadingProgress.m_bytesDownloaded, 0, ()); TEST_EQUAL(nodeAttrs.m_downloadingProgress.m_bytesTotal, 0, ()); TEST_EQUAL(nodeAttrs.m_localMwmCounter, 0, ()); @@ -958,7 +960,7 @@ UNIT_TEST(StorageTest_GetNodeAttrsSingleMwm) TEST_EQUAL(nodeAttrs.m_status, NodeStatus::NotDownloaded, ()); // It's a status of expandable node. TEST_EQUAL(nodeAttrs.m_error, NodeErrorCode::NoError, ()); TEST_EQUAL(nodeAttrs.m_parentInfo.size(), 1, ()); - TEST_EQUAL(nodeAttrs.m_parentInfo[0].m_id, "Countries", ()); + TEST_EQUAL(nodeAttrs.m_parentInfo[0].m_id, COUNTRIES_ROOT, ()); TEST_EQUAL(nodeAttrs.m_downloadingProgress.m_bytesDownloaded, 0, ()); TEST_EQUAL(nodeAttrs.m_downloadingProgress.m_bytesTotal, 0, ()); TEST_EQUAL(nodeAttrs.m_localMwmCounter, 0, ()); @@ -988,7 +990,7 @@ UNIT_TEST(StorageTest_GetNodeAttrsSingleMwm) TEST_EQUAL(nodeAttrs.m_status, NodeStatus::NotDownloaded, ()); TEST_EQUAL(nodeAttrs.m_error, NodeErrorCode::NoError, ()); TEST_EQUAL(nodeAttrs.m_parentInfo.size(), 1, ()); - TEST_EQUAL(nodeAttrs.m_parentInfo[0].m_id, "Countries", ()); + TEST_EQUAL(nodeAttrs.m_parentInfo[0].m_id, COUNTRIES_ROOT, ()); TEST_EQUAL(nodeAttrs.m_downloadingProgress.m_bytesDownloaded, 0, ()); TEST_EQUAL(nodeAttrs.m_downloadingProgress.m_bytesTotal, 0, ()); TEST_EQUAL(nodeAttrs.m_localMwmCounter, 0, ()); @@ -1339,7 +1341,7 @@ UNIT_TEST(StorageTest_GetQueuedChildrenSmokeTest) InitStorage(storage, runner); CountriesVec queuedChildren; - storage.GetQueuedChildren("Countries", queuedChildren); + storage.GetQueuedChildren(COUNTRIES_ROOT, queuedChildren); TEST(queuedChildren.empty(), ()); storage.GetQueuedChildren("Abkhazia", queuedChildren); @@ -1348,7 +1350,7 @@ UNIT_TEST(StorageTest_GetQueuedChildrenSmokeTest) storage.GetQueuedChildren("Country1", queuedChildren); TEST(queuedChildren.empty(), ()); } - + UNIT_TEST(StorageTest_GetGroupNodePathToRootTest) { Storage storage; @@ -1357,23 +1359,23 @@ UNIT_TEST(StorageTest_GetGroupNodePathToRootTest) storage.GetGroupNodePathToRoot("France_Auvergne_Allier", path); TEST(path.empty(), ()); - + storage.GetGroupNodePathToRoot("France_Auvergne", path); TEST_EQUAL(path.size(), 2, (path)); TEST_EQUAL(path[0], "France", ()); - TEST_EQUAL(path[1], "Countries", ()); - + TEST_EQUAL(path[1], COUNTRIES_ROOT, ()); + storage.GetGroupNodePathToRoot("France", path); TEST_EQUAL(path.size(), 1, (path)); - TEST_EQUAL(path[0], "Countries", ()); - + TEST_EQUAL(path[0], COUNTRIES_ROOT, ()); + storage.GetGroupNodePathToRoot("US_Florida_Miami", path); TEST(path.empty(), ()); storage.GetGroupNodePathToRoot("Florida", path); TEST_EQUAL(path.size(), 2, (path)); TEST_EQUAL(path[0], "United States of America", ()); - TEST_EQUAL(path[1], "Countries", ()); + TEST_EQUAL(path[1], COUNTRIES_ROOT, ()); storage.GetGroupNodePathToRoot("Country1", path); TEST(path.empty(), ()); -- 2.45.3 From 752e4c6508b1a1db698c3632c82ed743d87c29f5 Mon Sep 17 00:00:00 2001 From: Viktor Govako Date: Mon, 18 Apr 2022 16:18:02 +0300 Subject: [PATCH 17/21] [storage] Minor code prettify and fixes. Signed-off-by: Viktor Govako --- generator/utils.cpp | 21 ------- generator/utils.hpp | 2 - .../UI/Autoupdate/MWMAutoupdateController.mm | 2 +- map/map_tests/check_mwms.cpp | 18 ++++-- platform/country_file.cpp | 27 +++------ platform/country_file.hpp | 14 +++-- platform/local_country_file.cpp | 13 +++-- platform/local_country_file.hpp | 4 +- platform/local_country_file_utils.cpp | 55 +++++++++---------- platform/local_country_file_utils.hpp | 12 ++-- .../platform_tests/country_file_tests.cpp | 4 +- .../local_country_file_tests.cpp | 30 ++++++---- .../platform_tests_support/scoped_file.cpp | 4 +- storage/queued_country.cpp | 2 +- storage/storage.cpp | 34 ++++++------ storage/storage.hpp | 7 ++- .../download_calc_size_test.cpp | 2 +- .../storage_downloading_tests.cpp | 2 +- .../storage_group_download_tests.cpp | 2 +- .../storage_http_tests.cpp | 2 +- storage/storage_tests/storage_tests.cpp | 15 +++-- .../track_analyzer/cmd_balance_csv.cpp | 2 +- track_analyzing/track_analyzer/cmd_match.cpp | 4 +- track_analyzing/track_analyzer/cmd_table.cpp | 2 +- track_analyzing/utils.cpp | 3 +- 25 files changed, 138 insertions(+), 145 deletions(-) diff --git a/generator/utils.cpp b/generator/utils.cpp index c209f5977a..21c440d0e3 100644 --- a/generator/utils.cpp +++ b/generator/utils.cpp @@ -81,27 +81,6 @@ std::unique_ptr FeatureGetter::GetFeatureByIndex(uint32_t index) co return m_guard->GetFeatureByIndex(index); } -void LoadDataSource(DataSource & dataSource) -{ - std::vector localFiles; - - Platform & platform = GetPlatform(); - platform::FindAllLocalMapsInDirectoryAndCleanup(platform.WritableDir(), 0 /* version */, - -1 /* latestVersion */, localFiles); - for (auto const & localFile : localFiles) - { - LOG(LINFO, ("Found mwm:", localFile)); - try - { - dataSource.RegisterMap(localFile); - } - catch (RootException const & ex) - { - CHECK(false, (ex.Msg(), "Bad mwm file:", localFile)); - } - } -} - bool ParseFeatureIdToOsmIdMapping(std::string const & path, std::unordered_map & mapping) { diff --git a/generator/utils.hpp b/generator/utils.hpp index 204484e04d..83e829167c 100644 --- a/generator/utils.hpp +++ b/generator/utils.hpp @@ -53,8 +53,6 @@ private: MwmSet::MwmId m_mwmId; }; -void LoadDataSource(DataSource & dataSource); - class FeatureGetter { public: diff --git a/iphone/Maps/UI/Autoupdate/MWMAutoupdateController.mm b/iphone/Maps/UI/Autoupdate/MWMAutoupdateController.mm index 21a62cb66f..9327dbf783 100644 --- a/iphone/Maps/UI/Autoupdate/MWMAutoupdateController.mm +++ b/iphone/Maps/UI/Autoupdate/MWMAutoupdateController.mm @@ -252,7 +252,7 @@ using namespace storage; { auto const & s = GetFramework().GetStorage(); NodeAttrs nodeAttrs; - s.GetNodeAttrs(RootId().UTF8String, nodeAttrs); + s.GetNodeAttrs(s.GetRootId(), nodeAttrs); auto view = static_cast(self.view); NSString * nodeName = @(s.GetNodeLocalName(countryId).c_str()); [view setStatusForNodeName:nodeName rootAttributes:nodeAttrs]; diff --git a/map/map_tests/check_mwms.cpp b/map/map_tests/check_mwms.cpp index 6890dcabfd..033f5826d6 100644 --- a/map/map_tests/check_mwms.cpp +++ b/map/map_tests/check_mwms.cpp @@ -18,19 +18,24 @@ #include "defines.hpp" +namespace check_mwms +{ +using namespace platform; using namespace std; UNIT_TEST(CheckMWM_LoadAll) { - Platform & platform = GetPlatform(); - vector localFiles; - platform::FindAllLocalMapsInDirectoryAndCleanup(platform.WritableDir(), 0 /* version */, - -1 /* latestVersion */, localFiles); + // Parse root WritableDir folder. Expect at least World, WorldCoasts, minsk-pass. + vector localFiles; + size_t const count = FindAllLocalMapsInDirectoryAndCleanup(GetPlatform().WritableDir(), 0 /* version */, + -1 /* latestVersion */, localFiles); + TEST_EQUAL(count, localFiles.size(), ()); + TEST_GREATER_OR_EQUAL(count, 3, ()); FeaturesFetcher m; m.InitClassificator(); - for (platform::LocalCountryFile const & localFile : localFiles) + for (auto const & localFile : localFiles) { LOG(LINFO, ("Found mwm:", localFile)); try @@ -73,11 +78,14 @@ UNIT_TEST(CheckMWM_GeomIndex) // Count objects for each scale bucket. map resCount; for (size_t i = 0; i < scale2Index.size(); ++i) + { scale2Index[i]->ForEach([i, &resCount](uint64_t, uint32_t) { ++resCount[i]; }, beg, end); + } // Print results. LOG(LINFO, (resCount)); } +} // namespace check_mwms diff --git a/platform/country_file.cpp b/platform/country_file.cpp index 6ff6e77eab..08de611a9a 100644 --- a/platform/country_file.cpp +++ b/platform/country_file.cpp @@ -8,28 +8,24 @@ #include "defines.hpp" +namespace platform +{ using namespace std; -namespace +string GetFileName(string const & countryName, MapFileType type) { -/// \returns file name (m_name) with extension dependent on the file param. -/// The extension could be .mwm.routing or just .mwm. -/// The method is used for old (two components) mwm support. -string GetNameWithExt(string const & countryFile, MapFileType file) -{ - switch (file) + ASSERT(!countryName.empty(), ()); + + switch (type) { - case MapFileType::Map: return countryFile + DATA_FILE_EXTENSION; - case MapFileType::Diff: return countryFile + DIFF_FILE_EXTENSION; - case MapFileType::Count: CHECK(false, (countryFile)); + case MapFileType::Map: return countryName + DATA_FILE_EXTENSION; + case MapFileType::Diff: return countryName + DIFF_FILE_EXTENSION; + case MapFileType::Count: break; } UNREACHABLE(); } -} // namespace -namespace platform -{ CountryFile::CountryFile() : m_mapSize(0) {} CountryFile::CountryFile(std::string name) @@ -42,11 +38,6 @@ CountryFile::CountryFile(std::string name, MwmSize size, std::string sha1) { } -string GetFileName(string const & countryFile, MapFileType type) -{ - return GetNameWithExt(countryFile, type); -} - string DebugPrint(CountryFile const & file) { ostringstream os; diff --git a/platform/country_file.hpp b/platform/country_file.hpp index 01f0521896..e41504aadc 100644 --- a/platform/country_file.hpp +++ b/platform/country_file.hpp @@ -7,6 +7,10 @@ namespace platform { +/// \param countryName Country's name without any extensions. For example "Abkhazia". +/// \returns File name with extension (for download url and save on disk) for \a type. For example "Abkhazia.mwm". +std::string GetFileName(std::string const & countryName, MapFileType type); + /// This class represents a country file name and sizes of /// corresponding map files on a server, which should correspond to an /// entry in countries.txt file. Also, this class can be used to @@ -19,10 +23,14 @@ public: explicit CountryFile(std::string name); CountryFile(std::string name, MwmSize size, std::string sha1); + std::string GetFileName(MapFileType type) const + { + return platform::GetFileName(m_name, type); + } + /// \returns Empty (invalid) CountryFile. bool IsEmpty() const { return m_name.empty(); } - /// \returns file name without extensions. std::string const & GetName() const { return m_name; } MwmSize GetRemoteSize() const { return m_mapSize; } std::string const & GetSha1() const { return m_sha1; } @@ -41,9 +49,5 @@ private: std::string m_sha1; }; -/// \returns This method returns file name with extension. For example Abkhazia.mwm. -/// \param countryFile is a file name without extension. For example Abkhazia. -/// \param type is type of map data. -std::string GetFileName(std::string const & countryFile, MapFileType type); std::string DebugPrint(CountryFile const & file); } // namespace platform diff --git a/platform/local_country_file.cpp b/platform/local_country_file.cpp index 0d7bab1729..fc0b551b11 100644 --- a/platform/local_country_file.cpp +++ b/platform/local_country_file.cpp @@ -60,7 +60,12 @@ void LocalCountryFile::DeleteFromDisk(MapFileType type) const string LocalCountryFile::GetPath(MapFileType type) const { - return base::JoinPath(m_directory, GetFileName(m_countryFile.GetName(), type)); + return base::JoinPath(m_directory, GetFileName(type)); +} + +std::string LocalCountryFile::GetFileName(MapFileType type) const +{ + return m_countryFile.GetFileName(type); } uint64_t LocalCountryFile::GetSize(MapFileType type) const @@ -78,9 +83,9 @@ bool LocalCountryFile::HasFiles() const bool LocalCountryFile::OnDisk(MapFileType type) const { - ASSERT_LESS(base::Underlying(type), m_files.size(), ()); - - return m_files[base::Underlying(type)].has_value(); + auto const ut = base::Underlying(type); + ASSERT_LESS(ut, m_files.size(), ()); + return m_files[ut].has_value(); } bool LocalCountryFile::operator<(LocalCountryFile const & rhs) const diff --git a/platform/local_country_file.hpp b/platform/local_country_file.hpp index a0b023a818..ceab158f67 100644 --- a/platform/local_country_file.hpp +++ b/platform/local_country_file.hpp @@ -48,6 +48,7 @@ public: // Returns path to a file. // Return value may be empty until SyncWithDisk() is called. std::string GetPath(MapFileType type) const; + std::string GetFileName(MapFileType type) const; // Returns size of a file. // Return value may be zero until SyncWithDisk() is called. @@ -84,8 +85,7 @@ private: friend void FindAllLocalMapsAndCleanup(int64_t latestVersion, std::string const & dataDir, std::vector & localFiles); - /// @note! If directory is empty, the file is stored in resources. - /// In this case, the only valid params are m_countryFile and m_version. + /// Can be bundled (empty directory) or path to the file. std::string m_directory; CountryFile m_countryFile; int64_t m_version; diff --git a/platform/local_country_file_utils.cpp b/platform/local_country_file_utils.cpp index 0e907a5644..f9ebfa073d 100644 --- a/platform/local_country_file_utils.cpp +++ b/platform/local_country_file_utils.cpp @@ -54,6 +54,7 @@ bool IsDiffFile(string const & name) strings::EndsWith(name, DIFF_APPLYING_FILE_EXTENSION); } +/* bool DirectoryHasIndexesOnly(string const & directory) { Platform::TFilesWithType fwts; @@ -74,6 +75,7 @@ bool DirectoryHasIndexesOnly(string const & directory) return true; } +*/ inline string GetDataDirFullPath(string const & dataDir) { @@ -100,26 +102,22 @@ void FindAllDiffsInDirectory(string const & dir, vector & diff continue; base::GetNameWithoutExt(name); - if (isDiffReady) base::GetNameWithoutExt(name); - LocalCountryFile localDiff(dir, CountryFile(name), 0 /* version */); - - diffs.push_back(localDiff); + diffs.emplace_back(dir, CountryFile(std::move(name)), 0 /* version */); } } +} // namespace -string GetFilePath(int64_t version, string const & dataDir, CountryFile const & countryFile, - MapFileType type) +string GetFilePath(int64_t version, string const & dataDir, string const & countryName, MapFileType type) { - string const filename = GetFileName(countryFile.GetName(), type); + string const filename = GetFileName(countryName, type); string const dir = GetDataDirFullPath(dataDir); if (version == 0) return base::JoinPath(dir, filename); return base::JoinPath(dir, strings::to_string(version), filename); } -} // namespace void DeleteDownloaderFilesForCountry(int64_t version, CountryFile const & countryFile) { @@ -141,22 +139,21 @@ void DeleteDownloaderFilesForCountry(int64_t version, string const & dataDir, // Delete the diff that was downloaded but wasn't applied. { - string const path = GetFilePath(version, dataDir, countryFile, MapFileType::Diff); + string const path = GetFilePath(version, dataDir, countryFile.GetName(), MapFileType::Diff); Platform::RemoveFileIfExists(path); } } -void FindAllLocalMapsInDirectoryAndCleanup(string const & directory, int64_t version, - int64_t latestVersion, - vector & localFiles) +size_t FindAllLocalMapsInDirectoryAndCleanup(string const & directory, int64_t version, + int64_t latestVersion, + vector & localFiles) { Platform & platform = GetPlatform(); + size_t const szBefore = localFiles.size(); Platform::TFilesWithType fwts; - platform.GetFilesByType(directory, Platform::FILE_TYPE_REGULAR | Platform::FILE_TYPE_DIRECTORY, - fwts); + platform.GetFilesByType(directory, Platform::FILE_TYPE_REGULAR | Platform::FILE_TYPE_DIRECTORY, fwts); - unordered_set names; for (auto const & fwt : fwts) { if (fwt.second != Platform::FILE_TYPE_REGULAR) @@ -176,12 +173,13 @@ void FindAllLocalMapsInDirectoryAndCleanup(string const & directory, int64_t ver // Remove DATA_FILE_EXTENSION and use base name as a country file name. base::GetNameWithoutExt(name); - names.insert(name); - LocalCountryFile localFile(directory, CountryFile(name), version); - - localFiles.push_back(localFile); + localFiles.emplace_back(directory, CountryFile(std::move(name)), version); } + return localFiles.size() - szBefore; + + // Probably, indices will appear in future. + /* for (auto const & fwt : fwts) { if (fwt.second != Platform::FILE_TYPE_DIRECTORY) @@ -198,6 +196,7 @@ void FindAllLocalMapsInDirectoryAndCleanup(string const & directory, int64_t ver CountryIndexes::DeleteFromDisk(absentCountry); } } + */ } void FindAllDiffs(string const & dataDir, vector & diffs) @@ -235,10 +234,12 @@ void FindAllLocalMapsAndCleanup(int64_t latestVersion, string const & dataDir, continue; string const fullPath = base::JoinPath(dir, subdir); - FindAllLocalMapsInDirectoryAndCleanup(fullPath, version, latestVersion, localFiles); - Platform::EError err = Platform::RmDir(fullPath); - if (err != Platform::ERR_OK && err != Platform::ERR_DIRECTORY_NOT_EMPTY) - LOG(LWARNING, ("Can't remove directory:", fullPath, err)); + if (0 == FindAllLocalMapsInDirectoryAndCleanup(fullPath, version, latestVersion, localFiles)) + { + Platform::EError err = Platform::RmDir(fullPath); + if (err != Platform::ERR_OK) + LOG(LWARNING, ("Can't remove directory:", fullPath, err)); + } } // World and WorldCoasts can be stored in app bundle or in resources @@ -323,13 +324,9 @@ shared_ptr PreparePlaceForCountryFiles(int64_t version, string return make_shared(directory, countryFile, version); } -string GetFileDownloadPath(int64_t version, string const & dataDir, string const & mwmName, MapFileType type) +string GetFileDownloadPath(int64_t version, string const & dataDir, string const & countryName, MapFileType type) { - string const readyFile = GetFileName(mwmName, type) + READY_FILE_EXTENSION; - string const dir = GetDataDirFullPath(dataDir); - if (version == 0) - return base::JoinPath(dir, readyFile); - return base::JoinPath(dir, strings::to_string(version), readyFile); + return GetFilePath(version, dataDir, countryName, type) + READY_FILE_EXTENSION; } unique_ptr GetCountryReader(platform::LocalCountryFile const & file, MapFileType type) diff --git a/platform/local_country_file_utils.hpp b/platform/local_country_file_utils.hpp index c1c2169296..6b5e3c8678 100644 --- a/platform/local_country_file_utils.hpp +++ b/platform/local_country_file_utils.hpp @@ -21,9 +21,9 @@ void DeleteDownloaderFilesForCountry(int64_t version, std::string const & dataDi // Finds all local map files in |directory|. Version of these files is // passed as an argument. Also, performs cleanup described in comment // for FindAllLocalMapsAndCleanup(). -void FindAllLocalMapsInDirectoryAndCleanup(std::string const & directory, int64_t version, - int64_t latestVersion, - std::vector & localFiles); +size_t FindAllLocalMapsInDirectoryAndCleanup(std::string const & directory, int64_t version, + int64_t latestVersion, + std::vector & localFiles); // Finds all local map files in resources and writable directory. For // Android, checks /Android/obb directory. Subdirectories in the @@ -72,8 +72,12 @@ std::shared_ptr PreparePlaceForCountryFiles(int64_t version, s /// @note The function assumes the maps are located in writable dir/|dataDir|/|version| directory. /// If |dataDir| is empty (or is not set) the function assumes that maps are in writable dir. /// @{ +/// @param[in] countryName Actually, same as storage::CountryId, like "Abkhazia". +std::string GetFilePath(int64_t version, std::string const & dataDir, + std::string const & countryName, MapFileType type); std::string GetFileDownloadPath(int64_t version, std::string const & dataDir, - std::string const & mwmName, MapFileType type); + std::string const & countryName, MapFileType type); + inline std::string GetFileDownloadPath(int64_t version, std::string const & dataDir, CountryFile const & countryFile, MapFileType type) { diff --git a/platform/platform_tests/country_file_tests.cpp b/platform/platform_tests/country_file_tests.cpp index f3b313b491..c44a9d17de 100644 --- a/platform/platform_tests/country_file_tests.cpp +++ b/platform/platform_tests/country_file_tests.cpp @@ -16,7 +16,7 @@ UNIT_TEST(CountryFile_Smoke) { CountryFile cf("One"); TEST_EQUAL("One", cf.GetName(), ()); - string const mapFileName = GetFileName(cf.GetName(), MapFileType::Map); + string const mapFileName = cf.GetFileName(MapFileType::Map); TEST_EQUAL("One" DATA_FILE_EXTENSION, mapFileName, ()); TEST_EQUAL(0, cf.GetRemoteSize(), ()); @@ -25,7 +25,7 @@ UNIT_TEST(CountryFile_Smoke) { CountryFile cf("Three", 666, "xxxSHAxxx"); TEST_EQUAL("Three", cf.GetName(), ()); - string const mapFileName = GetFileName(cf.GetName(), MapFileType::Map); + string const mapFileName = cf.GetFileName(MapFileType::Map); TEST_EQUAL("Three" DATA_FILE_EXTENSION, mapFileName, ()); TEST_EQUAL(666, cf.GetRemoteSize(), ()); diff --git a/platform/platform_tests/local_country_file_tests.cpp b/platform/platform_tests/local_country_file_tests.cpp index 8886ea742c..4a91de8d54 100644 --- a/platform/platform_tests/local_country_file_tests.cpp +++ b/platform/platform_tests/local_country_file_tests.cpp @@ -88,7 +88,7 @@ UNIT_TEST(LocalCountryFile_DiskFiles) TEST(!localFile.OnDisk(MapFileType::Map), ()); TEST(!localFile.OnDisk(MapFileType::Diff), ()); - string const mapFileName = GetFileName(countryFile.GetName(), MapFileType::Map); + string const mapFileName = countryFile.GetFileName(MapFileType::Map); string const mapFileContents("map"); ScopedFile testMapFile(mapFileName, mapFileContents); @@ -140,28 +140,36 @@ UNIT_TEST(LocalCountryFile_CleanupMapFiles) TEST(dir4.Exists(), ()); - TEST(!absentCountryIndexesDir.Exists(), ("Indexes for absent country weren't deleted.")); - absentCountryIndexesDir.Reset(); + // Useless CountryIndexes::DeleteFromDisk calls are removed. + //TEST(!absentCountryIndexesDir.Exists(), ("Indexes for absent country weren't deleted.")); + //absentCountryIndexesDir.Reset(); TEST(irelandIndexesDir.Exists(), ()); } UNIT_TEST(LocalCountryFile_CleanupPartiallyDownloadedFiles) { + ScopedDir dataDir("101008"); + auto const DataFilePath = [&dataDir](char const * file) + { + return dataDir.GetRelativePath() + "/" + file; + }; + ScopedDir oldDir("101009"); ScopedDir latestDir("101010"); ScopedFile toBeDeleted[] = { - {"Ireland.mwm.ready", ScopedFile::Mode::Create}, - {"Netherlands.mwm.routing.downloading2", ScopedFile::Mode::Create}, - {"Germany.mwm.ready3", ScopedFile::Mode::Create}, - {"UK_England.mwm.resume4", ScopedFile::Mode::Create}, + {DataFilePath("Ireland.mwm.ready"), ScopedFile::Mode::Create}, + {DataFilePath("Netherlands.mwm.routing.downloading2"), ScopedFile::Mode::Create}, + {DataFilePath("Germany.mwm.ready3"), ScopedFile::Mode::Create}, + {DataFilePath("UK_England.mwm.resume4"), ScopedFile::Mode::Create}, {base::JoinPath(oldDir.GetRelativePath(), "Russia_Central.mwm.downloading"), ScopedFile::Mode::Create}}; + ScopedFile toBeKept[] = { - {"Italy.mwm", ScopedFile::Mode::Create}, - {"Spain.mwm", ScopedFile::Mode::Create}, - {"Spain.mwm.routing", ScopedFile::Mode::Create}, + {DataFilePath("Italy.mwm"), ScopedFile::Mode::Create}, + {DataFilePath("Spain.mwm"), ScopedFile::Mode::Create}, + {DataFilePath("Spain.mwm.routing"), ScopedFile::Mode::Create}, {base::JoinPath(latestDir.GetRelativePath(), "Russia_Southern.mwm.downloading"), ScopedFile::Mode::Create}}; @@ -177,7 +185,9 @@ UNIT_TEST(LocalCountryFile_CleanupPartiallyDownloadedFiles) for (ScopedFile & file : toBeKept) TEST(file.Exists(), (file)); + TEST(latestDir.Exists(), (latestDir)); + TEST(dataDir.Exists(), (dataDir)); } // Creates test-dir and following files: diff --git a/platform/platform_tests_support/scoped_file.cpp b/platform/platform_tests_support/scoped_file.cpp index 105c5e2b1f..9249b11ac2 100644 --- a/platform/platform_tests_support/scoped_file.cpp +++ b/platform/platform_tests_support/scoped_file.cpp @@ -31,9 +31,7 @@ ScopedFile::ScopedFile(std::string const & relativePath, std::string const & con } ScopedFile::ScopedFile(ScopedDir const & dir, CountryFile const & countryFile, MapFileType type) - : ScopedFile( - base::JoinPath(dir.GetRelativePath(), GetFileName(countryFile.GetName(), type)), - Mode::Create) +: ScopedFile(base::JoinPath(dir.GetRelativePath(), countryFile.GetFileName(type)), Mode::Create) { } diff --git a/storage/queued_country.cpp b/storage/queued_country.cpp index c2d505adeb..cf2ae569d9 100644 --- a/storage/queued_country.cpp +++ b/storage/queued_country.cpp @@ -51,7 +51,7 @@ CountryId const & QueuedCountry::GetCountryId() const std::string QueuedCountry::GetRelativeUrl() const { - auto const fileName = platform::GetFileName(m_countryFile.GetName(), m_fileType); + auto const fileName = m_countryFile.GetFileName(m_fileType); uint64_t diffVersion = 0; if (m_fileType == MapFileType::Diff) diff --git a/storage/storage.cpp b/storage/storage.cpp index ab5edab1eb..dc084d7a29 100644 --- a/storage/storage.cpp +++ b/storage/storage.cpp @@ -31,19 +31,15 @@ #include "3party/jansson/myjansson.hpp" #include -#include -#include #include +namespace storage +{ using namespace downloader; using namespace generator::mwm_diff; using namespace platform; using namespace std; -using namespace std::chrono; -using namespace std::placeholders; -namespace storage -{ namespace { string const kDownloadQueueKey = "DownloadQueue"; @@ -416,7 +412,7 @@ Status Storage::CountryStatusEx(CountryId const & countryId) const if (GetRemoteSize(countryFile) == 0) return Status::UnknownError; - if (localFile->GetVersion() != GetCurrentDataVersion()) + if (localFile->GetVersion() != m_currentVersion) return Status::OnDiskOutOfDate; return Status::OnDisk; } @@ -470,7 +466,7 @@ void Storage::DownloadCountry(CountryId const & countryId, MapFileType type) // If it's not even possible to prepare directory for files before // downloading, then mark this country as failed and switch to next // country. - if (!PreparePlaceForCountryFiles(GetCurrentDataVersion(), m_dataDir, countryFile)) + if (!PreparePlaceForCountryFiles(m_currentVersion, m_dataDir, countryFile)) { OnMapDownloadFinished(countryId, DownloadStatus::Failed, type); return; @@ -482,7 +478,7 @@ void Storage::DownloadCountry(CountryId const & countryId, MapFileType type) return; } - QueuedCountry queuedCountry(countryFile, countryId, type, GetCurrentDataVersion(), m_dataDir, + QueuedCountry queuedCountry(countryFile, countryId, type, m_currentVersion, m_dataDir, m_diffsDataSource); queuedCountry.Subscribe(*this); @@ -712,7 +708,7 @@ void Storage::RegisterDownloadedFiles(CountryId const & countryId, MapFileType t return; } - LocalFilePtr localFile = GetLocalFile(countryId, GetCurrentDataVersion()); + LocalFilePtr localFile = GetLocalFile(countryId, m_currentVersion); ASSERT(localFile, ()); // This is the final point of success download or diff or update, so better @@ -937,16 +933,20 @@ bool Storage::DeleteCountryFilesFromDownloader(CountryId const & countryId) m_diffsBeingApplied[countryId]->Cancel(); m_downloader->Remove(countryId); - DeleteDownloaderFilesForCountry(GetCurrentDataVersion(), m_dataDir, GetCountryFile(countryId)); + DeleteDownloaderFilesForCountry(m_currentVersion, m_dataDir, GetCountryFile(countryId)); SaveDownloadQueue(); return true; } +string Storage::GetFilePath(CountryId const & countryId, MapFileType type) const +{ + return platform::GetFilePath(m_currentVersion, m_dataDir, countryId, type); +} + string Storage::GetFileDownloadPath(CountryId const & countryId, MapFileType type) const { - return platform::GetFileDownloadPath(GetCurrentDataVersion(), m_dataDir, - GetCountryFile(countryId), type); + return platform::GetFileDownloadPath(m_currentVersion, m_dataDir, countryId, type); } bool Storage::CheckFailedCountries(CountriesVec const & countries) const @@ -1272,7 +1272,8 @@ bool Storage::IsDisputed(CountryTree::Node const & node) const void Storage::CalcMaxMwmSizeBytes() { m_maxMwmSizeBytes = 0; - m_countries.GetRoot().ForEachInSubtree([&](CountryTree::Node const & node) { + m_countries.GetRoot().ForEachInSubtree([&](CountryTree::Node const & node) + { if (node.ChildrenCount() == 0) { MwmSize mwmSizeBytes = node.Value().GetSubtreeMwmSizeBytes(); @@ -1321,7 +1322,7 @@ void Storage::ApplyDiff(CountryId const & countryId, functionVersionFor(countryId, version)) @@ -1415,14 +1416,13 @@ bool Storage::IsPossibleToAutoupdate() const if (m_diffsDataSource->GetStatus() != diffs::Status::Available) return false; - auto const currentVersion = GetCurrentDataVersion(); CountriesVec localMaps; GetLocalRealMaps(localMaps); for (auto const & countryId : localMaps) { auto const localFile = GetLatestLocalFile(countryId); auto const mapVersion = localFile->GetVersion(); - if (mapVersion != currentVersion && mapVersion > 0 && + if (mapVersion != m_currentVersion && mapVersion > 0 && !m_diffsDataSource->HasDiffFor(localFile->GetCountryName())) { return false; diff --git a/storage/storage.hpp b/storage/storage.hpp index eaeac11431..830c0233aa 100644 --- a/storage/storage.hpp +++ b/storage/storage.hpp @@ -483,7 +483,7 @@ public: // of several versions of the same map keeps only the latest one, others // are deleted from disk. // *NOTE* storage will forget all already known local maps. - void RegisterAllLocalMaps(bool enableDiffs); + void RegisterAllLocalMaps(bool enableDiffs = false); // Returns list of all local maps, including fake countries (World*.mwm). void GetLocalMaps(std::vector & maps) const; @@ -559,6 +559,8 @@ public: void SetStartDownloadingCallback(StartDownloadingCallback const & cb); + std::string GetFilePath(CountryId const & countryId, MapFileType file) const; + protected: void OnFinishDownloading(); @@ -598,8 +600,7 @@ private: // Removes country files from downloader. bool DeleteCountryFilesFromDownloader(CountryId const & countryId); - // Returns a path to a place on disk downloader can use for - // downloaded files. + // Returns a path to a place on disk downloader can use for downloaded files. std::string GetFileDownloadPath(CountryId const & countryId, MapFileType file) const; /// Fast version, doesn't check if country is out of date diff --git a/storage/storage_integration_tests/download_calc_size_test.cpp b/storage/storage_integration_tests/download_calc_size_test.cpp index bffc7cf321..fe3e4cc3f6 100644 --- a/storage/storage_integration_tests/download_calc_size_test.cpp +++ b/storage/storage_integration_tests/download_calc_size_test.cpp @@ -24,7 +24,7 @@ void InitStorage(Storage & storage, Storage::UpdateCallback const & didDownload, }; storage.Init(didDownload, [](CountryId const &, LocalFilePtr const) { return false; }); - storage.RegisterAllLocalMaps(false /* enableDiffs */); + storage.RegisterAllLocalMaps(); storage.Subscribe(changeCountryFunction, progress); storage.SetDownloadingServersForTesting({kTestWebServer}); } diff --git a/storage/storage_integration_tests/storage_downloading_tests.cpp b/storage/storage_integration_tests/storage_downloading_tests.cpp index c6cf3b4a89..eb33ca4275 100644 --- a/storage/storage_integration_tests/storage_downloading_tests.cpp +++ b/storage/storage_integration_tests/storage_downloading_tests.cpp @@ -58,7 +58,7 @@ void ChangeCountry(Storage & storage, CountryId const & countryId) void InitStorage(Storage & storage, Storage::ProgressFunction const & onProgressFn) { storage.Init(Update, [](CountryId const &, storage::LocalFilePtr const) { return false; }); - storage.RegisterAllLocalMaps(false /* enableDiffs */); + storage.RegisterAllLocalMaps(); storage.Subscribe(bind(&ChangeCountry, ref(storage), _1), onProgressFn); storage.SetDownloadingServersForTesting({kTestWebServer}); } diff --git a/storage/storage_integration_tests/storage_group_download_tests.cpp b/storage/storage_integration_tests/storage_group_download_tests.cpp index de39e38d1f..09aee12e8e 100644 --- a/storage/storage_integration_tests/storage_group_download_tests.cpp +++ b/storage/storage_integration_tests/storage_group_download_tests.cpp @@ -257,7 +257,7 @@ void TestDownloadDelete(bool downloadOneByOne, bool deleteOneByOne) }; storage.Init(onUpdatedFn, [](CountryId const &, storage::LocalFilePtr const) { return false; }); - storage.RegisterAllLocalMaps(false /* enableDiffs */); + storage.RegisterAllLocalMaps(); storage.SetDownloadingServersForTesting({kTestWebServer}); tests_support::ScopedDir cleanupVersionDir(version); diff --git a/storage/storage_integration_tests/storage_http_tests.cpp b/storage/storage_integration_tests/storage_http_tests.cpp index a5bcd8d189..1d16a9d94d 100644 --- a/storage/storage_integration_tests/storage_http_tests.cpp +++ b/storage/storage_integration_tests/storage_http_tests.cpp @@ -67,7 +67,7 @@ void InitStorage(Storage & storage, Storage::UpdateCallback const & didDownload, }; storage.Init(didDownload, [](CountryId const &, LocalFilePtr const) { return false; }); - storage.RegisterAllLocalMaps(false /* enableDiffs */); + storage.RegisterAllLocalMaps(); storage.Subscribe(changeCountryFunction, progress); storage.SetDownloadingServersForTesting({kTestWebServer}); } diff --git a/storage/storage_tests/storage_tests.cpp b/storage/storage_tests/storage_tests.cpp index 3d683d0786..4566b1c1c3 100644 --- a/storage/storage_tests/storage_tests.cpp +++ b/storage/storage_tests/storage_tests.cpp @@ -477,7 +477,7 @@ void InitStorage(Storage & storage, TaskRunner & runner, { storage.Clear(); storage.Init(update, [](CountryId const &, LocalFilePtr const) { return false; }); - storage.RegisterAllLocalMaps(false /* enableDiffs */); + storage.RegisterAllLocalMaps(); storage.SetDownloaderForTesting(make_unique(runner)); // Disable because of FakeMapFilesDownloader. storage.SetEnabledIntegrityValidationForTesting(false); @@ -515,8 +515,7 @@ UNIT_TEST(StorageTest_Smoke) CountryId const georgiaCountryId = storage.FindCountryIdByFile("Georgia"); TEST(IsCountryIdValid(georgiaCountryId), ()); CountryFile usaGeorgiaFile = storage.GetCountryFile(georgiaCountryId); - TEST_EQUAL(platform::GetFileName(usaGeorgiaFile.GetName(), MapFileType::Map), - "Georgia" DATA_FILE_EXTENSION, ()); + TEST_EQUAL(usaGeorgiaFile.GetFileName(MapFileType::Map), "Georgia" DATA_FILE_EXTENSION, ()); } UNIT_CLASS_TEST(StorageTest, CountryDownloading) @@ -555,7 +554,7 @@ UNIT_TEST(StorageTest_DeleteTwoVersionsOfTheSameCountry) int64_t const v2 = version::FOR_TESTING_MWM2; storage.Init(&OnCountryDownloaded, [](CountryId const &, LocalFilePtr const) { return false; }); - storage.RegisterAllLocalMaps(false /* enableDiffs */); + storage.RegisterAllLocalMaps(); CountryId const countryId = storage.FindCountryIdByFile("Azerbaijan"); TEST(IsCountryIdValid(countryId), ()); @@ -567,14 +566,14 @@ UNIT_TEST(StorageTest_DeleteTwoVersionsOfTheSameCountry) TEST_EQUAL(Status::NotDownloaded, storage.CountryStatusEx(countryId), ()); LocalFilePtr localFileV1 = CreateDummyMapFile(countryFile, v1, 1024 /* size */); - storage.RegisterAllLocalMaps(false /* enableDiffs */); + storage.RegisterAllLocalMaps(); latestLocalFile = storage.GetLatestLocalFile(countryId); TEST(latestLocalFile.get(), ("Created map file wasn't found by storage.")); TEST_EQUAL(latestLocalFile->GetVersion(), localFileV1->GetVersion(), ()); TEST_EQUAL(Status::OnDiskOutOfDate, storage.CountryStatusEx(countryId), ()); LocalFilePtr localFileV2 = CreateDummyMapFile(countryFile, v2, 2048 /* size */); - storage.RegisterAllLocalMaps(false /* enableDiffs */); + storage.RegisterAllLocalMaps(); latestLocalFile = storage.GetLatestLocalFile(countryId); TEST(latestLocalFile.get(), ("Created map file wasn't found by storage.")); TEST_EQUAL(latestLocalFile->GetVersion(), localFileV2->GetVersion(), ()); @@ -698,7 +697,7 @@ UNIT_TEST(StorageTest_ObsoleteMapsRemoval) TEST(map1.Exists(), ()); TEST(map2.Exists(), ()); - storage.RegisterAllLocalMaps(false /* enableDiffs */); + storage.RegisterAllLocalMaps(); TEST(!map1.Exists(), ()); map1.Reset(); @@ -1038,7 +1037,7 @@ UNIT_TEST(StorageTest_GetUpdateInfoSingleMwm) } Storage storage(kCountriesTxt, make_unique()); - storage.RegisterAllLocalMaps(false /* enableDiffs */); + storage.RegisterAllLocalMaps(); country1.SyncWithDisk(); country2.SyncWithDisk(); diff --git a/track_analyzing/track_analyzer/cmd_balance_csv.cpp b/track_analyzing/track_analyzer/cmd_balance_csv.cpp index 0dc806516b..ef7da05d08 100644 --- a/track_analyzing/track_analyzer/cmd_balance_csv.cpp +++ b/track_analyzing/track_analyzer/cmd_balance_csv.cpp @@ -274,7 +274,7 @@ void CmdBalanceCsv(string const & csvPath, string const & distributionPath, // Calculating statistics. storage::Storage storage; - storage.RegisterAllLocalMaps(false /* enableDiffs */); + storage.RegisterAllLocalMaps(); Stats stats; for (auto const & record : balancedTable) { diff --git a/track_analyzing/track_analyzer/cmd_match.cpp b/track_analyzing/track_analyzer/cmd_match.cpp index c3ece943ef..948516e6e4 100644 --- a/track_analyzing/track_analyzer/cmd_match.cpp +++ b/track_analyzing/track_analyzer/cmd_match.cpp @@ -113,7 +113,7 @@ void CmdMatch(string const & logFile, string const & trackFile, string const & i { LOG(LINFO, ("Matching", logFile)); Storage storage; - storage.RegisterAllLocalMaps(false /* enableDiffs */); + storage.RegisterAllLocalMaps(); shared_ptr numMwmIds = CreateNumMwmIds(storage); Stats stats; @@ -125,7 +125,7 @@ void CmdMatch(string const & logFile, string const & trackFile, string const & i void UnzipAndMatch(Iter begin, Iter end, string const & trackExt, Stats & stats) { Storage storage; - storage.RegisterAllLocalMaps(false /* enableDiffs */); + storage.RegisterAllLocalMaps(); shared_ptr numMwmIds = CreateNumMwmIds(storage); for (auto it = begin; it != end; ++it) { diff --git a/track_analyzing/track_analyzer/cmd_table.cpp b/track_analyzing/track_analyzer/cmd_table.cpp index c2c18c3b17..5a20c55c6e 100644 --- a/track_analyzing/track_analyzer/cmd_table.cpp +++ b/track_analyzing/track_analyzer/cmd_table.cpp @@ -391,7 +391,7 @@ void CmdTagsTable(string const & filepath, string const & trackExtension, String WriteCsvTableHeader(cout); storage::Storage storage; - storage.RegisterAllLocalMaps(false /* enableDiffs */); + storage.RegisterAllLocalMaps(); FrozenDataSource dataSource; auto numMwmIds = CreateNumMwmIds(storage); diff --git a/track_analyzing/utils.cpp b/track_analyzing/utils.cpp index cb927731cf..d18850dab0 100644 --- a/track_analyzing/utils.cpp +++ b/track_analyzing/utils.cpp @@ -94,8 +94,7 @@ MatchedTrack const & GetMatchedTrack(MwmToMatchedTracks const & mwmToMatchedTrac std::string GetCurrentVersionMwmFile(storage::Storage const & storage, std::string const & mwmName) { - return base::JoinPath(GetPlatform().WritableDir(), to_string(storage.GetCurrentDataVersion()), - mwmName + DATA_FILE_EXTENSION); + return storage.GetFilePath(mwmName, MapFileType::Map); } void ForEachTrackFile( -- 2.45.3 From feeff70bd7529a44ac676a4e431dde2f9214ec63 Mon Sep 17 00:00:00 2001 From: Viktor Govako Date: Mon, 18 Apr 2022 20:51:33 +0300 Subject: [PATCH 18/21] [android] Added World files into countries list. Signed-off-by: Viktor Govako --- .../maps/DownloadResourcesLegacyActivity.cpp | 99 ++++-------- android/jni/com/mapswithme/maps/Framework.cpp | 17 +- android/jni/com/mapswithme/maps/Framework.hpp | 1 + .../maps/DownloadResourcesLegacyActivity.java | 7 +- .../src/com/mapswithme/maps/Framework.java | 4 +- .../maps/downloader/DownloaderAdapter.java | 16 +- data/countries.txt | 10 ++ platform/local_country_file.hpp | 1 + platform/local_country_file_utils.cpp | 51 +++--- storage/country_info_getter.cpp | 13 +- storage/storage.cpp | 146 +++++++++++++++--- storage/storage.hpp | 10 +- storage/storage_tests/CMakeLists.txt | 1 + storage/storage_tests/countries_tests.cpp | 14 ++ storage/storage_tests/storage_tests.cpp | 15 +- 15 files changed, 248 insertions(+), 157 deletions(-) create mode 100644 storage/storage_tests/countries_tests.cpp diff --git a/android/jni/com/mapswithme/maps/DownloadResourcesLegacyActivity.cpp b/android/jni/com/mapswithme/maps/DownloadResourcesLegacyActivity.cpp index e577336829..50834befd2 100644 --- a/android/jni/com/mapswithme/maps/DownloadResourcesLegacyActivity.cpp +++ b/android/jni/com/mapswithme/maps/DownloadResourcesLegacyActivity.cpp @@ -40,18 +40,10 @@ using namespace std::placeholders; #define ERR_FILE_IN_PROGRESS -6 //@} -struct FileToDownload -{ - std::vector m_urls; - std::string m_fileName; - std::string m_pathOnSdcard; - uint64_t m_fileSize; -}; - namespace { -static std::vector g_filesToDownload; +static std::vector g_filesToDownload; static int g_totalDownloadedBytes; static int g_totalBytesToDownload; static std::shared_ptr g_currentRequest; @@ -77,24 +69,6 @@ extern "C" } } - // Check if we need to download mandatory resource file. - static bool NeedToDownload(Platform & pl, std::string const & name, int size) - { - try - { - ModelReaderPtr reader(pl.GetReader(name)); - return false; - } - catch (RootException const &) - { - // TODO: A hack for a changed font file name. Remove when this stops being relevant. - // This is because we don't want to force update users with the old font (which is good enough) - if (name == "02_droidsans-fallback.ttf") - return NeedToDownload(pl, "02_wqy-microhei.ttf", size); // Size is not checked anyway - } - return true; - } - JNIEXPORT jint JNICALL Java_com_mapswithme_maps_DownloadResourcesLegacyActivity_nativeGetBytesToDownload(JNIEnv * env, jclass clazz) { @@ -103,39 +77,14 @@ extern "C" g_totalBytesToDownload = 0; g_totalDownloadedBytes = 0; + storage::Storage const & storage = g_framework->GetStorage(); + bool const anyWorldWasMoved = storage.GetForceDownloadWorlds(g_filesToDownload); + + for (auto const & cf : g_filesToDownload) + g_totalBytesToDownload += cf.GetRemoteSize(); + Platform & pl = GetPlatform(); - std::string const path = pl.WritableDir(); - - ReaderStreamBuf buffer(pl.GetReader(EXTERNAL_RESOURCES_FILE)); - std::istream in(&buffer); - - std::string name; - int size; - while (true) - { - in >> name; - if (!in.good()) - break; - - in >> size; - if (!in.good()) - break; - - if (NeedToDownload(pl, name, size)) - { - LOG(LDEBUG, ("Should download", name, "size", size, "bytes")); - - FileToDownload f; - f.m_pathOnSdcard = path + name; - f.m_fileName = name; - f.m_fileSize = size; - - g_filesToDownload.push_back(f); - g_totalBytesToDownload += size; - } - } - - int const res = HasSpaceForFiles(pl, path, g_totalBytesToDownload); + int const res = HasSpaceForFiles(pl, pl.WritableDir(), g_totalBytesToDownload); if (res == ERR_STORAGE_DISCONNECTED) LOG(LWARNING, ("External file system is not available")); else if (res == ERR_NOT_ENOUGH_FREE_SPACE) @@ -143,6 +92,9 @@ extern "C" g_currentRequest.reset(); + if (anyWorldWasMoved && res == 0) + g_framework->ReloadWorldMaps(); + return res; } @@ -159,10 +111,11 @@ extern "C" if (errorCode == ERR_DOWNLOAD_SUCCESS) { - FileToDownload & curFile = g_filesToDownload.back(); - LOG(LDEBUG, ("finished downloading", curFile.m_fileName, "size", curFile.m_fileSize, "bytes")); + auto const & curFile = g_filesToDownload.back(); + size_t const sz = curFile.GetRemoteSize(); + LOG(LDEBUG, ("finished downloading", curFile.GetName(), "size", sz, "bytes")); - g_totalDownloadedBytes += curFile.m_fileSize; + g_totalDownloadedBytes += sz; LOG(LDEBUG, ("totalDownloadedBytes:", g_totalDownloadedBytes)); g_filesToDownload.pop_back(); @@ -189,18 +142,22 @@ extern "C" /// @todo One downloader instance with cached servers. All this routine will be refactored some time. static auto downloader = storage::GetDownloader(); - downloader->SetDataVersion(g_framework->GetStorage().GetCurrentDataVersion()); + storage::Storage const & storage = g_framework->GetStorage(); + downloader->SetDataVersion(storage.GetCurrentDataVersion()); - downloader->EnsureServersListReady([ptr = jni::make_global_ref(listener)]() + downloader->EnsureServersListReady([&storage, ptr = jni::make_global_ref(listener)]() { - FileToDownload const & curFile = g_filesToDownload.back(); - LOG(LINFO, ("Downloading file", curFile.m_fileName)); + auto const & curFile = g_filesToDownload.back(); + auto const fileName = curFile.GetFileName(MapFileType::Map); + LOG(LINFO, ("Downloading file", fileName)); - auto const urls = downloader->MakeUrlListLegacy(curFile.m_fileName); - g_currentRequest.reset(HttpRequest::GetFile(urls, curFile.m_pathOnSdcard, curFile.m_fileSize, - std::bind(&DownloadFileFinished, ptr, _1), - std::bind(&DownloadFileProgress, ptr, _1), - 512 * 1024, false)); + g_currentRequest.reset(HttpRequest::GetFile( + downloader->MakeUrlListLegacy(fileName), + storage.GetFilePath(curFile.GetName(), MapFileType::Map), + curFile.GetRemoteSize(), + std::bind(&DownloadFileFinished, ptr, _1), + std::bind(&DownloadFileProgress, ptr, _1), + 512 * 1024, false)); }); return ERR_FILE_IN_PROGRESS; diff --git a/android/jni/com/mapswithme/maps/Framework.cpp b/android/jni/com/mapswithme/maps/Framework.cpp index 88106faeec..5563e46a8b 100644 --- a/android/jni/com/mapswithme/maps/Framework.cpp +++ b/android/jni/com/mapswithme/maps/Framework.cpp @@ -554,6 +554,13 @@ void Framework::RemoveLocalMaps() m_work.DeregisterAllMaps(); } +void Framework::ReloadWorldMaps() +{ + /// @todo Can invent more optimal routine to remove/add World files only. + RemoveLocalMaps(); + AddLocalMaps(); +} + void Framework::ReplaceBookmark(kml::MarkId markId, kml::BookmarkData & bm) { m_work.GetBookmarkManager().GetEditSession().UpdateBookmark(markId, bm); @@ -1506,15 +1513,9 @@ Java_com_mapswithme_maps_Framework_nativeGetTransitRouteInfo(JNIEnv * env, jclas } JNIEXPORT void JNICALL -Java_com_mapswithme_maps_Framework_nativeRegisterMaps(JNIEnv * env, jclass) +Java_com_mapswithme_maps_Framework_nativeReloadWorldMaps(JNIEnv * env, jclass) { - frm()->RegisterAllMaps(); -} - -JNIEXPORT void JNICALL -Java_com_mapswithme_maps_Framework_nativeDeregisterMaps(JNIEnv * env, jclass) -{ - frm()->DeregisterAllMaps(); + g_framework->ReloadWorldMaps(); } JNIEXPORT jboolean JNICALL diff --git a/android/jni/com/mapswithme/maps/Framework.hpp b/android/jni/com/mapswithme/maps/Framework.hpp index 3950059149..ad693a0632 100644 --- a/android/jni/com/mapswithme/maps/Framework.hpp +++ b/android/jni/com/mapswithme/maps/Framework.hpp @@ -137,6 +137,7 @@ namespace android void AddLocalMaps(); void RemoveLocalMaps(); + void ReloadWorldMaps(); m2::PointD GetViewportCenter() const; diff --git a/android/src/com/mapswithme/maps/DownloadResourcesLegacyActivity.java b/android/src/com/mapswithme/maps/DownloadResourcesLegacyActivity.java index 0ca4a47379..37bf6c3309 100644 --- a/android/src/com/mapswithme/maps/DownloadResourcesLegacyActivity.java +++ b/android/src/com/mapswithme/maps/DownloadResourcesLegacyActivity.java @@ -404,10 +404,9 @@ public class DownloadResourcesLegacyActivity extends BaseMwmFragmentActivity imp { if (result == ERR_NO_MORE_FILES) { - // World and WorldCoasts has been downloaded, we should register maps again to correctly add them to the model and generate indexes etc. - // TODO fix the hack when separate download of World-s will be removed or refactored - Framework.nativeDeregisterMaps(); - Framework.nativeRegisterMaps(); + // World and WorldCoasts has been downloaded, we should register maps again to correctly add them to the model. + Framework.nativeReloadWorldMaps(); + if (mCurrentCountry != null && mChbDownloadCountry.isChecked()) { CountryItem item = CountryItem.fill(mCurrentCountry); diff --git a/android/src/com/mapswithme/maps/Framework.java b/android/src/com/mapswithme/maps/Framework.java index 06e77c4989..fba06cc87c 100644 --- a/android/src/com/mapswithme/maps/Framework.java +++ b/android/src/com/mapswithme/maps/Framework.java @@ -308,9 +308,7 @@ public class Framework /** * Registers all maps(.mwms). Adds them to the models, generates indexes and does all necessary stuff. */ - public static native void nativeRegisterMaps(); - - public static native void nativeDeregisterMaps(); + public static native void nativeReloadWorldMaps(); /** * Determines if currently is day or night at the given location. Used to switch day/night styles. diff --git a/android/src/com/mapswithme/maps/downloader/DownloaderAdapter.java b/android/src/com/mapswithme/maps/downloader/DownloaderAdapter.java index 3af7834645..9db1a5d593 100644 --- a/android/src/com/mapswithme/maps/downloader/DownloaderAdapter.java +++ b/android/src/com/mapswithme/maps/downloader/DownloaderAdapter.java @@ -334,10 +334,14 @@ class DownloaderAdapter extends RecyclerView.Adapter onExploreActionSelected(mItem, DownloaderAdapter.this)); } - private MenuBottomSheetItem getDeleteMenuItem() + private void appendDeleteMenuItem(ArrayList items) { - return new MenuBottomSheetItem(R.string.delete, R.drawable.ic_delete, - () -> onDeleteActionSelected(mItem, DownloaderAdapter.this)); + // Do not show "Delete" option for World files. + // Checking name is not beautiful, but the simplest way for now .. + if (!mItem.id.startsWith("World")) { + items.add(new MenuBottomSheetItem(R.string.delete, R.drawable.ic_delete, + () -> onDeleteActionSelected(mItem, DownloaderAdapter.this))); + } } private MenuBottomSheetItem getCancelMenuItem() @@ -362,7 +366,7 @@ class DownloaderAdapter extends RecyclerView.AdapterGetCountryFile().GetName() == file) + if (i->GetCountryName() == file) break; } try { - Platform & platform = GetPlatform(); - ModelReaderPtr reader( - platform.GetReader(file + DATA_FILE_EXTENSION, GetSpecialFilesSearchScope())); + ModelReaderPtr reader(platform.GetReader(file + DATA_FILE_EXTENSION, GetAdditionalWorldScope())); - // Assume that empty path means the resource file. - LocalCountryFile worldFile{string(), CountryFile(file), version::ReadVersionDate(reader)}; - worldFile.m_files[base::Underlying(MapFileType::Map)] = 1; + // Empty path means the resource file. + LocalCountryFile worldFile(string(), CountryFile(file), version::ReadVersionDate(reader)); + worldFile.m_files[base::Underlying(MapFileType::Map)] = reader.Size(); + + // Replace if newer only. if (i != localFiles.end()) { - // Always use resource World files instead of local on disk. - *i = worldFile; + if (worldFile.GetVersion() > i->GetVersion()) + *i = std::move(worldFile); } else - localFiles.push_back(worldFile); + localFiles.push_back(std::move(worldFile)); } catch (RootException const & ex) { @@ -329,16 +327,13 @@ string GetFileDownloadPath(int64_t version, string const & dataDir, string const return GetFilePath(version, dataDir, countryName, type) + READY_FILE_EXTENSION; } -unique_ptr GetCountryReader(platform::LocalCountryFile const & file, MapFileType type) +unique_ptr GetCountryReader(LocalCountryFile const & file, MapFileType type) { Platform & platform = GetPlatform(); - // See LocalCountryFile comment for explanation. - if (file.GetDirectory().empty()) - { - return platform.GetReader(file.GetCountryName() + DATA_FILE_EXTENSION, - GetSpecialFilesSearchScope()); - } - return platform.GetReader(file.GetPath(type), "f"); + if (file.IsInBundle()) + return platform.GetReader(file.GetFileName(type), GetAdditionalWorldScope()); + else + return platform.GetReader(file.GetPath(type), "f"); } // static @@ -408,11 +403,9 @@ string CountryIndexes::IndexesDir(LocalCountryFile const & localFile) string dir = localFile.GetDirectory(); CountryFile const & file = localFile.GetCountryFile(); - /// @todo It's a temporary code until we will put fIndex->fOffset into mwm container. - /// IndexesDir should not throw any exceptions. - if (dir.empty()) + if (localFile.IsInBundle()) { - // Local file is stored in resources. Need to prepare index folder in the writable directory. + // Local file is stored in bundle. Need to prepare index folder in the writable directory. int64_t const version = localFile.GetVersion(); ASSERT_GREATER(version, 0, ()); diff --git a/storage/country_info_getter.cpp b/storage/country_info_getter.cpp index a72adaeff4..cf881069f0 100644 --- a/storage/country_info_getter.cpp +++ b/storage/country_info_getter.cpp @@ -148,9 +148,16 @@ m2::RectD CountryInfoGetter::CalcLimitRect(std::string const & prefix) const m2::RectD CountryInfoGetter::GetLimitRectForLeaf(CountryId const & leafCountryId) const { auto const it = m_countryIndex.find(leafCountryId); - ASSERT(it != m_countryIndex.end(), ()); - ASSERT_LESS(it->second, m_countries.size(), ()); - return m_countries[it->second].m_rect; + if (it != m_countryIndex.end()) + { + ASSERT_LESS(it->second, m_countries.size(), ()); + return m_countries[it->second].m_rect; + } + else + { + // Full rect for World files. + return mercator::Bounds::FullRect(); + } } void CountryInfoGetter::GetMatchedRegions(std::string const & affiliation, diff --git a/storage/storage.cpp b/storage/storage.cpp index dc084d7a29..322fcdbc79 100644 --- a/storage/storage.cpp +++ b/storage/storage.cpp @@ -14,6 +14,7 @@ #include "platform/preferred_languages.hpp" #include "platform/settings.hpp" +#include "coding/file_reader.hpp" #include "coding/file_writer.hpp" #include "coding/internal/file_data.hpp" #include "coding/sha1.hpp" @@ -202,7 +203,83 @@ void Storage::Clear() SaveDownloadQueue(); } -void Storage::RegisterAllLocalMaps(bool enableDiffs) +bool Storage::GetForceDownloadWorlds(std::vector & res) const +{ + CHECK_THREAD_CHECKER(m_threadChecker, ()); + + bool hasWorld[] = { false, false }; + string const worldName[] = { WORLD_FILE_NAME, WORLD_COASTS_FILE_NAME }; + + { + // Check if Worlds already present. + std::vector localFiles; + FindAllLocalMapsAndCleanup(m_currentVersion, m_dataDir, localFiles); + for (auto const & f : localFiles) + { + for (int i = 0; i < 2; ++i) + { + if (f.GetCountryName() == worldName[i]) + hasWorld[i] = true; + } + } + + if (hasWorld[0] && hasWorld[1]) + return false; + } + + Platform & pl = GetPlatform(); + + // Parse root data folder (we stored Worlds here in older versions). + // Note that m_dataDir maybe empty and we take Platform::WritableDir. + std::vector rootFiles; + (void)FindAllLocalMapsInDirectoryAndCleanup(m_dataDir.empty() ? pl.WritableDir() : m_dataDir, + 0 /* version */, -1 /* latestVersion */, rootFiles); + + bool anyWorldWasMoved = false; + for (auto const & f : rootFiles) + { + for (int i = 0; i < 2; ++i) + { + if (f.GetCountryName() != worldName[i]) + continue; + + if (!hasWorld[i]) + { + try + { + auto const filePath = f.GetPath(MapFileType::Map); + uint32_t const version = version::ReadVersionDate(pl.GetReader(filePath, "f")); + ASSERT(version > 0, ()); + + auto const dirPath = base::JoinPath(f.GetDirectory(), std::to_string(version)); + if (pl.MkDirChecked(dirPath) && + base::RenameFileX(filePath, base::JoinPath(dirPath, worldName[i] + DATA_FILE_EXTENSION))) + { + anyWorldWasMoved = hasWorld[i] = true; + break; + } + else + LOG(LERROR, ("Can't move", filePath, "into", dirPath)); + } + catch (RootException const & ex) + { + LOG(LERROR, ("Corrupted World file", ex.Msg())); + } + } + DeleteFromDiskWithIndexes(f, MapFileType::Map); + } + } + + for (int i = 0; i < 2; ++i) + { + if (!hasWorld[i]) + res.push_back(GetCountryFile(worldName[i])); + } + + return anyWorldWasMoved; +} + +void Storage::RegisterAllLocalMaps(bool enableDiffs /* = false */) { CHECK_THREAD_CHECKER(m_threadChecker, ()); @@ -210,25 +287,20 @@ void Storage::RegisterAllLocalMaps(bool enableDiffs) m_localFilesForFakeCountries.clear(); vector localFiles; - FindAllLocalMapsAndCleanup(GetCurrentDataVersion(), m_dataDir, localFiles); + FindAllLocalMapsAndCleanup(m_currentVersion, m_dataDir, localFiles); - auto compareByCountryAndVersion = [](LocalCountryFile const & lhs, LocalCountryFile const & rhs) { + sort(localFiles.begin(), localFiles.end(), [](LocalCountryFile const & lhs, LocalCountryFile const & rhs) + { if (lhs.GetCountryFile() != rhs.GetCountryFile()) return lhs.GetCountryFile() < rhs.GetCountryFile(); return lhs.GetVersion() > rhs.GetVersion(); - }; - - auto equalByCountry = [](LocalCountryFile const & lhs, LocalCountryFile const & rhs) { - return lhs.GetCountryFile() == rhs.GetCountryFile(); - }; - - sort(localFiles.begin(), localFiles.end(), compareByCountryAndVersion); + }); auto i = localFiles.begin(); while (i != localFiles.end()) { auto j = i + 1; - while (j != localFiles.end() && equalByCountry(*i, *j)) + while (j != localFiles.end() && i->GetCountryFile() == j->GetCountryFile()) { LocalCountryFile & localFile = *j; LOG(LINFO, ("Removing obsolete", localFile)); @@ -405,7 +477,7 @@ Status Storage::CountryStatusEx(CountryId const & countryId) const return status; auto localFile = GetLatestLocalFile(countryId); - if (!localFile || !localFile->OnDisk(MapFileType::Map)) + if (!localFile || !(localFile->OnDisk(MapFileType::Map) || localFile->IsInBundle())) return Status::NotDownloaded; auto const & countryFile = GetCountryFile(countryId); @@ -731,9 +803,16 @@ void Storage::RegisterDownloadedFiles(CountryId const & countryId, MapFileType t ASSERT_EQUAL(type, MapFileType::Map, ()); CountryFile const countryFile = GetCountryFile(countryId); - LocalFilePtr localFile = GetLocalFile(countryId, GetCurrentDataVersion()); - if (!localFile) - localFile = PreparePlaceForCountryFiles(GetCurrentDataVersion(), m_dataDir, countryFile); + LocalFilePtr localFile = GetLocalFile(countryId, m_currentVersion); + + if (!localFile || localFile->IsInBundle()) + localFile = PreparePlaceForCountryFiles(m_currentVersion, m_dataDir, countryFile); + else + { + /// @todo If localFile already exists, we will remove it from disk below? + LOG(LERROR, ("Downloaded country file for already existing one", *localFile)); + } + if (!localFile) { LOG(LERROR, ("Can't prepare LocalCountryFile for", countryFile, "in folder", m_dataDir)); @@ -798,13 +877,9 @@ void Storage::GetOutdatedCountries(vector & countries) const for (auto const & p : m_localFiles) { CountryId const & countryId = p.first; - string const name = GetCountryFile(countryId).GetName(); LocalFilePtr file = GetLatestLocalFile(countryId); - if (file && file->GetVersion() != GetCurrentDataVersion() && name != WORLD_COASTS_FILE_NAME - && name != WORLD_FILE_NAME) - { + if (file && file->GetVersion() != m_currentVersion && !IsWorldCountryID(countryId)) countries.push_back(&CountryLeafByCountryId(countryId)); - } } } */ @@ -876,7 +951,12 @@ void Storage::RegisterCountryFiles(LocalFilePtr localFile) { LocalFilePtr existingFile = GetLocalFile(countryId, localFile->GetVersion()); if (existingFile) - ASSERT_EQUAL(localFile.get(), existingFile.get(), ()); + { + if (existingFile->IsInBundle()) + *existingFile = *localFile; + else + ASSERT_EQUAL(localFile.get(), existingFile.get(), ()); + } else m_localFiles[countryId].push_front(localFile); } @@ -1133,12 +1213,22 @@ void Storage::GetChildrenInGroups(CountryId const & parent, CountriesVec & downl CountriesVec disputedTerritoriesWithoutSiblings; // All disputed territories in subtree with root == |parent|. CountriesVec allDisputedTerritories; - parentNode->ForEachChild([&](CountryTree::Node const & childNode) { + parentNode->ForEachChild([&](CountryTree::Node const & childNode) + { + CountryId const & childValue = childNode.Value().Name(); + + // Do not show bundled World files in Downloader UI, they are always exist and up-to-date. + if (IsWorldCountryID(childValue)) + { + auto const pFile = GetLatestLocalFile(childValue); + if (pFile && pFile->IsInBundle()) + return; + } + vector> disputedTerritoriesAndStatus; StatusAndError const childStatus = GetNodeStatusInfo(childNode, disputedTerritoriesAndStatus, true /* isDisputedTerritoriesCounted */); - CountryId const & childValue = childNode.Value().Name(); ASSERT_NOT_EQUAL(childStatus.status, NodeStatus::Undefined, ()); for (auto const & disputed : disputedTerritoriesAndStatus) allDisputedTerritories.push_back(disputed.first); @@ -1269,6 +1359,16 @@ bool Storage::IsDisputed(CountryTree::Node const & node) const return found.size() > 1; } +bool Storage::IsCountryLeaf(CountryTree::Node const & node) +{ + return (node.ChildrenCount() == 0 && !IsWorldCountryID(node.Value().Name())); +} + +bool Storage::IsWorldCountryID(CountryId const & country) +{ + return strings::StartsWith(country, WORLD_FILE_NAME); +} + void Storage::CalcMaxMwmSizeBytes() { m_maxMwmSizeBytes = 0; diff --git a/storage/storage.hpp b/storage/storage.hpp index 830c0233aa..3432f829cf 100644 --- a/storage/storage.hpp +++ b/storage/storage.hpp @@ -479,6 +479,10 @@ public: // Clears local files registry and downloader's queue. void Clear(); + /// Used in Android to check Worlds to download. + /// @return true If any World file was moved. + bool GetForceDownloadWorlds(std::vector & res) const; + // Finds and registers all map files in maps directory. In the case // of several versions of the same map keeps only the latest one, others // are deleted from disk. @@ -634,6 +638,10 @@ private: /// @return true if |node.Value().Name()| is a disputed territory and false otherwise. bool IsDisputed(CountryTree::Node const & node) const; + /// @return true iff \a node is a country MWM leaf of the tree. + static bool IsCountryLeaf(CountryTree::Node const & node); + static bool IsWorldCountryID(CountryId const & country); + void CalcMaxMwmSizeBytes(); void OnMapDownloadFailed(CountryId const & countryId); @@ -713,7 +721,7 @@ void Storage::ForEachCountry(ToDo && toDo) const { m_countries.GetRoot().ForEachInSubtree([&](CountryTree::Node const & node) { - if (node.ChildrenCount() == 0) + if (IsCountryLeaf(node)) toDo(node.Value()); }); } diff --git a/storage/storage_tests/CMakeLists.txt b/storage/storage_tests/CMakeLists.txt index 2cebfe6c5c..3233d526f3 100644 --- a/storage/storage_tests/CMakeLists.txt +++ b/storage/storage_tests/CMakeLists.txt @@ -1,6 +1,7 @@ project(storage_tests) set(SRC + countries_tests.cpp country_info_getter_tests.cpp country_name_getter_tests.cpp downloader_tests.cpp diff --git a/storage/storage_tests/countries_tests.cpp b/storage/storage_tests/countries_tests.cpp new file mode 100644 index 0000000000..4478a6ca97 --- /dev/null +++ b/storage/storage_tests/countries_tests.cpp @@ -0,0 +1,14 @@ +#include "testing/testing.hpp" + +#include "platform/platform.hpp" + +#include "coding/sha1.hpp" + +#include "base/logging.hpp" + +UNIT_TEST(CalculateWorldSHA) +{ + auto const path = GetPlatform().ResourcesDir(); + for (char const * country : { WORLD_FILE_NAME, WORLD_COASTS_FILE_NAME }) + LOG(LINFO, (country, coding::SHA1::CalculateBase64(path + country + DATA_FILE_EXTENSION))); +} diff --git a/storage/storage_tests/storage_tests.cpp b/storage/storage_tests/storage_tests.cpp index 4566b1c1c3..544ce31939 100644 --- a/storage/storage_tests/storage_tests.cpp +++ b/storage/storage_tests/storage_tests.cpp @@ -797,29 +797,26 @@ UNIT_CLASS_TEST(StorageTest, DownloadedMap) } // Storage::GetLocalRealMaps() test. - /* - CountriesVec localRealMaps; - storage.GetLocalRealMaps(localRealMaps); - TEST_EQUAL(localRealMaps.size(), 4, ()); +// CountriesVec localRealMaps; +// storage.GetLocalRealMaps(localRealMaps); +// TEST_EQUAL(localRealMaps.size(), 4, ()); TEST(storage.IsNodeDownloaded("Algeria_Central"), ()); TEST(storage.IsNodeDownloaded("Algeria_Coast"), ()); TEST(!storage.IsNodeDownloaded("Algeria_Coast.mwm"), ()); - TEST(!storage.IsNodeDownloaded(WORLD_FILE_NAME), ()); - TEST(!storage.IsNodeDownloaded(WORLD_COASTS_FILE_NAME), ()); - */ + TEST(storage.IsNodeDownloaded(WORLD_FILE_NAME), ()); + TEST(storage.IsNodeDownloaded(WORLD_COASTS_FILE_NAME), ()); // Storage::GetChildrenInGroups test when at least Algeria_Central and Algeria_Coast have been downloaded. CountryId const rootCountryId = storage.GetRootId(); TEST_EQUAL(rootCountryId, COUNTRIES_ROOT, ()); CountriesVec downloaded, available; - CountriesVec downloadedWithKeep, availableWithKeep; - storage.GetChildrenInGroups(rootCountryId, downloaded, available); TEST_EQUAL(downloaded.size(), 1, (downloaded)); TEST_EQUAL(available.size(), 223, ()); + CountriesVec downloadedWithKeep, availableWithKeep; storage.GetChildrenInGroups(rootCountryId, downloadedWithKeep, availableWithKeep, true /* keepAvailableChildren*/); TEST_EQUAL(downloadedWithKeep.size(), 1, (downloadedWithKeep)); -- 2.45.3 From 864ce2eb41495adab5d65fae9fa95eb7d08e7f24 Mon Sep 17 00:00:00 2001 From: Viktor Govako Date: Tue, 19 Apr 2022 08:35:15 +0300 Subject: [PATCH 19/21] Updated hierarchy.txt, removed external_resources.txt Signed-off-by: Viktor Govako --- android/assets/external_resources.txt | 1 - android/script/replace_links.bat | 1 - data/external_resources.txt | 11 -------- data/hierarchy.txt | 2 ++ defines.hpp | 2 -- platform/platform.cpp | 1 - platform/platform_tests/apk_test.cpp | 1 - tools/python/airmaps/dags/build_maps.py | 1 - .../generator/stages_declaration.py | 27 +------------------ tools/python/maps_generator/maps_generator.py | 1 - 10 files changed, 3 insertions(+), 45 deletions(-) delete mode 120000 android/assets/external_resources.txt delete mode 100644 data/external_resources.txt diff --git a/android/assets/external_resources.txt b/android/assets/external_resources.txt deleted file mode 120000 index 767cf5f94e..0000000000 --- a/android/assets/external_resources.txt +++ /dev/null @@ -1 +0,0 @@ -../../data/external_resources.txt \ No newline at end of file diff --git a/android/script/replace_links.bat b/android/script/replace_links.bat index a51ecfcc66..3316ac1985 100644 --- a/android/script/replace_links.bat +++ b/android/script/replace_links.bat @@ -13,7 +13,6 @@ cp ../data/drules_proto_clear.bin assets/ cp ../data/drules_proto_vehicle_dark.bin assets/ cp ../data/drules_proto_vehicle_clear.bin assets/ cp ../data/editor.config assets/ -cp ../data/external_resources.txt assets/ cp ../data/faq.html assets/ cp ../data/fonts_blacklist.txt assets/ cp ../data/fonts_whitelist.txt assets/ diff --git a/data/external_resources.txt b/data/external_resources.txt deleted file mode 100644 index 3d73173f34..0000000000 --- a/data/external_resources.txt +++ /dev/null @@ -1,11 +0,0 @@ -World.mwm 35775691 -WorldCoasts.mwm 4803642 -00_NotoNaskhArabic-Regular.ttf 149192 -00_NotoSansThai-Regular.ttf 21952 -01_dejavusans.ttf 757076 -02_droidsans-fallback.ttf 3451900 -03_jomolhari-id-a3d.ttf 1817160 -04_padauk.ttf 248076 -05_khmeros.ttf 265552 -06_code2000.ttf 3155104 -07_roboto_medium.ttf 168644 diff --git a/data/hierarchy.txt b/data/hierarchy.txt index e68ed08c77..9682142251 100644 --- a/data/hierarchy.txt +++ b/data/hierarchy.txt @@ -1,3 +1,5 @@ +World +WorldCoasts Abkhazia;Q23334;;ab,ru Afghanistan;Q889;af;ps Albania;Q222;al;sq diff --git a/defines.hpp b/defines.hpp index 5aed2bbf7f..6d723efc4d 100644 --- a/defines.hpp +++ b/defines.hpp @@ -86,8 +86,6 @@ #define PACKED_POLYGONS_INFO_TAG "info" #define PACKED_POLYGONS_FILE "packed_polygons.bin" -#define EXTERNAL_RESOURCES_FILE "external_resources.txt" - #define GPS_TRACK_FILENAME "gps_track.dat" #define RESTRICTIONS_FILENAME "restrictions.csv" #define ROAD_ACCESS_FILENAME "road_access.csv" diff --git a/platform/platform.cpp b/platform/platform.cpp index 2cf0fc9f20..9ccd83f151 100644 --- a/platform/platform.cpp +++ b/platform/platform.cpp @@ -204,7 +204,6 @@ void Platform::GetFontNames(FilesList & res) const ASSERT(res.empty(), ()); /// @todo Actually, this list should present once in all our code. - /// We can take it from data/external_resources.txt char const * arrDef[] = { "00_NotoNaskhArabic-Regular.ttf", "00_NotoSansThai-Regular.ttf", diff --git a/platform/platform_tests/apk_test.cpp b/platform/platform_tests/apk_test.cpp index 465bdc8333..9194950311 100644 --- a/platform/platform_tests/apk_test.cpp +++ b/platform/platform_tests/apk_test.cpp @@ -36,7 +36,6 @@ char const * arrFiles[] = { "languages.txt", "unicode_blocks.txt", "drules_proto_clear.bin", - "external_resources.txt", "packed_polygons.bin", "countries.txt" }; diff --git a/tools/python/airmaps/dags/build_maps.py b/tools/python/airmaps/dags/build_maps.py index 9c5569391e..19f380b0d7 100644 --- a/tools/python/airmaps/dags/build_maps.py +++ b/tools/python/airmaps/dags/build_maps.py @@ -101,7 +101,6 @@ class MapsGenerationDAG(DAG): env, ( sd.StageCountriesTxt(), - sd.StageExternalResources(), sd.StageLocalAds(), sd.StageStatistics(), sd.StageCleanup(), diff --git a/tools/python/maps_generator/generator/stages_declaration.py b/tools/python/maps_generator/generator/stages_declaration.py index 671ce2904c..372bfa5f4b 100644 --- a/tools/python/maps_generator/generator/stages_declaration.py +++ b/tools/python/maps_generator/generator/stages_declaration.py @@ -352,29 +352,6 @@ class StageCountriesTxt(Stage): json.dump(countries, f, ensure_ascii=True, indent=1) -@outer_stage -class StageExternalResources(Stage): - def apply(self, env: Env): - black_list = {} - resources = [ - os.path.join(env.paths.user_resource_path, file) - for file in os.listdir(env.paths.user_resource_path) - if file.endswith(".ttf") and file not in black_list - ] - for ttf_file in resources: - shutil.copy2(ttf_file, env.paths.mwm_path) - - for file in os.listdir(env.paths.mwm_path): - if file.startswith(WORLD_NAME) and file.endswith(".mwm"): - resources.append(os.path.join(env.paths.mwm_path, file)) - - resources.sort() - with open(env.paths.external_resources_path, "w") as f: - for resource in resources: - fd = os.open(resource, os.O_RDONLY) - f.write(f"{os.path.basename(resource)} {os.fstat(fd).st_size}\n") - - @outer_stage @production_only class StageLocalAds(Stage): @@ -388,9 +365,7 @@ class StageLocalAds(Stage): ) with tarfile.open(f"{env.paths.localads_path}.tar.gz", "w:gz") as tar: for filename in os.listdir(env.paths.localads_path): - tar.add( - os.path.join(env.paths.localads_path, filename), arcname=filename - ) + tar.add(os.path.join(env.paths.localads_path, filename), arcname=filename) @outer_stage diff --git a/tools/python/maps_generator/maps_generator.py b/tools/python/maps_generator/maps_generator.py index 7fd9656af9..37e12f80ee 100644 --- a/tools/python/maps_generator/maps_generator.py +++ b/tools/python/maps_generator/maps_generator.py @@ -35,7 +35,6 @@ def generate_maps(env: Env, from_stage: Optional[AnyStr] = None): sd.StageDownloadDescriptions(), sd.StageMwm(), sd.StageCountriesTxt(), - sd.StageExternalResources(), sd.StageLocalAds(), sd.StageStatistics(), sd.StageCleanup(), -- 2.45.3 From edc9eef1a6bc195656d884541f3481d84cc816e9 Mon Sep 17 00:00:00 2001 From: dbf Date: Wed, 20 Apr 2022 01:06:36 +0300 Subject: [PATCH 20/21] Add ru-RU translation for Google play/F-droid - code-review fixes Signed-off-by: dbf --- .../play/listings/ru-RU/full-description.txt | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/android/src/fdroid/play/listings/ru-RU/full-description.txt b/android/src/fdroid/play/listings/ru-RU/full-description.txt index 73edf8288b..f007104acb 100644 --- a/android/src/fdroid/play/listings/ru-RU/full-description.txt +++ b/android/src/fdroid/play/listings/ru-RU/full-description.txt @@ -1,51 +1,51 @@ -‣ Наше бесплатное приложение не отслеживает вас и не показывает рекламу. -‣ Оно постоянно улучшается нашей маленькой командой в наше свободное время, на наши собственные деньги и с помощью пожертвований/вклада наших пользователей -‣ Если на карте что-то отсутствует или есть ошибка, то исправьте это в OpenStreetMap и изменение появится в Organic Maps со следующим обновлением -‣ Если поиск или навигатор работают неправильно, пожалуйста, напишите нам. Мы отвечаем на КАЖДОЕ письмо и исправим проблему как можно скорее! +‣ Наше бесплатное приложение не шпионит за пользователями и не показывает рекламу. +‣ Наша небольшая команда энтузиастов вместе с сообществом улучшает Organic Maps в свободное от основной работы время, за свои личные сбережения и пожертвования пользователей. +‣ Если вы нашли ошибки на карте, лучше всего исправить их в OpenStreetMap.org, т.к. все данные в Organic Maps именно оттуда. +‣ Если не работает поиск, навигатор или что-то ещё — пожалуйста, напишите нам. Мы отвечаем на КАЖДОЕ письмо и постараемся исправить проблемы как можно быстрее. -Ваш отзыв и оценка в 5 звёзд — лучшая поддержка для нас! +Лучшая поддержка — это ваш отзыв и оценка в 5 звёзд! Основные функции: • Бесплатно, с открытым исходным кодом, без слежки и рекламы -• Подробные оффлайн карты, во многих местах превосходящие Google maps, созданные сообществом OpenStreetMap -• Маршруты для велосипедистов, туристов и прогулок -• Профили высоты, вершины и склоны -• Turn-by-turn навигатор для прогулок, велосипедов и ЭКСПЕРИМЕНТАЛЬНАЯ навигация для машин с голосовыми подсказками -• Быстрый поиск без использования сети -• Поддержка закладок в формате KML/KMZ (GPX будет скоро добавлен) -• Тёмная тема, чтобы глазам было комфортнее +• Подробные оффлайн карты, созданные сообществом OpenStreetMap и во многих местах превосходящие коммерческие аналоги +• Маршруты для велосипедистов, туристов и пеших прогулок +• Профили высоты, вершины и изолинии +• Экспериментальный turn-by-turn навигатор для пеших прогулок, покатушек на велосипедах и автомобильной навигации с голосовыми подсказками +• Быстрый оффлайновый поиск без использования Интернета +• Поддержка закладок в формате KML/KMZ (GPX добавим) +• Тёмная тема для комфорта -У нас пока нет поддержки Android Auto, общественного транспорта, спутниковых снимков и многих других функций. Но с вашей помощью мы будем улучшать мир шаг за шагом. +У нас пока нет поддержки Android Auto, общественного транспорта, спутниковых снимков и многих других функций. Но с вашей помощью мы шаг за шагом сделаем Organic Maps лучше. -Organic Maps — полностью органические, сделанные с любовью: +Карты Organic Maps сделаны нами с любовью, для себя: • Невероятно быстро работают без использования сети • С уважением относятся к вашей конфиденциальности • Экономят заряд батареи • Без непредвиденных расходов на сотовую связь -• Простые в использовании, в наличие только самое необходимое +• Простые и удобные в использовании, в наличии только самое необходимое -Без отслеживания и подобных недостатков: +Мы гордимся, что Organic Maps: • Без рекламы • Без отслеживания -• Без сбора данных +• Без сбора данных о пользователях • Без передачи данных разработчикам • Без раздражающих регистраций • Без обязательного инструктажа • Без назойливого спама • Без пуш-уведомлений -• Б̶е̶з̶ ̶п̶е̶с̶т̶и̶ц̶и̶д̶о̶в̶ полностью органические +• Б̶е̶з̶ ̶п̶е̶с̶т̶и̶ц̶и̶д̶о̶в̶ полностью органические и натуральные -В Organic Maps мы верим, что конфиденциальность — это право каждого: +Мы считаем, что конфиденциальность — это право каждого: • Organic Maps — это независимый проект с открытым исходным кодом, разрабатываемый сообществом -• Мы защищаем конфиденциальность от корпораций +• Мы обеспечиваем конфиденциальность и защищаем от корпораций • Будьте в безопасности, где бы вы ни были -Отсутствие трекеров и минимальный набор разрешений, согласно Exodus Privacy Report. +Отсутствие трекеров и минимальный набор разрешений подтверждены независимым отчётом Exodus Privacy Report. -Посетите наш сайт organicmaps.app за дополнительной информацией или свяжитесь с нами в канале @OrganicMapsApp в Telegram. +Больше информации ищите на нашем сайте organicmaps.app, или свяжитесь с нами на канале @OrganicMapsApp или @OrganicMapsRu в Telegram. Сопротивляйтесь слежке — отстаивайте вашу свободу. Попробуйте Organic Maps! -- 2.45.3 From 0e0bcf95d1fd3baa1fec84c2e7a7b95e77127adc Mon Sep 17 00:00:00 2001 From: dbf Date: Wed, 20 Apr 2022 01:23:29 +0300 Subject: [PATCH 21/21] Add ru-RU translation for Google play/F-droid Apply suggestions from code review Signed-off-by: dbf --- android/src/fdroid/play/listings/ru-RU/full-description.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/src/fdroid/play/listings/ru-RU/full-description.txt b/android/src/fdroid/play/listings/ru-RU/full-description.txt index f007104acb..86745ce054 100644 --- a/android/src/fdroid/play/listings/ru-RU/full-description.txt +++ b/android/src/fdroid/play/listings/ru-RU/full-description.txt @@ -1,5 +1,5 @@ ‣ Наше бесплатное приложение не шпионит за пользователями и не показывает рекламу. -‣ Наша небольшая команда энтузиастов вместе с сообществом улучшает Organic Maps в свободное от основной работы время, за свои личные сбережения и пожертвования пользователей. +‣ Наша небольшая команда энтузиастов вместе с сообществом улучшает Organic Maps в свободное от основной работы время, на свои личные сбережения и пожертвования пользователей. ‣ Если вы нашли ошибки на карте, лучше всего исправить их в OpenStreetMap.org, т.к. все данные в Organic Maps именно оттуда. ‣ Если не работает поиск, навигатор или что-то ещё — пожалуйста, напишите нам. Мы отвечаем на КАЖДОЕ письмо и постараемся исправить проблемы как можно быстрее. -- 2.45.3