ribir_core 0.4.0-alpha.63

A non-intrusive declarative GUI framework, to build modern native/wasm cross-platform applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Universal Debug Bridge Client.
//!
//! Connects to the Bridge Server (CLI) via WebSocket:
//! - **Native**: Uses tokio-tungstenite WebSocket client (auto-connects to
//!   RIBIR_DEBUG_URL)
//! - **WASM**: Uses web_sys::WebSocket (via ribir_debug_server query param)
//!
//! Architecture: Both Native and WASM apps act as clients connecting to CLI
//! server. This eliminates duplicate HTTP server code and simplifies
//! maintenance.
//!
//! ## Usage
//!
//! **Native**: Auto-connects to `http://127.0.0.1:2333` by default (converted to ws://)
//! ```bash
//! cargo run --features debug
//! ```
//!
//! **WASM**: Pass `ribir_debug_server` query parameter (HTTP URL,
//! auto-converted to WebSocket) ```
//! http://localhost:8080/?ribir_debug_server=http://127.0.0.1:2333
//! ```

use std::sync::Arc;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::debug_tool::{
  runtime::{
    CaptureOneShotRequest, CaptureStartRequest, CaptureStopRequest, DebugServerState,
    build_status_response, capture_one_shot_bundle_inner, capture_start_inner,
    capture_stop_bundle_inner, start_debug_runtime,
  },
  service::*,
  types::DebugCommand,
};

/// Request from Bridge Server to client.
#[derive(Deserialize)]
pub struct BridgeRequest {
  pub request_id: u64,
  pub path: String,
  pub method: String,
  pub body: Option<Value>,
}

/// Response from client to Bridge Server.
#[derive(Serialize)]
pub struct BridgeResponse {
  pub request_id: u64,
  pub status: u16,
  pub body: Value,
}

/// Hello message from client to Bridge Server.
#[derive(Serialize)]
pub struct BridgeHello {
  /// Client type: "native" or "wasm"
  pub client_type: String,
  /// Optional metadata (PID for native, page URL for WASM)
  pub metadata: Option<String>,
}

/// Start the debug bridge client.
///
/// Works for both Native and WASM targets. Connects to CLI bridge server
/// and handles debug requests over WebSocket.
pub fn start_debug_client() -> tokio::sync::mpsc::Sender<DebugCommand> {
  let state = start_debug_runtime();
  let bridge_url = get_bridge_url();

  if let Some(url) = bridge_url {
    connect_bridge(url, state.clone());
  } else {
    tracing::warn!("Debug bridge URL not specified. Using default: ws://127.0.0.1:2333/ws");
  }

  state.command_tx.clone()
}

/// Get bridge URL from environment (native) or query params (WASM).
/// Converts HTTP URL to WebSocket URL.
#[cfg(not(target_arch = "wasm32"))]
fn get_bridge_url() -> Option<String> {
  let http_url = std::env::var("RIBIR_DEBUG_URL")
    .ok()
    .unwrap_or_else(|| "http://127.0.0.1:2333".to_string());

  // Convert http:// to ws:// and add /ws path
  let ws_url = if let Some(host) = http_url.strip_prefix("https://") {
    format!("wss://{}/ws", host)
  } else if let Some(host) = http_url.strip_prefix("http://") {
    format!("ws://{}/ws", host)
  } else if http_url.starts_with("ws://") || http_url.starts_with("wss://") {
    http_url
  } else {
    format!("ws://{}/ws", http_url)
  };

  Some(ws_url)
}

#[cfg(target_arch = "wasm32")]
fn get_bridge_url() -> Option<String> { bridge_url_from_query() }

