Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Framework.cpp « maps « mapswithme « com « jni « android - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 76d8697d75991a7cdceb995cda0e03a75999ded8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
#include "com/mapswithme/maps/Framework.hpp"
#include "com/mapswithme/core/jni_helper.hpp"
#include "com/mapswithme/maps/UserMarkHelper.hpp"
#include "com/mapswithme/opengl/androidoglcontextfactory.hpp"
#include "com/mapswithme/platform/Platform.hpp"
#include "com/mapswithme/util/NetworkPolicy.hpp"
#include "com/mapswithme/vulkan/android_vulkan_context_factory.hpp"

#include "map/chart_generator.hpp"
#include "map/everywhere_search_params.hpp"
#include "map/notifications/notification_queue.hpp"
#include "map/user_mark.hpp"
#include "map/purchase.hpp"

#include "partners_api/ads_engine.hpp"
#include "partners_api/banner.hpp"
#include "partners_api/booking_block_params.hpp"
#include "partners_api/downloader_promo.hpp"
#include "partners_api/mopub_ads.hpp"
#include "partners_api/megafon_countries.hpp"

#include "web_api/utils.hpp"

#include "storage/storage_defines.hpp"
#include "storage/storage_helpers.hpp"

#include "drape_frontend/user_event_stream.hpp"
#include "drape_frontend/visual_params.hpp"

#include "drape/pointers.hpp"
#include "drape/support_manager.hpp"
#include "drape/visual_scale.hpp"

#include "coding/files_container.hpp"

#include "geometry/angles.hpp"
#include "geometry/mercator.hpp"

#include "indexer/feature_altitude.hpp"

#include "routing/following_info.hpp"
#include "routing/speed_camera_manager.hpp"

#include "platform/country_file.hpp"
#include "platform/local_country_file.hpp"
#include "platform/local_country_file_utils.hpp"
#include "platform/location.hpp"
#include "platform/measurement_utils.hpp"
#include "platform/network_policy.hpp"
#include "platform/platform.hpp"
#include "platform/preferred_languages.hpp"
#include "platform/settings.hpp"

#include "base/assert.hpp"
#include "base/file_name_utils.hpp"
#include "base/logging.hpp"
#include "base/math.hpp"
#include "base/sunrise_sunset.hpp"

#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>

using namespace std;
using namespace std::placeholders;
using namespace notifications;

unique_ptr<android::Framework> g_framework;

namespace platform
{
NetworkPolicy ToNativeNetworkPolicy(JNIEnv * env, jobject obj)
{
  return NetworkPolicy(network_policy::GetNetworkPolicyStatus(env, obj));
}
}  // namespace platform

using namespace storage;
using platform::CountryFile;
using platform::LocalCountryFile;
using platform::ToNativeNetworkPolicy;

static_assert(sizeof(int) >= 4, "Size of jint in less than 4 bytes.");

namespace
{
::Framework * frm()
{
  return g_framework->NativeFramework();
}

jobject g_mapObjectListener = nullptr;
int const kUndefinedTip = -1;

android::AndroidVulkanContextFactory * CastFactory(drape_ptr<dp::GraphicsContextFactory> const & f)
{
  ASSERT(dynamic_cast<android::AndroidVulkanContextFactory *>(f.get()) != nullptr, ());
  return static_cast<android::AndroidVulkanContextFactory *>(f.get());
}
}  // namespace

