1use std::rc::Rc;
8
9use gpui_kit::component::checkbox::Checkbox;
10use gpui_kit::component::input::{Input, InputEvent, InputState};
11use gpui_kit::component::{Sizable as _, v_flex};
12use gpui_kit::{
13 App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, Styled as _,
14 Subscription, Window, div,
15};
16use serde::Serialize;
17use serde::de::DeserializeOwned;
18use serde_json::{Value, json};
19
20use crate::theme::{self, color};
21use crate::widgets::{MenuSelect, row};
22
23pub trait Params: Serialize + DeserializeOwned + Clone + PartialEq + 'static {
28 fn choices(_field: &str) -> Option<&'static [&'static str]> {
31 None
32 }
33
34 fn element_label(field: &str, _len: usize, i: usize) -> String {
36 format!("{} {}", label_of(field), i + 1)
37 }
38
39 fn on_choice(_value: &mut Value, _field: &str, _choice: &str) {}
41}
42
43pub type Commit<T> = Rc<dyn Fn(T, &mut App) -> Result<(), String>>;
45
46const MAX_LIST: usize = 2;
48
49struct Field {
51 key: String,
52 index: Option<usize>,
53 label: String,
54 input: Entity<InputState>,
55}
56
57pub struct ParamEditor<T: Params> {
59 fields: Vec<Field>,
60 fields_for: String,
62 field_subs: Vec<Subscription>,
63 error: Option<String>,
64 target: Option<(T, Commit<T>)>,
65}
66
67impl<T: Params> Default for ParamEditor<T> {
68 fn default() -> Self {
69 Self { fields: Vec::new(), fields_for: String::new(), field_subs: Vec::new(), error: None, target: None }
70 }
71}
72
73impl<T: Params> ParamEditor<T> {
74 pub fn new() -> Self {
76 Self::default()
77 }
78
79 pub fn set_target(&mut self, key: &str, op: &T, commit: Commit<T>, window: &mut Window, cx: &mut Context<Self>) {
82 let value = serde_json::to_value(op).unwrap_or(Value::Null);
83 self.target = Some((op.clone(), commit));
84 let fresh = format!("{key}/{value}");
85 if fresh == self.fields_for {
86 return;
87 }
88 if !self.fields_for.starts_with(&format!("{key}/")) {
89 self.error = None;
90 }
91 self.fields_for = fresh;
92 self.fields.clear();
93 self.field_subs.clear();
94 let Value::Object(map) = &value else { return };
95 for (k, v) in map {
96 match v {
97 Value::Number(n) => self.add_field(k, None, label_of(k), n.as_f64().unwrap_or(0.0), window, cx),
98 Value::Array(a) if a.len() <= MAX_LIST && !a.is_empty() && a.iter().all(Value::is_number) => {
99 for (i, n) in a.iter().enumerate() {
100 self.add_field(
101 k,
102 Some(i),
103 T::element_label(k, a.len(), i),
104 n.as_f64().unwrap_or(0.0),
105 window,
106 cx,
107 );
108 }
109 }
110 _ => {}
111 }
112 }
113 }
114
115 pub fn target(&self) -> Option<&T> {
117 self.target.as_ref().map(|(op, _)| op)
118 }
119
120 pub fn error(&self) -> Option<&str> {
122 self.error.as_deref()
123 }
124
125 fn add_field(
126 &mut self,
127 key: &str,
128 index: Option<usize>,
129 label: String,
130 v: f64,
131 window: &mut Window,
132 cx: &mut Context<Self>,
133 ) {
134 let input = cx.new(|cx| InputState::new(window, cx).default_value(trim_number(v)));
135 let sub = cx.subscribe(&input, |this, _, e: &InputEvent, cx| {
136 if matches!(e, InputEvent::PressEnter { .. } | InputEvent::Blur) {
137 this.apply_fields(cx);
138 }
139 });
140 self.field_subs.push(sub);
141 self.fields.push(Field { key: key.to_string(), index, label, input });
142 }
143
144 fn apply_fields(&mut self, cx: &mut Context<Self>) {
147 let Some((op, _)) = &self.target else { return };
148 let mut value = serde_json::to_value(op).unwrap_or(Value::Null);
149 for f in &self.fields {
150 let text = f.input.read(cx).value().to_string();
151 let Ok(n) = text.trim().parse::<f64>() else {
152 self.error = Some(format!("{}: {text:?} is not a number", f.label));
153 cx.notify();
154 return;
155 };
156 let slot = match f.index {
157 Some(i) => value.get_mut(&f.key).and_then(|a| a.get_mut(i)),
158 None => value.get_mut(&f.key),
159 };
160 if let Some(slot) = slot {
161 *slot = number_like(slot, n);
162 }
163 }
164 self.set_value(value, cx);
165 }
166
167 fn set_value(&mut self, value: Value, cx: &mut Context<Self>) {
168 let Some((op, commit)) = self.target.clone() else { return };
169 match serde_json::from_value::<T>(value) {
170 Ok(new) if new == op => self.error = None,
171 Ok(new) => self.error = commit(new, cx).err(),
172 Err(e) => self.error = Some(e.to_string()),
173 }
174 cx.notify();
175 }
176
177 fn set_choice(&mut self, key: &str, choice: &str, cx: &mut Context<Self>) {
178 let Some((op, _)) = &self.target else { return };
179 let mut value = serde_json::to_value(op).unwrap_or(Value::Null);
180 value[key] = json!(choice);
181 T::on_choice(&mut value, key, choice);
182 self.set_value(value, cx);
183 }
184
185 fn set_bool(&mut self, key: &str, on: bool, cx: &mut Context<Self>) {
186 let Some((op, _)) = &self.target else { return };
187 let mut value = serde_json::to_value(op).unwrap_or(Value::Null);
188 value[key] = json!(on);
189 self.set_value(value, cx);
190 }
191}
192
193impl<T: Params> Render for ParamEditor<T> {
194 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
195 let mut out = v_flex().w_full().gap(gpui_kit::px(theme::SM));
196 let Some((op, _)) = &self.target else { return out };
197 let value = serde_json::to_value(op).unwrap_or(Value::Null);
198 for f in &self.fields {
199 out = out.child(row(f.label.clone(), div().w_full().child(Input::new(&f.input).small())));
200 }
201 let mut shown = !self.fields.is_empty();
202 if let Value::Object(map) = &value {
203 for (k, v) in map {
204 if let (Some(opts), Some(cur)) = (T::choices(k), v.as_str()) {
205 let this = cx.entity().downgrade();
206 let key = k.clone();
207 let names: Vec<SharedString> =
208 opts.iter().map(|o| SharedString::from(o.replace('_', " "))).collect();
209 let sel = opts.iter().position(|o| *o == cur);
210 out = out.child(row(
211 label_of(k),
212 MenuSelect::new(SharedString::from(format!("param-{k}")), names, sel, move |i, _, cx| {
213 let _ = this.update(cx, |p, cx| p.set_choice(&key, opts[i], cx));
214 }),
215 ));
216 shown = true;
217 } else if let Some(b) = v.as_bool() {
218 let this = cx.entity().downgrade();
219 let key = k.clone();
220 out = out.child(row(
221 label_of(k),
222 Checkbox::new(SharedString::from(format!("param-{k}"))).checked(b).on_click(
223 move |on: &bool, _, cx| {
224 let on = *on;
225 let _ = this.update(cx, |p, cx| p.set_bool(&key, on, cx));
226 },
227 ),
228 ));
229 shown = true;
230 } else if let Some(a) = v.as_array().filter(|a| a.len() > MAX_LIST) {
231 out = out.child(row(
232 label_of(k),
233 div()
234 .text_xs()
235 .text_color(color::text_muted())
236 .child(format!("{} values (edit in the file)", a.len())),
237 ));
238 shown = true;
239 }
240 }
241 }
242 if !shown {
243 out = out.child(div().text_xs().text_color(color::text_muted()).child("No parameters."));
244 }
245 out.children(self.error.clone().map(|e| div().text_xs().text_color(color::danger()).child(e)))
246 }
247}
248
249fn number_like(slot: &Value, n: f64) -> Value {
252 if slot.is_u64() || slot.is_i64() { json!(n.round() as i64) } else { json!(n) }
253}
254
255pub fn label_of(key: &str) -> String {
257 let mut s = key.replace('_', " ");
258 if let Some(c) = s.get_mut(0..1) {
259 c.make_ascii_uppercase();
260 }
261 s
262}
263
264pub fn trim_number(v: f64) -> String {
266 if v.fract() == 0.0 && v.abs() < 1e15 {
267 format!("{}", v as i64)
268 } else {
269 let s = format!("{v:.6}");
270 s.trim_end_matches('0').trim_end_matches('.').to_string()
271 }
272}
273
274#[cfg(test)]
275mod tests {
276 use super::*;
277
278 #[test]
279 fn labels_and_numbers() {
280 assert_eq!(label_of("clip_limit"), "Clip limit");
281 assert_eq!(label_of("sigma_samples"), "Sigma samples");
282 assert_eq!(trim_number(300.0), "300");
283 assert_eq!(trim_number(0.25), "0.25");
284 assert_eq!(trim_number(-1.5), "-1.5");
285 }
286
287 #[test]
288 fn integers_stay_integers() {
289 assert_eq!(number_like(&json!(3), 4.6), json!(5));
290 assert_eq!(number_like(&json!(-3), -4.4), json!(-4));
291 assert_eq!(number_like(&json!(0.5), 2.0), json!(2.0));
292 let v = number_like(&json!(3), -2.0);
294 assert!(serde_json::from_value::<u32>(v).is_err());
295 }
296}