bunlet-cef-native 0.1.0

Native CEF (Chromium Embedded Framework) bindings using NAPI-RS — full Chromium 146+ backend for the Bunlet desktop framework
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
//! CEF (Chromium Embedded Framework) backend for Bunlet
//!
//! This module provides a full Chromium-based webview as an alternative
//! to the system webview backend. It offers full web compatibility
//! including DevTools, executeJavaScript, proper navigation, and
//! multi-process architecture.

#![deny(clippy::all)]

mod app_handler;
mod browser;
mod ipc;
mod state;

use napi::bindgen_prelude::*;
use napi::threadsafe_function::{ErrorStrategy, ThreadsafeFunction};
use napi_derive::napi;

pub use app_handler::*;
pub use browser::*;
pub use state::*;

// ============================================================================
// Application lifecycle
// ============================================================================

#[napi]
pub fn init_app() -> Result<()> {
    Ok(())
}

#[napi]
pub fn quit_app() {
    let state = CEF_STATE.lock();
    if state.initialized {
        drop(state);
        cef::quit_message_loop();
    } else {
        std::process::exit(0);
    }
}

#[napi]
pub fn get_path(name: String) -> Option<String> {
    use dirs_next as dirs;

    match name.as_str() {
        "home" => dirs::home_dir().map(|p| p.to_string_lossy().to_string()),
        "appData" | "config" => dirs::config_dir().map(|p| p.to_string_lossy().to_string()),
        "temp" => Some(std::env::temp_dir().to_string_lossy().to_string()),
        "desktop" => dirs::desktop_dir().map(|p| p.to_string_lossy().to_string()),
        "documents" => dirs::document_dir().map(|p| p.to_string_lossy().to_string()),
        "downloads" => dirs::download_dir().map(|p| p.to_string_lossy().to_string()),
        "music" => dirs::audio_dir().map(|p| p.to_string_lossy().to_string()),
        "pictures" => dirs::picture_dir().map(|p| p.to_string_lossy().to_string()),
        "videos" => dirs::video_dir().map(|p| p.to_string_lossy().to_string()),
        "cache" => dirs::cache_dir().map(|p| p.to_string_lossy().to_string()),
        "data" => dirs::data_dir().map(|p| p.to_string_lossy().to_string()),
        "dataLocal" => dirs::data_local_dir().map(|p| p.to_string_lossy().to_string()),
        "exe" => std::env::current_exe()
            .ok()
            .map(|p| p.to_string_lossy().to_string()),
        "runtime" => dirs::runtime_dir().map(|p| p.to_string_lossy().to_string()),
        _ => None,
    }
}

// ============================================================================
// Window management
// ============================================================================

#[napi(object)]
#[derive(Default, Clone)]
pub struct WindowOptions {
    pub width: Option<u32>,
    pub height: Option<u32>,
    pub title: Option<String>,
    pub resizable: Option<bool>,
    pub decorations: Option<bool>,
    pub transparent: Option<bool>,
    pub visible: Option<bool>,
    pub always_on_top: Option<bool>,
    pub x: Option<i32>,
    pub y: Option<i32>,
    pub min_width: Option<u32>,
    pub min_height: Option<u32>,
    pub max_width: Option<u32>,
    pub max_height: Option<u32>,
    pub preload_script: Option<String>,
    pub open_devtools: Option<bool>,
    pub parent_id: Option<u32>,
    pub modal: Option<bool>,
}

#[napi(object)]
pub struct WindowBounds {
    pub x: i32,
    pub y: i32,
    pub width: u32,
    pub height: u32,
}

#[napi(object)]
pub struct IpcMessage {
    pub window_id: u32,
    pub message: String,
}

#[napi(object)]
pub struct AppEvent {
    pub event: String,
    pub window_id: Option<u32>,
    pub title: Option<String>,
    pub url: Option<String>,
    pub bounds: Option<WindowBounds>,
}

#[napi]
pub fn create_window(options: Option<WindowOptions>) -> u32 {
    let opts = options.unwrap_or_default();
    let id = state::next_window_id();
    PENDING_WINDOWS.lock().push(state::PendingWindow {
        id,
        options: opts,
        url: None,
        html: None,
    });
    id
}

#[napi]
pub fn load_url(window_id: u32, url: String) -> Result<()> {
    let state = CEF_STATE.lock();
    if let Some(browser_id) = state.window_to_browser.get(&window_id) {
        let browser_id = *browser_id;
        drop(state);
        browser::cef_load_url(browser_id, &url)
    } else {
        drop(state);
        let mut pending = PENDING_WINDOWS.lock();
        for pw in pending.iter_mut() {
            if pw.id == window_id {
                pw.url = Some(url);
                pw.html = None;
                return Ok(());
            }
        }
        Err(Error::new(
            Status::InvalidArg,
            format!("Window {} not found", window_id),
        ))
    }
}

