├── cef ├── .gitignore ├── tests │ └── 01-can-initialize.rs ├── examples │ └── basic.rs ├── Cargo.toml └── src │ ├── cef_strings.rs │ ├── application │ ├── app.rs │ ├── browser_view_delegate.rs │ ├── mod.rs │ ├── browser_process_handler.rs │ └── window_delegate.rs │ ├── handler │ ├── render_handler.rs │ ├── display_handler.rs │ ├── load_handler.rs │ ├── client.rs │ ├── life_span_handler.rs │ └── mod.rs │ └── lib.rs ├── cef-sys ├── wrapper-win.h ├── .gitignore ├── src │ └── lib.rs ├── README.md ├── Cargo.toml ├── wrapper.h └── build.rs ├── Cargo.toml ├── README.md ├── cef-ref-counting ├── Cargo.toml ├── tests │ ├── 01-should-add-struct-field.rs │ └── 02-should-add-impl-methods.rs └── src │ └── lib.rs ├── .gitignore └── LICENSE /cef/.gitignore: -------------------------------------------------------------------------------- 1 | GPUCache/ 2 | -------------------------------------------------------------------------------- /cef-sys/wrapper-win.h: -------------------------------------------------------------------------------- 1 | #include 2 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["cef", "cef-sys", "cef-ref-counting"] 3 | -------------------------------------------------------------------------------- /cef-sys/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | /Release 4 | /Resources 5 | /include 6 | *.zip 7 | *.tar 8 | *.gz 9 | *.bz2 10 | 11 | -------------------------------------------------------------------------------- /cef-sys/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_upper_case_globals)] 2 | #![allow(non_camel_case_types)] 3 | #![allow(non_snake_case)] 4 | 5 | include!(concat!(env!("OUT_DIR"), "/cef_bindings.rs")); 6 | -------------------------------------------------------------------------------- /cef-sys/README.md: -------------------------------------------------------------------------------- 1 | # TODO 2 | 3 | * [ ] Automatically download CEF binaries and include files for the current platform / version 4 | * [ ] Automatically copy the CEF binaries into place when compiling 5 | 6 | -------------------------------------------------------------------------------- /cef/tests/01-can-initialize.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test { 3 | use cef::Cef; 4 | 5 | #[test] 6 | fn can_initialize() { 7 | let cef = Cef::initialize(); 8 | drop(cef); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /cef-sys/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cef-sys" 3 | version = "100.0.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | 8 | [build-dependencies] 9 | bindgen = "0.59" 10 | anyhow = "1" 11 | curl = "0.4" 12 | bzip2 = "0.4" 13 | tar = "0.4" 14 | 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cef-rs: Chromium Embedded Framework bindings for Rust 2 | 3 | This project aims to make [CEF](https://bitbucket.org/chromiumembedded/cef/) usable in Rust, with relatively up-to-date bindings. Ultimately it aims to replicate the CefSimple test which can be built upon to build a full application. 4 | 5 | -------------------------------------------------------------------------------- /cef-ref-counting/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cef-ref-counting" 3 | version = "1.0.0" 4 | edition = "2021" 5 | 6 | [lib] 7 | proc-macro = true 8 | 9 | [dependencies] 10 | cef-sys = { path = "../cef-sys" } 11 | log = "0.4" 12 | syn = {version = "1", features = ["full", "extra-traits"]} 13 | quote = "1" 14 | 15 | [dev-dependencies] 16 | env_logger = "0.8" 17 | 18 | -------------------------------------------------------------------------------- /cef-sys/wrapper.h: -------------------------------------------------------------------------------- 1 | #include "include/capi/cef_base_capi.h" 2 | #include "include/capi/cef_app_capi.h" 3 | #include "include/capi/cef_client_capi.h" 4 | #include "include/capi/cef_life_span_handler_capi.h" 5 | #include 6 | #include 7 | #include 8 | -------------------------------------------------------------------------------- /cef/examples/basic.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | use simplelog::*; 3 | 4 | fn main() -> Result<()> { 5 | TermLogger::init( 6 | LevelFilter::Debug, 7 | Config::default(), 8 | TerminalMode::Stdout, 9 | ColorChoice::Auto, 10 | ) 11 | .expect("can initialize logging"); 12 | 13 | let cef = cef::Cef::initialize()?; 14 | cef.run() 15 | } 16 | -------------------------------------------------------------------------------- /cef/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cef" 3 | version = "1.0.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | cef-sys = { path = "../cef-sys" } 8 | cef-ref-counting = { path = "../cef-ref-counting" } 9 | anyhow = "1" 10 | log = "0.4" 11 | base64 = "0.13" 12 | 13 | [target.'cfg(windows)'.dependencies.windows] 14 | version = "0.35" 15 | features = [ 16 | "Win32_Foundation", 17 | "Win32_System_LibraryLoader", 18 | ] 19 | 20 | [dev-dependencies] 21 | simplelog = { version = "0.11", features = ["paris"] } 22 | 23 | -------------------------------------------------------------------------------- /cef/src/cef_strings.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::CString; 2 | 3 | use cef_sys::{cef_string_t, cef_string_utf8_to_utf16}; 4 | 5 | pub unsafe fn to_cef_str(s: S) -> cef_string_t { 6 | let mut cstr = cef_string_t::default(); 7 | let s = s.to_string(); 8 | let bytes = s.as_bytes(); 9 | let s = CString::new(bytes).expect("can create c string from rust string bytes"); 10 | cef_string_utf8_to_utf16(s.as_ptr(), s.as_bytes().len() as u64, &mut cstr); 11 | cstr 12 | } 13 | 14 | pub unsafe fn from_cef_str(s: *const cef_string_t) -> String { 15 | let bytes: &[u16] = std::slice::from_raw_parts((*s).str_, (*s).length as usize); 16 | String::from_utf16_lossy(bytes) 17 | } 18 | -------------------------------------------------------------------------------- /cef-ref-counting/tests/01-should-add-struct-field.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod tests { 3 | use cef_ref_counting::{ref_count, RefCount}; 4 | 5 | #[test] 6 | fn adds_ref_count_field() { 7 | #[ref_count] 8 | #[derive(Debug)] 9 | struct Foo {} 10 | 11 | let bar = Foo { 12 | ref_count: std::sync::atomic::AtomicIsize::new(0), 13 | }; 14 | 15 | assert_ne!(std::mem::size_of_val(&bar), 0); 16 | } 17 | 18 | #[test] 19 | fn keeps_original_field() { 20 | #[ref_count] 21 | #[derive(Debug)] 22 | struct Foo { 23 | a: String, 24 | } 25 | 26 | let bar = Foo { 27 | a: "lorem ipsum".to_string(), 28 | ref_count: std::sync::atomic::AtomicIsize::new(0), 29 | }; 30 | 31 | assert_eq!(bar.a, "lorem ipsum"); 32 | } 33 | 34 | #[test] 35 | fn adds_field_with_derive() { 36 | #[ref_count] 37 | #[derive(Debug, RefCount)] 38 | struct Foo { 39 | a: String, 40 | } 41 | 42 | let bar = Foo { 43 | a: "lorem ipsum".to_string(), 44 | ref_count: std::sync::atomic::AtomicIsize::new(0), 45 | }; 46 | 47 | assert_eq!(bar.a, "lorem ipsum"); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /cef-ref-counting/tests/02-should-add-impl-methods.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod tests { 3 | use cef_ref_counting::{ref_count, RefCount}; 4 | use cef_sys::cef_base_ref_counted_t; 5 | 6 | #[test] 7 | fn impls_ref_counting_methods() { 8 | let _ = env_logger::builder().is_test(true).try_init(); 9 | 10 | #[ref_count] 11 | #[derive(Debug, RefCount)] 12 | #[allow(dead_code)] 13 | struct Foo { 14 | base: cef_base_ref_counted_t, 15 | } 16 | 17 | let foo = Foo { 18 | base: cef_base_ref_counted_t { 19 | size: std::mem::size_of::() as u64, 20 | add_ref: Some(Foo::add_ref), 21 | release: Some(Foo::release), 22 | has_one_ref: Some(Foo::has_one_ref), 23 | has_at_least_one_ref: Some(Foo::has_at_least_one_ref), 24 | }, 25 | ref_count: 0.into(), 26 | }; 27 | 28 | log::info!("derp"); 29 | unsafe { 30 | let foo: *mut Foo = Box::into_raw(Box::from(foo)); 31 | 32 | Foo::add_ref(foo as *mut cef_base_ref_counted_t); 33 | assert_eq!(Foo::has_one_ref(foo as *mut cef_base_ref_counted_t), 1); 34 | Foo::release(foo as *mut cef_base_ref_counted_t); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /cef/src/application/app.rs: -------------------------------------------------------------------------------- 1 | use std::mem::size_of; 2 | 3 | use cef_ref_counting::{ref_count, RefCount}; 4 | use cef_sys::{cef_app_t, cef_base_ref_counted_t, cef_browser_process_handler_t}; 5 | 6 | use crate::application::Application; 7 | 8 | #[ref_count] 9 | #[derive(RefCount, Debug)] 10 | #[allow(unused)] 11 | pub struct App { 12 | pub app: cef_app_t, 13 | pub application: *mut Application, 14 | } 15 | 16 | impl App { 17 | pub fn allocate() -> *mut Self { 18 | let app = App { 19 | app: cef_app_t { 20 | base: cef_base_ref_counted_t { 21 | size: size_of::() as u64, 22 | add_ref: Some(Self::add_ref), 23 | release: Some(Self::release), 24 | has_one_ref: Some(Self::has_one_ref), 25 | has_at_least_one_ref: Some(Self::has_at_least_one_ref), 26 | }, 27 | on_before_command_line_processing: None, 28 | on_register_custom_schemes: None, 29 | get_render_process_handler: None, 30 | get_browser_process_handler: Some(Self::get_browser_process_handler), 31 | get_resource_bundle_handler: None, 32 | }, 33 | application: std::ptr::null_mut(), 34 | ref_count: 1.into(), 35 | }; 36 | 37 | log::debug!("app allocated"); 38 | Box::into_raw(Box::from(app)) 39 | } 40 | 41 | unsafe extern "C" fn get_browser_process_handler( 42 | slf: *mut cef_app_t, 43 | ) -> *mut cef_browser_process_handler_t { 44 | log::debug!( 45 | "getting browser process handler, slf: {:?}, application: {:?}", 46 | slf, 47 | *(*(slf as *mut App)).application 48 | ); 49 | (*(*(slf as *mut App)).application).browser_process_handler_ptr() 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /cef/src/handler/render_handler.rs: -------------------------------------------------------------------------------- 1 | use std::mem::size_of; 2 | 3 | use cef_ref_counting::{ref_count, RefCount}; 4 | use cef_sys::{cef_base_ref_counted_t, cef_browser_t, cef_render_handler_t, cef_text_input_mode_t}; 5 | 6 | use crate::handler::Handler; 7 | 8 | #[ref_count] 9 | #[derive(RefCount)] 10 | #[allow(unused)] 11 | pub struct RenderHandler { 12 | pub render_handler: cef_render_handler_t, 13 | pub handler: *mut Handler, 14 | } 15 | 16 | impl RenderHandler { 17 | pub fn allocate() -> *mut Self { 18 | let render_handler = RenderHandler { 19 | render_handler: cef_render_handler_t { 20 | base: cef_base_ref_counted_t { 21 | size: size_of::() as u64, 22 | add_ref: Some(Self::add_ref), 23 | release: Some(Self::release), 24 | has_one_ref: Some(Self::has_one_ref), 25 | has_at_least_one_ref: Some(Self::has_at_least_one_ref), 26 | }, 27 | get_accessibility_handler: None, 28 | get_root_screen_rect: None, 29 | get_view_rect: None, 30 | get_screen_point: None, 31 | get_screen_info: None, 32 | on_popup_show: None, 33 | on_popup_size: None, 34 | on_paint: None, 35 | on_accelerated_paint: None, 36 | start_dragging: None, 37 | update_drag_cursor: None, 38 | on_scroll_offset_changed: None, 39 | on_ime_composition_range_changed: None, 40 | on_text_selection_changed: None, 41 | on_virtual_keyboard_requested: Some(Self::on_virtual_keyboard_requested), 42 | }, 43 | handler: std::ptr::null_mut(), 44 | ref_count: 1.into(), 45 | }; 46 | 47 | log::debug!("render_handler allocated"); 48 | Box::into_raw(Box::from(render_handler)) 49 | } 50 | 51 | unsafe extern "C" fn on_virtual_keyboard_requested( 52 | _slf: *mut cef_render_handler_t, 53 | _browser: *mut cef_browser_t, 54 | input_mode: cef_text_input_mode_t, 55 | ) { 56 | log::debug!( 57 | "on virtual keyboard requested, input mode: {:?}", 58 | input_mode 59 | ); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /cef/src/handler/display_handler.rs: -------------------------------------------------------------------------------- 1 | use std::mem::size_of; 2 | 3 | use cef_ref_counting::{ref_count, RefCount}; 4 | use cef_sys::{ 5 | cef_base_ref_counted_t, cef_browser_t, cef_browser_view_get_for_browser, cef_display_handler_t, 6 | cef_string_t, 7 | }; 8 | 9 | use crate::handler::Handler; 10 | 11 | #[ref_count] 12 | #[derive(RefCount)] 13 | #[allow(unused)] 14 | pub struct DisplayHandler { 15 | pub display_handler: cef_display_handler_t, 16 | pub handler: *mut Handler, 17 | } 18 | 19 | impl DisplayHandler { 20 | pub fn allocate() -> *mut Self { 21 | let display_handler = DisplayHandler { 22 | display_handler: cef_display_handler_t { 23 | base: cef_base_ref_counted_t { 24 | size: size_of::() as u64, 25 | add_ref: Some(Self::add_ref), 26 | release: Some(Self::release), 27 | has_one_ref: Some(Self::has_one_ref), 28 | has_at_least_one_ref: Some(Self::has_at_least_one_ref), 29 | }, 30 | on_title_change: Some(Self::on_title_change), 31 | on_tooltip: None, 32 | on_auto_resize: None, 33 | on_cursor_change: None, 34 | on_address_change: None, 35 | on_status_message: None, 36 | on_console_message: None, 37 | on_favicon_urlchange: None, 38 | on_fullscreen_mode_change: None, 39 | on_loading_progress_change: None, 40 | }, 41 | handler: std::ptr::null_mut(), 42 | ref_count: 1.into(), 43 | }; 44 | 45 | log::debug!("display_handler allocated"); 46 | Box::into_raw(Box::from(display_handler)) 47 | } 48 | 49 | unsafe extern "C" fn on_title_change( 50 | _slf: *mut cef_display_handler_t, 51 | browser: *mut cef_browser_t, 52 | title: *const cef_string_t, 53 | ) { 54 | log::debug!("on_title_change"); 55 | let browser_view = cef_browser_view_get_for_browser(browser); 56 | if browser_view as usize != 0 { 57 | let window = (*browser_view).base.get_window.unwrap()(&mut (*browser_view).base); 58 | if window as usize != 0 { 59 | (*window).set_title.unwrap()(window, title); 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | GPUCache/ 2 | 3 | # Created by https://www.toptal.com/developers/gitignore/api/rust,windows,osx,linux,visualstudiocode 4 | # Edit at https://www.toptal.com/developers/gitignore?templates=rust,windows,osx,linux,visualstudiocode 5 | 6 | ### Linux ### 7 | *~ 8 | 9 | # temporary files which can be created if a process still has a handle open of a deleted file 10 | .fuse_hidden* 11 | 12 | # KDE directory preferences 13 | .directory 14 | 15 | # Linux trash folder which might appear on any partition or disk 16 | .Trash-* 17 | 18 | # .nfs files are created when an open file is removed but is still being accessed 19 | .nfs* 20 | 21 | ### OSX ### 22 | # General 23 | .DS_Store 24 | .AppleDouble 25 | .LSOverride 26 | 27 | # Icon must end with two \r 28 | Icon 29 | 30 | # Thumbnails 31 | ._* 32 | 33 | # Files that might appear in the root of a volume 34 | .DocumentRevisions-V100 35 | .fseventsd 36 | .Spotlight-V100 37 | .TemporaryItems 38 | .Trashes 39 | .VolumeIcon.icns 40 | .com.apple.timemachine.donotpresent 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | 49 | ### Rust ### 50 | # Generated by Cargo 51 | # will have compiled files and executables 52 | /target/ 53 | 54 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 55 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 56 | Cargo.lock 57 | 58 | # These are backup files generated by rustfmt 59 | **/*.rs.bk 60 | 61 | ### VisualStudioCode ### 62 | .vscode/* 63 | !.vscode/settings.json 64 | !.vscode/tasks.json 65 | !.vscode/launch.json 66 | !.vscode/extensions.json 67 | *.code-workspace 68 | 69 | ### VisualStudioCode Patch ### 70 | # Ignore all local history of files 71 | .history 72 | 73 | ### Windows ### 74 | # Windows thumbnail cache files 75 | Thumbs.db 76 | Thumbs.db:encryptable 77 | ehthumbs.db 78 | ehthumbs_vista.db 79 | 80 | # Dump file 81 | *.stackdump 82 | 83 | # Folder config file 84 | [Dd]esktop.ini 85 | 86 | # Recycle Bin used on file shares 87 | $RECYCLE.BIN/ 88 | 89 | # Windows Installer files 90 | *.cab 91 | *.msi 92 | *.msix 93 | *.msm 94 | *.msp 95 | 96 | # Windows shortcuts 97 | *.lnk 98 | 99 | # End of https://www.toptal.com/developers/gitignore/api/rust,windows,osx,linux,visualstudiocode 100 | 101 | -------------------------------------------------------------------------------- /cef/src/handler/load_handler.rs: -------------------------------------------------------------------------------- 1 | use std::mem::size_of; 2 | 3 | use cef_ref_counting::{ref_count, RefCount}; 4 | use cef_sys::{ 5 | cef_base_ref_counted_t, cef_browser_t, cef_errorcode_t_ERR_ABORTED, cef_frame_t, 6 | cef_load_handler_t, cef_string_t, 7 | }; 8 | 9 | use crate::{ 10 | cef_strings::{from_cef_str, to_cef_str}, 11 | handler::Handler, 12 | }; 13 | 14 | #[ref_count] 15 | #[derive(RefCount)] 16 | #[allow(unused)] 17 | pub struct LoadHandler { 18 | pub load_handler: cef_load_handler_t, 19 | pub handler: *mut Handler, 20 | } 21 | 22 | impl LoadHandler { 23 | pub fn allocate() -> *mut Self { 24 | let load_handler = LoadHandler { 25 | load_handler: cef_load_handler_t { 26 | base: cef_base_ref_counted_t { 27 | size: size_of::() as u64, 28 | add_ref: Some(Self::add_ref), 29 | release: Some(Self::release), 30 | has_one_ref: Some(Self::has_one_ref), 31 | has_at_least_one_ref: Some(Self::has_at_least_one_ref), 32 | }, 33 | on_loading_state_change: None, 34 | on_load_end: None, 35 | on_load_error: Some(Self::on_load_error), 36 | on_load_start: None, 37 | }, 38 | handler: std::ptr::null_mut(), 39 | ref_count: 1.into(), 40 | }; 41 | 42 | log::debug!("load_handler allocated"); 43 | Box::into_raw(Box::from(load_handler)) 44 | } 45 | 46 | unsafe extern "C" fn on_load_error( 47 | _slf: *mut cef_load_handler_t, 48 | _browser: *mut cef_browser_t, 49 | frame: *mut cef_frame_t, 50 | error_code: i32, 51 | error_text: *const cef_string_t, 52 | failed_url: *const cef_string_t, 53 | ) { 54 | log::debug!("on_load_error"); 55 | crate::require_ui_thread(); 56 | // don't display an error for downloaded files 57 | if error_code == cef_errorcode_t_ERR_ABORTED { 58 | return; 59 | } 60 | 61 | let error_text = from_cef_str(error_text); 62 | let failed_url = from_cef_str(failed_url); 63 | 64 | let html = format!("