/// Connect to bridge server (Native implementation).
#[cfg(not(target_arch = "wasm32"))]
fn connect_bridge(url: String, state: Arc<DebugServerState>) {
  use futures::{SinkExt, StreamExt};
  use tokio::sync::mpsc;
  use tokio_tungstenite::{connect_async, tungstenite::Message};

  tokio::spawn(async move {
    let (ws_stream, response) = match connect_async(&url).await {
      Ok(conn) => conn,
      Err(e) => {
        tracing::warn!("Failed to connect to debug bridge: {}", e);
        return;
      }
    };

    tracing::info!("Connected to debug bridge (HTTP {})", response.status());

    let (mut write, mut read) = ws_stream.split();

    // Send hello
    let hello = BridgeHello {
      client_type: "native".to_string(),
      metadata: Some(std::process::id().to_string()),
    };

    if let Err(e) = write
      .send(Message::Text(serde_json::to_string(&hello).unwrap()))
      .await
    {
      tracing::warn!("Failed to send bridge hello: {}", e);
      return;
    }

    // Create channel for sending responses
    let (tx, mut rx) = mpsc::unbounded_channel::<String>();

    // Writer task: send responses back to bridge
    let writer_task = tokio::spawn(async move {
      while let Some(text) = rx.recv().await {
        if let Err(e) = write.send(Message::Text(text)).await {
          tracing::warn!("Failed to send bridge response: {}", e);
          break;
        }
      }
    });

    // Handle messages
    while let Some(msg) = read.next().await {
      match msg {
        Ok(Message::Text(text)) => {
          let state = state.clone();
          let tx = tx.clone();

          tokio::spawn(async move {
            if let Ok(request) = serde_json::from_str::<BridgeRequest>(&text) {
              let response = handle_request(request, &state).await;
              if let Ok(text) = serde_json::to_string(&response) {
                let _ = tx.send(text);
              }
            }
          });
        }
        Ok(Message::Close(_)) | Err(_) => break,
        _ => {}
      }
    }

    writer_task.abort();
    tracing::info!("Debug bridge connection lost");
  });
}

/// Connect to bridge server (WASM implementation).
#[cfg(target_arch = "wasm32")]
fn connect_bridge(url: String, state: Arc<DebugServerState>) {
  use web_sys::wasm_bindgen::{JsCast, closure::Closure};

  let Ok(ws) = web_sys::WebSocket::new(&url) else {
    tracing::warn!("Failed to create WebSocket for debug bridge");
    return;
  };

  // On open: send hello and start stats forwarding
  let ws_open = ws.clone();
  let state_open = state.clone();
  let onopen = Closure::<dyn FnMut(web_sys::Event)>::new(move |_| {
    let ws_for_send = ws_open.clone();
    let hello = BridgeHello { client_type: "wasm".to_string(), metadata: current_page_url() };
    let _ = ws_for_send.send_with_str(&serde_json::to_string(&hello).unwrap());
    start_stats_forwarding(state_open.clone());
  });
  ws.set_onopen(Some(onopen.as_ref().unchecked_ref()));
  onopen.forget();

  // On message: handle request
  let ws_msg = ws.clone();
  let state_msg = state.clone();
  let onmessage =
    Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |ev: web_sys::MessageEvent| {
      let Some(text) = ev.data().as_string() else { return };
      let ws = ws_msg.clone();
      let state = state_msg.clone();
      wasm_bindgen_futures::spawn_local(async move {
        if let Ok(req) = serde_json::from_str::<BridgeRequest>(&text) {
          let resp = handle_request(req, &state).await;
          let _ = ws.send_with_str(&serde_json::to_string(&resp).unwrap());
        }
      });
    });
  ws.set_onmessage(Some(onmessage.as_ref().unchecked_ref()));
  onmessage.forget();

  // On error/close
  ws.set_onerror(Some(
    Closure::<dyn FnMut(web_sys::Event)>::new(move |_| {
      tracing::warn!("Debug bridge WebSocket error");
    })
    .as_ref()
    .unchecked_ref(),
  ));
  ws.set_onclose(Some(
    Closure::<dyn FnMut(web_sys::Event)>::new(move |_| {
      tracing::warn!("Debug bridge WebSocket closed");
    })
    .as_ref()
    .unchecked_ref(),
  ));
}

