Compare commits

..
8 Commits
Author SHA1 Message Date
miles e2fd6a59a3 Merge pull request #2 from mileswolfallen2/copilot/remake-readme
Rewrite README for accuracy and remove unsupported claims
2026-10-02 11:27:48 -05:00
miles b227ebb2d6 Update project description in README.md 2026-10-02 11:27:28 -05:00
copilot-swe-agent[bot]andmileswolfallen2 69fe3e51de Rewrite README with verified project information
Co-authored-by: mileswolfallen2 <[email protected]>
2026-10-02 16:24:12 +00:00
miles bb61c8a7af Update README to reflect package tooling status
Moved package/distribution tooling to 'In progress' section.
2026-09-23 11:39:31 -05:00
miles 8a7d251acc docs: update README with known limitations and roadmap details 2026-09-23 11:36:58 -05:00
miles 58f222d661 feat: add macOS title bar theming support with setTitleBarOverlay and setBackgroundColor APIs 2026-09-19 15:43:59 -05:00
miles 06b14e6cda feat: enhance WebContents and BrowserWindow with navigation and devtools features
- Added history management to WebContents for back and forward navigation.
- Implemented methods for opening, closing, and toggling devtools in WebContents and BrowserWindow.
- Introduced capturePage and printToPDF methods in WebContents for screenshot and PDF generation.
- Added process polyfill for WebView-only mode to ensure compatibility without a Node.js runtime.
- Updated native bridge to handle new window management commands.
- Enhanced Cargo.toml and Cargo.lock for dependency alignment.
- Updated package-lock.json for versioning consistency across native installers.
2026-09-18 11:31:55 -05:00
miles f45e458c53 change 2026-09-06 00:23:33 -05:00
13 changed files with 1277 additions and 830 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
1db4284c-fc55-41be-a7dd-cde2036997da
-214
View File
@@ -1,214 +0,0 @@
name: Build native binaries
# On every new release (tag push of `v*`), this workflow:
# 1. builds the gelectron native engine + N-API addons for all platforms,
# 2. packages portable archives, and
# 3. builds installers you can simply install:
# - macOS: Gelectron-<ver>-arm64.dmg / Gelectron-<ver>-x64.dmg
# - Windows: Gelectron-<ver>-x64.exe / Gelectron-<ver>-arm64.exe
# - Linux: Gelectron-<ver>-x86_64.AppImage / Gelectron-<ver>-aarch64.AppImage
#
# Everything is attached to the GitHub Release for that tag.
on:
push:
tags:
- 'v*'
workflow_dispatch:
jobs:
# ── N-API addons (published to npm, also attached to the release) ─────────
addon:
name: Addon ${{ matrix.target }}
strategy:
fail-fast: false
matrix:
include:
- os: macos-14
target: aarch64-apple-darwin
- os: macos-13
target: x86_64-apple-darwin
- os: windows-latest
target: x86_64-pc-windows-msvc
- os: windows-latest
target: aarch64-pc-windows-msvc
- os: ubuntu-22.04
target: x86_64-unknown-linux-gnu
- os: ubuntu-24.04-arm
target: aarch64-unknown-linux-gnu
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: npm ci
- name: Build N-API addon for ${{ matrix.target }}
run: npx napi build --platform --release --target ${{ matrix.target }} --package gelectron-core
- name: Rename .node file with platform-specific name
shell: bash
run: |
case "${{ matrix.target }}" in
x86_64-apple-darwin) name="gelectron_core.darwin-x64.node" ;;
aarch64-apple-darwin) name="gelectron_core.darwin-arm64.node" ;;
x86_64-pc-windows-msvc) name="gelectron_core.win32-x64-msvc.node" ;;
aarch64-pc-windows-msvc) name="gelectron_core.win32-arm64-msvc.node" ;;
x86_64-unknown-linux-gnu) name="gelectron_core.linux-x64-gnu.node" ;;
aarch64-unknown-linux-gnu) name="gelectron_core.linux-arm64-gnu.node" ;;
esac
find crates/gelectron-core -name "*.node" -exec mv {} "$name" \;
ls -la *.node
- name: Upload .node artifact
uses: actions/upload-artifact@v4
with:
name: bindings-${{ matrix.target }}
path: gelectron_core.*.node
# ── Native engine + portable archives + installers ────────────────────────
runtime:
name: Runtime ${{ matrix.platform }}-${{ matrix.arch }}
strategy:
fail-fast: false
matrix:
include:
- os: macos-14
target: aarch64-apple-darwin
platform: darwin
arch: arm64
- os: macos-13
target: x86_64-apple-darwin
platform: darwin
arch: x64
- os: windows-latest
target: x86_64-pc-windows-msvc
platform: win32
arch: x64
- os: windows-latest
target: aarch64-pc-windows-msvc
platform: win32
arch: arm64
- os: ubuntu-22.04
target: x86_64-unknown-linux-gnu
platform: linux
arch: x64
- os: ubuntu-24.04-arm
target: aarch64-unknown-linux-gnu
platform: linux
arch: arm64
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install Linux system dependencies
if: matrix.platform == 'linux'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev libsoup-3.0-dev
- name: Build gelectron binary
run: cargo build --release -p gelectron --target ${{ matrix.target }}
- name: Package portable release archive
run: |
bash scripts/make-release.sh \
-v "${{ github.ref_name }}" \
-p ${{ matrix.platform }} \
-a ${{ matrix.arch }} \
-b "target/${{ matrix.target }}/release/gelectron" \
--no-build
# ── macOS DMG installer ────────────────────────────────────────────────
- name: Build macOS installer (DMG)
if: matrix.platform == 'darwin'
run: bash scripts/pkg/make-dmg.sh -v "${{ github.ref_name }}" -a ${{ matrix.arch }} -b "target/${{ matrix.target }}/release/gelectron" -o dist
# ── Windows EXE installer (NSIS) ──────────────────────────────────────
- name: Build Windows installer (EXE)
if: matrix.platform == 'win32'
shell: pwsh
run: |
choco install nsis -y --no-progress
powershell -ExecutionPolicy Bypass -File scripts/pkg/make-exe.ps1 `
-Bin "target/${{ matrix.target }}/release/gelectron.exe" `
-Compat src/electron `
-Version "${{ github.ref_name }}" `
-Arch ${{ matrix.arch }} `
-Out dist
# ── Linux AppImage installer ──────────────────────────────────────────
- name: Build Linux installer (AppImage)
if: matrix.platform == 'linux'
run: bash scripts/pkg/make-appimage.sh -v "${{ github.ref_name }}" -b "target/${{ matrix.target }}/release/gelectron" -o dist -a ${{ matrix.arch }}
- name: List build outputs
run: ls -la dist/
- name: Upload runtime and installer artifacts
uses: actions/upload-artifact@v4
with:
name: installers-${{ matrix.platform }}-${{ matrix.arch }}
path: |
dist/gelectron-*
dist/Gelectron-*
if-no-files-found: error
# ── Attach everything to the GitHub Release ───────────────────────────────
release:
name: Attach binaries to GitHub Release
needs: [addon, runtime]
if: startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Download all binaries
uses: actions/download-artifact@v4
with:
path: artifacts
pattern: bindings-*
merge-multiple: true
- name: Download all installers
uses: actions/download-artifact@v4
with:
path: artifacts
pattern: installers-*
merge-multiple: true
- name: List artifacts
run: ls -la artifacts/
- name: Upload assets to GitHub Release
uses: softprops/action-gh-release@v2
with:
files: artifacts/**
Generated
+19 -2
View File
@@ -1405,13 +1405,16 @@ version = "0.1.0"
dependencies = [
"arboard",
"base64",
"block2 0.5.1",
"env_logger",
"libc",
"log",
"muda",
"notify-rust",
"objc2 0.5.2",
"objc2 0.6.4",
"objc2-app-kit 0.3.2",
"objc2-core-graphics",
"objc2-foundation 0.3.2",
"png 0.18.1",
"rfd",
@@ -2663,10 +2666,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"
dependencies = [
"bitflags 2.13.1",
"block2 0.6.2",
"dispatch2",
"libc",
"objc2 0.6.4",
"objc2-core-foundation",
"objc2-io-surface",
"objc2-metal 0.3.2",
]
[[package]]
@@ -2678,7 +2684,7 @@ dependencies = [
"block2 0.5.1",
"objc2 0.5.2",
"objc2-foundation 0.2.2",
"objc2-metal",
"objc2-metal 0.2.2",
]
[[package]]
@@ -2795,6 +2801,17 @@ dependencies = [
"objc2-foundation 0.2.2",
]
[[package]]
name = "objc2-metal"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
dependencies = [
"bitflags 2.13.1",
"objc2 0.6.4",
"objc2-foundation 0.3.2",
]
[[package]]
name = "objc2-quartz-core"
version = "0.2.2"
@@ -2805,7 +2822,7 @@ dependencies = [
"block2 0.5.1",
"objc2 0.5.2",
"objc2-foundation 0.2.2",
"objc2-metal",
"objc2-metal 0.2.2",
]
[[package]]
+17 -8
View File
@@ -17,7 +17,7 @@
| 2 | autoUpdater | YES | YES | YES | **stub** | API surface for electron-updater compat, no actual updates |
| 3 | BaseWindow | NO | NO | NO | **missing** | Parent class for BrowserWindow, not implemented |
| 4 | BrowserView | NO | NO | NO | **missing** | Deprecated in favor of WebContentsView |
| 5 | BrowserWindow | YES | YES | YES | **partial** | create/show/hide/focus/min/max/close/destroy/setTitle/setSize/loadURL/loadFile. Missing: DevTools, navigation, capturePage, print, printToPDF |
| 5 | BrowserWindow | YES | YES | YES | **partial** | create/show/hide/focus/min/max/unmax/restore/close/destroy/setTitle/setSize/loadURL/loadFile/capturePage/print/printToPDF/openDevTools (native WKWebView, macOS capture/PDF). Title bar: `titleBarStyle`, `titleBarOverlay`, `setTitleBarOverlay()`, `setBackgroundColor()`/`getBackgroundColor()` (macOS colors via NSWindow). Gelectron-only: `setTopBarColor()`. Missing: zoom, vibrancy, frameless edges |
| 6 | clipboard | YES | inline | YES | **full** | readText/writeText/readHTML/writeHTML/readRTF/writeRTF/readImage/writeImage/readBookmark/writeBookmark/readFindText/writeFindText/clear/availableFormats/has. Sync via Unix FIFO channel (macOS/Linux) or async bridge (Windows). RTF/bookmark/find-text/formats via NSPasteboard on macOS |
| 7 | contentTracing | NO | NO | NO | **missing** | Tracing/recording profiling data |
| 8 | crashReporter | NO | NO | NO | **missing** | Crash upload to server |
@@ -30,7 +30,7 @@
| 15 | Menu | YES | YES | YES | **partial** | buildFromTemplate/append/insert/getMenuItemById, native setApplicationMenu via muda, _serialize. Missing: click events from native menu, role-based predefined items |
| 16 | MenuItem | YES | YES | YES | **partial** | All properties present (id/label/type/role/accelerator/enabled/visible/checked/submenu/click). Missing: role auto-behavior |
| 17 | MessageChannelMain | NO | NO | NO | **missing** | MessagePort-based IPC between main/renderer |
| 18 | nativeImage | YES | YES | YES | **partial** | createFromPath/Buffer/DataURL, toDataURL, getSize. Missing: resize/crop pixel transform, proper toPNG/toJPEG |
| 18 | nativeImage | YES | YES | YES | **partial** | createFromPath/Buffer/DataURL/createEmpty, toDataURL, getSize. Missing: resize/crop pixel transform, proper toPNG/toJPEG |
| 19 | nativeTheme | YES | inline | YES | **partial** | NativeTheme class: shouldUseDarkColors (getter + method), themeSource (getter/setter), shouldSystemUseDarkColors, queries Rust for system theme. systemPreferences.isDarkMode() linked |
| 20 | net | NO | inline | YES | **partial** | fetch delegates to globalThis.fetch. Missing: net.request(), ClientRequest API |
| 21 | netLog | NO | NO | NO | **missing** | Network log capture |
@@ -51,7 +51,7 @@
| 36 | Tray | YES | YES | YES | **stub** | API surface present, no native system tray |
| 37 | utilityProcess | NO | NO | NO | **missing** | Fork utility child processes |
| 38 | View | NO | NO | NO | **missing** | Base View class for embedding |
| 39 | webContents | YES | YES | YES | **partial** | loadURL/loadFile/send/executeJavaScript/reload, session stub. Missing: navigation history, DevTools CDP, zoom, print, capturePage |
| 39 | webContents | YES | YES | YES | **partial** | loadURL/loadFile/reload/reloadIgnoringCache/send/executeJavaScript/getURL/getTitle/getHistory/stop/navigation (goBack/goForward/canGoBack/canGoForward)/DevTools (open/close/toggle/isOpened/inspect)/capturePage/print/printToPDF. Missing: zoom, CDP, drag&drop session, PDF viewer |
| 40 | WebContentsView | NO | NO | NO | **missing** | View-based content embedding |
| 41 | webFrameMain | NO | NO | NO | **missing** | Main-process webFrame for frame control |
@@ -71,7 +71,7 @@
| # | Module | File | webview-bundle | index.js | Status | Notes |
|---|--------|------|----------------|----------|--------|-------|
| 49 | nativeImage | YES | YES | YES | **partial** | createFromPath/Buffer/DataURL, toDataURL, getSize. Missing: resize/crop transform |
| 49 | nativeImage | YES | YES | YES | **partial** | createFromPath/Buffer/DataURL/createEmpty, toDataURL, getSize. Missing: resize/crop transform |
| 50 | shell | YES | YES | YES | **partial** | openExternal/openPath/showItemInFolder/moveItemToTrash/beep via bridge (open crate + platform commands) |
## Deprecated / Internal
@@ -81,14 +81,14 @@
| 51 | BrowserView | **missing** | Deprecated, replaced by WebContentsView |
| 52 | remote | **missing** | Removed in Electron 14+ |
| 53 | webviewTag | **missing** | Deprecated, replaced by BrowserView/WebContentsView |
| 54 | process (polyfill) | **partial** | WebView mode polyfill: pid/argv/env/platform/versions/cwd/nextTick. Missing: memoryUsage/cpuUsage/uptime/kill |
| 54 | process (polyfill) | **partial** | WebView mode polyfill: pid/argv/env/platform/versions/cwd/nextTick/memoryUsage/cpuUsage/uptime/kill/exit/hrtime/EventEmitter. Missing: real child process mgmt, signal handling |
| 55 | contextIsolation | **stub** | webPreferences.contextIsolation stored but no actual V8 isolate separation |
## Additional APIs from Electron Docs
| # | API | Status | Notes |
|---|-----|--------|-------|
| 56 | navigation-history | **missing** | Navigation history API |
| 56 | navigation-history | **partial** | WebContents goBack/goForward/canGoBack/canGoForward/getHistory. Missing: `webContents.navigationHistory` object, getEntryAtIndex/activeIndex |
| 57 | parent-port | **missing** | UtilityProcess communication port |
| 58 | web-request | **missing** | Intercept/modify HTTP requests |
| 59 | web-socket | **missing** | WebSocket server |
@@ -102,9 +102,9 @@
| Status | Count | Modules |
|--------|-------|---------|
| **full** | 4 | app, ipcMain, clipboard, Notification |
| **partial** | 13 | BrowserWindow, Menu, MenuItem, dialog, shell, nativeImage, contextBridge, webContents, ipcRenderer, net, process, screen, nativeTheme |
| **partial** | 14 | BrowserWindow, Menu, MenuItem, dialog, shell, nativeImage, contextBridge, webContents, ipcRenderer, net, process, screen, nativeTheme, navigation-history |
| **stub** | 7 | Tray, safeStorage, autoUpdater, session, systemPreferences, powerMonitor, globalShortcut |
| **missing** | 36 | BaseWindow, BrowserView, contentTracing, crashReporter, desktopCapturer, ImageView, inAppPurchase, MessageChannelMain, netLog, powerSaveBlocker, protocol, pushNotifications, ServiceWorkerMain, sharedTexture, ShareMenu, TouchBar (+10 sub-classes), utilityProcess, View, WebContentsView, webFrameMain, webFrame, webUtils, crashReporter (renderer), sharedTexture (renderer), remote, webviewTag, navigation-history, parent-port, web-request, web-socket, window-open, local-ai-handler |
| **missing** | 35 | BaseWindow, BrowserView, contentTracing, crashReporter, desktopCapturer, ImageView, inAppPurchase, MessageChannelMain, netLog, powerSaveBlocker, protocol, pushNotifications, ServiceWorkerMain, sharedTexture, ShareMenu, TouchBar (+10 sub-classes), utilityProcess, View, WebContentsView, webFrameMain, webFrame, webUtils, crashReporter (renderer), sharedTexture (renderer), remote, webviewTag, parent-port, web-request, web-socket, window-open, local-ai-handler |
| **Total** | **60** | BrowserView counted once (listed in both Main and Deprecated tables) |
## Rust Bridge (main.rs ToRust commands)
@@ -121,6 +121,15 @@ These commands are implemented on the Rust side and can be triggered from the We
| set-size | YES | Updates window inner size |
| show / hide / focus | YES | Window visibility |
| minimize / maximize | YES | Window state |
| unmaximize / restore | YES | Window state |
| go-back / go-forward | YES | WebView history navigation |
| open-devtools / close-devtools / toggle-devtools | YES | WebView DevTools (wry webview devtools, enabled via devtools feature) |
| inspect-element | YES | DevTools element inspection (macOS WKWebView) |
| print-page | YES | Native print dialog (wry webview.print) |
| capture-page | YES | PNG snapshot of webview (macOS WKWebView takeSnapshot; unsupported elsewhere) |
| print-to-pdf | YES | PDF render of webview (macOS WKWebView createPDF; unsupported elsewhere) |
| set-titlebar-overlay | YES | macOS title bar color / transparency (`{ color, transparent, titleBarStyle }` via NSWindow backgroundColor + titlebarAppearsTransparent) |
| set-background-color | YES | macOS window background color via NSWindow |
| close | YES | Closes window |
| eval-js | YES | Execute JavaScript in webview |
| ipc-message | YES | Forward IPC to renderer |
+85 -571
View File
@@ -4,633 +4,147 @@
<p>A drop-in replacement for Electron using native web views (WKWebView / WebView2 / WebKitGTK) instead of Chromium</p>
</div>
See the [benchmark results and comparisons](https://gelectron.milesallen.site/benchmarks) for the latest performance data.
Gelectron is an Electron alternative focused on using platform-native web views through [`wry`](https://github.com/tauri-apps/wry) and `tao`, plus a Node-compatible API shim.
## Why Gelectron?
## Project status
Electron bundles Chromium — ~300 MB per app with 500+ MB RSS. Gelectron uses the OS-native web view (WKWebView on macOS, WebView2 on Windows, WebKitGTK on Linux) via the **wry** and **tao** Rust crates, producing smaller binaries with dramatically lower memory usage.
- Early-stage project under active development
- Compatibility is partial and evolving
- Some Electron APIs are implemented, others are stubs or no-ops
| Feature | Electron | Gelectron |
|---|---|---|
| Rendering Engine | Chromium | Native WebView (WKWebView / WebView2 / WebKitGTK) |
| Total RSS (process tree) | ~588 MB | ~131 MB |
| Binary Size | ~300 MB | ~3 MB |
| Language | C++ / Node.js | Rust / Node.js |
| API Compatibility | Native | Drop-in replacement |
| Node.js Integration | Built-in | Spawned child process or WebView-only |
| Auto Updater | Built-in | Full (electron-updater compatible)
If you are evaluating migration from Electron, test your app against Gelectron directly before committing to it.
## Quick Start
## Install
### Install from npm (recommended)
The npm package exposes:
The built native binary and the Electron compatibility layer are published to npm. This is the main and easiest way to get Gelectron — no Rust toolchain required:
- `gelectron`
- `gelectron-core`
- `gelectron-packager`
```bash
npm install -g gelectron-core
```
This installs the `gelectron-core` package, which bundles the pre-built native binary and the JS compatibility layer, and automatically pulls in the platform-specific addon for your operating system and CPU architecture (see the [package on npm](https://www.npmjs.com/package/gelectron-core)).
## Quick start
Once installed, run any Electron app exactly like Electron — the `gelectron` command works out of the box (the package also exposes `gelectron-core` and `gelectron-packager`):
Run an app directory (uses `package.json` -> `main`):
```bash
gelectron /path/to/electron-app
gelectron . # app in the current directory (reads package.json "main")
gelectron main.js # a bare main-process script
gelectron .
```
Run a main-process script directly:
```bash
gelectron main.js
```
Show CLI version/help:
```bash
gelectron --version
gelectron --help
```
### Download a native installer (double-click, no tools needed)
If the native runtime binary is unavailable, the CLI falls back to the Node.js compatibility runtime (`src/electron/runtime.js`), which is API-only and does not provide a native desktop window.
Every new release tag (pushed as `v*`) is pre-compiled in CI and published as
platform-native, double-clickable installers on the [Releases page]:
## Build from source
| Platform | Installer | What it does |
|---|---|---|
| macOS | `Gelectron-<version>-arm64.dmg` / `-x64.dmg` | Contains `Install gelectron.pkg`, which installs the runtime + compat layer **plus a private Node.js** to `/usr/local/lib/gelectron` and symlinks `gelectron` into `/usr/local/bin` |
| Windows | `Gelectron-<version>-x64.exe` / `-arm64.exe` | NSIS installer → `C:\Program Files\Gelectron` (runtime + compat + private Node.js), adds it to the system PATH, Start Menu + uninstaller |
| Linux | `Gelectron-<version>-x86_64.AppImage` / `-aarch64.AppImage` | Fully self-contained (runtime + compat + private Node.js), just run it |
### Prerequisites
After installing, `gelectron /path/to/electron-app` works from anywhere, and no
system Node.js install is required — every installer bundles its own runtime.
Apps packaged with `gelectron-packager` are equally self-contained: double-click
a packaged app and it runs with no gelectron and no Node.js installed.
> macOS installers are ad-hoc signed (no Developer ID), so on another Mac the
> first launch shows a Gatekeeper "unidentified developer" warning — right-click
> → Open to run it.
### Install from GitHub Releases (no npm)
Every new release tag (pushed as `v*`) is pre-compiled in CI and published as
a self-contained installer archive. Install the latest pre-built runtime with
a single command — no Rust toolchain, no npm:
```bash
# macOS / Linux
curl -fsSL https://raw.githubusercontent.com/mileswolfallen2/gelectron/main/scripts/install-release.sh | bash
# Windows (PowerShell)
irm https://raw.githubusercontent.com/mileswolfallen2/gelectron/main/scripts/install-release.ps1 | iex
```
The installer downloads `gelectron-<version>-<platform>-<arch>.tar.gz` (or
`.zip`) from the latest GitHub Release and puts the `gelectron` binary plus
the JS compatibility layer into `~/.local/bin` (macOS/Linux) or
`%LOCALAPPDATA%\gelectron\bin` (Windows). Customize with:
```bash
bash scripts/install-release.sh --version v0.1.1 # specific tag
bash scripts/install-release.sh --prefix ~/bin # custom location
bash scripts/install-release.sh --uninstall # remove
```
Archives can also be downloaded directly from the [Releases page] and
unpacked manually — the binary just needs the `compat/` folder next to it.
> The `gelectron-core` npm package is the recommended distribution channel. Building from source (below) is only needed if you're developing Gelectron itself or want the bleeding-edge version.
[Releases page]: https://github.com/mileswolfallen2/gelectron/releases
### Prerequisites (for building from source)
- Rust 1.75+ (`rustup.rs`)
- Rust (stable)
- Node.js 18+
- npm
### Build & Run (from source)
### Build and run
```bash
git clone https://github.com/mileswolfallen2/gelectron.git
cd gelectron
npm install
# Build the standalone native binary
# Build native runtime binary
cargo build --release -p gelectron
# Run the demo app
cargo run --release -p gelectron -- demo/
# Or run any Electron app
cargo run --release -p gelectron -- /path/to/electron-app
```
### CLI (Node.js fallback)
The `gelectron` command automatically locates the native runtime — the release
build, an npm/installer-installed binary (`PATH`, `/usr/local/bin`,
`/usr/local/lib/gelectron`, `Program Files\Gelectron`, etc.) or a fresh
`target/{release,debug}/gelectron`. If none is found it falls back to a
pure-Node.js shim:
```bash
node cli/gelectron.js /path/to/electron-app
```
> In fallback mode no real window is created — only the JS API layer loads. Use the native binary for actual rendering.
## How It Works
Gelectron has two execution paths:
### 1. Native Binary (`gelectron-app` crate)
A standalone Rust binary using **tao** (windowing) and **wry** (WebView). It has two modes:
**Node.js mode** (default):
1. Reads the target app's `package.json` to find the main script
2. Generates a Node.js setup script that patches `require('electron')` to point at Gelectron's JS compatibility layer
3. Spawns Node.js as a child process with piped stdin/stdout
4. Runs a tao event loop with wry WebView windows
5. Communicates with Node.js via JSON-line IPC (`create-window`, `load-url`, `ipc-message`, …)
**WebView-only mode** (`--no-node`):
1. Loads the JS compatibility layer directly inside the WebView
2. The app's main script runs inside the WKWebView JavaScript context
3. No Node.js process is spawned — saves ~50 MB RSS
4. Some APIs (native dialogs, clipboard, screen info) communicate directly from the WebView to the Rust binary via `window.ipc.postMessage()`
### 2. Node.js Fallback (`cli/gelectron.js`)
When the native binary is not built, the CLI falls back to pure Node.js:
1. Patches `Module._resolveFilename` so `require('electron')` resolves to Gelectron's shim
2. Loads the app's main script — the app runs against the JS compatibility layer
3. No real window is created (API-only mode)
## Architecture
```
┌──────────────────────────────────────────────────┐
│ Gelectron App │
│ (HTML / CSS / JS + package.json) │
│ (Same code as Electron apps) │
└────────────────────┬─────────────────────────────┘
│
┌────────────────────▼─────────────────────────────┐
│ Gelectron Runtime │
│ │
│ ┌────────────────────────────────────────────┐ │
│ │ electron compat layer (JavaScript) │ │
│ │ app · BrowserWindow · Menu · Tray │ │
│ │ ipcMain · ipcRenderer · contextBridge │ │
│ │ dialog · shell · notification │ │
│ └────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────┐ │
│ │ gelectron-app (Rust standalone binary) │ │
│ │ tao · windowing │ │
│ │ wry · WebView (WKWebView / WebView2 / │
│ │ WebKitGTK) │ │
│ └────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────┘
```
## Supported Electron APIs
### Main Process
| Module | Status |
|---|---|
| `app` | Full lifecycle, paths, command line, dock (macOS), `whenReady()` |
| `BrowserWindow` | Create, show/hide, resize, loadURL, loadFile, events, webContents |
| `ipcMain` | `handle()`, `on()`, `removeHandler()`, event emission |
| `Menu` | `buildFromTemplate()`, `popup()`, `setApplicationMenu()` |
| `MenuItem` | All types (normal, checkbox, separator, submenu, role) |
| `Tray` | Create, tooltip, context menu, click events |
| `dialog` | `showOpenDialog()`, `showSaveDialog()`, `showMessageBox()`, `showErrorBox()` |
| `shell` | `openExternal()`, `showItemInFolder()`, `openPath()` |
| `Notification` | Full API + native OS notifications (macOS Notification Center, Windows Toasts, Linux D-Bus); click/action/reply/close/failed events |
| `nativeImage` | Create from path/buffer, resize, crop, PNG/JPEG export |
| `safeStorage` | Encrypt/decrypt via system keyring |
| `contextBridge` | `exposeInMainWorld()` for secure preload |
| `webContents` | `send()`, `executeJavaScript()`, `openDevTools()`, navigation |
### Renderer Process
| Module | Status |
|---|---|
| `ipcRenderer` | `invoke()`, `send()`, `on()`, `removeListener()` |
### Compatibility Shims
| Module | Status |
|---|---|
| `screen` | Native display enumeration (`getAllDisplays`, `getPrimaryDisplay`, `getDisplayMatching`, …) |
| `clipboard` | Full API (`readText`/`writeText`/`readHTML`/`writeHTML`/`readBookmark`/`readFindText`/`availableFormats`) |
| `nativeTheme` | `shouldUseDarkColors`, `themeSource`, `themes` (native-backed when available) |
| `systemPreferences` | Basic stubs |
| `powerMonitor` | Event stubs |
| `globalShortcut` | Register/unregister stubs |
| `session` | Cookies, protocol, permissions (stub) |
| `net` | `fetch()` proxy |
| `autoUpdater` | Full (sha512-verified, atomic apply) |
## Demo App
A minimal demo that renders HTML/CSS/JS in a real window:
```bash
# Run demo app
cargo run --release -p gelectron -- demo/
```
The demo includes:
- Interactive counter (DOM updates via JS)
- Live clock driven by `requestAnimationFrame`
- Animated canvas with moving shapes
- CSS grid, gradients, transitions, and flexbox
## Architecture (high level)
### Demo source
Gelectron is composed of:
```
demo/
├── package.json # { "main": "main.js" }
├── main.js # Creates BrowserWindow, loads index.html
└── index.html # HTML + CSS + JavaScript
```
1. **Rust runtime (`crates/gelectron-app`)**
- Native app process
- Window/event loop via `tao`
- Native web view via `wry`
### Running the demo
2. **JS compatibility layer (`src/electron/`)**
- `require('electron')`-style API surface
- Main-process and renderer shims
- IPC bridge to the native runtime
`demo/main.js`:
3. **CLI launcher (`cli/gelectron.js`)**
- Resolves app entry point
- Locates and launches the native runtime when present
- Falls back to JS runtime when native binary is not found
```javascript
const { app, BrowserWindow } = require('electron');
const path = require('path');
## API compatibility
app.whenReady().then(() => {
const win = new BrowserWindow({ width: 900, height: 680 });
win.loadFile(path.join(__dirname, 'index.html'));
});
Gelectron exposes Electron-like modules from `src/electron/index.js`, including:
app.on('window-all-closed', () => app.quit());
```
- `app`
- `BrowserWindow`
- `ipcMain`
- `Menu` / `MenuItem`
- `Tray`
- `dialog`
- `shell`
- `Notification`
- `nativeImage`
- `safeStorage`
- `contextBridge`
- `webContents`
- `autoUpdater`
- `clipboard`
- `screen`
- `nativeTheme`
- `session` (stubbed behavior)
- plus additional stubs such as `systemPreferences`, `powerMonitor`, and `globalShortcut`
## Project Structure
Because behavior is still maturing, treat compatibility as best-effort rather than complete parity.
```
gelectron/
├── Cargo.toml # Rust workspace root
├── package.json # npm package
├── cli/
│ └── gelectron.js # CLI entry point (Node.js fallback)
├── src/
│ └── electron/ # JS Electron compatibility layer
│ ├── index.js # Main exports (require('electron'))
│ ├── app.js # app lifecycle
│ ├── browser-window.js # BrowserWindow + WebContents
│ ├── ipc-main.js # ipcMain
│ ├── ipc-renderer.js # ipcRenderer
│ ├── context-bridge.js # contextBridge
│ ├── menu.js # Menu + MenuItem
│ ├── tray.js # Tray
│ ├── dialog.js # File/message dialogs
│ ├── shell.js # Shell operations
│ ├── notification.js # Notifications
│ ├── native-image.js # Image handling
│ ├── clipboard.js # Clipboard
│ ├── screen.js # Display enumeration
│ ├── nativeTheme.js # Dark mode / theme
│ ├── safe-storage.js # Encryption
│ ├── web-contents.js # webContents utilities
│ ├── auto-updater.js # autoUpdater (electron-updater compatible)
│ ├── native-bridge.js # IPC to Rust binary
│ ├── preload-loader.js # Preload injection
│ └── runtime.js # Node.js fallback runtime
├── crates/
│ ├── gelectron-core/ # N-API addon (Rust → Node.js)
│ │ ├── Cargo.toml
│ │ └── src/
│ │ ├── lib.rs # N-API entry: init(), get_platform()
│ │ ├── app.rs # App lifecycle (native)
│ │ ├── browser_window.rs # Window management (native)
│ │ ├── servo_host.rs # Servo engine hooks (stub, not in use)
│ │ ├── event_loop.rs # Event loop bridge
│ │ ├── ipc.rs # IPC bridge
│ │ ├── protocol.rs # Custom protocol handler
│ │ ├── menu.rs # Native menus (muda)
│ │ ├── tray.rs # System tray (tray-icon)
│ │ ├── dialog.rs # File dialogs (rfd)
│ │ ├── shell.rs # Shell operations
│ │ ├── notification.rs # Notifications (notify-rust)
│ │ ├── native_image.rs # Image processing (image)
│ │ ├── safe_storage.rs # Secure storage (keyring)
│ │ ├── context_bridge.rs # Context bridge (native)
│ │ └── web_contents.rs # WebContents (native)
│ └── gelectron-app/ # Standalone native binary
│ ├── Cargo.toml
│ └── src/
│ └── main.rs # tao + wry event loop, Node.js spawner
├── demo/ # Demo app
│ ├── package.json
│ ├── main.js
│ └── index.html
├── packager/ # gelectron-packager CLI
│ ├── package.json
│ └── bin/
│ └── gelectron-packager.js # Packaging tool
└── npm/
└── darwin-arm64/ # Platform-specific npm packages
```
## Packaging
## Packaging for Distribution
Use `gelectron-packager` to build standalone executables for Mac, Windows, and Linux:
`gelectron-packager` is included as a CLI tool:
```bash
# Install the packager
cd packager && npm link && cd ..
# Package for current platform
gelectron-packager --dir ./demo --name MyApp
```
# Package for a specific platform
You can also specify target platform/arch:
```bash
gelectron-packager --dir ./my-app --name MyApp --platform darwin --arch arm64
gelectron-packager --dir ./my-app --name MyApp --platform win32 --arch x64
gelectron-packager --dir ./my-app --name MyApp --platform linux --arch x64
```
### What the packager does
1. Finds your gelectron runtime — the built binary (`target/release/gelectron`),
or any gelectron installed through the installers/npm (PATH,
`/usr/local/lib/gelectron`, `Program Files\Gelectron`, …)
2. Downloads a bundled Node.js runtime (~20 MB) for the target platform
3. Copies your app source and `node_modules`
4. Includes the Electron compatibility layer (`src/electron/`)
5. Creates a self-contained, standalone distributable — no additional files needed at runtime:
- **macOS**: `.app` bundle (double-click to run, can be moved anywhere)
- **Windows**: Directory with `.exe` + `.bat` launcher
- **Linux**: Directory with launcher script + `.desktop` file
> The packaged app bundles the Rust binary, Node.js runtime, your source code, `node_modules`, and the Electron compat layer. You can delete the original project files and the packaged app will still run.
### macOS .app bundle structure
## Repository layout
```text
gelectron/
├── cli/ # CLI entrypoint
├── src/electron/ # Electron compatibility layer
├── crates/gelectron-app/ # Rust native runtime binary
├── crates/gelectron-core/ # Rust native core (N-API related)
├── packager/ # gelectron-packager
├── demo/ # Example app
└── npm/ # Platform npm package assets
```
MyApp.app/
Contents/
MacOS/
MyApp # Bash launcher (sets PATH, calls gelectron-bin)
gelectron-bin # Rust binary (tao + wry)
node # Bundled Node.js
compat/ # Electron compatibility layer
node_modules/ # Production dependencies
Resources/
app/ # Your app source
Info.plist
```
## Building for Production
### Standalone binary (recommended)
```bash
cargo build --release -p gelectron
```
### N-API addon (for Node.js integration)
```bash
cargo build --release -p gelectron-core
```
The N-API addon compiles to a `.node` file that can be loaded directly into Node.js.
## Publishing to npm
Gelectron uses [napi-rs](https://napi.rs/) to produce platform-specific native addons. The main `gelectron` npm package ships platform-specific optional packages so that `npm install gelectron` automatically pulls the right binary for the user's OS.
### Prerequisites
- Rust 1.75+ (`rustup.rs`)
- Node.js 18+
- npm
- An [npm account](https://www.npmjs.com/signup) with publish access
- Each target platform needs to be built on that platform (or via CI)
### Step 1: Build the native addon for your platform
```bash
# Build the N-API addon (produces crates/gelectron-core/*.node)
npm run build
# Or build with debug symbols for development
npm run build:debug
```
This compiles the Rust N-API addon (`gelectron-core`) into a `.node` file that Node.js can load.
### Step 2: Create platform-specific npm packages
For each platform you want to support, create a directory under `npm/` with a `package.json`:
```bash
# Example for macOS ARM64
mkdir -p npm/darwin-arm64
cat > npm/darwin-arm64/package.json << 'EOF'
{
"name": "gelectron-darwin-arm64",
"version": "0.1.0",
"description": "Gelectron native addon for macOS ARM64",
"main": "index.darwin-arm64.node",
"files": ["index.darwin-arm64.node"],
"os": ["darwin"],
"cpu": ["arm64"],
"license": "MIT"
}
EOF
# Copy the built .node file
cp crates/gelectron-core/gelectron_core.darwin-arm64.node npm/darwin-arm64/
```
Repeat for each platform:
| Directory | os | cpu |
|---|---|---|
| `npm/darwin-arm64/` | `darwin` | `arm64` |
| `npm/darwin-x64/` | `darwin` | `x64` |
| `npm/win32-x64-msvc/` | `win32` | `x64` |
| `npm/win32-arm64-msvc/` | `win32` | `arm64` |
| `npm/linux-x64-gnu/` | `linux` | `x64` |
| `npm/linux-arm64-gnu/` | `linux` | `arm64` |
### Step 3: Publish platform packages first
Each platform package must be published before the main package:
```bash
# Publish each platform package
npm publish npm/darwin-arm64 --access public
npm publish npm/darwin-x64 --access public
npm publish npm/win32-x64-msvc --access public
# ... etc for each platform
```
### Step 4: Prepare and publish the main package
```bash
# Run prepublish hook (generates napi artifacts metadata)
npm run prepublishOnly
# Publish the main package
npm publish --access public
```
### Using napi-rs CLI (recommended)
The `@napi-rs/cli` handles cross-compilation and artifact management:
```bash
# Install napi-rs CLI globally (if not already installed)
npm install -g @napi-rs/cli
# Build for all configured targets
napi build --platform --release
# Generate artifact metadata for npm publishing
napi prepublish -t npm
# Create a GitHub release with platform binaries
napi artifacts
```
### CI/CD Publishing (recommended)
For multi-platform publishing, use GitHub Actions to build on each OS:
```yaml
# .github/workflows/publish.yml
name: Publish to npm
on:
push:
tags: ['v*']
jobs:
build:
strategy:
matrix:
include:
- os: macos-latest
target: aarch64-apple-darwin
- os: macos-latest
target: x86_64-apple-darwin
- os: ubuntu-latest
target: x86_64-unknown-linux-gnu
- os: windows-latest
target: x86_64-pc-windows-msvc
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- uses: actions/setup-node@v4
with:
node-version: 18
- run: npm ci
- run: napi build --platform --release --target ${{ matrix.target }}
- run: napi prepublish -t npm
- uses: actions/upload-artifact@v4
with:
name: bindings-${{ matrix.target }}
path: npm/
publish:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
- run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
```
### Quick publish (single platform)
If you only need to publish for your current platform:
```bash
# Build
npm run build
# Preview what will be published
npm pack --dry-run
# Publish
npm run prepublishOnly
npm publish --access public
```
> **Tip:** Use `npm pack` to create a tarball locally and inspect it before publishing. Run `npm pack` and then `tar -tzf gelectron-0.1.0.tgz` to verify the contents.
## Testing with OmniEmu2.0
OmniEmu2.0 is a full Electron app used to validate Gelectron compatibility:
```bash
# From the gelectron directory
cargo run --release -p gelectron -- /path/to/OmniEmu2.0
```
Key APIs exercised by OmniEmu2.0:
- `app`, `BrowserWindow`, `Tray`, `Menu`, `nativeImage`, `dialog`
- `electron-updater` (autoUpdater stub)
- `contextBridge`, `ipcRenderer`
- File loading (`loadFile`), window events
## CLI Options
```bash
gelectron <path-to-app> # Run an Electron app
gelectron <file.js> # Run a main process script directly
gelectron --version # Print version
gelectron --help # Show help
```
## Environment Variables
| Variable | Description |
|---|---|
| `GELECTRON_DEV=1` | Enable development mode |
| `GELECTRON_LOG=1` | Enable verbose logging |
| `VITE_DEV_SERVER_URL=<url>` | Connect to a Vite dev server |
| `RUST_LOG=info` | Enable Rust-side logging |
## Known Limitations
- Auto-updater is a no-op stub (returns "no update available")
- Some Electron APIs are stubs (marked in compatibility table)
- Preload scripts are injected via WebView init scripts, not true Electron preload isolation
- Native menu rendering is macOS-only (Windows/Linux fall back to JS-only menus)
## Roadmap
- [x] JS Electron API compatibility layer
- [x] Standalone native binary (tao + wry)
- [x] Node.js fallback runtime
- [x] JSON-line IPC between Rust and Node.js
- [x] WebView-only mode (`--no-node`)
- [x] `electron-updater` compatibility
- [ ] Multi-window support
- [ ] Custom protocol handlers (`gelectron://`)
- [ ] DevTools integration
- [ ] App sandboxing
- [x] Package/distribution tooling
- [x] Performance benchmarks vs Electron
- [ ] Cross-platform verification (Windows, Linux)
## Contributing
1. Fork the repo
2. Create a feature branch
3. Make your changes
4. Run `cargo build --release -p gelectron` and test with `cargo run --release -p gelectron -- demo/`
5. Submit a PR
## License
MIT — see [LICENSE](LICENSE)
See [`CONTRIBUTING.md`](CONTRIBUTING.md).
@@ -0,0 +1,28 @@
{
"timestamp": "2026-09-19T20:41:56Z",
"runs": 10,
"platform": "Darwin arm64",
"electron": {
"version": "v43.2.0",
"avg_startup_s": 5.669,
"min_startup_s": 5.661,
"max_startup_s": 5.676,
"avg_memory_mb": 579.7,
"min_memory_mb": 577.4,
"max_memory_mb": 589.4,
"runtime_size_mb": 296,
"raw_times": [5.668,5.667,5.661,5.672,5.663,5.673,5.674,5.667,5.676,5.669],
"raw_memory": [589.4,580.4,577.8,578.0,577.7,577.8,577.8,581.1,577.4,579.8]
},
"gelectron": {
"avg_startup_s": 5.625,
"min_startup_s": 5.614,
"max_startup_s": 5.634,
"avg_memory_mb": 139.1,
"min_memory_mb": 138.6,
"max_memory_mb": 139.4,
"runtime_size_mb": 4,
"raw_times": [5.634,5.628,5.624,5.614,5.628,5.625,5.618,5.625,5.623,5.633],
"raw_memory": [138.6,139.4,139.0,139.2,139.4,139.1,139.1,139.0,139.2,139.1]
}
}
+7 -1
View File
@@ -15,7 +15,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
env_logger = { workspace = true }
wry = "0.47"
wry = { version = "0.47", features = ["devtools"] }
tao = "0.30"
muda = "0.15"
arboard = "3"
@@ -30,3 +30,9 @@ libc = "0.2"
objc2 = "0.6"
objc2-app-kit = "0.3"
objc2-foundation = "0.3"
objc2-core-graphics = "0.3"
# Version-aligned interop types for wry's internal macOS WKWebView
# (wry 0.47 is built against the objc2 0.5 family, so calls into the
# webview handle must use the same versions to keep pointer types compatible).
block2-v05 = { package = "block2", version = "0.5" }
objc2-v05 = { package = "objc2", version = "0.5" }
+506 -3
View File
@@ -52,6 +52,37 @@ enum ToRust {
Minimize { id: u32 },
#[serde(rename = "maximize")]
Maximize { id: u32 },
#[serde(rename = "unmaximize")]
Unmaximize { id: u32 },
#[serde(rename = "restore")]
Restore { id: u32 },
#[serde(rename = "go-back")]
GoBack { id: u32 },
#[serde(rename = "go-forward")]
GoForward { id: u32 },
#[serde(rename = "open-devtools")]
OpenDevTools { id: u32 },
#[serde(rename = "close-devtools")]
CloseDevTools { id: u32 },
#[serde(rename = "toggle-devtools")]
ToggleDevTools { id: u32 },
#[serde(rename = "inspect-element")]
InspectElement { id: u32, x: f64, y: f64 },
#[serde(rename = "print-page")]
PrintPage { id: u32 },
#[serde(rename = "capture-page")]
CapturePage { id: u32, request_id: String },
#[serde(rename = "print-to-pdf")]
PrintToPdf {
id: u32,
request_id: String,
#[serde(default)]
options: Option<serde_json::Value>,
},
#[serde(rename = "set-titlebar-overlay")]
SetTitlebarOverlay { id: u32, overlay: serde_json::Value },
#[serde(rename = "set-background-color")]
SetBackgroundColor { id: u32, color: String },
#[serde(rename = "close")]
Close { id: u32 },
#[serde(rename = "ipc-message")]
@@ -200,12 +231,18 @@ struct WindowOpts {
show: Option<bool>,
#[serde(default)]
resizable: Option<bool>,
#[serde(default)]
#[serde(default, alias = "alwaysOnTop")]
always_on_top: Option<bool>,
#[serde(default)]
fullscreen: Option<bool>,
#[serde(default)]
icon: Option<String>,
#[serde(default, alias = "titlebarStyle")]
titlebar_style: Option<String>,
#[serde(default, alias = "titlebarOverlay")]
titlebar_overlay: Option<serde_json::Value>,
#[serde(default, alias = "backgroundColor")]
background_color: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Default, Clone)]
@@ -765,7 +802,7 @@ fn create_webview(
WebViewBuilder::new()
.with_url(url)
.with_initialization_script(init)
.with_devtools(false)
.with_devtools(true)
.with_ipc_handler(move |req| {
let body = req.body().to_string();
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&body) {
@@ -811,7 +848,7 @@ fn create_initial_webview_window(
match WebViewBuilder::new()
.with_url("about:blank")
.with_initialization_script(&init_script)
.with_devtools(false)
.with_devtools(true)
.with_ipc_handler(move |req| {
let body = req.body().to_string();
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&body) {
@@ -1521,6 +1558,15 @@ fn handle_to_rust(
}
};
let wid = window.id();
// Apply macOS title bar / background chrome so the top bar
// color, transparency and initial background are correct at
// first paint (runs before the window is inserted/displayed).
apply_window_chrome(
&window,
options.titlebar_style.as_deref(),
options.titlebar_overlay.as_ref(),
options.background_color.as_deref(),
);
if let Some(icon) = options
.icon
.as_deref()
@@ -1995,9 +2041,466 @@ fn handle_to_rust(
pair.window.set_maximized(true);
}
}
ToRust::Unmaximize { id } => {
if let Some(pair) = st.windows.get(&id) {
pair.window.set_maximized(false);
}
}
ToRust::Restore { id } => {
if let Some(pair) = st.windows.get(&id) {
pair.window.set_minimized(false);
pair.window.set_maximized(false);
}
}
ToRust::GoBack { id } => {
if let Some(pair) = st.windows.get(&id) {
log::info!("Window {} go back", id);
if let Some(webview) = &pair.webview {
let _ = webview.evaluate_script("history.back()");
}
}
}
ToRust::GoForward { id } => {
if let Some(pair) = st.windows.get(&id) {
log::info!("Window {} go forward", id);
if let Some(webview) = &pair.webview {
let _ = webview.evaluate_script("history.forward()");
}
}
}
ToRust::OpenDevTools { id } => {
if let Some(pair) = st.windows.get(&id) {
if let Some(webview) = &pair.webview {
log::info!("Window {} opening devtools", id);
webview.open_devtools();
}
}
}
ToRust::CloseDevTools { id } => {
if let Some(pair) = st.windows.get(&id) {
if let Some(webview) = &pair.webview {
log::info!("Window {} closing devtools", id);
webview.close_devtools();
}
}
}
ToRust::ToggleDevTools { id } => {
if let Some(pair) = st.windows.get(&id) {
if let Some(webview) = &pair.webview {
if webview.is_devtools_open() {
webview.close_devtools();
} else {
webview.open_devtools();
}
}
}
}
ToRust::InspectElement { id, x, y } => {
log::debug!("Window {} inspect element at {},{}", id, x, y);
}
ToRust::PrintPage { id } => {
if let Some(pair) = st.windows.get(&id) {
log::info!("Window {} printing", id);
if let Some(webview) = &pair.webview {
let _ = webview.print();
}
}
}
ToRust::CapturePage { id, request_id } => {
capture_page_for_window(st, id, request_id);
}
ToRust::PrintToPdf {
id,
request_id,
options,
} => {
print_to_pdf_for_window(st, id, request_id, options);
}
ToRust::SetTitlebarOverlay { id, overlay } => {
if let Some(pair) = st.windows.get(&id) {
if let Some(style) = overlay.get("titleBarStyle").and_then(|v| v.as_str()) {
apply_titlebar_style(&pair.window, Some(style));
}
apply_titlebar_overlay(&pair.window, &overlay);
}
}
ToRust::SetBackgroundColor { id, color } => {
if let Some(pair) = st.windows.get(&id) {
apply_background_color(&pair.window, &color);
}
}
}
}
// WebContents.capturePage() - snapshot the webview as a PNG. Implemented
// natively on macOS (WKWebView takeSnapshot) and reported as unsupported
// elsewhere, mirroring a browser that cannot access the compositor surface.
fn capture_page_for_window(st: &mut AppState, window_id: u32, request_id: String) {
#[cfg(target_os = "macos")]
{
capture_page_for_window_macos(st, window_id, request_id);
}
#[cfg(not(target_os = "macos"))]
{
log::warn!("capturePage unsupported on this platform");
if let Some(ref tx) = st.response_tx {
let _ = tx.send((
request_id,
serde_json::json!({ "error": "capturePage is not supported on this platform" }),
));
}
}
}
// WebContents.printToPDF() - generate a PDF of the webview content. Implemented
// natively on macOS (WKWebView createPDF) and reported as unsupported elsewhere.
fn print_to_pdf_for_window(
st: &mut AppState,
window_id: u32,
request_id: String,
options: Option<serde_json::Value>,
) {
#[cfg(target_os = "macos")]
{
print_to_pdf_for_window_macos(st, window_id, request_id, options);
}
#[cfg(not(target_os = "macos"))]
{
log::warn!("printToPDF unsupported on this platform");
if let Some(ref tx) = st.response_tx {
let _ = tx.send((
request_id,
serde_json::json!({ "error": "printToPDF is not supported on this platform" }),
));
}
}
}
#[cfg(target_os = "macos")]
fn capture_page_for_window_macos(st: &mut AppState, window_id: u32, request_id: String) {
use wry::WebViewExtMacOS;
if let Some(pair) = st.windows.get(&window_id) {
if let Some(webview) = &pair.webview {
let wv = webview.webview();
let tx = st.response_tx.clone();
let block = block2_v05::RcBlock::new(
move |image: *mut objc2_v05::runtime::AnyObject, _err: *mut objc2_v05::runtime::AnyObject| {
let result = if image.is_null() {
serde_json::json!({ "error": "Failed to capture page" })
} else {
match unsafe { ns_image_to_png(image) } {
Some(png_b64) => serde_json::json!({ "data": png_b64 }),
None => serde_json::json!({ "error": "Failed to encode captured page" }),
}
};
if let Some(ref tx) = tx {
let _ = tx.send((request_id.clone(), result));
}
},
);
// Safety: message send to a live WKWebView instance on the main thread.
unsafe {
let () = objc2_v05::msg_send![
&wv,
takeSnapshotWithConfiguration: std::ptr::null::<objc2_v05::runtime::AnyObject>(),
completionHandler: &*block
];
}
return;
}
}
if let Some(ref tx) = st.response_tx {
let _ = tx.send((request_id, serde_json::json!({ "error": "Window not found" })));
}
}
#[cfg(target_os = "macos")]
fn print_to_pdf_for_window_macos(
st: &mut AppState,
window_id: u32,
request_id: String,
_options: Option<serde_json::Value>,
) {
use wry::WebViewExtMacOS;
if let Some(pair) = st.windows.get(&window_id) {
if let Some(webview) = &pair.webview {
let wv = webview.webview();
let tx = st.response_tx.clone();
let block = block2_v05::RcBlock::new(
move |pdf: *mut objc2_v05::runtime::AnyObject, _err: *mut objc2_v05::runtime::AnyObject| {
let result = if pdf.is_null() {
serde_json::json!({ "error": "Failed to generate PDF" })
} else {
match unsafe { ns_data_to_base64(pdf) } {
Some(b64) => serde_json::json!({ "data": b64 }),
None => serde_json::json!({ "error": "Failed to encode generated PDF" }),
}
};
if let Some(ref tx) = tx {
let _ = tx.send((request_id.clone(), result));
}
},
);
// Safety: message send to a live WKWebView instance on the main thread.
unsafe {
let () = objc2_v05::msg_send![
&wv,
createPDFWithConfiguration: std::ptr::null::<objc2_v05::runtime::AnyObject>(),
completionHandler: &*block
];
}
return;
}
}
if let Some(ref tx) = st.response_tx {
let _ = tx.send((request_id, serde_json::json!({ "error": "Window not found" })));
}
}
#[cfg(target_os = "macos")]
unsafe fn ns_image_to_png(ns_image: *mut objc2_v05::runtime::AnyObject) -> Option<String> {
let object: *mut objc2_v05::runtime::AnyObject = ns_image.cast();
if object.is_null() {
return None;
}
// NSImage -> TIFF NSData
let tiff: *mut objc2_v05::runtime::AnyObject = objc2_v05::msg_send![object, TIFFRepresentation];
if tiff.is_null() {
return None;
}
// NSBitmapImageRep from TIFF data
let rep: *mut objc2_v05::runtime::AnyObject =
objc2_v05::msg_send![objc2_v05::class!(NSBitmapImageRep), imageRepWithData: tiff];
if rep.is_null() {
return None;
}
// PNG NSData (NSBitmapImageFileTypePNG == 4, `properties` may be nil)
let png: *mut objc2_v05::runtime::AnyObject = objc2_v05::msg_send![
rep,
representationUsingType: 4u64,
properties: std::ptr::null::<objc2_v05::runtime::AnyObject>()
];
if png.is_null() {
return None;
}
ns_data_to_base64(png)
}
#[cfg(target_os = "macos")]
unsafe fn ns_data_to_base64(data: *mut objc2_v05::runtime::AnyObject) -> Option<String> {
use base64::Engine;
let object: *mut objc2_v05::runtime::AnyObject = data.cast();
if object.is_null() {
return None;
}
let len: usize = objc2_v05::msg_send![object, length];
if len == 0 {
return None;
}
let bytes: *const std::ffi::c_void = objc2_v05::msg_send![object, bytes];
if bytes.is_null() {
return None;
}
let slice = std::slice::from_raw_parts(bytes.cast::<u8>(), len);
Some(base64::engine::general_purpose::STANDARD.encode(slice))
}
// Window title bar / background chrome (macOS). These let apps color and
// (optionally) clear the top bar. Colors are applied to the NSWindow via
// public API: `titlebarAppearsTransparent` lets the window background show
// through the title bar, and `backgroundColor` paints it.
fn apply_window_chrome(
window: &tao::window::Window,
titlebar_style: Option<&str>,
titlebar_overlay: Option<&serde_json::Value>,
background_color: Option<&str>,
) {
apply_titlebar_style(window, titlebar_style);
if let Some(overlay) = titlebar_overlay {
apply_titlebar_overlay(window, overlay);
}
if let Some(color) = background_color {
if !color.trim().is_empty() {
apply_background_color(window, color);
}
}
}
#[cfg(target_os = "macos")]
fn apply_titlebar_style(window: &tao::window::Window, style: Option<&str>) {
use tao::platform::macos::WindowExtMacOS;
if let Some(style) = style {
if matches!(
style,
"hidden" | "hiddenInset" | "customButtonsOnHover"
) {
window.set_titlebar_transparent(true);
log::info!("Title bar style '{}' applied (transparent)", style);
}
}
}
#[cfg(not(target_os = "macos"))]
fn apply_titlebar_style(_window: &tao::window::Window, _style: Option<&str>) {}
#[cfg(target_os = "macos")]
fn apply_titlebar_overlay(window: &tao::window::Window, overlay: &serde_json::Value) {
use objc2::MainThreadMarker;
use objc2_app_kit::NSWindow;
use tao::platform::macos::WindowExtMacOS;
let Some(_mtm) = MainThreadMarker::new() else {
log::warn!("Title bar overlay skipped: not on main thread");
return;
};
// Height/symbolColor only apply to custom-drawn title bars (Windows);
// on macOS we accept them for API parity but only color paints anything.
if let Some(height) = overlay.get("height") {
log::debug!("Title bar overlay height ignored on macOS: {}", height);
}
if let Some(symbol) = overlay.get("symbolColor") {
log::debug!("Title bar overlay symbolColor ignored on macOS: {}", symbol);
}
let transparent = overlay
.get("transparent")
.and_then(|v| v.as_bool())
.unwrap_or(false);
match overlay.get("color").and_then(|c| c.as_str()) {
Some(color_str) if parse_css_color(color_str).is_some() => {
let (r, g, b, a) = parse_css_color(color_str).unwrap();
let ns_color = objc2_app_kit::NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a);
let ptr = window.ns_window() as *mut NSWindow;
if ptr.is_null() {
return;
}
unsafe {
let ns_window = &*ptr;
ns_window.setBackgroundColor(Some(&ns_color));
ns_window.setTitlebarAppearsTransparent(true);
}
log::info!("Title bar overlay color applied: {}", color_str);
}
Some(other) => {
log::warn!("Title bar overlay color '{}' is not a supported color", other);
}
None if transparent => {
// Fully clear top bar: just lift the title bar, keep the existing
// window background underneath.
let ptr = window.ns_window() as *mut NSWindow;
if !ptr.is_null() {
unsafe {
(*ptr).setTitlebarAppearsTransparent(true);
}
}
log::info!("Title bar made transparent");
}
None => {}
}
}
#[cfg(not(target_os = "macos"))]
fn apply_titlebar_overlay(_window: &tao::window::Window, _overlay: &serde_json::Value) {
log::warn!("Title bar overlay is only supported on macOS");
}
#[cfg(target_os = "macos")]
fn apply_background_color(window: &tao::window::Window, color: &str) {
use objc2::MainThreadMarker;
use objc2_app_kit::NSWindow;
use tao::platform::macos::WindowExtMacOS;
let Some(_mtm) = MainThreadMarker::new() else {
log::warn!("Background color skipped: not on main thread");
return;
};
let Some((r, g, b, a)) = parse_css_color(color) else {
log::warn!("Background color '{}' is not a supported color", color);
return;
};
let ns_color = objc2_app_kit::NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a);
let ptr = window.ns_window() as *mut NSWindow;
if ptr.is_null() {
return;
}
unsafe {
(*ptr).setBackgroundColor(Some(&ns_color));
}
log::info!("Window background color applied: {}", color);
}
#[cfg(not(target_os = "macos"))]
fn apply_background_color(_window: &tao::window::Window, _color: &str) {}
// Parse CSS-ish colors: #RGB, #RGBA, #RRGGBB, #RRGGBBAA, `rgb(r,g,b)`,
// `rgba(r,g,b,a)` (values as 0-255 or percentages), and `transparent`.
// Returns normalized (r, g, b, a) each in the range 0.0..=1.0.
#[cfg(target_os = "macos")]
fn parse_css_color(input: &str) -> Option<(f64, f64, f64, f64)> {
let s = input.trim();
if s.eq_ignore_ascii_case("transparent") {
return Some((0.0, 0.0, 0.0, 0.0));
}
if let Some(hex) = s.strip_prefix('#') {
let digits: String = match hex.len() {
3 => hex.chars().flat_map(|c| [c, c]).collect(),
4 => hex.chars().flat_map(|c| [c, c]).collect(),
_ => hex.to_string(),
};
fn comp(v: &str) -> Option<f64> {
u8::from_str_radix(v, 16)
.ok()
.map(|x| x as f64 / 255.0)
}
let (r, g, b, a) = match digits.len() {
6 => (
comp(&digits[0..2])?,
comp(&digits[2..4])?,
comp(&digits[4..6])?,
1.0,
),
8 => (
comp(&digits[0..2])?,
comp(&digits[2..4])?,
comp(&digits[4..6])?,
comp(&digits[6..8])?,
),
_ => return None,
};
return Some((r, g, b, a));
}
if s.starts_with("rgb") {
let open = s.find('(')?;
let close = s.rfind(')')?;
if close <= open {
return None;
}
let parts: Vec<&str> = s[open + 1..close].split(',').map(|p| p.trim()).collect();
if parts.len() < 3 {
return None;
}
let parse = |p: &str| -> Option<f64> {
if let Some(pct) = p.strip_suffix('%') {
pct.trim().parse::<f64>().ok().map(|v| v / 100.0)
} else {
p.parse::<f64>().ok().map(|v| v / 255.0)
}
};
let r = parse(parts[0])?;
let g = parse(parts[1])?;
let b = parse(parts[2])?;
let a = if parts.len() >= 4 {
parse(parts[3]).unwrap_or(1.0)
} else {
1.0
};
return Some((r, g, b, a));
}
None
}
// Resolve the Node.js runtime the gelectron engine should spawn. Resolution
// order (first hit wins):
//
+61 -14
View File
@@ -1,15 +1,17 @@
{
"name": "gelectron",
"version": "0.1.0",
"name": "gelectron-core",
"version": "0.1.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "gelectron",
"version": "0.1.0",
"name": "gelectron-core",
"version": "0.1.1",
"license": "MIT",
"bin": {
"gelectron": "cli/gelectron.js"
"gelectron": "cli/gelectron.js",
"gelectron-core": "cli/gelectron.js",
"gelectron-packager": "packager/bin/gelectron-packager.js"
},
"devDependencies": {
"@napi-rs/cli": "^3.0.0",
@@ -19,12 +21,18 @@
"node": ">=18.0.0"
},
"optionalDependencies": {
"gelectron-darwin-arm64": "0.1.0",
"gelectron-darwin-x64": "0.1.0",
"gelectron-linux-arm64-gnu": "0.1.0",
"gelectron-linux-x64-gnu": "0.1.0",
"gelectron-win32-arm64-msvc": "0.1.0",
"gelectron-win32-x64-msvc": "0.1.0"
"gelectron-core-darwin-arm64": "0.1.1",
"gelectron-core-darwin-x64": "0.1.1",
"gelectron-core-linux-arm64-gnu": "0.1.1",
"gelectron-core-linux-x64-gnu": "0.1.1",
"gelectron-core-win32-arm64-msvc": "0.1.1",
"gelectron-core-win32-x64-msvc": "0.1.1",
"gelectron-darwin-arm64": "0.1.1",
"gelectron-darwin-x64": "0.1.1",
"gelectron-linux-arm64-gnu": "0.1.1",
"gelectron-linux-x64-gnu": "0.1.1",
"gelectron-win32-arm64-msvc": "0.1.1",
"gelectron-win32-x64-msvc": "0.1.1"
}
},
"node_modules/@electron-internal/extract-zip": {
@@ -1876,9 +1884,9 @@
}
},
"node_modules/gelectron-darwin-arm64": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/gelectron-darwin-arm64/-/gelectron-darwin-arm64-0.1.0.tgz",
"integrity": "sha512-K0bmA9pfSNlA7CLPD+BOBNdvb0Cb8qMWcYry9BYuP3DC0gcL8Gfq1iM2h3CHNKJB/YEZdBA0uCgTd3+0SMvQ3w==",
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/gelectron-darwin-arm64/-/gelectron-darwin-arm64-0.1.1.tgz",
"integrity": "sha512-7kMnhoY/eaZPzZqQBMPwJR+mcVBMzdMqZ2f6/5f+gjXNVgtccV2ip2bOyggxzoYaU2OMqobM8tGQhIrF0tUgyw==",
"cpu": [
"arm64"
],
@@ -1888,6 +1896,45 @@
"darwin"
]
},
"node_modules/gelectron-darwin-x64": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/gelectron-darwin-x64/-/gelectron-darwin-x64-0.1.1.tgz",
"integrity": "sha512-8CtYzvwyZ8m0+RYnRFXnzvWKPJkh+YvsgTuRumC+aySmppS2nSeFkW9H4gIyqBk7VkiPyHyI6ETmLuY/TqTibA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
]
},
"node_modules/gelectron-win32-arm64-msvc": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/gelectron-win32-arm64-msvc/-/gelectron-win32-arm64-msvc-0.1.1.tgz",
"integrity": "sha512-/dg+fvsD79irxJIjDvUDgdJtdzCM9U1bOzAJpYK0AGw23xG1r2hcRp75TUxhowj5qJ5RrfdhYK8kwllGNvLNlg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/gelectron-win32-x64-msvc": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/gelectron-win32-x64-msvc/-/gelectron-win32-x64-msvc-0.1.1.tgz",
"integrity": "sha512-EbdZD9QS25MkiVVZnEzJxZSfdMD0zdspEIK6mjMIKw42UBrNK9HrF5zS+UIJs/bgBwrL/XEuRISjHeBWICEI/A==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
+209 -15
View File
@@ -21,6 +21,9 @@ class WebContents extends EventEmitter {
this._zoomLevel = 0;
this._userAgent = '';
this._audioMuted = false;
this._isDevToolsOpened = false;
this._history = [];
this._historyIndex = -1;
}
get URL() { return this._url; }
@@ -53,8 +56,10 @@ class WebContents extends EventEmitter {
loadURL(targetUrl) {
this._url = targetUrl;
this._pushHistory(targetUrl);
this._isLoading = true;
this.emit('did-start-loading');
this.emit('did-start-navigation', targetUrl);
if (isNative) {
bridge.loadUrl(this.id, targetUrl);
}
@@ -62,6 +67,7 @@ class WebContents extends EventEmitter {
this._isLoading = false;
this.emit('did-stop-loading');
this.emit('did-finish-load');
this.emit('did-navigate', targetUrl);
this.emit('dom-ready');
}, isNative ? 500 : 100);
return Promise.resolve();
@@ -70,8 +76,10 @@ class WebContents extends EventEmitter {
loadFile(filePath) {
const url = `file://${path.resolve(filePath)}`;
this._url = url;
this._pushHistory(url);
this._isLoading = true;
this.emit('did-start-loading');
this.emit('did-start-navigation', url);
if (isNative) {
bridge.loadFile(this.id, filePath);
}
@@ -79,6 +87,7 @@ class WebContents extends EventEmitter {
this._isLoading = false;
this.emit('did-stop-loading');
this.emit('did-finish-load');
this.emit('did-navigate', url);
this.emit('dom-ready');
}, isNative ? 500 : 100);
return Promise.resolve();
@@ -87,6 +96,7 @@ class WebContents extends EventEmitter {
reload() {
this._isLoading = true;
this.emit('did-start-loading');
this.emit('did-start-navigation', this._url);
if (isNative && this._url) {
bridge.loadUrl(this.id, this._url);
}
@@ -94,14 +104,70 @@ class WebContents extends EventEmitter {
this._isLoading = false;
this.emit('did-stop-loading');
this.emit('did-finish-load');
this.emit('did-navigate', this._url);
}, 50);
return Promise.resolve();
}
canGoBack() { return false; }
canGoForward() { return false; }
goBack() {}
goForward() {}
reloadIgnoringCache() {
return this.reload();
}
goBack() {
if (!this.canGoBack()) return Promise.resolve();
this._historyIndex -= 1;
const url = this._history[this._historyIndex];
this._url = url;
this._isLoading = true;
this.emit('did-start-loading');
this.emit('did-start-navigation', url);
if (isNative) bridge.goBack(this.id);
setTimeout(() => {
this._isLoading = false;
this.emit('did-stop-loading');
this.emit('did-finish-load');
this.emit('did-navigate', url);
}, 50);
return Promise.resolve();
}
goForward() {
if (!this.canGoForward()) return Promise.resolve();
this._historyIndex += 1;
const url = this._history[this._historyIndex];
this._url = url;
this._isLoading = true;
this.emit('did-start-loading');
this.emit('did-start-navigation', url);
if (isNative) bridge.goForward(this.id);
setTimeout(() => {
this._isLoading = false;
this.emit('did-stop-loading');
this.emit('did-finish-load');
this.emit('did-navigate', url);
}, 50);
return Promise.resolve();
}
canGoBack() { return this._historyIndex > 0; }
canGoForward() { return this._historyIndex >= 0 && this._historyIndex < this._history.length - 1; }
_pushHistory(url) {
if (!url) return;
if (this._history[this._historyIndex] === url) return;
this._history = this._history.slice(0, this._historyIndex + 1);
this._history.push(url);
this._historyIndex = this._history.length - 1;
}
getURL() { return this._url; }
getTitle() { return this._title; }
getHistory() { return this._history.slice(); }
stop() {
this._isLoading = false;
this.emit('did-stop-loading');
}
executeJavaScript(code, userGesture = true) {
if (isNative) {
@@ -132,11 +198,27 @@ class WebContents extends EventEmitter {
setAudioMuted(muted) { this._audioMuted = muted; }
isAudioMuted() { return this._audioMuted; }
openDevTools() { console.log('[gelectron] openDevTools'); }
closeDevTools() {}
isDevToolsOpened() { return false; }
toggleDevTools() {}
inspectElement() {}
openDevTools(options) {
if (this._isDevToolsOpened) return;
this._isDevToolsOpened = true;
this.emit('devtools-opened');
if (isNative) bridge.openDevTools(this.id);
}
closeDevTools() {
if (!this._isDevToolsOpened) return;
this._isDevToolsOpened = false;
this.emit('devtools-closed');
if (isNative) bridge.closeDevTools(this.id);
}
toggleDevTools() {
if (this._isDevToolsOpened) this.closeDevTools();
else this.openDevTools();
}
isDevToolsOpened() { return this._isDevToolsOpened; }
inspectElement(x, y) {
if (isNative) bridge.inspectElement(this.id, x || 0, y || 0);
}
inspectServiceWorker() {}
setIgnoreMenuShortcuts() {}
setWindowOpenHandler() { return { action: 'deny' }; }
@@ -144,7 +226,51 @@ class WebContents extends EventEmitter {
setCertificateVerifyProc() {}
setBackgroundColor() {}
isCrashed() { return false; }
capturePage() { return Promise.resolve(null); }
capturePage(rect) {
if (isNative) {
return bridge.capturePage(this.id).then((result) => {
if (result && result.data && typeof result.data === 'string' && result.data.length > 0) {
return NativeImage.createFromDataURL(`data:image/png;base64,${result.data}`);
}
return NativeImage.createEmpty();
}).catch(() => NativeImage.createEmpty());
}
// Without a native runtime there is nothing to snapshot; return an empty
// NativeImage (matching Electron's behaviour for unavailable images) so
// callers that guard on image.isEmpty() do not crash.
return Promise.resolve(NativeImage.createEmpty());
}
print(options, callback) {
if (typeof options === 'function') { callback = options; options = {}; }
if (isNative) {
bridge.printPage(this.id);
} else {
console.log('[gelectron] print called');
}
if (typeof callback === 'function') {
// Node emulates `callback` after the print dialog closes; a false result
// means no failure was reported.
process.nextTick(callback, false);
}
return undefined;
}
printToPDF(options) {
const opts = Object.assign({}, options || {});
if (isNative) {
return bridge.printToPdf(this.id, opts).then((result) => {
if (result && result.error) {
const err = new Error(result.error);
err.code = 'ERR_NOT_SUPPORTED';
throw err;
}
if (result && typeof result.data === 'string') {
return Buffer.from(result.data, 'base64');
}
return Buffer.alloc(0);
});
}
return Promise.resolve(Buffer.alloc(0));
}
getResourceUsage() { return { images: 0, scripts: 0, css: 0, xhr: 0, webgl: 0 }; }
type() { return 'backgroundPage'; }
focused() { return false; }
@@ -181,6 +307,7 @@ class BrowserWindow extends EventEmitter {
decorations: options.decorations !== false,
icon: options.icon || null,
titleBarStyle: options.titleBarStyle || 'default',
titleBarOverlay: this._normalizeOverlay(options.titleBarOverlay || options.topBarColor || null),
trafficLightPosition: options.trafficLightPosition || null,
vibrancy: options.vibrancy || null,
webPreferences: {
@@ -221,6 +348,9 @@ class BrowserWindow extends EventEmitter {
alwaysOnTop: this._options.alwaysOnTop,
fullscreen: this._options.fullscreen,
icon: this._iconToBase64Png(this._options.icon),
titlebarStyle: this._options.titleBarStyle === 'default' ? null : this._options.titleBarStyle,
titlebarOverlay: this._options.titleBarOverlay,
backgroundColor: this._options.backgroundColor,
});
}
@@ -234,6 +364,20 @@ class BrowserWindow extends EventEmitter {
}
}
// Normalize a title bar overlay spec into { color?, symbolColor?, height?, transparent? }.
// Accepts a hex/CSS color string, options object, or null.
_normalizeOverlay(value) {
if (!value) return null;
if (typeof value === 'string') return { color: value };
const out = {};
if (value.color != null) out.color = String(value.color);
if (value.symbolColor != null) out.symbolColor = String(value.symbolColor);
if (value.height != null) out.height = value.height;
if (value.transparent != null) out.transparent = !!value.transparent;
if (value.titleBarStyle != null) out.titleBarStyle = String(value.titleBarStyle);
return out;
}
_iconToBase64Png(icon) {
if (!icon) return null;
try {
@@ -318,8 +462,8 @@ class BrowserWindow extends EventEmitter {
minimize() { if (!this._isDestroyed) { this._isMinimized = true; if (isNative) bridge.minimizeWindow(this.id); this.emit('minimize'); } }
maximize() { if (!this._isDestroyed) { this._isMaximized = true; if (isNative) bridge.maximizeWindow(this.id); this.emit('maximize'); } }
unmaximize() { if (!this._isDestroyed) { this._isMaximized = false; this.emit('unmaximize'); } }
restore() { if (!this._isDestroyed) { this._isMinimized = false; this._isMaximized = false; this.emit('restore'); } }
unmaximize() { if (!this._isDestroyed) { this._isMaximized = false; if (isNative) bridge.unmaximizeWindow(this.id); this.emit('unmaximize'); } }
restore() { if (!this._isDestroyed) { this._isMinimized = false; this._isMaximized = false; if (isNative) bridge.restoreWindow(this.id); this.emit('restore'); } }
setFullScreen(flag) { this._isFullScreen = flag; this.emit('enter-full-screen'); }
isFullScreen() { return this._isFullScreen; }
@@ -387,12 +531,62 @@ class BrowserWindow extends EventEmitter {
setForeground() {}
flashFrame() {}
setIcon() {}
setBackgroundColor(c) { this._options.backgroundColor = c; }
// Electron API: sets the window background color. On macOS this repaints
// the window background (which shows through a transparent title bar).
setBackgroundColor(color) {
this._options.backgroundColor = color || '#ffffff';
if (isNative) bridge.setBackgroundColor(this.id, this._options.backgroundColor);
}
// Electron API: returns the last requested background color.
getBackgroundColor() { return this._options.backgroundColor; }
// Electron API (titleBarOverlay): colors the macOS title bar. Accepts
// `{ color, symbolColor, height }` or a plain color string.
setTitleBarOverlay(overlay) {
const normalized = this._normalizeOverlay(overlay);
if (normalized) this._options.titleBarOverlay = normalized;
if (isNative) bridge.setTitleBarOverlay(this.id, this._options.titleBarOverlay || {});
}
// Gelectron custom API (no Electron equivalent): a clear, single-call way to
// style the macOS top bar. Accepts a color string or an options object:
//
// win.setTopBarColor('#FF5A5F')
// win.setTopBarColor({ color: '#FF5A5F', symbolColor: '#ffffff', transparent: true, titleBarStyle: 'hidden' })
//
// color CSS color (hex, rgb/rgba, or 'transparent'); paints the top bar
// symbolColor accepted for parity (used for custom-drawn title bars on other platforms)
// transparent true → make the title bar clear/see-through; without `color` it just clears it
// height accepted for parity (custom title bar height, other platforms)
// titleBarStyle 'default' | 'hidden' | 'hiddenInset' | 'customButtonsOnHover'
setTopBarColor(value) {
const normalized = this._normalizeOverlay(value);
if (normalized) {
this._options.titleBarOverlay = normalized;
if (normalized.transparent === true && !normalized.color) {
// A purely-transparent top bar: clear it without painting a color.
this.setTitleBarOverlay({ ...normalized, color: 'transparent' });
return;
}
this.setTitleBarOverlay(normalized);
}
}
capturePage() { return this.webContents.capturePage(); }
print() { console.log('[gelectron] print called'); }
printToPDF() { return Promise.resolve(Buffer.alloc(0)); }
print(options, callback) { return this.webContents.print(options, callback); }
printToPDF(options) { return this.webContents.printToPDF(options); }
openDevTools(options) { this.webContents.openDevTools(options); }
closeDevTools() { this.webContents.closeDevTools(); }
toggleDevTools() { this.webContents.toggleDevTools(); }
isDevToolsOpened() { return this.webContents.isDevToolsOpened(); }
reload() { return this.webContents.reload(); }
reloadIgnoringCache() { return this.webContents.reloadIgnoringCache(); }
goBack() { return this.webContents.goBack(); }
goForward() { return this.webContents.goForward(); }
canGoBack() { return this.webContents.canGoBack(); }
canGoForward() { return this.webContents.canGoForward(); }
stop() { this.webContents.stop(); }
setParentWindow() {}
getParentWindow() { return null; }
getChildWindows() { return []; }
+52
View File
@@ -148,6 +148,58 @@ class NativeBridge extends EventEmitter {
this._send({ type: 'maximize', id });
}
unmaximizeWindow(id) {
this._send({ type: 'unmaximize', id });
}
goBack(id) {
this._send({ type: 'go-back', id });
}
goForward(id) {
this._send({ type: 'go-forward', id });
}
restoreWindow(id) {
this._send({ type: 'restore', id });
}
openDevTools(id) {
this._send({ type: 'open-devtools', id });
}
closeDevTools(id) {
this._send({ type: 'close-devtools', id });
}
toggleDevTools(id) {
this._send({ type: 'toggle-devtools', id });
}
inspectElement(id, x, y) {
this._send({ type: 'inspect-element', id, x: x || 0, y: y || 0 });
}
printPage(id) {
this._send({ type: 'print-page', id });
}
capturePage(id) {
return this.request('capture-page', { id });
}
printToPdf(id, options) {
return this.request('print-to-pdf', { id, options: options || {} });
}
setTitleBarOverlay(id, overlay) {
this._send({ type: 'set-titlebar-overlay', id, overlay: overlay || {} });
}
setBackgroundColor(id, color) {
this._send({ type: 'set-background-color', id, color });
}
closeWindow(id) {
this._send({ type: 'close', id });
}
+6 -1
View File
@@ -4,14 +4,19 @@
* Gelectron - Preload script injection
*
* This script is injected into the renderer process before the page loads.
* It provides the ipcRenderer and contextBridge APIs to preload scripts.
* It provides the ipcRenderer and contextBridge APIs to preload scripts,
* plus a Node-compatible `process` polyfill for WebView-only mode.
*/
const { processPolyfillScript } = require('./process');
function getPreloadScript() {
return `
(function() {
'use strict';
${processPolyfillScript()}
// Expose gelectron preload APIs
window.__gelectron = window.__gelectron || {};
+287
View File
@@ -0,0 +1,287 @@
'use strict';
/**
* Gelectron - `process` polyfill for WebView-only (no Node.js) mode.
*
* When an Electron app runs inside a WebView without a Node.js runtime the
* compat layer has to provide its own `process` object. This module builds
* one that mirrors the parts of the Node.js `process` global that apps and
* libraries commonly rely on:
*
* - Identity/state: pid, title, argv, execPath, execArgv, arch, platform
* - Environment: env, cwd()
* - Runtime info: version, versions, uptime()
* - Resources: memoryUsage(), cpuUsage()
* - Scheduling: nextTick(), hrtime()
* - Control: exit(), kill(), abort(), crash()
* - Events: on()/once()/removeListener()/emit() (EventEmitter-like)
*
* All the values come from real measurements where possible
* (performance.now(), navigator.hardwareConcurrency, performance.memory).
*
* The polyfill lives in a single function (`buildProcessPolyfill`) whose
* source can be embedded as a string - `processPolyfillScript()` - so both
* the Node-compatible module (`createProcess`) and the WebView preload
* injection share exactly one implementation.
*/
function buildProcessPolyfill(g, opts) {
'use strict';
opts = opts || {};
const startTime = Date.now();
const listeners = new Map();
const win = (g && g.window) || (typeof window !== 'undefined' ? window : null);
const hasPerf = (typeof performance !== 'undefined' && performance && typeof performance.now === 'function');
const ua = (typeof navigator !== 'undefined' && navigator.userAgent) || '';
const resolvedPlatform = /Windows/i.test(ua) ? 'win32'
: (/Mac|iOS/.test(ua) ? 'darwin'
: (/Android|Linux/.test(ua) ? 'linux' : 'linux'));
const resolvedArch = /aarch64|arm64|ARM64/i.test(ua) ? 'arm64'
: (/\bx64\b|amd64|x86_64/i.test(ua) ? 'x64' : 'x64');
const process = {
title: opts.title || 'gelectron',
arch: opts.arch || resolvedArch,
platform: opts.platform || resolvedPlatform,
version: 'v18.20.0',
versions: {
gelectron: opts.version || '0.1.1',
node: '18.20.0',
v8: '10.2.154.26',
uv: '1.44.2',
zlib: '1.2.13',
modules: '108',
openssl: '3.0.10',
},
pid: opts.pid != null ? opts.pid : (Math.floor(Math.random() * 1e5) + 1000),
ppid: opts.ppid || 0,
execPath: opts.execPath || (typeof location !== 'undefined' ? String(location.href || '') : ''),
execArgv: opts.execArgv || [],
argv: opts.argv ? opts.argv.slice() : [],
env: opts.env ? Object.assign({}, opts.env) : {},
config: {},
release: { name: 'node', lts: 'Hydrogen' },
cwd() {
return opts.cwd || (typeof location !== 'undefined' ? String(location.pathname).replace(/\/[^/]*$/, '/') : '/');
},
// --- scheduling ----------------------------------------------------
nextTick(callback, ...args) {
if (typeof callback !== 'function') {
throw new TypeError('callback must be a function');
}
if (typeof Promise !== 'undefined') {
Promise.resolve().then(() => callback(...args));
} else {
setTimeout(() => callback(...args), 0);
}
},
hrtime(previous) {
const ms = hasPerf ? performance.now() : Date.now() - startTime;
let seconds = Math.floor(ms / 1000);
let nanos = Math.floor((ms - seconds * 1000) * 1e6);
if (previous) {
seconds -= previous[0];
nanos -= previous[1];
if (nanos < 0) {
seconds -= 1;
nanos += 1e9;
}
}
return [seconds, nanos];
},
uptime() {
return (Date.now() - startTime) / 1000;
},
// --- resources -----------------------------------------------------
memoryUsage() {
let total = 16 * 1024 * 1024;
let used = 8 * 1024 * 1024;
if (hasPerf && performance.memory && performance.memory.usedJSHeapSize) {
used = performance.memory.usedJSHeapSize;
total = performance.memory.totalJSHeapSize || Math.max(total, used);
}
const external = estimateHeapBytes();
return {
rss: used + external,
heapTotal: total,
heapUsed: used,
external: external,
arrayBuffers: 0,
};
},
cpuUsage(previousValue) {
// Best-effort: measure wall-clock since launch with a synthetic user
// share so {user}/{system} deltas behave monotonically like Node's.
const now = hasPerf ? performance.now() : Date.now() - startTime;
const current = {
user: Math.round(now * 1000),
system: Math.round(now * 120),
};
if (previousValue) {
current.user = Math.max(0, current.user - (previousValue.user || 0));
current.system = Math.max(0, current.system - (previousValue.system || 0));
}
return current;
},
// --- control -------------------------------------------------------
kill(pid, signal) {
if (typeof pid !== 'number') {
throw new TypeError('pid must be a number');
}
const sig = String(signal || 'SIGTERM');
if (win && typeof win.close === 'function' && (pid === process.pid || pid <= 0)) {
try {
if (sig === 'SIGKILL' || sig === 'SIGTERM' || sig === 'SIGINT') {
win.close();
}
} catch (e) {
// Ignore - window may not be closable from script
}
}
// No real process table exists in a WebView; report success so
// signal-sending logic in apps does not crash.
return true;
},
abort() {
throw new Error('Aborted');
},
crash() {
throw new Error('Gelectron process.crash()');
},
exit(code) {
if (win && typeof win.close === 'function') {
win.close();
} else {
throw new Error('Process exit requested with code ' + code);
}
},
// --- permissions ---------------------------------------------------
getuid() { return 0; },
setuid() {},
getgid() { return 0; },
setgid() {},
geteuid() { return 0; },
getgroups() { return [0]; },
// --- event emitter -------------------------------------------------
on(type, listener) {
if (!listeners.has(type)) listeners.set(type, []);
listeners.get(type).push(listener);
return process;
},
once(type, listener) {
const wrapped = (...args) => {
process.removeListener(type, wrapped);
listener(...args);
};
return process.on(type, wrapped);
},
addListener(type, listener) {
return process.on(type, listener);
},
removeListener(type, listener) {
const arr = listeners.get(type);
if (arr) {
const i = arr.indexOf(listener);
if (i !== -1) arr.splice(i, 1);
}
return process;
},
removeAllListeners(type) {
if (type) listeners.delete(type);
else listeners.clear();
return process;
},
emit(type, ...args) {
const arr = (listeners.get(type) || []).slice();
for (const fn of arr) {
try {
fn(...args);
} catch (e) {
if (typeof console !== 'undefined') console.error(e);
}
}
return arr.length > 0;
},
_getActiveRequests: () => [],
_getActiveHandles: () => [],
};
if (!process.env.GELECTRON_NATIVE) {
process.env.GELECTRON_NATIVE = '1';
process.env.GELECTRON_POLYFILL = '1';
}
function estimateHeapBytes() {
if (!win) return 0;
let live = 0;
let refs = [win];
const seen = new Set();
const MAX_WALK = 150000;
while (refs.length && live < MAX_WALK) {
const next = [];
for (const obj of refs) {
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) continue;
if (seen.has(obj)) continue;
seen.add(obj);
live += 48;
let keys;
try {
keys = Object.keys(obj);
} catch (e) {
continue;
}
for (let i = 0; i < keys.length && next.length < 5000; i++) {
const v = obj[keys[i]];
if (v && (typeof v === 'object' || typeof v === 'function') && !seen.has(v)) {
next.push(v);
}
}
}
refs = next;
}
return live;
}
return process;
}
// Node-compatible entry point: build a fresh `process`-like object.
function createProcess(opts = {}) {
const g = typeof globalThis !== 'undefined' ? globalThis : {};
return buildProcessPolyfill(g, opts);
}
// Self-contained script that installs `window.process` if it does not exist.
// Used by the preload layer / webview bundle so WebView-only apps get the
// same `process` API without needing a Node.js runtime.
function processPolyfillScript(opts = {}) {
const optsJson = JSON.stringify(opts);
const src = buildProcessPolyfill.toString();
return `(function () {
var g = typeof window !== 'undefined' ? window
: (typeof globalThis !== 'undefined' ? globalThis : {});
if (g.process) return;
var build = (${src});
var proc = build(g, ${optsJson});
try {
Object.defineProperty(g, 'process', { value: proc, writable: true, configurable: true });
} catch (e) {
g.process = proc;
}
})();`;
}
module.exports = { createProcess, processPolyfillScript, buildProcessPolyfill };