tauri-runtime-cef 3.0.0-alpha.1

Tauri runtime interface for Chromium Embedded 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
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
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

//! Extension traits exposing CEF-specific APIs on [`tauri`] types.
//!
//! The traits are implemented for the statically typed [`CefRuntime`](crate::CefRuntime)
//! and for the type-erased [`tauri::DynRuntime`]. With the latter, the methods fail with
//! [`tauri_runtime::Error::RuntimeTypeMismatch`] when the application is not running on CEF.

use std::sync::Arc;

use tauri::{EventLoopMessage, Manager, Runtime, Webview, WebviewWindow};
use tauri_runtime::dynamic::{DynWebviewAttributes, DynWebviewDispatcher, DynWindowOpener};

use crate::{
  CefWebviewAttributes, CefWebviewDispatcher, ChromeCommandGroup, ConsoleMessage, DevToolsProtocol,
  FrameEvent, NewWindowOpener, RuntimeStyle,
};

type Result<T> = std::result::Result<T, tauri::Error>;

fn not_cef() -> tauri::Error {
  tauri_runtime::Error::RuntimeTypeMismatch(
    "the application is not running on the CEF runtime".into(),
  )
  .into()
}

/// Webview dispatchers that may expose the underlying [`CefWebviewDispatcher`].
pub trait AsCefWebviewDispatcher {
  /// Returns the CEF webview dispatcher, if the runtime is CEF.
  fn as_cef_webview_dispatcher(&self) -> Option<&CefWebviewDispatcher<EventLoopMessage>>;
}

impl AsCefWebviewDispatcher for CefWebviewDispatcher<EventLoopMessage> {
  fn as_cef_webview_dispatcher(&self) -> Option<&CefWebviewDispatcher<EventLoopMessage>> {
    Some(self)
  }
}

impl AsCefWebviewDispatcher for DynWebviewDispatcher<EventLoopMessage> {
  fn as_cef_webview_dispatcher(&self) -> Option<&CefWebviewDispatcher<EventLoopMessage>> {
    self.downcast_ref()
  }
}

/// Window openers that may expose the CEF [`NewWindowOpener`].
///
/// Lets a new window handler read the CEF popup source regardless of the runtime generic in use:
///
/// ```rust,no_run
/// use tauri::{WebviewUrl, WebviewWindowBuilder, webview::NewWindowResponse};
/// use tauri_runtime_cef::AsCefWindowOpener;
///
/// tauri::Builder::default()
///   .runtime(tauri_runtime_cef::Cef::default())
///   .setup(|app| {
///     WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into()))
///       .on_new_window(|url, features| {
///         if let Some(opener) = features.opener().as_cef_window_opener() {
///           println!("{url} was opened by {:?}", opener.source_url());
///         }
///         NewWindowResponse::Allow
///       })
///       .build()?;
///     Ok(())
///   });
/// ```
pub trait AsCefWindowOpener {
  /// Returns the CEF window opener, `None` when the opener belongs to another runtime.
  fn as_cef_window_opener(&self) -> Option<&NewWindowOpener>;
}

impl AsCefWindowOpener for NewWindowOpener {
  fn as_cef_window_opener(&self) -> Option<&NewWindowOpener> {
    Some(self)
  }
}

impl AsCefWindowOpener for DynWindowOpener {
  fn as_cef_window_opener(&self) -> Option<&NewWindowOpener> {
    self.downcast_ref()
  }
}

/// Runtime webview attributes that may expose the [`CefWebviewAttributes`].
pub trait AsCefWebviewAttributes {
  /// Returns the CEF attributes, `None` when the attributes belong to another runtime.
  fn as_cef_webview_attributes_mut(&mut self) -> Option<&mut CefWebviewAttributes>;
}

impl AsCefWebviewAttributes for CefWebviewAttributes {
  fn as_cef_webview_attributes_mut(&mut self) -> Option<&mut CefWebviewAttributes> {
    Some(self)
  }
}

impl AsCefWebviewAttributes for DynWebviewAttributes {
  fn as_cef_webview_attributes_mut(&mut self) -> Option<&mut CefWebviewAttributes> {
    self.get_or_default()
  }
}

/// Modifies the CEF attributes of a webview builder, if the builder's attributes are not of another runtime.
fn with_cef_webview_attributes<A: AsCefWebviewAttributes>(
  attributes: &mut A,
  f: impl FnOnce(&mut CefWebviewAttributes),
) {
  match attributes.as_cef_webview_attributes_mut() {
    Some(attributes) => f(attributes),
    None => log::warn!(
      "ignoring the CEF webview attributes: attributes of another runtime were already set on the webview builder"
    ),
  }
}