#[napi]
pub fn load_file(window_id: u32, file_path: String) -> Result<()> {
    let absolute = std::path::PathBuf::from(&file_path);
    let resolved = if absolute.is_absolute() {
        absolute
    } else {
        std::env::current_dir()
            .map_err(|e| Error::new(Status::GenericFailure, e.to_string()))?
            .join(absolute)
    };
    let url = format!("file://{}", resolved.to_string_lossy());
    load_url(window_id, url)
}

#[napi]
pub fn load_html(window_id: u32, html: String) -> Result<()> {
    let state = CEF_STATE.lock();
    if let Some(_browser_id) = state.window_to_browser.get(&window_id) {
        drop(state);
        let encoded = urlencoding::encode(&html);
        let url = format!("data:text/html,{}", encoded);
        load_url(window_id, url)
    } else {
        drop(state);
        let mut pending = PENDING_WINDOWS.lock();
        for pw in pending.iter_mut() {
            if pw.id == window_id {
                pw.url = None;
                pw.html = Some(html);
                return Ok(());
            }
        }
        Err(Error::new(
            Status::InvalidArg,
            format!("Window {} not found", window_id),
        ))
    }
}

#[napi]
pub fn show_window(window_id: u32) -> Result<()> {
    browser::cef_show_window(window_id)
}

#[napi]
pub fn hide_window(window_id: u32) -> Result<()> {
    browser::cef_hide_window(window_id)
}

#[napi]
pub fn close_window(window_id: u32) -> Result<()> {
    browser::cef_close_window(window_id)
}

#[napi]
pub fn focus_window(window_id: u32) -> Result<()> {
    browser::cef_focus_window(window_id)
}

#[napi]
pub fn maximize_window(window_id: u32) -> Result<()> {
    browser::cef_maximize_window(window_id)
}

#[napi]
pub fn minimize_window(window_id: u32) -> Result<()> {
    browser::cef_minimize_window(window_id)
}

#[napi]
pub fn restore_window(window_id: u32) -> Result<()> {
    browser::cef_restore_window(window_id)
}

#[napi]
pub fn set_fullscreen(window_id: u32, fullscreen: bool) -> Result<()> {
    browser::cef_set_fullscreen(window_id, fullscreen)
}

#[napi]
pub fn get_window_bounds(window_id: u32) -> Result<WindowBounds> {
    browser::cef_get_window_bounds(window_id)
}

#[napi]
pub fn set_window_bounds(
    window_id: u32,
    x: Option<i32>,
    y: Option<i32>,
    width: Option<u32>,
    height: Option<u32>,
) -> Result<()> {
    browser::cef_set_window_bounds(window_id, x, y, width, height)
}

#[napi]
pub fn set_window_title(window_id: u32, title: String) -> Result<()> {
    browser::cef_set_window_title(window_id, &title)
}

#[napi]
pub fn set_window_always_on_top(window_id: u32, always_on_top: bool) -> Result<()> {
    browser::cef_set_always_on_top(window_id, always_on_top)
}

#[napi]
pub fn is_window_visible(window_id: u32) -> Result<bool> {
    browser::cef_is_window_visible(window_id)
}

#[napi]
pub fn is_window_focused(window_id: u32) -> Result<bool> {
    browser::cef_is_window_focused(window_id)
}

#[napi]
pub fn is_window_maximized(window_id: u32) -> Result<bool> {
    browser::cef_is_window_maximized(window_id)
}

#[napi]
pub fn is_window_minimized(window_id: u32) -> Result<bool> {
    browser::cef_is_window_minimized(window_id)
}

#[napi]
pub fn is_window_fullscreen(window_id: u32) -> Result<bool> {
    browser::cef_is_window_fullscreen(window_id)
}

#[napi]
pub fn get_focused_window_id() -> Option<u32> {
    browser::cef_get_focused_window_id()
}

#[napi]
pub fn get_all_window_ids() -> Vec<u32> {
    CEF_STATE.lock().window_to_browser.keys().cloned().collect()
}

// ============================================================================
// WebView / Navigation
// ============================================================================

#[napi]
pub async fn execute_java_script(window_id: u32, script: String) -> Result<String> {
    browser::cef_execute_java_script(window_id, &script)
}

#[napi]
pub fn webview_reload(window_id: u32) -> Result<()> {
    browser::cef_webview_reload(window_id)
}

#[napi]
pub fn webview_stop(window_id: u32) -> Result<()> {
    browser::cef_webview_stop(window_id)
}