/// Handle a bridge request.
async fn handle_request(request: BridgeRequest, state: &Arc<DebugServerState>) -> BridgeResponse {
  let BridgeRequest { request_id, path, method, body } = request;
  let path = path.trim_start_matches('/');

  let (status, body) = match (method.as_str(), path) {
    ("GET", "status") => (200, serde_json::to_value(build_status_response(state).await).unwrap()),
    ("GET", "windows") => match get_windows_svc(state).await {
      Ok(w) => (200, serde_json::to_value(w).unwrap()),
      Err(_) => (500, json_error("Failed to get windows")),
    },
    ("GET", p) if p.starts_with("inspect/tree") => {
      let opts = parse_query_options(path);
      match inspect_tree_svc(state, None, opts).await {
        Ok(t) => (200, t),
        Err(_) => (500, json_error("Failed to inspect tree")),
      }
    }
    ("GET", p) if p.starts_with("inspect/") => {
      let id = p
        .strip_prefix("inspect/")
        .unwrap()
        .split('?')
        .next()
        .unwrap();
      let opts = parse_query_options(path);
      match inspect_widget_svc(state, None, id.into(), opts).await {
        Ok(i) => (200, i),
        Err(ServiceError::NotFound) => (404, json_error("Widget not found")),
        Err(_) => (500, json_error("Failed to inspect widget")),
      }
    }
    ("GET", "screenshot") => match capture_screenshot_svc(state).await {
      Ok(img) => {
        let mut data = Vec::new();
        if img.write_as_webp(&mut data).is_ok() {
          use base64::{Engine as _, engine::general_purpose};
          (
            200,
            serde_json::json!({ "content_type": "image/png", "data": general_purpose::STANDARD.encode(&data) }),
          )
        } else {
          (500, json_error("Failed to encode image"))
        }
      }
      Err(_) => (500, json_error("Failed to capture screenshot")),
    },
    ("POST", "overlay") => {
      let b = body.unwrap_or_default();
      let id = b.get("id").and_then(|v| v.as_str()).unwrap_or("");
      let color = b
        .get("color")
        .and_then(|v| v.as_str())
        .unwrap_or("#FF000080");
      match add_overlay_svc(state, None, id.into(), color.into()).await {
        Ok(()) => (200, serde_json::json!({ "ok": true })),
        Err(_) => (500, json_error("Failed to add overlay")),
      }
    }
    ("DELETE", p) if p.starts_with("overlay/") => {
      let id = p.strip_prefix("overlay/").unwrap();
      match remove_overlay_svc(state, None, id.into()).await {
        Ok(()) => (200, serde_json::json!({ "ok": true })),
        Err(_) => (500, json_error("Failed to remove overlay")),
      }
    }
    ("DELETE", "overlays") => {
      let _ = clear_overlays_svc(state, None).await;
      (200, serde_json::json!({ "ok": true }))
    }
    ("GET", "overlays") => {
      use crate::debug_tool::service::get_windows_svc;
      let overlays = match get_windows_svc(state).await {
        Ok(windows) if !windows.is_empty() => {
          let window_id = windows[0].id;
          get_overlays_svc(window_id)
        }
        _ => Vec::new(),
      };
      let result: Vec<_> = overlays
        .into_iter()
        .map(|(id, color)| serde_json::json!([id, color]))
        .collect();
      (200, serde_json::to_value(result).unwrap())
    }
    ("POST", "events/inject") => {
      let b = body.unwrap_or_default();
      match serde_json::from_value::<crate::debug_tool::types::InjectEventsRequest>(b) {
        Ok(req) => match inject_events_svc(state, None, req.events).await {
          Ok(r) => (200, serde_json::to_value(r).unwrap()),
          Err(e) => (400, json_error(&e.to_string())),
        },
        Err(e) => (400, json_error(&e.to_string())),
      }
    }
    ("POST", "events/macro/start") => {
      let b = body.unwrap_or_default();
      match serde_json::from_value::<crate::debug_tool::types::StartEventMacroRecordingRequest>(b) {
        Ok(req) => {
          let (tx, rx) = tokio::sync::oneshot::channel();
          if state
            .command_tx
            .send(crate::debug_tool::types::DebugCommand::StartEventMacroRecording {
              window_id: req.window_id,
              duration_ms: req.duration_ms,
              reply: tx,
            })
            .await
            .is_ok()
          {
            match rx.await {
              Ok(Ok(r)) => (200, serde_json::to_value(r).unwrap()),
              Ok(Err(e)) => (400, json_error(&e)),
              Err(_) => (500, json_error("Internal error")),
            }
          } else {
            (500, json_error("Internal error"))
          }
        }
        Err(e) => (400, json_error(&e.to_string())),
      }
    }
    ("POST", "events/macro/stop") => {
      let b = body.unwrap_or_default();
      match serde_json::from_value::<crate::debug_tool::types::StopEventMacroRecordingRequest>(b) {
        Ok(req) => {
          let (tx, rx) = tokio::sync::oneshot::channel();
          if state
            .command_tx
            .send(crate::debug_tool::types::DebugCommand::StopEventMacroRecording {
              recording_id: req.recording_id,
              reply: tx,
            })
            .await
            .is_ok()
          {
            match rx.await {
              Ok(Ok(r)) => (200, serde_json::to_value(r).unwrap()),
              Ok(Err(e)) => (400, json_error(&e)),
              Err(_) => (500, json_error("Internal error")),
            }
          } else {
            (500, json_error("Internal error"))
          }
        }
        Err(e) => (400, json_error(&e.to_string())),
      }
    }
    ("POST", "capture/start") => {
      let b = body.unwrap_or_default();
      match serde_json::from_value::<CaptureStartRequest>(b) {
        Ok(req) => match capture_start_inner(
          state.clone(),
          req.include,
          req.pre_ms.unwrap_or(2_000),
          req.post_ms.unwrap_or(1_000),
          None,
        )
        .await
        {
          Ok(r) => (200, serde_json::to_value(r).unwrap()),
          Err(e) => capture_error(e),
        },
        Err(e) => (400, json_error(&e.to_string())),
      }
    }
    ("POST", "capture/stop") => {
      let b = body.unwrap_or_default();
      match serde_json::from_value::<CaptureStopRequest>(b) {
        Ok(req) => match capture_stop_bundle_inner(state.clone(), req).await {
          Ok(r) => (200, serde_json::to_value(r).unwrap()),
          Err(e) => capture_error(e),
        },
        Err(e) => (400, json_error(&e.to_string())),
      }
    }
    ("POST", "capture/one_shot") => {
      let b = body.unwrap_or_default();
      match serde_json::from_value::<CaptureOneShotRequest>(b) {
        Ok(req) => match capture_one_shot_bundle_inner(state.clone(), req).await {
          Ok(r) => (200, serde_json::to_value(r).unwrap()),
          Err(e) => capture_error(e),
        },
        Err(e) => (400, json_error(&e.to_string())),
      }
    }
    ("GET", p) if p == "logs" || p.starts_with("logs?") => {
      let (since, until, limit, from_seq) = parse_logs_query(path);
      let (lines, max_ts, ring_len, max_seq) = {
        let ring = state.log_ring.lock().await;
        if let Some(seq) = from_seq {
          // Use seq-based query for precise streaming
          let seq_lines = ring.query_lines_from_seq(seq, limit);
          let lines: Vec<Arc<str>> = seq_lines
            .iter()
            .map(|(_, line)| line.clone())
            .collect();
          let max_seq = seq_lines.iter().map(|(seq, _)| *seq).max();
          (lines, ring.max_ts(), ring.len(), max_seq)
        } else {
          (ring.query_lines(since, until, limit), ring.max_ts(), ring.len(), ring.max_seq())
        }
      };
      let mut out = String::new();
      for line in lines {
        out.push_str(line.as_ref());
        out.push('\n');
      }
      let mut resp = serde_json::json!({
        "content_type": "application/x-ndjson",
        "data": out,
        "dropped_total": crate::logging::dropped_logs_total(),
        "ring_len": ring_len,
      });
      if let Some(ts) = max_ts {
        resp["max_ts"] = serde_json::json!(ts);
      }
      if let Some(seq) = max_seq {
        resp["max_seq"] = serde_json::json!(seq);
      }
      (200, resp)
    }
    ("POST", "logs/filter") => {
      let filter = body
        .and_then(|b| {
          b.get("filter")
            .and_then(|v| v.as_str().map(String::from))
        })
        .unwrap_or_default();
      match crate::logging::update_filter(&filter) {
        Ok(()) => (200, serde_json::json!({ "ok": true })),
        Err(e) => (400, json_error(&e)),
      }
    }
    _ => (404, json_error(&format!("Unknown endpoint: {} {}", method, path))),
  };

  BridgeResponse { request_id, status, body }
}