/// CEF-specific APIs of [`tauri::Webview`] and [`tauri::WebviewWindow`].
pub trait WebviewCefExt {
  /// Send a message to the DevTools agent. The message should be a UTF-8 encoded JSON
  /// string following the Chrome DevTools Protocol format.
  ///
  /// Callers share one native request identifier space on this browser, so the
  /// message's `id` must come from
  /// [`allocate_devtools_message_id`](crate::allocate_devtools_message_id).
  /// A hardcoded or self-incremented `id` can collide with a request another
  /// caller already sent, which consumes that producer's
  /// [`DevToolsProtocol::MethodResult`]. The runtime's own requests are issued
  /// from a reserved range the public allocator never returns, so they cannot
  /// be consumed this way.
  ///
  /// # Examples
  ///
  /// ```rust,no_run
  /// use tauri::Manager;
  /// use tauri_runtime_cef::{WebviewCefExt, allocate_devtools_message_id};
  ///
  /// tauri::Builder::default()
  ///   .runtime(tauri_runtime_cef::Cef::default())
  ///   .setup(|app| {
  ///     let webview = app.get_webview_window("main").unwrap();
  ///     // Enable Page domain to receive page lifecycle events
  ///     let message_id = allocate_devtools_message_id()?;
  ///     let msg = format!(r#"{{"id":{message_id},"method":"Page.enable","params":{{}}}}"#);
  ///     webview.send_dev_tools_message(msg.as_bytes())?;
  ///     Ok(())
  ///   });
  /// ```
  fn send_dev_tools_message(&self, message: &[u8]) -> Result<()>;

  /// Register a callback to receive DevTools protocol messages. Messages include
  /// both method results and events from the DevTools agent.
  ///
  /// The callback observes the whole browser, including requests the runtime and
  /// other callers sent. Match [`DevToolsProtocol::MethodResult`] against an
  /// identifier obtained from
  /// [`allocate_devtools_message_id`](crate::allocate_devtools_message_id)
  /// instead of assuming every result belongs to this observer.
  ///
  /// It is scoped to this webview's own native browser, so a CEF-owned popup is
  /// a separate browser whose protocol traffic — its page content, its network
  /// activity and its dialog messages — is never reported here; observe popups
  /// through [`Webview::popups`](crate::Webview::popups).
  ///
  /// # Examples
  ///
  /// ```rust,no_run
  /// use tauri::Manager;
  /// use tauri_runtime_cef::{DevToolsProtocol, WebviewCefExt, allocate_devtools_message_id};
  ///
  /// tauri::Builder::default()
  ///   .runtime(tauri_runtime_cef::Cef::default())
  ///   .setup(|app| {
  ///     let webview = app.get_webview_window("main").unwrap();
  ///     let message_id = allocate_devtools_message_id()?;
  ///     webview.on_dev_tools_protocol(move |protocol| {
  ///       match protocol {
  ///         DevToolsProtocol::Message(msg) => {
  ///           if let Ok(s) = std::str::from_utf8(&msg) {
  ///             println!("DevTools message: {}", s);
  ///           }
  ///         }
  ///         DevToolsProtocol::Event { method, params } => {
  ///           println!("DevTools event: {} {:?}", method, params);
  ///         }
  ///         // Only this result answers the request sent below.
  ///         DevToolsProtocol::MethodResult { message_id: id, success, .. } if id == message_id => {
  ///           println!("Page.enable success={}", success);
  ///         }
  ///         DevToolsProtocol::MethodResult { .. } => {}
  ///       }
  ///     })?;
  ///     let msg = format!(r#"{{"id":{message_id},"method":"Page.enable","params":{{}}}}"#);
  ///     webview.send_dev_tools_message(msg.as_bytes())?;
  ///     Ok(())
  ///   });
  /// ```
  fn on_dev_tools_protocol<F: Fn(DevToolsProtocol) + Send + Sync + 'static>(
    &self,
    f: F,
  ) -> Result<()>;

  /// Executes a closure with the CEF platform webview handle, on the CEF UI thread.
  ///
  /// See [`crate::Webview`] for the native state it exposes, which is sampled
  /// immediately before the closure runs and is not refreshed afterwards.
  fn with_cef_webview<F: FnOnce(&crate::Webview) + Send + 'static>(&self, f: F) -> Result<()>;
}