Failed to load!

Failed to load URL '{}' with error: {} ({}).

", failed_url, error_text, error_code); 65 | let uri = format!("data:text/html;base64,{}", base64::encode(html)); 66 | let uri = to_cef_str(uri); 67 | 68 | (*frame).load_url.unwrap()(frame, &uri); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /cef/src/application/browser_view_delegate.rs: -------------------------------------------------------------------------------- 1 | use std::mem::size_of; 2 | 3 | use cef_ref_counting::{ref_count, RefCount}; 4 | use cef_sys::{ 5 | cef_base_ref_counted_t, cef_browser_view_delegate_t, cef_browser_view_t, cef_view_delegate_t, 6 | cef_window_create_top_level, cef_window_delegate_t, 7 | }; 8 | 9 | use super::window_delegate::WindowDelegate; 10 | 11 | #[ref_count] 12 | #[derive(RefCount)] 13 | #[allow(unused)] 14 | pub struct BrowserViewDelegate { 15 | pub browser_view_delegate: cef_browser_view_delegate_t, 16 | } 17 | 18 | impl BrowserViewDelegate { 19 | pub fn allocate() -> *mut Self { 20 | let browser_view_delegate = BrowserViewDelegate { 21 | browser_view_delegate: cef_browser_view_delegate_t { 22 | base: cef_view_delegate_t { 23 | base: cef_base_ref_counted_t { 24 | size: size_of::() as u64, 25 | add_ref: Some(Self::add_ref), 26 | release: Some(Self::release), 27 | has_one_ref: Some(Self::has_one_ref), 28 | has_at_least_one_ref: Some(Self::has_at_least_one_ref), 29 | }, 30 | get_preferred_size: None, 31 | get_minimum_size: None, 32 | get_maximum_size: None, 33 | get_height_for_width: None, 34 | on_parent_view_changed: None, 35 | on_child_view_changed: None, 36 | on_window_changed: None, 37 | on_layout_changed: None, 38 | on_focus: None, 39 | on_blur: None, 40 | }, 41 | on_browser_created: None, 42 | on_browser_destroyed: None, 43 | get_delegate_for_popup_browser_view: None, 44 | on_popup_browser_view_created: Some(Self::on_popup_browser_view_created), 45 | get_chrome_toolbar_type: None, 46 | }, 47 | ref_count: 1.into(), 48 | }; 49 | 50 | log::debug!("browser_view_delegate allocated"); 51 | Box::into_raw(Box::from(browser_view_delegate)) 52 | } 53 | 54 | unsafe extern "C" fn on_popup_browser_view_created( 55 | _slf: *mut cef_browser_view_delegate_t, 56 | _browser_view: *mut cef_browser_view_t, 57 | popup_browser_view: *mut cef_browser_view_t, 58 | _is_dev_tools: i32, 59 | ) -> i32 { 60 | log::debug!( 61 | "on_popup_browser_view_created, opening top level window with view = {:?}", 62 | popup_browser_view 63 | ); 64 | cef_window_create_top_level( 65 | WindowDelegate::allocate(popup_browser_view) as *mut cef_window_delegate_t 66 | ); 67 | 1 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /cef/src/application/mod.rs: -------------------------------------------------------------------------------- 1 | use cef_sys::{cef_app_t, cef_base_ref_counted_t, cef_browser_process_handler_t}; 2 | 3 | mod app; 4 | mod browser_process_handler; 5 | mod browser_view_delegate; 6 | mod window_delegate; 7 | 8 | use app::App; 9 | use browser_process_handler::BrowserProcessHandler; 10 | 11 | #[derive(Debug)] 12 | pub struct Application { 13 | app: *mut App, 14 | browser_process_handler: *mut BrowserProcessHandler, 15 | } 16 | 17 | impl Application { 18 | pub fn new() -> Application { 19 | let mut application = Application { 20 | app: App::allocate(), 21 | browser_process_handler: BrowserProcessHandler::allocate(), 22 | }; 23 | application.apply_pointers(); 24 | 25 | log::debug!("new application created: {:#?}", application); 26 | unsafe { 27 | log::trace!(" app -> {:#?}", (*application.app)); 28 | log::trace!( 29 | " browser_process_handler -> {:#?}", 30 | (*application.browser_process_handler) 31 | ); 32 | } 33 | application 34 | } 35 | 36 | pub fn apply_pointers(&mut self) { 37 | unsafe { 38 | (*self.app).application = self; 39 | (*self.browser_process_handler).application = self; 40 | } 41 | } 42 | 43 | pub fn app_ptr(&self) -> *mut cef_app_t { 44 | log::trace!("add ref to app",); 45 | log::trace!("self: {:?}", self); 46 | unsafe { 47 | App::add_ref(self.app as *mut cef_base_ref_counted_t); 48 | } 49 | log::trace!("app -> {:p}", self.app); 50 | self.app as *mut cef_app_t 51 | } 52 | 53 | pub fn browser_process_handler_ptr(&self) -> *mut cef_browser_process_handler_t { 54 | log::trace!("add ref to browser_process_handler",); 55 | log::trace!("self: {:?}", self); 56 | unsafe { 57 | BrowserProcessHandler::add_ref( 58 | self.browser_process_handler as *mut cef_base_ref_counted_t, 59 | ); 60 | } 61 | log::trace!( 62 | "browser_process_handler -> {:p}", 63 | self.browser_process_handler 64 | ); 65 | self.browser_process_handler as *mut cef_browser_process_handler_t 66 | } 67 | } 68 | 69 | impl Drop for Application { 70 | fn drop(&mut self) { 71 | unsafe { 72 | log::debug!("dropping app"); 73 | let app = self.app as *mut cef_base_ref_counted_t; 74 | while App::has_at_least_one_ref(app) == 1 { 75 | App::release(app); 76 | } 77 | log::debug!("dropping browser_process_handler"); 78 | let browser_process_handler = 79 | self.browser_process_handler as *mut cef_base_ref_counted_t; 80 | while BrowserProcessHandler::has_at_least_one_ref(browser_process_handler) == 1 { 81 | BrowserProcessHandler::release(browser_process_handler); 82 | } 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /cef/src/handler/client.rs: -------------------------------------------------------------------------------- 1 | use std::mem::size_of; 2 | 3 | use cef_ref_counting::{ref_count, RefCount}; 4 | use cef_sys::{ 5 | cef_base_ref_counted_t, cef_client_t, cef_display_handler_t, cef_life_span_handler_t, 6 | cef_load_handler_t, cef_render_handler_t, 7 | }; 8 | 9 | use crate::handler::Handler; 10 | 11 | #[ref_count] 12 | #[derive(RefCount)] 13 | #[allow(unused)] 14 | pub struct Client { 15 | pub client: cef_client_t, 16 | pub handler: *mut Handler, 17 | } 18 | 19 | impl Client { 20 | pub fn allocate() -> *mut Self { 21 | let client = Client { 22 | client: cef_client_t { 23 | base: cef_base_ref_counted_t { 24 | size: size_of::() as u64, 25 | add_ref: Some(Self::add_ref), 26 | release: Some(Self::release), 27 | has_one_ref: Some(Self::has_one_ref), 28 | has_at_least_one_ref: Some(Self::has_at_least_one_ref), 29 | }, 30 | get_audio_handler: None, 31 | get_context_menu_handler: None, 32 | get_dialog_handler: None, 33 | get_display_handler: Some(Self::get_display_handler), 34 | get_download_handler: None, 35 | get_drag_handler: None, 36 | get_find_handler: None, 37 | get_focus_handler: None, 38 | get_frame_handler: None, 39 | get_jsdialog_handler: None, 40 | get_keyboard_handler: None, 41 | get_life_span_handler: Some(Self::get_life_span_handler), 42 | get_load_handler: Some(Self::get_load_handler), 43 | get_print_handler: None, 44 | get_render_handler: Some(Self::get_render_handler), 45 | get_request_handler: None, 46 | on_process_message_received: None, 47 | }, 48 | handler: std::ptr::null_mut(), 49 | ref_count: 1.into(), 50 | }; 51 | 52 | log::debug!("client allocated"); 53 | Box::into_raw(Box::from(client)) 54 | } 55 | 56 | unsafe extern "C" fn get_display_handler(slf: *mut cef_client_t) -> *mut cef_display_handler_t { 57 | let slf = slf as *mut Client; 58 | //log::debug!("getting display handler"); 59 | (*((*slf).handler)).display_handler_ptr() 60 | } 61 | 62 | unsafe extern "C" fn get_life_span_handler( 63 | slf: *mut cef_client_t, 64 | ) -> *mut cef_life_span_handler_t { 65 | let slf = slf as *mut Client; 66 | //log::debug!("getting life_span_handler"); 67 | (*((*slf).handler)).life_span_handler_ptr() 68 | } 69 | 70 | unsafe extern "C" fn get_load_handler(slf: *mut cef_client_t) -> *mut cef_load_handler_t { 71 | let slf = slf as *mut Client; 72 | //log::debug!("getting load_handler"); 73 | (*((*slf).handler)).load_handler_ptr() 74 | } 75 | 76 | unsafe extern "C" fn get_render_handler(slf: *mut cef_client_t) -> *mut cef_render_handler_t { 77 | let slf = slf as *mut Client; 78 | //log::debug!("getting render_handler"); 79 | (*((*slf).handler)).render_handler_ptr() 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /cef/src/handler/life_span_handler.rs: -------------------------------------------------------------------------------- 1 | use std::mem::size_of; 2 | 3 | use cef_ref_counting::{ref_count, RefCount}; 4 | use cef_sys::{ 5 | cef_base_ref_counted_t, cef_browser_t, cef_life_span_handler_t, cef_quit_message_loop, 6 | }; 7 | 8 | use crate::handler::Handler; 9 | 10 | #[ref_count] 11 | #[derive(RefCount)] 12 | #[allow(unused)] 13 | pub struct LifeSpanHandler { 14 | pub life_span_handler: cef_life_span_handler_t, 15 | pub handler: *mut Handler, 16 | } 17 | 18 | impl LifeSpanHandler { 19 | pub fn allocate() -> *mut Self { 20 | let life_span_handler = LifeSpanHandler { 21 | life_span_handler: cef_life_span_handler_t { 22 | base: cef_base_ref_counted_t { 23 | size: size_of::() as u64, 24 | add_ref: Some(Self::add_ref), 25 | release: Some(Self::release), 26 | has_one_ref: Some(Self::has_one_ref), 27 | has_at_least_one_ref: Some(Self::has_at_least_one_ref), 28 | }, 29 | on_before_popup: None, 30 | on_after_created: Some(Self::on_after_created), 31 | on_before_close: Some(Self::on_before_close), 32 | do_close: Some(Self::do_close), 33 | }, 34 | handler: std::ptr::null_mut(), 35 | ref_count: 1.into(), 36 | }; 37 | 38 | log::debug!("life_span_handler allocated"); 39 | Box::into_raw(Box::from(life_span_handler)) 40 | } 41 | 42 | unsafe extern "C" fn on_after_created( 43 | slf: *mut cef_life_span_handler_t, 44 | browser: *mut cef_browser_t, 45 | ) { 46 | log::debug!("on_after_created"); 47 | crate::require_ui_thread(); 48 | (*((*(slf as *mut LifeSpanHandler)).handler)) 49 | .browsers 50 | .push(browser); 51 | } 52 | 53 | unsafe extern "C" fn on_before_close( 54 | slf: *mut cef_life_span_handler_t, 55 | browser: *mut cef_browser_t, 56 | ) { 57 | log::debug!("on_before_close"); 58 | crate::require_ui_thread(); 59 | for (i, b) in (*((*(slf as *mut LifeSpanHandler)).handler)) 60 | .browsers 61 | .iter() 62 | .enumerate() 63 | { 64 | if (*browser).is_same.unwrap()(browser, *b) != 0 { 65 | log::debug!("removing browser {}", i); 66 | (*((*(slf as *mut LifeSpanHandler)).handler)) 67 | .browsers 68 | .remove(i); 69 | break; 70 | } 71 | } 72 | 73 | if (*((*(slf as *mut LifeSpanHandler)).handler)) 74 | .browsers 75 | .is_empty() 76 | { 77 | log::debug!("browser list is empty, quitting"); 78 | cef_quit_message_loop(); 79 | } 80 | } 81 | 82 | unsafe extern "C" fn do_close( 83 | slf: *mut cef_life_span_handler_t, 84 | _browser: *mut cef_browser_t, 85 | ) -> i32 { 86 | log::debug!("do_close"); 87 | crate::require_ui_thread(); 88 | if (*((*(slf as *mut LifeSpanHandler)).handler)).browsers.len() == 1 { 89 | log::debug!("only 1 browser remaining, marking closing"); 90 | (*((*(slf as *mut LifeSpanHandler)).handler)).is_closing = true; 91 | } 92 | 0 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /cef-ref-counting/src/lib.rs: -------------------------------------------------------------------------------- 1 | use proc_macro::TokenStream; 2 | use quote::quote; 3 | use syn::parse::Parser; 4 | use syn::{parse, parse_macro_input, ItemStruct}; 5 | 6 | #[proc_macro_attribute] 7 | pub fn ref_count(args: TokenStream, input: TokenStream) -> TokenStream { 8 | let mut item_struct = parse_macro_input!(input as ItemStruct); 9 | let _ = parse_macro_input!(args as parse::Nothing); 10 | 11 | if let syn::Fields::Named(ref mut fields) = item_struct.fields { 12 | fields.named.push( 13 | syn::Field::parse_named 14 | .parse2(quote! { ref_count: std::sync::atomic::AtomicIsize }) 15 | .unwrap(), 16 | ); 17 | } 18 | 19 | return quote! { 20 | #item_struct 21 | } 22 | .into(); 23 | } 24 | 25 | #[proc_macro_derive(RefCount)] 26 | pub fn ref_count_derive(input: TokenStream) -> TokenStream { 27 | let ast = syn::parse(input).unwrap(); 28 | impl_ref_count_derive(&ast) 29 | } 30 | 31 | fn impl_ref_count_derive(ast: &syn::DeriveInput) -> TokenStream { 32 | let name = &ast.ident; 33 | let gen = quote! { 34 | impl #name { 35 | pub unsafe extern "C" fn add_ref(base: *mut cef_sys::cef_base_ref_counted_t) { 36 | let slf = base as *mut Self; 37 | let count = (*slf) 38 | .ref_count 39 | .fetch_add(1, std::sync::atomic::Ordering::SeqCst); 40 | log::trace!("{}::add_ref, {} -> {}", stringify!(#name), count, count + 1); 41 | } 42 | 43 | pub unsafe extern "C" fn release(base: *mut cef_sys::cef_base_ref_counted_t) -> i32 { 44 | let slf = base as *mut Self; 45 | let count = (*slf) 46 | .ref_count 47 | .fetch_sub(1, std::sync::atomic::Ordering::SeqCst) 48 | - 1; 49 | 50 | if count < 1 { 51 | let slf: Box = Box::from_raw(slf as *mut Self); 52 | log::trace!("{}::release {} -> 0 (dropping!)", stringify!(#name), count + 1); 53 | drop(slf); // not needed, but just to be extra clear 54 | 1 55 | } else { 56 | log::trace!("{}::release, {} -> {}", stringify!(#name), count + 1, count); 57 | 0 58 | } 59 | } 60 | 61 | pub unsafe extern "C" fn has_one_ref(base: *mut cef_sys::cef_base_ref_counted_t) -> i32 { 62 | let slf = base as *mut Self; 63 | let count = (*slf).ref_count.load(std::sync::atomic::Ordering::SeqCst); 64 | log::trace!("{}::has_one_ref ({} -> {:?})", stringify!(#name), count, count == 1); 65 | if count == 1 { 66 | 1 67 | } else { 68 | 0 69 | } 70 | } 71 | 72 | pub unsafe extern "C" fn has_at_least_one_ref(base: *mut cef_sys::cef_base_ref_counted_t) -> i32 { 73 | let slf = base as *mut Self; 74 | let count = (*slf).ref_count.load(std::sync::atomic::Ordering::SeqCst); 75 | log::trace!("{}::has_at_least_one_ref ({} -> {:?})", stringify!(#name), count, count >= 1); 76 | if count >= 1 { 77 | 1 78 | } else { 79 | 0 80 | } 81 | } 82 | } 83 | }; 84 | gen.into() 85 | } 86 | -------------------------------------------------------------------------------- /cef/src/application/browser_process_handler.rs: -------------------------------------------------------------------------------- 1 | use std::mem::size_of; 2 | 3 | use cef_ref_counting::{ref_count, RefCount}; 4 | use cef_sys::{ 5 | cef_base_ref_counted_t, cef_browser_process_handler_t, cef_browser_settings_t, 6 | cef_browser_view_create, cef_browser_view_delegate_t, cef_client_t, 7 | cef_window_create_top_level, cef_window_delegate_t, 8 | }; 9 | 10 | use crate::{ 11 | application::{browser_view_delegate::BrowserViewDelegate, window_delegate::WindowDelegate}, 12 | cef_strings::to_cef_str, 13 | handler::Handler, 14 | }; 15 | 16 | use super::Application; 17 | 18 | #[ref_count] 19 | #[derive(RefCount, Debug)] 20 | #[allow(unused)] 21 | pub struct BrowserProcessHandler { 22 | pub browser_process_handler: cef_browser_process_handler_t, 23 | pub application: *mut Application, 24 | pub handler: Option, 25 | } 26 | 27 | impl BrowserProcessHandler { 28 | pub fn allocate() -> *mut Self { 29 | let browser_process_handler = BrowserProcessHandler { 30 | browser_process_handler: cef_browser_process_handler_t { 31 | base: cef_base_ref_counted_t { 32 | size: size_of::() as u64, 33 | add_ref: Some(Self::add_ref), 34 | release: Some(Self::release), 35 | has_one_ref: Some(Self::has_one_ref), 36 | has_at_least_one_ref: Some(Self::has_at_least_one_ref), 37 | }, 38 | on_context_initialized: Some(Self::on_context_initialized), 39 | get_default_client: Some(Self::get_default_client), 40 | on_before_child_process_launch: None, 41 | on_schedule_message_pump_work: None, 42 | }, 43 | application: std::ptr::null_mut(), 44 | handler: None, 45 | ref_count: 1.into(), 46 | }; 47 | 48 | log::debug!( 49 | "browser_process_handler allocated: {:?}", 50 | browser_process_handler 51 | ); 52 | Box::into_raw(Box::from(browser_process_handler)) 53 | } 54 | 55 | unsafe extern "C" fn on_context_initialized(slf: *mut cef_browser_process_handler_t) { 56 | log::debug!("on_context_initialized"); 57 | let url = to_cef_str("https://google.ca"); 58 | let settings = cef_browser_settings_t::default(); 59 | 60 | let mut handler = Handler::new(); 61 | handler.apply_pointers(); 62 | log::debug!("creating browser_view"); 63 | let browser_view = cef_browser_view_create( 64 | handler.client_ptr(), 65 | &url, 66 | &settings, 67 | std::ptr::null_mut(), 68 | std::ptr::null_mut(), 69 | BrowserViewDelegate::allocate() as *mut cef_browser_view_delegate_t, 70 | ); 71 | 72 | log::debug!("creating top level window with view = {:?}", browser_view); 73 | cef_window_create_top_level( 74 | WindowDelegate::allocate(browser_view) as *mut cef_window_delegate_t 75 | ); 76 | 77 | (*(slf as *mut BrowserProcessHandler)).handler = Some(handler); 78 | (*(slf as *mut BrowserProcessHandler)) 79 | .handler 80 | .as_mut() 81 | .unwrap() 82 | .apply_pointers(); 83 | } 84 | 85 | unsafe extern "C" fn get_default_client( 86 | slf: *mut cef_browser_process_handler_t, 87 | ) -> *mut cef_client_t { 88 | let slf = slf as *mut BrowserProcessHandler; 89 | if let Some(handler) = &(*(slf as *mut BrowserProcessHandler)).handler { 90 | log::debug!("getting default client: {:p}", handler.client_ptr()); 91 | handler.client_ptr() 92 | } else { 93 | log::debug!("getting default client but NULL"); 94 | std::ptr::null_mut() 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /cef/src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::ptr::null_mut; 2 | 3 | use anyhow::{anyhow, Result}; 4 | use application::Application; 5 | use cef_sys::{ 6 | cef_currently_on, cef_enable_highdpi_support, cef_execute_process, cef_initialize, 7 | cef_log_severity_t_LOGSEVERITY_WARNING, cef_main_args_t, cef_run_message_loop, cef_settings_t, 8 | cef_shutdown, cef_thread_id_t_TID_UI, 9 | }; 10 | 11 | mod application; 12 | mod cef_strings; 13 | mod handler; 14 | 15 | pub fn require_ui_thread() { 16 | unsafe { 17 | if cef_currently_on(cef_thread_id_t_TID_UI) == 0 { 18 | log::warn!("Not on UI thread!"); 19 | } 20 | } 21 | } 22 | 23 | #[allow(unused)] 24 | pub struct Cef { 25 | application: Application, 26 | } 27 | 28 | impl Cef { 29 | #[cfg(unix)] 30 | fn main_args() -> (Vec, cef_main_args_t) { 31 | use std::ffi::CString; 32 | use std::os::raw::{c_char, c_int}; 33 | let args: Vec = std::env::args().map(|x| CString::new(x).unwrap()).collect(); 34 | let _args: Vec<*mut c_char> = args.iter().map(|x| x.as_ptr() as *mut c_char).collect(); 35 | ( 36 | args, 37 | cef_main_args_t { 38 | argc: _args.len() as c_int, 39 | argv: _args.as_ptr() as *mut *mut c_char, 40 | }, 41 | ) 42 | } 43 | 44 | #[cfg(windows)] 45 | fn main_args() -> ((), cef_main_args_t) { 46 | ( 47 | (), 48 | cef_main_args_t { 49 | instance: unsafe { 50 | windows::Win32::System::LibraryLoader::GetModuleHandleA(windows::core::PCSTR( 51 | null_mut(), 52 | )) 53 | .0 as *mut cef_sys::HINSTANCE__ 54 | }, 55 | }, 56 | ) 57 | } 58 | 59 | #[cfg(unix)] 60 | fn sandbox() -> *mut ::std::os::raw::c_void { 61 | null_mut() 62 | } 63 | 64 | #[cfg(windows)] 65 | fn sandbox() -> *mut ::std::os::raw::c_void { 66 | unsafe { cef_sys::cef_sandbox_info_create() } 67 | } 68 | 69 | pub fn initialize() -> Result { 70 | unsafe { 71 | cef_enable_highdpi_support(); 72 | } 73 | 74 | let sandbox_info = Self::sandbox(); 75 | let (_args, main_args) = Self::main_args(); 76 | 77 | // CEF applications have multiple sub-processes that share the same exe. Check for a 78 | // subprocess, and exit accordingly 79 | let exit_code = unsafe { cef_execute_process(&main_args, null_mut(), sandbox_info) }; 80 | if exit_code >= 0 { 81 | std::process::exit(exit_code); 82 | } 83 | 84 | let settings = cef_settings_t { 85 | size: std::mem::size_of::() as u64, 86 | no_sandbox: if cfg!(windows) { 0 } else { 1 }, 87 | remote_debugging_port: 8765, 88 | command_line_args_disabled: 0, 89 | log_severity: cef_log_severity_t_LOGSEVERITY_WARNING, 90 | ..Default::default() 91 | }; 92 | 93 | log::debug!("preparing application"); 94 | let mut application = Application::new(); 95 | application.apply_pointers(); 96 | log::debug!("application prepared: {:?}", application); 97 | 98 | log::debug!("initializing"); 99 | unsafe { 100 | if cef_initialize(&main_args, &settings, application.app_ptr(), sandbox_info) != 1 { 101 | return Err(anyhow!("failed to initialize!")); 102 | } 103 | } 104 | 105 | Ok(Cef { application }) 106 | } 107 | 108 | pub fn run(mut self) -> Result<()> { 109 | self.application.apply_pointers(); 110 | unsafe { 111 | log::debug!("running message loop"); 112 | cef_run_message_loop(); 113 | log::debug!("shutting down"); 114 | cef_shutdown(); 115 | } 116 | 117 | Ok(()) 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /cef/src/handler/mod.rs: -------------------------------------------------------------------------------- 1 | use cef_sys::{ 2 | cef_base_ref_counted_t, cef_browser_t, cef_client_t, cef_display_handler_t, 3 | cef_life_span_handler_t, cef_load_handler_t, cef_render_handler_t, 4 | }; 5 | 6 | use self::{ 7 | client::Client, display_handler::DisplayHandler, life_span_handler::LifeSpanHandler, 8 | load_handler::LoadHandler, render_handler::RenderHandler, 9 | }; 10 | 11 | mod client; 12 | mod display_handler; 13 | mod life_span_handler; 14 | mod load_handler; 15 | mod render_handler; 16 | 17 | #[derive(Debug)] 18 | pub struct Handler { 19 | client: *mut Client, 20 | display_handler: *mut DisplayHandler, 21 | life_span_handler: *mut LifeSpanHandler, 22 | load_handler: *mut LoadHandler, 23 | render_handler: *mut RenderHandler, 24 | browsers: Vec<*mut cef_browser_t>, 25 | is_closing: bool, 26 | } 27 | 28 | impl Handler { 29 | pub fn new() -> Handler { 30 | let mut handler = Handler { 31 | client: Client::allocate(), 32 | display_handler: DisplayHandler::allocate(), 33 | life_span_handler: LifeSpanHandler::allocate(), 34 | load_handler: LoadHandler::allocate(), 35 | render_handler: RenderHandler::allocate(), 36 | browsers: Vec::new(), 37 | is_closing: false, 38 | }; 39 | handler.apply_pointers(); 40 | 41 | log::debug!("handler created"); 42 | handler 43 | } 44 | 45 | pub fn apply_pointers(&mut self) { 46 | unsafe { 47 | (*self.client).handler = self; 48 | (*self.display_handler).handler = self; 49 | (*self.life_span_handler).handler = self; 50 | (*self.load_handler).handler = self; 51 | (*self.render_handler).handler = self; 52 | } 53 | } 54 | 55 | pub fn client_ptr(&self) -> *mut cef_client_t { 56 | unsafe { 57 | Client::add_ref(self.client as *mut cef_base_ref_counted_t); 58 | } 59 | self.client as *mut cef_client_t 60 | } 61 | 62 | pub fn display_handler_ptr(&self) -> *mut cef_display_handler_t { 63 | unsafe { 64 | DisplayHandler::add_ref(self.display_handler as *mut cef_base_ref_counted_t); 65 | } 66 | self.display_handler as *mut cef_display_handler_t 67 | } 68 | 69 | pub fn life_span_handler_ptr(&self) -> *mut cef_life_span_handler_t { 70 | unsafe { 71 | LifeSpanHandler::add_ref(self.life_span_handler as *mut cef_base_ref_counted_t); 72 | } 73 | self.life_span_handler as *mut cef_life_span_handler_t 74 | } 75 | 76 | pub fn load_handler_ptr(&self) -> *mut cef_load_handler_t { 77 | unsafe { 78 | LoadHandler::add_ref(self.load_handler as *mut cef_base_ref_counted_t); 79 | } 80 | self.load_handler as *mut cef_load_handler_t 81 | } 82 | 83 | pub fn render_handler_ptr(&self) -> *mut cef_render_handler_t { 84 | unsafe { 85 | RenderHandler::add_ref(self.render_handler as *mut cef_base_ref_counted_t); 86 | } 87 | self.render_handler as *mut cef_render_handler_t 88 | } 89 | } 90 | 91 | impl Drop for Handler { 92 | fn drop(&mut self) { 93 | unsafe { 94 | log::debug!("dropping client"); 95 | let client = self.client as *mut cef_base_ref_counted_t; 96 | while Client::has_at_least_one_ref(client) == 1 { 97 | Client::release(client); 98 | } 99 | 100 | log::debug!("dropping display_handler"); 101 | let display_handler = self.display_handler as *mut cef_base_ref_counted_t; 102 | while DisplayHandler::has_at_least_one_ref(display_handler) == 1 { 103 | DisplayHandler::release(display_handler); 104 | } 105 | 106 | log::debug!("dropping life_span_handler"); 107 | let life_span_handler = self.life_span_handler as *mut cef_base_ref_counted_t; 108 | while LifeSpanHandler::has_at_least_one_ref(life_span_handler) == 1 { 109 | LifeSpanHandler::release(life_span_handler); 110 | } 111 | 112 | log::debug!("dropping load_handler"); 113 | let load_handler = self.load_handler as *mut cef_base_ref_counted_t; 114 | while LoadHandler::has_at_least_one_ref(load_handler) == 1 { 115 | LoadHandler::release(load_handler); 116 | } 117 | 118 | log::debug!("dropping render_handler"); 119 | let render_handler = self.render_handler as *mut cef_base_ref_counted_t; 120 | while RenderHandler::has_at_least_one_ref(render_handler) == 1 { 121 | RenderHandler::release(render_handler); 122 | } 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /cef-sys/build.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | use std::env; 3 | use std::path::PathBuf; 4 | 5 | /*fn download_cef() -> Result<()> { 6 | #[cfg(target_os = "linux")] 7 | let url = "https://cef-builds.spotifycdn.com/cef_binary_97.1.2%2Bgb821dc3%2Bchromium-97.0.4692.71_linux64_minimal.tar.bz2"; 8 | #[cfg(target_os = "linux")] 9 | let filename = "cef_binary_97.1.1+g50067f2+chromium-97.0.4692.71_linux64_minimal.tar.bz2"; 10 | 11 | let path = env::var("CARGO_MANIFEST_DIR").unwrap(); 12 | let path = PathBuf::from(&path).join(filename); 13 | if path.exists() { 14 | return Ok(()); 15 | } 16 | 17 | use curl::easy::Easy; 18 | use std::io::Write; 19 | 20 | let mut handle = Easy::new(); 21 | handle 22 | .progress(true) 23 | .with_context(|| "Failed to enable progress reporting")?; 24 | handle 25 | .url(url) 26 | .with_context(|| format!("Failed to open url {}", url))?; 27 | let mut file = std::fs::File::create(&path) 28 | .with_context(|| format!("Failed to create download file path {}", path.display()))?; 29 | handle 30 | .write_function(move |data| { 31 | file.write_all(data).unwrap(); 32 | Ok(data.len()) 33 | }) 34 | .with_context(|| "Failed to cURL write function")?; 35 | handle 36 | .perform() 37 | .with_context(|| "Failed to initiate download")?; 38 | 39 | Ok(()) 40 | }*/ 41 | 42 | fn main() -> Result<()> { 43 | // make sure we have CEF downloaded 44 | // TODO: check for it being downloaded 45 | //download_cef().with_context(|| "Failed to download CEF!")?; 46 | // instead for now, make sure that cef's include, Release, and Resources folders are placed in the cef-sys directory 47 | 48 | // let us link the proper CEF version depending on what host we're compiling for 49 | let target_os = env::var("TARGET").expect("target"); 50 | let cef_lib_name = match target_os.as_ref() { 51 | "x86_64-pc-windows-msvc" => "libcef", 52 | _ => "cef", 53 | }; 54 | println!("cargo:rustc-link-lib={}", cef_lib_name); 55 | 56 | if cfg!(windows) { 57 | println!("cargo:rustc-link-lib=cef_sandbox"); 58 | println!("cargo:rustc-link-lib=delayimp"); 59 | } 60 | 61 | let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); 62 | let cef_lib_path = PathBuf::from(&manifest_dir).join("Release"); 63 | assert!(cef_lib_path.exists()); 64 | println!("cargo:rustc-link-search={}", cef_lib_path.display()); 65 | 66 | println!("cargo:rerun-if-changed=wrapper.h"); 67 | 68 | let bindings = bindgen::Builder::default() 69 | .header("wrapper.h") 70 | .clang_arg(format!("-I{}", manifest_dir)) 71 | .parse_callbacks(Box::new(bindgen::CargoCallbacks)) 72 | .allowlist_type("cef_main_args_t") 73 | .allowlist_function("cef_execute_process") 74 | .allowlist_type("cef_settings_t") 75 | .allowlist_function("cef_initialize") 76 | .allowlist_function("cef_run_message_loop") 77 | .allowlist_function("cef_shutdown") 78 | .allowlist_type("cef_string_t") 79 | .allowlist_function("cef_string_utf8_to_utf16") 80 | .allowlist_type("cef_base_ref_counted_t") 81 | .allowlist_type("cef_client_t") 82 | .allowlist_type("cef_life_span_handler_t") 83 | .allowlist_type("cef_display_handler_t") 84 | .allowlist_type("cef_browser_t") 85 | .allowlist_function("cef_browser_view_get_for_browser") 86 | .allowlist_function("cef_quit_message_loop") 87 | .allowlist_type("cef_frame_t") 88 | .allowlist_type("cef_load_handler_t") 89 | .allowlist_type("cef_app_t") 90 | .allowlist_type("cef_browser_process_handler_t") 91 | .allowlist_type("cef_browser_settings_t") 92 | .allowlist_type("cef_browser_view_delegate_t") 93 | .allowlist_type("cef_window_delegate_t") 94 | .allowlist_function("cef_browser_view_create") 95 | .allowlist_function("cef_window_create_top_level") 96 | .allowlist_type("cef_window_delegate_t") 97 | .allowlist_type("cef_browser_view_delegate_t") 98 | .allowlist_type("cef_view_delegate_t") 99 | .allowlist_type("cef_panel_delegate_t") 100 | .allowlist_type("cef_size_t") 101 | .allowlist_type("cef_render_handler_t") 102 | .allowlist_type("cef_text_input_mode_t") 103 | .allowlist_function("cef_enable_highdpi_support") 104 | .allowlist_function("cef_currently_on") 105 | .allowlist_type("cef_thread_id_t") 106 | .derive_default(true); 107 | 108 | let bindings = if cfg!(windows) { 109 | bindings 110 | .header("wrapper-win.h") 111 | .allowlist_function("cef_sandbox_info_create") 112 | .allowlist_function("cef_sandbox_info_destroy") 113 | } else { 114 | bindings 115 | }; 116 | let bindings = bindings.generate().expect("Can generate CAPI bindings"); 117 | 118 | let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); 119 | bindings 120 | .write_to_file(out_path.join("cef_bindings.rs")) 121 | .expect("Can write bindings"); 122 | 123 | Ok(()) 124 | } 125 | -------------------------------------------------------------------------------- /cef/src/application/window_delegate.rs: -------------------------------------------------------------------------------- 1 | use cef_ref_counting::{ref_count, RefCount}; 2 | use cef_sys::{ 3 | cef_base_ref_counted_t, cef_browser_view_t, cef_panel_delegate_t, cef_size_t, 4 | cef_view_delegate_t, cef_view_t, cef_window_delegate_t, cef_window_t, 5 | }; 6 | 7 | #[ref_count] 8 | #[derive(RefCount, Debug)] 9 | #[allow(unused)] 10 | pub struct WindowDelegate { 11 | pub window_delegate: cef_window_delegate_t, 12 | browser_view: *mut cef_browser_view_t, 13 | } 14 | 15 | impl WindowDelegate { 16 | pub fn allocate(browser_view: *mut cef_browser_view_t) -> *mut Self { 17 | log::debug!( 18 | "allocating window delegate with browser view = {:p}", 19 | browser_view 20 | ); 21 | let window_delegate = WindowDelegate { 22 | window_delegate: cef_window_delegate_t { 23 | base: cef_panel_delegate_t { 24 | base: cef_view_delegate_t { 25 | base: cef_base_ref_counted_t { 26 | size: std::mem::size_of::() as u64, 27 | add_ref: Some(Self::add_ref), 28 | release: Some(Self::release), 29 | has_one_ref: Some(Self::has_one_ref), 30 | has_at_least_one_ref: Some(Self::has_at_least_one_ref), 31 | }, 32 | get_preferred_size: Some(Self::get_preferred_size), 33 | get_minimum_size: None, 34 | get_maximum_size: None, 35 | get_height_for_width: None, 36 | on_parent_view_changed: None, 37 | on_child_view_changed: None, 38 | on_focus: None, 39 | on_blur: None, 40 | on_window_changed: None, 41 | on_layout_changed: None, 42 | }, 43 | }, 44 | on_window_created: Some(Self::on_window_created), 45 | on_window_destroyed: Some(Self::on_window_destroyed), 46 | get_parent_window: None, 47 | is_frameless: None, 48 | can_resize: None, 49 | can_maximize: None, 50 | can_minimize: None, 51 | can_close: Some(Self::can_close), 52 | on_accelerator: None, 53 | on_key_event: None, 54 | get_initial_bounds: None, 55 | get_initial_show_state: None, 56 | }, 57 | browser_view, 58 | ref_count: 1.into(), 59 | }; 60 | 61 | log::debug!("window_delegate allocated"); 62 | Box::into_raw(Box::from(window_delegate)) 63 | } 64 | 65 | unsafe extern "C" fn on_window_created( 66 | slf: *mut cef_window_delegate_t, 67 | window: *mut cef_window_t, 68 | ) { 69 | log::debug!("on_window_created, adding child view"); 70 | let slf = slf as *mut WindowDelegate; 71 | ((*window).base).add_child_view.unwrap()( 72 | &mut (*window).base, 73 | &mut (*((*slf).browser_view)).base, 74 | ); 75 | log::debug!("showing window"); 76 | (*window).show.unwrap()(window); 77 | 78 | //log::debug!("focussing window"); 79 | //(*((*slf).browser_view)).base.request_focus.unwrap()(&mut (*((*slf).browser_view)).base); 80 | } 81 | 82 | unsafe extern "C" fn on_window_destroyed( 83 | slf: *mut cef_window_delegate_t, 84 | _window: *mut cef_window_t, 85 | ) { 86 | log::debug!("on_window_destroyed"); 87 | (*(slf as *mut WindowDelegate)).browser_view = std::ptr::null_mut(); 88 | } 89 | 90 | unsafe extern "C" fn get_preferred_size( 91 | _: *mut cef_view_delegate_t, 92 | _view: *mut cef_view_t, 93 | ) -> cef_size_t { 94 | log::debug!("getting preferred size (800x600)"); 95 | cef_size_t { 96 | width: 800, 97 | height: 600, 98 | } 99 | } 100 | 101 | unsafe extern "C" fn can_close( 102 | slf: *mut cef_window_delegate_t, 103 | _window: *mut cef_window_t, 104 | ) -> i32 { 105 | log::debug!("can_close"); 106 | 107 | let slf = slf as *mut WindowDelegate; 108 | log::debug!("slf: {:?}", *slf); 109 | let browser_view = (*slf).browser_view; 110 | if browser_view as usize != 0 { 111 | let get_browser = (*browser_view).get_browser; 112 | log::debug!("get_browser = {:?}", get_browser); 113 | if let Some(get_browser) = get_browser { 114 | let browser = get_browser(browser_view); 115 | log::debug!("browser = {:?}", browser); 116 | if browser as usize != 0 { 117 | log::debug!("trying to close browser"); 118 | let get_host = (*browser).get_host; 119 | log::debug!("get_host = {:?}", get_host); 120 | if let Some(get_host) = get_host { 121 | let host = get_host(browser); 122 | log::debug!("host = {:?}", host); 123 | if host as usize != 0 { 124 | let try_close_browser = (*host).try_close_browser; 125 | log::debug!("try_close_browser = {:?}", try_close_browser); 126 | if let Some(try_close_browser) = try_close_browser { 127 | try_close_browser(host); 128 | } 129 | } 130 | } 131 | } else { 132 | log::debug!("can't close browser, there isn't one"); 133 | } 134 | } else { 135 | log::debug!("get_browser is null?!"); 136 | } 137 | } else { 138 | log::warn!("browser view is null?!"); 139 | } 140 | 1 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | --------------------------------------------------------------------------------