123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785 |
- // Copyright (c) 2014 GitHub, Inc.
- // Use of this source code is governed by the MIT license that can be
- // found in the LICENSE file.
- #include "shell/browser/native_window_views.h"
- #if BUILDFLAG(IS_WIN)
- #include <dwmapi.h>
- #include <wrl/client.h>
- #endif
- #include <memory>
- #include <utility>
- #include <vector>
- #include "base/containers/contains.h"
- #include "base/memory/raw_ptr.h"
- #include "base/stl_util.h"
- #include "base/strings/utf_string_conversions.h"
- #include "content/public/browser/browser_thread.h"
- #include "content/public/browser/desktop_media_id.h"
- #include "shell/browser/api/electron_api_web_contents.h"
- #include "shell/browser/native_browser_view_views.h"
- #include "shell/browser/ui/inspectable_web_contents.h"
- #include "shell/browser/ui/views/inspectable_web_contents_view_views.h"
- #include "shell/browser/ui/views/root_view.h"
- #include "shell/browser/web_contents_preferences.h"
- #include "shell/browser/web_view_manager.h"
- #include "shell/browser/window_list.h"
- #include "shell/common/electron_constants.h"
- #include "shell/common/gin_converters/image_converter.h"
- #include "shell/common/gin_helper/dictionary.h"
- #include "shell/common/options_switches.h"
- #include "ui/aura/window_tree_host.h"
- #include "ui/base/hit_test.h"
- #include "ui/gfx/image/image.h"
- #include "ui/gfx/native_widget_types.h"
- #include "ui/views/background.h"
- #include "ui/views/controls/webview/webview.h"
- #include "ui/views/widget/native_widget_private.h"
- #include "ui/views/widget/widget.h"
- #include "ui/views/window/client_view.h"
- #include "ui/wm/core/shadow_types.h"
- #include "ui/wm/core/window_util.h"
- #if BUILDFLAG(IS_LINUX)
- #include "base/strings/string_util.h"
- #include "shell/browser/browser.h"
- #include "shell/browser/linux/unity_service.h"
- #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h"
- #include "shell/browser/ui/views/client_frame_view_linux.h"
- #include "shell/browser/ui/views/frameless_view.h"
- #include "shell/browser/ui/views/native_frame_view.h"
- #include "shell/common/platform_util.h"
- #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
- #include "ui/views/window/native_frame_view.h"
- #if defined(USE_OZONE)
- #include "shell/browser/ui/views/global_menu_bar_x11.h"
- #include "shell/browser/ui/x/event_disabler.h"
- #include "shell/browser/ui/x/x_window_utils.h"
- #include "ui/base/x/x11_util.h"
- #include "ui/gfx/x/shape.h"
- #include "ui/gfx/x/x11_atom_cache.h"
- #include "ui/gfx/x/xproto.h"
- #include "ui/gfx/x/xproto_util.h"
- #include "ui/ozone/public/ozone_platform.h"
- #endif
- #elif BUILDFLAG(IS_WIN)
- #include "base/win/win_util.h"
- #include "base/win/windows_version.h"
- #include "content/public/common/color_parser.h"
- #include "shell/browser/ui/views/win_frame_view.h"
- #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h"
- #include "skia/ext/skia_utils_win.h"
- #include "ui/base/win/shell.h"
- #include "ui/display/screen.h"
- #include "ui/display/win/screen_win.h"
- #include "ui/gfx/color_utils.h"
- #include "ui/gfx/win/msg_util.h"
- #endif
- namespace electron {
- #if BUILDFLAG(IS_WIN)
- DWM_SYSTEMBACKDROP_TYPE GetBackdropFromString(const std::string& material) {
- if (material == "none") {
- return DWMSBT_NONE;
- } else if (material == "acrylic") {
- return DWMSBT_TRANSIENTWINDOW;
- } else if (material == "mica") {
- return DWMSBT_MAINWINDOW;
- } else if (material == "tabbed") {
- return DWMSBT_TABBEDWINDOW;
- }
- return DWMSBT_AUTO;
- }
- // Similar to the ones in display::win::ScreenWin, but with rounded values
- // These help to avoid problems that arise from unresizable windows where the
- // original ceil()-ed values can cause calculation errors, since converting
- // both ways goes through a ceil() call. Related issue: #15816
- gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) {
- float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd);
- gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor);
- dip_rect.set_origin(
- display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin());
- return dip_rect;
- }
- #endif
- namespace {
- #if BUILDFLAG(IS_WIN)
- const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd";
- void FlipWindowStyle(HWND handle, bool on, DWORD flag) {
- DWORD style = ::GetWindowLong(handle, GWL_STYLE);
- if (on)
- style |= flag;
- else
- style &= ~flag;
- ::SetWindowLong(handle, GWL_STYLE, style);
- // Window's frame styles are cached so we need to call SetWindowPos
- // with the SWP_FRAMECHANGED flag to update cache properly.
- ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored
- SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
- SWP_NOACTIVATE | SWP_NOOWNERZORDER);
- }
- gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) {
- float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd);
- gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor);
- screen_rect.set_origin(
- display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin());
- return screen_rect;
- }
- // Chromium uses a buggy implementation that converts content rect to window
- // rect when calculating min/max size, we should use the same implementation
- // when passing min/max size so we can get correct results.
- gfx::Size WindowSizeToContentSizeBuggy(HWND hwnd, const gfx::Size& size) {
- // Calculate the size of window frame, using same code with the
- // HWNDMessageHandler::OnGetMinMaxInfo method.
- // The pitfall is, when window is minimized the calculated window frame size
- // will be different from other states.
- RECT client_rect, rect;
- GetClientRect(hwnd, &client_rect);
- GetWindowRect(hwnd, &rect);
- CR_DEFLATE_RECT(&rect, &client_rect);
- // Convert DIP size to pixel size, do calculation and then return DIP size.
- gfx::Rect screen_rect = DIPToScreenRect(hwnd, gfx::Rect(size));
- gfx::Size screen_client_size(screen_rect.width() - (rect.right - rect.left),
- screen_rect.height() - (rect.bottom - rect.top));
- return ScreenToDIPRect(hwnd, gfx::Rect(screen_client_size)).size();
- }
- #endif
- #if defined(USE_OZONE)
- bool CreateGlobalMenuBar() {
- return ui::OzonePlatform::GetInstance()
- ->GetPlatformProperties()
- .supports_global_application_menus;
- }
- #endif
- #if defined(USE_OZONE_PLATFORM_X11)
- bool IsX11() {
- return ui::OzonePlatform::GetInstance()
- ->GetPlatformProperties()
- .electron_can_call_x11;
- }
- #endif
- class NativeWindowClientView : public views::ClientView {
- public:
- NativeWindowClientView(views::Widget* widget,
- views::View* root_view,
- NativeWindowViews* window)
- : views::ClientView{widget, root_view},
- window_{raw_ref<NativeWindowViews>::from_ptr(window)} {}
- ~NativeWindowClientView() override = default;
- // disable copy
- NativeWindowClientView(const NativeWindowClientView&) = delete;
- NativeWindowClientView& operator=(const NativeWindowClientView&) = delete;
- views::CloseRequestResult OnWindowCloseRequested() override {
- window_->NotifyWindowCloseButtonClicked();
- return views::CloseRequestResult::kCannotClose;
- }
- private:
- const raw_ref<NativeWindowViews> window_;
- };
- } // namespace
- NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options,
- NativeWindow* parent)
- : NativeWindow(options, parent) {
- options.Get(options::kTitle, &title_);
- bool menu_bar_autohide;
- if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide))
- root_view_.SetAutoHideMenuBar(menu_bar_autohide);
- #if BUILDFLAG(IS_WIN)
- // On Windows we rely on the CanResize() to indicate whether window can be
- // resized, and it should be set before window is created.
- options.Get(options::kResizable, &resizable_);
- options.Get(options::kMinimizable, &minimizable_);
- options.Get(options::kMaximizable, &maximizable_);
- // Transparent window must not have thick frame.
- options.Get("thickFrame", &thick_frame_);
- if (transparent())
- thick_frame_ = false;
- overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE);
- overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT);
- v8::Local<v8::Value> titlebar_overlay;
- if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) &&
- titlebar_overlay->IsObject()) {
- gin_helper::Dictionary titlebar_overlay_obj =
- gin::Dictionary::CreateEmpty(options.isolate());
- options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj);
- std::string overlay_color_string;
- if (titlebar_overlay_obj.Get(options::kOverlayButtonColor,
- &overlay_color_string)) {
- bool success = content::ParseCssColorString(overlay_color_string,
- &overlay_button_color_);
- DCHECK(success);
- }
- std::string overlay_symbol_color_string;
- if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor,
- &overlay_symbol_color_string)) {
- bool success = content::ParseCssColorString(overlay_symbol_color_string,
- &overlay_symbol_color_);
- DCHECK(success);
- }
- }
- if (title_bar_style_ != TitleBarStyle::kNormal)
- set_has_frame(false);
- // If the taskbar is re-created after we start up, we have to rebuild all of
- // our buttons.
- taskbar_created_message_ = RegisterWindowMessage(TEXT("TaskbarCreated"));
- #endif
- if (enable_larger_than_screen())
- // We need to set a default maximum window size here otherwise Windows
- // will not allow us to resize the window larger than scree.
- // Setting directly to INT_MAX somehow doesn't work, so we just divide
- // by 10, which should still be large enough.
- SetContentSizeConstraints(extensions::SizeConstraints(
- gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10)));
- int width = 800, height = 600;
- options.Get(options::kWidth, &width);
- options.Get(options::kHeight, &height);
- gfx::Rect bounds(0, 0, width, height);
- widget_size_ = bounds.size();
- widget()->AddObserver(this);
- views::Widget::InitParams params;
- params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
- params.bounds = bounds;
- params.delegate = this;
- params.type = views::Widget::InitParams::TYPE_WINDOW;
- params.remove_standard_frame = !has_frame() || has_client_frame();
- // If a client frame, we need to draw our own shadows.
- if (transparent() || has_client_frame())
- params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent;
- // The given window is most likely not rectangular since it uses
- // transparency and has no standard frame, don't show a shadow for it.
- if (transparent() && !has_frame())
- params.shadow_type = views::Widget::InitParams::ShadowType::kNone;
- bool focusable;
- if (options.Get(options::kFocusable, &focusable) && !focusable)
- params.activatable = views::Widget::InitParams::Activatable::kNo;
- #if BUILDFLAG(IS_WIN)
- if (parent)
- params.parent = parent->GetNativeWindow();
- params.native_widget = new ElectronDesktopNativeWidgetAura(this);
- #elif BUILDFLAG(IS_LINUX)
- std::string name = Browser::Get()->GetName();
- // Set WM_WINDOW_ROLE.
- params.wm_role_name = "browser-window";
- // Set WM_CLASS.
- params.wm_class_name = base::ToLowerASCII(name);
- params.wm_class_class = name;
- // Set Wayland application ID.
- params.wayland_app_id = platform_util::GetXdgAppId();
- auto* native_widget = new views::DesktopNativeWidgetAura(widget());
- params.native_widget = native_widget;
- params.desktop_window_tree_host =
- new ElectronDesktopWindowTreeHostLinux(this, native_widget);
- #endif
- widget()->Init(std::move(params));
- SetCanResize(resizable_);
- bool fullscreen = false;
- options.Get(options::kFullscreen, &fullscreen);
- std::string window_type;
- options.Get(options::kType, &window_type);
- #if BUILDFLAG(IS_LINUX)
- // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set.
- bool use_dark_theme = false;
- if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) {
- SetGTKDarkThemeEnabled(use_dark_theme);
- }
- if (parent)
- SetParentWindow(parent);
- #endif
- #if defined(USE_OZONE_PLATFORM_X11)
- if (IsX11()) {
- // Before the window is mapped the SetWMSpecState can not work, so we have
- // to manually set the _NET_WM_STATE.
- std::vector<x11::Atom> state_atom_list;
- // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE.
- if (fullscreen) {
- state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN"));
- }
- if (parent) {
- // Force using dialog type for child window.
- window_type = "dialog";
- // Modal window needs the _NET_WM_STATE_MODAL hint.
- if (is_modal())
- state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL"));
- }
- if (!state_atom_list.empty())
- SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()),
- x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM,
- state_atom_list);
- // Set the _NET_WM_WINDOW_TYPE.
- if (!window_type.empty())
- SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()),
- window_type);
- }
- #endif
- #if BUILDFLAG(IS_WIN)
- if (!has_frame()) {
- // Set Window style so that we get a minimize and maximize animation when
- // frameless.
- DWORD frame_style = WS_CAPTION | WS_OVERLAPPED;
- if (resizable_)
- frame_style |= WS_THICKFRAME;
- if (minimizable_)
- frame_style |= WS_MINIMIZEBOX;
- if (maximizable_)
- frame_style |= WS_MAXIMIZEBOX;
- // We should not show a frame for transparent window.
- if (!thick_frame_)
- frame_style &= ~(WS_THICKFRAME | WS_CAPTION);
- ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style);
- }
- LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE);
- if (window_type == "toolbar")
- ex_style |= WS_EX_TOOLWINDOW;
- ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style);
- #endif
- if (has_frame() && !has_client_frame()) {
- // TODO(zcbenz): This was used to force using native frame on Windows 2003,
- // we should check whether setting it in InitParams can work.
- widget()->set_frame_type(views::Widget::FrameType::kForceNative);
- widget()->FrameTypeChanged();
- #if BUILDFLAG(IS_WIN)
- // thickFrame also works for normal window.
- if (!thick_frame_)
- FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME);
- #endif
- }
- // Default content view.
- SetContentView(new views::View());
- gfx::Size size = bounds.size();
- if (has_frame() &&
- options.Get(options::kUseContentSize, &use_content_size_) &&
- use_content_size_)
- size = ContentBoundsToWindowBounds(gfx::Rect(size)).size();
- widget()->CenterWindow(size);
- #if BUILDFLAG(IS_WIN)
- // Save initial window state.
- if (fullscreen)
- last_window_state_ = ui::SHOW_STATE_FULLSCREEN;
- else
- last_window_state_ = ui::SHOW_STATE_NORMAL;
- #endif
- // Listen to mouse events.
- aura::Window* window = GetNativeWindow();
- if (window)
- window->AddPreTargetHandler(this);
- #if BUILDFLAG(IS_LINUX)
- // On linux after the widget is initialized we might have to force set the
- // bounds if the bounds are smaller than the current display
- SetBounds(gfx::Rect(GetPosition(), bounds.size()), false);
- #endif
- SetOwnedByWidget(false);
- RegisterDeleteDelegateCallback(base::BindOnce(
- [](NativeWindowViews* window) {
- if (window->is_modal() && window->parent()) {
- auto* parent = window->parent();
- // Enable parent window after current window gets closed.
- static_cast<NativeWindowViews*>(parent)->DecrementChildModals();
- // Focus on parent window.
- parent->Focus(true);
- }
- window->NotifyWindowClosed();
- },
- this));
- }
- NativeWindowViews::~NativeWindowViews() {
- widget()->RemoveObserver(this);
- #if BUILDFLAG(IS_WIN)
- // Disable mouse forwarding to relinquish resources, should any be held.
- SetForwardMouseMessages(false);
- #endif
- aura::Window* window = GetNativeWindow();
- if (window)
- window->RemovePreTargetHandler(this);
- }
- void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) {
- #if defined(USE_OZONE_PLATFORM_X11)
- if (IsX11()) {
- const std::string color = use_dark_theme ? "dark" : "light";
- x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()),
- x11::GetAtom("_GTK_THEME_VARIANT"),
- x11::GetAtom("UTF8_STRING"), color);
- }
- #endif
- }
- void NativeWindowViews::SetContentView(views::View* view) {
- if (content_view()) {
- root_view_.RemoveChildView(content_view());
- }
- set_content_view(view);
- focused_view_ = view;
- root_view_.AddChildView(content_view());
- root_view_.Layout();
- }
- void NativeWindowViews::Close() {
- if (!IsClosable()) {
- WindowList::WindowCloseCancelled(this);
- return;
- }
- widget()->Close();
- }
- void NativeWindowViews::CloseImmediately() {
- widget()->CloseNow();
- }
- void NativeWindowViews::Focus(bool focus) {
- // For hidden window focus() should do nothing.
- if (!IsVisible())
- return;
- if (focus) {
- widget()->Activate();
- } else {
- widget()->Deactivate();
- }
- }
- bool NativeWindowViews::IsFocused() {
- return widget()->IsActive();
- }
- void NativeWindowViews::Show() {
- if (is_modal() && NativeWindow::parent() &&
- !widget()->native_widget_private()->IsVisible())
- static_cast<NativeWindowViews*>(parent())->IncrementChildModals();
- widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect());
- // explicitly focus the window
- widget()->Activate();
- NotifyWindowShow();
- #if defined(USE_OZONE)
- if (global_menu_bar_)
- global_menu_bar_->OnWindowMapped();
- #endif
- #if defined(USE_OZONE_PLATFORM_X11)
- // On X11, setting Z order before showing the window doesn't take effect,
- // so we have to call it again.
- if (IsX11())
- widget()->SetZOrderLevel(widget()->GetZOrderLevel());
- #endif
- }
- void NativeWindowViews::ShowInactive() {
- widget()->ShowInactive();
- NotifyWindowShow();
- #if defined(USE_OZONE)
- if (global_menu_bar_)
- global_menu_bar_->OnWindowMapped();
- #endif
- }
- void NativeWindowViews::Hide() {
- if (is_modal() && NativeWindow::parent())
- static_cast<NativeWindowViews*>(parent())->DecrementChildModals();
- widget()->Hide();
- NotifyWindowHide();
- #if defined(USE_OZONE)
- if (global_menu_bar_)
- global_menu_bar_->OnWindowUnmapped();
- #endif
- #if BUILDFLAG(IS_WIN)
- // When the window is removed from the taskbar via win.hide(),
- // the thumbnail buttons need to be set up again.
- // Ensure that when the window is hidden,
- // the taskbar host is notified that it should re-add them.
- taskbar_host_.SetThumbarButtonsAdded(false);
- #endif
- }
- bool NativeWindowViews::IsVisible() {
- #if BUILDFLAG(IS_WIN)
- // widget()->IsVisible() calls ::IsWindowVisible, which returns non-zero if a
- // window or any of its parent windows are visible. We want to only check the
- // current window.
- bool visible =
- ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_VISIBLE;
- // WS_VISIBLE is true even if a window is miminized - explicitly check that.
- return visible && !IsMinimized();
- #else
- return widget()->IsVisible();
- #endif
- }
- bool NativeWindowViews::IsEnabled() {
- #if BUILDFLAG(IS_WIN)
- return ::IsWindowEnabled(GetAcceleratedWidget());
- #elif BUILDFLAG(IS_LINUX)
- #if defined(USE_OZONE_PLATFORM_X11)
- if (IsX11())
- return !event_disabler_.get();
- #endif
- NOTIMPLEMENTED();
- return true;
- #endif
- }
- void NativeWindowViews::IncrementChildModals() {
- num_modal_children_++;
- SetEnabledInternal(ShouldBeEnabled());
- }
- void NativeWindowViews::DecrementChildModals() {
- if (num_modal_children_ > 0) {
- num_modal_children_--;
- }
- SetEnabledInternal(ShouldBeEnabled());
- }
- void NativeWindowViews::SetEnabled(bool enable) {
- if (enable != is_enabled_) {
- is_enabled_ = enable;
- SetEnabledInternal(ShouldBeEnabled());
- }
- }
- bool NativeWindowViews::ShouldBeEnabled() {
- return is_enabled_ && (num_modal_children_ == 0);
- }
- void NativeWindowViews::SetEnabledInternal(bool enable) {
- if (enable && IsEnabled()) {
- return;
- } else if (!enable && !IsEnabled()) {
- return;
- }
- #if BUILDFLAG(IS_WIN)
- ::EnableWindow(GetAcceleratedWidget(), enable);
- #elif defined(USE_OZONE_PLATFORM_X11)
- if (IsX11()) {
- views::DesktopWindowTreeHostPlatform* tree_host =
- views::DesktopWindowTreeHostLinux::GetHostForWidget(
- GetAcceleratedWidget());
- if (enable) {
- tree_host->RemoveEventRewriter(event_disabler_.get());
- event_disabler_.reset();
- } else {
- event_disabler_ = std::make_unique<EventDisabler>();
- tree_host->AddEventRewriter(event_disabler_.get());
- }
- }
- #endif
- }
- #if BUILDFLAG(IS_LINUX)
- void NativeWindowViews::Maximize() {
- if (IsVisible()) {
- widget()->Maximize();
- } else {
- widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED,
- gfx::Rect());
- NotifyWindowShow();
- }
- }
- #endif
- void NativeWindowViews::Unmaximize() {
- if (IsMaximized()) {
- #if BUILDFLAG(IS_WIN)
- if (transparent()) {
- SetBounds(restore_bounds_, false);
- NotifyWindowUnmaximize();
- return;
- }
- #endif
- widget()->Restore();
- }
- }
- bool NativeWindowViews::IsMaximized() {
- if (widget()->IsMaximized()) {
- return true;
- } else {
- #if BUILDFLAG(IS_WIN)
- if (transparent() && !IsMinimized()) {
- // Compare the size of the window with the size of the display
- auto display = display::Screen::GetScreen()->GetDisplayNearestWindow(
- GetNativeWindow());
- // Maximized if the window is the same dimensions and placement as the
- // display
- return GetBounds() == display.work_area();
- }
- #endif
- return false;
- }
- }
- void NativeWindowViews::Minimize() {
- if (IsVisible())
- widget()->Minimize();
- else
- widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED,
- gfx::Rect());
- }
- void NativeWindowViews::Restore() {
- widget()->Restore();
- }
- bool NativeWindowViews::IsMinimized() {
- return widget()->IsMinimized();
- }
- void NativeWindowViews::SetFullScreen(bool fullscreen) {
- if (!IsFullScreenable())
- return;
- #if BUILDFLAG(IS_WIN)
- // There is no native fullscreen state on Windows.
- bool leaving_fullscreen = IsFullscreen() && !fullscreen;
- if (fullscreen) {
- last_window_state_ = ui::SHOW_STATE_FULLSCREEN;
- NotifyWindowEnterFullScreen();
- } else {
- last_window_state_ = ui::SHOW_STATE_NORMAL;
- NotifyWindowLeaveFullScreen();
- }
- // For window without WS_THICKFRAME style, we can not call SetFullscreen().
- // This path will be used for transparent windows as well.
- if (!thick_frame_) {
- if (fullscreen) {
- restore_bounds_ = GetBounds();
- auto display =
- display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition());
- SetBounds(display.bounds(), false);
- } else {
- SetBounds(restore_bounds_, false);
- }
- return;
- }
- // We set the new value after notifying, so we can handle the size event
- // correctly.
- widget()->SetFullscreen(fullscreen);
- // If restoring from fullscreen and the window isn't visible, force visible,
- // else a non-responsive window shell could be rendered.
- // (this situation may arise when app starts with fullscreen: true)
- // Note: the following must be after "widget()->SetFullscreen(fullscreen);"
- if (leaving_fullscreen && !IsVisible())
- FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE);
- #else
- if (IsVisible())
- widget()->SetFullscreen(fullscreen);
- else if (fullscreen)
- widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN,
- gfx::Rect());
- // Auto-hide menubar when in fullscreen.
- if (fullscreen) {
- menu_bar_visible_before_fullscreen_ = IsMenuBarVisible();
- SetMenuBarVisibility(false);
- } else {
- SetMenuBarVisibility(!IsMenuBarAutoHide() &&
- menu_bar_visible_before_fullscreen_);
- menu_bar_visible_before_fullscreen_ = false;
- }
- #endif
- }
- bool NativeWindowViews::IsFullscreen() const {
- return widget()->IsFullscreen();
- }
- void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) {
- #if BUILDFLAG(IS_WIN)
- if (is_moving_ || is_resizing_) {
- pending_bounds_change_ = bounds;
- }
- #endif
- #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
- // On Linux and Windows the minimum and maximum size should be updated with
- // window size when window is not resizable.
- if (!resizable_) {
- SetMaximumSize(bounds.size());
- SetMinimumSize(bounds.size());
- }
- #endif
- widget()->SetBounds(bounds);
- }
- gfx::Rect NativeWindowViews::GetBounds() {
- #if BUILDFLAG(IS_WIN)
- if (IsMinimized())
- return widget()->GetRestoredBounds();
- #endif
- return widget()->GetWindowBoundsInScreen();
- }
- gfx::Rect NativeWindowViews::GetContentBounds() {
- return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect();
- }
- gfx::Size NativeWindowViews::GetContentSize() {
- #if BUILDFLAG(IS_WIN)
- if (IsMinimized())
- return NativeWindow::GetContentSize();
- #endif
- return content_view() ? content_view()->size() : gfx::Size();
- }
- gfx::Rect NativeWindowViews::GetNormalBounds() {
- #if BUILDFLAG(IS_WIN)
- if (IsMaximized() && transparent())
- return restore_bounds_;
- #endif
- return widget()->GetRestoredBounds();
- }
- void NativeWindowViews::SetContentSizeConstraints(
- const extensions::SizeConstraints& size_constraints) {
- NativeWindow::SetContentSizeConstraints(size_constraints);
- #if BUILDFLAG(IS_WIN)
- // Changing size constraints would force adding the WS_THICKFRAME style, so
- // do nothing if thickFrame is false.
- if (!thick_frame_)
- return;
- #endif
- // widget_delegate() is only available after Init() is called, we make use of
- // this to determine whether native widget has initialized.
- if (widget() && widget()->widget_delegate())
- widget()->OnSizeConstraintsChanged();
- if (resizable_)
- old_size_constraints_ = size_constraints;
- }
- #if BUILDFLAG(IS_WIN)
- // This override does almost the same with its parent, except that it uses
- // the WindowSizeToContentSizeBuggy method to convert window size to content
- // size. See the comment of the method for the reason behind this.
- extensions::SizeConstraints NativeWindowViews::GetContentSizeConstraints()
- const {
- if (content_size_constraints_)
- return *content_size_constraints_;
- if (!size_constraints_)
- return extensions::SizeConstraints();
- extensions::SizeConstraints constraints;
- if (size_constraints_->HasMaximumSize()) {
- constraints.set_maximum_size(WindowSizeToContentSizeBuggy(
- GetAcceleratedWidget(), size_constraints_->GetMaximumSize()));
- }
- if (size_constraints_->HasMinimumSize()) {
- constraints.set_minimum_size(WindowSizeToContentSizeBuggy(
- GetAcceleratedWidget(), size_constraints_->GetMinimumSize()));
- }
- return constraints;
- }
- #endif
- void NativeWindowViews::SetResizable(bool resizable) {
- if (resizable != resizable_) {
- // On Linux there is no "resizable" property of a window, we have to set
- // both the minimum and maximum size to the window size to achieve it.
- if (resizable) {
- SetContentSizeConstraints(old_size_constraints_);
- SetMaximizable(maximizable_);
- } else {
- old_size_constraints_ = GetContentSizeConstraints();
- resizable_ = false;
- gfx::Size content_size = GetContentSize();
- SetContentSizeConstraints(
- extensions::SizeConstraints(content_size, content_size));
- }
- }
- #if BUILDFLAG(IS_WIN)
- if (has_frame() && thick_frame_)
- FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME);
- #endif
- resizable_ = resizable;
- SetCanResize(resizable_);
- }
- bool NativeWindowViews::MoveAbove(const std::string& sourceId) {
- const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId);
- if (id.type != content::DesktopMediaID::TYPE_WINDOW)
- return false;
- #if BUILDFLAG(IS_WIN)
- const HWND otherWindow = reinterpret_cast<HWND>(id.id);
- if (!::IsWindow(otherWindow))
- return false;
- ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0,
- 0, 0, 0,
- SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
- #elif defined(USE_OZONE_PLATFORM_X11)
- if (IsX11()) {
- if (!IsWindowValid(static_cast<x11::Window>(id.id)))
- return false;
- electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()),
- static_cast<x11::Window>(id.id));
- }
- #endif
- return true;
- }
- void NativeWindowViews::MoveTop() {
- // TODO(julien.isorce): fix chromium in order to use existing
- // widget()->StackAtTop().
- #if BUILDFLAG(IS_WIN)
- gfx::Point pos = GetPosition();
- gfx::Size size = GetSize();
- ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(),
- size.width(), size.height(),
- SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
- #elif defined(USE_OZONE_PLATFORM_X11)
- if (IsX11())
- electron::MoveWindowToForeground(
- static_cast<x11::Window>(GetAcceleratedWidget()));
- #endif
- }
- bool NativeWindowViews::IsResizable() {
- #if BUILDFLAG(IS_WIN)
- if (has_frame())
- return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME;
- #endif
- return resizable_;
- }
- void NativeWindowViews::SetAspectRatio(double aspect_ratio,
- const gfx::Size& extra_size) {
- NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
- gfx::SizeF aspect(aspect_ratio, 1.0);
- // Scale up because SetAspectRatio() truncates aspect value to int
- aspect.Scale(100);
- widget()->SetAspectRatio(aspect);
- }
- void NativeWindowViews::SetMovable(bool movable) {
- movable_ = movable;
- }
- bool NativeWindowViews::IsMovable() {
- #if BUILDFLAG(IS_WIN)
- return movable_;
- #else
- return true; // Not implemented on Linux.
- #endif
- }
- void NativeWindowViews::SetMinimizable(bool minimizable) {
- #if BUILDFLAG(IS_WIN)
- FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX);
- if (IsWindowControlsOverlayEnabled()) {
- auto* frame_view =
- static_cast<WinFrameView*>(widget()->non_client_view()->frame_view());
- frame_view->caption_button_container()->UpdateButtons();
- }
- #endif
- minimizable_ = minimizable;
- }
- bool NativeWindowViews::IsMinimizable() {
- #if BUILDFLAG(IS_WIN)
- return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX;
- #else
- return true; // Not implemented on Linux.
- #endif
- }
- void NativeWindowViews::SetMaximizable(bool maximizable) {
- #if BUILDFLAG(IS_WIN)
- FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX);
- if (IsWindowControlsOverlayEnabled()) {
- auto* frame_view =
- static_cast<WinFrameView*>(widget()->non_client_view()->frame_view());
- frame_view->caption_button_container()->UpdateButtons();
- }
- #endif
- maximizable_ = maximizable;
- }
- bool NativeWindowViews::IsMaximizable() {
- #if BUILDFLAG(IS_WIN)
- return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX;
- #else
- return true; // Not implemented on Linux.
- #endif
- }
- void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {}
- bool NativeWindowViews::IsExcludedFromShownWindowsMenu() {
- // return false on unsupported platforms
- return false;
- }
- void NativeWindowViews::SetFullScreenable(bool fullscreenable) {
- fullscreenable_ = fullscreenable;
- }
- bool NativeWindowViews::IsFullScreenable() {
- return fullscreenable_;
- }
- void NativeWindowViews::SetClosable(bool closable) {
- #if BUILDFLAG(IS_WIN)
- HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false);
- if (closable) {
- EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED);
- } else {
- EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
- }
- if (IsWindowControlsOverlayEnabled()) {
- auto* frame_view =
- static_cast<WinFrameView*>(widget()->non_client_view()->frame_view());
- frame_view->caption_button_container()->UpdateButtons();
- }
- #endif
- }
- bool NativeWindowViews::IsClosable() {
- #if BUILDFLAG(IS_WIN)
- HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false);
- MENUITEMINFO info;
- memset(&info, 0, sizeof(info));
- info.cbSize = sizeof(info);
- info.fMask = MIIM_STATE;
- if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) {
- return false;
- }
- return !(info.fState & MFS_DISABLED);
- #elif BUILDFLAG(IS_LINUX)
- return true;
- #endif
- }
- void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order,
- const std::string& level,
- int relativeLevel) {
- bool level_changed = z_order != widget()->GetZOrderLevel();
- widget()->SetZOrderLevel(z_order);
- #if BUILDFLAG(IS_WIN)
- // Reset the placement flag.
- behind_task_bar_ = false;
- if (z_order != ui::ZOrderLevel::kNormal) {
- // On macOS the window is placed behind the Dock for the following levels.
- // Re-use the same names on Windows to make it easier for the user.
- static const std::vector<std::string> levels = {
- "floating", "torn-off-menu", "modal-panel", "main-menu", "status"};
- behind_task_bar_ = base::Contains(levels, level);
- }
- #endif
- MoveBehindTaskBarIfNeeded();
- // This must be notified at the very end or IsAlwaysOnTop
- // will not yet have been updated to reflect the new status
- if (level_changed)
- NativeWindow::NotifyWindowAlwaysOnTopChanged();
- }
- ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() {
- return widget()->GetZOrderLevel();
- }
- void NativeWindowViews::Center() {
- widget()->CenterWindow(GetSize());
- }
- void NativeWindowViews::Invalidate() {
- widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size()));
- }
- void NativeWindowViews::SetTitle(const std::string& title) {
- title_ = title;
- widget()->UpdateWindowTitle();
- }
- std::string NativeWindowViews::GetTitle() {
- return title_;
- }
- void NativeWindowViews::FlashFrame(bool flash) {
- #if BUILDFLAG(IS_WIN)
- // The Chromium's implementation has a bug stopping flash.
- if (!flash) {
- FLASHWINFO fwi;
- fwi.cbSize = sizeof(fwi);
- fwi.hwnd = GetAcceleratedWidget();
- fwi.dwFlags = FLASHW_STOP;
- fwi.uCount = 0;
- FlashWindowEx(&fwi);
- return;
- }
- #endif
- widget()->FlashFrame(flash);
- }
- void NativeWindowViews::SetSkipTaskbar(bool skip) {
- #if BUILDFLAG(IS_WIN)
- Microsoft::WRL::ComPtr<ITaskbarList> taskbar;
- if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr,
- CLSCTX_INPROC_SERVER,
- IID_PPV_ARGS(&taskbar))) ||
- FAILED(taskbar->HrInit()))
- return;
- if (skip) {
- taskbar->DeleteTab(GetAcceleratedWidget());
- } else {
- taskbar->AddTab(GetAcceleratedWidget());
- taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget());
- }
- #endif
- }
- void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) {
- SetFullScreen(simple_fullscreen);
- }
- bool NativeWindowViews::IsSimpleFullScreen() {
- return IsFullscreen();
- }
- void NativeWindowViews::SetKiosk(bool kiosk) {
- SetFullScreen(kiosk);
- }
- bool NativeWindowViews::IsKiosk() {
- return IsFullscreen();
- }
- bool NativeWindowViews::IsTabletMode() const {
- #if BUILDFLAG(IS_WIN)
- return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget());
- #else
- return false;
- #endif
- }
- SkColor NativeWindowViews::GetBackgroundColor() {
- auto* background = root_view_.background();
- if (!background)
- return SK_ColorTRANSPARENT;
- return background->get_color();
- }
- void NativeWindowViews::SetBackgroundColor(SkColor background_color) {
- // web views' background color.
- root_view_.SetBackground(views::CreateSolidBackground(background_color));
- #if BUILDFLAG(IS_WIN)
- // Set the background color of native window.
- HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color));
- ULONG_PTR previous_brush =
- SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND,
- reinterpret_cast<LONG_PTR>(brush));
- if (previous_brush)
- DeleteObject((HBRUSH)previous_brush);
- InvalidateRect(GetAcceleratedWidget(), NULL, 1);
- #endif
- }
- void NativeWindowViews::SetHasShadow(bool has_shadow) {
- wm::SetShadowElevation(GetNativeWindow(),
- has_shadow ? wm::kShadowElevationInactiveWindow
- : wm::kShadowElevationNone);
- }
- bool NativeWindowViews::HasShadow() {
- return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) !=
- wm::kShadowElevationNone;
- }
- void NativeWindowViews::SetOpacity(const double opacity) {
- #if BUILDFLAG(IS_WIN)
- const double boundedOpacity = std::clamp(opacity, 0.0, 1.0);
- HWND hwnd = GetAcceleratedWidget();
- if (!layered_) {
- LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE);
- ex_style |= WS_EX_LAYERED;
- ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style);
- layered_ = true;
- }
- ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA);
- opacity_ = boundedOpacity;
- #else
- opacity_ = 1.0; // setOpacity unsupported on Linux
- #endif
- }
- double NativeWindowViews::GetOpacity() {
- return opacity_;
- }
- void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) {
- #if BUILDFLAG(IS_WIN)
- LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE);
- if (ignore)
- ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED);
- else
- ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED);
- if (layered_)
- ex_style |= WS_EX_LAYERED;
- ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style);
- // Forwarding is always disabled when not ignoring mouse messages.
- if (!ignore) {
- SetForwardMouseMessages(false);
- } else {
- SetForwardMouseMessages(forward);
- }
- #elif defined(USE_OZONE_PLATFORM_X11)
- if (IsX11()) {
- auto* connection = x11::Connection::Get();
- if (ignore) {
- x11::Rectangle r{0, 0, 1, 1};
- connection->shape().Rectangles({
- .operation = x11::Shape::So::Set,
- .destination_kind = x11::Shape::Sk::Input,
- .ordering = x11::ClipOrdering::YXBanded,
- .destination_window =
- static_cast<x11::Window>(GetAcceleratedWidget()),
- .rectangles = {r},
- });
- } else {
- connection->shape().Mask({
- .operation = x11::Shape::So::Set,
- .destination_kind = x11::Shape::Sk::Input,
- .destination_window =
- static_cast<x11::Window>(GetAcceleratedWidget()),
- .source_bitmap = x11::Pixmap::None,
- });
- }
- }
- #endif
- }
- void NativeWindowViews::SetContentProtection(bool enable) {
- #if BUILDFLAG(IS_WIN)
- HWND hwnd = GetAcceleratedWidget();
- DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE;
- ::SetWindowDisplayAffinity(hwnd, affinity);
- if (!layered_) {
- // Workaround to prevent black window on screen capture after hiding and
- // showing the BrowserWindow.
- LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE);
- ex_style |= WS_EX_LAYERED;
- ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style);
- layered_ = true;
- }
- #endif
- }
- void NativeWindowViews::SetFocusable(bool focusable) {
- widget()->widget_delegate()->SetCanActivate(focusable);
- #if BUILDFLAG(IS_WIN)
- LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE);
- if (focusable)
- ex_style &= ~WS_EX_NOACTIVATE;
- else
- ex_style |= WS_EX_NOACTIVATE;
- ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style);
- SetSkipTaskbar(!focusable);
- Focus(false);
- #endif
- }
- bool NativeWindowViews::IsFocusable() {
- bool can_activate = widget()->widget_delegate()->CanActivate();
- #if BUILDFLAG(IS_WIN)
- LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE);
- bool no_activate = ex_style & WS_EX_NOACTIVATE;
- return !no_activate && can_activate;
- #else
- return can_activate;
- #endif
- }
- void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) {
- #if defined(USE_OZONE)
- // Remove global menu bar.
- if (global_menu_bar_ && menu_model == nullptr) {
- global_menu_bar_.reset();
- root_view_.UnregisterAcceleratorsWithFocusManager();
- return;
- }
- // Use global application menu bar when possible.
- if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) {
- if (!global_menu_bar_)
- global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this);
- if (global_menu_bar_->IsServerStarted()) {
- root_view_.RegisterAcceleratorsWithFocusManager(menu_model);
- global_menu_bar_->SetMenu(menu_model);
- return;
- }
- }
- #endif
- // Should reset content size when setting menu.
- gfx::Size content_size = GetContentSize();
- bool should_reset_size = use_content_size_ && has_frame() &&
- !IsMenuBarAutoHide() &&
- ((!!menu_model) != root_view_.HasMenu());
- root_view_.SetMenu(menu_model);
- if (should_reset_size) {
- // Enlarge the size constraints for the menu.
- int menu_bar_height = root_view_.GetMenuBarHeight();
- extensions::SizeConstraints constraints = GetContentSizeConstraints();
- if (constraints.HasMinimumSize()) {
- gfx::Size min_size = constraints.GetMinimumSize();
- min_size.set_height(min_size.height() + menu_bar_height);
- constraints.set_minimum_size(min_size);
- }
- if (constraints.HasMaximumSize()) {
- gfx::Size max_size = constraints.GetMaximumSize();
- max_size.set_height(max_size.height() + menu_bar_height);
- constraints.set_maximum_size(max_size);
- }
- SetContentSizeConstraints(constraints);
- // Resize the window to make sure content size is not changed.
- SetContentSize(content_size);
- }
- }
- void NativeWindowViews::AddBrowserView(NativeBrowserView* view) {
- if (!content_view())
- return;
- if (!view) {
- return;
- }
- add_browser_view(view);
- if (view->GetInspectableWebContentsView())
- content_view()->AddChildView(
- view->GetInspectableWebContentsView()->GetView());
- }
- void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) {
- if (!content_view())
- return;
- if (!view) {
- return;
- }
- if (view->GetInspectableWebContentsView())
- content_view()->RemoveChildView(
- view->GetInspectableWebContentsView()->GetView());
- remove_browser_view(view);
- }
- void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) {
- if (!content_view())
- return;
- if (!view) {
- return;
- }
- remove_browser_view(view);
- add_browser_view(view);
- if (view->GetInspectableWebContentsView())
- content_view()->ReorderChildView(
- view->GetInspectableWebContentsView()->GetView(), -1);
- }
- void NativeWindowViews::SetParentWindow(NativeWindow* parent) {
- NativeWindow::SetParentWindow(parent);
- #if defined(USE_OZONE_PLATFORM_X11)
- if (IsX11())
- x11::SetProperty(
- static_cast<x11::Window>(GetAcceleratedWidget()),
- x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW,
- parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget())
- : ui::GetX11RootWindow());
- #elif BUILDFLAG(IS_WIN)
- // To set parentship between windows into Windows is better to play with the
- // owner instead of the parent, as Windows natively seems to do if a parent
- // is specified at window creation time.
- // For do this we must NOT use the ::SetParent function, instead we must use
- // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set
- // to "GWLP_HWNDPARENT" which actually means the window owner.
- HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL;
- if (hwndParent ==
- (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT))
- return;
- ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT,
- (LONG_PTR)hwndParent);
- // Ensures the visibility
- if (IsVisible()) {
- WINDOWPLACEMENT wp;
- wp.length = sizeof(WINDOWPLACEMENT);
- ::GetWindowPlacement(GetAcceleratedWidget(), &wp);
- ::ShowWindow(GetAcceleratedWidget(), SW_HIDE);
- ::ShowWindow(GetAcceleratedWidget(), wp.showCmd);
- ::BringWindowToTop(GetAcceleratedWidget());
- }
- #endif
- }
- gfx::NativeView NativeWindowViews::GetNativeView() const {
- return widget()->GetNativeView();
- }
- gfx::NativeWindow NativeWindowViews::GetNativeWindow() const {
- return widget()->GetNativeWindow();
- }
- void NativeWindowViews::SetProgressBar(double progress,
- NativeWindow::ProgressState state) {
- #if BUILDFLAG(IS_WIN)
- taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state);
- #elif BUILDFLAG(IS_LINUX)
- if (unity::IsRunning()) {
- unity::SetProgressFraction(progress);
- }
- #endif
- }
- void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay,
- const std::string& description) {
- #if BUILDFLAG(IS_WIN)
- SkBitmap overlay_bitmap = overlay.AsBitmap();
- taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap,
- description);
- #endif
- }
- void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) {
- root_view_.SetAutoHideMenuBar(auto_hide);
- }
- bool NativeWindowViews::IsMenuBarAutoHide() {
- return root_view_.IsMenuBarAutoHide();
- }
- void NativeWindowViews::SetMenuBarVisibility(bool visible) {
- root_view_.SetMenuBarVisibility(visible);
- }
- bool NativeWindowViews::IsMenuBarVisible() {
- return root_view_.IsMenuBarVisible();
- }
- void NativeWindowViews::SetBackgroundMaterial(const std::string& material) {
- #if BUILDFLAG(IS_WIN)
- // DWMWA_USE_HOSTBACKDROPBRUSH is only supported on Windows 11 22H2 and up.
- if (base::win::GetVersion() < base::win::Version::WIN11_22H2)
- return;
- DWM_SYSTEMBACKDROP_TYPE backdrop_type = GetBackdropFromString(material);
- HRESULT result =
- DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_SYSTEMBACKDROP_TYPE,
- &backdrop_type, sizeof(backdrop_type));
- if (FAILED(result))
- LOG(WARNING) << "Failed to set background material to " << material;
- #endif
- }
- void NativeWindowViews::SetVisibleOnAllWorkspaces(
- bool visible,
- bool visibleOnFullScreen,
- bool skipTransformProcessType) {
- widget()->SetVisibleOnAllWorkspaces(visible);
- }
- bool NativeWindowViews::IsVisibleOnAllWorkspaces() {
- #if defined(USE_OZONE_PLATFORM_X11)
- if (IsX11()) {
- // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to
- // determine whether the current window is visible on all workspaces.
- x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY");
- std::vector<x11::Atom> wm_states;
- GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()),
- x11::GetAtom("_NET_WM_STATE"), &wm_states);
- return base::Contains(wm_states, sticky_atom);
- }
- #endif
- return false;
- }
- content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const {
- const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget();
- content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId;
- content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId;
- #if BUILDFLAG(IS_WIN)
- window_handle =
- reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget);
- #elif BUILDFLAG(IS_LINUX)
- window_handle = static_cast<uint32_t>(accelerated_widget);
- #endif
- aura::WindowTreeHost* const host =
- aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget);
- aura::Window* const aura_window = host ? host->window() : nullptr;
- if (aura_window) {
- aura_id = content::DesktopMediaID::RegisterNativeWindow(
- content::DesktopMediaID::TYPE_WINDOW, aura_window)
- .window_id;
- }
- // No constructor to pass the aura_id. Make sure to not use the other
- // constructor that has a third parameter, it is for yet another purpose.
- content::DesktopMediaID result = content::DesktopMediaID(
- content::DesktopMediaID::TYPE_WINDOW, window_handle);
- // Confusing but this is how content::DesktopMediaID is designed. The id
- // property is the window handle whereas the window_id property is an id
- // given by a map containing all aura instances.
- result.window_id = aura_id;
- return result;
- }
- gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const {
- if (GetNativeWindow() && GetNativeWindow()->GetHost())
- return GetNativeWindow()->GetHost()->GetAcceleratedWidget();
- else
- return gfx::kNullAcceleratedWidget;
- }
- NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const {
- return GetAcceleratedWidget();
- }
- gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds(
- const gfx::Rect& bounds) const {
- if (!has_frame())
- return bounds;
- gfx::Rect window_bounds(bounds);
- #if BUILDFLAG(IS_WIN)
- if (widget()->non_client_view()) {
- HWND hwnd = GetAcceleratedWidget();
- gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds);
- window_bounds = ScreenToDIPRect(
- hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds(
- dpi_bounds));
- }
- #endif
- if (root_view_.HasMenu() && root_view_.IsMenuBarVisible()) {
- int menu_bar_height = root_view_.GetMenuBarHeight();
- window_bounds.set_y(window_bounds.y() - menu_bar_height);
- window_bounds.set_height(window_bounds.height() + menu_bar_height);
- }
- return window_bounds;
- }
- gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
- const gfx::Rect& bounds) const {
- if (!has_frame())
- return bounds;
- gfx::Rect content_bounds(bounds);
- #if BUILDFLAG(IS_WIN)
- HWND hwnd = GetAcceleratedWidget();
- content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size());
- RECT rect;
- SetRectEmpty(&rect);
- DWORD style = ::GetWindowLong(hwnd, GWL_STYLE);
- DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE);
- AdjustWindowRectEx(&rect, style, FALSE, ex_style);
- content_bounds.set_width(content_bounds.width() - (rect.right - rect.left));
- content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top));
- content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size());
- #endif
- if (root_view_.HasMenu() && root_view_.IsMenuBarVisible()) {
- int menu_bar_height = root_view_.GetMenuBarHeight();
- content_bounds.set_y(content_bounds.y() + menu_bar_height);
- content_bounds.set_height(content_bounds.height() - menu_bar_height);
- }
- return content_bounds;
- }
- #if BUILDFLAG(IS_WIN)
- void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) {
- // We are responsible for storing the images.
- window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon));
- app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon));
- HWND hwnd = GetAcceleratedWidget();
- SendMessage(hwnd, WM_SETICON, ICON_SMALL,
- reinterpret_cast<LPARAM>(window_icon_.get()));
- SendMessage(hwnd, WM_SETICON, ICON_BIG,
- reinterpret_cast<LPARAM>(app_icon_.get()));
- }
- #elif BUILDFLAG(IS_LINUX)
- void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) {
- auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget(
- GetAcceleratedWidget());
- tree_host->SetWindowIcons(icon, {});
- }
- #endif
- void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget,
- bool active) {
- if (changed_widget != widget())
- return;
- if (active) {
- MoveBehindTaskBarIfNeeded();
- NativeWindow::NotifyWindowFocus();
- } else {
- NativeWindow::NotifyWindowBlur();
- }
- // Hide menu bar when window is blurred.
- if (!active && IsMenuBarAutoHide() && IsMenuBarVisible())
- SetMenuBarVisibility(false);
- root_view_.ResetAltState();
- }
- void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget,
- const gfx::Rect& bounds) {
- if (changed_widget != widget())
- return;
- // Note: We intentionally use `GetBounds()` instead of `bounds` to properly
- // handle minimized windows on Windows.
- const auto new_bounds = GetBounds();
- if (widget_size_ != new_bounds.size()) {
- int width_delta = new_bounds.width() - widget_size_.width();
- int height_delta = new_bounds.height() - widget_size_.height();
- for (NativeBrowserView* item : browser_views()) {
- auto* native_view = static_cast<NativeBrowserViewViews*>(item);
- native_view->SetAutoResizeProportions(widget_size_);
- native_view->AutoResize(new_bounds, width_delta, height_delta);
- }
- NotifyWindowResize();
- widget_size_ = new_bounds.size();
- }
- }
- void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) {
- aura::Window* window = GetNativeWindow();
- if (window)
- window->RemovePreTargetHandler(this);
- }
- void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) {
- widget_destroyed_ = true;
- }
- views::View* NativeWindowViews::GetInitiallyFocusedView() {
- return focused_view_;
- }
- bool NativeWindowViews::CanMaximize() const {
- return resizable_ && maximizable_;
- }
- bool NativeWindowViews::CanMinimize() const {
- #if BUILDFLAG(IS_WIN)
- return minimizable_;
- #elif BUILDFLAG(IS_LINUX)
- return true;
- #endif
- }
- std::u16string NativeWindowViews::GetWindowTitle() const {
- return base::UTF8ToUTF16(title_);
- }
- views::View* NativeWindowViews::GetContentsView() {
- return &root_view_;
- }
- bool NativeWindowViews::ShouldDescendIntoChildForEventHandling(
- gfx::NativeView child,
- const gfx::Point& location) {
- return NonClientHitTest(location) == HTNOWHERE;
- }
- views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) {
- return new NativeWindowClientView{widget, GetContentsView(), this};
- }
- std::unique_ptr<views::NonClientFrameView>
- NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) {
- #if BUILDFLAG(IS_WIN)
- auto frame_view = std::make_unique<WinFrameView>();
- frame_view->Init(this, widget);
- return frame_view;
- #else
- if (has_frame() && !has_client_frame()) {
- return std::make_unique<NativeFrameView>(this, widget);
- } else {
- auto frame_view = has_frame() && has_client_frame()
- ? std::make_unique<ClientFrameViewLinux>()
- : std::make_unique<FramelessView>();
- frame_view->Init(this, widget);
- return frame_view;
- }
- #endif
- }
- void NativeWindowViews::OnWidgetMove() {
- NotifyWindowMove();
- }
- void NativeWindowViews::HandleKeyboardEvent(
- content::WebContents*,
- const content::NativeWebKeyboardEvent& event) {
- if (widget_destroyed_)
- return;
- #if BUILDFLAG(IS_LINUX)
- if (event.windows_key_code == ui::VKEY_BROWSER_BACK)
- NotifyWindowExecuteAppCommand(kBrowserBackward);
- else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD)
- NotifyWindowExecuteAppCommand(kBrowserForward);
- #endif
- keyboard_event_handler_.HandleKeyboardEvent(event,
- root_view_.GetFocusManager());
- root_view_.HandleKeyEvent(event);
- }
- void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) {
- if (event->type() != ui::ET_MOUSE_PRESSED)
- return;
- // Alt+Click should not toggle menu bar.
- root_view_.ResetAltState();
- #if BUILDFLAG(IS_LINUX)
- if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON)
- NotifyWindowExecuteAppCommand(kBrowserBackward);
- else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON)
- NotifyWindowExecuteAppCommand(kBrowserForward);
- #endif
- }
- ui::WindowShowState NativeWindowViews::GetRestoredState() {
- if (IsMaximized()) {
- #if BUILDFLAG(IS_WIN)
- // Only restore Maximized state when window is NOT transparent style
- if (!transparent()) {
- return ui::SHOW_STATE_MAXIMIZED;
- }
- #else
- return ui::SHOW_STATE_MAXIMIZED;
- #endif
- }
- if (IsFullscreen())
- return ui::SHOW_STATE_FULLSCREEN;
- return ui::SHOW_STATE_NORMAL;
- }
- void NativeWindowViews::MoveBehindTaskBarIfNeeded() {
- #if BUILDFLAG(IS_WIN)
- if (behind_task_bar_) {
- const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr);
- ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0,
- SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
- }
- #endif
- // TODO(julien.isorce): Implement X11 case.
- }
- // static
- NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options,
- NativeWindow* parent) {
- return new NativeWindowViews(options, parent);
- }
- } // namespace electron
|