impl<R: Runtime> WebviewCefExt for Webview<R>
where
  R::WebviewDispatcher: AsCefWebviewDispatcher,
{
  fn send_dev_tools_message(&self, message: &[u8]) -> Result<()> {
    self
      .dispatcher()
      .as_cef_webview_dispatcher()
      .ok_or_else(not_cef)?
      .send_dev_tools_message(message)
      .map_err(Into::into)
  }

  fn on_dev_tools_protocol<F: Fn(DevToolsProtocol) + Send + Sync + 'static>(
    &self,
    f: F,
  ) -> Result<()> {
    self
      .dispatcher()
      .as_cef_webview_dispatcher()
      .ok_or_else(not_cef)?
      .on_dev_tools_protocol(f)
      .map_err(Into::into)
  }

  fn with_cef_webview<F: FnOnce(&crate::Webview) + Send + 'static>(&self, f: F) -> Result<()> {
    if self.dispatcher().as_cef_webview_dispatcher().is_none() {
      return Err(not_cef());
    }
    self.with_webview(move |webview| {
      if let Some(webview) = webview.downcast_ref::<crate::Webview>() {
        f(webview)
      }
    })
  }
}

impl<R: Runtime> WebviewCefExt for WebviewWindow<R>
where
  R::WebviewDispatcher: AsCefWebviewDispatcher,
{
  fn send_dev_tools_message(&self, message: &[u8]) -> Result<()> {
    self.as_ref().send_dev_tools_message(message)
  }

  fn on_dev_tools_protocol<F: Fn(DevToolsProtocol) + Send + Sync + 'static>(
    &self,
    f: F,
  ) -> Result<()> {
    self.as_ref().on_dev_tools_protocol(f)
  }

  fn with_cef_webview<F: FnOnce(&crate::Webview) + Send + 'static>(&self, f: F) -> Result<()> {
    self.as_ref().with_cef_webview(f)
  }
}

/// CEF-specific APIs of [`tauri::WebviewWindowBuilder`].
pub trait WebviewWindowBuilderCefExt {
  /// Sets the browser runtime style.
  ///
  /// See [`RuntimeStyle`] for more information.
  #[must_use]
  fn browser_runtime_style(self, style: RuntimeStyle) -> Self;

  /// Observes native CEF lifecycle events for main and child frames.
  ///
  /// The callback runs synchronously on CEF's UI thread. It must return
  /// promptly and must not wait for an event-loop operation. This observer
  /// does not replace the navigation policy configured by `on_navigation`.
  /// It is scoped to this webview's own native browser, so a CEF-owned popup
  /// is a separate browser that is never reported here — observe popups
  /// through [`Webview::popups`](crate::Webview::popups).
  #[must_use]
  fn on_frame_event<F: Fn(FrameEvent) + Send + Sync + 'static>(self, handler: F) -> Self;

  /// Observes the messages the renderer writes to the JavaScript console,
  /// without DevTools having to be open.
  ///
  /// The callback runs synchronously on CEF's UI thread, so it must return
  /// promptly and must not wait for an event-loop operation. Observing a message
  /// does not suppress it: CEF logs it as it normally would. It is scoped to this
  /// webview's own native browser, so neither a CEF-owned popup's output nor that
  /// of a DevTools window opened on this webview is reported here.
  #[must_use]
  fn on_console_message<F: Fn(ConsoleMessage) + Send + Sync + 'static>(self, handler: F) -> Self;

  /// Keeps the named families of Chrome commands rather than swallowing them.
  ///
  /// A Chrome style browser keeps its whole accelerator table live even hosted as a
  /// child view with no browser UI, so by default this runtime swallows the commands
  /// that have no meaning in an app window — new window and tab, the tab strip,
  /// history, downloads and settings, print, save page, view source, the omnibox
  /// focus commands. Naming a [`ChromeCommandGroup`] here lets that family run the
  /// way it would in a browser. Calling this more than once replaces the previous
  /// list.
  ///
  /// DevTools and zoom accelerators are not covered here: they follow
  /// `WebviewAttributes::devtools` and `WebviewAttributes::zoom_hotkeys_enabled`.
  ///
  /// ```no_run
  /// # use tauri_runtime_cef::{AsCefWebviewAttributes, ChromeCommandGroup};
  /// # fn f<R, M>(builder: tauri::WebviewWindowBuilder<'_, R, M>)
  /// # where
  /// #   R: tauri::Runtime,
  /// #   M: tauri::Manager<R>,
  /// #   R::RuntimeWebviewAttributes: AsCefWebviewAttributes,
  /// # {
  /// use tauri_runtime_cef::WebviewWindowBuilderCefExt;
  /// // Ctrl+P prints and Alt+Left goes back, as a user expects.
  /// builder.allow_chrome_commands([ChromeCommandGroup::Document, ChromeCommandGroup::History]);
  /// # }
  /// ```
  #[must_use]
  fn allow_chrome_commands<I: IntoIterator<Item = ChromeCommandGroup>>(self, groups: I) -> Self;

