```
feat(map-settings): 新增地图设置面板,支持底图偏好与离线瓦片下载 共享层新增 map_settings 模块,定义 Bounds、Region、Preferences 和 DownloadRequest 数据结构及验证逻辑,单次下载上限 20000 张瓦片。 前端新增独立地图设置视图,包含: - 底图切换(影像/路网)与默认定位点配置 - 地图选点、框选下载范围交互 - 常用区域保存与离线下载任务管理 实时地图适配器改为从 Preferences 读取初始中心点和缩放级别, 使设置面板与工作台地图共享视图状态。 同时微调目标列表行高与 footer 布局,在紧凑模式下隐藏黑名单提示。 ```
This commit is contained in:
@@ -1,6 +1,7 @@
|
|||||||
//! Versioned synthetic telemetry contract. This is not a device wire protocol.
|
//! Versioned synthetic telemetry contract. This is not a device wire protocol.
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
pub mod map_settings;
|
||||||
pub mod target_lists;
|
pub mod target_lists;
|
||||||
|
|
||||||
pub const PROTOCOL_VERSION: u16 = 1;
|
pub const PROTOCOL_VERSION: u16 = 1;
|
||||||
|
|||||||
@@ -0,0 +1,180 @@
|
|||||||
|
//! Persistent map preferences and bounded manual download coverage.
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
pub const MAX_DOWNLOAD_TILES: u64 = 20_000;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub struct Bounds {
|
||||||
|
pub west: f64,
|
||||||
|
pub south: f64,
|
||||||
|
pub east: f64,
|
||||||
|
pub north: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Bounds {
|
||||||
|
pub fn valid(&self) -> bool {
|
||||||
|
[self.west, self.south, self.east, self.north]
|
||||||
|
.iter()
|
||||||
|
.all(|v| v.is_finite())
|
||||||
|
&& self.west >= -180.0
|
||||||
|
&& self.east <= 180.0
|
||||||
|
&& self.south >= -85.051128
|
||||||
|
&& self.north <= 85.051128
|
||||||
|
&& self.west < self.east
|
||||||
|
&& self.south < self.north
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tile_range(&self, z: u8) -> (u32, u32, u32, u32) {
|
||||||
|
let n = f64::from(1u32 << z);
|
||||||
|
let x = |lon: f64| (((lon + 180.0) / 360.0 * n).floor() as u32).min((1u32 << z) - 1);
|
||||||
|
let y = |lat: f64| {
|
||||||
|
let rad = lat.to_radians();
|
||||||
|
((1.0 - (rad.tan() + 1.0 / rad.cos()).ln() / std::f64::consts::PI) / 2.0 * n)
|
||||||
|
.floor()
|
||||||
|
.clamp(0.0, n - 1.0) as u32
|
||||||
|
};
|
||||||
|
(x(self.west), x(self.east), y(self.north), y(self.south))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub struct Region {
|
||||||
|
pub name: String,
|
||||||
|
pub bounds: Bounds,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub struct Preferences {
|
||||||
|
pub basemap: String,
|
||||||
|
pub longitude: f64,
|
||||||
|
pub latitude: f64,
|
||||||
|
pub zoom: f64,
|
||||||
|
pub regions: Vec<Region>,
|
||||||
|
pub revision: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Preferences {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
basemap: "imagery".into(),
|
||||||
|
longitude: 120.1538,
|
||||||
|
latitude: 30.2874,
|
||||||
|
zoom: 11.0,
|
||||||
|
regions: vec![],
|
||||||
|
revision: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Preferences {
|
||||||
|
pub fn valid(&self) -> bool {
|
||||||
|
matches!(self.basemap.as_str(), "road" | "imagery")
|
||||||
|
&& self.longitude.is_finite()
|
||||||
|
&& (-180.0..=180.0).contains(&self.longitude)
|
||||||
|
&& self.latitude.is_finite()
|
||||||
|
&& (-85.051128..=85.051128).contains(&self.latitude)
|
||||||
|
&& self.zoom.is_finite()
|
||||||
|
&& (0.0..=18.0).contains(&self.zoom)
|
||||||
|
&& self.regions.len() <= 30
|
||||||
|
&& self.regions.iter().enumerate().all(|(i, r)| {
|
||||||
|
!r.name.trim().is_empty()
|
||||||
|
&& r.name.chars().count() <= 40
|
||||||
|
&& !r.name.chars().any(char::is_control)
|
||||||
|
&& r.bounds.valid()
|
||||||
|
&& !self.regions[..i].iter().any(|p| p.name == r.name)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub struct DownloadRequest {
|
||||||
|
pub bounds: Bounds,
|
||||||
|
pub min_zoom: u8,
|
||||||
|
pub max_zoom: u8,
|
||||||
|
pub road: bool,
|
||||||
|
pub imagery: bool,
|
||||||
|
}
|
||||||
|
impl DownloadRequest {
|
||||||
|
pub fn layers(&self) -> Vec<&'static str> {
|
||||||
|
let mut layers = vec![];
|
||||||
|
if self.road {
|
||||||
|
layers.extend(["vec_w", "cva_w"]);
|
||||||
|
}
|
||||||
|
if self.imagery {
|
||||||
|
layers.extend(["img_w", "cia_w"]);
|
||||||
|
}
|
||||||
|
layers
|
||||||
|
}
|
||||||
|
pub fn count(&self) -> Result<u64, &'static str> {
|
||||||
|
if !self.bounds.valid()
|
||||||
|
|| self.min_zoom > self.max_zoom
|
||||||
|
|| self.max_zoom > 18
|
||||||
|
|| (!self.road && !self.imagery)
|
||||||
|
{
|
||||||
|
return Err("范围、层级或图层无效");
|
||||||
|
}
|
||||||
|
let mut count = 0u64;
|
||||||
|
for z in self.min_zoom..=self.max_zoom {
|
||||||
|
let (x0, x1, y0, y1) = self.bounds.tile_range(z);
|
||||||
|
count += u64::from(x1 - x0 + 1) * u64::from(y1 - y0 + 1) * self.layers().len() as u64;
|
||||||
|
if count > MAX_DOWNLOAD_TILES {
|
||||||
|
return Err("单次下载最多 20000 张瓦片,请缩小区域或降低层级");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn rejects_invalid_and_excessive_coverage() {
|
||||||
|
let mut r = DownloadRequest {
|
||||||
|
bounds: Bounds {
|
||||||
|
west: 120.15,
|
||||||
|
south: 30.28,
|
||||||
|
east: 120.16,
|
||||||
|
north: 30.29,
|
||||||
|
},
|
||||||
|
min_zoom: 11,
|
||||||
|
max_zoom: 11,
|
||||||
|
road: true,
|
||||||
|
imagery: true,
|
||||||
|
};
|
||||||
|
assert_eq!(r.count(), Ok(4));
|
||||||
|
r.bounds.west = f64::NAN;
|
||||||
|
assert!(r.count().is_err());
|
||||||
|
r.bounds = Bounds {
|
||||||
|
west: -180.0,
|
||||||
|
south: -85.0,
|
||||||
|
east: 180.0,
|
||||||
|
north: 85.0,
|
||||||
|
};
|
||||||
|
r.max_zoom = 18;
|
||||||
|
assert!(r.count().is_err());
|
||||||
|
r.min_zoom = 19;
|
||||||
|
assert!(r.count().is_err());
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn validates_defaults_and_regions() {
|
||||||
|
let mut p = Preferences::default();
|
||||||
|
assert!(p.valid());
|
||||||
|
p.latitude = 90.0;
|
||||||
|
assert!(!p.valid());
|
||||||
|
p.latitude = 30.0;
|
||||||
|
p.regions.push(Region {
|
||||||
|
name: " ".into(),
|
||||||
|
bounds: Bounds {
|
||||||
|
west: 1.0,
|
||||||
|
south: 1.0,
|
||||||
|
east: 2.0,
|
||||||
|
north: 2.0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert!(!p.valid());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,2 +1,2 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="dark"><title>FPV-RID · 本地登记与核验</title><link data-trunk rel="rust" data-wasm-opt="0"><link data-trunk rel="copy-file" href="public/app.css"><link data-trunk rel="copy-file" href="public/fpv-rid-icon.png"><link data-trunk rel="copy-dir" href="public/vendor"><link data-trunk rel="copy-file" href="public/map-adapter.js"><link data-trunk rel="copy-file" href="public/map-loader.js"><link data-trunk rel="copy-file" href="public/realtime.css"><link rel="stylesheet" href="/app.css"><link rel="stylesheet" href="/realtime.css"><link rel="stylesheet" href="/vendor/maplibre-gl.css"><script type="module" src="/map-loader.js"></script><link data-trunk rel="copy-file" href="public/workspace.css"><link data-trunk rel="copy-file" href="public/workspace-native.css"><link data-trunk rel="copy-dir" href="public/wallpapers"><link rel="stylesheet" href="/workspace.css"><link rel="stylesheet" href="/workspace-native.css"><link data-trunk rel="copy-dir" href="public/home"><link data-trunk rel="copy-file" href="public/home.css"><link rel="stylesheet" href="/home.css"><link data-trunk rel="copy-file" href="public/registry.css"><link rel="stylesheet" href="/registry.css"><link data-trunk rel="copy-file" href="public/glass.css"><link rel="stylesheet" href="/glass.css"><link data-trunk rel="copy-file" href="public/workbench.css"><link rel="stylesheet" href="/workbench.css"><link data-trunk rel="copy-file" href="public/target-lists.css"><link rel="stylesheet" href="/target-lists.css"><link rel="icon" href="/fpv-rid-icon.png"></head><body></body></html>
|
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="dark"><title>FPV-RID · 本地登记与核验</title><link data-trunk rel="rust" data-wasm-opt="0"><link data-trunk rel="copy-file" href="public/app.css"><link data-trunk rel="copy-file" href="public/fpv-rid-icon.png"><link data-trunk rel="copy-dir" href="public/vendor"><link data-trunk rel="copy-file" href="public/map-adapter.js"><link data-trunk rel="copy-file" href="public/map-loader.js"><link data-trunk rel="copy-file" href="public/realtime.css"><link rel="stylesheet" href="/app.css"><link rel="stylesheet" href="/realtime.css"><link rel="stylesheet" href="/vendor/maplibre-gl.css"><script type="module" src="/map-loader.js"></script><link data-trunk rel="copy-file" href="public/workspace.css"><link data-trunk rel="copy-file" href="public/workspace-native.css"><link data-trunk rel="copy-dir" href="public/wallpapers"><link rel="stylesheet" href="/workspace.css"><link rel="stylesheet" href="/workspace-native.css"><link data-trunk rel="copy-dir" href="public/home"><link data-trunk rel="copy-file" href="public/home.css"><link rel="stylesheet" href="/home.css"><link data-trunk rel="copy-file" href="public/registry.css"><link rel="stylesheet" href="/registry.css"><link data-trunk rel="copy-file" href="public/glass.css"><link rel="stylesheet" href="/glass.css"><link data-trunk rel="copy-file" href="public/workbench.css"><link rel="stylesheet" href="/workbench.css"><link data-trunk rel="copy-file" href="public/target-lists.css"><link rel="stylesheet" href="/target-lists.css"><link rel="icon" href="/fpv-rid-icon.png"><link data-trunk rel="copy-file" href="public/map-settings.css"><link rel="stylesheet" href="/map-settings.css"><link data-trunk rel="copy-file" href="public/map-settings-adapter.js"></head><body></body></html>
|
||||||
|
|||||||
@@ -17,10 +17,12 @@ function shader(gl, type, source) {
|
|||||||
const s=gl.createShader(type);gl.shaderSource(s,source);gl.compileShader(s);
|
const s=gl.createShader(type);gl.shaderSource(s,source);gl.compileShader(s);
|
||||||
if (!gl.getShaderParameter(s,gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));return s;
|
if (!gl.getShaderParameter(s,gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));return s;
|
||||||
}
|
}
|
||||||
function create(container,initialBasemap="imagery") {
|
function create(container,initialBasemap="imagery",preferences=null) {
|
||||||
basemap=initialBasemap==="road"?"road":"imagery";mapCreations++;
|
basemap=initialBasemap==="road"?"road":"imagery";mapCreations++;
|
||||||
if (map) map.remove();
|
if (map) map.remove();
|
||||||
map=new maplibre.Map({container,center:[120.1538,30.2874],zoom:11,pitch:0,bearing:0,attributionControl:false,
|
const initialCenter=preferences&&Number.isFinite(preferences.longitude)&&Number.isFinite(preferences.latitude)?[preferences.longitude,preferences.latitude]:[120.1538,30.2874];
|
||||||
|
const initialZoom=Number.isFinite(preferences?.zoom)?Math.max(0,Math.min(18,preferences.zoom)):11;
|
||||||
|
map=new maplibre.Map({container,center:initialCenter,zoom:initialZoom,pitch:0,bearing:0,attributionControl:false,
|
||||||
style:{version:8,sources:{
|
style:{version:8,sources:{
|
||||||
'tdt-base':{type:'raster',tiles:[tileUrl(0)],tileSize:256,maxzoom:18,attribution:'天地图 © 自然资源部 / 本地缓存与离线资源'},
|
'tdt-base':{type:'raster',tiles:[tileUrl(0)],tileSize:256,maxzoom:18,attribution:'天地图 © 自然资源部 / 本地缓存与离线资源'},
|
||||||
'tdt-labels':{type:'raster',tiles:[tileUrl(1)],tileSize:256,maxzoom:18}
|
'tdt-labels':{type:'raster',tiles:[tileUrl(1)],tileSize:256,maxzoom:18}
|
||||||
@@ -34,7 +36,7 @@ function create(container,initialBasemap="imagery") {
|
|||||||
layer={id:'rid-targets',type:'custom',renderingMode:'2d',
|
layer={id:'rid-targets',type:'custom',renderingMode:'2d',
|
||||||
onAdd(map,gl){
|
onAdd(map,gl){
|
||||||
if (!gl.drawArraysInstanced) throw new Error('WebGL2 required');
|
if (!gl.drawArraysInstanced) throw new Error('WebGL2 required');
|
||||||
this.gl=gl;this.map=map;this.origin=maplibre.MercatorCoordinate.fromLngLat([120.1538,30.2874]);
|
this.gl=gl;this.map=map;this.origin=maplibre.MercatorCoordinate.fromLngLat(initialCenter);
|
||||||
this.program=gl.createProgram();
|
this.program=gl.createProgram();
|
||||||
this.vs=shader(gl,gl.VERTEX_SHADER,`#version 300 es
|
this.vs=shader(gl,gl.VERTEX_SHADER,`#version 300 es
|
||||||
precision highp float; in vec2 shape; in vec4 target; uniform mat4 matrix; uniform vec2 pixel; uniform float bearing; out float chosen;
|
precision highp float; in vec2 shape; in vec4 target; uniform mat4 matrix; uniform vec2 pixel; uniform float bearing; out float chosen;
|
||||||
@@ -64,10 +66,10 @@ function create(container,initialBasemap="imagery") {
|
|||||||
map.on('style.load',()=>{
|
map.on('style.load',()=>{
|
||||||
// Mission Control tactical radar grid & range rings
|
// Mission Control tactical radar grid & range rings
|
||||||
const features=[];
|
const features=[];
|
||||||
for(let lon=118;lon<=122;lon+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[lon,28],[lon,32]]},properties:{}});
|
for(let lon=initialCenter[0]-2;lon<=initialCenter[0]+2;lon+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[lon,initialCenter[1]-2],[lon,initialCenter[1]+2]]},properties:{}});
|
||||||
for(let lat=28;lat<=32;lat+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[118,lat],[122,lat]]},properties:{}});
|
for(let lat=initialCenter[1]-2;lat<=initialCenter[1]+2;lat+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[initialCenter[0]-2,lat],[initialCenter[0]+2,lat]]},properties:{}});
|
||||||
// Concentric tactical range rings around default center
|
// Concentric tactical range rings around default center
|
||||||
const center=[120.1538,30.2874];
|
const center=initialCenter;
|
||||||
for(const radiusKm of [1, 2, 5, 10]) {
|
for(const radiusKm of [1, 2, 5, 10]) {
|
||||||
const ring=[];
|
const ring=[];
|
||||||
for(let a=0;a<=360;a+=6){
|
for(let a=0;a<=360;a+=6){
|
||||||
|
|||||||
@@ -1,2 +1,10 @@
|
|||||||
// Load the map engine only for the approved realtime workspace.
|
// Load the map engine only for the approved realtime workspace.
|
||||||
if (location.pathname === '/realtime') await import('./map-adapter.js');
|
if (location.pathname === '/realtime') await import('./map-adapter.js');
|
||||||
|
// A separate, lazy map keeps configuration independent of the live receiver map.
|
||||||
|
let settings, generation=0;
|
||||||
|
window.ridMapSettings={
|
||||||
|
async open(p){const token=++generation;settings??=await import('./map-settings-adapter.js');if(token===generation)settings.open(p);},
|
||||||
|
close(){generation++;settings?.close();},refresh(){settings?.refresh();window.ridMap?.refresh();},
|
||||||
|
configure(p){settings?.configure(p);},setBasemap(v){settings?.setBasemap(v);},
|
||||||
|
tool(v){settings?.tool(v);},bounds(v){settings?.bounds(v);},current(){settings?.current();},metrics(){return settings?.metrics();}
|
||||||
|
};
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
// MapLibre interop only. Preferences, download state and API requests live in Rust.
|
||||||
|
import * as ml from './vendor/maplibre-gl.mjs';
|
||||||
|
ml.setWorkerUrl('/vendor/maplibre-gl-worker.mjs');
|
||||||
|
let map,kind='imagery',mode='',marker,observer,start,box,boxElement,revision=0;
|
||||||
|
const pairs={imagery:['img_w','cia_w'],road:['vec_w','cva_w']};
|
||||||
|
function urls(i){return `/api/maps/tile/${pairs[kind][i]}/{z}/{x}/{y}?v=${revision}`;}
|
||||||
|
function emit(type,detail){window.dispatchEvent(new CustomEvent(type,{detail}));}
|
||||||
|
export function open(p){
|
||||||
|
if(map){configure(p);map.resize();return;}
|
||||||
|
kind=p.basemap==='road'?'road':'imagery';
|
||||||
|
try{
|
||||||
|
map=new ml.Map({container:'settings-map',center:[p.longitude,p.latitude],zoom:p.zoom,pitch:0,bearing:0,maxZoom:18,style:{version:8,sources:{base:{type:'raster',tiles:[urls(0)],tileSize:256,maxzoom:18},labels:{type:'raster',tiles:[urls(1)],tileSize:256,maxzoom:18}},layers:[{id:'background',type:'background',paint:{'background-color':'#061221'}},{id:'base',type:'raster',source:'base'},{id:'labels',type:'raster',source:'labels'}]}});
|
||||||
|
map.addControl(new ml.NavigationControl({visualizePitch:false}),'bottom-left');
|
||||||
|
map.addControl(new ml.AttributionControl({customAttribution:'天地图 © 自然资源部 · 本机在线缓存 / 离线资源',compact:true}),'bottom-right');
|
||||||
|
marker=new ml.Marker({color:'#9bcaff'}).setLngLat([p.longitude,p.latitude]).addTo(map);
|
||||||
|
observer=new ResizeObserver(()=>map?.resize());observer.observe(document.getElementById('settings-map'));
|
||||||
|
map.on('click',e=>{if(mode!=='point')return;marker.setLngLat(e.lngLat);emit('rid-map-point',{longitude:e.lngLat.lng,latitude:e.lngLat.lat,zoom:map.getZoom()});tool('');});
|
||||||
|
map.on('error',e=>{if(e.sourceId?.match(/base|labels/))return;emit('rid-map-error',{message:'地图引擎加载失败,请检查浏览器 WebGL 支持。'});});
|
||||||
|
boxElement=document.createElement('div');boxElement.className='map-download-selection';boxElement.hidden=true;document.getElementById('settings-map').appendChild(boxElement);
|
||||||
|
const canvas=map.getCanvasContainer();
|
||||||
|
canvas.addEventListener('pointerdown',e=>{if(mode!=='box'||e.button!==0)return;e.preventDefault();const r=canvas.getBoundingClientRect();start=[e.clientX-r.left,e.clientY-r.top];canvas.setPointerCapture(e.pointerId);boxElement.hidden=false;});
|
||||||
|
canvas.addEventListener('pointermove',e=>{if(!start)return;const r=canvas.getBoundingClientRect(),end=[Math.max(0,Math.min(r.width,e.clientX-r.left)),Math.max(0,Math.min(r.height,e.clientY-r.top))];box=[Math.min(start[0],end[0]),Math.min(start[1],end[1]),Math.max(start[0],end[0]),Math.max(start[1],end[1])];Object.assign(boxElement.style,{left:box[0]+'px',top:box[1]+'px',width:(box[2]-box[0])+'px',height:(box[3]-box[1])+'px'});});
|
||||||
|
canvas.addEventListener('pointerup',()=>{if(!start)return;start=null;if(box&&box[2]-box[0]>6&&box[3]-box[1]>6){const a=map.unproject([box[0],box[3]]),b=map.unproject([box[2],box[1]]);emit('rid-map-bounds',{west:Math.max(-180,a.lng),south:Math.max(-85.051128,a.lat),east:Math.min(180,b.lng),north:Math.min(85.051128,b.lat)});}tool('');});
|
||||||
|
canvas.addEventListener('pointercancel',()=>{start=null;box=null;tool('');});
|
||||||
|
map.getCanvas().addEventListener('keydown',e=>{if(e.key==='Escape'){start=null;box=null;boxElement.hidden=true;tool('');emit('rid-map-error',{message:'已退出地图选择模式。'});}});
|
||||||
|
}catch{map?.remove();map=null;emit('rid-map-error',{message:'无法创建地图。仍可输入坐标、下载范围并保存配置。'});}
|
||||||
|
}
|
||||||
|
export function configure(p){if(!map)return;setBasemap(p.basemap);map.jumpTo({center:[p.longitude,p.latitude],zoom:p.zoom});marker?.setLngLat([p.longitude,p.latitude]);}
|
||||||
|
export function setBasemap(value){if(!map)return;kind=value==='road'?'road':'imagery';for(const [i,k]of ['base','labels'].entries())map.getSource(k)?.setTiles([urls(i)]);}
|
||||||
|
export function refresh(){revision++;setBasemap(kind);}
|
||||||
|
export function tool(value){mode=value;start=null;box=null;if(!map)return;if(mode==='box')map.dragPan.disable();else map.dragPan.enable();map.getCanvas().style.cursor=mode?'crosshair':'';}
|
||||||
|
export function bounds(value){if(!map)return;map.fitBounds([[value.west,value.south],[value.east,value.north]],{padding:{left:60,right:Math.min(430,map.getContainer().clientWidth/2),top:70,bottom:60},duration:400});}
|
||||||
|
export function current(){if(!map)return;const p=map.getCenter();emit('rid-map-point',{longitude:p.lng,latitude:p.lat,zoom:map.getZoom()});marker?.setLngLat(p);}
|
||||||
|
export function metrics(){return map?{ready:map.loaded(),camera:{longitude:map.getCenter().lng,latitude:map.getCenter().lat,zoom:map.getZoom()},basemap:kind}:null;}
|
||||||
|
export function close(){observer?.disconnect();observer=null;map?.remove();map=null;marker=null;boxElement=null;mode='';}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
.map-settings-layout{height:100%;min-height:0;display:grid;grid-template-columns:210px minmax(0,1fr);gap:18px;padding:24px}.map-settings-stage{position:relative;overflow:hidden;min-height:0}.map-settings-head{height:68px;display:flex;align-items:center;justify-content:space-between;padding:0 20px;gap:14px;border-bottom:1px solid var(--work-line)}.map-settings-head h2{font-size:16px}.map-settings-head p{font-size:11px;color:var(--work-muted);margin-top:5px}.map-settings-head button{font-size:12px;padding:8px 12px;border-radius:7px}#settings-map{position:absolute;inset:68px 0 0;background:#061221}.map-settings-hint{position:absolute;left:16px;bottom:32px;right:430px;font-size:11px;color:var(--work-text);background:var(--glass-solid);border:1px solid var(--work-line);border-radius:7px;padding:10px 12px;pointer-events:none;z-index:3;line-height:1.8}.map-settings-drawer{position:absolute;right:16px;top:84px;bottom:16px;width:390px;display:flex;flex-direction:column;background:var(--glass-solid);z-index:4;overflow:hidden}.map-settings-drawer .setting-panel-head button{padding:4px 10px;border:0;background:none;box-shadow:none}.map-settings-scroll{flex:1;min-height:0;overflow:auto;padding:16px;scrollbar-width:thin;scroll-padding-block:18px}.map-settings-caption{display:flex;align-items:center;justify-content:space-between;gap:8px;border-top:1px solid var(--work-line);padding-top:18px;margin:20px 0 16px;font-size:13px;font-weight:600}.map-settings-caption span{color:var(--work-muted);font-size:10px;font-weight:400}.map-settings-label{display:block;color:var(--work-muted);font-size:12px;min-width:0}.map-settings-scroll :is(input:not([type=checkbox]),select){display:block;width:100%;min-width:0;box-shadow:none;font:inherit;color:var(--work-text);background:var(--work-input);border:1px solid var(--work-line);border-radius:7px;padding:10px;margin-top:8px;height:39px;font-size:12px}.map-settings-fields{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin:16px 0}.map-settings-actions{display:flex;gap:9px;align-items:center;flex-wrap:wrap;margin:18px 0 12px}.map-settings-actions button,.map-region-name button{font-size:12px;padding:8px 10px;border-radius:7px}.map-settings-message{font-size:11px;line-height:1.9;color:#bdd9ff;overflow-wrap:anywhere;min-height:22px}.map-settings-message.error{color:var(--mc-danger,#ffaaa4)}.map-settings-small{font-size:11px;line-height:1.9;color:var(--work-muted);margin:10px 0}.map-network-note{padding:12px;border:1px solid var(--work-line);border-radius:8px;font-size:11px;line-height:1.9;background:#8bbdff0a;overflow-wrap:anywhere}.map-network-note.warning{border-color:#ffd08a66;color:#ffd08a;background:#ffd08a0a}.map-layer-choices{display:flex;flex-wrap:wrap;gap:15px;font-size:11px;margin:16px 0}.map-layer-choices label{display:flex;align-items:center;gap:8px}.map-layer-choices input{width:14px;height:14px;margin:0;padding:0;box-shadow:none}.map-region-name{display:flex;gap:6px;align-items:center}.map-region-name input{flex:1;margin:0!important}.map-region-name button{flex:none}#map-download-progress{width:100%;height:7px;accent-color:#8bbdff;margin:8px 0}.map-reload{font-size:11px;padding:5px 0;border:0;background:none;box-shadow:none;color:var(--work-muted)}.map-settings-layout button:disabled{opacity:.45;cursor:not-allowed}.map-download-selection{position:absolute;border:2px dashed #b3d5ff;background:#8bbdff26;pointer-events:none;z-index:2}.map-settings-layout .maplibregl-ctrl-attrib{font-size:9px}.map-settings-stage:has(.map-settings-drawer[hidden]) .map-settings-hint{right:16px}body[data-menu-hidden=true] #map-settings-view{left:0}
|
||||||
|
@media(max-width:1200px){.map-settings-layout{grid-template-columns:180px minmax(0,1fr);padding:18px;gap:14px}.map-settings-drawer{width:360px;right:12px}.map-settings-hint{right:390px}}
|
||||||
|
@media(max-width:900px){.map-settings-layout{display:flex;flex-direction:column;height:auto;padding:14px;gap:14px}.map-settings-layout>.settings-sidebar{display:flex;flex-wrap:wrap;padding:8px;gap:5px}.map-settings-layout>.settings-sidebar :is(h2,.micro){display:none}.map-settings-layout .setting-link{width:auto;font-size:11px}.map-settings-stage{min-height:700px;overflow:visible}.map-settings-head{height:auto;min-height:68px;padding:14px;flex-wrap:wrap}.map-settings-head .row{flex-wrap:wrap;gap:6px}.map-settings-head button{padding:6px 9px;font-size:11px}#settings-map{position:relative;inset:auto;height:360px}.map-settings-drawer{position:relative;inset:auto;width:auto;margin:12px;max-height:650px;min-height:300px}.map-settings-hint{position:relative;inset:auto;margin:12px}.map-settings-stage:has(.map-settings-drawer[hidden]) .map-settings-hint{right:auto}.map-settings-caption{flex-wrap:wrap}}
|
||||||
@@ -43,7 +43,7 @@
|
|||||||
.rt-list-manager :is(input, select, textarea) { width: 100%; min-width: 0; padding: 9px 10px; background: var(--work-input); border: 1px solid var(--work-line); border-radius: 7px; color: var(--work-text); font-size: 12px; box-shadow: none; }
|
.rt-list-manager :is(input, select, textarea) { width: 100%; min-width: 0; padding: 9px 10px; background: var(--work-input); border: 1px solid var(--work-line); border-radius: 7px; color: var(--work-text); font-size: 12px; box-shadow: none; }
|
||||||
.rt-list-manager input, .rt-list-manager select { height: 38px; }
|
.rt-list-manager input, .rt-list-manager select { height: 38px; }
|
||||||
.rt-list-manager input::placeholder { color: var(--work-muted); }
|
.rt-list-manager input::placeholder { color: var(--work-muted); }
|
||||||
.rt-list-rows { max-height: 240px; overflow: auto; scrollbar-width: thin; margin-top: 6px; }
|
.rt-list-rows { max-height: 180px; overflow: auto; scrollbar-width: thin; margin-top: 6px; }
|
||||||
.rt-list-row { display: flex; gap: 7px; align-items: center; border-bottom: 1px solid var(--work-line); padding: 13px 0; }
|
.rt-list-row { display: flex; gap: 7px; align-items: center; border-bottom: 1px solid var(--work-line); padding: 13px 0; }
|
||||||
.rt-list-row-main { flex: 1; min-width: 0; }
|
.rt-list-row-main { flex: 1; min-width: 0; }
|
||||||
.rt-list-row strong { font-size: 12px; overflow-wrap: anywhere; }
|
.rt-list-row strong { font-size: 12px; overflow-wrap: anywhere; }
|
||||||
@@ -56,7 +56,7 @@
|
|||||||
#rt-list-entry-form label { display: block; font-size: 12px; margin: 14px 0 7px; }
|
#rt-list-entry-form label { display: block; font-size: 12px; margin: 14px 0 7px; }
|
||||||
#rt-list-entry-form textarea { height: 65px; resize: vertical; max-height: 180px; }
|
#rt-list-entry-form textarea { height: 65px; resize: vertical; max-height: 180px; }
|
||||||
.rt-list-manager #rt-list-entry-form .primary { width: 100%; background: var(--glass-action); color: white; margin-top: 14px; }
|
.rt-list-manager #rt-list-entry-form .primary { width: 100%; background: var(--glass-action); color: white; margin-top: 14px; }
|
||||||
.rt-list-manager-footer { background: var(--glass-solid); border-top: 1px solid var(--work-line); padding: 11px 16px; flex-shrink: 0; }
|
.rt-list-manager-footer { display: block; background: var(--glass-solid); border-top: 1px solid var(--work-line); padding: 11px 16px; flex-shrink: 0; }
|
||||||
.rt-list-manager-footer p { font-size: 12px; line-height: 1.8; margin-bottom: 5px; color: #9edac1; overflow-wrap: anywhere; }
|
.rt-list-manager-footer p { font-size: 12px; line-height: 1.8; margin-bottom: 5px; color: #9edac1; overflow-wrap: anywhere; }
|
||||||
.rt-list-manager-footer p:empty { display: none; }
|
.rt-list-manager-footer p:empty { display: none; }
|
||||||
.rt-list-manager-footer p.error { color: #ffb1a9; }
|
.rt-list-manager-footer p.error { color: #ffb1a9; }
|
||||||
@@ -74,3 +74,5 @@
|
|||||||
.rt-list-manager-body { padding: 14px; }
|
.rt-list-manager-body { padding: 14px; }
|
||||||
.rt-blacklist-alert span { display: none; }
|
.rt-blacklist-alert span { display: none; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.mc-layout-b.compact[data-lists-open=true] .rt-blacklist-alert { visibility: hidden; }
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use leptos::prelude::*;
|
use leptos::prelude::*;
|
||||||
|
mod map_settings;
|
||||||
mod realtime_layout;
|
mod realtime_layout;
|
||||||
mod realtime_ui;
|
mod realtime_ui;
|
||||||
mod receiver_ui;
|
mod receiver_ui;
|
||||||
@@ -16,12 +17,14 @@ fn main() {
|
|||||||
mount_to_body(move || {
|
mount_to_body(move || {
|
||||||
view! {
|
view! {
|
||||||
<div inner_html=include_str!("workspace.html")/>
|
<div inner_html=include_str!("workspace.html")/>
|
||||||
|
<section id="map-settings-view" class="workspace-pane" hidden inner_html=include_str!("map_settings.html")/>
|
||||||
<section id="workspace-content" class="workspace-pane">
|
<section id="workspace-content" class="workspace-pane">
|
||||||
{if realtime { view! { <realtime_ui::Realtime/> }.into_any() }
|
{if realtime { view! { <realtime_ui::Realtime/> }.into_any() }
|
||||||
else { view! { <Registry/> }.into_any() }}
|
else { view! { <Registry/> }.into_any() }}
|
||||||
</section>
|
</section>
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
map_settings::init();
|
||||||
workspace::init(realtime);
|
workspace::init(realtime);
|
||||||
if !realtime {
|
if !realtime {
|
||||||
registry::init();
|
registry::init();
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,690 @@
|
|||||||
|
//! Application-owned map settings. JavaScript is limited to MapLibre interoperability.
|
||||||
|
use gloo_net::http::Request;
|
||||||
|
use gloo_timers::future::TimeoutFuture;
|
||||||
|
use rid_shared::map_settings::{Bounds, DownloadRequest, Preferences, Region};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::{cell::RefCell, rc::Rc};
|
||||||
|
use wasm_bindgen::{JsCast, closure::Closure};
|
||||||
|
use wasm_bindgen_futures::spawn_local;
|
||||||
|
use web_sys::{Element, Event, HtmlInputElement, HtmlSelectElement};
|
||||||
|
|
||||||
|
struct State {
|
||||||
|
prefs: Option<Preferences>,
|
||||||
|
estimate: Option<DownloadRequest>,
|
||||||
|
available: bool,
|
||||||
|
running: bool,
|
||||||
|
busy: bool,
|
||||||
|
dirty: bool,
|
||||||
|
}
|
||||||
|
type Shared = Rc<RefCell<State>>;
|
||||||
|
thread_local! {static STATE:RefCell<Option<Shared>>=const{RefCell::new(None)};}
|
||||||
|
fn document() -> web_sys::Document {
|
||||||
|
web_sys::window()
|
||||||
|
.expect("browser")
|
||||||
|
.document()
|
||||||
|
.expect("document")
|
||||||
|
}
|
||||||
|
fn el(id: &str) -> Option<Element> {
|
||||||
|
document().get_element_by_id(id)
|
||||||
|
}
|
||||||
|
fn text(id: &str, s: &str) {
|
||||||
|
if let Some(e) = el(id) {
|
||||||
|
e.set_text_content(Some(s));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn disabled(id: &str, value: bool) {
|
||||||
|
if let Some(e) = el(id) {
|
||||||
|
if value {
|
||||||
|
let _ = e.set_attribute("disabled", "");
|
||||||
|
} else {
|
||||||
|
let _ = e.remove_attribute("disabled");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn value(id: &str) -> String {
|
||||||
|
el(id)
|
||||||
|
.and_then(|e| e.dyn_into::<HtmlInputElement>().ok())
|
||||||
|
.map(|e| e.value())
|
||||||
|
.or_else(|| {
|
||||||
|
el(id)
|
||||||
|
.and_then(|e| e.dyn_into::<HtmlSelectElement>().ok())
|
||||||
|
.map(|e| e.value())
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
fn set(id: &str, v: &str) {
|
||||||
|
if let Some(e) = el(id) {
|
||||||
|
if let Some(i) = e.dyn_ref::<HtmlInputElement>() {
|
||||||
|
i.set_value(v)
|
||||||
|
} else if let Some(s) = e.dyn_ref::<HtmlSelectElement>() {
|
||||||
|
s.set_value(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn number(id: &str) -> f64 {
|
||||||
|
value(id).parse().unwrap_or(f64::NAN)
|
||||||
|
}
|
||||||
|
fn checked(id: &str) -> bool {
|
||||||
|
el(id)
|
||||||
|
.and_then(|e| e.dyn_into::<HtmlInputElement>().ok())
|
||||||
|
.is_some_and(|e| e.checked())
|
||||||
|
}
|
||||||
|
fn message(id: &str, s: &str, error: bool) {
|
||||||
|
text(id, s);
|
||||||
|
if let Some(e) = el(id) {
|
||||||
|
let _ = e.set_attribute(
|
||||||
|
"class",
|
||||||
|
if error {
|
||||||
|
"map-settings-message error"
|
||||||
|
} else {
|
||||||
|
"map-settings-message"
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn map(method: &str, arg: &Value) {
|
||||||
|
let Ok(api) = js_sys::Reflect::get(&js_sys::global(), &"ridMapSettings".into()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Ok(f) =
|
||||||
|
js_sys::Reflect::get(&api, &method.into()).and_then(|f| f.dyn_into::<js_sys::Function>())
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if let Ok(arg) = js_sys::JSON::parse(&arg.to_string()) {
|
||||||
|
let _ = f.call1(&api, &arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn visible() -> bool {
|
||||||
|
document()
|
||||||
|
.body()
|
||||||
|
.is_some_and(|b| b.get_attribute("data-screen").as_deref() == Some("maps"))
|
||||||
|
}
|
||||||
|
fn drawer(show: bool) {
|
||||||
|
if let Some(e) = el("map-settings-drawer") {
|
||||||
|
if show {
|
||||||
|
let _ = e.remove_attribute("hidden");
|
||||||
|
} else {
|
||||||
|
let _ = e.set_attribute("hidden", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(buttons) = document().query_selector_all("[data-map-action=drawer]") {
|
||||||
|
for i in 0..buttons.length() {
|
||||||
|
if let Some(e) = buttons.item(i).and_then(|n| n.dyn_into::<Element>().ok()) {
|
||||||
|
let _ = e.set_attribute("aria-expanded", if show { "true" } else { "false" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn update_buttons(s: &Shared) {
|
||||||
|
let state = s.borrow();
|
||||||
|
disabled("map-save", state.prefs.is_none() || state.busy);
|
||||||
|
disabled("map-estimate", state.running || state.busy);
|
||||||
|
disabled(
|
||||||
|
"map-download-start",
|
||||||
|
state.estimate.is_none() || state.running || state.busy || !state.available,
|
||||||
|
);
|
||||||
|
disabled("map-download-cancel", !state.running);
|
||||||
|
}
|
||||||
|
fn paint(s: &Shared) {
|
||||||
|
let p = s.borrow().prefs.clone();
|
||||||
|
let Some(p) = p else { return };
|
||||||
|
set("map-basemap", &p.basemap);
|
||||||
|
set("map-longitude", &p.longitude.to_string());
|
||||||
|
set("map-latitude", &p.latitude.to_string());
|
||||||
|
set("map-zoom", &p.zoom.to_string());
|
||||||
|
paint_regions(&p);
|
||||||
|
update_buttons(s);
|
||||||
|
}
|
||||||
|
fn paint_regions(p: &Preferences) {
|
||||||
|
if let Some(select) = el("map-region") {
|
||||||
|
select.set_inner_html("<option value=\"\">选择已保存的区域…</option>");
|
||||||
|
for (i, r) in p.regions.iter().enumerate() {
|
||||||
|
if let Ok(o) = document().create_element("option") {
|
||||||
|
let _ = o.set_attribute("value", &i.to_string());
|
||||||
|
o.set_text_content(Some(&r.name));
|
||||||
|
let _ = select.append_child(&o);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn bounds() -> Bounds {
|
||||||
|
Bounds {
|
||||||
|
west: number("map-west"),
|
||||||
|
south: number("map-south"),
|
||||||
|
east: number("map-east"),
|
||||||
|
north: number("map-north"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn set_bounds(b: &Bounds) {
|
||||||
|
for (id, n) in [
|
||||||
|
("map-west", b.west),
|
||||||
|
("map-south", b.south),
|
||||||
|
("map-east", b.east),
|
||||||
|
("map-north", b.north),
|
||||||
|
] {
|
||||||
|
set(id, &format!("{n:.6}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn request() -> Result<DownloadRequest, String> {
|
||||||
|
let min = number("map-min-zoom");
|
||||||
|
let max = number("map-max-zoom");
|
||||||
|
if !min.is_finite()
|
||||||
|
|| !max.is_finite()
|
||||||
|
|| min.fract() != 0.0
|
||||||
|
|| max.fract() != 0.0
|
||||||
|
|| !(0.0..=18.0).contains(&min)
|
||||||
|
|| !(0.0..=18.0).contains(&max)
|
||||||
|
{
|
||||||
|
return Err("层级必须为 0–18 的整数".into());
|
||||||
|
}
|
||||||
|
let r = DownloadRequest {
|
||||||
|
bounds: bounds(),
|
||||||
|
min_zoom: min as u8,
|
||||||
|
max_zoom: max as u8,
|
||||||
|
road: checked("map-download-road"),
|
||||||
|
imagery: checked("map-download-imagery"),
|
||||||
|
};
|
||||||
|
r.count().map_err(str::to_owned)?;
|
||||||
|
Ok(r)
|
||||||
|
}
|
||||||
|
fn invalidate(s: &Shared) {
|
||||||
|
s.borrow_mut().estimate = None;
|
||||||
|
text(
|
||||||
|
"map-estimate-message",
|
||||||
|
"范围或图层已变化,请重新核算后下载。",
|
||||||
|
);
|
||||||
|
update_buttons(s);
|
||||||
|
}
|
||||||
|
async fn response(r: gloo_net::http::Response) -> Result<Value, String> {
|
||||||
|
let ok = r.ok();
|
||||||
|
let v = r.json::<Value>().await.map_err(|_| "服务返回无效响应")?;
|
||||||
|
if ok {
|
||||||
|
Ok(v)
|
||||||
|
} else {
|
||||||
|
Err(v["error"].as_str().unwrap_or("操作失败,请重试").into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async fn get(url: &str) -> Result<Value, String> {
|
||||||
|
response(
|
||||||
|
Request::get(url)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|_| "无法连接本机服务")?,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
async fn post(url: &str, v: &Value) -> Result<Value, String> {
|
||||||
|
response(
|
||||||
|
Request::post(url)
|
||||||
|
.json(v)
|
||||||
|
.map_err(|_| "请求内容无效")?
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|_| "无法连接本机服务")?,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
async fn load(s: Shared) {
|
||||||
|
s.borrow_mut().busy = true;
|
||||||
|
update_buttons(&s);
|
||||||
|
let result = get("/api/maps/preferences").await.and_then(|v| {
|
||||||
|
serde_json::from_value::<Preferences>(v).map_err(|_| "地图设置格式无效".into())
|
||||||
|
});
|
||||||
|
s.borrow_mut().busy = false;
|
||||||
|
match result {
|
||||||
|
Ok(p) => {
|
||||||
|
s.borrow_mut().prefs = Some(p.clone());
|
||||||
|
s.borrow_mut().dirty = false;
|
||||||
|
paint(&s);
|
||||||
|
message(
|
||||||
|
"map-save-message",
|
||||||
|
"已读取本机地图设置。修改后点击保存。",
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
if visible() {
|
||||||
|
map("open", &json!(p));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => message("map-save-message", &e, true),
|
||||||
|
}
|
||||||
|
update_buttons(&s);
|
||||||
|
}
|
||||||
|
async fn save(s: Shared) {
|
||||||
|
let Some(mut p) = s.borrow().prefs.clone() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
p.basemap = value("map-basemap");
|
||||||
|
p.longitude = number("map-longitude");
|
||||||
|
p.latitude = number("map-latitude");
|
||||||
|
p.zoom = number("map-zoom");
|
||||||
|
if !p.valid() {
|
||||||
|
message(
|
||||||
|
"map-save-message",
|
||||||
|
"请输入有效经纬度和 0–18 的缩放级别。",
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s.borrow_mut().busy = true;
|
||||||
|
update_buttons(&s);
|
||||||
|
let result = async {
|
||||||
|
let r = Request::put("/api/maps/preferences")
|
||||||
|
.json(&p)
|
||||||
|
.map_err(|_| "设置格式无效")?
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|_| "无法连接本机服务")?;
|
||||||
|
response(r).await
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
s.borrow_mut().busy = false;
|
||||||
|
match result {
|
||||||
|
Ok(v) => match serde_json::from_value::<Preferences>(v) {
|
||||||
|
Ok(p) => {
|
||||||
|
s.borrow_mut().prefs = Some(p.clone());
|
||||||
|
s.borrow_mut().dirty = false;
|
||||||
|
paint(&s);
|
||||||
|
map("configure", &json!(p));
|
||||||
|
message(
|
||||||
|
"map-save-message",
|
||||||
|
"已保存。实时地图下次打开将使用此起始点与底图。",
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(_) => message("map-save-message", "保存响应无效,请重新加载核实。", true),
|
||||||
|
},
|
||||||
|
Err(e) => message("map-save-message", &e, true),
|
||||||
|
}
|
||||||
|
update_buttons(&s);
|
||||||
|
}
|
||||||
|
async fn poll(s: Shared) {
|
||||||
|
if let Ok(v) = get("/api/maps/status").await {
|
||||||
|
let (key, mode, error) = (
|
||||||
|
v["keyConfigured"].as_bool().unwrap_or(false),
|
||||||
|
v["mode"].as_str().unwrap_or("offline"),
|
||||||
|
v["configError"].is_string(),
|
||||||
|
);
|
||||||
|
let label = if error {
|
||||||
|
"天地图配置文件无效,请修复 maps/config.json;原文件已保留。"
|
||||||
|
} else if !key {
|
||||||
|
"天地图密钥未配置。可使用已有离线地图;联网下载需先配置服务端密钥。"
|
||||||
|
} else if mode == "offline" {
|
||||||
|
"天地图当前不可用。请检查网络或授权;已有离线区域可继续使用。"
|
||||||
|
} else {
|
||||||
|
"已配置天地图。缺少离线覆盖时,请联网手动下载;密钥不进入浏览器。"
|
||||||
|
};
|
||||||
|
text("map-network-note", label);
|
||||||
|
if let Some(e) = el("map-network-note") {
|
||||||
|
let _ = e.set_attribute(
|
||||||
|
"class",
|
||||||
|
if error || !key || mode == "offline" {
|
||||||
|
"map-network-note warning"
|
||||||
|
} else {
|
||||||
|
"map-network-note"
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match get("/api/maps/downloads").await {
|
||||||
|
Ok(v) => {
|
||||||
|
s.borrow_mut().available = v["available"].as_bool().unwrap_or(false);
|
||||||
|
let j = &v["job"];
|
||||||
|
let was_running=s.borrow().running;
|
||||||
|
s.borrow_mut().running = j["state"] == "running";
|
||||||
|
if was_running && j["state"] == "completed" { map("refresh", &Value::Null); }
|
||||||
|
if j.is_object() {
|
||||||
|
let state = j["state"].as_str().unwrap_or("");
|
||||||
|
message(
|
||||||
|
"map-download-message",
|
||||||
|
j["message"].as_str().unwrap_or("正在检查下载状态"),
|
||||||
|
state == "failed",
|
||||||
|
);
|
||||||
|
if let Some(progress) = el("map-download-progress") {
|
||||||
|
let _ = progress
|
||||||
|
.set_attribute("max", &j["total"].as_u64().unwrap_or(1).max(1).to_string());
|
||||||
|
let _ = progress
|
||||||
|
.set_attribute("value", &j["done"].as_u64().unwrap_or(0).to_string());
|
||||||
|
}
|
||||||
|
} else if !s.borrow().available {
|
||||||
|
message(
|
||||||
|
"map-download-message",
|
||||||
|
"Go 下载器未安装,请运行 scripts/build-map-downloader.ps1 或使用完整发布包。",
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => message("map-download-message", &e, true),
|
||||||
|
}
|
||||||
|
update_buttons(&s);
|
||||||
|
}
|
||||||
|
pub fn open() {
|
||||||
|
STATE.with(|slot| {
|
||||||
|
if let Some(s) = slot.borrow().clone() {
|
||||||
|
drawer(true);
|
||||||
|
if s.borrow().prefs.is_none() {
|
||||||
|
spawn_local(load(s));
|
||||||
|
} else {
|
||||||
|
if !s.borrow().dirty {
|
||||||
|
paint(&s);
|
||||||
|
}
|
||||||
|
if let Some(mut p) = s.borrow().prefs.clone() {
|
||||||
|
let candidate = (
|
||||||
|
number("map-longitude"),
|
||||||
|
number("map-latitude"),
|
||||||
|
number("map-zoom"),
|
||||||
|
);
|
||||||
|
if candidate.0.is_finite() && candidate.1.is_finite() && candidate.2.is_finite()
|
||||||
|
{
|
||||||
|
p.longitude = candidate.0;
|
||||||
|
p.latitude = candidate.1;
|
||||||
|
p.zoom = candidate.2;
|
||||||
|
}
|
||||||
|
if p.valid() {
|
||||||
|
map("open", &json!(p));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
pub fn close() {
|
||||||
|
map("close", &Value::Null);
|
||||||
|
}
|
||||||
|
fn listen(name: &str, f: impl FnMut(Event) + 'static) {
|
||||||
|
let c = Closure::<dyn FnMut(Event)>::new(f);
|
||||||
|
let _ = document().add_event_listener_with_callback(name, c.as_ref().unchecked_ref());
|
||||||
|
c.forget();
|
||||||
|
}
|
||||||
|
pub fn init() {
|
||||||
|
let s = Rc::new(RefCell::new(State {
|
||||||
|
prefs: None,
|
||||||
|
estimate: None,
|
||||||
|
available: false,
|
||||||
|
running: false,
|
||||||
|
busy: false,
|
||||||
|
dirty: false,
|
||||||
|
}));
|
||||||
|
STATE.with(|slot| *slot.borrow_mut() = Some(s.clone()));
|
||||||
|
let state = s.clone();
|
||||||
|
listen("click", move |e| {
|
||||||
|
let Some(b) = e
|
||||||
|
.target()
|
||||||
|
.and_then(|t| t.dyn_into::<Element>().ok())
|
||||||
|
.and_then(|t| t.closest("[data-map-action]").ok().flatten())
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(action) = b.get_attribute("data-map-action") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let s = state.clone();
|
||||||
|
match action.as_str() {
|
||||||
|
"drawer" => {
|
||||||
|
drawer(el("map-settings-drawer").is_some_and(|e| e.has_attribute("hidden")))
|
||||||
|
}
|
||||||
|
"downloads" => {
|
||||||
|
drawer(true);
|
||||||
|
if let Some(e) = el("map-download-section") {
|
||||||
|
e.scroll_into_view();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"point" => {
|
||||||
|
map("tool", &json!("point"));
|
||||||
|
text(
|
||||||
|
"map-tool-hint",
|
||||||
|
"请点击地图选择起始点,随后点击保存。按 Esc 可退出。",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
"box" => {
|
||||||
|
map("tool", &json!("box"));
|
||||||
|
text(
|
||||||
|
"map-tool-hint",
|
||||||
|
"请在地图中拖出矩形范围。也可手动填写四侧坐标。按 Esc 可退出。",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
"current" => map("current", &Value::Null),
|
||||||
|
"reload" => {
|
||||||
|
if !s.borrow().busy {
|
||||||
|
spawn_local(load(s));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"save" => {
|
||||||
|
if !s.borrow().busy {
|
||||||
|
spawn_local(save(s));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"region-save" => {
|
||||||
|
let name = value("map-region-name").trim().to_owned();
|
||||||
|
let b = bounds();
|
||||||
|
if name.is_empty() || name.chars().count() > 40 || !b.valid() {
|
||||||
|
message(
|
||||||
|
"map-save-message",
|
||||||
|
"请填写有效区域范围和 1–40 字名称。",
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let mut state = s.borrow_mut();
|
||||||
|
if let Some(p) = state.prefs.as_mut() {
|
||||||
|
if let Some(r) = p.regions.iter_mut().find(|r| r.name == name) {
|
||||||
|
r.bounds = b
|
||||||
|
} else if p.regions.len() < 30 {
|
||||||
|
p.regions.push(Region { name, bounds: b })
|
||||||
|
} else {
|
||||||
|
message("map-save-message", "最多保存 30 个常用区域。", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
paint_regions(p);
|
||||||
|
state.dirty = true;
|
||||||
|
message(
|
||||||
|
"map-save-message",
|
||||||
|
"常用区域已加入草稿,请点击保存地图设置。",
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"region-delete" => {
|
||||||
|
if let Ok(index) = value("map-region").parse::<usize>() {
|
||||||
|
let mut state = s.borrow_mut();
|
||||||
|
if let Some(p) = state.prefs.as_mut()
|
||||||
|
&& index < p.regions.len()
|
||||||
|
{
|
||||||
|
p.regions.remove(index);
|
||||||
|
paint_regions(p);
|
||||||
|
state.dirty = true;
|
||||||
|
message(
|
||||||
|
"map-save-message",
|
||||||
|
"区域已从草稿移除,请点击保存地图设置。",
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"estimate" => {
|
||||||
|
let r = match request() {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
message("map-download-message", &e, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
s.borrow_mut().busy = true;
|
||||||
|
update_buttons(&s);
|
||||||
|
spawn_local(async move {
|
||||||
|
let result = post("/api/maps/downloads/estimate", &json!(r)).await;
|
||||||
|
s.borrow_mut().busy = false;
|
||||||
|
match result {
|
||||||
|
Ok(v) => {
|
||||||
|
text(
|
||||||
|
"map-estimate-message",
|
||||||
|
&format!(
|
||||||
|
"共 {} 张瓦片,估计约 {:.1} MiB(实际大小可能不同)。点击开始下载。",
|
||||||
|
v["tiles"],
|
||||||
|
v["estimatedBytes"].as_u64().unwrap_or(0) as f64 / 1048576.0
|
||||||
|
),
|
||||||
|
);
|
||||||
|
s.borrow_mut().estimate = Some(r);
|
||||||
|
}
|
||||||
|
Err(e) => message("map-download-message", &e, true),
|
||||||
|
}
|
||||||
|
update_buttons(&s);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
"start" => {
|
||||||
|
let Some(r) = s.borrow().estimate.clone() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if request().ok().map(|v| json!(v)) != Some(json!(r)) {
|
||||||
|
invalidate(&s);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s.borrow_mut().busy = true;
|
||||||
|
update_buttons(&s);
|
||||||
|
spawn_local(async move {
|
||||||
|
match post("/api/maps/downloads", &json!(r)).await {
|
||||||
|
Ok(_) => {
|
||||||
|
s.borrow_mut().estimate = None;
|
||||||
|
s.borrow_mut().running = true;
|
||||||
|
message("map-download-message", "下载任务已开始。", false);
|
||||||
|
}
|
||||||
|
Err(e) => message("map-download-message", &e, true),
|
||||||
|
}
|
||||||
|
s.borrow_mut().busy = false;
|
||||||
|
poll(s).await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
"cancel" => spawn_local(async move {
|
||||||
|
match post("/api/maps/downloads/cancel", &json!({})).await {
|
||||||
|
Ok(v) => message(
|
||||||
|
"map-download-message",
|
||||||
|
v["message"].as_str().unwrap_or("已请求取消"),
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
Err(e) => message("map-download-message", &e, true),
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let state = s.clone();
|
||||||
|
listen("input", move |e| {
|
||||||
|
let Some(id) = e
|
||||||
|
.target()
|
||||||
|
.and_then(|t| t.dyn_into::<Element>().ok())
|
||||||
|
.map(|t| t.id())
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if ["map-longitude", "map-latitude", "map-zoom"].contains(&id.as_str()) {
|
||||||
|
state.borrow_mut().dirty = true;
|
||||||
|
message(
|
||||||
|
"map-save-message",
|
||||||
|
"有未保存的修改。离开页面后草稿保留,重新加载页面前请保存。",
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if [
|
||||||
|
"map-west",
|
||||||
|
"map-south",
|
||||||
|
"map-east",
|
||||||
|
"map-north",
|
||||||
|
"map-min-zoom",
|
||||||
|
"map-max-zoom",
|
||||||
|
"map-download-road",
|
||||||
|
"map-download-imagery",
|
||||||
|
]
|
||||||
|
.contains(&id.as_str())
|
||||||
|
{
|
||||||
|
invalidate(&state);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let state = s.clone();
|
||||||
|
listen("change", move |e| {
|
||||||
|
let Some(id) = e
|
||||||
|
.target()
|
||||||
|
.and_then(|t| t.dyn_into::<Element>().ok())
|
||||||
|
.map(|t| t.id())
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
match id.as_str() {
|
||||||
|
"map-basemap" => {
|
||||||
|
state.borrow_mut().dirty = true;
|
||||||
|
map("setBasemap", &json!(value("map-basemap")));
|
||||||
|
message(
|
||||||
|
"map-save-message",
|
||||||
|
"底图已预览,点击保存后作为默认底图。",
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
"map-region" => {
|
||||||
|
if let Ok(i) = value("map-region").parse::<usize>()
|
||||||
|
&& let Some(p) = state.borrow().prefs.as_ref()
|
||||||
|
&& let Some(r) = p.regions.get(i)
|
||||||
|
{
|
||||||
|
set_bounds(&r.bounds);
|
||||||
|
set("map-region-name", &r.name);
|
||||||
|
map("bounds", &json!(r.bounds));
|
||||||
|
}
|
||||||
|
invalidate(&state);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
for event in ["rid-map-point", "rid-map-bounds", "rid-map-error"] {
|
||||||
|
let state = s.clone();
|
||||||
|
let name = event.to_owned();
|
||||||
|
let c = Closure::<dyn FnMut(web_sys::CustomEvent)>::new(move |e: web_sys::CustomEvent| {
|
||||||
|
let v = js_sys::JSON::stringify(&e.detail())
|
||||||
|
.ok()
|
||||||
|
.and_then(|s| s.as_string())
|
||||||
|
.and_then(|s| serde_json::from_str::<Value>(&s).ok())
|
||||||
|
.unwrap_or(Value::Null);
|
||||||
|
match name.as_str() {
|
||||||
|
"rid-map-point" => {
|
||||||
|
for (id, key) in [
|
||||||
|
("map-longitude", "longitude"),
|
||||||
|
("map-latitude", "latitude"),
|
||||||
|
("map-zoom", "zoom"),
|
||||||
|
] {
|
||||||
|
if let Some(n) = v[key].as_f64() {
|
||||||
|
set(id, &format!("{n:.6}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state.borrow_mut().dirty = true;
|
||||||
|
message("map-save-message", "起始点已选定,请保存地图设置。", false);
|
||||||
|
}
|
||||||
|
"rid-map-bounds" => {
|
||||||
|
if let Ok(b) = serde_json::from_value::<Bounds>(v)
|
||||||
|
&& b.valid()
|
||||||
|
{
|
||||||
|
set_bounds(&b);
|
||||||
|
drawer(true);
|
||||||
|
invalidate(&state);
|
||||||
|
text(
|
||||||
|
"map-tool-hint",
|
||||||
|
"已选中下载范围。请检查层级与图层,核算后手动开始下载。",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => text(
|
||||||
|
"map-tool-hint",
|
||||||
|
v["message"].as_str().unwrap_or("地图操作失败"),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if let Some(w) = web_sys::window() {
|
||||||
|
let _ = w.add_event_listener_with_callback(event, c.as_ref().unchecked_ref());
|
||||||
|
}
|
||||||
|
c.forget();
|
||||||
|
}
|
||||||
|
spawn_local(async move {
|
||||||
|
loop {
|
||||||
|
if visible() {
|
||||||
|
poll(s.clone()).await;
|
||||||
|
}
|
||||||
|
TimeoutFuture::new(2000).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -292,11 +292,40 @@ pub fn Realtime() -> impl IntoView {
|
|||||||
let stop = stopped.clone();
|
let stop = stopped.clone();
|
||||||
let workers = worker_holder.clone();
|
let workers = worker_holder.clone();
|
||||||
spawn_local(async move {
|
spawn_local(async move {
|
||||||
|
let preferences = if let Ok(response) =
|
||||||
|
gloo_net::http::Request::get("/api/maps/preferences")
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
if response.ok() {
|
||||||
|
response.json::<Value>().await.ok()
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
if let Some(value) = preferences.as_ref().and_then(|p| p["basemap"].as_str()) {
|
||||||
|
basemap.set(value.to_owned());
|
||||||
|
}
|
||||||
|
let initial_camera = preferences
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|p| js_sys::JSON::parse(&p.to_string()).ok())
|
||||||
|
.unwrap_or(JsValue::NULL);
|
||||||
for _ in 0..100 {
|
for _ in 0..100 {
|
||||||
if stop.get() {
|
if stop.get() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if map_call("create", &["rt-map".into(), basemap.get_untracked().into()]).is_ok() {
|
if map_call(
|
||||||
|
"create",
|
||||||
|
&[
|
||||||
|
"rt-map".into(),
|
||||||
|
basemap.get_untracked().into(),
|
||||||
|
initial_camera.clone(),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
TimeoutFuture::new(50).await;
|
TimeoutFuture::new(50).await;
|
||||||
@@ -516,7 +545,7 @@ pub fn Realtime() -> impl IntoView {
|
|||||||
view! {
|
view! {
|
||||||
<main class="rt-page"><div id="rt-layout" class="mc-layout-b" class:compact=move||layout.compact.get() class:dock-hidden=move||!layout.dock_visible() class:list-hidden=move||!layout.list_visible() class:detail-hidden=move||!layout.detail_visible() data-lists-open=move||lists.open.get().to_string() style=("--dock-height",move||format!("{}px",layout.height.get()))>
|
<main class="rt-page"><div id="rt-layout" class="mc-layout-b" class:compact=move||layout.compact.get() class:dock-hidden=move||!layout.dock_visible() class:list-hidden=move||!layout.list_visible() class:detail-hidden=move||!layout.detail_visible() data-lists-open=move||lists.open.get().to_string() style=("--dock-height",move||format!("{}px",layout.height.get()))>
|
||||||
<section class="mc-map-area-top"><div tabindex="-1" id="rt-map" class="rt-map-canvas"></div>
|
<section class="mc-map-area-top"><div tabindex="-1" id="rt-map" class="rt-map-canvas"></div>
|
||||||
<div class="live-panel-restores"><button id="rt-list-manager-open" title="管理黑白名单" aria-label="管理黑白名单" hidden=move||layout.list_visible() on:click=move |_|lists.show()>"名单管理"</button>
|
<div class="live-panel-restores"><button id="rt-list-manager-open" aria-controls="rt-list-manager" aria-expanded=move||lists.open.get().to_string() title="管理黑白名单" aria-label="管理黑白名单" hidden=move||layout.list_visible() on:click=move |_|lists.show()>"名单管理"</button>
|
||||||
<button id="rt-list-toggle" title="显示目标目录" aria-label="显示目标目录" aria-controls="rt-directory" hidden=move||layout.list_visible() on:click=move |_|layout.toggle_list()>"目标目录"</button>
|
<button id="rt-list-toggle" title="显示目标目录" aria-label="显示目标目录" aria-controls="rt-directory" hidden=move||layout.list_visible() on:click=move |_|layout.toggle_list()>"目标目录"</button>
|
||||||
<button id="rt-detail-toggle" title="显示目标详情" aria-label="显示目标详情" aria-controls="rt-details" hidden=move||layout.detail_visible() on:click=move |_|layout.toggle_detail()>"目标详情"</button>
|
<button id="rt-detail-toggle" title="显示目标详情" aria-label="显示目标详情" aria-controls="rt-details" hidden=move||layout.detail_visible() on:click=move |_|layout.toggle_detail()>"目标详情"</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -524,10 +553,10 @@ pub fn Realtime() -> impl IntoView {
|
|||||||
<div class="mc-map-infobar">{move||map_label(&map_status.get(),&basemap.get())}</div>
|
<div class="mc-map-infobar">{move||map_label(&map_status.get(),&basemap.get())}</div>
|
||||||
</section>
|
</section>
|
||||||
<aside id="rt-directory" class="mc-floating-panel live-targets" aria-label="目标目录" hidden=move||!layout.list_visible()>
|
<aside id="rt-directory" class="mc-floating-panel live-targets" aria-label="目标目录" hidden=move||!layout.list_visible()>
|
||||||
<div class="live-panel-head"><h2>"目标目录"</h2><button id="rt-list-manager-from-directory" title="管理黑白名单" aria-label="管理黑白名单" on:click=move |_|lists.show()>"名单管理"</button><button title="收起目标目录" aria-label="收起目标目录" on:click=move |_|{layout.toggle_list();super::realtime_layout::focus("rt-list-toggle");}>"‹"</button></div><div class="live-list-controls">
|
<div class="live-panel-head"><h2>"目标目录"</h2><button id="rt-list-manager-from-directory" aria-controls="rt-list-manager" aria-expanded=move||lists.open.get().to_string() title="管理黑白名单" aria-label="管理黑白名单" on:click=move |_|lists.show()>"名单管理"</button><button title="收起目标目录" aria-label="收起目标目录" on:click=move |_|{layout.toggle_list();super::realtime_layout::focus("rt-list-toggle");}>"‹"</button></div><div class="live-list-controls">
|
||||||
<span class="live-data-label rt-status">{move||status.get()}</span>
|
<span class="live-data-label rt-status">{move||status.get()}</span>
|
||||||
<input class="live-search" aria-label="搜索实时目标" placeholder="搜索目标标识" prop:value=move||query.get() on:input=move|e|{query.set(event_target_value(&e));page.set(0);}/>
|
<input class="live-search" aria-label="搜索实时目标" placeholder="搜索目标标识" prop:value=move||query.get() on:input=move|e|{query.set(event_target_value(&e));page.set(0);}/>
|
||||||
<span class="live-data-label">{move||format!("目标 {} · 数据年龄 {} ms",ids.get().len(),age.get())}</span><div class="rt-target-list-filters" role="group" aria-label="目标名单筛选">{[Filter::All,Filter::White,Filter::Black,Filter::Unknown].into_iter().map(move |filter|view!{<button type="button" disabled=move||!lists.ready.get() aria-pressed=move||(lists.filter.get()==filter).to_string() on:click=move |_|{lists.filter.set(filter);page.set(0);}>{filter.label()}" "{move||{let kinds=classification.get();ids.with(|targets|targets.iter().filter(|id|filter.matches(kinds.get(*id).copied())).count())}}</button>}).collect_view()}</div><p class="rt-list-sync-error" role="status" hidden=move||lists.sync_error.get().is_empty()>{move||lists.sync_error.get()}<button type="button" on:click=move |_|spawn_local(lists.refresh())>"重试"</button></p>
|
<span class="live-data-label">{move||format!("目标 {} · 数据年龄 {} ms",ids.get().len(),age.get())}</span><div class="rt-target-list-filters" role="group" aria-label="目标名单筛选">{[Filter::All,Filter::White,Filter::Black,Filter::Unknown].into_iter().map(move |filter|view!{<button type="button" disabled=move||!lists.ready.get() aria-pressed=move||(lists.filter.get()==filter).to_string() on:click=move |_|{lists.filter.set(filter);page.set(0);}>{filter.label()}" "{move||{if !lists.ready.get() && filter!=Filter::All {"—".to_owned()}else{let kinds=classification.get();ids.with(|targets|targets.iter().filter(|id|filter.matches(kinds.get(*id).copied())).count()).to_string()}}}</button>}).collect_view()}</div><p class="rt-list-sync-error" role="status" hidden=move||lists.sync_error.get().is_empty()>{move||lists.sync_error.get()}<button type="button" on:click=move |_|spawn_local(lists.refresh())>"重试"</button></p>
|
||||||
</div><div class="live-list-body"><div class="live-target-list">{move||filtered.get().into_iter().skip(visible_page.get()*100).take(100).map(|id|{let check=id.clone();let pick=id.clone();let badge_id=id.clone();let description_id=id.clone();view!{<button class="rt-target" aria-label=id.clone() aria-description=move||if lists.ready.get(){super::target_lists::label(lists.kind(&description_id))}else{"名单未知"} aria-pressed=move||(selected.get()==check).to_string() on:click=move |_|choose(pick.clone())><span aria-hidden="true">"◈"</span><span class="rt-target-id">{id.clone()}</span><Badge lists=lists target=badge_id/></button>}}).collect_view()}</div>
|
</div><div class="live-list-body"><div class="live-target-list">{move||filtered.get().into_iter().skip(visible_page.get()*100).take(100).map(|id|{let check=id.clone();let pick=id.clone();let badge_id=id.clone();let description_id=id.clone();view!{<button class="rt-target" aria-label=id.clone() aria-description=move||if lists.ready.get(){super::target_lists::label(lists.kind(&description_id))}else{"名单未知"} aria-pressed=move||(selected.get()==check).to_string() on:click=move |_|choose(pick.clone())><span aria-hidden="true">"◈"</span><span class="rt-target-id">{id.clone()}</span><Badge lists=lists target=badge_id/></button>}}).collect_view()}</div>
|
||||||
<p class="live-empty" hidden=move||!filtered.get().is_empty()>{move||if ids.get().is_empty(){"暂无目标。请检查接收器和数据源。"}else{"没有匹配的目标。"}}</p>
|
<p class="live-empty" hidden=move||!filtered.get().is_empty()>{move||if ids.get().is_empty(){"暂无目标。请检查接收器和数据源。"}else{"没有匹配的目标。"}}</p>
|
||||||
</div><nav class="pagination"><button disabled=move||{visible_page.get()==0} on:click=move |_|page.set(visible_page.get().saturating_sub(1))>"上一组"</button><span>{move||format!("{} / {}",visible_page.get()+1,filtered.get().len().div_ceil(100).max(1))}</span><button disabled=move||{(visible_page.get()+1)*100>=filtered.get().len()} on:click=move |_|page.set(visible_page.get()+1)>"下一组"</button></nav>
|
</div><nav class="pagination"><button disabled=move||{visible_page.get()==0} on:click=move |_|page.set(visible_page.get().saturating_sub(1))>"上一组"</button><span>{move||format!("{} / {}",visible_page.get()+1,filtered.get().len().div_ceil(100).max(1))}</span><button disabled=move||{(visible_page.get()+1)*100>=filtered.get().len()} on:click=move |_|page.set(visible_page.get()+1)>"下一组"</button></nav>
|
||||||
|
|||||||
@@ -127,7 +127,11 @@ impl Lists {
|
|||||||
match result {
|
match result {
|
||||||
Ok(Some(snapshot)) => self.apply(snapshot),
|
Ok(Some(snapshot)) => self.apply(snapshot),
|
||||||
Ok(None) => self.sync_error.set(String::new()),
|
Ok(None) => self.sync_error.set(String::new()),
|
||||||
Err(error) => self.sync_error.set(error.into()),
|
Err(error) => self.sync_error.set(if self.ready.get_untracked() {
|
||||||
|
format!("{error};暂用上次名单")
|
||||||
|
} else {
|
||||||
|
error.into()
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn kind(self, id: &str) -> Option<ListKind> {
|
pub fn kind(self, id: &str) -> Option<ListKind> {
|
||||||
@@ -141,15 +145,39 @@ impl Lists {
|
|||||||
}
|
}
|
||||||
pub fn show(self) {
|
pub fn show(self) {
|
||||||
self.open.set(true);
|
self.open.set(true);
|
||||||
|
super::realtime_layout::focus("rt-list-manager");
|
||||||
}
|
}
|
||||||
pub fn close(self) {
|
pub fn close(self) {
|
||||||
self.open.set(false);
|
self.open.set(false);
|
||||||
let directory_visible = super::realtime_layout::element("rt-directory")
|
// Layout compactness is reconciled every 100 ms; choose a visible return
|
||||||
.is_some_and(|e| !e.has_attribute("hidden"));
|
// target after that reconciliation rather than a button about to hide.
|
||||||
super::realtime_layout::focus(if directory_visible {
|
spawn_local(async move {
|
||||||
"rt-list-manager-from-directory"
|
gloo_timers::future::TimeoutFuture::new(150).await;
|
||||||
} else {
|
if self.open.get_untracked() {
|
||||||
"rt-list-manager-open"
|
return;
|
||||||
|
}
|
||||||
|
let Some(document) = web_sys::window().and_then(|window| window.document()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if document.active_element().is_some_and(|active| {
|
||||||
|
active.tag_name() != "BODY"
|
||||||
|
&& active.closest("#rt-list-manager").ok().flatten().is_none()
|
||||||
|
}) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for id in ["rt-list-manager-from-directory", "rt-list-manager-open"] {
|
||||||
|
if let Some(element) = super::realtime_layout::element(id)
|
||||||
|
.filter(|element| element.client_height() > 0)
|
||||||
|
{
|
||||||
|
let _ = element.focus();
|
||||||
|
if document
|
||||||
|
.active_element()
|
||||||
|
.is_some_and(|active| active.id() == id)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
pub fn edit(self, id: String) {
|
pub fn edit(self, id: String) {
|
||||||
@@ -299,6 +327,17 @@ pub(super) fn Badge(lists: Lists, target: String) -> impl IntoView {
|
|||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
pub(super) fn Manager(lists: Lists) -> impl IntoView {
|
pub(super) fn Manager(lists: Lists) -> impl IntoView {
|
||||||
|
let escape = window_event_listener(leptos::ev::keydown, move |event| {
|
||||||
|
let realtime = web_sys::window()
|
||||||
|
.and_then(|window| window.document())
|
||||||
|
.and_then(|document| document.body())
|
||||||
|
.is_some_and(|body| body.get_attribute("data-screen").as_deref() == Some("realtime"));
|
||||||
|
if event.key() == "Escape" && lists.open.get_untracked() && realtime {
|
||||||
|
event.prevent_default();
|
||||||
|
lists.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
on_cleanup(move || escape.remove());
|
||||||
let rows = Memo::new(move |_| {
|
let rows = Memo::new(move |_| {
|
||||||
let query = lists.query.get().to_lowercase();
|
let query = lists.query.get().to_lowercase();
|
||||||
let filter = lists.manager_filter.get();
|
let filter = lists.manager_filter.get();
|
||||||
@@ -322,20 +361,20 @@ pub(super) fn Manager(lists: Lists) -> impl IntoView {
|
|||||||
.min(rows.get().len().div_ceil(50).max(1) - 1)
|
.min(rows.get().len().div_ceil(50).max(1) - 1)
|
||||||
});
|
});
|
||||||
view! {
|
view! {
|
||||||
<aside id="rt-list-manager" class="rt-list-manager" aria-label="黑白名单管理" hidden=move||!lists.open.get() on:keydown=move|event|{if event.key()=="Escape"{event.stop_propagation();lists.close();}}>
|
<aside id="rt-list-manager" tabindex="-1" class="rt-list-manager" aria-label="黑白名单管理" hidden=move||!lists.open.get()>
|
||||||
<header class="rt-list-manager-head"><h2>"黑白名单管理"</h2><button type="button" disabled=move||lists.busy.get() on:click=move |_|{lists.draft_id.set(String::new());lists.draft_note.set(String::new());lists.editing.set(false);lists.message.set(String::new());super::realtime_layout::focus("rt-list-entry-id");}>"新增条目"</button><button type="button" aria-label="关闭名单管理" on:click=move |_|lists.close()>"关闭"</button></header>
|
<header class="rt-list-manager-head"><h2>"黑白名单管理"</h2><button type="button" disabled=move||lists.busy.get() on:click=move |_|{lists.draft_id.set(String::new());lists.draft_note.set(String::new());lists.editing.set(false);lists.message.set(String::new());super::realtime_layout::focus("rt-list-entry-id");}>"新增条目"</button><button type="button" aria-label="关闭名单管理" on:click=move |_|lists.close()>"关闭"</button></header>
|
||||||
<div class="rt-list-manager-body">
|
<div class="rt-list-manager-body">
|
||||||
<p class="rt-list-help">"按目标标识精确匹配,区分大小写。名单独立于备案档案;可提前录入离线目标。"</p>
|
<p class="rt-list-help">"按目标标识精确匹配,区分大小写。名单独立于备案档案;可提前录入离线目标。"</p>
|
||||||
<div class="rt-list-tabs" role="group" aria-label="管理名单分类">{[Filter::All,Filter::White,Filter::Black].into_iter().map(move |filter|view!{<button type="button" aria-pressed=move||(lists.manager_filter.get()==filter).to_string() on:click=move |_|{lists.manager_filter.set(filter);lists.manager_page.set(0);}>{filter.label()}" "{move||lists.snapshot.with(|s|s.entries.iter().filter(|entry|filter.matches(Some(entry.list_kind))).count())}</button>}).collect_view()}</div>
|
<div class="rt-list-tabs" role="group" aria-label="管理名单分类">{[Filter::All,Filter::White,Filter::Black].into_iter().map(move |filter|view!{<button type="button" aria-pressed=move||(lists.manager_filter.get()==filter).to_string() on:click=move |_|{lists.manager_filter.set(filter);lists.manager_page.set(0);}>{filter.label()}" "{move||if lists.ready.get(){lists.snapshot.with(|s|s.entries.iter().filter(|entry|filter.matches(Some(entry.list_kind))).count()).to_string()}else{"—".into()}}</button>}).collect_view()}</div>
|
||||||
<label class="rt-list-search"><span>"搜索名单"</span><input placeholder="搜索目标标识或备注" prop:value=move||lists.query.get() on:input=move|event|{lists.query.set(event_target_value(&event));lists.manager_page.set(0);}/></label>
|
<label class="rt-list-search"><span>"搜索名单"</span><input placeholder="搜索目标标识或备注" prop:value=move||lists.query.get() on:input=move|event|{lists.query.set(event_target_value(&event));lists.manager_page.set(0);}/></label>
|
||||||
<p class="rt-list-help" hidden=move||lists.ready.get()>"正在读取本机名单…"</p>
|
<p class="rt-list-help" hidden=move||lists.ready.get()>"正在读取本机名单…"</p>
|
||||||
<p class="rt-list-sync-error" role="status" hidden=move||lists.sync_error.get().is_empty()>{move||lists.sync_error.get()}<button type="button" on:click=move |_|spawn_local(lists.refresh())>"重试"</button></p>
|
<p class="rt-list-sync-error" role="status" hidden=move||lists.sync_error.get().is_empty()>{move||lists.sync_error.get()}<button type="button" on:click=move |_|spawn_local(lists.refresh())>"重试"</button></p>
|
||||||
<div class="rt-list-rows"><For each={move||rows.get().into_iter().skip(page.get()*50).take(50).collect::<Vec<_>>()} key=|entry|entry.target_id.clone() children=move |entry|{
|
<div class="rt-list-rows"><For each={move||rows.get().into_iter().skip(page.get()*50).take(50).collect::<Vec<_>>()} key=|entry|entry.target_id.clone() children=move |entry|{
|
||||||
let edit_id=entry.target_id.clone();let remove_id=entry.target_id.clone();let badge_id=entry.target_id.clone();
|
let edit_id=entry.target_id.clone();let remove_id=entry.target_id.clone();let badge_id=entry.target_id.clone();let note_id=entry.target_id.clone();
|
||||||
view!{<div class="rt-list-row" data-target-id=entry.target_id.clone()><div class="rt-list-row-main"><strong>{entry.target_id.clone()}</strong><p>{entry.note.clone()}</p></div><Badge lists=lists target=badge_id/><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.edit(edit_id.clone())>"编辑"</button><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.remove(remove_id.clone())>"移除"</button></div>}
|
view!{<div class="rt-list-row" data-target-id=entry.target_id.clone()><div class="rt-list-row-main"><strong>{entry.target_id.clone()}</strong><p>{move||lists.snapshot.with(|snapshot|snapshot.entries.iter().find(|entry|entry.target_id==note_id).map(|entry|entry.note.clone()).unwrap_or_default())}</p></div><Badge lists=lists target=badge_id/><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.edit(edit_id.clone())>"编辑"</button><button type="button" disabled=move||lists.busy.get() on:click=move |_|lists.remove(remove_id.clone())>"移除"</button></div>}
|
||||||
}/></div>
|
}/></div>
|
||||||
<p class="rt-list-help" hidden=move||!lists.ready.get()||!rows.get().is_empty()>"暂无匹配条目,可在下面新增。"</p>
|
<p class="rt-list-help" hidden=move||!lists.ready.get()||!rows.get().is_empty()>"暂无匹配条目,可在下面新增。"</p>
|
||||||
<nav class="rt-list-pagination" aria-label="名单分页"><button type="button" disabled=move||page.get()==0 on:click=move |_|lists.manager_page.set(page.get().saturating_sub(1))>"上一页"</button><span>{move||format!("{} / {}",page.get()+1,rows.get().len().div_ceil(50).max(1))}</span><button type="button" disabled=move||(page.get()+1)*50>=rows.get().len() on:click=move |_|lists.manager_page.set(page.get()+1)>"下一页"</button></nav>
|
<nav class="rt-list-pagination" aria-label="名单分页"><button type="button" disabled=move||page.get()==0 on:click=move |_|lists.manager_page.set(page.get().saturating_sub(1))>"上一页"</button><span>{move||format!("{} / {}",page.get()+1,rows.get().len().div_ceil(50).max(1))}</span><button type="button" disabled={move||(page.get()+1)*50>=rows.get().len()} on:click=move |_|lists.manager_page.set(page.get()+1)>"下一页"</button></nav>
|
||||||
<form id="rt-list-entry-form" on:submit=move |event|{event.prevent_default();lists.save(lists.draft_id.get_untracked().trim().to_owned(),lists.draft_kind.get_untracked(),lists.draft_note.get_untracked());}>
|
<form id="rt-list-entry-form" on:submit=move |event|{event.prevent_default();lists.save(lists.draft_id.get_untracked().trim().to_owned(),lists.draft_kind.get_untracked(),lists.draft_note.get_untracked());}>
|
||||||
<h3>{move||if lists.editing.get(){"编辑名单条目"}else{"新增名单条目"}}</h3>
|
<h3>{move||if lists.editing.get(){"编辑名单条目"}else{"新增名单条目"}}</h3>
|
||||||
<label for="rt-list-entry-id">"目标标识"</label><input id="rt-list-entry-id" required maxlength="64" pattern="[A-Za-z0-9_-]{1,64}" autocomplete="off" readonly=move||lists.editing.get() disabled=move||lists.busy.get() prop:value=move||lists.draft_id.get() on:input=move|event|lists.draft_id.set(event_target_value(&event))/>
|
<label for="rt-list-entry-id">"目标标识"</label><input id="rt-list-entry-id" required maxlength="64" pattern="[A-Za-z0-9_-]{1,64}" autocomplete="off" readonly=move||lists.editing.get() disabled=move||lists.busy.get() prop:value=move||lists.draft_id.get() on:input=move|event|lists.draft_id.set(event_target_value(&event))/>
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -269,7 +269,7 @@ fn show(view: &str, realtime: bool) {
|
|||||||
.body()
|
.body()
|
||||||
.and_then(|body| body.get_attribute("data-screen"));
|
.and_then(|body| body.get_attribute("data-screen"));
|
||||||
let view = match view {
|
let view = match view {
|
||||||
"register" | "realtime" | "settings" => view,
|
"register" | "realtime" | "settings" | "maps" => view,
|
||||||
_ => "home",
|
_ => "home",
|
||||||
};
|
};
|
||||||
if (view == "realtime" && !realtime) || (view == "register" && realtime) {
|
if (view == "realtime" && !realtime) || (view == "register" && realtime) {
|
||||||
@@ -283,8 +283,17 @@ fn show(view: &str, realtime: bool) {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
hidden("workspace-content", view == "home" || view == "settings");
|
hidden(
|
||||||
|
"workspace-content",
|
||||||
|
matches!(view, "home" | "settings" | "maps"),
|
||||||
|
);
|
||||||
hidden("appearance-view", view != "settings");
|
hidden("appearance-view", view != "settings");
|
||||||
|
hidden("map-settings-view", view != "maps");
|
||||||
|
if view == "maps" {
|
||||||
|
crate::map_settings::open();
|
||||||
|
} else {
|
||||||
|
crate::map_settings::close();
|
||||||
|
}
|
||||||
text(
|
text(
|
||||||
"workspace-brand",
|
"workspace-brand",
|
||||||
if view == "home" {
|
if view == "home" {
|
||||||
@@ -309,11 +318,14 @@ fn show(view: &str, realtime: bool) {
|
|||||||
"register" => "设备登记",
|
"register" => "设备登记",
|
||||||
"realtime" => "实时目标工作台",
|
"realtime" => "实时目标工作台",
|
||||||
"settings" => "壁纸与外观",
|
"settings" => "壁纸与外观",
|
||||||
|
"maps" => "地图配置",
|
||||||
_ => "应用总览",
|
_ => "应用总览",
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
each("[data-menu]", |e| {
|
each("[data-menu]", |e| {
|
||||||
if e.get_attribute("data-menu").as_deref() == Some(view) {
|
if e.get_attribute("data-menu").as_deref()
|
||||||
|
== Some(if view == "maps" { "settings" } else { view })
|
||||||
|
{
|
||||||
let _ = e.set_attribute("aria-current", "page");
|
let _ = e.set_attribute("aria-current", "page");
|
||||||
} else {
|
} else {
|
||||||
let _ = e.remove_attribute("aria-current");
|
let _ = e.remove_attribute("aria-current");
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# 地图配置与手动离线下载
|
||||||
|
|
||||||
|
## 设置入口与 C 布局
|
||||||
|
|
||||||
|
从应用设置的「壁纸与外观」左侧进入「地图配置」。地图占据主工作区,右侧抽屉可收起。
|
||||||
|
既有深海蓝玻璃材质、壁纸及外观接口保持不变。
|
||||||
|
|
||||||
|
- 默认底图:天地图影像 + 路网标注,或天地图路网图 + 中文标注。
|
||||||
|
- 默认定位:地图选点、采用当前地图中心,或输入 WGS84 经度、纬度及 0–18 级缩放。
|
||||||
|
- 点击「保存地图设置」后生效;实时目标地图下次创建时读取此默认位置和底图。打开设置不会重置正在运行的接收器。
|
||||||
|
- 常用区域由用户框选或填写四侧坐标后命名保存,可再次选择;不是内置行政区划数据库。最多 30 个,不支持跨日期变更线的单个范围。
|
||||||
|
|
||||||
|
配置保存在 `--data-root/maps/preferences.json`,不与 `maps/config.json` 的天地图密钥混存。
|
||||||
|
采用版本冲突检查,其他窗口保存后旧版本返回 409;重新加载会丢弃当前草稿。
|
||||||
|
损坏配置不自动覆盖,原文件保留等待修复。真实运行数据仍不提交 Git。
|
||||||
|
|
||||||
|
## 联网与离线行为
|
||||||
|
|
||||||
|
浏览器及 Go 进程只访问本机瓦片代理,密钥继续保留在 Rust 服务端。
|
||||||
|
当前代理可能从缓存、天地图或离线文件返回瓦片;离线准备也可将已有缓存变成持久离线瓦片。
|
||||||
|
无覆盖、无可用缓存且无法访问上游的瓦片会下载失败,不生成假图,不将部分下载标为完整。
|
||||||
|
界面区分密钥未配置、配置损坏、上游当前不可用和本机服务不可达。
|
||||||
|
|
||||||
|
下载步骤:框选/填写/选择常用区域 → 选择路网、影像和层级 → 核算 → 手动开始。
|
||||||
|
单次最多 20000 张(底图与标注分别计数);大小按每张 50 KB 估算,实际大小以结果为准。
|
||||||
|
一次只允许一个下载任务,可取消;已完成且通过校验的瓦片保留,重试跳过有效文件、补齐缺失或损坏文件。
|
||||||
|
任务状态为进程内状态,重启后不自动恢复任务;可重新选择范围手动补齐。
|
||||||
|
|
||||||
|
## Go 开源来源与构建
|
||||||
|
|
||||||
|
适配器位于 `scripts/map-downloader/`,基于 MIT 项目
|
||||||
|
<https://github.com/Cyclenerd/offline-map-tile-downloader> 的 Web Mercator 算法改编,
|
||||||
|
固定来源提交 `9b61800537b2c50a71345dfed3bbc0fcd8731711`。
|
||||||
|
这不是原项目全部网页服务的直接嵌入:本项目提供无额外依赖的 JSON 标准输入适配、限速下载、进度输出和图像校验。
|
||||||
|
原始许可证保留在 `scripts/map-downloader/LICENSE-upstream.txt`,随发布包携带。
|
||||||
|
|
||||||
|
运行 `./scripts/build-map-downloader.ps1`,使用本机 Go 1.22 或兼容版本构建:
|
||||||
|
|
||||||
|
- 工具:`D:/Rust_Contact/util/tools/rid-map-downloader/0.1.0/rid-map-downloader.exe`
|
||||||
|
- Go 缓存:统一 `D:/Rust_Contact/util/tools/` 下的 `go-cache` 与 `go-modules`
|
||||||
|
- 覆盖入口:当前进程 `RID_MAP_DOWNLOADER`;不修改系统全局配置。
|
||||||
|
- 发布包内包含同目录的 `rid-map-downloader.exe` 和 `map-downloader-LICENSE.txt`。
|
||||||
|
|
||||||
|
下载器最多 4 个并发,全局每 250 ms 放行一次请求,单请求最多 15 秒。
|
||||||
|
只允许本机 HTTP 代理地址,禁止重定向和路径符号链接,瓦片最大 2 MiB,必须能完整解码为 256×256 PNG/JPEG。
|
||||||
|
文件写入临时文件并原子替换到 `maps/offline/{layer}/{z}/{x}/{y}.png`。
|
||||||
|
扩展名统一 png,具体 MIME 按内容识别,因此 JPEG 影像仍可被现有代理读取。
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
- `GET /api/maps/preferences`:读取默认底图、中心点、缩放、常用区域与 revision。
|
||||||
|
- `PUT /api/maps/preferences`:保存完整配置,要求 revision 与当前值一致。
|
||||||
|
- `POST /api/maps/downloads/estimate`:参数 bounds、minZoom、maxZoom、road、imagery;返回 tiles、estimatedBytes。
|
||||||
|
- `POST /api/maps/downloads`:同上;创建任务返回 202,已有任务返回 409。
|
||||||
|
- `GET /api/maps/downloads`:available 与当前/最近任务 state、total、done、failed、message。
|
||||||
|
- `POST /api/maps/downloads/cancel`:请求取消,部分瓦片保留。
|
||||||
|
|
||||||
|
这些接口沿用本机来源限制。bounds 字段为 west、south、east、north,纬度约束为 ±85.051128°。
|
||||||
|
|
||||||
|
## 验证边界
|
||||||
|
|
||||||
|
相关验证入口:共享模型及宿主单元测试、宿主/wasm Clippy、Go 单元测试,
|
||||||
|
以及 `node scripts/test-map-settings.mjs` 的 Rust/Wasm + Go 隔离实例联测。
|
||||||
|
集成测试使用真实 Go 子进程和本机合成瓦片,不使用真实天地图密钥、不打开接收器。
|
||||||
|
测试通过不代表真实天地图账号的批量下载配额、目标地区覆盖及设备运行已获验证。
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# 实时目标黑白名单
|
||||||
|
|
||||||
|
## 业务规则
|
||||||
|
|
||||||
|
- 按实时 `target_id` 精确匹配,区分大小写,不将设备 SN 或备案状态自动解释为名单身份。
|
||||||
|
- 同一目标只有白名单、黑名单中的一种;移除条目后恢复未分类。
|
||||||
|
- 白名单为人工可信分类,黑名单用于人工关注;两者均不改变接收器配置、遥测接收和登记档案。
|
||||||
|
- 支持在线目标快捷加入、离线目标提前录入、备注、搜索、分页和移除。
|
||||||
|
- 目标标识为 1–64 位 ASCII 字母、数字、短横线、下划线;备注最多 200 个字符。最多保存 5000 条名单。
|
||||||
|
|
||||||
|
## 界面与告警
|
||||||
|
|
||||||
|
采用已选定的 A 方案:目标详情中快捷标记,右侧按需展开名单管理侧栏。
|
||||||
|
|
||||||
|
目标目录和地图使用同一名单筛选;筛选只影响显示,原始接收数量与数据流不变。名单加载失败时显示“名单未知”,已有快照同步失败时明确提示暂用上次名单,不把读取失败解释为空名单。
|
||||||
|
|
||||||
|
黑名单用红色、白名单用绿色,配合文字与符号区分。选中目标仍保留选中反馈。黑名单告警按全部在线目标计算,不因当前显示筛选而关闭。
|
||||||
|
|
||||||
|
同一目标连续在线且持续属于黑名单时只记一次命中;高频遥测、备注更新、筛选和连接状态变化不会重复刷屏。目标实际过期离线后重新出现,或从其他分类再次进入黑名单时重新记录。
|
||||||
|
|
||||||
|
告警复用当前工作台事件面板及其有界事件缓存。名单持久化,但当前版本不提供跨重启的长期告警历史。
|
||||||
|
|
||||||
|
## 本机存储与接口
|
||||||
|
|
||||||
|
名单保存在当前数据目录的 `registry/data/registry.sqlite`,新增 `target_list_entries` 和 `target_list_state` 两张表。初始化可重复执行,不修改原有登记或照片表;名单不依赖登记记录外键。
|
||||||
|
|
||||||
|
- `GET /api/target-lists`:返回 `{ revision, entries }`。
|
||||||
|
- `GET /api/target-lists?revision=N`:版本相同时返回 HTTP 304,无响应正文;不同时返回完整快照。
|
||||||
|
- `PUT /api/target-lists/{target_id}`:创建或更新,正文为 `{ list_kind, note, expected_revision }`。
|
||||||
|
- `DELETE /api/target-lists/{target_id}?revision=N`:移除条目,返回更新后的快照。
|
||||||
|
|
||||||
|
`list_kind` 为 `white` 或 `black`。条目字段为 `target_id`、`list_kind`、`note`、`updated_at`,时间由服务端生成。接口继承应用的本机来源检查。
|
||||||
|
|
||||||
|
修改与版本递增在同一 SQLite 事务中执行。相同内容重复保存或移除不存在的目标不递增版本。客户端版本过旧时返回 HTTP 400,提示刷新后重试;不会静默覆盖其他页面的修改。
|
||||||
|
|
||||||
|
前端约每 5 秒同步一次名单版本;本页面修改成功后立即使用服务端快照。后台页面更新会同步显示,但不会覆盖正在编辑的备注草稿。失败请求保留原分类和输入,等待用户重试。
|
||||||
|
|
||||||
|
## 验证入口
|
||||||
|
|
||||||
|
- `. ./scripts/rust-env.ps1`
|
||||||
|
- `cargo test --workspace --exclude rid-web-ui --locked`
|
||||||
|
- `cargo clippy -p rid-web-ui --target wasm32-unknown-unknown --locked -- -D warnings`
|
||||||
|
- `cargo xtask web`,随后构建宿主程序。
|
||||||
|
- `node scripts/test-target-lists.mjs [待验证程序绝对路径]`
|
||||||
|
|
||||||
|
浏览器验收使用独立数据库与显式开启的模拟输入,不打开物理接收器。覆盖互斥分类、重启保留、在线与离线加入、跨浏览器同步、冲突及失败保护、告警去重、地图筛选、窄屏、缩放和键盘焦点。
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$ridTools = 'D:/Rust_Contact/util/tools/rid-map-downloader/0.1.0'
|
||||||
|
$env:GOCACHE = 'D:/Rust_Contact/util/tools/go-cache'
|
||||||
|
$env:GOMODCACHE = 'D:/Rust_Contact/util/tools/go-modules'
|
||||||
|
New-Item -ItemType Directory -Force $ridTools | Out-Null
|
||||||
|
Push-Location (Join-Path $PSScriptRoot 'map-downloader')
|
||||||
|
try {
|
||||||
|
go test ./...
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw 'Go map downloader tests failed' }
|
||||||
|
go build -trimpath -ldflags '-s -w' -o (Join-Path $ridTools 'rid-map-downloader.exe') .
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw 'Go map downloader build failed' }
|
||||||
|
Copy-Item -LiteralPath 'LICENSE-upstream.txt' -Destination $ridTools
|
||||||
|
$env:RID_MAP_DOWNLOADER = Join-Path $ridTools 'rid-map-downloader.exe'
|
||||||
|
Write-Output $env:RID_MAP_DOWNLOADER
|
||||||
|
} finally { Pop-Location }
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
module rid-map-downloader
|
||||||
|
|
||||||
|
go 1.22.0
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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")
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-1
@@ -6,7 +6,7 @@ $ridRepo = Split-Path $PSScriptRoot -Parent
|
|||||||
if (-not $OutputRoot) { $OutputRoot = Join-Path $ridRepo 'dist' }
|
if (-not $OutputRoot) { $OutputRoot = Join-Path $ridRepo 'dist' }
|
||||||
$ridOutputRoot = [IO.Path]::GetFullPath($OutputRoot)
|
$ridOutputRoot = [IO.Path]::GetFullPath($OutputRoot)
|
||||||
$ridDestination = Join-Path $ridOutputRoot 'FPV-RID-Rust'
|
$ridDestination = Join-Path $ridOutputRoot 'FPV-RID-Rust'
|
||||||
$ridWhitelist = @('fpv-rid-registry.exe', '启动Rust版.cmd', '使用说明.md', 'third-party-licenses.txt', 'dependency-licenses.txt', 'build-info.json', 'SHA256SUMS.txt')
|
$ridWhitelist = @('fpv-rid-registry.exe', 'rid-map-downloader.exe', 'map-downloader-LICENSE.txt', '启动Rust版.cmd', '使用说明.md', 'third-party-licenses.txt', 'dependency-licenses.txt', 'build-info.json', 'SHA256SUMS.txt')
|
||||||
|
|
||||||
function Assert-CleanDestination {
|
function Assert-CleanDestination {
|
||||||
if (Test-Path -LiteralPath $ridDestination) {
|
if (Test-Path -LiteralPath $ridDestination) {
|
||||||
@@ -27,6 +27,7 @@ function Get-RidSourceManifest {
|
|||||||
|
|
||||||
# Refuse a used deployment folder before building or changing any published files.
|
# Refuse a used deployment folder before building or changing any published files.
|
||||||
Assert-CleanDestination
|
Assert-CleanDestination
|
||||||
|
& (Join-Path $PSScriptRoot 'build-map-downloader.ps1')
|
||||||
$ridStageRoot = Join-Path $ridOutputRoot ('.package-' + [guid]::NewGuid().ToString('N'))
|
$ridStageRoot = Join-Path $ridOutputRoot ('.package-' + [guid]::NewGuid().ToString('N'))
|
||||||
$ridStage = Join-Path $ridStageRoot 'FPV-RID-Rust'
|
$ridStage = Join-Path $ridStageRoot 'FPV-RID-Rust'
|
||||||
$ridTemporaryZip = Join-Path $ridStageRoot 'release.zip'
|
$ridTemporaryZip = Join-Path $ridStageRoot 'release.zip'
|
||||||
@@ -46,6 +47,8 @@ try {
|
|||||||
if ($LASTEXITCODE -ne 0) { throw 'Cargo metadata failed' }
|
if ($LASTEXITCODE -ne 0) { throw 'Cargo metadata failed' }
|
||||||
New-Item -ItemType Directory -Force -Path $ridStage | Out-Null
|
New-Item -ItemType Directory -Force -Path $ridStage | Out-Null
|
||||||
Copy-Item -LiteralPath (Join-Path $ridMetadata.target_directory 'release/fpv-rid-registry-fullstack.exe') -Destination (Join-Path $ridStage 'fpv-rid-registry.exe')
|
Copy-Item -LiteralPath (Join-Path $ridMetadata.target_directory 'release/fpv-rid-registry-fullstack.exe') -Destination (Join-Path $ridStage 'fpv-rid-registry.exe')
|
||||||
|
Copy-Item -LiteralPath $env:RID_MAP_DOWNLOADER -Destination (Join-Path $ridStage 'rid-map-downloader.exe')
|
||||||
|
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'map-downloader/LICENSE-upstream.txt') -Destination (Join-Path $ridStage 'map-downloader-LICENSE.txt')
|
||||||
Copy-Item -LiteralPath (Join-Path $ridRepo '启动Rust版.cmd') -Destination $ridStage
|
Copy-Item -LiteralPath (Join-Path $ridRepo '启动Rust版.cmd') -Destination $ridStage
|
||||||
Copy-Item -LiteralPath (Join-Path $ridRepo 'doc/registry/rust/使用说明.md') -Destination $ridStage
|
Copy-Item -LiteralPath (Join-Path $ridRepo 'doc/registry/rust/使用说明.md') -Destination $ridStage
|
||||||
Copy-Item -LiteralPath (Join-Path $ridRepo 'crates/web-ui/public/vendor/LICENSE.txt') -Destination (Join-Path $ridStage 'third-party-licenses.txt')
|
Copy-Item -LiteralPath (Join-Path $ridRepo 'crates/web-ui/public/vendor/LICENSE.txt') -Destination (Join-Path $ridStage 'third-party-licenses.txt')
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
# Dot-source this file for the workspace's shared Rust installation.
|
# Dot-source this file for the workspace's shared Rust installation.
|
||||||
$env:CARGO_HOME = 'D:\Rust_Contact\util\cargo'
|
$env:CARGO_HOME = 'D:\Rust_Contact\util\cargo'
|
||||||
$env:RUSTUP_HOME = 'D:\Rust_Contact\util\rustup'
|
$env:RUSTUP_HOME = 'D:\Rust_Contact\util\rustup'
|
||||||
|
if (-not $env:RID_MAP_DOWNLOADER) {
|
||||||
|
$env:RID_MAP_DOWNLOADER = 'D:/Rust_Contact/util/tools/rid-map-downloader/0.1.0/rid-map-downloader.exe'
|
||||||
|
}
|
||||||
if (($env:Path -split ';') -notcontains "$env:CARGO_HOME\bin") {
|
if (($env:Path -split ';') -notcontains "$env:CARGO_HOME\bin") {
|
||||||
$env:Path = "$env:CARGO_HOME\bin;$env:Path"
|
$env:Path = "$env:CARGO_HOME\bin;$env:Path"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
// Actual Rust/Wasm + Go integration against an isolated data root and local fixtures.
|
||||||
|
// Does not use a real TianDiTu key or open any receiver transport.
|
||||||
|
import {mkdtemp,mkdir,writeFile,readFile} from 'node:fs/promises';
|
||||||
|
import {tmpdir} from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import {spawn} from 'node:child_process';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {createRequire} from 'node:module';
|
||||||
|
const require=createRequire(import.meta.url);
|
||||||
|
const {chromium}=require('C:/Users/20143/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
|
||||||
|
const {PNG}=require('C:/Users/20143/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/pngjs');
|
||||||
|
const root=await mkdtemp(path.join(tmpdir(),'RID-map-settings-'));
|
||||||
|
const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
|
||||||
|
const base='http://127.0.0.1:8787';
|
||||||
|
try{await fetch(base,{signal:AbortSignal.timeout(800)});throw Error('8787 is occupied; existing service preserved');}catch(e){if(e.message.includes('occupied'))throw e;}
|
||||||
|
const env={...process.env,RID_MAP_DOWNLOADER:process.env.RID_MAP_DOWNLOADER||'D:/Rust_Contact/util/tools/rid-map-downloader/0.1.0/rid-map-downloader.exe'};delete env.TIANDITU_TOKEN;
|
||||||
|
const fixture=new PNG({width:256,height:256});for(let i=0;i<fixture.data.length;i+=4){fixture.data[i]=25;fixture.data[i+1]=45;fixture.data[i+2]=65;fixture.data[i+3]=255;}const png=PNG.sync.write(fixture);
|
||||||
|
function xy(lon,lat,z){const n=2**z,r=lat*Math.PI/180;return [Math.floor((lon+180)/360*n),Math.floor((1-Math.log(Math.tan(r)+1/Math.cos(r))/Math.PI)/2*n)];}
|
||||||
|
const [x,y]=xy(120.155,30.285,11);
|
||||||
|
for(const layer of ['vec_w','cva_w','img_w','cia_w']){const dir=path.join(root,`maps/cache/${layer}/11/${x}`);await mkdir(dir,{recursive:true});await writeFile(path.join(dir,y+'.tile'),png);}
|
||||||
|
let child,browser,output='';const errors=[],csp=[];let report={};
|
||||||
|
function start(){child=spawn(exe,['--data-root',root],{env,windowsHide:true,stdio:['ignore','pipe','pipe']});child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);}
|
||||||
|
async function ready(){for(let i=0;i<150;i++){if(child.exitCode!==null)throw Error(output);try{if((await fetch(base+'/api/maps/preferences')).ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw Error('server timeout');}
|
||||||
|
async function stop(){if(child?.exitCode===null){const done=new Promise(r=>child.once('exit',r));child.kill();await done;}}
|
||||||
|
const json=async(url,method='GET',body)=>{const r=await fetch(base+url,{method,headers:{'content-type':'application/json'},...(body?{body:JSON.stringify(body)}:{})});const v=await r.json();return {status:r.status,value:v};};
|
||||||
|
async function job(state){for(let i=0;i<150;i++){const v=(await json('/api/maps/downloads')).value.job;if(v?.state===state)return v;if(v?.state==='failed'&&state==='completed')throw Error(JSON.stringify(v));await new Promise(r=>setTimeout(r,100));}throw Error('job timeout '+state);}
|
||||||
|
try{
|
||||||
|
start();await ready();browser=await chromium.launch({headless:true,channel:'msedge'});const page=await browser.newPage({viewport:{width:1600,height:1000}});
|
||||||
|
page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(/Content Security Policy|Refused to/i.test(m.text()))csp.push(m.text());});
|
||||||
|
await page.goto(base);await page.locator('#home-app-settings').click();await page.locator('#appearance-view [data-open=maps]').click();await page.locator('#map-save').waitFor();await page.waitForFunction(()=>!document.querySelector('#map-save').disabled);
|
||||||
|
await page.waitForFunction(()=>window.ridMapSettings?.metrics()?.camera);
|
||||||
|
await page.locator('#map-settings-drawer [data-map-action=drawer]').click();assert.equal(await page.locator('#map-settings-drawer').isHidden(),true);await page.locator('.map-settings-head [data-map-action=drawer]').click();
|
||||||
|
await page.locator('.map-settings-head [data-map-action=point]').click();await page.locator('#settings-map').click({position:{x:220,y:220}});assert.match(await page.locator('#map-save-message').textContent(),/起始点已选定/);
|
||||||
|
await page.locator('#map-longitude').fill('181');await page.locator('#map-save').click();assert.match(await page.locator('#map-save-message').textContent(),/有效经纬度/);
|
||||||
|
await page.locator('#map-longitude').fill('116.4');await page.locator('#map-latitude').fill('39.9');await page.locator('#map-zoom').fill('12');await page.locator('#map-basemap').selectOption('road');await page.locator('#map-save').click();await page.waitForFunction(()=>document.querySelector('#map-save-message').textContent.includes('已保存'));
|
||||||
|
assert.equal((await json('/api/maps/preferences')).value.longitude,116.4);
|
||||||
|
// Unsaved fields survive a settings navigation within this document.
|
||||||
|
await page.locator('#map-longitude').fill('116.41');await page.locator('#map-settings-view [data-open=settings]').click();await page.locator('#appearance-view [data-open=maps]').click();assert.equal(await page.locator('#map-longitude').inputValue(),'116.41');await page.locator('#map-longitude').fill('116.4');
|
||||||
|
for(const [id,v]of Object.entries({'map-west':'120.15','map-south':'30.28','map-east':'120.16','map-north':'30.29','map-min-zoom':'11','map-max-zoom':'11'}))await page.locator('#'+id).fill(v);
|
||||||
|
await page.locator('#map-region-name').fill('验收常用区域');await page.locator('[data-map-action=region-save]').click();await page.locator('#map-save').click();await page.waitForFunction(()=>document.querySelector('#map-save-message').textContent.includes('已保存'));
|
||||||
|
await page.locator('#map-estimate').click();await page.waitForFunction(()=>document.querySelector('#map-estimate-message').textContent.includes('共 4 张'));
|
||||||
|
await page.locator('#map-download-start').click();const done=await job('completed');assert.equal(done.done,4);assert.equal(done.failed,0);
|
||||||
|
for(const layer of ['vec_w','cva_w','img_w','cia_w'])assert.deepEqual(await readFile(path.join(root,`maps/offline/${layer}/11/${x}/${y}.png`)),png);
|
||||||
|
// Offline files remain readable even after the online cache is no longer needed.
|
||||||
|
const tile=await fetch(base+`/api/maps/tile/vec_w/11/${x}/${y}`);assert.equal(tile.status,200);
|
||||||
|
const task={bounds:{west:120.15,south:30.28,east:120.16,north:30.29},minZoom:16,maxZoom:16,road:true,imagery:true};
|
||||||
|
assert.equal((await json('/api/maps/downloads','POST',task)).status,202);
|
||||||
|
assert.equal((await json('/api/maps/downloads','POST',task)).status,409);
|
||||||
|
await json('/api/maps/downloads/cancel','POST',{});await job('cancelled');
|
||||||
|
const failing={...task,bounds:{west:116.4,south:39.9,east:116.401,north:39.901},minZoom:11,maxZoom:11};await json('/api/maps/downloads','POST',failing);await job('failed');
|
||||||
|
assert.equal((await json('/api/maps/downloads/estimate','POST',{...task,minZoom:19})).status,400);
|
||||||
|
assert.equal((await fetch(base+'/api/maps/preferences',{headers:{origin:'https://foreign.invalid'}})).status,403);
|
||||||
|
// Real live renderer reads the persisted default; no telemetry is injected.
|
||||||
|
await page.goto(base+'/realtime');await page.waitForFunction(()=>window.ridMap?.metrics()?.mapReady);
|
||||||
|
const camera=await page.evaluate(()=>window.ridMap.metrics().camera);assert.ok(Math.abs(camera.center[0]-116.4)<.0001,JSON.stringify(camera));assert.ok(Math.abs(camera.center[1]-39.9)<.0001,JSON.stringify(camera));assert.equal(camera.zoom,12);
|
||||||
|
assert.equal(await page.evaluate(()=>window.ridMap.metrics().basemap),'road');
|
||||||
|
await page.locator('[data-open=settings]').first().click();await page.locator('#appearance-view [data-open=maps]').click();await page.waitForFunction(()=>!document.querySelector('#map-save').disabled);await page.waitForFunction(()=>window.ridMapSettings?.metrics()?.camera);
|
||||||
|
assert.equal(await page.locator('#map-region option').count(),2);await page.screenshot({path:path.resolve('previews/map-settings-live-C-20261023.png')});
|
||||||
|
await page.setViewportSize({width:800,height:1000});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||||||
|
await stop();start();await ready();const reloaded=(await json('/api/maps/preferences')).value;assert.equal(reloaded.longitude,116.4);assert.equal(reloaded.regions[0].name,'验收常用区域');
|
||||||
|
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
|
||||||
|
report={status:'PASS',root,camera,download:done,scenarios:['actual C drawer and MapLibre point selection','invalid coordinates','persistent default camera','draft retained across navigation','saved region reload','actual Go sidecar and four-layer offline raster validation','download cancellation and single-job limit','unavailable tiles fail honestly','foreign origin rejection','800px width','no page errors or CSP violations']};console.log(JSON.stringify(report));
|
||||||
|
}finally{await browser?.close();await stop();await writeFile(path.join(root,'server.log'),output);await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
// Real SQLite, Rust/Wasm, Worker and WebGL acceptance. No physical transports opened.
|
||||||
|
import {mkdtemp,readFile,writeFile} from 'node:fs/promises';
|
||||||
|
import {tmpdir} from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import http from 'node:http';
|
||||||
|
import net from 'node:net';
|
||||||
|
import {spawn} from 'node:child_process';
|
||||||
|
import {createRequire} from 'node:module';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
const {chromium}=createRequire(import.meta.url)('playwright');
|
||||||
|
const root=await mkdtemp(path.join(tmpdir(),'RID-target-lists-'));
|
||||||
|
const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
|
||||||
|
const probe=net.createServer();await new Promise(r=>probe.listen(0,'127.0.0.1',r));const backend=probe.address().port;await new Promise(r=>probe.close(r));
|
||||||
|
let base,child,browser,heartbeat,output='';const errors=[],csp=[],sockets=new Set();
|
||||||
|
const proxy=http.createServer((req,res)=>{const headers={...req.headers,host:'127.0.0.1:8787'};if(headers.origin===base)headers.origin='http://127.0.0.1:8787';const upstream=http.request({hostname:'127.0.0.1',port:backend,path:req.url,method:req.method,headers},r=>{res.writeHead(r.statusCode,r.headers);r.pipe(res)});upstream.on('error',()=>{res.writeHead(502);res.end()});req.pipe(upstream)});
|
||||||
|
proxy.on('upgrade',(req,socket,head)=>{const upstream=net.connect(backend,'127.0.0.1');sockets.add(socket);sockets.add(upstream);upstream.on('connect',()=>{const headers={...req.headers,host:'127.0.0.1:8787'};if(headers.origin===base)headers.origin='http://127.0.0.1:8787';const nl=String.fromCharCode(13,10);upstream.write(['GET '+req.url+' HTTP/1.1',...Object.entries(headers).map(([k,v])=>k+': '+v),'',''].join(nl));if(head.length)upstream.write(head);socket.pipe(upstream);upstream.pipe(socket)});upstream.on('error',()=>socket.destroy());socket.on('error',()=>upstream.destroy());socket.on('close',()=>{upstream.destroy();sockets.delete(socket);sockets.delete(upstream)})});
|
||||||
|
const wait=ms=>new Promise(r=>setTimeout(r,ms));
|
||||||
|
function start(){child=spawn(exe,['--data-root',root,'--simulation-api'],{env:{...process.env,RID_TEST_PORT:String(backend),PATH:'C:\\Windows\\System32'},windowsHide:true,stdio:['ignore','pipe','pipe']});child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>output+=e.message)}
|
||||||
|
async function stop(){if(child&&child.exitCode===null){const done=new Promise(r=>child.once('exit',r));child.kill();await done}}
|
||||||
|
async function ready(){for(let i=0;i<150;i++){if(child.exitCode!==null)throw Error(output);try{if((await fetch(base+'/api/target-lists')).ok)return}catch{}await wait(100)}throw Error('server timeout '+output)}
|
||||||
|
async function snapshot(){return(await fetch(base+'/api/target-lists')).json()}
|
||||||
|
async function save(id,kind,note='验收备注'){const current=await snapshot();const r=await fetch(base+'/api/target-lists/'+id,{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({list_kind:kind,note,expected_revision:current.revision})});assert.equal(r.status,200);return r.json()}
|
||||||
|
let sequence=0;const targetIds=['LIST-WHITE','LIST-BLACK','LIST-OTHER'];
|
||||||
|
async function ingest(){sequence++;const frames=targetIds.map((target_id,i)=>({target_id,receiver_id:'TEST',source_epoch:1,sequence,longitude:120.15+i*.001,latitude:30.28+i*.001,altitude_m:100,heading_deg:40}));const r=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(frames)});assert.equal(r.status,200)}
|
||||||
|
let report={};
|
||||||
|
try{
|
||||||
|
await new Promise(r=>proxy.listen(0,'127.0.0.1',r));base='http://127.0.0.1:'+proxy.address().port;start();await ready();
|
||||||
|
assert.deepEqual((await snapshot()).entries,[]);
|
||||||
|
await save('LIST-WHITE','white');await save('LIST-BLACK','black');await save('OFFLINE_001','white');
|
||||||
|
for(const file of ['target-lists.css','map-adapter.js'])assert.equal(await(await fetch(base+'/'+file)).text(),await readFile(path.join('dist/web-ui',file),'utf8'));
|
||||||
|
browser=await chromium.launch({headless:true,channel:'msedge'});const context=await browser.newContext({viewport:{width:1600,height:1000}});const page=await context.newPage();page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(/violates.*Content Security|Refused.*policy/i.test(m.text()))csp.push(m.text())});
|
||||||
|
await page.goto(base+'/realtime');await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();
|
||||||
|
const filters=page.getByRole('group',{name:'目标名单筛选'});
|
||||||
|
await page.waitForFunction(()=>![...document.querySelectorAll('.rt-target-list-filters button')].some(b=>b.disabled));
|
||||||
|
await ingest();heartbeat=setInterval(()=>ingest().catch(()=>{}),3000);
|
||||||
|
await page.getByRole('button',{name:'LIST-BLACK',exact:true}).waitFor();await page.waitForFunction(()=>window.ridMap?.metrics().mapReady&&window.ridMap.metrics().classifiedTargets.black===1);
|
||||||
|
assert.equal(await page.getByRole('button',{name:'LIST-WHITE',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'white');
|
||||||
|
assert.equal(await page.getByRole('button',{name:'LIST-OTHER',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'unknown');
|
||||||
|
const blackEvents=()=>page.locator('.live-events li[data-alert=true]').filter({hasText:'LIST-BLACK'});
|
||||||
|
await blackEvents().waitFor();for(let i=0;i<5;i++)await ingest();await wait(500);assert.equal(await blackEvents().count(),1);
|
||||||
|
await page.getByRole('button',{name:'LIST-BLACK',exact:true}).click();await page.locator('.rt-detail-classification').waitFor();
|
||||||
|
await page.screenshot({path:path.join(root,'classified-workspace.png')});
|
||||||
|
await filters.getByRole('button',{name:/^白名单/}).click();await page.waitForFunction(()=>window.ridMap.metrics().visibleTargets===1);assert.equal(await page.locator('.rt-target').count(),1);assert.equal(await page.evaluate(()=>window.ridMap.metrics().targets),3);
|
||||||
|
await filters.getByRole('button',{name:/^全部/}).click();await page.getByRole('button',{name:'LIST-WHITE',exact:true}).click();
|
||||||
|
await page.getByRole('button',{name:'加入黑名单',exact:true}).click();
|
||||||
|
await page.waitForFunction(()=>window.ridMap.metrics().classifiedTargets.black===2);assert.equal(await page.getByRole('button',{name:'LIST-WHITE',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'black');
|
||||||
|
await page.locator('.rt-detail-classification').getByRole('button',{name:'加入黑名单',exact:true}).click();await wait(350);
|
||||||
|
assert.equal(await page.locator('.live-events li[data-alert=true]').filter({hasText:'LIST-WHITE'}).count(),1);
|
||||||
|
await page.getByRole('button',{name:'管理黑白名单',exact:true}).click();await page.locator('#rt-list-manager').waitFor();assert.equal((await page.locator('#rt-list-manager').innerText()).includes('rows.get'),false);assert.equal(await page.locator('.rt-list-pagination').getByRole('button',{name:'下一页',exact:true}).isDisabled(),true);
|
||||||
|
await page.locator('#rt-list-entry-id').fill('OFFLINE_002');await page.locator('#rt-list-entry-kind').selectOption('white');await page.locator('#rt-list-entry-note').fill('离线条目');await page.locator('#rt-list-entry-form .primary').click();
|
||||||
|
await page.locator('.rt-list-manager-footer').filter({hasText:'已将 OFFLINE_002 保存为白名单'}).waitFor();assert.equal(await page.evaluate(()=>window.ridMap.metrics().targets),3);
|
||||||
|
assert.equal((await(await fetch(base+'/api/records?page=1')).json()).total,0);
|
||||||
|
const offline=page.locator('.rt-list-row[data-target-id=OFFLINE_002]');await offline.getByRole('button',{name:'编辑',exact:true}).click();assert.equal(await page.locator('#rt-list-entry-id').isEditable(),false);
|
||||||
|
await page.locator('#rt-list-entry-note').fill('<img src=x onerror=alert(1)>人工备注');await page.locator('#rt-list-entry-form .primary').click();await offline.filter({hasText:'人工备注'}).waitFor();assert.equal(await offline.locator('img').count(),0);
|
||||||
|
const otherContext=await browser.newContext({viewport:{width:1280,height:900}}),other=await otherContext.newPage();await other.goto(base+'/realtime');await other.waitForFunction(()=>![...document.querySelectorAll('.rt-target-list-filters button')].some(b=>b.disabled));
|
||||||
|
await other.getByRole('button',{name:'管理黑白名单',exact:true}).click();await other.locator('.rt-list-row[data-target-id=OFFLINE_002]').filter({hasText:'人工备注'}).waitFor();
|
||||||
|
await page.locator('#rt-list-entry-note').fill('尚未保存的备注');await save('OFFLINE_002','white','来自其他浏览器');
|
||||||
|
await offline.filter({hasText:'来自其他浏览器'}).waitFor({timeout:12000});assert.equal(await page.locator('#rt-list-entry-note').inputValue(),'尚未保存的备注');
|
||||||
|
await page.getByRole('button',{name:'新增条目',exact:true}).click();await page.locator('#rt-list-entry-id').fill('LIST-OTHER');await page.locator('#rt-list-entry-note').fill('冲突后保留草稿');
|
||||||
|
let releaseRequest,heldRequest;const gate=new Promise(r=>releaseRequest=r),held=new Promise(r=>heldRequest=r);let intercept=true;
|
||||||
|
await page.route('**/api/target-lists/LIST-OTHER',async route=>{if(route.request().method()==='PUT'&&intercept){intercept=false;heldRequest();await gate;}await route.continue()});
|
||||||
|
await page.locator('#rt-list-entry-form .primary').click();await held;assert.equal(await page.locator('#rt-list-entry-id').isDisabled(),true);await save('REMOTE_001','white');releaseRequest();
|
||||||
|
await page.locator('.rt-list-manager-footer p.error').filter({hasText:'其他页面修改'}).waitFor();await page.locator('.rt-list-row[data-target-id=REMOTE_001]').waitFor();assert.equal(await page.locator('#rt-list-entry-note').inputValue(),'冲突后保留草稿');
|
||||||
|
await page.unroute('**/api/target-lists/LIST-OTHER');await page.locator('#rt-list-entry-form .primary').click();await page.locator('.rt-list-row[data-target-id=LIST-OTHER]').waitFor();
|
||||||
|
await page.locator('#rt-list-entry-note').fill('保存失败仍保留');await page.route('**/api/target-lists/LIST-OTHER',r=>r.fulfill({status:500,contentType:'application/json',body:JSON.stringify({error:'隔离保存失败'})}));
|
||||||
|
await page.locator('#rt-list-entry-form .primary').click();await page.locator('.rt-list-manager-footer p.error').filter({hasText:'隔离保存失败'}).waitFor();assert.equal(await page.locator('#rt-list-entry-note').inputValue(),'保存失败仍保留');assert.equal((await snapshot()).entries.find(e=>e.target_id==='LIST-OTHER').note,'冲突后保留草稿');await page.unroute('**/api/target-lists/LIST-OTHER');
|
||||||
|
await page.getByRole('button',{name:'新增条目',exact:true}).click();await page.locator('#rt-list-entry-id').fill('bad id');await page.locator('#rt-list-entry-form').evaluate(f=>f.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true})));await page.locator('.rt-list-manager-footer p.error').filter({hasText:'目标标识须'}).waitFor();
|
||||||
|
await page.screenshot({path:path.join(root,'manager-validation.png')});
|
||||||
|
await page.locator('.rt-list-row[data-target-id=LIST-OTHER]').getByRole('button',{name:'移除',exact:true}).click();await page.waitForFunction(()=>window.ridMap.metrics().classifiedTargets.black===2);
|
||||||
|
await page.route('**/api/target-lists?revision=*',r=>r.fulfill({status:503,contentType:'application/json',body:'{}'}));
|
||||||
|
await page.locator('#rt-list-manager .rt-list-sync-error').filter({hasText:'暂用上次名单'}).waitFor({timeout:12000});
|
||||||
|
assert.equal(await page.evaluate(()=>window.ridMap.metrics().classifiedTargets.black),2);
|
||||||
|
await page.unroute('**/api/target-lists?revision=*');await page.locator('#rt-list-manager .rt-list-sync-error').getByRole('button',{name:'重试',exact:true}).click();await page.locator('#rt-list-manager .rt-list-sync-error').waitFor({state:'hidden'});
|
||||||
|
const unavailableContext=await browser.newContext(),unavailable=await unavailableContext.newPage();
|
||||||
|
await unavailable.route('**/api/target-lists**',r=>r.fulfill({status:503,contentType:'application/json',body:'{}'}));await unavailable.goto(base+'/realtime');
|
||||||
|
await unavailable.locator('.rt-list-sync-error').filter({hasText:'名单读取失败'}).first().waitFor();await unavailable.locator('.rt-target').first().waitFor();
|
||||||
|
assert.equal(await unavailable.locator('.rt-target .rt-list-badge[data-kind=unavailable]').count(),3);
|
||||||
|
assert.equal(await unavailable.getByRole('group',{name:'目标名单筛选'}).getByRole('button',{name:/^黑名单/}).isDisabled(),true);assert.ok((await unavailable.getByRole('group',{name:'目标名单筛选'}).getByRole('button',{name:/^黑名单/}).innerText()).includes('—'));
|
||||||
|
await unavailableContext.close();
|
||||||
|
const sizes=[[1600,1000],[1366,600],[1080,900],[390,844]];const geometry=[];
|
||||||
|
for(const [width,height]of sizes){await page.setViewportSize({width,height});await wait(250);await page.locator('#rt-list-entry-form .primary').scrollIntoViewIfNeeded();const box=await page.locator('#rt-list-entry-form .primary').boundingBox();assert.ok(box.x>=0&&box.x+box.width<=width&&box.y>=48&&box.y+box.height<=height+1);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.locator('.rt-list-manager-body').evaluate(e=>e.scrollTop=0);await page.screenshot({path:path.join(root,'manager-'+width+'.png')});geometry.push({width,height})}
|
||||||
|
await page.setViewportSize({width:1280,height:720});await page.evaluate(()=>document.documentElement.style.zoom='2');await page.locator('#rt-list-entry-form .primary').scrollIntoViewIfNeeded();assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:path.join(root,'manager-zoom200.png')});await page.evaluate(()=>document.documentElement.style.zoom='');
|
||||||
|
await page.keyboard.press('Escape');await page.locator('#rt-list-manager').waitFor({state:'hidden'});await page.waitForFunction(()=>['rt-list-manager-open','rt-list-manager-from-directory'].includes(document.activeElement.id));
|
||||||
|
await page.setViewportSize({width:1600,height:1000});await otherContext.close();
|
||||||
|
const persisted=await snapshot();clearInterval(heartbeat);await stop();start();await ready();assert.deepEqual(await snapshot(),persisted);
|
||||||
|
await page.reload();await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();await ingest();await page.waitForFunction(()=>window.ridMap.metrics().targets===3&&window.ridMap.metrics().classifiedTargets.black===2);assert.equal(await page.getByRole('button',{name:'LIST-OTHER',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'unknown');
|
||||||
|
// Registration remains independent: registered targets are not automatically trusted.
|
||||||
|
for(const [id,expectedKind]of [['LIST-BLACK','black'],['LIST-OTHER','unknown']]){
|
||||||
|
const response=await fetch(base+'/api/records',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({serialNo:id})});assert.equal(response.status,200);const record=(await response.json()).record;
|
||||||
|
await page.getByRole('button',{name:id,exact:true}).click();await page.locator('.rt-details').filter({hasText:'已匹配本地登记档案'}).waitFor();
|
||||||
|
assert.equal(await page.locator('.rt-detail-classification .rt-list-badge').getAttribute('data-kind'),expectedKind);
|
||||||
|
assert.equal((await fetch(base+'/api/records/'+record.id,{method:'DELETE'})).status,200);
|
||||||
|
}
|
||||||
|
assert.equal((await snapshot()).entries.find(e=>e.target_id==='LIST-BLACK').list_kind,'black');
|
||||||
|
assert.equal(await page.locator('.mc-map-toolstrip').count(),0);assert.equal(await page.evaluate(()=>window.ridMap.metrics().camera.pitch),0);
|
||||||
|
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
|
||||||
|
report={status:'PASS',root,exe,geometry,errors,csp,revision:persisted.revision,entries:persisted.entries.length,checks:['exact persisted membership independent of registration','online quick marking and offline entry','map and directory filtering without telemetry loss','black alert deduplication','safe notes and reactive remote updates','cross-browser sync preserves unsaved draft','optimistic concurrency and failed save rollback','busy controls and ID validation','removal restores unclassified','four viewports and 200% zoom','escape return focus','restart persistence','failed initial load and stale snapshot recovery','topdown map and removed toolbar preserved']};console.log(JSON.stringify(report));
|
||||||
|
}catch(error){console.log('FAILED ROOT',root,error.stack);if(browser){const p=browser.contexts()[0]?.pages()[0];if(p)await p.screenshot({path:path.join(root,'failure.png')}).catch(()=>{});}throw error;}finally{clearInterval(heartbeat);if(browser)await browser.close();await stop();for(const socket of sockets)socket.destroy();const closed=new Promise(r=>proxy.close(r));proxy.closeAllConnections();await closed;await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));await writeFile(path.join(root,'server.log'),output)}
|
||||||
+5
-1
@@ -2,6 +2,7 @@ mod appearance;
|
|||||||
mod archive;
|
mod archive;
|
||||||
mod error;
|
mod error;
|
||||||
mod http;
|
mod http;
|
||||||
|
mod map_settings;
|
||||||
mod maps;
|
mod maps;
|
||||||
mod realtime;
|
mod realtime;
|
||||||
mod receiver;
|
mod receiver;
|
||||||
@@ -102,13 +103,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
println!("FPV-RID Rust 登记站:http://127.0.0.1:{port}");
|
println!("FPV-RID Rust 登记站:http://127.0.0.1:{port}");
|
||||||
let live_store = realtime::new_store();
|
let live_store = realtime::new_store();
|
||||||
let receivers = receiver::router(map_root.clone(), live_store.clone()).await;
|
let receivers = receiver::router(map_root.clone(), live_store.clone()).await;
|
||||||
|
let (map_preferences, map_downloads) = crate::map_settings::router(map_root.clone(), port);
|
||||||
let app = http::router(Worker(tx))
|
let app = http::router(Worker(tx))
|
||||||
.merge(realtime::with_store(simulation_api, live_store))
|
.merge(realtime::with_store(simulation_api, live_store))
|
||||||
.merge(receivers)
|
.merge(receivers)
|
||||||
|
.merge(map_preferences)
|
||||||
.merge(maps::router(map_root)?);
|
.merge(maps::router(map_root)?);
|
||||||
let served = axum::serve(listener, app)
|
let served = axum::serve(listener, app)
|
||||||
.with_graceful_shutdown(async {
|
.with_graceful_shutdown(async move {
|
||||||
let _ = tokio::signal::ctrl_c().await;
|
let _ = tokio::signal::ctrl_c().await;
|
||||||
|
map_downloads.cancel();
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
let _ = shutdown.send(Job::Shutdown).await;
|
let _ = shutdown.send(Job::Shutdown).await;
|
||||||
|
|||||||
@@ -0,0 +1,389 @@
|
|||||||
|
//! Local map defaults and one bounded, cancellable Go downloader child at a time.
|
||||||
|
use axum::{
|
||||||
|
Json, Router,
|
||||||
|
extract::State,
|
||||||
|
http::{HeaderMap, StatusCode},
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
routing::{get, post},
|
||||||
|
};
|
||||||
|
use rid_shared::map_settings::{DownloadRequest, Preferences};
|
||||||
|
use serde::Serialize;
|
||||||
|
use serde_json::json;
|
||||||
|
use std::{
|
||||||
|
io::{BufRead, BufReader, Write},
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
process::{Command, Stdio},
|
||||||
|
sync::{
|
||||||
|
Arc, Mutex,
|
||||||
|
atomic::{AtomicBool, Ordering},
|
||||||
|
},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Clone, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct Job {
|
||||||
|
state: String,
|
||||||
|
total: u64,
|
||||||
|
done: u64,
|
||||||
|
failed: u64,
|
||||||
|
message: String,
|
||||||
|
}
|
||||||
|
struct Manager {
|
||||||
|
root: PathBuf,
|
||||||
|
preferences: Mutex<Result<Preferences, String>>,
|
||||||
|
job: Mutex<Option<Job>>,
|
||||||
|
cancel: AtomicBool,
|
||||||
|
executable: Option<PathBuf>,
|
||||||
|
port: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn executable() -> Option<PathBuf> {
|
||||||
|
std::env::var_os("RID_MAP_DOWNLOADER")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.or_else(|| {
|
||||||
|
std::env::current_exe()
|
||||||
|
.ok()?
|
||||||
|
.parent()
|
||||||
|
.map(|p| p.join("rid-map-downloader.exe"))
|
||||||
|
})
|
||||||
|
.filter(|p| p.is_file())
|
||||||
|
}
|
||||||
|
fn read_preferences(root: &Path) -> Result<Preferences, String> {
|
||||||
|
let path = root.join("preferences.json");
|
||||||
|
if !crate::maps::allowed(root, &path) {
|
||||||
|
return Err("地图配置路径无效,原文件已保留".into());
|
||||||
|
}
|
||||||
|
if !path.exists() {
|
||||||
|
return Ok(Preferences::default());
|
||||||
|
}
|
||||||
|
if std::fs::metadata(&path)
|
||||||
|
.map_err(|_| "无法读取地图设置")?
|
||||||
|
.len()
|
||||||
|
> 65536
|
||||||
|
{
|
||||||
|
return Err("地图设置文件过大,原文件已保留".into());
|
||||||
|
}
|
||||||
|
let p: Preferences =
|
||||||
|
serde_json::from_slice(&std::fs::read(path).map_err(|_| "无法读取地图设置")?)
|
||||||
|
.map_err(|_| "地图设置损坏,原文件已保留")?;
|
||||||
|
if !p.valid() {
|
||||||
|
return Err("地图设置内容无效,原文件已保留".into());
|
||||||
|
}
|
||||||
|
Ok(p)
|
||||||
|
}
|
||||||
|
pub struct Shutdown(Arc<Manager>);
|
||||||
|
impl Shutdown {
|
||||||
|
pub fn cancel(&self) {
|
||||||
|
self.0.cancel.store(true, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn router(root: PathBuf, port: u16) -> (Router, Shutdown) {
|
||||||
|
let root = root.join("maps");
|
||||||
|
let manager = Arc::new(Manager {
|
||||||
|
preferences: Mutex::new(read_preferences(&root)),
|
||||||
|
root,
|
||||||
|
job: Mutex::new(None),
|
||||||
|
cancel: AtomicBool::new(false),
|
||||||
|
executable: executable(),
|
||||||
|
port,
|
||||||
|
});
|
||||||
|
let shutdown = Shutdown(manager.clone());
|
||||||
|
let router = Router::new()
|
||||||
|
.route("/api/maps/preferences", get(preferences).put(save))
|
||||||
|
.route("/api/maps/downloads", get(status).post(start))
|
||||||
|
.route("/api/maps/downloads/estimate", post(estimate))
|
||||||
|
.route("/api/maps/downloads/cancel", post(cancel))
|
||||||
|
.with_state(manager);
|
||||||
|
(router, shutdown)
|
||||||
|
}
|
||||||
|
fn error(status: StatusCode, message: &str) -> Response {
|
||||||
|
(status, Json(json!({"error":message}))).into_response()
|
||||||
|
}
|
||||||
|
fn forbidden(headers: &HeaderMap) -> bool {
|
||||||
|
!crate::maps::local_request(headers)
|
||||||
|
}
|
||||||
|
async fn preferences(State(s): State<Arc<Manager>>, headers: HeaderMap) -> Response {
|
||||||
|
if forbidden(&headers) {
|
||||||
|
return error(StatusCode::FORBIDDEN, "拒绝跨站请求");
|
||||||
|
}
|
||||||
|
match s.preferences.lock() {
|
||||||
|
Ok(p) => match p.as_ref() {
|
||||||
|
Ok(p) => Json(p).into_response(),
|
||||||
|
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
|
||||||
|
},
|
||||||
|
Err(_) => error(StatusCode::INTERNAL_SERVER_ERROR, "地图配置暂不可用"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async fn save(
|
||||||
|
State(s): State<Arc<Manager>>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Json(mut p): Json<Preferences>,
|
||||||
|
) -> Response {
|
||||||
|
if forbidden(&headers) {
|
||||||
|
return error(StatusCode::FORBIDDEN, "拒绝跨站请求");
|
||||||
|
}
|
||||||
|
if !p.valid() {
|
||||||
|
return error(StatusCode::BAD_REQUEST, "地图配置内容无效");
|
||||||
|
}
|
||||||
|
tokio::task::spawn_blocking(move || {
|
||||||
|
let Ok(mut current) = s.preferences.lock() else {
|
||||||
|
return error(StatusCode::INTERNAL_SERVER_ERROR, "地图配置暂不可用");
|
||||||
|
};
|
||||||
|
let Ok(old) = current.as_ref() else {
|
||||||
|
return error(StatusCode::CONFLICT, "原配置损坏,已保留文件,请先修复");
|
||||||
|
};
|
||||||
|
if p.revision != old.revision {
|
||||||
|
return error(StatusCode::CONFLICT, "其他窗口已更改地图设置,请重新加载");
|
||||||
|
}
|
||||||
|
let Some(revision) = old.revision.checked_add(1) else {
|
||||||
|
return error(StatusCode::CONFLICT, "地图设置版本已达到上限");
|
||||||
|
};
|
||||||
|
p.revision = revision;
|
||||||
|
let path = s.root.join("preferences.json");
|
||||||
|
let temp = s.root.join("preferences.json.tmp");
|
||||||
|
let result = (|| -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
if !crate::maps::allowed(&s.root, &path) || !crate::maps::allowed(&s.root, &temp) {
|
||||||
|
return Err("地图路径无效".into());
|
||||||
|
}
|
||||||
|
std::fs::create_dir_all(&s.root)?;
|
||||||
|
let bytes = serde_json::to_vec(&p)?;
|
||||||
|
let mut file = std::fs::File::create(&temp)?;
|
||||||
|
file.write_all(&bytes)?;
|
||||||
|
file.sync_all()?;
|
||||||
|
drop(file);
|
||||||
|
std::fs::rename(&temp, &path)?;
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
if result.is_err() {
|
||||||
|
return error(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
"地图配置保存失败,原配置仍然有效",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
*current = Ok(p.clone());
|
||||||
|
Json(p).into_response()
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|_| error(StatusCode::INTERNAL_SERVER_ERROR, "地图配置保存失败"))
|
||||||
|
}
|
||||||
|
async fn status(State(s): State<Arc<Manager>>, headers: HeaderMap) -> Response {
|
||||||
|
if forbidden(&headers) {
|
||||||
|
return error(StatusCode::FORBIDDEN, "拒绝跨站请求");
|
||||||
|
}
|
||||||
|
match s.job.lock() {
|
||||||
|
Ok(job) => Json(json!({"available":s.executable.is_some(),"job":*job})).into_response(),
|
||||||
|
Err(_) => error(StatusCode::INTERNAL_SERVER_ERROR, "下载状态暂不可用"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async fn estimate(headers: HeaderMap, Json(request): Json<DownloadRequest>) -> Response {
|
||||||
|
if forbidden(&headers) {
|
||||||
|
return error(StatusCode::FORBIDDEN, "拒绝跨站请求");
|
||||||
|
}
|
||||||
|
match request.count() {
|
||||||
|
Ok(total) => Json(json!({"tiles":total,"estimatedBytes":total*50_000,"estimateOnly":true}))
|
||||||
|
.into_response(),
|
||||||
|
Err(e) => error(StatusCode::BAD_REQUEST, e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async fn cancel(State(s): State<Arc<Manager>>, headers: HeaderMap) -> Response {
|
||||||
|
if forbidden(&headers) {
|
||||||
|
return error(StatusCode::FORBIDDEN, "拒绝跨站请求");
|
||||||
|
}
|
||||||
|
s.cancel.store(true, Ordering::Relaxed);
|
||||||
|
Json(json!({"message":"已请求取消;已完成瓦片保留,可重试补齐"})).into_response()
|
||||||
|
}
|
||||||
|
async fn start(
|
||||||
|
State(s): State<Arc<Manager>>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Json(request): Json<DownloadRequest>,
|
||||||
|
) -> Response {
|
||||||
|
if forbidden(&headers) {
|
||||||
|
return error(StatusCode::FORBIDDEN, "拒绝跨站请求");
|
||||||
|
}
|
||||||
|
let total = match request.count() {
|
||||||
|
Ok(n) => n,
|
||||||
|
Err(e) => return error(StatusCode::BAD_REQUEST, e),
|
||||||
|
};
|
||||||
|
let Some(executable) = s.executable.clone() else {
|
||||||
|
return error(
|
||||||
|
StatusCode::SERVICE_UNAVAILABLE,
|
||||||
|
"Go 地图下载器未安装,请运行 scripts/build-map-downloader.ps1 或使用完整发布包",
|
||||||
|
);
|
||||||
|
};
|
||||||
|
{
|
||||||
|
let Ok(mut job) = s.job.lock() else {
|
||||||
|
return error(StatusCode::INTERNAL_SERVER_ERROR, "下载状态暂不可用");
|
||||||
|
};
|
||||||
|
if job.as_ref().is_some_and(|j| j.state == "running") {
|
||||||
|
return error(StatusCode::CONFLICT, "已有下载任务,请等待或取消");
|
||||||
|
}
|
||||||
|
s.cancel.store(false, Ordering::Relaxed);
|
||||||
|
*job = Some(Job {
|
||||||
|
state: "running".into(),
|
||||||
|
total,
|
||||||
|
done: 0,
|
||||||
|
failed: 0,
|
||||||
|
message: "正在准备下载".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
tokio::task::spawn_blocking(move || run(s, executable, request));
|
||||||
|
(StatusCode::ACCEPTED, Json(json!({"total":total}))).into_response()
|
||||||
|
}
|
||||||
|
fn run(s: Arc<Manager>, executable: PathBuf, request: DownloadRequest) {
|
||||||
|
let outcome = (|| -> Result<bool, Box<dyn std::error::Error>> {
|
||||||
|
let offline = s.root.join("offline");
|
||||||
|
if !crate::maps::allowed(&s.root, &offline) {
|
||||||
|
return Err("地图输出路径无效".into());
|
||||||
|
}
|
||||||
|
std::fs::create_dir_all(&offline)?;
|
||||||
|
let payload = json!({"bounds":request.bounds,"minZoom":request.min_zoom,"maxZoom":request.max_zoom,
|
||||||
|
"layers":request.layers(),"output":offline,"baseUrl":format!("http://127.0.0.1:{}/api/maps/tile",s.port)});
|
||||||
|
let mut command = Command::new(executable);
|
||||||
|
command
|
||||||
|
.stdin(Stdio::piped())
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::null());
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use std::os::windows::process::CommandExt;
|
||||||
|
command.creation_flags(0x08000000);
|
||||||
|
}
|
||||||
|
let mut child = command.spawn()?;
|
||||||
|
let input_result = (|| -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let mut input = child.stdin.take().ok_or("下载器输入不可用")?;
|
||||||
|
input.write_all(&serde_json::to_vec(&payload)?)?;
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
if let Err(e) = input_result {
|
||||||
|
let _ = child.kill();
|
||||||
|
let _ = child.wait();
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
let output = child.stdout.take().ok_or("下载器输出不可用")?;
|
||||||
|
let progress = s.clone();
|
||||||
|
let reader = std::thread::spawn(move || {
|
||||||
|
for line in BufReader::new(output).lines().map_while(Result::ok) {
|
||||||
|
if line.len() > 1024 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&line)
|
||||||
|
&& let Ok(mut job) = progress.job.lock()
|
||||||
|
&& let Some(j) = job.as_mut()
|
||||||
|
{
|
||||||
|
j.done = v["done"].as_u64().unwrap_or(j.done).min(j.total);
|
||||||
|
j.failed = v["failed"].as_u64().unwrap_or(j.failed).min(j.done);
|
||||||
|
j.message = format!("已处理 {} / {},失败 {}", j.done, j.total, j.failed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let result = loop {
|
||||||
|
if s.cancel.load(Ordering::Relaxed) {
|
||||||
|
let _ = child.kill();
|
||||||
|
}
|
||||||
|
match child.try_wait() {
|
||||||
|
Ok(Some(status)) => break Ok(status.success()),
|
||||||
|
Ok(None) => std::thread::sleep(Duration::from_millis(100)),
|
||||||
|
Err(e) => {
|
||||||
|
let _ = child.kill();
|
||||||
|
let _ = child.wait();
|
||||||
|
break Err(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let _ = reader.join();
|
||||||
|
Ok(result?)
|
||||||
|
})();
|
||||||
|
if let Ok(mut job) = s.job.lock()
|
||||||
|
&& let Some(j) = job.as_mut()
|
||||||
|
{
|
||||||
|
if s.cancel.load(Ordering::Relaxed) {
|
||||||
|
j.state = "cancelled".into();
|
||||||
|
j.message = "已取消,完成的瓦片已保留;重新下载可跳过已有瓦片".into();
|
||||||
|
} else if outcome.is_ok_and(|ok| ok) && j.done == j.total && j.failed == 0 {
|
||||||
|
j.state = "completed".into();
|
||||||
|
j.message = "离线地图准备完成,所有瓦片已通过图像校验".into();
|
||||||
|
} else {
|
||||||
|
j.state = "failed".into();
|
||||||
|
j.message = format!(
|
||||||
|
"下载未完成(已处理 {} / {},失败 {}),请检查网络、天地图授权或磁盘空间后重试",
|
||||||
|
j.done, j.total, j.failed
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use axum::{
|
||||||
|
body::{Body, to_bytes},
|
||||||
|
http::Request,
|
||||||
|
};
|
||||||
|
use tower::ServiceExt;
|
||||||
|
#[tokio::test]
|
||||||
|
async fn preferences_persist_conflict_and_reject_cross_origin() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (app, _shutdown) = router(temp.path().into(), 8787);
|
||||||
|
let response = app
|
||||||
|
.clone()
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.uri("/api/maps/preferences")
|
||||||
|
.body(Body::empty())
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
|
let mut p: Preferences =
|
||||||
|
serde_json::from_slice(&to_bytes(response.into_body(), 65536).await.unwrap()).unwrap();
|
||||||
|
p.longitude = 116.4;
|
||||||
|
p.latitude = 39.9;
|
||||||
|
let save = || {
|
||||||
|
Request::builder()
|
||||||
|
.method("PUT")
|
||||||
|
.uri("/api/maps/preferences")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.body(Body::from(serde_json::to_vec(&p).unwrap()))
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
app.clone().oneshot(save()).await.unwrap().status(),
|
||||||
|
StatusCode::OK
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
app.clone().oneshot(save()).await.unwrap().status(),
|
||||||
|
StatusCode::CONFLICT
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
read_preferences(&temp.path().join("maps"))
|
||||||
|
.unwrap()
|
||||||
|
.longitude,
|
||||||
|
116.4
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
app.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.uri("/api/maps/preferences")
|
||||||
|
.header("origin", "https://evil.invalid")
|
||||||
|
.body(Body::empty())
|
||||||
|
.unwrap()
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.status(),
|
||||||
|
StatusCode::FORBIDDEN
|
||||||
|
);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn corrupt_preferences_are_preserved() {
|
||||||
|
let t = tempfile::tempdir().unwrap();
|
||||||
|
std::fs::write(t.path().join("preferences.json"), b"broken").unwrap();
|
||||||
|
assert!(read_preferences(t.path()).is_err());
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(t.path().join("preferences.json")).unwrap(),
|
||||||
|
b"broken"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -135,7 +135,7 @@ pub fn router(root: PathBuf) -> Result<Router, reqwest::Error> {
|
|||||||
.with_state(maps))
|
.with_state(maps))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn local_request(headers: &HeaderMap) -> bool {
|
pub(super) fn local_request(headers: &HeaderMap) -> bool {
|
||||||
headers.get("origin").is_none_or(|v| {
|
headers.get("origin").is_none_or(|v| {
|
||||||
matches!(
|
matches!(
|
||||||
v.to_str(),
|
v.to_str(),
|
||||||
@@ -187,7 +187,7 @@ fn tile_response(bytes: Vec<u8>, source: &str) -> Response {
|
|||||||
.insert("x-map-source", source.parse().unwrap());
|
.insert("x-map-source", source.parse().unwrap());
|
||||||
response
|
response
|
||||||
}
|
}
|
||||||
fn allowed(root: &FsPath, path: &FsPath) -> bool {
|
pub(super) fn allowed(root: &FsPath, path: &FsPath) -> bool {
|
||||||
let Ok(relative) = path.strip_prefix(root) else {
|
let Ok(relative) = path.strip_prefix(root) else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user