diff --git a/.gitignore b/.gitignore index 73f238c..1a4ff9c 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/c_src/aumid_nif.c b/c_src/aumid_nif.c new file mode 100644 index 0000000..1ef0536 --- /dev/null +++ b/c_src/aumid_nif.c @@ -0,0 +1,53 @@ +#include +#include + +#ifdef _WIN32 +#include +#include +#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) diff --git a/docs/packaging.md b/docs/packaging.md index 0bdd783..f6d0863 100644 --- a/docs/packaging.md +++ b/docs/packaging.md @@ -45,9 +45,20 @@ MyApp/ `DesktopWebView.exe` from `desktop_webview` / `DESKTOP_HOST_BINARY`. - Ini discovery: `--edw-config` → `.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. @@ -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 diff --git a/docs/status/windows.md b/docs/status/windows.md index 4e58257..50b4068 100644 --- a/docs/status/windows.md +++ b/docs/status/windows.md @@ -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 | @@ -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 | diff --git a/lib/desktop_webview/app_user_model_id.ex b/lib/desktop_webview/app_user_model_id.ex new file mode 100644 index 0000000..f4c05ba --- /dev/null +++ b/lib/desktop_webview/app_user_model_id.ex @@ -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 diff --git a/lib/desktop_webview/application.ex b/lib/desktop_webview/application.ex index 1bee49b..ce8e1fa 100644 --- a/lib/desktop_webview/application.ex +++ b/lib/desktop_webview/application.ex @@ -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) diff --git a/lib/desktop_webview/backend.ex b/lib/desktop_webview/backend.ex index 403855e..4f00774 100644 --- a/lib/desktop_webview/backend.ex +++ b/lib/desktop_webview/backend.ex @@ -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() diff --git a/lib/desktop_webview/event_bridge.ex b/lib/desktop_webview/event_bridge.ex index 69b8835..3434526 100644 --- a/lib/desktop_webview/event_bridge.ex +++ b/lib/desktop_webview/event_bridge.ex @@ -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 @@ -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, %{ @@ -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 diff --git a/lib/desktop_webview/transport.ex b/lib/desktop_webview/transport.ex index 2fbee63..743971f 100644 --- a/lib/desktop_webview/transport.ex +++ b/lib/desktop_webview/transport.ex @@ -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() end end diff --git a/mix.exs b/mix.exs index 70ceb1e..caa9aec 100644 --- a/mix.exs +++ b/mix.exs @@ -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 diff --git a/native/windows/CMakeLists.txt b/native/windows/CMakeLists.txt index 9b3a277..ff1cdfb 100644 --- a/native/windows/CMakeLists.txt +++ b/native/windows/CMakeLists.txt @@ -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 diff --git a/native/windows/README.md b/native/windows/README.md index 280fcee..3f0d32e 100644 --- a/native/windows/README.md +++ b/native/windows/README.md @@ -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) @@ -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`). diff --git a/native/windows/src/aumid.cpp b/native/windows/src/aumid.cpp new file mode 100644 index 0000000..e257910 --- /dev/null +++ b/native/windows/src/aumid.cpp @@ -0,0 +1,17 @@ +#include "aumid.hpp" +#include "win_util.hpp" + +#include +#include + +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(hr)); + return false; + } + return true; +} diff --git a/native/windows/src/aumid.hpp b/native/windows/src/aumid.hpp new file mode 100644 index 0000000..c3e7c2d --- /dev/null +++ b/native/windows/src/aumid.hpp @@ -0,0 +1,7 @@ +#pragma once + +#include + +// 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); diff --git a/native/windows/src/config.cpp b/native/windows/src/config.cpp index 3ab1ef3..8cc7a61 100644 --- a/native/windows/src/config.cpp +++ b/native/windows/src/config.cpp @@ -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()); } @@ -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; } diff --git a/native/windows/src/config.hpp b/native/windows/src/config.hpp index de0ffe9..9254775 100644 --- a/native/windows/src/config.hpp +++ b/native/windows/src/config.hpp @@ -36,6 +36,12 @@ struct HostConfig { std::vector forwarded_argv; Instances instances = Instances::Multi; std::optional 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 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 app_user_model_id; static HostConfig parse(int argc, char** argv); diff --git a/native/windows/src/host_controller.cpp b/native/windows/src/host_controller.cpp index 9f3f795..186de85 100644 --- a/native/windows/src/host_controller.cpp +++ b/native/windows/src/host_controller.cpp @@ -81,6 +81,7 @@ HostController::~HostController() { } for (auto& [_, menu] : menus_) destroy_menu_entry(menu); windows_.clear(); + dismiss_splash(); if (hwnd_) { DestroyWindow(hwnd_); hwnd_ = nullptr; @@ -113,11 +114,42 @@ bool HostController::start() { if (!server_.start(config_.host, config_.port, hwnd_)) return false; if (config_.beam_enabled && !config_.no_beam) { + show_splash(L"Starting app"); spawn_beam(); } return true; } +bool HostController::splash_enabled() const { + return config_.beam_enabled && !config_.no_beam; +} + +std::optional HostController::resolved_splash_icon_path() const { + if (!config_.splash_icon || config_.splash_icon->empty()) return std::nullopt; + std::string path = *config_.splash_icon; + if (!is_absolute_path(path)) path = join_path(config_.resources_root(), path); + if (!file_exists(path)) { + fprintf(stderr, "edw: splash_icon not found: %s\n", path.c_str()); + return std::nullopt; + } + return utf8_to_wide(path); +} + +void HostController::show_splash(const wchar_t* status) { + if (!splash_enabled()) return; + splash_.show(status, resolved_splash_icon_path()); +} + +void HostController::set_splash_status(const wchar_t* status) { + if (!splash_enabled()) return; + if (splash_.visible()) + splash_.set_status(status); + else + splash_.show(status, resolved_splash_icon_path()); +} + +void HostController::dismiss_splash() { splash_.dismiss(); } + LRESULT CALLBACK HostController::HostWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { HostController* self = nullptr; if (msg == WM_NCCREATE) { @@ -191,7 +223,7 @@ LRESULT HostController::on_host_message(HWND hwnd, UINT msg, WPARAM wParam, LPAR if (tray.nid.uID == id) { jsonutil::Json o{{"tray_id", tid}}; server_.notify("event.tray.click", std::move(o)); - if (lParam == WM_RBUTTONUP && !tray.menu_id.empty()) { + if (!tray.menu_id.empty()) { auto it = menus_.find(tray.menu_id); if (it != menus_.end() && it->second.menu) { POINT pt{}; @@ -280,6 +312,7 @@ void HostController::mark_prepare_quit_window() { } void HostController::exit_host_clean() { + dismiss_splash(); stop_liveness_timer(); if (respawn_timer_id_) { KillTimer(hwnd_, respawn_timer_id_); @@ -361,6 +394,7 @@ void HostController::beam_did_exit() { if (config_.recovery_after > 0 && startup_failures_ >= config_.recovery_after && config_.recovery_script) { fprintf(stderr, "edw: startup crash limit reached; running recovery script\n"); + set_splash_status(L"Repairing"); beamcli::run_recover(config_); startup_failures_ = 0; } @@ -369,9 +403,11 @@ void HostController::beam_did_exit() { if (config_.restart_max_attempts > 0 && beam_restart_attempts_ >= config_.restart_max_attempts) { fprintf(stderr, "edw: beam exited; restart limit reached, terminating host\n"); + dismiss_splash(); PostQuitMessage(1); return; } + set_splash_status(L"Restarting"); schedule_beam_respawn(); } @@ -409,6 +445,9 @@ std::string HostController::next_id(const std::string& prefix) { } void HostController::spawn_beam() { + if (splash_enabled() && windows_.empty()) { + set_splash_status(L"Starting app"); + } auto root = config_.resources_root(); std::string beam_dir = config_.beam_path @@ -522,6 +561,9 @@ void HostController::spawn_beam() { } env["EDW_PORT"] = std::to_string(server_.port()); env["EDW_HOST"] = config_.host; + if (config_.app_user_model_id && !config_.app_user_model_id->empty()) { + env["EDW_APP_USER_MODEL_ID"] = *config_.app_user_model_id; + } for (auto& [k, v] : config_.extra_env) env[k] = v; if (env.find("RELEASE_DISTRIBUTION") == env.end()) { env["RELEASE_DISTRIBUTION"] = "none"; @@ -769,6 +811,7 @@ jsonutil::Json HostController::window_open(const jsonutil::Json& params) { win->show(); webviews_[webview_id] = window_id; windows_[window_id] = std::move(win); + dismiss_splash(); return jsonutil::Json{{"window_id", window_id}, {"webview_id", webview_id}}; } diff --git a/native/windows/src/host_controller.hpp b/native/windows/src/host_controller.hpp index 12705cf..ccfd9bc 100644 --- a/native/windows/src/host_controller.hpp +++ b/native/windows/src/host_controller.hpp @@ -3,12 +3,14 @@ #include "win_prefix.hpp" #include "config.hpp" #include "rpc_server.hpp" +#include "splash_window.hpp" #include "web_window.hpp" #include #include #include #include +#include #include #include @@ -107,9 +109,16 @@ class HostController { LRESULT on_host_message(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); bool on_menu_command(UINT cmd); + bool splash_enabled() const; + std::optional resolved_splash_icon_path() const; + void show_splash(const wchar_t* status); + void set_splash_status(const wchar_t* status); + void dismiss_splash(); + HostConfig config_; RpcServer server_; HWND hwnd_ = nullptr; + SplashWindow splash_; bool initialized_ = false; bool quit_initiated_ = false; // Tick count deadline for system.prepare_quit (0 = no window). diff --git a/native/windows/src/main.cpp b/native/windows/src/main.cpp index 5d408c5..8a0b7c0 100644 --- a/native/windows/src/main.cpp +++ b/native/windows/src/main.cpp @@ -1,3 +1,4 @@ +#include "aumid.hpp" #include "beam_cli.hpp" #include "config.hpp" #include "host_controller.hpp" @@ -38,6 +39,8 @@ int WINAPI wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) { for (auto& s : args) argv_ptrs.push_back(s.data()); auto config = HostConfig::parse(static_cast(argv_ptrs.size()), argv_ptrs.data()); + // Before any HWND / Shell_NotifyIcon — shared with BEAM via EDW_APP_USER_MODEL_ID. + if (config.app_user_model_id) set_app_user_model_id(*config.app_user_model_id); int exclusive = 0; if (beamcli::maybe_run_exclusive(config, &exclusive)) { CoUninitialize(); diff --git a/native/windows/src/splash_window.cpp b/native/windows/src/splash_window.cpp new file mode 100644 index 0000000..846cf64 --- /dev/null +++ b/native/windows/src/splash_window.cpp @@ -0,0 +1,151 @@ +#include "splash_window.hpp" +#include "win_util.hpp" + +namespace { +constexpr const wchar_t* kSplashClass = L"DesktopWebViewSplash"; +constexpr int kSplashWidth = 360; +constexpr int kSplashHeight = 240; +constexpr int kIconSize = 128; +constexpr COLORREF kSplashBg = RGB(220, 220, 220); +bool g_class_registered = false; +HBRUSH g_bg_brush = nullptr; + +HBRUSH splash_bg_brush() { + if (!g_bg_brush) g_bg_brush = CreateSolidBrush(kSplashBg); + return g_bg_brush; +} +} // namespace + +void SplashWindow::register_class() { + if (g_class_registered) return; + WNDCLASSEXW wc{}; + wc.cbSize = sizeof(wc); + // CS_DROPSHADOW: system drop shadow on borderless WS_POPUP (DWM composition). + wc.style = CS_DROPSHADOW; + wc.lpfnWndProc = SplashWindow::WndProc; + wc.hInstance = GetModuleHandleW(nullptr); + wc.hCursor = LoadCursorW(nullptr, IDC_ARROW); + wc.hbrBackground = splash_bg_brush(); + wc.lpszClassName = kSplashClass; + wc.hIcon = extract_module_icon(); + wc.hIconSm = extract_module_icon(); + RegisterClassExW(&wc); + g_class_registered = true; +} + +SplashWindow::SplashWindow() = default; + +SplashWindow::~SplashWindow() { dismiss(); } + +void SplashWindow::load_icon(const std::optional& icon_path) { + if (icon_ && owns_icon_) DestroyIcon(icon_); + icon_ = nullptr; + owns_icon_ = false; + + if (icon_path && !icon_path->empty()) { + icon_ = load_hicon_from_file(*icon_path); + if (icon_) { + owns_icon_ = true; + return; + } + } + icon_ = extract_module_icon(); + owns_icon_ = icon_ != nullptr; +} + +void SplashWindow::show(const std::wstring& status, const std::optional& icon_path) { + status_ = status; + if (hwnd_) { + if (icon_path) load_icon(icon_path); + InvalidateRect(hwnd_, nullptr, TRUE); + ShowWindow(hwnd_, SW_SHOW); + UpdateWindow(hwnd_); + return; + } + + register_class(); + load_icon(icon_path); + + RECT work{}; + SystemParametersInfoW(SPI_GETWORKAREA, 0, &work, 0); + int x = work.left + ((work.right - work.left) - kSplashWidth) / 2; + int y = work.top + ((work.bottom - work.top) - kSplashHeight) / 2; + + hwnd_ = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW, kSplashClass, L"", WS_POPUP, x, y, + kSplashWidth, kSplashHeight, nullptr, nullptr, GetModuleHandleW(nullptr), + this); + if (!hwnd_) return; + ShowWindow(hwnd_, SW_SHOW); + UpdateWindow(hwnd_); +} + +void SplashWindow::set_status(const std::wstring& status) { + status_ = status; + if (!hwnd_) return; + InvalidateRect(hwnd_, nullptr, TRUE); + UpdateWindow(hwnd_); +} + +void SplashWindow::dismiss() { + if (hwnd_) { + SetWindowLongPtrW(hwnd_, GWLP_USERDATA, 0); + DestroyWindow(hwnd_); + hwnd_ = nullptr; + } + if (icon_ && owns_icon_) DestroyIcon(icon_); + icon_ = nullptr; + owns_icon_ = false; +} + +LRESULT CALLBACK SplashWindow::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { + SplashWindow* self = nullptr; + if (msg == WM_NCCREATE) { + auto* cs = reinterpret_cast(lParam); + self = static_cast(cs->lpCreateParams); + SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast(self)); + self->hwnd_ = hwnd; + } else { + self = reinterpret_cast(GetWindowLongPtrW(hwnd, GWLP_USERDATA)); + } + if (!self) return DefWindowProcW(hwnd, msg, wParam, lParam); + return self->on_message(hwnd, msg, wParam, lParam); +} + +LRESULT SplashWindow::on_message(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { + switch (msg) { + case WM_PAINT: + paint(hwnd); + return 0; + case WM_CLOSE: + // Splash is not user-dismissible; host owns lifetime. + return 0; + case WM_DESTROY: + hwnd_ = nullptr; + return 0; + default: + return DefWindowProcW(hwnd, msg, wParam, lParam); + } +} + +void SplashWindow::paint(HWND hwnd) { + PAINTSTRUCT ps{}; + HDC hdc = BeginPaint(hwnd, &ps); + + RECT client{}; + GetClientRect(hwnd, &client); + FillRect(hdc, &client, splash_bg_brush()); + + if (icon_) { + int icon_x = (client.right - kIconSize) / 2; + int icon_y = 28; + DrawIconEx(hdc, icon_x, icon_y, icon_, kIconSize, kIconSize, 0, nullptr, DI_NORMAL); + } + + RECT text_rc{16, 28 + kIconSize + 16, client.right - 16, client.bottom - 16}; + SetBkMode(hdc, TRANSPARENT); + SetTextColor(hdc, RGB(32, 32, 32)); + DrawTextW(hdc, status_.c_str(), static_cast(status_.size()), &text_rc, + DT_CENTER | DT_TOP | DT_WORDBREAK | DT_NOPREFIX); + + EndPaint(hwnd, &ps); +} diff --git a/native/windows/src/splash_window.hpp b/native/windows/src/splash_window.hpp new file mode 100644 index 0000000..b96f226 --- /dev/null +++ b/native/windows/src/splash_window.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include "win_prefix.hpp" + +#include +#include + +// Small centered boot UI for packaged (host-first) Windows launches. +class SplashWindow { + public: + SplashWindow(); + ~SplashWindow(); + + SplashWindow(const SplashWindow&) = delete; + SplashWindow& operator=(const SplashWindow&) = delete; + + // icon_path: optional filesystem path (PNG/ICO). Empty/nullopt uses the + // embedded PE/module icon so the host stays app-agnostic. + void show(const std::wstring& status, const std::optional& icon_path = std::nullopt); + void set_status(const std::wstring& status); + void dismiss(); + bool visible() const { return hwnd_ != nullptr; } + + private: + static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); + static void register_class(); + LRESULT on_message(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); + void paint(HWND hwnd); + void load_icon(const std::optional& icon_path); + + HWND hwnd_ = nullptr; + HICON icon_ = nullptr; + bool owns_icon_ = false; + std::wstring status_; +}; diff --git a/scripts/build_windows.ps1 b/scripts/build_windows.ps1 index c106e1d..dbe1628 100644 --- a/scripts/build_windows.ps1 +++ b/scripts/build_windows.ps1 @@ -1,4 +1,4 @@ -# Build DesktopWebView.exe (x64) and copy to priv/native/windows/ +# Build DesktopWebView.exe + aumid_nif.dll (x64) into priv/native/windows/ $ErrorActionPreference = "Stop" $Root = Split-Path -Parent $PSScriptRoot @@ -16,8 +16,49 @@ if (-not $vsPath) { throw "Visual Studio with MSVC not found" } $vcvars = Join-Path $vsPath "VC\Auxiliary\Build\vcvars64.bat" if (-not (Test-Path $vcvars)) { throw "vcvars64.bat not found at $vcvars" } +function Get-ErtsInclude { + $elixir = Get-Command elixir -ErrorAction SilentlyContinue + if (-not $elixir) { return $null } + # elixir.bat + powershell -e "(...)" breaks on parentheses; use a temp script. + $exs = Join-Path $env:TEMP ("edw-erts-" + [guid]::NewGuid().ToString("n") + ".exs") + try { + Set-Content -Path $exs -Encoding ASCII -Value @( + 'IO.write(Path.join([' + ' List.to_string(:code.root_dir()),' + ' "erts-#{List.to_string(:erlang.system_info(:version))}",' + ' "include"' + ']))' + ) + $path = & elixir $exs + if ($LASTEXITCODE -ne 0 -or -not $path -or -not (Test-Path (Join-Path $path "erl_nif.h"))) { + return $null + } + return $path + } finally { + Remove-Item $exs -ErrorAction SilentlyContinue + } +} + +$ertsInclude = Get-ErtsInclude + $cmdExe = Join-Path $env:SystemRoot "System32\cmd.exe" $bat = Join-Path $env:TEMP ("edw-build-" + [guid]::NewGuid().ToString("n") + ".cmd") + +# enif_* resolve via WinDynNifCallbacks (no erl_dll.lib). shell32/ole32 for AUMID. +$nifBlock = "echo aumid_nif: skipped (elixir/erl_nif.h not found)" +if ($ertsInclude) { + $nifSrc = Join-Path $Root "c_src\aumid_nif.c" + $nifDll = Join-Path $OutDir "aumid_nif.dll" + $nifObj = Join-Path $BuildDir "aumid_nif.obj" + $nifExp = Join-Path $OutDir "aumid_nif.exp" + $nifLib = Join-Path $OutDir "aumid_nif.lib" + $nifBlock = @" +cl /nologo /LD /O2 /MD /I"$ertsInclude" "$nifSrc" /Fo"$nifObj" /Fe"$nifDll" /link shell32.lib ole32.lib || exit /b 1 +del /q "$nifExp" "$nifLib" 2>nul +echo Built priv\native\windows\aumid_nif.dll +"@ +} + @" @echo off call "$vcvars" || exit /b 1 @@ -38,6 +79,7 @@ if exist native\windows\build\DesktopWebView.exe ( exit /b 1 ) echo Built priv\native\windows\DesktopWebView.exe +$nifBlock "@ | Set-Content -Path $bat -Encoding ASCII try { @@ -46,3 +88,7 @@ try { } finally { Remove-Item $bat -ErrorAction SilentlyContinue } + +if (-not $ertsInclude) { + Write-Warning "aumid_nif.dll not built: need elixir on PATH with erl_nif.h (CI/setup-beam provides this)." +} diff --git a/test/event_bridge_test.exs b/test/event_bridge_test.exs index 3f22c6b..10ce29d 100644 --- a/test/event_bridge_test.exs +++ b/test/event_bridge_test.exs @@ -60,4 +60,27 @@ defmodule DesktopWebview.EventBridgeTest do Process.sleep(50) assert Process.alive?(bridge) end + + test "resubscribes after Transport crash", %{bridge: bridge} do + alias DesktopWebview.Transport + + EventBridge.register_window("w1", self()) + transport = Process.whereis(Transport) + assert is_pid(transport) + Process.exit(transport, :kill) + + # Wait for EventBridge to see DOWN and attach a new Transport. + :ok = + Enum.reduce_while(1..50, :error, fn _, _ -> + case Process.whereis(Transport) do + pid when is_pid(pid) and pid != transport -> {:halt, :ok} + _ -> + Process.sleep(10) + {:cont, :error} + end + end) + + send(bridge, {:edw_event, "event.window.close_requested", %{"window_id" => "w1"}}) + assert_receive {:"$gen_cast", :close_window}, 500 + end end