mirror of
https://github.com/mileswolfallen2/gelectron.git
synced 2026-12-03 23:53:26 +00:00
Compare commits
3
Commits
new1
...
58f222d661
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58f222d661 | ||
|
|
06b14e6cda | ||
|
|
f45e458c53 |
No files matched your search
@@ -1 +0,0 @@
|
||||
1db4284c-fc55-41be-a7dd-cde2036997da
|
||||
@@ -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
@@ -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
@@ -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 |
|
||||
|
||||
@@ -195,7 +195,7 @@ When the native binary is not built, the CLI falls back to pure Node.js:
|
||||
| Module | Status |
|
||||
|---|---|
|
||||
| `app` | Full lifecycle, paths, command line, dock (macOS), `whenReady()` |
|
||||
| `BrowserWindow` | Create, show/hide, resize, loadURL, loadFile, events, webContents |
|
||||
| `BrowserWindow` | Create, show/hide, min/max/restore, resize, loadURL/loadFile, history navigation, DevTools, `capturePage()`, `print()`, `printToPDF()`, macOS title bar theming, events, webContents |
|
||||
| `ipcMain` | `handle()`, `on()`, `removeHandler()`, event emission |
|
||||
| `Menu` | `buildFromTemplate()`, `popup()`, `setApplicationMenu()` |
|
||||
| `MenuItem` | All types (normal, checkbox, separator, submenu, role) |
|
||||
@@ -203,10 +203,10 @@ When the native binary is not built, the CLI falls back to pure Node.js:
|
||||
| `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 |
|
||||
| `nativeImage` | Create from path/buffer/dataURL, `createEmpty()`, PNG/JPEG export |
|
||||
| `safeStorage` | Encrypt/decrypt via system keyring |
|
||||
| `contextBridge` | `exposeInMainWorld()` for secure preload |
|
||||
| `webContents` | `send()`, `executeJavaScript()`, `openDevTools()`, navigation |
|
||||
| `webContents` | `send()`, `executeJavaScript()`, DevTools (open/close/toggle/inspect), history navigation (`goBack`/`goForward`), `capturePage()`, `print()`, `printToPDF()`, reload, stop |
|
||||
|
||||
### Renderer Process
|
||||
|
||||
@@ -228,6 +228,36 @@ When the native binary is not built, the CLI falls back to pure Node.js:
|
||||
| `net` | `fetch()` proxy |
|
||||
| `autoUpdater` | Full (sha512-verified, atomic apply) |
|
||||
|
||||
## macOS Title Bar Theming
|
||||
|
||||
Electron-compatible APIs (work in stock Electron):
|
||||
|
||||
```js
|
||||
const win = new BrowserWindow({
|
||||
titleBarStyle: 'hidden',
|
||||
titleBarOverlay: { color: '#24a0ed', symbolColor: '#ffffff', height: 40 },
|
||||
backgroundColor: '#0f0f23',
|
||||
});
|
||||
|
||||
win.setTitleBarOverlay({ color: '#FF5A5F', transparent: true, titleBarStyle: 'hiddenInset' });
|
||||
win.setBackgroundColor('#123456');
|
||||
win.getBackgroundColor(); // '#123456'
|
||||
```
|
||||
|
||||
Gelectron-only helper (no Electron equivalent — a single clear call for the top bar):
|
||||
|
||||
```js
|
||||
win.setTopBarColor('#FF5A5F'); // just a color
|
||||
win.setTopBarColor({ color: '#19b1ff', transparent: false }); // options object
|
||||
win.setTopBarColor({ transparent: true }); // clear / see-through
|
||||
win.setTopBarColor('transparent'); // shorthand for clear
|
||||
```
|
||||
|
||||
Colors accept `#RGB`, `#RGBA`, `#RRGGBB`, `#RRGGBBAA`, `rgb()`, `rgba()`, or `transparent`.
|
||||
On macOS the title bar is painted via `NSWindow` (`backgroundColor` +
|
||||
`titlebarAppearsTransparent`). On other platforms the APIs are accepted for
|
||||
compatibility but are no-ops.
|
||||
|
||||
## Demo App
|
||||
|
||||
A minimal demo that renders HTML/CSS/JS in a real window:
|
||||
@@ -617,7 +647,8 @@ gelectron --help # Show help
|
||||
- [x] `electron-updater` compatibility
|
||||
- [ ] Multi-window support
|
||||
- [ ] Custom protocol handlers (`gelectron://`)
|
||||
- [ ] DevTools integration
|
||||
- [x] DevTools integration (wry webview devtools, native on macOS)
|
||||
- [x] WebContents navigation history (`goBack`/`goForward`)
|
||||
- [ ] App sandboxing
|
||||
- [x] Package/distribution tooling
|
||||
- [x] Performance benchmarks vs Electron
|
||||
|
||||
@@ -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]
|
||||
}
|
||||
}
|
||||
@@ -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" }
|
||||
@@ -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):
|
||||
//
|
||||
|
||||
Generated
+61
-14
@@ -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
@@ -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 []; }
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -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 || {};
|
||||
|
||||
|
||||
@@ -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 };
|
||||
Reference in new issue
Block a user