#[napi]
pub fn webview_go_back(window_id: u32) -> Result<()> {
    browser::cef_webview_go_back(window_id)
}

#[napi]
pub fn webview_go_forward(window_id: u32) -> Result<()> {
    browser::cef_webview_go_forward(window_id)
}

// ============================================================================
// DevTools
// ============================================================================

#[napi]
pub fn open_devtools(window_id: u32) -> Result<()> {
    browser::cef_open_devtools(window_id)
}

#[napi]
pub fn close_devtools(window_id: u32) -> Result<()> {
    browser::cef_close_devtools(window_id)
}

#[napi]
pub fn toggle_devtools(window_id: u32) -> Result<()> {
    browser::cef_toggle_devtools(window_id)
}

#[napi]
pub fn is_devtools_open(window_id: u32) -> Result<bool> {
    browser::cef_is_devtools_open(window_id)
}

// ============================================================================
// IPC
// ============================================================================

#[napi]
pub fn set_ipc_handler(callback: ThreadsafeFunction<IpcMessage, ErrorStrategy::Fatal>) {
    *IPC_CALLBACK.lock() = Some(callback);
}

#[napi]
pub fn set_app_event_handler(callback: ThreadsafeFunction<AppEvent, ErrorStrategy::Fatal>) {
    *APP_EVENT_CALLBACK.lock() = Some(callback);
}

#[napi]
pub fn send_ipc_message(window_id: u32, message: String) -> Result<()> {
    browser::cef_send_ipc_message(window_id, &message)
}

#[napi]
pub fn poll_ipc_messages() -> Vec<IpcMessage> {
    PENDING_IPC.lock().drain(..).collect()
}

// ============================================================================
// Event loop integration
// ============================================================================

#[napi]
pub fn init_event_loop() -> Result<()> {
    state::ensure_cef_initialized()?;
    Ok(())
}

#[napi]
pub fn pump_events() -> Result<PumpResult> {
    let messages: Vec<IpcMessage> = PENDING_IPC.lock().drain(..).collect();

    let state = CEF_STATE.lock();
    if state.initialized {
        drop(state);
        cef::do_message_loop_work();
    }

    #[cfg(target_os = "linux")]
    {
        while gtk::events_pending() {
            gtk::main_iteration();
        }
    }

    let should_quit = CEF_STATE.lock().window_to_browser.is_empty();

    Ok(PumpResult {
        should_quit,
        messages,
    })
}

#[napi]
pub fn run_event_loop() -> Result<()> {
    state::ensure_cef_initialized()?;
    state::process_pending_windows();

    let state = CEF_STATE.lock();
    if state.window_to_browser.is_empty() {
        state::dispatch_app_event("window-all-closed");
        return Ok(());
    }
    drop(state);

    cef::run_message_loop();

    Ok(())
}

#[napi(object)]
pub struct PumpResult {
    pub should_quit: bool,
    pub messages: Vec<IpcMessage>,
}

// ============================================================================
// Session / Cookies
// ============================================================================

#[napi(object)]
pub struct NativeCookie {
    pub name: String,
    pub value: String,
    pub domain: Option<String>,
    pub path: Option<String>,
    pub secure: Option<bool>,
    pub http_only: Option<bool>,
    pub same_site: Option<String>,
    pub expiration_date: Option<f64>,
}

#[napi(object)]
pub struct SetCookieParams {
    pub name: String,
    pub value: String,
    pub domain: Option<String>,
    pub path: Option<String>,
    pub secure: Option<bool>,
    pub http_only: Option<bool>,
    pub same_site: Option<String>,
    pub expiration_date: Option<f64>,
}

#[napi(object)]
pub struct ClearStorageOptions {
    pub cookies: Option<bool>,
    pub local_storage: Option<bool>,
    pub session_storage: Option<bool>,
    pub indexed_db: Option<bool>,
    pub cache_storage: Option<bool>,
}

#[napi]
pub async fn get_cookies(window_id: u32) -> Result<Vec<NativeCookie>> {
    browser::cef_get_cookies(window_id)
}

#[napi]
pub fn set_cookie(window_id: u32, cookie: SetCookieParams) -> Result<()> {
    browser::cef_set_cookie(window_id, &cookie)
}

#[napi]
pub fn remove_cookie(window_id: u32, name: String, url: String) -> Result<()> {
    browser::cef_remove_cookie(window_id, &name, &url)
}

#[napi]
pub fn clear_storage_data(window_id: u32, options: Option<ClearStorageOptions>) -> Result<()> {
    browser::cef_clear_storage_data(window_id, options.as_ref())
}

#[napi]
pub async fn get_user_agent(window_id: u32) -> Result<String> {
    browser::cef_get_user_agent(window_id)
}