-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
osm.el
1838 lines (1673 loc) · 69.1 KB
/
osm.el
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
;;; osm.el --- OpenStreetMap viewer -*- lexical-binding: t -*-
;; Copyright (C) 2022-2024 Free Software Foundation, Inc.
;; Author: Daniel Mendler <mail@daniel-mendler.de>
;; Maintainer: Daniel Mendler <mail@daniel-mendler.de>
;; Created: 2022
;; Version: 1.5
;; Package-Requires: ((emacs "28.1") (compat "30"))
;; URL: https://github.com/minad/osm
;; Keywords: network, multimedia, hypermedia, mouse
;; This file is part of GNU Emacs.
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Osm.el is a tile-based map viewer, with a responsive movable and
;; zoomable display. The map can be controlled with the keyboard or with
;; the mouse. The viewer fetches the map tiles in parallel from tile
;; servers via the `curl' program. The package comes with a list of
;; multiple preconfigured tile servers. You can bookmark your favorite
;; locations using regular Emacs bookmarks or create links from Org files
;; to locations. Furthermore the package provides commands to measure
;; distances, search for locations by name and to open and display GPX
;; tracks.
;; osm.el requires Emacs 28 and depends on the external `curl' program.
;; Emacs must be built with libxml, libjansson, librsvg, libjpeg and
;; libpng support.
;;; Code:
(require 'compat)
(require 'bookmark)
(require 'dom)
(eval-when-compile
(require 'cl-lib)
(require 'subr-x))
(defgroup osm nil
"OpenStreetMap viewer."
:link '(info-link :tag "Info Manual" "(osm)")
:link '(url-link :tag "Website" "https://github.com/minad/osm")
:link '(url-link :tag "Wiki" "https://github.com/minad/osm/wiki")
:link '(emacs-library-link :tag "Library Source" "osm.el")
:group 'web
:prefix "osm-")
(defcustom osm-curl-options
"--disable --fail --location --silent --max-time 30"
"Curl command line options."
:type 'string)
(defcustom osm-search-language "en"
"Language used for search results.
Use RFC 1766 abbreviations, e.g.: `en' for English, `de' for German.
A comma-separated specifies descending order of preference. See also
`url-mime-language-string'."
:type 'string)
(defcustom osm-search-server
"https://nominatim.openstreetmap.org"
"Server used to search for location names.
The server must offer the nominatim.org API."
:type 'string)
(defcustom osm-server-defaults
'(:min-zoom 2
:max-zoom 19
:download-batch 4
:max-connections 2
:subdomains ("a" "b" "c"))
"Default server properties.
See also `osm-server-list'."
:type 'plist)
(defcustom osm-server-list
'((default
:name "Carto"
:description "Standard Carto map provided by OpenStreetMap"
:url "https://%s.tile.openstreetmap.org/%z/%x/%y.png"
:group "Standard"
:copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors"
"Map style © {OpenStreetMap Standard|https://www.openstreetmap.org/copyright}"))
(de
:name "Carto(de)"
:description "Localized Carto map provided by OpenStreetMap Germany"
:url "https://%s.tile.openstreetmap.de/%z/%x/%y.png"
:group "Standard"
:copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors"
"Map style © {OpenStreetMap Deutschland|https://www.openstreetmap.de/germanstyle.html}"))
(fr
:name "Carto(fr)"
:description "Localized Carto map by OpenStreetMap France"
:url "https://%s.tile.openstreetmap.fr/osmfr/%z/%x/%y.png"
:group "Standard"
:copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors"
"Map style © {OpenStreetMap France|https://www.openstreetmap.fr/mentions-legales/}"))
(humanitarian
:name "Humanitarian"
:description "Humanitarian map provided by OpenStreetMap France"
:url "https://%s.tile.openstreetmap.fr/hot/%z/%x/%y.png"
:group "Special Purpose"
:copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors"
"Map style © {Humanitarian OpenStreetMap Team|https://www.hotosm.org/updates/2013-09-29_a_new_window_on_openstreetmap_data}"))
(cyclosm
:name "CyclOSM"
:description "Bicycle-oriented map provided by OpenStreetMap France"
:url "https://%s.tile-cyclosm.openstreetmap.fr/cyclosm/%z/%x/%y.png"
:group "Transportation"
:copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors"
"Map style © {CyclOSM|https://www.cyclosm.org/} contributors"))
(openriverboatmap
:name "OpenRiverBoatMap"
:description "Waterways map provided by OpenStreetMap France"
:url "https://%s.tile.openstreetmap.fr/openriverboatmap/%z/%x/%y.png"
:group "Transportation"
:copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors"
"Map style © {OpenRiverBoatMap|https://github.com/tilery/OpenRiverboatMap}"))
(opentopomap
:name "OpenTopoMap"
:description "Topographical map provided by OpenTopoMap"
:url "https://%s.tile.opentopomap.org/%z/%x/%y.png"
:group "Topographical"
:copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors"
"Map style © {OpenTopoMap|https://www.opentopomap.org} ({CC-BY-SA|https://creativecommons.org/licenses/by-sa/3.0/})"
"Elevation data: {SRTM|https://www2.jpl.nasa.gov/srtm/}"))
(opvn
:name "ÖPNV" :max-zoom 18
:description "Base layer with public transport information"
:url "http://%s.tile.memomaps.de/tilegen/%z/%x/%y.png"
:group "Transportation"
:copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors"
"Map style © {ÖPNVKarte|https://www.öpnvkarte.de}")))
"List of tile servers.
Allowed keys:
:name Server name
:description Server description
:copyright Copyright information
:group Name of server groups for related servers
:url Url with placeholders
:ext File name extension
:min-zoom Minimum zoom level
:max-zoom Maximum zoom level
:download-batch Number of tiles downloaded via a single connection
:max-connections Maximum number of parallel connections
:subdomains Subdomains used for the %s placeholder
See also `osm-server-defaults' for default values used for a
server if the property is missing.
The :url of each server should specify %x, %y, %z and %s placeholders
for the map coordinates. It can optionally use an %s placeholder
for the subdomain and a %k placeholder for an apikey. The apikey
will be retrieved via `auth-source-search' with the :host set to
the domain name and the :user to the string \"apikey\"."
:type '(alist :key-type symbol :value-type plist))
(defcustom osm-copyright t
"Display the copyright information above the map."
:type 'boolean)
(defcustom osm-pin-colors
'((osm-selected . "#e20")
(osm-bookmark . "#f80")
(osm-poi . "#88f")
(osm-home . "#80f")
(osm-track . "#00a"))
"Colors of pins."
:type '(alist :key-type symbol :value-type string))
(defcustom osm-track-style
"stroke:#00a;stroke-width:5;stroke-linejoin:round;stroke-linecap:round;opacity:0.4;"
"SVG style used to draw tracks."
:type 'string)
(defcustom osm-home
(let ((lat (bound-and-true-p calendar-latitude))
(lon (bound-and-true-p calendar-longitude)))
(if (and lat lon)
(list lat lon 12)
(list 0 0 3)))
"Home coordinates, latitude, longitude and zoom level."
:type '(list :tag "Coordinates"
(number :tag "Latitude ")
(number :tag "Longitude ")
(number :tag "Zoom ")))
(defcustom osm-large-step 256
"Scroll step in pixel."
:type 'natnum)
(defcustom osm-tile-border nil
"Set to t to display thin tile borders.
For debugging set the value to `debug', such that a border is
shown around SVG tiles."
:type '(choice boolean (const debug)))
(defcustom osm-small-step 16
"Scroll step in pixel."
:type 'natnum)
(defcustom osm-server 'default
"Tile server name."
:type 'symbol)
(defcustom osm-tile-directory
(expand-file-name (file-name-concat
(or (getenv "XDG_CACHE_HOME") "~/.cache/")
"emacs/osm/"))
"Tile cache directory."
:type 'string)
(defcustom osm-max-age 14
"Maximum tile age in days.
Should be at least 7 days according to the server usage policies."
:type '(choice (const nil) natnum))
(defcustom osm-max-tiles 256
"Number of tiles to keep in the memory cache."
:type '(choice (const nil) natnum))
(defun osm--menu-item (menu)
"Generate menu item from MENU."
`(menu-item
"" nil :filter
,(lambda (&optional _)
(select-window
(posn-window
(event-start last-input-event)))
(if (functionp menu)
(funcall menu)
menu))))
(defun osm--mouse-ignore-wheel (_prompt)
"Ignore mouse wheel events during key translation."
(pcase (this-single-command-raw-keys)
((and `[,e]
(let y (event-basic-type e))
(guard (symbolp y))
(guard (string-search "wheel-" (symbol-name y))))
[])
(k k)))
(defvar-keymap osm-prefix-map
:doc "Global prefix map of OSM entry points."
"h" #'osm-home
"s" #'osm-search
"v" #'osm-server
"t" #'osm-goto
"j" #'osm-jump
"x" #'osm-gpx-show
"X" #'osm-gpx-hide)
;;;###autoload (autoload 'osm-prefix-map "osm" nil t 'keymap)
(defalias 'osm-prefix-map osm-prefix-map)
(defvar-keymap osm-mode-map
:doc "Keymap used by `osm-mode'."
:parent (make-composed-keymap osm-prefix-map special-mode-map)
"<home>" #'osm-home
"+" #'osm-zoom-in
"-" #'osm-zoom-out
"SPC" #'osm-zoom-in
"S-SPC" #'osm-zoom-out
"<mouse-1>" #'osm-mouse-pin
"<mouse-2>" 'org-store-link
"<mouse-3>" #'osm-bookmark-set
"S-<down-mouse-1>" #'ignore
"S-<mouse-1>" #'osm-mouse-track
"<down-mouse-1>" #'osm-mouse-drag
"<down-mouse-2>" #'osm-mouse-drag
"<down-mouse-3>" #'osm-mouse-drag
"<drag-mouse-1>" #'ignore
"<drag-mouse-2>" #'ignore
"<drag-mouse-3>" #'ignore
"<up>" #'osm-up
"<down>" #'osm-down
"<left>" #'osm-left
"<right>" #'osm-right
"C-<up>" #'osm-up-up
"C-<down>" #'osm-down-down
"C-<left>" #'osm-left-left
"C-<right>" #'osm-right-right
"M-<up>" #'osm-up-up
"M-<down>" #'osm-down-down
"M-<left>" #'osm-left-left
"M-<right>" #'osm-right-right
"S-<up>" #'osm-up-up
"S-<down>" #'osm-down-down
"S-<left>" #'osm-left-left
"S-<right>" #'osm-right-right
"n" #'osm-rename
"d" #'osm-delete
"DEL" #'osm-delete
"<deletechar>" #'osm-delete
"c" #'osm-center
"o" #'clone-buffer
"u" #'osm-save-url
"l" 'org-store-link
"b" #'osm-bookmark-set
"X" #'osm-gpx-hide
"<remap> <scroll-down-command>" #'osm-down
"<remap> <scroll-up-command>" #'osm-up
"<" nil
">" nil)
(dolist (pin osm-pin-colors)
(setq pin (vector (car pin)))
(define-key key-translation-map pin #'osm--mouse-ignore-wheel)
(define-key osm-mode-map pin #'osm-mouse-select))
(easy-menu-define osm-mode-menu osm-mode-map
"Menu for `osm-mode'."
'("OSM"
["Go home" osm-home]
["Center" osm-center]
["Go to coordinates" osm-goto]
["Jump to pin" osm-jump]
["Search by name" osm-search]
["Change tile server" osm-server]
"--"
["Org Link" org-store-link]
["Geo Url" osm-save-url]
["Elisp Link" (osm-save-url t)]
("Bookmark"
["Set" osm-bookmark-set]
["Jump" osm-bookmark-jump]
["Rename" osm-bookmark-rename]
["Delete" osm-bookmark-delete])
"--"
["Show GPX file" osm-gpx-show]
["Hide GPX file" osm-gpx-hide]
"--"
["Clone buffer" clone-buffer]
["Revert buffer" revert-buffer]
"--"
["Manual" (info "(osm)")]
["Customize" (customize-group 'osm)]))
(defconst osm--placeholder
'(:type svg :width 256 :height 256
:data "<svg width='256' height='256' version='1.1' xmlns='http://www.w3.org/2000/svg'>
<defs>
<pattern id='grid' width='16' height='16' patternUnits='userSpaceOnUse'>
<path d='m 0 0 l 0 16 16 0' fill='none' stroke='#888888'/>
</pattern>
</defs>
<rect width='256' height='256' fill='url(#grid)'/>
</svg>")
"Placeholder image for tiles.")
(defvar osm--search-history nil
"Minibuffer history used by command `osm-search'.")
(defvar osm--jump-history nil
"Minibuffer history used by command `osm-jump'.")
(defvar osm--server-history nil
"Minibuffer history used by command `osm-server'.")
(defvar osm--purge-directory 0
"Last time the tile cache was cleaned.")
(defvar osm--tile-cache nil
"Global tile memory cache.")
(defvar osm--tile-age 0
"Tile age, incremented on every update.")
(defvar osm--gpx-files nil
"Global list of loaded tracks.")
(defvar osm--track nil
"List of track coordinates.")
(defvar osm--download-processes nil
"Globally active download processes.")
(defvar osm--download-active nil
"Globally active download jobs.")
(defvar osm--download-subdomain nil
"Subdomain indices to query the servers in a round-robin fashion.")
(defvar-local osm--download-queue nil
"Buffer-local tile download queue.")
(defvar-local osm--wx 0
"Half window width in pixel.")
(defvar-local osm--wy 0
"Half window height in pixel.")
(defvar-local osm--nx 0
"Number of tiles in x direction.")
(defvar-local osm--ny 0
"Number of tiles in y direction.")
(defvar-local osm--zoom nil
"Zoom level of the map.")
(defvar-local osm--lat nil
"Latitude coordinate.")
(defvar-local osm--lon nil
"Longitude coordinate.")
(defvar-local osm--overlays nil
"Overlay hash table.
Local per buffer since the overlays depend on the zoom level.")
(defvar-local osm--pin nil
"Currently selected pin.")
(defmacro osm--each (&rest body)
"Execute BODY in each `osm-mode' buffer."
(cl-with-gensyms (buf)
`(dolist (,buf (buffer-list))
(when (eq (buffer-local-value 'major-mode ,buf) #'osm-mode)
(with-current-buffer ,buf
,@body)))))
(defun osm--server-menu ()
"Generate server menu."
(let (menu last-group)
(dolist (server osm-server-list)
(let* ((plist (cdr server))
(group (plist-get plist :group)))
(unless (equal last-group group)
(push (format "─── %s ───" group) menu)
(setq last-group group))
(push
`[,(plist-get plist :name)
(osm-server ',(car server))
:style toggle
:selected (eq osm-server ',(car server))]
menu)))
(easy-menu-create-menu "Server" (nreverse menu))))
(defsubst osm--lon-to-normalized-x (lon)
"Convert LON to normalized x coordinate."
(/ (+ lon 180.0) 360.0))
(defsubst osm--lat-to-normalized-y (lat)
"Convert LAT to normalized y coordinate."
(setq lat (* lat (/ float-pi 180.0)))
(- 0.5 (/ (log (+ (tan lat) (/ 1.0 (cos lat)))) float-pi 2)))
(defun osm--boundingbox-to-zoom (lat1 lat2 lon1 lon2)
"Compute zoom level from boundingbox LAT1 to LAT2 and LON1 to LON2."
(let ((w (/ (frame-pixel-width) 256))
(h (/ (frame-pixel-height) 256)))
(max (osm--server-property :min-zoom)
(min
(osm--server-property :max-zoom)
(min (logb (/ w (abs (- (osm--lon-to-normalized-x lon1) (osm--lon-to-normalized-x lon2)))))
(logb (/ h (abs (- (osm--lat-to-normalized-y lat1) (osm--lat-to-normalized-y lat2))))))))))
(defun osm--x-to-lon (x zoom)
"Return longitude in degrees for X/ZOOM."
(- (/ (* x 360.0) 256.0 (expt 2.0 zoom)) 180.0))
(defun osm--y-to-lat (y zoom)
"Return latitude in degrees for Y/ZOOM."
(setq y (* float-pi (- 1 (* 2 (/ y 256.0 (expt 2.0 zoom))))))
(/ (* 180 (atan (/ (- (exp y) (exp (- y))) 2))) float-pi))
(defsubst osm--lon-to-x (lon zoom)
"Convert LON/ZOOM to x coordinate in pixel."
(floor (* 256 (expt 2.0 zoom) (osm--lon-to-normalized-x lon))))
(defsubst osm--lat-to-y (lat zoom)
"Convert LAT/ZOOM to y coordinate in pixel."
(floor (* 256 (expt 2.0 zoom) (osm--lat-to-normalized-y lat))))
(defsubst osm--x ()
"Return longitude in pixel of map center."
(osm--lon-to-x osm--lon osm--zoom))
(defsubst osm--y ()
"Return latitude in pixel of map center."
(osm--lat-to-y osm--lat osm--zoom))
(defsubst osm--x0 ()
"Return longitude in pixel of top left corner."
(- (osm--x) osm--wx))
(defsubst osm--y0 ()
"Return latitude in pixel of top left corner."
(- (osm--y) osm--wy))
(defun osm--server-property (prop &optional server)
"Return server property PROP for SERVER."
(or (plist-get (alist-get (or server osm-server) osm-server-list) prop)
(plist-get osm-server-defaults prop)))
(defun osm--tile-url (x y zoom)
"Return tile url for coordinate X, Y and ZOOM."
(let ((url (osm--server-property :url))
(sub (osm--server-property :subdomains))
(key (osm--server-property :key)))
(when (and (string-search "%k" url) (not key))
(require 'auth-source)
(declare-function auth-source-search "auth-source")
(let ((host (string-join
(last (split-string (cadr (split-string url "/" t)) "\\.") 2)
".")))
(setq key (plist-get
(car (auth-source-search :require '(:user :host :secret)
:host host
:user "apikey"))
:secret))
(unless key
(warn "No auth source secret found for apikey@%s" host)
(setq key ""))
(setf (plist-get (alist-get osm-server osm-server-list) :key) key)))
(format-spec
url `((?z . ,zoom) (?x . ,x) (?y . ,y)
(?k . ,(if (functionp key) (funcall key) key))
(?s . ,(nth (mod (alist-get osm-server osm--download-subdomain 0)
(length sub))
sub))))))
(defun osm--tile-file (x y zoom)
"Return tile file name for coordinate X, Y and ZOOM."
(file-name-concat
(expand-file-name osm-tile-directory)
(symbol-name osm-server)
(format "%d-%d-%d.%s"
zoom x y
(or (osm--server-property :ext)
(file-name-extension
(url-file-nondirectory
(osm--server-property :url)))))))
(defun osm--enqueue-download (x y)
"Enqueue tile X/Y for download."
(when (let ((n (expt 2 osm--zoom))) (and (>= x 0) (>= y 0) (< x n) (< y n)))
(let ((job (list osm-server osm--zoom x y)))
(unless (or (member job osm--download-queue) (member job osm--download-active))
(setq osm--download-queue (nconc osm--download-queue (list job)))))))
(defun osm--download-filter (output)
"Filter function for the download process which receives OUTPUT."
(while (string-match
"\\`\\([0-9]+\\) \\(.*?/\\([^/]+\\)/\\([0-9]+\\)-\\([0-9]+\\)-\\([0-9]+\\)\\.[^\r\n]+\\)\r?\n"
output)
(let ((status (match-string 1 output))
(file (match-string 2 output))
(server (intern-soft (match-string 3 output)))
(zoom (string-to-number (match-string 4 output)))
(x (string-to-number (match-string 5 output)))
(y (string-to-number (match-string 6 output))))
(setq output (substring output (match-end 0)))
(when (equal status "200")
(ignore-errors (rename-file file (string-remove-suffix ".tmp" file) t))
(osm--each
(when (and (= osm--zoom zoom) (eq osm-server server))
(osm--display-tile x y (osm--get-tile x y)))))
(cl-callf2 delete (list server zoom x y) osm--download-active)
(delete-file file)))
output)
(defun osm--download-command ()
"Build download command."
(let* ((count 0)
(batch (osm--server-property :download-batch))
(subs (length (osm--server-property :subdomains)))
(parallel (* subs (osm--server-property :max-connections)))
args jobs job)
(while (and (< count batch)
(setq job (nth (* count parallel) osm--download-queue)))
(pcase-let ((`(,_server ,zoom ,x ,y) job))
(setq args `(,(osm--tile-url x y zoom)
,(concat (osm--tile-file x y zoom) ".tmp")
"--output"
,@args))
(push job jobs)
(push job osm--download-active)
(cl-incf count)))
(osm--each
(dolist (job jobs)
(cl-callf2 delq job osm--download-queue)))
(cl-callf (lambda (s) (mod (1+ s) subs))
(alist-get osm-server osm--download-subdomain 0))
(cons `("curl" "--write-out" "%{http_code} %{filename_effective}\n"
,@(split-string-and-unquote osm-curl-options) ,@(nreverse args))
jobs)))
(defun osm--download ()
"Download next tiles from the queue."
(when (and (< (length (alist-get osm-server osm--download-processes))
(* (length (osm--server-property :subdomains))
(osm--server-property :max-connections)))
osm--download-queue)
(pcase-let ((`(,command . ,jobs) (osm--download-command))
(dir (file-name-concat (expand-file-name osm-tile-directory)
(symbol-name osm-server)))
(server osm-server))
(make-directory dir t)
(push
(make-process
:name "*osm curl*"
:connection-type 'pipe
:noquery t
:command command
:filter
(let ((output ""))
(lambda (_proc out)
(setq output (osm--download-filter (concat output out)))
(force-mode-line-update t)))
:sentinel
(lambda (proc _status)
(dolist (job jobs)
(cl-callf2 delq job osm--download-active))
(cl-callf2 delq proc (alist-get server osm--download-processes nil t))
(force-mode-line-update t)
(osm--download)))
(alist-get server osm--download-processes))
(force-mode-line-update t)
(osm--download))))
(defun osm-mouse-drag (event)
"Handle drag EVENT."
(declare (completion ignore))
(interactive "@e")
(pcase-let* ((`(,sx . ,sy) (posn-x-y (event-start event)))
(win (selected-window))
(map (define-keymap
"<mouse-movement>"
(lambda (event)
(interactive "e")
(setq event (event-start event))
(when (eq win (posn-window event))
(pcase-let ((`(,ex . ,ey) (posn-x-y event)))
(osm--move (- sx ex) (- sy ey))
(setq sx ex sy ey)
(osm--update)))))))
(setq track-mouse 'dragging)
(set-transient-map map
(lambda () (eq (car-safe last-input-event) 'mouse-movement))
(lambda () (setq track-mouse nil)))))
(defun osm--zoom-in-wheel (_n)
"Zoom in with the mouse wheel."
(pcase-let ((`(,x . ,y) (posn-x-y (event-start last-input-event))))
(when (< osm--zoom (osm--server-property :max-zoom))
(osm--move (/ (- x osm--wx) 2) (/ (- y osm--wy) 2))
(osm-zoom-in))))
(defun osm--zoom-out-wheel (_n)
"Zoom out with the mouse wheel."
(pcase-let ((`(,x . ,y) (posn-x-y (event-start last-input-event))))
(when (> osm--zoom (osm--server-property :min-zoom))
(osm--move (- osm--wx x) (- osm--wy y))
(osm-zoom-out))))
(defun osm-center ()
"Center to location of selected pin."
(interactive nil osm-mode)
(osm--barf-unless-osm)
(pcase osm--pin
(`(,lat ,lon ,_id ,name)
(setq osm--lat lat osm--lon lon)
(message "%s" name)
(osm--update))))
(defun osm--haversine (lat1 lon1 lat2 lon2)
"Compute distance between LAT1/LON1 and LAT2/LON2 in km."
;; https://en.wikipedia.org/wiki/Haversine_formula
(let* ((rad (/ float-pi 180))
(y (sin (* 0.5 rad (- lat2 lat1))))
(x (sin (* 0.5 rad (- lon2 lon1))))
(h (+ (* x x) (* (cos (* rad lat1)) (cos (* rad lat2)) y y))))
(* 2 6371 (atan (sqrt h) (sqrt (- 1 h))))))
(defun osm-mouse-track (event)
"Set track pin at location of the click EVENT."
(declare (completion ignore))
(interactive "@e")
(pcase osm--pin
((and (guard (not osm--track)) `(,lat ,lon ,_id ,_name))
(push (list lat lon "WP1") osm--track)))
(osm--set-pin-event event 'osm-track
(format "WP%s" (1+ (length osm--track))) 'quiet)
(pcase-let ((`(,lat ,lon ,_id ,name) osm--pin))
(push (list lat lon name) osm--track))
(osm--revert)
(osm--track-length))
(defun osm--track-length ()
"Echo track length."
(when (cdr osm--track)
(pcase-let* ((len1 0)
(len2 0)
(p osm--track)
(`(,sel-lat ,sel-lon ,_ ,sel-name) osm--pin))
(while (and (cdr p) (not (and (equal (caar p) sel-lat)
(equal (cadar p) sel-lon))))
(cl-incf len2 (osm--haversine (caar p) (cadar p)
(caadr p) (cadadr p)))
(pop p))
(while (cdr p)
(cl-incf len1 (osm--haversine (caar p) (cadar p)
(caadr p) (cadadr p)))
(pop p))
(message "%s way points, length %.2fkm, %s"
(length osm--track) (+ len1 len2)
(if (or (= len1 0) (= len2 0))
sel-name
(format "%.2fkm → %s → %.2fkm"
len1 sel-name len2))))))
(defun osm--pin-at (event &optional type)
"Get pin of TYPE at EVENT."
(let* ((xy (posn-x-y (event-start event)))
(x (+ (osm--x0) (car xy)))
(y (+ (osm--y0) (cdr xy)))
(min most-positive-fixnum)
found)
(dolist (pin (car (osm--get-overlays (/ x 256) (/ y 256))))
(pcase-let ((`(,p ,q ,_lat ,_lon ,id ,_name) pin))
(when (or (not type) (eq type id))
(let ((d (+ (* (- p x) (- p x)) (* (- q y) (- q y)))))
(when (and (>= q y) (< q (+ y 50)) (>= p (- x 20)) (< p (+ x 20)) (< d min))
(setq min d found pin))))))
(cddr found)))
(defun osm-mouse-pin (event)
"Create location pin at the click EVENT."
(declare (completion ignore))
(interactive "@e")
(osm--set-pin-event event)
(osm--update))
(defun osm-mouse-select (event)
"Select pin at position of click EVENT."
(declare (completion ignore))
(interactive "@e")
(when (memq (event-basic-type event) '(mouse-1 mouse-2 mouse-3))
(pcase (osm--pin-at event)
(`(,lat ,lon ,id ,name)
(osm--set-pin id lat lon name (eq id 'osm-track))
(when (eq id 'osm-track) (osm--track-length))
(osm--update)))))
(defun osm-zoom-in (&optional n)
"Zoom N times into the map."
(interactive "p" osm-mode)
(osm--barf-unless-osm)
(setq osm--zoom (max (osm--server-property :min-zoom)
(min (osm--server-property :max-zoom)
(+ osm--zoom (or n 1)))))
(osm--update))
(defun osm-zoom-out (&optional n)
"Zoom N times out of the map."
(interactive "p" osm-mode)
(osm-zoom-in (- (or n 1))))
(defun osm--move (dx dy)
"Move by DX/DY."
(osm--barf-unless-osm)
(setq osm--lon (osm--x-to-lon (+ (osm--x) dx) osm--zoom)
osm--lat (osm--y-to-lat (+ (osm--y) dy) osm--zoom)))
(defun osm-right (&optional n)
"Move N small steps to the right."
(interactive "p" osm-mode)
(osm--move (* (or n 1) osm-small-step) 0)
(osm--update))
(defun osm-down (&optional n)
"Move N small steps down."
(interactive "p" osm-mode)
(osm--move 0 (* (or n 1) osm-small-step))
(osm--update))
(defun osm-up (&optional n)
"Move N small steps up."
(interactive "p" osm-mode)
(osm-down (- (or n 1))))
(defun osm-left (&optional n)
"Move N small steps to the left."
(interactive "p" osm-mode)
(osm-right (- (or n 1))))
(defun osm-right-right (&optional n)
"Move N large steps to the right."
(interactive "p" osm-mode)
(osm--move (* (or n 1) osm-large-step) 0)
(osm--update))
(defun osm-down-down (&optional n)
"Move N large steps down."
(interactive "p" osm-mode)
(osm--move 0 (* (or n 1) osm-large-step))
(osm--update))
(defun osm-up-up (&optional n)
"Move N large steps up."
(interactive "p" osm-mode)
(osm-down-down (- (or n 1))))
(defun osm-left-left (&optional n)
"Move N large steps to the left."
(interactive "p" osm-mode)
(osm-right-right (- (or n 1))))
(defun osm--purge-directory ()
"Clean tile directory."
(when (and (integerp osm-max-age)
(> (- (float-time) osm--purge-directory) (* 60 60 24)))
(setq osm--purge-directory (float-time))
(run-with-idle-timer
30 nil
(lambda ()
(dolist (dir (directory-files osm-tile-directory t "\\`[^.]+\\'" t))
(dolist (file (directory-files
dir t "\\.\\(?:png\\|jpe?g\\)\\(?:\\.tmp\\)?\\'" t))
(when (> (float-time (time-since
(file-attribute-modification-time
(file-attributes file))))
(* 60 60 24 osm-max-age))
(delete-file file)))
(when (directory-empty-p dir)
(ignore-errors (delete-directory dir))))))))
(defun osm--check-libraries ()
"Check that Emacs is compiled with the necessary libraries."
(let (req)
(unless (display-graphic-p)
(push "graphical display" req))
(dolist (type '(svg jpeg png))
(unless (image-type-available-p type)
(push (format "%s support" type) req)))
(unless (libxml-available-p)
(push "libxml" req))
(unless (json-available-p)
(push "libjansson" req))
(when req
(error "Osm: Please compile Emacs with the required libraries, %s needed to proceed"
(string-join req ", ")))))
(define-derived-mode osm-mode special-mode "Osm"
"OpenStreetMap viewer mode."
:interactive nil :abbrev-table nil :syntax-table nil
(osm--check-libraries)
(setq-local osm-server osm-server
line-spacing nil
cursor-type nil
cursor-in-non-selected-windows nil
left-fringe-width 1
right-fringe-width 1
left-margin-width 0
right-margin-width 0
truncate-lines t
show-trailing-whitespace nil
display-line-numbers nil
buffer-read-only t
fringe-indicator-alist '((truncation . nil))
revert-buffer-function #'osm--revert
mode-line-process '(:eval (osm--download-queue-info))
mode-line-position nil
mode-line-modified nil
mode-line-mule-info nil
mode-line-remote nil
default-directory (expand-file-name "~/")
eldoc-documentation-functions nil
mouse-wheel-progressive-speed nil
mwheel-scroll-up-function #'osm--zoom-out-wheel
mwheel-scroll-down-function #'osm--zoom-in-wheel
mwheel-scroll-left-function #'osm--zoom-out-wheel
mwheel-scroll-right-function #'osm--zoom-in-wheel
bookmark-make-record-function #'osm--bookmark-record-default)
(when (boundp 'mwheel-coalesce-scroll-events)
(setq-local mwheel-coalesce-scroll-events t))
(when (boundp 'pixel-scroll-precision-mode)
(setq-local pixel-scroll-precision-mode nil))
(add-hook 'change-major-mode-hook #'osm--barf-change-mode nil 'local)
(add-hook 'write-contents-functions #'osm--barf-write nil 'local)
(add-hook 'window-size-change-functions #'osm--resize nil 'local))
(defun osm--barf-write ()
"Barf for write operation."
(set-buffer-modified-p nil)
(setq buffer-read-only t)
(set-visited-file-name nil)
(error "Writing the buffer to a file is not supported"))
(defun osm--barf-change-mode ()
"Barf for change mode operation."
(error "Changing the major mode is not supported"))
(defun osm--barf-unless-osm ()
"Barf if not an `osm-mode' buffer."
(unless (eq major-mode #'osm-mode)
(error "Not an `osm-mode' buffer")))
(defun osm--each-pin (fun)
"Call FUN for each pin on the map."
(pcase osm-home
(`(,lat ,lon ,zoom)
(funcall fun 'osm-home lat lon zoom "Home")))
(bookmark-maybe-load-default-file)
(cl-loop for bm in bookmark-alist
if (eq (bookmark-prop-get bm 'handler) #'osm-bookmark-jump) do
(pcase-let ((`(,lat ,lon ,zoom) (bookmark-prop-get bm 'coordinates)))
(funcall fun 'osm-bookmark lat lon zoom (car bm))))
(dolist (file osm--gpx-files)
(cl-loop for (lat lon name) in (cddr file) do
(funcall fun 'osm-poi lat lon 15 name)))
(cl-loop for (lat lon name) in osm--track do
(funcall fun 'osm-track lat lon 15 name)))
(defun osm--pin-inside-p (x y lat lon)
"Return non-nil if pin at LAT/LON is inside tile X/Y."
(let ((p (/ (osm--lon-to-x lon osm--zoom) 256.0))
(q (/ (osm--lat-to-y lat osm--zoom) 256.0)))
(and (>= p (- x 0.125)) (< p (+ x 1.125))
(>= q y) (< q (+ y 1.25)))))
(defun osm--add-pin (pins id lat lon _zoom name)
"Add pin at LAT/LON with NAME and ID to the PINS hash table."
(let* ((x (osm--lon-to-x lon osm--zoom))
(y (osm--lat-to-y lat osm--zoom))
(x0 (/ x 256))
(y0 (/ y 256))
(pin (list x y lat lon id name)))
(push pin (gethash (cons x0 y0) pins))
(cl-loop
for i from -1 to 1 do
(cl-loop
for j from -1 to 0 do
(let ((x1 (/ (+ x (* 32 i)) 256))
(y1 (/ (+ y (* 64 j)) 256)))
(unless (and (= x0 x1) (= y0 y1))
(push pin (gethash (cons x1 y1) pins))))))))
;; TODO: The Bresenham algorithm used here to add the line segments to the tiles
;; has the issue that lines which go along a tile border may be drawn only
;; partially. Use a more precise algorithm instead.
(defun osm--add-track (tracks seg)
"Add track segment SEG to TRACKS hash table."
(when seg
(let ((p0 (cons (osm--lon-to-x (or (car-safe (cdar seg)) (cdar seg)) osm--zoom)
(osm--lat-to-y (caar seg) osm--zoom))))
(dolist (pt (cdr seg))
(let* ((px1 (cdr pt))
(px1 (osm--lon-to-x (if (consp px1) (car px1) px1) osm--zoom))
(py1 (osm--lat-to-y (car pt) osm--zoom))
(pdx (- px1 (car p0)))
(pdy (- py1 (cdr p0))))
;; Ignore point if too close to last point
(unless (< (+ (* pdx pdx) (* pdy pdy)) 50)
(let* ((p1 (cons px1 py1))
(line (cons p0 p1))
(x0 (/ (car p0) 256))
(y0 (/ (cdr p0) 256))
(x1 (/ px1 256))
(y1 (/ py1 256))
(sx (if (< x0 x1) 1 -1))
(sy (if (< y0 y1) 1 -1))
(dx (* sx (- x1 x0)))
(dy (* sy (- y0 y1)))
(err (+ dx dy)))
;; Bresenham
(while
(let ((ey (> (* err 2) dy))
(ex (< (* err 2) dx)))
(push line (gethash (cons x0 y0) tracks))
(unless (and (= x0 x1) (= y0 y1))
(when (and ey ex)
(push line (gethash (cons x0 (+ y0 sy)) tracks))
(push line (gethash (cons (+ x0 sx) y0) tracks)))
(when ey
(cl-incf err dy)
(cl-incf x0 sx))
(when ex
(cl-incf err dx)
(cl-incf y0 sy))
t)))
(setq p0 p1))))))))