Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,8 @@ native/windows/build/
priv/native/macos/DesktopWebView
priv/native/linux/DesktopWebView
priv/native/windows/DesktopWebView.exe
priv/native/windows/aumid_nif.dll
priv/native/windows/aumid_nif.exp
priv/native/windows/aumid_nif.lib
.DS_Store
*.swp
53 changes: 53 additions & 0 deletions c_src/aumid_nif.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include <erl_nif.h>
#include <string.h>

#ifdef _WIN32
#include <windows.h>
#include <shobjidl.h>
#endif

static ERL_NIF_TERM atom_ok;
static ERL_NIF_TERM atom_error;

static int on_load(ErlNifEnv *env, void **priv_data, ERL_NIF_TERM load_info) {
(void)priv_data;
(void)load_info;
atom_ok = enif_make_atom(env, "ok");
atom_error = enif_make_atom(env, "error");
return 0;
}

static ERL_NIF_TERM set_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {
(void)argc;
#ifndef _WIN32
(void)argv;
return atom_ok;
#else
char id[512];
if (enif_get_string(env, argv[0], id, sizeof(id), ERL_NIF_LATIN1) <= 0) {
ErlNifBinary bin;
if (!enif_inspect_binary(env, argv[0], &bin) || bin.size >= sizeof(id)) {
return enif_make_badarg(env);
}
memcpy(id, bin.data, bin.size);
id[bin.size] = '\0';
}
if (id[0] == '\0') return atom_ok;

int n = MultiByteToWideChar(CP_UTF8, 0, id, -1, NULL, 0);
if (n <= 0) return enif_make_tuple2(env, atom_error, enif_make_atom(env, "utf8"));
WCHAR *wide = (WCHAR *)enif_alloc(sizeof(WCHAR) * (size_t)n);
if (!wide) return enif_make_tuple2(env, atom_error, enif_make_atom(env, "alloc"));
MultiByteToWideChar(CP_UTF8, 0, id, -1, wide, n);
HRESULT hr = SetCurrentProcessExplicitAppUserModelID(wide);
enif_free(wide);
if (FAILED(hr)) {
return enif_make_tuple2(env, atom_error, enif_make_int(env, (int)hr));
}
return atom_ok;
#endif
}

static ErlNifFunc nif_funcs[] = {{"set_nif", 1, set_nif}};

ERL_NIF_INIT(Elixir.DesktopWebview.AppUserModelId, nif_funcs, on_load, NULL, NULL, NULL)
17 changes: 14 additions & 3 deletions docs/packaging.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,20 @@ MyApp/
`DesktopWebView.exe` from `desktop_webview` / `DESKTOP_HOST_BINARY`.
- Ini discovery: `--edw-config` → `<exe_basename>.ini` beside the executable →
`DesktopWebView.ini` beside the executable.
- Relative `beam.path` / `working_dir` resolve against the directory containing
the host executable.
- Relative `beam.path` / `working_dir` / `[ui] splash_icon` resolve against the
directory containing the host executable. Optional splash logo:
`package.splash_icon` (via `desktop_deployment`) → `splash.png` beside the
host + `[ui] splash_icon = splash.png`, or `--edw-splash-icon=PATH`. When
unset, the splash uses the PE/module icon.
- Forwarded argv and `EDW_PORT` / `EDW_HOST` are unchanged.
- Shared Task Manager / taskbar grouping: set `[windows] app_user_model_id`
(from `package.identifier` via desktop_deployment) or
`--edw-app-user-model-id=`. The host calls
`SetCurrentProcessExplicitAppUserModelID` before creating windows, and passes
`EDW_APP_USER_MODEL_ID` to the BEAM child so Elixir can set the same ID
in-process via prebuilt `priv/native/windows/aumid_nif.dll`
(`scripts/build_windows.ps1`, same as the host binary — not `mix compile`).