fn json_error(msg: &str) -> Value { serde_json::json!({ "error": msg }) }

fn capture_error(err: crate::debug_tool::runtime::CaptureError) -> (u16, Value) {
  match err {
    crate::debug_tool::runtime::CaptureError::Conflict => {
      (409, json_error("Capture already in progress"))
    }
    crate::debug_tool::runtime::CaptureError::Timeout => (408, json_error("Capture timeout")),
    crate::debug_tool::runtime::CaptureError::NotFound => {
      (404, json_error("No active capture found"))
    }
    crate::debug_tool::runtime::CaptureError::Internal => (500, json_error("Failed to capture")),
  }
}

fn parse_query_options(path: &str) -> crate::debug_tool::types::InspectOptions {
  let mut opts = crate::debug_tool::types::InspectOptions::default();
  if let Some(query) = path.split('?').nth(1) {
    for pair in query.split('&') {
      if let Some((key, value)) = pair.split_once('=')
        && key == "options"
      {
        opts = crate::debug_tool::helpers::parse_inspect_options(Some(value));
      }
    }
  }
  opts
}

fn parse_logs_query(path: &str) -> (Option<u64>, Option<u64>, Option<usize>, Option<u64>) {
  let (mut since, mut until, mut limit, mut from_seq) = (None, None, None, None);
  if let Some(query) = path.split('?').nth(1) {
    for pair in query.split('&') {
      if let Some((k, v)) = pair.split_once('=') {
        match k {
          "since_ts" => since = v.parse().ok(),
          "until_ts" => until = v.parse().ok(),
          "limit" => limit = v.parse().ok(),
          "from_seq" => from_seq = v.parse().ok(),
          _ => {}
        }
      }
    }
  }
  (since, until, limit, from_seq)
}

