native_window_views.cc 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863
  1. // Copyright (c) 2014 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. // FIXME(ckerr) this incorrect #include order is a temporary
  5. // fix to unblock the roll. Will fix in an upgrade followup.
  6. #include "ui/base/ozone_buildflags.h"
  7. #if BUILDFLAG(IS_OZONE_X11)
  8. #include "ui/base/x/x11_util.h"
  9. #endif
  10. #include "shell/browser/native_window_views.h"
  11. #if BUILDFLAG(IS_WIN)
  12. #include <dwmapi.h>
  13. #include <wrl/client.h>
  14. #endif
  15. #include <memory>
  16. #include <utility>
  17. #include <vector>
  18. #include "base/containers/contains.h"
  19. #include "base/memory/raw_ref.h"
  20. #include "base/numerics/ranges.h"
  21. #include "base/strings/utf_string_conversions.h"
  22. #include "content/public/browser/desktop_media_id.h"
  23. #include "content/public/common/color_parser.h"
  24. #include "shell/browser/api/electron_api_web_contents.h"
  25. #include "shell/browser/ui/views/root_view.h"
  26. #include "shell/browser/web_contents_preferences.h"
  27. #include "shell/browser/web_view_manager.h"
  28. #include "shell/browser/window_list.h"
  29. #include "shell/common/electron_constants.h"
  30. #include "shell/common/gin_converters/image_converter.h"
  31. #include "shell/common/gin_helper/dictionary.h"
  32. #include "shell/common/options_switches.h"
  33. #include "ui/aura/window_tree_host.h"
  34. #include "ui/base/hit_test.h"
  35. #include "ui/display/screen.h"
  36. #include "ui/gfx/image/image.h"
  37. #include "ui/gfx/native_widget_types.h"
  38. #include "ui/ozone/public/ozone_platform.h"
  39. #include "ui/views/background.h"
  40. #include "ui/views/controls/webview/webview.h"
  41. #include "ui/views/widget/native_widget_private.h"
  42. #include "ui/views/widget/widget.h"
  43. #include "ui/views/window/client_view.h"
  44. #include "ui/wm/core/shadow_types.h"
  45. #include "ui/wm/core/window_util.h"
  46. #if BUILDFLAG(IS_LINUX)
  47. #include "base/strings/string_util.h"
  48. #include "shell/browser/browser.h"
  49. #include "shell/browser/linux/unity_service.h"
  50. #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h"
  51. #include "shell/browser/ui/views/client_frame_view_linux.h"
  52. #include "shell/browser/ui/views/native_frame_view.h"
  53. #include "shell/browser/ui/views/opaque_frame_view.h"
  54. #include "shell/common/platform_util.h"
  55. #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
  56. #include "ui/views/window/native_frame_view.h"
  57. #if BUILDFLAG(IS_OZONE_X11)
  58. #include "shell/browser/ui/views/global_menu_bar_x11.h"
  59. #include "shell/browser/ui/x/event_disabler.h"
  60. #include "shell/browser/ui/x/x_window_utils.h"
  61. #include "ui/gfx/x/atom_cache.h"
  62. #include "ui/gfx/x/connection.h"
  63. #include "ui/gfx/x/shape.h"
  64. #include "ui/gfx/x/xproto.h"
  65. #endif
  66. #elif BUILDFLAG(IS_WIN)
  67. #include "base/win/win_util.h"
  68. #include "base/win/windows_version.h"
  69. #include "shell/browser/ui/views/win_frame_view.h"
  70. #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h"
  71. #include "skia/ext/skia_utils_win.h"
  72. #include "ui/display/win/screen_win.h"
  73. #include "ui/gfx/color_utils.h"
  74. #include "ui/gfx/win/hwnd_util.h"
  75. #include "ui/gfx/win/msg_util.h"
  76. #endif
  77. namespace electron {
  78. #if BUILDFLAG(IS_WIN)
  79. DWM_SYSTEMBACKDROP_TYPE GetBackdropFromString(const std::string& material) {
  80. if (material == "none") {
  81. return DWMSBT_NONE;
  82. } else if (material == "acrylic") {
  83. return DWMSBT_TRANSIENTWINDOW;
  84. } else if (material == "mica") {
  85. return DWMSBT_MAINWINDOW;
  86. } else if (material == "tabbed") {
  87. return DWMSBT_TABBEDWINDOW;
  88. }
  89. return DWMSBT_AUTO;
  90. }
  91. // Similar to the ones in display::win::ScreenWin, but with rounded values
  92. // These help to avoid problems that arise from unresizable windows where the
  93. // original ceil()-ed values can cause calculation errors, since converting
  94. // both ways goes through a ceil() call. Related issue: #15816
  95. gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) {
  96. float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd);
  97. gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor);
  98. dip_rect.set_origin(
  99. display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin());
  100. return dip_rect;
  101. }
  102. #endif
  103. namespace {
  104. #if BUILDFLAG(IS_WIN)
  105. const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd";
  106. void FlipWindowStyle(HWND handle, bool on, DWORD flag) {
  107. DWORD style = ::GetWindowLong(handle, GWL_STYLE);
  108. if (on)
  109. style |= flag;
  110. else
  111. style &= ~flag;
  112. ::SetWindowLong(handle, GWL_STYLE, style);
  113. // Window's frame styles are cached so we need to call SetWindowPos
  114. // with the SWP_FRAMECHANGED flag to update cache properly.
  115. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored
  116. SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
  117. SWP_NOACTIVATE | SWP_NOOWNERZORDER);
  118. }
  119. gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) {
  120. float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd);
  121. gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor);
  122. screen_rect.set_origin(
  123. display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin());
  124. return screen_rect;
  125. }
  126. // Chromium uses a buggy implementation that converts content rect to window
  127. // rect when calculating min/max size, we should use the same implementation
  128. // when passing min/max size so we can get correct results.
  129. gfx::Size WindowSizeToContentSizeBuggy(HWND hwnd, const gfx::Size& size) {
  130. // Calculate the size of window frame, using same code with the
  131. // HWNDMessageHandler::OnGetMinMaxInfo method.
  132. // The pitfall is, when window is minimized the calculated window frame size
  133. // will be different from other states.
  134. RECT client_rect, rect;
  135. GetClientRect(hwnd, &client_rect);
  136. GetWindowRect(hwnd, &rect);
  137. CR_DEFLATE_RECT(&rect, &client_rect);
  138. // Convert DIP size to pixel size, do calculation and then return DIP size.
  139. gfx::Rect screen_rect = DIPToScreenRect(hwnd, gfx::Rect(size));
  140. gfx::Size screen_client_size(screen_rect.width() - (rect.right - rect.left),
  141. screen_rect.height() - (rect.bottom - rect.top));
  142. return ScreenToDIPRect(hwnd, gfx::Rect(screen_client_size)).size();
  143. }
  144. #endif
  145. [[maybe_unused]] bool IsX11() {
  146. return ui::OzonePlatform::GetInstance()
  147. ->GetPlatformProperties()
  148. .electron_can_call_x11;
  149. }
  150. class NativeWindowClientView : public views::ClientView {
  151. public:
  152. NativeWindowClientView(views::Widget* widget,
  153. views::View* root_view,
  154. NativeWindowViews* window)
  155. : views::ClientView{widget, root_view},
  156. window_{raw_ref<NativeWindowViews>::from_ptr(window)} {}
  157. ~NativeWindowClientView() override = default;
  158. // disable copy
  159. NativeWindowClientView(const NativeWindowClientView&) = delete;
  160. NativeWindowClientView& operator=(const NativeWindowClientView&) = delete;
  161. // views::ClientView
  162. views::CloseRequestResult OnWindowCloseRequested() override {
  163. window_->NotifyWindowCloseButtonClicked();
  164. return views::CloseRequestResult::kCannotClose;
  165. }
  166. private:
  167. const raw_ref<NativeWindowViews> window_;
  168. };
  169. } // namespace
  170. NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options,
  171. NativeWindow* parent)
  172. : NativeWindow(options, parent) {
  173. options.Get(options::kTitle, &title_);
  174. bool menu_bar_autohide;
  175. if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide))
  176. root_view_.SetAutoHideMenuBar(menu_bar_autohide);
  177. #if BUILDFLAG(IS_WIN)
  178. // On Windows we rely on the CanResize() to indicate whether window can be
  179. // resized, and it should be set before window is created.
  180. options.Get(options::kResizable, &resizable_);
  181. options.Get(options::kMinimizable, &minimizable_);
  182. options.Get(options::kMaximizable, &maximizable_);
  183. // Transparent window must not have thick frame.
  184. options.Get("thickFrame", &thick_frame_);
  185. if (transparent())
  186. thick_frame_ = false;
  187. overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE);
  188. overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT);
  189. #endif
  190. v8::Local<v8::Value> titlebar_overlay;
  191. if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) &&
  192. titlebar_overlay->IsObject()) {
  193. auto titlebar_overlay_obj =
  194. gin_helper::Dictionary::CreateEmpty(options.isolate());
  195. options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj);
  196. std::string overlay_color_string;
  197. if (titlebar_overlay_obj.Get(options::kOverlayButtonColor,
  198. &overlay_color_string)) {
  199. bool success = content::ParseCssColorString(overlay_color_string,
  200. &overlay_button_color_);
  201. DCHECK(success);
  202. }
  203. std::string overlay_symbol_color_string;
  204. if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor,
  205. &overlay_symbol_color_string)) {
  206. bool success = content::ParseCssColorString(overlay_symbol_color_string,
  207. &overlay_symbol_color_);
  208. DCHECK(success);
  209. }
  210. }
  211. // |hidden| is the only non-default titleBarStyle valid on Windows and Linux.
  212. if (title_bar_style_ == TitleBarStyle::kHidden)
  213. set_has_frame(false);
  214. #if BUILDFLAG(IS_WIN)
  215. // If the taskbar is re-created after we start up, we have to rebuild all of
  216. // our buttons.
  217. taskbar_created_message_ = RegisterWindowMessage(TEXT("TaskbarCreated"));
  218. #endif
  219. if (enable_larger_than_screen())
  220. // We need to set a default maximum window size here otherwise Windows
  221. // will not allow us to resize the window larger than scree.
  222. // Setting directly to INT_MAX somehow doesn't work, so we just divide
  223. // by 10, which should still be large enough.
  224. SetContentSizeConstraints(extensions::SizeConstraints(
  225. gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10)));
  226. int width = 800, height = 600;
  227. options.Get(options::kWidth, &width);
  228. options.Get(options::kHeight, &height);
  229. gfx::Rect bounds(0, 0, width, height);
  230. widget_size_ = bounds.size();
  231. widget()->AddObserver(this);
  232. using InitParams = views::Widget::InitParams;
  233. auto params = InitParams{InitParams::WIDGET_OWNS_NATIVE_WIDGET,
  234. InitParams::TYPE_WINDOW};
  235. params.bounds = bounds;
  236. params.delegate = this;
  237. params.remove_standard_frame = !has_frame() || has_client_frame();
  238. // If a client frame, we need to draw our own shadows.
  239. if (IsTranslucent() || has_client_frame())
  240. params.opacity = InitParams::WindowOpacity::kTranslucent;
  241. // The given window is most likely not rectangular since it is translucent and
  242. // has no standard frame, don't show a shadow for it.
  243. if (IsTranslucent() && !has_frame())
  244. params.shadow_type = InitParams::ShadowType::kNone;
  245. bool focusable;
  246. if (options.Get(options::kFocusable, &focusable) && !focusable)
  247. params.activatable = InitParams::Activatable::kNo;
  248. #if BUILDFLAG(IS_WIN)
  249. if (parent)
  250. params.parent = parent->GetNativeWindow();
  251. params.native_widget = new ElectronDesktopNativeWidgetAura(this);
  252. #elif BUILDFLAG(IS_LINUX)
  253. std::string name = Browser::Get()->GetName();
  254. // Set WM_WINDOW_ROLE.
  255. params.wm_role_name = "browser-window";
  256. // Set WM_CLASS.
  257. params.wm_class_name = base::ToLowerASCII(name);
  258. params.wm_class_class = name;
  259. // Set Wayland application ID.
  260. params.wayland_app_id = platform_util::GetXdgAppId();
  261. auto* native_widget = new views::DesktopNativeWidgetAura(widget());
  262. params.native_widget = native_widget;
  263. params.desktop_window_tree_host =
  264. new ElectronDesktopWindowTreeHostLinux(this, native_widget);
  265. #endif
  266. widget()->Init(std::move(params));
  267. widget()->SetNativeWindowProperty(kElectronNativeWindowKey, this);
  268. SetCanResize(resizable_);
  269. bool fullscreen = false;
  270. options.Get(options::kFullscreen, &fullscreen);
  271. std::string window_type;
  272. options.Get(options::kType, &window_type);
  273. #if BUILDFLAG(IS_LINUX)
  274. // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set.
  275. bool use_dark_theme = false;
  276. if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) {
  277. SetGTKDarkThemeEnabled(use_dark_theme);
  278. }
  279. if (parent)
  280. SetParentWindow(parent);
  281. if (IsX11()) {
  282. // Before the window is mapped the SetWMSpecState can not work, so we have
  283. // to manually set the _NET_WM_STATE.
  284. std::vector<x11::Atom> state_atom_list;
  285. // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE.
  286. if (fullscreen) {
  287. state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN"));
  288. }
  289. if (parent) {
  290. // Force using dialog type for child window.
  291. window_type = "dialog";
  292. // Modal window needs the _NET_WM_STATE_MODAL hint.
  293. if (is_modal())
  294. state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL"));
  295. }
  296. if (!state_atom_list.empty()) {
  297. auto* connection = x11::Connection::Get();
  298. connection->SetArrayProperty(
  299. static_cast<x11::Window>(GetAcceleratedWidget()),
  300. x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list);
  301. }
  302. // Set the _NET_WM_WINDOW_TYPE.
  303. if (!window_type.empty())
  304. SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()),
  305. window_type);
  306. }
  307. #endif
  308. #if BUILDFLAG(IS_WIN)
  309. if (!has_frame()) {
  310. // Set Window style so that we get a minimize and maximize animation when
  311. // frameless.
  312. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED;
  313. if (resizable_)
  314. frame_style |= WS_THICKFRAME;
  315. if (minimizable_)
  316. frame_style |= WS_MINIMIZEBOX;
  317. if (maximizable_)
  318. frame_style |= WS_MAXIMIZEBOX;
  319. // We should not show a frame for transparent window.
  320. if (!thick_frame_)
  321. frame_style &= ~(WS_THICKFRAME | WS_CAPTION);
  322. ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style);
  323. bool rounded_corner = true;
  324. options.Get(options::kRoundedCorners, &rounded_corner);
  325. if (!rounded_corner)
  326. SetRoundedCorners(false);
  327. }
  328. LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE);
  329. if (window_type == "toolbar")
  330. ex_style |= WS_EX_TOOLWINDOW;
  331. ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style);
  332. #endif
  333. if (has_frame() && !has_client_frame()) {
  334. // TODO(zcbenz): This was used to force using native frame on Windows 2003,
  335. // we should check whether setting it in InitParams can work.
  336. widget()->set_frame_type(views::Widget::FrameType::kForceNative);
  337. widget()->FrameTypeChanged();
  338. #if BUILDFLAG(IS_WIN)
  339. // thickFrame also works for normal window.
  340. if (!thick_frame_)
  341. FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME);
  342. #endif
  343. }
  344. // Default content view.
  345. SetContentView(new views::View());
  346. gfx::Size size = bounds.size();
  347. if (has_frame() &&
  348. options.Get(options::kUseContentSize, &use_content_size_) &&
  349. use_content_size_)
  350. size = ContentBoundsToWindowBounds(gfx::Rect(size)).size();
  351. widget()->CenterWindow(size);
  352. #if BUILDFLAG(IS_WIN)
  353. // Save initial window state.
  354. if (fullscreen)
  355. last_window_state_ = ui::mojom::WindowShowState::kFullscreen;
  356. else
  357. last_window_state_ = ui::mojom::WindowShowState::kNormal;
  358. #endif
  359. // Listen to mouse events.
  360. aura::Window* window = GetNativeWindow();
  361. if (window)
  362. window->AddPreTargetHandler(this);
  363. #if BUILDFLAG(IS_LINUX)
  364. // On linux after the widget is initialized we might have to force set the
  365. // bounds if the bounds are smaller than the current display
  366. SetBounds(gfx::Rect(GetPosition(), bounds.size()), false);
  367. #endif
  368. SetOwnedByWidget(false);
  369. RegisterDeleteDelegateCallback(base::BindOnce(
  370. [](NativeWindowViews* window) {
  371. if (window->is_modal() && window->parent()) {
  372. auto* parent = window->parent();
  373. // Enable parent window after current window gets closed.
  374. static_cast<NativeWindowViews*>(parent)->DecrementChildModals();
  375. // Focus on parent window.
  376. parent->Focus(true);
  377. }
  378. window->NotifyWindowClosed();
  379. },
  380. this));
  381. }
  382. NativeWindowViews::~NativeWindowViews() {
  383. widget()->RemoveObserver(this);
  384. #if BUILDFLAG(IS_WIN)
  385. // Disable mouse forwarding to relinquish resources, should any be held.
  386. SetForwardMouseMessages(false);
  387. #endif
  388. aura::Window* window = GetNativeWindow();
  389. if (window)
  390. window->RemovePreTargetHandler(this);
  391. }
  392. void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) {
  393. #if BUILDFLAG(IS_LINUX)
  394. if (IsX11()) {
  395. const std::string color = use_dark_theme ? "dark" : "light";
  396. auto* connection = x11::Connection::Get();
  397. connection->SetStringProperty(
  398. static_cast<x11::Window>(GetAcceleratedWidget()),
  399. x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color);
  400. }
  401. #endif
  402. }
  403. void NativeWindowViews::SetContentView(views::View* view) {
  404. if (content_view()) {
  405. root_view_.GetMainView()->RemoveChildView(content_view());
  406. }
  407. set_content_view(view);
  408. focused_view_ = view;
  409. root_view_.GetMainView()->AddChildView(content_view());
  410. root_view_.GetMainView()->DeprecatedLayoutImmediately();
  411. }
  412. void NativeWindowViews::Close() {
  413. if (!IsClosable()) {
  414. WindowList::WindowCloseCancelled(this);
  415. return;
  416. }
  417. widget()->Close();
  418. }
  419. void NativeWindowViews::CloseImmediately() {
  420. widget()->CloseNow();
  421. }
  422. void NativeWindowViews::Focus(bool focus) {
  423. // For hidden window focus() should do nothing.
  424. if (!IsVisible())
  425. return;
  426. if (focus) {
  427. widget()->Activate();
  428. } else {
  429. widget()->Deactivate();
  430. }
  431. }
  432. bool NativeWindowViews::IsFocused() const {
  433. return widget()->IsActive();
  434. }
  435. void NativeWindowViews::Show() {
  436. if (is_modal() && NativeWindow::parent() &&
  437. !widget()->native_widget_private()->IsVisible())
  438. static_cast<NativeWindowViews*>(parent())->IncrementChildModals();
  439. widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect());
  440. // explicitly focus the window
  441. widget()->Activate();
  442. NotifyWindowShow();
  443. #if BUILDFLAG(IS_LINUX)
  444. if (global_menu_bar_)
  445. global_menu_bar_->OnWindowMapped();
  446. // On X11, setting Z order before showing the window doesn't take effect,
  447. // so we have to call it again.
  448. if (IsX11())
  449. widget()->SetZOrderLevel(widget()->GetZOrderLevel());
  450. #endif
  451. }
  452. void NativeWindowViews::ShowInactive() {
  453. widget()->ShowInactive();
  454. NotifyWindowShow();
  455. #if BUILDFLAG(IS_LINUX)
  456. if (global_menu_bar_)
  457. global_menu_bar_->OnWindowMapped();
  458. // On X11, setting Z order before showing the window doesn't take effect,
  459. // so we have to call it again.
  460. if (IsX11())
  461. widget()->SetZOrderLevel(widget()->GetZOrderLevel());
  462. #endif
  463. }
  464. void NativeWindowViews::Hide() {
  465. if (is_modal() && NativeWindow::parent())
  466. static_cast<NativeWindowViews*>(parent())->DecrementChildModals();
  467. widget()->Hide();
  468. NotifyWindowHide();
  469. #if BUILDFLAG(IS_LINUX)
  470. if (global_menu_bar_)
  471. global_menu_bar_->OnWindowUnmapped();
  472. #endif
  473. #if BUILDFLAG(IS_WIN)
  474. // When the window is removed from the taskbar via win.hide(),
  475. // the thumbnail buttons need to be set up again.
  476. // Ensure that when the window is hidden,
  477. // the taskbar host is notified that it should re-add them.
  478. taskbar_host_.SetThumbarButtonsAdded(false);
  479. #endif
  480. }
  481. bool NativeWindowViews::IsVisible() const {
  482. #if BUILDFLAG(IS_WIN)
  483. // widget()->IsVisible() calls ::IsWindowVisible, which returns non-zero if a
  484. // window or any of its parent windows are visible. We want to only check the
  485. // current window.
  486. bool visible =
  487. ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_VISIBLE;
  488. // WS_VISIBLE is true even if a window is minimized - explicitly check that.
  489. return visible && !IsMinimized();
  490. #else
  491. return widget()->IsVisible();
  492. #endif
  493. }
  494. bool NativeWindowViews::IsEnabled() const {
  495. #if BUILDFLAG(IS_WIN)
  496. return ::IsWindowEnabled(GetAcceleratedWidget());
  497. #elif BUILDFLAG(IS_LINUX)
  498. if (IsX11())
  499. return !event_disabler_.get();
  500. NOTIMPLEMENTED();
  501. return true;
  502. #endif
  503. }
  504. void NativeWindowViews::IncrementChildModals() {
  505. num_modal_children_++;
  506. SetEnabledInternal(ShouldBeEnabled());
  507. }
  508. void NativeWindowViews::DecrementChildModals() {
  509. if (num_modal_children_ > 0) {
  510. num_modal_children_--;
  511. }
  512. SetEnabledInternal(ShouldBeEnabled());
  513. }
  514. void NativeWindowViews::SetEnabled(bool enable) {
  515. if (enable != is_enabled_) {
  516. is_enabled_ = enable;
  517. SetEnabledInternal(ShouldBeEnabled());
  518. }
  519. }
  520. bool NativeWindowViews::ShouldBeEnabled() const {
  521. return is_enabled_ && (num_modal_children_ == 0);
  522. }
  523. void NativeWindowViews::SetEnabledInternal(bool enable) {
  524. if (enable && IsEnabled()) {
  525. return;
  526. } else if (!enable && !IsEnabled()) {
  527. return;
  528. }
  529. #if BUILDFLAG(IS_WIN)
  530. ::EnableWindow(GetAcceleratedWidget(), enable);
  531. #else
  532. if (IsX11()) {
  533. views::DesktopWindowTreeHostPlatform* tree_host =
  534. views::DesktopWindowTreeHostLinux::GetHostForWidget(
  535. GetAcceleratedWidget());
  536. if (enable) {
  537. tree_host->RemoveEventRewriter(event_disabler_.get());
  538. event_disabler_.reset();
  539. } else {
  540. event_disabler_ = std::make_unique<EventDisabler>();
  541. tree_host->AddEventRewriter(event_disabler_.get());
  542. }
  543. }
  544. #endif
  545. }
  546. void NativeWindowViews::Maximize() {
  547. #if BUILDFLAG(IS_WIN)
  548. if (IsTranslucent()) {
  549. // If a window is translucent but not transparent on Windows,
  550. // that means it must have a backgroundMaterial set.
  551. if (!transparent())
  552. SetRoundedCorners(false);
  553. restore_bounds_ = GetBounds();
  554. auto display = display::Screen::GetScreen()->GetDisplayNearestWindow(
  555. GetNativeWindow());
  556. SetBounds(display.work_area(), false);
  557. NotifyWindowMaximize();
  558. return;
  559. }
  560. #endif
  561. if (IsVisible()) {
  562. widget()->Maximize();
  563. } else {
  564. widget()->native_widget_private()->Show(
  565. ui::mojom::WindowShowState::kMaximized, gfx::Rect());
  566. NotifyWindowShow();
  567. }
  568. }
  569. void NativeWindowViews::Unmaximize() {
  570. if (!IsMaximized())
  571. return;
  572. #if BUILDFLAG(IS_WIN)
  573. if (IsTranslucent()) {
  574. SetBounds(restore_bounds_, false);
  575. NotifyWindowUnmaximize();
  576. if (transparent()) {
  577. UpdateThickFrame();
  578. } else {
  579. SetRoundedCorners(true);
  580. }
  581. return;
  582. }
  583. #endif
  584. widget()->Restore();
  585. #if BUILDFLAG(IS_WIN)
  586. UpdateThickFrame();
  587. #endif
  588. }
  589. bool NativeWindowViews::IsMaximized() const {
  590. if (widget()->IsMaximized())
  591. return true;
  592. #if BUILDFLAG(IS_WIN)
  593. if (IsTranslucent() && !IsMinimized()) {
  594. // If the window is the same dimensions and placement as the
  595. // display, we consider it maximized.
  596. auto display = display::Screen::GetScreen()->GetDisplayNearestWindow(
  597. GetNativeWindow());
  598. return GetBounds() == display.work_area();
  599. }
  600. #endif
  601. return false;
  602. }
  603. void NativeWindowViews::Minimize() {
  604. if (IsVisible())
  605. widget()->Minimize();
  606. else
  607. widget()->native_widget_private()->Show(
  608. ui::mojom::WindowShowState::kMinimized, gfx::Rect());
  609. }
  610. void NativeWindowViews::Restore() {
  611. #if BUILDFLAG(IS_WIN)
  612. if (IsMaximized() && IsTranslucent()) {
  613. SetBounds(restore_bounds_, false);
  614. NotifyWindowRestore();
  615. if (transparent()) {
  616. UpdateThickFrame();
  617. } else {
  618. SetRoundedCorners(true);
  619. }
  620. return;
  621. }
  622. #endif
  623. widget()->Restore();
  624. #if BUILDFLAG(IS_WIN)
  625. UpdateThickFrame();
  626. #endif
  627. }
  628. bool NativeWindowViews::IsMinimized() const {
  629. return widget()->IsMinimized();
  630. }
  631. void NativeWindowViews::SetFullScreen(bool fullscreen) {
  632. if (!IsFullScreenable())
  633. return;
  634. #if BUILDFLAG(IS_WIN)
  635. // There is no native fullscreen state on Windows.
  636. bool leaving_fullscreen = IsFullscreen() && !fullscreen;
  637. if (fullscreen) {
  638. last_window_state_ = ui::mojom::WindowShowState::kFullscreen;
  639. NotifyWindowEnterFullScreen();
  640. } else {
  641. last_window_state_ = ui::mojom::WindowShowState::kNormal;
  642. NotifyWindowLeaveFullScreen();
  643. }
  644. // For window without WS_THICKFRAME style, we can not call SetFullscreen().
  645. // This path will be used for transparent windows as well.
  646. if (!thick_frame_) {
  647. if (fullscreen) {
  648. restore_bounds_ = GetBounds();
  649. auto display =
  650. display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition());
  651. SetBounds(display.bounds(), false);
  652. } else {
  653. SetBounds(restore_bounds_, false);
  654. }
  655. return;
  656. }
  657. // We set the new value after notifying, so we can handle the size event
  658. // correctly.
  659. widget()->SetFullscreen(fullscreen);
  660. // If restoring from fullscreen and the window isn't visible, force visible,
  661. // else a non-responsive window shell could be rendered.
  662. // (this situation may arise when app starts with fullscreen: true)
  663. // Note: the following must be after "widget()->SetFullscreen(fullscreen);"
  664. if (leaving_fullscreen && !IsVisible())
  665. FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE);
  666. // Auto-hide menubar when in fullscreen.
  667. if (fullscreen) {
  668. menu_bar_visible_before_fullscreen_ = IsMenuBarVisible();
  669. SetMenuBarVisibility(false);
  670. } else {
  671. // No fullscreen -> fullscreen video -> un-fullscreen video results
  672. // in `NativeWindowViews::SetFullScreen(false)` being called twice.
  673. // `menu_bar_visible_before_fullscreen_` is always false on the
  674. // second call which results in `SetMenuBarVisibility(false)` no
  675. // matter what. We check `leaving_fullscreen` to avoid this.
  676. if (!leaving_fullscreen)
  677. return;
  678. SetMenuBarVisibility(!IsMenuBarAutoHide() &&
  679. menu_bar_visible_before_fullscreen_);
  680. menu_bar_visible_before_fullscreen_ = false;
  681. }
  682. #else
  683. if (IsVisible())
  684. widget()->SetFullscreen(fullscreen);
  685. else if (fullscreen)
  686. widget()->native_widget_private()->Show(
  687. ui::mojom::WindowShowState::kFullscreen, gfx::Rect());
  688. // Auto-hide menubar when in fullscreen.
  689. if (fullscreen) {
  690. menu_bar_visible_before_fullscreen_ = IsMenuBarVisible();
  691. SetMenuBarVisibility(false);
  692. } else {
  693. SetMenuBarVisibility(!IsMenuBarAutoHide() &&
  694. menu_bar_visible_before_fullscreen_);
  695. menu_bar_visible_before_fullscreen_ = false;
  696. }
  697. #endif
  698. }
  699. bool NativeWindowViews::IsFullscreen() const {
  700. return widget()->IsFullscreen();
  701. }
  702. void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) {
  703. #if BUILDFLAG(IS_WIN)
  704. if (is_moving_ || is_resizing_) {
  705. pending_bounds_change_ = bounds;
  706. }
  707. #endif
  708. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
  709. // On Linux and Windows the minimum and maximum size should be updated with
  710. // window size when window is not resizable.
  711. if (!resizable_) {
  712. SetMaximumSize(bounds.size());
  713. SetMinimumSize(bounds.size());
  714. }
  715. #endif
  716. widget()->SetBounds(bounds);
  717. }
  718. gfx::Rect NativeWindowViews::GetBounds() const {
  719. #if BUILDFLAG(IS_WIN)
  720. if (IsMinimized())
  721. return widget()->GetRestoredBounds();
  722. #endif
  723. return widget()->GetWindowBoundsInScreen();
  724. }
  725. gfx::Rect NativeWindowViews::GetContentBounds() const {
  726. return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect();
  727. }
  728. gfx::Size NativeWindowViews::GetContentSize() const {
  729. #if BUILDFLAG(IS_WIN)
  730. if (IsMinimized())
  731. return NativeWindow::GetContentSize();
  732. #endif
  733. return content_view() ? content_view()->size() : gfx::Size();
  734. }
  735. gfx::Rect NativeWindowViews::GetNormalBounds() const {
  736. #if BUILDFLAG(IS_WIN)
  737. if (IsMaximized() && IsTranslucent())
  738. return restore_bounds_;
  739. #endif
  740. return widget()->GetRestoredBounds();
  741. }
  742. void NativeWindowViews::SetContentSizeConstraints(
  743. const extensions::SizeConstraints& size_constraints) {
  744. NativeWindow::SetContentSizeConstraints(size_constraints);
  745. #if BUILDFLAG(IS_WIN)
  746. // Changing size constraints would force adding the WS_THICKFRAME style, so
  747. // do nothing if thickFrame is false.
  748. if (!thick_frame_)
  749. return;
  750. #endif
  751. // widget_delegate() is only available after Init() is called, we make use
  752. // of this to determine whether native widget has initialized.
  753. if (widget() && widget()->widget_delegate())
  754. widget()->OnSizeConstraintsChanged();
  755. if (resizable_)
  756. old_size_constraints_ = size_constraints;
  757. }
  758. #if BUILDFLAG(IS_WIN)
  759. // This override does almost the same with its parent, except that it uses
  760. // the WindowSizeToContentSizeBuggy method to convert window size to content
  761. // size. See the comment of the method for the reason behind this.
  762. extensions::SizeConstraints NativeWindowViews::GetContentSizeConstraints()
  763. const {
  764. if (content_size_constraints_)
  765. return *content_size_constraints_;
  766. if (!size_constraints_)
  767. return extensions::SizeConstraints();
  768. extensions::SizeConstraints constraints;
  769. if (size_constraints_->HasMaximumSize()) {
  770. constraints.set_maximum_size(WindowSizeToContentSizeBuggy(
  771. GetAcceleratedWidget(), size_constraints_->GetMaximumSize()));
  772. }
  773. if (size_constraints_->HasMinimumSize()) {
  774. constraints.set_minimum_size(WindowSizeToContentSizeBuggy(
  775. GetAcceleratedWidget(), size_constraints_->GetMinimumSize()));
  776. }
  777. return constraints;
  778. }
  779. #endif
  780. void NativeWindowViews::SetResizable(bool resizable) {
  781. if (resizable != resizable_) {
  782. // On Linux there is no "resizable" property of a window, we have to set
  783. // both the minimum and maximum size to the window size to achieve it.
  784. if (resizable) {
  785. SetContentSizeConstraints(old_size_constraints_);
  786. SetMaximizable(maximizable_);
  787. } else {
  788. old_size_constraints_ = GetContentSizeConstraints();
  789. resizable_ = false;
  790. gfx::Size content_size = GetContentSize();
  791. SetContentSizeConstraints(
  792. extensions::SizeConstraints(content_size, content_size));
  793. }
  794. }
  795. resizable_ = resizable;
  796. SetCanResize(resizable_);
  797. #if BUILDFLAG(IS_WIN)
  798. UpdateThickFrame();
  799. #endif
  800. }
  801. bool NativeWindowViews::MoveAbove(const std::string& sourceId) {
  802. const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId);
  803. if (id.type != content::DesktopMediaID::TYPE_WINDOW)
  804. return false;
  805. #if BUILDFLAG(IS_WIN)
  806. const HWND otherWindow = reinterpret_cast<HWND>(id.id);
  807. if (!::IsWindow(otherWindow))
  808. return false;
  809. ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0,
  810. 0, 0, 0,
  811. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
  812. #else
  813. if (IsX11()) {
  814. if (!IsWindowValid(static_cast<x11::Window>(id.id)))
  815. return false;
  816. electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()),
  817. static_cast<x11::Window>(id.id));
  818. }
  819. #endif
  820. return true;
  821. }
  822. void NativeWindowViews::MoveTop() {
  823. // TODO(julien.isorce): fix chromium in order to use existing
  824. // widget()->StackAtTop().
  825. #if BUILDFLAG(IS_WIN)
  826. gfx::Point pos = GetPosition();
  827. gfx::Size size = GetSize();
  828. ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(),
  829. size.width(), size.height(),
  830. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
  831. #else
  832. if (IsX11())
  833. electron::MoveWindowToForeground(
  834. static_cast<x11::Window>(GetAcceleratedWidget()));
  835. #endif
  836. }
  837. bool NativeWindowViews::IsResizable() const {
  838. #if BUILDFLAG(IS_WIN)
  839. if (has_frame())
  840. return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME;
  841. #endif
  842. return resizable_;
  843. }
  844. void NativeWindowViews::SetAspectRatio(double aspect_ratio,
  845. const gfx::Size& extra_size) {
  846. NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
  847. gfx::SizeF aspect(aspect_ratio, 1.0);
  848. // Scale up because SetAspectRatio() truncates aspect value to int
  849. aspect.Scale(100);
  850. widget()->SetAspectRatio(aspect);
  851. }
  852. void NativeWindowViews::SetMovable(bool movable) {
  853. movable_ = movable;
  854. }
  855. bool NativeWindowViews::IsMovable() const {
  856. #if BUILDFLAG(IS_WIN)
  857. return movable_;
  858. #else
  859. return true; // Not implemented on Linux.
  860. #endif
  861. }
  862. void NativeWindowViews::SetMinimizable(bool minimizable) {
  863. #if BUILDFLAG(IS_WIN)
  864. FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX);
  865. if (IsWindowControlsOverlayEnabled()) {
  866. auto* frame_view =
  867. static_cast<WinFrameView*>(widget()->non_client_view()->frame_view());
  868. frame_view->caption_button_container()->UpdateButtons();
  869. }
  870. #endif
  871. minimizable_ = minimizable;
  872. }
  873. bool NativeWindowViews::IsMinimizable() const {
  874. #if BUILDFLAG(IS_WIN)
  875. return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX;
  876. #else
  877. return true; // Not implemented on Linux.
  878. #endif
  879. }
  880. void NativeWindowViews::SetMaximizable(bool maximizable) {
  881. #if BUILDFLAG(IS_WIN)
  882. FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX);
  883. if (IsWindowControlsOverlayEnabled()) {
  884. auto* frame_view =
  885. static_cast<WinFrameView*>(widget()->non_client_view()->frame_view());
  886. frame_view->caption_button_container()->UpdateButtons();
  887. }
  888. #endif
  889. maximizable_ = maximizable;
  890. }
  891. bool NativeWindowViews::IsMaximizable() const {
  892. #if BUILDFLAG(IS_WIN)
  893. return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX;
  894. #else
  895. return true; // Not implemented on Linux.
  896. #endif
  897. }
  898. bool NativeWindowViews::IsExcludedFromShownWindowsMenu() const {
  899. // return false on unsupported platforms
  900. return false;
  901. }
  902. void NativeWindowViews::SetFullScreenable(bool fullscreenable) {
  903. fullscreenable_ = fullscreenable;
  904. }
  905. bool NativeWindowViews::IsFullScreenable() const {
  906. return fullscreenable_;
  907. }
  908. void NativeWindowViews::SetClosable(bool closable) {
  909. #if BUILDFLAG(IS_WIN)
  910. HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false);
  911. if (closable) {
  912. EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED);
  913. } else {
  914. EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
  915. }
  916. if (IsWindowControlsOverlayEnabled()) {
  917. auto* frame_view =
  918. static_cast<WinFrameView*>(widget()->non_client_view()->frame_view());
  919. frame_view->caption_button_container()->UpdateButtons();
  920. }
  921. #endif
  922. }
  923. bool NativeWindowViews::IsClosable() const {
  924. #if BUILDFLAG(IS_WIN)
  925. HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false);
  926. MENUITEMINFO info;
  927. memset(&info, 0, sizeof(info));
  928. info.cbSize = sizeof(info);
  929. info.fMask = MIIM_STATE;
  930. if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) {
  931. return false;
  932. }
  933. return !(info.fState & MFS_DISABLED);
  934. #elif BUILDFLAG(IS_LINUX)
  935. return true;
  936. #endif
  937. }
  938. void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order,
  939. const std::string& level,
  940. int relativeLevel) {
  941. bool level_changed = z_order != widget()->GetZOrderLevel();
  942. widget()->SetZOrderLevel(z_order);
  943. #if BUILDFLAG(IS_WIN)
  944. // Reset the placement flag.
  945. behind_task_bar_ = false;
  946. if (z_order != ui::ZOrderLevel::kNormal) {
  947. // On macOS the window is placed behind the Dock for the following levels.
  948. // Re-use the same names on Windows to make it easier for the user.
  949. static const std::vector<std::string> levels = {
  950. "floating", "torn-off-menu", "modal-panel", "main-menu", "status"};
  951. behind_task_bar_ = base::Contains(levels, level);
  952. }
  953. #endif
  954. MoveBehindTaskBarIfNeeded();
  955. // This must be notified at the very end or IsAlwaysOnTop
  956. // will not yet have been updated to reflect the new status
  957. if (level_changed)
  958. NativeWindow::NotifyWindowAlwaysOnTopChanged();
  959. }
  960. ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() const {
  961. return widget()->GetZOrderLevel();
  962. }
  963. // We previous called widget()->CenterWindow() here, but in
  964. // Chromium CL 4916277 behavior was changed to center relative to the
  965. // parent window if there is one. We want to keep the old behavior
  966. // for now to avoid breaking API contract, but should consider the long
  967. // term plan for this aligning with upstream.
  968. void NativeWindowViews::Center() {
  969. #if BUILDFLAG(IS_LINUX)
  970. auto display =
  971. display::Screen::GetScreen()->GetDisplayNearestWindow(GetNativeWindow());
  972. gfx::Rect window_bounds_in_screen = display.work_area();
  973. window_bounds_in_screen.ClampToCenteredSize(GetSize());
  974. widget()->SetBounds(window_bounds_in_screen);
  975. #else
  976. HWND hwnd = GetAcceleratedWidget();
  977. gfx::Size size = display::win::ScreenWin::DIPToScreenSize(hwnd, GetSize());
  978. gfx::CenterAndSizeWindow(nullptr, hwnd, size);
  979. #endif
  980. }
  981. void NativeWindowViews::Invalidate() {
  982. widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size()));
  983. }
  984. void NativeWindowViews::SetTitle(const std::string& title) {
  985. title_ = title;
  986. widget()->UpdateWindowTitle();
  987. }
  988. std::string NativeWindowViews::GetTitle() const {
  989. return title_;
  990. }
  991. void NativeWindowViews::FlashFrame(bool flash) {
  992. #if BUILDFLAG(IS_WIN)
  993. // The Chromium's implementation has a bug stopping flash.
  994. if (!flash) {
  995. FLASHWINFO fwi;
  996. fwi.cbSize = sizeof(fwi);
  997. fwi.hwnd = GetAcceleratedWidget();
  998. fwi.dwFlags = FLASHW_STOP;
  999. fwi.uCount = 0;
  1000. FlashWindowEx(&fwi);
  1001. return;
  1002. }
  1003. #endif
  1004. widget()->FlashFrame(flash);
  1005. }
  1006. void NativeWindowViews::SetSkipTaskbar(bool skip) {
  1007. #if BUILDFLAG(IS_WIN)
  1008. Microsoft::WRL::ComPtr<ITaskbarList> taskbar;
  1009. if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr,
  1010. CLSCTX_INPROC_SERVER,
  1011. IID_PPV_ARGS(&taskbar))) ||
  1012. FAILED(taskbar->HrInit()))
  1013. return;
  1014. if (skip) {
  1015. taskbar->DeleteTab(GetAcceleratedWidget());
  1016. } else {
  1017. taskbar->AddTab(GetAcceleratedWidget());
  1018. taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget());
  1019. }
  1020. #endif
  1021. }
  1022. void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) {
  1023. SetFullScreen(simple_fullscreen);
  1024. }
  1025. bool NativeWindowViews::IsSimpleFullScreen() const {
  1026. return IsFullscreen();
  1027. }
  1028. void NativeWindowViews::SetKiosk(bool kiosk) {
  1029. SetFullScreen(kiosk);
  1030. }
  1031. bool NativeWindowViews::IsKiosk() const {
  1032. return IsFullscreen();
  1033. }
  1034. bool NativeWindowViews::IsTabletMode() const {
  1035. #if BUILDFLAG(IS_WIN)
  1036. return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget());
  1037. #else
  1038. return false;
  1039. #endif
  1040. }
  1041. SkColor NativeWindowViews::GetBackgroundColor() const {
  1042. auto* background = root_view_.background();
  1043. if (!background)
  1044. return SK_ColorTRANSPARENT;
  1045. return background->get_color();
  1046. }
  1047. void NativeWindowViews::SetBackgroundColor(SkColor background_color) {
  1048. // web views' background color.
  1049. root_view_.SetBackground(views::CreateSolidBackground(background_color));
  1050. #if BUILDFLAG(IS_WIN)
  1051. // Set the background color of native window.
  1052. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color));
  1053. ULONG_PTR previous_brush =
  1054. SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND,
  1055. reinterpret_cast<LONG_PTR>(brush));
  1056. if (previous_brush)
  1057. DeleteObject((HBRUSH)previous_brush);
  1058. InvalidateRect(GetAcceleratedWidget(), nullptr, 1);
  1059. #endif
  1060. }
  1061. void NativeWindowViews::SetHasShadow(bool has_shadow) {
  1062. wm::SetShadowElevation(GetNativeWindow(),
  1063. has_shadow ? wm::kShadowElevationInactiveWindow
  1064. : wm::kShadowElevationNone);
  1065. }
  1066. bool NativeWindowViews::HasShadow() const {
  1067. return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) !=
  1068. wm::kShadowElevationNone;
  1069. }
  1070. void NativeWindowViews::SetOpacity(const double opacity) {
  1071. #if BUILDFLAG(IS_WIN)
  1072. const double boundedOpacity = std::clamp(opacity, 0.0, 1.0);
  1073. HWND hwnd = GetAcceleratedWidget();
  1074. if (!layered_) {
  1075. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE);
  1076. ex_style |= WS_EX_LAYERED;
  1077. ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style);
  1078. layered_ = true;
  1079. }
  1080. ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA);
  1081. opacity_ = boundedOpacity;
  1082. #else
  1083. opacity_ = 1.0; // setOpacity unsupported on Linux
  1084. #endif
  1085. }
  1086. double NativeWindowViews::GetOpacity() const {
  1087. return opacity_;
  1088. }
  1089. void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) {
  1090. #if BUILDFLAG(IS_WIN)
  1091. LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE);
  1092. if (ignore)
  1093. ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED);
  1094. else
  1095. ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED);
  1096. if (layered_)
  1097. ex_style |= WS_EX_LAYERED;
  1098. ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style);
  1099. // Forwarding is always disabled when not ignoring mouse messages.
  1100. if (!ignore) {
  1101. SetForwardMouseMessages(false);
  1102. } else {
  1103. SetForwardMouseMessages(forward);
  1104. }
  1105. #else
  1106. if (IsX11()) {
  1107. auto* connection = x11::Connection::Get();
  1108. if (ignore) {
  1109. x11::Rectangle r{0, 0, 1, 1};
  1110. connection->shape().Rectangles({
  1111. .operation = x11::Shape::So::Set,
  1112. .destination_kind = x11::Shape::Sk::Input,
  1113. .ordering = x11::ClipOrdering::YXBanded,
  1114. .destination_window =
  1115. static_cast<x11::Window>(GetAcceleratedWidget()),
  1116. .rectangles = {r},
  1117. });
  1118. } else {
  1119. connection->shape().Mask({
  1120. .operation = x11::Shape::So::Set,
  1121. .destination_kind = x11::Shape::Sk::Input,
  1122. .destination_window =
  1123. static_cast<x11::Window>(GetAcceleratedWidget()),
  1124. .source_bitmap = x11::Pixmap::None,
  1125. });
  1126. }
  1127. }
  1128. #endif
  1129. }
  1130. void NativeWindowViews::SetContentProtection(bool enable) {
  1131. #if BUILDFLAG(IS_WIN)
  1132. widget()->native_widget_private()->SetAllowScreenshots(!enable);
  1133. #endif
  1134. }
  1135. bool NativeWindowViews::IsContentProtected() const {
  1136. #if BUILDFLAG(IS_WIN)
  1137. return !widget()->native_widget_private()->AreScreenshotsAllowed();
  1138. #else // Not implemented on Linux
  1139. return false;
  1140. #endif
  1141. }
  1142. void NativeWindowViews::SetFocusable(bool focusable) {
  1143. widget()->widget_delegate()->SetCanActivate(focusable);
  1144. #if BUILDFLAG(IS_WIN)
  1145. LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE);
  1146. if (focusable)
  1147. ex_style &= ~WS_EX_NOACTIVATE;
  1148. else
  1149. ex_style |= WS_EX_NOACTIVATE;
  1150. ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style);
  1151. SetSkipTaskbar(!focusable);
  1152. Focus(false);
  1153. #endif
  1154. }
  1155. bool NativeWindowViews::IsFocusable() const {
  1156. bool can_activate = widget()->widget_delegate()->CanActivate();
  1157. #if BUILDFLAG(IS_WIN)
  1158. LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE);
  1159. bool no_activate = ex_style & WS_EX_NOACTIVATE;
  1160. return !no_activate && can_activate;
  1161. #else
  1162. return can_activate;
  1163. #endif
  1164. }
  1165. void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) {
  1166. #if BUILDFLAG(IS_LINUX)
  1167. // Remove global menu bar.
  1168. if (global_menu_bar_ && menu_model == nullptr) {
  1169. global_menu_bar_.reset();
  1170. root_view_.UnregisterAcceleratorsWithFocusManager();
  1171. return;
  1172. }
  1173. // Use global application menu bar when possible.
  1174. bool can_use_global_menus = ui::OzonePlatform::GetInstance()
  1175. ->GetPlatformProperties()
  1176. .supports_global_application_menus;
  1177. if (can_use_global_menus && ShouldUseGlobalMenuBar()) {
  1178. if (!global_menu_bar_)
  1179. global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this);
  1180. if (global_menu_bar_->IsServerStarted()) {
  1181. root_view_.RegisterAcceleratorsWithFocusManager(menu_model);
  1182. global_menu_bar_->SetMenu(menu_model);
  1183. return;
  1184. }
  1185. }
  1186. #endif
  1187. // Should reset content size when setting menu.
  1188. gfx::Size content_size = GetContentSize();
  1189. bool should_reset_size = use_content_size_ && has_frame() &&
  1190. !IsMenuBarAutoHide() &&
  1191. ((!!menu_model) != root_view_.HasMenu());
  1192. root_view_.SetMenu(menu_model);
  1193. if (should_reset_size) {
  1194. // Enlarge the size constraints for the menu.
  1195. int menu_bar_height = root_view_.GetMenuBarHeight();
  1196. extensions::SizeConstraints constraints = GetContentSizeConstraints();
  1197. if (constraints.HasMinimumSize()) {
  1198. gfx::Size min_size = constraints.GetMinimumSize();
  1199. min_size.set_height(min_size.height() + menu_bar_height);
  1200. constraints.set_minimum_size(min_size);
  1201. }
  1202. if (constraints.HasMaximumSize()) {
  1203. gfx::Size max_size = constraints.GetMaximumSize();
  1204. max_size.set_height(max_size.height() + menu_bar_height);
  1205. constraints.set_maximum_size(max_size);
  1206. }
  1207. SetContentSizeConstraints(constraints);
  1208. // Resize the window to make sure content size is not changed.
  1209. SetContentSize(content_size);
  1210. }
  1211. }
  1212. void NativeWindowViews::SetParentWindow(NativeWindow* parent) {
  1213. NativeWindow::SetParentWindow(parent);
  1214. #if BUILDFLAG(IS_LINUX)
  1215. if (IsX11()) {
  1216. auto* connection = x11::Connection::Get();
  1217. connection->SetProperty(
  1218. static_cast<x11::Window>(GetAcceleratedWidget()),
  1219. x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW,
  1220. parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget())
  1221. : ui::GetX11RootWindow());
  1222. }
  1223. #elif BUILDFLAG(IS_WIN)
  1224. // To set parentship between windows into Windows is better to play with the
  1225. // owner instead of the parent, as Windows natively seems to do if a parent
  1226. // is specified at window creation time.
  1227. // For do this we must NOT use the ::SetParent function, instead we must use
  1228. // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set
  1229. // to "GWLP_HWNDPARENT" which actually means the window owner.
  1230. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : nullptr;
  1231. if (hwndParent ==
  1232. (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT))
  1233. return;
  1234. ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT,
  1235. (LONG_PTR)hwndParent);
  1236. // Ensures the visibility
  1237. if (IsVisible()) {
  1238. WINDOWPLACEMENT wp;
  1239. wp.length = sizeof(WINDOWPLACEMENT);
  1240. ::GetWindowPlacement(GetAcceleratedWidget(), &wp);
  1241. ::ShowWindow(GetAcceleratedWidget(), SW_HIDE);
  1242. ::ShowWindow(GetAcceleratedWidget(), wp.showCmd);
  1243. ::BringWindowToTop(GetAcceleratedWidget());
  1244. }
  1245. #endif
  1246. }
  1247. gfx::NativeView NativeWindowViews::GetNativeView() const {
  1248. return widget()->GetNativeView();
  1249. }
  1250. gfx::NativeWindow NativeWindowViews::GetNativeWindow() const {
  1251. return widget()->GetNativeWindow();
  1252. }
  1253. void NativeWindowViews::SetProgressBar(double progress,
  1254. NativeWindow::ProgressState state) {
  1255. #if BUILDFLAG(IS_WIN)
  1256. taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state);
  1257. #elif BUILDFLAG(IS_LINUX)
  1258. if (unity::IsRunning()) {
  1259. unity::SetProgressFraction(progress);
  1260. }
  1261. #endif
  1262. }
  1263. void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay,
  1264. const std::string& description) {
  1265. #if BUILDFLAG(IS_WIN)
  1266. SkBitmap overlay_bitmap = overlay.AsBitmap();
  1267. taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap,
  1268. description);
  1269. #endif
  1270. }
  1271. void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) {
  1272. root_view_.SetAutoHideMenuBar(auto_hide);
  1273. }
  1274. bool NativeWindowViews::IsMenuBarAutoHide() const {
  1275. return root_view_.is_menu_bar_auto_hide();
  1276. }
  1277. void NativeWindowViews::SetMenuBarVisibility(bool visible) {
  1278. root_view_.SetMenuBarVisibility(visible);
  1279. }
  1280. bool NativeWindowViews::IsMenuBarVisible() const {
  1281. return root_view_.is_menu_bar_visible();
  1282. }
  1283. void NativeWindowViews::SetBackgroundMaterial(const std::string& material) {
  1284. NativeWindow::SetBackgroundMaterial(material);
  1285. #if BUILDFLAG(IS_WIN)
  1286. // DWMWA_USE_HOSTBACKDROPBRUSH is only supported on Windows 11 22H2 and up.
  1287. if (base::win::GetVersion() < base::win::Version::WIN11_22H2)
  1288. return;
  1289. DWM_SYSTEMBACKDROP_TYPE backdrop_type = GetBackdropFromString(material);
  1290. HRESULT result =
  1291. DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_SYSTEMBACKDROP_TYPE,
  1292. &backdrop_type, sizeof(backdrop_type));
  1293. if (FAILED(result))
  1294. LOG(WARNING) << "Failed to set background material to " << material;
  1295. // For frameless windows with a background material set, we also need to
  1296. // remove the caption color so it doesn't render a caption bar (since the
  1297. // window is frameless)
  1298. COLORREF caption_color = DWMWA_COLOR_DEFAULT;
  1299. if (backdrop_type != DWMSBT_NONE && backdrop_type != DWMSBT_AUTO &&
  1300. !has_frame()) {
  1301. caption_color = DWMWA_COLOR_NONE;
  1302. }
  1303. result = DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_CAPTION_COLOR,
  1304. &caption_color, sizeof(caption_color));
  1305. if (FAILED(result))
  1306. LOG(WARNING) << "Failed to set caption color to transparent";
  1307. #endif
  1308. }
  1309. void NativeWindowViews::SetVisibleOnAllWorkspaces(
  1310. bool visible,
  1311. bool visibleOnFullScreen,
  1312. bool skipTransformProcessType) {
  1313. widget()->SetVisibleOnAllWorkspaces(visible);
  1314. }
  1315. bool NativeWindowViews::IsVisibleOnAllWorkspaces() const {
  1316. #if BUILDFLAG(IS_LINUX)
  1317. if (IsX11()) {
  1318. // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to
  1319. // determine whether the current window is visible on all workspaces.
  1320. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY");
  1321. std::vector<x11::Atom> wm_states;
  1322. auto* connection = x11::Connection::Get();
  1323. connection->GetArrayProperty(
  1324. static_cast<x11::Window>(GetAcceleratedWidget()),
  1325. x11::GetAtom("_NET_WM_STATE"), &wm_states);
  1326. return base::Contains(wm_states, sticky_atom);
  1327. }
  1328. #endif
  1329. return false;
  1330. }
  1331. content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const {
  1332. const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget();
  1333. content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId;
  1334. content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId;
  1335. #if BUILDFLAG(IS_WIN)
  1336. window_handle =
  1337. reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget);
  1338. #elif BUILDFLAG(IS_LINUX)
  1339. window_handle = static_cast<uint32_t>(accelerated_widget);
  1340. #endif
  1341. aura::WindowTreeHost* const host =
  1342. aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget);
  1343. aura::Window* const aura_window = host ? host->window() : nullptr;
  1344. if (aura_window) {
  1345. aura_id = content::DesktopMediaID::RegisterNativeWindow(
  1346. content::DesktopMediaID::TYPE_WINDOW, aura_window)
  1347. .window_id;
  1348. }
  1349. // No constructor to pass the aura_id. Make sure to not use the other
  1350. // constructor that has a third parameter, it is for yet another purpose.
  1351. content::DesktopMediaID result = content::DesktopMediaID(
  1352. content::DesktopMediaID::TYPE_WINDOW, window_handle);
  1353. // Confusing but this is how content::DesktopMediaID is designed. The id
  1354. // property is the window handle whereas the window_id property is an id
  1355. // given by a map containing all aura instances.
  1356. result.window_id = aura_id;
  1357. return result;
  1358. }
  1359. gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const {
  1360. if (GetNativeWindow() && GetNativeWindow()->GetHost())
  1361. return GetNativeWindow()->GetHost()->GetAcceleratedWidget();
  1362. else
  1363. return gfx::kNullAcceleratedWidget;
  1364. }
  1365. NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const {
  1366. return GetAcceleratedWidget();
  1367. }
  1368. gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds(
  1369. const gfx::Rect& bounds) const {
  1370. if (!has_frame())
  1371. return bounds;
  1372. gfx::Rect window_bounds(bounds);
  1373. #if BUILDFLAG(IS_WIN)
  1374. if (widget()->non_client_view()) {
  1375. HWND hwnd = GetAcceleratedWidget();
  1376. gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds);
  1377. window_bounds = ScreenToDIPRect(
  1378. hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds(
  1379. dpi_bounds));
  1380. }
  1381. #endif
  1382. if (root_view_.HasMenu() && root_view_.is_menu_bar_visible()) {
  1383. int menu_bar_height = root_view_.GetMenuBarHeight();
  1384. window_bounds.set_y(window_bounds.y() - menu_bar_height);
  1385. window_bounds.set_height(window_bounds.height() + menu_bar_height);
  1386. }
  1387. return window_bounds;
  1388. }
  1389. gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
  1390. const gfx::Rect& bounds) const {
  1391. if (!has_frame())
  1392. return bounds;
  1393. gfx::Rect content_bounds(bounds);
  1394. #if BUILDFLAG(IS_WIN)
  1395. HWND hwnd = GetAcceleratedWidget();
  1396. content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size());
  1397. RECT rect;
  1398. SetRectEmpty(&rect);
  1399. DWORD style = ::GetWindowLong(hwnd, GWL_STYLE);
  1400. DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE);
  1401. AdjustWindowRectEx(&rect, style, FALSE, ex_style);
  1402. content_bounds.set_width(content_bounds.width() - (rect.right - rect.left));
  1403. content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top));
  1404. content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size());
  1405. #endif
  1406. if (root_view_.HasMenu() && root_view_.is_menu_bar_visible()) {
  1407. int menu_bar_height = root_view_.GetMenuBarHeight();
  1408. content_bounds.set_y(content_bounds.y() + menu_bar_height);
  1409. content_bounds.set_height(content_bounds.height() - menu_bar_height);
  1410. }
  1411. return content_bounds;
  1412. }
  1413. #if BUILDFLAG(IS_WIN)
  1414. void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) {
  1415. // We are responsible for storing the images.
  1416. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon));
  1417. app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon));
  1418. HWND hwnd = GetAcceleratedWidget();
  1419. SendMessage(hwnd, WM_SETICON, ICON_SMALL,
  1420. reinterpret_cast<LPARAM>(window_icon_.get()));
  1421. SendMessage(hwnd, WM_SETICON, ICON_BIG,
  1422. reinterpret_cast<LPARAM>(app_icon_.get()));
  1423. }
  1424. #elif BUILDFLAG(IS_LINUX)
  1425. void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) {
  1426. auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget(
  1427. GetAcceleratedWidget());
  1428. tree_host->SetWindowIcons(icon, {});
  1429. }
  1430. #endif
  1431. #if BUILDFLAG(IS_WIN)
  1432. void NativeWindowViews::UpdateThickFrame() {
  1433. if (!thick_frame_)
  1434. return;
  1435. if (IsMaximized() && !transparent()) {
  1436. // For maximized window add thick frame always, otherwise it will be
  1437. // removed in HWNDMessageHandler::SizeConstraintsChanged() which will
  1438. // result in maximized window bounds change.
  1439. FlipWindowStyle(GetAcceleratedWidget(), true, WS_THICKFRAME);
  1440. } else if (has_frame()) {
  1441. FlipWindowStyle(GetAcceleratedWidget(), resizable_, WS_THICKFRAME);
  1442. }
  1443. }
  1444. #endif
  1445. void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget,
  1446. bool active) {
  1447. if (changed_widget != widget())
  1448. return;
  1449. if (active) {
  1450. MoveBehindTaskBarIfNeeded();
  1451. NativeWindow::NotifyWindowFocus();
  1452. } else {
  1453. NativeWindow::NotifyWindowBlur();
  1454. }
  1455. // Hide menu bar when window is blurred.
  1456. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible())
  1457. SetMenuBarVisibility(false);
  1458. root_view_.ResetAltState();
  1459. }
  1460. void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget,
  1461. const gfx::Rect& bounds) {
  1462. if (changed_widget != widget())
  1463. return;
  1464. #if BUILDFLAG(IS_WIN)
  1465. // OnWidgetBoundsChanged is emitted both when a window is moved and when a
  1466. // window is resized. If the window is moving, then
  1467. // WidgetObserver::OnWidgetBoundsChanged is being called from
  1468. // Widget::OnNativeWidgetMove() and not Widget::OnNativeWidgetSizeChanged.
  1469. // |GetWindowBoundsInScreen| has a ~1 pixel margin
  1470. // of error because it converts from floats to integers between
  1471. // calculations, so if we check existing bounds directly against the new
  1472. // bounds without accounting for that we'll have constant false positives
  1473. // when the window is moving but the user hasn't changed its size at all.
  1474. auto isWithinOnePixel = [](gfx::Size old_size, gfx::Size new_size) -> bool {
  1475. return base::IsApproximatelyEqual(old_size.width(), new_size.width(), 1) &&
  1476. base::IsApproximatelyEqual(old_size.height(), new_size.height(), 1);
  1477. };
  1478. if (is_moving_ && isWithinOnePixel(widget_size_, bounds.size()))
  1479. return;
  1480. #endif
  1481. // We use |GetBounds| to account for minimized windows on Windows.
  1482. const auto new_bounds = GetBounds();
  1483. if (widget_size_ != new_bounds.size()) {
  1484. NotifyWindowResize();
  1485. widget_size_ = new_bounds.size();
  1486. }
  1487. }
  1488. void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) {
  1489. aura::Window* window = GetNativeWindow();
  1490. if (window)
  1491. window->RemovePreTargetHandler(this);
  1492. }
  1493. void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) {
  1494. widget_destroyed_ = true;
  1495. }
  1496. views::View* NativeWindowViews::GetInitiallyFocusedView() {
  1497. return focused_view_;
  1498. }
  1499. bool NativeWindowViews::CanMaximize() const {
  1500. return resizable_ && maximizable_;
  1501. }
  1502. bool NativeWindowViews::CanMinimize() const {
  1503. #if BUILDFLAG(IS_WIN)
  1504. return minimizable_;
  1505. #elif BUILDFLAG(IS_LINUX)
  1506. return true;
  1507. #endif
  1508. }
  1509. std::u16string NativeWindowViews::GetWindowTitle() const {
  1510. return base::UTF8ToUTF16(title_);
  1511. }
  1512. views::View* NativeWindowViews::GetContentsView() {
  1513. return root_view_.GetMainView();
  1514. }
  1515. bool NativeWindowViews::ShouldDescendIntoChildForEventHandling(
  1516. gfx::NativeView child,
  1517. const gfx::Point& location) {
  1518. return NonClientHitTest(location) == HTNOWHERE;
  1519. }
  1520. views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) {
  1521. return new NativeWindowClientView{widget, &root_view_, this};
  1522. }
  1523. std::unique_ptr<views::NonClientFrameView>
  1524. NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) {
  1525. #if BUILDFLAG(IS_WIN)
  1526. auto frame_view = std::make_unique<WinFrameView>();
  1527. frame_view->Init(this, widget);
  1528. return frame_view;
  1529. #else
  1530. if (has_frame() && !has_client_frame()) {
  1531. return std::make_unique<NativeFrameView>(this, widget);
  1532. } else {
  1533. if (has_frame() && has_client_frame()) {
  1534. auto frame_view = std::make_unique<ClientFrameViewLinux>();
  1535. frame_view->Init(this, widget);
  1536. return frame_view;
  1537. } else {
  1538. auto frame_view = std::make_unique<OpaqueFrameView>();
  1539. frame_view->Init(this, widget);
  1540. return frame_view;
  1541. }
  1542. }
  1543. #endif
  1544. }
  1545. void NativeWindowViews::OnWidgetMove() {
  1546. NotifyWindowMove();
  1547. }
  1548. void NativeWindowViews::HandleKeyboardEvent(
  1549. content::WebContents*,
  1550. const input::NativeWebKeyboardEvent& event) {
  1551. if (widget_destroyed_)
  1552. return;
  1553. #if BUILDFLAG(IS_LINUX)
  1554. if (event.windows_key_code == ui::VKEY_BROWSER_BACK)
  1555. NotifyWindowExecuteAppCommand(kBrowserBackward);
  1556. else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD)
  1557. NotifyWindowExecuteAppCommand(kBrowserForward);
  1558. #endif
  1559. keyboard_event_handler_.HandleKeyboardEvent(event,
  1560. root_view_.GetFocusManager());
  1561. root_view_.HandleKeyEvent(event);
  1562. }
  1563. void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) {
  1564. if (event->type() != ui::EventType::kMousePressed)
  1565. return;
  1566. // Alt+Click should not toggle menu bar.
  1567. root_view_.ResetAltState();
  1568. #if BUILDFLAG(IS_LINUX)
  1569. if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON)
  1570. NotifyWindowExecuteAppCommand(kBrowserBackward);
  1571. else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON)
  1572. NotifyWindowExecuteAppCommand(kBrowserForward);
  1573. #endif
  1574. }
  1575. ui::mojom::WindowShowState NativeWindowViews::GetRestoredState() {
  1576. if (IsMaximized()) {
  1577. #if BUILDFLAG(IS_WIN)
  1578. // Restore maximized state for windows that are not translucent.
  1579. if (!IsTranslucent()) {
  1580. return ui::mojom::WindowShowState::kMaximized;
  1581. }
  1582. #else
  1583. return ui::mojom::WindowShowState::kMinimized;
  1584. #endif
  1585. }
  1586. if (IsFullscreen())
  1587. return ui::mojom::WindowShowState::kFullscreen;
  1588. return ui::mojom::WindowShowState::kNormal;
  1589. }
  1590. void NativeWindowViews::MoveBehindTaskBarIfNeeded() {
  1591. #if BUILDFLAG(IS_WIN)
  1592. if (behind_task_bar_) {
  1593. const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr);
  1594. ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0,
  1595. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
  1596. }
  1597. #endif
  1598. // TODO(julien.isorce): Implement X11 case.
  1599. }
  1600. // static
  1601. std::unique_ptr<NativeWindow> NativeWindow::Create(
  1602. const gin_helper::Dictionary& options,
  1603. NativeWindow* parent) {
  1604. return std::make_unique<NativeWindowViews>(options, parent);
  1605. }
  1606. } // namespace electron