1use crate::{detectors, Project, UserCatalog, BUILTIN_BLOCKS};
13use schemars::generate::SchemaSettings;
14use schemars::{JsonSchema, Schema};
15use serde_json::{json, Map, Value};
16
17pub const NAMES: [&str; 4] = ["project", "system", "user-catalog", "edit-ops"];
19
20pub const BASE_URL: &str = "https://masa-iwm.github.io/lensbench/schema/";
22
23pub fn version() -> &'static str {
26 minor_of(env!("CARGO_PKG_VERSION"))
27}
28
29pub fn minor_of(v: &str) -> &str {
31 let v = v.split(['-', '+']).next().unwrap_or(v);
32 let mut dots = v.match_indices('.').map(|(i, _)| i);
33 match (dots.next(), dots.next()) {
34 (Some(_), Some(j)) => &v[..j],
35 _ => v,
36 }
37}
38
39#[allow(dead_code)]
41#[derive(JsonSchema)]
42#[schemars(rename = "SystemFile")]
43struct SystemFile {
44 #[schemars(extend("const" = "lensbench-system"))]
46 format: String,
47 format_version: u64,
49 #[serde(default)]
51 lensbench: String,
52 #[serde(default)]
54 hash: String,
55 #[serde(default)]
57 coatings: Vec<String>,
58 system: crate::sysfile_v2::Prescription,
60}
61
62pub fn gen<T: JsonSchema>() -> Value {
64 let g = SchemaSettings::draft2020_12()
65 .for_deserialize()
66 .into_generator();
67 let s: Schema = g.into_root_schema_for::<T>();
68 s.to_value()
69}
70
71pub fn schema(name: &str) -> Option<Value> {
73 schema_with(name, &detectors::list())
74}
75
76pub fn schema_with(name: &str, kinds: &[detectors::DetectorKind]) -> Option<Value> {
78 let (mut v, title) = match name {
79 "project" => (gen::<Project>(), "lensbench プロジェクトファイル"),
80 "system" => {
81 let mut v = gen::<SystemFile>();
82 allow_nonfinite(&mut v);
83 v["$defs"]["NonFinite"] = json!({
84 "description": "JSON に書けない数(無限遠の inf、NaN)",
85 "type": "object",
86 "properties": {"$f": {"enum": ["inf", "-inf", "nan"]}},
87 "required": ["$f"],
88 "additionalProperties": false
89 });
90 (v, "lensbench 系ファイル")
91 }
92 "user-catalog" => (gen::<UserCatalog>(), "lensbench ユーザーカタログ"),
93 "edit-ops" => (
94 gen::<Vec<crate::edit_spec::EditOp>>(),
95 "lensbench 系の編集の操作の列(serve の edit の ops)",
96 ),
97 _ => return None,
98 };
99 add_detectors(&mut v, kinds);
100 finish(&mut v, name, title);
101 Some(v)
102}
103
104pub fn finish(v: &mut Value, name: &str, title: &str) {
106 let o = v.as_object_mut().expect("スキーマはオブジェクト");
107 o.insert("$id".into(), Value::from(url(name)));
108 o.insert("title".into(), Value::from(title));
109 if let Some(Value::Object(p)) = o.get_mut("properties") {
110 p.insert(
111 "$schema".into(),
112 json!({
113 "description": "このファイルのスキーマ(エディタの補完・検査用。読むときは無視する)",
114 "type": "string"
115 }),
116 );
117 }
118}
119
120pub fn all() -> Vec<(&'static str, Value)> {
122 all_with(&detectors::list())
123}
124
125pub fn all_with(kinds: &[detectors::DetectorKind]) -> Vec<(&'static str, Value)> {
128 NAMES
129 .iter()
130 .map(|n| (*n, schema_with(n, kinds).expect("NAMES の名前")))
131 .collect()
132}
133
134pub fn to_text(v: &Value) -> String {
137 serde_json::to_string_pretty(&sorted(v)).expect("JSON") + "\n"
138}
139
140fn sorted(v: &Value) -> Value {
141 match v {
142 Value::Object(o) => {
143 let mut keys: Vec<&String> = o.keys().collect();
144 keys.sort();
145 Value::Object(
146 keys.into_iter()
147 .map(|k| (k.clone(), sorted(&o[k])))
148 .collect(),
149 )
150 }
151 Value::Array(a) => Value::Array(a.iter().map(sorted).collect()),
152 x => x.clone(),
153 }
154}
155
156fn add_detectors(v: &mut Value, kinds: &[detectors::DetectorKind]) {
159 let Some(Value::Array(a)) = v.pointer_mut("/$defs/Block/oneOf") else {
160 return;
161 };
162 let id = json!({"type": "string", "default": ""});
163 let mut taken: Vec<&str> = BUILTIN_BLOCKS.to_vec();
164 for k in kinds {
165 let Some(f) = k.schema else { continue };
166 let mut sc = f();
167 if let Some(o) = sc.as_object_mut() {
168 o.insert("description".into(), json!(k.doc));
169 let props = o
170 .entry("properties")
171 .or_insert_with(|| json!({}))
172 .as_object_mut()
173 .expect("properties はオブジェクト");
174 props.insert("type".into(), json!({"type": "string", "const": k.name}));
175 props.insert("id".into(), id.clone());
176 let req = o.entry("required").or_insert_with(|| json!([]));
177 if let Value::Array(r) = req {
178 r.push(json!("type"));
179 }
180 }
181 a.push(sc);
182 taken.push(k.name);
183 }
184 a.push(json!({
185 "description": "検出器(登録した種類。最後のブロックだけに置け、面は足さない)。項目は種類ごと",
186 "type": "object",
187 "properties": {
188 "type": {"type": "string", "not": {"enum": taken}},
189 "id": id,
190 },
191 "required": ["type"],
192 }));
193}
194
195fn is_number_type(t: &Value) -> bool {
196 match t {
197 Value::String(s) => s == "number",
198 Value::Array(a) => a.iter().any(|x| x == "number"),
199 _ => false,
200 }
201}
202
203fn allow_nonfinite(v: &mut Value) {
205 match v {
206 Value::Object(o) => {
207 for x in o.values_mut() {
208 allow_nonfinite(x);
209 }
210 if o.get("type").is_some_and(is_number_type) {
211 let mut outer = Map::new();
212 for k in ["description", "default", "title"] {
213 if let Some(x) = o.remove(k) {
214 outer.insert(k.into(), x);
215 }
216 }
217 let inner = Value::Object(std::mem::take(o));
218 outer.insert(
219 "anyOf".into(),
220 json!([inner, {"$ref": "#/$defs/NonFinite"}]),
221 );
222 *o = outer;
223 }
224 }
225 Value::Array(a) => {
226 for x in a {
227 allow_nonfinite(x);
228 }
229 }
230 _ => {}
231 }
232}
233
234pub fn url(name: &str) -> String {
238 format!("{BASE_URL}v{}/{name}.schema.json", version())
239}
240
241pub fn stamp_text(txt: &str, name: &str) -> String {
244 let Some(rest) = txt.strip_prefix("{\n") else {
245 return txt.to_string();
246 };
247 let rest = match rest.strip_prefix(" \"$schema\":") {
248 Some(r) => r.split_once('\n').map_or("", |(_, r)| r),
249 None => rest,
250 };
251 let comma = if rest.trim_start().starts_with('}') {
252 ""
253 } else {
254 ","
255 };
256 format!(
257 "{{\n \"$schema\": {}{comma}\n{rest}",
258 Value::from(url(name))
259 )
260}
261
262pub fn pretty_with_schema(v: &Value, name: &str) -> String {
264 let txt = match v {
265 Value::Object(o) if o.contains_key("$schema") => {
266 let mut o = o.clone();
267 o.remove("$schema");
268 serde_json::to_string_pretty(&o)
269 }
270 _ => serde_json::to_string_pretty(v),
271 };
272 stamp_text(&txt.expect("JSON of plain data"), name)
273}
274
275pub fn strip_schema_key(txt: &str) -> Option<Value> {
277 if !txt.contains("$schema") {
278 return None;
279 }
280 match serde_json::from_str::<Value>(txt) {
281 Ok(Value::Object(mut o)) => o.remove("$schema").map(|_| Value::Object(o)),
282 _ => None,
283 }
284}