#[cfg(target_arch = "wasm32")]
fn start_stats_forwarding(state: Arc<DebugServerState>) {
  use web_sys::wasm_bindgen::{JsCast, closure::Closure};
  let window = web_sys::window().unwrap();
  let cb = Closure::<dyn FnMut()>::new(move || {
    let state = state.clone();
    wasm_bindgen_futures::spawn_local(async move {
      let ring_len = state.log_ring.lock().await.len();
      tracing::debug!("WASM debug stats: ring_len={}", ring_len);
    });
  });
  let _ = window.set_interval_with_callback_and_timeout_and_arguments(
    cb.as_ref().unchecked_ref(),
    2000,
    &js_sys::Array::new(),
  );
  cb.forget();
}

#[cfg(target_arch = "wasm32")]
fn bridge_url_from_query() -> Option<String> {
  let window = web_sys::window()?;
  let location = window.location();
  let search = location.search().ok()?;
  let query = search.strip_prefix('?').unwrap_or(&search);
  let http_url = url::form_urlencoded::parse(query.as_bytes())
    .find(|(k, _)| k == "ribir_debug_server")
    .map(|(_, v)| v.into_owned())
    .filter(|v| !v.trim().is_empty())?;

  // Convert HTTP URL to WebSocket URL
  Some(if http_url.starts_with("https://") {
    format!("wss://{}/ws", &http_url["https://".len()..])
  } else if http_url.starts_with("http://") {
    format!("ws://{}/ws", &http_url["http://".len()..])
  } else if http_url.starts_with("ws://") || http_url.starts_with("wss://") {
    http_url
  } else {
    format!("ws://{}/ws", http_url)
  })
}

#[cfg(target_arch = "wasm32")]
fn current_page_url() -> Option<String> { web_sys::window().and_then(|w| w.location().href().ok()) }