Repository navigation
Expand file tree
/
Copy pathtest_locations.cpp
More file actions
2543 lines (2120 loc) · 118 KB
/
Copy pathtest_locations.cpp
File metadata and controls
2543 lines (2120 loc) · 118 KB
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
// This file is part of the Diffractor photo and video organizer
// Copyright 2026 Zac Walker
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Purpose: Tests for places and location search (model_location*) -- the gazetteer, place naming,
// distance, map-driven queries, visits and the timeline. Owning document: docs/locations.md.
#include "pch.h"
#include <sqlite3.h>
#include "test_fixtures.h"
#include "test_runner.h"
#include "model_location.h"
#include "model_tile_cache.h"
#include "model_visits.h"
#include "ui_globe.h"
#include "ui_map_common.h"
static void should_group_sidebar_map_by_place()
{
const location_cache locations;
index_histograms histograms;
const auto record = [&]
{
df::index_file_item file;
file.ft = files::file_type_from_name("test.jpg");
const auto metadata = std::make_shared<prop::item_metadata>();
metadata->coordinate = gps_coordinate(50.08806, 14.42083);
metadata->location_place = "Prague"_c;
metadata->location_state = "Prague"_c;
metadata->location_country = "Czechia"_c;
file.metadata.store(metadata);
histograms.record(locations, file);
};
record();
record();
const auto map_loc = df::location_heat_map::calc_map_loc({50.08806, 14.42083});
const auto heat = histograms._locations.coordinates[map_loc.y * df::location_heat_map::map_width + map_loc.x];
assert_equal(2u, heat, "map heat accumulates repeated coordinates");
assert_equal(1u, static_cast<uint32_t>(histograms._location_groups.size()), "one place group");
const auto& group = histograms._location_groups.begin()->second;
assert_equal(2u, group.count, "place group count");
assert_equal(true, !core::is_empty(group.country), "place group country");
assert_equal(true, group.centroid().distance_in_kilometers({50.08806, 14.42083}) < 0.01,
"place group uses photo centroid");
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Map tiles (OpenStreetMap tile usage policy compliance)
///////////////////////////////////////////////////////////////////////////////////////////////////
static void should_build_tile_user_agent()
{
// The OSM tile usage policy requires a User-Agent that names the app + version
// and provides a contact URL; a generic/library-default agent is blocked.
const auto ua = tile_user_agent();
const auto expected = std::format("Diffractor/{} (+https://diffractor.com)", s_app_version);
assert_equal(expected, ua, "stable product, version and contact url", "tile user agent");
assert_equal(std::string::npos, ua.find_first_of("\r\n\t"), "contains no invalid header characters",
"tile user agent");
}
static void should_pack_tile_database_keys()
{
// Zoom caps at 18, so x and y stay below 2^20 and the whole address fits a positive int64 -
// which is what lets the store key its rows on the rowid.
assert_equal(true, map_tile_db_key(0, 0, 0) == 0, "origin", "tile key");
constexpr auto widest = 1 << map_max_zoom;
assert_equal(true, map_tile_db_key(map_max_zoom, widest - 1, widest - 1) > 0, "widest address stays positive",
"tile key");
std::set<int64_t> seen;
for (auto z = map_min_zoom; z <= map_max_zoom; ++z)
{
const auto span = 1 << z;
for (const auto x : {0, 1, span / 2, span - 1})
{
for (const auto y : {0, 1, span / 2, span - 1})
{
assert_equal(true, seen.insert(map_tile_db_key(z, x, y)).second, "address is unique", "tile key");
}
}
}
}
static core::date_t tile_days_ago(const uint32_t days)
{
return core::date_t(core::utc_now().to_int64() - days * core::date_t::intervals_per_day);
}
static void should_cache_tiles_in_a_database()
{
tile_cache_db db;
db.open(test_temps.next_path(".db"));
assert_equal(true, db.is_open(), "database opened", "tile cache");
constexpr auto key = map_tile_db_key(3, 1, 2);
assert_equal(true, db.load(key).empty(), "load absent returns empty", "tile cache");
const core::blob bytes = {0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4};
db.store(key, core::cspan(bytes));
db.flush();
const auto loaded = db.load(key);
assert_equal(static_cast<int>(bytes.size()), static_cast<int>(loaded.size()), "size round-trips", "tile cache");
assert_equal(true, loaded == bytes, "bytes round-trip", "tile cache");
assert_equal(1, static_cast<int>(db.count()), "one row stored", "tile cache");
const auto path = db.path();
db.close();
// A fresh connection over the same file still finds it (persists between sessions).
tile_cache_db reopened;
reopened.open(path);
assert_equal(true, reopened.load(key) == bytes, "persists across sessions", "tile cache");
reopened.close();
}
static void should_prune_unused_tiles()
{
tile_cache_db db;
db.open(test_temps.next_path(".db"));
const core::blob bytes = {1, 2, 3, 4};
const auto long_ago = tile_days_ago(60);
for (auto i = 0; i < 3; ++i)
{
db.store(map_tile_db_key(5, i, i), core::cspan(bytes), long_ago);
}
db.flush();
assert_equal(3, static_cast<int>(db.count()), "stored before prune", "tile cache");
db.prune(30, tile_cache_db::max_bytes);
assert_equal(0, static_cast<int>(db.count()), "tiles unused for longer than the window are dropped", "tile cache");
db.close();
}
static void should_bound_tile_cache_by_size()
{
tile_cache_db db;
db.open(test_temps.next_path(".db"));
const core::blob bytes(8192, 0x5a);
const auto long_ago = tile_days_ago(60);
for (auto i = 0; i < 8; ++i)
{
db.store(map_tile_db_key(6, i, i), core::cspan(bytes), long_ago);
}
db.flush();
assert_equal(8, static_cast<int>(db.count()), "stored before prune", "tile cache");
// A window wide enough that the age pass matches nothing, so only the size pass can evict.
db.prune(365, 1);
assert_equal(0, static_cast<int>(db.count()), "size cap evicts least recently used", "tile cache");
db.close();
}
static void should_budget_expired_tile_pruning()
{
tile_cache_db db;
db.open(test_temps.next_path(".db"));
const core::blob bytes = {1, 2, 3, 4};
const auto long_ago = tile_days_ago(60);
const auto recent = tile_days_ago(1);
for (auto i = 0; i < 4100; ++i)
{
db.store(map_tile_db_key(8, i, i), core::cspan(bytes), long_ago);
}
for (auto i = 0; i < 3; ++i)
{
db.store(map_tile_db_key(9, i, i), core::cspan(bytes), recent);
}
assert_equal(4103, static_cast<int>(db.count()), "stored before prune", "tile cache");
db.prune(30, tile_cache_db::max_bytes);
assert_equal(7, static_cast<int>(db.count()), "one maintenance pass removes only its row budget", "tile cache");
db.prune(30, tile_cache_db::max_bytes);
assert_equal(3, static_cast<int>(db.count()), "a later pass finishes expired cleanup", "tile cache");
db.close();
}
static void should_classify_tile_cache_open_failures_before_replacement()
{
assert_equal(false, tile_cache_test_seams::failure_allows_replacement(SQLITE_BUSY),
"busy is environmental, not replaceable", "tile cache");
assert_equal(false, tile_cache_test_seams::failure_allows_replacement(SQLITE_LOCKED),
"locked is environmental, not replaceable", "tile cache");
assert_equal(false, tile_cache_test_seams::failure_allows_replacement(SQLITE_IOERR),
"I/O is environmental, not replaceable", "tile cache");
assert_equal(true, tile_cache_test_seams::failure_allows_replacement(SQLITE_ERROR),
"incompatible schema is replaceable", "tile cache");
assert_equal(true, tile_cache_test_seams::failure_allows_replacement(SQLITE_CORRUPT),
"corrupt bytes are replaceable", "tile cache");
assert_equal(true, tile_cache_test_seams::failure_allows_replacement(SQLITE_NOTADB),
"non-database bytes are replaceable", "tile cache");
}
static void should_keep_tile_transaction_bookkeeping_after_commit_failure()
{
tile_cache_db db;
db.open(test_temps.next_path(".db"));
const core::blob bytes = {1, 2, 3, 4};
for (auto i = 0u; i < tile_cache_db::prune_write_interval; ++i)
{
db.store(map_tile_db_key(10, static_cast<int>(i), static_cast<int>(i)), core::cspan(bytes));
}
tile_cache_test_seams::fail_next_commit();
db.flush();
assert_equal(false, tile_cache_test_seams::wrapper_transaction_active(db),
"wrapper state is not left inside a transaction", "tile cache");
assert_equal(false, tile_cache_test_seams::sqlite_transaction_active(db),
"SQLite state agrees after failed commit recovery", "tile cache");
assert_equal(tile_cache_db::prune_write_interval, tile_cache_test_seams::writes_since_prune(db),
"prune is not run after persistence failed", "tile cache");
assert_equal(0, static_cast<int>(db.count()), "rolled back rows are not reported as stored", "tile cache");
constexpr auto key = map_tile_db_key(11, 1, 1);
db.store(key, core::cspan(bytes));
db.flush();
assert_equal(true, db.load(key) == bytes, "subsequent writes persist after the fault clears", "tile cache");
db.close();
}
static void should_keep_tiles_inside_the_retention_window()
{
// The OSM tile usage policy asks clients to keep what they download for at least a week, so a
// prune that has run out of anything older must give up rather than evict a fresh tile.
tile_cache_db db;
db.open(test_temps.next_path(".db"));
const core::blob bytes(8192, 0x5a);
for (auto i = 0; i < 4; ++i)
{
db.store(map_tile_db_key(7, i, i), core::cspan(bytes));
}
db.flush();
db.prune(0, 1);
assert_equal(4, static_cast<int>(db.count()), "recently fetched tiles survive any cap", "tile cache");
assert_equal(0u, tile_cache_test_seams::writes_since_prune(db),
"protected tiles over the cap do not reschedule idle prune passes", "tile cache");
db.close();
}
static void should_replace_an_unreadable_tile_cache()
{
const auto path = test_temps.next_path(".db");
const core::blob junk(4096, 0x7f);
platform::blob_save_to_file(core::cspan(junk), path);
tile_cache_db db;
db.open(path);
assert_equal(true, db.is_open(), "a file this build cannot read is replaced", "tile cache");
constexpr auto key = map_tile_db_key(4, 5, 6);
const core::blob bytes = {9, 8, 7};
db.store(key, core::cspan(bytes));
db.flush();
assert_equal(true, db.load(key) == bytes, "usable after replacement", "tile cache");
db.close();
}
static void should_resolve_tile_cache_db_beside_index_db()
{
// The tile database shares the folder the index database (diffractor-cache.db) is opened from.
const auto db_path = resolve_tile_cache_db_path();
const auto base = known_path(platform::known_folder::app_cache_data);
assert_equal(true, db_path == base.combine_file("map-tiles-cache.db"sv), "database beside index database",
"tile cache location");
assert_equal(true, platform::exists(base), "base folder exists", "tile cache location");
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Map geometry
///////////////////////////////////////////////////////////////////////////////////////////////////
static void should_anchor_map_marker_cells_to_world()
{
const gps_coordinate first(50.0755, 14.4378);
const gps_coordinate nearby(50.07551, 14.43781);
const auto first_cell = map_marker_world_cell(first, 16);
const auto nearby_cell = map_marker_world_cell(nearby, 16);
assert_equal(true, first_cell == map_marker_world_cell(first, 16), "cell is independent of viewport center",
"map markers");
assert_equal(true, first_cell == nearby_cell, "nearby markers aggregate in the same world cell", "map markers");
assert_equal(false, first_cell == map_marker_world_cell(first, 17), "zoom recalculates world cells", "map markers");
}
static void should_publish_prepared_map_marker_snapshots()
{
null_async_strategy async;
auto invalidated = false;
map_engine engine(async, [&invalidated] { invalidated = true; });
constexpr sizei extent(800, 600);
constexpr recti bounds(0, 0, extent.cx, extent.cy);
const gps_coordinate prague(50.0755, 14.4378);
std::vector<map_engine::marker> markers;
markers.reserve(100);
for (auto i = 0; i < 100; ++i) markers.push_back({prague, 1});
auto snapshot = map_engine::prepare_marker_snapshot(markers, 16);
assert_equal(true, snapshot.has_markers, "snapshot has markers", "map markers");
assert_equal(1u, static_cast<uint32_t>(map_engine::prepared_marker_count(snapshot)),
"snapshot work is bounded by prepared cells", "map markers");
engine.set_location(prague, bounds);
invalidated = false;
engine.set_marker_snapshot(std::move(snapshot));
assert_equal(true, invalidated, "publishing a snapshot invalidates once", "map markers");
const auto visible = engine.visible_cluster_coordinates(extent);
assert_equal(1u, static_cast<uint32_t>(visible.size()), "colocated markers form one bubble", "map markers");
assert_equal(1u, static_cast<uint32_t>(engine.last_cluster_work()),
"paint clustering visits prepared cells, not source markers", "map markers");
pointi anchor;
auto count = 0;
const auto marker = engine.hit_test_marker({extent.cx / 2, extent.cy / 2}, extent, anchor, count);
assert_equal(true, marker >= 0, "the prepared bubble is hit-testable", "map markers");
assert_equal(100, count, "hit testing and paint use the same aggregate count", "map markers");
}
static void should_cull_prepared_map_marker_cells_to_view()
{
null_async_strategy async;
map_engine engine(async, [] {});
constexpr sizei extent(800, 600);
constexpr recti bounds(0, 0, extent.cx, extent.cy);
const gps_coordinate prague(50.0755, 14.4378);
std::vector<map_engine::marker> markers;
for (auto lat = -60; lat <= 60; lat += 5)
{
for (auto lon = -175; lon <= 175; lon += 5)
{
markers.push_back({gps_coordinate(static_cast<double>(lat), static_cast<double>(lon)), 1});
}
}
markers.push_back({prague, 1});
auto snapshot = map_engine::prepare_marker_snapshot(markers, 8);
const auto prepared_count = map_engine::prepared_marker_count(snapshot);
assert_equal(true, prepared_count > 100u, "test prepares many cells", "map markers");
engine.set_location(prague, bounds);
engine.set_marker_snapshot(std::move(snapshot));
const auto visible = engine.visible_cluster_coordinates(extent);
assert_equal(true, !visible.empty(), "the viewport still has visible cells", "map markers");
assert_equal(true, engine.last_cluster_work() < prepared_count / 4,
"viewport clustering visits nearby prepared cells, not every prepared cell", "map markers");
}
static void should_clear_map_marker_hits_when_snapshot_changes()
{
null_async_strategy async;
map_engine engine(async, [] {});
constexpr sizei extent(800, 600);
constexpr recti bounds(0, 0, extent.cx, extent.cy);
const gps_coordinate prague(50.0755, 14.4378);
engine.set_location(prague, bounds);
engine.set_marker_snapshot(map_engine::prepare_marker_snapshot({{prague, 1}}, 16));
(void)engine.visible_cluster_coordinates(extent);
pointi anchor;
auto count = 0;
assert_equal(true, engine.hit_test_marker({extent.cx / 2, extent.cy / 2}, extent, anchor, count) >= 0,
"initial snapshot is hit-testable", "map markers");
engine.set_marker_snapshot({});
assert_equal(-1, engine.hit_test_marker({extent.cx / 2, extent.cy / 2}, extent, anchor, count),
"a replaced snapshot cannot return stale hit-test indices", "map markers");
}
static void should_measure_distance_to_map_cells()
{
constexpr recti cell(10, 20, 30, 40);
assert_equal(0, static_cast<int>(distance_squared({20, 30}, cell)), "cursor inside cell has zero distance",
"map cells");
assert_equal(25, static_cast<int>(distance_squared({35, 30}, cell)), "horizontal gap is measured", "map cells");
assert_equal(50, static_cast<int>(distance_squared({35, 45}, cell)), "diagonal gap is measured", "map cells");
const auto left_distance = distance_squared({50, 30}, cell);
constexpr auto right_distance = distance_squared({50, 30}, recti(60, 20, 80, 40));
assert_equal(true, right_distance < left_distance, "nearest occupied cell wins between cells", "map cells");
}
static void should_frame_map_on_the_box_that_holds_items()
{
constexpr sizei extent(800, 600);
// locations.md 5.5: the gesture is to see a hot spot and click it, so a map that opens has
// to show the region that holds items rather than an arbitrary coordinate inside it.
const map_box empty;
assert_equal(false, empty.valid, "an empty box frames nothing", "map framing");
assert_equal(false, empty.centre().is_valid(), "an empty box has no centre", "map framing");
map_box city;
city.add(gps_coordinate(51.4, -0.3));
city.add(gps_coordinate(51.6, 0.1));
const auto centre = city.centre();
assert_equal(true, std::abs(centre.latitude() - 51.5) < 0.0001, "centre latitude", "map framing");
assert_equal(true, std::abs(centre.longitude() - -0.1) < 0.0001, "centre longitude", "map framing");
map_box world;
world.add(gps_coordinate(-60.0, -170.0));
world.add(gps_coordinate(60.0, 170.0));
const auto city_zoom = map_fit_zoom(city, extent);
const auto world_zoom = map_fit_zoom(world, extent);
assert_equal(true, city_zoom > world_zoom, "a smaller box frames closer", "map framing");
assert_equal(true, world_zoom >= map_min_zoom && city_zoom <= map_max_zoom, "framing stays on served tiles",
"map framing");
// The fitted zoom shows the whole box; one step closer would cut it off.
const auto span_px = [](const map_box& box, const int zoom)
{
return std::max((lon_to_tile_x(box.max_longitude, zoom) - lon_to_tile_x(box.min_longitude, zoom)) * TILE_SIZE,
(lat_to_tile_y(box.min_latitude, zoom) - lat_to_tile_y(box.max_latitude, zoom)) * TILE_SIZE);
};
assert_equal(true, span_px(city, city_zoom) <= extent.cx, "the framed box fits", "map framing");
assert_equal(true, span_px(city, city_zoom + 1) > extent.cx - TILE_SIZE, "framing is not needlessly wide",
"map framing");
map_box point;
point.add(gps_coordinate(51.5, -0.1));
assert_equal(map_max_zoom, map_fit_zoom(point, extent), "a single place frames as close as the tiles go",
"map framing");
assert_equal(map_min_zoom, map_fit_zoom(city, sizei(0, 0)), "an unlaid-out map cannot frame", "map framing");
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// The sidebar globe
///////////////////////////////////////////////////////////////////////////////////////////////////
static void should_project_globe_coordinates()
{
constexpr pointi center(160, 160);
constexpr double radius = 150.0;
const globe_projection equator({0.0, 0.0}, center, radius);
const auto middle = equator.project({0.0, 0.0});
assert_equal(true, middle.has_value(), "the view coordinate faces the viewer", "globe");
assert_equal(true, middle.value() == center, "and lands dead centre", "globe");
const auto east = equator.project({0.0, 90.0});
assert_equal(false, east.has_value(), "a quarter turn away sits exactly on the limb", "globe");
assert_equal(false, equator.project({0.0, 180.0}).has_value(), "the far side is not shown", "globe");
const auto right = equator.project({0.0, 30.0});
assert_equal(true, right.has_value(), "an eastward place stays visible", "globe");
assert_equal(true, right->x > center.x, "and is drawn to the east", "globe");
assert_equal(center.y, right->y, "with no northward drift", "globe");
const auto north = equator.project({30.0, 0.0});
assert_equal(true, north.has_value(), "a northward place stays visible", "globe");
assert_equal(true, north->y < center.y, "and is drawn above the centre", "globe");
// Full pan: with the view over Australia the antipode is hidden and Australia is centred.
const gps_coordinate sydney(-33.8688, 151.2093);
const globe_projection tilted(sydney, center, radius);
const auto framed = tilted.project(sydney);
assert_equal(true, framed.has_value(), "the framed place faces the viewer", "globe");
assert_equal(true, framed.value() == center, "and holds the centre under a tilted view", "globe");
assert_equal(false, tilted.project({33.8688, -28.7907}).has_value(), "its antipode is hidden", "globe");
const auto pole = globe_projection({90.0, 0.0}, center, radius).project({90.0, 137.0});
assert_equal(true, pole.has_value(), "a polar view can hold the pole itself", "globe");
assert_equal(true, pole.value() == center, "wherever the longitude claims to be", "globe");
}
static void should_round_trip_globe_pixels()
{
constexpr pointi center(160, 160);
constexpr double radius = 150.0;
const gps_coordinate views[] = {{0.0, 0.0}, {-33.8688, 151.2093}, {39.5, -98.35}, {89.0, 0.0}};
const gps_coordinate places[] = {{0.0, 0.0}, {51.5, -0.1}, {-33.8688, 151.2093}, {35.7, 139.7}, {-60.0, -170.0}};
for (const auto& view : views)
{
const globe_projection projection(view, center, radius);
for (const auto& place : places)
{
const auto pixel = projection.project(place);
if (!pixel) continue;
const auto shown = projection.unproject(pixel.value());
assert_equal(true, shown.has_value(), "a pixel on the disc shows a coordinate", "globe");
// Rounding to the pixel costs about a fifth of a degree at this radius, and more as
// the limb compresses; a degree of slack keeps the check honest without being noise.
assert_near(place.latitude(), shown->latitude(), 1.0, "round trip latitude", "globe");
assert_near(0.0, globe_wrap_longitude(place.longitude() - shown->longitude()), 1.0, "round trip longitude",
"globe");
}
}
const globe_projection projection({0.0, 0.0}, center, radius);
assert_equal(false, projection.unproject({center.x + 200, center.y}).has_value(), "a pixel off the disc shows none",
"globe");
assert_equal(true, projection.unproject({center.x + 149, center.y}).has_value(), "a pixel inside the limb does",
"globe");
}
static void should_rotate_globe_by_drag()
{
constexpr double radius = 150.0;
const gps_coordinate start(0.0, 0.0);
const auto west = globe_view_from_drag(start, {static_cast<int>(radius * 2), 0}, radius);
assert_near(-180.0, west.longitude(), 0.0001, "a drag across the diameter turns half way round", "globe");
assert_near(0.0, west.latitude(), 0.0001, "and leaves the latitude alone", "globe");
const auto east = globe_view_from_drag(start, {-static_cast<int>(radius), 0}, radius);
assert_near(90.0, east.longitude(), 0.0001, "dragging left turns the globe east", "globe");
// Dragging down brings the north to the centre - the ball rolls under the finger.
const auto north = globe_view_from_drag(start, {0, static_cast<int>(radius / 2)}, radius);
assert_near(45.0, north.latitude(), 0.0001, "dragging down looks north", "globe");
const auto clamped = globe_view_from_drag({80.0, 0.0}, {0, static_cast<int>(radius)}, radius);
assert_near(90.0, clamped.latitude(), 0.0001, "the pole is as far as the view tilts", "globe");
assert_near(-90.0, globe_view_from_drag({-80.0, 0.0}, {0, -static_cast<int>(radius)}, radius).latitude(), 0.0001,
"in both directions", "globe");
// Turning past the date line has to stay continuous: a jump here reads as the globe flipping.
const auto crossed = globe_view_from_drag({0.0, -170.0}, {static_cast<int>(radius / 3), 0}, radius);
assert_near(160.0, crossed.longitude(), 0.0001, "the view wraps through the date line", "globe");
assert_near(-179.0, globe_wrap_longitude(181.0), 0.0001, "wrapping is symmetric", "globe");
// gps_coordinate spends exactly +-180 as its "no coordinate" sentinel, so a view that turns onto
// the date line must still be a view rather than a hole.
assert_near(-180.0, globe_wrap_longitude(-180.0), 0.001, "the date line stays the date line", "globe");
assert_equal(true, gps_coordinate(0.0, globe_wrap_longitude(-180.0)).is_valid(),
"and is a coordinate, not the invalid sentinel", "globe");
assert_equal(true, gps_coordinate(0.0, globe_wrap_longitude(540.0)).is_valid(), "from either direction", "globe");
assert_equal(true, globe_view_from_drag(start, {50, 50}, 0.0).longitude() == start.longitude(),
"an unlaid-out globe cannot turn", "globe");
}
static void should_frame_globe_on_the_collection()
{
// An Australian collection opens on Australia, a US one on the US: the default view is where
// the photos are, not a fixed prime meridian.
globe_framer australian;
australian.add(gps_coordinate(-33.8688, 151.2093), 400);
australian.add(gps_coordinate(-37.8136, 144.9631), 100);
const auto australia = australian.view();
assert_equal(true, australia.is_valid(), "a collection has a view", "globe framing");
assert_near(-34.7, australia.latitude(), 1.5, "framed on the southern hemisphere", "globe framing");
assert_near(149.9, australia.longitude(), 1.5, "and weighted toward the larger place", "globe framing");
globe_framer american;
american.add(gps_coordinate(37.7749, -122.4194), 300);
american.add(gps_coordinate(40.7128, -74.0060), 300);
const auto usa = american.view();
assert_near(-98.0, usa.longitude(), 3.0, "a coast-to-coast collection frames on the middle", "globe framing");
assert_equal(true, usa.latitude() > 30.0, "in the northern hemisphere", "globe framing");
// The antimeridian trap: averaging the numbers would face the Atlantic instead.
globe_framer date_line;
date_line.add(gps_coordinate(0.0, 170.0), 1);
date_line.add(gps_coordinate(0.0, -170.0), 1);
const auto crossing = date_line.view();
assert_near(180.0, std::abs(crossing.longitude()), 0.001, "places either side face the date line", "globe framing");
assert_equal(true, crossing.is_valid(), "and the view is usable there", "globe framing");
globe_framer empty;
assert_equal(false, empty.view().is_valid(), "an empty collection frames nothing", "globe framing");
globe_framer cancelling;
cancelling.add(gps_coordinate(90.0, 0.0), 1);
cancelling.add(gps_coordinate(-90.0, 0.0), 1);
assert_equal(false, cancelling.view().is_valid(), "and neither does one with no deserved direction",
"globe framing");
globe_framer ignored;
ignored.add(gps_coordinate(), 10);
ignored.add(gps_coordinate(10.0, 20.0), 0);
assert_equal(false, ignored.view().is_valid(), "places without a coordinate or a count are not framed on",
"globe framing");
}
static void should_build_aggregate_location_matrix()
{
location_matrix matrix({16, 44, -60.0, -30.0, 60.0, 170.0});
const gps_coordinate prague1(50.0755, 14.4378);
const gps_coordinate prague2(50.0756, 14.4379);
const gps_coordinate sydney(-33.8688, 151.2093);
const gps_coordinate excluded_by_bounds(64.1466, -21.9426);
matrix.add(core::file_path("c:\\b.jpg"), prague2, true, 5);
matrix.add(core::file_path("c:\\sydney.jpg"), sydney, true, 0);
matrix.add(core::file_path("c:\\a.jpg"), prague1, true, 3);
matrix.add(core::file_path("c:\\reykjavik.jpg"), excluded_by_bounds, true, 5);
matrix.finalize();
assert_equal(2_z, matrix.cells.size(), "only occupied in-bounds cells are stored", "location matrix");
const auto prague = std::ranges::find(matrix.cells, matrix.params.cell(prague1), &location_matrix::cell::index);
assert_equal(true, prague != matrix.cells.end(), "nearby items share a cell", "location matrix");
assert_equal(2, static_cast<int>(prague->count), "cell retains the item count", "location matrix");
assert_equal("b.jpg", prague->representative_path.name(), "high-rated media is representative", "location matrix");
assert_equal(50.07555, prague->centroid.latitude(), "cell coordinate is the centroid", "location matrix");
assert_equal(50.0755, prague->min_latitude, "cell retains minimum latitude", "location matrix");
assert_equal(14.4379, prague->max_longitude, "cell retains maximum longitude", "location matrix");
location_matrix ranked;
ranked.add(core::file_path("c:\\0.txt"), prague1, false, 5);
ranked.add(core::file_path("c:\\a.jpg"), prague1, true, 3);
ranked.add(core::file_path("c:\\b.jpg"), prague1, true, 5);
ranked.finalize();
assert_equal("b.jpg", ranked.cells.front().representative_path.name(),
"rated visual media outranks non-visual and lower-rated items", "location matrix");
location_matrix_params sidebar_params;
sidebar_params.projection = location_matrix_projection::location_heat_map;
sidebar_params.area_cell_span = 4;
const auto heat_cell = df::location_heat_map::calc_map_loc(prague1);
const auto sidebar_cell = sidebar_params.cell(prague1);
assert_equal(heat_cell.x / 4 * 4, sidebar_cell.x, "fixed projection aligns horizontally", "location matrix");
assert_equal(heat_cell.y / 4 * 4, sidebar_cell.y, "fixed projection aligns vertically", "location matrix");
}
static void should_select_thumbnail_representatives_while_counting()
{
auto make_file = [](const std::string_view name, const int rating)
{
df::index_file_item result;
result.name = core::cache(name);
result.ft = files::file_type_from_name(name);
const auto metadata = std::make_shared<prop::item_metadata>();
metadata->rating = static_cast<int16_t>(rating);
result.metadata.store(metadata);
return result;
};
const auto text = make_file("0.txt", 5);
const auto ordinary_photo = make_file("a.jpg", 3);
const auto rated_photo = make_file("b.jpg", 5);
df::file_group_histogram first;
first.record(text, core::file_path("c:\\0.txt"));
first.record(ordinary_photo, core::file_path("c:\\a.jpg"));
assert_equal("a.jpg", first.representative_path.name(), "visual media outranks non-thumbnail files",
"summary thumbnail");
df::file_group_histogram second;
second.record(rated_photo, core::file_path("c:\\b.jpg"));
first.add(second);
assert_equal("b.jpg", first.representative_path.name(), "rated media survives histogram merge",
"summary thumbnail");
df::date_histogram dates;
dates.record_representative(0, ordinary_photo, core::file_path("c:\\a.jpg"));
dates.record_representative(0, rated_photo, core::file_path("c:\\b.jpg"));
assert_equal("b.jpg", dates.representative_paths[0].name(), "date bucket prioritises rated media",
"summary thumbnail");
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Gazetteer lookup
///////////////////////////////////////////////////////////////////////////////////////////////////
static void should_find_location()
{
auto& locations = test_locations();
// The display language is shared state; every early return below would otherwise leak it.
const core::scope_exit restore_language([&locations] { locations.set_display_language({}); });
const auto default_location = gps_coordinate(51.5255317687988, -0.116743430495262); // London
assert_equal("City of London", locations.find_by_id(2643741).place, "City");
assert_equal(true, locations.find_by_id(2643741).population > 0.0, "City population");
assert_equal("King of Prussia", locations.find_by_id(5196220).place, "City");
assert_equal("London", locations.find_largest(51.3, -0.5, 51.7, 0.3).place,
"largest population center inside photo bounds");
const auto boulder_city_coord = gps_coordinate(35.9786, -114.8325);
assert_equal("Boulder City",
locations.find_closest(boulder_city_coord.latitude(), boulder_city_coord.longitude()).place,
"Boulder City reverse geocode");
df::index_file_item boulder_city_file;
boulder_city_file.ft = files::file_type_from_name("test.jpg");
auto boulder_city_metadata = boulder_city_file.safe_ps();
boulder_city_metadata->coordinate = boulder_city_coord;
boulder_city_metadata->location_state = "Nevada"_c;
boulder_city_metadata->location_country = "United States"_c;
const auto boulder_city_search = df::search_t::parse("loc:\"Boulder City\"");
const df::search_matcher boulder_city_matcher(boulder_city_search, core::utc_now().to_days(), &locations);
assert_equal(true, boulder_city_matcher.match_item({}, boulder_city_file).is_match(),
"loc place uses map reverse geocode when stored place is empty");
// locations.md 2.3: a prediction is labelled at its qualification level, not always fully.
assert_equal("London, United Kingdom", locations.auto_complete("london", 8, default_location)[0].location.str(),
"City");
assert_equal("London, Canada", locations.auto_complete("london canada", 8, default_location)[0].location.str(),
"City");
assert_equal("Armidale", locations.auto_complete("armid aust", 8, default_location)[0].location.str(), "City");
assert_equal("Birmingham, United Kingdom",
locations.auto_complete("birm gb", 8, default_location)[0].location.str(), "City");
assert_equal("King of Prussia", locations.auto_complete("king pru usa", 8, default_location)[0].location.str(),
"City");
assert_equal("King of Prussia",
locations.auto_complete("king of prussia pennsylvania", 8, default_location)[0].location.str(),
"State");
const auto czech_matches = locations.auto_complete("cz", 8, default_location);
assert_equal(true, !czech_matches.empty(), "country code produces location predictions");
assert_equal("Czechia"s, std::string(czech_matches.front().location.country), "CZ predicts Czechia");
const auto short_local = locations.auto_complete("bi", 4, default_location);
assert_equal(true,
std::ranges::any_of(short_local,
[](const location_match& match)
{
return core::icmp(match.location.place, "Birmingham") == 0 &&
core::icmp(match.location.country, "United Kingdom") == 0;
}),
"short prefixes include local places by canonical country code");
assert_equal(true, short_local.size() <= 4, "short completion honours the result cap");
const auto short_nonlocal = locations.auto_complete("ar", 8, default_location);
assert_equal(false,
std::ranges::any_of(short_nonlocal, [](const location_match& match)
{ return core::icmp(match.location.place, "Armidale") == 0; }),
"short prefixes still suppress non-local place matches");
// Issue #119: the displayed place and country names follow the selected UI language.
locations.set_display_language("de");
const auto munich_de = locations.find_by_id(2867714);
assert_equal("München", munich_de.place, "German place");
assert_equal("Deutschland", munich_de.country, "German country");
const auto local_de = locations.auto_complete("bi", 4, default_location);
assert_equal(true,
std::ranges::any_of(local_de,
[](const location_match& match)
{
return core::icmp(match.location.place, "Birmingham") == 0 &&
core::icmp(match.location.country, "Vereinigtes Königreich") == 0;
}),
"localized display names do not break short local completion");
locations.set_display_language("es");
const auto munich_es = locations.find_by_id(2867714);
assert_equal("Múnich", munich_es.place, "Spanish place");
assert_equal("Alemania", munich_es.country, "Spanish country");
const auto local_es = locations.auto_complete("bi", 4, default_location);
assert_equal(true,
std::ranges::any_of(local_es,
[](const location_match& match)
{
return core::icmp(match.location.place, "Birmingham") == 0 &&
core::icmp(match.location.country, "Reino Unido") == 0;
}),
"a second localized display language still completes local short prefixes");
locations.set_display_language("zh");
const auto munich_zh = locations.find_by_id(2867714);
assert_equal("慕尼黑", munich_zh.place, "Chinese place");
assert_equal("德国", munich_zh.country, "Chinese country");
// Issue #119 regression guard: find_country() feeds the map/heat-map country grouping whose
// label doubles as a SEARCH term (sidebar .with(name)). It must stay canonical (English)
// regardless of the selected display language so a map click still matches the country name
// stored in the index -- localizing it here previously broke map-click search in zh/de/etc.
const auto grouping = locations.find_country(48.137, 11.575); // Munich, Germany
assert_equal("Germany", grouping.name, "Country grouping key stays canonical while display is localized");
country_loc combined_country;
const auto combined_location = locations.find_closest(48.137, 11.575, &combined_country);
assert_equal("慕尼黑", combined_location.place, "Combined lookup keeps localized place");
assert_equal("Germany", combined_country.name, "Combined lookup keeps canonical country grouping key");
locations.set_display_language("xx"); // unknown language falls back to the default names
const auto munich_default = locations.find_by_id(2867714);
assert_equal("Munich", munich_default.place, "Unknown language falls back");
assert_equal("Germany", munich_default.country, "Default country");
locations.set_display_language("en"); // English exonym equals the default name -> fallback
assert_equal("Munich", locations.find_by_id(2867714).place, "English name");
}
static void should_return_no_place_for_empty_location_lookup()
{
const location_cache locations;
const auto closest = locations.find_closest(0.0, 0.0);
assert_equal(true, core::is_empty(closest.place), "empty gazetteer has no closest place");
assert_equal(0u, closest.id, "empty gazetteer has no closest id");
const auto invalid = locations.find_closest(std::numeric_limits<double>::quiet_NaN(), 0.0);
assert_equal(true, core::is_empty(invalid.place), "invalid lookup has no closest place");
const auto country = locations.find_country(std::numeric_limits<double>::quiet_NaN(), 0.0);
assert_equal(0u, country.code, "invalid country lookup has no country code");
}
static void should_find_places_across_the_antimeridian_and_poles()
{
auto& locations = test_locations();
const auto seam = locations.find_closest(66.323, 179.9);
assert_equal("Egvekinot"s, std::string(seam.place.sv()), "nearest lookup wraps across the antimeridian");
const auto attributed = locations.find_attributed(66.323, 179.9);
assert_equal("Egvekinot"s, std::string(attributed.nearest.place.sv()),
"attribution starts from the wrapped nearest place");
assert_equal(180.0, location_longitude_span_degrees(89.9, 100.0),
"a polar attribution radius conservatively spans every longitude");
assert_equal(true, location_longitude_span_degrees(0.0, 100.0) < 1.0, "ordinary midlatitude bounds stay narrow");
}
// Records are read back through a mapping that load_index drops and rebuilds, and the index is
// appended to rather than assigned, so a reload is the case where both a stale mapping and a
// doubled index would first show up.
static void should_reload_location_index()
{
auto& locations = test_locations();
const core::scope_exit restore_language([&locations] { locations.set_display_language({}); });
const auto default_location = gps_coordinate(51.5255317687988, -0.116743430495262); // London
const auto before = locations.auto_complete("london", 8, default_location);
assert_equal(true, !before.empty(), "predictions before reload");
locations.load_index();
assert_equal(true, locations.is_index_loaded(), "index is loaded again after a reload");
// A record read after the reload proves the read-back mapping was re-established, not just
// that the offsets survived.
assert_equal("City of London", locations.find_by_id(2643741).place, "id lookup survives a reload");
assert_equal("London", locations.find_largest(51.3, -0.5, 51.7, 0.3).place, "bounds lookup survives a reload");
assert_equal("Boulder City", locations.find_closest(35.9786, -114.8325).place, "reverse geocode survives a reload");
const auto after = locations.auto_complete("london", 8, default_location);
assert_equal(before.size(), after.size(), "reload does not change the number of predictions");
assert_equal("London, United Kingdom", after[0].location.str(), "reload keeps the top prediction");
}
#ifndef _DEBUG
static void should_find_closest_location()
{
const auto& locations = test_locations();
assert_equal("Bread Street", locations.find_closest(51.5142, -000.0985).place, "City");
assert_equal("Armidale", locations.find_closest(-30.515, 151.665).place, "City");
assert_equal("Johannesburg", locations.find_closest(-26.204444, 28.045556).place, "City");
assert_equal("Santiago", locations.find_closest(-33.45, -70.666667).place, "City");
assert_equal("Eastern Parkway", locations.find_closest(40.664167, -73.938611).place, "City");
assert_equal("Beijing", locations.find_closest(39.913889, 116.391667).place, "City");
}
#endif
static void should_offset_localized_name()
{
// Issue #119: bit unset (or no language selected) resolves to the default name (offset 0).
assert_equal(0, location_localized_name_offset(0u, 2), "no bits set");
assert_equal(0, location_localized_name_offset(0b0010u, 2), "requested bit unset");
assert_equal(0, location_localized_name_offset(0xFFFFFFFFu, -1), "no language selected");
assert_equal(0, location_localized_name_offset(0xFFFFFFFFu, 32), "bit out of range");
// Only the requested bit set -> first localized name (offset 1).
assert_equal(1, location_localized_name_offset(0b0001u, 0), "first bit");
assert_equal(1, location_localized_name_offset(0b0100u, 2), "single higher bit");
// Lower set bits push the localized name further along, one column per earlier name.
assert_equal(2, location_localized_name_offset(0b0101u, 2), "one lower bit");
assert_equal(3, location_localized_name_offset(0b0111u, 2), "two lower bits");
// Highest bit works and counts all lower set bits.
assert_equal(1, location_localized_name_offset(1u << 31, 31), "top bit alone");
assert_equal(2, location_localized_name_offset((1u << 31) | 1u, 31), "top bit with one lower");
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Place naming and attribution
///////////////////////////////////////////////////////////////////////////////////////////////////
static void should_read_place_qualification_level()
{
// locations.md 2.1/2.2: the flags column carries the smallest name form that identifies
// the place. Levels are assigned by tools/generate_locations.py over the emitted records.
auto& locations = test_locations();
const auto level = [&locations](const std::string_view query)
{
return static_cast<int>(locations.find_by_name(query).qualification());
};
// A name held by exactly one record needs no qualifier.
assert_equal(0, level("Reykjavík"), "unique name is level 0");
assert_equal(0, level("Ouagadougou"), "unique name is level 0");
// London collides across countries but is unique within each, so the country is enough.
assert_equal(1, level("London"), "name unique within its country is level 1");
assert_equal(1, level("London, Canada"), "the qualifier does not change the level");
// Springfield and Toronto collide inside one country, so the region is also needed.
assert_equal(2, level("Springfield"), "name repeated within a country is level 2");
assert_equal(2, level("Toronto"), "name repeated within a country is level 2");
// Populated places are never extent features; bits 3-31 are reserved and read as zero.
assert_equal(false, locations.find_by_name("London").is_extent(), "a place is not an extent feature");
assert_equal(false, locations.find_by_name("Reykjavík").is_extent(), "a place is not an extent feature");
// The reserved level encoding 3 degrades to level 2, so a newer file over-qualifies
// rather than mislabels.
location_t reserved;
reserved.flags = 3u;
assert_equal(2, static_cast<int>(reserved.qualification()), "reserved level reads as level 2");
location_t extent;
extent.flags = location_flag_extent;
assert_equal(0, static_cast<int>(extent.qualification()), "the extent bit does not disturb the level");
assert_equal(true, extent.is_extent(), "the extent bit is readable");
}
static void should_compose_qualified_place_name()
{
// locations.md 2.3: one composer, driven by the qualification level, using the country's
// short common form.
auto& locations = test_locations();
const auto name = [&locations](const std::string_view query)
{
return qualified_name(locations.find_by_name(query));
};
// Level 0 carries no qualifier at all.
assert_equal("Reykjavík"s, name("Reykjavík"), "level 0 is the bare name");
assert_equal("King of Prussia"s, name("King of Prussia"), "level 0 is the bare name");
// Level 1 adds the country and nothing else, so the region is omitted even though it is known.
assert_equal("London, United Kingdom"s, name("London"), "level 1 is name and country");
assert_equal("London, Canada"s, name("London, Canada"), "level 1 is name and country");
assert_equal("Birmingham, United Kingdom"s, name("Birmingham, United Kingdom"), "level 1 is name and country");
// The short common form, not the long official one.
assert_equal("United Kingdom"s, std::string(locations.find_by_name("London").country.sv()),
"the country is the short common form");
// Level 2 needs the region to separate same-country namesakes.
assert_equal("Reno, Nevada, United States"s, name("Reno, Nevada"), "level 2 is name, region and country");
// A repeated part is dropped and the level is treated as satisfied.
location_t city_state;
city_state.place = "Singapore"_c;
city_state.state = "Singapore"_c;
city_state.country = "Singapore"_c;
city_state.flags = 2u;
assert_equal("Singapore"s, qualified_name(city_state), "a city-state does not repeat itself");
location_t place_is_region;
place_is_region.place = "Luxembourg"_c;
place_is_region.state = "Luxembourg"_c;
place_is_region.country = "Luxembourg"_c;
place_is_region.flags = 2u;
assert_equal("Luxembourg"s, qualified_name(place_is_region), "a place equal to its region does not repeat it");
// A record with no place name still labels itself.