- Release asset name: `DesktopWebView-windows-x64.exe` (see Binaries).
- WebView2: document Evergreen Runtime dependency in the app installer; the host
should fail with a clear stderr message if the runtime is missing.
Expand Down Expand Up @@ -210,7 +221,7 @@ environment key is unset.
| Platform | Delivery | Artifact name |
|----------|----------|---------------|
| macOS | Universal binary in Hex `priv/native/macos/DesktopWebView` | `DesktopWebView-macos-universal` (also on GitHub Releases) |
| Windows | GitHub Releases (draft on tag); **not** in Hex `priv/` | `DesktopWebView-windows-x64.exe` + `.sha256` |
| Windows | GitHub Releases (draft on tag); **not** in Hex `priv/` | `DesktopWebView-windows-x64.exe` + `.sha256`; local/CI also builds `aumid_nif.dll` beside the host via `scripts/build_windows.ps1` |
| Linux | GitHub Releases (draft on tag); **not** in Hex `priv/` | `DesktopWebView-linux-x86_64` + `.sha256` |

CI ad-hoc signs the macOS binary (`codesign -s -`). Full Developer ID / notarization
Expand Down
4 changes: 3 additions & 1 deletion docs/status/windows.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Release asset: `DesktopWebView-windows-x64.exe` (GitHub Releases; not Hex `priv/
| `initialize` + capabilities | done | E2E setup |
| `--edw-no-beam` / argv strip | done | E2E |
| Ini + defaults | done | Same semantics as Linux/macOS |
| Shared AppUserModelID | done | `[windows] app_user_model_id` / `--edw-app-user-model-id`; host sets via Win32 API; BEAM via `EDW_APP_USER_MODEL_ID` + prebuilt `aumid_nif.dll` (`build_windows.ps1`) |
| Lifetime reconnect | done | Packaged mode (keep listening) |
| Lifetime coupled | done | Exit on disconnect; `--edw-no-beam` exits |
| Window open/show/hide/title/min size | done | E2E window test |
Expand All @@ -23,7 +24,8 @@ Release asset: `DesktopWebView-windows-x64.exe` (GitHub Releases; not Hex `priv/
| New window → external open | done | `ShellExecute` + event |
| Context menu disable | done | WebView2 settings |
| Menubar from DOM | done | E2E menu create |
| Tray / status item | done | `Shell_NotifyIcon`; E2E tray create |
| Tray / status item | done | `Shell_NotifyIcon`; left- and right-click both open the bound context menu; E2E tray create |
| Packaged splash | done | Host-first only (`beam` spawn): `[ui] splash_icon` / `--edw-splash-icon` or PE icon + Starting/Repairing/Restarting; dismiss on first `window.open` |
| Apple menu | n/a | Successful no-op |
| Notifications | done | Balloon via tray when present; E2E |
| Icons from path / PNG | done | ICO via `LoadImage`; PNG/JPEG via GDI+ `Bitmap::GetHICON`; class/default from exe |
Expand Down
32 changes: 32 additions & 0 deletions lib/desktop_webview/app_user_model_id.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
defmodule DesktopWebview.AppUserModelId do
@moduledoc false

# Prebuilt by scripts/build_windows.ps1 → priv/native/windows/aumid_nif.dll
# (not compiled via mix). Missing DLL keeps the Elixir stub (:ok no-op).

@on_load :load_nif

def load_nif do
path =
[:code.priv_dir(:desktop_webview), "native", "windows", "aumid_nif"]
|> Path.join()
|> String.to_charlist()

case :erlang.load_nif(path, 0) do
:ok -> :ok
{:error, _} -> :ok
end
end

# Host passes EDW_APP_USER_MODEL_ID so BEAM shares the host AppUserModelID.
def apply_from_env do
case System.get_env("EDW_APP_USER_MODEL_ID") do
id when is_binary(id) and id != "" -> set(id)
_ -> :ok
end
end

def set(id) when is_binary(id), do: set_nif(id)

def set_nif(_id), do: :ok
end
3 changes: 3 additions & 0 deletions lib/desktop_webview/application.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ defmodule DesktopWebview.Application do

@impl true
def start(_type, _args) do
# When spawned by the Windows host, share its AppUserModelID before any UI/shell use.
DesktopWebview.AppUserModelId.apply_from_env()

# Transport is started on demand via DesktopWebview.Transport.ensure_started/0
# (and by E2E tests) so it is not permanently supervised here.
Supervisor.start_link([], strategy: :one_for_one, name: DesktopWebview.Supervisor)
Expand Down
3 changes: 3 additions & 0 deletions lib/desktop_webview/backend.ex
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ defmodule DesktopWebview.Backend do

@impl true
def init_env do
# Before any Shell/toast use — share host AppUserModelID for Task Manager grouping.
DesktopWebview.AppUserModelId.apply_from_env()

Transport.ensure_started()
EventBridge.ensure_started()

Expand Down
24 changes: 18 additions & 6 deletions lib/desktop_webview/event_bridge.ex
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,15 @@ defmodule DesktopWebview.EventBridge do

@impl true
def init(_opts) do
Transport.ensure_started()
Transport.subscribe(self())

{:ok,
%{
attach_transport(%{
windows: %{},
menus: %{},
notifications: %{},
pending_open: [],
open_wait: 0
}}
open_wait: 0,
transport_ref: nil
})}
end