  /// Takes a last look at the CEF [`BrowserSettings`](cef::BrowserSettings) before the
  /// browser is created.
  ///
  /// The runtime maps the portable `WebviewAttributes` onto these settings first, so this
  /// can change what it decided as well as reach the fields Tauri has no attribute for:
  /// the font families and sizes, `remote_fonts`, `local_storage`, `databases`, `webgl`,
  /// `tab_to_links`, `javascript_dom_paste` and `default_encoding`.
  ///
  /// ```no_run
  /// # use tauri_runtime_cef::AsCefWebviewAttributes;
  /// # fn f<R, M>(builder: tauri::WebviewWindowBuilder<'_, R, M>)
  /// # where
  /// #   R: tauri::Runtime,
  /// #   M: tauri::Manager<R>,
  /// #   R::RuntimeWebviewAttributes: AsCefWebviewAttributes,
  /// # {
  /// use tauri_runtime_cef::WebviewWindowBuilderCefExt;
  /// use tauri_runtime_cef::cef::{State, sys::cef_state_t};
  ///
  /// // An app that ships its own fonts has no use for the ones a page asks for.
  /// builder.with_browser_settings(|settings| {
  ///   settings.remote_fonts = State::from(cef_state_t::STATE_DISABLED);
  /// });
  /// # }
  /// ```
  #[must_use]
  fn with_browser_settings<F: Fn(&mut cef::BrowserSettings) + Send + Sync + 'static>(
    self,
    callback: F,
  ) -> Self;
}

impl<'a, R: Runtime, M: Manager<R>> WebviewWindowBuilderCefExt
  for tauri::WebviewWindowBuilder<'a, R, M>
where
  R::RuntimeWebviewAttributes: AsCefWebviewAttributes,
{
  fn browser_runtime_style(mut self, style: RuntimeStyle) -> Self {
    with_cef_webview_attributes(self.runtime_specific_attributes_mut(), |attributes| {
      attributes.runtime_style = Some(style);
    });
    self
  }

  fn on_frame_event<F: Fn(FrameEvent) + Send + Sync + 'static>(mut self, handler: F) -> Self {
    let handler = Arc::new(handler);
    with_cef_webview_attributes(self.runtime_specific_attributes_mut(), |attributes| {
      attributes.frame_event_handler = Some(handler);
    });
    self
  }

  fn on_console_message<F: Fn(ConsoleMessage) + Send + Sync + 'static>(
    mut self,
    handler: F,
  ) -> Self {
    let handler = Arc::new(handler);
    with_cef_webview_attributes(self.runtime_specific_attributes_mut(), |attributes| {
      attributes.console_message_handler = Some(handler);
    });
    self
  }

  fn allow_chrome_commands<I: IntoIterator<Item = ChromeCommandGroup>>(
    mut self,
    groups: I,
  ) -> Self {
    let groups = groups.into_iter().collect::<Vec<_>>();
    with_cef_webview_attributes(self.runtime_specific_attributes_mut(), |attributes| {
      attributes.allowed_chrome_commands = groups.clone();
    });
    self
  }

  fn with_browser_settings<F: Fn(&mut cef::BrowserSettings) + Send + Sync + 'static>(
    mut self,
    callback: F,
  ) -> Self {
    let callback = Arc::new(callback);
    with_cef_webview_attributes(self.runtime_specific_attributes_mut(), |attributes| {
      attributes.browser_settings_callback = Some(callback.clone());
    });
    self
  }
}

/// CEF-specific APIs of [`tauri::webview::WebviewBuilder`].
#[cfg(feature = "unstable")]
pub trait WebviewBuilderCefExt {
  /// Sets the browser runtime style.
  ///
  /// See [`RuntimeStyle`] for more information.
  #[must_use]
  fn browser_runtime_style(self, style: RuntimeStyle) -> Self;

