tauri-runtime-cef 3.0.0-alpha.0

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
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use std::{
  borrow::Cow,
  io::{Cursor, Read},
  sync::{Arc, Mutex},
};

use cef::{rc::*, *};
use dioxus_debug_cell::RefCell;
use html5ever::{LocalName, interface::QualName, namespace_url, ns};
use http::{
  HeaderMap, HeaderName, HeaderValue,
  header::{CONTENT_SECURITY_POLICY, CONTENT_TYPE, ORIGIN},
};
use kuchiki::{Attribute, ExpandedName, NodeRef};
use tauri_runtime::{
  UserEvent,
  webview::{NavigationHandler, UriSchemeProtocolHandler},
  window::WindowId,
};
use tauri_utils::{
  config::{Csp, CspDirectiveSources},
  html::{parse as parse_html, serialize_node},
};
use url::Url;

use crate::{
  cef_impl::client::{
    DragDropEventTarget, DragDropState, WebDragDropResourceRequestHandler,
    WebDragDropResourceRequestHandlerArgs,
  },
  macros::wrap_with_args,
  runtime::RuntimeContext,
  webview::{CefInitScript, INITIAL_LOAD_URL},
};

type HttpResponse = Arc<RefCell<Option<http::Response<Cursor<Vec<u8>>>>>>;
pub(crate) type SchemeRegistry = Arc<
  Mutex<
    std::collections::HashMap<
      (i32, String),
      (
        String,
        Arc<Box<UriSchemeProtocolHandler>>,
        Arc<Vec<CefInitScript>>,
      ),
    >,
  >,
>;

fn csp_inject_initialization_scripts_hashes(
  existing_csp: String,
  initialization_scripts: &[CefInitScript],
  is_main_frame: bool,
) -> String {
  if initialization_scripts.is_empty() {
    return existing_csp;
  }

  let script_hashes: Vec<String> = initialization_scripts
    .iter()
    .filter(|script| script.runs_in_frame(is_main_frame))
    .map(|s| s.hash.clone())
    .collect();

  if script_hashes.is_empty() {
    return existing_csp;
  }

  let mut csp_map: std::collections::HashMap<String, CspDirectiveSources> =
    Csp::Policy(existing_csp.to_string()).into();

  let script_src = csp_map
    .entry("script-src".to_string())
    .or_insert_with(|| CspDirectiveSources::List(vec!["'self'".to_string()]));

  script_src.extend(script_hashes);

  Csp::DirectiveMap(csp_map).to_string()
}

fn inject_scripts_into_html_body(
  body: &[u8],
  initialization_scripts: &[CefInitScript],
  is_main_frame: bool,
) -> Option<Vec<u8>> {
  let Ok(body_str) = std::str::from_utf8(body) else {
    return None;
  };

  let document = parse_html(body_str.to_string());

  let head = if let Ok(ref head_node) = document.select_first("head") {
    head_node.as_node().clone()
  } else {
    let head_node = NodeRef::new_element(
      QualName::new(None, ns!(html), LocalName::from("head")),
      None,
    );
    document.prepend(head_node.clone());
    head_node
  };

  for init_script in initialization_scripts
    .iter()
    .rev()
    .filter(|script| script.runs_in_frame(is_main_frame))
  {
    let script_el = NodeRef::new_element(QualName::new(None, ns!(html), "script".into()), None);
    script_el.append(NodeRef::new_text(init_script.script.as_str()));
    head.prepend(script_el);
  }

  keep_encoding_declaration_first(&document, &head);

  Some(serialize_node(&document))
}