@impl true
Expand Down Expand Up @@ -80,6 +78,12 @@ defmodule DesktopWebview.EventBridge do
{:noreply, flush_open_urls(state)}
end

# Transport is started unlinked (so EventBridge test kills do not race a dead
# Transport). Monitor it and re-subscribe after a crash so host events resume.
def handle_info({:DOWN, ref, :process, _pid, _}, %{transport_ref: ref} = state) do
{:noreply, attach_transport(%{state | transport_ref: nil})}
end

def handle_info({:DOWN, _ref, :process, pid, _}, state) do
{:noreply,
%{
Expand All @@ -92,6 +96,14 @@ defmodule DesktopWebview.EventBridge do

def handle_info(_other, state), do: {:noreply, state}

defp attach_transport(state) do
if state.transport_ref, do: Process.demonitor(state.transport_ref, [:flush])
Transport.ensure_started()
transport = Process.whereis(Transport)
:ok = Transport.subscribe(self())
%{state | transport_ref: Process.monitor(transport)}
end

defp dispatch("event.window.close_requested", %{"window_id" => wid}, state) do
if pid = Map.get(state.windows, wid), do: GenServer.cast(pid, :close_window)
state
Expand Down
21 changes: 17 additions & 4 deletions lib/desktop_webview/transport.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,27 @@ defmodule DesktopWebview.Transport do
GenServer.start_link(__MODULE__, opts, name: @name)
end

# Start unlinked: EventBridge (and unit tests that kill it) must not take
# Transport down with them, or the next subscribe races a dead name.
def ensure_started do
case Process.whereis(@name) do
pid when is_pid(pid) ->
if Process.alive?(pid) do
:ok
else
start_unlinked()
end

nil ->
{:ok, _} = start_link([])
:ok
start_unlinked()
end
end

_ ->
:ok
defp start_unlinked do
case GenServer.start(__MODULE__, [], name: @name) do
{:ok, _} -> :ok
{:error, {:already_started, pid}} ->
if Process.alive?(pid), do: :ok, else: start_unlinked()
Comment thread
dominicletz marked this conversation as resolved.
Resolved
end
end

Expand Down
3 changes: 2 additions & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ defmodule DesktopWebview.MixProject do
name: "desktop_webview",
licenses: ["MIT"],
links: %{"GitHub" => @url},
files: ~w(lib priv native/macos/README.md mix.exs README.md AGENTS.md LICENSE docs)
files:
~w(lib priv c_src native/macos/README.md mix.exs README.md AGENTS.md LICENSE docs)
]
end
end
2 changes: 2 additions & 0 deletions native/windows/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@ endif()

add_executable(DesktopWebView WIN32
src/main.cpp
src/aumid.cpp
src/config.cpp
src/json_util.cpp
src/rpc_server.cpp
src/web_window.cpp
src/splash_window.cpp
src/host_controller.cpp
src/beam_cli.cpp
src/instance_lock.cpp
Expand Down
28 changes: 26 additions & 2 deletions native/windows/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ CMake fetches `Microsoft.Web.WebView2` and `nlohmann/json` during configure.
```

Output is copied to `priv\native\windows\DesktopWebView.exe` for local/CI use.
Release artifact name: `DesktopWebView-windows-x64.exe` (see [packaging.md](../../docs/packaging.md)).
When Elixir/OTP is on `PATH`, the same script also builds
`priv\native\windows\aumid_nif.dll` from `c_src/aumid_nif.c` (BEAM-side
AppUserModelID; not compiled by `mix`). Rebuild the NIF with the same OTP
major you run against. Release artifact name:
`DesktopWebView-windows-x64.exe` (see [packaging.md](../../docs/packaging.md)).

## Run (dev / E2E)

Expand Down Expand Up @@ -57,12 +61,32 @@ This browser feature is separate from the [`dialog.choose_file` JSON-RPC
method](../../docs/protocol.md#dialog). That method is an explicit host dialog
request for code that needs a path returned through the Elixir transport.

## Packaged splash

In host-first mode (BEAM spawned by the host, not `--edw-no-beam`), a small
centered splash shows a logo and a status label:

- Logo from `[ui] splash_icon` / `--edw-splash-icon=` when set (PNG/ICO beside
the host, or absolute path); otherwise the embedded PE/module icon
- `Starting app` on cold start / respawn
- `Repairing` while the recovery script runs
- `Restarting` before a backoff respawn

The splash dismisses on the first `window.open`. Dev launches with
`--edw-no-beam` do not show it. Packaging can set `package.splash_icon` so
`desktop_deployment` copies `splash.png` and writes the ini key.

## Tray

Left- and right-click on the tray icon both open the same bound context menu
(and both still emit `event.tray.click`).

## Structure

| Path | Role |
|------|------|
| `CMakeLists.txt` | CMake project + WebView2 / JSON deps |
| `src/` | Host sources (config, RPC, windows, dispatch) |
| `src/` | Host sources (config, RPC, windows, splash, dispatch) |

Do not add a native unit-test suite; exercise the binary from Elixir E2E (`mix test.e2e`).

Expand Down
17 changes: 17 additions & 0 deletions native/windows/src/aumid.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#include "aumid.hpp"
#include "win_util.hpp"

#include <cstdio>
#include <shobjidl.h>

bool set_app_user_model_id(const std::string& utf8_id) {
if (utf8_id.empty()) return true;
std::wstring wide = utf8_to_wide(utf8_id);
HRESULT hr = SetCurrentProcessExplicitAppUserModelID(wide.c_str());
if (FAILED(hr)) {
fprintf(stderr, "edw: SetCurrentProcessExplicitAppUserModelID failed (0x%08lx)\n",
static_cast<unsigned long>(hr));
return false;
}
return true;
}
7 changes: 7 additions & 0 deletions native/windows/src/aumid.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#pragma once

#include <string>

// Set the process AppUserModelID (Task Manager / taskbar grouping). No-op if empty.
// Returns true on success or when id is empty.
bool set_app_user_model_id(const std::string& utf8_id);
12 changes: 12 additions & 0 deletions native/windows/src/config.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ HostConfig HostConfig::parse(int argc, char** argv) {
cfg.instances = (v == "single") ? Instances::Single : Instances::Multi;
} else if (body.rfind("instance-id=", 0) == 0) {
cfg.instance_id = body.substr(12);
} else if (body.rfind("splash-icon=", 0) == 0) {
cfg.splash_icon = body.substr(12);
} else if (body.rfind("app-user-model-id=", 0) == 0) {
cfg.app_user_model_id = body.substr(18);
} else {
fprintf(stderr, "unknown --edw flag: %s\n", a.c_str());
}
Expand Down Expand Up @@ -223,6 +227,14 @@ void HostConfig::apply_ini() {
if (auto v = ini.get("beam", "node")) beam_node = *v;
if (auto v = ini.get("beam", "cookie")) beam_cookie = *v;
if (auto v = ini.get("beam", "cookie_file")) beam_cookie_file = *v;
// CLI --edw-splash-icon= wins when already set before apply_ini.
if (!splash_icon) {
if (auto v = ini.get("ui", "splash_icon")) splash_icon = *v;
}
// CLI --edw-app-user-model-id= wins when already set before apply_ini.
if (!app_user_model_id) {
if (auto v = ini.get("windows", "app_user_model_id")) app_user_model_id = *v;
}
for (auto& [k, v] : ini.section("env")) {
extra_env[k] = v;
}
Expand Down
6 changes: 6 additions & 0 deletions native/windows/src/config.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ struct HostConfig {
std::vector<std::string> forwarded_argv;
Instances instances = Instances::Multi;
std::optional<std::string> instance_id;
// Optional path to a splash logo (PNG/ICO). Relative paths resolve against
// resources_root(). When unset, the splash falls back to the PE/module icon.
std::optional<std::string> splash_icon;
// Shared with BEAM (EDW_APP_USER_MODEL_ID) so Task Manager groups both processes.
// From ini [windows] app_user_model_id or --edw-app-user-model-id=.
std::optional<std::string> app_user_model_id;

static HostConfig parse(int argc, char** argv);

Expand Down
Loading
Loading