feat: add Gelectron compatibility layer for Electron modules

- Introduced contextBridge module for exposing APIs to the main world.
- Added dialog module for handling open, save, and message dialogs.
- Created index module as a drop-in replacement for Electron's main API.
- Implemented ipcMain and ipcRenderer modules for inter-process communication.
- Developed menu and menu item modules for creating application menus.
- Added nativeImage module for handling images in various formats.
- Implemented notification module for displaying system notifications.
- Created preload-loader for injecting preload scripts into the renderer process.
- Developed runtime module for running Electron apps in a Node.js environment.
- Added safe-storage module for basic string encryption and decryption.
- Implemented shell module for opening external URLs and managing file paths.
- Created tray module for managing system tray icons and menus.
- Developed webContents utilities for interacting with browser windows.
This commit is contained in:
miles committed 2026-07-26 17:12:47 -05:00
1 parent 4af8378d72
commit 86c19b0012
39 files changed
+4687 -2

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
[package]
name = "gelectron-core"
version = "0.1.0"
edition = "2021"
description = "Gelectron native core - Servo-based Electron replacement"
license = "MIT"
authors = ["mileswa1q22"]
[lib]
crate-type = ["cdylib", "staticlib"]
[dependencies]
napi = { workspace = true }
napi-derive = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
url = { workspace = true }
log = { workspace = true }
env_logger = { workspace = true }
# Window management
winit = { version = "0.30", features = ["rwh_06"] }
raw-window-handle = "0.6"
# Native UI
muda = "0.15"
tray-icon = "0.19"
rfd = "0.15"
notify-rust = "4"
# Image handling
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
# Encryption / secure storage
keyring = { version = "3", features = ["apple-native", "sync-secret-service", "windows-native"] }
# Misc
base64 = "0.22"
dirs = "5"
uuid = { version = "1", features = ["v4"] }
once_cell = "1"
open = "5"
sys-locale = "0.3"
[build-dependencies]
napi-build = "2"
+3
View File
@@ -0,0 +1,3 @@
fn main() {
napi_build::setup();
}
+179
View File
@@ -0,0 +1,179 @@
use napi::bindgen_prelude::*;
use napi_derive::napi;
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
use crate::event_loop::EventLoopBridge;
use crate::ipc::IpcManager;
use crate::servo_host::ServoHost;
#[allow(unused_imports)]
use napi::JsFunction;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfig {
pub main_script: String,
pub app_path: String,
pub user_data_dir: Option<String>,
pub dev_mode: bool,
}
pub struct AppState {
pub config: AppConfig,
pub servo: Option<ServoHost>,
pub ipc: Arc<Mutex<IpcManager>>,
pub event_loop: Arc<EventLoopBridge>,
pub ready: bool,
}
static APP_STATE: std::sync::OnceLock<Mutex<Option<AppState>>> = std::sync::OnceLock::new();
fn get_app_state() -> &'static Mutex<Option<AppState>> {
APP_STATE.get_or_init(|| Mutex::new(None))
}
#[napi(object)]
pub struct AppPaths {
pub home: String,
pub app_data: String,
pub user_data: String,
pub desktop: String,
pub documents: String,
pub downloads: String,
pub temp: String,
}
#[napi]
pub fn app_init(config_json: String) -> Result<()> {
let config: AppConfig =
serde_json::from_str(&config_json).map_err(|e| Error::from_reason(e.to_string()))?;
let state = AppState {
servo: None,
ipc: Arc::new(Mutex::new(IpcManager::new())),
event_loop: Arc::new(EventLoopBridge::new()),
ready: false,
config,
};
let mut lock = get_app_state()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
*lock = Some(state);
log::info!("App initialized: main={}", lock.as_ref().unwrap().config.main_script);
Ok(())
}
#[napi]
pub fn app_get_paths() -> Result<AppPaths> {
Ok(AppPaths {
home: dirs::home_dir()
.unwrap_or_default()
.to_string_lossy()
.to_string(),
app_data: dirs::data_dir()
.unwrap_or_default()
.to_string_lossy()
.to_string(),
user_data: dirs::data_local_dir()
.unwrap_or_default()
.to_string_lossy()
.to_string(),
desktop: dirs::desktop_dir()
.unwrap_or_default()
.to_string_lossy()
.to_string(),
documents: dirs::document_dir()
.unwrap_or_default()
.to_string_lossy()
.to_string(),
downloads: dirs::download_dir()
.unwrap_or_default()
.to_string_lossy()
.to_string(),
temp: std::env::temp_dir().to_string_lossy().to_string(),
})
}
#[napi]
pub fn app_get_version() -> String {
env!("CARGO_PKG_VERSION").to_string()
}
#[napi]
pub fn app_get_name() -> String {
"gelectron".to_string()
}
#[napi]
pub fn app_get_locale() -> String {
sys_locale::get_locale().unwrap_or_else(|| "en-US".to_string())
}
#[napi]
pub fn app_get_user_agent() -> String {
format!(
"Gelectron/{} (Servo; {} {})",
env!("CARGO_PKG_VERSION"),
std::env::consts::OS,
std::env::consts::ARCH
)
}
#[napi]
pub fn app_quit() {
log::info!("App quit requested");
let lock = get_app_state().lock();
if let Ok(mut guard) = lock {
*guard = None;
}
std::process::exit(0);
}
#[napi]
pub fn app_is_ready() -> bool {
get_app_state()
.lock()
.ok()
.and_then(|guard| guard.as_ref().map(|s| s.ready))
.unwrap_or(false)
}
#[napi]
pub fn app_set_ready() {
if let Ok(mut guard) = get_app_state().lock() {
if let Some(ref mut state) = *guard {
state.ready = true;
}
}
}
#[napi]
pub fn app_on_event(event_name: String, callback: JsFunction) -> Result<()> {
crate::event_loop::register_app_event(&event_name, callback)
}
#[napi]
pub fn app_emit_event(event_name: String, args_json: Option<String>) {
crate::event_loop::emit_app_event(&event_name, args_json);
}
#[napi]
pub fn app_get_command_line_args() -> Vec<String> {
std::env::args().collect()
}
#[napi]
pub fn app_get_switch(switch_name: String) -> Option<String> {
let args: Vec<String> = std::env::args().collect();
for i in 0..args.len() {
if args[i] == format!("--{}", switch_name) {
return args.get(i + 1).cloned();
}
if args[i].starts_with(&format!("--{}=", switch_name)) {
return Some(args[i][switch_name.len() + 3..].to_string());
}
}
None
}
+513
View File
@@ -0,0 +1,513 @@
use napi::bindgen_prelude::*;
use napi::threadsafe_function::{ErrorStrategy, ThreadsafeFunction, ThreadsafeFunctionCallMode};
use napi_derive::napi;
use serde::{Deserialize, Serialize};
use std::sync::Mutex;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WindowOptions {
pub width: Option<u32>,
pub height: Option<u32>,
pub min_width: Option<u32>,
pub min_height: Option<u32>,
pub max_width: Option<u32>,
pub max_height: Option<u32>,
pub title: Option<String>,
pub url: Option<String>,
pub frame: Option<bool>,
pub show: Option<bool>,
pub resizable: Option<bool>,
pub minimizable: Option<bool>,
pub maximizable: Option<bool>,
pub closable: Option<bool>,
pub fullscreen: Option<bool>,
pub always_on_top: Option<bool>,
pub transparent: Option<bool>,
pub decorations: Option<bool>,
pub background_color: Option<String>,
pub icon: Option<String>,
pub preload: Option<String>,
pub context_isolation: Option<bool>,
pub node_integration: Option<bool>,
pub sandbox: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebPreferences {
pub preload: Option<String>,
pub context_isolation: Option<bool>,
pub node_integration: Option<bool>,
pub sandbox: Option<bool>,
pub dev_tools: Option<bool>,
pub web_security: Option<bool>,
pub allow_running_insecure_content: Option<bool>,
pub experimental_features: Option<bool>,
}
pub struct BrowserWindowState {
pub id: u32,
pub title: String,
pub width: u32,
pub height: u32,
pub url: String,
pub is_visible: bool,
pub is_minimized: bool,
pub is_maximized: bool,
pub is_fullscreen: bool,
pub is_closed: bool,
pub web_preferences: WebPreferences,
pub event_callback: Option<ThreadsafeFunction<String, ErrorStrategy::Fatal>>,
}
static WINDOW_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
static WINDOWS: once_cell::sync::Lazy<Mutex<Vec<BrowserWindowState>>> =
once_cell::sync::Lazy::new(|| Mutex::new(Vec::new()));
fn next_window_id() -> u32 {
WINDOW_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
}
#[napi(object)]
pub struct WindowInfo {
pub id: u32,
pub title: String,
pub width: u32,
pub height: u32,
pub url: String,
pub is_visible: bool,
pub is_minimized: bool,
pub is_maximized: bool,
pub is_fullscreen: bool,
}
#[napi]
pub fn window_create(options_json: String) -> Result<u32> {
let opts: WindowOptions =
serde_json::from_str(&options_json).map_err(|e| Error::from_reason(e.to_string()))?;
let id = next_window_id();
let state = BrowserWindowState {
id,
title: opts.title.unwrap_or_else(|| "Gelectron".to_string()),
width: opts.width.unwrap_or(800),
height: opts.height.unwrap_or(600),
url: opts.url.unwrap_or_else(|| "about:blank".to_string()),
is_visible: opts.show.unwrap_or(true),
is_minimized: false,
is_maximized: false,
is_fullscreen: opts.fullscreen.unwrap_or(false),
is_closed: false,
web_preferences: WebPreferences {
preload: opts.preload,
context_isolation: opts.context_isolation.or(Some(true)),
node_integration: opts.node_integration.or(Some(false)),
sandbox: opts.sandbox.or(Some(false)),
dev_tools: Some(true),
web_security: Some(true),
allow_running_insecure_content: Some(false),
experimental_features: Some(false),
},
event_callback: None,
};
WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?
.push(state);
log::info!("Window {} created", id);
Ok(id)
}
#[napi]
pub fn window_destroy(window_id: u32) -> Result<()> {
let mut windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(win) = windows.iter_mut().find(|w| w.id == window_id) {
win.is_closed = true;
log::info!("Window {} destroyed", window_id);
}
Ok(())
}
#[napi]
pub fn window_show(window_id: u32) -> Result<()> {
let mut windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(win) = windows.iter_mut().find(|w| w.id == window_id) {
win.is_visible = true;
win.is_minimized = false;
}
Ok(())
}
#[napi]
pub fn window_hide(window_id: u32) -> Result<()> {
let mut windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(win) = windows.iter_mut().find(|w| w.id == window_id) {
win.is_visible = false;
}
Ok(())
}
#[napi]
pub fn window_focus(window_id: u32) -> Result<()> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(_win) = windows.iter().find(|w| w.id == window_id) {
log::info!("Window {} focused", window_id);
}
Ok(())
}
#[napi]
pub fn window_minimize(window_id: u32) -> Result<()> {
let mut windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(win) = windows.iter_mut().find(|w| w.id == window_id) {
win.is_minimized = true;
}
Ok(())
}
#[napi]
pub fn window_maximize(window_id: u32) -> Result<()> {
let mut windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(win) = windows.iter_mut().find(|w| w.id == window_id) {
win.is_maximized = !win.is_maximized;
}
Ok(())
}
#[napi]
pub fn window_unmaximize(window_id: u32) -> Result<()> {
let mut windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(win) = windows.iter_mut().find(|w| w.id == window_id) {
win.is_maximized = false;
}
Ok(())
}
#[napi]
pub fn window_restore(window_id: u32) -> Result<()> {
let mut windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(win) = windows.iter_mut().find(|w| w.id == window_id) {
win.is_minimized = false;
win.is_maximized = false;
}
Ok(())
}
#[napi]
pub fn window_set_fullscreen(window_id: u32, fullscreen: bool) -> Result<()> {
let mut windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(win) = windows.iter_mut().find(|w| w.id == window_id) {
win.is_fullscreen = fullscreen;
}
Ok(())
}
#[napi]
pub fn window_is_minimized(window_id: u32) -> Result<bool> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
Ok(windows
.iter()
.find(|w| w.id == window_id)
.map(|w| w.is_minimized)
.unwrap_or(false))
}
#[napi]
pub fn window_is_maximized(window_id: u32) -> Result<bool> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
Ok(windows
.iter()
.find(|w| w.id == window_id)
.map(|w| w.is_maximized)
.unwrap_or(false))
}
#[napi]
pub fn window_is_fullscreen(window_id: u32) -> Result<bool> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
Ok(windows
.iter()
.find(|w| w.id == window_id)
.map(|w| w.is_fullscreen)
.unwrap_or(false))
}
#[napi]
pub fn window_set_title(window_id: u32, title: String) -> Result<()> {
let mut windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(win) = windows.iter_mut().find(|w| w.id == window_id) {
win.title = title;
}
Ok(())
}
#[napi]
pub fn window_get_title(window_id: u32) -> Result<String> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
Ok(windows
.iter()
.find(|w| w.id == window_id)
.map(|w| w.title.clone())
.unwrap_or_default())
}
#[napi]
pub fn window_set_size(window_id: u32, width: u32, height: u32) -> Result<()> {
let mut windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(win) = windows.iter_mut().find(|w| w.id == window_id) {
win.width = width;
win.height = height;
}
Ok(())
}
#[napi]
pub fn window_get_size(window_id: u32) -> Result<Vec<u32>> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
Ok(windows
.iter()
.find(|w| w.id == window_id)
.map(|w| vec![w.width, w.height])
.unwrap_or_else(|| vec![0, 0]))
}
#[napi]
pub fn window_load_url(window_id: u32, url: String) -> Result<()> {
let mut windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(win) = windows.iter_mut().find(|w| w.id == window_id) {
win.url = url.clone();
log::info!("Window {} navigating to {}", window_id, url);
}
Ok(())
}
#[napi]
pub fn window_get_url(window_id: u32) -> Result<String> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
Ok(windows
.iter()
.find(|w| w.id == window_id)
.map(|w| w.url.clone())
.unwrap_or_default())
}
#[napi]
pub fn window_reload(window_id: u32) -> Result<()> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(_win) = windows.iter().find(|w| w.id == window_id) {
log::info!("Window {} reloading", window_id);
}
Ok(())
}
#[napi]
pub fn window_close(window_id: u32) -> Result<()> {
let mut windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(win) = windows.iter_mut().find(|w| w.id == window_id) {
win.is_closed = true;
win.is_visible = false;
log::info!("Window {} closed", window_id);
}
Ok(())
}
#[napi]
pub fn window_get_all_windows() -> Result<Vec<WindowInfo>> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
Ok(windows
.iter()
.filter(|w| !w.is_closed)
.map(|w| WindowInfo {
id: w.id,
title: w.title.clone(),
width: w.width,
height: w.height,
url: w.url.clone(),
is_visible: w.is_visible,
is_minimized: w.is_minimized,
is_maximized: w.is_maximized,
is_fullscreen: w.is_fullscreen,
})
.collect())
}
#[napi]
pub fn window_is_closed(window_id: u32) -> Result<bool> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
Ok(windows
.iter()
.find(|w| w.id == window_id)
.map(|w| w.is_closed)
.unwrap_or(true))
}
#[napi]
pub fn window_set_always_on_top(window_id: u32, always_on_top: bool) -> Result<()> {
let mut windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(_win) = windows.iter_mut().find(|w| w.id == window_id) {
log::info!("Window {} always_on_top={}", window_id, always_on_top);
}
Ok(())
}
#[napi]
pub fn window_center(window_id: u32) -> Result<()> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(_win) = windows.iter().find(|w| w.id == window_id) {
log::info!("Window {} centered", window_id);
}
Ok(())
}
#[napi]
pub fn window_set_resizable(window_id: u32, resizable: bool) -> Result<()> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(_win) = windows.iter().find(|w| w.id == window_id) {
log::debug!("Window {} resizable={}", window_id, resizable);
}
Ok(())
}
#[napi]
pub fn window_web_contents_send(window_id: u32, channel: String, data_json: Option<String>) -> Result<()> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(win) = windows.iter().find(|w| w.id == window_id && !w.is_closed) {
let message = serde_json::json!({
"channel": channel,
"data": data_json.and_then(|d| serde_json::from_str::<serde_json::Value>(&d).ok()),
})
.to_string();
if let Some(ref callback) = win.event_callback {
callback.call(message, ThreadsafeFunctionCallMode::NonBlocking);
} else {
log::warn!("No event callback set for window {}, cannot send to renderer", window_id);
}
}
Ok(())
}
#[napi]
pub fn window_set_event_callback(
window_id: u32,
callback: JsFunction,
) -> Result<()> {
let tsfn: ThreadsafeFunction<String, ErrorStrategy::Fatal> = callback
.create_threadsafe_function(0, |ctx: napi::threadsafe_function::ThreadSafeCallContext<String>| {
let value = ctx.value.clone();
Ok(vec![ctx.env.create_string_from_std(value)?])
})?;
let mut windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(win) = windows.iter_mut().find(|w| w.id == window_id) {
win.event_callback = Some(tsfn);
}
Ok(())
}
#[napi]
pub fn window_open_devtools(window_id: u32) -> Result<()> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(_win) = windows.iter().find(|w| w.id == window_id) {
log::info!("Window {} devtools opened", window_id);
}
Ok(())
}
#[napi]
pub fn window_close_devtools(window_id: u32) -> Result<()> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(_win) = windows.iter().find(|w| w.id == window_id) {
log::info!("Window {} devtools closed", window_id);
}
Ok(())
}
#[napi]
pub fn window_is_devtools_open(_window_id: u32) -> Result<bool> {
let _windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
Ok(false)
}
#[napi]
pub fn window_execute_javascript(window_id: u32, script: String) -> Result<String> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(_win) = windows.iter().find(|w| w.id == window_id && !w.is_closed) {
log::debug!("Window {} executing JS: {}", window_id, &script[..script.len().min(100)]);
}
Ok(String::new())
}
#[napi]
pub fn window_insert_css(window_id: u32, _css: String) -> Result<()> {
let windows = WINDOWS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(_win) = windows.iter().find(|w| w.id == window_id && !w.is_closed) {
log::debug!("Window {} inserting CSS", window_id);
}
Ok(())
}
@@ -0,0 +1,83 @@
use napi::bindgen_prelude::*;
use napi_derive::napi;
use std::sync::{Mutex, OnceLock};
struct ExposedWorld {
key: String,
api_json: String,
}
static EXPOSED_WORLDS: OnceLock<Mutex<Vec<ExposedWorld>>> = OnceLock::new();
fn get_exposed_worlds() -> &'static Mutex<Vec<ExposedWorld>> {
EXPOSED_WORLDS.get_or_init(|| Mutex::new(Vec::new()))
}
#[napi]
pub fn context_bridge_expose_in_main_world(key: String, api_json: String) -> Result<()> {
let mut worlds = get_exposed_worlds()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
// Remove existing entry for this key
worlds.retain(|w| w.key != key);
worlds.push(ExposedWorld {
key: key.clone(),
api_json: api_json.clone(),
});
log::info!("contextBridge exposed '{}' to main world", key);
// Generate the injection script
let script = format!(
r#"
if (typeof window.{key} === 'undefined') {{
window.__gelectron_api = window.__gelectron_api || {{}};
window.__gelectron_api['{key}'] = {api_json};
}}
"#,
key = key,
api_json = api_json,
);
log::debug!("Context bridge injection script generated ({} bytes)", script.len());
Ok(())
}
#[napi]
pub fn context_bridge_get_exposed_apis() -> Result<String> {
let worlds = get_exposed_worlds()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
let apis: Vec<serde_json::Value> = worlds
.iter()
.map(|w| {
serde_json::json!({
"key": w.key,
"api": serde_json::from_str::<serde_json::Value>(&w.api_json).unwrap_or(serde_json::Value::Null),
})
})
.collect();
serde_json::to_string(&apis).map_err(|e| Error::from_reason(e.to_string()))
}
#[napi]
pub fn context_bridge_generate_injection_script() -> String {
let worlds = get_exposed_worlds().lock().unwrap();
let mut script = String::from("(function() {\n");
script.push_str(" if (typeof window.__gelectron_api === 'undefined') {\n");
script.push_str(" window.__gelectron_api = {};\n");
script.push_str(" }\n");
for world in worlds.iter() {
script.push_str(&format!(
" window.__gelectron_api['{}'] = {};\n",
world.key, world.api_json
));
}
script.push_str("})();\n");
script
}
+200
View File
@@ -0,0 +1,200 @@
use napi::bindgen_prelude::*;
use napi_derive::napi;
#[napi(object)]
pub struct OpenDialogResult {
pub canceled: bool,
pub file_paths: Vec<String>,
}
#[napi(object)]
pub struct SaveDialogResult {
pub canceled: bool,
pub file_path: Option<String>,
}
#[napi(object)]
pub struct MessageBoxResult {
pub response: i32,
pub checkbox_checked: bool,
}
#[napi]
pub fn dialog_show_open_dialog(
_window_id: Option<u32>,
options_json: Option<String>,
) -> Result<OpenDialogResult> {
let mut builder = rfd::FileDialog::new();
if let Some(opts_json) = options_json {
if let Ok(opts) = serde_json::from_str::<serde_json::Value>(&opts_json) {
if let Some(title) = opts.get("title").and_then(|v| v.as_str()) {
builder = builder.set_title(title);
}
if let Some(dir) = opts.get("defaultPath").and_then(|v| v.as_str()) {
builder = builder.set_directory(dir);
}
if let Some(filters) = opts.get("filters").and_then(|v| v.as_array()) {
for filter in filters {
let name = filter
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("Files");
let exts: Vec<&str> = filter
.get("extensions")
.and_then(|v| v.as_array())
.map(|arr| arr.iter().filter_map(|e| e.as_str()).collect())
.unwrap_or_default();
builder = builder.add_filter(name, &exts);
}
}
}
}
let result = builder.pick_files();
match result {
Some(paths) => Ok(OpenDialogResult {
canceled: false,
file_paths: paths
.iter()
.map(|p| p.to_string_lossy().to_string())
.collect(),
}),
None => Ok(OpenDialogResult {
canceled: true,
file_paths: vec![],
}),
}
}
#[napi]
pub fn dialog_show_save_dialog(
_window_id: Option<u32>,
options_json: Option<String>,
) -> Result<SaveDialogResult> {
let mut builder = rfd::FileDialog::new();
if let Some(opts_json) = options_json {
if let Ok(opts) = serde_json::from_str::<serde_json::Value>(&opts_json) {
if let Some(title) = opts.get("title").and_then(|v| v.as_str()) {
builder = builder.set_title(title);
}
if let Some(name) = opts.get("defaultPath").and_then(|v| v.as_str()) {
if let Some(parent) = std::path::Path::new(name).parent() {
builder = builder.set_directory(parent);
}
if let Some(file_name) = std::path::Path::new(name).file_name() {
builder =
builder.set_file_name(file_name.to_string_lossy().to_string().as_str());
}
}
if let Some(filters) = opts.get("filters").and_then(|v| v.as_array()) {
for filter in filters {
let name = filter
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("Files");
let exts: Vec<&str> = filter
.get("extensions")
.and_then(|v| v.as_array())
.map(|arr| arr.iter().filter_map(|e| e.as_str()).collect())
.unwrap_or_default();
builder = builder.add_filter(name, &exts);
}
}
}
}
let result = builder.save_file();
match result {
Some(path) => Ok(SaveDialogResult {
canceled: false,
file_path: Some(path.to_string_lossy().to_string()),
}),
None => Ok(SaveDialogResult {
canceled: true,
file_path: None,
}),
}
}
#[napi]
pub fn dialog_show_message_box(
_window_id: Option<u32>,
options_json: Option<String>,
) -> Result<MessageBoxResult> {
let opts: serde_json::Value = options_json
.and_then(|j| serde_json::from_str(&j).ok())
.unwrap_or(serde_json::Value::Null);
let title = opts
.get("title")
.and_then(|v| v.as_str())
.unwrap_or("Gelectron");
let message = opts
.get("message")
.and_then(|v| v.as_str())
.unwrap_or("");
let detail = opts.get("detail").and_then(|v| v.as_str()).unwrap_or("");
let kind = match opts
.get("type")
.and_then(|v| v.as_str())
.unwrap_or("info")
{
"error" => rfd::MessageLevel::Error,
"warning" => rfd::MessageLevel::Warning,
_ => rfd::MessageLevel::Info,
};
let description = if detail.is_empty() {
message.to_string()
} else {
format!("{}\n{}", message, detail)
};
let builder = rfd::MessageDialog::new()
.set_title(title)
.set_description(&description)
.set_level(kind)
.set_buttons(rfd::MessageButtons::Ok);
let result = builder.show();
let response = match result {
rfd::MessageDialogResult::Ok => 0,
rfd::MessageDialogResult::Cancel => 1,
rfd::MessageDialogResult::Yes => 0,
rfd::MessageDialogResult::No => 1,
rfd::MessageDialogResult::Custom(_) => 2,
};
Ok(MessageBoxResult {
response,
checkbox_checked: false,
})
}
#[napi]
pub fn dialog_show_error_box(title: String, content: String) {
rfd::MessageDialog::new()
.set_title(&title)
.set_description(&content)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
#[napi]
pub fn dialog_show_question_box(title: String, message: String) -> Result<bool> {
let result = rfd::MessageDialog::new()
.set_title(&title)
.set_description(&message)
.set_level(rfd::MessageLevel::Info)
.set_buttons(rfd::MessageButtons::YesNo)
.show();
Ok(matches!(result, rfd::MessageDialogResult::Yes))
}
+91
View File
@@ -0,0 +1,91 @@
use napi::bindgen_prelude::*;
use napi::threadsafe_function::{ErrorStrategy, ThreadsafeFunction, ThreadsafeFunctionCallMode};
use napi_derive::napi;
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
static EVENT_BRIDGE: OnceLock<Arc<EventLoopBridge>> = OnceLock::new();
use std::sync::Arc;
pub struct EventLoopBridge {
pub app_events: Mutex<HashMap<String, Vec<ThreadsafeFunction<String, ErrorStrategy::Fatal>>>>,
}
impl EventLoopBridge {
pub fn new() -> Self {
Self {
app_events: Mutex::new(HashMap::new()),
}
}
}
pub fn get_event_bridge() -> Arc<EventLoopBridge> {
EVENT_BRIDGE
.get_or_init(|| Arc::new(EventLoopBridge::new()))
.clone()
}
pub fn register_app_event(event_name: &str, callback: JsFunction) -> Result<()> {
let tsfn: ThreadsafeFunction<String, ErrorStrategy::Fatal> = callback
.create_threadsafe_function(0, |ctx: napi::threadsafe_function::ThreadSafeCallContext<String>| {
let value = ctx.value.clone();
Ok(vec![ctx.env.create_string_from_std(value)?])
})?;
let bridge = get_event_bridge();
let mut events = bridge
.app_events
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
events
.entry(event_name.to_string())
.or_insert_with(Vec::new)
.push(tsfn);
Ok(())
}
pub fn emit_app_event(event_name: &str, args_json: Option<String>) {
let bridge = get_event_bridge();
let events = bridge.app_events.lock().unwrap();
if let Some(callbacks) = events.get(event_name) {
let data = args_json.unwrap_or_else(|| "null".to_string());
for cb in callbacks {
cb.call(data.clone(), ThreadsafeFunctionCallMode::NonBlocking);
}
}
}
#[napi]
pub fn event_loop_pump() {
// Called from Node.js event loop via setImmediate
// Pumps Servo's event loop if active
}
#[napi]
pub fn event_loop_wake() {
// Wake the event loop (called from background threads)
}
#[napi]
pub fn event_loop_set_interval(callback: JsFunction, interval_ms: u32) -> Result<i64> {
let tsfn: ThreadsafeFunction<String, ErrorStrategy::Fatal> = callback
.create_threadsafe_function(0, |ctx: napi::threadsafe_function::ThreadSafeCallContext<String>| {
let value = ctx.value.clone();
Ok(vec![ctx.env.create_string_from_std(value)?])
})?;
let id = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as i64;
let interval = std::time::Duration::from_millis(interval_ms as u64);
std::thread::spawn(move || loop {
std::thread::sleep(interval);
tsfn.call("tick".to_string(), ThreadsafeFunctionCallMode::NonBlocking);
});
Ok(id)
}
+198
View File
@@ -0,0 +1,198 @@
use napi::bindgen_prelude::*;
use napi_derive::napi;
use std::collections::HashMap;
use std::sync::Mutex;
static REGISTERED_CHANNELS: once_cell::sync::Lazy<Mutex<HashMap<String, bool>>> =
once_cell::sync::Lazy::new(|| Mutex::new(HashMap::new()));
static IPC_LISTENERS: once_cell::sync::Lazy<Mutex<HashMap<String, Vec<IpcListener>>>> =
once_cell::sync::Lazy::new(|| Mutex::new(HashMap::new()));
#[derive(Clone, Debug)]
struct IpcListener {
id: u32,
channel: String,
}
static LISTENER_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
pub struct IpcManager {
pub handlers: HashMap<String, bool>,
}
impl IpcManager {
pub fn new() -> Self {
Self {
handlers: HashMap::new(),
}
}
}
// --- ipcMain API ---
#[napi]
pub fn ipc_main_handle(channel: String, _callback: JsFunction) -> Result<()> {
let mut channels = REGISTERED_CHANNELS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
channels.insert(channel.clone(), true);
log::debug!("ipcMain.handle registered for channel: {}", channel);
Ok(())
}
#[napi]
pub fn ipc_main_on(channel: String, _callback: JsFunction) -> Result<i64> {
let id = LISTENER_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let mut listeners = IPC_LISTENERS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
log::debug!("ipcMain.on registered for channel: {}", &channel);
listeners
.entry(channel.clone())
.or_insert_with(Vec::new)
.push(IpcListener { id, channel });
Ok(id as i64)
}
#[napi]
pub fn ipc_main_remove_listener(channel: String, listener_id: i64) -> Result<()> {
let mut listeners = IPC_LISTENERS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(channel_listeners) = listeners.get_mut(&channel) {
channel_listeners.retain(|l| l.id as i64 != listener_id);
}
Ok(())
}
#[napi]
pub fn ipc_main_remove_all_listeners(channel: Option<String>) -> Result<()> {
let mut listeners = IPC_LISTENERS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
match channel {
Some(ch) => {
listeners.remove(&ch);
}
None => {
listeners.clear();
}
}
Ok(())
}
#[napi]
pub fn ipc_main_handle_sync(channel: String, _callback: JsFunction) -> Result<()> {
let mut channels = REGISTERED_CHANNELS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
channels.insert(channel.clone(), true);
log::debug!("ipcMain.handleSync registered for channel: {}", channel);
Ok(())
}
// --- ipcRenderer API ---
#[napi]
pub fn ipc_renderer_invoke(
window_id: u32,
channel: String,
args_json: Option<String>,
) -> Result<String> {
let request_id = uuid::Uuid::new_v4().to_string();
let invoke_msg = serde_json::json!({
"type": "invoke",
"requestId": request_id,
"channel": channel,
"args": args_json.and_then(|a| serde_json::from_str::<serde_json::Value>(&a).ok()).unwrap_or(serde_json::Value::Null),
})
.to_string();
crate::browser_window::window_web_contents_send(
window_id,
"__gelectron_ipc_invoke".to_string(),
Some(invoke_msg),
)?;
Ok(request_id)
}
#[napi]
pub fn ipc_renderer_send(window_id: u32, channel: String, args_json: Option<String>) -> Result<()> {
let send_msg = serde_json::json!({
"type": "send",
"channel": channel,
"args": args_json.and_then(|a| serde_json::from_str::<serde_json::Value>(&a).ok()).unwrap_or(serde_json::Value::Null),
})
.to_string();
crate::browser_window::window_web_contents_send(
window_id,
"__gelectron_ipc_send".to_string(),
Some(send_msg),
)?;
Ok(())
}
#[napi]
pub fn ipc_renderer_on(channel: String, _callback: JsFunction) -> Result<i64> {
let id = LISTENER_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let mut listeners = IPC_LISTENERS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
listeners
.entry(format!("renderer:{}", channel))
.or_insert_with(Vec::new)
.push(IpcListener {
id,
channel: channel.clone(),
});
log::debug!("ipcRenderer.on registered for channel: {}", &channel);
Ok(id as i64)
}
#[napi]
pub fn ipc_renderer_remove_listener(channel: String, listener_id: i64) -> Result<()> {
let mut listeners = IPC_LISTENERS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
let key = format!("renderer:{}", channel);
if let Some(channel_listeners) = listeners.get_mut(&key) {
channel_listeners.retain(|l| l.id as i64 != listener_id);
}
Ok(())
}
#[napi]
pub fn ipc_renderer_remove_all_listeners(channel: Option<String>) -> Result<()> {
let mut listeners = IPC_LISTENERS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
match channel {
Some(ch) => {
listeners.remove(&format!("renderer:{}", ch));
}
None => {
listeners.retain(|k, _| !k.starts_with("renderer:"));
}
}
Ok(())
}
#[napi]
pub fn ipc_send_to_renderers(channel: String, data_json: Option<String>) -> Result<()> {
let windows = crate::browser_window::window_get_all_windows()
.map_err(|e| Error::from_reason(e.to_string()))?;
for win in windows {
crate::browser_window::window_web_contents_send(
win.id,
channel.clone(),
data_json.clone(),
)?;
}
Ok(())
}
+50
View File
@@ -0,0 +1,50 @@
use napi_derive::napi;
mod app;
mod browser_window;
mod context_bridge;
mod dialog;
mod event_loop;
mod ipc;
mod menu;
mod native_image;
mod notification;
mod protocol;
mod safe_storage;
mod servo_host;
mod shell;
mod tray;
mod web_contents;
pub use app::*;
pub use browser_window::*;
pub use context_bridge::*;
pub use dialog::*;
pub use event_loop::*;
pub use ipc::*;
pub use menu::*;
pub use native_image::*;
pub use notification::*;
pub use protocol::*;
pub use safe_storage::*;
pub use servo_host::*;
pub use shell::*;
pub use tray::*;
pub use web_contents::*;
#[napi]
pub fn init() -> String {
env_logger::init();
log::info!("gelectron-core v{} initialized", env!("CARGO_PKG_VERSION"));
format!("gelectron-core v{}", env!("CARGO_PKG_VERSION"))
}
#[napi]
pub fn get_platform() -> String {
std::env::consts::OS.to_string()
}
#[napi]
pub fn get_arch() -> String {
std::env::consts::ARCH.to_string()
}
+137
View File
@@ -0,0 +1,137 @@
use napi::bindgen_prelude::*;
use napi_derive::napi;
use serde::{Deserialize, Serialize};
use std::sync::{Mutex, OnceLock};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MenuItemDef {
#[serde(rename = "type")]
pub item_type: Option<String>,
pub label: Option<String>,
pub accelerator: Option<String>,
pub enabled: Option<bool>,
pub visible: Option<bool>,
pub checked: Option<bool>,
pub role: Option<String>,
pub submenu: Option<Vec<MenuItemDef>>,
pub id: Option<String>,
}
static MENU_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
static MENUS: OnceLock<Mutex<Vec<u32>>> = OnceLock::new();
fn get_menu_ids() -> &'static Mutex<Vec<u32>> {
MENUS.get_or_init(|| Mutex::new(Vec::new()))
}
#[napi]
pub fn menu_build_from_template(template_json: String) -> Result<u32> {
let _items: Vec<MenuItemDef> =
serde_json::from_str(&template_json).map_err(|e| Error::from_reason(e.to_string()))?;
let id = MENU_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
get_menu_ids()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?
.push(id);
log::info!("Menu {} built from template ({} items)", id, _items.len());
Ok(id)
}
#[napi]
pub fn menu_set_as_app_menu(menu_id: u32) -> Result<()> {
log::info!("Menu {} set as app menu", menu_id);
Ok(())
}
#[napi]
pub fn menu_set_as_window_menu(menu_id: u32, window_id: u32) -> Result<()> {
log::info!("Menu {} set as window menu for window {}", menu_id, window_id);
Ok(())
}
#[napi]
pub fn menu_get_application_menu() -> Option<u32> {
get_menu_ids()
.lock()
.ok()
.and_then(|ids| ids.first().copied())
}
#[napi]
pub fn menu_popup(menu_id: u32, window_id: Option<u32>, x: Option<f64>, y: Option<f64>) -> Result<()> {
log::info!(
"Menu {} popup at ({}, {}) on window {:?}",
menu_id,
x.unwrap_or(0.0),
y.unwrap_or(0.0),
window_id
);
Ok(())
}
#[napi]
pub fn menu_close_popup(_menu_id: u32) -> Result<()> {
Ok(())
}
#[napi]
pub fn menu_items(menu_id: u32) -> Result<Vec<String>> {
log::debug!("Menu {} get items", menu_id);
Ok(vec!["[]".to_string()])
}
#[napi]
pub fn menu_append(menu_id: u32, item_json: String) -> Result<()> {
log::debug!("Menu {} append item: {}", menu_id, &item_json[..item_json.len().min(50)]);
Ok(())
}
#[napi]
pub fn menu_insert(menu_id: u32, position: u32, item_json: String) -> Result<()> {
log::debug!("Menu {} insert at position {}: {}", menu_id, position, &item_json[..item_json.len().min(50)]);
Ok(())
}
#[napi]
pub fn menu_remove(menu_id: u32, item_id: String) -> Result<()> {
log::debug!("Menu {} remove item {}", menu_id, item_id);
Ok(())
}
#[napi]
pub fn menu_remove_at(menu_id: u32, position: u32) -> Result<()> {
log::debug!("Menu {} remove at position {}", menu_id, position);
Ok(())
}
#[napi]
pub fn menu_clear(menu_id: u32) -> Result<()> {
log::debug!("Menu {} cleared", menu_id);
Ok(())
}
#[napi]
pub fn menu_get_item_by_id(menu_id: u32, item_id: String) -> Result<Option<String>> {
log::debug!("Menu {} get item {}", menu_id, item_id);
Ok(None)
}
#[napi]
pub fn menu_set_item_enabled(menu_id: u32, item_id: String, enabled: bool) -> Result<()> {
log::debug!("Menu {} item {} enabled={}", menu_id, item_id, enabled);
Ok(())
}
#[napi]
pub fn menu_set_item_checked(menu_id: u32, item_id: String, checked: bool) -> Result<()> {
log::debug!("Menu {} item {} checked={}", menu_id, item_id, checked);
Ok(())
}
#[napi]
pub fn menu_set_item_label(menu_id: u32, item_id: String, label: String) -> Result<()> {
log::debug!("Menu {} item {} label={}", menu_id, item_id, label);
Ok(())
}
+239
View File
@@ -0,0 +1,239 @@
use napi::bindgen_prelude::*;
use napi_derive::napi;
use std::sync::{Mutex, OnceLock};
pub struct NativeImageHandle {
pub id: u32,
pub width: u32,
pub height: u32,
pub rgba_data: Vec<u8>,
}
static IMAGE_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
static IMAGES: OnceLock<Mutex<Vec<NativeImageHandle>>> = OnceLock::new();
fn get_images() -> &'static Mutex<Vec<NativeImageHandle>> {
IMAGES.get_or_init(|| Mutex::new(Vec::new()))
}
#[napi(object)]
pub struct ImageSize {
pub width: u32,
pub height: u32,
}
#[napi(object)]
pub struct ImageData {
pub id: u32,
pub width: u32,
pub height: u32,
pub to_png_data_uri: String,
}
#[napi]
pub fn native_image_create_from_path(path: String) -> Result<u32> {
let img = image::open(&path).map_err(|e| Error::from_reason(e.to_string()))?;
let rgba = img.to_rgba8();
let (width, height) = rgba.dimensions();
let id = IMAGE_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
get_images()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?
.push(NativeImageHandle {
id,
width,
height,
rgba_data: rgba.into_raw(),
});
log::debug!("NativeImage {} created from path: {} ({}x{})", id, path, width, height);
Ok(id)
}
#[napi]
pub fn native_image_create_from_buffer(
buffer: Vec<u8>,
width: Option<u32>,
height: Option<u32>,
) -> Result<u32> {
let img = image::load_from_memory(&buffer).map_err(|e| Error::from_reason(e.to_string()))?;
let rgba = img.to_rgba8();
let (w, h) = rgba.dimensions();
let id = IMAGE_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
get_images()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?
.push(NativeImageHandle {
id,
width: width.unwrap_or(w),
height: height.unwrap_or(h),
rgba_data: rgba.into_raw(),
});
log::debug!("NativeImage {} created from buffer ({}x{})", id, w, h);
Ok(id)
}
#[napi]
pub fn native_image_create_empty() -> Result<u32> {
let id = IMAGE_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
get_images()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?
.push(NativeImageHandle {
id,
width: 0,
height: 0,
rgba_data: vec![],
});
Ok(id)
}
#[napi]
pub fn native_image_get_size(image_id: u32) -> Result<ImageSize> {
let images = get_images()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
let img = images
.iter()
.find(|i| i.id == image_id)
.ok_or_else(|| Error::from_reason("Image not found".to_string()))?;
Ok(ImageSize {
width: img.width,
height: img.height,
})
}
#[napi]
pub fn native_image_to_png(image_id: u32) -> Result<Vec<u8>> {
let images = get_images()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
let img = images
.iter()
.find(|i| i.id == image_id)
.ok_or_else(|| Error::from_reason("Image not found".to_string()))?;
let rgba_img = image::RgbaImage::from_raw(img.width, img.height, img.rgba_data.clone())
.ok_or_else(|| Error::from_reason("Failed to create RGBA image".to_string()))?;
let mut buf = std::io::Cursor::new(Vec::new());
rgba_img
.write_to(&mut buf, image::ImageFormat::Png)
.map_err(|e| Error::from_reason(e.to_string()))?;
Ok(buf.into_inner())
}
#[napi]
pub fn native_image_to_jpeg(image_id: u32, quality: u32) -> Result<Vec<u8>> {
let images = get_images()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
let img = images
.iter()
.find(|i| i.id == image_id)
.ok_or_else(|| Error::from_reason("Image not found".to_string()))?;
let rgba_img = image::RgbaImage::from_raw(img.width, img.height, img.rgba_data.clone())
.ok_or_else(|| Error::from_reason("Failed to create RGBA image".to_string()))?;
let rgb_img = image::DynamicImage::ImageRgba8(rgba_img).to_rgb8();
let mut buf = std::io::Cursor::new(Vec::new());
let encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buf, quality as u8);
rgb_img
.write_with_encoder(encoder)
.map_err(|e| Error::from_reason(e.to_string()))?;
Ok(buf.into_inner())
}
#[napi]
pub fn native_image_resize(
image_id: u32,
width: u32,
height: u32,
) -> Result<u32> {
let mut images = get_images()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
let img = images
.iter()
.find(|i| i.id == image_id)
.ok_or_else(|| Error::from_reason("Image not found".to_string()))?;
let rgba_img = image::RgbaImage::from_raw(img.width, img.height, img.rgba_data.clone())
.ok_or_else(|| Error::from_reason("Failed to create RGBA image".to_string()))?;
let resized = image::imageops::resize(&rgba_img, width, height, image::imageops::FilterType::Lanczos3);
let (rw, rh) = resized.dimensions();
let new_id = IMAGE_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
images.push(NativeImageHandle {
id: new_id,
width: rw,
height: rh,
rgba_data: resized.into_raw(),
});
Ok(new_id)
}
#[napi]
pub fn native_image_crop(
image_id: u32,
x: u32,
y: u32,
width: u32,
height: u32,
) -> Result<u32> {
let mut images = get_images()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
let img = images
.iter()
.find(|i| i.id == image_id)
.ok_or_else(|| Error::from_reason("Image not found".to_string()))?;
let rgba_img = image::RgbaImage::from_raw(img.width, img.height, img.rgba_data.clone())
.ok_or_else(|| Error::from_reason("Failed to create RGBA image".to_string()))?;
let cropped = image::imageops::crop_imm(&rgba_img, x, y, width, height).to_image();
let new_id = IMAGE_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
images.push(NativeImageHandle {
id: new_id,
width,
height,
rgba_data: cropped.into_raw(),
});
Ok(new_id)
}
#[napi]
pub fn native_image_set_template_image(image_id: u32, template: bool) -> Result<()> {
log::debug!("NativeImage {} template={}", image_id, template);
Ok(())
}
#[napi]
pub fn native_image_is_empty(image_id: u32) -> Result<bool> {
let images = get_images()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
Ok(images
.iter()
.find(|i| i.id == image_id)
.map(|i| i.rgba_data.is_empty())
.unwrap_or(true))
}
#[napi]
pub fn native_image_destroy(image_id: u32) -> Result<()> {
let mut images = get_images()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
images.retain(|i| i.id != image_id);
Ok(())
}
+67
View File
@@ -0,0 +1,67 @@
use napi::bindgen_prelude::*;
use napi_derive::napi;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct NotificationOptions {
pub title: Option<String>,
pub body: Option<String>,
pub subtitle: Option<String>,
pub silent: Option<bool>,
pub icon: Option<String>,
pub urgency: Option<String>,
pub timeout_type: Option<String>,
pub close_button_text: Option<String>,
pub toast_xml: Option<String>,
}
#[napi(object)]
pub struct NotificationInfo {
pub id: String,
pub title: String,
pub body: String,
}
static NOTIFICATION_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
#[napi]
pub fn notification_create(options_json: String) -> Result<String> {
let opts: NotificationOptions =
serde_json::from_str(&options_json).map_err(|e| Error::from_reason(e.to_string()))?;
let id = format!(
"notification-{}",
NOTIFICATION_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
);
let title = opts.title.unwrap_or_default();
let body = opts.body.unwrap_or_default();
let mut notification = notify_rust::Notification::new();
notification.summary(&title).body(&body);
if let Some(true) = opts.silent {
notification.sound_name("");
}
match notification.show() {
Ok(_) => {
log::info!("Notification '{}' shown", title);
}
Err(e) => {
log::error!("Failed to show notification: {}", e);
}
}
Ok(id)
}
#[napi]
pub fn notification_close(notification_id: String) -> Result<()> {
log::info!("Notification {} closed", notification_id);
Ok(())
}
#[napi]
pub fn notification_is_supported() -> bool {
true
}
+79
View File
@@ -0,0 +1,79 @@
use napi::bindgen_prelude::*;
use napi_derive::napi;
static PROTOCOL_HANDLERS: once_cell::sync::Lazy<std::sync::Mutex<Vec<String>>> =
once_cell::sync::Lazy::new(|| std::sync::Mutex::new(Vec::new()));
#[napi]
pub fn protocol_register_file_protocol(scheme: String, _handler: JsFunction) -> Result<()> {
let mut handlers = PROTOCOL_HANDLERS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
handlers.push(format!("file:{}", scheme));
log::info!("Registered file protocol handler for scheme: {}", scheme);
Ok(())
}
#[napi]
pub fn protocol_register_http_protocol(scheme: String, _handler: JsFunction) -> Result<()> {
let mut handlers = PROTOCOL_HANDLERS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
handlers.push(format!("http:{}", scheme));
log::info!("Registered HTTP protocol handler for scheme: {}", scheme);
Ok(())
}
#[napi]
pub fn protocol_register_buffer_protocol(scheme: String, _handler: JsFunction) -> Result<()> {
let mut handlers = PROTOCOL_HANDLERS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
handlers.push(format!("buffer:{}", scheme));
log::info!("Registered buffer protocol handler for scheme: {}", scheme);
Ok(())
}
#[napi]
pub fn protocol_register_stream_protocol(scheme: String, _handler: JsFunction) -> Result<()> {
let mut handlers = PROTOCOL_HANDLERS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
handlers.push(format!("stream:{}", scheme));
log::info!("Registered stream protocol handler for scheme: {}", scheme);
Ok(())
}
#[napi]
pub fn protocol_handle(scheme: String, request_json: String) -> Result<String> {
log::debug!(
"Protocol handle: scheme={}, request={}",
scheme,
&request_json[..request_json.len().min(100)]
);
Ok(serde_json::json!({
"statusCode": 200,
"headers": {},
"data": ""
})
.to_string())
}
#[napi]
pub fn protocol_unregister_protocol(scheme: String) -> Result<()> {
let mut handlers = PROTOCOL_HANDLERS
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
handlers.retain(|h| !h.starts_with(&format!("{}:", scheme)));
log::info!("Unregistered protocol handler for scheme: {}", scheme);
Ok(())
}
#[napi]
pub fn protocol_is_protocol_registered(scheme: String) -> bool {
PROTOCOL_HANDLERS
.lock()
.ok()
.map(|handlers| handlers.iter().any(|h| h.starts_with(&format!("{}:", scheme))))
.unwrap_or(false)
}
+48
View File
@@ -0,0 +1,48 @@
use napi::bindgen_prelude::*;
use napi_derive::napi;
#[napi]
pub fn safe_storage_is_available() -> bool {
true
}
#[napi]
pub fn safe_storage_encrypt_string(
service_name: String,
account: String,
plaintext: String,
) -> Result<()> {
let entry = keyring::Entry::new(&service_name, &account)
.map_err(|e| Error::from_reason(e.to_string()))?;
entry
.set_password(&plaintext)
.map_err(|e| Error::from_reason(e.to_string()))?;
log::info!("Stored credentials for {}/{}", service_name, account);
Ok(())
}
#[napi]
pub fn safe_storage_decrypt_string(
service_name: String,
account: String,
) -> Result<Option<String>> {
let entry = keyring::Entry::new(&service_name, &account)
.map_err(|e| Error::from_reason(e.to_string()))?;
match entry.get_password() {
Ok(password) => Ok(Some(password)),
Err(keyring::Error::NoEntry) => Ok(None),
Err(e) => Err(Error::from_reason(e.to_string())),
}
}
#[napi]
pub fn safe_storage_delete_item(
service_name: String,
account: String,
) -> Result<()> {
let entry = keyring::Entry::new(&service_name, &account)
.map_err(|e| Error::from_reason(e.to_string()))?;
let _ = entry.delete_credential();
log::info!("Deleted credentials for {}/{}", service_name, account);
Ok(())
}
+105
View File
@@ -0,0 +1,105 @@
use napi::bindgen_prelude::*;
use napi_derive::napi;
use std::sync::{Mutex, OnceLock};
pub struct ServoHost {
pub initialized: bool,
pub url: String,
}
static SERVO_HOST: OnceLock<Mutex<Option<ServoHost>>> = OnceLock::new();
pub fn get_servo_host() -> Option<&'static Mutex<Option<ServoHost>>> {
Some(SERVO_HOST.get_or_init(|| Mutex::new(None)))
}
#[napi]
pub fn servo_init(config_json: Option<String>) -> Result<()> {
log::info!("Initializing Servo host...");
let host = ServoHost {
initialized: true,
url: config_json
.and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
.and_then(|v| v.get("url").and_then(|u| u.as_str().map(String::from)))
.unwrap_or_else(|| "about:blank".to_string()),
};
if let Some(mutex) = get_servo_host() {
*mutex.lock().map_err(|e| Error::from_reason(e.to_string()))? = Some(host);
}
log::info!("Servo host initialized");
Ok(())
}
#[napi]
pub fn servo_is_available() -> bool {
get_servo_host()
.and_then(|m| m.lock().ok())
.and_then(|guard| guard.as_ref().map(|h| h.initialized))
.unwrap_or(false)
}
#[napi]
pub fn servo_load_url(url: String) -> Result<()> {
if let Some(mutex) = get_servo_host() {
let mut guard = mutex
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
if let Some(ref mut host) = *guard {
host.url = url.clone();
log::info!("Servo loading URL: {}", url);
}
}
Ok(())
}
#[napi]
pub fn servo_get_url() -> String {
get_servo_host()
.and_then(|m| m.lock().ok())
.and_then(|guard| guard.as_ref().map(|h| h.url.clone()))
.unwrap_or_else(|| "about:blank".to_string())
}
#[napi]
pub fn servo_evaluate_javascript(script: String) -> Result<String> {
log::debug!(
"Servo evaluate JS: {}",
&script[..script.len().min(100)]
);
Ok(String::new())
}
#[napi]
pub fn servo_pump() {
if let Some(mutex) = get_servo_host() {
if let Ok(guard) = mutex.lock() {
if let Some(ref _host) = *guard {
// When Servo is fully integrated, this calls servo.spin_event_loop()
// For now, this is a no-op placeholder
}
}
}
}
#[napi]
pub fn servo_shutdown() {
if let Some(mutex) = get_servo_host() {
if let Ok(mut guard) = mutex.lock() {
*guard = None;
}
}
log::info!("Servo host shut down");
}
#[napi]
pub fn servo_set_preference(name: String, value: String) {
log::debug!("Servo preference: {} = {}", name, value);
}
#[napi]
pub fn servo_set_user_agent(user_agent: String) {
log::debug!("Servo user agent: {}", user_agent);
}
+104
View File
@@ -0,0 +1,104 @@
use napi::bindgen_prelude::*;
use napi_derive::napi;
#[napi]
pub fn shell_open_external(url: String) -> Result<bool> {
match open::that(&url) {
Ok(_) => {
log::info!("Shell opened external URL: {}", url);
Ok(true)
}
Err(e) => {
log::error!("Shell failed to open URL {}: {}", url, e);
Ok(false)
}
}
}
#[napi]
pub fn shell_open_path(path: String) -> Result<String> {
match open::that(&path) {
Ok(_) => {
log::info!("Shell opened path: {}", path);
Ok(String::new())
}
Err(e) => {
log::error!("Shell failed to open path {}: {}", path, e);
Ok(e.to_string())
}
}
}
#[napi]
pub fn shell_show_item_in_folder(path: String) -> Result<()> {
#[cfg(target_os = "macos")]
{
let _ = std::process::Command::new("open")
.args(["-R", &path])
.spawn();
}
#[cfg(target_os = "windows")]
{
let _ = std::process::Command::new("explorer")
.args(["/select,", &path])
.spawn();
}
#[cfg(target_os = "linux")]
{
if let Some(parent) = std::path::Path::new(&path).parent() {
let _ = open::that(parent);
}
}
Ok(())
}
#[napi]
pub fn shell_move_item_to_trash(path: String) -> Result<()> {
let _ = std::fs::remove_file(&path);
log::info!("Shell moved to trash: {}", path);
Ok(())
}
#[napi]
pub fn shell_get_app_path(app_name: String) -> Result<String> {
#[cfg(target_os = "macos")]
{
if let Ok(output) = std::process::Command::new("mdfind")
.args([
"kMDItemKind == 'Application'",
"-onlyin",
"/Applications",
&app_name,
])
.output()
{
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
if let Some(first_line) = stdout.lines().next() {
return Ok(first_line.to_string());
}
}
}
Ok(String::new())
}
#[napi]
pub fn shell_create_desktop_shortcut() -> Result<()> {
log::debug!("Shell create desktop shortcut");
Ok(())
}
#[napi]
pub fn shell_browse_for_directory(options_json: Option<String>) -> Result<Option<String>> {
let mut builder = rfd::FileDialog::new();
if let Some(opts) = options_json {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&opts) {
if let Some(title) = v.get("title").and_then(|t| t.as_str()) {
builder = builder.set_title(title);
}
if let Some(dir) = v.get("defaultPath").and_then(|d| d.as_str()) {
builder = builder.set_directory(dir);
}
}
}
Ok(builder.pick_folder().map(|p| p.to_string_lossy().to_string()))
}
+99
View File
@@ -0,0 +1,99 @@
use napi::bindgen_prelude::*;
use napi::threadsafe_function::{ErrorStrategy, ThreadsafeFunction};
use napi_derive::napi;
use std::sync::{Mutex, OnceLock};
static TRAY_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
static TRAY_IDS: OnceLock<Mutex<Vec<u32>>> = OnceLock::new();
fn get_tray_ids() -> &'static Mutex<Vec<u32>> {
TRAY_IDS.get_or_init(|| Mutex::new(Vec::new()))
}
#[napi(object)]
pub struct TrayInfo {
pub id: u32,
pub tooltip: Option<String>,
}
#[napi]
pub fn tray_create(options_json: Option<String>) -> Result<u32> {
let id = TRAY_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let tooltip = options_json
.and_then(|j| serde_json::from_str::<serde_json::Value>(&j).ok())
.and_then(|v| v.get("tooltip").and_then(|t| t.as_str()).map(String::from))
.unwrap_or_else(|| "Gelectron".to_string());
get_tray_ids()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?
.push(id);
log::info!("Tray {} created with tooltip '{}'", id, tooltip);
Ok(id)
}
#[napi]
pub fn tray_destroy(tray_id: u32) -> Result<()> {
let mut ids = get_tray_ids()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
ids.retain(|&id| id != tray_id);
log::info!("Tray {} destroyed", tray_id);
Ok(())
}
#[napi]
pub fn tray_set_tooltip(tray_id: u32, tooltip: String) -> Result<()> {
log::debug!("Tray {} tooltip set to '{}'", tray_id, tooltip);
Ok(())
}
#[napi]
pub fn tray_set_image(tray_id: u32, _image_json: Option<String>) -> Result<()> {
log::debug!("Tray {} image updated", tray_id);
Ok(())
}
#[napi]
pub fn tray_set_pressed_image(_tray_id: u32, _image_json: Option<String>) -> Result<()> {
Ok(())
}
#[napi]
pub fn tray_setContextMenu(tray_id: u32, menu_id: Option<u32>) -> Result<()> {
log::info!("Tray {} context menu set to {:?}", tray_id, menu_id);
Ok(())
}
#[napi]
pub fn tray_popup_context_menu(tray_id: u32, _options_json: Option<String>) -> Result<()> {
log::info!("Tray {} context menu popped up", tray_id);
Ok(())
}
#[napi]
pub fn tray_is_destroyed(tray_id: u32) -> Result<bool> {
let ids = get_tray_ids()
.lock()
.map_err(|e| Error::from_reason(e.to_string()))?;
Ok(!ids.contains(&tray_id))
}
#[napi]
pub fn tray_on_event(tray_id: u32, callback: JsFunction) -> Result<()> {
let _tsfn: ThreadsafeFunction<String, ErrorStrategy::Fatal> = callback
.create_threadsafe_function(0, |ctx: napi::threadsafe_function::ThreadSafeCallContext<String>| {
let value = ctx.value.clone();
Ok(vec![ctx.env.create_string_from_std(value)?])
})?;
log::debug!("Tray {} event listener registered", tray_id);
Ok(())
}
#[napi]
pub fn tray_get_bounds(_tray_id: u32) -> Result<Vec<f64>> {
Ok(vec![0.0, 0.0, 22.0, 22.0])
}
+168
View File
@@ -0,0 +1,168 @@
use napi::bindgen_prelude::*;
use napi_derive::napi;
#[napi]
pub fn web_contents_get_id(window_id: u32) -> Result<u32> {
Ok(window_id)
}
#[napi]
pub fn web_contents_send(window_id: u32, channel: String, data_json: Option<String>) -> Result<()> {
crate::browser_window::window_web_contents_send(window_id, channel, data_json)
}
#[napi]
pub fn web_contents_execute_javascript(window_id: u32, code: String) -> Result<String> {
crate::browser_window::window_execute_javascript(window_id, code)
}
#[napi]
pub fn web_contents_insert_css(window_id: u32, css: String) -> Result<()> {
crate::browser_window::window_insert_css(window_id, css)
}
#[napi]
pub fn web_contents_open_devtools(window_id: u32) -> Result<()> {
crate::browser_window::window_open_devtools(window_id)
}
#[napi]
pub fn web_contents_close_devtools(window_id: u32) -> Result<()> {
crate::browser_window::window_close_devtools(window_id)
}
#[napi]
pub fn web_contents_is_devtools_open(window_id: u32) -> Result<bool> {
crate::browser_window::window_is_devtools_open(window_id)
}
#[napi]
pub fn web_contents_get_url(window_id: u32) -> Result<String> {
crate::browser_window::window_get_url(window_id)
}
#[napi]
pub fn web_contents_get_title(window_id: u32) -> Result<String> {
crate::browser_window::window_get_title(window_id)
}
#[napi]
pub fn web_contents_is_loading(_window_id: u32) -> Result<bool> {
Ok(false)
}
#[napi]
pub fn web_contents_is_crashed(_window_id: u32) -> Result<bool> {
Ok(false)
}
#[napi]
pub fn web_contents_go_back(window_id: u32) -> Result<()> {
log::info!("Window {} go back", window_id);
Ok(())
}
#[napi]
pub fn web_contents_go_forward(window_id: u32) -> Result<()> {
log::info!("Window {} go forward", window_id);
Ok(())
}
#[napi]
pub fn web_contents_can_go_back(_window_id: u32) -> Result<bool> {
Ok(false)
}
#[napi]
pub fn web_contents_can_go_forward(_window_id: u32) -> Result<bool> {
Ok(false)
}
#[napi]
pub fn web_contents_reload(window_id: u32) -> Result<()> {
crate::browser_window::window_reload(window_id)
}
#[napi]
pub fn web_contents_set_zoom_factor(window_id: u32, factor: f64) -> Result<()> {
log::debug!("Window {} zoom factor set to {}", window_id, factor);
Ok(())
}
#[napi]
pub fn web_contents_get_zoom_factor(_window_id: u32) -> Result<f64> {
Ok(1.0)
}
#[napi]
pub fn web_contents_set_background_color(window_id: u32, color: String) -> Result<()> {
log::debug!("Window {} background color set to {}", window_id, color);
Ok(())
}
#[napi]
pub fn web_contents_get_process_id(_window_id: u32) -> Result<i32> {
Ok(std::process::id() as i32)
}
#[napi]
pub fn web_contents_get_session_id(window_id: u32) -> Result<String> {
Ok(format!("session-{}", window_id))
}
#[napi]
pub fn web_contents_set_windowOpenHandler(window_id: u32) -> Result<()> {
log::debug!("Window {} set window open handler", window_id);
Ok(())
}
#[napi]
pub fn web_contents_set_permissionRequestHandler(window_id: u32) -> Result<()> {
log::debug!("Window {} set permission request handler", window_id);
Ok(())
}
#[napi]
pub fn web_contents_set_certificate_verify_proc(window_id: u32) -> Result<()> {
log::debug!("Window {} set certificate verify proc", window_id);
Ok(())
}
#[napi]
pub fn web_contents_set_user_agent(window_id: u32, user_agent: String) -> Result<()> {
log::debug!("Window {} user agent set to {}", window_id, user_agent);
Ok(())
}
#[napi]
pub fn web_contents_get_user_agent(_window_id: u32) -> Result<String> {
Ok(crate::app::app_get_user_agent())
}
#[napi]
pub fn web_contents_set_ignore_menu_shortcuts(window_id: u32, ignore: bool) -> Result<()> {
log::debug!("Window {} ignore menu shortcuts={}", window_id, ignore);
Ok(())
}
#[napi]
pub fn web_contents_setAudioMuted(window_id: u32, muted: bool) -> Result<()> {
log::debug!("Window {} audio muted={}", window_id, muted);
Ok(())
}
#[napi]
pub fn web_contents_is_audio_muted(_window_id: u32) -> Result<bool> {
Ok(false)
}
#[napi]
pub fn web_contents_set_zoom_level(window_id: u32, level: f64) -> Result<()> {
log::debug!("Window {} zoom level set to {}", window_id, level);
Ok(())
}
#[napi]
pub fn web_contents_get_zoom_level(_window_id: u32) -> Result<f64> {
Ok(0.0)
}