/// Keeps the document's character encoding declaration ahead of the injected scripts.
///
/// Chromium only pre-scans the first 1024 bytes of a document for a `<meta charset>`
/// declaration. The initialization scripts we prepend to `<head>` are much larger than
/// that, so an encoding declaration that used to be in the pre-scan window ends up out
/// of reach and the document is decoded with the fallback encoding (windows-1252)
/// instead. That mojibakes every non-ASCII byte in the page and in the injected scripts,
/// which additionally breaks the CSP hashes we compute over the UTF-8 source, so the
/// browser refuses to execute the affected script.
fn keep_encoding_declaration_first(document: &NodeRef, head: &NodeRef) {
  let existing_declaration = document.select("meta").ok().and_then(|metas| {
    metas.into_iter().find(|meta| {
      let attributes = meta.attributes.borrow();
      attributes.get("charset").is_some()
        || attributes
          .get("http-equiv")
          .map(|value| value.trim().eq_ignore_ascii_case("content-type"))
          .unwrap_or(false)
    })
  });

  match existing_declaration {
    // the document declares its encoding, move that declaration back into the pre-scan window
    Some(declaration) => {
      let node = declaration.as_node().clone();
      node.detach();
      head.prepend(node);
    }
    // no declaration at all: the assets are served as UTF-8 (this handler parses them as
    // such), so make that explicit instead of leaving it to the fallback encoding
    None => head.prepend(NodeRef::new_element(
      QualName::new(None, ns!(html), LocalName::from("meta")),
      [(
        ExpandedName::new(ns!(), LocalName::from("charset")),
        Attribute {
          prefix: None,
          value: "utf-8".into(),
        },
      )],
    )),
  }
}

