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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
use crate::browser_process::BrpHandler;
use crate::browser_process::ClientHandlerBuilder;
use crate::browser_process::client_handler::{IpcEventRaw, JsEmitEventHandler};
use crate::prelude::IntoString;
use crate::prelude::*;
use async_channel::Sender;
use bevy::platform::collections::HashMap;
use bevy::prelude::*;
use bevy_remote::BrpMessage;
use cef::{
Browser, BrowserHost, BrowserSettings, CefString, Client, CompositionUnderline,
DictionaryValue, ImplBrowser, ImplBrowserHost, ImplDictionaryValue, ImplFrame, ImplListValue,
ImplProcessMessage, ImplRequestContext, MouseButtonType, ProcessId, Range, RequestContext,
RequestContextSettings, WindowInfo, browser_host_create_browser_sync, dictionary_value_create,
process_message_create,
};
use cef_dll_sys::{cef_event_flags_t, cef_mouse_button_type_t};
#[allow(deprecated)]
use raw_window_handle::RawWindowHandle;
use std::cell::Cell;
use std::rc::Rc;
mod devtool_render_handler;
mod keyboard;
use crate::browser_process::browsers::devtool_render_handler::DevToolRenderHandlerBuilder;
use crate::browser_process::cookie_flush::{CookieFlusher, ProfileFlusher};
use crate::browser_process::display_handler::{
AddressChangedSenderInner, DisplayHandlerBuilder, SystemCursorIconSenderInner,
TitleChangedSenderInner,
};
use crate::browser_process::drag_handler::{DragHandlerBuilder, DraggableRegionSenderInner};
use crate::browser_process::initial_zoom::{InitialZoom, SharedInitialZoom, ZoomRequest};
use crate::browser_process::load_handler::{LoadHandlerBuilder, LoadHandlerSenderInner};
use crate::browser_process::profiles::ProfileContext;
use crate::error::{CefCoreResult, CreateBrowserError, ProfileContextError};
pub use keyboard::*;
/// Whether bevy_cef drives CEF compositing with `SendExternalBeginFrame`.
///
/// `false` on Windows: CEF composites on its own at `windowless_frame_rate`. With
/// externally driven begin frames, opening DevTools on Windows permanently stops the
/// inspected webview's rAF and painting (observed with a CEF 152.0.6 runtime; not
/// re-checked against other CEF versions). This one flag decides both
/// `WindowInfo::external_begin_frame_enabled` and whether the `send_external_begin_frame`
/// system is scheduled, so the two can never disagree.
pub const EXTERNAL_BEGIN_FRAME: bool = !cfg!(target_os = "windows");
pub struct WebviewBrowser {
pub client: Browser,
pub host: BrowserHost,
pub size: SharedViewSize,
pub dpr: SharedDpr,
pub initial_zoom: SharedInitialZoom,
#[cfg(not(target_os = "macos"))]
pub view_slot: SharedTexture,
#[cfg(not(target_os = "macos"))]
pub popup_slot: SharedTexture,
/// [macOS GPU OSR] Latest IOSurface retained by `on_accelerated_paint`
/// (Approach 2). Drained by the main-world collect system for extraction
/// into the render world, where the `webview_blit` render-graph-schedule
/// system imports + blits it.
#[cfg(target_os = "macos")]
pub latest_iosurface: crate::browser_process::accelerated_paint::SharedRetainedIoSurface,
}
/// Editor commands dispatched to a webview's focused frame.
///
/// On macOS the windowless (OSR) browser has no real `NSView`, so the AppKit
/// key-binding → editor-command translation never runs and shortcuts like ⌘C
/// never reach Blink's editor. The embedder detects those shortcuts and
/// dispatches the matching command via [`Browsers::exec_edit_command`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EditCommand {
Copy,
Cut,
Paste,
SelectAll,
Undo,
Redo,
}
#[derive(Default)]
pub struct Browsers {
browsers: HashMap<Entity, WebviewBrowser>,
live_browsers: SharedLiveBrowsers,
/// One shared request context per profile, keyed by the profile's cache path.
profiles: HashMap<String, ProfileContext>,
}
impl Browsers {
/// Creates a browser for `webview` and stores it in the entity map.
///
/// With `profile: None` the browser gets its own fresh in-memory request context. With
/// `Some(cache_path)` it uses the profile context [`Self::prepare_profile`] registered for
/// that cache path, which should be ready (see [`Self::is_profile_ready`]).
///
/// # Errors
///
/// Fails with [`CreateBrowserError::UnknownProfile`] when no context is registered for
/// `profile`, and with [`CreateBrowserError::NullBrowser`] when CEF creates no browser.
#[allow(clippy::too_many_arguments)]
pub fn create_browser(
&mut self,
webview: Entity,
uri: &str,
webview_size: Vec2,
initial_dpr: f32,
requester: Requester,
ipc_event_sender: Sender<IpcEventRaw>,
brp_sender: Sender<BrpMessage>,
system_cursor_icon_sender: SystemCursorIconSenderInner,
drag_regions_sender: DraggableRegionSenderInner,
load_handler_sender: LoadHandlerSenderInner,
address_changed_sender: AddressChangedSenderInner,
title_changed_sender: TitleChangedSenderInner,
initialize_scripts: &[String],
_window_handle: Option<RawWindowHandle>,
initial_zoom: f64,
profile: Option<&str>,
) -> CefCoreResult {
let (mut context, cookie_flusher) = match profile {
Some(cache_path) => {
let profile = self
.profiles
.get(cache_path)
.ok_or(CreateBrowserError::UnknownProfile)?;
(
Some(profile.context.clone()),
Some(profile.flusher.handle()),
)
}
None => (Self::request_context(requester), None),
};
let size: SharedViewSize = Rc::new(Cell::new(webview_size));
let dpr: SharedDpr = Rc::new(Cell::new(initial_dpr));
let initial_zoom: SharedInitialZoom =
Rc::new(Cell::new(InitialZoom::waiting(initial_zoom)));
#[cfg(not(target_os = "macos"))]
let view_slot: SharedTexture = Rc::new(Cell::new(None));
#[cfg(not(target_os = "macos"))]
let popup_slot: SharedTexture = Rc::new(Cell::new(None));
#[cfg(target_os = "macos")]
let latest_iosurface: crate::browser_process::accelerated_paint::SharedRetainedIoSurface =
Rc::new(std::cell::RefCell::new(None));
let browser = browser_host_create_browser_sync(
Some(&WindowInfo {
windowless_rendering_enabled: true as _,
external_begin_frame_enabled: EXTERNAL_BEGIN_FRAME as _,
// macOS GPU OSR: ask CEF to deliver GPU shared textures (IOSurface)
// via on_accelerated_paint instead of CPU buffers via on_paint.
#[cfg(target_os = "macos")]
shared_texture_enabled: true as _,
#[cfg(target_os = "macos")]
parent_view: match _window_handle {
Some(RawWindowHandle::AppKit(handle)) => handle.ns_view.as_ptr(),
_ => std::ptr::null_mut(),
},
// Windowless rendering does not require a parent window handle on Linux.
#[cfg(target_os = "linux")]
parent_window: 0,
// NOTE: Windows keeps the default null `parent_window`. With a real HWND, CEF
// turns on its default OSR context menu and native JS dialogs, which bevy_cef
// neither positions (`GetScreenPoint` is not implemented) nor suppresses.
..Default::default()
}),
Some(&mut self.client_handler(
webview,
size.clone(),
#[cfg(not(target_os = "macos"))]
view_slot.clone(),
#[cfg(not(target_os = "macos"))]
popup_slot.clone(),
dpr.clone(),
ipc_event_sender,
brp_sender,
system_cursor_icon_sender,
drag_regions_sender,
load_handler_sender,
address_changed_sender,
#[cfg(target_os = "macos")]
latest_iosurface.clone(),
title_changed_sender,
initial_zoom.clone(),
cookie_flusher,
)),
Some(&uri.into()),
Some(&BrowserSettings {
windowless_frame_rate: 60,
..Default::default()
}),
Self::create_extra_info(initialize_scripts).as_mut(),
context.as_mut(),
)
.ok_or(CreateBrowserError::NullBrowser)?;
let host = browser.host().ok_or(CreateBrowserError::NullBrowser)?;
let webview_browser = WebviewBrowser {
host,
client: browser,
size,
dpr,
initial_zoom,
#[cfg(not(target_os = "macos"))]
view_slot,
#[cfg(not(target_os = "macos"))]
popup_slot,
#[cfg(target_os = "macos")]
latest_iosurface,
};
self.browsers.insert(webview, webview_browser);
Ok(())
}
/// Gets or creates the shared request context for the profile stored at `cache_path`.
///
/// A new context is created with `persist_session_cookies` on, gets the `cef://localhost`
/// and custom scheme factories, and is registered under `cache_path` until
/// [`Self::release_all`]. `cache_path` must be an absolute direct child of the root cache
/// path. Browsers can be created on the context once [`Self::is_profile_ready`] returns
/// `true`.
///
/// # Errors
///
/// Fails with [`ProfileContextError::CreationFailed`] when CEF creates no context, and with
/// [`ProfileContextError::DidNotLoad`] when CEF replaced `cache_path` with in-memory
/// storage. Neither registers a context.
pub fn prepare_profile(&mut self, cache_path: &str, requester: Requester) -> CefCoreResult {
if self.profiles.contains_key(cache_path) {
return Ok(());
}
let ready = Rc::new(Cell::new(false));
let mut context = cef::request_context_create_context(
Some(&RequestContextSettings {
cache_path: cache_path.into(),
persist_session_cookies: 1,
..Default::default()
}),
Some(&mut RequestContextHandlerBuilder::build_with_ready(
ready.clone(),
)),
)
.ok_or(ProfileContextError::CreationFailed)?;
if context.cache_path().into_string().is_empty() {
return Err(ProfileContextError::DidNotLoad.into());
}
Self::register_scheme_factories(&mut context, requester);
self.profiles.insert(
cache_path.to_owned(),
ProfileContext {
flusher: ProfileFlusher::new(context.clone()),
context,
ready,
},
);
Ok(())
}
/// Requests a cookie-store flush on every profile context.
///
/// A context with a flush in flight queues one follow-up instead of starting another.
pub fn flush_profile_cookies(&self) {
for profile in self.profiles.values() {
profile.flusher.request();
}
}
/// Whether a profile context is registered for `cache_path`, initialized or not.
pub fn has_profile(&self, cache_path: &str) -> bool {
self.profiles.contains_key(cache_path)
}
/// Whether the profile context registered for `cache_path` has finished initializing.
///
/// Returns `false` when no context is registered for `cache_path`.
pub fn is_profile_ready(&self, cache_path: &str) -> bool {
self.profiles
.get(cache_path)
.is_some_and(ProfileContext::is_ready)
}
pub fn send_external_begin_frame(&self) {
for browser in self.browsers.values() {
browser.host.send_external_begin_frame();
}
}
/// [macOS GPU OSR] Drains the latest retained IOSurface for every webview
/// that has received a new accelerated-paint frame since the last call
/// (Approach 2).
///
/// Returns `(entity, RetainedIoSurface)` pairs, **transferring ownership** of
/// the retain (the +1 IOSurface use-count) to the caller. This is essential
/// under pipelined rendering: the render world consumes the surface one frame
/// behind the main world, so the retain must travel with the data — reading a
/// raw pointer that `on_accelerated_paint` may release on the next main-world
/// frame would dereference a freed IOSurface (segfault in Metal's
/// `newTextureWithDescriptor:iosurface:`).
///
/// A webview that fails the `keep` predicate (e.g. its surface
/// `Handle<Image>` is not allocated yet) is NOT drained: the retain stays in
/// its latest-frame slot so the frame can be collected once the consumer is
/// ready. This matters for static pages — under external begin-frames CEF
/// never repaints undamaged content, so dropping the only delivered frame
/// would leave the webview on its black placeholder forever. The slot is
/// latest-wins, so a deferred frame is bounded to one retained surface per
/// webview.
///
/// A webview with no new frame this call yields nothing; its owned GPU
/// texture already holds the last good contents, so sampling stays correct.
#[cfg(target_os = "macos")]
pub fn take_latest_webview_iosurfaces(
&self,
keep: impl Fn(Entity) -> bool,
) -> Vec<(
Entity,
crate::browser_process::accelerated_paint::RetainedIoSurface,
)> {
self.browsers
.iter()
.filter_map(|(entity, b)| {
if !keep(*entity) {
return None;
}
b.latest_iosurface
.borrow_mut()
.take()
.map(|retained| (*entity, retained))
})
.collect()
}
pub fn send_mouse_move<'a>(
&self,
webview: &Entity,
buttons: impl IntoIterator<Item = &'a MouseButton>,
position: Vec2,
mouse_leave: bool,
) {
if let Some(browser) = self.get_focused_browser(webview) {
let mouse_event = cef::MouseEvent {
x: position.x as i32,
y: position.y as i32,
modifiers: modifiers_from_mouse_buttons(buttons),
};
browser
.host
.send_mouse_move_event(Some(&mouse_event), mouse_leave as _);
}
}
/// Tells CEF the pointer left the webview, clearing its hover state.
///
/// Used when an embedder-side interaction (drag, resize) takes over the pointer.
pub fn send_mouse_leave(&self, webview: &Entity, position: Vec2) {
self.send_mouse_move(webview, std::iter::empty::<&MouseButton>(), position, true);
}
pub fn send_mouse_click(
&self,
webview: &Entity,
position: Vec2,
button: PointerButton,
mouse_up: bool,
) {
if let Some(browser) = self.get_focused_browser(webview) {
let mouse_event = cef::MouseEvent {
x: position.x as i32,
y: position.y as i32,
modifiers: match button {
PointerButton::Primary => cef_event_flags_t::EVENTFLAG_LEFT_MOUSE_BUTTON.0,
PointerButton::Secondary => cef_event_flags_t::EVENTFLAG_RIGHT_MOUSE_BUTTON.0,
PointerButton::Middle => cef_event_flags_t::EVENTFLAG_MIDDLE_MOUSE_BUTTON.0,
} as _, // No modifiers for simplicity
};
let mouse_button = match button {
PointerButton::Secondary => cef_mouse_button_type_t::MBT_RIGHT,
PointerButton::Middle => cef_mouse_button_type_t::MBT_MIDDLE,
_ => cef_mouse_button_type_t::MBT_LEFT,
};
browser.host.set_focus(true as _);
browser.host.send_mouse_click_event(
Some(&mouse_event),
MouseButtonType::from(mouse_button),
mouse_up as _,
1,
);
}
}
/// [`SendMouseWheelEvent`](https://cef-builds.spotifycdn.com/docs/106.1/classCefBrowserHost.html#acd5d057bd5230baa9a94b7853ba755f7)
pub fn send_mouse_wheel(&self, webview: &Entity, position: Vec2, delta: Vec2) {
if let Some(browser) = self.get_focused_browser(webview) {
let mouse_event = cef::MouseEvent {
x: position.x as i32,
y: position.y as i32,
modifiers: 0,
};
browser
.host
.send_mouse_wheel_event(Some(&mouse_event), delta.x as _, delta.y as _);
}
}
#[inline]
pub fn send_key(&self, webview: &Entity, event: cef::KeyEvent) {
if let Some(browser) = self.get_focused_browser(webview) {
browser.host.send_key_event(Some(&event));
}
}
/// Dispatches an editor command to the webview's focused frame.
///
/// No-op when the webview has no browser or no focused frame. Used on macOS
/// to make clipboard/editing shortcuts work under windowless rendering,
/// where CEF does not translate key events into editor commands itself.
#[inline]
pub fn exec_edit_command(&self, webview: &Entity, cmd: EditCommand) {
if let Some(browser) = self.browsers.get(webview)
&& let Some(frame) = browser.client.focused_frame()
{
match cmd {
EditCommand::Copy => frame.copy(),
EditCommand::Cut => frame.cut(),
EditCommand::Paste => frame.paste(),
EditCommand::SelectAll => frame.select_all(),
EditCommand::Undo => frame.undo(),
EditCommand::Redo => frame.redo(),
}
}
}
/// Sets the CEF input focus state for a webview's browser.
///
/// Uses a direct lookup (not `get_focused_browser`) because this is what
/// *grants* focus; gating on existing focus would make focusing impossible.
pub fn set_focus(&self, webview: &Entity, focused: bool) {
if let Some(browser) = self.browsers.get(webview) {
browser.host.set_focus(focused as _);
}
}
pub fn emit_event(&self, webview: &Entity, id: impl Into<String>, event: &serde_json::Value) {
if let Some(browser) = self.browsers.get(webview)
&& let Some(frame) = browser.client.main_frame()
&& let Some(mut process_message) =
process_message_create(Some(&PROCESS_MESSAGE_HOST_EMIT.into()))
&& let Some(argument_list) = process_message.argument_list()
{
argument_list.set_string(0, Some(&id.into().as_str().into()));
argument_list.set_string(1, Some(&event.to_string().as_str().into()));
frame.send_process_message(
ProcessId::from(cef_dll_sys::cef_process_id_t::PID_RENDERER),
Some(&mut process_message),
);
};
}
pub fn resize(&self, webview: &Entity, size: Vec2) {
if let Some(browser) = self.browsers.get(webview) {
browser.size.set(size);
browser.host.was_resized();
}
}
/// Update the stored device scale factor for the webview's backing browser.
///
/// Must be called before [`Self::notify_screen_info_changed`] — otherwise
/// CEF re-queries `GetScreenInfo` with the stale value.
pub fn set_dpr(&self, webview: &Entity, dpr: f32) {
if let Some(browser) = self.browsers.get(webview) {
browser.dpr.set(dpr);
}
}
/// Tell CEF to re-query screen info and force Blink to reflow at the new DPR.
///
/// `notify_screen_info_changed` alone updates Chromium's cached screen
/// metrics but does not run `ResizeRootLayer` / `SynchronizeVisualProperties`.
/// Only `was_resized()` pushes new `VisualProperties` (including the new
/// `device_scale_factor`) to Blink. Without the pair, the CSS viewport
/// ends up laid out as `view_rect × DSF` DIP wide and on-screen text
/// shrinks by exactly `1/DSF`. Matches the cefclient OSR convention
/// (`tests/cefclient/browser/osr_window_win.cc::SetDeviceScaleFactor`).
pub fn notify_screen_info_changed(&self, webview: &Entity) {
if let Some(browser) = self.browsers.get(webview) {
browser.host.notify_screen_info_changed();
browser.host.was_resized();
}
}
/// Closes the browser associated with the given webview entity.
///
/// The browser will be removed from the hash map after closing.
pub fn close(&mut self, webview: &Entity) {
if let Some(browser) = self.browsers.remove(webview) {
browser.host.close_browser(true as _);
debug!("Closed browser with webview: {:?}", webview);
}
}
/// Returns how many browsers CEF has created and not yet closed, popups and DevTools included.
///
/// A closed browser leaves the count only once CEF reports it closed, which happens during
/// message-loop work.
pub fn live_browser_count(&self) -> usize {
self.live_browsers.borrow().len()
}
/// Force-closes every live browser, popups and DevTools included, and forgets every webview's
/// browser.
///
/// The browsers leave [`Self::live_browser_count`] as CEF reports them closed.
pub fn close_all(&mut self) {
// NOTE: CEF may report a close from inside `close_browser`, and the life-span handler
// then mutably borrows the live list; iterate over a copy so no borrow is held.
let live: Vec<Browser> = self.live_browsers.borrow().clone();
for browser in live {
if let Some(host) = browser.host() {
host.close_browser(1);
}
}
self.browsers.clear();
}
/// Drops every CEF reference `Browsers` holds: the webview browsers, the live-browser list
/// and the profile contexts.
///
/// Must run before `cef::shutdown()`, so no reference outlives CEF.
pub fn release_all(&mut self) {
self.browsers.clear();
self.live_browsers.borrow_mut().clear();
self.profiles.clear();
}
/// Drains the latest texture from each webview's view and popup slots.
///
/// Non-macOS only: the CPU `OnPaint` path. macOS uses the GPU IOSurface path.
#[cfg(not(target_os = "macos"))]
pub fn try_receive_textures(&self) -> impl Iterator<Item = RenderTextureMessage> + '_ {
self.browsers.values().flat_map(|b| {
[b.view_slot.take(), b.popup_slot.take()]
.into_iter()
.flatten()
})
}
/// Shows the DevTools for the specified webview.
pub fn show_devtool(&self, webview: &Entity) {
let Some(browser) = self.browsers.get(webview) else {
return;
};
browser.host.show_dev_tools(
Some(&WindowInfo::default()),
Some(
&mut ClientHandlerBuilder::new(DevToolRenderHandlerBuilder::build())
.with_life_span_handler(LifeSpanHandlerBuilder::build(
self.live_browsers.clone(),
))
.build(),
),
Some(&BrowserSettings::default()),
None,
);
}
/// Closes the DevTools for the specified webview.
pub fn close_devtools(&self, webview: &Entity) {
if let Some(browser) = self.browsers.get(webview) {
browser.host.close_dev_tools();
}
}
/// Navigate backwards.
///
/// ## Reference
///
/// - [`GoBack`](https://cef-builds.spotifycdn.com/docs/122.0/classCefBrowser.html#a85b02760885c070e4ad2a2705cea56cb)
pub fn go_back(&self, webview: &Entity) {
if let Some(browser) = self.browsers.get(webview)
&& browser.client.can_go_back() == 1
{
browser.client.go_back();
}
}
/// Navigate forwards.
///
/// ## Reference
///
/// - [`GoForward`](https://cef-builds.spotifycdn.com/docs/122.0/classCefBrowser.html#aa8e97fc210ee0e73f16b2d98482419d0)
pub fn go_forward(&self, webview: &Entity) {
if let Some(browser) = self.browsers.get(webview)
&& browser.client.can_go_forward() == 1
{
browser.client.go_forward();
}
}
/// Returns whether the webview can navigate back in history.
///
/// Returns `false` if the entity is not a known browser.
///
/// ## Reference
///
/// - [`CanGoBack`](https://cef-builds.spotifycdn.com/docs/122.0/classCefBrowser.html#a3a4f4327a498a8b6a498abb9e2b2ecf3)
pub fn can_go_back(&self, webview: &Entity) -> bool {
self.browsers
.get(webview)
.is_some_and(|b| b.client.can_go_back() == 1)
}
/// Returns whether the webview can navigate forward in history.
///
/// Returns `false` if the entity is not a known browser.
///
/// ## Reference
///
/// - [`CanGoForward`](https://cef-builds.spotifycdn.com/docs/122.0/classCefBrowser.html#a6537bcc556f449284e3c1b76c8d26de1)
pub fn can_go_forward(&self, webview: &Entity) -> bool {
self.browsers
.get(webview)
.is_some_and(|b| b.client.can_go_forward() == 1)
}
/// Navigate a specific webview to a new URL.
pub fn navigate(&self, webview: &Entity, url: &str) {
if let Some(browser) = self.browsers.get(webview)
&& let Some(frame) = browser.client.main_frame()
{
frame.load_url(Some(&url.into()));
}
}
/// Reload a specific webview's current page.
pub fn reload_webview(&self, webview: &Entity) {
if let Some(browser) = self.browsers.get(webview)
&& let Some(frame) = browser.client.main_frame()
{
let url = frame.url().into_string();
frame.load_url(Some(&url.as_str().into()));
}
}
/// Returns the current zoom level for the specified webview.
///
/// ## Reference
///
/// - [`GetZoomLevel`](https://cef-builds.spotifycdn.com/docs/122.0/classCefBrowserHost.html#a524d4a358287dab284c0dfec6d6d229e)
pub fn zoom_level(&self, webview: &Entity) -> Option<f64> {
self.browsers
.get(webview)
.map(|browser| browser.host.zoom_level())
}
/// Sets the zoom level for the specified webview.
///
/// ## Reference
///
/// - [`SetZoomLevel`](https://cef-builds.spotifycdn.com/docs/122.0/classCefBrowserHost.html#af2b7bf250ac78345117cd575190f2f7b)
pub fn set_zoom_level(&self, webview: &Entity, zoom_level: f64) {
if let Some(browser) = self.browsers.get(webview) {
let mut state = browser.initial_zoom.get();
let request = state.request(zoom_level);
browser.initial_zoom.set(state);
if request == ZoomRequest::SendNow {
browser.host.set_zoom_level(zoom_level);
}
}
}
/// Sets whether the audio is muted for the specified webview.
///
/// ## Reference
///
/// - [`SetAudioMuted`](https://cef-builds.spotifycdn.com/docs/122.0/classCefBrowserHost.html#a153d179c9ff202c8bb8869d2e9a820a2)
pub fn set_audio_muted(&self, webview: &Entity, muted: bool) {
if let Some(browser) = self.browsers.get(webview) {
browser.host.set_audio_muted(muted as _);
}
}
/// Returns whether the audio of the specified webview is muted.
///
/// Returns `None` when the webview has no browser.
///
/// ## Reference
///
/// - [`CefBrowserHost::IsAudioMuted`](https://cef-builds.spotifycdn.com/docs/122.0/classCefBrowserHost.html)
pub fn is_audio_muted(&self, webview: &Entity) -> Option<bool> {
self.browsers
.get(webview)
.map(|browser| browser.host.is_audio_muted() == 1)
}
#[inline]
pub fn reload(&self) {
for browser in self.browsers.values() {
if let Some(frame) = browser.client.main_frame() {
let url = frame.url().into_string();
info!("Reloading browser with URL: {}", url);
frame.load_url(Some(&url.as_str().into()));
}
}
}
/// ## Reference
///
/// - [`ImeSetComposition`](https://cef-builds.spotifycdn.com/docs/122.0/classCefBrowserHost.html#a567b41fb2d3917843ece3b57adc21ebe)
pub fn set_ime_composition(&self, text: &str, cursor_utf16: Option<u32>) {
let underlines = make_underlines_for(text, cursor_utf16.map(|i| (i, i)));
let i = text.encode_utf16().count();
let selection_range = Range {
from: i as _,
to: i as _,
};
for browser in self
.browsers
.values()
.filter(|b| b.client.focused_frame().is_some())
{
let replacement_range = Self::ime_caret_range_for();
browser.host.ime_set_composition(
Some(&text.into()),
Some(&underlines),
Some(&replacement_range),
Some(&selection_range),
);
}
}
/// ## Reference
///
/// [`ImeCancelComposition`](https://cef-builds.spotifycdn.com/docs/122.0/classCefBrowserHost.html#ac12a8076859d0c1e58e55080f698e7a9)
pub fn ime_cancel_composition(&self) {
for browser in self
.browsers
.values()
.filter(|b| b.client.focused_frame().is_some())
{
browser.host.ime_cancel_composition();
}
}
/// ## Reference
///
/// [`ImeSetComposition`](https://cef-builds.spotifycdn.com/docs/122.0/classCefBrowserHost.html#a567b41fb2d3917843ece3b57adc21ebe)
pub fn ime_finish_composition(&self, keep_selection: bool) {
for browser in self
.browsers
.values()
.filter(|b| b.client.focused_frame().is_some())
{
browser.host.ime_finish_composing_text(keep_selection as _);
}
}
pub fn set_ime_commit_text(&self, text: &str) {
for browser in self
.browsers
.values()
.filter(|b| b.client.focused_frame().is_some())
{
let replacement_range = Self::ime_caret_range_for();
browser
.host
.ime_commit_text(Some(&text.into()), Some(&replacement_range), 0);
}
}
fn request_context(requester: Requester) -> Option<RequestContext> {
let mut context = cef::request_context_create_context(
Some(&RequestContextSettings::default()),
Some(&mut RequestContextHandlerBuilder::build()),
);
if let Some(context) = context.as_mut() {
Self::register_scheme_factories(context, requester);
}
context
}
fn register_scheme_factories(context: &mut RequestContext, requester: Requester) {
context.register_scheme_handler_factory(
Some(&SCHEME_CEF.into()),
Some(&HOST_CEF.into()),
Some(&mut LocalSchemaHandlerBuilder::build(requester)),
);
crate::custom_scheme::register_custom_scheme_factories(context);
}
#[allow(clippy::too_many_arguments)]
fn client_handler(
&self,
webview: Entity,
size: SharedViewSize,
#[cfg(not(target_os = "macos"))] view_slot: SharedTexture,
#[cfg(not(target_os = "macos"))] popup_slot: SharedTexture,
dpr: SharedDpr,
ipc_event_sender: Sender<IpcEventRaw>,
brp_sender: Sender<BrpMessage>,
system_cursor_icon_sender: SystemCursorIconSenderInner,
drag_regions_sender: DraggableRegionSenderInner,
load_handler_sender: LoadHandlerSenderInner,
address_changed_sender: AddressChangedSenderInner,
#[cfg(target_os = "macos")]
latest_iosurface: crate::browser_process::accelerated_paint::SharedRetainedIoSurface,
title_changed_sender: TitleChangedSenderInner,
initial_zoom: SharedInitialZoom,
cookie_flusher: Option<CookieFlusher>,
) -> Client {
#[cfg(target_os = "macos")]
let render_handler =
RenderHandlerBuilder::build(webview, size.clone(), dpr, latest_iosurface);
#[cfg(not(target_os = "macos"))]
let render_handler =
RenderHandlerBuilder::build(webview, view_slot, popup_slot, size.clone(), dpr);
ClientHandlerBuilder::new(render_handler)
.with_display_handler(DisplayHandlerBuilder::build(
webview,
system_cursor_icon_sender,
address_changed_sender,
title_changed_sender,
))
.with_drag_handler(DragHandlerBuilder::build(webview, drag_regions_sender))
.with_load_handler(LoadHandlerBuilder::build(
webview,
load_handler_sender,
initial_zoom,
cookie_flusher,
))
.with_life_span_handler(LifeSpanHandlerBuilder::build(self.live_browsers.clone()))
.with_message_handler(JsEmitEventHandler::new(webview, ipc_event_sender))
.with_message_handler(BrpHandler::new(brp_sender))
.build()
}
#[inline]
fn ime_caret_range_for() -> Range {
// Use sentinel replacement range to indicate caret position
Range {
from: u32::MAX,
to: u32::MAX,
}
}
#[inline]
fn get_focused_browser(&self, webview: &Entity) -> Option<&WebviewBrowser> {
self.browsers
.get(webview)
.and_then(|b| b.client.focused_frame().is_some().then_some(b))
}
fn create_extra_info(scripts: &[String]) -> Option<DictionaryValue> {
if scripts.is_empty() {
return None;
}
let extra = dictionary_value_create()?;
extra.set_string(
Some(&CefString::from(INIT_SCRIPT_KEY)),
Some(&CefString::from(scripts.join(";").as_str())),
);
Some(extra)
}
}
#[allow(clippy::unnecessary_cast)]
pub fn modifiers_from_mouse_buttons<'a>(buttons: impl IntoIterator<Item = &'a MouseButton>) -> u32 {
let mut modifiers = cef_event_flags_t::EVENTFLAG_NONE.0 as u32;
for button in buttons {
match button {
MouseButton::Left => {
modifiers |= cef_event_flags_t::EVENTFLAG_LEFT_MOUSE_BUTTON.0 as u32
}
MouseButton::Right => {
modifiers |= cef_event_flags_t::EVENTFLAG_RIGHT_MOUSE_BUTTON.0 as u32
}
MouseButton::Middle => {
modifiers |= cef_event_flags_t::EVENTFLAG_MIDDLE_MOUSE_BUTTON.0 as u32
}
_ => {}
}
}
modifiers
}
pub fn make_underlines_for(
text: &str,
selection_utf16: Option<(u32, u32)>,
) -> Vec<CompositionUnderline> {
let len16 = utf16_len(text);
let base = CompositionUnderline {
size: size_of::<CompositionUnderline>(),
range: Range { from: 0, to: len16 },
color: 0,
background_color: 0,
thick: 0,
style: Default::default(),
};
if let Some((from, to)) = selection_utf16
&& from < to
{
let sel = CompositionUnderline {
size: size_of::<CompositionUnderline>(),
range: Range { from, to },
color: 0,
background_color: 0,
thick: 1,
style: Default::default(),
};
return vec![base, sel];
}
vec![base]
}
#[inline]
fn utf16_len(s: &str) -> u32 {
s.encode_utf16().count() as u32
}
#[allow(dead_code)]
fn utf16_index_from_byte(s: &str, byte_idx: usize) -> u32 {
s[..byte_idx].encode_utf16().count() as u32
}
#[cfg(test)]
mod tests {
use crate::prelude::modifiers_from_mouse_buttons;
use bevy::prelude::*;
#[test]
#[allow(clippy::unnecessary_cast)]
fn test_modifiers_from_mouse_buttons() {
let buttons = vec![&MouseButton::Left, &MouseButton::Right];
let modifiers = modifiers_from_mouse_buttons(buttons);
assert_eq!(
modifiers,
cef_dll_sys::cef_event_flags_t::EVENTFLAG_LEFT_MOUSE_BUTTON.0 as u32
| cef_dll_sys::cef_event_flags_t::EVENTFLAG_RIGHT_MOUSE_BUTTON.0 as u32
);
}
}