// Windows side of the `cesiumjs/webview` channel. // // Same protocol and approach as linux/cesiumjs_plugin.cc: each viewer is a // WebView2 hosted in a native child window placed *above* the Flutter view, // at the rectangle reported by Dart (setRect, logical pixels * scale). #include "include/cesiumjs/cesiumjs_plugin_c_api.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { using flutter::EncodableMap; using flutter::EncodableValue; using Microsoft::WRL::Callback; using Microsoft::WRL::ComPtr; using MethodResultPtr = std::unique_ptr>; constexpr char kChannelName[] = "cesiumjs/webview"; constexpr wchar_t kHostClass[] = L"CesiumjsWebViewHost"; constexpr char kDefaultBaseUrl[] = "https://cesium.localhost/"; // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- std::wstring Utf8ToWide(const std::string& s) { if (s.empty()) return {}; int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), nullptr, 0); std::wstring out(n, L'\0'); MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), out.data(), n); return out; } std::string WideToUtf8(const wchar_t* s) { if (s == nullptr || *s == 0) return {}; int n = WideCharToMultiByte(CP_UTF8, 0, s, -1, nullptr, 0, nullptr, nullptr); std::string out(n > 0 ? n - 1 : 0, '\0'); WideCharToMultiByte(CP_UTF8, 0, s, -1, out.data(), n, nullptr, nullptr); return out; } // Frees a WebView2 out-string on scope exit. struct CoStr { LPWSTR p = nullptr; ~CoStr() { CoTaskMemFree(p); } }; const EncodableValue* Lookup(const EncodableValue* args, const char* key) { const auto* map = args ? std::get_if(args) : nullptr; if (map == nullptr) return nullptr; auto it = map->find(EncodableValue(key)); return it == map->end() ? nullptr : &it->second; } std::optional GetInt(const EncodableValue* args, const char* key) { const EncodableValue* v = Lookup(args, key); if (v == nullptr) return std::nullopt; if (auto i = std::get_if(v)) return *i; if (auto i = std::get_if(v)) return *i; if (auto d = std::get_if(v)) return (int64_t)*d; return std::nullopt; } double GetDouble(const EncodableValue* args, const char* key, double fb = 0) { const EncodableValue* v = Lookup(args, key); if (v == nullptr) return fb; if (auto d = std::get_if(v)) return *d; if (auto i = std::get_if(v)) return *i; if (auto i = std::get_if(v)) return (double)*i; return fb; } const std::string* GetString(const EncodableValue* args, const char* key) { const EncodableValue* v = Lookup(args, key); return v ? std::get_if(v) : nullptr; } void AppendUtf8(std::string& out, uint32_t cp) { if (cp < 0x80) { out += (char)cp; } else if (cp < 0x800) { out += (char)(0xC0 | (cp >> 6)); out += (char)(0x80 | (cp & 0x3F)); } else if (cp < 0x10000) { out += (char)(0xE0 | (cp >> 12)); out += (char)(0x80 | ((cp >> 6) & 0x3F)); out += (char)(0x80 | (cp & 0x3F)); } else { out += (char)(0xF0 | (cp >> 18)); out += (char)(0x80 | ((cp >> 12) & 0x3F)); out += (char)(0x80 | ((cp >> 6) & 0x3F)); out += (char)(0x80 | (cp & 0x3F)); } } // ExecuteScript returns JSON. Mimic the Linux result: null for // undefined/null, the plain text for strings, the JSON text otherwise. std::optional JsonResultToString(const std::string& json) { if (json.empty() || json == "null") return std::nullopt; if (json.size() < 2 || json.front() != '"' || json.back() != '"') { return json; } std::string out; for (size_t i = 1; i + 1 < json.size(); ++i) { char c = json[i]; if (c != '\\' || i + 2 >= json.size()) { out += c; continue; } char e = json[++i]; switch (e) { case 'n': out += '\n'; break; case 't': out += '\t'; break; case 'r': out += '\r'; break; case 'b': out += '\b'; break; case 'f': out += '\f'; break; case 'u': { if (i + 4 >= json.size()) return json; uint32_t cp = std::stoul(json.substr(i + 1, 4), nullptr, 16); i += 4; if (cp >= 0xD800 && cp < 0xDC00 && i + 6 < json.size() && json[i + 1] == '\\' && json[i + 2] == 'u') { uint32_t lo = std::stoul(json.substr(i + 3, 4), nullptr, 16); cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00); i += 6; } AppendUtf8(out, cp); break; } default: out += e; // \" \\ \/ } } return out; } std::wstring UserDataFolder() { std::wstring base; PWSTR local = nullptr; if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &local))) { base = local; } CoTaskMemFree(local); wchar_t exe[MAX_PATH]; GetModuleFileNameW(nullptr, exe, MAX_PATH); std::wstring name = PathFindFileNameW(exe); if (auto dot = name.rfind(L'.'); dot != std::wstring::npos) { name.resize(dot); } return base + L"\\" + name + L"\\CesiumWebView2"; } // --------------------------------------------------------------------------- // Plugin // --------------------------------------------------------------------------- struct View { HWND host = nullptr; ComPtr controller; ComPtr webview; std::string html; std::wstring base_url; RECT bounds{}; // physical pixels, in host parent's client coordinates bool visible = false; // Run once WebView2 is ready; called with false if the view is disposed // first (so queued Dart futures still complete). std::vector> pending; }; class CesiumjsPlugin : public flutter::Plugin { public: explicit CesiumjsPlugin(flutter::PluginRegistrarWindows* registrar) : registrar_(registrar) { channel_ = std::make_unique>( registrar->messenger(), kChannelName, &flutter::StandardMethodCodec::GetInstance()); channel_->SetMethodCallHandler([this](const auto& call, auto result) { HandleMethodCall(call, std::move(result)); }); // WebView2 wants to know when the top-level window moves (popups, // IME and drop-down positions). proc_id_ = registrar->RegisterTopLevelWindowProcDelegate( [this](HWND, UINT msg, WPARAM, LPARAM) -> std::optional { if (msg == WM_MOVE || msg == WM_MOVING) { for (auto& [id, v] : views_) { if (v->controller) v->controller->NotifyParentWindowPositionChanged(); } } return std::nullopt; }); } ~CesiumjsPlugin() override { registrar_->UnregisterTopLevelWindowProcDelegate(proc_id_); DisposeAll(); } private: HWND FlutterHwnd() const { auto* view = registrar_->GetView(); return view ? view->GetNativeWindow() : nullptr; } // The runner makes the Flutter view a child of its top-level window; web // views are siblings stacked above it. HWND HostParent() const { HWND fv = FlutterHwnd(); HWND parent = fv ? GetParent(fv) : nullptr; return parent ? parent : fv; } static void EnsureHostClass() { static bool registered = false; if (registered) return; WNDCLASSEXW wc{}; wc.cbSize = sizeof(wc); wc.lpfnWndProc = DefWindowProcW; wc.hInstance = GetModuleHandleW(nullptr); wc.lpszClassName = kHostClass; wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wc.hCursor = LoadCursor(nullptr, IDC_ARROW); RegisterClassExW(&wc); registered = true; } void SendEvent(const char* method, int64_t id, const std::string& message) { channel_->InvokeMethod( method, std::make_unique(EncodableMap{ {EncodableValue("id"), EncodableValue(id)}, {EncodableValue("message"), EncodableValue(message)}, })); } View* Find(int64_t id) { auto it = views_.find(id); return it == views_.end() ? nullptr : it->second.get(); } void ApplyBounds(View* v) { bool show = v->visible && v->bounds.right > v->bounds.left && v->bounds.bottom > v->bounds.top; if (show) { SetWindowPos(v->host, HWND_TOP, v->bounds.left, v->bounds.top, v->bounds.right - v->bounds.left, v->bounds.bottom - v->bounds.top, SWP_NOACTIVATE | SWP_SHOWWINDOW); } else { ShowWindow(v->host, SW_HIDE); } if (v->controller) { RECT inner{0, 0, v->bounds.right - v->bounds.left, v->bounds.bottom - v->bounds.top}; v->controller->put_Bounds(inner); v->controller->put_IsVisible(show ? TRUE : FALSE); } } // --- create --------------------------------------------------------------- void Create(int64_t id, const std::string& html, const std::string& base, MethodResultPtr result) { HWND parent = HostParent(); if (parent == nullptr) { result->Error("no_window", "Flutter view has no native window"); return; } // Keep the Flutter view from painting over its sibling web views. HWND fv = FlutterHwnd(); if (fv && fv != parent) { SetWindowLongPtrW(fv, GWL_STYLE, GetWindowLongPtrW(fv, GWL_STYLE) | WS_CLIPSIBLINGS); } EnsureHostClass(); auto view = std::make_unique(); view->html = html; view->base_url = Utf8ToWide(base); view->host = CreateWindowExW( 0, kHostClass, L"", WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0, 0, 0, parent, nullptr, GetModuleHandleW(nullptr), nullptr); views_[id] = std::move(view); HRESULT create_hr = CreateCoreWebView2EnvironmentWithOptions( nullptr, UserDataFolder().c_str(), nullptr, Callback( [this, id](HRESULT env_hr, ICoreWebView2Environment* env) -> HRESULT { View* view = Find(id); if (view == nullptr) return S_OK; // disposed meanwhile if (FAILED(env_hr) || env == nullptr) { SendEvent("onError", id, "WebView2 runtime not available (install the " "Microsoft Edge WebView2 Runtime)"); return S_OK; } ComPtr environment(env); return env->CreateCoreWebView2Controller( view->host, Callback< ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>( [this, id, environment]( HRESULT, ICoreWebView2Controller* controller) -> HRESULT { View* v = Find(id); if (controller == nullptr) { if (v) SendEvent("onError", id, "WebView2 controller creation failed"); return S_OK; } if (v == nullptr) { controller->Close(); return S_OK; } OnControllerReady(id, v, environment.Get(), controller); return S_OK; }) .Get()); }) .Get()); if (FAILED(create_hr)) { SendEvent("onError", id, "WebView2 runtime not available (install the Microsoft Edge " "WebView2 Runtime)"); } result->Success(); } void OnControllerReady(int64_t id, View* v, ICoreWebView2Environment* env, ICoreWebView2Controller* controller) { v->controller = controller; controller->get_CoreWebView2(&v->webview); ICoreWebView2* wv = v->webview.Get(); ComPtr controller2; if (SUCCEEDED(controller->QueryInterface(IID_PPV_ARGS(&controller2)))) { controller2->put_DefaultBackgroundColor({255, 0, 0, 0}); // opaque black } ComPtr settings; if (SUCCEEDED(wv->get_Settings(&settings))) { settings->put_IsScriptEnabled(TRUE); settings->put_IsWebMessageEnabled(TRUE); settings->put_AreDevToolsEnabled(TRUE); settings->put_IsStatusBarEnabled(FALSE); settings->put_AreDefaultContextMenusEnabled(FALSE); } EventRegistrationToken token; // JS -> Dart: window.chrome.webview.postMessage("...") wv->add_WebMessageReceived( Callback( [this, id](ICoreWebView2*, ICoreWebView2WebMessageReceivedEventArgs* args) { CoStr msg; if (SUCCEEDED(args->TryGetWebMessageAsString(&msg.p))) { SendEvent("onMessage", id, WideToUtf8(msg.p)); } return S_OK; }) .Get(), &token); // Serve the page from the virtual origin, like load_html on Linux. std::wstring filter = v->base_url + L"*"; wv->AddWebResourceRequestedFilter(filter.c_str(), COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT); ComPtr environment(env); wv->add_WebResourceRequested( Callback( [this, id, environment]( ICoreWebView2*, ICoreWebView2WebResourceRequestedEventArgs* args) { View* target = Find(id); if (target == nullptr) return S_OK; ComPtr stream; stream.Attach(SHCreateMemStream( reinterpret_cast(target->html.data()), (UINT)target->html.size())); ComPtr response; environment->CreateWebResourceResponse( stream.Get(), 200, L"OK", L"Content-Type: text/html; charset=utf-8", &response); args->put_Response(response.Get()); return S_OK; }) .Get(), &token); // Links opening a new window (Cesium credits...) go to the browser. wv->add_NewWindowRequested( Callback( [](ICoreWebView2*, ICoreWebView2NewWindowRequestedEventArgs* args) { CoStr uri; if (SUCCEEDED(args->get_Uri(&uri.p)) && uri.p) { ShellExecuteW(nullptr, L"open", uri.p, nullptr, nullptr, SW_SHOWNORMAL); } args->put_Handled(TRUE); return S_OK; }) .Get(), &token); wv->add_NavigationCompleted( Callback( [this, id](ICoreWebView2*, ICoreWebView2NavigationCompletedEventArgs* args) { BOOL ok = TRUE; args->get_IsSuccess(&ok); if (!ok) { COREWEBVIEW2_WEB_ERROR_STATUS status; args->get_WebErrorStatus(&status); SendEvent("onError", id, "Load failed (WebView2 error " + std::to_string((int)status) + ")"); } return S_OK; }) .Get(), &token); wv->add_ProcessFailed( Callback( [this, id](ICoreWebView2*, ICoreWebView2ProcessFailedEventArgs* args) { COREWEBVIEW2_PROCESS_FAILED_KIND kind; args->get_ProcessFailedKind(&kind); SendEvent("onError", id, kind == COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED ? "Web browser process exited" : "Web process crashed"); return S_OK; }) .Get(), &token); ApplyBounds(v); wv->Navigate(v->base_url.c_str()); auto pending = std::move(v->pending); for (auto& fn : pending) fn(true); } // --- other methods -------------------------------------------------------- void SetRect(View* v, const EncodableValue* args) { double scale = GetDouble(args, "scale", 1.0); if (scale <= 0) scale = 1.0; POINT origin{(LONG)std::lround(GetDouble(args, "x") * scale), (LONG)std::lround(GetDouble(args, "y") * scale)}; // Dart reports coordinates relative to the Flutter view. HWND fv = FlutterHwnd(); HWND parent = GetParent(v->host); if (fv && parent && fv != parent) MapWindowPoints(fv, parent, &origin, 1); v->bounds = {origin.x, origin.y, origin.x + (LONG)std::lround(GetDouble(args, "width") * scale), origin.y + (LONG)std::lround(GetDouble(args, "height") * scale)}; const EncodableValue* vis = Lookup(args, "visible"); const bool* b = vis ? std::get_if(vis) : nullptr; v->visible = b == nullptr || *b; ApplyBounds(v); } void RunJavaScript(View* v, const std::string& script, MethodResultPtr result) { std::shared_ptr> shared( result.release()); std::wstring wscript = Utf8ToWide(script); auto run = [v, wscript, shared](bool ready) { if (!ready) { shared->Error("disposed", "the view was disposed"); return; } HRESULT hr = v->webview->ExecuteScript( wscript.c_str(), Callback( [shared](HRESULT exec_hr, LPCWSTR json) { if (FAILED(exec_hr)) { shared->Error("js_error", "ExecuteScript failed"); return S_OK; } auto value = JsonResultToString(WideToUtf8(json)); if (value) { shared->Success(EncodableValue(*value)); } else { shared->Success(); } return S_OK; }) .Get()); if (FAILED(hr)) shared->Error("js_error", "ExecuteScript failed"); }; if (v->webview) { run(true); } else { v->pending.push_back(run); } } void Dispose(int64_t id) { auto it = views_.find(id); if (it == views_.end()) return; std::unique_ptr v = std::move(it->second); views_.erase(it); for (auto& fn : v->pending) fn(false); if (v->controller) v->controller->Close(); if (v->host) DestroyWindow(v->host); } void DisposeAll() { while (!views_.empty()) Dispose(views_.begin()->first); } void HandleMethodCall(const flutter::MethodCall& call, MethodResultPtr result) { const std::string& method = call.method_name(); const EncodableValue* args = call.arguments(); auto id = GetInt(args, "id"); if (method == "disposeAll") { // Called once per Dart isolate start (hot restart). DisposeAll(); result->Success(); return; } if (method == "dispose") { if (id) Dispose(*id); result->Success(); return; } if (method == "create") { const std::string* html = GetString(args, "html"); if (!id || html == nullptr) { result->Error("bad_args", "create requires id and html"); } else if (Find(*id)) { result->Error("exists", "a view with this id already exists"); } else { const std::string* base = GetString(args, "baseUrl"); Create(*id, *html, base ? *base : kDefaultBaseUrl, std::move(result)); } return; } View* v = id ? Find(*id) : nullptr; if (method != "setRect" && method != "runJavaScript" && method != "openInspector") { result->NotImplemented(); return; } if (v == nullptr) { result->Error("not_found", "unknown view id"); return; } if (method == "setRect") { SetRect(v, args); result->Success(); } else if (method == "runJavaScript") { const std::string* script = GetString(args, "script"); if (script == nullptr) { result->Error("bad_args", "script missing"); } else { RunJavaScript(v, *script, std::move(result)); } } else { // openInspector if (v->webview) v->webview->OpenDevToolsWindow(); result->Success(); } } flutter::PluginRegistrarWindows* registrar_; std::unique_ptr> channel_; std::map> views_; int proc_id_ = 0; }; } // namespace void CesiumjsPluginCApiRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar_ref) { auto* registrar = flutter::PluginRegistrarManager::GetInstance() ->GetRegistrar(registrar_ref); registrar->AddPlugin(std::make_unique(registrar)); }