diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index b68f089aeb..324e796078 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc @@ -3,6 +3,14 @@ // found in the LICENSE file. #include "chrome/browser/ui/views/frame/browser_view.h" +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) +#include "chrome/browser/ui/views/side_panel/kour_flutter_panel.h" +#include "chrome/browser/ui/views/side_panel/kour_popup_window.h" +#endif +#if BUILDFLAG(IS_LINUX) +#include "chrome/browser/ui/views/side_panel/kour_shell_frames.h" +#endif + #include @@ -953,9 +961,29 @@ BrowserView::BrowserView(BrowserWindowInterface* browser) top_container_separator_->SetProperty(views::kElementIdentifierKey, kContentsSeparatorTopEdgeElementId); +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) + // Kour's shell is for a person's window. Headless (automation, the media + // checks) is Chromium's plain browser: there is no display for the shell's + // engine, whose creation fails. + if (browser_->GetType() == BrowserWindowInterface::Type::TYPE_NORMAL && + !headless::IsHeadlessMode()) { + AddChildView(CreateKourFlutterPanel(browser_)); + LOG(INFO) << "KOUR_SHELL_ROOT_V1"; + } +#endif + auto multi_contents_view = std::make_unique( this, std::make_unique(*browser_)); multi_contents_view_ = AddChildView(std::move(multi_contents_view)); +#if BUILDFLAG(IS_LINUX) + // X11 does not blend Kour's shell, a child window, over the pages: while + // something of the shell is over one, the compositor draws its frames in + // this view. Added here it is above the pages and below everything + // Chromium adds after them. + if (auto* shell = GetViewByID(kKourShellViewId)) { + AttachKourShellFrames(shell, AddChildView(CreateKourShellFrames())); + } +#endif set_contents_view(multi_contents_view_); @@ -1108,6 +1136,12 @@ BrowserView::BrowserView(BrowserWindowInterface* browser) } BrowserView::~BrowserView() { +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) + // Stop Flutter callbacks while BrowserView and its model are still alive. + if (auto* shell = GetViewByID(kKourShellViewId)) { + RemoveChildViewT(shell); + } +#endif // Remove the layout manager to avoid dangling. This needs to be earlier than // other cleanups that destroy views referenced in the layout manager. SetLayoutManager(nullptr); @@ -1363,6 +1397,7 @@ BrowserView::GetExclusiveAccessBubbleViewsContextForTesting() { return exclusive_access_context_.get(); } + bool BrowserView::GetTabStripVisible() const { if (!ShouldDrawTabStrip()) { return false; @@ -1425,6 +1460,9 @@ bool BrowserView::ShouldDrawTabStrokes() const { } bool BrowserView::ShouldDrawTabStrip() const { +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) + if (browser_->GetType() == BrowserWindowInterface::Type::TYPE_NORMAL) return false; +#endif // Return false if this window does not normally display a tabstrip or if the // tabstrip is currently hidden, e.g. because we're in fullscreen. if (!WindowFeatureController::From(browser_)->SupportsWindowFeature( @@ -1575,6 +1613,11 @@ float BrowserView::GetTopControlsSlideBehaviorShownRatio() const { views::Widget* BrowserView::GetWidgetForAnchoring() { #if BUILDFLAG(IS_MAC) + // Kour: its window's dialogs and bubbles stay on it in full screen, not on + // the overlay (ImmersiveModeControllerMac::ShouldMoveChild). + if (GetViewByID(kKourShellViewId)) { + return GetWidget(); + } if (WindowFeatureController::From(browser())->UsesImmersiveFullscreenMode()) { return IsFullscreen() ? overlay_widget_.get() : GetWidget(); } @@ -1977,6 +2020,11 @@ void BrowserView::OnActiveTabChanged(content::WebContents* old_contents, int reason) { DCHECK(new_contents); TRACE_EVENT0("ui", "BrowserView::OnActiveTabChanged"); +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) + if (GetViewByID(kKourShellViewId)) { + multi_contents_view_->SetKourActiveWebContents(new_contents); + } +#endif views::WebView* active_contents_view = GetActiveContentsWebView(); bool tab_change_in_split_view = IsTabChangeInSplitView(old_contents, new_contents); @@ -2384,6 +2432,12 @@ void BrowserView::UpdateToolbar(content::WebContents* contents) { if (toolbar_) { toolbar_->Update(contents); } + // Kour's layout never shows the split's mini toolbar, and keeps a container + // for every page it showed: a closing page's still holds it while the tab + // strip tells of the close, its tab's helpers already gone. + if (!multi_contents_view_ || multi_contents_view_->HasKourLayout()) { + return; + } for (ContentsContainerView* contents_container : multi_contents_view_->contents_container_views()) { contents_container->mini_toolbar()->UpdateContents(); @@ -3064,6 +3118,9 @@ void BrowserView::DisableTabStripEditingForTesting() { } bool BrowserView::IsToolbarVisible() const { +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) + if (browser_->GetType() == BrowserWindowInterface::Type::TYPE_NORMAL) return false; +#endif #if BUILDFLAG(IS_MAC) // Immersive full screen makes it possible to display the toolbar when // kShowFullscreenToolbar is not set. @@ -3333,6 +3390,11 @@ void BrowserView::HandleDragEnded() { } bool BrowserView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) { + // Kour's page-first commands (⌘D, ⌘J) the page did not take: Kour's, not Chrome's Bookmark This Tab. + if (auto* shell = GetViewByID(kKourShellViewId); + shell && HandleKourUnhandledKey(shell, event)) { + return true; + } if (browser_widget_->HandleKeyboardEvent(event)) { return true; } @@ -4437,12 +4499,10 @@ void BrowserView::MaybeUpdateStoredFocusForWebContents( std::vector BrowserView::GetAllVisibleContentsWebViews() { std::vector contents_views; - contents_views.push_back(multi_contents_view_->GetActiveContentsView()); - ContentsWebView* inactive_contents_view = - multi_contents_view_->GetInactiveContentsView(); - if (multi_contents_view_->IsInSplitView()) { - contents_views.push_back(inactive_contents_view); - } + multi_contents_view_->ExecuteOnEachVisibleContentsView(base::BindRepeating( + [](std::vector* result, ContentsWebView* view) { + result->push_back(view); + }, &contents_views)); return contents_views; } @@ -4452,6 +4512,14 @@ void BrowserView::RevealTopContainerIfNeeded() { if (!immersive_mode_controller->IsEnabled()) { return; } +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) + // Kour's tab strip is Flutter's and stays on screen in full screen. The + // top container is hidden, so a reveal would only bring AppKit's empty + // title bar down over that strip for a second at every page switch. + if (GetViewByID(kKourShellViewId)) { + return; + } +#endif // With vertical tab strip, the tab strip isn't in the immersive bar so it // only needs to be shown if the toolbar or location bar had focus. @@ -4595,6 +4663,16 @@ views::CloseRequestResult BrowserView::OnWindowCloseRequested() { return views::CloseRequestResult::kCannotClose; } +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) + if (auto* shell = GetViewByID(kKourShellViewId)) { + if (!CanCloseKourWindow(shell, base::BindOnce([](base::WeakPtr view) { + if (view) view->GetWidget()->Close(); + }, weak_ptr_factory_.GetWeakPtr()))) { + return views::CloseRequestResult::kCannotClose; + } + } +#endif + // Give beforeunload handlers, the user, or policy the chance to cancel the // close before we hide the window below. if (!UnloadController::From(browser_)->HandleBeforeClose()) { @@ -4886,6 +4964,52 @@ void BrowserView::Layout(PassKey) { } LayoutSuperclass(this); +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) + // A sign-in window's row of Kour's goes under its page, which gives it + // the room (kour_sign_in_window.cc). + if (auto* row = GetViewByID(kour::popup::kSignInRowViewId); + row && row->GetVisible()) { + gfx::Rect contents = multi_contents_view_->bounds(); + const int height = std::min(row->GetHeightForWidth(contents.width()), + contents.height() / 2); + contents.set_height(contents.height() - height); + multi_contents_view_->SetBoundsRect(contents); + row->SetBounds(contents.x(), contents.bottom(), contents.width(), height); + } + if (auto* shell = GetViewByID(kKourShellViewId)) { + top_container_->SetVisible(false); + if (horizontal_tab_strip_region_view_) horizontal_tab_strip_region_view_->SetVisible(false); + if (vertical_tab_strip_region_view_) vertical_tab_strip_region_view_->SetVisible(false); + if (organizer_tray_) organizer_tray_->SetVisible(false); + main_background_region_->SetVisible(false); + main_shadow_overlay_->SetVisible(false); + side_panel_->SetVisible(false); + auto shell_bounds = GetLocalBounds(); +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) + // The shell takes the frame's whole client area, the sign-in screen's too: + // Kour draws the window's buttons over it (docs/specs/2026-10-25-window-caption.md), + // and under Linux's system title bar the window manager's are outside it. + // The frame accounts for themes, DPI and fullscreen. + const auto frame = browser_widget()->GetFrameView()->GetBrowserLayoutParams(); + auto available = frame.visual_client_area; + auto origin = available.origin(); + views::View::ConvertPointFromWidget(this, &origin); + available.set_origin(origin); + shell_bounds.Intersect(available); +#endif + // Full screen on macOS: the shell stays where it is when the menu bar + // comes down over it; AppKit's title bar window, which would come down + // with it as an empty strip, is kept invisible by the shell's bridge, + // and the shell draws the traffic lights itself + // (docs/specs/2026-10-21-flat-shell.md). + shell->SetBoundsRect(shell_bounds); + multi_contents_view_->SetBoundsRect(shell_bounds); + // Keep Chromium's ownership/layout invariant while Flutter places each pane. + multi_contents_view_->SetVisible(true); + LayoutKourWebContents(shell, multi_contents_view_); + } +#endif + // TODO(jamescook): Why was this in the middle of layout code? toolbar_->location_bar()->UpdateFocusBehavior(IsToolbarVisible()); @@ -4989,6 +5113,12 @@ void BrowserView::AddedToWidget() { } views::ClientView::AddedToWidget(); +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) + // Kour: a popup (a sign-in) is dark or light as Kour is, not the system. + if (browser_->GetType() == BrowserWindowInterface::Type::TYPE_POPUP) { + kour::popup::FollowKour(GetWidget()); + } +#endif #if BUILDFLAG(IS_WIN) // Register for screen capture exclusion updates. This is specific to diff --git a/chrome/browser/ui/views/frame/browser_native_widget_mac.mm b/chrome/browser/ui/views/frame/browser_native_widget_mac.mm index 818924fc76..062b5a9bfa 100644 --- a/chrome/browser/ui/views/frame/browser_native_widget_mac.mm +++ b/chrome/browser/ui/views/frame/browser_native_widget_mac.mm @@ -40,6 +40,8 @@ #include "chrome/browser/ui/tabs/vertical_tab_strip_state_controller.h" #include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/views/frame/browser_frame_view.h" +#include "chrome/browser/ui/views/side_panel/kour_flutter_panel.h" +#include "chrome/browser/ui/views/side_panel/kour_popup_window.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/browser_widget.h" #include "chrome/browser/ui/views/frame/glass_frame_service.h" @@ -268,6 +270,21 @@ - (NSTouchBar*)makeTouchBar { void BrowserNativeWidgetMac::GetWindowFrameTitlebarHeight( bool* override_titlebar_height, float* titlebar_height) { + // The hidden tab strip would otherwise collapse the title bar and pin the + // traffic lights to the window's top edge. + if (browser_view_ && browser_view_->GetViewByID(kKourShellViewId)) { + *override_titlebar_height = true; + *titlebar_height = kKourTitlebarHeight; + return; + } + // A popup's row is its title bar: the traffic lights centre in it. + if (browser_view_ && + browser_view_->browser()->GetType() == + BrowserWindowInterface::Type::TYPE_POPUP) { + *override_titlebar_height = true; + *titlebar_height = kour::popup::kRowHeight; + return; + } if (browser_view_ && browser_view_->browser_widget() && browser_view_->browser_widget()->GetFrameView()) { *override_titlebar_height = true; @@ -737,6 +754,16 @@ - (NSTouchBar*)makeTouchBar { if (browser_view_->GetIsWebAppType()) { params->window_title_hidden = true; } + } else if (browser_view_->browser()->GetType() == + BrowserWindowInterface::Type::TYPE_POPUP) { + // Kour: a popup (a sign-in) has no title row; its address row sits + // beside the traffic lights, as Kour's own bar does. The browser's + // window class, which takes the row's height for the title bar's + // (GetWindowFrameTitlebarHeight), so the lights centre in the row. + params->window_class = remote_cocoa::mojom::WindowClass::kBrowser; + params->style_mask |= NSWindowStyleMaskFullSizeContentView; + params->titlebar_appears_transparent = true; + params->window_title_hidden = true; } else { params->window_class = remote_cocoa::mojom::WindowClass::kDefault; } diff --git a/chrome/browser/ui/views/side_panel/BUILD.gn b/chrome/browser/ui/views/side_panel/BUILD.gn index 64303e7ca0..1225c6f0f4 100644 --- a/chrome/browser/ui/views/side_panel/BUILD.gn +++ b/chrome/browser/ui/views/side_panel/BUILD.gn @@ -54,6 +54,60 @@ source_set("side_panel") { "tabs_from_other_devices/tabs_from_other_devices_side_panel_metrics.cc", "tabs_from_other_devices/tabs_from_other_devices_side_panel_metrics.h", ] + if (is_mac || is_win || is_linux) { + sources += [ + "kour_browser_data.cc", + "kour_browser_data.h", + "kour_browser_host.cc", + "kour_browser_host.h", + "kour_context_menu.cc", + "kour_context_menu.h", + "kour_extension_actions.cc", + "kour_extension_actions.h", + "kour_file_handoff.cc", + "kour_file_handoff.h", + "kour_flutter_panel.h", + "kour_mail_body.cc", + "kour_mail_body.h", + "kour_page_print.cc", + "kour_page_print.h", + "kour_page_agent.cc", + "kour_page_agent.h", + "kour_page_input.cc", + "kour_page_input.h", + "kour_page_media.cc", + "kour_page_media.h", + "kour_page_bell.cc", + "kour_page_bell.h", + "kour_page_switch.cc", + "kour_page_switch.h", + "kour_popup_window.cc", + "kour_popup_window.h", + "kour_sign_in_window.cc", + "kour_sign_in_window.h", + "kour_spaces.cc", + "kour_spaces.h", + ] + } + if (is_mac) { + sources += [ + "kour_flutter_panel.mm", + "kour_panel_abi.h", + ] + } + if (is_win || is_linux) { + sources += [ + "kour_desktop_panel_abi.h", + "kour_flutter_panel_desktop.cc", + ] + } + if (is_linux) { + sources += [ + "kour_shell_frames.cc", + "kour_shell_frames.h", + ] + } + public_deps = [ "//base", "//chrome/browser:browser_public_dependencies", @@ -94,6 +148,27 @@ source_set("side_panel") { "//url", ] deps = [ + "//chrome/browser/affiliations", + "//chrome/browser/history", + "//chrome/browser/device_reauth", + "//chrome/browser/password_manager/factories", + "//components/device_reauth", + "//ui/base/clipboard", + "//components/find_in_page", + "//components/history/core/browser", + "//components/password_manager/core/browser", + "//components/password_manager/core/browser:password_string", + "//components/password_manager/core/browser/export", + "//components/password_manager/core/browser/import:importer", + "//components/password_manager/core/browser/password_store:password_store_interface", + "//components/password_manager/core/browser/ui", + "//components/password_manager/core/browser/ui:credential_ui_entry", + "//components/input", + "//components/keep_alive_registry", + "//components/viz/common", + "//ui/events:dom_keycode_converter", + "//ui/events:events_base", + "//ui/gfx/codec", "//base:i18n", "//chrome/app:generated_resources", "//chrome/app:generated_resources_grit", @@ -154,6 +229,16 @@ source_set("side_panel") { "//components/language/core/common", "//components/omnibox/browser:vector_icons", "//components/optimization_guide/core:features", + # kour_page_agent: the page as the browser lays it out, and the actor's page tools + "//chrome/common:mojo_bindings", + "//components/actor/core:task_id", + "//components/optimization_guide/content/browser", + "//components/optimization_guide/proto:optimization_guide_proto", + "//components/page_content_annotations/content/browser", + # and what a page waits on the person for (askingPage): its dialog, a permission, the browser's sign-in + "//chrome/browser/ui/login", + "//components/javascript_dialogs", + "//components/permissions", "//components/performance_manager", "//components/pref_registry", "//components/search", @@ -179,6 +264,38 @@ source_set("side_panel") { "//ui/gfx/geometry:geometry_skia", "//ui/webui", ] + if (is_mac || is_win || is_linux) { + # kour_page_media: the page's media session (Chrome's media controls). + deps += [ + "//services/media_session/public/cpp", + "//services/media_session/public/mojom", + # kour_mail_body: the bodies' requests are refused at their factory. + "//services/network/public/cpp", + # kour_context_menu: Kour's items in a page's own menu. + "//components/renderer_context_menu", + # kour_page_print: a page as it would print, as a PDF. + "//components/printing/browser/print_to_pdf", + "//services/network/public/mojom", + ] + } + + if (is_win || is_linux) { + deps += [ + "//ui/aura", + "//ui/events", + ] + } + if (is_linux) { + deps += [ + "//cc/paint", + "//components/viz/common", + "//gpu/command_buffer/client", + "//gpu/command_buffer/common", + "//gpu/ipc/common:surface_handle_type", + # kour_flutter_panel_desktop: the system's window button layout. + "//ui/linux:linux_ui", + ] + } if (enable_extensions_core) { public_deps += [ diff --git a/ui/accessibility/platform/ax_platform_node_cocoa.h b/ui/accessibility/platform/ax_platform_node_cocoa.h index c6da73dc16..88dc266dd8 100644 --- a/ui/accessibility/platform/ax_platform_node_cocoa.h +++ b/ui/accessibility/platform/ax_platform_node_cocoa.h @@ -33,7 +33,10 @@ COMPONENT_EXPORT(AX_PLATFORM) @property(nonatomic, readonly) BOOL polite; @end +// Flutter ships a separate AXPlatformNodeCocoa implementation in this process. +// Keep Chromium's runtime identity distinct from the Flutter framework. COMPONENT_EXPORT(AX_PLATFORM) +__attribute__((objc_runtime_name("AnfaChromiumAXPlatformNodeCocoa"))) @interface AXPlatformNodeCocoa : NSAccessibilityElement diff --git a/chrome/browser/ui/views/side_panel/kour_flutter_panel.h b/chrome/browser/ui/views/side_panel/kour_flutter_panel.h new file mode 100644 index 0000000000..a590ea8d82 --- /dev/null +++ b/chrome/browser/ui/views/side_panel/kour_flutter_panel.h @@ -0,0 +1,45 @@ +#ifndef CHROME_BROWSER_UI_VIEWS_SIDE_PANEL_KOUR_FLUTTER_PANEL_H_ +#define CHROME_BROWSER_UI_VIEWS_SIDE_PANEL_KOUR_FLUTTER_PANEL_H_ + +#include +#include +#include "base/functional/callback_forward.h" +#include "build/build_config.h" +#include "ui/gfx/geometry/rect.h" + +class BrowserWidget; +class BrowserWindowInterface; +class MultiContentsView; +namespace input { struct NativeWebKeyboardEvent; } +namespace views { class View; } + +inline constexpr int kKourShellViewId = 0x414e4641; +// The Flutter sidebar's title bar; the traffic lights centre within it, on the line the Space, the sidebar's toggle +// and the card's bars share (8 + 38 / 2 = 27). +inline constexpr float kKourTitlebarHeight = 54; +std::unique_ptr CreateKourFlutterPanel(BrowserWindowInterface* browser); +void LayoutKourWebContents(views::View* shell, MultiContentsView* contents); +bool CanCloseKourWindow(views::View* shell, base::OnceClosure retry_close); +#if BUILDFLAG(IS_WIN) +// Whether the shell has the window clear for the system backdrop under its +// sidebar, and how dark that backdrop is to be (`windowBackdrop`). +bool KourShellWantsBackdrop(views::View* shell); +std::optional KourShellBackdropDark(views::View* shell); +#endif +// A key a web page left (Chrome's order: the page first, the browser after): true when it is one of Kour's +// page-first commands (⌘D, ⌘J), which the shell is then given instead of Chromium's own menu or accelerator. +bool HandleKourUnhandledKey(views::View* shell, const input::NativeWebKeyboardEvent& event); +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) +// Whether Kour's shell draws the window's minimise, maximise and close itself +// (docs/specs/2026-10-25-window-caption.md): always on Windows; on Linux where +// the browser draws the window's frame, not the system's title bar. The shell +// then takes the window's whole client area, with no caption strip above it. +bool KourDrawsWindowButtons(BrowserWidget* widget); +#endif +#if BUILDFLAG(IS_LINUX) +// `frames` (kour_shell_frames.h) is where the browser's compositor draws the +// shell while its own window is off the screen; it follows the shell's bounds. +void AttachKourShellFrames(views::View* shell, views::View* frames); +#endif + +#endif diff --git a/chrome/browser/ui/views/side_panel/kour_flutter_panel.mm b/chrome/browser/ui/views/side_panel/kour_flutter_panel.mm new file mode 100644 index 0000000000..3726c83ff1 --- /dev/null +++ b/chrome/browser/ui/views/side_panel/kour_flutter_panel.mm @@ -0,0 +1,1567 @@ +#include "chrome/browser/ui/views/side_panel/kour_flutter_panel.h" +#include "chrome/browser/ui/views/side_panel/kour_popup_window.h" +#include "chrome/browser/ui/views/side_panel/kour_sign_in_window.h" +#include "components/input/native_web_keyboard_event.h" +#include "chrome/browser/ui/views/side_panel/kour_browser_data.h" +#include "chrome/browser/ui/views/side_panel/kour_extension_actions.h" +#include "chrome/browser/ui/views/side_panel/kour_browser_host.h" +#include "chrome/browser/ui/views/side_panel/kour_page_agent.h" +#include "chrome/browser/ui/views/side_panel/kour_page_input.h" +#include "chrome/browser/ui/views/side_panel/kour_page_media.h" +#include "chrome/browser/ui/views/side_panel/kour_page_print.h" +#include "chrome/browser/ui/views/side_panel/kour_page_bell.h" +#include "chrome/browser/ui/views/side_panel/kour_context_menu.h" +#include "chrome/browser/ui/views/side_panel/kour_file_handoff.h" +#include "chrome/browser/download/kour_download_folders.h" +#include "chrome/browser/ui/views/side_panel/kour_mail_body.h" +#include "chrome/browser/ui/views/side_panel/kour_page_switch.h" +#include "chrome/browser/ui/views/side_panel/kour_spaces.h" +#include "chrome/browser/ui/browser_commands.h" + +#import +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "base/apple/bundle_locations.h" +#include "base/base64.h" +#include "base/check.h" +#include "base/containers/span.h" +#include "base/task/cancelable_task_tracker.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/no_destructor.h" +#include "base/task/task_traits.h" +#include "base/task/thread_pool.h" +#include "content/public/common/mhtml_generation_params.h" +#include "base/callback_list.h" +#include "base/timer/timer.h" +#include "chrome/browser/devtools/devtools_window.h" +#include "content/public/browser/web_contents.h" +#include "third_party/blink/public/mojom/frame/sudden_termination_disabler_type.mojom.h" +#include "base/functional/bind.h" +#include "base/memory/raw_ptr.h" +#include "base/memory/weak_ptr.h" +#include "base/json/json_reader.h" +#include "base/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/ui/browser_window/public/browser_window_interface.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/browser/favicon/favicon_service_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "components/favicon/core/favicon_service.h" +#include "components/favicon_base/favicon_types.h" +#include "components/keyed_service/core/service_access_type.h" +#include "content/public/browser/favicon_status.h" +#include "content/public/browser/navigation_entry.h" +#include "chrome/browser/ui/browser_tabstrip.h" +#include "chrome/browser/ui/navigator/browser_navigator.h" +#include "chrome/browser/ui/navigator/browser_navigator_params.h" +#include "chrome/browser/lifetime/browser_shutdown.h" +#include "base/strings/string_number_conversions.h" +#include "chrome/browser/ui/unload_controller.h" +#include "chrome/browser/ui/views/frame/multi_contents_view.h" +#include "chrome/common/chrome_isolated_world_ids.h" +#include "content/public/browser/render_frame_host.h" +#include "base/task/sequenced_task_runner.h" +#include "base/time/time.h" +#include "content/public/browser/navigation_controller.h" +#include "content/public/browser/browser_accessibility_state.h" +#include "content/public/browser/scoped_accessibility_mode.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/render_widget_host_view.h" +#include "components/tabs/public/tab_interface.h" +#include "base/check_op.h" +#include "base/logging.h" +#include "chrome/browser/ui/views/side_panel/kour_panel_abi.h" +#include "ui/base/base_window.h" +#include "url/url_constants.h" +#include "ui/base/metadata/metadata_header_macros.h" +#include "ui/base/metadata/metadata_impl_macros.h" +#include "ui/base/page_transition_types.h" +#include "ui/base/window_open_disposition.h" +#include "url/origin.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/size.h" +#include "ui/gfx/native_ui_types.h" +#include "url/gurl.h" +#include "ui/views/controls/native/native_view_host.h" + +namespace { + +// A path in the outer application's Contents/Frameworks. +std::string Bundled(std::string_view name) { + return base::apple::OuterBundlePath() + .Append("Contents") + .Append("Frameworks") + .Append(name) + .value(); +} + +struct PanelModule { + PanelModule() { + // Kour's own code is in the application's Frameworks, where the build + // put it: the browser finds it there, and is told nothing by a launcher. + const std::string path = Bundled("libKourPanel.dylib"); + // Process-lifetime loading: unloading a registered Objective-C/Flutter + // runtime is unsafe. No engine is loaded by GN into renderer helpers. + void* module = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + CHECK(module) << dlerror(); + auto version = reinterpret_cast( + dlsym(module, "KourPanelAbiVersion")); + CHECK(version); + CHECK_EQ(version(), 7u); + create = reinterpret_cast(dlsym(module, "KourCreatePanel")); + view = reinterpret_cast(dlsym(module, "KourPanelNativeView")); + destroy = reinterpret_cast(dlsym(module, "KourDestroyPanel")); + prepare_close = reinterpret_cast(dlsym(module, "KourPreparePanelClose")); + unhandled_key = reinterpret_cast(dlsym(module, "KourPanelUnhandledKey")); + page_event = reinterpret_cast(dlsym(module, "KourPanelPageEvent")); + CHECK(create && view && destroy && prepare_close && unhandled_key && page_event); + } + decltype(&KourCreatePanel) create = nullptr; + decltype(&KourPanelNativeView) view = nullptr; + decltype(&KourDestroyPanel) destroy = nullptr; + decltype(&KourPreparePanelClose) prepare_close = nullptr; + decltype(&KourPanelUnhandledKey) unhandled_key = nullptr; + decltype(&KourPanelPageEvent) page_event = nullptr; +}; + +PanelModule& Module() { + // Trivially destructible; no exit-time teardown or dlclose is registered. + static PanelModule module; + return module; +} + +void Record(std::string_view kind) { + LOG(INFO) << "KOUR_EVENT {\"surface\":\"chromium-native-host\",\"kind\":\"" + << kind << "\"}"; +} + +class KourFlutterPanel final : public views::NativeViewHost { + METADATA_HEADER(KourFlutterPanel, views::NativeViewHost) + + public: + explicit KourFlutterPanel(BrowserWindowInterface* browser) + : browser_(browser), browser_data_(browser->GetProfile()), extensions_(browser, this), + mail_bodies_(browser), panel_(nullptr, Module().destroy) { + All().insert(this); + SetID(kKourShellViewId); + SetFocusBehavior(FocusBehavior::ALWAYS); + kour::WatchDownloadsForHandoff(browser->GetProfile()); + // (the Spaces' folders as last said, for a download before the shell speaks) + kour::LoadSpaceDownloadFolders(browser->GetProfile()); + SweepArchives(browser->GetProfile()->GetPath()); + // Kour's documents printed in a mail body, a note's PDF; a body's ⌘P told + // to the shell (compat-fixes B7). + mail_bodies_.SetPrinting(&prints_, base::BindRepeating( + [](KourFlutterPanel* self, base::DictValue event) { self->SendPageEvent(event); }, + base::Unretained(this))); + page_menu_id_ = kour::AddPageMenu( + base::BindRepeating([](base::WeakPtr self, content::WebContents* contents) { + return self ? self->MenuItemsFor(contents) : std::vector(); + }, weak_factory_.GetWeakPtr()), + base::BindRepeating([](base::WeakPtr self, content::WebContents* contents, + const std::string& item, const std::u16string& text) { + if (self) self->MenuChosen(contents, item, text); + }, weak_factory_.GetWeakPtr())); + + // A close that is refused, by anyone (a save that failed here, a page's + // "Leave site?", a download still running): the window this panel hid + // for the close is shown again. + close_cancelled_ = browser->RegisterBrowserCloseCancelled(base::BindRepeating( + [](base::WeakPtr self, BrowserWindowInterface*, + BrowserWindowInterface::ClosingStatus status) { + if (self) self->CloseRefused(status); + }, + weak_factory_.GetWeakPtr())); + // This window's page commands are the browser host's too: the assistant's browser tool drives the pages from the core. + // Never a private window's (P16): the assistant is not given its pages or its session. + if (!browser_->GetProfile()->IsOffTheRecord()) export_id_ = kour::BrowserHostExport::Get().AddPanel(base::BindRepeating( + [](base::WeakPtr self, std::string_view method, std::string_view arguments) -> std::string { + return self ? self->Command(method, arguments) : std::string(R"({"error":"page_not_open"})"); + }, + weak_factory_.GetWeakPtr())); + } + + ~KourFlutterPanel() override { + All().erase(this); + kour::RemovePageMenu(page_menu_id_); + weak_factory_.InvalidateWeakPtrs(); + // Archives nobody collected: their files go with the window. + for (const auto& [ticket, job] : archives_) RemoveArchive(job.path); + // No shell here any more: links are tabs again. + kour::TakeExternalLinks(browser_, false); + // A sign-in window belongs to the window that opened it. + sign_in_.reset(); + if (export_id_ >= 0) kour::BrowserHostExport::Get().RemovePanel(export_id_); + // Base destruction happens after members: detach before panel_ releases + // the NSView and engine that NativeViewHost otherwise still references. + Detach(); + panel_.reset(); + Record("destroyed"); + } + + void AddedToWidget() override { + views::NativeViewHost::AddedToWidget(); + // View's add notification follows ViewHierarchyChanged, where + // NativeViewHost creates its platform wrapper. Attaching earlier is invalid. + if (!panel_) { + const std::string bundle = Bundled("App.framework"); + panel_.reset(Module().create(bundle.c_str(), &HandleCommand, this)); + CHECK(panel_) << "Flutter panel creation failed; inspect KOUR_EVENT"; + } + NSView* native = (__bridge NSView*)Module().view(panel_.get()); + CHECK(native); + if (!native_view()) Attach(gfx::NativeView(native)); + Record("attached"); + } + + void RemovedFromWidget() override { + Detach(); + views::NativeViewHost::RemovedFromWidget(); + // Keep the engine during temporary view reparenting; destruction shuts it down. + Record("detached"); + } + + void LayoutWebContents(MultiContentsView* contents) { + contents_view_ = contents; + std::vector surfaces; + // Mail bodies are no tabs: each in a web view of its own, never a + // contents container (MultiContentsView::SetKourBodies). + std::vector bodies; + for (const auto& [page_id, bounds] : viewports_) { + if (auto* page = Page(page_id)) { + surfaces.push_back({page, bounds, false, Background(page_id, page)}); + } else if (auto* body = mail_bodies_.Get(page_id)) { + bodies.push_back({body, bounds}); + } + } + // The pages held over the ones that took their place (showPages). + for (const auto& held : page_switch_.held()) { + content::WebContents* page = held.contents.get(); + // (not one another window has taken since: adoptPage) + if (page && browser_->GetTabStripModel()->GetIndexOfWebContents(page) != TabStripModel::kNoTab && + std::ranges::none_of(surfaces, [page](const auto& surface) { + return surface.contents == page; + })) { + surfaces.push_back({page, held.bounds, true, Background(held.id, page)}); + } + } + contents->SetKourWebContents(surfaces, browser_->GetTabStripModel()->GetActiveWebContents(), modal_); + contents->SetKourBodies(bodies, modal_); + } + + void OnFocus() override { + views::NativeViewHost::OnFocus(); + // This callback proves a Views focus request, not that AppKit accepted it. + Record("focusRequested"); + } + + bool HandleUnhandledKey(const input::NativeWebKeyboardEvent& event) { + // (one key-down: its character event carries the same NSEvent) + if (!panel_ || event.GetType() != blink::WebInputEvent::Type::kRawKeyDown || event.skip_if_unhandled || + !event.os_event) { + return false; + } + return Module().unhandled_key(panel_.get(), (__bridge void*)event.os_event.Get()) == 1; + } + + bool CanClose(base::OnceClosure retry_close) { + if (!panel_) return true; + if (close_ready_) { + // Approval belongs to this attempt. A webpage can subsequently cancel + // its beforeunload, in which case the next attempt must save again. + close_ready_ = false; + return true; + } + if (!close_pending_) { + close_pending_ = true; + // The window goes at once, as Chromium's own close hides it before + // its tabs have closed. The save below may wait on a disk or a + // network, for seconds: a window that stayed all that time looked like + // a Quit that was not heard, and asking again did nothing (a close + // under way takes no second one). Not while a page may still ask + // "Leave site?": that question needs its window. Nor in full screen, + // where a window taken away leaves its empty Space behind. + auto* widget = GetWidget(); + if (widget && widget->IsVisible() && !widget->IsMinimized() && + !widget->IsFullscreen() && + !(UnloadController::From(browser_)->TabsNeedBeforeUnloadFired() && + PagesMayAskToStay())) { + hidden_for_close_ = true; + widget->Hide(); + // A save that never answers must not leave a window nobody can see. + close_watchdog_.Start(FROM_HERE, base::Seconds(30), + base::BindOnce(&KourFlutterPanel::ShowAfterRefusedClose, + base::Unretained(this))); + } + // Accepted native writes outlive navigation away from the import page. + // Once the current batch ends, Flutter cancels/drains the remaining flow. + browser_data_.WhenIdle(base::BindOnce(&KourFlutterPanel::PrepareClose, + weak_factory_.GetWeakPtr(), std::move(retry_close))); + } + return false; + } + + private: + // A page that can ask "Leave site?" when it is closed: a frame with a + // beforeunload handler, or DevTools with a question of its own. (What + // Chromium counts as "needs beforeunload fired" is wider: unload, pagehide + // and visibilitychange handlers too, which most pages have and which show + // nothing.) + bool PagesMayAskToStay() const { + auto* model = browser_->GetTabStripModel(); + for (int i = 0; i < model->count(); ++i) { + content::WebContents* contents = model->GetWebContentsAt(i); + if (DevToolsWindow::NeedsToInterceptBeforeUnload(contents)) return true; + bool asks = false; + contents->GetPrimaryMainFrame()->ForEachRenderFrameHost( + [&asks](content::RenderFrameHost* frame) { + asks = asks || frame->GetSuddenTerminationDisablerState( + blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler); + }); + if (asks) return true; + } + return false; + } + void CloseRefused(BrowserWindowInterface::ClosingStatus status) { + // "Unload handlers need time" is not a refusal: the close goes on when + // they have run, and the window stays away. Unless one of them may ask. + if (status == BrowserWindowInterface::ClosingStatus::kDeniedUnloadHandlersNeedTime && + !(UnloadController::From(browser_)->TabsNeedBeforeUnloadFired() && + PagesMayAskToStay())) { + return; + } + ShowAfterRefusedClose(); + } + void ShowAfterRefusedClose() { + close_watchdog_.Stop(); + if (!hidden_for_close_) return; + hidden_for_close_ = false; + // Its tabs already closed (the barrier is asked a second time then, and + // Chromium has hidden the window itself): nothing to show. + if (browser_->GetTabStripModel()->empty()) return; + if (auto* widget = GetWidget()) widget->Show(); + } + void PrepareClose(base::OnceClosure retry_close) { + LOG(INFO) << "KOUR_SHELL_CLOSE_V1"; + auto* reply = new base::OnceCallback(base::BindOnce( + &KourFlutterPanel::DidPrepareClose, weak_factory_.GetWeakPtr(), + std::move(retry_close))); + Module().prepare_close(panel_.get(), [](void* context, int allowed) { + auto callback = std::unique_ptr>( + static_cast*>(context)); + std::move(*callback).Run(allowed != 0); + }, reply); + } + void DidPrepareClose(base::OnceClosure retry_close, bool allowed) { + // Chromium has let go of the panel: its window is being deleted, and the + // bridge refuses, as it lets go, a close it was still asked about. That + // close is past undoing; cancelling it fails UnloadController's CHECK. + // (unique_ptr::reset clears panel_ before KourDestroyPanel runs.) + if (!panel_) return; + close_watchdog_.Stop(); + close_pending_ = false; + close_ready_ = allowed; + if (allowed) { + std::move(retry_close).Run(); + } else { + // Undo Chromium's application-quit state as a cancelled beforeunload + // would. Otherwise Command-Q stays latched and its faded windows may + // remain hidden after a save failure. + auto* unload = UnloadController::From(browser_); + unload->CancelWindowClose(); + unload->NotifyWindowCloseCancelled( + BrowserWindowInterface::ClosingStatus::kDeniedByUser); + // And the quit itself: the application takes no Quit while it believes + // one is under way, and nothing else ends this one (Chromium ends it + // when a page refuses to unload, which is before the windows are asked + // to close; this refusal comes after). Left set, no later Quit was + // heard at all, from the menu, the keyboard or the Dock. + browser_shutdown::SetTryingToQuit(false); + } + } + int Index(int handle) const { + auto* model = browser_->GetTabStripModel(); + for (int i = 0; i < model->count(); ++i) { + if (model->GetTabAtIndex(i)->GetHandle().raw_value() == handle) return i; + } + return -1; + } + + // Every Kour window's panel: a page is in one window at a time, and may + // move to another (one engine, every window a view of it). + static std::set& All() { + static base::NoDestructor> all; + return *all; + } + + // The other window's panel that holds the page [id], else null. + KourFlutterPanel* Holder(const std::string& id) const { + for (auto* other : All()) { + // (a page of one profile never goes to another's window) + if (other != this && other->browser_->GetProfile() == browser_->GetProfile() && other->Page(id)) return other; + } + return nullptr; + } + + // `askingPage`: what the page waits on the person for and what it opened (KourPageAgent::Asking), with the tabs of + // this window it opened, by their pages. + std::string Asking(content::WebContents* contents) { + base::DictValue out = KourPageAgent::Asking(contents); + base::ListValue opened; + if (const base::ListValue* windows = out.FindList("opened")) opened = windows->Clone(); + TabStripModel* model = browser_->GetTabStripModel(); + for (int i = 0; i < model->count(); ++i) { + content::WebContents* tab = model->GetWebContentsAt(i); + if (tab == contents || tab->GetFirstWebContentsInLiveOriginalOpenerChain() != contents) { + continue; + } + const int handle = model->GetTabAtIndex(i)->GetHandle().raw_value(); + const std::string site = url::Origin::Create(tab->GetVisibleURL()).Serialize(); + bool bound = false; + for (const auto& [id, page_handle] : pages_) { + if (page_handle == handle) { + opened.Append(base::DictValue() + .Set("page", id) + .Set("url", site) + .Set("title", base::UTF16ToUTF8(tab->GetTitle()))); + bound = true; + } + } + if (!bound) { + opened.Append(base::DictValue() + .Set("tab", true) + .Set("url", site) + .Set("title", base::UTF16ToUTF8(tab->GetTitle()))); + } + } + if (!opened.empty()) out.Set("opened", std::move(opened)); + return base::WriteJson(out).value_or("{}"); + } + + content::WebContents* Page(const std::string& id) const { + auto found = pages_.find(id); + if (found == pages_.end()) return nullptr; + const int index = Index(found->second); + return index < 0 ? nullptr : browser_->GetTabStripModel()->GetWebContentsAt(index); + } + + // What `panes` may place: a page, or a mail message's body. Nothing else + // of a page's is a body's: no command finds one by Page(). + content::WebContents* Surface(const std::string& id) const { + if (auto* page = Page(id)) return page; + return mail_bodies_.Get(id); + } + + bool ValidId(const std::string* id) const { return kour::ValidPageId(id); } + + bool ValidURL(const std::string* value) const { + if (!value || value->size() > 16384) return false; + const GURL url(*value); + return url.is_valid() && !url.has_username() && !url.has_password() && + (url.SchemeIsHTTPOrHTTPS() || url.SchemeIsFile() || url.SchemeIs("chrome") || + url.SchemeIs("chrome-extension") || url.spec() == "about:blank"); + } + + std::string State() { + // A private window is named so for Kour's voice keys, which read nothing of it and keep nothing (P16). + if (browser_->GetProfile()->IsOffTheRecord() && GetWidget()) { + [GetWidget()->GetNativeWindow().GetNativeNSWindow() setIdentifier:@"kour.private"]; + } + auto* model = browser_->GetTabStripModel(); + std::erase_if(pages_, [&](const auto& entry) { return Index(entry.second) < 0; }); + std::erase_if(accessibility_modes_, [&](const auto& entry) { return Index(entry.first) < 0; }); + base::ListValue pages; + base::ListValue unbound; + for (int i = 0; i < model->count(); ++i) { + auto* contents = model->GetWebContentsAt(i); + const int handle = model->GetTabAtIndex(i)->GetHandle().raw_value(); + if (accessibility_requested_ && !accessibility_modes_.contains(handle)) { + // A platform query of the Flutter shell also needs the real webpage + // subtrees. Scope activation to this window's sessions, including pages + // opened after the first query; the mode's lifetime ends with the page. + accessibility_modes_.emplace(handle, + content::BrowserAccessibilityState::GetInstance()->CreateScopedModeForWebContents( + contents, ui::kAXModeComplete)); + } + auto record = base::DictValue() + .Set("nativeId", handle) + .Set("title", base::UTF16ToUTF8(contents->GetTitle())) + .Set("url", contents->GetVisibleURL().spec()) + .Set("active", i == model->active_index()) + .Set("focused", kour::PageFocused(contents)) + .Set("back", contents->GetController().CanGoBack()) + .Set("forward", contents->GetController().CanGoForward()) + .Set("loading", contents->IsLoading()); + // A document Kour is fetching for this page (kour_file_handoff). + if (auto handing = kour::HandoffProgress(contents)) record.Set("handing", std::move(*handing)); + // The Space the page was made in: its web data is that Space's. + if (const std::string space = kour::SpaceOf(contents); !space.empty()) { + record.Set("space", space); + } + // Playing sound now: a page the person is listening to is not + // tidied away. + if (contents->IsCurrentlyAudible()) record.Set("audible", true); + // Its media, as the browser's media session has it (kour_page_media). + if (auto media = kour::PageMedia(contents)) record.Set("media", std::move(*media)); + // The page's declared theme colour, else its painted background: shell + // tabs continue the page's colour into its tab. + if (auto color = contents->GetThemeColor()) { + record.Set("themeColor", base::StringPrintf("#%08X", *color)); + } + if (auto color = contents->GetBackgroundColor()) { + record.Set("backgroundColor", base::StringPrintf("#%08X", *color)); + } + // The address of the page's own icon, once the browser has it: only + // the address, so the shell knows when to ask for the picture + // ("pageIcon") without the picture riding in every state. A web + // address only: an icon drawn by script as a data: address would + // change the state at every frame of it. + if (auto* entry = contents->GetController().GetLastCommittedEntry()) { + const content::FaviconStatus& icon = entry->GetFavicon(); + if (icon.valid && icon.url.is_valid() && icon.url.SchemeIsHTTPOrHTTPS() && + icon.url.spec().size() <= 2048) { + record.Set("icon", icon.url.spec()); + } + } + bool bound = false; + for (const auto& [id, page_handle] : pages_) { + if (page_handle == handle) { + record.Set("pageId", id); + pages.Append(std::move(record)); + bound = true; + break; + } + } + if (!bound) { + // A page another page opened (window.open, target=_blank) says + // which: the shell shows it as a tab beside its opener. One opened + // as a tab of its own (a Command-click, a link from another + // application) has no opener here, and is in front or not as + // Chromium opened it ("active"). + if (auto* opener = contents->GetFirstWebContentsInLiveOriginalOpenerChain()) { + const int at = model->GetIndexOfWebContents(opener); + if (at >= 0) { + record.Set("opener", model->GetTabAtIndex(at)->GetHandle().raw_value()); + } + } else if (const int self = model->GetIndexOfWebContents(contents); self >= 0) { + // A tab of its own that a page's link opened (a Command-click, a + // middle-click, Open Link in New Tab) is no popup, but says whose + // link it was: Tidy tells its model which page opened which. + if (tabs::TabInterface* from = model->GetOpenerOfTabAt(self)) { + record.Set("linkedFrom", from->GetHandle().raw_value()); + } + } + unbound.Append(std::move(record)); + } + } + // Documents the browser handed to Kour's viewers (kour_file_handoff), + // by the page they came from; until the shell acknowledges them. + base::ListValue files; + for (const auto& file : kour::HandedFiles()) { + std::string page; + for (const auto& [id, page_handle] : pages_) { + if (page_handle == file.tab || page_handle == file.opener) page = id; + } + // A window's file is that window's to show (its tab may be gone: one + // opened only for the file); one from no window is any window's of + // its profile. + if (file.window >= 0 ? file.window != browser_->GetSessionID().id() + : file.profile != kour::ProfileKey(browser_->GetProfile())) { + continue; + } + auto record = base::DictValue() + .Set("id", file.id) + .Set("path", file.path) + .Set("name", file.name) + .Set("mime", file.mime) + .Set("url", file.url) + .Set("requested", file.requested.empty() ? file.url : file.requested) + .Set("disposition", file.disposition) + .Set("origin", file.origin); + if (!page.empty()) record.Set("pageId", page); + if (file.has_space) record.Set("space", file.space); + files.Append(std::move(record)); + } + // Links the system handed to Kour, waiting for the shell to place them + // (kour_spaces): until it acknowledges them. + base::ListValue arrivals; + for (const auto& link : kour::ExternalLinks(browser_)) { + auto record = base::DictValue().Set("id", link.id).Set("url", link.url); + if (!link.app.empty()) record.Set("app", link.app); + arrivals.Append(std::move(record)); + } + base::ListValue capabilities; + capabilities.Append("evaluatePage"); + capabilities.Append("closePages"); + capabilities.Append("files"); + capabilities.Append("downloads"); + capabilities.Append("pageIcon"); + capabilities.Append("inputPage"); + capabilities.Append("capturePage"); + capabilities.Append("contentPage"); + capabilities.Append("toolPage"); + capabilities.Append("evaluateFrame"); + capabilities.Append("pageMedia"); + capabilities.Append("autoPictureInPicture"); + capabilities.Append("captureVideoFrame"); + capabilities.Append("showPages"); + capabilities.Append("archivePage"); + capabilities.Append("printPage"); + // Kour's own documents printed with the system's dialog, and as PDFs (B7). + capabilities.Append("printMailBody"); + capabilities.Append("pageEvents"); + capabilities.Append("pageMenu"); + capabilities.Append("downloadPrefs"); + capabilities.Append("spaceDownloadFolders"); + capabilities.Append("browserHost"); + capabilities.Append("findPage"); + capabilities.Append("spaces"); + capabilities.Append("forgetAddresses"); + // Clear History in the browser's own history, every Space (C17). + capabilities.Append("clearHistory"); + capabilities.Append("externalLinks"); + capabilities.Append("installExtension"); + // Helpers the person's assistant wrote: loaded, switched, held to a Space, removed. + capabilities.Append("kourHelpers"); + capabilities.Append("siteSignals"); + capabilities.Append("focusPage"); + capabilities.Append("mailBody"); + capabilities.Append("bookBody"); + capabilities.Append("privateWindows"); + return base::WriteJson(base::DictValue().Set("pages", std::move(pages)) + .Set("unbound", std::move(unbound)) + .Set("extensionsRevision", extensions_.revision()) + .Set("files", std::move(files)) + .Set("downloads", kour::Downloads(browser_->GetProfile())) + .Set("arrivals", std::move(arrivals)) + .Set("profile", base::NumberToString(reinterpret_cast(browser_->GetProfile()))) + // (an off-the-record window: its shell records nothing, P16) + .Set("private", browser_->GetProfile()->IsOffTheRecord()) + .Set("capabilities", std::move(capabilities))).value_or("{}"); + } + + // A script the Agent runs in a page, in Kour's isolated world: the page's + // own scripts cannot see or change it. Chromium answers later; the shell + // asks for the result by its token. + // + // The world is Chrome's internal one: the page cannot reach it, and every + // id outside Chrome's own is an extension's (adding one would renumber + // extension worlds in a header much of Chrome includes). + std::string Evaluate(content::WebContents* contents, const std::string& script, bool body = false) { + if (script.size() > 262144) return R"({"error":"invalid_script"})"; + // Web pages only, and a book's chapter ([body], checked by its caller): + // never the browser's own pages or an extension's. + if (!body && !contents->GetPrimaryMainFrame()->GetLastCommittedURL().SchemeIsHTTPOrHTTPS()) { + return R"({"error":"page_not_scriptable"})"; + } + // A result nobody asked for within a while (the shell gave up, the + // page went away) is forgotten. + const base::TimeTicks now = base::TimeTicks::Now(); + std::erase_if(evaluations_, [&](const auto& entry) { + return now - entry.second.started > base::Seconds(30); + }); + if (evaluations_.size() >= 32) return R"({"error":"too_many_scripts"})"; + const int token = ++next_evaluation_; + evaluations_[token] = {now, false, std::nullopt}; + contents->GetPrimaryMainFrame()->ExecuteJavaScriptInIsolatedWorld( + base::UTF8ToUTF16(script), + base::BindOnce(&KourFlutterPanel::Evaluated, weak_factory_.GetWeakPtr(), token), + ISOLATED_WORLD_ID_CHROME_INTERNAL); + return base::WriteJson(base::DictValue().Set("token", token)).value_or("{}"); + } + void Evaluated(int token, base::Value value) { + auto found = evaluations_.find(token); + if (found == evaluations_.end()) return; + found->second.done = true; + if (value.is_string()) found->second.value = value.GetString(); + // The shell waits for this rather than asking again and again. + SendPageEvent(base::DictValue().Set("kind", "evaluated").Set("token", token)); + } + + // Page events to the shell (KourPanelPageEvent): bells, menu choices, + // scripts' answers. + void SendPageEvent(const base::DictValue& event) { + if (!panel_) return; + const std::string json = base::WriteJson(event).value_or("{}"); + Module().page_event(panel_.get(), json.c_str()); + } + + // The id the shell knows `contents` by, or none. + std::string PageIdOf(content::WebContents* contents) const { + for (const auto& [id, handle] : pages_) { + if (Page(id) == contents) return id; + } + return std::string(); + } + + // Kour's items in a page's right-click menu, as the shell last said them. + std::vector MenuItemsFor(content::WebContents* contents) const { + if (PageIdOf(contents).empty()) return {}; + return page_menu_items_; + } + + void MenuChosen(content::WebContents* contents, const std::string& item, const std::u16string& text) { + const std::string page = PageIdOf(contents); + if (page.empty()) return; + SendPageEvent(base::DictValue().Set("pageId", page).Set("kind", "menu").Set("item", item) + .Set("text", base::UTF16ToUTF8(text.substr(0, 4096)))); + } + + + // The page as Chromium's own serializer archives it (MHTML, its parts as + // text): what a web clip's snapshot is made from. It has what a script in + // the page cannot read: fonts, and pictures of other sites. Web pages + // only, as Evaluate. The answer comes later: the shell asks + // `archiveResult` for it by its token, and is given the file and the + // address that was archived. The archive never crosses this thread (it + // may be tens of megabytes, and the shell shares the thread): the shell + // reads the file itself, off it, and removes it. + // + // The file is the page as the person sees it, signed in or not. It is + // written in a directory of Kour's own in the profile, emptied when the + // browser starts, and removed when the panel goes, when the page goes or + // moves on, and when the serializer has not answered in a while. + std::string Archive(content::WebContents* contents) { + auto* frame = contents->GetPrimaryMainFrame(); + if (!frame || !frame->IsRenderFrameLive()) return R"({"error":"page_not_ready"})"; + if (!frame->GetLastCommittedURL().SchemeIsHTTPOrHTTPS()) { + return R"({"error":"page_not_scriptable"})"; + } + // A private window leaves nothing on disk, and its profile's directory + // is the ordinary one's. + if (browser_->GetProfile()->IsOffTheRecord()) { + return R"({"error":"private_window"})"; + } + ForgetArchives(); + // One at a time for a page. + for (const auto& [ticket, page] : archive_pages_) { + if (page == contents) return R"({"error":"archive_under_way"})"; + } + if (archives_.size() >= 4) return R"({"error":"too_many_archives"})"; + const int ticket = ++next_archive_; + archives_[ticket].started = base::TimeTicks::Now(); + archive_pages_[ticket] = contents; + // The file is named off this thread, then written by the serializer. + ArchiveFiles()->PostTaskAndReplyWithResult( + FROM_HERE, + base::BindOnce([](base::FilePath directory) { + base::FilePath path; + return base::CreateDirectory(directory) && + base::CreateTemporaryFileInDir(directory, &path) + ? path + : base::FilePath(); + }, ArchiveDirectory(browser_->GetProfile()->GetPath())), + base::BindOnce(&KourFlutterPanel::ArchiveInto, weak_factory_.GetWeakPtr(), + ticket, contents->GetWeakPtr())); + // One the shell never collects is not left for the next asking. + base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask( + FROM_HERE, + base::BindOnce(&KourFlutterPanel::ForgetArchives, weak_factory_.GetWeakPtr()), + kArchiveForgotten + base::Seconds(1)); + return base::WriteJson(base::DictValue().Set("token", ticket)).value_or("{}"); + } + + // How long the serializer is waited for, and how long an answer is kept + // for the shell (which stops asking a little after the first). + static constexpr base::TimeDelta kArchiveOverdue = base::Seconds(20); + static constexpr base::TimeDelta kArchiveForgotten = base::Seconds(30); + + static base::FilePath ArchiveDirectory(const base::FilePath& profile) { + return profile.AppendASCII("KourArchives"); + } + + // Where archives' files are named, and where what an earlier run left + // is removed: one after the other, so that the removing is always done + // before the first file of this run is named (done apart, it could take + // away a file a page was just written to). + static scoped_refptr ArchiveFiles() { + static base::NoDestructor> runner( + base::ThreadPool::CreateSequencedTaskRunner( + {base::MayBlock(), base::TaskPriority::USER_VISIBLE})); + return *runner; + } + + // What an earlier run left (it crashed, or quit while a page was being + // written): removed once for each profile, when its first window of this + // run opens. Removed in the task itself: the callback base has for this + // tries again later on Windows, apart from this queue, and would then + // take away a file of this run. + static void SweepArchives(const base::FilePath& profile) { + static base::NoDestructor> swept; + if (!swept->insert(profile).second) return; + ArchiveFiles()->PostTask( + FROM_HERE, base::BindOnce([](base::FilePath directory) { + base::DeletePathRecursively(directory); + }, ArchiveDirectory(profile))); + } + + // Removes an archive's file, also while the browser is quitting. + static void RemoveArchive(const base::FilePath& path) { + if (path.empty()) return; + base::ThreadPool::PostTask( + FROM_HERE, + {base::MayBlock(), base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, + base::GetDeleteFileCallback(path)); + } + + // Entries nobody collected in a while, and those whose page never + // answered. + void ForgetArchives() { + const base::TimeTicks now = base::TimeTicks::Now(); + std::erase_if(archives_, [&](const auto& entry) { + const bool old = now - entry.second.started > kArchiveForgotten; + if (old) { + archive_pages_.erase(entry.first); + RemoveArchive(entry.second.path); + } + return old; + }); + } + + // Ends [ticket] without an archive. + void FailArchive(int ticket) { + archive_pages_.erase(ticket); + if (auto found = archives_.find(ticket); found != archives_.end()) { + found->second.done = true; + found->second.ok = false; + found->second.path.clear(); + } + } + + // The address of the web page [contents] shows now, or none: it is asked + // again at each step, as the page may have moved on (to one of the + // browser's own, or a file) since the step before. + static std::string WebAddress(content::WebContents* contents) { + auto* frame = contents ? contents->GetPrimaryMainFrame() : nullptr; + if (!frame || !frame->IsRenderFrameLive()) return std::string(); + const GURL& url = frame->GetLastCommittedURL(); + return url.SchemeIsHTTPOrHTTPS() ? url.spec() : std::string(); + } + + // (A static step: it runs, and removes the file, with the panel gone.) + static void ArchiveInto(base::WeakPtr panel, int ticket, + base::WeakPtr contents, + base::FilePath path) { + const bool wanted = panel && panel->archives_.contains(ticket) && + !panel->archives_[ticket].done; + const std::string address = wanted ? WebAddress(contents.get()) : std::string(); + if (address.empty() || path.empty()) { + if (panel) panel->FailArchive(ticket); + RemoveArchive(path); + return; + } + panel->archives_[ticket].path = path; + panel->archives_[ticket].url = address; + content::MHTMLGenerationParams params(path); + // Text parts (quoted-printable, base64): the archive is read as text. + params.use_binary_encoding = false; + contents->GenerateMHTML( + params, base::BindOnce(&KourFlutterPanel::Archived, panel, ticket, contents, path)); + // A page that never answers (a frame of it hung): given up on, and its + // file removed, after a while. The shell has the script's reading of + // the page meanwhile and waits for this one. + base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask( + FROM_HERE, + base::BindOnce(&KourFlutterPanel::ArchiveOverdue, panel, ticket, path), + kArchiveOverdue); + } + + static void ArchiveOverdue(base::WeakPtr panel, int ticket, + base::FilePath path) { + // Gone with its panel, answered, or collected meanwhile: seen to. + if (!panel || !panel->archive_pages_.contains(ticket)) return; + panel->FailArchive(ticket); + RemoveArchive(path); + } + + static void Archived(base::WeakPtr panel, int ticket, + base::WeakPtr contents, + base::FilePath path, int64_t size) { + // Kept only when it is still wanted, was written, is no larger than + // 64 MiB (a page past that is not kept as a snapshot), and the page is + // still the web page it was when the writing began. + const bool wanted = panel && panel->archive_pages_.erase(ticket) > 0 && + panel->archives_.contains(ticket) && + !panel->archives_[ticket].done; + // (A fragment that changed meanwhile is the same page.) + if (!wanted || size <= 0 || size > (int64_t{64} << 20) || + GURL(WebAddress(contents.get())).GetWithoutRef() != + GURL(panel->archives_[ticket].url).GetWithoutRef()) { + if (panel) panel->FailArchive(ticket); + RemoveArchive(path); + return; + } + panel->archives_[ticket].done = true; + panel->archives_[ticket].ok = true; + } + + std::string ArchiveResult(const base::DictValue& args) { + ForgetArchives(); + const auto ticket = args.FindInt("token"); + auto found = ticket ? archives_.find(*ticket) : archives_.end(); + if (found == archives_.end()) return R"({"error":"unknown_token"})"; + if (!found->second.done) return R"({"pending":true})"; + if (!found->second.ok) { + archives_.erase(found); + return R"({"error":"archive_failed"})"; + } + // The file is the shell's from here: it reads it and removes it. + base::DictValue answer; + answer.Set("path", found->second.path.AsUTF8Unsafe()); + answer.Set("url", found->second.url); + archives_.erase(found); + return base::WriteJson(answer).value_or("{}"); + } + + // The icon the browser keeps for a web address, as PNG: from its own + // store of the icons of pages it has shown, so nothing is fetched and no + // other party hears of the address. It answers later; the shell asks + // `pageIconResult` for the picture by its token. + std::string PageIcon(const base::DictValue& args) { + const auto* url = args.FindString("url"); + if (!url || url->size() > 16384) return R"({"error":"invalid_url"})"; + const GURL address(*url); + if (!address.is_valid() || !address.SchemeIsHTTPOrHTTPS()) return R"({"error":"invalid_url"})"; + const base::TimeTicks now = base::TimeTicks::Now(); + std::erase_if(icons_, [&](const auto& entry) { + return now - entry.second.started > base::Seconds(30); + }); + if (icons_.size() >= 64) return R"({"error":"too_many_icons"})"; + auto* service = FaviconServiceFactory::GetForProfile( + browser_->GetProfile(), ServiceAccessType::EXPLICIT_ACCESS); + if (!service) return R"({"none":true})"; + const int token = ++next_icon_; + icons_[token] = {now, false, std::nullopt}; + // Twice a sidebar row's 16 points, for a dense display; the page's own + // icon, else any its host has. + service->GetRawFaviconForPageURL( + address, {favicon_base::IconType::kFavicon}, 32, true, + base::BindOnce(&KourFlutterPanel::PageIconFound, weak_factory_.GetWeakPtr(), token), + &icon_tasks_); + return base::WriteJson(base::DictValue().Set("token", token)).value_or("{}"); + } + + void PageIconFound(int token, const favicon_base::FaviconRawBitmapResult& result) { + auto found = icons_.find(token); + if (found == icons_.end()) return; + found->second.done = true; + // An icon is a few kilobytes; one that is not is left out. + if (result.is_valid() && result.bitmap_data->size() <= 262144) { + found->second.value = base::Base64Encode(base::span(*result.bitmap_data)); + } + } + + std::string PageIconResult(const base::DictValue& args) { + const auto token = args.FindInt("token"); + auto found = token ? icons_.find(*token) : icons_.end(); + if (found == icons_.end()) return R"({"error":"unknown_token"})"; + if (!found->second.done) return R"({"pending":true})"; + std::optional png = std::move(found->second.value); + icons_.erase(found); + if (!png) return R"({"none":true})"; + return base::WriteJson(base::DictValue().Set("png", std::move(*png))).value_or("{}"); + } + + std::string Command(std::string_view method, std::string_view arguments) { + auto args = base::JSONReader::ReadDict(arguments, base::JSON_PARSE_RFC); + if (!args) return R"({"error":"invalid_arguments"})"; + auto* model = browser_->GetTabStripModel(); + // The shell hands the browser the core's entry points, so the assistant's browser tool drives the pages itself. + if (method == "registerBrowserHost") return kour::BrowserHostExport::Get().Register(*args); + // Whether a window's close is part of the application quitting or the + // window alone closing: what the window's saves are told (`closeWindow + // {quit}`). The core closes only as the application ends (`quit` on + // kour/windows), never for a window. + // A new window, as the person's ⌘N would open one (never a private one, whatever window asks): the application + // asks it for "Move to new window" and to open again, as it starts, the windows it had + // (docs/specs/2026-10-25-ux-sidebar-sync.md, rule 12). + if (method == "newWindow") { + chrome::NewEmptyWindow(browser_->GetProfile()->GetOriginalProfile()); + return R"({"ok":true})"; + } + if (method == "closeReason") { + return browser_shutdown::IsTryingToQuit() ? R"({"quit":true})" : R"({"quit":false})"; + } + if (method == "enableAccessibility") { + if (!accessibility_requested_) { + accessibility_requested_ = true; + State(); + } + return R"({"enabled":true})"; + } + // Extensions' toolbar actions, for the page Flutter shows. + if (method.starts_with("extensionAction")) { + content::WebContents* page = nullptr; + if (const auto* page_id = args->FindString("pageId"); ValidId(page_id)) { + page = Page(*page_id); + } + if (!page) page = model->GetActiveWebContents(); + // An action acts on the active tab: make it the page that ran it. + if (method == "extensionActionRun" && page) { + model->ActivateTabAt(model->GetIndexOfWebContents(page)); + } + if (auto result = extensions_.Command(method, *args, page, GetColorProvider())) { + std::string json; + base::JSONWriter::Write(*result, &json); + return json; + } + } + // Under what dims the window a page takes no drop and is not read out + // (MultiContentsView::SetKourWebContents). The bridge keeps the rest of + // what `windowOverlays` says to itself, and sends this as it changes. + if (method == "windowOverlays") { + const bool modal = args->FindBool("modal").value_or(false); + if (modal != modal_) { + modal_ = modal; + if (parent()) parent()->InvalidateLayout(); + } + return "{}"; + } + if (auto result = browser_data_.Command(method, *args)) { + std::string json; + base::JSONWriter::Write(*result, &json); + return json; + } + if (method == "browserState") return State(); + if (method == "webViewports") { + std::map next; + base::ListValue result; + std::map colors; + if (const char* error = ReadPanes(*args, &next, &result, &colors)) return error; + const auto backdrop = kour::popup::TellBackdrop(kour::ParseColor(args->FindString("backdrop"))); + if (next != viewports_ || backdrop != backdrop_ || colors != colors_) { + viewports_ = std::move(next); + backdrop_ = backdrop; + colors_ = std::move(colors); + if (parent()) parent()->InvalidateLayout(); + } + return base::WriteJson(base::DictValue().Set("viewports", std::move(result))).value_or("{}"); + } + // One change of what the window shows, whole: where each page is, which + // is the active one, and the layout, made before this answers. The shell + // then asks `pagesPresented` whether the pages it brought in have drawn. + if (method == "showPages") { + if (export_id_ >= 0 && GetWidget() && GetWidget()->IsActive()) kour::BrowserHostExport::Get().Foreground(export_id_); + std::map next; + base::ListValue result; + std::map colors; + if (const char* error = ReadPanes(*args, &next, &result, &colors)) return error; + // Pages the change takes away stay where they are, over the ones that + // take their place, until those have drawn (kour::PageSwitch). + std::vector held = page_switch_.Hold( + args->FindList("hold"), next, viewports_, + base::BindRepeating(&KourFlutterPanel::Surface, + base::Unretained(this))); + std::vector incoming; + for (const auto& [id, rect] : next) { + if (!viewports_.contains(id)) incoming.push_back(Surface(id)); + } + viewports_ = std::move(next); + backdrop_ = kour::popup::TellBackdrop(kour::ParseColor(args->FindString("backdrop"))); + colors_ = std::move(colors); + if (const auto* active = args->FindString("active"); ValidId(active)) { + auto* page = Page(*active); + if (page) model->ActivateTabAt(model->GetIndexOfWebContents(page)); + } + // A change that brings no page in while the last one's are still + // awaited is that one going on, not another. + const int change = args->FindInt("switch").value_or(0); + const bool goes_on = + incoming.empty() && page_switch_.Continue(change, held); + if (!goes_on) { + page_switch_.Begin(change, std::move(held), + args->FindDouble("started").value_or(0)); + } + LayoutNow(); + if (!goes_on) page_switch_.Await(incoming); + auto state = base::JSONReader::ReadDict(State(), base::JSON_PARSE_RFC) + .value_or(base::DictValue()); + state.Set("viewports", std::move(result)); + state.Set("held", !page_switch_.held().empty()); + return base::WriteJson(state).value_or("{}"); + } + if (method == "pagesPresented") { + return base::WriteJson(page_switch_.Result(args->FindInt("switch").value_or(0))) + .value_or("{}"); + } + // A page the person is about to ask for (the pointer is on its row) is + // made ready at the size it will have. + if (method == "preparePages") { + std::map next; + base::ListValue result; + if (const char* error = ReadPanes(*args, &next, &result)) return error; + for (const auto& [id, rect] : next) { + if (viewports_.contains(id)) continue; + page_switch_.Prepare(Page(id), rect.size()); + break; + } + return "{}"; + } + // Signing in with Apple or Google, and connecting another service, + // happen in Kour, the browser: a window of its own over this one, with + // this profile's cookies and the page's address shown. The provider sees + // a browser, not an embedded view, and an account already signed in here + // is one click. The round trip ends at an address in the app's own + // scheme, which is not opened: it is the answer, and the window closes. + if (method == "signInWindow") { + return kour::SignInWindow::Call(browser_, GetWidget(), sign_in_, *args); + } + if (method == "evaluateResult") { + const auto token = args->FindInt("token"); + auto found = token ? evaluations_.find(*token) : evaluations_.end(); + if (found == evaluations_.end()) return R"({"error":"unknown_token"})"; + if (!found->second.done) return R"({"pending":true})"; + if (!found->second.value) { + evaluations_.erase(found); + return R"({"error":"script_failed"})"; + } + std::string value = std::move(*found->second.value); + evaluations_.erase(found); + return base::WriteJson(base::DictValue().Set("value", value)).value_or("{}"); + } + if (method == "archiveResult") return ArchiveResult(*args); + if (method == "forgetAddresses") { + const auto* urls = args->FindList("urls"); + if (!urls || !kour::ForgetAddresses(browser_->GetProfile(), *urls)) { + return R"({"error":"invalid_urls"})"; + } + return State(); + } + if (method == "forgetSpace") { + const auto* space = args->FindString("space"); + if (!space || !kour::ForgetSpace(browser_->GetProfile(), *space)) { + return R"({"error":"invalid_space"})"; + } + return State(); + } + if (method == "siteSignals" || method == "siteSignalsResult") { + return kour::SiteSignalsCommand(browser_->GetProfile(), method, *args); + } + if (method == "pageIcon") return PageIcon(*args); + if (method == "pageIconResult") return PageIconResult(*args); + if (method == "captureResult") return page_input_.CaptureResult(*args); + if (method == "contentResult" || method == "toolResult" || method == "evaluateFrameResult" || + method == "settleResult") { + return page_agent_.Result(*args); + } + if (method == "videoFrameResult") return video_frames_.Result(*args); + if (method == "closePages") { + const auto* ids = args->FindList("pageIds"); + if (!ids || ids->size() > 300) return R"({"error":"invalid_page_ids"})"; + for (const auto& value : *ids) { + const auto* page = value.GetIfString(); + if (!page || !ValidId(page)) continue; + // The window's last tab stays: closing it would close the window. + // What it plays ends with the page all the same. A page that stays + // open (beforeunload) keeps its binding; State() forgets those whose + // tabs are gone. + auto* contents = Page(*page); + if (!contents) continue; + kour::EndPageMedia(contents); + if (model->count() <= 1) continue; + model->CloseWebContentsAt(model->GetIndexOfWebContents(contents), + TabCloseTypes::CLOSE_NONE); + } + return State(); + } + if (method == "downloadPrefs") return kour::DownloadPrefsCommand(browser_->GetProfile(), *args); + if (method == "autoPictureInPicture") { + return kour::AutoPictureInPictureCommand(browser_->GetProfile(), *args); + } + if (method == "spaceDownloadFolders") return kour::SpaceDownloadFoldersCommand(browser_->GetProfile(), *args); + if (method == "printResult") return prints_.Result(*args); + if (method == "pageMenu") { + page_menu_items_ = kour::PageMenuItemsOf(*args); + return "{}"; + } + if (method == "downloadAction") { + const auto* download = args->FindString("id"); + const auto* action = args->FindString("action"); + if (!download || !action) return R"({"error":"invalid_download"})"; + kour::DownloadAction(browser_->GetProfile(), *download, *action); + return State(); + } + // Links from other applications: the shell says it takes them, and + // says when it has placed some. + if (method == "externalLinks") { + kour::TakeExternalLinks(browser_, args->FindBool("take").value_or(false)); + return State(); + } + if (method == "ackArrivals") { + const auto* ids = args->FindList("ids"); + if (!ids || ids->size() > 100) return R"({"error":"invalid_ids"})"; + std::vector taken; + for (const auto& value : *ids) { + if (const auto* link = value.GetIfString()) taken.push_back(*link); + } + // What was still waiting, and so is the shell's alone to open. + base::ListValue acknowledged; + for (const auto& link : kour::AckExternalLinks(taken)) { + acknowledged.Append(link); + } + return base::WriteJson( + base::DictValue().Set("taken", std::move(acknowledged))) + .value_or("{}"); + } + if (method == "ackFiles") { + const auto* ids = args->FindList("ids"); + if (!ids || ids->size() > 100) return R"({"error":"invalid_ids"})"; + std::vector taken; + for (const auto& value : *ids) { + if (const auto* file = value.GetIfString()) taken.push_back(*file); + } + kour::AckHandedFiles(taken); + return State(); + } + // A private window (P16): Chromium's off-the-record profile in a window + // of its own, at an address when one is given; its shell records + // nothing. Every private window shares the one off-the-record profile, + // which Chromium lets go of when its last window closes. + if (method == "openPrivateWindow") { + const std::string* url = args->FindString("url"); + GURL target = url ? GURL(*url) : GURL(url::kAboutBlankURL); + if (url && (!target.is_valid() || !target.SchemeIsHTTPOrHTTPS())) return R"({"error":"invalid_url"})"; + Profile* original = browser_->GetProfile()->GetOriginalProfile(); + NavigateParams params(original->GetPrimaryOTRProfile(/*create_if_needed=*/true), target, + ui::PAGE_TRANSITION_TYPED); + params.disposition = WindowOpenDisposition::OFF_THE_RECORD; + params.window_action = NavigateParams::WindowAction::kShowWindow; + Navigate(¶ms); + return R"({"ok":true})"; + } + // This window brought forward (an open document it shows, asked for + // from another window: P16). + if (method == "raiseWindow") { + browser_->GetWindow()->Activate(); + return R"({"ok":true})"; + } + // Kour's own script in a book's chapter (R23): the body's id, never a + // page's; only a book body showing its chapter. + if (method == "evaluatePage") { + const auto* body_id = args->FindString("pageId"); + if (body_id && mail_bodies_.Get(*body_id)) { + content::WebContents* body = mail_bodies_.Scriptable(*body_id); + if (!body) return R"({"error":"page_not_scriptable"})"; + const auto* script = args->FindString("script"); + if (!script) return R"({"error":"invalid_script"})"; + return Evaluate(body, *script, /*body=*/true); + } + } + // A mail message's body (kour_mail_body.h): placed as a page is, and + // nothing else of a page's; its own id, never a page's. + if (auto answer = mail_bodies_.Command( + method, *args, + [this](const std::string& id) { return Page(id) != nullptr; }, + [this](const std::string& id) { + if (viewports_.erase(id)) LayoutNow(); + })) { + return *answer; + } + const auto* id = args->FindString("pageId"); + if (!ValidId(id)) return R"({"error":"invalid_page_id"})"; + auto* contents = Page(*id); + // A page another window holds: moved here as it is (its history, its + // state, nothing reloaded), or that window brought forward. + if (method == "adoptPage" || method == "raisePage") { + if (contents) return State(); + auto* holder = Holder(*id); + if (!holder) return R"({"error":"page_not_open"})"; + if (method == "raisePage") { + holder->browser_->GetWindow()->Activate(); + return R"({"ok":true})"; + } + // A window closing (a page's "Leave site?" still open, say): the page + // stays with it, or the answer would go to this window. + if (holder->close_pending_ || UnloadController::From(holder->browser_)->is_attempting_to_close_browser()) { + return R"({"error":"page_closing"})"; + } + auto* from = holder->browser_->GetTabStripModel(); + const int index = holder->Index(holder->pages_.at(*id)); + if (index < 0) return R"({"error":"page_not_open"})"; + // It leaves every view of that window first: a container there that + // still showed it would keep watching it from two windows. + if (auto* page = holder->Page(*id); page && holder->contents_view_) { + holder->contents_view_->ReleaseKourContainer(page); + } + holder->viewports_.erase(*id); + // A window whose last tab leaves closes: that window stays, with a + // blank tab of its own (as a new window has), until it is closed. + if (from->count() == 1) chrome::AddAndReturnTabAt(holder->browser_, GURL(url::kAboutBlankURL), -1, false); + std::unique_ptr tab = from->DetachTabAtForInsertion(index); + if (!tab) return R"({"error":"page_not_open"})"; + holder->pages_.erase(*id); + holder->LayoutNow(); + auto* to = browser_->GetTabStripModel(); + const int at = to->InsertDetachedTabAt(to->count(), std::move(tab), AddTabTypes::ADD_NONE); + pages_[*id] = to->GetTabAtIndex(at)->GetHandle().raw_value(); + return State(); + } + if (method == "openPage") { + // Opening an existing identity must preserve its history and navigation. + if (contents) return State(); + // One page, one window: one another window holds is moved or shown + // there (adoptPage, raisePage), never opened twice under one identity. + if (Holder(*id)) return R"({"error":"page_elsewhere"})"; + if (mail_bodies_.Get(*id)) return R"({"error":"invalid_page_id"})"; + const auto* url = args->FindString("url"); + if (!ValidURL(url)) return R"({"error":"invalid_url"})"; + int index = -1; + if (auto native_id = args->FindInt("nativeId")) { + index = Index(*native_id); + if (index < 0) return R"({"error":"native_page_gone"})"; + for (const auto& [other_id, handle] : pages_) { + if (handle == *native_id) return R"({"error":"native_page_bound"})"; + } + } else { + // A page the Agent opens is the browser's to show, documents too. + if (args->FindBool("agent").value_or(false)) kour::LeaveToBrowser(browser_->GetProfile(), GURL(*url)); + // A page of a Space uses that Space's web data, for good. + if (const auto* space = args->FindString("space"); space && !space->empty()) { + if (!kour::ValidSpace(*space)) return R"({"error":"invalid_space"})"; + contents = kour::AddTabInSpace(browser_, GURL(*url), *space); + } else { + contents = chrome::AddAndReturnTabAt(browser_, GURL(*url), -1, false); + } + if (!contents) return R"({"error":"page_creation_failed"})"; + index = model->GetIndexOfWebContents(contents); + } + pages_[*id] = model->GetTabAtIndex(index)->GetHandle().raw_value(); + return State(); + } + if (method == "hasPage") return contents ? R"({"open":true})" : R"({"open":false})"; + if (!contents) return R"({"error":"page_not_open"})"; + if (method == "askingPage") return Asking(contents); + // The page takes the keyboard (Kour's find bar closed over it). + if (method == "focusPage") { + contents->Focus(); + return R"({"ok":true})"; + } + if (method == "findPage") return KourPageInput::Find(contents, *args); + if (method == "findResultPage") return KourPageInput::FindResult(contents); + if (method == "stopFindPage") return KourPageInput::StopFind(contents, *args); + if (method == "activatePage") { + if (export_id_ >= 0 && GetWidget() && GetWidget()->IsActive()) kour::BrowserHostExport::Get().Foreground(export_id_); + model->ActivateTabAt(model->GetIndexOfWebContents(contents)); + } else if (method == "navigatePage") { + const auto* value = args->FindString("url"); + if (!ValidURL(value)) return R"({"error":"invalid_url"})"; + if (args->FindBool("agent").value_or(false)) kour::LeaveToBrowser(browser_->GetProfile(), GURL(*value)); + content::NavigationController::LoadURLParams params{GURL(*value)}; + params.transition_type = ui::PAGE_TRANSITION_TYPED; + contents->GetController().LoadURLWithParams(params); + } else if (method == "backPage") { + if (contents->GetController().CanGoBack()) contents->GetController().GoBack(); + } else if (method == "forwardPage") { + if (contents->GetController().CanGoForward()) contents->GetController().GoForward(); + } else if (method == "evaluatePage") { + const auto* script = args->FindString("script"); + if (!script) return R"({"error":"invalid_script"})"; + return Evaluate(contents, *script); + } else if (method == "archivePage") { + return Archive(contents); + } else if (method == "printPage") { + return prints_.Print(contents, browser_->GetProfile()); + } else if (method == "pageBell") { + return bells_.Bell(contents, *args->FindString("pageId")); + } else if (method == "inputPage") { + return page_input_.Input(contents, *args); + } else if (method == "capturePage") { + return page_input_.Capture(contents, *args); + } else if (method == "contentPage" || method == "toolPage" || method == "evaluateFrame" || + method == "settlePage") { + // the page is laid out and takes input while the Agent reads it or uses its tools + if (!page_input_.KeepAwake(contents)) return R"({"error":"page_not_shown"})"; + if (method == "contentPage") return page_agent_.Content(contents); + if (method == "toolPage") return page_agent_.Tool(contents, *args); + if (method == "settlePage") return page_agent_.Settle(contents); + return page_agent_.EvaluateFrame(contents, *args); + } else if (method == "mediaControl") { + return kour::MediaControl(contents, *args); + } else if (method == "captureVideoFrame") { + return video_frames_.Capture(contents, *args); + } else if (method == "reloadPage") { + // `bypassCache`: ⇧⌘R, the page and what it loads fetched again. + contents->GetController().Reload(args->FindBool("bypassCache").value_or(false) + ? content::ReloadType::BYPASSING_CACHE + : content::ReloadType::NORMAL, + true); + } else { + return R"({"error":"unknown_command"})"; + } + return State(); + } + + // The pages `panes` places and where, as `webViewports` and `showPages` + // take them: `result` is what was accepted, in this view's coordinates. + // The error to answer with, or null. + const char* ReadPanes(const base::DictValue& args, + std::map* next, + base::ListValue* result, + std::map* colors = nullptr) const { + const auto* panes = args.FindList("panes"); + if (!panes || panes->size() > 300) return R"({"error":"invalid_viewports"})"; + for (const auto& value : *panes) { + const auto* pane = value.GetIfDict(); + if (!pane) return R"({"error":"invalid_viewports"})"; + const auto* id = pane->FindString("pageId"); + if (!ValidId(id) || !Surface(*id) || next->contains(*id)) + return R"({"error":"invalid_viewport_page"})"; + bool valid = true; + auto number = [&](const char* key) { + // JSON integer and floating point inputs share the same coordinate API. + const auto* number = pane->Find(key); + double coordinate = number && number->is_int() ? number->GetInt() + : number && number->is_double() ? number->GetDouble() : -1; + if (!std::isfinite(coordinate) || coordinate < 0 || coordinate > 100000) { + valid = false; + return 0; + } + return static_cast(std::round(coordinate)); + }; + gfx::Rect bounds(number("x"), number("y"), number("width"), number("height")); + if (!valid) return R"({"error":"invalid_viewport_geometry"})"; + bounds.Intersect(GetLocalBounds()); + for (const auto& [other, rect] : *next) { + if (rect.Intersects(bounds)) return R"({"error":"overlapping_viewports"})"; + } + next->emplace(*id, bounds); + // The colour the shell knows the page by (`color`): under the page + // until it has drawn. + if (colors) { + if (const auto color = kour::ParseColor(pane->FindString("color"))) { + colors->emplace(*id, *color); + } + } + result->Append(base::DictValue().Set("pageId", *id).Set("x", bounds.x()) + .Set("y", bounds.y()).Set("width", bounds.width()).Set("height", bounds.height())); + } + return nullptr; + } + + // Lays the pages out now, not when the window next lays itself out: what + // asked has the answer when the pages are where it says. + // What `page` has under it where it has not drawn. + std::optional Background(const std::string& id, + content::WebContents* page) const { + const auto known = colors_.find(id); + return kour::PageBackground( + page, known == colors_.end() ? std::nullopt : std::optional(known->second), + backdrop_); + } + + void LayoutNow() { + if (!contents_view_) { + if (parent()) parent()->InvalidateLayout(); + return; + } + LayoutWebContents(contents_view_); + contents_view_->DeprecatedLayoutImmediately(); + } + + static const char* HandleCommand(void* context, const char* method, + const char* arguments) { + auto* self = static_cast(context); + self->response_ = self->Command(method, arguments); + return self->response_.c_str(); + } + raw_ptr browser_; + KourBrowserData browser_data_; + KourExtensionActions extensions_; + // Mail messages' bodies, by the id the shell gave each. + kour::MailBodies mail_bodies_; + bool accessibility_requested_ = false; + std::map> accessibility_modes_; + std::map pages_; + std::map viewports_; + // The view the pages are laid out in, once the window has laid them out. + // It outlives this one: BrowserView takes the shell out first. + raw_ptr contents_view_ = nullptr; + kour::PageSwitch page_switch_{base::BindRepeating( + &KourFlutterPanel::LayoutNow, base::Unretained(this))}; + // The shell's own colour where the pages are (`backdrop`, with the pages' + // places): what a page that has told no colour of its own has under it. + std::optional backdrop_; + // The colour the shell knows each placed page by. + std::map colors_; + // Something of Flutter's dims the whole window (windowOverlays). + bool modal_ = false; + struct Evaluation { + base::TimeTicks started; + bool done = false; + std::optional value; + }; + std::map evaluations_; + int next_evaluation_ = 0; + // Pages being archived for a clip, by ticket (see Archive), and the page + // each is of until its serializer has answered (never dereferenced). + struct ArchiveJob { + base::TimeTicks started; + bool done = false; + bool ok = false; + base::FilePath path; + std::string url; + }; + std::map archives_; + std::map> archive_pages_; + int next_archive_ = 0; + // Icons asked for and not yet collected: PNG as base64 once found. + std::map icons_; + int next_icon_ = 0; + base::CancelableTaskTracker icon_tasks_; + KourPageInput page_input_; + KourPageAgent page_agent_; + kour::KourVideoFrames video_frames_; + kour::KourPagePrints prints_; + std::vector page_menu_items_; + int page_menu_id_ = -1; + kour::KourPageBells bells_{base::BindRepeating( + [](KourFlutterPanel* self, base::DictValue event) { self->SendPageEvent(event); }, + base::Unretained(this))}; + std::string response_; + std::unique_ptr sign_in_; + std::unique_ptr panel_; + bool close_pending_ = false; + bool close_ready_ = false; + // The window was hidden when its close was asked (CanClose). + bool hidden_for_close_ = false; + base::CallbackListSubscription close_cancelled_; + base::OneShotTimer close_watchdog_; + // This window in the browser host (kour_browser_host.h). + // (-1: not the browser host's, a private window) + int export_id_ = -1; + base::WeakPtrFactory weak_factory_{this}; +}; + +BEGIN_METADATA(KourFlutterPanel) +END_METADATA + +} // namespace + +std::unique_ptr CreateKourFlutterPanel(BrowserWindowInterface* browser) { + return std::make_unique(browser); +} + +void LayoutKourWebContents(views::View* shell, MultiContentsView* contents) { + static_cast(shell)->LayoutWebContents(contents); +} + +bool CanCloseKourWindow(views::View* shell, base::OnceClosure retry_close) { + return static_cast(shell)->CanClose(std::move(retry_close)); +} + +bool HandleKourUnhandledKey(views::View* shell, const input::NativeWebKeyboardEvent& event) { + return static_cast(shell)->HandleUnhandledKey(event); +} diff --git a/chrome/browser/ui/views/side_panel/kour_panel_abi.h b/chrome/browser/ui/views/side_panel/kour_panel_abi.h new file mode 100644 index 0000000000..42db32250f --- /dev/null +++ b/chrome/browser/ui/views/side_panel/kour_panel_abi.h @@ -0,0 +1,40 @@ +#ifndef KOUR_PANEL_ABI_H_ +#define KOUR_PANEL_ABI_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +// Browser-process main thread only. The opaque owner holds a window's view +// controller of the application's one engine. Detach the borrowed native view +// before releasing its owner. +// ABI 4 adds asynchronous preparation before destroying a window. +// ABI 5: every window is a view of one engine; a window's close is asked of +// it on its own channel, with whether the application quits (closeReason). +// ABI 6: a key a page left (⌘D, ⌘J) is offered to Kour (KourPanelUnhandledKey). +// ABI 7: what happened in a page, for the window's shell (KourPanelPageEvent). +unsigned KourPanelAbiVersion(void); +// JSON requests stay on the main thread. The result is borrowed until the +// next call to the same callback; the Flutter bridge copies it immediately. +typedef const char* (*KourHostCommand)(void* context, const char* method, + const char* arguments_json); +void* KourCreatePanel(const char* app_framework_path, KourHostCommand command, + void* context); +void* KourPanelNativeView(void* panel); +// A key-down a web page did not handle (an NSEvent*): 1 when it is one of Kour's page-first commands, which the +// window's channel is then given; 0 leaves it to the browser. +int KourPanelUnhandledKey(void* panel, void* ns_event); +// What happened in one of the window's pages, as a JSON object +// ({pageId, kind, ...}: a reading of the page is due, its document changed, a +// script's answer is in, a menu item was chosen): the window's channel is +// given it as `pageEvent`. Borrowed for the call. +void KourPanelPageEvent(void* panel, const char* event_json); +// Called exactly once on the main thread, including cancellation on destruction. +typedef void (*KourCloseReply)(void* context, int allow_close); +void KourPreparePanelClose(void* panel, KourCloseReply reply, void* context); +void KourDestroyPanel(void* panel); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/chrome/browser/ui/views/frame/multi_contents_view.h b/chrome/browser/ui/views/frame/multi_contents_view.h index e39f000c2a..1cad9008cd 100644 --- a/chrome/browser/ui/views/frame/multi_contents_view.h +++ b/chrome/browser/ui/views/frame/multi_contents_view.h @@ -7,16 +7,21 @@ #include #include +#include +#include #include "base/callback_list.h" #include "base/functional/callback_forward.h" #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" +#include "base/memory/weak_ptr.h" #include "chrome/browser/ui/tabs/split_tab_highlight_controller.h" #include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/views/frame/contents_container_view.h" #include "components/prefs/pref_change_registrar.h" #include "components/split_tabs/split_tab_visual_data.h" +#include "content/public/browser/web_contents.h" +#include "third_party/skia/include/core/SkColor.h" #include "ui/base/interaction/element_identifier.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/gfx/geometry/rounded_corners_f.h" @@ -80,6 +85,44 @@ class MultiContentsView ContentsContainerView* GetContentsContainerViewFor( content::WebContents* web_contents) const; + // Kour owns the complete pane layout. Contents stay attached to their own + // containers across focus changes; rectangles are in this view's coordinates. + struct KourSurface { + raw_ptr contents; + gfx::Rect bounds; + // A page another has taken the place of, kept over it until that one + // has drawn: nothing shows between the two. + bool held = false; + // What shows where the page has not drawn: its own colour as it last + // was, or the shell's. Chromium's own (the new tab page's) without one. + std::optional background; + }; + // `modal`: something of Kour's dims the whole window. The pages under it + // take no input (a file dropped on one is refused) and are out of the + // accessibility tree until it is gone. + void SetKourWebContents(const std::vector& surfaces, + content::WebContents* active, + bool modal = false); + void SetKourActiveWebContents(content::WebContents* active); + // Kour: `contents` is leaving this window for another (adoptPage). The + // containers that still show it let it go, so what watches a container's + // page (Reading mode's immersive overlay, one per page) watches it from one + // window only. The active one is the browser's: it puts the next active + // page there itself as the tab leaves. + void ReleaseKourContainer(content::WebContents* contents); + // Kour: pages that are no tab (a mail message's body, kour_mail_body), each + // in a plain web view of its own beside the window's pages, in the + // rectangle Flutter gives it as it gives theirs. Never in a + // contents container: the browser's own views take whatever is in one for + // a tab's. Under what dims the window (`modal`) they take no input and are + // out of the accessibility tree, as the pages are. + struct KourBody { + raw_ptr contents; + gfx::Rect bounds; + }; + void SetKourBodies(const std::vector& bodies, bool modal); + bool HasKourLayout() const { return kour_layout_; } + // Returns the currently active ContentsWebView. ContentsWebView* GetActiveContentsView() const; @@ -260,9 +303,62 @@ class MultiContentsView const gfx::Rect& available_space, views::ProposedLayout::ChildLayoutList& child_layouts) const; + void RegisterContentsContainer(ContentsContainerView* container); + // Kour: follows a container's docked DevTools (its devtools_web_view). A + // press there chooses the container's page, as a press in the page does + // (OnKourInteraction); DevTools docked while something dims the window is + // held from input as the page is (OnKourDevToolsDocked). + class KourDevToolsWatch; + void OnKourDevToolsDocked(content::WebContents* devtools); + void OnKourDevToolsUndocked(content::WebContents* devtools); + // Holds `contents` from input while something dims the window, once. + void HoldKourInput(content::WebContents* contents); + std::vector> kour_devtools_watches_; + // Whether the last SetKourWebContents had something dim the window. + bool kour_modal_ = false; + size_t EnsureKourContainer(content::WebContents* contents); + bool kour_layout_ = false; + std::vector kour_bounds_; + // The pages shown, and their docked DevTools, kept from input while + // something dims the window. + std::vector, + content::WebContents::ScopedIgnoreInputEvents>> + kour_modal_held_; + // The bodies' web views (SetKourBodies), where each is, and those held + // from input while something dims the window. A view is kept for the next + // body once its own has gone: there are as many as were ever shown at + // once. + std::vector> kour_body_views_; + std::vector kour_body_bounds_; + std::vector, + content::WebContents::ScopedIgnoreInputEvents>> + kour_modal_bodies_; + // Counts the changes of the active page, so that a press which has not yet + // become an activation yields to a change made in between (Flutter's own). + int kour_epoch_ = 0; + // The page the last SetKourActiveWebContents made active, and whether an + // activation of ours is under way (it is not a change to yield to). + base::WeakPtr kour_active_; + bool kour_activating_ = false; + // Per container: the page is only held over the one that took its place + // (SetKourWebContents), where a press is not a choice of page. + std::vector kour_held_; + int GetInactiveIndex() const; void OnWebContentsFocused(views::WebView*); + // Kour: the user pressed a mouse button or touched `view`'s page. A page + // that is not the active one becomes it. Posted, never run inline: input + // can be reported from inside the tab strip's own notifications, which do + // not allow a second change. + void OnKourInteraction(ContentsWebView* view); + // A press in `view`'s page, or in its docked DevTools (`keep_focus`): + // activating a page gives the keyboard back to where it last was in it + // (BrowserView's stored focus), so DevTools takes it again after. + void OnKourPress(ContentsWebView* view, views::View* keep_focus); + void ActivateKourPage(base::WeakPtr contents, + int epoch, + views::View* keep_focus); void OnNtpFooterFocused(views::WebView*); void OnActorOverlayFocused(views::WebView*); void OnReadAnythingOverlayFocused(ContentsContainerView* container, @@ -357,6 +453,8 @@ class MultiContentsView // `BrowserView::MaybeUpdateStoredFocusForWebContents` base::flat_map container_focusable_map_; + + base::WeakPtrFactory kour_weak_factory_{this}; }; #endif // CHROME_BROWSER_UI_VIEWS_FRAME_MULTI_CONTENTS_VIEW_H_ diff --git a/chrome/browser/ui/views/frame/multi_contents_view.cc b/chrome/browser/ui/views/frame/multi_contents_view.cc index a756f076ff..7f599123e6 100644 --- a/chrome/browser/ui/views/frame/multi_contents_view.cc +++ b/chrome/browser/ui/views/frame/multi_contents_view.cc @@ -6,11 +6,16 @@ #include #include +#include +#include "base/auto_reset.h" #include "base/check_deref.h" +#include "base/location.h" +#include "base/task/single_thread_task_runner.h" #include "base/notreached.h" #include "chrome/browser/actor/ui/actor_overlay_web_view.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/devtools/devtools_ui_controller.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser_element_identifiers.h" #include "chrome/browser/ui/color/chrome_color_id.h" @@ -18,10 +23,12 @@ #include "chrome/browser/ui/sad_tab_helper.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/view_ids.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/contents_container_view.h" #include "chrome/browser/ui/views/frame/contents_separator.h" #include "chrome/browser/ui/views/frame/contents_web_view.h" +#include "chrome/browser/ui/views/status_bubble_views.h" #include "chrome/browser/ui/views/frame/custom_floating_corner.h" #include "chrome/browser/ui/views/frame/multi_contents_background_view.h" #include "chrome/browser/ui/views/frame/multi_contents_drop_target_view.h" @@ -40,20 +47,47 @@ #include "components/split_tabs/split_tab_visual_data.h" #include "components/tabs/public/tab_interface.h" #include "content/public/browser/web_contents.h" +#include "content/public/browser/web_contents_observer.h" #include "content/public/common/url_constants.h" +#include "third_party/blink/public/common/input/web_input_event.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/ozone_buildflags.h" #include "ui/compositor/layer.h" #include "ui/gfx/geometry/outsets.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rounded_corners_f.h" +#include "ui/views/controls/webview/webview.h" #include "ui/views/layout/flex_layout_types.h" #include "ui/views/layout/layout_types.h" #include "ui/views/layout/proposed_layout.h" #include "ui/views/view_class_properties.h" +#include "ui/views/view_targeter.h" +#include "ui/views/view_targeter_delegate.h" + +DEFINE_UI_CLASS_PROPERTY_TYPE(views::WebView::ScopedAxDisconnectLock*) namespace { constexpr int kSnapDistance = 15; + +DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(views::WebView::ScopedAxDisconnectLock, + kKourHiddenAccessibility) + +// The Kour container spans the window, but only its visible web panes should +// intercept input. Empty space belongs to the Flutter NativeViewHost behind it. +class KourContentsTargeter : public views::ViewTargeterDelegate { + public: + bool DoesIntersectRect(const views::View* target, + const gfx::Rect& rect) const override { + const auto* contents = static_cast(target); + if (!contents->HasKourLayout()) { + return views::ViewTargeterDelegate::DoesIntersectRect(target, rect); + } + for (const auto& child : contents->children()) { + if (child->GetVisible() && child->bounds().Intersects(rect)) return true; + } + return false; + } +}; } void MultiContentsView::ContentsSeparators::Reset() { @@ -63,6 +97,72 @@ void MultiContentsView::ContentsSeparators::Reset() { corner_separator = nullptr; } +class MultiContentsView::KourDevToolsWatch + : public content::WebContentsObserver { + public: + KourDevToolsWatch( + views::WebView* devtools_web_view, + base::RepeatingClosure pressed, + base::RepeatingCallback docked, + base::RepeatingCallback undocked) + : pressed_(std::move(pressed)), + docked_(std::move(docked)), + undocked_(std::move(undocked)) { + // Attached: DevTools docked (or its view back in the window); detached: + // it goes, before the view takes another. + attached_ = devtools_web_view->AddWebContentsAttachedCallback( + base::BindRepeating(&KourDevToolsWatch::OnAttached, + base::Unretained(this))); + detached_ = devtools_web_view->AddWebContentsDetachedCallback( + base::BindRepeating(&KourDevToolsWatch::OnDetached, + base::Unretained(this))); + Observe(devtools_web_view->web_contents()); + } + + void DidGetUserInteraction(const blink::WebInputEvent& event) override { + if (ContentsWebView::IsKourPress(event)) pressed_.Run(); + } + + private: + void OnAttached(views::WebView* web_view) { + Observe(web_view->web_contents()); + if (web_view->web_contents()) docked_.Run(web_view->web_contents()); + } + void OnDetached(views::WebView* web_view) { + // Undocked (into a window of its own) or closed: what held it here no + // longer does. + if (content::WebContents* devtools = web_contents()) undocked_.Run(devtools); + Observe(nullptr); + } + + base::RepeatingClosure pressed_; + base::RepeatingCallback docked_; + base::RepeatingCallback undocked_; + base::CallbackListSubscription attached_; + base::CallbackListSubscription detached_; +}; + +void MultiContentsView::HoldKourInput(content::WebContents* contents) { + if (std::ranges::none_of(kour_modal_held_, [&](const auto& held) { + return held.first.get() == contents; + })) { + kour_modal_held_.emplace_back(contents->GetWeakPtr(), + contents->IgnoreInputEvents(std::nullopt)); + } +} + +void MultiContentsView::OnKourDevToolsDocked(content::WebContents* devtools) { + // Under what dims the window, as its page is. The next SetKourWebContents + // lets it go with the dimming or with its page. + if (kour_modal_) HoldKourInput(devtools); +} + +void MultiContentsView::OnKourDevToolsUndocked(content::WebContents* devtools) { + std::erase_if(kour_modal_held_, [&](const auto& held) { + return held.first.get() == devtools; + }); +} + MultiContentsView::MultiContentsView( BrowserView* browser_view, std::unique_ptr delegate) @@ -135,40 +235,8 @@ MultiContentsView::MultiContentsView( lens_overlay_view->SetLayoutManager(std::make_unique()); lens_overlay_view_ = AddChildView(std::move(lens_overlay_view)); - for (auto& contents_container_view : contents_container_views_) { - auto& view_map = container_focusable_map_[contents_container_view]; - - auto* contents_view = contents_container_view->contents_view(); - view_map[contents_view->GetClassName()] = contents_view; - - contents_focused_subscriptions_.push_back( - contents_view->AddWebContentsFocusedCallback(base::BindRepeating( - &MultiContentsView::OnWebContentsFocused, base::Unretained(this)))); - - if (auto* footer = contents_container_view->new_tab_footer_view()) { - view_map[footer->GetClassName()] = footer; - contents_focused_subscriptions_.push_back( - footer->AddWebContentsFocusedCallback(base::BindRepeating( - &MultiContentsView::OnNtpFooterFocused, base::Unretained(this)))); - } - - if (auto* actor_overlay = - contents_container_view->actor_overlay_web_view()) { - view_map[actor_overlay->GetClassName()] = actor_overlay; - contents_focused_subscriptions_.push_back( - actor_overlay->AddWebContentsFocusedCallback( - base::BindRepeating(&MultiContentsView::OnActorOverlayFocused, - base::Unretained(this)))); - } - - if (auto* read_anything_overlay = - contents_container_view->read_anything_immersive_overlay_view()) { - view_map[read_anything_overlay->GetClassName()] = read_anything_overlay; - contents_focused_subscriptions_.push_back( - read_anything_overlay->AddWebViewFocusedCallback(base::BindRepeating( - &MultiContentsView::OnReadAnythingOverlayFocused, - base::Unretained(this), contents_container_view))); - } + for (auto& container : contents_container_views_) { + RegisterContentsContainer(container); } is_drag_drop_pref_enabled_ = @@ -182,11 +250,291 @@ MultiContentsView::MultiContentsView( base::Unretained(this))); } +void MultiContentsView::RegisterContentsContainer(ContentsContainerView* container) { + auto& view_map = container_focusable_map_[container]; + + auto* contents_view = container->contents_view(); + view_map[contents_view->GetClassName()] = contents_view; + + contents_focused_subscriptions_.push_back( + contents_view->AddWebContentsFocusedCallback(base::BindRepeating( + &MultiContentsView::OnWebContentsFocused, base::Unretained(this)))); + contents_view->SetKourInteractionCallback(base::BindRepeating( + &MultiContentsView::OnKourInteraction, base::Unretained(this), + base::Unretained(contents_view))); + kour_devtools_watches_.push_back(std::make_unique( + container->devtools_web_view(), + // A press in DevTools chooses its page and leaves the keyboard there. + base::BindRepeating(&MultiContentsView::OnKourPress, + base::Unretained(this), + base::Unretained(contents_view), + base::Unretained(container->devtools_web_view())), + base::BindRepeating(&MultiContentsView::OnKourDevToolsDocked, + base::Unretained(this)), + base::BindRepeating(&MultiContentsView::OnKourDevToolsUndocked, + base::Unretained(this)))); + + if (auto* footer = container->new_tab_footer_view()) { + view_map[footer->GetClassName()] = footer; + contents_focused_subscriptions_.push_back( + footer->AddWebContentsFocusedCallback(base::BindRepeating( + &MultiContentsView::OnNtpFooterFocused, base::Unretained(this)))); + } + + if (auto* actor_overlay = + container->actor_overlay_web_view()) { + view_map[actor_overlay->GetClassName()] = actor_overlay; + contents_focused_subscriptions_.push_back( + actor_overlay->AddWebContentsFocusedCallback( + base::BindRepeating(&MultiContentsView::OnActorOverlayFocused, + base::Unretained(this)))); + } + + if (auto* read_anything_overlay = + container->read_anything_immersive_overlay_view()) { + view_map[read_anything_overlay->GetClassName()] = read_anything_overlay; + contents_focused_subscriptions_.push_back( + read_anything_overlay->AddWebViewFocusedCallback(base::BindRepeating( + &MultiContentsView::OnReadAnythingOverlayFocused, + base::Unretained(this), container))); + } +} + +void MultiContentsView::ReleaseKourContainer(content::WebContents* contents) { + if (!contents) return; + for (size_t i = 0; i < contents_container_views_.size(); ++i) { + if (static_cast(i) == active_index_) continue; + ContentsContainerView* container = contents_container_views_[i]; + if (container->contents_view()->web_contents() != contents) continue; + container->contents_view()->SetWebContents(nullptr); + container->SetVisible(false); + if (i < kour_bounds_.size()) kour_bounds_[i] = gfx::Rect(); + InvalidateLayout(); + } +} + +size_t MultiContentsView::EnsureKourContainer(content::WebContents* contents) { + CHECK(contents); + for (size_t i = 0; i < contents_container_views_.size(); ++i) { + if (contents_container_views_[i]->contents_view()->web_contents() == contents) + return i; + } + size_t index = 0; + while (index < contents_container_views_.size() && + contents_container_views_[index]->contents_view()->web_contents()) { + ++index; + } + if (index == contents_container_views_.size()) { + auto* container = AddChildView(std::make_unique(browser_view_)); + container->SetVisible(false); + contents_container_views_.push_back(container); + RegisterContentsContainer(container); + // Docked DevTools is shown in the page's container by the window's + // DevtoolsUIController, which knows only the containers the window was + // made with: it is told of this one before a page is set into it, so its + // attach callback docks that page's DevTools. + if (auto* devtools = DevtoolsUIController::From(browser_view_->browser())) { + devtools->AddContentsContainer(container); + } + } + kour_bounds_.resize(contents_container_views_.size()); + auto* container = contents_container_views_[index].get(); + container->contents_view()->SetWebContents(contents); + container->UpdateBorderAndOverlay(false, false, false); + container->SetRoundedCorners(gfx::RoundedCornersF()); + return index; +} + +void MultiContentsView::SetKourActiveWebContents(content::WebContents* active) { + if (!kour_layout_) { + SetEventTargeter(std::make_unique( + std::make_unique())); + kour_layout_ = true; + } + resize_area_->SetVisible(false); + if (!active) return; + const int previous = active_index_; + active_index_ = EnsureKourContainer(active); + // By page, not by slot: a closed page's slot is the next page's. + if ((active_index_ != previous || kour_active_.get() != active) && + !kour_activating_) { + ++kour_epoch_; + } + kour_active_ = active->GetWeakPtr(); + for (size_t i = 0; i < contents_container_views_.size(); ++i) { + contents_container_views_[i]->contents_view() + ->set_is_primary_web_contents_for_window(i == static_cast(active_index_)); + } +} + +void MultiContentsView::SetKourWebContents( + const std::vector& surfaces, content::WebContents* active, + bool modal) { + SetKourActiveWebContents(active); + // Ensure first: growing the container vector must not invalidate its bounds. + for (const auto& surface : surfaces) EnsureKourContainer(surface.contents); + std::vector bounds(contents_container_views_.size()); + std::vector held(contents_container_views_.size()); + // The pages shown, and the DevTools docked beside them (the input hold + // below). + std::vector shown; + for (const auto& surface : surfaces) { + const size_t index = EnsureKourContainer(surface.contents); + bounds[index] = surface.bounds; + held[index] = surface.held; + contents_container_views_[index]->contents_view()->SetKourBackgroundColor( + surface.background); + shown.push_back(surface.contents); + if (content::WebContents* devtools = + contents_container_views_[index]->devtools_web_view()->web_contents()) { + shown.push_back(devtools); + } + } + // A hidden native NSView can still publish its WebContents accessibility + // subtree. Disconnect that bridge as well as hiding its painted surface: + // the page's and its docked DevTools' (in the same container). The lock is + // the web view's, so it holds for DevTools docked after. + for (size_t i = 0; i < contents_container_views_.size(); ++i) { + ContentsContainerView* container = contents_container_views_[i]; + for (views::WebView* web_view : + {static_cast(container->contents_view()), + container->devtools_web_view()}) { + if (bounds[i].IsEmpty() || modal) { + if (!web_view->GetProperty(kKourHiddenAccessibility)) { + web_view->SetProperty(kKourHiddenAccessibility, + web_view->DisconnectWebContentsAccessibility()); + } + } else { + web_view->ClearProperty(kKourHiddenAccessibility); + } + } + } + // Input likewise: each page shown under what dims the window, and its + // docked DevTools, is held from it once, and let go when the dimming or + // the page goes. DevTools docked while the window is dimmed is held when + // it docks (OnKourDevToolsDocked). + kour_modal_ = modal; + std::erase_if(kour_modal_held_, [&](const auto& held) { + return !modal || !held.first || + std::ranges::find(shown, held.first.get()) == shown.end(); + }); + if (modal) { + for (content::WebContents* contents : shown) HoldKourInput(contents); + } + // A held page is over the one that took its place: last among the + // children, which are stacked in their order. Reordering lays out again, + // so only what is not yet in its place is moved. + std::vector over; + for (const auto& surface : surfaces) { + if (surface.held) { + over.push_back( + contents_container_views_[EnsureKourContainer(surface.contents)].get()); + } + } + bool stacked = over.size() <= children().size(); + for (size_t i = 0; stacked && i < over.size(); ++i) { + stacked = children()[children().size() - over.size() + i] == over[i]; + } + if (!stacked) { + for (views::View* container : over) { + ReorderChildView(container, children().size()); + } + } + kour_held_ = std::move(held); + // A status bubble is a window of its own over everything, and a page hidden is + // out of what the browser tells to clear it or hide it: what it was hovering + // would stay over whatever came in its place. + for (size_t i = 0; i < bounds.size() && i < kour_bounds_.size(); ++i) { + if (bounds[i].IsEmpty() && !kour_bounds_[i].IsEmpty()) { + if (StatusBubbleViews* bubble = + contents_container_views_[i]->contents_view()->GetStatusBubble()) { + bubble->Hide(); + } + } + } + if (bounds != kour_bounds_) { + kour_bounds_ = std::move(bounds); + InvalidateLayout(); + } +} + +void MultiContentsView::SetKourBodies(const std::vector& bodies, + bool modal) { + std::vector bounds(kour_body_views_.size()); + std::vector used(kour_body_views_.size()); + for (const auto& body : bodies) { + // Its view, else one no body has, else a new one. + size_t index = 0; + while (index < kour_body_views_.size() && + kour_body_views_[index]->web_contents() != body.contents) { + ++index; + } + if (index == kour_body_views_.size()) { + index = 0; + while (index < kour_body_views_.size() && + (used[index] || kour_body_views_[index]->web_contents())) { + ++index; + } + } + if (index == kour_body_views_.size()) { + auto* view = AddChildView(std::make_unique(nullptr)); + view->SetVisible(false); + kour_body_views_.push_back(view); + bounds.emplace_back(); + used.push_back(false); + } + views::WebView* view = kour_body_views_[index]; + if (view->web_contents() != body.contents) { + view->SetWebContents(body.contents); + } + used[index] = true; + bounds[index] = body.bounds; + } + for (size_t i = 0; i < kour_body_views_.size(); ++i) { + views::WebView* view = kour_body_views_[i]; + // A body no longer shown leaves its view (it lives on with its owner). + if (!used[i] && view->web_contents()) view->SetWebContents(nullptr); + if (used[i] && (bounds[i].IsEmpty() || modal)) { + if (!view->GetProperty(kKourHiddenAccessibility)) { + view->SetProperty(kKourHiddenAccessibility, + view->DisconnectWebContentsAccessibility()); + } + } else { + view->ClearProperty(kKourHiddenAccessibility); + } + } + std::erase_if(kour_modal_bodies_, [&](const auto& held) { + return !modal || !held.first || + std::ranges::none_of(bodies, [&](const KourBody& body) { + return body.contents == held.first.get(); + }); + }); + if (modal) { + for (const auto& body : bodies) { + if (std::ranges::none_of(kour_modal_bodies_, [&](const auto& held) { + return held.first.get() == body.contents; + })) { + kour_modal_bodies_.emplace_back( + body.contents->GetWeakPtr(), + body.contents->IgnoreInputEvents(std::nullopt)); + } + } + } + if (bounds != kour_body_bounds_) { + kour_body_bounds_ = std::move(bounds); + InvalidateLayout(); + } +} + MultiContentsView::~MultiContentsView() { // Clear the map and vectors before `RemoveAllChildViews()` to avoid having // dangling pointers. container_focusable_map_.clear(); + // The watches before the views they follow (RemoveAllChildViews). + kour_devtools_watches_.clear(); contents_container_views_.clear(); + kour_body_views_.clear(); + kour_modal_bodies_.clear(); if (drop_target_controller_) { drop_target_controller_.reset(); } @@ -256,7 +604,7 @@ MultiContentsView::GetFocusableViewsMapFor( } bool MultiContentsView::IsInSplitView() const { - return resize_area_->GetVisible(); + return !kour_layout_ && resize_area_->GetVisible(); } void MultiContentsView::SetWebContentsAtIndex( @@ -395,6 +743,7 @@ void MultiContentsView::SetIsAnimatingContent(bool is_animating, std::vector MultiContentsView::GetAccessiblePanes() { std::vector accessible_panes; for (auto& contents_container_view : contents_container_views_) { + if (kour_layout_ && !contents_container_view->GetVisible()) continue; auto contents_accessible_panes = contents_container_view->GetAccessiblePanes(); accessible_panes.insert(accessible_panes.end(), @@ -446,6 +795,15 @@ int MultiContentsView::GetInactiveIndex() const { } void MultiContentsView::OnWebContentsFocused(views::WebView* web_view) { + if (kour_layout_) { + // Focus does not choose the active page here. It also follows a tab + // switch (the page left behind is told it is key again when a dialog + // gives the window back) and the window's activation, and this runs + // inside the tab strip's notifications, where activating a page again + // is a CHECK failure. A press does (OnKourInteraction); keyboard focus + // moving between panes is Flutter's (`focused` in the browser state). + return; + } if (IsInSplitView()) { // Check whether the widget is visible as otherwise during browser hide, // inactive web contents gets focus. See crbug.com/419335827 @@ -456,6 +814,55 @@ void MultiContentsView::OnWebContentsFocused(views::WebView* web_view) { } } +void MultiContentsView::OnKourInteraction(ContentsWebView* view) { + OnKourPress(view, nullptr); +} + +void MultiContentsView::OnKourPress(ContentsWebView* view, + views::View* keep_focus) { + content::WebContents* contents = view->web_contents(); + if (!kour_layout_ || !contents || !GetWidget() || !GetWidget()->IsVisible() || + browser_view_->browser()->GetTabStripModel()->GetActiveWebContents() == + contents) { + return; + } + for (size_t i = 0; i < contents_container_views_.size(); ++i) { + if (contents_container_views_[i]->contents_view() == view && + i < kour_held_.size() && kour_held_[i]) { + return; + } + } + base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( + FROM_HERE, base::BindOnce(&MultiContentsView::ActivateKourPage, + kour_weak_factory_.GetWeakPtr(), + contents->GetWeakPtr(), kour_epoch_, + base::Unretained(keep_focus))); +} + +void MultiContentsView::ActivateKourPage( + base::WeakPtr contents, + int epoch, + views::View* keep_focus) { + // What was true when the user pressed may not be now: the page may have + // closed, the active page may have changed (Flutter's showPages and + // activatePage decide, and a later decision wins), the window hidden. + if (epoch != kour_epoch_ || !contents || !GetWidget() || + !GetWidget()->IsVisible()) { + return; + } + auto* model = browser_view_->browser()->GetTabStripModel(); + if (model->GetActiveWebContents() == contents.get()) return; + const int index = model->GetIndexOfWebContents(contents.get()); + if (index >= 0) { + // Our own choice is not a change that a later press yields to. + base::AutoReset activating(&kour_activating_, true); + model->ActivateTabAt(index); + // `keep_focus` is a view of ours (a container's DevTools), alive while + // this is, which the weak pointer that ran this vouches for. + if (keep_focus && keep_focus->GetVisible()) keep_focus->RequestFocus(); + } +} + void MultiContentsView::OnActorOverlayFocused(views::WebView* web_view) { if (IsInSplitView() && GetWidget()->IsVisible()) { for (auto& contents_container_view : contents_container_views_) { @@ -505,6 +912,37 @@ views::ProposedLayout MultiContentsView::CalculateProposedLayout( const int width = size_bounds.width().value(); const int height = size_bounds.height().value(); + if (kour_layout_) { + layouts.host_size = gfx::Size(width, height); + // Explicitly hide every Chrome overlay; Flutter owns pane chrome and drag. + for (const auto& child : children()) { + layouts.child_layouts.emplace_back(child.get(), false, gfx::Rect()); + } + for (size_t i = 0; i < kour_bounds_.size(); ++i) { + gfx::Rect bounds = kour_bounds_[i]; + bounds.Intersect(gfx::Rect(width, height)); + for (auto& child : layouts.child_layouts) { + if (child.child_view == contents_container_views_[i]) { + child.visible = !bounds.IsEmpty(); + child.bounds = bounds; + break; + } + } + } + for (size_t i = 0; i < kour_body_bounds_.size(); ++i) { + gfx::Rect bounds = kour_body_bounds_[i]; + bounds.Intersect(gfx::Rect(width, height)); + for (auto& child : layouts.child_layouts) { + if (child.child_view == kour_body_views_[i]) { + child.visible = !bounds.IsEmpty() && kour_body_views_[i]->web_contents(); + child.bounds = bounds; + break; + } + } + } + return layouts; + } + gfx::Rect available_space = gfx::Rect(width, height); const bool show_background = @@ -559,7 +997,7 @@ views::ProposedLayout MultiContentsView::CalculateProposedLayout( } void MultiContentsView::BeforeApplyLayout(const views::ProposedLayout& layout) { - if (!target_content_bounds_) { + if (kour_layout_ || !target_content_bounds_) { for (auto& contents : contents_container_views_) { contents->SetTargetContentBounds(std::nullopt); } @@ -816,7 +1254,7 @@ MultiContentsView::drop_target_controller() const { bool MultiContentsView::IsDragAndDropEnabled() const { // Split view drag and drop is only supported on normal browser types. - if (!browser_view_->GetIsNormalType() || !is_drag_drop_pref_enabled_) { + if (kour_layout_ || !browser_view_->GetIsNormalType() || !is_drag_drop_pref_enabled_) { return false; } diff --git a/chrome/browser/ui/views/side_panel/kour_browser_data.h b/chrome/browser/ui/views/side_panel/kour_browser_data.h new file mode 100644 index 0000000000..ae870db9a9 --- /dev/null +++ b/chrome/browser/ui/views/side_panel/kour_browser_data.h @@ -0,0 +1,84 @@ +#ifndef CHROME_BROWSER_UI_VIEWS_SIDE_PANEL_KOUR_BROWSER_DATA_H_ +#define CHROME_BROWSER_UI_VIEWS_SIDE_PANEL_KOUR_BROWSER_DATA_H_ + +#include +#include +#include +#include + +#include "base/memory/raw_ptr.h" +#include "base/functional/callback.h" +#include "base/memory/scoped_refptr.h" +#include "base/memory/weak_ptr.h" +#include "base/task/cancelable_task_tracker.h" +#include "base/values.h" + +class Profile; +class KourSpaceLogins; +struct KourLoginsAct; +namespace device_reauth { +class DeviceAuthenticator; +} +namespace password_manager { +class PasswordImporter; +class PasswordStoreInterface; +class SavedPasswordsPresenter; +struct ImportResults; +} + +// Profile-owned stores stay behind this boundary. Password contents never leave +// for the Flutter protocol; callers receive only sites, usernames, aggregate +// counts and error codes. A password the person types (editing or adding one) +// comes in to be saved, and nothing is sent back of it. +class KourBrowserData { + public: + explicit KourBrowserData(Profile* profile); + ~KourBrowserData(); + std::optional Command(std::string_view method, + const base::DictValue& arguments); + bool busy() const; + void WhenIdle(base::OnceClosure done); + + private: + void Complete(int serial, base::DictValue result); + // A passwords job (listing, copying, removing) ended: its own status, apart + // from an import's, so neither ever waits for nor loses the other. + void CompletePasswords(int serial, base::DictValue result); + void ImportPasswords(std::string path, int serial, int attempt = 0); + void PasswordsFinished(int serial, const password_manager::ImportResults& result); + // The store a Space's passwords are in: the Space's own, or the profile's for + // the first Space (''). Null when there is none. + scoped_refptr StoreOf( + const std::string& space); + // The person confirmed it was them (or not): one password then copied. + // Asks the person whether it is them where the system can (macOS, + // Windows), then [then]; at once on Linux. False where it cannot ask. + bool Ask(const std::string* reason, base::OnceCallback then); + void Authenticated(int serial, + scoped_refptr store, + base::DictValue copy, + bool authenticated); + // The person confirmed it was them (or not): a password changed, or every + // password exported. + void AuthenticatedAct(int serial, + scoped_refptr store, + std::unique_ptr act, + bool authenticated); + raw_ptr profile_; + base::CancelableTaskTracker tasks_; + int serial_ = 0; + // Passwords jobs are numbered apart from imports (from a million up). + int password_serial_ = 1000000; + base::DictValue password_status_; + int skipped_passwords_ = 0; + base::DictValue status_; + scoped_refptr password_store_; + std::unique_ptr presenter_; + std::unique_ptr importer_; + std::unique_ptr logins_; + std::unique_ptr authenticator_; + base::OnceClosure idle_; + base::WeakPtrFactory weak_factory_{this}; +}; + +#endif diff --git a/chrome/browser/ui/views/side_panel/kour_browser_data.cc b/chrome/browser/ui/views/side_panel/kour_browser_data.cc new file mode 100644 index 0000000000..a385a648e9 --- /dev/null +++ b/chrome/browser/ui/views/side_panel/kour_browser_data.cc @@ -0,0 +1,734 @@ +#include "chrome/browser/ui/views/side_panel/kour_browser_data.h" + +#include +#include +#include +#include +#include + +#include "base/files/file_path.h" +#include "base/functional/bind.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/utf_string_conversions.h" +#include "base/task/sequenced_task_runner.h" +#include "chrome/browser/browsing_data/chrome_browsing_data_remover_constants.h" +#include "content/public/browser/browsing_data_remover.h" +#include "base/time/time.h" +#include "chrome/browser/affiliations/affiliation_service_factory.h" +#include "chrome/browser/history/history_service_factory.h" +#include "chrome/browser/password_manager/factories/kour_space_password_stores.h" +#include "chrome/browser/password_manager/factories/profile_password_store_factory.h" +#include "components/password_manager/core/browser/password_store/password_store_consumer.h" +#include "components/password_manager/core/browser/password_store/stored_credential.h" +#include "base/files/file_util.h" +#include "base/task/thread_pool.h" +#include "components/password_manager/core/browser/export/password_csv_writer.h" +#include "components/password_manager/core/browser/password_manager_util.h" +#include "components/password_manager/core/browser/password_store/password_form_converters.h" +#include "components/password_manager/core/browser/password_string.h" +#include "components/password_manager/core/browser/ui/credential_ui_entry.h" +#include "build/build_config.h" +#if BUILDFLAG(IS_WIN) +#include + +#include "base/win/access_control_list.h" +#include "base/win/access_token.h" +#include "base/win/security_descriptor.h" +#endif +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) +#include "chrome/browser/device_reauth/chrome_device_authenticator_factory.h" +#endif +#include "chrome/browser/kour_space.h" +#include "components/device_reauth/device_authenticator.h" +#include "ui/base/clipboard/scoped_clipboard_writer.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/views/side_panel/kour_spaces.h" +#include "components/history/core/browser/history_backend.h" +#include "components/history/core/browser/history_database.h" +#include "components/history/core/browser/history_db_task.h" +#include "components/history/core/browser/history_service.h" +#include "components/password_manager/core/browser/import/import_results.h" +#include "components/password_manager/core/browser/import/password_importer.h" +#include "components/password_manager/core/browser/password_store/password_store_interface.h" +#include "components/password_manager/core/browser/ui/saved_passwords_presenter.h" +#include "ui/base/page_transition_types.h" + +namespace { +base::DictValue Error(std::string code) { + return base::DictValue().Set("error", std::move(code)); +} + +// Run through HistoryService's serial database runner. Never write the live +// profile SQLite file externally. Timestamp + canonical URL makes retries safe. +class ImportHistoryTask final : public history::HistoryDBTask { + public: + // `app_id`: the Space the visits go into (`kourspace:`; none for the + // first Space), as HistoryTabHelper tags a visit made there. + ImportHistoryTask(base::ListValue rows, + std::optional app_id, + base::OnceCallback done) + : rows_(std::move(rows)), + app_id_(std::move(app_id)), + done_(std::move(done)) {} + + bool RunOnDBThread(history::HistoryBackend* backend, + history::HistoryDatabase* database) override { + if (!database) { + result_ = Error("historyUnavailable"); + return true; + } + int imported = 0, duplicates = 0, rejected = 0; + std::map> known; + for (const auto& value : rows_) { + const auto* row = value.GetIfDict(); + const auto* address = row ? row->FindString("url") : nullptr; + const auto* timestamp = row ? row->FindString("visitedAt") : nullptr; + int64_t micros = 0; + const GURL url(address ? *address : ""); + if (!url.is_valid() || !url.SchemeIsHTTPOrHTTPS() || url.has_username() || + url.has_password() || !timestamp || + !base::StringToInt64(*timestamp, µs) || micros <= 0 || + micros > (base::Time::Now() - base::Time::UnixEpoch() + base::Days(1)).InMicroseconds()) { + ++rejected; + continue; + } + const auto when = base::Time::UnixEpoch() + base::Microseconds(micros); + auto [found, first] = known.try_emplace(url.spec()); + auto& times = found->second; + if (first) { + history::URLRow stored; + if (const auto id = database->GetRowForURL(url, &stored)) { + history::VisitVector visits; + if (!database->GetVisitsForURL(id, &visits)) { + result_ = Error("historyUnavailable"); + return true; + } + // (a visit is the same only in the same Space: imported into + // another Space, it is that Space's too) + for (const auto& visit : visits) { + if (visit.app_id == app_id_) times.insert(visit.visit_time); + } + } + } + if (times.contains(when)) { + ++duplicates; + continue; + } + history::HistoryAddPageArgs args; + args.url = url; + args.time = when; + const int transition = row->FindInt("transition").value_or(0); + args.transition = ui::PageTransitionFromInt( + (transition >= 0 && transition <= 10 ? transition : 0) | + ui::PAGE_TRANSITION_CHAIN_START | ui::PAGE_TRANSITION_CHAIN_END); + args.visit_source = history::SOURCE_OS_MIGRATION_IMPORTED; + args.app_id = app_id_; + if (const auto* title = row->FindString("title")) + args.title = base::UTF8ToUTF16(title->substr(0, 16384)); + backend->AddPage(args); + history::URLRow saved; + history::VisitVector visits; + const auto id = database->GetRowForURL(url, &saved); + if (!id || !database->GetVisitsForURL(id, &visits)) { + ++rejected; + continue; + } + bool persisted = false; + for (const auto& visit : visits) { + if (visit.app_id != app_id_) continue; + times.insert(visit.visit_time); + if (visit.visit_time == when) persisted = true; + } + persisted ? ++imported : ++rejected; + } + result_ = base::DictValue().Set("imported", imported).Set("duplicates", duplicates) + .Set("rejected", rejected); + return true; + } + + void DoneRunOnMainThread() override { + std::move(done_).Run(std::move(result_)); + } + + private: + base::ListValue rows_; + std::optional app_id_; + base::OnceCallback done_; + base::DictValue result_; +}; +} // namespace + +// What a passwords job does besides listing: at most one of these. +struct KourLoginsAct { + // {realm, username}: removed. + std::optional remove; + // {realm, username}: its password to the clipboard. + std::optional copy; + // {realm, username, newUsername?, newPassword?}: changed. + std::optional edit; + // {url, username, password}: saved, unless the site has that username. + std::optional add; + // Every password of the Space, as Chrome exports them (CSV), to this file. + std::optional export_to; +}; + +// A Space's saved logins, read (and, when asked, one removed, changed or +// added, or all exported) for Settings › Passwords: sites and usernames +// only, never a password, go back to Kour (P8). A password the person types +// comes in to be saved; none goes out but to the clipboard or the file the +// person chose. +class KourSpaceLogins final : public password_manager::PasswordStoreConsumer { + public: + KourSpaceLogins( + scoped_refptr store, + std::optional remove, + base::OnceCallback done, + std::optional copy = std::nullopt) + : store_(std::move(store)), done_(std::move(done)) { + act_.remove = std::move(remove); + act_.copy = std::move(copy); + } + KourSpaceLogins( + scoped_refptr store, + KourLoginsAct act, + base::OnceCallback done) + : store_(std::move(store)), act_(std::move(act)), done_(std::move(done)) {} + + void Start() { store_->GetAllLogins(weak_factory_.GetWeakPtr()); } + + // A store made just now answers once its database is open: asked again a + // moment later, a few seconds at most. + bool Again() { + if (attempts_++ >= 50) return false; + base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask( + FROM_HERE, + base::BindOnce(&KourSpaceLogins::Start, weak_factory_.GetWeakPtr()), + base::Milliseconds(100)); + return true; + } + + void OnGetPasswordStoreResultsOrErrorFrom( + password_manager::PasswordStoreInterface* store, + base::expected, + password_manager::PasswordStoreBackendError> + results_or_error) override { + if (!results_or_error.has_value()) { + if (Again()) return; + std::move(done_).Run(Error("passwordStoreUnavailable")); + return; + } + const auto& all = results_or_error.value(); + auto has = [&](const std::string& realm, const std::u16string& username) { + return std::ranges::any_of(all, [&](const auto& login) { + return !login.blocked_by_user && login.signon_realm == realm && + login.username_value == username; + }); + }; + if (act_.add) { + const GURL url(*act_.add->FindString("url")); + const std::u16string username = + base::UTF8ToUTF16(*act_.add->FindString("username")); + const std::string realm = password_manager_util::GetSignonRealm(url); + if (has(realm, username)) { + std::move(done_).Run(Error("passwordExists")); + return; + } + password_manager::StoredCredential login; + login.scheme = password_manager::PasswordForm::Scheme::kHtml; + login.url = url; + login.signon_realm = realm; + login.username_value = username; + login.password_value = password_manager::PasswordString( + base::UTF8ToUTF16(*act_.add->FindString("password"))); + login.type = password_manager::PasswordForm::Type::kManuallyAdded; + login.date_created = login.date_password_modified = base::Time::Now(); + store_->AddLogin(std::move(login)); + std::move(done_).Run(base::DictValue().Set("added", true)); + return; + } + if (act_.export_to) { + std::vector entries; + for (const auto& login : all) { + // (a federated sign-in has no password to export) + if (login.blocked_by_user || login.federation_origin.IsValid()) continue; + entries.emplace_back(login); + } + const int count = static_cast(entries.size()); + base::ThreadPool::PostTaskAndReplyWithResult( + FROM_HERE, {base::MayBlock(), base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, + base::BindOnce( + [](base::FilePath path, std::string csv) { + // Readable by the person alone, before anything is in it: + // every password is. + if (!base::WriteFile(path, "")) return false; +#if BUILDFLAG(IS_POSIX) + base::SetPosixFilePermissions(path, 0600); +#elif BUILDFLAG(IS_WIN) + // (the person's alone: a DACL of their own, not inherited) + base::win::SecurityDescriptor owner_only; + const auto token = base::win::AccessToken::FromCurrentProcess(); + if (!token || + !owner_only.SetDaclEntry(*token, base::win::SecurityAccessMode::kGrant, FILE_ALL_ACCESS, 0)) { + base::DeleteFile(path); + return false; + } + owner_only.set_dacl_protected(true); + if (!owner_only.WriteToFile(path, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION)) { + base::DeleteFile(path); + return false; + } +#endif + return base::WriteFile(path, csv); + }, + *act_.export_to, + password_manager::PasswordCSVWriter::SerializePasswords(entries)), + base::BindOnce( + [](base::OnceCallback done, int count, + bool written) { + std::move(done).Run(written ? base::DictValue().Set("exported", count) + : Error("exportFailed")); + }, + std::move(done_), count)); + return; + } + if (act_.edit) { + const std::string realm = *act_.edit->FindString("realm"); + const std::u16string username = + base::UTF8ToUTF16(*act_.edit->FindString("username")); + const std::string* new_username = act_.edit->FindString("newUsername"); + const std::string* new_password = act_.edit->FindString("newPassword"); + const auto found = std::ranges::find_if(all, [&](const auto& login) { + return !login.blocked_by_user && login.signon_realm == realm && + login.username_value == username; + }); + if (found == all.end()) { + std::move(done_).Run(Error("passwordNotFound")); + return; + } + password_manager::StoredCredential changed = + password_manager::CloneStoredCredential(*found); + const bool renamed = + new_username && base::UTF8ToUTF16(*new_username) != username; + if (renamed) { + changed.username_value = base::UTF8ToUTF16(*new_username); + if (has(realm, changed.username_value)) { + std::move(done_).Run(Error("passwordExists")); + return; + } + } + if (new_password && !new_password->empty()) { + changed.password_value = + password_manager::PasswordString(base::UTF8ToUTF16(*new_password)); + changed.date_password_modified = base::Time::Now(); + } + if (renamed) { + store_->UpdateLoginWithPrimaryKey(std::move(changed), *found); + } else { + store_->UpdateLogin(std::move(changed)); + } + std::move(done_).Run(base::DictValue().Set("edited", true)); + return; + } + base::ListValue logins; + int removed = 0; + bool copied = false; + for (const auto& login : all) { + if (login.blocked_by_user) continue; + const std::string username = base::UTF16ToUTF8(login.username_value); + // One password, to the clipboard only (marked confidential, so a + // clipboard history leaves it out); it never comes to Kour. + if (act_.copy && !copied && + login.signon_realm == *act_.copy->FindString("realm") && + username == *act_.copy->FindString("username")) { + ui::ScopedClipboardWriter writer(ui::ClipboardBuffer::kCopyPaste); + writer.WriteText(login.password_value.value()); + writer.MarkAsConfidential(); + copied = true; + } + if (act_.remove && login.signon_realm == + *act_.remove->FindString("realm") && + username == *act_.remove->FindString("username")) { + store_->RemoveLogin(FROM_HERE, login); + ++removed; + continue; + } + logins.Append(base::DictValue() + .Set("realm", login.signon_realm) + .Set("url", login.url.spec()) + .Set("username", username)); + } + if (act_.copy && !copied) { + std::move(done_).Run(Error("passwordNotFound")); + return; + } + std::move(done_).Run(base::DictValue() + .Set("logins", std::move(logins)) + .Set("removed", removed) + .Set("copied", copied)); + } + + private: + scoped_refptr store_; + KourLoginsAct act_; + base::OnceCallback done_; + int attempts_ = 0; + base::WeakPtrFactory weak_factory_{this}; +}; + +// Waits for one Clear History of the remover, then goes. +class KourHistoryClearing : public content::BrowsingDataRemover::Observer { + public: + KourHistoryClearing(content::BrowsingDataRemover* remover, base::OnceCallback done) + : remover_(remover), done_(std::move(done)) { + remover_->AddObserver(this); + } + + void OnBrowsingDataRemoverDone(uint64_t failed_data_types) override { + remover_->RemoveObserver(this); + auto done = std::move(done_); + delete this; + std::move(done).Run(failed_data_types == 0); + } + + private: + raw_ptr remover_; + base::OnceCallback done_; +}; + +KourBrowserData::KourBrowserData(Profile* profile) : profile_(profile) {} + +void KourBrowserData::Authenticated( + int serial, + scoped_refptr store, + base::DictValue copy, + bool authenticated) { + if (!authenticated) { + CompletePasswords(serial, Error("notAuthenticated")); + return; + } + logins_ = std::make_unique( + std::move(store), std::nullopt, + base::BindOnce(&KourBrowserData::CompletePasswords, + weak_factory_.GetWeakPtr(), serial), + std::move(copy)); + logins_->Start(); +} + +void KourBrowserData::AuthenticatedAct( + int serial, + scoped_refptr store, + std::unique_ptr act, + bool authenticated) { + if (!authenticated) { + CompletePasswords(serial, Error("notAuthenticated")); + return; + } + logins_ = std::make_unique( + std::move(store), std::move(*act), + base::BindOnce(&KourBrowserData::CompletePasswords, + weak_factory_.GetWeakPtr(), serial)); + logins_->Start(); +} + +scoped_refptr +KourBrowserData::StoreOf(const std::string& space) { + return space.empty() + ? ProfilePasswordStoreFactory::GetForProfile( + profile_, ServiceAccessType::EXPLICIT_ACCESS) + : kour::SpacePasswordStore(profile_, space); +} +KourBrowserData::~KourBrowserData() = default; + +bool KourBrowserData::Ask(const std::string* reason, base::OnceCallback then) { +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) + // The person says it is them first (Touch ID, the Mac's password, Windows + // Hello), as the browser's own manager asks before it shows one. + authenticator_ = ChromeDeviceAuthenticatorFactory::GetForProfile( + profile_, gfx::NativeWindow(), + device_reauth::DeviceAuthParams( + base::Seconds(60), device_reauth::DeviceAuthSource::kPasswordManager)); + if (!authenticator_) return false; + password_status_ = base::DictValue().Set("jobId", ++password_serial_).Set("running", true); + authenticator_->AuthenticateWithMessage(base::UTF8ToUTF16(reason ? *reason : std::string()), std::move(then)); +#else + // Linux has no such question: Chrome there shows, copies and exports a + // password at once (compat-fixes B11). + password_status_ = base::DictValue().Set("jobId", ++password_serial_).Set("running", true); + base::SequencedTaskRunner::GetCurrentDefault()->PostTask(FROM_HERE, base::BindOnce(std::move(then), true)); +#endif + return true; +} + +bool KourBrowserData::busy() const { + return status_.FindBool("running").value_or(false); +} + +void KourBrowserData::WhenIdle(base::OnceClosure done) { + if (busy()) idle_ = std::move(done); + else std::move(done).Run(); +} + +std::optional KourBrowserData::Command( + std::string_view method, const base::DictValue& args) { + if (method == "browserImportCapabilities") + return base::DictValue().Set("version", 1).Set("marker", "KOUR_BROWSER_IMPORT_V1"); + if (method == "browserDataJob") { + const std::optional job = args.FindInt("jobId"); + if (job == password_serial_ && !password_status_.empty()) + return password_status_.Clone(); + if (job != serial_) return Error("invalidImportJob"); + return status_.Clone(); + } + const bool passwords_busy = + password_status_.FindBool("running").value_or(false); + if (method == "copySpacePassword") { + if (profile_->IsOffTheRecord()) return Error("privateProfile"); + if (passwords_busy) return Error("passwordsBusy"); + const std::string* space = args.FindString("space"); + const std::string* realm = args.FindString("realm"); + const std::string* username = args.FindString("username"); + const std::string* reason = args.FindString("reason"); + if ((space && !space->empty() && !kour::ValidSpace(*space)) || !realm || + !username) { + return Error("invalidPassword"); + } + auto store = StoreOf(space ? *space : std::string()); + if (!store) return Error("passwordStoreUnavailable"); + auto copied = base::BindOnce(&KourBrowserData::Authenticated, + weak_factory_.GetWeakPtr(), password_serial_ + 1, + std::move(store), + base::DictValue() + .Set("realm", *realm) + .Set("username", *username)); + if (!Ask(reason, std::move(copied))) return Error("notAuthenticated"); + return password_status_.Clone(); + } + // A password changed, or every password written to a file: the person says + // it is them first, as the browser's own manager asks. + if (method == "editSpacePassword" || method == "exportSpacePasswords") { + if (profile_->IsOffTheRecord()) return Error("privateProfile"); + if (passwords_busy) return Error("passwordsBusy"); + const std::string* space = args.FindString("space"); + const std::string* reason = args.FindString("reason"); + if (space && !space->empty() && + (!kour::ValidSpace(*space) || kour::SpaceForgotten(profile_, *space))) { + return Error("invalidSpace"); + } + auto act = std::make_unique(); + if (method == "editSpacePassword") { + const std::string* realm = args.FindString("realm"); + const std::string* username = args.FindString("username"); + const std::string* new_username = args.FindString("newUsername"); + const std::string* new_password = args.FindString("newPassword"); + if (!realm || !username || (!new_username && !new_password) || + (new_username && new_username->size() > 1024) || + (new_password && new_password->size() > 1024)) { + return Error("invalidPassword"); + } + auto edit = base::DictValue().Set("realm", *realm).Set("username", *username); + if (new_username) edit.Set("newUsername", *new_username); + if (new_password) edit.Set("newPassword", *new_password); + act->edit = std::move(edit); + } else { + const std::string* path = args.FindString("path"); + const base::FilePath file = + base::FilePath::FromUTF8Unsafe(path ? *path : std::string()); + if (!path || !file.IsAbsolute() || + !file.MatchesExtension(FILE_PATH_LITERAL(".csv"))) { + return Error("invalidPasswordFile"); + } + act->export_to = file; + } + auto store = StoreOf(space ? *space : std::string()); + if (!store) return Error("passwordStoreUnavailable"); + auto acted = base::BindOnce(&KourBrowserData::AuthenticatedAct, + weak_factory_.GetWeakPtr(), password_serial_ + 1, + std::move(store), std::move(act)); + if (!Ask(reason, std::move(acted))) return Error("notAuthenticated"); + return password_status_.Clone(); + } + // A login the person types in: saved into the Space's own store (no + // prompt: adding shows nothing that was kept). + if (method == "addSpacePassword") { + if (profile_->IsOffTheRecord()) return Error("privateProfile"); + if (passwords_busy) return Error("passwordsBusy"); + const std::string* space = args.FindString("space"); + const std::string* address = args.FindString("url"); + const std::string* username = args.FindString("username"); + const std::string* password = args.FindString("password"); + if (space && !space->empty() && + (!kour::ValidSpace(*space) || kour::SpaceForgotten(profile_, *space))) { + return Error("invalidSpace"); + } + const GURL url(address ? *address : std::string()); + if (!url.is_valid() || !url.SchemeIsHTTPOrHTTPS() || !username || + !password || password->empty() || username->size() > 1024 || + password->size() > 1024) { + return Error("invalidPassword"); + } + auto store = StoreOf(space ? *space : std::string()); + if (!store) return Error("passwordStoreUnavailable"); + KourLoginsAct act; + act.add = base::DictValue() + .Set("url", url.GetWithEmptyPath().spec()) + .Set("username", *username) + .Set("password", *password); + password_status_ = base::DictValue() + .Set("jobId", ++password_serial_) + .Set("running", true); + logins_ = std::make_unique( + std::move(store), std::move(act), + base::BindOnce(&KourBrowserData::CompletePasswords, + weak_factory_.GetWeakPtr(), password_serial_)); + logins_->Start(); + return password_status_.Clone(); + } + if (method == "spacePasswords" || method == "removeSpacePassword") { + if (profile_->IsOffTheRecord()) return Error("privateProfile"); + if (passwords_busy) return Error("passwordsBusy"); + const std::string* space = args.FindString("space"); + if (space && !space->empty() && !kour::ValidSpace(*space)) + return Error("invalidSpace"); + std::optional remove; + if (method == "removeSpacePassword") { + const std::string* realm = args.FindString("realm"); + const std::string* username = args.FindString("username"); + if (!realm || !username) return Error("invalidPassword"); + remove = base::DictValue().Set("realm", *realm).Set("username", *username); + } + auto store = StoreOf(space ? *space : std::string()); + if (!store) return Error("passwordStoreUnavailable"); + password_status_ = base::DictValue() + .Set("jobId", ++password_serial_) + .Set("running", true); + logins_ = std::make_unique( + std::move(store), std::move(remove), + base::BindOnce(&KourBrowserData::CompletePasswords, + weak_factory_.GetWeakPtr(), password_serial_)); + logins_->Start(); + return password_status_.Clone(); + } + // Clear History (compat-fixes C17): the browser's own history of every + // Space (they are one profile's partitions), as Chrome's "Browsing + // history" clears it: its observers take recently closed tabs, the open + // pages' back and forward, the address field's shortcuts, top sites and + // favicons with it. Cookies and site data stay. [before]: up to then only + // (another device's clearing). Behind any import job. + if (method == "clearHistory") { + if (profile_->IsOffTheRecord()) return Error("privateProfile"); + if (busy()) return Error("importBusy"); + const std::optional before = args.FindDouble("before"); + const base::Time end = before ? base::Time::FromMillisecondsSinceUnixEpoch(*before) : base::Time::Max(); + status_ = base::DictValue().Set("jobId", ++serial_).Set("running", true); + content::BrowsingDataRemover* remover = profile_->GetBrowsingDataRemover(); + // (lives until the remover says it is done) + auto* clearing = new KourHistoryClearing(remover, base::BindOnce( + [](base::WeakPtr self, int serial, bool ok) { + if (self) self->Complete(serial, ok ? base::DictValue().Set("cleared", true) : Error("clearFailed")); + }, + weak_factory_.GetWeakPtr(), serial_)); + remover->RemoveAndReply(base::Time(), end, chrome_browsing_data_remover::DATA_TYPE_HISTORY, + content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB, + clearing); + return status_.Clone(); + } + if (method != "importHistory" && method != "importPasswords") return std::nullopt; + if (profile_->IsOffTheRecord()) return Error("privateProfile"); + if (busy()) return Error("importBusy"); + if (method == "importHistory") { + const auto* rows = args.FindList("rows"); + if (!rows || rows->size() > 1000) return Error("invalidHistoryBatch"); + // The Space the history goes into (none: the first Space's). + const std::string* space = args.FindString("space"); + if (space && !space->empty() && + (!kour::ValidSpace(*space) || kour::SpaceForgotten(profile_, *space))) + return Error("invalidSpace"); + std::optional app_id; + if (space && !space->empty()) app_id = kour::HistoryTagOf(*space); + auto* history = HistoryServiceFactory::GetForProfile(profile_, ServiceAccessType::EXPLICIT_ACCESS); + if (!history) return Error("historyUnavailable"); + status_ = base::DictValue().Set("jobId", ++serial_).Set("running", true); + history->ScheduleDBTask(FROM_HERE, std::make_unique( + rows->Clone(), std::move(app_id), base::BindOnce(&KourBrowserData::Complete, + weak_factory_.GetWeakPtr(), serial_)), &tasks_); + } else { + const auto* path = args.FindString("path"); + if (!path || !base::FilePath::FromUTF8Unsafe(*path).IsAbsolute() || + !base::FilePath::FromUTF8Unsafe(*path).MatchesExtension(FILE_PATH_LITERAL(".csv"))) + return Error("invalidPasswordFile"); + // Into the Space chosen: its own store (the profile's for the first Space). + const std::string* space = args.FindString("space"); + if (space && !space->empty() && + (!kour::ValidSpace(*space) || kour::SpaceForgotten(profile_, *space))) + return Error("invalidSpace"); + password_store_ = StoreOf(space ? *space : std::string()); + if (!password_store_) return Error("passwordStoreUnavailable"); + // Destroy importer before its presenter on a subsequent import. + importer_.reset(); + presenter_ = std::make_unique( + AffiliationServiceFactory::GetForProfile(profile_), password_store_, nullptr); + skipped_passwords_ = 0; + status_ = base::DictValue().Set("jobId", ++serial_).Set("running", true); + presenter_->Init(base::BindOnce(&KourBrowserData::ImportPasswords, + weak_factory_.GetWeakPtr(), *path, serial_, /*attempt=*/0)); + } + return status_.Clone(); +} + +void KourBrowserData::CompletePasswords(int serial, base::DictValue result) { + if (serial != password_serial_) return; + password_status_ = + std::move(result).Set("jobId", serial).Set("running", false); +} + +void KourBrowserData::Complete(int serial, base::DictValue result) { + if (serial != serial_) return; + status_ = std::move(result).Set("jobId", serial).Set("running", false); + if (idle_) std::move(idle_).Run(); +} + +void KourBrowserData::ImportPasswords(std::string path, int serial, int attempt) { + // A Space's store made just now opens its database a moment later: waited + // for (a few seconds at most) before it is said to be unavailable. + if (password_store_->GetError() == + password_manager::ActionableError::kInactionable && + attempt < 50) { + base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask( + FROM_HERE, + base::BindOnce(&KourBrowserData::ImportPasswords, + weak_factory_.GetWeakPtr(), std::move(path), serial, + attempt + 1), + base::Milliseconds(100)); + return; + } + if (password_store_->GetError() != password_manager::ActionableError::kNoError) { + Complete(serial, Error("passwordStoreUnavailable")); + return; + } + importer_ = std::make_unique(*presenter_); + importer_->Import(base::FilePath::FromUTF8Unsafe(path), password_manager::PasswordForm::Store::kProfileStore, + base::BindOnce(&KourBrowserData::PasswordsFinished, weak_factory_.GetWeakPtr(), serial)); +} + +void KourBrowserData::PasswordsFinished(int serial, const password_manager::ImportResults& result) { + using Results = password_manager::ImportResults; + if (result.status == Results::CONFLICTS) { + skipped_passwords_ = static_cast(result.displayed_entries.size()); + importer_->ContinueImport({}, base::BindOnce(&KourBrowserData::PasswordsFinished, + weak_factory_.GetWeakPtr(), serial)); + return; + } + if (password_store_->GetError() != password_manager::ActionableError::kNoError) { + Complete(serial, Error("passwordStoreUnavailable")); + return; + } + if (result.status != Results::SUCCESS) { + Complete(serial, Error("passwordImportFailed").Set("reason", static_cast(result.status))); + return; + } + // Chromium includes exact matches in number_imported. Label it "available" + // in the UI, not "new passwords". Conflicts retain their existing value. + Complete(serial, base::DictValue().Set("available", static_cast(result.number_imported)) + .Set("skipped", skipped_passwords_) + .Set("rejected", static_cast(result.displayed_entries.size()))); +} diff --git a/chrome/BUILD.gn b/chrome/BUILD.gn index d98c86e5da..77149dfcee 100644 --- a/chrome/BUILD.gn +++ b/chrome/BUILD.gn @@ -33,6 +33,12 @@ import("//tools/v8_context_snapshot/v8_context_snapshot.gni") import("//ui/gl/features.gni") import("//v8/gni/v8.gni") +# Kour's names (kour_executable, kour_data_dir) on Windows and Linux, used from +# the top of this file on (reorder_imports). +if (!is_android && !is_mac) { + import("//build/util/branding.gni") +} + assert(!is_fuchsia, "Fuchsia shouldn't use anything in //chrome") if (is_android) { @@ -72,6 +78,13 @@ declare_args() { # signing identity. If `include_branded_entitlements` is set to false, these # entitlements will be skipped. include_branded_entitlements = true + + # Kour's own code and release record, built outside Chromium: the directory + # written by Kour's payload builder (hosts/chromium/macos/build_payload.py: + # Frameworks/, Resources/; hosts/chromium/desktop/build_payload.py: + # payload/; both with kour-bundle.json and kour-payload.json). The browser + # is built with it inside. Empty builds the browser alone. + kour_payload_dir = "" } assert(!is_ios, "Chromium/iOS shouldn't use anything in //chrome") @@ -86,13 +99,14 @@ if (is_win) { # initialexe/ is used so that the we can reorder imports and write back to # the final destination at $root_out_dir/. + # Kour's name, from its BRANDING (KOUR_EXECUTABLE). inputs = [ - "$root_out_dir/initialexe/chrome.exe", - "$root_out_dir/initialexe/chrome.exe.pdb", + "$root_out_dir/initialexe/$kour_executable.exe", + "$root_out_dir/initialexe/$kour_executable.exe.pdb", ] outputs = [ - "$root_out_dir/chrome.exe", - "$root_out_dir/chrome.exe.pdb", + "$root_out_dir/$kour_executable.exe", + "$root_out_dir/$kour_executable.exe.pdb", ] args = [ "-i", @@ -101,6 +115,8 @@ if (is_win) { rebase_path("$root_out_dir", root_build_dir), "-a", current_cpu, + "-n", + kour_executable, ] deps = [ ":chrome_initial" ] } @@ -131,6 +147,47 @@ group("assert_no_deps") { } if (!is_android && !is_mac) { + if (kour_payload_dir != "") { + # Kour's code beside the browser, in payload/: one copy per directory of + # the record, so the build copies exactly the files that changed. + _kour_bundle = read_file("$kour_payload_dir/kour-bundle.json", "json") + _kour_payload_copies = [] + foreach(_directory, _kour_bundle.directories) { + _kour_relative = "" + if (_directory.path != "") { + _kour_relative = "/" + _directory.path + } + copy("kour_payload_${_directory.id}") { + sources = [] + foreach(_name, _directory.files) { + sources += [ "$kour_payload_dir/payload$_kour_relative/$_name" ] + } + outputs = [ "$root_out_dir/payload$_kour_relative/{{source_file_part}}" ] + + # What is no longer listed goes first, so the copies never race it. + deps = [ ":kour_payload_prune" ] + } + _kour_payload_copies += [ ":kour_payload_${_directory.id}" ] + } + + group("kour_payload") { + data_deps = _kour_payload_copies + } + + # A copy never deletes: what the record no longer lists is removed, so the + # output holds exactly the payload it was built with. + action("kour_payload_prune") { + script = "app/kour_payload_prune.py" + inputs = [ "$kour_payload_dir/kour-bundle.json" ] + outputs = [ "$target_gen_dir/kour_payload_prune.stamp" ] + args = [ + rebase_path(inputs[0], root_build_dir), + rebase_path("$root_out_dir/payload", root_build_dir), + rebase_path(outputs[0], root_build_dir), + ] + } + } + group("chrome") { public_deps = [ ":chrome_initial", @@ -154,10 +211,11 @@ if (!is_android && !is_mac) { } } + # Kour's name, from its BRANDING (KOUR_EXECUTABLE). if (is_win) { - _chrome_output_name = "initialexe/chrome" + _chrome_output_name = "initialexe/$kour_executable" } else { - _chrome_output_name = "chrome" + _chrome_output_name = kour_executable } executable("chrome_initial") { @@ -406,6 +464,12 @@ if (!is_android && !is_mac) { if (is_chrome_for_testing) { deps += [ "//chrome/browser/chrome_for_testing:browser" ] } + + if (kour_payload_dir != "") { + # The copies are what ships (runtime deps); the prune only has to run. + data_deps += [ ":kour_payload" ] + deps += [ ":kour_payload_prune" ] + } } # TODO(crbug.com/40204298): Make this work on other platforms. @@ -535,10 +599,91 @@ if (is_win) { } } + if (kour_payload_dir != "") { + _kour_payload_record = "$kour_payload_dir/kour-payload.json" + + # What to bundle, as names alone: GN reads a JSON object's keys as + # identifiers, and the record's are also paths. + _kour_payload = read_file("$kour_payload_dir/kour-bundle.json", "json") + + # The record's version, update feed and usage descriptions, in the + # bundle's Info.plist. + action("kour_app_plist") { + script = "app/kour_app_plist.py" + _tweaked = get_target_outputs(":chrome_app_plist") + inputs = [ + _kour_payload_record, + _tweaked[0], + ] + outputs = [ "$target_gen_dir/kour_app.plist" ] + args = [ + rebase_path(_tweaked[0], root_build_dir), + rebase_path(_kour_payload_record, root_build_dir), + rebase_path(outputs[0], root_build_dir), + ] + deps = [ ":chrome_app_plist" ] + } + + # What an earlier payload carried and this one does not leaves the app + # before the copies (they never remove anything). + action("kour_app_prune") { + script = "app/kour_app_prune.py" + inputs = [ "$kour_payload_dir/kour-bundle.json" ] + outputs = [ "$target_gen_dir/kour_app_prune.stamp" ] + args = [ + rebase_path("$kour_payload_dir/kour-bundle.json", root_build_dir), + rebase_path("$root_out_dir/$chrome_product_full_name.app/Contents", + root_build_dir), + "$chrome_product_full_name Framework.framework", + rebase_path("$target_gen_dir/kour_app_prune.last.json", root_build_dir), + rebase_path(outputs[0], root_build_dir), + ] + } + + bundle_data("kour_payload_frameworks") { + sources = [] + foreach(_name, _kour_payload.frameworks) { + sources += [ "$kour_payload_dir/Frameworks/$_name" ] + } + outputs = [ "{{bundle_contents_dir}}/Frameworks/{{source_file_part}}" ] + public_deps = [ ":kour_app_prune" ] + } + + bundle_data("kour_payload_resources") { + sources = [] + foreach(_name, _kour_payload.resources) { + sources += [ "$kour_payload_dir/Resources/$_name" ] + } + outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ] + public_deps = [ ":kour_app_prune" ] + } + + # Beside the browser's executable: a release's Velopack UpdateMac, which + # applies a downloaded update (hosts/desktop-updater). + _kour_executables = [] + if (defined(_kour_payload.executables)) { + _kour_executables = _kour_payload.executables + } + if (_kour_executables != []) { + bundle_data("kour_payload_executables") { + sources = [] + foreach(_name, _kour_executables) { + sources += [ "$kour_payload_dir/MacOS/$_name" ] + } + outputs = [ "{{bundle_executable_dir}}/{{source_file_part}}" ] + public_deps = [ ":kour_app_prune" ] + } + } + } + mac_app_bundle("chrome_app") { output_name = chrome_product_full_name - info_plist_target = ":chrome_app_plist" + if (kour_payload_dir != "") { + info_plist_target = ":kour_app_plist" + } else { + info_plist_target = ":chrome_app_plist" + } extra_substitutions = [ "CHROMIUM_BUNDLE_ID=$chrome_mac_bundle_id", "CHROMIUM_SHORT_NAME=$chrome_product_short_name", @@ -572,6 +717,16 @@ if (is_win) { bundle_deps += [ ":chromium_updater_privileged_helper" ] } + if (kour_payload_dir != "") { + deps += [ + ":kour_payload_frameworks", + ":kour_payload_resources", + ] + if (_kour_executables != []) { + deps += [ ":kour_payload_executables" ] + } + } + if (enable_stripping) { # At link time, preserve the global symbols specified in the .exports # file. All other global symbols will be marked as private. The default @@ -1684,6 +1839,12 @@ if (is_win) { process_version_rc_template("chrome_exe_version") { sources = [ "app/chrome_exe.ver" ] output = "$target_gen_dir/chrome_exe_version.rc" + + # Kour's file name (BRANDING KOUR_EXECUTABLE). + extra_args = [ + "-e", + "ORIGINAL_FILENAME=KOUR_EXECUTABLE+'.exe'", + ] } process_version_rc_template("chrome_dll_version") { @@ -1705,12 +1866,19 @@ if (is_win) { } } +# Kour: Windows reads .VisualElementsManifest.xml beside the +# executable. +copy("kour_visual_elements_manifest") { + sources = [ "app/visual_elements_resources/chrome.VisualElementsManifest.xml" ] + outputs = [ "$root_out_dir/$kour_executable.VisualElementsManifest.xml" ] +} + copy("visual_elements_resources") { sources = [ "//chrome/app/theme/$branding_path_component/win/tiles/Logo.png", "//chrome/app/theme/$branding_path_component/win/tiles/SmallLogo.png", - "app/visual_elements_resources/chrome.VisualElementsManifest.xml", ] + public_deps = [ ":kour_visual_elements_manifest" ] if (is_chrome_branded) { sources += [ @@ -1892,7 +2060,7 @@ if (is_linux || is_chromeos) { } extract_symbols("chrome_symbols") { - binary = "$root_out_dir/chrome" + binary = "$root_out_dir/$kour_executable" if (current_cpu == "x86") { # GYP used "ia32" so keep that naming for back-compat. @@ -2027,14 +2195,16 @@ if (is_linux || is_chromeos) { # Copies some scripts and resources that are used for desktop integration. copy("linux_cros_extra_data") { - sources = [ "//chrome/tools/build/linux/chrome-wrapper" ] if (is_linux) { - sources += [ + # Kour starts as itself: no chrome-wrapper (it runs "$HERE/chrome"). + sources = [ "//chrome/app/theme/$branding_path_component/linux/product_logo_48.png", ] } else { - sources += - [ "//chrome/app/theme/$branding_path_component/product_logo_48.png" ] + sources = [ + "//chrome/tools/build/linux/chrome-wrapper", + "//chrome/app/theme/$branding_path_component/product_logo_48.png", + ] } outputs = [ "$root_out_dir/{{source_file_part}}" ] } diff --git a/chrome/app/chrome_main.cc b/chrome/app/chrome_main.cc index 199142d671..1ab8c9596c 100644 --- a/chrome/app/chrome_main.cc +++ b/chrome/app/chrome_main.cc @@ -9,9 +9,11 @@ #include #include #include +#include #include "base/command_line.h" #include "base/environment.h" +#include "base/files/file_path.h" #include "base/functional/bind.h" #include "base/functional/callback_helpers.h" #include "base/logging.h" @@ -32,30 +34,53 @@ #include "partition_alloc/buildflags.h" #if BUILDFLAG(IS_MAC) +#include + +#include + +#include "base/base_paths.h" +#include "base/path_service.h" #include "chrome/app/chrome_main_mac.h" +#include "chrome/common/chrome_paths_internal.h" +#include "chrome/common/chrome_version.h" #include "chrome/common/mac/detect_inappropriate_exit.h" #endif -#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) #include "base/base_switches.h" #endif #if BUILDFLAG(IS_LINUX) +#include +#include +#include +#include + +#include + +#include "base/files/file_util.h" #include "chrome/app/chrome_main_linux.h" +#include "chrome/common/chrome_paths_internal.h" +#include "chrome/common/chrome_version.h" #endif #if BUILDFLAG(IS_WIN) #include +#include +#include + #include "base/dcheck_is_on.h" #include "base/debug/dump_without_crashing.h" #include "base/debug/handle_hooks_win.h" +#include "base/strings/utf_string_conversions.h" #include "base/win/current_module.h" #include "base/win/win_util.h" #include "chrome/chrome_elf/chrome_elf_main.h" #include "chrome/common/chrome_constants.h" #include "chrome/install_static/initialize_from_primary_module.h" #include "chrome/install_static/install_details.h" +#include "chrome/install_static/install_util.h" #define DLLEXPORT __declspec(dllexport) #endif // BUILDFLAG(IS_WIN) @@ -69,6 +94,242 @@ std::optional& GetInitialCommandLineStorage() { return *initial_command_line; } +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) +// Turns a Chromium feature off, merged into any --disable-features already +// given: the last instance of a switch is the one that counts. +void DisableKourFeature(base::CommandLine* command_line, + const std::string& feature) { + std::string disabled = + command_line->GetSwitchValueASCII(::switches::kDisableFeatures); + if (("," + disabled + ",").find("," + feature + ",") == std::string::npos) { + disabled += disabled.empty() ? feature : "," + feature; + command_line->AppendSwitchASCII(::switches::kDisableFeatures, disabled); + } +} + +// What Chromium's field-trial testing config, which every build that is not +// Google's own applies, turns on (macOS and Windows) and Kour keeps off: +// - Chrome's search launcher outside the browser, Omnibox Everywhere (a global +// shortcut, a search box over other apps, a prompt under it to pick that +// shortcut, a menu-bar or taskbar entry that keeps the browser running): +// not Kour's, and nothing of it starts with this off; +// - TreesInViz (layer trees drawn in the GPU process), an experiment Chromium +// has off: there the GPU process stopped on a NOTREACHED in +// cc::LayerTreeHostImpl::CalculateRenderPasses. +void DisableChromiumTrials(base::CommandLine* command_line) { + DisableKourFeature(command_line, "OmniboxEverywhere"); + DisableKourFeature(command_line, "TreesInViz"); +} +#endif // BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) + +#if BUILDFLAG(IS_MAC) +// Kour is the browser, and starts as itself: no launcher passes it these. +// Its data is one directory of its own, the profile and beside it the crash +// database, which Chromium would otherwise keep with every unbranded +// Chromium's on the machine. KOUR_CRASH_DUMPS tells the application the same +// directory: it uploads minidumps from there only. +void ApplyKourBrowserDefaults(base::CommandLine* command_line) { + base::FilePath profile; + if (!chrome::GetKourDefaultUserDataDirectory(&profile)) { + return; + } + // The brand's own directory (chrome_paths.cc): the profile, and beside it + // the crash database. + const base::FilePath data = profile.DirName(); + if (!command_line->HasSwitch(switches::kUserDataDir)) { + command_line->AppendSwitchPath(switches::kUserDataDir, profile); + } + command_line->AppendSwitch(switches::kNoFirstRun); + command_line->AppendSwitch(switches::kNoDefaultBrowserCheck); + DisableChromiumTrials(command_line); + std::unique_ptr env(base::Environment::Create()); + std::optional dumps = env->GetVar("BREAKPAD_DUMP_LOCATION"); + if (!dumps.has_value()) { + dumps = data.Append("Crashpad").value(); + env->SetVar("BREAKPAD_DUMP_LOCATION", dumps.value()); + } + env->SetVar("KOUR_CRASH_DUMPS", dumps.value()); +} +#endif // BUILDFLAG(IS_MAC) + +#if BUILDFLAG(IS_LINUX) +// Kour is the browser, and starts as itself. Its data directory and crash +// database are Chromium's defaults here (chrome_paths_linux.cc), so nothing +// names them; this keeps the directory private, tells the application where +// crash dumps are, and fixes the toolkits the Flutter shell runs under: an +// X11 child window in GTK 3 (Wayland desktops through XWayland). +void ApplyKourBrowserDefaults(base::CommandLine* command_line) { + const base::FilePath data = chrome::GetKourDataRoot(); + if (base::CreateDirectory(data)) { + base::SetPosixFilePermissions(data, 0700); + } + command_line->AppendSwitch(switches::kNoFirstRun); + command_line->AppendSwitch(switches::kNoDefaultBrowserCheck); + if (!command_line->HasSwitch("ozone-platform")) { + command_line->AppendSwitchASCII("ozone-platform", "x11"); + } + if (!command_line->HasSwitch("gtk-version")) { + command_line->AppendSwitchASCII("gtk-version", "3"); + } + std::unique_ptr env(base::Environment::Create()); + if (command_line->GetSwitchValueASCII("ozone-platform") == "x11") { + // GTK must agree with Ozone (someone may have asked for another one). + env->SetVar("GDK_BACKEND", "x11"); + env->SetVar("GDK_GL", ""); + } + // The application uploads minidumps only from the directory Crashpad + // writes to, and checks the two names agree (minidumps.dart). + std::optional dumps = env->GetVar("BREAKPAD_DUMP_LOCATION"); + if (!dumps.has_value()) { + dumps = data.Append("Crashpad").value(); + env->SetVar("BREAKPAD_DUMP_LOCATION", dumps.value()); + } + env->SetVar("KOUR_CRASH_DUMPS", dumps.value()); +} +#endif // BUILDFLAG(IS_LINUX) + +#if BUILDFLAG(IS_WIN) +// Kour is the browser, and starts as itself. Its data directory and crash +// database are Chromium's defaults here (install_static), so nothing names +// them; this tells the application where crash dumps are, and sets what the +// Flutter shell needs in the browser process on Windows: dynamic code allowed +// (Chromium's BrowserDynamicCodeDisabled forbids it there). DirectComposition +// stays on: the shell's picture is on the root window's topmost composition +// target, above the pages' own tree (the panel bridge), not in a child +// window their layers would cover. +// +// On a machine with no graphics adapter of its own (a virtual machine with a +// display-only driver, a server) Chromium composites without +// DirectComposition, and the shell then showed nothing at all: an empty +// window (Kour 2026.10.22 on Windows 11 in a virtual machine). With Direct3D's +// own software adapter asked for by name Chromium presents through +// DirectComposition as on any other machine, which is how the builders have +// always started Kour. +#pragma comment(lib, "dxgi.lib") +bool KourHasGraphicsAdapter() { + Microsoft::WRL::ComPtr factory; + if (FAILED(::CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) { + // Not known: Chromium decides as it always did. + return true; + } + Microsoft::WRL::ComPtr adapter; + for (UINT index = 0; + factory->EnumAdapters1(index, &adapter) != DXGI_ERROR_NOT_FOUND; + ++index) { + DXGI_ADAPTER_DESC1 description = {}; + // 0x1414, 0x8c: the Microsoft Basic Render Driver, which is software. + if (SUCCEEDED(adapter->GetDesc1(&description)) && + !(description.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + !(description.VendorId == 0x1414 && description.DeviceId == 0x8c)) { + return true; + } + adapter.Reset(); + } + return false; +} + +void ApplyKourBrowserDefaults(base::CommandLine* command_line) { + command_line->AppendSwitch(switches::kNoFirstRun); + command_line->AppendSwitch(switches::kNoDefaultBrowserCheck); + if (!command_line->HasSwitch("use-gl") && + !command_line->HasSwitch("use-angle") && + !command_line->HasSwitch("disable-gpu") && !KourHasGraphicsAdapter()) { + command_line->AppendSwitchASCII("use-gl", "angle"); + command_line->AppendSwitchASCII("use-angle", "d3d11-warp"); + } + DisableKourFeature(command_line, "BrowserDynamicCodeDisabled"); + DisableChromiumTrials(command_line); + // The application uploads minidumps only from the directory Crashpad + // writes to, and checks the two names agree (minidumps.dart). + std::unique_ptr env(base::Environment::Create()); + std::optional dumps = env->GetVar("BREAKPAD_DUMP_LOCATION"); + if (!dumps.has_value()) { + dumps = base::WideToUTF8(install_static::GetCrashDumpLocation()); + env->SetVar("BREAKPAD_DUMP_LOCATION", dumps.value()); + } + env->SetVar("KOUR_CRASH_DUMPS", dumps.value()); +} +#endif // BUILDFLAG(IS_WIN) + +#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) +#if BUILDFLAG(IS_MAC) +// Kour's updater (Contents/Frameworks/libkour_updater.dylib, +// hosts/desktop-updater), in the bundle the browser runs from; Velopack's +// UpdateMac beside the executable applies what it downloads. +std::string KourUpdaterPath() { + base::FilePath exe; + if (!base::PathService::Get(base::FILE_EXE, &exe)) { + return std::string(); + } + return exe.DirName() + .DirName() + .Append("Frameworks") + .Append("libkour_updater.dylib") + .value(); +} +#else +// Kour's updater (payload/lib/libkour_updater.so, hosts/desktop-updater), +// beside the browser in its payload. +std::string KourUpdaterPath() { + char exe[PATH_MAX]; + const ssize_t length = readlink("/proc/self/exe", exe, sizeof(exe) - 1); + if (length <= 0) { + return std::string(); + } + std::string path(exe, static_cast(length)); + return path.substr(0, path.rfind('/') + 1) + "payload/lib/libkour_updater.so"; +} +#endif // BUILDFLAG(IS_MAC) + +// The browser process's first call into Kour's updater: Velopack's hooks +// (which exit), then the update checks on a thread of the updater's own. +void StartKourUpdater(int argc, const char** argv) { + void* updater = dlopen(KourUpdaterPath().c_str(), RTLD_NOW | RTLD_LOCAL); + if (!updater) { + return; + } + auto startup = reinterpret_cast( + dlsym(updater, "kour_updater_startup")); + if (startup) { + startup(argc, argv, + std::string_view(KOUR_EXECUTABLE_STRING) == "kour-nightly"); + } +} +#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) + +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) +// The browser's last call into Kour's updater, after its final, successful +// shutdown (a cancelled quit never ends the process): an update the user +// asked for (Kour Nightly: any ready one) starts, and Velopack waits for this +// process to exit. Loaded at the browser's start (Linux and macOS: +// StartKourUpdater; Windows: chrome_exe_main_win.cc); not loaded, nothing +// happens. +void ApplyKourUpdateAfterExit(int rv) { + if (rv != content::RESULT_CODE_NORMAL_EXIT) { + return; + } +#if BUILDFLAG(IS_WIN) + HMODULE updater = ::GetModuleHandleW(L"kour_updater.dll"); + if (!updater) { + return; + } + auto apply = reinterpret_cast( + ::GetProcAddress(updater, "kour_updater_apply_after_exit")); +#else + void* updater = + dlopen(KourUpdaterPath().c_str(), RTLD_NOW | RTLD_LOCAL | RTLD_NOLOAD); + if (!updater) { + return; + } + auto apply = reinterpret_cast( + dlsym(updater, "kour_updater_apply_after_exit")); +#endif + if (apply) { + apply(); + } +} +#endif + } // namespace const base::CommandLine& GetInitialBrowserCommandLine() { @@ -176,15 +437,29 @@ int ChromeMain(int argc, const char** argv) { // Raise the timer interrupt frequency and leave it raised. timeBeginPeriod(1); } + const bool kour_browser = !command_line->HasSwitch(switches::kProcessType); + if (kour_browser) { + ApplyKourBrowserDefaults(command_line); + } #endif #if BUILDFLAG(IS_MAC) chrome::InitializeExitSixtyNineDetector(); SetUpBundleOverrides(); + const bool kour_browser = !command_line->HasSwitch(switches::kProcessType); + if (kour_browser) { + ApplyKourBrowserDefaults(command_line); + StartKourUpdater(argc, argv); + } #endif #if BUILDFLAG(IS_LINUX) AppendExtraArgumentsToCommandLine(command_line); + const bool kour_browser = !command_line->HasSwitch(switches::kProcessType); + if (kour_browser) { + ApplyKourBrowserDefaults(command_line); + StartKourUpdater(argc, argv); + } #endif // PoissonAllocationSampler's TLS slots need to be set up before @@ -224,7 +499,24 @@ int ChromeMain(int argc, const char** argv) { int rv = content::ContentMain(std::move(params)); if (IsNormalResultCode(static_cast(rv))) { - return content::RESULT_CODE_NORMAL_EXIT; + rv = content::RESULT_CODE_NORMAL_EXIT; } +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) + if (kour_browser) { + ApplyKourUpdateAfterExit(rv); + } +#endif +#if BUILDFLAG(IS_LINUX) + // The browser has shut down. Kour's Flutter engines have not: a closed + // window's engine is destroyed two seconds after it leaves the window + // (panel_bridge.cc), and a quit does not wait for that. exit() would run + // the Flutter library's static destructors under their raster threads, + // which then read freed memory, and the quit crashed. Chromium keeps no + // exit-time destructors, so the browser leaves without running any. + if (kour_browser) { + fflush(nullptr); + _exit(rv); + } +#endif return rv; } diff --git a/chrome/app/kour_app_plist.py b/chrome/app/kour_app_plist.py new file mode 100644 index 0000000000..0012458639 --- /dev/null +++ b/chrome/app/kour_app_plist.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +# Kour: the application's Info.plist carries Kour's release, not Chromium's. +"""Writes the Info.plist of a Kour build from Chromium's and Kour's record. + +The record (kour-payload.json) is written with Kour's own code by Kour's +build_payload.py. Its version is Kour's release, which the updater compares; +Chromium's own version stays where Chromium reads it, in its framework. +The document types Kour opens are added to Chromium's, never in their +place: what the browser opens (PDF, HTML, images) stays declared. +""" + +import json +import plistlib +import sys + + +def merge(plist, info): + """Chromium's plist with Kour's record: its values replace Chromium's, + its document types and type declarations follow Chromium's, and a type + Chromium already names is not named again.""" + documents = list(plist.get('CFBundleDocumentTypes', [])) + imported = list(plist.get('UTImportedTypeDeclarations', [])) + handled = {t for d in documents for t in d.get('LSItemContentTypes', [])} + known = {d.get('UTTypeIdentifier') + for d in imported + plist.get('UTExportedTypeDeclarations', [])} + for entry in info.get('CFBundleDocumentTypes', []): + types = [t for t in entry.get('LSItemContentTypes', []) if t not in handled] + if types: + handled.update(types) + documents.append({**entry, 'LSItemContentTypes': types}) + for entry in info.get('UTImportedTypeDeclarations', []): + if entry.get('UTTypeIdentifier') not in known: + known.add(entry.get('UTTypeIdentifier')) + imported.append(entry) + plist.update({k: v for k, v in info.items() + if k not in ('CFBundleDocumentTypes', 'UTImportedTypeDeclarations')}) + if documents: + plist['CFBundleDocumentTypes'] = documents + if imported: + plist['UTImportedTypeDeclarations'] = imported + return plist + + +def main(argv): + source, record, output = argv + with open(source, 'rb') as stream: + plist = plistlib.load(stream) + with open(record, encoding='utf-8') as stream: + info = json.load(stream)['infoPlist'] + merge(plist, info) + with open(output, 'wb') as stream: + plistlib.dump(plist, stream) + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/gritsettings/resource_ids.spec b/tools/gritsettings/resource_ids.spec index 8749c14d44..b3644cd089 100644 --- a/tools/gritsettings/resource_ids.spec +++ b/tools/gritsettings/resource_ids.spec @@ -41,6 +41,14 @@ "chrome/app/google_chrome_strings.grd": { "messages": [800], }, + # Kour and Kour Nightly: written beside Chromium's by Kour's prepare.py; + # one of these is built. + "chrome/app/kour_strings.grd": { + "messages": [800], + }, + "chrome/app/kour_nightly_strings.grd": { + "messages": [800], + }, # Leave lots of space for generated_resources since it has most of our # strings. @@ -1235,6 +1243,12 @@ "components/components_google_chrome_strings.grd": { "messages": [7020], }, + "components/components_kour_strings.grd": { + "messages": [7020], + }, + "components/components_kour_nightly_strings.grd": { + "messages": [7020], + }, "components/components_locale_settings.grd": { "META": {"join": 2}, "includes": [7040], diff --git a/chrome/browser/ui/startup/infobar_utils.cc b/chrome/browser/ui/startup/infobar_utils.cc index 598e361a29..5ab8f99b31 100644 --- a/chrome/browser/ui/startup/infobar_utils.cc +++ b/chrome/browser/ui/startup/infobar_utils.cc @@ -213,9 +213,11 @@ void AddInfoBarsIfNecessary(BrowserWindowInterface* browser, return; } - // Web apps should not display the session restore bubble (crbug.com/40800614) - const bool should_display_bubble = - !is_web_app && HasPendingUncleanExit(browser->GetProfile()); + // Kour never shows the session restore bubble: it is anchored to the + // toolbar, which Kour's shell replaces (AppMenuButton::GetAnchor() then + // fails its CHECK and the browser dies at every start after an unclean + // exit), and Kour reopens what was open itself. + const bool should_display_bubble = false; base::UmaHistogramBoolean("Startup.CrashBubbleShown", should_display_bubble); if (should_display_bubble) { SessionCrashedBubble::ShowIfNotOffTheRecordProfile( diff --git a/chrome/browser/profiles/profile_impl.cc b/chrome/browser/profiles/profile_impl.cc index 81e83a8848..6db5b11296 100644 --- a/chrome/browser/profiles/profile_impl.cc +++ b/chrome/browser/profiles/profile_impl.cc @@ -1272,7 +1272,15 @@ bool ProfileImpl::WasCreatedByVersionOrLater(const std::string& version) { } bool ProfileImpl::ShouldRestoreOldSessionCookies() { -#if BUILDFLAG(IS_ANDROID) +#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) + // Kour reopens the pages that were open itself, at every start, so the + // session they were signed in with goes on. Chromium keeps session cookies + // only when it restores the session's tabs itself (or after a crash): it + // did neither here, so every quit signed its person out of each site that + // signs in with a session cookie, and left others half signed in (a + // remembered account whose session and request tokens were gone). + return true; +#elif BUILDFLAG(IS_ANDROID) SessionStartupPref startup_pref(SessionStartupPref::GetDefaultStartupType()); return startup_pref.ShouldRestoreLastSession(); #else diff --git a/components/os_crypt/common/keychain_password_mac.mm b/components/os_crypt/common/keychain_password_mac.mm index 212b930952..34cf025070 100644 --- a/components/os_crypt/common/keychain_password_mac.mm +++ b/components/os_crypt/common/keychain_password_mac.mm @@ -6,6 +6,10 @@ #import +#include "base/base_paths.h" +#include "base/path_service.h" +#include "base/files/file_util.h" +#include "base/files/file_path.h" #include "base/apple/osstatus_logging.h" #include "base/apple/scoped_cftyperef.h" #include "base/base64.h" @@ -35,8 +39,32 @@ const char kDefaultServiceName[] = "Chrome Safe Storage"; const char kDefaultAccountName[] = "Chrome"; #else -const char kDefaultServiceName[] = "Chromium Safe Storage"; -const char kDefaultAccountName[] = "Chromium"; +// Kour's own item. Under Chromium's unbranded name the key that encrypts +// cookies and saved passwords was one item shared with every Chromium on the +// machine and every differently signed build of Kour: an item whose access a +// build was refused, or that another program replaced, left Kour unable to +// read its cookies or to write new ones, so a site signed out and would not +// stay signed in. +const char kDefaultServiceName[] = "Kour Safe Storage"; +const char kDefaultAccountName[] = "Kour"; +// Where the key was before: read once, so the cookies it encrypted are still +// read. +const char kEarlierServiceName[] = "Chromium Safe Storage"; +const char kEarlierAccountName[] = "Chromium"; +#endif + +#if !BUILDFLAG(GOOGLE_CHROME_BRANDING) +// Whether Kour has run here before and kept cookies: only then is there a +// key under the earlier name worth taking over. A first install has none to +// keep, and does not look. +bool KourHasSavedCookies() { + base::FilePath data; + if (!base::PathService::Get(base::DIR_APP_DATA, &data)) { + return false; + } + return base::PathExists( + data.Append("Kour").Append("Profile").Append("Default").Append("Cookies")); +} #endif // These values are persisted to logs. Entries should not be renumbered and @@ -105,6 +133,40 @@ if (password.error() == errSecItemNotFound) { uma_result = FindGenericPasswordResult::kPasswordNotFound; +#if !BUILDFLAG(GOOGLE_CHROME_BRANDING) + // The first start with Kour's own item: the key the profile's cookies + // were encrypted with, if this build may read it, becomes Kour's. A key + // that cannot be read (refused, or never there) is not waited for. + if (GetServiceName() == kDefaultServiceName && + GetAccountName() == kDefaultAccountName && + KourHasSavedCookies()) { + // Never by asking: a Mac where another Chromium made the earlier item + // would show its person a password prompt for "Chromium Safe Storage" + // at Kour's first start. Readable silently, it is Kour's own (an + // earlier Kour made it); otherwise Kour starts with a key of its own. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + Boolean interactive = true; + SecKeychainGetUserInteractionAllowed(&interactive); + SecKeychainSetUserInteractionAllowed(false); + auto earlier = + keychain_->FindGenericPassword(kEarlierServiceName, kEarlierAccountName); + SecKeychainSetUserInteractionAllowed(interactive); +#pragma clang diagnostic pop + if (earlier.has_value()) { + std::string key(base::as_string_view(*earlier)); + const OSStatus added = keychain_->AddGenericPassword( + GetServiceName(), GetAccountName(), base::as_byte_span(key)); + // The key is the one the cookies were encrypted with whether or not + // it could be saved under Kour's name: this start uses it, and the + // next start takes it over again. + if (added != noErr) { + OSSTATUS_LOG(ERROR, added) << "Keychain add failed"; + } + return key; + } + } +#endif return AddRandomPasswordToKeychain(*keychain_, GetServiceName(), GetAccountName()); } diff --git a/chrome/browser/ui/views/frame/browser_frame_view_mac.mm b/chrome/browser/ui/views/frame/browser_frame_view_mac.mm index 8354a9179e..8fcf6500dc 100644 --- a/chrome/browser/ui/views/frame/browser_frame_view_mac.mm +++ b/chrome/browser/ui/views/frame/browser_frame_view_mac.mm @@ -39,6 +39,7 @@ #include "chrome/browser/ui/views/frame/caption_button_placeholder_container.h" #include "chrome/browser/ui/views/frame/glass_frame_service.h" #include "chrome/browser/ui/views/frame/tab_strip_region_view.h" +#include "chrome/browser/ui/views/side_panel/kour_flutter_panel.h" #include "chrome/browser/ui/views/tabs/tab_strip.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" #include "chrome/browser/ui/views/web_apps/frame_toolbar/web_app_frame_toolbar_utils.h" @@ -253,6 +254,16 @@ FullscreenToolbarStyle GetUserPreferredToolbarStyle(bool always_show) { new_style = FullscreenToolbarStyle::TOOLBAR_NONE; } else { bool always_show = fullscreen_utils::IsAlwaysShowToolbarEnabled(browser); +#if BUILDFLAG(IS_MAC) + // Kour's window has no toolbar to keep on screen: a pinned title bar + // would push Flutter down and leave an empty strip across the top of + // the screen. Only the menu bar comes down when the pointer reaches the + // top edge; the shell's bridge keeps AppKit's title bar window + // invisible, and the shell stays where it is (BrowserView::Layout). + if (GetBrowserView()->GetViewByID(kKourShellViewId)) { + always_show = false; + } +#endif new_style = GetUserPreferredToolbarStyle(always_show); } @@ -387,6 +398,19 @@ FullscreenToolbarStyle GetUserPreferredToolbarStyle(bool always_show) { } int BrowserFrameViewMac::NonClientHitTest(const gfx::Point& point) { + // Kour: a popup's row is its title bar (no title row above it): what is + // not the address or a button drags the window. + if (GetBrowserView()->browser()->GetType() == + BrowserWindowInterface::Type::TYPE_POPUP && + GetBrowserView()->toolbar()) { + views::View* row = GetBrowserView()->toolbar(); + gfx::Point in_row = point; + views::View::ConvertPointToTarget(this, row, &in_row); + if (row->GetVisible() && row->HitTestPoint(in_row) && + row->GetEventHandlerForPoint(in_row) == row) { + return HTCAPTION; + } + } int super_component = BrowserFrameView::NonClientHitTest(point); if (super_component != HTNOWHERE) { return super_component; diff --git a/chrome/browser/ui/views/side_panel/kour_extension_actions.h b/chrome/browser/ui/views/side_panel/kour_extension_actions.h new file mode 100644 index 0000000000..152663d332 --- /dev/null +++ b/chrome/browser/ui/views/side_panel/kour_extension_actions.h @@ -0,0 +1,69 @@ +#ifndef CHROME_BROWSER_UI_VIEWS_SIDE_PANEL_KOUR_EXTENSION_ACTIONS_H_ +#define CHROME_BROWSER_UI_VIEWS_SIDE_PANEL_KOUR_EXTENSION_ACTIONS_H_ + +#include +#include +#include +#include +#include + +#include "base/callback_list.h" +#include "base/memory/raw_ptr.h" +#include "base/memory/weak_ptr.h" +#include "base/scoped_observation.h" +#include "base/values.h" +#include "chrome/browser/ui/toolbar/toolbar_actions_model.h" + +class BrowserWindowInterface; +class ExtensionActionViewModel; +namespace content { class WebContents; } +namespace ui { class ColorProvider; } +namespace views { class View; } + +// Extensions' toolbar actions for Kour's own toolbar. Chromium's toolbar is +// hidden, and with it the place an extension is pinned and clicked; Flutter +// draws the pinned actions instead. It asks for them here, pins and unpins +// them, and runs one with the rectangle of its button, which anchors the +// extension's popup as Chromium's toolbar button would. +class KourExtensionActions : public ToolbarActionsModel::Observer { + public: + KourExtensionActions(BrowserWindowInterface* browser, views::View* host); + ~KourExtensionActions() override; + + // Null when |method| is not one of these commands. |contents| is the page + // the command is for (the shown page), or null. + std::optional Command(std::string_view method, + const base::DictValue& arguments, + content::WebContents* contents, + const ui::ColorProvider* colors); + + // Changes whenever an action is added, removed, pinned or redrawn. + int revision() const { return revision_; } + + private: + ExtensionActionViewModel* Model(const std::string& id); + void CloseAll(); + void Changed() { ++revision_; } + + // ToolbarActionsModel::Observer: + void OnToolbarActionAdded(const ToolbarActionsModel::ActionId& id) override; + void OnToolbarActionRemoved(const ToolbarActionsModel::ActionId& id) override; + void OnToolbarActionUpdated(const ToolbarActionsModel::ActionId& id) override; + void OnToolbarModelInitialized() override; + void OnToolbarPinnedActionsChanged() override; + void OnToolbarActionsModelShutdown() override; + + raw_ptr browser_; + raw_ptr host_; + // Placed over the Flutter button that ran an action: its popup's anchor. + raw_ptr anchor_ = nullptr; + raw_ptr model_; + std::map> models_; + std::map icon_updates_; + base::ScopedObservation + observation_{this}; + int revision_ = 1; + base::WeakPtrFactory weak_factory_{this}; +}; + +#endif diff --git a/chrome/browser/ui/views/side_panel/kour_extension_actions.cc b/chrome/browser/ui/views/side_panel/kour_extension_actions.cc new file mode 100644 index 0000000000..2f624d09e1 --- /dev/null +++ b/chrome/browser/ui/views/side_panel/kour_extension_actions.cc @@ -0,0 +1,552 @@ +#include "chrome/browser/ui/views/side_panel/kour_extension_actions.h" + +#include +#include + +#include "base/base64.h" +#include "base/functional/callback_helpers.h" +#include "base/memory/scoped_refptr.h" +#include "base/memory/weak_ptr.h" +#include "base/strings/utf_string_conversions.h" +#include "base/time/time.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser_window/public/browser_window_interface.h" +#include "chrome/browser/ui/extensions/extension_action_delegate.h" +#include "chrome/browser/ui/extensions/extension_action_view_model.h" +#include "chrome/browser/ui/toolbar/toolbar_action_view_model.h" +#include "chrome/browser/ui/views/extensions/extension_popup.h" +#include "content/public/browser/web_contents.h" +#include "extensions/browser/extension_host.h" +#include "extensions/browser/extension_host_observer.h" +#include "chrome/browser/extensions/extension_view_host.h" +#include "chrome/browser/extensions/webstore_install_with_prompt.h" +#include "components/crx_file/id_util.h" // nogncheck +#include "extensions/browser/extension_registry.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/no_destructor.h" +#include "base/strings/string_split.h" +#include "base/strings/string_util.h" +#include "base/task/thread_pool.h" +#include "chrome/browser/extensions/extension_action_runner.h" +#include "extensions/browser/disable_reason.h" +#include "extensions/browser/extension_registrar.h" +#include "extensions/browser/permissions/scripting_permissions_modifier.h" +#include "extensions/browser/permissions_manager.h" +#include "extensions/browser/uninstall_reason.h" +#include "extensions/browser/unpacked_installer.h" +#include "extensions/common/manifest.h" +#include "extensions/common/manifest_handlers/version_name_info.h" +#include "extensions/common/permissions/permissions_data.h" +#include "extensions/common/extension.h" +#include "ui/base/base_window.h" +#include "ui/gfx/native_ui_types.h" +#include "third_party/skia/include/core/SkBitmap.h" +#include "ui/base/models/image_model.h" +#include "ui/gfx/codec/png_codec.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/size.h" +#include "ui/gfx/image/image_skia.h" +#include "ui/gfx/image/image_skia_rep.h" +#include "ui/views/bubble/bubble_border.h" +#include "ui/views/view.h" + +namespace { + +// Shows an action's popup at the Flutter button that ran it, which the +// anchor view covers. One popup at a time, as in Chromium's toolbar. +class KourActionDelegate : public ExtensionActionDelegate, + public extensions::ExtensionHostObserver { + public: + KourActionDelegate(BrowserWindowInterface* browser, views::View* anchor) + : browser_(browser), anchor_(anchor) {} + ~KourActionDelegate() override { HidePopup(); } + + // A click on the button whose popup is open closes the popup first (the + // window's activation does), and reaches here just after: it must not + // open the popup again. + bool ClosedJustNow() const { + return base::TimeTicks::Now() - closed_ < base::Milliseconds(400); + } + + void AttachToModel(ExtensionActionViewModel* model) override { model_ = model; } + void DetachFromModel() override { model_ = nullptr; } + // Chromium's hidden toolbar keeps the extensions' keyboard shortcuts. + void RegisterCommand() override {} + void UnregisterCommand() override {} + bool IsShowingPopup() const override { return popup_host_ != nullptr; } + void HidePopup() override { + if (!popup_host_) return; + observation_.Reset(); + auto* host = popup_host_.get(); + popup_host_ = nullptr; + if (opened_) host->Close(); + opened_ = false; + closed_ = base::TimeTicks::Now(); + } + gfx::NativeView GetPopupNativeView() override { + if (!popup_host_ || !popup_host_->view()) return gfx::NativeView(); + return popup_host_->view()->GetNativeView(); + } + void TriggerPopup(std::unique_ptr host, + PopupShowAction show_action, + bool by_user, + ShowPopupCallback callback) override { + HidePopup(); + popup_host_ = host.get(); + observation_.Observe(popup_host_.get()); + opened_ = true; + ExtensionPopup::ShowPopup(browser_, std::move(host), + views::BubbleAnchor(anchor_.get()), + views::BubbleBorder::TOP_RIGHT, show_action, + std::move(callback)); + } + // Flutter shows the action's menu itself. + void ShowContextMenuAsFallback() override {} + void CloseExtensionsMenuIfOpen() override {} + + // extensions::ExtensionHostObserver: + void OnExtensionHostDestroyed(extensions::ExtensionHost* host) override { + if (host != popup_host_) return; + observation_.Reset(); + popup_host_ = nullptr; + opened_ = false; + closed_ = base::TimeTicks::Now(); + } + + private: + raw_ptr browser_; + raw_ptr anchor_; + raw_ptr model_ = nullptr; + raw_ptr popup_host_ = nullptr; + bool opened_ = false; + base::TimeTicks closed_; + base::ScopedObservation + observation_{this}; +}; + +// The action's icon, with its badge, as a 2x PNG in base64. +std::string IconPng(ExtensionActionViewModel* model, + content::WebContents* contents, + const ui::ColorProvider* colors) { + const ui::ImageModel image = model->GetIcon(contents, gfx::Size(16, 16)); + if (image.IsEmpty()) return std::string(); + const gfx::ImageSkia skia = image.Rasterize(colors); + if (skia.isNull()) return std::string(); + const gfx::ImageSkiaRep& rep = skia.GetRepresentation(2.0f); + if (rep.is_null()) return std::string(); + auto png = gfx::PNGCodec::EncodeBGRASkBitmap(rep.GetBitmap(), + /*discard_transparency=*/false); + return png ? base::Base64Encode(*png) : std::string(); +} + +// Whether extension `id` came from the store: what another of the person's +// devices could install too. +bool FromStore(Profile* profile, const std::string& id) { + const extensions::Extension* extension = + extensions::ExtensionRegistry::Get(profile)->GetInstalledExtension(id); + return extension && extension->from_webstore(); +} + +// Kour's helpers: extensions the person's assistant wrote, each a folder of +// its own under the profile, loaded unpacked once the person said yes (Kour +// asks, in its own words, before it adds one). These commands touch nothing +// outside that folder. +constexpr char kHelpersDir[] = "Kour Helpers"; +constexpr size_t kMaxHelperBytes = 4 * 1024 * 1024; + +base::FilePath HelpersRoot(Profile* profile) { + return profile->GetPath().AppendASCII(kHelpersDir); +} + +// A helper's folder name: what Kour names it by (its library file's id). +bool ValidHelperName(const std::string& name) { + if (name.empty() || name.size() > 64) return false; + for (char c : name) { + if (!(base::IsAsciiAlphaNumeric(c) || c == '-' || c == '_')) return false; + } + return true; +} + +// A file's path in its folder: relative and plain, never climbing out. +bool ValidHelperPath(const std::string& path) { + if (path.empty() || path.size() > 200 || path.front() == '/') return false; + for (const auto& part : base::SplitStringPiece( + path, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL)) { + // (no part ending in a dot: Windows drops it, and `x.` would be written + // over `x`) + if (part.empty() || part == "." || part == ".." || part.back() == '.') { + return false; + } + for (char c : part) { + if (!(base::IsAsciiAlphaNumeric(c) || c == '-' || c == '_' || + c == '.')) { + return false; + } + } + } + return true; +} + +// The helper `id`, enabled or not, when Kour wrote it (unpacked, in Kour's +// folder); null for any other extension. +const extensions::Extension* Helper(Profile* profile, const std::string& id) { + const extensions::Extension* extension = + extensions::ExtensionRegistry::Get(profile)->GetInstalledExtension(id); + if (!extension || + extension->location() != extensions::mojom::ManifestLocation::kUnpacked || + !HelpersRoot(profile).IsParent(extension->path())) { + return nullptr; + } + return extension; +} + +// On a blocking thread: the folder replaced whole by `files`. +bool WriteHelper(const base::FilePath& dir, + std::vector> files) { + if (!base::DeletePathRecursively(dir) || !base::CreateDirectory(dir)) { + return false; + } + for (const auto& [path, text] : files) { + const base::FilePath file = dir.AppendASCII(path); + // (the folder is new: a file already there is another name for one just + // written — a disk that does not tell case apart — and what was checked + // would not be what runs) + if (base::PathExists(file) || !base::CreateDirectory(file.DirName()) || + !base::WriteFile(file, text)) { + return false; + } + } + return true; +} + +// Why a helper last failed to load, by its folder's name. +std::map& HelperErrors() { + static base::NoDestructor> errors; + return *errors; +} + +} // namespace + +KourExtensionActions::KourExtensionActions(BrowserWindowInterface* browser, + views::View* host) + : browser_(browser), + host_(host), + model_(ToolbarActionsModel::Get(browser->GetProfile())) { + if (model_) observation_.Observe(model_.get()); +} + +KourExtensionActions::~KourExtensionActions() { + icon_updates_.clear(); + CloseAll(); + if (anchor_ && anchor_->parent()) { + anchor_->parent()->RemoveChildViewT(anchor_.get()); + } + anchor_ = nullptr; +} + +void KourExtensionActions::CloseAll() { + // A model's popup closes before the model goes. + for (auto& [id, model] : models_) model->HidePopup(); + models_.clear(); +} + +ExtensionActionViewModel* KourExtensionActions::Model(const std::string& id) { + if (!model_ || !model_->HasAction(id)) return nullptr; + if (auto it = models_.find(id); it != models_.end()) return it->second.get(); + if (!anchor_) { + if (!host_ || !host_->parent()) return nullptr; + anchor_ = host_->parent()->AddChildView(std::make_unique()); + anchor_->SetBounds(0, 0, 0, 0); + // It marks a place and takes no input. Left where a popup hung from, it + // was the view under the pointer there, ahead of the Flutter panel + // behind it: a button that had opened its popup once took no more + // clicks until the window was resized. + anchor_->SetCanProcessEventsWithinSubtree(false); + } + auto view_model = ExtensionActionViewModel::Create( + id, browser_.get(), + std::make_unique(browser_.get(), anchor_.get())); + auto* raw = view_model.get(); + icon_updates_[id] = raw->RegisterIconUpdateObserver(base::BindRepeating( + &KourExtensionActions::Changed, base::Unretained(this))); + models_[id] = std::move(view_model); + return raw; +} + +std::optional KourExtensionActions::Command( + std::string_view method, + const base::DictValue& arguments, + content::WebContents* contents, + const ui::ColorProvider* colors) { + if (method == "extensionActions") { + base::ListValue actions; + if (model_ && model_->actions_initialized()) { + // Pinned first, in the order they were pinned in; then the rest. + std::vector ids(model_->pinned_action_ids().begin(), + model_->pinned_action_ids().end()); + for (const auto& id : model_->action_ids()) { + if (!model_->IsActionPinned(id)) ids.push_back(id); + } + for (const auto& id : ids) { + auto* action = Model(id); + if (!action) continue; + actions.Append( + base::DictValue() + .Set("id", id) + .Set("name", base::UTF16ToUTF8(action->GetActionName())) + .Set("tooltip", base::UTF16ToUTF8(action->GetTooltip(contents))) + .Set("pinned", model_->IsActionPinned(id)) + .Set("forcePinned", model_->IsActionForcePinned(id)) + .Set("enabled", contents && action->IsEnabled(contents)) + .Set("store", FromStore(browser_->GetProfile(), id)) + .Set("icon", IconPng(action, contents, colors))); + } + } + // Kour's helpers, enabled or not, by their folder's name. + base::ListValue helpers; + Profile* profile = browser_->GetProfile(); + const auto* registry = extensions::ExtensionRegistry::Get(profile); + for (const auto& extension : registry->GenerateInstalledExtensionsSet()) { + if (!Helper(profile, extension->id())) continue; + helpers.Append( + base::DictValue() + .Set("id", extension->id()) + .Set("name", extension->path().BaseName().AsUTF8Unsafe()) + .Set("on", registry->enabled_extensions().Contains(extension->id())) + .Set("versionName", extensions::VersionNameInfo::GetVersionName(*extension)) + .Set("withheld", + extensions::PermissionsManager::Get(profile) + ->HasWithheldHostPermissions(*extension))); + } + base::DictValue errors; + for (const auto& [name, error] : HelperErrors()) errors.Set(name, error); + return base::DictValue() + .Set("revision", revision_) + .Set("actions", std::move(actions)) + .Set("helpers", std::move(helpers)) + .Set("helperErrors", std::move(errors)); + } + if (method == "extensionActionHelper") { + // A helper Kour wrote: its files written to its folder, then loaded (one + // loaded already is loaded again, as it now is). The listing's revision + // says when it is in, or `helperErrors` why not. + Profile* profile = browser_->GetProfile(); + const auto* name = arguments.FindString("name"); + const auto* files = arguments.FindDict("files"); + if (!name || !ValidHelperName(*name) || !files || files->empty()) { + return base::DictValue().Set("error", "invalid_helper"); + } + std::vector> written; + size_t bytes = 0; + for (const auto [path, text] : *files) { + if (!ValidHelperPath(path) || !text.is_string()) { + return base::DictValue().Set("error", "invalid_helper"); + } + bytes += text.GetString().size(); + written.emplace_back(path, text.GetString()); + } + if (bytes > kMaxHelperBytes) { + return base::DictValue().Set("error", "invalid_helper"); + } + const base::FilePath dir = HelpersRoot(profile).AppendASCII(*name); + // Off, or held to a Space, from the moment it is in: set before any page + // it names can load with it. + const bool on = arguments.FindBool("on").value_or(true); + const bool withheld = arguments.FindBool("withheld").value_or(false); + HelperErrors().erase(*name); + base::ThreadPool::PostTaskAndReplyWithResult( + FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::BindOnce(&WriteHelper, dir, std::move(written)), + base::BindOnce( + [](base::WeakPtr weak, base::FilePath dir, + std::string name, bool on, bool withheld, + base::RepeatingClosure changed, bool ok) { + Profile* profile = weak.get(); + if (!profile) return; + if (!ok) { + HelperErrors()[name] = "not_written"; + changed.Run(); + return; + } + auto installer = extensions::UnpackedInstaller::Create(profile); + installer->set_be_noisy_on_failure(false); + installer->set_completion_callback(base::BindOnce( + [](base::WeakPtr weak, std::string name, bool on, + bool withheld, base::RepeatingClosure changed, + const extensions::Extension* extension, + const base::FilePath&, const std::u16string& error) { + Profile* profile = weak.get(); + if (!extension) { + HelperErrors()[name] = base::UTF16ToUTF8(error); + } else if (profile) { + if (withheld) { + extensions::ScriptingPermissionsModifier(profile, extension) + .SetWithholdHostPermissions(true); + } + if (!on) { + extensions::ExtensionRegistrar::Get(profile)->DisableExtension( + extension->id(), + {extensions::disable_reason::DISABLE_USER_ACTION}); + } + } + changed.Run(); + }, + weak, name, on, withheld, changed)); + installer->Load(dir); + }, + profile->GetWeakPtr(), dir, *name, on, withheld, + base::BindRepeating(&KourExtensionActions::Changed, + weak_factory_.GetWeakPtr()))); + return base::DictValue().Set("started", true); + } + if (method == "extensionActionSetEnabled" || + method == "extensionActionRemove" || + method == "extensionActionWithhold" || + method == "extensionActionGrantPage") { + Profile* profile = browser_->GetProfile(); + const auto* id = arguments.FindString("id"); + const extensions::Extension* helper = id ? Helper(profile, *id) : nullptr; + if (!helper) return base::DictValue().Set("error", "invalid_helper"); + auto* registrar = extensions::ExtensionRegistrar::Get(profile); + if (method == "extensionActionSetEnabled") { + const auto on = arguments.FindBool("on"); + if (!on) return base::DictValue().Set("error", "invalid_helper"); + if (*on) { + registrar->EnableExtension(*id); + } else { + registrar->DisableExtension( + *id, {extensions::disable_reason::DISABLE_USER_ACTION}); + } + } else if (method == "extensionActionRemove") { + // Uninstalled, and its folder gone with it. + const base::FilePath dir = helper->path(); + const std::string helper_id = *id; + std::u16string error; + registrar->UninstallExtension( + helper_id, extensions::UNINSTALL_REASON_USER_INITIATED, &error); + base::ThreadPool::PostTask( + FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::GetDeletePathRecursivelyCallback(dir)); + } else if (method == "extensionActionWithhold") { + // Held to a Space: its sites held back everywhere, then given page by + // page (`extensionActionGrantPage`) where the page is in that Space. + const auto on = arguments.FindBool("on"); + if (!on) return base::DictValue().Set("error", "invalid_helper"); + extensions::ScriptingPermissionsModifier(profile, helper) + .SetWithholdHostPermissions(*on); + } else { + // This page alone, while it stays on its site, and only for a site the + // helper names and was held back from. + if (!contents) return base::DictValue().Set("error", "invalid_page_id"); + if (!helper->permissions_data() + ->withheld_permissions() + .effective_hosts() + .MatchesURL(contents->GetLastCommittedURL())) { + return base::DictValue().Set("granted", false); + } + auto* runner = + extensions::ExtensionActionRunner::GetForWebContents(contents); + if (!runner) return base::DictValue().Set("granted", false); + runner->GrantTabPermissions({helper}); + return base::DictValue().Set("granted", true); + } + Changed(); + return base::DictValue().Set("revision", revision_); + } + if (method == "extensionActionInstall") { + // An extension another of the person's devices has: the store's own + // question (what it may do, Add or Cancel) over this window, and it is + // installed only on Add. + const auto* id = arguments.FindString("id"); + if (!id || !crx_file::id_util::IdIsValid(*id)) { + return base::DictValue().Set("error", "invalid_extension"); + } + gfx::NativeWindow window = gfx::NativeWindow(); + if (browser_->GetWindow()) window = browser_->GetWindow()->GetNativeWindow(); + // The installer keeps itself until it has finished. + base::MakeRefCounted( + *id, browser_->GetProfile(), window, base::DoNothing()) + ->BeginInstall(); + return base::DictValue().Set("started", true); + } + if (method == "extensionActionPin") { + const auto* id = arguments.FindString("id"); + const auto pinned = arguments.FindBool("pinned"); + if (!id || !pinned || !model_ || !model_->HasAction(*id)) { + return base::DictValue().Set("error", "invalid_action"); + } + model_->SetActionVisibility(*id, *pinned); + return base::DictValue().Set("revision", revision_); + } + if (method == "extensionActionRun") { + const auto* id = arguments.FindString("id"); + auto* action = id ? Model(*id) : nullptr; + if (!action || !contents) { + return base::DictValue().Set("error", "invalid_action"); + } + // The popup hangs from the button Flutter drew, in this view's + // coordinates (the shell fills the window). + const auto x = arguments.FindDouble("x"), y = arguments.FindDouble("y"); + const auto width = arguments.FindDouble("width"), + height = arguments.FindDouble("height"); + if (!x || !y || !width || !height || *x < 0 || *y < 0 || *width < 0 || + *height < 0 || *x > 100000 || *y > 100000 || *width > 1000 || + *height > 1000) { + return base::DictValue().Set("error", "invalid_geometry"); + } + // From the shell's coordinates to its parent's, where the anchor is. + gfx::Rect bounds(static_cast(*x), static_cast(*y), + static_cast(*width), static_cast(*height)); + if (host_ && anchor_->parent()) { + bounds = views::View::ConvertRectToTarget(host_.get(), anchor_->parent(), + bounds); + } + anchor_->SetBoundsRect(bounds); + auto* delegate = static_cast(action->delegate()); + if (action->IsShowingPopup()) { + action->HidePopup(); + } else if (!delegate->ClosedJustNow()) { + action->ExecuteUserAction( + ToolbarActionViewModel::InvocationSource::kToolbarButton); + } + return base::DictValue().Set("revision", revision_); + } + return std::nullopt; +} + +void KourExtensionActions::OnToolbarActionAdded( + const ToolbarActionsModel::ActionId& id) { + Changed(); +} + +void KourExtensionActions::OnToolbarActionRemoved( + const ToolbarActionsModel::ActionId& id) { + icon_updates_.erase(id); + if (auto it = models_.find(id); it != models_.end()) { + it->second->HidePopup(); + models_.erase(it); + } + Changed(); +} + +void KourExtensionActions::OnToolbarActionUpdated( + const ToolbarActionsModel::ActionId& id) { + Changed(); +} + +void KourExtensionActions::OnToolbarModelInitialized() { + Changed(); +} + +void KourExtensionActions::OnToolbarPinnedActionsChanged() { + Changed(); +} + +void KourExtensionActions::OnToolbarActionsModelShutdown() { + icon_updates_.clear(); + CloseAll(); + observation_.Reset(); + model_ = nullptr; +} diff --git a/chrome/browser/ui/views/side_panel/kour_flutter_panel_desktop.cc b/chrome/browser/ui/views/side_panel/kour_flutter_panel_desktop.cc new file mode 100644 index 0000000000..5c93833146 --- /dev/null +++ b/chrome/browser/ui/views/side_panel/kour_flutter_panel_desktop.cc @@ -0,0 +1,2232 @@ +#include "chrome/browser/ui/views/side_panel/kour_flutter_panel.h" +#include "chrome/browser/ui/views/side_panel/kour_popup_window.h" +#include "chrome/browser/ui/views/side_panel/kour_sign_in_window.h" +#include "components/input/native_web_keyboard_event.h" +#include "chrome/browser/ui/views/side_panel/kour_browser_data.h" +#include "chrome/browser/ui/views/side_panel/kour_extension_actions.h" +#include "chrome/browser/ui/views/side_panel/kour_browser_host.h" +#include "chrome/browser/ui/views/side_panel/kour_page_agent.h" +#include "chrome/browser/ui/views/side_panel/kour_page_input.h" +#include "chrome/browser/ui/views/side_panel/kour_page_media.h" +#include "chrome/browser/ui/views/side_panel/kour_page_print.h" +#include "chrome/browser/ui/views/side_panel/kour_page_bell.h" +#include "chrome/browser/ui/views/side_panel/kour_context_menu.h" +#include "chrome/browser/ui/views/side_panel/kour_file_handoff.h" +#include "chrome/browser/download/kour_download_folders.h" +#include "chrome/browser/ui/views/side_panel/kour_mail_body.h" +#include "chrome/browser/ui/views/side_panel/kour_page_switch.h" +#include "chrome/browser/ui/views/side_panel/kour_spaces.h" + +#include "base/native_library.h" +#include "base/base_paths.h" +#include "base/path_service.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/no_destructor.h" +#include "base/task/task_traits.h" +#include "base/task/thread_pool.h" +#include "content/public/common/mhtml_generation_params.h" +#include "base/task/single_thread_task_runner.h" +#include "build/build_config.h" +#include "ui/aura/window.h" +#include "ui/aura/window_tree_host.h" +#include "ui/compositor/compositor.h" +#include "ui/views/widget/widget.h" +#if BUILDFLAG(IS_WIN) +#include "chrome/browser/kour_taskbar_badge.h" // nogncheck +#include "chrome/browser/taskbar/taskbar_decorator_win.h" +#include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h" +#endif +#include "ui/events/event_handler.h" +#include "ui/events/event.h" +#include "ui/events/keycodes/keyboard_codes.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "base/base64.h" +#include "base/check.h" +#include "base/containers/span.h" +#include "base/task/cancelable_task_tracker.h" +#include "base/callback_list.h" +#include "base/timer/timer.h" +#include "chrome/browser/devtools/devtools_window.h" +#include "content/public/browser/web_contents.h" +#include "third_party/blink/public/mojom/frame/sudden_termination_disabler_type.mojom.h" +#include "base/functional/bind.h" +#include "base/memory/weak_ptr.h" +#include "base/memory/raw_ptr.h" +#include "base/time/time.h" +#include "base/json/json_reader.h" +#include "base/json/json_writer.h" +#include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/ui/browser_window/public/browser_window_interface.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/browser/favicon/favicon_service_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "components/favicon/core/favicon_service.h" +#include "components/favicon_base/favicon_types.h" +#include "components/keyed_service/core/service_access_type.h" +#include "content/public/browser/favicon_status.h" +#if BUILDFLAG(IS_WIN) +#include "ui/views/win/hwnd_util.h" +#include "content/public/browser/context_factory.h" +#include "content/public/browser/gpu_data_manager.h" +#include "content/public/browser/gpu_data_manager_observer.h" +#include "gpu/config/gpu_info.h" +#endif +#include "content/public/browser/navigation_entry.h" +#include "chrome/browser/ui/browser_tabstrip.h" +#include "chrome/browser/ui/navigator/browser_navigator.h" +#include "chrome/browser/ui/navigator/browser_navigator_params.h" +#include "chrome/browser/lifetime/application_lifetime.h" +#include "chrome/browser/lifetime/browser_shutdown.h" +#include "chrome/browser/lifetime/termination_notification.h" +#include "base/strings/string_number_conversions.h" +#include "components/keep_alive_registry/keep_alive_registry.h" +#include "components/keep_alive_registry/keep_alive_types.h" +#include "components/keep_alive_registry/scoped_keep_alive.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/ui/browser_commands.h" +#include "components/keep_alive_registry/keep_alive_state_observer.h" +#include "chrome/browser/ui/browser_window/public/browser_window_interface_iterator.h" +#include "chrome/browser/ui/unload_controller.h" +#include "chrome/browser/ui/views/frame/multi_contents_view.h" +#include "chrome/browser/ui/views/frame/browser_native_widget.h" +#include "chrome/browser/ui/views/frame/browser_widget.h" +#include "ui/views/window/frame_buttons.h" +#include "ui/views/window/window_button_order_provider.h" +#include "ui/views/widget/widget_observer.h" +#include "base/scoped_observation.h" +#if BUILDFLAG(IS_LINUX) +#include "ui/linux/linux_ui.h" +#include "ui/linux/window_button_order_observer.h" +#endif +#include "base/task/sequenced_task_runner.h" +#include "content/public/browser/navigation_controller.h" +#include "content/public/browser/browser_accessibility_state.h" +#include "content/public/browser/scoped_accessibility_mode.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/render_frame_host.h" +#include "chrome/common/chrome_isolated_world_ids.h" +#include "content/public/browser/render_widget_host_view.h" +#include "components/tabs/public/tab_interface.h" +#include "base/check_op.h" +#include "base/logging.h" +#include "chrome/browser/ui/views/side_panel/kour_desktop_panel_abi.h" +#if BUILDFLAG(IS_LINUX) +#include "chrome/browser/ui/views/side_panel/kour_shell_frames.h" +#include "ui/gfx/x/atom_cache.h" // nogncheck +#include "ui/gfx/x/connection.h" // nogncheck +#include "ui/views/view_tracker.h" +#endif +#include "ui/base/base_window.h" +#include "url/url_constants.h" +#include "ui/base/metadata/metadata_header_macros.h" +#include "ui/base/metadata/metadata_impl_macros.h" +#include "ui/base/page_transition_types.h" +#include "ui/base/window_open_disposition.h" +#include "url/origin.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/size.h" +#include "ui/gfx/native_ui_types.h" +#include "url/gurl.h" +#include "ui/accessibility/ax_enums.mojom.h" +#include "ui/views/accessibility/view_accessibility.h" +#include "ui/views/view.h" + +namespace { + +// Kour's own code, put beside the browser by its build (chrome/BUILD.gn, +// kour_payload_dir): nothing has to tell the browser where it is. +base::FilePath KourPayload() { + base::FilePath executable_dir; + CHECK(base::PathService::Get(base::DIR_EXE, &executable_dir)); + return executable_dir.Append(FILE_PATH_LITERAL("payload")); +} + +// Kour stays when its last window closes (the tray on Windows and Linux; +// kour/resident): that window's close is then not a quit. +bool& Stays() { + static bool stays = false; + return stays; +} + +// What the application asks of the browser while no window may be open +// (ABI 9): staying, a new window, quitting, the unread count on the taskbar. +const char* ApplicationCommand(const char* method, const char* arguments) { + static base::NoDestructor answer; + static base::NoDestructor> keep_alive; + const std::string_view name(method ? method : ""); + const auto args = base::JSONReader::ReadDict(arguments ? arguments : "{}", base::JSON_PARSE_RFC); + *answer = R"({"ok":true})"; + if (name == "stay") { + // Any quit, not only the tray's (Kour's own Quit, the system ending the + // session), lets go of the browser: it must not stay alive with every + // window closed, the core never told it ended. + static base::NoDestructor watching; + if (!*watching) { + // Kept for the process's life: a dropped subscription ends the watch. + *watching = browser_shutdown::AddAppTerminatingCallback(base::BindOnce([] { + Stays() = false; + keep_alive->reset(); + })); + } + Stays() = args && args->FindBool("on").value_or(false); + if (!Stays()) { + keep_alive->reset(); + } else if (!*keep_alive) { + *keep_alive = std::make_unique(KeepAliveOrigin::BACKGROUND_MODE_MANAGER, + KeepAliveRestartOption::DISABLED); + } + } else if (name == "openWindow") { + if (Profile* profile = ProfileManager::GetLastUsedProfileAllowedByPolicy()) { + chrome::NewEmptyWindow(profile); + } else { + *answer = R"({"error":"no_profile"})"; + } + } else if (name == "badge") { +#if BUILDFLAG(IS_WIN) + // The unread mail on every window's taskbar button, as Chrome draws an + // installed web app's badge (taskbar_decorator_win: a 16 px overlay, "99+" + // past 99); none takes it away, or brings the profile's avatar back. + const int count = args ? args->FindInt("count").value_or(0) : 0; + const std::string* label = args ? args->FindString("label") : nullptr; + auto& badge = kour::CurrentTaskbarBadge(); + badge.text = count <= 0 ? std::string() : count > 99 ? std::string("99+") : base::NumberToString(count); + badge.label = label ? *label : std::string(); + for (BrowserWindowInterface* browser : GetAllBrowserWindowInterfaces()) { + gfx::NativeWindow window = browser->GetWindow()->GetNativeWindow(); + if (badge.text.empty()) { + taskbar::UpdateTaskbarDecoration(browser->GetProfile(), window); + } else { + taskbar::DrawTaskbarDecorationString(window, badge.text, badge.label); + } + } +#endif + } else if (name == "quit") { + // For good: the tray's Quit. Nothing keeps the browser any more. + Stays() = false; + keep_alive->reset(); + chrome::AttemptExit(); + } else { + *answer = R"({"error":"unknown_method"})"; + } + return answer->c_str(); +} + +struct PanelModule { + PanelModule() { +#if BUILDFLAG(IS_WIN) + const base::FilePath path = KourPayload().Append(FILE_PATH_LITERAL("kour_panel.dll")); +#else + const base::FilePath path = + KourPayload().Append(FILE_PATH_LITERAL("lib")).Append(FILE_PATH_LITERAL("libkour_panel.so")); +#endif + // Process-lifetime load: Flutter/plugins register global types and callbacks. + // LoadNativeLibrary uses LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR on Windows. + base::NativeLibraryLoadError error; + base::NativeLibrary module = base::LoadNativeLibrary(path, &error); + CHECK(module) << error.ToString(); + auto symbol = [module](const char* name) { + return base::GetFunctionPointerFromNativeLibrary(module, name); + }; + auto version = reinterpret_cast(symbol("KourPanelAbiVersion")); + CHECK(version); + CHECK_EQ(version(), 10u); + create = reinterpret_cast(symbol("KourCreateDesktopPanel")); + resize = reinterpret_cast(symbol("KourResizeDesktopPanel")); + show = reinterpret_cast(symbol("KourShowDesktopPanel")); + focus = reinterpret_cast(symbol("KourFocusDesktopPanel")); + focus_parent = reinterpret_cast(symbol("KourFocusDesktopParent")); + command = reinterpret_cast(symbol("KourDesktopPanelCommand")); + page_event = reinterpret_cast(symbol("KourDesktopPanelPageEvent")); + ending = reinterpret_cast(symbol("KourDesktopApplicationEnding")); + destroy = reinterpret_cast(symbol("KourDestroyPanel")); + prepare_close = reinterpret_cast(symbol("KourPreparePanelClose")); + set_frame_sink = reinterpret_cast(symbol("KourSetDesktopPanelFrameSink")); + CHECK(create && resize && show && focus && focus_parent && command && page_event && destroy && prepare_close && + set_frame_sink); + auto set_application = reinterpret_cast( + symbol("KourSetDesktopApplicationCommand")); + CHECK(set_application); + set_application(&ApplicationCommand); + } + decltype(&KourCreateDesktopPanel) create = nullptr; + decltype(&KourResizeDesktopPanel) resize = nullptr; + decltype(&KourShowDesktopPanel) show = nullptr; + decltype(&KourFocusDesktopPanel) focus = nullptr; + decltype(&KourFocusDesktopParent) focus_parent = nullptr; + decltype(&KourDesktopPanelCommand) command = nullptr; + decltype(&KourDesktopPanelPageEvent) page_event = nullptr; + decltype(&KourDesktopApplicationEnding) ending = nullptr; + decltype(&KourDestroyPanel) destroy = nullptr; + decltype(&KourPreparePanelClose) prepare_close = nullptr; + // Only where the browser's compositor draws the shell over the pages (X11). + decltype(&KourSetDesktopPanelFrameSink) set_frame_sink = nullptr; +}; + +PanelModule& Module() { + // Trivially destructible; no exit-time teardown or dlclose is registered. + static PanelModule module; + return module; +} + +void Record(std::string_view kind) { + LOG(INFO) << "KOUR_EVENT {\"surface\":\"chromium-native-host\",\"kind\":\"" + << kind << "\"}"; +} + +// The process ends when nothing keeps the browser alive, not when Kour's last +// window goes: a sign-in popup (a window with no Kour) or background work +// keeps it, and a window opened after has the core open still. As it ends, +// the application's Dart closes what it holds (after the browser's own +// teardown of the last window, not inside it). +class ApplicationEnding : public KeepAliveStateObserver { + public: + static void Watch() { static base::NoDestructor watcher; } + + ApplicationEnding() { KeepAliveRegistry::GetInstance()->AddObserver(this); } + + void OnKeepAliveStateChanged(bool is_keeping_alive) override { + if (is_keeping_alive || told_) return; + base::SequencedTaskRunner::GetCurrentDefault()->PostTask(FROM_HERE, base::BindOnce(&ApplicationEnding::Tell)); + } + void OnKeepAliveRestartStateChanged(bool) override {} + + private: + static void Tell() { + // (not before the browser has started: nothing is ending then) + if (told_ || !KeepAliveRegistry::GetInstance()->IsShuttingDown() || !Module().ending) return; + told_ = true; + Module().ending(); + } + + static inline bool told_ = false; +}; + +class KourFlutterPanel final : public views::View +#if BUILDFLAG(IS_WIN) + , + public content::GpuDataManagerObserver +#endif +{ + METADATA_HEADER(KourFlutterPanel, views::View) + + public: + explicit KourFlutterPanel(BrowserWindowInterface* browser) + : browser_(browser), browser_data_(browser->GetProfile()), extensions_(browser, this), + mail_bodies_(browser), panel_(nullptr, Module().destroy) { + All().insert(this); + ApplicationEnding::Watch(); + SetID(kKourShellViewId); + SetFocusBehavior(FocusBehavior::ALWAYS); + // This Views node is the focus gateway to the separate native Flutter + // tree. Keep it named and semantic even before that tree is available. + GetViewAccessibility().SetRole(ax::mojom::Role::kPane); + GetViewAccessibility().SetName(u"Kour"); + kour::WatchDownloadsForHandoff(browser->GetProfile()); + // (the Spaces' folders as last said, for a download before the shell speaks) + kour::LoadSpaceDownloadFolders(browser->GetProfile()); + SweepArchives(browser->GetProfile()->GetPath()); + // Kour's documents printed in a mail body, a note's PDF; a body's ⌘P told + // to the shell (compat-fixes B7). + mail_bodies_.SetPrinting(&prints_, base::BindRepeating( + [](KourFlutterPanel* self, base::DictValue event) { self->SendPageEvent(event); }, + base::Unretained(this))); + page_menu_id_ = kour::AddPageMenu( + base::BindRepeating([](base::WeakPtr self, content::WebContents* contents) { + return self ? self->MenuItemsFor(contents) : std::vector(); + }, weak_factory_.GetWeakPtr()), + base::BindRepeating([](base::WeakPtr self, content::WebContents* contents, + const std::string& item, const std::u16string& text) { + if (self) self->MenuChosen(contents, item, text); + }, weak_factory_.GetWeakPtr())); + + // A close that is refused, by anyone (a save that failed here, a page's + // "Leave site?", a download still running): the window this panel hid + // for the close is shown again. + close_cancelled_ = browser->RegisterBrowserCloseCancelled(base::BindRepeating( + [](base::WeakPtr self, BrowserWindowInterface*, + BrowserWindowInterface::ClosingStatus status) { + if (self) self->CloseRefused(status); + }, + weak_factory_.GetWeakPtr())); + // This window's page commands are the browser host's too: the assistant's browser tool drives the pages from the core. + // Never a private window's (P16): the assistant is not given its pages or its session. + if (!browser_->GetProfile()->IsOffTheRecord()) export_id_ = kour::BrowserHostExport::Get().AddPanel(base::BindRepeating( + [](base::WeakPtr self, std::string_view method, std::string_view arguments) -> std::string { + return self ? self->Command(method, arguments) : std::string(R"({"error":"page_not_open"})"); + }, + weak_factory_.GetWeakPtr())); +#if BUILDFLAG(IS_WIN) + content::GpuDataManager::GetInstance()->AddObserver(this); + direct_composition_ = DirectComposition(); +#endif + } + + ~KourFlutterPanel() override { + All().erase(this); + kour::RemovePageMenu(page_menu_id_); + weak_factory_.InvalidateWeakPtrs(); + // Archives nobody collected: their files go with the window. + for (const auto& [ticket, job] : archives_) RemoveArchive(job.path); + // No shell here any more: links are tabs again. + kour::TakeExternalLinks(browser_, false); + // A sign-in window belongs to the window that opened it. + sign_in_.reset(); + if (export_id_ >= 0) kour::BrowserHostExport::Get().RemovePanel(export_id_); + if (event_root_) event_root_->RemovePreTargetHandler(&focus_handler_); +#if BUILDFLAG(IS_WIN) + content::GpuDataManager::GetInstance()->RemoveObserver(this); +#endif + ReleasePanel(); + Record("destroyed"); + } + + void AddedToWidget() override { + views::View::AddedToWidget(); + chrome_watch_.Watch(GetWidget()); + event_root_ = GetWidget()->GetNativeWindow()->GetRootWindow(); + event_root_->AddPreTargetHandler(&focus_handler_); +#if BUILDFLAG(IS_WIN) + // Widget::Init still has to initialize BrowserWindowFeatures. Creating or + // resizing the Flutter HWND can synchronously SetFocus and activate its + // parent, re-entering BrowserView before its extension registry exists. + // Start on the next UI task, after the browser window finishes construction. + base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( + FROM_HERE, base::BindOnce(&KourFlutterPanel::InitializeNativePanel, + weak_factory_.GetWeakPtr())); +#else + InitializeNativePanel(); +#endif + } + + void InitializeNativePanel() { + if (!GetWidget() || panel_) return; + if (!panel_) { + const std::string payload = KourPayload().AsUTF8Unsafe(); + auto native = GetWidget()->GetNativeWindow()->GetHost()->GetAcceleratedWidget(); +#if BUILDFLAG(IS_WIN) + uintptr_t parent = reinterpret_cast(native); +#else + uintptr_t parent = static_cast(native); +#endif + panel_.reset(Module().create(payload.c_str(), parent, &HandleCommand, this)); + CHECK(panel_) << "Flutter panel creation failed; inspect KOUR_EVENT"; +#if BUILDFLAG(IS_LINUX) + GiveFrameSink(); +#endif + } + UpdateNativeBounds(); + Module().show(panel_.get(), IsDrawn()); + Record("attached"); + } + + void RemovedFromWidget() override { + // The native child must never survive its parent HWND/X window. Destroy it + // on removal; BrowserView normally removes this View only at teardown. + if (event_root_) event_root_->RemovePreTargetHandler(&focus_handler_); + event_root_ = nullptr; + chrome_watch_.Watch(nullptr); + ReleasePanel(); + views::View::RemovedFromWidget(); + Record("detached"); + } + + void OnBoundsChanged(const gfx::Rect& previous_bounds) override { + views::View::OnBoundsChanged(previous_bounds); +#if BUILDFLAG(IS_LINUX) + if (frames_.view()) frames_.view()->SetBoundsRect(bounds()); +#endif + UpdateNativeBounds(); + } + +#if BUILDFLAG(IS_LINUX) + // The view the panel's frames are drawn in: a sibling above the pages, + // which the shell's own view is under. + void AttachFrames(views::View* frames) { + frames_.SetView(frames); + // Should that view go before this one, the panel is told first. + frames_.SetIsDeletingCallback(base::BindOnce(&KourFlutterPanel::TakeFrameSink, + base::Unretained(this))); + frames->SetBoundsRect(bounds()); + GiveFrameSink(); + } +#endif + + void VisibilityChanged(views::View* starting_from, bool is_visible) override { + views::View::VisibilityChanged(starting_from, is_visible); + if (panel_) Module().show(panel_.get(), IsDrawn()); + } + + void OnDeviceScaleFactorChanged(float old_scale, float new_scale) override { + views::View::OnDeviceScaleFactorChanged(old_scale, new_scale); + UpdateNativeBounds(); + } + + // What the shell needs to draw the window's own buttons + // (docs/specs/2026-10-25-window-caption.md): which, in the system's order on + // either side, where Kour draws them (none where the system does); whether + // the window is maximised (maximise then reads as restore) and in full + // screen (no buttons then). + base::DictValue WindowChrome() { + auto* widget = static_cast(GetWidget()); + base::DictValue chrome; + if (!widget) return chrome; + chrome.Set("maximized", widget->IsMaximized()); + chrome.Set("fullScreen", widget->IsFullscreen()); + // (as the frame paints itself: a bubble of the window's own, a permission or a download, keeps it in front) + chrome.Set("active", widget->ShouldPaintAsActive()); + if (!KourDrawsWindowButtons(widget)) return chrome; + const auto names = [](const std::vector& buttons) { + base::ListValue list; + for (const auto button : buttons) { + list.Append(button == views::FrameButton::kMinimize ? "minimize" + : button == views::FrameButton::kMaximize ? "maximize" + : "close"); + } + return list; + }; + // The system's order (Linux: its decoration layout; Windows: minimise, + // maximise, close at the trailing end). + const auto* order = views::WindowButtonOrderProvider::GetInstance(); + chrome.Set("buttons", base::DictValue() + .Set("leading", names(order->leading_buttons())) + .Set("trailing", names(order->trailing_buttons()))); + return chrome; + } + + // The shell is told when what WindowChrome says changes (a window maximised + // or restored, in or out of full screen, each of which resizes the shell; + // the window painted in front or behind; on Linux the system's button + // layout changing: ChromeWatch), and asks for it again. + void NotifyWindowChrome() { + if (!panel_) return; + auto chrome = WindowChrome(); + if (window_chrome_ == chrome) return; + const bool first = !window_chrome_.has_value(); + window_chrome_ = std::move(chrome); + if (!first) Module().command(panel_.get(), "windowChanged"); + } + + void UpdateNativeBounds() { + if (!panel_ || !GetWidget()) return; + NotifyWindowChrome(); + const auto origin = GetWidget()->GetClientAreaBoundsInScreen().origin(); + auto bounds = GetBoundsInScreen(); + bounds.Offset(-origin.x(), -origin.y()); + const double scale = GetWidget()->GetCompositor()->device_scale_factor(); + Module().resize(panel_.get(), std::lround(bounds.x() * scale), + std::lround(bounds.y() * scale), std::lround(bounds.width() * scale), + std::lround(bounds.height() * scale), scale); + } + + void LayoutWebContents(MultiContentsView* contents) { + contents_view_ = contents; + std::vector surfaces; + // Mail bodies are no tabs: each in a web view of its own, never a + // contents container (MultiContentsView::SetKourBodies). + std::vector bodies; + for (const auto& [page_id, bounds] : viewports_) { + if (auto* page = Page(page_id)) { + surfaces.push_back({page, bounds, false, Background(page_id, page)}); + } else if (auto* body = mail_bodies_.Get(page_id)) { + bodies.push_back({body, bounds}); + } + } + // The pages held over the ones that took their place (showPages). + for (const auto& held : page_switch_.held()) { + content::WebContents* page = held.contents.get(); + // (not one another window has taken since: adoptPage) + if (page && browser_->GetTabStripModel()->GetIndexOfWebContents(page) != TabStripModel::kNoTab && + std::ranges::none_of(surfaces, [page](const auto& surface) { + return surface.contents == page; + })) { + surfaces.push_back({page, held.bounds, true, Background(held.id, page)}); + } + } + contents->SetKourWebContents(surfaces, browser_->GetTabStripModel()->GetActiveWebContents(), modal_); + contents->SetKourBodies(bodies, modal_); + } + + void OnFocus() override { + views::View::OnFocus(); + if (panel_) Module().focus(panel_.get()); + Record("focusRequested"); + } + + void OnBlur() override { + views::View::OnBlur(); + if (panel_) Module().focus_parent(panel_.get()); + } + + bool HandleUnhandledKey(const input::NativeWebKeyboardEvent& event) { + if (!panel_ || event.GetType() != blink::WebInputEvent::Type::kRawKeyDown || event.skip_if_unhandled || + !event.os_event || !event.os_event->IsKeyEvent()) { + return false; + } + const ui::KeyEvent* key = event.os_event->AsKeyEvent(); + const std::string* command = CommandFor(*key, unhandled_); + if (!command) return false; + if (!key->is_repeat()) Module().command(panel_.get(), command->c_str()); + return true; + } + + bool CanClose(base::OnceClosure retry_close) { + if (!panel_) return true; + if (close_ready_) { + // Approval belongs to this attempt. A webpage can subsequently cancel + // its beforeunload, in which case the next attempt must save again. + close_ready_ = false; + return true; + } + if (!close_pending_) { + close_pending_ = true; + // The window goes at once, as Chromium's own close hides it before + // its tabs have closed. The save below may wait on a disk or a + // network, for seconds: a window that stayed all that time looked like + // a Quit that was not heard, and asking again did nothing (a close + // under way takes no second one). Not while a page may still ask + // "Leave site?": that question needs its window. Nor in full screen, + // where a window taken away leaves its empty Space behind. + auto* widget = GetWidget(); + if (widget && widget->IsVisible() && !widget->IsMinimized() && + !widget->IsFullscreen() && + !(UnloadController::From(browser_)->TabsNeedBeforeUnloadFired() && + PagesMayAskToStay())) { + hidden_for_close_ = true; + widget->Hide(); + // A save that never answers must not leave a window nobody can see. + close_watchdog_.Start(FROM_HERE, base::Seconds(30), + base::BindOnce(&KourFlutterPanel::ShowAfterRefusedClose, + base::Unretained(this))); + } + // Accepted native writes outlive navigation away from the import page. + // Once the current batch ends, Flutter cancels/drains the remaining flow. + browser_data_.WhenIdle(base::BindOnce(&KourFlutterPanel::PrepareClose, + weak_factory_.GetWeakPtr(), std::move(retry_close))); + } + return false; + } +#if BUILDFLAG(IS_WIN) + // The system's backdrop under the sidebar (windowBackdrop): whether the + // window is clear for it, and Kour's look for it while it shows (the + // browser's otherwise). + bool WantsBackdrop() const { return system_backdrop_; } + std::optional BackdropDark() const { + return system_backdrop_ ? system_backdrop_dark_ : std::nullopt; + } +#endif + + private: + // The panel goes: nothing of its frames is drawn after, and it is told so + // before the view that drew them can go (kour_desktop_panel_abi.h). + void ReleasePanel() { +#if BUILDFLAG(IS_LINUX) + TakeFrameSink(); +#endif + panel_.reset(); + } +#if BUILDFLAG(IS_LINUX) + void GiveFrameSink() { + if (panel_ && frames_.view()) Module().set_frame_sink(panel_.get(), &ShowFrame, this); + } + // The panel puts its window back on the screen as it loses the sink; the + // picture is taken down after. Memory frames only: no release is owed. + void TakeFrameSink() { + if (panel_) Module().set_frame_sink(panel_.get(), nullptr, nullptr); + if (frames_.view()) ShowKourShellFrame(frames_.view(), nullptr); + } + static int ShowFrame(void* context, const KourPanelFrame* frame) { + auto* self = static_cast(context); + return self->frames_.view() ? ShowKourShellFrame(self->frames_.view(), frame) : 0; + } +#endif + class NativeFocusHandler final : public ui::EventHandler { + public: + explicit NativeFocusHandler(KourFlutterPanel* owner) : owner_(owner) {} + void OnMouseEvent(ui::MouseEvent* event) override { + // Flutter child events do not enter Aura. These clicks belong to + // Chromium, including webpages exposed by the native shape mask. + if (!owner_->panel_ || event->type() != ui::EventType::kMousePressed) return; + // A press on a page beside an open Flutter menu closes the menu, as + // its barrier would, and is the barrier's. Only on a page: the frame, + // its caption buttons and its edges keep their own presses. + if (owner_->menus_open_ && !(event->flags() & ui::EF_IS_NON_CLIENT) && + owner_->OverPage(event->root_location())) { + owner_->menus_open_ = false; + Module().command(owner_->panel_.get(), "dismissMenus"); + event->StopPropagation(); + return; + } + Module().focus_parent(owner_->panel_.get()); + } + // Kour's commands are taken before the page and before Chromium's own + // accelerators. With a web page focused the keys come here, never to + // Flutter (its native child has its own focus), and Chromium gave them + // to the tab strip and toolbar Kour does not show: Ctrl+T opened a tab + // nobody could see, Ctrl+W closed one, Ctrl+L focused a hidden address + // bar. With Flutter focused the same table is matched there. + void OnKeyEvent(ui::KeyEvent* event) override { + if (!owner_->panel_ || event->type() != ui::EventType::kKeyPressed) return; + const std::string* command = owner_->CommandFor(*event); + if (!command) return; + // A key held down repeats; a command is given once. + if (!event->is_repeat()) Module().command(owner_->panel_.get(), command->c_str()); + event->StopPropagation(); + } + private: + raw_ptr owner_; + }; + // One chord of the command table Dart gave (core/commands.dart). + struct Shortcut { + ui::KeyboardCode code; + bool control, alt, shift; + std::string id; + }; + static ui::KeyboardCode KeyCode(const std::string& key) { + if (key.size() == 1) { + const char c = key[0]; + if (c >= 'a' && c <= 'z') return static_cast(ui::VKEY_A + (c - 'a')); + if (c >= '0' && c <= '9') return static_cast(ui::VKEY_0 + (c - '0')); + switch (c) { + case ',': return ui::VKEY_OEM_COMMA; + case '.': return ui::VKEY_OEM_PERIOD; + case '/': return ui::VKEY_OEM_2; + case '\\': return ui::VKEY_OEM_5; + case '[': return ui::VKEY_OEM_4; + case ']': return ui::VKEY_OEM_6; + case '-': return ui::VKEY_OEM_MINUS; + case '=': return ui::VKEY_OEM_PLUS; + default: return ui::VKEY_UNKNOWN; + } + } + // f1…f12: F5 reloads and F3 finds the next match, as in Chrome. + if (key.size() >= 2 && key.size() <= 3 && key[0] == 'f') { + int n = 0; + for (size_t i = 1; i < key.size(); ++i) { + if (key[i] < '0' || key[i] > '9') return ui::VKEY_UNKNOWN; + n = n * 10 + (key[i] - '0'); + } + if (n >= 1 && n <= 12) return static_cast(ui::VKEY_F1 + (n - 1)); + return ui::VKEY_UNKNOWN; + } + if (key == "tab") return ui::VKEY_TAB; + if (key == "up") return ui::VKEY_UP; + if (key == "down") return ui::VKEY_DOWN; + if (key == "left") return ui::VKEY_LEFT; + if (key == "right") return ui::VKEY_RIGHT; + // (Chrome's Ctrl+PgDn and Ctrl+PgUp for the next and previous tab) + if (key == "pageup") return ui::VKEY_PRIOR; + if (key == "pagedown") return ui::VKEY_NEXT; + return ui::VKEY_UNKNOWN; + } + const std::string* CommandFor(const ui::KeyEvent& event) const { return CommandFor(event, shortcuts_); } + const std::string* CommandFor(const ui::KeyEvent& event, const std::vector& table) const { + // AltGr types characters; the Windows key is the system's. + if (event.IsAltGrDown() || event.IsCommandDown()) return nullptr; + for (const auto& shortcut : table) { + if (shortcut.code == event.key_code() && shortcut.control == event.IsControlDown() && + shortcut.alt == event.IsAltDown() && shortcut.shift == event.IsShiftDown()) { + return &shortcut.id; + } + } + return nullptr; + } + // A page that can ask "Leave site?" when it is closed: a frame with a + // beforeunload handler, or DevTools with a question of its own. (What + // Chromium counts as "needs beforeunload fired" is wider: unload, pagehide + // and visibilitychange handlers too, which most pages have and which show + // nothing.) + bool PagesMayAskToStay() const { + auto* model = browser_->GetTabStripModel(); + for (int i = 0; i < model->count(); ++i) { + content::WebContents* contents = model->GetWebContentsAt(i); + if (DevToolsWindow::NeedsToInterceptBeforeUnload(contents)) return true; + bool asks = false; + contents->GetPrimaryMainFrame()->ForEachRenderFrameHost( + [&asks](content::RenderFrameHost* frame) { + asks = asks || frame->GetSuddenTerminationDisablerState( + blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler); + }); + if (asks) return true; + } + return false; + } + void CloseRefused(BrowserWindowInterface::ClosingStatus status) { + // "Unload handlers need time" is not a refusal: the close goes on when + // they have run, and the window stays away. Unless one of them may ask. + if (status == BrowserWindowInterface::ClosingStatus::kDeniedUnloadHandlersNeedTime && + !(UnloadController::From(browser_)->TabsNeedBeforeUnloadFired() && + PagesMayAskToStay())) { + return; + } + ShowAfterRefusedClose(); + } + void ShowAfterRefusedClose() { + close_watchdog_.Stop(); + if (!hidden_for_close_) return; + hidden_for_close_ = false; + // Its tabs already closed (the barrier is asked a second time then, and + // Chromium has hidden the window itself): nothing to show. + if (browser_->GetTabStripModel()->empty()) return; + if (auto* widget = GetWidget()) widget->Show(); + } + void PrepareClose(base::OnceClosure retry_close) { + LOG(INFO) << "KOUR_SHELL_CLOSE_V1"; + auto* reply = new base::OnceCallback(base::BindOnce( + &KourFlutterPanel::DidPrepareClose, weak_factory_.GetWeakPtr(), + std::move(retry_close))); + Module().prepare_close(panel_.get(), [](void* context, int allowed) { + auto callback = std::unique_ptr>( + static_cast*>(context)); + std::move(*callback).Run(allowed != 0); + }, reply); + } + void DidPrepareClose(base::OnceClosure retry_close, bool allowed) { + // Chromium has let go of the panel: its window is being deleted, and the + // bridge refuses, as it lets go, a close it was still asked about. That + // close is past undoing; cancelling it fails UnloadController's CHECK. + // (unique_ptr::reset clears panel_ before KourDestroyPanel runs.) + if (!panel_) return; + close_watchdog_.Stop(); + close_pending_ = false; + close_ready_ = allowed; + if (allowed) { + std::move(retry_close).Run(); + } else { + // Undo Chromium's application-quit state as a cancelled beforeunload + // would. Otherwise Command-Q stays latched and its faded windows may + // remain hidden after a save failure. + auto* unload = UnloadController::From(browser_); + unload->CancelWindowClose(); + unload->NotifyWindowCloseCancelled( + BrowserWindowInterface::ClosingStatus::kDeniedByUser); + // And the quit itself: the application takes no Quit while it believes + // one is under way, and nothing else ends this one (Chromium ends it + // when a page refuses to unload, which is before the windows are asked + // to close; this refusal comes after). Left set, no later Quit was + // heard at all, from the menu, the keyboard or the Dock. + browser_shutdown::SetTryingToQuit(false); + } + } + int Index(int handle) const { + auto* model = browser_->GetTabStripModel(); + for (int i = 0; i < model->count(); ++i) { + if (model->GetTabAtIndex(i)->GetHandle().raw_value() == handle) return i; + } + return -1; + } + + // Every Kour window's panel: a page is in one window at a time, and may + // move to another (one engine, every window a view of it). + static std::set& All() { + static base::NoDestructor> all; + return *all; + } + + // The other window's panel that holds the page [id], else null. + KourFlutterPanel* Holder(const std::string& id) const { + for (auto* other : All()) { + // (a page of one profile never goes to another's window) + if (other != this && other->browser_->GetProfile() == browser_->GetProfile() && other->Page(id)) return other; + } + return nullptr; + } + + // `askingPage`: what the page waits on the person for and what it opened (KourPageAgent::Asking), with the tabs of + // this window it opened, by their pages. + std::string Asking(content::WebContents* contents) { + base::DictValue out = KourPageAgent::Asking(contents); + base::ListValue opened; + if (const base::ListValue* windows = out.FindList("opened")) opened = windows->Clone(); + TabStripModel* model = browser_->GetTabStripModel(); + for (int i = 0; i < model->count(); ++i) { + content::WebContents* tab = model->GetWebContentsAt(i); + if (tab == contents || tab->GetFirstWebContentsInLiveOriginalOpenerChain() != contents) { + continue; + } + const int handle = model->GetTabAtIndex(i)->GetHandle().raw_value(); + const std::string site = url::Origin::Create(tab->GetVisibleURL()).Serialize(); + bool bound = false; + for (const auto& [id, page_handle] : pages_) { + if (page_handle == handle) { + opened.Append(base::DictValue() + .Set("page", id) + .Set("url", site) + .Set("title", base::UTF16ToUTF8(tab->GetTitle()))); + bound = true; + } + } + if (!bound) { + // a tab the page opened that is not in Kour's library yet (a sign-in): it is still the person's to see and + // finish, and the Agent may not read it by a page id + opened.Append(base::DictValue() + .Set("tab", true) + .Set("url", site) + .Set("title", base::UTF16ToUTF8(tab->GetTitle()))); + } + } + if (!opened.empty()) out.Set("opened", std::move(opened)); + return base::WriteJson(out).value_or("{}"); + } + + content::WebContents* Page(const std::string& id) const { + auto found = pages_.find(id); + if (found == pages_.end()) return nullptr; + const int index = Index(found->second); + return index < 0 ? nullptr : browser_->GetTabStripModel()->GetWebContentsAt(index); + } + + // What `panes` may place: a page, or a mail message's body. Nothing else + // of a page's is a body's: no command finds one by Page(). + content::WebContents* Surface(const std::string& id) const { + if (auto* page = Page(id)) return page; + return mail_bodies_.Get(id); + } + + bool ValidId(const std::string* id) const { return kour::ValidPageId(id); } + + bool ValidURL(const std::string* value) const { + if (!value || value->size() > 16384) return false; + const GURL url(*value); + return url.is_valid() && !url.has_username() && !url.has_password() && + (url.SchemeIsHTTPOrHTTPS() || url.SchemeIsFile() || url.SchemeIs("chrome") || + url.SchemeIs("chrome-extension") || url.spec() == "about:blank"); + } + + std::string State() { +#if BUILDFLAG(IS_WIN) + // A private window is marked for Kour's voice keys, which read nothing of it and keep nothing (P16). + if (browser_->GetProfile()->IsOffTheRecord() && GetWidget()) { + if (HWND window = views::HWNDForWidget(GetWidget())) SetPropW(window, L"KourPrivate", reinterpret_cast(1)); + } +#elif BUILDFLAG(IS_LINUX) + // The same on X11 (the bridge's windows are X11's): a property of the + // browser's top-level window the bridge reads (compat-fixes B10). + if (browser_->GetProfile()->IsOffTheRecord() && GetWidget() && !private_marked_) { + auto* connection = x11::Connection::Get(); + if (connection && connection->Ready()) { + private_marked_ = true; + const auto native = GetWidget()->GetNativeWindow()->GetHost()->GetAcceleratedWidget(); + connection->SetProperty(static_cast(native), x11::GetAtom("_KOUR_PRIVATE"), x11::Atom::CARDINAL, + uint32_t{1}); + connection->Flush(); + } + } +#endif + auto* model = browser_->GetTabStripModel(); + std::erase_if(pages_, [&](const auto& entry) { return Index(entry.second) < 0; }); + std::erase_if(accessibility_modes_, [&](const auto& entry) { return Index(entry.first) < 0; }); + base::ListValue pages; + base::ListValue unbound; + for (int i = 0; i < model->count(); ++i) { + auto* contents = model->GetWebContentsAt(i); + const int handle = model->GetTabAtIndex(i)->GetHandle().raw_value(); + if (accessibility_requested_ && !accessibility_modes_.contains(handle)) { + // A platform query of the Flutter shell also needs the real webpage + // subtrees. Scope activation to this window's sessions, including pages + // opened after the first query; the mode's lifetime ends with the page. + accessibility_modes_.emplace(handle, + content::BrowserAccessibilityState::GetInstance()->CreateScopedModeForWebContents( + contents, ui::kAXModeComplete)); + } + auto record = base::DictValue() + .Set("nativeId", handle) + .Set("title", base::UTF16ToUTF8(contents->GetTitle())) + .Set("url", contents->GetVisibleURL().spec()) + .Set("active", i == model->active_index()) + .Set("focused", kour::PageFocused(contents)) + .Set("back", contents->GetController().CanGoBack()) + .Set("forward", contents->GetController().CanGoForward()) + .Set("loading", contents->IsLoading()); + // A document Kour is fetching for this page (kour_file_handoff). + if (auto handing = kour::HandoffProgress(contents)) record.Set("handing", std::move(*handing)); + // The Space the page was made in: its web data is that Space's. + if (const std::string space = kour::SpaceOf(contents); !space.empty()) { + record.Set("space", space); + } + // Playing sound now: a page the person is listening to is not + // tidied away. + if (contents->IsCurrentlyAudible()) record.Set("audible", true); + // Its media, as the browser's media session has it (kour_page_media). + if (auto media = kour::PageMedia(contents)) record.Set("media", std::move(*media)); + // The page's declared theme colour, else its painted background: shell + // tabs continue the page's colour into its tab. + if (auto color = contents->GetThemeColor()) { + record.Set("themeColor", base::StringPrintf("#%08X", *color)); + } + if (auto color = contents->GetBackgroundColor()) { + record.Set("backgroundColor", base::StringPrintf("#%08X", *color)); + } + // The address of the page's own icon, once the browser has it: only + // the address, so the shell knows when to ask for the picture + // ("pageIcon") without the picture riding in every state. A web + // address only: an icon drawn by script as a data: address would + // change the state at every frame of it. + if (auto* entry = contents->GetController().GetLastCommittedEntry()) { + const content::FaviconStatus& icon = entry->GetFavicon(); + if (icon.valid && icon.url.is_valid() && icon.url.SchemeIsHTTPOrHTTPS() && + icon.url.spec().size() <= 2048) { + record.Set("icon", icon.url.spec()); + } + } + bool bound = false; + for (const auto& [id, page_handle] : pages_) { + if (page_handle == handle) { + record.Set("pageId", id); + pages.Append(std::move(record)); + bound = true; + break; + } + } + if (!bound) { + // A page another page opened (window.open, target=_blank) says + // which: the shell shows it as a tab beside its opener. One opened + // as a tab of its own (a Control-click, a link from another + // application) has no opener here, and is in front or not as + // Chromium opened it ("active"). + if (auto* opener = contents->GetFirstWebContentsInLiveOriginalOpenerChain()) { + const int at = model->GetIndexOfWebContents(opener); + if (at >= 0) { + record.Set("opener", model->GetTabAtIndex(at)->GetHandle().raw_value()); + } + } else if (const int self = model->GetIndexOfWebContents(contents); self >= 0) { + // A tab of its own that a page's link opened (a Command-click, a + // middle-click, Open Link in New Tab) is no popup, but says whose + // link it was: Tidy tells its model which page opened which. + if (tabs::TabInterface* from = model->GetOpenerOfTabAt(self)) { + record.Set("linkedFrom", from->GetHandle().raw_value()); + } + } + unbound.Append(std::move(record)); + } + } + // Documents the browser handed to Kour's viewers (kour_file_handoff), + // by the page they came from; until the shell acknowledges them. + base::ListValue files; + for (const auto& file : kour::HandedFiles()) { + std::string page; + for (const auto& [id, page_handle] : pages_) { + if (page_handle == file.tab || page_handle == file.opener) page = id; + } + // A window's file is that window's to show (its tab may be gone: one + // opened only for the file); one from no window is any window's of + // its profile. + if (file.window >= 0 ? file.window != browser_->GetSessionID().id() + : file.profile != kour::ProfileKey(browser_->GetProfile())) { + continue; + } + auto record = base::DictValue() + .Set("id", file.id) + .Set("path", file.path) + .Set("name", file.name) + .Set("mime", file.mime) + .Set("url", file.url) + .Set("requested", file.requested.empty() ? file.url : file.requested) + .Set("disposition", file.disposition) + .Set("origin", file.origin); + if (!page.empty()) record.Set("pageId", page); + if (file.has_space) record.Set("space", file.space); + files.Append(std::move(record)); + } + // Links the system handed to Kour, waiting for the shell to place them + // (kour_spaces): until it acknowledges them. + base::ListValue arrivals; + for (const auto& link : kour::ExternalLinks(browser_)) { + auto record = base::DictValue().Set("id", link.id).Set("url", link.url); + if (!link.app.empty()) record.Set("app", link.app); + arrivals.Append(std::move(record)); + } + return base::WriteJson(base::DictValue().Set("pages", std::move(pages)) + .Set("unbound", std::move(unbound)) + .Set("extensionsRevision", extensions_.revision()) + .Set("files", std::move(files)) + .Set("downloads", kour::Downloads(browser_->GetProfile())) + .Set("arrivals", std::move(arrivals)) + .Set("profile", base::NumberToString(reinterpret_cast(browser_->GetProfile()))) + // (an off-the-record window: its shell records nothing, P16) + .Set("private", browser_->GetProfile()->IsOffTheRecord()) + .Set("capabilities", Capabilities()) + .Set("window", base::DictValue().Set("fullScreen", GetWidget()->IsFullscreen()))).value_or("{}"); + } + + // What this browser does beyond showing pages: the shell offers the + // Agent's page tools by it. + static base::ListValue Capabilities() { + return base::ListValue().Append("evaluatePage").Append("closePages").Append("files").Append("downloads").Append("pageIcon") + .Append("inputPage").Append("capturePage").Append("contentPage").Append("toolPage").Append("evaluateFrame").Append("pageMedia").Append("captureVideoFrame") + .Append("showPages").Append("archivePage").Append("printPage").Append("printMailBody").Append("pageEvents").Append("pageMenu").Append("downloadPrefs") + .Append("autoPictureInPicture") + .Append("spaceDownloadFolders").Append("browserHost").Append("findPage").Append("focusPage") + .Append("spaces").Append("forgetAddresses").Append("clearHistory").Append("externalLinks").Append("installExtension").Append("kourHelpers") + .Append("siteSignals").Append("mailBody").Append("bookBody").Append("privateWindows"); + } + + // Runs the Agent's script in the page's main frame, in Chrome's internal + // isolated world, where the page's own scripts cannot see or change it. + // The answer comes later: the shell asks `evaluateResult` for it. + std::string Evaluate(content::WebContents* contents, const base::DictValue& args, bool body = false) { + const auto* script = args.FindString("script"); + if (!script || script->size() > 262144) return R"({"error":"invalid_script"})"; + auto* frame = contents->GetPrimaryMainFrame(); + if (!frame || !frame->IsRenderFrameLive()) return R"({"error":"page_not_ready"})"; + // Web pages only, and a book's chapter ([body], checked by its caller): + // never the browser's own pages or an extension's. + if (!body && !frame->GetLastCommittedURL().SchemeIsHTTPOrHTTPS()) { + return R"({"error":"page_not_scriptable"})"; + } + // An answer nobody asked for within a while (the shell gave up, the page + // went away) is forgotten. + const base::TimeTicks now = base::TimeTicks::Now(); + std::erase_if(evaluations_, [&](const auto& entry) { + return now - entry.second.started > base::Seconds(30); + }); + if (evaluations_.size() >= 32) return R"({"error":"too_many_scripts"})"; + const int ticket = ++next_evaluation_; + evaluations_[ticket] = {now, false, std::nullopt}; + frame->ExecuteJavaScriptInIsolatedWorld( + base::UTF8ToUTF16(*script), + base::BindOnce(&KourFlutterPanel::Evaluated, weak_factory_.GetWeakPtr(), ticket), + ISOLATED_WORLD_ID_CHROME_INTERNAL); + return base::WriteJson(base::DictValue().Set("token", ticket)).value_or("{}"); + } + + void Evaluated(int ticket, base::Value value) { + auto found = evaluations_.find(ticket); + if (found == evaluations_.end()) return; + found->second.done = true; + // Kour's scripts evaluate to a string; one that threw evaluates to + // nothing, and failed. + if (value.is_string()) found->second.value = value.GetString(); + // The shell waits for this rather than asking again and again. + SendPageEvent(base::DictValue().Set("kind", "evaluated").Set("token", ticket)); + } + + // Page events to the shell (KourDesktopPanelPageEvent): bells, menu + // choices, scripts' answers. + void SendPageEvent(const base::DictValue& event) { + if (!panel_) return; + const std::string json = base::WriteJson(event).value_or("{}"); + Module().page_event(panel_.get(), json.c_str()); + } + + // The id the shell knows `contents` by, or none. + std::string PageIdOf(content::WebContents* contents) const { + for (const auto& [id, handle] : pages_) { + if (Page(id) == contents) return id; + } + return std::string(); + } + + // Kour's items in a page's right-click menu, as the shell last said them. + std::vector MenuItemsFor(content::WebContents* contents) const { + if (PageIdOf(contents).empty()) return {}; + return page_menu_items_; + } + + void MenuChosen(content::WebContents* contents, const std::string& item, const std::u16string& text) { + const std::string page = PageIdOf(contents); + if (page.empty()) return; + SendPageEvent(base::DictValue().Set("pageId", page).Set("kind", "menu").Set("item", item) + .Set("text", base::UTF16ToUTF8(text.substr(0, 4096)))); + } + + + std::string EvaluationResult(const base::DictValue& args) { + const auto ticket = args.FindInt("token"); + auto found = ticket ? evaluations_.find(*ticket) : evaluations_.end(); + if (found == evaluations_.end()) return R"({"error":"unknown_token"})"; + if (!found->second.done) return R"({"pending":true})"; + if (!found->second.value) { + evaluations_.erase(found); + return R"({"error":"script_failed"})"; + } + std::string value = std::move(*found->second.value); + evaluations_.erase(found); + return base::WriteJson(base::DictValue().Set("value", value)).value_or("{}"); + } + + // The page as Chromium's own serializer archives it (MHTML, its parts as + // text): what a web clip's snapshot is made from. It has what a script in + // the page cannot read: fonts, and pictures of other sites. Web pages + // only, as Evaluate. The answer comes later: the shell asks + // `archiveResult` for it by its token, and is given the file and the + // address that was archived. The archive never crosses this thread (it + // may be tens of megabytes, and the shell shares the thread): the shell + // reads the file itself, off it, and removes it. + // + // The file is the page as the person sees it, signed in or not. It is + // written in a directory of Kour's own in the profile, emptied when the + // browser starts, and removed when the panel goes, when the page goes or + // moves on, and when the serializer has not answered in a while. + std::string Archive(content::WebContents* contents) { + auto* frame = contents->GetPrimaryMainFrame(); + if (!frame || !frame->IsRenderFrameLive()) return R"({"error":"page_not_ready"})"; + if (!frame->GetLastCommittedURL().SchemeIsHTTPOrHTTPS()) { + return R"({"error":"page_not_scriptable"})"; + } + // A private window leaves nothing on disk, and its profile's directory + // is the ordinary one's. + if (browser_->GetProfile()->IsOffTheRecord()) { + return R"({"error":"private_window"})"; + } + ForgetArchives(); + // One at a time for a page. + for (const auto& [ticket, page] : archive_pages_) { + if (page == contents) return R"({"error":"archive_under_way"})"; + } + if (archives_.size() >= 4) return R"({"error":"too_many_archives"})"; + const int ticket = ++next_archive_; + archives_[ticket].started = base::TimeTicks::Now(); + archive_pages_[ticket] = contents; + // The file is named off this thread, then written by the serializer. + ArchiveFiles()->PostTaskAndReplyWithResult( + FROM_HERE, + base::BindOnce([](base::FilePath directory) { + base::FilePath path; + return base::CreateDirectory(directory) && + base::CreateTemporaryFileInDir(directory, &path) + ? path + : base::FilePath(); + }, ArchiveDirectory(browser_->GetProfile()->GetPath())), + base::BindOnce(&KourFlutterPanel::ArchiveInto, weak_factory_.GetWeakPtr(), + ticket, contents->GetWeakPtr())); + // One the shell never collects is not left for the next asking. + base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask( + FROM_HERE, + base::BindOnce(&KourFlutterPanel::ForgetArchives, weak_factory_.GetWeakPtr()), + kArchiveForgotten + base::Seconds(1)); + return base::WriteJson(base::DictValue().Set("token", ticket)).value_or("{}"); + } + + // How long the serializer is waited for, and how long an answer is kept + // for the shell (which stops asking a little after the first). + static constexpr base::TimeDelta kArchiveOverdue = base::Seconds(20); + static constexpr base::TimeDelta kArchiveForgotten = base::Seconds(30); + + static base::FilePath ArchiveDirectory(const base::FilePath& profile) { + return profile.AppendASCII("KourArchives"); + } + + // Where archives' files are named, and where what an earlier run left + // is removed: one after the other, so that the removing is always done + // before the first file of this run is named (done apart, it could take + // away a file a page was just written to). + static scoped_refptr ArchiveFiles() { + static base::NoDestructor> runner( + base::ThreadPool::CreateSequencedTaskRunner( + {base::MayBlock(), base::TaskPriority::USER_VISIBLE})); + return *runner; + } + + // What an earlier run left (it crashed, or quit while a page was being + // written): removed once for each profile, when its first window of this + // run opens. Removed in the task itself: the callback base has for this + // tries again later on Windows, apart from this queue, and would then + // take away a file of this run. + static void SweepArchives(const base::FilePath& profile) { + static base::NoDestructor> swept; + if (!swept->insert(profile).second) return; + ArchiveFiles()->PostTask( + FROM_HERE, base::BindOnce([](base::FilePath directory) { + base::DeletePathRecursively(directory); + }, ArchiveDirectory(profile))); + } + + // Removes an archive's file, also while the browser is quitting. + static void RemoveArchive(const base::FilePath& path) { + if (path.empty()) return; + base::ThreadPool::PostTask( + FROM_HERE, + {base::MayBlock(), base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, + base::GetDeleteFileCallback(path)); + } + + // Entries nobody collected in a while, and those whose page never + // answered. + void ForgetArchives() { + const base::TimeTicks now = base::TimeTicks::Now(); + std::erase_if(archives_, [&](const auto& entry) { + const bool old = now - entry.second.started > kArchiveForgotten; + if (old) { + archive_pages_.erase(entry.first); + RemoveArchive(entry.second.path); + } + return old; + }); + } + + // Ends [ticket] without an archive. + void FailArchive(int ticket) { + archive_pages_.erase(ticket); + if (auto found = archives_.find(ticket); found != archives_.end()) { + found->second.done = true; + found->second.ok = false; + found->second.path.clear(); + } + } + + // The address of the web page [contents] shows now, or none: it is asked + // again at each step, as the page may have moved on (to one of the + // browser's own, or a file) since the step before. + static std::string WebAddress(content::WebContents* contents) { + auto* frame = contents ? contents->GetPrimaryMainFrame() : nullptr; + if (!frame || !frame->IsRenderFrameLive()) return std::string(); + const GURL& url = frame->GetLastCommittedURL(); + return url.SchemeIsHTTPOrHTTPS() ? url.spec() : std::string(); + } + + // (A static step: it runs, and removes the file, with the panel gone.) + static void ArchiveInto(base::WeakPtr panel, int ticket, + base::WeakPtr contents, + base::FilePath path) { + const bool wanted = panel && panel->archives_.contains(ticket) && + !panel->archives_[ticket].done; + const std::string address = wanted ? WebAddress(contents.get()) : std::string(); + if (address.empty() || path.empty()) { + if (panel) panel->FailArchive(ticket); + RemoveArchive(path); + return; + } + panel->archives_[ticket].path = path; + panel->archives_[ticket].url = address; + content::MHTMLGenerationParams params(path); + // Text parts (quoted-printable, base64): the archive is read as text. + params.use_binary_encoding = false; + contents->GenerateMHTML( + params, base::BindOnce(&KourFlutterPanel::Archived, panel, ticket, contents, path)); + // A page that never answers (a frame of it hung): given up on, and its + // file removed, after a while. The shell has the script's reading of + // the page meanwhile and waits for this one. + base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask( + FROM_HERE, + base::BindOnce(&KourFlutterPanel::ArchiveOverdue, panel, ticket, path), + kArchiveOverdue); + } + + static void ArchiveOverdue(base::WeakPtr panel, int ticket, + base::FilePath path) { + // Gone with its panel, answered, or collected meanwhile: seen to. + if (!panel || !panel->archive_pages_.contains(ticket)) return; + panel->FailArchive(ticket); + RemoveArchive(path); + } + + static void Archived(base::WeakPtr panel, int ticket, + base::WeakPtr contents, + base::FilePath path, int64_t size) { + // Kept only when it is still wanted, was written, is no larger than + // 64 MiB (a page past that is not kept as a snapshot), and the page is + // still the web page it was when the writing began. + const bool wanted = panel && panel->archive_pages_.erase(ticket) > 0 && + panel->archives_.contains(ticket) && + !panel->archives_[ticket].done; + // (A fragment that changed meanwhile is the same page.) + if (!wanted || size <= 0 || size > (int64_t{64} << 20) || + GURL(WebAddress(contents.get())).GetWithoutRef() != + GURL(panel->archives_[ticket].url).GetWithoutRef()) { + if (panel) panel->FailArchive(ticket); + RemoveArchive(path); + return; + } + panel->archives_[ticket].done = true; + panel->archives_[ticket].ok = true; + } + + std::string ArchiveResult(const base::DictValue& args) { + ForgetArchives(); + const auto ticket = args.FindInt("token"); + auto found = ticket ? archives_.find(*ticket) : archives_.end(); + if (found == archives_.end()) return R"({"error":"unknown_token"})"; + if (!found->second.done) return R"({"pending":true})"; + if (!found->second.ok) { + archives_.erase(found); + return R"({"error":"archive_failed"})"; + } + // The file is the shell's from here: it reads it and removes it. + base::DictValue answer; + answer.Set("path", found->second.path.AsUTF8Unsafe()); + answer.Set("url", found->second.url); + archives_.erase(found); + return base::WriteJson(answer).value_or("{}"); + } + + // An action on a download of the person's (the shell's list of them). + std::string DownloadAction(const base::DictValue& args) { + const auto* download = args.FindString("id"); + const auto* action = args.FindString("action"); + if (!download || !action) return R"({"error":"invalid_download"})"; + kour::DownloadAction(browser_->GetProfile(), *download, *action); + return State(); + } + + // The shell took these handed files: they leave the state. + std::string AckFiles(const base::DictValue& args) { + const auto* ids = args.FindList("ids"); + if (!ids || ids->size() > 100) return R"({"error":"invalid_ids"})"; + std::vector taken; + for (const auto& value : *ids) { + if (const auto* file = value.GetIfString()) taken.push_back(*file); + } + kour::AckHandedFiles(taken); + return State(); + } + + // Closes the tabs of pages whose tabs closed in the shell. A page stays + // bound until its tab is gone (an unbound tab would arrive in the shell as + // a new page). The window's last tab stays: closing it closes the window; + // what it plays ends with the page all the same. + std::string ClosePages(const base::DictValue& args) { + const auto* ids = args.FindList("pageIds"); + if (!ids || ids->size() > 300) return R"({"error":"invalid_page_ids"})"; + auto* model = browser_->GetTabStripModel(); + for (const auto& value : *ids) { + const auto* id = value.GetIfString(); + if (!ValidId(id)) continue; + auto* contents = Page(*id); + if (!contents) continue; + kour::EndPageMedia(contents); + if (model->count() <= 1) continue; + if (auto* tab = tabs::TabInterface::MaybeGetFromContents(contents)) tab->Close(); + } + return State(); + } + + // The icon the browser keeps for a web address, as PNG: from its own + // store of the icons of pages it has shown, so nothing is fetched and no + // other party hears of the address. It answers later; the shell asks + // `pageIconResult` for the picture by its token. + std::string PageIcon(const base::DictValue& args) { + const auto* url = args.FindString("url"); + if (!url || url->size() > 16384) return R"({"error":"invalid_url"})"; + const GURL address(*url); + if (!address.is_valid() || !address.SchemeIsHTTPOrHTTPS()) return R"({"error":"invalid_url"})"; + const base::TimeTicks now = base::TimeTicks::Now(); + std::erase_if(icons_, [&](const auto& entry) { + return now - entry.second.started > base::Seconds(30); + }); + if (icons_.size() >= 64) return R"({"error":"too_many_icons"})"; + auto* service = FaviconServiceFactory::GetForProfile( + browser_->GetProfile(), ServiceAccessType::EXPLICIT_ACCESS); + if (!service) return R"({"none":true})"; + const int token = ++next_icon_; + icons_[token] = {now, false, std::nullopt}; + // Twice a sidebar row's 16 points, for a dense display; the page's own + // icon, else any its host has. + service->GetRawFaviconForPageURL( + address, {favicon_base::IconType::kFavicon}, 32, true, + base::BindOnce(&KourFlutterPanel::PageIconFound, weak_factory_.GetWeakPtr(), token), + &icon_tasks_); + return base::WriteJson(base::DictValue().Set("token", token)).value_or("{}"); + } + + void PageIconFound(int token, const favicon_base::FaviconRawBitmapResult& result) { + auto found = icons_.find(token); + if (found == icons_.end()) return; + found->second.done = true; + // An icon is a few kilobytes; one that is not is left out. + if (result.is_valid() && result.bitmap_data->size() <= 262144) { + found->second.value = base::Base64Encode(base::span(*result.bitmap_data)); + } + } + + std::string PageIconResult(const base::DictValue& args) { + const auto token = args.FindInt("token"); + auto found = token ? icons_.find(*token) : icons_.end(); + if (found == icons_.end()) return R"({"error":"unknown_token"})"; + if (!found->second.done) return R"({"pending":true})"; + std::optional png = std::move(found->second.value); + icons_.erase(found); + if (!png) return R"({"none":true})"; + return base::WriteJson(base::DictValue().Set("png", std::move(*png))).value_or("{}"); + } + + std::string Command(std::string_view method, std::string_view arguments) { + auto args = base::JSONReader::ReadDict(arguments, base::JSON_PARSE_RFC); + if (!args) return R"({"error":"invalid_arguments"})"; + auto* model = browser_->GetTabStripModel(); + // The shell hands the browser the core's entry points, so the assistant's browser tool drives the pages itself. + if (method == "registerBrowserHost") return kour::BrowserHostExport::Get().Register(*args); + // Whether a window's close is part of the application quitting or the + // window alone closing: what the window's saves are told (`closeWindow + // {quit}`). The core closes only as the application ends (`quit` on + // kour/windows), never for a window. + // A new window, as the person's ⌘N would open one (never a private one, whatever window asks): the application + // asks it for "Move to new window" and to open again, as it starts, the windows it had + // (docs/specs/2026-10-25-ux-sidebar-sync.md, rule 12). + if (method == "newWindow") { + chrome::NewEmptyWindow(browser_->GetProfile()->GetOriginalProfile()); + return R"({"ok":true})"; + } + if (method == "closeReason") { + // On Windows and Linux Kour's last window closing is a quit for its + // saves (the core itself closes as the browser ends: ApplicationEnding), + // unless Kour stays in the tray. + // This is asked before the pages' beforeunload: not when a + // page of this window may still ask to stay ("Leave site?"). Only Kour's + // windows count (a window without a panel, a sign-in popup or DevTools, + // asks nothing of Dart when it closes). + bool last = !PagesMayAskToStay(); + for (auto* other : GetAllBrowserWindowInterfaces()) { + if (other != browser_ && other->GetType() == BrowserWindowInterface::TYPE_NORMAL) { + last = false; + break; + } + } + return browser_shutdown::IsTryingToQuit() || (last && !Stays()) ? R"({"quit":true})" : R"({"quit":false})"; + } + if (method == "enableAccessibility") { + if (!accessibility_requested_) { + accessibility_requested_ = true; + State(); + } + return R"({"enabled":true})"; + } + // Extensions' toolbar actions, for the page Flutter shows. + if (method.starts_with("extensionAction")) { + content::WebContents* page = nullptr; + if (const auto* page_id = args->FindString("pageId"); ValidId(page_id)) { + page = Page(*page_id); + } + if (!page) page = model->GetActiveWebContents(); + // An action acts on the active tab: make it the page that ran it. + if (method == "extensionActionRun" && page) { + model->ActivateTabAt(model->GetIndexOfWebContents(page)); + } + if (auto result = extensions_.Command(method, *args, page, GetColorProvider())) { + std::string json; + base::JSONWriter::Write(*result, &json); + return json; + } + } +#if BUILDFLAG(IS_WIN) + // Whether the pages reach the screen through DirectComposition: the + // shell's picture, on the root window's topmost composition target, is + // over them only then. Without it (software compositing, a GPU process + // that has none) they are drawn on the root window itself, and the + // panel cuts them out of its own window as it did before. + if (method == "presentation") { + return direct_composition_ ? R"({"directComposition":true})" + : R"({"directComposition":false})"; + } + // The sidebar's material (docs/specs/2026-10-21-flat-shell.md): the + // window clear where nothing is drawn, so that the system backdrop + // Chromium gives it (Mica) shows under the shell's thinned sidebar, dark + // or light as Kour is. Only through DirectComposition, where the shell + // paints over the rest of the window. + if (method == "windowBackdrop") { + SetBackdrop(args->FindBool("on").value_or(false) && direct_composition_, + args->FindBool("dark")); + return system_backdrop_ ? R"({"backdrop":true})" : R"({"backdrop":false})"; + } +#endif + if (method == "windowOverlays") { + menus_open_ = args->FindBool("open").value_or(false); + // Under what dims the window a page takes no drop and is not read out + // (MultiContentsView::SetKourWebContents). + const bool modal = args->FindBool("modal").value_or(false); + if (modal != modal_) { + modal_ = modal; + if (parent()) parent()->InvalidateLayout(); + } + return "{}"; + } + if (auto result = browser_data_.Command(method, *args)) { + std::string json; + base::JSONWriter::Write(*result, &json); + return json; + } + if (method == "windowChrome") return base::WriteJson(WindowChrome()).value_or("{}"); + if (method == "windowAction") { + const auto* action = args->FindString("action"); + if (!action) return R"({"error":"invalid_window_action"})"; + if (*action == "close") GetWidget()->Close(); + // Every window must pass its cancellable save/unload gate before the + // supervising launcher can install a confirmed application update. + else if (*action == "quit") chrome::AttemptUserExit(); + else if (*action == "minimize") GetWidget()->Minimize(); + else if (*action == "maximize") { + if (GetWidget()->IsMaximized()) GetWidget()->Restore(); + else GetWidget()->Maximize(); + } else return R"({"error":"invalid_window_action"})"; + return "{}"; + } + if (method == "setFullScreen") { + // A slideshow takes the screen, and gives it back, after this call. + const bool wanted = args->FindBool("on").value_or(false); + if (GetWidget()->IsFullscreen() == wanted) return R"({"changed":false})"; + base::SequencedTaskRunner::GetCurrentDefault()->PostTask( + FROM_HERE, base::BindOnce( + [](base::WeakPtr self, bool on) { + if (self && self->GetWidget()) self->GetWidget()->SetFullscreen(on); + }, + weak_factory_.GetWeakPtr(), wanted)); + return R"({"changed":true})"; + } + if (method == "shortcuts") { + // The command table: the keys this window takes for Kour. + std::vector table; + if (const auto* bindings = args->FindList("bindings")) { + for (const auto& value : *bindings) { + const auto* binding = value.GetIfDict(); + const auto* id = binding ? binding->FindString("id") : nullptr; + const auto* key = binding ? binding->FindString("key") : nullptr; + if (!id || !key || id->empty() || id->size() > 64 || table.size() >= 200) continue; + const auto code = KeyCode(*key); + // A chord with neither Control nor Alt would take plain typing. + const bool control = binding->FindBool("control").value_or(false); + const bool alt = binding->FindBool("alt").value_or(false); + if (code == ui::VKEY_UNKNOWN || !(control || alt)) continue; + table.push_back({code, control, alt, binding->FindBool("shift").value_or(false), *id}); + } + } + shortcuts_ = std::move(table); + // Keys a page answers first (Ctrl+D, Ctrl+J): Kour's only when the page leaves them (HandleUnhandledKey). + std::vector left; + if (const auto* unhandled = args->FindList("unhandled")) { + for (const auto& value : *unhandled) { + const auto* binding = value.GetIfDict(); + const auto* id = binding ? binding->FindString("id") : nullptr; + const auto* key = binding ? binding->FindString("key") : nullptr; + if (!id || !key || id->empty() || id->size() > 64 || left.size() >= 50) continue; + const auto code = KeyCode(*key); + const bool control = binding->FindBool("control").value_or(false); + const bool alt = binding->FindBool("alt").value_or(false); + if (code == ui::VKEY_UNKNOWN || !(control || alt)) continue; + left.push_back({code, control, alt, binding->FindBool("shift").value_or(false), *id}); + } + } + unhandled_ = std::move(left); + return base::StringPrintf(R"({"bindings":%d})", static_cast(shortcuts_.size())); + } + if (method == "browserState") return State(); + if (method == "focusShell") { + RequestFocus(); + return "{}"; + } + if (method == "webViewports") { + std::map next; + base::ListValue result; + std::map colors; + if (const char* error = ReadPanes(*args, &next, &result, &colors)) return error; + const auto backdrop = kour::popup::TellBackdrop(kour::ParseColor(args->FindString("backdrop"))); + if (next != viewports_ || backdrop != backdrop_ || colors != colors_) { + viewports_ = std::move(next); + backdrop_ = backdrop; + colors_ = std::move(colors); + if (parent()) parent()->InvalidateLayout(); + } + return base::WriteJson(base::DictValue().Set("viewports", std::move(result))).value_or("{}"); + } + // One change of what the window shows, whole: where each page is, which + // is the active one, and the layout, made before this answers. The shell + // then asks `pagesPresented` whether the pages it brought in have drawn. + if (method == "showPages") { + if (export_id_ >= 0 && GetWidget() && GetWidget()->IsActive()) kour::BrowserHostExport::Get().Foreground(export_id_); + std::map next; + base::ListValue result; + std::map colors; + if (const char* error = ReadPanes(*args, &next, &result, &colors)) return error; + // Pages the change takes away stay where they are, over the ones that + // take their place, until those have drawn (kour::PageSwitch, which + // also keeps a page under another's window drawing meanwhile). + std::vector held = page_switch_.Hold( + args->FindList("hold"), next, viewports_, + base::BindRepeating(&KourFlutterPanel::Surface, + base::Unretained(this))); + std::vector incoming; + for (const auto& [id, rect] : next) { + if (!viewports_.contains(id)) incoming.push_back(Surface(id)); + } + viewports_ = std::move(next); + backdrop_ = kour::popup::TellBackdrop(kour::ParseColor(args->FindString("backdrop"))); + colors_ = std::move(colors); + if (const auto* active = args->FindString("active"); ValidId(active)) { + auto* page = Page(*active); + if (page) { + model->ActivateTabAt(model->GetIndexOfWebContents(page)); + Module().focus_parent(panel_.get()); + page->Focus(); + } + } + // A change that brings no page in while the last one's are still + // awaited is that one going on, not another. + const int change = args->FindInt("switch").value_or(0); + const bool goes_on = + incoming.empty() && page_switch_.Continue(change, held); + if (!goes_on) { + page_switch_.Begin(change, std::move(held), + args->FindDouble("started").value_or(0)); + } + LayoutNow(); + if (!goes_on) page_switch_.Await(incoming); + auto state = base::JSONReader::ReadDict(State(), base::JSON_PARSE_RFC) + .value_or(base::DictValue()); + state.Set("viewports", std::move(result)); + state.Set("held", !page_switch_.held().empty()); + return base::WriteJson(state).value_or("{}"); + } + if (method == "pagesPresented") { + return base::WriteJson(page_switch_.Result(args->FindInt("switch").value_or(0))) + .value_or("{}"); + } + // A page the person is about to ask for (the pointer is on its row) is + // made ready at the size it will have. + if (method == "preparePages") { + std::map next; + base::ListValue result; + if (const char* error = ReadPanes(*args, &next, &result)) return error; + for (const auto& [id, rect] : next) { + if (viewports_.contains(id)) continue; + page_switch_.Prepare(Page(id), rect.size()); + break; + } + return "{}"; + } + // Signing in with Apple or Google, and connecting another service, + // happen in Kour, the browser: a window of its own over this one, with + // this profile's cookies and the page's address shown. The provider sees + // a browser, not an embedded view, and an account already signed in here + // is one click. The round trip ends at an address in the app's own + // scheme, which is not opened: it is the answer, and the window closes. + if (method == "signInWindow") { + return kour::SignInWindow::Call(browser_, GetWidget(), sign_in_, *args); + } + if (method == "forgetAddresses") { + const auto* urls = args->FindList("urls"); + if (!urls || !kour::ForgetAddresses(browser_->GetProfile(), *urls)) { + return R"({"error":"invalid_urls"})"; + } + return State(); + } + if (method == "forgetSpace") { + const auto* space = args->FindString("space"); + if (!space || !kour::ForgetSpace(browser_->GetProfile(), *space)) { + return R"({"error":"invalid_space"})"; + } + return State(); + } + if (method == "siteSignals" || method == "siteSignalsResult") { + return kour::SiteSignalsCommand(browser_->GetProfile(), method, *args); + } + if (method == "pageIcon") return PageIcon(*args); + if (method == "pageIconResult") return PageIconResult(*args); + if (method == "captureResult") return page_input_.CaptureResult(*args); + if (method == "contentResult" || method == "toolResult" || method == "evaluateFrameResult" || + method == "settleResult") { + return page_agent_.Result(*args); + } + if (method == "videoFrameResult") return video_frames_.Result(*args); + if (method == "closePages") return ClosePages(*args); + if (method == "evaluateResult") return EvaluationResult(*args); + if (method == "archiveResult") return ArchiveResult(*args); + // Links from other applications: the shell says it takes them, and + // says when it has placed some. + if (method == "externalLinks") { + kour::TakeExternalLinks(browser_, args->FindBool("take").value_or(false)); + return State(); + } + if (method == "ackArrivals") { + const auto* ids = args->FindList("ids"); + if (!ids || ids->size() > 100) return R"({"error":"invalid_ids"})"; + std::vector taken; + for (const auto& value : *ids) { + if (const auto* link = value.GetIfString()) taken.push_back(*link); + } + // What was still waiting, and so is the shell's alone to open. + base::ListValue acknowledged; + for (const auto& link : kour::AckExternalLinks(taken)) { + acknowledged.Append(link); + } + return base::WriteJson( + base::DictValue().Set("taken", std::move(acknowledged))) + .value_or("{}"); + } + if (method == "ackFiles") return AckFiles(*args); + if (method == "downloadAction") return DownloadAction(*args); + if (method == "downloadPrefs") return kour::DownloadPrefsCommand(browser_->GetProfile(), *args); + if (method == "autoPictureInPicture") { + return kour::AutoPictureInPictureCommand(browser_->GetProfile(), *args); + } + if (method == "spaceDownloadFolders") return kour::SpaceDownloadFoldersCommand(browser_->GetProfile(), *args); + if (method == "printResult") return prints_.Result(*args); + if (method == "pageMenu") { + page_menu_items_ = kour::PageMenuItemsOf(*args); + return "{}"; + } + // A private window (P16): Chromium's off-the-record profile in a window + // of its own, at an address when one is given; its shell records + // nothing. Every private window shares the one off-the-record profile, + // which Chromium lets go of when its last window closes. + if (method == "openPrivateWindow") { + const std::string* url = args->FindString("url"); + GURL target = url ? GURL(*url) : GURL(url::kAboutBlankURL); + if (url && (!target.is_valid() || !target.SchemeIsHTTPOrHTTPS())) return R"({"error":"invalid_url"})"; + Profile* original = browser_->GetProfile()->GetOriginalProfile(); + NavigateParams params(original->GetPrimaryOTRProfile(/*create_if_needed=*/true), target, + ui::PAGE_TRANSITION_TYPED); + params.disposition = WindowOpenDisposition::OFF_THE_RECORD; + params.window_action = NavigateParams::WindowAction::kShowWindow; + Navigate(¶ms); + return R"({"ok":true})"; + } + // This window brought forward (an open document it shows, asked for + // from another window: P16). + if (method == "raiseWindow") { + browser_->GetWindow()->Activate(); + return R"({"ok":true})"; + } + // Kour's own script in a book's chapter (R23): the body's id, never a + // page's; only a book body showing its chapter. + if (method == "evaluatePage") { + const auto* body_id = args->FindString("pageId"); + if (body_id && mail_bodies_.Get(*body_id)) { + content::WebContents* body = mail_bodies_.Scriptable(*body_id); + if (!body) return R"({"error":"page_not_scriptable"})"; + return Evaluate(body, *args, /*body=*/true); + } + } + // A mail message's body (kour_mail_body.h): placed as a page is, and + // nothing else of a page's; its own id, never a page's. + if (auto answer = mail_bodies_.Command( + method, *args, + [this](const std::string& id) { return Page(id) != nullptr; }, + [this](const std::string& id) { + if (viewports_.erase(id)) LayoutNow(); + })) { + return *answer; + } + const auto* id = args->FindString("pageId"); + if (!ValidId(id)) return R"({"error":"invalid_page_id"})"; + auto* contents = Page(*id); + // A page another window holds: moved here as it is (its history, its + // state, nothing reloaded), or that window brought forward. + if (method == "adoptPage" || method == "raisePage") { + if (contents) return State(); + auto* holder = Holder(*id); + if (!holder) return R"({"error":"page_not_open"})"; + if (method == "raisePage") { + holder->browser_->GetWindow()->Activate(); + return R"({"ok":true})"; + } + // A window closing (a page's "Leave site?" still open, say): the page + // stays with it, or the answer would go to this window. + if (holder->close_pending_ || UnloadController::From(holder->browser_)->is_attempting_to_close_browser()) { + return R"({"error":"page_closing"})"; + } + auto* from = holder->browser_->GetTabStripModel(); + const int index = holder->Index(holder->pages_.at(*id)); + if (index < 0) return R"({"error":"page_not_open"})"; + // It leaves every view of that window first: a container there that + // still showed it would keep watching it from two windows. + if (auto* page = holder->Page(*id); page && holder->contents_view_) { + holder->contents_view_->ReleaseKourContainer(page); + } + holder->viewports_.erase(*id); + // A window whose last tab leaves closes: that window stays, with a + // blank tab of its own (as a new window has), until it is closed. + if (from->count() == 1) chrome::AddAndReturnTabAt(holder->browser_, GURL(url::kAboutBlankURL), -1, false); + std::unique_ptr tab = from->DetachTabAtForInsertion(index); + if (!tab) return R"({"error":"page_not_open"})"; + holder->pages_.erase(*id); + holder->LayoutNow(); + auto* to = browser_->GetTabStripModel(); + const int at = to->InsertDetachedTabAt(to->count(), std::move(tab), AddTabTypes::ADD_NONE); + pages_[*id] = to->GetTabAtIndex(at)->GetHandle().raw_value(); + return State(); + } + if (method == "openPage") { + // Opening an existing identity must preserve its history and navigation. + if (contents) return State(); + // One page, one window: one another window holds is moved or shown + // there (adoptPage, raisePage), never opened twice under one identity. + if (Holder(*id)) return R"({"error":"page_elsewhere"})"; + if (mail_bodies_.Get(*id)) return R"({"error":"invalid_page_id"})"; + const auto* url = args->FindString("url"); + if (!ValidURL(url)) return R"({"error":"invalid_url"})"; + int index = -1; + if (auto native_id = args->FindInt("nativeId")) { + index = Index(*native_id); + if (index < 0) return R"({"error":"native_page_gone"})"; + for (const auto& [other_id, handle] : pages_) { + if (handle == *native_id) return R"({"error":"native_page_bound"})"; + } + } else { + // A page the Agent opens is the browser's to show, documents too. + if (args->FindBool("agent").value_or(false)) kour::LeaveToBrowser(browser_->GetProfile(), GURL(*url)); + // A page of a Space uses that Space's web data, for good. + if (const auto* space = args->FindString("space"); space && !space->empty()) { + if (!kour::ValidSpace(*space)) return R"({"error":"invalid_space"})"; + contents = kour::AddTabInSpace(browser_, GURL(*url), *space); + } else { + contents = chrome::AddAndReturnTabAt(browser_, GURL(*url), -1, false); + } + if (!contents) return R"({"error":"page_creation_failed"})"; + index = model->GetIndexOfWebContents(contents); + } + pages_[*id] = model->GetTabAtIndex(index)->GetHandle().raw_value(); + return State(); + } + if (method == "hasPage") return contents ? R"({"open":true})" : R"({"open":false})"; + if (!contents) return R"({"error":"page_not_open"})"; + if (method == "askingPage") return Asking(contents); + if (method == "evaluatePage") return Evaluate(contents, *args); + if (method == "archivePage") return Archive(contents); + if (method == "printPage") return prints_.Print(contents, browser_->GetProfile()); + if (method == "pageBell") return bells_.Bell(contents, *args->FindString("pageId")); + if (method == "inputPage") return page_input_.Input(contents, *args); + if (method == "capturePage") return page_input_.Capture(contents, *args); + if (method == "contentPage" || method == "toolPage" || method == "evaluateFrame" || + method == "settlePage") { + // the page is laid out and takes input while the Agent reads it or uses its tools + if (!page_input_.KeepAwake(contents)) return R"({"error":"page_not_shown"})"; + if (method == "contentPage") return page_agent_.Content(contents); + if (method == "toolPage") return page_agent_.Tool(contents, *args); + if (method == "settlePage") return page_agent_.Settle(contents); + return page_agent_.EvaluateFrame(contents, *args); + } + if (method == "mediaControl") return kour::MediaControl(contents, *args); + if (method == "captureVideoFrame") return video_frames_.Capture(contents, *args); + // The page takes the keyboard (Kour's find bar closed over it). + if (method == "focusPage") { + Module().focus_parent(panel_.get()); + contents->Focus(); + return R"({"ok":true})"; + } + if (method == "findPage") return KourPageInput::Find(contents, *args); + if (method == "findResultPage") return KourPageInput::FindResult(contents); + if (method == "stopFindPage") return KourPageInput::StopFind(contents, *args); + if (method == "activatePage") { + if (export_id_ >= 0 && GetWidget() && GetWidget()->IsActive()) kour::BrowserHostExport::Get().Foreground(export_id_); + model->ActivateTabAt(model->GetIndexOfWebContents(contents)); + Module().focus_parent(panel_.get()); + contents->Focus(); + } else if (method == "navigatePage") { + const auto* value = args->FindString("url"); + if (!ValidURL(value)) return R"({"error":"invalid_url"})"; + if (args->FindBool("agent").value_or(false)) kour::LeaveToBrowser(browser_->GetProfile(), GURL(*value)); + content::NavigationController::LoadURLParams params{GURL(*value)}; + params.transition_type = ui::PAGE_TRANSITION_TYPED; + contents->GetController().LoadURLWithParams(params); + } else if (method == "backPage") { + if (contents->GetController().CanGoBack()) contents->GetController().GoBack(); + } else if (method == "forwardPage") { + if (contents->GetController().CanGoForward()) contents->GetController().GoForward(); + } else if (method == "reloadPage") { + // `bypassCache`: ⇧⌘R, the page and what it loads fetched again. + contents->GetController().Reload(args->FindBool("bypassCache").value_or(false) + ? content::ReloadType::BYPASSING_CACHE + : content::ReloadType::NORMAL, + true); + } else { + return R"({"error":"unknown_command"})"; + } + return State(); + } + + // The pages `panes` places and where, as `webViewports` and `showPages` + // take them: `result` is what was accepted, in this view's coordinates. + // The error to answer with, or null. + const char* ReadPanes(const base::DictValue& args, + std::map* next, + base::ListValue* result, + std::map* colors = nullptr) const { + const auto* panes = args.FindList("panes"); + if (!panes || panes->size() > 300) return R"({"error":"invalid_viewports"})"; + for (const auto& value : *panes) { + const auto* pane = value.GetIfDict(); + if (!pane) return R"({"error":"invalid_viewports"})"; + const auto* id = pane->FindString("pageId"); + if (!ValidId(id) || !Surface(*id) || next->contains(*id)) + return R"({"error":"invalid_viewport_page"})"; + bool valid = true; + auto number = [&](const char* key) { + // JSON integer and floating point inputs share the same coordinate API. + const auto* number = pane->Find(key); + double coordinate = number && number->is_int() ? number->GetInt() + : number && number->is_double() ? number->GetDouble() : -1; + if (!std::isfinite(coordinate) || coordinate < 0 || coordinate > 100000) { + valid = false; + return 0; + } + return static_cast(std::round(coordinate)); + }; + gfx::Rect bounds(number("x"), number("y"), number("width"), number("height")); + if (!valid) return R"({"error":"invalid_viewport_geometry"})"; + bounds.Intersect(GetLocalBounds()); + for (const auto& [other, rect] : *next) { + if (rect.Intersects(bounds)) return R"({"error":"overlapping_viewports"})"; + } + next->emplace(*id, bounds); + // The colour the shell knows the page by (`color`): under the page + // until it has drawn. + if (colors) { + if (const auto color = kour::ParseColor(pane->FindString("color"))) { + colors->emplace(*id, *color); + } + } + result->Append(base::DictValue().Set("pageId", *id).Set("x", bounds.x()) + .Set("y", bounds.y()).Set("width", bounds.width()).Set("height", bounds.height())); + } + return nullptr; + } + + // Lays the pages out now, not when the window next lays itself out: what + // asked has the answer when the pages are where it says. + // What `page` has under it where it has not drawn. + std::optional Background(const std::string& id, + content::WebContents* page) const { + const auto known = colors_.find(id); + return kour::PageBackground( + page, known == colors_.end() ? std::nullopt : std::optional(known->second), + backdrop_); + } + + void LayoutNow() { + if (!contents_view_) { + if (parent()) parent()->InvalidateLayout(); + return; + } + LayoutWebContents(contents_view_); + contents_view_->DeprecatedLayoutImmediately(); + } + + static const char* HandleCommand(void* context, const char* method, + const char* arguments) { + auto* self = static_cast(context); + self->response_ = self->Command(method, arguments); + return self->response_.c_str(); + } + raw_ptr browser_; + raw_ptr event_root_ = nullptr; + NativeFocusHandler focus_handler_{this}; + std::vector shortcuts_; + std::vector unhandled_; + KourBrowserData browser_data_; + KourExtensionActions extensions_; + // Mail messages' bodies, by the id the shell gave each. + kour::MailBodies mail_bodies_; +#if BUILDFLAG(IS_WIN) + static bool DirectComposition() { + auto* gpu = content::GpuDataManager::GetInstance(); + // The GPU process says so of itself; it goes on saying so when the + // browser composites in software, which leaves no raster context. + return gpu->IsEssentialGpuInfoAvailable() && + gpu->GetGPUInfo().overlay_info.direct_composition && + content::GetContextFactory() + ->SharedMainThreadRasterContextProvider(); + } + // content::GpuDataManagerObserver: a GPU process started, restarted or + // given up for software, and what it then presents through. + void OnGpuInfoUpdate() override { + const bool now = DirectComposition(); + if (now == direct_composition_) return; + direct_composition_ = now; + // (drawn on the window itself, it is not clear under anything) + if (!now) SetBackdrop(false, system_backdrop_dark_); + Record(now ? "directComposition" : "noDirectComposition"); + if (panel_) Module().command(panel_.get(), "presentationChanged"); + } + bool direct_composition_ = false; + + void SetBackdrop(bool on, std::optional dark) { + const bool clear = on != system_backdrop_; + const bool look = clear || dark != system_backdrop_dark_; + system_backdrop_ = on; + system_backdrop_dark_ = dark; + if (!GetWidget() || !look) return; + // The compositor clear or not again (DesktopNativeWidgetAura:: + // UpdateWindowTransparency, through a frame change, which also rebuilds + // the frame view: only when it is needed). + if (clear) GetWidget()->FrameTypeChanged(); + // The backdrop's look set again (a widget's own colour change, which + // would set it, does not happen: the toolbar's colour stays). + if (auto* host = GetWidget()->GetNativeWindow()->GetHost()) { + static_cast(host) + ->BackdropDarkOverrideChanged(); + } + } + // The system's backdrop under the sidebar (windowBackdrop): not the + // shell's colour under the pages ([backdrop_]). + bool system_backdrop_ = false; + std::optional system_backdrop_dark_; +#endif + // A Flutter menu is open over the window (windowOverlays). + bool menus_open_ = false; + // Something of Flutter's dims the whole window (windowOverlays). + bool modal_ = false; +#if BUILDFLAG(IS_LINUX) + views::ViewTracker frames_; +#endif + // Whether a point of the window (root coordinates) is on a page. + bool OverPage(gfx::Point point) const { + views::View::ConvertPointFromWidget(this, &point); + for (const auto& [id, rect] : viewports_) { + if (rect.Contains(point)) return true; + } + return false; + } + bool accessibility_requested_ = false; + std::map> accessibility_modes_; + std::map pages_; + std::map viewports_; + // The view the pages are laid out in, once the window has laid them out. + // It outlives this one: BrowserView takes the shell out first. + raw_ptr contents_view_ = nullptr; + kour::PageSwitch page_switch_{base::BindRepeating( + &KourFlutterPanel::LayoutNow, base::Unretained(this))}; + // The shell's own colour where the pages are (`backdrop`, with the pages' + // places): what a page that has told no colour of its own has under it. + std::optional backdrop_; + // The colour the shell knows each placed page by. + std::map colors_; + // The Agent's scripts by ticket: empty until the page answers. + struct Evaluation { + base::TimeTicks started; + bool done = false; + std::optional value; + }; + std::map evaluations_; + int next_evaluation_ = 0; + // Pages being archived for a clip, by ticket (see Archive), and the page + // each is of until its serializer has answered (never dereferenced). + struct ArchiveJob { + base::TimeTicks started; + bool done = false; + bool ok = false; + base::FilePath path; + std::string url; + }; + std::map archives_; + std::map> archive_pages_; + int next_archive_ = 0; + // Icons asked for and not yet collected: PNG as base64 once found. + std::map icons_; + int next_icon_ = 0; + base::CancelableTaskTracker icon_tasks_; + KourPageInput page_input_; + KourPageAgent page_agent_; + kour::KourVideoFrames video_frames_; + kour::KourPagePrints prints_; + std::vector page_menu_items_; + int page_menu_id_ = -1; + kour::KourPageBells bells_{base::BindRepeating( + [](KourFlutterPanel* self, base::DictValue event) { self->SendPageEvent(event); }, + base::Unretained(this))}; + std::unique_ptr sign_in_; + std::string response_; + std::unique_ptr panel_; + // What the shell was last told of the window's buttons (WindowChrome). + std::optional window_chrome_; + // What else changes what WindowChrome says without resizing the shell. + class ChromeWatch final : public views::WidgetObserver +#if BUILDFLAG(IS_LINUX) + , + public ui::WindowButtonOrderObserver +#endif + { + public: + explicit ChromeWatch(KourFlutterPanel* owner) : owner_(owner) {} + // The window watched from now on (none: none). + void Watch(views::Widget* widget) { + widget_.Reset(); + paint_as_active_ = {}; + if (widget) { + widget_.Observe(widget); + paint_as_active_ = widget->RegisterPaintAsActiveChangedCallback( + base::BindRepeating(&KourFlutterPanel::NotifyWindowChrome, base::Unretained(owner_.get()))); + } +#if BUILDFLAG(IS_LINUX) + order_.Reset(); + if (auto* linux_ui = widget ? ui::LinuxUi::instance() : nullptr) order_.Observe(linux_ui); +#endif + } + void OnWidgetDestroying(views::Widget*) override { + widget_.Reset(); + paint_as_active_ = {}; + } +#if BUILDFLAG(IS_LINUX) + void OnWindowButtonOrderingChange() override { owner_->NotifyWindowChrome(); } +#endif + + private: + raw_ptr owner_; + base::ScopedObservation widget_{this}; + // The window painted in front or not (Widget::ShouldPaintAsActive) changing. + base::CallbackListSubscription paint_as_active_; +#if BUILDFLAG(IS_LINUX) + base::ScopedObservation order_{this}; +#endif + }; + ChromeWatch chrome_watch_{this}; + // A private window's X11 top-level is marked (Linux), once. + bool private_marked_ = false; + bool close_pending_ = false; + bool close_ready_ = false; + // The window was hidden when its close was asked (CanClose). + bool hidden_for_close_ = false; + base::CallbackListSubscription close_cancelled_; + base::OneShotTimer close_watchdog_; + // This window in the browser host (kour_browser_host.h). + // (-1: not the browser host's, a private window) + int export_id_ = -1; + base::WeakPtrFactory weak_factory_{this}; +}; + +BEGIN_METADATA(KourFlutterPanel) +END_METADATA + +} // namespace + +std::unique_ptr CreateKourFlutterPanel(BrowserWindowInterface* browser) { + return std::make_unique(browser); +} + +bool KourDrawsWindowButtons(BrowserWidget* widget) { + if (!widget) return false; +#if BUILDFLAG(IS_LINUX) + // Under the system's title bar the window manager draws them. + auto* native = widget->browser_native_widget(); + return native && native->UseCustomFrame(); +#else + return true; +#endif +} + +void LayoutKourWebContents(views::View* shell, MultiContentsView* contents) { + static_cast(shell)->LayoutWebContents(contents); +} + +bool HandleKourUnhandledKey(views::View* shell, const input::NativeWebKeyboardEvent& event) { + return static_cast(shell)->HandleUnhandledKey(event); +} + +bool CanCloseKourWindow(views::View* shell, base::OnceClosure retry_close) { + return static_cast(shell)->CanClose(std::move(retry_close)); +} + +#if BUILDFLAG(IS_WIN) +bool KourShellWantsBackdrop(views::View* shell) { + return static_cast(shell)->WantsBackdrop(); +} + +std::optional KourShellBackdropDark(views::View* shell) { + return static_cast(shell)->BackdropDark(); +} +#endif + +#if BUILDFLAG(IS_LINUX) +void AttachKourShellFrames(views::View* shell, views::View* frames) { + static_cast(shell)->AttachFrames(frames); +} +#endif diff --git a/chrome/browser/ui/views/side_panel/kour_desktop_panel_abi.h b/chrome/browser/ui/views/side_panel/kour_desktop_panel_abi.h new file mode 100644 index 0000000000..e10f848a08 --- /dev/null +++ b/chrome/browser/ui/views/side_panel/kour_desktop_panel_abi.h @@ -0,0 +1,135 @@ +#ifndef KOUR_DESKTOP_PANEL_ABI_H_ +#define KOUR_DESKTOP_PANEL_ABI_H_ +#include +#if defined(_WIN32) && defined(KOUR_PANEL_BUILD) +#define KOUR_PANEL_EXPORT __declspec(dllexport) +#elif defined(__GNUC__) +#define KOUR_PANEL_EXPORT __attribute__((visibility("default"))) +#else +#define KOUR_PANEL_EXPORT +#endif +#ifdef __cplusplus +extern "C" { +#endif + +// ABI 10: what happened in a page, for the window's shell +// (KourDesktopPanelPageEvent). +// ABI 9: the browser hands the panel, before its first window, what the +// application may ask of it while no window is open +// (KourSetDesktopApplicationCommand): staying when Kour's last window closes +// ("stay" {on}), a new window ("openWindow"), quitting ("quit"). +// ABI 8: every window is a view of one engine; a window's close is asked of +// it on its own channel, with whether the application quits (the browser's +// closeReason command). +// ABI 7: Windows HWND / Linux X11 XID parenting; the browser hands the panel +// a command taken from the keyboard; the panel hands the browser its frames +// where the browser's compositor is what puts them over the pages. Every +// call and callback is confined to Chromium's browser UI thread; no renderer +// loads this module. +typedef const char* (*KourHostCommand)(void*, const char*, const char*); +typedef void (*KourCloseReply)(void*, int); +KOUR_PANEL_EXPORT unsigned KourPanelAbiVersion(void); +// The browser ends (nothing keeps it alive any more: no window of any kind, +// no background work): the application's Dart is told (`quit` on +// kour/windows) and answered before this returns, 30 seconds at most. +// Called once, on the browser UI thread, outside any window's teardown. +KOUR_PANEL_EXPORT void KourDesktopApplicationEnding(void); +// The application's command (ABI 9): `method` and `arguments` (a JSON +// object) in, a JSON answer out, the browser's until its next call. Called +// on the browser UI thread. +typedef const char* (*KourApplicationCommand)(const char* method, const char* arguments); +KOUR_PANEL_EXPORT void KourSetDesktopApplicationCommand(KourApplicationCommand command); +KOUR_PANEL_EXPORT void* KourCreateDesktopPanel(const char* payload_path, + uintptr_t parent_window, KourHostCommand command, void* context); +// Native parent-client coordinates are physical pixels. Browser scale converts +// Chromium DIP to those pixels; the bridge independently measures Flutter DPI. +KOUR_PANEL_EXPORT void KourResizeDesktopPanel(void*, int x, int y, + int width, int height, double browser_scale); +KOUR_PANEL_EXPORT void KourShowDesktopPanel(void*, int visible); +KOUR_PANEL_EXPORT void KourFocusDesktopPanel(void*); +KOUR_PANEL_EXPORT void KourFocusDesktopParent(void*); +// One of Kour's commands ("newTab", "closeTab"…), given by a key the browser +// took while a web page had the keyboard. The panel's application runs it. +KOUR_PANEL_EXPORT void KourDesktopPanelCommand(void*, const char* id); +// What happened in one of the window's pages, as a JSON object ({pageId, +// kind, ...}: a reading of the page is due, its document changed, a script's +// answer is in, a menu item was chosen): the window's channel is given it as +// `pageEvent`. Borrowed for the call; browser UI thread. +KOUR_PANEL_EXPORT void KourDesktopPanelPageEvent(void*, const char* event_json); +// The shell over the pages (docs/research/2026-10-09-shell-over-pages.md). +// Where the system blends Flutter's window over the pages itself (Windows: +// its picture on the root window's topmost composition target) nothing of +// this is used. Where it cannot (X11), the panel gives the browser each of +// its frames while something of Flutter's is over a page, and the browser +// draws them in a layer of its own above the pages. +// +// A frame is the whole panel. One frame pixel is one device pixel of the +// browser window; the frame's top-left is the panel's top-left as last given +// to KourResizeDesktopPanel; a frame is never stretched (one of another size +// than the panel is drawn at its own size, clipped to the panel). +// +// A memory frame: `pixels` is `height` rows of `stride` bytes (`stride` is +// positive and at least 4 * width), 8 bits a channel, premultiplied, sRGB, +// in the byte order `format` names; the rows run top to bottom unless +// `flags` has KOUR_PANEL_FRAME_BOTTOM_UP. The panel keeps `pixels` alive and +// unchanged until the sink returns; the browser copies what it keeps. +// +// A dmabuf frame (`dmabuf_fd` >= 0, `pixels` null): one plane, described by +// `drm_format`, `drm_modifier`, `offset` and `stride`; a buffer that needs +// more planes is sent as memory. The browser duplicates the descriptor +// during the call. `release` is then owed exactly once, on the browser UI +// thread, when the browser no longer reads the buffer; the panel does not +// draw into it before. Every release owed is called before +// KourSetDesktopPanelFrameSink(panel, null, ...) returns, so before +// KourDestroyPanel, and when the browser loses its GPU context; a buffer +// released that way may still be read for a frame, so the panel frees it +// rather than drawing into it again. A sink that refuses a frame (returns +// 0 for it, below) owes no release for it. A panel sends dmabufs only where +// its engine can export one; memory is always understood. +// +// `damage_*` is what changed since the frame before, the whole frame when +// its width is 0; it is ignored for the first frame after a null one and +// when the frame's size differs from the frame before. +// +// The sink returns 1 once a frame of that size is what the browser shows +// (it may be this one or the one before), 0 until then or if it cannot take +// the frame. Start: the panel sends whole frames and takes its own window +// off the screen only after the sink has returned 1 for a frame of the +// panel's present size. Stop: the panel puts its window back on the screen +// first, then sends a null frame, at which the browser stops drawing its +// layer (the return is then 0). +// +// The panel marshals: the sink is only ever called on the browser UI thread +// (on Linux the default GLib main context, which Chromium's UI message pump +// runs), whichever thread the engine made the frame on. +#define KOUR_PANEL_FRAME_BGRA8888 1u // bytes B, G, R, A +#define KOUR_PANEL_FRAME_RGBA8888 2u // bytes R, G, B, A +#define KOUR_PANEL_FRAME_BOTTOM_UP 1u +typedef struct KourPanelFrame { + uint32_t struct_size; // sizeof(KourPanelFrame), for a later field + uint32_t format; // of a memory frame: KOUR_PANEL_FRAME_BGRA8888 or _RGBA8888 + int32_t width, height; + int32_t stride; // bytes from one row to the next + uint32_t flags; // KOUR_PANEL_FRAME_BOTTOM_UP + const void* pixels; // a memory frame; null for a dmabuf + int32_t dmabuf_fd; // -1 for a memory frame + uint32_t drm_format; // the dmabuf's DRM fourcc + uint64_t drm_modifier; + uint32_t offset; // of the plane in the dmabuf + int32_t damage_x, damage_y, damage_width, damage_height; + void (*release)(void* release_context); + void* release_context; +} KourPanelFrame; +typedef int (*KourFrameSink)(void* context, const KourPanelFrame* frame); +// Given once after the panel is made, and taken back (null) before the view +// that draws the frames goes. A browser that never gives one draws no layer: +// the panel keeps cutting the pages out of its window. After the sink is +// null the browser calls nothing of the panel's frames. +KOUR_PANEL_EXPORT void KourSetDesktopPanelFrameSink(void*, KourFrameSink, void* context); +// A pending reply is completed exactly once, including cancellation at teardown. +KOUR_PANEL_EXPORT void KourPreparePanelClose(void*, KourCloseReply, void*); +KOUR_PANEL_EXPORT void KourDestroyPanel(void*); +#ifdef __cplusplus +} +#endif +#endif diff --git a/chrome/app/kour_payload_prune.py b/chrome/app/kour_payload_prune.py new file mode 100644 index 0000000000..95fccc80f0 --- /dev/null +++ b/chrome/app/kour_payload_prune.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +# Copyright 2026 ParkourLabs, Inc. +"""Remove from the output's payload/ every file Kour's record does not list.""" +import json +import os +import sys + + +def main(record, payload, stamp): + with open(record, encoding="utf-8") as stream: + bundle = json.load(stream) + listed = set() + for directory in bundle["directories"]: + for name in directory["files"]: + listed.add(os.path.normpath(os.path.join(directory["path"], name))) + if os.path.isdir(payload): + for root, folders, files in os.walk(payload, topdown=False): + for name in files: + path = os.path.join(root, name) + if os.path.normpath(os.path.relpath(path, payload)) not in listed: + os.remove(path) + for name in folders: + path = os.path.join(root, name) + if not os.listdir(path): + os.rmdir(path) + with open(stamp, "w", encoding="utf-8") as stream: + stream.write("pruned\n") + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/build/util/branding.gni b/build/util/branding.gni index 1d4ffd68a7..9880b24be1 100644 --- a/build/util/branding.gni +++ b/build/util/branding.gni @@ -21,7 +21,9 @@ _branding_dictionary_template = "creator_code = \"@MAC_CREATOR_CODE@\" " + "installer_full_name = \"@PRODUCT_INSTALLER_FULLNAME@\" " + "installer_short_name = \"@PRODUCT_INSTALLER_SHORTNAME@\" " + - "team_id = \"@MAC_TEAM_ID@\" " + "team_id = \"@MAC_TEAM_ID@\" " + + "kour_executable = \"@KOUR_EXECUTABLE@\" " + + "kour_data_dir = \"@KOUR_DATA_DIR@\" " _result = exec_script("version.py", [ @@ -38,6 +40,11 @@ chrome_product_short_name = _result.short_name chrome_product_installer_full_name = _result.installer_full_name chrome_product_installer_short_name = _result.installer_short_name +# Kour: the browser's file name on Windows and Linux, and its data directory's +# name (BRANDING KOUR_EXECUTABLE, KOUR_DATA_DIR). +kour_executable = _result.kour_executable +kour_data_dir = _result.kour_data_dir + if (is_mac) { chrome_mac_bundle_id = _result.bundle_id chrome_mac_creator_code = _result.creator_code diff --git a/chrome/app/theme/chromium/BRANDING b/chrome/app/theme/chromium/BRANDING index f8363d5b29..e6df10bb9e 100644 --- a/chrome/app/theme/chromium/BRANDING +++ b/chrome/app/theme/chromium/BRANDING @@ -8,3 +8,5 @@ COPYRIGHT=Copyright @LASTCHANGE_YEAR@ The Chromium Authors. All rights reserved. MAC_BUNDLE_ID=org.chromium.Chromium MAC_CREATOR_CODE=Cr24 MAC_TEAM_ID= +KOUR_EXECUTABLE=chrome +KOUR_DATA_DIR=Kour Unbranded diff --git a/chrome/common/chrome_version.h.in b/chrome/common/chrome_version.h.in index 8449e74fa0..263306d1f4 100644 --- a/chrome/common/chrome_version.h.in +++ b/chrome/common/chrome_version.h.in @@ -21,6 +21,10 @@ #define PRODUCT_FULLNAME_STRING "@PRODUCT_FULLNAME@" #define PRODUCT_SHORTNAME_STRING "@PRODUCT_SHORTNAME@" #define COPYRIGHT_STRING "@COPYRIGHT@" +// Kour: the browser's file name on Windows and Linux (no extension), and its +// data directory's name. +#define KOUR_EXECUTABLE_STRING "@KOUR_EXECUTABLE@" +#define KOUR_DATA_DIR_STRING "@KOUR_DATA_DIR@" #define OFFICIAL_BUILD_STRING "@OFFICIAL_BUILD@" // Distribution Information diff --git a/chrome/common/chrome_constants.cc b/chrome/common/chrome_constants.cc index 1a6b899b4b..91bb7fc794 100644 --- a/chrome/common/chrome_constants.cc +++ b/chrome/common/chrome_constants.cc @@ -31,10 +31,11 @@ const char kChromeVersion[] = CHROME_VERSION_STRING; // do so. #if BUILDFLAG(IS_WIN) +// Kour's file name (BRANDING KOUR_EXECUTABLE). const base::FilePath::CharType kBrowserProcessExecutableName[] = - FPL("chrome.exe"); + L"" KOUR_EXECUTABLE_STRING L".exe"; const base::FilePath::CharType kHelperProcessExecutableName[] = - FPL("chrome.exe"); + L"" KOUR_EXECUTABLE_STRING L".exe"; #elif BUILDFLAG(IS_MAC) const base::FilePath::CharType kBrowserProcessExecutableName[] = FPL(PRODUCT_FULLNAME_STRING); @@ -46,7 +47,10 @@ const base::FilePath::CharType kBrowserProcessExecutableName[] = FPL("chrome"); const base::FilePath::CharType kHelperProcessExecutableName[] = FPL("sandboxed_process"); #elif BUILDFLAG(IS_POSIX) -const base::FilePath::CharType kBrowserProcessExecutableName[] = FPL("chrome"); +// Kour's file name (BRANDING KOUR_EXECUTABLE). The process singleton compares +// it with the running browser's, so it must be the real one. +const base::FilePath::CharType kBrowserProcessExecutableName[] = + FPL(KOUR_EXECUTABLE_STRING); // Helper processes end up with a name of "exe" due to execing via // /proc/self/exe. See bug 22703. const base::FilePath::CharType kHelperProcessExecutableName[] = FPL("exe"); @@ -54,9 +58,9 @@ const base::FilePath::CharType kHelperProcessExecutableName[] = FPL("exe"); #if BUILDFLAG(IS_WIN) const base::FilePath::CharType kBrowserProcessExecutablePath[] = - FPL("chrome.exe"); + L"" KOUR_EXECUTABLE_STRING L".exe"; const base::FilePath::CharType kHelperProcessExecutablePath[] = - FPL("chrome.exe"); + L"" KOUR_EXECUTABLE_STRING L".exe"; #elif BUILDFLAG(IS_MAC) const base::FilePath::CharType kBrowserProcessExecutablePath[] = FPL(PRODUCT_FULLNAME_STRING ".app/Contents/MacOS/" PRODUCT_FULLNAME_STRING); diff --git a/chrome/common/chrome_paths_linux.cc b/chrome/common/chrome_paths_linux.cc index 5575c049b2..dac37578a6 100644 --- a/chrome/common/chrome_paths_linux.cc +++ b/chrome/common/chrome_paths_linux.cc @@ -17,6 +17,7 @@ #include "build/build_config.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_paths_internal.h" +#include "chrome/common/chrome_version.h" namespace chrome { @@ -77,6 +78,22 @@ bool GetUserMediaDirectory(const std::string& xdg_name, // See http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html // for a spec on where config files go. Using ~/.config also helps us sidestep // issues with other apps grabbing ~/.chromium . +#if BUILDFLAG(IS_LINUX) +// Kour keeps everything of its own in one data directory, +// $XDG_DATA_HOME/ (else ~/.local/share/): the +// profile in Profile/, crash dumps in Crashpad/. These are Chromium's +// defaults, so nothing has to be passed to the browser. +base::FilePath GetKourDataRoot() { + std::unique_ptr env(base::Environment::Create()); + return GetXDGDirectory(env.get(), "XDG_DATA_HOME", ".local/share") + .Append(KOUR_EXECUTABLE_STRING); +} + +bool GetDefaultUserDataDirectory(base::FilePath* result) { + *result = GetKourDataRoot().Append("Profile"); + return true; +} +#else bool GetDefaultUserDataDirectory(base::FilePath* result) { std::unique_ptr env(base::Environment::Create()); base::FilePath config_dir; @@ -100,6 +117,7 @@ bool GetDefaultUserDataDirectory(base::FilePath* result) { *result = config_dir.Append(data_dir_basename + GetChannelSuffixForDataDir()); return true; } +#endif // BUILDFLAG(IS_LINUX) void GetUserCacheDirectory(const base::FilePath& profile_dir, base::FilePath* result) { @@ -119,6 +137,15 @@ void GetUserCacheDirectory(const base::FilePath& profile_dir, base::FilePath cache_dir; if (!base::PathService::Get(base::DIR_CACHE, &cache_dir)) return; +#if BUILDFLAG(IS_LINUX) + // Kour: a profile in its data directory caches under + // $XDG_CACHE_HOME/, at the same relative path. + base::FilePath relative; + if (GetKourDataRoot().AppendRelativePath(profile_dir, &relative)) { + *result = cache_dir.Append(KOUR_EXECUTABLE_STRING).Append(relative); + return; + } +#endif base::FilePath config_dir(GetXDGDirectory(env.get(), kXdgConfigHomeEnvVar, kDotConfigDir)); diff --git a/chrome/common/chrome_paths.cc b/chrome/common/chrome_paths.cc index 32d01c008e..f8f219aa45 100644 --- a/chrome/common/chrome_paths.cc +++ b/chrome/common/chrome_paths.cc @@ -17,6 +17,7 @@ #include "chrome/common/buildflags.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths_internal.h" +#include "chrome/common/chrome_version.h" #include "extensions/buildflags/buildflags.h" #include "media/media_buildflags.h" @@ -224,7 +225,14 @@ bool PathProvider(int key, base::FilePath* result) { return false; } #endif -#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID) +#if BUILDFLAG(IS_LINUX) + // Kour: beside the profile in its data directory, not inside it. + cur = GetKourDataRoot().Append(FILE_PATH_LITERAL("Crashpad")); +#elif BUILDFLAG(IS_WIN) + // Kour: beside the default profile (\Profile), as + // install_static::GetCrashDumpLocation() puts it for Crashpad. + cur = cur.DirName().Append(FILE_PATH_LITERAL("Crashpad")); +#elif BUILDFLAG(IS_MAC) || BUILDFLAG(IS_ANDROID) cur = cur.Append(FILE_PATH_LITERAL("Crashpad")); #else cur = cur.Append(FILE_PATH_LITERAL("Crash Reports")); @@ -521,6 +529,19 @@ bool PathProvider(int key, base::FilePath* result) { return true; } +bool GetKourDefaultUserDataDirectory(base::FilePath* result) { +#if BUILDFLAG(IS_MAC) + // The brand's own directory: Kour Nightly never shares Kour's data. + if (!base::PathService::Get(base::DIR_APP_DATA, result)) { + return false; + } + *result = result->Append(KOUR_DATA_DIR_STRING).Append("Profile"); + return true; +#else + return GetDefaultUserDataDirectory(result); +#endif +} + std::optional IsUsingDefaultDataDirectory() { if (g_override_using_default_data_directory_for_testing.has_value()) { return g_override_using_default_data_directory_for_testing.value(); diff --git a/chrome/common/chrome_paths_internal.h b/chrome/common/chrome_paths_internal.h index 8deb4b9838..3162201e37 100644 --- a/chrome/common/chrome_paths_internal.h +++ b/chrome/common/chrome_paths_internal.h @@ -26,6 +26,17 @@ namespace chrome { // DIR_USER_DATA has been overridden by a command-line option. bool GetDefaultUserDataDirectory(base::FilePath* result); +#if BUILDFLAG(IS_LINUX) +// Kour's data directory: the default user data directory is its Profile/ +// and the crash database its Crashpad/. +base::FilePath GetKourDataRoot(); +#endif + +// Kour's own profile: the user data directory the browser takes when it is +// given no other. macOS passes it itself (chrome_main.cc); on Windows and +// Linux it is Chromium's default (install_static, chrome_paths_linux.cc). +bool GetKourDefaultUserDataDirectory(base::FilePath* result); + // Returns true if the current user data directory is the default user data // directory. Returns `std::nullopt` if this could not be determined e.g. API // calls failed. diff --git a/chrome/common/BUILD.gn b/chrome/common/BUILD.gn index 582f9b2193..3f767b372e 100644 --- a/chrome/common/BUILD.gn +++ b/chrome/common/BUILD.gn @@ -104,6 +104,7 @@ source_set("channel_info") { deps += [ "//chromeos/ash/components/channel" ] } else if (is_posix) { sources += [ "channel_info_posix.cc" ] + deps += [ ":version_header" ] } } @@ -690,6 +691,7 @@ mojom("mojo_bindings") { sources = [ "actor.mojom", "chrome_render_frame.mojom", + "kour_page_bell.mojom", "google_accounts_private_api_extension.mojom", "media/webrtc_logging.mojom", "net/net_error_page_support.mojom", diff --git a/chrome/common/channel_info_posix.cc b/chrome/common/channel_info_posix.cc index f6bcb3cc8e..b1b6e7078c 100644 --- a/chrome/common/channel_info_posix.cc +++ b/chrome/common/channel_info_posix.cc @@ -15,6 +15,7 @@ #include "base/strings/string_util.h" #include "base/version_info/nix/version_extra_utils.h" #include "build/branding_buildflags.h" +#include "chrome/common/chrome_version.h" #include "build/build_config.h" #include "components/version_info/version_info.h" @@ -148,7 +149,8 @@ std::string GetDesktopName(base::Environment* env) { if (name.has_value() && !name.value().empty()) { return name.value(); } - return "chromium-browser.desktop"; + // Kour's desktop file is named after its executable (kour.desktop). + return KOUR_EXECUTABLE_STRING ".desktop"; #endif } #endif // BUILDFLAG(IS_LINUX) diff --git a/chrome/browser/shell_integration_linux.cc b/chrome/browser/shell_integration_linux.cc index bc6dc20d5b..9c7d380d0a 100644 --- a/chrome/browser/shell_integration_linux.cc +++ b/chrome/browser/shell_integration_linux.cc @@ -44,6 +44,7 @@ #include "chrome/browser/web_applications/web_app_helpers.h" #include "chrome/common/buildflags.h" #include "chrome/common/channel_info.h" +#include "chrome/common/chrome_version.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" #include "chrome/grit/branded_strings.h" @@ -471,7 +472,8 @@ std::string GetIconName() { #if BUILDFLAG(GOOGLE_CHROME_BRANDING) return "google-chrome"; #else // BUILDFLAG(CHROMIUM_BRANDING) - return "chromium-browser"; + // Kour's icon, installed with its desktop file under its executable's name. + return KOUR_EXECUTABLE_STRING; #endif } @@ -885,7 +887,7 @@ std::string GetDirectLaunchUrlScheme() { return "google-chrome"; } #else - return "chromium"; + return KOUR_EXECUTABLE_STRING; #endif } diff --git a/components/os_crypt/async/browser/freedesktop_secret_key_provider.h b/components/os_crypt/async/browser/freedesktop_secret_key_provider.h index e2eb3958ef..505c2f2624 100644 --- a/components/os_crypt/async/browser/freedesktop_secret_key_provider.h +++ b/components/os_crypt/async/browser/freedesktop_secret_key_provider.h @@ -158,9 +158,10 @@ class FreedesktopSecretKeyProvider : public KeyProvider { static constexpr char kKeyName[] = "Chrome Safe Storage"; static constexpr char kAppName[] = "chrome"; #else - static constexpr char kKWalletFolder[] = "Chromium Keys"; - static constexpr char kKeyName[] = "Chromium Safe Storage"; - static constexpr char kAppName[] = "chromium"; + // Kour's own key, not the one every unbranded Chromium shares. + static constexpr char kKWalletFolder[] = "Kour Keys"; + static constexpr char kKeyName[] = "Kour Safe Storage"; + static constexpr char kAppName[] = "kour"; #endif void InitializeFreedesktopSecretService(); diff --git a/chrome/app/theme/chrome_unscaled_resources.grd b/chrome/app/theme/chrome_unscaled_resources.grd index c8fb1b8e88..2cffbfc0e3 100644 --- a/chrome/app/theme/chrome_unscaled_resources.grd +++ b/chrome/app/theme/chrome_unscaled_resources.grd @@ -88,10 +88,10 @@ - - - - + + + +