wrap_with_args! {
  wrap_request_handler => WebRequestHandlerArgs;

  pub struct WebRequestHandler<T: UserEvent> {
    navigation_handler: Option<Arc<NavigationHandler>>,
    frame_event_handler: Option<Arc<crate::FrameEventHandler>>,
    context: RuntimeContext<T>,
    window_id: WindowId,
    webview_id: u32,
    drag_drop_event_target: DragDropEventTarget,
    drag_drop_handler_enabled: bool,
    drag_drop_state: Arc<Mutex<DragDropState>>,
    web_content_process_terminate_handler: Option<Arc<tauri_runtime::webview::OnWebContentProcessTerminateHandler>>,
    certificate_errors: crate::CertificateErrorPolicy,
  }

  impl RequestHandler {
    /// Answers a TLS certificate that does not validate, per
    /// [`CertificateErrorPolicy`](crate::CertificateErrorPolicy).
    ///
    /// Returning 0 hands the error back to Chromium, which shows the SSL interstitial
    /// with its "proceed anyway" link. Cancelling instead means dropping the callback
    /// without continuing it: CEF reads a `false` return as "cancel this request", and
    /// the page gets a network error it cannot click past.
    fn on_certificate_error(
      &self,
      _browser: Option<&mut Browser>,
      cert_error: Errorcode,
      request_url: Option<&CefString>,
      _ssl_info: Option<&mut Sslinfo>,
      _callback: Option<&mut Callback>,
    ) -> ::std::os::raw::c_int {
      match self.certificate_errors {
        crate::CertificateErrorPolicy::ChromeInterstitial => 0,
        crate::CertificateErrorPolicy::Cancel => {
          // The URL can carry credentials and tokens, so only its origin is logged.
          let origin = request_url
            .map(ToString::to_string)
            .and_then(|url| url::Url::parse(&url).ok())
            .map(|url| url.origin().ascii_serialization())
            .unwrap_or_else(|| "an unknown origin".to_string());
          log::warn!(
            "cancelling a request to {origin}: its TLS certificate did not validate \
             (Chromium error {cert_error:?}), and the runtime is set to \
             CertificateErrorPolicy::Cancel"
          );
          1
        }
      }
    }
    fn on_render_process_terminated(
      &self,
      browser: Option<&mut Browser>,
      status: TerminationStatus,
      error_code: ::std::os::raw::c_int,
      error_string: Option<&CefString>,
    ) {
      let mut frame = browser.as_ref().and_then(|browser| browser.main_frame());
      crate::frame::emit_frame_event(&self.frame_event_handler, browser, frame.as_mut(), crate::FrameEventKind::RendererTerminated);
      if let Some(handler) = &self.web_content_process_terminate_handler {
        handler(tauri_runtime::webview::WebContentProcessTermination {
          reason: termination_reason(status),
          error_code: Some(error_code),
          error_string: error_string.map(ToString::to_string),
        });
      }
    }

    fn on_before_browse(
      &self,
      browser: Option<&mut Browser>,
      frame: Option<&mut Frame>,
      request: Option<&mut Request>,
      _user_gesture: ::std::os::raw::c_int,
      _is_redirect: ::std::os::raw::c_int,
    ) -> ::std::os::raw::c_int {
      let _ = (&self.context, self.window_id, self.webview_id);

      let Some(frame) = frame else {
        return 0;
      };
      let Some(request) = request else {
        return 0;
      };

      let url_str = CefString::from(&request.url()).to_string();

      if url_str == INITIAL_LOAD_URL {
        return 0;
      }

      let Ok(url) = url::Url::parse(&url_str) else {
        return 0;
      };

      // Preserve the portable main-frame policy. Native observers receive only
      // admitted navigations, so a denied navigation cannot strand their barrier.
      if frame.is_main() != 0
        && self.navigation_handler.as_ref().is_some_and(|handler| !handler(&url))
      {
        return 1;
      }
      crate::frame::emit_frame_event(
        &self.frame_event_handler,
        browser,
        Some(frame),
        crate::FrameEventKind::NavigationStarted { url },
      );
      0
    }

    fn resource_request_handler(
      &self,
      _browser: Option<&mut Browser>,
      _frame: Option<&mut Frame>,
      _request: Option<&mut Request>,
      _is_navigation: ::std::os::raw::c_int,
      _is_download: ::std::os::raw::c_int,
      _request_initiator: Option<&CefString>,
      _disable_default_handling: Option<&mut ::std::os::raw::c_int>,
    ) -> Option<ResourceRequestHandler> {
      // The handler only intercepts the drag-drop bridge requests; when the
      // bridge is disabled it would pass every request straight through, so skip
      // building (and cloning the context + state into) a handler that CEF calls
      // for every subresource/fetch/XHR the page makes.
      if !self.drag_drop_handler_enabled {
        return None;
      }

      Some(WebDragDropResourceRequestHandler::build(
        WebDragDropResourceRequestHandlerArgs {
          context: self.context.clone(),
          window_id: self.window_id,
          webview_id: self.webview_id,
          drag_drop_event_target: self.drag_drop_event_target,
          drag_drop_handler_enabled: self.drag_drop_handler_enabled,
          drag_drop_state: self.drag_drop_state.clone(),
        },
      ))
    }
  }
}