namespace android
{

enum MultiTouchAction
{
  MULTITOUCH_UP    =   0x00000001,
  MULTITOUCH_DOWN  =   0x00000002,
  MULTITOUCH_MOVE  =   0x00000003,
  MULTITOUCH_CANCEL =  0x00000004
};

Framework::Framework()
  : m_lastCompass(0.0)
  , m_isSurfaceDestroyed(false)
  , m_currentMode(location::PendingPosition)
  , m_isCurrentModeInitialized(false)
  , m_isChoosePositionMode(false)
{
  m_work.GetTrafficManager().SetStateListener(bind(&Framework::TrafficStateChanged, this, _1));
  m_work.GetTransitManager().SetStateListener(bind(&Framework::TransitSchemeStateChanged, this, _1));
  m_work.GetIsolinesManager().SetStateListener(bind(&Framework::IsolinesSchemeStateChanged, this, _1));
  m_work.GetPowerManager().Subscribe(this);
}

void Framework::OnLocationError(int errorCode)
{
  m_work.OnLocationError(static_cast<location::TLocationError>(errorCode));
}

void Framework::OnLocationUpdated(location::GpsInfo const & info)
{
  ASSERT(IsDrapeEngineCreated(), ());
  m_work.OnLocationUpdate(info);
}

void Framework::OnCompassUpdated(location::CompassInfo const & info, bool forceRedraw)
{
  static double const COMPASS_THRESHOLD = base::DegToRad(1.0);

  /// @todo Do not emit compass bearing too often.
  /// Need to make more experiments in future.
  if (forceRedraw || fabs(ang::GetShortestDistance(m_lastCompass, info.m_bearing)) >= COMPASS_THRESHOLD)
  {
    m_lastCompass = info.m_bearing;
    m_work.OnCompassUpdate(info);
  }
}

void Framework::UpdateCompassSensor(int ind, float * arr)
{
  m_sensors[ind].Next(arr);
}

void Framework::MyPositionModeChanged(location::EMyPositionMode mode, bool routingActive)
{
  if (m_myPositionModeSignal)
    m_myPositionModeSignal(mode, routingActive);
}

void Framework::TrafficStateChanged(TrafficManager::TrafficState state)
{
  if (m_onTrafficStateChangedFn)
    m_onTrafficStateChangedFn(state);
}

void Framework::TransitSchemeStateChanged(TransitReadManager::TransitSchemeState state)
{
  if (m_onTransitStateChangedFn)
    m_onTransitStateChangedFn(state);
}

void Framework::IsolinesSchemeStateChanged(IsolinesManager::IsolinesState state)
{
  if (m_onIsolinesStateChangedFn)
    m_onIsolinesStateChangedFn(state);
}

bool Framework::DestroySurfaceOnDetach()
{
  if (m_vulkanContextFactory)
    return false;
  return true;
}

bool Framework::CreateDrapeEngine(JNIEnv * env, jobject jSurface, int densityDpi, bool firstLaunch,
                                  bool launchByDeepLink, int appVersionCode)
{
  // Vulkan is supported only since Android 8.0, because some Android devices with Android 7.x
  // have fatal driver issue, which can lead to process termination and whole OS destabilization.
  int constexpr kMinSdkVersionForVulkan = 26;
  // Ban Vulkan temporarily for Android 10.0 because of unfixed rendering artifacts.
  int constexpr kMaxSdkVersionForVulkan = 28;
  int const sdkVersion = GetAndroidSdkVersion();
  auto const vulkanForbidden = sdkVersion < kMinSdkVersionForVulkan ||
                               sdkVersion > kMaxSdkVersionForVulkan ||
                               dp::SupportManager::Instance().IsVulkanForbidden();
  if (vulkanForbidden)
    LOG(LWARNING, ("Vulkan API is forbidden on this device."));

  if (m_work.LoadPreferredGraphicsAPI() == dp::ApiVersion::Vulkan && !vulkanForbidden)
  {
    m_vulkanContextFactory = make_unique_dp<AndroidVulkanContextFactory>(appVersionCode);
    if (!CastFactory(m_vulkanContextFactory)->IsVulkanSupported())
    {
      LOG(LWARNING, ("Vulkan API is not supported."));
      m_vulkanContextFactory.reset();
    }

    if (m_vulkanContextFactory)
    {
      auto f = CastFactory(m_vulkanContextFactory);
      f->SetSurface(env, jSurface);
      if (!f->IsValid())
      {
        LOG(LWARNING, ("Invalid Vulkan API context."));
        m_vulkanContextFactory.reset();
      }
    }
  }

  AndroidOGLContextFactory * oglFactory = nullptr;
  if (!m_vulkanContextFactory)
  {
    m_oglContextFactory = make_unique_dp<dp::ThreadSafeFactory>(
      new AndroidOGLContextFactory(env, jSurface));
    oglFactory = m_oglContextFactory->CastFactory<AndroidOGLContextFactory>();
    if (!oglFactory->IsValid())
    {
      LOG(LWARNING, ("Invalid GL context."));
      return false;
    }
  }

  ::Framework::DrapeCreationParams p;
  if (m_vulkanContextFactory)
  {
    auto f = CastFactory(m_vulkanContextFactory);
    p.m_apiVersion = dp::ApiVersion::Vulkan;
    p.m_surfaceWidth = f->GetWidth();
    p.m_surfaceHeight = f->GetHeight();
  }
  else
  {
    CHECK(oglFactory != nullptr, ());
    p.m_apiVersion = oglFactory->IsSupportedOpenGLES3() ? dp::ApiVersion::OpenGLES3 :
                                                          dp::ApiVersion::OpenGLES2;
    p.m_surfaceWidth = oglFactory->GetWidth();
    p.m_surfaceHeight = oglFactory->GetHeight();
  }
  p.m_visualScale = static_cast<float>(dp::VisualScale(densityDpi));
  p.m_hasMyPositionState = m_isCurrentModeInitialized;
  p.m_initialMyPositionState = m_currentMode;
  p.m_isChoosePositionMode = m_isChoosePositionMode;
  p.m_hints.m_isFirstLaunch = firstLaunch;
  p.m_hints.m_isLaunchByDeepLink = launchByDeepLink;
  ASSERT(!m_guiPositions.empty(), ("GUI elements must be set-up before engine is created"));
  p.m_widgetsInitInfo = m_guiPositions;

  m_work.SetMyPositionModeListener(bind(&Framework::MyPositionModeChanged, this, _1, _2));

  if (m_vulkanContextFactory)
    m_work.CreateDrapeEngine(make_ref(m_vulkanContextFactory), move(p));
  else
    m_work.CreateDrapeEngine(make_ref(m_oglContextFactory), move(p));
  m_work.EnterForeground();

  return true;
}

bool Framework::IsDrapeEngineCreated()
{
  return m_work.IsDrapeEngineCreated();
}

void Framework::Resize(JNIEnv * env, jobject jSurface, int w, int h)
{
  if (m_vulkanContextFactory)
  {
    auto vulkanContextFactory = CastFactory(m_vulkanContextFactory);
    if (vulkanContextFactory->GetWidth() != w || vulkanContextFactory->GetHeight() != h)
    {
      m_vulkanContextFactory->SetPresentAvailable(false);
      m_work.SetRenderingDisabled(false /* destroySurface */);

      vulkanContextFactory->ChangeSurface(env, jSurface, w, h);

      vulkanContextFactory->SetPresentAvailable(true);
      m_work.SetRenderingEnabled();
    }
  }
  else
  {
    m_oglContextFactory->CastFactory<AndroidOGLContextFactory>()->UpdateSurfaceSize(w, h);
  }
  m_work.OnSize(w, h);

  //TODO: remove after correct visible rect calculation.
  frm()->SetVisibleViewport(m2::RectD(0, 0, w, h));
}

void Framework::DetachSurface(bool destroySurface)
{
  LOG(LINFO, ("Detach surface started. destroySurface =", destroySurface));
  if (m_vulkanContextFactory)
  {
    m_vulkanContextFactory->SetPresentAvailable(false);
  }
  else
  {
    ASSERT(m_oglContextFactory != nullptr, ());
    m_oglContextFactory->SetPresentAvailable(false);
  }

  if (destroySurface)
  {
    LOG(LINFO, ("Destroy surface."));
    m_isSurfaceDestroyed = true;
    m_work.OnDestroySurface();
  }

  if (m_vulkanContextFactory)
  {
    // With Vulkan we don't need to recreate all graphics resources,
    // we have to destroy only resources bound with surface (swapchains,
    // image views, framebuffers and command buffers). All these resources will be
    // destroyed in ResetSurface().
    m_work.SetRenderingDisabled(false /* destroySurface */);

    // Allow pipeline dump only on enter background.
    CastFactory(m_vulkanContextFactory)->ResetSurface(destroySurface /* allowPipelineDump */);
  }
  else
  {
    m_work.SetRenderingDisabled(destroySurface);
    auto factory = m_oglContextFactory->CastFactory<AndroidOGLContextFactory>();
    factory->ResetSurface();
  }
  LOG(LINFO, ("Detach surface finished."));
}

bool Framework::AttachSurface(JNIEnv * env, jobject jSurface)
{
  LOG(LINFO, ("Attach surface started."));

  int w = 0, h = 0;
  if (m_vulkanContextFactory)
  {
    auto factory = CastFactory(m_vulkanContextFactory);
    factory->SetSurface(env, jSurface);
    if (!factory->IsValid())
    {
      LOG(LWARNING, ("Invalid Vulkan API context."));
      return false;
    }
    w = factory->GetWidth();
    h = factory->GetHeight();
  }
  else
  {
    ASSERT(m_oglContextFactory != nullptr, ());
    auto factory = m_oglContextFactory->CastFactory<AndroidOGLContextFactory>();
    factory->SetSurface(env, jSurface);
    if (!factory->IsValid())
    {
      LOG(LWARNING, ("Invalid GL context."));
      return false;
    }
    w = factory->GetWidth();
    h = factory->GetHeight();
  }

  ASSERT(!m_guiPositions.empty(), ("GUI elements must be set-up before engine is created"));

  if (m_vulkanContextFactory)
  {
    m_vulkanContextFactory->SetPresentAvailable(true);
    m_work.SetRenderingEnabled();
  }
  else
  {
    m_oglContextFactory->SetPresentAvailable(true);
    m_work.SetRenderingEnabled(make_ref(m_oglContextFactory));
  }

  if (m_isSurfaceDestroyed)
  {
    LOG(LINFO, ("Recover surface, viewport size:", w, h));
    bool const recreateContextDependentResources = (m_vulkanContextFactory == nullptr);
    m_work.OnRecoverSurface(w, h, recreateContextDependentResources);
    m_isSurfaceDestroyed = false;
  }

  LOG(LINFO, ("Attach surface finished."));

  return true;
}

void Framework::PauseSurfaceRendering()
{
  if (m_vulkanContextFactory)
    m_vulkanContextFactory->SetPresentAvailable(false);
  if (m_oglContextFactory)
    m_oglContextFactory->SetPresentAvailable(false);

  LOG(LINFO, ("Pause surface rendering."));
}

void Framework::ResumeSurfaceRendering()
{
  if (m_vulkanContextFactory)
  {
    if (CastFactory(m_vulkanContextFactory)->IsValid())
      m_vulkanContextFactory->SetPresentAvailable(true);
  }
  if (m_oglContextFactory)
  {
    AndroidOGLContextFactory * factory = m_oglContextFactory->CastFactory<AndroidOGLContextFactory>();
    if (factory->IsValid())
      factory->SetPresentAvailable(true);
  }
  LOG(LINFO, ("Resume surface rendering."));
}

void Framework::SetMapStyle(MapStyle mapStyle)
{
  m_work.SetMapStyle(mapStyle);
}

void Framework::MarkMapStyle(MapStyle mapStyle)
{
  // In case of Vulkan rendering we don't recreate geometry and textures data, so
  // we need use SetMapStyle instead of MarkMapStyle in all cases.
  if (m_vulkanContextFactory)
    m_work.SetMapStyle(mapStyle);
  else
    m_work.MarkMapStyle(mapStyle);
}

MapStyle Framework::GetMapStyle() const
{
  return m_work.GetMapStyle();
}

void Framework::Save3dMode(bool allow3d, bool allow3dBuildings)
{
  m_work.Save3dMode(allow3d, allow3dBuildings);
}

void Framework::Set3dMode(bool allow3d, bool allow3dBuildings)
{
  m_work.Allow3dMode(allow3d, allow3dBuildings);
}

void Framework::Get3dMode(bool & allow3d, bool & allow3dBuildings)
{
  m_work.Load3dMode(allow3d, allow3dBuildings);
}

void Framework::SetChoosePositionMode(bool isChoosePositionMode, bool isBusiness,
                                      bool hasPosition, m2::PointD const & position)
{
  m_isChoosePositionMode = isChoosePositionMode;
  m_work.BlockTapEvents(isChoosePositionMode);
  m_work.EnableChoosePositionMode(isChoosePositionMode, isBusiness, hasPosition, position);
}

bool Framework::GetChoosePositionMode()
{
  return m_isChoosePositionMode;
}

Storage & Framework::GetStorage()
{
  return m_work.GetStorage();
}

DataSource const & Framework::GetDataSource() { return m_work.GetDataSource(); }

void Framework::ShowNode(CountryId const & idx, bool zoomToDownloadButton)
{
  if (zoomToDownloadButton)
  {
    m2::RectD const rect = CalcLimitRect(idx, m_work.GetStorage(), m_work.GetCountryInfoGetter());
    m_work.SetViewportCenter(rect.Center(), 10);
  }
  else
  {
    m_work.ShowNode(idx);
  }
}

void Framework::Touch(int action, Finger const & f1, Finger const & f2, uint8_t maskedPointer)
{
  MultiTouchAction eventType = static_cast<MultiTouchAction>(action);
  df::TouchEvent event;

  switch(eventType)
  {
  case MULTITOUCH_DOWN:
    event.SetTouchType(df::TouchEvent::TOUCH_DOWN);
    break;
  case MULTITOUCH_MOVE:
    event.SetTouchType(df::TouchEvent::TOUCH_MOVE);
    break;
  case MULTITOUCH_UP:
    event.SetTouchType(df::TouchEvent::TOUCH_UP);
    break;
  case MULTITOUCH_CANCEL:
    event.SetTouchType(df::TouchEvent::TOUCH_CANCEL);
    break;
  default:
    return;
  }

  df::Touch touch;
  touch.m_location = m2::PointD(f1.m_x, f1.m_y);
  touch.m_id = f1.m_id;
  event.SetFirstTouch(touch);

  touch.m_location = m2::PointD(f2.m_x, f2.m_y);
  touch.m_id = f2.m_id;
  event.SetSecondTouch(touch);

  event.SetFirstMaskedPointer(maskedPointer);
  m_work.TouchEvent(event);
}

m2::PointD Framework::GetViewportCenter() const
{
  return m_work.GetViewportCenter();
}

void Framework::AddString(string const & name, string const & value)
{
  m_work.AddString(name, value);
}

void Framework::Scale(::Framework::EScaleMode mode)
{
  m_work.Scale(mode, true);
}

void Framework::Scale(m2::PointD const & centerPt, int targetZoom, bool animate)
{
  ref_ptr<df::DrapeEngine> engine = m_work.GetDrapeEngine();
  if (engine)
    engine->SetModelViewCenter(centerPt, targetZoom, animate, false);
}

::Framework * Framework::NativeFramework()
{
  return &m_work;
}

bool Framework::Search(search::EverywhereSearchParams const & params)
{
  m_searchQuery = params.m_query;
  return m_work.SearchEverywhere(params);
}

void Framework::AddLocalMaps()
{
  m_work.RegisterAllMaps();
}

void Framework::RemoveLocalMaps()
{
  m_work.DeregisterAllMaps();
}

void Framework::ReplaceBookmark(kml::MarkId markId, kml::BookmarkData & bm)
{
  m_work.GetBookmarkManager().GetEditSession().UpdateBookmark(markId, bm);
}

void Framework::MoveBookmark(kml::MarkId markId, kml::MarkGroupId curCat, kml::MarkGroupId newCat)
{
  m_work.GetBookmarkManager().GetEditSession().MoveBookmark(markId, curCat, newCat);
}

bool Framework::ShowMapForURL(string const & url)
{
  return m_work.ShowMapForURL(url);
}

void Framework::DeactivatePopup()
{
  m_work.DeactivateMapSelection(false);
}

string Framework::GetOutdatedCountriesString()
{
  vector<Country const *> countries;
  class Storage const & storage = GetStorage();
  storage.GetOutdatedCountries(countries);

  string res;
  NodeAttrs attrs;

  for (size_t i = 0; i < countries.size(); ++i)
  {
    storage.GetNodeAttrs(countries[i]->Name(), attrs);

    if (i > 0)
      res += ", ";

    res += attrs.m_nodeLocalName;
  }

  return res;
}

void Framework::SetTrafficStateListener(TrafficManager::TrafficStateChangedFn const & fn)
{
  m_onTrafficStateChangedFn = fn;
}

void Framework::SetTransitSchemeListener(TransitReadManager::TransitStateChangedFn const & function)
{
  m_onTransitStateChangedFn = function;
}

void Framework::SetIsolinesListener(IsolinesManager::IsolinesStateChangedFn const & function)
{
  m_onIsolinesStateChangedFn = function;
}

bool Framework::IsTrafficEnabled()
{
  return m_work.GetTrafficManager().IsEnabled();
}

void Framework::EnableTraffic()
{
  m_work.GetTrafficManager().SetEnabled(true);
  NativeFramework()->SaveTrafficEnabled(true);
}

void Framework::DisableTraffic()
{
  m_work.GetTrafficManager().SetEnabled(false);
  NativeFramework()->SaveTrafficEnabled(false);
}

void Framework::SetMyPositionModeListener(location::TMyPositionModeChanged const & fn)
{
  m_myPositionModeSignal = fn;
}

location::EMyPositionMode Framework::GetMyPositionMode()
{
  if (!m_isCurrentModeInitialized)
  {
    if (!settings::Get(settings::kLocationStateMode, m_currentMode))
      m_currentMode = location::NotFollowNoPosition;

    m_isCurrentModeInitialized = true;
  }

  return m_currentMode;
}

void Framework::OnMyPositionModeChanged(location::EMyPositionMode mode)
{
  m_currentMode = mode;
  m_isCurrentModeInitialized = true;
}

void Framework::SwitchMyPositionNextMode()
{
  ASSERT(IsDrapeEngineCreated(), ());
  m_work.SwitchMyPositionNextMode();
}

void Framework::SetupWidget(gui::EWidget widget, float x, float y, dp::Anchor anchor)
{
  m_guiPositions[widget] = gui::Position(m2::PointF(x, y), anchor);
}

void Framework::ApplyWidgets()
{
  gui::TWidgetsLayoutInfo layout;
  for (auto const & widget : m_guiPositions)
    layout[widget.first] = widget.second.m_pixelPivot;

  m_work.SetWidgetLayout(move(layout));
}

void Framework::CleanWidgets()
{
  m_guiPositions.clear();
}

void Framework::SetupMeasurementSystem()
{
  m_work.SetupMeasurementSystem();
}

place_page::Info & Framework::GetPlacePageInfo()
{
  return m_work.GetCurrentPlacePageInfo();
}

void Framework::RequestBookingMinPrice(JNIEnv * env, jobject policy,
                                       booking::BlockParams && params,
                                       booking::BlockAvailabilityCallback const & callback)
{
  auto const bookingApi = m_work.GetBookingApi(ToNativeNetworkPolicy(env, policy));
  if (bookingApi)
    bookingApi->GetBlockAvailability(move(params), callback);
}

void Framework::RequestBookingInfo(JNIEnv * env, jobject policy,
                                   string const & hotelId, string const & lang,
                                   booking::GetHotelInfoCallback const & callback)
{
  auto const bookingApi = m_work.GetBookingApi(ToNativeNetworkPolicy(env, policy));
  if (bookingApi)
    bookingApi->GetHotelInfo(hotelId, lang, callback);
}

bool Framework::IsAutoRetryDownloadFailed()
{
  return m_work.GetDownloadingPolicy().IsAutoRetryDownloadFailed();
}

bool Framework::IsDownloadOn3gEnabled()
{
  return m_work.GetDownloadingPolicy().IsCellularDownloadEnabled();
}

void Framework::EnableDownloadOn3g()
{
  m_work.GetDownloadingPolicy().EnableCellularDownload(true);
}

void Framework::DisableAdProvider(ads::Banner::Type const type, ads::Banner::Place const place)
{
  m_work.DisableAdProvider(type, place);
}

uint64_t Framework::RequestTaxiProducts(JNIEnv * env, jobject policy, ms::LatLon const & from,
                                        ms::LatLon const & to,
                                        taxi::SuccessCallback const & onSuccess,
                                        taxi::ErrorCallback const & onError)
{
  auto const taxiEngine = m_work.GetTaxiEngine(ToNativeNetworkPolicy(env, policy));
  if (!taxiEngine)
    return 0;

  return taxiEngine->GetAvailableProducts(from, to, onSuccess, onError);
}

taxi::RideRequestLinks Framework::GetTaxiLinks(JNIEnv * env, jobject policy, taxi::Provider::Type type,
                                               string const & productId, ms::LatLon const & from,
                                               ms::LatLon const & to)
{
  auto const taxiEngine = m_work.GetTaxiEngine(ToNativeNetworkPolicy(env, policy));
  if (!taxiEngine)
    return {};

  return taxiEngine->GetRideRequestLinks(type, productId, from, to);
}

void Framework::RequestUGC(FeatureID const & fid, ugc::Api::UGCCallback const & ugcCallback)
{
  m_work.GetUGC(fid, ugcCallback);
}

void Framework::SetUGCUpdate(FeatureID const & fid, ugc::UGCUpdate const & ugc,
                             ugc::Api::OnResultCallback const & callback /*  = nullptr */)
{
  m_work.GetUGCApi()->SetUGCUpdate(fid, ugc, callback);
}

void Framework::UploadUGC()
{
  m_work.UploadUGC(nullptr /* onCompleteUploading */);
}

int Framework::ToDoAfterUpdate() const
{
  return (int) m_work.ToDoAfterUpdate();
}

uint64_t Framework::GetLocals(JNIEnv * env, jobject policy, double lat, double lon,
                              locals::LocalsSuccessCallback const & successFn,
                              locals::LocalsErrorCallback const & errorFn)
{
  auto api = NativeFramework()->GetLocalsApi(ToNativeNetworkPolicy(env, policy));
  if (api == nullptr)
    return 0;

  std::string const langStr = languages::GetCurrentNorm();
  size_t constexpr kResultsOnPage = 5;
  size_t constexpr kPageNumber = 1;
  return api->GetLocals(lat, lon, langStr, kResultsOnPage, kPageNumber, successFn, errorFn);
}

void Framework::GetPromoCityGallery(JNIEnv * env, jobject policy,
                                    m2::PointD const & point, UTM utm,
                                    promo::CityGalleryCallback const & onSuccess,
                                    promo::OnError const & onError)
{
  auto api = NativeFramework()->GetPromoApi(ToNativeNetworkPolicy(env, policy));
  if (api == nullptr)
  {
    onError();
    return;
  }

  api->GetCityGallery(point, languages::GetCurrentNorm(), utm, onSuccess, onError);
}

void Framework::GetPromoPoiGallery(JNIEnv * env, jobject policy,
                                   m2::PointD const & point, promo::Tags const & tags,
                                   bool useCoordinates, UTM utm,
                                   promo::CityGalleryCallback const & onSuccess,
                                   promo::OnError const & onError)
{
  auto api = NativeFramework()->GetPromoApi(ToNativeNetworkPolicy(env, policy));
  if (api == nullptr)
  {
    onError();
    return;
  }

  api->GetPoiGallery(point, languages::GetCurrentNorm(), tags, useCoordinates, utm, onSuccess,
                     onError);
}

promo::AfterBooking Framework::GetPromoAfterBooking(JNIEnv * env, jobject policy)
{
  auto api = NativeFramework()->GetPromoApi(ToNativeNetworkPolicy(env, policy));
  if (api == nullptr)
    return {};

  return api->GetAfterBooking(languages::GetCurrentNorm());
}

std::string Framework::GetPromoCityUrl(JNIEnv * env, jobject policy, jdouble lat, jdouble lon)
{
  auto api = NativeFramework()->GetPromoApi(ToNativeNetworkPolicy(env, policy));
  if (api == nullptr)
    return {};
  auto const point = mercator::FromLatLon(static_cast<double>(lat), static_cast<double>(lon));
  return api->GetCityUrl(point);
}

void Framework::LogLocalAdsEvent(local_ads::EventType type, double lat, double lon, uint16_t accuracy)
{
  ::Framework * frm = g_framework->NativeFramework();
  if (!frm->HasPlacePageInfo())
    return;

  auto const & info = g_framework->GetPlacePageInfo();
  auto const & featureID = info.GetID();
  auto const & mwmInfo = featureID.m_mwmId.GetInfo();
  if (!mwmInfo)
    return;

  local_ads::Event event(type, mwmInfo->GetVersion(), mwmInfo->GetCountryName(), featureID.m_index,
                         m_work.GetDrawScale(), local_ads::Clock::now(), lat, lon, accuracy);
  m_work.GetLocalAdsManager().GetStatistics().RegisterEvent(std::move(event));
}

void Framework::OnPowerFacilityChanged(power_management::Facility const facility, bool enabled)
{
  // Dummy
  // TODO: provide information for UI Properties.
}

void Framework::OnPowerSchemeChanged(power_management::Scheme const actualScheme)
{
  // Dummy
  // TODO: provide information for UI Properties.
}
}  // namespace android

