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;
190                let meta_changed = prev_decl.meta != decl.meta;
191                if value_changed || meta_changed {
192                    outgoing.push(ServerMsg::Update {
193                        id: decl.id.clone(),
194                        value: decl.value.clone(),
195                        meta: if meta_changed {
196                            Some(decl.meta.clone())
197                        } else {
198                            None
199                        },
200                    });
201                }
202            }
203        }
204    }
205
206    // Detect removed elements
207    let current_ids: HashSet<&str> = current.iter().map(|d| d.id.as_str()).collect();
208    for prev_decl in prev {
209        if !current_ids.contains(prev_decl.id.as_str()) {
210            outgoing.push(ServerMsg::Remove {
211                id: prev_decl.id.clone(),
212            });
213        }
214    }
215
216    outgoing
217}
218
219const _: () = {
220    fn _assert_send_sync<T: Send + Sync>() {}
221    fn _check() { _assert_send_sync::<Context>(); }
222};
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227    use crate::element::{ElementKind, ElementMeta, Value};
228    use std::sync::Arc;
229
230    fn make_decl(id: &str, value: Value) -> ElementDecl {
231        ElementDecl {
232            id: id.to_string(),
233            kind: ElementKind::Label,
234            label: id.to_string(),
235            value,
236            meta: ElementMeta::default(),
237            window: Arc::from("test"),
238        }
239    }
240
241    #[test]
242    fn reconcile_detects_additions() {
243        let msgs = reconcile(&[], &[make_decl("a", Value::Bool(true))]);
244        assert_eq!(msgs.len(), 1);
245        assert!(matches!(&msgs[0], ServerMsg::Add { element } if element.id == "a"));
246    }
247
248    #[test]
249    fn reconcile_detects_removals() {
250        let msgs = reconcile(&[make_decl("a", Value::Bool(true))], &[]);
251        assert_eq!(msgs.len(), 1);
252        assert!(matches!(&msgs[0], ServerMsg::Remove { id } if id == "a"));
253    }
254
255    #[test]
256    fn reconcile_detects_updates() {
257        let prev = vec![make_decl("a", Value::Bool(true))];
258        let current = vec![make_decl("a", Value::Bool(false))];
259        let msgs = reconcile(&prev, &current);
260        assert_eq!(msgs.len(), 1);
261        assert!(matches!(&msgs[0], ServerMsg::Update { id, .. } if id == "a"));
262    }
263
264    #[test]
265    fn reconcile_unchanged() {
266        let prev = vec![make_decl("a", Value::Bool(true))];
267        let current = vec![make_decl("a", Value::Bool(true))];
268        assert!(reconcile(&prev, &current).is_empty());
269    }
270
271    #[test]
272    fn reconcile_mixed() {
273        let prev = vec![
274            make_decl("keep", Value::Bool(true)),
275            make_decl("update", Value::Float(1.0)),
276            make_decl("remove", Value::Bool(false)),
277        ];
278        let current = vec![
279            make_decl("keep", Value::Bool(true)),
280            make_decl("update", Value::Float(2.0)),
281            make_decl("add", Value::Bool(true)),
282        ];
283        let msgs = reconcile(&prev, &current);
284        assert_eq!(msgs.len(), 3); // update + remove + add
285    }
286}