Skip to main content

w_gui/
context.rs

1use std::collections::{HashMap, HashSet};
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::sync::mpsc;
4use std::sync::{Arc, Mutex};
5use std::thread::JoinHandle;
6
7use crate::element::{ElementDecl, ElementId, Value};
8use crate::protocol::ServerMsg;
9use crate::server;
10use crate::window::Window;
11
12/// Options for creating a wgui [`Context`].
13pub struct ContextOptions {
14    /// Starting port for the HTTP server (WS gets port + 1).
15    pub start_port: u16,
16    /// Page title shown in the browser tab.
17    pub title: String,
18    /// Optional PNG favicon bytes. When `None`, no favicon is served.
19    pub favicon: Option<Vec<u8>>,
20    /// When `true`, bind to `0.0.0.0` (accessible on the network).
21    /// When `false`, bind to `127.0.0.1` (localhost only).
22    pub public: bool,
23}
24
25impl Default for ContextOptions {
26    fn default() -> Self {
27        Self {
28            start_port: 9080,
29            title: "wgui".to_string(),
30            favicon: None,
31            public: false,
32        }
33    }
34}
35
36pub struct Context {
37    // Sends batched ServerMsg diffs to the WS thread each frame
38    ws_tx: mpsc::SyncSender<Vec<ServerMsg>>,
39    // Receives browser edits from WS thread (wrapped in Mutex for Sync)
40    edit_rx: Mutex<mpsc::Receiver<(ElementId, Value)>>,
41    // Local cache of pending edits, drained from edit_rx on demand
42    incoming_edits: HashMap<ElementId, Value>,
43    // Signals HTTP thread to shut down
44    shutdown: Arc<AtomicBool>,
45
46    prev_frame: Vec<ElementDecl>,
47    current_frame: Vec<ElementDecl>,
48    http_port: u16,
49    ws_port: u16,
50    _http_handle: JoinHandle<()>,
51    _ws_handle: JoinHandle<()>,
52}
53
54impl Context {
55    /// Create a new wgui context with default options (localhost, port 9080, title "wgui").
56    pub fn new() -> Self {
57        Self::with_options(ContextOptions::default())
58    }
59
60    /// Create a new wgui context starting port search from `start_port`.
61    pub fn with_port(start_port: u16) -> Self {
62        Self::with_options(ContextOptions {
63            start_port,
64            ..Default::default()
65        })
66    }
67
68    /// Create a new wgui context with the given options.
69    pub fn with_options(opts: ContextOptions) -> Self {
70        let bind_addr = if opts.public { "0.0.0.0" } else { "127.0.0.1" };
71        let (http_port, ws_port) = server::find_port_pair(opts.start_port, bind_addr);
72
73        // Create channels for inter-thread communication
74        let (ws_tx, ws_rx) = mpsc::sync_channel::<Vec<ServerMsg>>(2);
75        let (edit_tx, edit_rx) = mpsc::channel::<(ElementId, Value)>();
76        let shutdown = Arc::new(AtomicBool::new(false));
77
78        let http_handle =
79            server::spawn_http(shutdown.clone(), http_port, bind_addr, &opts.title, opts.favicon);
80        let ws_handle = server::spawn_ws(ws_rx, edit_tx, ws_port, bind_addr);
81
82        println!("wgui: UI available at http://{bind_addr}:{http_port}");
83
84        Self {
85            ws_tx,
86            edit_rx: Mutex::new(edit_rx),
87            incoming_edits: HashMap::new(),
88            shutdown,
89            prev_frame: Vec::new(),
90            current_frame: Vec::new(),
91            http_port,
92            ws_port,
93            _http_handle: http_handle,
94            _ws_handle: ws_handle,
95        }
96    }
97
98    /// Returns the HTTP port the UI is served on.
99    pub fn http_port(&self) -> u16 {
100        self.http_port
101    }
102
103    /// Returns the WebSocket port.
104    pub fn ws_port(&self) -> u16 {
105        self.ws_port
106    }
107
108    /// Get or create a named window. Call widget methods on the returned `Window`.
109    pub fn window(&mut self, name: &str) -> Window<'_> {
110        Window::new(name.to_string(), self)
111    }
112
113    /// Consume a pending browser edit for the given element id, if any.
114    pub(crate) fn consume_edit(&mut self, id: &str) -> Option<Value> {
115        // Drain all pending edits from the channel into the local cache
116        let rx = self.edit_rx.lock().unwrap();
117        while let Ok((elem_id, value)) = rx.try_recv() {
118            self.incoming_edits.insert(elem_id, value);
119        }
120        drop(rx);
121        self.incoming_edits.remove(id)
122    }
123
124    /// Record an element declaration for the current frame.
125    pub(crate) fn declare(&mut self, decl: ElementDecl) {
126        self.current_frame.push(decl);
127    }
128
129    /// Number of elements declared so far this frame (for generating unique separator ids).
130    pub(crate) fn current_frame_len(&self) -> usize {
131        self.current_frame.len()
132    }
133
134    /// Finish the current frame: reconcile with previous frame, send diffs over WS.
135    pub fn end_frame(&mut self) {
136        let outgoing = reconcile(&self.prev_frame, &self.current_frame);
137
138        if !outgoing.is_empty() {
139            match self.ws_tx.try_send(outgoing) {
140                Ok(()) => {}
141                Err(mpsc::TrySendError::Full(_)) => {
142                    log::warn!("wgui: WS channel backpressure, skipping frame update");
143                }
144                Err(mpsc::TrySendError::Disconnected(_)) => {
145                    log::warn!("wgui: WS thread disconnected");
146                }
147            }
148        }
149
150        // Swap frames
151        self.prev_frame = std::mem::take(&mut self.current_frame);
152    }
153}
154
155impl Default for Context {
156    fn default() -> Self {
157        Self::new()
158    }
159}
160
161impl Drop for Context {
162    fn drop(&mut self) {
163        self.shutdown.store(true, Ordering::Release);
164    }
165}
166
167/// Compare previous and current frames, producing the minimal set of
168/// Add / Update / Remove messages needed to bring a client up to date.
169fn reconcile(prev: &[ElementDecl], current: &[ElementDecl]) -> Vec<ServerMsg> {
170    let mut outgoing = Vec::new();
171
172    // Build index of previous frame for O(1) lookup
173    let prev_index: HashMap<&str, usize> = prev
174        .iter()
175        .enumerate()
176        .map(|(i, d)| (d.id.as_str(), i))
177        .collect();
178
179    // Detect added and updated elements
180    for decl in current {
181        match prev_index.get(decl.id.as_str()) {
182            None => {
183                outgoing.push(ServerMsg::Add {
184                    element: decl.clone(),
185                });
186            }
187            Some(&idx) => {
188                let prev_decl = &prev[idx];
189                let value_changed = prev_decl.value != decl.value || prev_decl.kind != decl.kind || prev_decl.label != decl.label;
190                let meta_changed = prev_decl.meta != decl.meta;
191                let label_changed = prev_decl.label != decl.label;
192                if value_changed || meta_changed || label_changed {
193                    outgoing.push(ServerMsg::Update {
194                        id: decl.id.clone(),
195                        value: decl.value.clone(),
196                        label: if label_changed {
197                            Some(decl.label.clone())
198                        } else {
199                            None
200                        },
201                        meta: if meta_changed {
202                            Some(decl.meta.clone())
203                        } else {
204                            None
205                        },
206                    });
207                }
208            }
209        }
210    }
211
212    // Detect removed elements
213    let current_ids: HashSet<&str> = current.iter().map(|d| d.id.as_str()).collect();
214    for prev_decl in prev {
215        if !current_ids.contains(prev_decl.id.as_str()) {
216            outgoing.push(ServerMsg::Remove {
217                id: prev_decl.id.clone(),
218            });
219        }
220    }
221
222    outgoing
223}
224
225const _: () = {
226    fn _assert_send_sync<T: Send + Sync>() {}
227    fn _check() { _assert_send_sync::<Context>(); }
228};
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233    use crate::element::{ElementKind, ElementMeta, Value};
234    use std::sync::Arc;
235
236    fn make_decl(id: &str, value: Value) -> ElementDecl {
237        ElementDecl {
238            id: id.to_string(),
239            kind: ElementKind::Label,
240            label: id.to_string(),
241            value,
242            meta: ElementMeta::default(),
243            window: Arc::from("test"),
244        }
245    }
246
247    #[test]
248    fn reconcile_detects_additions() {
249        let msgs = reconcile(&[], &[make_decl("a", Value::Bool(true))]);
250        assert_eq!(msgs.len(), 1);
251        assert!(matches!(&msgs[0], ServerMsg::Add { element } if element.id == "a"));
252    }
253
254    #[test]
255    fn reconcile_detects_removals() {
256        let msgs = reconcile(&[make_decl("a", Value::Bool(true))], &[]);
257        assert_eq!(msgs.len(), 1);
258        assert!(matches!(&msgs[0], ServerMsg::Remove { id } if id == "a"));
259    }
260
261    #[test]
262    fn reconcile_detects_updates() {
263        let prev = vec![make_decl("a", Value::Bool(true))];
264        let current = vec![make_decl("a", Value::Bool(false))];
265        let msgs = reconcile(&prev, &current);
266        assert_eq!(msgs.len(), 1);
267        assert!(matches!(&msgs[0], ServerMsg::Update { id, .. } if id == "a"));
268    }
269
270    #[test]
271    fn reconcile_unchanged() {
272        let prev = vec![make_decl("a", Value::Bool(true))];
273        let current = vec![make_decl("a", Value::Bool(true))];
274        assert!(reconcile(&prev, &current).is_empty());
275    }
276
277    #[test]
278    fn reconcile_mixed() {
279        let prev = vec![
280            make_decl("keep", Value::Bool(true)),
281            make_decl("update", Value::Float(1.0)),
282            make_decl("remove", Value::Bool(false)),
283        ];
284        let current = vec![
285            make_decl("keep", Value::Bool(true)),
286            make_decl("update", Value::Float(2.0)),
287            make_decl("add", Value::Bool(true)),
288        ];
289        let msgs = reconcile(&prev, &current);
290        assert_eq!(msgs.len(), 3); // update + remove + add
291    }
292}