1use std::sync::{Arc, Mutex};
31
32use egui::{Id, Response, Ui};
33use egui_pop_model::commands::Origin;
34use egui_pop_model::ids::OwnerId;
35use egui_pop_model::values::{Change, GestureId, Set, Store, Value};
36
37use crate::state::{Slot, lock, shared};
38use crate::strings::{self, HELD_BY, NO_VALUE, READ_ONLY};
39
40pub type SharedStore = Arc<Mutex<Store>>;
42
43pub trait Bindable: Clone + PartialEq + Default {
45 fn from_value(value: &Value) -> Option<Self>;
46 fn to_value(&self) -> Value;
47}
48
49impl Bindable for f64 {
50 fn from_value(v: &Value) -> Option<Self> {
51 v.as_f64()
52 }
53 fn to_value(&self) -> Value {
54 Value::Float(*self)
55 }
56}
57
58impl Bindable for f32 {
59 fn from_value(v: &Value) -> Option<Self> {
60 v.as_f64().map(|v| v as f32)
61 }
62 fn to_value(&self) -> Value {
63 Value::Float(*self as f64)
64 }
65}
66
67impl Bindable for i64 {
68 fn from_value(v: &Value) -> Option<Self> {
69 v.as_i64().or_else(|| v.as_f64().map(|f| f.round() as i64))
70 }
71 fn to_value(&self) -> Value {
72 Value::Int(*self)
73 }
74}
75
76impl Bindable for i32 {
77 fn from_value(v: &Value) -> Option<Self> {
78 i64::from_value(v).map(|v| v as i32)
79 }
80 fn to_value(&self) -> Value {
81 Value::Int(*self as i64)
82 }
83}
84
85impl Bindable for bool {
86 fn from_value(v: &Value) -> Option<Self> {
87 v.as_bool()
88 }
89 fn to_value(&self) -> Value {
90 Value::Bool(*self)
91 }
92}
93
94impl Bindable for String {
95 fn from_value(v: &Value) -> Option<Self> {
96 v.as_text().map(str::to_string)
97 }
98 fn to_value(&self) -> Value {
99 Value::Text(self.clone())
100 }
101}
102
103#[derive(Debug)]
105pub enum Binding<'a, T> {
106 Plain(&'a mut T),
108 Bound {
110 store: &'a SharedStore,
111 path: &'a str,
112 },
113 Watch {
115 store: &'a SharedStore,
116 path: &'a str,
117 },
118}
119
120impl<'a, T> Binding<'a, T> {
121 pub fn plain(value: &'a mut T) -> Self {
122 Binding::Plain(value)
123 }
124
125 pub fn bound(store: &'a SharedStore, path: &'a str) -> Self {
126 Binding::Bound { store, path }
127 }
128
129 pub fn watch(store: &'a SharedStore, path: &'a str) -> Self {
130 Binding::Watch { store, path }
131 }
132}
133
134const GESTURE: Slot<u64> = Slot::new("core.binding.gesture");
136const CANCELLED: Slot<bool> = Slot::new("core.binding.cancelled");
138const REFUSED: Slot<String> = Slot::new("core.binding.refused");
140
141pub fn cancel_gesture(ctx: &egui::Context, response_id: Id) {
145 CANCELLED.keyed(response_id).set(ctx, true);
146}
147
148struct OpenGesture {
151 window: egui::ViewportId,
152 widget: Id,
153 store: SharedStore,
154 gesture: GestureId,
155}
156
157impl std::fmt::Debug for OpenGesture {
158 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159 f.debug_struct("OpenGesture")
160 .field("window", &self.window)
161 .field("widget", &self.widget)
162 .field("gesture", &self.gesture)
163 .finish_non_exhaustive()
164 }
165}
166
167#[derive(Debug, Default)]
170struct Open {
171 gestures: Vec<OpenGesture>,
172 registered: bool,
173}
174
175fn open_gestures(ctx: &egui::Context) -> Arc<Mutex<Open>> {
176 shared::<Open>(ctx, "core.binding.open")
177}
178
179fn opened(ctx: &egui::Context, widget: Id, store: &SharedStore, gesture: GestureId) {
182 let st = open_gestures(ctx);
183 let mut open = lock(&st);
184 open.gestures.retain(|g| g.widget != widget);
185 open.gestures.push(OpenGesture {
186 window: ctx.viewport_id(),
187 widget,
188 store: Arc::clone(store),
189 gesture,
190 });
191 if !open.registered {
192 open.registered = true;
193 ctx.on_end_pass(
194 "egui_pop_core::binding",
195 Arc::new(|ui: &mut Ui| cancel_orphans(ui.ctx())),
196 );
197 }
198}
199
200fn closed(ctx: &egui::Context, widget: Id) {
202 lock(&open_gestures(ctx))
203 .gestures
204 .retain(|g| g.widget != widget);
205}
206
207fn cancel_orphans(ctx: &egui::Context) {
212 let window = ctx.viewport_id();
213 let orphans: Vec<OpenGesture> = {
214 let st = open_gestures(ctx);
215 let mut open = lock(&st);
216 let (gone, kept) = std::mem::take(&mut open.gestures)
217 .into_iter()
218 .partition(|g| {
219 g.window == window && !ctx.viewport(|v| v.this_pass.widgets.contains(g.widget))
220 });
221 open.gestures = kept;
222 gone
223 };
224 for g in orphans {
225 lock(&g.store).cancel(g.gesture);
226 GESTURE.keyed(g.widget).remove(ctx);
227 if ctx.dragged_id() == Some(g.widget) {
228 ctx.stop_dragging();
229 }
230 log::debug!(target: "egui_pop", "binding: the widget {:?} went away mid-gesture; gesture cancelled", g.widget);
231 }
232}
233
234pub fn edit<T: Bindable>(
243 ui: &mut Ui,
244 binding: Binding<'_, T>,
245 widget: impl FnOnce(&mut Ui, &mut T) -> Response,
246) -> Response {
247 match binding {
248 Binding::Plain(v) => widget(ui, v),
249 Binding::Watch { store, path } => {
250 let mut v = read(store, path).unwrap_or_default();
251 let r = ui.add_enabled_ui(false, |ui| widget(ui, &mut v)).inner;
252 r.on_disabled_hover_text(strings::tr(ui.ctx(), &READ_ONLY))
253 }
254 Binding::Bound { store, path } => {
255 let (current, held) = {
256 let s = lock(store);
257 match s.get(path) {
258 Some(e) => (
259 T::from_value(&e.value),
260 s.held_by(path).filter(|o| **o != Origin::User).cloned(),
261 ),
262 None => (None, None),
263 }
264 };
265 let Some(mut v) = current else {
266 let mut dummy = T::default();
267 let r = ui.add_enabled_ui(false, |ui| widget(ui, &mut dummy)).inner;
268 log::warn!(target: "egui_pop", "binding to `{path}`: no such value (or not this type); the widget is disabled");
269 return r.on_disabled_hover_text(strings::tr_args(
270 ui.ctx(),
271 &NO_VALUE,
272 &[("path", path)],
273 ));
274 };
275 let before = v.clone();
276 let mut r = widget(ui, &mut v);
277 let gid = GESTURE.keyed(r.id);
278 if r.drag_started() {
279 let g = lock(store).begin_gesture(Origin::User, &format!("drag {path}"));
280 gid.set(ui.ctx(), g.0);
281 opened(ui.ctx(), r.id, store, g);
282 }
283 let gesture = gid.get(ui.ctx()).map(GestureId);
284 let cancelled = CANCELLED.keyed(r.id).remove(ui.ctx()).unwrap_or(false)
285 || (r.drag_stopped() && crate::focus::escape_cancelled(ui.ctx()).is_some());
286 if cancelled {
287 if let Some(g) = gesture {
291 lock(store).cancel(g);
292 gid.remove(ui.ctx());
293 closed(ui.ctx(), r.id);
294 }
295 return r;
296 }
297 if v != before {
298 let mut set =
301 Set::new(path, Change::To(v.to_value()), Origin::User).by(&OwnerId::FRAMEWORK);
302 set.gesture = gesture;
303 let outcome = lock(store).set(set);
304 match outcome {
305 Ok(_) => {
306 REFUSED.keyed(r.id).remove(ui.ctx());
307 }
308 Err(refused) => {
309 log::warn!(target: "egui_pop", "write to `{path}` refused: {refused}");
310 REFUSED.keyed(r.id).set(ui.ctx(), refused.to_string());
311 }
312 }
313 }
314 if r.drag_stopped()
315 && let Some(g) = gesture
316 {
317 lock(store).end(g);
318 gid.remove(ui.ctx());
319 closed(ui.ctx(), r.id);
320 }
321 if let Some(by) = held {
322 r = r.on_hover_text(strings::tr_args(
323 ui.ctx(),
324 &HELD_BY,
325 &[("origin", &format!("{by:?}"))],
326 ));
327 }
328 if let Some(e) = REFUSED.keyed(r.id).get(ui.ctx()) {
329 r = r.on_hover_text(e);
330 }
331 r
332 }
333 }
334}
335
336pub fn read<T: Bindable>(store: &SharedStore, path: &str) -> Option<T> {
338 lock(store).get(path).and_then(|e| T::from_value(&e.value))
339}
340
341#[derive(Clone, Debug, Default, PartialEq, Eq)]
344pub struct Choice(pub String);
345
346impl Bindable for Choice {
347 fn from_value(v: &Value) -> Option<Self> {
348 v.as_choice().map(|c| Choice(c.to_string()))
349 }
350 fn to_value(&self) -> Value {
351 Value::Choice(self.0.clone())
352 }
353}
354
355impl Bindable for Vec<f64> {
356 fn from_value(v: &Value) -> Option<Self> {
357 match v {
358 Value::Floats(f) => Some(f.clone()),
359 _ => None,
360 }
361 }
362 fn to_value(&self) -> Value {
363 Value::Floats(self.clone())
364 }
365}