wrap_with_args! {
  wrap_resource_handler => WebResourceHandlerArgs;

  pub struct WebResourceHandler {
    webview_label: String,
    handler: Arc<Box<UriSchemeProtocolHandler>>,
    initialization_scripts: Arc<Vec<CefInitScript>>,
    // Whether the document this response is loaded into is the main frame. Scripts flagged
    // `for_main_frame_only` are skipped for subframes - the isolation iframe most notably -
    // matching both the wry runtime and the guard in the document-start script we register
    // over CDP for documents that are not served by a custom protocol.
    is_main_frame: bool,
    // Serialized origin of the main frame that initiated this request, captured
    // browser-side in the scheme handler factory. The renderer can issue an IPC
    // request before its execution context is fully wired to the loader; in
    // that window Chromium tags the request with `Origin: null` even though the
    // document already has a proper origin. We use this to repair the `Origin`
    // header in that case. `None` when the initiator is not the (non-opaque)
    // main frame, so sandboxed/subframe `Origin: null` requests are left as-is.
    initiator_origin: Option<String>,
    // we clone response to send it to the handler thread
    response: HttpResponse,
  }

  impl ResourceHandler {
    fn process_request(
      &self,
      request: Option<&mut Request>,
      callback: Option<&mut Callback>,
    ) -> ::std::os::raw::c_int {
      let Some(request) = request else { return 0 };
      let Some(callback) = callback else { return 0 };

      let url = CefString::from(&request.url()).to_string();
      let url = Url::parse(&url).ok();

      if let Some(url) = url {
        let callback = ThreadSafe(callback.clone());
        let response_store = ThreadSafe(self.response.clone());
        let initialization_scripts = self.initialization_scripts.clone();
        let is_main_frame = self.is_main_frame;
        let responder = Box::new(move |response: http::Response<Cow<'static, [u8]>>| {
          let is_html = response
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|ct| ct.to_str().ok())
            .map(|ct| ct.to_lowercase().starts_with("text/html"))
            .unwrap_or(false);

          let (parts, body) = response.into_parts();
          let body_bytes = body.into_owned();
          let body_bytes = if is_html {
            inject_scripts_into_html_body(&body_bytes, &initialization_scripts, is_main_frame)
              .unwrap_or(body_bytes)
          } else {
            body_bytes
          };

          let mut response = http::Response::from_parts(parts, Cursor::new(body_bytes));

          if let Some(csp) = response.headers_mut().get_mut(CONTENT_SECURITY_POLICY) {
            let csp_string = csp.to_str().unwrap_or_default().to_string();
            let new_csp = csp_inject_initialization_scripts_hashes(
              csp_string,
              &initialization_scripts,
              is_main_frame,
            );
            if let Ok(new_csp) = HeaderValue::from_str(&new_csp) {
              *csp = new_csp;
            }
          }

          response_store.into_owned().borrow_mut().replace(response);

          let callback = callback.into_owned();
          callback.cont();
        });

        let label = self.webview_label.clone();
        let handler = self.handler.clone();

        let data = read_request_body(request);
        let mut headers = get_request_headers(request);

        // The renderer can issue an IPC request before its execution context is
        // fully wired to the loader; in that window Chromium sends the request
        // with `Origin: null` even though the document already has a real
        // origin. Repair it from the initiating main frame's URL, which the
        // browser process tracks reliably. Only done when the renderer sent no
        // origin or a literal `null`, so a correct renderer-sent origin always
        // wins.
        if let Some(initiator_origin) = &self.initiator_origin {
          let origin_missing_or_null = headers
            .get(ORIGIN)
            .map(|value| value.as_bytes() == b"null")
            .unwrap_or(true);
          if origin_missing_or_null && let Ok(value) = HeaderValue::from_str(initiator_origin) {
            headers.insert(ORIGIN, value);
          }
        }

        let method_str = CefString::from(&request.method()).to_string();
        let method = http::Method::from_bytes(method_str.as_bytes()).unwrap_or(http::Method::GET);

        std::thread::spawn(move || {
          let mut http_request = http::Request::builder()
            .method(method)
            .uri(url.as_str())
            .body(data)
            .unwrap();
          *http_request.headers_mut() = headers;
          // handler is Arc<Box<UriSchemeProtocol>>, so we need to dereference to call it
          (**handler)(&label, http_request, responder);
        });
        1
      } else {
        0
      }
    }

    fn read(
      &self,
      data_out: *mut u8,
      bytes_to_read: ::std::os::raw::c_int,
      bytes_read: Option<&mut ::std::os::raw::c_int>,
      _callback: Option<&mut ResourceReadCallback>,
    ) -> ::std::os::raw::c_int {
      let Ok(bytes_to_read) = usize::try_from(bytes_to_read) else {
        return 0;
      };
      let data_out = unsafe { std::slice::from_raw_parts_mut(data_out, bytes_to_read) };
      let count = self
        .response
        .borrow_mut()
        .as_mut()
        .and_then(|response| response.body_mut().read(data_out).ok())
        .unwrap_or(0);
      if let Some(bytes_read) = bytes_read {
        let Ok(count) = count.try_into() else {
          return 0;
        };
        *bytes_read = count;
        if count > 0 {
          return 1;
        }
      }
      0
    }

    fn response_headers(
      &self,
      response: Option<&mut Response>,
      response_length: Option<&mut i64>,
      redirect_url: Option<&mut CefString>,
    ) {
      let (Some(response), Some(response_data)) = (response, &*self.response.borrow()) else {
        return;
      };

      response.set_status(response_data.status().as_u16() as i32);
      let mut content_type = None;

      // Set response headers and remember the MIME type for CEF.
      for (name, value) in response_data.headers() {
        let Ok(value) = value.to_str() else {
          continue;
        };

        response.set_header_by_name(Some(&name.as_str().into()), Some(&value.into()), 0);

        if name == CONTENT_TYPE {
          content_type.replace(value.to_string());
        }
      }

      response.set_header_by_name(Some(&"Cache-Control".into()), Some(&"no-store".into()), 1);

      let mime_type = content_type
        .as_ref()
        .and_then(|t| t.split(';').next())
        .map(str::trim)
        .unwrap_or("text/plain");
      response.set_mime_type(Some(&mime_type.into()));

      if let Some(length) = response_length {
        *length = -1;
      }

      if let Some(redirect_url) = redirect_url {
        let _ = std::mem::take(redirect_url);
      }
    }
  }
}

