feat(map-settings): 新增地图设置面板,支持底图偏好与离线瓦片下载

共享层新增 map_settings 模块,定义 Bounds、Region、Preferences 和
DownloadRequest 数据结构及验证逻辑,单次下载上限 20000 张瓦片。

前端新增独立地图设置视图,包含:
- 底图切换(影像/路网)与默认定位点配置
- 地图选点、框选下载范围交互
- 常用区域保存与离线下载任务管理

实时地图适配器改为从 Preferences 读取初始中心点和缩放级别,
使设置面板与工作台地图共享视图状态。

同时微调目标列表行高与 footer 布局,在紧凑模式下隐藏黑名单提示。
```
This commit is contained in:
2026-10-23 09:43:14 +08:00
parent df9e8bdeb5
commit 5e3c89fdf4
29 changed files with 2052 additions and 33 deletions
@@ -0,0 +1,25 @@
Source: https://github.com/Cyclenerd/offline-map-tile-downloader
Pinned revision: 9b61800537b2c50a71345dfed3bbc0fcd8731711
Adaptation: RID headless JSON adapter; Web Mercator tile algorithm retained.
MIT License
Copyright (c) 2025 Matthew Drummonds
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+3
View File
@@ -0,0 +1,3 @@
module rid-map-downloader
go 1.22.0
+225
View File
@@ -0,0 +1,225 @@
// RID headless adapter derived from Cyclenerd/offline-map-tile-downloader (MIT).
// Upstream: 9b61800537b2c50a71345dfed3bbc0fcd8731711. See LICENSE-upstream.txt.
// Retains its Web Mercator tile algorithm; replaces web UI with a bounded JSON job.
package main
import (
"bytes"
"encoding/json"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"math"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
type bounds struct{ West, South, East, North float64 }
type request struct {
Bounds bounds
MinZoom, MaxZoom int
Layers []string
Output, BaseURL string
}
type tile struct {
layer string
x, y, z uint32
}
type progress struct {
Done uint64 `json:"done"`
Failed uint64 `json:"failed"`
}
// latLonToTile is from the pinned MIT upstream; clamp at Mercator world edges.
func latLonToTile(lat, lon float64, zoom uint32) (x, y uint32) {
latRad := lat * math.Pi / 180
n := math.Pow(2, float64(zoom))
x = uint32(n * ((lon + 180) / 360))
y = uint32(n * (1 - (math.Log(math.Tan(latRad)+1/math.Cos(latRad)) / math.Pi)) / 2)
if x >= uint32(n) {
x = uint32(n) - 1
}
if y >= uint32(n) {
y = uint32(n) - 1
}
return
}
func coverage(r request) ([]tile, error) {
b := r.Bounds
for _, v := range []float64{b.West, b.East, b.South, b.North} {
if math.IsNaN(v) || math.IsInf(v, 0) {
return nil, fmt.Errorf("invalid bounds")
}
}
if b.West < -180 || b.East > 180 || b.South < -85.051128 || b.North > 85.051128 || b.West >= b.East || b.South >= b.North || r.MinZoom < 0 || r.MaxZoom > 18 || r.MinZoom > r.MaxZoom || len(r.Layers) == 0 || len(r.Layers) > 4 {
return nil, fmt.Errorf("invalid coverage")
}
seen := map[string]bool{}
for _, l := range r.Layers {
if seen[l] || !(l == "vec_w" || l == "cva_w" || l == "img_w" || l == "cia_w") {
return nil, fmt.Errorf("invalid layer")
}
seen[l] = true
}
var tiles []tile
for z := uint32(r.MinZoom); z <= uint32(r.MaxZoom); z++ {
x0, y0 := latLonToTile(b.North, b.West, z)
x1, y1 := latLonToTile(b.South, b.East, z)
if uint64(x1-x0+1)*uint64(y1-y0+1)*uint64(len(r.Layers))+uint64(len(tiles)) > 20000 {
return nil, fmt.Errorf("coverage exceeds limit")
}
for _, l := range r.Layers {
for x := x0; x <= x1; x++ {
for y := y0; y <= y1; y++ {
tiles = append(tiles, tile{l, x, y, z})
}
}
}
}
return tiles, nil
}
func validImage(data []byte) bool {
if len(data) == 0 || len(data) > 2*1024*1024 {
return false
}
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil || cfg.Width != 256 || cfg.Height != 256 {
return false
}
_, _, err = image.Decode(bytes.NewReader(data))
return err == nil
}
func safePath(path string) bool {
for p := filepath.Clean(path); ; p = filepath.Dir(p) {
info, err := os.Lstat(p)
if err == nil && info.Mode()&os.ModeSymlink != 0 {
return false
}
if err != nil && !os.IsNotExist(err) {
return false
}
if filepath.Dir(p) == p {
return true
}
}
}
func store(path string, data []byte) error {
if !safePath(path) {
return fmt.Errorf("symlink output denied")
}
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
f, err := os.CreateTemp(filepath.Dir(path), ".rid-map-*.tmp")
if err != nil {
return err
}
name := f.Name()
defer os.Remove(name)
if _, err = f.Write(data); err != nil {
f.Close()
return err
}
if err = f.Sync(); err != nil {
f.Close()
return err
}
if err = f.Close(); err != nil {
return err
}
return os.Rename(name, path)
}
func fetch(client *http.Client, r request, t tile) error {
path := filepath.Join(r.Output, t.layer, fmt.Sprint(t.z), fmt.Sprint(t.x), fmt.Sprintf("%d.png", t.y))
if !safePath(path) {
return fmt.Errorf("invalid output")
}
if info, err := os.Stat(path); err == nil && info.Size() <= 2*1024*1024 {
if data, err := os.ReadFile(path); err == nil && validImage(data) {
return nil
}
}
resp, err := client.Get(fmt.Sprintf("%s/%s/%d/%d/%d", strings.TrimRight(r.BaseURL, "/"), t.layer, t.z, t.x, t.y))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("tile unavailable")
}
data, err := io.ReadAll(io.LimitReader(resp.Body, 2*1024*1024+1))
if err != nil {
return err
}
if !validImage(data) {
return fmt.Errorf("invalid image")
}
return store(path, data)
}
func run(input io.Reader, output io.Writer) error {
var r request
d := json.NewDecoder(io.LimitReader(input, 65537))
d.DisallowUnknownFields()
if err := d.Decode(&r); err != nil {
return err
}
u, err := url.Parse(r.BaseURL)
if err != nil || u.Scheme != "http" || u.Hostname() != "127.0.0.1" || u.Port() == "" || u.Path != "/api/maps/tile" || u.RawQuery != "" || u.User != nil {
return fmt.Errorf("only local tile proxy is allowed")
}
if !filepath.IsAbs(r.Output) || !safePath(r.Output) {
return fmt.Errorf("invalid output")
}
tiles, err := coverage(r)
if err != nil {
return err
}
client := &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}
// A single ticker limits the whole pool, rather than each worker independently.
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
jobs := make(chan tile)
var wg sync.WaitGroup
var mu sync.Mutex
p := progress{}
encoder := json.NewEncoder(output)
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for t := range jobs {
<-ticker.C
err := fetch(client, r, t)
mu.Lock()
p.Done++
if err != nil {
p.Failed++
}
_ = encoder.Encode(p)
mu.Unlock()
}
}()
}
for _, t := range tiles {
jobs <- t
}
close(jobs)
wg.Wait()
if p.Failed > 0 {
return fmt.Errorf("some tiles failed")
}
return nil
}
func main() {
if err := run(os.Stdin, os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, "map download failed")
os.Exit(1)
}
}
+75
View File
@@ -0,0 +1,75 @@
package main
import (
"bytes"
"encoding/json"
"image"
"image/png"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
)
func TestCoverageBoundaries(t *testing.T) {
r := request{Bounds: bounds{120.15, 30.28, 120.16, 30.29}, MinZoom: 11, MaxZoom: 11, Layers: []string{"vec_w", "cva_w", "img_w", "cia_w"}}
tiles, err := coverage(r)
if err != nil || len(tiles) != 4 {
t.Fatalf("coverage %d %v", len(tiles), err)
}
r.Bounds = bounds{-180, -85, 180, 85}
r.MaxZoom = 18
if _, err = coverage(r); err == nil {
t.Fatal("excessive range accepted")
}
r.MaxZoom = 19
if _, err = coverage(r); err == nil {
t.Fatal("zoom accepted")
}
}
func TestDownloadValidatesAndResumes(t *testing.T) {
var imageBytes bytes.Buffer
_ = png.Encode(&imageBytes, image.NewRGBA(image.Rect(0, 0, 256, 256)))
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; w.Write(imageBytes.Bytes()) }))
defer server.Close()
r := request{Bounds: bounds{120.15, 30.28, 120.16, 30.29}, MinZoom: 11, MaxZoom: 11, Layers: []string{"vec_w"}, Output: t.TempDir(), BaseURL: server.URL + "/api/maps/tile"}
body, _ := json.Marshal(r)
var output bytes.Buffer
if err := run(bytes.NewReader(body), &output); err != nil {
t.Fatal(err)
}
files, _ := filepath.Glob(filepath.Join(r.Output, "vec_w", "11", "*", "*.png"))
if len(files) != 1 {
t.Fatalf("files %v", files)
}
if err := run(bytes.NewReader(body), &output); err != nil {
t.Fatal(err)
}
if calls != 1 {
t.Fatal("existing valid tile downloaded again")
}
_ = os.WriteFile(files[0], []byte("bad"), 0600)
if err := run(bytes.NewReader(body), &output); err != nil {
t.Fatal(err)
}
if calls != 2 {
t.Fatal("corrupt tile not replaced")
}
r.BaseURL = "https://example.com/api/maps/tile"
body, _ = json.Marshal(r)
if run(bytes.NewReader(body), &output) == nil {
t.Fatal("external endpoint accepted")
}
}
func TestRejectsBrokenImage(t *testing.T) {
if validImage([]byte("<html>error</html>")) {
t.Fatal("invalid image accepted")
}
var b bytes.Buffer
_ = png.Encode(&b, image.NewRGBA(image.Rect(0, 0, 4096, 4096)))
if validImage(b.Bytes()) {
t.Fatal("oversized dimensions accepted")
}
}