//============ GLUE CODE for com.mapswithme.maps.Framework class =============//
/*            ____
 *          _ |||| _
 *          \\    //
 *           \\  //
 *            \\//
 *             \/
 */

extern "C"
{
void CallRoutingListener(shared_ptr<jobject> listener, int errorCode,
                         storage::CountriesSet const & absentMaps)
{
  JNIEnv * env = jni::GetEnv();
  jmethodID const method = jni::GetMethodID(env, *listener, "onRoutingEvent", "(I[Ljava/lang/String;)V");
  ASSERT(method, ());

  env->CallVoidMethod(*listener, method, errorCode, jni::TScopedLocalObjectArrayRef(env, jni::ToJavaStringArray(env, absentMaps)).get());
}

void CallRouteProgressListener(shared_ptr<jobject> listener, float progress)
{
  JNIEnv * env = jni::GetEnv();
  jmethodID const methodId = jni::GetMethodID(env, *listener, "onRouteBuildingProgress", "(F)V");
  env->CallVoidMethod(*listener, methodId, progress);
}

void CallRouteRecommendationListener(shared_ptr<jobject> listener,
                                     RoutingManager::Recommendation recommendation)
{
  JNIEnv * env = jni::GetEnv();
  jmethodID const methodId = jni::GetMethodID(env, *listener, "onRecommend", "(I)V");
  env->CallVoidMethod(*listener, methodId, static_cast<int>(recommendation));
}

void CallSetRoutingLoadPointsListener(shared_ptr<jobject> listener, bool success)
{
  JNIEnv * env = jni::GetEnv();
  jmethodID const methodId = jni::GetMethodID(env, *listener, "onRoutePointsLoaded", "(Z)V");
  env->CallVoidMethod(*listener, methodId, static_cast<jboolean>(success));
}

RoutingManager::LoadRouteHandler g_loadRouteHandler;

void CallPurchaseValidationListener(shared_ptr<jobject> listener, Purchase::ValidationCode code,
                                    Purchase::ValidationInfo const & validationInfo)
{
  JNIEnv * env = jni::GetEnv();
  jmethodID const methodId = jni::GetMethodID(env, *listener, "onValidatePurchase",
    "(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");

  jni::TScopedLocalRef const serverId(env, jni::ToJavaString(env, validationInfo.m_serverId));
  jni::TScopedLocalRef const vendorId(env, jni::ToJavaString(env, validationInfo.m_vendorId));
  jni::TScopedLocalRef const receiptData(env, jni::ToJavaString(env, validationInfo.m_receiptData));

  env->CallVoidMethod(*listener, methodId, static_cast<jint>(code), serverId.get(), vendorId.get(),
                      receiptData.get());
}

void CallStartPurchaseTransactionListener(shared_ptr<jobject> listener, bool success,
                                          std::string const & serverId,
                                          std::string const & vendorId)
{
  JNIEnv * env = jni::GetEnv();
  jmethodID const methodId = jni::GetMethodID(env, *listener, "onStartTransaction",
                                              "(ZLjava/lang/String;Ljava/lang/String;)V");

  jni::TScopedLocalRef const serverIdStr(env, jni::ToJavaString(env, serverId));
  jni::TScopedLocalRef const vendorIdStr(env, jni::ToJavaString(env, vendorId));

  env->CallVoidMethod(*listener, methodId, static_cast<jboolean>(success),
                      serverIdStr.get(), vendorIdStr.get());
}

/// @name JNI EXPORTS
JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeGetAddress(JNIEnv * env, jclass clazz, jdouble lat, jdouble lon)
{
  auto const info = frm()->GetAddressAtPoint(mercator::FromLatLon(lat, lon));
  return jni::ToJavaString(env, info.FormatAddress());
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeClearApiPoints(JNIEnv * env, jclass clazz)
{
  frm()->GetBookmarkManager().GetEditSession().ClearGroup(UserMark::Type::API);
}

JNIEXPORT jint JNICALL
Java_com_mapswithme_maps_Framework_nativeParseAndSetApiUrl(JNIEnv * env, jclass clazz, jstring url)
{
  return static_cast<jint>(frm()->ParseAndSetApiURL(jni::ToNativeString(env, url)));
}

JNIEXPORT jobject JNICALL
Java_com_mapswithme_maps_Framework_nativeGetParsedRoutingData(JNIEnv * env, jclass clazz)
{
  using namespace url_scheme;
  static jclass const pointClazz = jni::GetGlobalClassRef(env, "com/mapswithme/maps/api/RoutePoint");
  // Java signature : RoutePoint(double lat, double lon, String name)
  static jmethodID const pointConstructor = jni::GetConstructorID(env, pointClazz, "(DDLjava/lang/String;)V");

  static jclass const routeDataClazz = jni::GetGlobalClassRef(env, "com/mapswithme/maps/api/ParsedRoutingData");
  // Java signature : ParsedRoutingData(RoutePoint[] points, int routerType) {
  static jmethodID const routeDataConstructor = jni::GetConstructorID(env, routeDataClazz, "([Lcom/mapswithme/maps/api/RoutePoint;I)V");

  auto const & routingData = frm()->GetParsedRoutingData();
  jobjectArray points = jni::ToJavaArray(env, pointClazz, routingData.m_points,
                                         [](JNIEnv * env, RoutePoint const & point)
                                         {
                                           jni::TScopedLocalRef const name(env, jni::ToJavaString(env, point.m_name));
                                           return env->NewObject(pointClazz, pointConstructor,
                                                                 mercator::YToLat(point.m_org.y),
                                                                 mercator::XToLon(point.m_org.x), name.get());
                                         });

  return env->NewObject(routeDataClazz, routeDataConstructor, points, routingData.m_type);
}

JNIEXPORT jobject JNICALL
Java_com_mapswithme_maps_Framework_nativeGetParsedSearchRequest(JNIEnv * env, jclass clazz)
{
  using namespace url_scheme;
  static jclass const cl = jni::GetGlobalClassRef(env, "com/mapswithme/maps/api/ParsedSearchRequest");
  // Java signature : ParsedSearchRequest(String query, String locale, double lat, double lon, boolean isSearchOnMap)
  static jmethodID const ctor = jni::GetConstructorID(env, cl, "(Ljava/lang/String;Ljava/lang/String;DDZ)V");
  auto const & r = frm()->GetParsedSearchRequest();
  return env->NewObject(cl, ctor, jni::ToJavaString(env, r.m_query), jni::ToJavaString(env, r.m_locale), r.m_centerLat, r.m_centerLon, r.m_isSearchOnMap);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetMapObjectListener(JNIEnv * env, jclass clazz, jobject jListener)
{
  LOG(LINFO, ("Set global map object listener"));
  g_mapObjectListener = env->NewGlobalRef(jListener);
  // void onMapObjectActivated(MapObject object);
  jmethodID const activatedId = jni::GetMethodID(env, g_mapObjectListener, "onMapObjectActivated",
                                                 "(Lcom/mapswithme/maps/bookmarks/data/MapObject;)V");
  // void onDismiss(boolean switchFullScreenMode);
  jmethodID const dismissId = jni::GetMethodID(env, g_mapObjectListener, "onDismiss", "(Z)V");
  auto const fillPlacePage = [activatedId]()
  {
    JNIEnv * env = jni::GetEnv();
    auto const & info = frm()->GetCurrentPlacePageInfo();
    jni::TScopedLocalRef mapObject(env, usermark_helper::CreateMapObject(env, info));
    env->CallVoidMethod(g_mapObjectListener, activatedId, mapObject.get());
  };
  auto const closePlacePage = [dismissId](bool switchFullScreenMode)
  {
    JNIEnv * env = jni::GetEnv();
    env->CallVoidMethod(g_mapObjectListener, dismissId, switchFullScreenMode);
  };
  frm()->SetPlacePageListeners(fillPlacePage, closePlacePage, fillPlacePage);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeRemoveMapObjectListener(JNIEnv * env, jclass)
{
  if (g_mapObjectListener == nullptr)
    return;

  frm()->SetPlacePageListeners({} /* onOpen */, {} /* onClose */, {} /* onUpdate */);
  LOG(LINFO, ("Remove global map object listener"));
  env->DeleteGlobalRef(g_mapObjectListener);
  g_mapObjectListener = nullptr;
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeGetGe0Url(JNIEnv * env, jclass, jdouble lat, jdouble lon, jdouble zoomLevel, jstring name)
{
  ::Framework * fr = frm();
  double const scale = (zoomLevel > 0 ? zoomLevel : fr->GetDrawScale());
  string const url = fr->CodeGe0url(lat, lon, scale, jni::ToNativeString(env, name));
  return jni::ToJavaString(env, url);
}

JNIEXPORT jobject JNICALL
Java_com_mapswithme_maps_Framework_nativeGetDistanceAndAzimuth(
    JNIEnv * env, jclass, jdouble merX, jdouble merY, jdouble cLat, jdouble cLon, jdouble north)
{
  string distance;
  double azimut = -1.0;
  frm()->GetDistanceAndAzimut(m2::PointD(merX, merY), cLat, cLon, north, distance, azimut);

  static jclass const daClazz = jni::GetGlobalClassRef(env, "com/mapswithme/maps/bookmarks/data/DistanceAndAzimut");
  // Java signature : DistanceAndAzimut(String distance, double azimuth)
  static jmethodID const methodID = jni::GetConstructorID(env, daClazz, "(Ljava/lang/String;D)V");

  return env->NewObject(daClazz, methodID,
                        jni::ToJavaString(env, distance.c_str()),
                        static_cast<jdouble>(azimut));
}

JNIEXPORT jobject JNICALL
Java_com_mapswithme_maps_Framework_nativeGetDistanceAndAzimuthFromLatLon(
    JNIEnv * env, jclass clazz, jdouble lat, jdouble lon, jdouble cLat, jdouble cLon, jdouble north)
{
  double const merY = mercator::LatToY(lat);
  double const merX = mercator::LonToX(lon);
  return Java_com_mapswithme_maps_Framework_nativeGetDistanceAndAzimuth(env, clazz, merX, merY, cLat, cLon, north);
}

JNIEXPORT jobject JNICALL
Java_com_mapswithme_maps_Framework_nativeFormatLatLon(JNIEnv * env, jclass, jdouble lat, jdouble lon, jboolean useDMSFormat)
{
  return jni::ToJavaString(
      env, (useDMSFormat ? measurement_utils::FormatLatLonAsDMS(lat, lon, 2)
                         : measurement_utils::FormatLatLon(lat, lon, true /* withSemicolon */, 6)));
}

JNIEXPORT jobjectArray JNICALL
Java_com_mapswithme_maps_Framework_nativeFormatLatLonToArr(JNIEnv * env, jclass, jdouble lat, jdouble lon, jboolean useDMSFormat)
{
  string slat, slon;
  if (useDMSFormat)
    measurement_utils::FormatLatLonAsDMS(lat, lon, slat, slon, 2);
  else
    measurement_utils::FormatLatLon(lat, lon, slat, slon, 6);

  static jclass const klass = jni::GetGlobalClassRef(env, "java/lang/String");
  jobjectArray arr = env->NewObjectArray(2, klass, 0);

  env->SetObjectArrayElement(arr, 0, jni::ToJavaString(env, slat));
  env->SetObjectArrayElement(arr, 1, jni::ToJavaString(env, slon));

  return arr;
}

JNIEXPORT jobject JNICALL
Java_com_mapswithme_maps_Framework_nativeFormatAltitude(JNIEnv * env, jclass, jdouble alt)
{
  return jni::ToJavaString(env, measurement_utils::FormatAltitude(alt));
}

JNIEXPORT jobject JNICALL
Java_com_mapswithme_maps_Framework_nativeFormatSpeed(JNIEnv * env, jclass, jdouble speed)
{
  return jni::ToJavaString(env, measurement_utils::FormatSpeedWithDeviceUnits(speed));
}

JNIEXPORT jobject JNICALL
Java_com_mapswithme_maps_Framework_nativeGetOutdatedCountriesString(JNIEnv * env, jclass)
{
  return jni::ToJavaString(env, g_framework->GetOutdatedCountriesString());
}

JNIEXPORT jobjectArray JNICALL
Java_com_mapswithme_maps_Framework_nativeGetOutdatedCountries(JNIEnv * env, jclass)
{
  vector<Country const *> countries;
  Storage const & storage = g_framework->GetStorage();
  storage.GetOutdatedCountries(countries);

  vector<string> ids;
  for (auto country : countries)
    ids.push_back(country->Name());

  return jni::ToJavaStringArray(env, ids);
}

JNIEXPORT jint JNICALL
Java_com_mapswithme_maps_Framework_nativeToDoAfterUpdate(JNIEnv * env, jclass)
{
  return g_framework->ToDoAfterUpdate();
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeIsDataVersionChanged(JNIEnv * env, jclass)
{
  return frm()->IsDataVersionUpdated() ? JNI_TRUE : JNI_FALSE;
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeUpdateSavedDataVersion(JNIEnv * env, jclass)
{
  frm()->UpdateSavedDataVersion();
}

JNIEXPORT jlong JNICALL
Java_com_mapswithme_maps_Framework_nativeGetDataVersion(JNIEnv * env, jclass)
{
  return frm()->GetCurrentDataVersion();
}

JNIEXPORT jint JNICALL
Java_com_mapswithme_maps_Framework_nativeGetDrawScale(JNIEnv * env, jclass)
{
  return static_cast<jint>(frm()->GetDrawScale());
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativePokeSearchInViewport(JNIEnv * env, jclass)
{
  frm()->PokeSearchInViewport();
}

JNIEXPORT jdoubleArray JNICALL
Java_com_mapswithme_maps_Framework_nativeGetScreenRectCenter(JNIEnv * env, jclass)
{
  m2::PointD const center = frm()->GetViewportCenter();

  double latlon[] = {mercator::YToLat(center.y), mercator::XToLon(center.x)};
  jdoubleArray jLatLon = env->NewDoubleArray(2);
  env->SetDoubleArrayRegion(jLatLon, 0, 2, latlon);

  return jLatLon;
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeShowTrackRect(JNIEnv * env, jclass, jlong track)
{
  frm()->ShowTrack(static_cast<kml::TrackId>(track));
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeGetBookmarkDir(JNIEnv * env, jclass)
{
  return jni::ToJavaString(env, GetPlatform().SettingsDir().c_str());
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeGetWritableDir(JNIEnv * env, jclass)
{
  return jni::ToJavaString(env, GetPlatform().WritableDir().c_str());
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeGetSettingsDir(JNIEnv * env, jclass)
{
  return jni::ToJavaString(env, GetPlatform().SettingsDir().c_str());
}

JNIEXPORT jobjectArray JNICALL
Java_com_mapswithme_maps_Framework_nativeGetMovableFilesExts(JNIEnv * env, jclass)
{
  vector<string> exts = { DATA_FILE_EXTENSION, FONT_FILE_EXTENSION, ROUTING_FILE_EXTENSION };
  platform::CountryIndexes::GetIndexesExts(exts);
  return jni::ToJavaStringArray(env, exts);
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeGetBookmarksExt(JNIEnv * env, jclass)
{
  return jni::ToJavaString(env, BOOKMARKS_FILE_EXTENSION);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetWritableDir(JNIEnv * env, jclass, jstring jNewPath)
{
  string newPath = jni::ToNativeString(env, jNewPath);
  g_framework->RemoveLocalMaps();
  android::Platform::Instance().SetWritableDir(newPath);
  g_framework->AddLocalMaps();
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeIsRoutingActive(JNIEnv * env, jclass)
{
  return frm()->GetRoutingManager().IsRoutingActive();
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeIsRouteBuilding(JNIEnv * env, jclass)
{
  return frm()->GetRoutingManager().IsRouteBuilding();
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeIsRouteBuilt(JNIEnv * env, jclass)
{
  return frm()->GetRoutingManager().IsRouteBuilt();
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeCloseRouting(JNIEnv * env, jclass)
{
  frm()->GetRoutingManager().CloseRouting(true /* remove route points */);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeBuildRoute(JNIEnv * env, jclass)
{
  frm()->GetRoutingManager().BuildRoute();
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeRemoveRoute(JNIEnv * env, jclass)
{
  frm()->GetRoutingManager().RemoveRoute(false /* deactivateFollowing */);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeFollowRoute(JNIEnv * env, jclass)
{
  frm()->GetRoutingManager().FollowRoute();
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeDisableFollowing(JNIEnv * env, jclass)
{
  frm()->GetRoutingManager().DisableFollowMode();
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeGetUserAgent(JNIEnv * env, jclass)
{
  return jni::ToJavaString(env, GetPlatform().GetAppUserAgent());
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeGetDeviceId(JNIEnv * env, jclass)
{
  return jni::ToJavaString(env, web_api::DeviceId());
}

JNIEXPORT jobjectArray JNICALL
Java_com_mapswithme_maps_Framework_nativeGenerateNotifications(JNIEnv * env, jclass)
{
  ::Framework * fr = frm();
  if (!fr->GetRoutingManager().IsRoutingActive())
    return nullptr;

  vector<string> notifications;
  fr->GetRoutingManager().GenerateNotifications(notifications);
  if (notifications.empty())
    return nullptr;

  return jni::ToJavaStringArray(env, notifications);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetSpeedCamManagerMode(JNIEnv * env, jclass, jint mode)
{
  frm()->GetRoutingManager().GetSpeedCamManager().SetMode(
    static_cast<routing::SpeedCameraManagerMode>(mode));
}

JNIEXPORT jint JNICALL
Java_com_mapswithme_maps_Framework_nativeGetSpeedCamManagerMode(JNIEnv * env, jclass)
{
  return static_cast<jint>(frm()->GetRoutingManager().GetSpeedCamManager().GetMode());
}

JNIEXPORT jobject JNICALL
Java_com_mapswithme_maps_Framework_nativeGetRouteFollowingInfo(JNIEnv * env, jclass)
{
  ::Framework * fr = frm();
  if (!fr->GetRoutingManager().IsRoutingActive())
    return nullptr;

  routing::FollowingInfo info;
  fr->GetRoutingManager().GetRouteFollowingInfo(info);
  if (!info.IsValid())
    return nullptr;

  static jclass const klass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/routing/RoutingInfo");
  // Java signature : RoutingInfo(String distToTarget, String units, String distTurn, String turnSuffix, String currentStreet, String nextStreet,
  //                              double completionPercent, int vehicleTurnOrdinal, int vehicleNextTurnOrdinal, int pedestrianTurnOrdinal,
  //                              double pedestrianDirectionLat, double pedestrianDirectionLon, int exitNum, int totalTime, SingleLaneInfo[] lanes)
  static jmethodID const ctorRouteInfoID = jni::GetConstructorID(env, klass,
                                               "(Ljava/lang/String;Ljava/lang/String;"
                                               "Ljava/lang/String;Ljava/lang/String;"
                                               "Ljava/lang/String;Ljava/lang/String;DIIIDDII"
                                               "[Lcom/mapswithme/maps/routing/SingleLaneInfo;ZZ)V");

  vector<routing::FollowingInfo::SingleLaneInfoClient> const & lanes = info.m_lanes;
  jobjectArray jLanes = nullptr;
  if (!lanes.empty())
  {
    static jclass const laneClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/routing/SingleLaneInfo");
    auto const lanesSize = static_cast<jsize>(lanes.size());
    jLanes = env->NewObjectArray(lanesSize, laneClass, nullptr);
    ASSERT(jLanes, (jni::DescribeException()));
    static jmethodID const ctorSingleLaneInfoID = jni::GetConstructorID(env, laneClass, "([BZ)V");

    for (jsize j = 0; j < lanesSize; ++j)
    {
      auto const laneSize = static_cast<jsize>(lanes[j].m_lane.size());
      jni::TScopedLocalByteArrayRef singleLane(env, env->NewByteArray(laneSize));
      ASSERT(singleLane.get(), (jni::DescribeException()));
      env->SetByteArrayRegion(singleLane.get(), 0, laneSize, lanes[j].m_lane.data());

      jni::TScopedLocalRef singleLaneInfo(
          env, env->NewObject(laneClass, ctorSingleLaneInfoID, singleLane.get(),
                              lanes[j].m_isRecommended));
      ASSERT(singleLaneInfo.get(), (jni::DescribeException()));
      env->SetObjectArrayElement(jLanes, j, singleLaneInfo.get());
    }
  }

  auto const & rm = frm()->GetRoutingManager();
  auto const isSpeedLimitExceeded = rm.IsRoutingActive() ? rm.IsSpeedLimitExceeded() : false;
  auto const shouldPlaySignal = frm()->GetRoutingManager().GetSpeedCamManager().ShouldPlayBeepSignal();
  jobject const result = env->NewObject(
      klass, ctorRouteInfoID, jni::ToJavaString(env, info.m_distToTarget),
      jni::ToJavaString(env, info.m_targetUnitsSuffix), jni::ToJavaString(env, info.m_distToTurn),
      jni::ToJavaString(env, info.m_turnUnitsSuffix), jni::ToJavaString(env, info.m_sourceName),
      jni::ToJavaString(env, info.m_displayedStreetName), info.m_completionPercent, info.m_turn, info.m_nextTurn, info.m_pedestrianTurn,
      info.m_pedestrianDirectionPos.m_lat, info.m_pedestrianDirectionPos.m_lon, info.m_exitNum, info.m_time, jLanes,
      static_cast<jboolean>(isSpeedLimitExceeded), static_cast<jboolean>(shouldPlaySignal));
  ASSERT(result, (jni::DescribeException()));
  return result;
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeDisableAdProvider(JNIEnv * env, jclass, jint type,
                                                           jint place)
{
  auto const & bannerType = static_cast<ads::Banner::Type>(type);
  auto const & bannerPlace = static_cast<ads::Banner::Place>(place);
  g_framework->DisableAdProvider(bannerType, bannerPlace);
}

JNIEXPORT jintArray JNICALL
Java_com_mapswithme_maps_Framework_nativeGenerateRouteAltitudeChartBits(JNIEnv * env, jclass, jint width, jint height, jobject routeAltitudeLimits)
{
  ::Framework * fr = frm();
  ASSERT(fr, ());

  feature::TAltitudes altitudes;
  vector<double> routePointDistanceM;
  if (!fr->GetRoutingManager().GetRouteAltitudesAndDistancesM(routePointDistanceM, altitudes))
  {
    LOG(LWARNING, ("Can't get distance to route points and altitude."));
    return nullptr;
  }

  vector<uint8_t> imageRGBAData;
  int32_t minRouteAltitude = 0;
  int32_t maxRouteAltitude = 0;
  measurement_utils::Units units = measurement_utils::Units::Metric;
  if (!fr->GetRoutingManager().GenerateRouteAltitudeChart(
        width, height, altitudes, routePointDistanceM, imageRGBAData,
        minRouteAltitude, maxRouteAltitude, units))
  {
    LOG(LWARNING, ("Can't generate route altitude image."));
    return nullptr;
  }

  // Passing route limits.
  jclass const routeAltitudeLimitsClass = env->GetObjectClass(routeAltitudeLimits);
  ASSERT(routeAltitudeLimitsClass, ());

  static jfieldID const minRouteAltitudeField = env->GetFieldID(routeAltitudeLimitsClass, "minRouteAltitude", "I");
  ASSERT(minRouteAltitudeField, ());
  env->SetIntField(routeAltitudeLimits, minRouteAltitudeField, minRouteAltitude);

  static jfieldID const maxRouteAltitudeField = env->GetFieldID(routeAltitudeLimitsClass, "maxRouteAltitude", "I");
  ASSERT(maxRouteAltitudeField, ());
  env->SetIntField(routeAltitudeLimits, maxRouteAltitudeField, maxRouteAltitude);

  static jfieldID const isMetricUnitsField = env->GetFieldID(routeAltitudeLimitsClass, "isMetricUnits", "Z");
  ASSERT(isMetricUnitsField, ());
  env->SetBooleanField(routeAltitudeLimits, isMetricUnitsField, units == measurement_utils::Units::Metric);

  size_t const imageRGBADataSize = imageRGBAData.size();
  ASSERT_NOT_EQUAL(imageRGBADataSize, 0, ("GenerateRouteAltitudeChart returns true but the vector with altitude image bits is empty."));

  size_t const pxlCount = width * height;
  if (maps::kAltitudeChartBPP * pxlCount != imageRGBADataSize)
  {
    LOG(LWARNING, ("Wrong size of vector with altitude image bits. Expected size:", pxlCount, ". Real size:", imageRGBADataSize));
    return nullptr;
  }

  jintArray imageRGBADataArray = env->NewIntArray(static_cast<jsize>(pxlCount));
  ASSERT(imageRGBADataArray, ());
  jint * arrayElements = env->GetIntArrayElements(imageRGBADataArray, 0);
  ASSERT(arrayElements, ());

  for (size_t i = 0; i < pxlCount; ++i)
  {
    size_t const shiftInBytes = i * maps::kAltitudeChartBPP;
    // Type of |imageRGBAData| elements is uint8_t. But uint8_t is promoted to unsinged int in code below before shifting.
    // So there's no data lost in code below.
    arrayElements[i] = (imageRGBAData[shiftInBytes + 3] << 24) /* alpha */
        | (imageRGBAData[shiftInBytes] << 16) /* red */
        | (imageRGBAData[shiftInBytes + 1] << 8) /* green */
        | (imageRGBAData[shiftInBytes + 2]); /* blue */
  }
  env->ReleaseIntArrayElements(imageRGBADataArray, arrayElements, 0);

  return imageRGBADataArray;
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeShowCountry(JNIEnv * env, jclass, jstring countryId, jboolean zoomToDownloadButton)
{
  g_framework->ShowNode(jni::ToNativeString(env, countryId), (bool) zoomToDownloadButton);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetRoutingListener(JNIEnv * env, jclass, jobject listener)
{
  CHECK(g_framework, ("Framework isn't created yet!"));
  auto rf = jni::make_global_ref(listener);
  frm()->GetRoutingManager().SetRouteBuildingListener(
      [rf](routing::RouterResultCode e, storage::CountriesSet const & countries) {
        CallRoutingListener(rf, static_cast<int>(e), countries);
      });
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetRouteProgressListener(JNIEnv * env, jclass, jobject listener)
{
  CHECK(g_framework, ("Framework isn't created yet!"));
  frm()->GetRoutingManager().SetRouteProgressListener(
      bind(&CallRouteProgressListener, jni::make_global_ref(listener), _1));
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetRoutingRecommendationListener(JNIEnv * env, jclass,
                                                                          jobject listener)
{
  CHECK(g_framework, ("Framework isn't created yet!"));
  frm()->GetRoutingManager().SetRouteRecommendationListener(
      bind(&CallRouteRecommendationListener, jni::make_global_ref(listener), _1));
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetRoutingLoadPointsListener(
        JNIEnv *, jclass, jobject listener)
{
  CHECK(g_framework, ("Framework isn't created yet!"));
  if (listener != nullptr)
    g_loadRouteHandler = bind(&CallSetRoutingLoadPointsListener, jni::make_global_ref(listener), _1);
  else
    g_loadRouteHandler = nullptr;
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeDeactivatePopup(JNIEnv * env, jclass)
{
  return g_framework->DeactivatePopup();
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetMapStyle(JNIEnv * env, jclass, jint mapStyle)
{
  MapStyle const val = static_cast<MapStyle>(mapStyle);
  if (val != g_framework->GetMapStyle())
    g_framework->SetMapStyle(val);
}

JNIEXPORT jint JNICALL
Java_com_mapswithme_maps_Framework_nativeGetMapStyle(JNIEnv * env, jclass, jint mapStyle)
{
  return g_framework->GetMapStyle();
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeMarkMapStyle(JNIEnv * env, jclass, jint mapStyle)
{
  MapStyle const val = static_cast<MapStyle>(mapStyle);
  if (val != g_framework->GetMapStyle())
    g_framework->MarkMapStyle(val);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetRouter(JNIEnv * env, jclass, jint routerType)
{
  g_framework->GetRoutingManager().SetRouter(static_cast<routing::RouterType>(routerType));
}

JNIEXPORT jint JNICALL
Java_com_mapswithme_maps_Framework_nativeGetRouter(JNIEnv * env, jclass)
{
  return static_cast<jint>(g_framework->GetRoutingManager().GetRouter());
}

JNIEXPORT jint JNICALL
Java_com_mapswithme_maps_Framework_nativeGetLastUsedRouter(JNIEnv * env, jclass)
{
  return static_cast<jint>(g_framework->GetRoutingManager().GetLastUsedRouter());
}

JNIEXPORT jint JNICALL
Java_com_mapswithme_maps_Framework_nativeGetBestRouter(JNIEnv * env, jclass,
                                                       jdouble srcLat, jdouble srcLon,
                                                       jdouble dstLat, jdouble dstLon)
{
  return static_cast<jint>(frm()->GetRoutingManager().GetBestRouter(
      mercator::FromLatLon(srcLat, srcLon), mercator::FromLatLon(dstLat, dstLon)));
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeAddRoutePoint(JNIEnv * env, jclass, jstring title,
                                                       jstring subtitle, jint markType,
                                                       jint intermediateIndex,
                                                       jboolean isMyPosition,
                                                       jdouble lat, jdouble lon)
{
  RouteMarkData data;
  data.m_title = jni::ToNativeString(env, title);
  data.m_subTitle = jni::ToNativeString(env, subtitle);
  data.m_pointType = static_cast<RouteMarkType>(markType);
  data.m_intermediateIndex = static_cast<size_t>(intermediateIndex);
  data.m_isMyPosition = static_cast<bool>(isMyPosition);
  data.m_position = m2::PointD(mercator::FromLatLon(lat, lon));

  frm()->GetRoutingManager().AddRoutePoint(std::move(data));
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeRemoveRoutePoint(JNIEnv * env, jclass,
                                                          jint markType, jint intermediateIndex)
{
  frm()->GetRoutingManager().RemoveRoutePoint(static_cast<RouteMarkType>(markType),
                                              static_cast<size_t>(intermediateIndex));
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeRemoveIntermediateRoutePoints(JNIEnv * env, jclass)
{
  frm()->GetRoutingManager().RemoveIntermediateRoutePoints();
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeCouldAddIntermediatePoint(JNIEnv * env, jclass)
{
  return frm()->GetRoutingManager().CouldAddIntermediatePoint();
}

JNIEXPORT jobjectArray JNICALL
Java_com_mapswithme_maps_Framework_nativeGetRoutePoints(JNIEnv * env, jclass)
{
  auto const points = frm()->GetRoutingManager().GetRoutePoints();

  static jclass const pointClazz = jni::GetGlobalClassRef(env,
                                   "com/mapswithme/maps/routing/RouteMarkData");
  // Java signature : RouteMarkData(String title, String subtitle,
  //                                @RoutePointInfo.RouteMarkType int pointType,
  //                                int intermediateIndex, boolean isVisible, boolean isMyPosition,
  //                                boolean isPassed, double lat, double lon)
  static jmethodID const pointConstructor = jni::GetConstructorID(env, pointClazz,
                                            "(Ljava/lang/String;Ljava/lang/String;IIZZZDD)V");
  return jni::ToJavaArray(env, pointClazz, points, [&](JNIEnv * jEnv, RouteMarkData const & data)
  {
    jni::TScopedLocalRef const title(env, jni::ToJavaString(env, data.m_title));
    jni::TScopedLocalRef const subtitle(env, jni::ToJavaString(env, data.m_subTitle));
    return env->NewObject(pointClazz, pointConstructor,
                          title.get(), subtitle.get(),
                          static_cast<jint>(data.m_pointType),
                          static_cast<jint>(data.m_intermediateIndex),
                          static_cast<jboolean>(data.m_isVisible),
                          static_cast<jboolean>(data.m_isMyPosition),
                          static_cast<jboolean>(data.m_isPassed),
                          mercator::YToLat(data.m_position.y),
                          mercator::XToLon(data.m_position.x));
  });
}

JNIEXPORT jobject JNICALL
Java_com_mapswithme_maps_Framework_nativeGetTransitRouteInfo(JNIEnv * env, jclass)
{
  auto const routeInfo = frm()->GetRoutingManager().GetTransitRouteInfo();

  static jclass const transitStepClass = jni::GetGlobalClassRef(env,
                                         "com/mapswithme/maps/routing/TransitStepInfo");
  // Java signature : TransitStepInfo(@TransitType int type, @Nullable String distance, @Nullable String distanceUnits,
  //                                  int timeInSec, @Nullable String number, int color, int intermediateIndex)
  static jmethodID const transitStepConstructor = jni::GetConstructorID(env, transitStepClass,
                                                  "(ILjava/lang/String;Ljava/lang/String;ILjava/lang/String;II)V");

  jni::TScopedLocalRef const steps(env, jni::ToJavaArray(env, transitStepClass,
                                                         routeInfo.m_steps,
                                                         [&](JNIEnv * jEnv, TransitStepInfo const & stepInfo)
  {
      jni::TScopedLocalRef const distance(env, jni::ToJavaString(env, stepInfo.m_distanceStr));
      jni::TScopedLocalRef const distanceUnits(env, jni::ToJavaString(env, stepInfo.m_distanceUnitsSuffix));
      jni::TScopedLocalRef const number(env, jni::ToJavaString(env, stepInfo.m_number));
      return env->NewObject(transitStepClass, transitStepConstructor,
                            static_cast<jint>(stepInfo.m_type),
                            distance.get(),
                            distanceUnits.get(),
                            static_cast<jint>(stepInfo.m_timeInSec),
                            number.get(),
                            static_cast<jint>(stepInfo.m_colorARGB),
                            static_cast<jint>(stepInfo.m_intermediateIndex));
  }));

  static jclass const transitRouteInfoClass = jni::GetGlobalClassRef(env,
                                                                     "com/mapswithme/maps/routing/TransitRouteInfo");
  // Java signature : TransitRouteInfo(@NonNull String totalDistance, @NonNull String totalDistanceUnits, int totalTimeInSec,
  //                                   @NonNull String totalPedestrianDistance, @NonNull String totalPedestrianDistanceUnits,
  //                                   int totalPedestrianTimeInSec, @NonNull TransitStepInfo[] steps)
  static jmethodID const transitRouteInfoConstructor = jni::GetConstructorID(env, transitRouteInfoClass,
                                                                             "(Ljava/lang/String;Ljava/lang/String;I"
                                                                             "Ljava/lang/String;Ljava/lang/String;I"
                                                                             "[Lcom/mapswithme/maps/routing/TransitStepInfo;)V");
  jni::TScopedLocalRef const distance(env, jni::ToJavaString(env, routeInfo.m_totalDistanceStr));
  jni::TScopedLocalRef const distanceUnits(env, jni::ToJavaString(env, routeInfo.m_totalDistanceUnitsSuffix));
  jni::TScopedLocalRef const distancePedestrian(env, jni::ToJavaString(env, routeInfo.m_totalPedestrianDistanceStr));
  jni::TScopedLocalRef const distancePedestrianUnits(env, jni::ToJavaString(env, routeInfo.m_totalPedestrianUnitsSuffix));
  return env->NewObject(transitRouteInfoClass, transitRouteInfoConstructor,
                        distance.get(), distanceUnits.get(), static_cast<jint>(routeInfo.m_totalTimeInSec),
                        distancePedestrian.get(), distancePedestrianUnits.get(), static_cast<jint>(routeInfo.m_totalPedestrianTimeInSec),
                        steps.get());
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeRegisterMaps(JNIEnv * env, jclass)
{
  frm()->RegisterAllMaps();
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeDeregisterMaps(JNIEnv * env, jclass)
{
  frm()->DeregisterAllMaps();
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeIsDayTime(JNIEnv * env, jclass, jlong utcTimeSeconds, jdouble lat, jdouble lon)
{
  DayTimeType const dt = GetDayTime(static_cast<time_t>(utcTimeSeconds), lat, lon);
  return (dt == DayTimeType::Day || dt == DayTimeType::PolarDay);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSet3dMode(JNIEnv * env, jclass, jboolean allow, jboolean allowBuildings)
{
  bool const allow3d = static_cast<bool>(allow);
  bool const allow3dBuildings = static_cast<bool>(allowBuildings);

  g_framework->Save3dMode(allow3d, allow3dBuildings);
  g_framework->Set3dMode(allow3d, allow3dBuildings);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeGet3dMode(JNIEnv * env, jclass, jobject result)
{
  bool enabled;
  bool buildings;
  g_framework->Get3dMode(enabled, buildings);

  jclass const resultClass = env->GetObjectClass(result);

  static jfieldID const enabledField = env->GetFieldID(resultClass, "enabled", "Z");
  env->SetBooleanField(result, enabledField, enabled);

  static jfieldID const buildingsField = env->GetFieldID(resultClass, "buildings", "Z");
  env->SetBooleanField(result, buildingsField, buildings);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetAutoZoomEnabled(JNIEnv * env, jclass, jboolean enabled)
{
  bool const autoZoomEnabled = static_cast<bool>(enabled);
  frm()->SaveAutoZoom(autoZoomEnabled);
  frm()->AllowAutoZoom(autoZoomEnabled);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetTransitSchemeEnabled(JNIEnv * env, jclass, jboolean enabled)
{
  frm()->GetTransitManager().EnableTransitSchemeMode(static_cast<bool>(enabled));
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeIsTransitSchemeEnabled(JNIEnv * env, jclass)
{
  return static_cast<jboolean>(frm()->LoadTransitSchemeEnabled());
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetIsolinesLayerEnabled(JNIEnv * env, jclass, jboolean enabled)
{
  auto const isolinesEnabled = static_cast<bool>(enabled);
  frm()->GetIsolinesManager().SetEnabled(isolinesEnabled);
  frm()->SaveIsolonesEnabled(isolinesEnabled);
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeIsIsolinesLayerEnabled(JNIEnv * env, jclass)
{
  return static_cast<jboolean>(frm()->LoadIsolinesEnabled());
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSaveSettingSchemeEnabled(JNIEnv * env, jclass, jboolean enabled)
{
  frm()->SaveTransitSchemeEnabled(static_cast<bool>(enabled));
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeGetAutoZoomEnabled(JNIEnv *, jclass)
{
  return frm()->LoadAutoZoom();
}

// static void nativeZoomToPoint(double lat, double lon, int zoom, boolean animate);
JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeZoomToPoint(JNIEnv * env, jclass, jdouble lat, jdouble lon, jint zoom, jboolean animate)
{
  g_framework->Scale(m2::PointD(mercator::FromLatLon(lat, lon)), zoom, animate);
}

JNIEXPORT jobject JNICALL
Java_com_mapswithme_maps_Framework_nativeDeleteBookmarkFromMapObject(JNIEnv * env, jclass)
{
  if (!frm()->HasPlacePageInfo())
    return nullptr;

  place_page::Info const & info = g_framework->GetPlacePageInfo();
  auto const bookmarkId = info.GetBookmarkId();
  frm()->GetBookmarkManager().GetEditSession().DeleteBookmark(bookmarkId);

  auto buildInfo = info.GetBuildInfo();
  buildInfo.m_match = place_page::BuildInfo::Match::FeatureOnly;
  buildInfo.m_userMarkId = kml::kInvalidMarkId;
  buildInfo.m_source = place_page::BuildInfo::Source::Other;
  frm()->UpdatePlacePageInfoForCurrentSelection(buildInfo);

  return usermark_helper::CreateMapObject(env, g_framework->GetPlacePageInfo());
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeTurnOnChoosePositionMode(JNIEnv *, jclass, jboolean isBusiness, jboolean applyPosition)
{
  auto const pos = applyPosition && frm()->HasPlacePageInfo()
      ? g_framework->GetPlacePageInfo().GetMercator()
      : m2::PointD();
  g_framework->SetChoosePositionMode(true, isBusiness, applyPosition, pos);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeTurnOffChoosePositionMode(JNIEnv *, jclass)
{
  g_framework->SetChoosePositionMode(false, false, false, m2::PointD());
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeIsInChoosePositionMode(JNIEnv *, jclass)
{
  return g_framework->GetChoosePositionMode();
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeIsDownloadedMapAtScreenCenter(JNIEnv *, jclass)
{
  ::Framework * fr = frm();
  return storage::IsPointCoveredByDownloadedMaps(fr->GetViewportCenter(), fr->GetStorage(), fr->GetCountryInfoGetter());
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeGetActiveObjectFormattedCuisine(JNIEnv * env, jclass)
{
  ::Framework * frm = g_framework->NativeFramework();
  if (!frm->HasPlacePageInfo())
    return {};

  return jni::ToJavaString(env, g_framework->GetPlacePageInfo().FormatCuisines());
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetVisibleRect(JNIEnv * env, jclass, jint left, jint top, jint right, jint bottom)
{
  frm()->SetVisibleViewport(m2::RectD(left, top, right, bottom));
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeIsRouteFinished(JNIEnv * env, jclass)
{
  return frm()->GetRoutingManager().IsRouteFinished();
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeLogLocalAdsEvent(JNIEnv * env, jclass, jint type,
                                                          jdouble lat, jdouble lon, jint accuracy)
{
  g_framework->LogLocalAdsEvent(static_cast<local_ads::EventType>(type), lat, lon, accuracy);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeRunFirstLaunchAnimation(JNIEnv * env, jclass)
{
  frm()->RunFirstLaunchAnimation();
}

JNIEXPORT jint JNICALL
Java_com_mapswithme_maps_Framework_nativeOpenRoutePointsTransaction(JNIEnv * env, jclass)
{
  return frm()->GetRoutingManager().OpenRoutePointsTransaction();
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeApplyRoutePointsTransaction(JNIEnv * env, jclass,
                                                                     jint transactionId)
{
  frm()->GetRoutingManager().ApplyRoutePointsTransaction(transactionId);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeCancelRoutePointsTransaction(JNIEnv * env, jclass,
                                                                      jint transactionId)
{
  frm()->GetRoutingManager().CancelRoutePointsTransaction(transactionId);
}

JNIEXPORT jint JNICALL
Java_com_mapswithme_maps_Framework_nativeInvalidRoutePointsTransactionId(JNIEnv * env, jclass)
{
  return frm()->GetRoutingManager().InvalidRoutePointsTransactionId();
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeHasSavedRoutePoints()
{
  return frm()->GetRoutingManager().HasSavedRoutePoints();
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeLoadRoutePoints()
{
  frm()->GetRoutingManager().LoadRoutePoints(g_loadRouteHandler);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSaveRoutePoints()
{
  frm()->GetRoutingManager().SaveRoutePoints();
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeDeleteSavedRoutePoints()
{
  frm()->GetRoutingManager().DeleteSavedRoutePoints();
}

JNIEXPORT jobjectArray JNICALL
Java_com_mapswithme_maps_Framework_nativeGetSearchBanners(JNIEnv * env, jclass)
{
  auto const & purchase = frm()->GetPurchase();
  if (purchase && purchase->IsSubscriptionActive(SubscriptionType::RemoveAds))
    return nullptr;
  return usermark_helper::ToBannersArray(env, frm()->GetAdsEngine().GetSearchBanners());
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeAuthenticateUser(JNIEnv * env, jclass, jstring socialToken,
                                                          jint socialTokenType,
                                                          jboolean privacyAccepted,
                                                          jboolean termsAccepted,
                                                          jboolean promoAccepted,
                                                          jobject listener)
{
  std::shared_ptr<_jobject> gListener(env->NewGlobalRef(listener), [](jobject l)
  {
    jni::GetEnv()->DeleteGlobalRef(l);
  });

  auto const tokenStr = jni::ToNativeString(env, socialToken);
  auto & user = frm()->GetUser();
  auto s = make_unique<User::Subscriber>();
  s->m_postCallAction = User::Subscriber::Action::RemoveSubscriber;
  s->m_onAuthenticate = [gListener](bool success)
  {
    GetPlatform().RunTask(Platform::Thread::Gui, [gListener, success]
    {
      auto e = jni::GetEnv();
      jmethodID const callback = jni::GetMethodID(e, gListener.get(), "onAuthorized", "(Z)V");
      e->CallVoidMethod(gListener.get(), callback, success);
    });
  };
  user.AddSubscriber(std::move(s));
  user.Authenticate(tokenStr, static_cast<User::SocialTokenType>(socialTokenType),
                    static_cast<bool>(privacyAccepted), static_cast<bool>(termsAccepted),
                    static_cast<bool>(promoAccepted));
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeIsUserAuthenticated()
{
  return frm()->GetUser().IsAuthenticated();
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeGetPhoneAuthUrl(JNIEnv * env, jclass, jstring redirectUrl)
{
  return jni::ToJavaString(env, User::GetPhoneAuthUrl(jni::ToNativeString(env, redirectUrl)));
}

JNIEXPORT jobjectArray JNICALL
Java_com_mapswithme_maps_Framework_nativeGetDefaultAuthHeaders(JNIEnv * env, jobject)
{
  auto const & bm = frm()->GetBookmarkManager();
  return jni::ToKeyValueArray(env, web_api::GetDefaultAuthHeaders());
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeGetPrivacyPolicyLink(JNIEnv * env, jclass)
{
  return jni::ToJavaString(env, User::GetPrivacyPolicyLink());
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeGetTermsOfUseLink(JNIEnv * env, jclass)
{
  return jni::ToJavaString(env, User::GetTermsOfUseLink());
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeShowFeatureByLatLon(JNIEnv * env, jclass,
                                                             jdouble lat, jdouble lon)
{
  frm()->ShowFeatureByMercator(mercator::FromLatLon(ms::LatLon(lat, lon)));
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeShowBookmarkCategory(JNIEnv * env, jclass, jlong cat)
{
  frm()->ShowBookmarkCategory(static_cast<kml::MarkGroupId>(cat));
}

JNIEXPORT jint JNICALL
Java_com_mapswithme_maps_Framework_nativeGetFilterRating(JNIEnv * env, jclass, jfloat rawRating)
{
  return static_cast<jint>(place_page::rating::GetFilterRating(rawRating));
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeMoPubInitializationBannerId(JNIEnv * env, jclass)
{
  return jni::ToJavaString(env, ads::Mopub::InitializationBannerId());
}

JNIEXPORT jobject JNICALL
Java_com_mapswithme_maps_Framework_nativeGetDownloaderPromoBanner(JNIEnv * env, jclass,
                                                                  jstring mwmId)
{
  static jclass const downloaderPromoBannerClass = jni::GetGlobalClassRef(env,
      "com/mapswithme/maps/downloader/DownloaderPromoBanner");
  // Java signature : DownloaderPromoBanner(@DownloaderPromoType int type, @NonNull String url)
  static jmethodID const downloaderPromoBannerConstructor = jni::GetConstructorID(env,
      downloaderPromoBannerClass, "(ILjava/lang/String;)V");

  auto const & purchase = frm()->GetPurchase();
  bool const hasSubscription = purchase != nullptr &&
                               purchase->IsSubscriptionActive(SubscriptionType::RemoveAds);

  promo::DownloaderPromo::Banner banner;
  auto const policy = platform::GetCurrentNetworkPolicy();
  if (policy.CanUse())
  {
    auto const * promoApi = frm()->GetPromoApi(policy);
    CHECK(promoApi != nullptr, ());
    banner = promo::DownloaderPromo::GetBanner(frm()->GetStorage(), *promoApi,
                                               jni::ToNativeString(env, mwmId),
                                               languages::GetCurrentNorm(), hasSubscription);
  }

  jni::TScopedLocalRef const url(env, jni::ToJavaString(env, banner.m_url));
  return env->NewObject(downloaderPromoBannerClass, downloaderPromoBannerConstructor,
                        static_cast<jint>(banner.m_type), url.get());
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeHasMegafonCategoryBanner(JNIEnv * env, jclass)
{
  auto const & purchase = frm()->GetPurchase();
  if (purchase && purchase->IsSubscriptionActive(SubscriptionType::RemoveAds))
    return static_cast<jboolean>(false);

  auto const position = frm()->GetCurrentPosition();
  if (!position)
    return static_cast<jboolean>(false);

  auto const latLon = mercator::ToLatLon(position.get());
  return static_cast<jboolean>(ads::HasMegafonCategoryBanner(frm()->GetStorage(),
                                                             frm()->GetTopmostCountries(latLon),
                                                             languages::GetCurrentNorm()));
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeGetMegafonCategoryBannerUrl(JNIEnv * env, jclass)
{
  return jni::ToJavaString(env, ads::GetMegafonCategoryBannerUrl());
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeMakeCrash(JNIEnv *env, jclass type)
{
  CHECK(false, ("Diagnostic native crash!"));
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeValidatePurchase(JNIEnv * env, jclass, jstring serverId,
                                                          jstring vendorId, jstring purchaseData)
{
  auto const & purchase = frm()->GetPurchase();
  if (purchase == nullptr)
    return;

  Purchase::ValidationInfo info;
  info.m_serverId = jni::ToNativeString(env, serverId);
  info.m_vendorId = jni::ToNativeString(env, vendorId);
  info.m_receiptData = jni::ToNativeString(env, purchaseData);

  purchase->Validate(info, frm()->GetUser().GetAccessToken());
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeStartPurchaseTransaction(JNIEnv * env, jclass,
                                                                  jstring serverId,
                                                                  jstring vendorId)
{
  auto const & purchase = frm()->GetPurchase();
  if (purchase == nullptr)
    return;

  purchase->StartTransaction(jni::ToNativeString(env, serverId),
                             jni::ToNativeString(env, vendorId),
                             frm()->GetUser().GetAccessToken());
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetPurchaseValidationListener(JNIEnv *, jclass,
                                                                       jobject listener)
{
  auto const & purchase = frm()->GetPurchase();
  if (purchase == nullptr)
    return;

  if (listener != nullptr)
  {
    purchase->SetValidationCallback(bind(&CallPurchaseValidationListener,
                                         jni::make_global_ref(listener), _1, _2));
  }
  else
  {
    purchase->SetValidationCallback(nullptr);
  }
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeStartPurchaseTransactionListener(JNIEnv *, jclass,
                                                                          jobject listener)
{
  auto const & purchase = frm()->GetPurchase();
  if (purchase == nullptr)
    return;

  if (listener != nullptr)
  {
    purchase->SetStartTransactionCallback(bind(&CallStartPurchaseTransactionListener,
                                          jni::make_global_ref(listener), _1, _2, _3));
  }
  else
  {
    purchase->SetStartTransactionCallback(nullptr);
  }
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeHasActiveSubscription(JNIEnv *, jclass, jint type)
{
  auto const & purchase = frm()->GetPurchase();
  return purchase != nullptr ?
    static_cast<jboolean>(purchase->IsSubscriptionActive(static_cast<SubscriptionType>(type))) :
    static_cast<jboolean>(false);
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetActiveSubscription(JNIEnv *, jclass, jint type,
                                                               jboolean isActive)
{
  auto const & purchase = frm()->GetPurchase();
  if (purchase == nullptr)
    return;
  purchase->SetSubscriptionEnabled(static_cast<SubscriptionType>(type),
                                   static_cast<bool>(isActive));
}

JNIEXPORT jint JNICALL
Java_com_mapswithme_maps_Framework_nativeGetCurrentTipIndex(JNIEnv * env, jclass)
{
  auto const & tipsApi = frm()->GetTipsApi();
  auto const tip = tipsApi.GetTip();
  return tip.is_initialized() ? static_cast<jint>(tip.get()) : kUndefinedTip;
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeBindUser(JNIEnv * env, jclass, jobject listener)
{
  auto listenerRef = jni::make_global_ref(listener);
  auto & user = frm()->GetUser();
  user.BindUser([listenerRef](bool success)
  {
    auto e = jni::GetEnv();
    jmethodID const callback = jni::GetMethodID(e, *listenerRef, "onUserBound", "(Z)V");
    e->CallVoidMethod(*listenerRef, callback, static_cast<jboolean>(success));
  });
}

JNIEXPORT jstring JNICALL
Java_com_mapswithme_maps_Framework_nativeGetAccessToken(JNIEnv * env, jclass)
{
  auto & user = frm()->GetUser();
  return jni::ToJavaString(env, user.GetAccessToken());
}

JNIEXPORT jobject JNICALL
Java_com_mapswithme_maps_Framework_nativeGetMapObject(JNIEnv * env, jclass,
                                                      jobject notificationCandidate)
{
  NotificationCandidate notification(NotificationCandidate::Type::UgcReview);
  auto const getBestTypeId =
      jni::GetMethodID(env, notificationCandidate, "getFeatureBestType", "()Ljava/lang/String;");
  auto const bestType =
      static_cast<jstring>(env->CallObjectMethod(notificationCandidate, getBestTypeId));
  notification.SetBestFeatureType(jni::ToNativeString(env, bestType));

  auto const getMercatorPosXId =
      jni::GetMethodID(env, notificationCandidate, "getMercatorPosX", "()D");
  auto const getMercatorPosYId =
      jni::GetMethodID(env, notificationCandidate, "getMercatorPosY", "()D");

  auto const posX =
      static_cast<double>(env->CallDoubleMethod(notificationCandidate, getMercatorPosXId));
  auto const posY =
      static_cast<double>(env->CallDoubleMethod(notificationCandidate, getMercatorPosYId));
  notification.SetPos({posX, posY});

  auto const getDefaultNameId =
      jni::GetMethodID(env, notificationCandidate, "getDefaultName", "()Ljava/lang/String;");
  auto const defaultName =
      static_cast<jstring>(env->CallObjectMethod(notificationCandidate, getDefaultNameId));
  notification.SetDefaultName(jni::ToNativeString(env, defaultName));

  if (frm()->MakePlacePageForNotification(notification))
    return usermark_helper::CreateMapObject(env, frm()->GetCurrentPlacePageInfo());

  return nullptr;
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetPowerManagerFacility(JNIEnv *, jclass,
                                                                 jint facilityType, jboolean state)
{
  frm()->GetPowerManager().SetFacility(static_cast<power_management::Facility>(facilityType),
                                       static_cast<bool>(state));
}

JNIEXPORT jint JNICALL
Java_com_mapswithme_maps_Framework_nativeGetPowerManagerScheme(JNIEnv *, jclass)
{
  return static_cast<jint>(frm()->GetPowerManager().GetScheme());
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetPowerManagerScheme(JNIEnv *, jclass, jint schemeType)
{
  frm()->GetPowerManager().SetScheme(static_cast<power_management::Scheme>(schemeType));
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetViewportCenter(JNIEnv *, jclass, jdouble lat,
                                                           jdouble lon, jint zoom, jboolean isAnim)
{
  auto const center = mercator::FromLatLon(static_cast<double>(lat),
                                           static_cast<double>(lon));
  frm()->SetViewportCenter(center, static_cast<int>(zoom), static_cast<bool>(isAnim));
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeStopLocationFollow(JNIEnv *, jclass)
{
  frm()->StopLocationFollow();
}

JNIEXPORT void JNICALL
Java_com_mapswithme_maps_Framework_nativeSetSearchViewport(JNIEnv *, jclass, jdouble lat,
                                                           jdouble lon, jint zoom)
{
  auto const center = mercator::FromLatLon(static_cast<double>(lat),
                                           static_cast<double>(lon));
  auto const rect = df::GetRectForDrawScale(static_cast<int>(zoom), center);
  frm()->GetSearchAPI().OnViewportChanged(rect);
}

JNIEXPORT jboolean JNICALL
Java_com_mapswithme_maps_Framework_nativeHasPlacePageInfo(JNIEnv *, jclass)
{
  return static_cast<jboolean>(frm()->HasPlacePageInfo());
}
}  // extern "C"