wrap_scheme_handler_factory! {
  pub struct UriSchemeHandlerFactory {
    registry: SchemeRegistry,
    scheme: String,
  }

  impl SchemeHandlerFactory {
    fn create(
      &self,
      browser: Option<&mut Browser>,
      frame: Option<&mut Frame>,
      _scheme_name: Option<&CefString>,
      _request: Option<&mut Request>,
    ) -> Option<ResourceHandler> {
      let (webview_label, handler, initialization_scripts) = match browser {
        Some(browser) => {
          let id = browser.identifier();

          // get handler from our regsitry based on browser ID and scheme
          self
            .registry
            .lock()
            .unwrap()
            .get(&(id, self.scheme.clone()))
            .cloned()?
        }
        // `browser`/`frame` are null for requests that do not originate from a
        // browser: service worker (main script and update) fetches and
        // CefURLRequest. Returning `None` here would fall through to the
        // network service, where `{scheme}.localhost` resolves to loopback and
        // the connection is refused — which is exactly how service worker
        // registration on a custom-protocol origin used to fail with "An
        // unknown error occurred when fetching the script.".
        //
        // Every registry entry for a given scheme wraps the same app-level
        // `UriSchemeProtocolHandler`, so any live entry can serve the request;
        // only the webview label differs, and asset serving does not depend on
        // it. Initialization scripts are per-document injections, meaningless
        // without a browser, so they are not applied on this path.
        None => {
          let (webview_label, handler, _) = self
            .registry
            .lock()
            .unwrap()
            .iter()
            .find(|((_, scheme), _)| *scheme == self.scheme)
            .map(|(_, entry)| entry.clone())?;
          (webview_label, handler, Arc::new(Vec::new()))
        }
      };

      // A subframe navigation is the only case we can positively identify here, so anything
      // else (a null frame included) keeps the main frame behavior of injecting everything.
      let is_main_frame = frame.as_ref().map(|frame| frame.is_main() == 1).unwrap_or(true);

      // Capture the initiating main frame's origin so `process_request` can
      // repair a racy `Origin: null` header. Restricted to the main frame: it
      // is never an opaque-origin (sandboxed) document in a Tauri webview, so
      // upgrading its origin is safe; subframes are intentionally left alone.
      let initiator_origin = frame
        .filter(|frame| frame.is_main() == 1)
        .map(|frame| CefString::from(&frame.url()).to_string())
        .and_then(|url| Url::parse(&url).ok())
        .map(|url| url.origin().ascii_serialization())
        .filter(|origin| origin != "null");

      Some(WebResourceHandler::build(WebResourceHandlerArgs {
        webview_label,
        handler,
        initialization_scripts,
        is_main_frame,
        initiator_origin,
        response: Arc::new(RefCell::new(None)),
      }))
    }
  }
}