  /// Observes native CEF lifecycle events for main and child frames.
  ///
  /// The callback runs synchronously on CEF's UI thread. It must return
  /// promptly and must not wait for an event-loop operation. This observer
  /// does not replace the navigation policy configured by `on_navigation`.
  /// It is scoped to this webview's own native browser, so a CEF-owned popup
  /// is a separate browser that is never reported here — observe popups
  /// through [`Webview::popups`](crate::Webview::popups).
  #[must_use]
  fn on_frame_event<F: Fn(FrameEvent) + Send + Sync + 'static>(self, handler: F) -> Self;

  /// Observes the messages the renderer writes to the JavaScript console,
  /// without DevTools having to be open.
  ///
  /// The callback runs synchronously on CEF's UI thread, so it must return
  /// promptly and must not wait for an event-loop operation. Observing a message
  /// does not suppress it: CEF logs it as it normally would. It is scoped to this
  /// webview's own native browser, so neither a CEF-owned popup's output nor that
  /// of a DevTools window opened on this webview is reported here.
  #[must_use]
  fn on_console_message<F: Fn(ConsoleMessage) + Send + Sync + 'static>(self, handler: F) -> Self;

  /// Keeps the named families of Chrome commands rather than swallowing them.
  ///
  /// A Chrome style browser keeps its whole accelerator table live even hosted as a
  /// child view with no browser UI, so by default this runtime swallows the commands
  /// that have no meaning in an app window — new window and tab, the tab strip,
  /// history, downloads and settings, print, save page, view source, the omnibox
  /// focus commands. Naming a [`ChromeCommandGroup`] here lets that family run the
  /// way it would in a browser. Calling this more than once replaces the previous
  /// list.
  ///
  /// DevTools and zoom accelerators are not covered here: they follow
  /// `WebviewAttributes::devtools` and `WebviewAttributes::zoom_hotkeys_enabled`.
  #[must_use]
  fn allow_chrome_commands<I: IntoIterator<Item = ChromeCommandGroup>>(self, groups: I) -> Self;

  /// Takes a last look at the CEF [`BrowserSettings`](cef::BrowserSettings) before the
  /// browser is created.
  ///
  /// The runtime maps the portable `WebviewAttributes` onto these settings first, so this
  /// can change what it decided as well as reach the fields Tauri has no attribute for:
  /// the font families and sizes, `remote_fonts`, `local_storage`, `databases`, `webgl`,
  /// `tab_to_links`, `javascript_dom_paste` and `default_encoding`.
  #[must_use]
  fn with_browser_settings<F: Fn(&mut cef::BrowserSettings) + Send + Sync + 'static>(
    self,
    callback: F,
  ) -> Self;
}

#[cfg(feature = "unstable")]
impl<R: Runtime> WebviewBuilderCefExt for tauri::webview::WebviewBuilder<R>
where
  R::RuntimeWebviewAttributes: AsCefWebviewAttributes,
{
  fn browser_runtime_style(mut self, style: RuntimeStyle) -> Self {
    with_cef_webview_attributes(self.runtime_specific_attributes_mut(), |attributes| {
      attributes.runtime_style = Some(style);
    });
    self
  }

  fn on_frame_event<F: Fn(FrameEvent) + Send + Sync + 'static>(mut self, handler: F) -> Self {
    let handler = Arc::new(handler);
    with_cef_webview_attributes(self.runtime_specific_attributes_mut(), |attributes| {
      attributes.frame_event_handler = Some(handler);
    });
    self
  }

  fn on_console_message<F: Fn(ConsoleMessage) + Send + Sync + 'static>(
    mut self,
    handler: F,
  ) -> Self {
    let handler = Arc::new(handler);
    with_cef_webview_attributes(self.runtime_specific_attributes_mut(), |attributes| {
      attributes.console_message_handler = Some(handler);
    });
    self
  }

  fn allow_chrome_commands<I: IntoIterator<Item = ChromeCommandGroup>>(
    mut self,
    groups: I,
  ) -> Self {
    let groups = groups.into_iter().collect::<Vec<_>>();
    with_cef_webview_attributes(self.runtime_specific_attributes_mut(), |attributes| {
      attributes.allowed_chrome_commands = groups.clone();
    });
    self
  }

  fn with_browser_settings<F: Fn(&mut cef::BrowserSettings) + Send + Sync + 'static>(
    mut self,
    callback: F,
  ) -> Self {
    let callback = Arc::new(callback);
    with_cef_webview_attributes(self.runtime_specific_attributes_mut(), |attributes| {
      attributes.browser_settings_callback = Some(callback.clone());
    });
    self
  }
}