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;
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
40    edit_rx: 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,
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        while let Ok((elem_id, value)) = self.edit_rx.try_recv() {
117            self.incoming_edits.insert(elem_id, value);
118        }
119        self.incoming_edits.remove(id)
120    }
121
122    /// Record an element declaration for the current frame.
123    pub(crate) fn declare(&mut self, decl: ElementDecl) {
124        self.current_frame.push(decl);
125    }
126
127    /// Number of elements declared so far this frame (for generating unique separator ids).
128    pub(crate) fn current_frame_len(&self) -> usize {
129        self.current_frame.len()
130    }
131
132    /// Finish the current frame: reconcile with previous frame, send diffs over WS.
133    pub fn end_frame(&mut self) {
134        let outgoing = reconcile(&self.prev_frame, &self.current_frame);
135
136        if !outgoing.is_empty() {
137            match self.ws_tx.try_send(outgoing) {
138                Ok(()) => {}
139                Err(mpsc::TrySendError::Full(_)) => {
140                    log::warn!("wgui: WS channel backpressure, skipping frame update");
141                }
142                Err(mpsc::TrySendError::Disconnected(_)) => {
143                    log::warn!("wgui: WS thread disconnected");
144                }
145            }
146        }
147
148        // Swap frames
149        self.prev_frame = std::mem::take(&mut self.current_frame);
150    }
151}
152
153impl Default for Context {
154    fn default() -> Self {
155        Self::new()
156    }
157}
158
159impl Drop for Context {
160    fn drop(&mut self) {
161        self.shutdown.store(true, Ordering::Release);
162    }
163}
164
165/// Compare previous and current frames, producing the minimal set of
166/// Add / Update / Remove messages needed to bring a client up to date.
167fn reconcile(prev: &[ElementDecl], current: &[ElementDecl]) -> Vec<ServerMsg> {
168    let mut outgoing = Vec::new();
169
170    // Build index of previous frame for O(1) lookup
171    let prev_index: HashMap<&str, usize> = prev
172        .iter()
173        .enumerate()
174        .map(|(i, d)| (d.id.as_str(), i))
175        .collect();
176
177    // Detect added and updated elements
178    for decl in current {
179        match prev_index.get(decl.id.as_str()) {
180            None => {
181                outgoing.push(ServerMsg::Add {
182                    element: decl.clone(),
183                });
184            }
185            Some(&idx) => {
186                let prev_decl = &prev[idx];
187                let value_changed = prev_decl.value != decl.value || prev_decl.kind != decl.kind;
188                let meta_changed = prev_decl.meta != decl.meta;
189                if value_changed || meta_changed {
190                    outgoing.push(ServerMsg::Update {
191                        id: decl.id.clone(),
192                        value: decl.value.clone(),
193                        meta: if meta_changed {
194                            Some(decl.meta.clone())
195                        } else {
196                            None
197                        },
198                    });
199                }
200            }
201        }
202    }
203
204    // Detect removed elements
205    let current_ids: HashSet<&str> = current.iter().map(|d| d.id.as_str()).collect();
206    for prev_decl in prev {
207        if !current_ids.contains(prev_decl.id.as_str()) {
208            outgoing.push(ServerMsg::Remove {
209                id: prev_decl.id.clone(),
210            });
211        }
212    }
213
214    outgoing
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220    use crate::element::{ElementKind, ElementMeta, Value};
221    use std::sync::Arc;
222
223    fn make_decl(id: &str, value: Value) -> ElementDecl {
224        ElementDecl {
225            id: id.to_string(),
226            kind: ElementKind::Label,
227            label: id.to_string(),
228            value,
229            meta: ElementMeta::default(),
230            window: Arc::from("test"),
231        }
232    }
233
234    #[test]
235    fn reconcile_detects_additions() {
236        let msgs = reconcile(&[], &[make_decl("a", Value::Bool(true))]);
237        assert_eq!(msgs.len(), 1);
238        assert!(matches!(&msgs[0], ServerMsg::Add { element } if element.id == "a"));
239    }
240
241    #[test]
242    fn reconcile_detects_removals() {
243        let msgs = reconcile(&[make_decl("a", Value::Bool(true))], &[]);
244        assert_eq!(msgs.len(), 1);
245        assert!(matches!(&msgs[0], ServerMsg::Remove { id } if id == "a"));
246    }
247
248    #[test]
249    fn reconcile_detects_updates() {
250        let prev = vec![make_decl("a", Value::Bool(true))];
251        let current = vec![make_decl("a", Value::Bool(false))];
252        let msgs = reconcile(&prev, &current);
253        assert_eq!(msgs.len(), 1);
254        assert!(matches!(&msgs[0], ServerMsg::Update { id, .. } if id == "a"));
255    }
256
257    #[test]
258    fn reconcile_unchanged() {
259        let prev = vec![make_decl("a", Value::Bool(true))];
260        let current = vec![make_decl("a", Value::Bool(true))];
261        assert!(reconcile(&prev, &current).is_empty());
262    }
263
264    #[test]
265    fn reconcile_mixed() {
266        let prev = vec![
267            make_decl("keep", Value::Bool(true)),
268            make_decl("update", Value::Float(1.0)),
269            make_decl("remove", Value::Bool(false)),
270        ];
271        let current = vec![
272            make_decl("keep", Value::Bool(true)),
273            make_decl("update", Value::Float(2.0)),
274            make_decl("add", Value::Bool(true)),
275        ];
276        let msgs = reconcile(&prev, &current);
277        assert_eq!(msgs.len(), 3); // update + remove + add
278    }
279}