struct ThreadSafe<T>(T);

impl<T> ThreadSafe<T> {
  fn into_owned(self) -> T {
    self.0
  }
}

unsafe impl<T> Send for ThreadSafe<T> {}
unsafe impl<T> Sync for ThreadSafe<T> {}

fn read_request_body(request: &mut Request) -> Vec<u8> {
  let mut body = Vec::new();

  if let Some(post_data) = request.post_data() {
    let mut elements = vec![None; post_data.element_count()];
    post_data.elements(Some(&mut elements));
    for element in elements.into_iter().flatten() {
      match element.get_type().as_ref() {
        sys::cef_postdataelement_type_t::PDE_TYPE_BYTES => {
          let size = element.bytes_count();
          if size > 0 {
            let mut buf = vec![0u8; size];
            // Copy bytes into our buffer
            let copied = element.bytes(size, buf.as_mut_ptr());
            // Safety: CEF promises it wrote `copied` bytes into buf
            unsafe {
              buf.set_len(copied);
            }
            body.extend(buf);
          }
        }
        sys::cef_postdataelement_type_t::PDE_TYPE_FILE => {
          // Read file from disk
          let file_path = CefString::from(&element.file()).to_string();
          if let Ok(mut file) = std::fs::File::open(&file_path) {
            use std::io::Read;
            let mut buf = Vec::new();
            if file.read_to_end(&mut buf).is_ok() {
              body.extend(buf);
            }
          }
        }
        _ => {}
      }
    }
  }

  body
}

fn get_request_headers(request: &mut Request) -> HeaderMap {
  let mut headers = HeaderMap::new();

  let mut map = CefStringMultimap::new();

  request.header_map(Some(&mut map));

  // Iterate through all entries
  for (name, value) in map {
    for v in value {
      headers.append(
        HeaderName::from_bytes(name.as_bytes()).unwrap(),
        HeaderValue::from_str(&v).unwrap(),
      );
    }
  }

  headers
}

// ==== Renderer termination boundary ====

fn termination_reason(
  status: TerminationStatus,
) -> tauri_runtime::webview::WebContentProcessTerminationReason {
  use tauri_runtime::webview::WebContentProcessTerminationReason as Reason;
  match status {
    TerminationStatus::ABNORMAL_TERMINATION => Reason::Abnormal,
    TerminationStatus::PROCESS_WAS_KILLED => Reason::Killed,
    TerminationStatus::PROCESS_CRASHED => Reason::Crashed,
    TerminationStatus::PROCESS_OOM => Reason::OutOfMemory,
    TerminationStatus::LAUNCH_FAILED => Reason::LaunchFailed,
    TerminationStatus::INTEGRITY_FAILURE => Reason::IntegrityFailure,
    _ => Reason::Unknown,
  }
}

#[cfg(test)]
mod termination_tests {
  use super::*;
  use tauri_runtime::webview::WebContentProcessTerminationReason as Reason;

  #[test]
  fn preserves_every_cef_termination_reason() {
    for (status, expected) in [
      (TerminationStatus::ABNORMAL_TERMINATION, Reason::Abnormal),
      (TerminationStatus::PROCESS_WAS_KILLED, Reason::Killed),
      (TerminationStatus::PROCESS_CRASHED, Reason::Crashed),
      (TerminationStatus::PROCESS_OOM, Reason::OutOfMemory),
      (TerminationStatus::LAUNCH_FAILED, Reason::LaunchFailed),
      (
        TerminationStatus::INTEGRITY_FAILURE,
        Reason::IntegrityFailure,
      ),
      (TerminationStatus::NUM_VALUES, Reason::Unknown),
    ] {
      assert_eq!(termination_reason(status), expected);
    }
  }
}