native_window_mac.mm 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819
  1. // Copyright (c) 2013 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/browser/native_window_mac.h"
  5. #include <AvailabilityMacros.h>
  6. #include <objc/objc-runtime.h>
  7. #include <algorithm>
  8. #include <memory>
  9. #include <string>
  10. #include <utility>
  11. #include <vector>
  12. #include "base/apple/scoped_cftyperef.h"
  13. #include "base/mac/mac_util.h"
  14. #include "base/strings/sys_string_conversions.h"
  15. #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
  16. #include "components/remote_cocoa/browser/scoped_cg_window_id.h"
  17. #include "content/public/browser/browser_accessibility_state.h"
  18. #include "content/public/browser/browser_task_traits.h"
  19. #include "content/public/browser/browser_thread.h"
  20. #include "content/public/browser/desktop_media_id.h"
  21. #include "shell/browser/browser.h"
  22. #include "shell/browser/javascript_environment.h"
  23. #include "shell/browser/ui/cocoa/electron_native_widget_mac.h"
  24. #include "shell/browser/ui/cocoa/electron_ns_panel.h"
  25. #include "shell/browser/ui/cocoa/electron_ns_window.h"
  26. #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h"
  27. #include "shell/browser/ui/cocoa/electron_preview_item.h"
  28. #include "shell/browser/ui/cocoa/electron_touch_bar.h"
  29. #include "shell/browser/ui/cocoa/root_view_mac.h"
  30. #include "shell/browser/ui/cocoa/window_buttons_proxy.h"
  31. #include "shell/browser/ui/drag_util.h"
  32. #include "shell/browser/window_list.h"
  33. #include "shell/common/gin_converters/gfx_converter.h"
  34. #include "shell/common/gin_helper/dictionary.h"
  35. #include "shell/common/node_includes.h"
  36. #include "shell/common/options_switches.h"
  37. #include "skia/ext/skia_utils_mac.h"
  38. #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h"
  39. #include "ui/base/hit_test.h"
  40. #include "ui/display/screen.h"
  41. #include "ui/gl/gpu_switching_manager.h"
  42. #include "ui/views/background.h"
  43. #include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
  44. #include "ui/views/widget/widget.h"
  45. #include "ui/views/window/native_frame_view_mac.h"
  46. @interface ElectronProgressBar : NSProgressIndicator
  47. @end
  48. @implementation ElectronProgressBar
  49. - (void)drawRect:(NSRect)dirtyRect {
  50. if (self.style != NSProgressIndicatorStyleBar)
  51. return;
  52. // Draw edges of rounded rect.
  53. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0);
  54. CGFloat radius = rect.size.height / 2;
  55. NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
  56. xRadius:radius
  57. yRadius:radius];
  58. [bezier_path setLineWidth:2.0];
  59. [[NSColor grayColor] set];
  60. [bezier_path stroke];
  61. // Fill the rounded rect.
  62. rect = NSInsetRect(rect, 2.0, 2.0);
  63. radius = rect.size.height / 2;
  64. bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
  65. xRadius:radius
  66. yRadius:radius];
  67. [bezier_path setLineWidth:1.0];
  68. [bezier_path addClip];
  69. // Calculate the progress width.
  70. rect.size.width =
  71. floor(rect.size.width * ([self doubleValue] / [self maxValue]));
  72. // Fill the progress bar with color blue.
  73. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set];
  74. NSRectFill(rect);
  75. }
  76. @end
  77. namespace gin {
  78. template <>
  79. struct Converter<electron::NativeWindowMac::VisualEffectState> {
  80. static bool FromV8(v8::Isolate* isolate,
  81. v8::Local<v8::Value> val,
  82. electron::NativeWindowMac::VisualEffectState* out) {
  83. using VisualEffectState = electron::NativeWindowMac::VisualEffectState;
  84. std::string visual_effect_state;
  85. if (!ConvertFromV8(isolate, val, &visual_effect_state))
  86. return false;
  87. if (visual_effect_state == "followWindow") {
  88. *out = VisualEffectState::kFollowWindow;
  89. } else if (visual_effect_state == "active") {
  90. *out = VisualEffectState::kActive;
  91. } else if (visual_effect_state == "inactive") {
  92. *out = VisualEffectState::kInactive;
  93. } else {
  94. return false;
  95. }
  96. return true;
  97. }
  98. };
  99. } // namespace gin
  100. namespace electron {
  101. NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options,
  102. NativeWindow* parent)
  103. : NativeWindow(options, parent), root_view_(new RootViewMac(this)) {
  104. ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this);
  105. display::Screen::GetScreen()->AddObserver(this);
  106. int width = 800, height = 600;
  107. options.Get(options::kWidth, &width);
  108. options.Get(options::kHeight, &height);
  109. NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame];
  110. gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2),
  111. round((NSHeight(main_screen_rect) - height) / 2), width,
  112. height);
  113. bool resizable = true;
  114. options.Get(options::kResizable, &resizable);
  115. options.Get(options::kZoomToPageWidth, &zoom_to_page_width_);
  116. options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_);
  117. options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_);
  118. options.Get(options::kVisualEffectState, &visual_effect_state_);
  119. bool minimizable = true;
  120. options.Get(options::kMinimizable, &minimizable);
  121. bool maximizable = true;
  122. options.Get(options::kMaximizable, &maximizable);
  123. bool closable = true;
  124. options.Get(options::kClosable, &closable);
  125. std::string tabbingIdentifier;
  126. options.Get(options::kTabbingIdentifier, &tabbingIdentifier);
  127. std::string windowType;
  128. options.Get(options::kType, &windowType);
  129. bool hiddenInMissionControl = false;
  130. options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl);
  131. bool useStandardWindow = true;
  132. // eventually deprecate separate "standardWindow" option in favor of
  133. // standard / textured window types
  134. options.Get(options::kStandardWindow, &useStandardWindow);
  135. if (windowType == "textured") {
  136. useStandardWindow = false;
  137. }
  138. // The window without titlebar is treated the same with frameless window.
  139. if (title_bar_style_ != TitleBarStyle::kNormal)
  140. set_has_frame(false);
  141. NSUInteger styleMask = NSWindowStyleMaskTitled;
  142. // The NSWindowStyleMaskFullSizeContentView style removes rounded corners
  143. // for frameless window.
  144. bool rounded_corner = true;
  145. options.Get(options::kRoundedCorners, &rounded_corner);
  146. if (!rounded_corner && !has_frame())
  147. styleMask = NSWindowStyleMaskBorderless;
  148. // TODO: remove NSWindowStyleMaskTexturedBackground.
  149. // https://github.com/electron/electron/issues/43125
  150. #pragma clang diagnostic push
  151. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  152. if (minimizable)
  153. styleMask |= NSWindowStyleMaskMiniaturizable;
  154. if (closable)
  155. styleMask |= NSWindowStyleMaskClosable;
  156. if (resizable)
  157. styleMask |= NSWindowStyleMaskResizable;
  158. if (!useStandardWindow || transparent() || !has_frame())
  159. styleMask |= NSWindowStyleMaskTexturedBackground;
  160. // -Wdeprecated-declarations
  161. #pragma clang diagnostic pop
  162. // Create views::Widget and assign window_ with it.
  163. // TODO(zcbenz): Get rid of the window_ in future.
  164. views::Widget::InitParams params(
  165. views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET,
  166. views::Widget::InitParams::TYPE_WINDOW);
  167. params.bounds = bounds;
  168. params.delegate = this;
  169. params.type = views::Widget::InitParams::TYPE_WINDOW;
  170. params.native_widget =
  171. new ElectronNativeWidgetMac(this, windowType, styleMask, widget());
  172. widget()->Init(std::move(params));
  173. widget()->SetNativeWindowProperty(kElectronNativeWindowKey, this);
  174. SetCanResize(resizable);
  175. window_ = static_cast<ElectronNSWindow*>(
  176. widget()->GetNativeWindow().GetNativeNSWindow());
  177. RegisterDeleteDelegateCallback(base::BindOnce(
  178. [](NativeWindowMac* window) {
  179. if (window->window_)
  180. window->window_ = nil;
  181. if (window->buttons_proxy_)
  182. window->buttons_proxy_ = nil;
  183. },
  184. this));
  185. [window_ setEnableLargerThanScreen:enable_larger_than_screen()];
  186. window_delegate_ = [[ElectronNSWindowDelegate alloc] initWithShell:this];
  187. [window_ setDelegate:window_delegate_];
  188. // Only use native parent window for non-modal windows.
  189. if (parent && !is_modal()) {
  190. SetParentWindow(parent);
  191. }
  192. if (transparent()) {
  193. // Setting the background color to clear will also hide the shadow.
  194. [window_ setBackgroundColor:[NSColor clearColor]];
  195. }
  196. if (windowType == "desktop") {
  197. [window_ setLevel:kCGDesktopWindowLevel - 1];
  198. [window_ setDisableKeyOrMainWindow:YES];
  199. [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces |
  200. NSWindowCollectionBehaviorStationary |
  201. NSWindowCollectionBehaviorIgnoresCycle)];
  202. }
  203. if (windowType == "panel") {
  204. [window_ setLevel:NSFloatingWindowLevel];
  205. }
  206. bool focusable;
  207. if (options.Get(options::kFocusable, &focusable) && !focusable)
  208. [window_ setDisableKeyOrMainWindow:YES];
  209. if (transparent() || !has_frame()) {
  210. // Don't show title bar.
  211. [window_ setTitlebarAppearsTransparent:YES];
  212. [window_ setTitleVisibility:NSWindowTitleHidden];
  213. // Remove non-transparent corners, see
  214. // https://github.com/electron/electron/issues/517.
  215. [window_ setOpaque:NO];
  216. // Show window buttons if titleBarStyle is not "normal".
  217. if (title_bar_style_ == TitleBarStyle::kNormal) {
  218. InternalSetWindowButtonVisibility(false);
  219. } else {
  220. buttons_proxy_ = [[WindowButtonsProxy alloc] initWithWindow:window_];
  221. [buttons_proxy_ setHeight:titlebar_overlay_height()];
  222. if (traffic_light_position_) {
  223. [buttons_proxy_ setMargin:*traffic_light_position_];
  224. } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) {
  225. // For macOS >= 11, while this value does not match official macOS apps
  226. // like Safari or Notes, it matches titleBarStyle's old implementation
  227. // before Electron <= 12.
  228. [buttons_proxy_ setMargin:gfx::Point(12, 11)];
  229. }
  230. if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) {
  231. [buttons_proxy_ setShowOnHover:YES];
  232. } else {
  233. // customButtonsOnHover does not show buttons initially.
  234. InternalSetWindowButtonVisibility(true);
  235. }
  236. }
  237. }
  238. // Create a tab only if tabbing identifier is specified and window has
  239. // a native title bar.
  240. if (tabbingIdentifier.empty() || transparent() || !has_frame()) {
  241. [window_ setTabbingMode:NSWindowTabbingModeDisallowed];
  242. } else {
  243. [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)];
  244. }
  245. // Resize to content bounds.
  246. bool use_content_size = false;
  247. options.Get(options::kUseContentSize, &use_content_size);
  248. if (!has_frame() || use_content_size)
  249. SetContentSize(gfx::Size(width, height));
  250. // Enable the NSView to accept first mouse event.
  251. bool acceptsFirstMouse = false;
  252. options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse);
  253. [window_ setAcceptsFirstMouse:acceptsFirstMouse];
  254. // Disable auto-hiding cursor.
  255. bool disableAutoHideCursor = false;
  256. options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor);
  257. [window_ setDisableAutoHideCursor:disableAutoHideCursor];
  258. SetHiddenInMissionControl(hiddenInMissionControl);
  259. // Set maximizable state last to ensure zoom button does not get reset
  260. // by calls to other APIs.
  261. SetMaximizable(maximizable);
  262. // Default content view.
  263. SetContentView(new views::View());
  264. AddContentViewLayers();
  265. UpdateWindowOriginalFrame();
  266. original_level_ = [window_ level];
  267. }
  268. NativeWindowMac::~NativeWindowMac() = default;
  269. void NativeWindowMac::SetContentView(views::View* view) {
  270. views::View* root_view = GetContentsView();
  271. if (content_view())
  272. root_view->RemoveChildView(content_view());
  273. set_content_view(view);
  274. root_view->AddChildView(content_view());
  275. root_view->DeprecatedLayoutImmediately();
  276. }
  277. void NativeWindowMac::Close() {
  278. if (!IsClosable()) {
  279. WindowList::WindowCloseCancelled(this);
  280. return;
  281. }
  282. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) {
  283. SetHasDeferredWindowClose(true);
  284. return;
  285. }
  286. // Ensure we're detached from the parent window before closing.
  287. RemoveChildFromParentWindow();
  288. while (!child_windows_.empty()) {
  289. auto* child = child_windows_.back();
  290. child->RemoveChildFromParentWindow();
  291. }
  292. // If a sheet is attached to the window when we call
  293. // [window_ performClose:nil], the window won't close properly
  294. // even after the user has ended the sheet.
  295. // Ensure it's closed before calling [window_ performClose:nil].
  296. if ([window_ attachedSheet])
  297. [window_ endSheet:[window_ attachedSheet]];
  298. // window_ could be nil after performClose.
  299. bool should_notify = is_modal() && parent() && IsVisible();
  300. [window_ performClose:nil];
  301. // Closing a sheet doesn't trigger windowShouldClose,
  302. // so we need to manually call it ourselves here.
  303. if (should_notify) {
  304. NotifyWindowCloseButtonClicked();
  305. }
  306. }
  307. void NativeWindowMac::CloseImmediately() {
  308. // Ensure we're detached from the parent window before closing.
  309. RemoveChildFromParentWindow();
  310. while (!child_windows_.empty()) {
  311. auto* child = child_windows_.back();
  312. child->RemoveChildFromParentWindow();
  313. }
  314. [window_ close];
  315. }
  316. void NativeWindowMac::Focus(bool focus) {
  317. if (!IsVisible())
  318. return;
  319. if (focus) {
  320. // If we're a panel window, we do not want to activate the app,
  321. // which enables Electron-apps to build Spotlight-like experiences.
  322. if (!IsPanel()) {
  323. [[NSApplication sharedApplication] activateIgnoringOtherApps:NO];
  324. }
  325. [window_ makeKeyAndOrderFront:nil];
  326. } else {
  327. [window_ orderOut:nil];
  328. [window_ orderBack:nil];
  329. }
  330. }
  331. bool NativeWindowMac::IsFocused() const {
  332. return [window_ isKeyWindow];
  333. }
  334. void NativeWindowMac::Show() {
  335. if (is_modal() && parent()) {
  336. NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow();
  337. if ([window_ sheetParent] == nil)
  338. [window beginSheet:window_
  339. completionHandler:^(NSModalResponse){
  340. }];
  341. return;
  342. }
  343. set_wants_to_be_visible(true);
  344. // Reattach the window to the parent to actually show it.
  345. if (parent())
  346. InternalSetParentWindow(parent(), true);
  347. // Panels receive key focus when shown but should not activate the app.
  348. if (!IsPanel()) {
  349. [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
  350. }
  351. [window_ makeKeyAndOrderFront:nil];
  352. }
  353. void NativeWindowMac::ShowInactive() {
  354. set_wants_to_be_visible(true);
  355. // Reattach the window to the parent to actually show it.
  356. if (parent())
  357. InternalSetParentWindow(parent(), true);
  358. [window_ orderFrontRegardless];
  359. }
  360. void NativeWindowMac::Hide() {
  361. // If a sheet is attached to the window when we call [window_ orderOut:nil],
  362. // the sheet won't be able to show again on the same window.
  363. // Ensure it's closed before calling [window_ orderOut:nil].
  364. if ([window_ attachedSheet])
  365. [window_ endSheet:[window_ attachedSheet]];
  366. if (is_modal() && parent()) {
  367. [window_ orderOut:nil];
  368. [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_];
  369. return;
  370. }
  371. // If the window wants to be visible and has a parent, then the parent may
  372. // order it back in (in the period between orderOut: and close).
  373. set_wants_to_be_visible(false);
  374. DetachChildren();
  375. // Detach the window from the parent before.
  376. if (parent())
  377. InternalSetParentWindow(parent(), false);
  378. [window_ orderOut:nil];
  379. }
  380. bool NativeWindowMac::IsVisible() const {
  381. bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible;
  382. return [window_ isVisible] && !occluded && !IsMinimized();
  383. }
  384. bool NativeWindowMac::IsEnabled() const {
  385. return [window_ attachedSheet] == nil;
  386. }
  387. void NativeWindowMac::SetEnabled(bool enable) {
  388. if (!enable) {
  389. NSRect frame = [window_ frame];
  390. NSWindow* window =
  391. [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width,
  392. frame.size.height)
  393. styleMask:NSWindowStyleMaskTitled
  394. backing:NSBackingStoreBuffered
  395. defer:NO];
  396. [window setAlphaValue:0.5];
  397. [window_ beginSheet:window
  398. completionHandler:^(NSModalResponse returnCode) {
  399. NSLog(@"main window disabled");
  400. return;
  401. }];
  402. } else if ([window_ attachedSheet]) {
  403. [window_ endSheet:[window_ attachedSheet]];
  404. }
  405. }
  406. void NativeWindowMac::Maximize() {
  407. const bool is_visible = [window_ isVisible];
  408. if (IsMaximized()) {
  409. if (!is_visible)
  410. ShowInactive();
  411. return;
  412. }
  413. // Take note of the current window size
  414. if (IsNormal())
  415. UpdateWindowOriginalFrame();
  416. [window_ zoom:nil];
  417. if (!is_visible) {
  418. ShowInactive();
  419. NotifyWindowMaximize();
  420. }
  421. }
  422. void NativeWindowMac::Unmaximize() {
  423. // Bail if the last user set bounds were the same size as the window
  424. // screen (e.g. the user set the window to maximized via setBounds)
  425. //
  426. // Per docs during zoom:
  427. // > If there’s no saved user state because there has been no previous
  428. // > zoom,the size and location of the window don’t change.
  429. //
  430. // However, in classic Apple fashion, this is not the case in practice,
  431. // and the frame inexplicably becomes very tiny. We should prevent
  432. // zoom from being called if the window is being unmaximized and its
  433. // unmaximized window bounds are themselves functionally maximized.
  434. if (!IsMaximized() || user_set_bounds_maximized_)
  435. return;
  436. [window_ zoom:nil];
  437. }
  438. bool NativeWindowMac::IsMaximized() const {
  439. // It's possible for [window_ isZoomed] to be true
  440. // when the window is minimized or fullscreened.
  441. if (IsMinimized() || IsFullscreen())
  442. return false;
  443. if (HasStyleMask(NSWindowStyleMaskResizable) != 0)
  444. return [window_ isZoomed];
  445. NSRect rectScreen = aspect_ratio() > 0.0
  446. ? default_frame_for_zoom()
  447. : [[NSScreen mainScreen] visibleFrame];
  448. return NSEqualRects([window_ frame], rectScreen);
  449. }
  450. void NativeWindowMac::Minimize() {
  451. if (IsMinimized())
  452. return;
  453. // Take note of the current window size
  454. if (IsNormal())
  455. UpdateWindowOriginalFrame();
  456. [window_ miniaturize:nil];
  457. }
  458. void NativeWindowMac::Restore() {
  459. [window_ deminiaturize:nil];
  460. }
  461. bool NativeWindowMac::IsMinimized() const {
  462. return [window_ isMiniaturized];
  463. }
  464. bool NativeWindowMac::IsPanel() {
  465. return [window_ isKindOfClass:[ElectronNSPanel class]];
  466. }
  467. bool NativeWindowMac::HandleDeferredClose() {
  468. if (has_deferred_window_close_) {
  469. SetHasDeferredWindowClose(false);
  470. Close();
  471. return true;
  472. }
  473. return false;
  474. }
  475. void NativeWindowMac::RemoveChildWindow(NativeWindow* child) {
  476. child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); });
  477. [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()];
  478. }
  479. void NativeWindowMac::RemoveChildFromParentWindow() {
  480. if (parent() && !is_modal()) {
  481. parent()->RemoveChildWindow(this);
  482. NativeWindow::SetParentWindow(nullptr);
  483. }
  484. }
  485. void NativeWindowMac::AttachChildren() {
  486. for (auto* child : child_windows_) {
  487. if (!static_cast<NativeWindowMac*>(child)->wants_to_be_visible())
  488. continue;
  489. auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow();
  490. if ([child_nswindow parentWindow] == window_)
  491. continue;
  492. // Attaching a window as a child window resets its window level, so
  493. // save and restore it afterwards.
  494. NSInteger level = window_.level;
  495. [window_ addChildWindow:child_nswindow ordered:NSWindowAbove];
  496. [window_ setLevel:level];
  497. }
  498. }
  499. void NativeWindowMac::DetachChildren() {
  500. // Hide all children before hiding/minimizing the window.
  501. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown()
  502. // will DCHECK otherwise.
  503. for (auto* child : child_windows_) {
  504. [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil];
  505. }
  506. }
  507. void NativeWindowMac::SetFullScreen(bool fullscreen) {
  508. // [NSWindow -toggleFullScreen] is an asynchronous operation, which means
  509. // that it's possible to call it while a fullscreen transition is currently
  510. // in process. This can create weird behavior (incl. phantom windows),
  511. // so we want to schedule a transition for when the current one has completed.
  512. if (fullscreen_transition_state() != FullScreenTransitionState::kNone) {
  513. if (!pending_transitions_.empty()) {
  514. bool last_pending = pending_transitions_.back();
  515. // Only push new transitions if they're different than the last transition
  516. // in the queue.
  517. if (last_pending != fullscreen)
  518. pending_transitions_.push(fullscreen);
  519. } else {
  520. pending_transitions_.push(fullscreen);
  521. }
  522. return;
  523. }
  524. if (fullscreen == IsFullscreen() || !IsFullScreenable())
  525. return;
  526. // Take note of the current window size
  527. if (IsNormal())
  528. UpdateWindowOriginalFrame();
  529. // This needs to be set here because it can be the case that
  530. // SetFullScreen is called by a user before windowWillEnterFullScreen
  531. // or windowWillExitFullScreen are invoked, and so a potential transition
  532. // could be dropped.
  533. fullscreen_transition_state_ = fullscreen
  534. ? FullScreenTransitionState::kEntering
  535. : FullScreenTransitionState::kExiting;
  536. if (![window_ toggleFullScreenMode:nil])
  537. fullscreen_transition_state_ = FullScreenTransitionState::kNone;
  538. }
  539. bool NativeWindowMac::IsFullscreen() const {
  540. return HasStyleMask(NSWindowStyleMaskFullScreen);
  541. }
  542. void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) {
  543. // Do nothing if in fullscreen mode.
  544. if (IsFullscreen())
  545. return;
  546. // Check size constraints since setFrame does not check it.
  547. gfx::Size size = bounds.size();
  548. size.SetToMax(GetMinimumSize());
  549. gfx::Size max_size = GetMaximumSize();
  550. if (!max_size.IsEmpty())
  551. size.SetToMin(max_size);
  552. NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height());
  553. // Flip coordinates based on the primary screen.
  554. NSScreen* screen = [[NSScreen screens] firstObject];
  555. cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y();
  556. [window_ setFrame:cocoa_bounds display:YES animate:animate];
  557. user_set_bounds_maximized_ = IsMaximized() ? true : false;
  558. UpdateWindowOriginalFrame();
  559. }
  560. gfx::Rect NativeWindowMac::GetBounds() const {
  561. NSRect frame = [window_ frame];
  562. gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
  563. NSScreen* screen = [[NSScreen screens] firstObject];
  564. bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
  565. return bounds;
  566. }
  567. bool NativeWindowMac::IsNormal() const {
  568. return NativeWindow::IsNormal() && !IsSimpleFullScreen();
  569. }
  570. gfx::Rect NativeWindowMac::GetNormalBounds() const {
  571. if (IsNormal()) {
  572. return GetBounds();
  573. }
  574. NSRect frame = original_frame_;
  575. gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
  576. NSScreen* screen = [[NSScreen screens] firstObject];
  577. bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
  578. return bounds;
  579. // Works on OS_WIN !
  580. // return widget()->GetRestoredBounds();
  581. }
  582. void NativeWindowMac::SetSizeConstraints(
  583. const extensions::SizeConstraints& window_constraints) {
  584. // Apply the size constraints to NSWindow.
  585. if (window_constraints.HasMinimumSize())
  586. [window_ setMinSize:window_constraints.GetMinimumSize().ToCGSize()];
  587. if (window_constraints.HasMaximumSize())
  588. [window_ setMaxSize:window_constraints.GetMaximumSize().ToCGSize()];
  589. NativeWindow::SetSizeConstraints(window_constraints);
  590. }
  591. void NativeWindowMac::SetContentSizeConstraints(
  592. const extensions::SizeConstraints& size_constraints) {
  593. auto convertSize = [this](const gfx::Size& size) {
  594. // Our frameless window still has titlebar attached, so setting contentSize
  595. // will result in actual content size being larger.
  596. if (!has_frame()) {
  597. NSRect frame = NSMakeRect(0, 0, size.width(), size.height());
  598. NSRect content = [window_ originalContentRectForFrameRect:frame];
  599. return content.size;
  600. } else {
  601. return NSMakeSize(size.width(), size.height());
  602. }
  603. };
  604. // Apply the size constraints to NSWindow.
  605. NSView* content = [window_ contentView];
  606. if (size_constraints.HasMinimumSize()) {
  607. NSSize min_size = convertSize(size_constraints.GetMinimumSize());
  608. [window_ setContentMinSize:[content convertSize:min_size toView:nil]];
  609. }
  610. if (size_constraints.HasMaximumSize()) {
  611. NSSize max_size = convertSize(size_constraints.GetMaximumSize());
  612. [window_ setContentMaxSize:[content convertSize:max_size toView:nil]];
  613. }
  614. NativeWindow::SetContentSizeConstraints(size_constraints);
  615. }
  616. bool NativeWindowMac::MoveAbove(const std::string& sourceId) {
  617. const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId);
  618. if (id.type != content::DesktopMediaID::TYPE_WINDOW)
  619. return false;
  620. // Check if the window source is valid.
  621. const CGWindowID window_id = id.id;
  622. if (!webrtc::GetWindowOwnerPid(window_id))
  623. return false;
  624. [window_ orderWindowByShuffling:NSWindowAbove relativeTo:window_id];
  625. return true;
  626. }
  627. void NativeWindowMac::MoveTop() {
  628. [window_ orderWindowByShuffling:NSWindowAbove relativeTo:0];
  629. }
  630. void NativeWindowMac::SetResizable(bool resizable) {
  631. ScopedDisableResize disable_resize;
  632. SetStyleMask(resizable, NSWindowStyleMaskResizable);
  633. bool was_fullscreenable = IsFullScreenable();
  634. // Right now, resizable and fullscreenable are decoupled in
  635. // documentation and on Windows/Linux. Chromium disables
  636. // fullscreen collection behavior as well as the maximize traffic
  637. // light in SetCanResize if resizability is false on macOS unless
  638. // the window is both resizable and maximizable. We want consistent
  639. // cross-platform behavior, so if resizability is disabled we disable
  640. // the maximize button and ensure fullscreenability matches user setting.
  641. SetCanResize(resizable);
  642. SetFullScreenable(was_fullscreenable);
  643. UpdateZoomButton();
  644. }
  645. bool NativeWindowMac::IsResizable() const {
  646. bool in_fs_transition =
  647. fullscreen_transition_state() != FullScreenTransitionState::kNone;
  648. bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable);
  649. return has_rs_mask && !IsFullscreen() && !in_fs_transition;
  650. }
  651. void NativeWindowMac::SetMovable(bool movable) {
  652. [window_ setMovable:movable];
  653. }
  654. bool NativeWindowMac::IsMovable() const {
  655. return [window_ isMovable];
  656. }
  657. void NativeWindowMac::SetMinimizable(bool minimizable) {
  658. SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable);
  659. }
  660. bool NativeWindowMac::IsMinimizable() const {
  661. return HasStyleMask(NSWindowStyleMaskMiniaturizable);
  662. }
  663. void NativeWindowMac::SetMaximizable(bool maximizable) {
  664. maximizable_ = maximizable;
  665. UpdateZoomButton();
  666. }
  667. bool NativeWindowMac::IsMaximizable() const {
  668. return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled];
  669. }
  670. void NativeWindowMac::UpdateZoomButton() {
  671. [[window_ standardWindowButton:NSWindowZoomButton]
  672. setEnabled:HasStyleMask(NSWindowStyleMaskResizable) &&
  673. (CanMaximize() || IsFullScreenable())];
  674. }
  675. void NativeWindowMac::SetFullScreenable(bool fullscreenable) {
  676. SetCollectionBehavior(fullscreenable,
  677. NSWindowCollectionBehaviorFullScreenPrimary);
  678. // On EL Capitan this flag is required to hide fullscreen button.
  679. SetCollectionBehavior(!fullscreenable,
  680. NSWindowCollectionBehaviorFullScreenAuxiliary);
  681. UpdateZoomButton();
  682. }
  683. bool NativeWindowMac::IsFullScreenable() const {
  684. NSUInteger collectionBehavior = [window_ collectionBehavior];
  685. return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary;
  686. }
  687. void NativeWindowMac::SetClosable(bool closable) {
  688. SetStyleMask(closable, NSWindowStyleMaskClosable);
  689. }
  690. bool NativeWindowMac::IsClosable() const {
  691. return HasStyleMask(NSWindowStyleMaskClosable);
  692. }
  693. void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order,
  694. const std::string& level_name,
  695. int relative_level) {
  696. if (z_order == ui::ZOrderLevel::kNormal) {
  697. SetWindowLevel(NSNormalWindowLevel);
  698. return;
  699. }
  700. int level = NSNormalWindowLevel;
  701. if (level_name == "floating") {
  702. level = NSFloatingWindowLevel;
  703. } else if (level_name == "torn-off-menu") {
  704. level = NSTornOffMenuWindowLevel;
  705. } else if (level_name == "modal-panel") {
  706. level = NSModalPanelWindowLevel;
  707. } else if (level_name == "main-menu") {
  708. level = NSMainMenuWindowLevel;
  709. } else if (level_name == "status") {
  710. level = NSStatusWindowLevel;
  711. } else if (level_name == "pop-up-menu") {
  712. level = NSPopUpMenuWindowLevel;
  713. } else if (level_name == "screen-saver") {
  714. level = NSScreenSaverWindowLevel;
  715. }
  716. SetWindowLevel(level + relative_level);
  717. }
  718. std::string NativeWindowMac::GetAlwaysOnTopLevel() const {
  719. std::string level_name = "normal";
  720. int level = [window_ level];
  721. if (level == NSFloatingWindowLevel) {
  722. level_name = "floating";
  723. } else if (level == NSTornOffMenuWindowLevel) {
  724. level_name = "torn-off-menu";
  725. } else if (level == NSModalPanelWindowLevel) {
  726. level_name = "modal-panel";
  727. } else if (level == NSMainMenuWindowLevel) {
  728. level_name = "main-menu";
  729. } else if (level == NSStatusWindowLevel) {
  730. level_name = "status";
  731. } else if (level == NSPopUpMenuWindowLevel) {
  732. level_name = "pop-up-menu";
  733. } else if (level == NSScreenSaverWindowLevel) {
  734. level_name = "screen-saver";
  735. }
  736. return level_name;
  737. }
  738. void NativeWindowMac::SetWindowLevel(int unbounded_level) {
  739. int level = std::min(
  740. std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)),
  741. CGWindowLevelForKey(kCGMaximumWindowLevelKey));
  742. ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel
  743. ? ui::ZOrderLevel::kNormal
  744. : ui::ZOrderLevel::kFloatingWindow;
  745. bool did_z_order_level_change = z_order_level != GetZOrderLevel();
  746. was_maximizable_ = IsMaximizable();
  747. // We need to explicitly keep the NativeWidget up to date, since it stores the
  748. // window level in a local variable, rather than reading it from the NSWindow.
  749. // Unfortunately, it results in a second setLevel call. It's not ideal, but we
  750. // don't expect this to cause any user-visible jank.
  751. widget()->SetZOrderLevel(z_order_level);
  752. [window_ setLevel:level];
  753. // Set level will make the zoom button revert to default, probably
  754. // a bug of Cocoa or macOS.
  755. SetMaximizable(was_maximizable_);
  756. // This must be notified at the very end or IsAlwaysOnTop
  757. // will not yet have been updated to reflect the new status
  758. if (did_z_order_level_change)
  759. NativeWindow::NotifyWindowAlwaysOnTopChanged();
  760. }
  761. ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() const {
  762. return widget()->GetZOrderLevel();
  763. }
  764. void NativeWindowMac::Center() {
  765. [window_ center];
  766. }
  767. void NativeWindowMac::Invalidate() {
  768. [[window_ contentView] setNeedsDisplay:YES];
  769. }
  770. void NativeWindowMac::SetTitle(const std::string& title) {
  771. [window_ setTitle:base::SysUTF8ToNSString(title)];
  772. if (buttons_proxy_)
  773. [buttons_proxy_ redraw];
  774. }
  775. std::string NativeWindowMac::GetTitle() const {
  776. return base::SysNSStringToUTF8([window_ title]);
  777. }
  778. void NativeWindowMac::FlashFrame(bool flash) {
  779. if (flash) {
  780. attention_request_id_ = [NSApp requestUserAttention:NSCriticalRequest];
  781. } else {
  782. [NSApp cancelUserAttentionRequest:attention_request_id_];
  783. attention_request_id_ = 0;
  784. }
  785. }
  786. void NativeWindowMac::SetSkipTaskbar(bool skip) {}
  787. bool NativeWindowMac::IsExcludedFromShownWindowsMenu() const {
  788. NSWindow* window = GetNativeWindow().GetNativeNSWindow();
  789. return [window isExcludedFromWindowsMenu];
  790. }
  791. void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) {
  792. NSWindow* window = GetNativeWindow().GetNativeNSWindow();
  793. [window setExcludedFromWindowsMenu:excluded];
  794. }
  795. void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display,
  796. uint32_t changed_metrics) {
  797. // We only want to force screen recalibration if we're in simpleFullscreen
  798. // mode.
  799. if (!is_simple_fullscreen_)
  800. return;
  801. content::GetUIThreadTaskRunner({})->PostTask(
  802. FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr()));
  803. }
  804. void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) {
  805. NSWindow* window = GetNativeWindow().GetNativeNSWindow();
  806. if (simple_fullscreen && !is_simple_fullscreen_) {
  807. is_simple_fullscreen_ = true;
  808. // Take note of the current window size and level
  809. if (IsNormal()) {
  810. UpdateWindowOriginalFrame();
  811. original_level_ = [window_ level];
  812. }
  813. simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions];
  814. simple_fullscreen_mask_ = [window styleMask];
  815. // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu
  816. // bar
  817. NSApplicationPresentationOptions options =
  818. NSApplicationPresentationAutoHideDock |
  819. NSApplicationPresentationAutoHideMenuBar;
  820. [NSApp setPresentationOptions:options];
  821. was_maximizable_ = IsMaximizable();
  822. was_movable_ = IsMovable();
  823. NSRect fullscreenFrame = [window.screen frame];
  824. // If our app has dock hidden, set the window level higher so another app's
  825. // menu bar doesn't appear on top of our fullscreen app.
  826. if ([[NSRunningApplication currentApplication] activationPolicy] !=
  827. NSApplicationActivationPolicyRegular) {
  828. window.level = NSPopUpMenuWindowLevel;
  829. }
  830. // Always hide the titlebar in simple fullscreen mode.
  831. //
  832. // Note that we must remove the NSWindowStyleMaskTitled style instead of
  833. // using the [window_ setTitleVisibility:], as the latter would leave the
  834. // window with rounded corners.
  835. SetStyleMask(false, NSWindowStyleMaskTitled);
  836. if (!window_button_visibility_.has_value()) {
  837. // Lets keep previous behaviour - hide window controls in titled
  838. // fullscreen mode when not specified otherwise.
  839. InternalSetWindowButtonVisibility(false);
  840. }
  841. [window setFrame:fullscreenFrame display:YES animate:YES];
  842. // Fullscreen windows can't be resized, minimized, maximized, or moved
  843. SetMinimizable(false);
  844. SetResizable(false);
  845. SetMaximizable(false);
  846. SetMovable(false);
  847. } else if (!simple_fullscreen && is_simple_fullscreen_) {
  848. is_simple_fullscreen_ = false;
  849. [window setFrame:original_frame_ display:YES animate:YES];
  850. window.level = original_level_;
  851. [NSApp setPresentationOptions:simple_fullscreen_options_];
  852. // Restore original style mask
  853. ScopedDisableResize disable_resize;
  854. [window_ setStyleMask:simple_fullscreen_mask_];
  855. // Restore window manipulation abilities
  856. SetMaximizable(was_maximizable_);
  857. SetMovable(was_movable_);
  858. // Restore default window controls visibility state.
  859. if (!window_button_visibility_.has_value()) {
  860. bool visibility;
  861. if (has_frame())
  862. visibility = true;
  863. else
  864. visibility = title_bar_style_ != TitleBarStyle::kNormal;
  865. InternalSetWindowButtonVisibility(visibility);
  866. }
  867. if (buttons_proxy_)
  868. [buttons_proxy_ redraw];
  869. }
  870. }
  871. bool NativeWindowMac::IsSimpleFullScreen() const {
  872. return is_simple_fullscreen_;
  873. }
  874. void NativeWindowMac::SetKiosk(bool kiosk) {
  875. if (kiosk && !is_kiosk_) {
  876. kiosk_options_ = [NSApp currentSystemPresentationOptions];
  877. NSApplicationPresentationOptions options =
  878. NSApplicationPresentationHideDock |
  879. NSApplicationPresentationHideMenuBar |
  880. NSApplicationPresentationDisableAppleMenu |
  881. NSApplicationPresentationDisableProcessSwitching |
  882. NSApplicationPresentationDisableForceQuit |
  883. NSApplicationPresentationDisableSessionTermination |
  884. NSApplicationPresentationDisableHideApplication;
  885. [NSApp setPresentationOptions:options];
  886. is_kiosk_ = true;
  887. fullscreen_before_kiosk_ = IsFullscreen();
  888. if (!fullscreen_before_kiosk_)
  889. SetFullScreen(true);
  890. } else if (!kiosk && is_kiosk_) {
  891. is_kiosk_ = false;
  892. if (!fullscreen_before_kiosk_)
  893. SetFullScreen(false);
  894. // Set presentation options *after* asynchronously exiting
  895. // fullscreen to ensure they take effect.
  896. [NSApp setPresentationOptions:kiosk_options_];
  897. }
  898. }
  899. bool NativeWindowMac::IsKiosk() const {
  900. return is_kiosk_;
  901. }
  902. void NativeWindowMac::SetBackgroundColor(SkColor color) {
  903. base::apple::ScopedCFTypeRef<CGColorRef> cgcolor(
  904. skia::CGColorCreateFromSkColor(color));
  905. [[[window_ contentView] layer] setBackgroundColor:cgcolor.get()];
  906. }
  907. SkColor NativeWindowMac::GetBackgroundColor() const {
  908. CGColorRef color = [[[window_ contentView] layer] backgroundColor];
  909. if (!color)
  910. return SK_ColorTRANSPARENT;
  911. return skia::CGColorRefToSkColor(color);
  912. }
  913. void NativeWindowMac::SetHasShadow(bool has_shadow) {
  914. [window_ setHasShadow:has_shadow];
  915. }
  916. bool NativeWindowMac::HasShadow() const {
  917. return [window_ hasShadow];
  918. }
  919. void NativeWindowMac::InvalidateShadow() {
  920. [window_ invalidateShadow];
  921. }
  922. void NativeWindowMac::SetOpacity(const double opacity) {
  923. const double boundedOpacity = std::clamp(opacity, 0.0, 1.0);
  924. [window_ setAlphaValue:boundedOpacity];
  925. }
  926. double NativeWindowMac::GetOpacity() const {
  927. return [window_ alphaValue];
  928. }
  929. void NativeWindowMac::SetRepresentedFilename(const std::string& filename) {
  930. [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)];
  931. if (buttons_proxy_)
  932. [buttons_proxy_ redraw];
  933. }
  934. std::string NativeWindowMac::GetRepresentedFilename() const {
  935. return base::SysNSStringToUTF8([window_ representedFilename]);
  936. }
  937. void NativeWindowMac::SetDocumentEdited(bool edited) {
  938. [window_ setDocumentEdited:edited];
  939. if (buttons_proxy_)
  940. [buttons_proxy_ redraw];
  941. }
  942. bool NativeWindowMac::IsDocumentEdited() const {
  943. return [window_ isDocumentEdited];
  944. }
  945. bool NativeWindowMac::IsHiddenInMissionControl() const {
  946. NSUInteger collectionBehavior = [window_ collectionBehavior];
  947. return collectionBehavior & NSWindowCollectionBehaviorTransient;
  948. }
  949. void NativeWindowMac::SetHiddenInMissionControl(bool hidden) {
  950. SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient);
  951. }
  952. void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) {
  953. [window_ setIgnoresMouseEvents:ignore];
  954. if (!ignore) {
  955. SetForwardMouseMessages(NO);
  956. } else {
  957. SetForwardMouseMessages(forward);
  958. }
  959. }
  960. void NativeWindowMac::SetContentProtection(bool enable) {
  961. [window_
  962. setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly];
  963. }
  964. void NativeWindowMac::SetFocusable(bool focusable) {
  965. // No known way to unfocus the window if it had the focus. Here we do not
  966. // want to call Focus(false) because it moves the window to the back, i.e.
  967. // at the bottom in term of z-order.
  968. [window_ setDisableKeyOrMainWindow:!focusable];
  969. }
  970. bool NativeWindowMac::IsFocusable() const {
  971. return ![window_ disableKeyOrMainWindow];
  972. }
  973. void NativeWindowMac::SetParentWindow(NativeWindow* parent) {
  974. InternalSetParentWindow(parent, IsVisible());
  975. }
  976. gfx::NativeView NativeWindowMac::GetNativeView() const {
  977. return [window_ contentView];
  978. }
  979. gfx::NativeWindow NativeWindowMac::GetNativeWindow() const {
  980. return window_;
  981. }
  982. gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const {
  983. return [window_ windowNumber];
  984. }
  985. content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const {
  986. auto desktop_media_id = content::DesktopMediaID(
  987. content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget());
  988. // c.f.
  989. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc
  990. // Refs https://github.com/electron/electron/pull/30507
  991. // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2`
  992. #if 0
  993. if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) {
  994. desktop_media_id.window_id = desktop_media_id.id;
  995. }
  996. #endif
  997. return desktop_media_id;
  998. }
  999. NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const {
  1000. return [window_ contentView];
  1001. }
  1002. void NativeWindowMac::SetProgressBar(double progress,
  1003. const NativeWindow::ProgressState state) {
  1004. NSDockTile* dock_tile = [NSApp dockTile];
  1005. // Sometimes macOS would install a default contentView for dock, we must
  1006. // verify whether NSProgressIndicator has been installed.
  1007. bool first_time = !dock_tile.contentView ||
  1008. [[dock_tile.contentView subviews] count] == 0 ||
  1009. ![[[dock_tile.contentView subviews] lastObject]
  1010. isKindOfClass:[NSProgressIndicator class]];
  1011. // For the first time API invoked, we need to create a ContentView in
  1012. // DockTile.
  1013. if (first_time) {
  1014. NSImageView* image_view = [[NSImageView alloc] init];
  1015. [image_view setImage:[NSApp applicationIconImage]];
  1016. [dock_tile setContentView:image_view];
  1017. NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0);
  1018. NSProgressIndicator* progress_indicator =
  1019. [[ElectronProgressBar alloc] initWithFrame:frame];
  1020. [progress_indicator setStyle:NSProgressIndicatorStyleBar];
  1021. [progress_indicator setIndeterminate:NO];
  1022. [progress_indicator setBezeled:YES];
  1023. [progress_indicator setMinValue:0];
  1024. [progress_indicator setMaxValue:1];
  1025. [progress_indicator setHidden:NO];
  1026. [dock_tile.contentView addSubview:progress_indicator];
  1027. }
  1028. NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>(
  1029. [[[dock_tile contentView] subviews] lastObject]);
  1030. if (progress < 0) {
  1031. [progress_indicator setHidden:YES];
  1032. } else if (progress > 1) {
  1033. [progress_indicator setHidden:NO];
  1034. [progress_indicator setIndeterminate:YES];
  1035. [progress_indicator setDoubleValue:1];
  1036. } else {
  1037. [progress_indicator setHidden:NO];
  1038. [progress_indicator setDoubleValue:progress];
  1039. }
  1040. [dock_tile display];
  1041. }
  1042. void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay,
  1043. const std::string& description) {}
  1044. void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible,
  1045. bool visibleOnFullScreen,
  1046. bool skipTransformProcessType) {
  1047. // In order for NSWindows to be visible on fullscreen we need to invoke
  1048. // app.dock.hide() since Apple changed the underlying functionality of
  1049. // NSWindows starting with 10.14 to disallow NSWindows from floating on top of
  1050. // fullscreen apps.
  1051. if (!skipTransformProcessType) {
  1052. if (visibleOnFullScreen) {
  1053. Browser::Get()->DockHide();
  1054. } else {
  1055. Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate());
  1056. }
  1057. }
  1058. SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces);
  1059. SetCollectionBehavior(visibleOnFullScreen,
  1060. NSWindowCollectionBehaviorFullScreenAuxiliary);
  1061. }
  1062. bool NativeWindowMac::IsVisibleOnAllWorkspaces() const {
  1063. NSUInteger collectionBehavior = [window_ collectionBehavior];
  1064. return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces;
  1065. }
  1066. void NativeWindowMac::SetAutoHideCursor(bool auto_hide) {
  1067. [window_ setDisableAutoHideCursor:!auto_hide];
  1068. }
  1069. void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) {
  1070. NSVisualEffectView* vibrantView = [window_ vibrantView];
  1071. if (vibrantView != nil && !vibrancy_type_.empty()) {
  1072. const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled);
  1073. const int macos_version = base::mac::MacOSMajorVersion();
  1074. const bool modal = is_modal();
  1075. // If the window is modal, its corners are rounded on macOS >= 11 or higher
  1076. // unless the user has explicitly passed noRoundedCorners.
  1077. bool should_round_modal =
  1078. !no_rounded_corner && macos_version >= 11 && modal;
  1079. // If the window is nonmodal, its corners are rounded if it is frameless and
  1080. // the user hasn't passed noRoundedCorners.
  1081. bool should_round_nonmodal = !no_rounded_corner && !modal && !has_frame();
  1082. if (should_round_nonmodal || should_round_modal) {
  1083. CGFloat radius;
  1084. if (fullscreen) {
  1085. radius = 0.0f;
  1086. } else if (macos_version >= 11) {
  1087. radius = 9.0f;
  1088. } else {
  1089. // Smaller corner radius on versions prior to Big Sur.
  1090. radius = 5.0f;
  1091. }
  1092. CGFloat dimension = 2 * radius + 1;
  1093. NSSize size = NSMakeSize(dimension, dimension);
  1094. NSImage* maskImage = [NSImage imageWithSize:size
  1095. flipped:NO
  1096. drawingHandler:^BOOL(NSRect rect) {
  1097. NSBezierPath* bezierPath = [NSBezierPath
  1098. bezierPathWithRoundedRect:rect
  1099. xRadius:radius
  1100. yRadius:radius];
  1101. [[NSColor blackColor] set];
  1102. [bezierPath fill];
  1103. return YES;
  1104. }];
  1105. [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)];
  1106. [maskImage setResizingMode:NSImageResizingModeStretch];
  1107. [vibrantView setMaskImage:maskImage];
  1108. [window_ setCornerMask:maskImage];
  1109. }
  1110. }
  1111. }
  1112. void NativeWindowMac::UpdateWindowOriginalFrame() {
  1113. original_frame_ = [window_ frame];
  1114. }
  1115. void NativeWindowMac::SetVibrancy(const std::string& type) {
  1116. NativeWindow::SetVibrancy(type);
  1117. NSVisualEffectView* vibrantView = [window_ vibrantView];
  1118. views::View* rootView = GetContentsView();
  1119. if (type.empty()) {
  1120. if (vibrant_native_view_host_ != nullptr) {
  1121. // Transfers ownership back to caller in the form of a unique_ptr which is
  1122. // subsequently deleted.
  1123. rootView->RemoveChildViewT(vibrant_native_view_host_);
  1124. vibrant_native_view_host_ = nullptr;
  1125. }
  1126. if (vibrantView != nil) {
  1127. [window_ setVibrantView:nil];
  1128. }
  1129. return;
  1130. }
  1131. NSVisualEffectMaterial vibrancyType{};
  1132. if (type == "titlebar") {
  1133. vibrancyType = NSVisualEffectMaterialTitlebar;
  1134. } else if (type == "selection") {
  1135. vibrancyType = NSVisualEffectMaterialSelection;
  1136. } else if (type == "menu") {
  1137. vibrancyType = NSVisualEffectMaterialMenu;
  1138. } else if (type == "popover") {
  1139. vibrancyType = NSVisualEffectMaterialPopover;
  1140. } else if (type == "sidebar") {
  1141. vibrancyType = NSVisualEffectMaterialSidebar;
  1142. } else if (type == "header") {
  1143. vibrancyType = NSVisualEffectMaterialHeaderView;
  1144. } else if (type == "sheet") {
  1145. vibrancyType = NSVisualEffectMaterialSheet;
  1146. } else if (type == "window") {
  1147. vibrancyType = NSVisualEffectMaterialWindowBackground;
  1148. } else if (type == "hud") {
  1149. vibrancyType = NSVisualEffectMaterialHUDWindow;
  1150. } else if (type == "fullscreen-ui") {
  1151. vibrancyType = NSVisualEffectMaterialFullScreenUI;
  1152. } else if (type == "tooltip") {
  1153. vibrancyType = NSVisualEffectMaterialToolTip;
  1154. } else if (type == "content") {
  1155. vibrancyType = NSVisualEffectMaterialContentBackground;
  1156. } else if (type == "under-window") {
  1157. vibrancyType = NSVisualEffectMaterialUnderWindowBackground;
  1158. } else if (type == "under-page") {
  1159. vibrancyType = NSVisualEffectMaterialUnderPageBackground;
  1160. }
  1161. if (vibrancyType) {
  1162. vibrancy_type_ = type;
  1163. if (vibrantView == nil) {
  1164. vibrantView = [[NSVisualEffectView alloc]
  1165. initWithFrame:[[window_ contentView] bounds]];
  1166. [window_ setVibrantView:vibrantView];
  1167. [vibrantView
  1168. setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
  1169. [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
  1170. if (visual_effect_state_ == VisualEffectState::kActive) {
  1171. [vibrantView setState:NSVisualEffectStateActive];
  1172. } else if (visual_effect_state_ == VisualEffectState::kInactive) {
  1173. [vibrantView setState:NSVisualEffectStateInactive];
  1174. } else {
  1175. [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState];
  1176. }
  1177. // Vibrant view is inserted into the root view hierarchy underneath all
  1178. // other views.
  1179. vibrant_native_view_host_ = rootView->AddChildViewAt(
  1180. std::make_unique<views::NativeViewHost>(), 0);
  1181. vibrant_native_view_host_->Attach(vibrantView);
  1182. rootView->DeprecatedLayoutImmediately();
  1183. UpdateVibrancyRadii(IsFullscreen());
  1184. }
  1185. [vibrantView setMaterial:vibrancyType];
  1186. }
  1187. }
  1188. void NativeWindowMac::SetWindowButtonVisibility(bool visible) {
  1189. window_button_visibility_ = visible;
  1190. if (buttons_proxy_) {
  1191. if (visible)
  1192. [buttons_proxy_ redraw];
  1193. [buttons_proxy_ setVisible:visible];
  1194. }
  1195. if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover)
  1196. InternalSetWindowButtonVisibility(visible);
  1197. NotifyLayoutWindowControlsOverlay();
  1198. }
  1199. bool NativeWindowMac::GetWindowButtonVisibility() const {
  1200. return ![window_ standardWindowButton:NSWindowZoomButton].hidden ||
  1201. ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden ||
  1202. ![window_ standardWindowButton:NSWindowCloseButton].hidden;
  1203. }
  1204. void NativeWindowMac::SetWindowButtonPosition(
  1205. std::optional<gfx::Point> position) {
  1206. traffic_light_position_ = std::move(position);
  1207. if (buttons_proxy_) {
  1208. [buttons_proxy_ setMargin:traffic_light_position_];
  1209. NotifyLayoutWindowControlsOverlay();
  1210. }
  1211. }
  1212. std::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const {
  1213. return traffic_light_position_;
  1214. }
  1215. void NativeWindowMac::RedrawTrafficLights() {
  1216. if (buttons_proxy_ && !IsFullscreen())
  1217. [buttons_proxy_ redraw];
  1218. }
  1219. // In simpleFullScreen mode, update the frame for new bounds.
  1220. void NativeWindowMac::UpdateFrame() {
  1221. NSWindow* window = GetNativeWindow().GetNativeNSWindow();
  1222. NSRect fullscreenFrame = [window.screen frame];
  1223. [window setFrame:fullscreenFrame display:YES animate:YES];
  1224. }
  1225. void NativeWindowMac::SetTouchBar(
  1226. std::vector<gin_helper::PersistentDictionary> items) {
  1227. touch_bar_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_
  1228. window:this
  1229. settings:std::move(items)];
  1230. [window_ setTouchBar:nil];
  1231. }
  1232. void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) {
  1233. if (touch_bar_ && [window_ touchBar])
  1234. [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id];
  1235. }
  1236. void NativeWindowMac::SetEscapeTouchBarItem(
  1237. gin_helper::PersistentDictionary item) {
  1238. if (touch_bar_ && [window_ touchBar])
  1239. [touch_bar_ setEscapeTouchBarItem:std::move(item)
  1240. forTouchBar:[window_ touchBar]];
  1241. }
  1242. void NativeWindowMac::SelectPreviousTab() {
  1243. [window_ selectPreviousTab:nil];
  1244. }
  1245. void NativeWindowMac::SelectNextTab() {
  1246. [window_ selectNextTab:nil];
  1247. }
  1248. void NativeWindowMac::ShowAllTabs() {
  1249. [window_ toggleTabOverview:nil];
  1250. }
  1251. void NativeWindowMac::MergeAllWindows() {
  1252. [window_ mergeAllWindows:nil];
  1253. }
  1254. void NativeWindowMac::MoveTabToNewWindow() {
  1255. [window_ moveTabToNewWindow:nil];
  1256. }
  1257. void NativeWindowMac::ToggleTabBar() {
  1258. [window_ toggleTabBar:nil];
  1259. }
  1260. bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) {
  1261. if (window_ == window->GetNativeWindow().GetNativeNSWindow()) {
  1262. return false;
  1263. } else {
  1264. [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow()
  1265. ordered:NSWindowAbove];
  1266. }
  1267. return true;
  1268. }
  1269. std::optional<std::string> NativeWindowMac::GetTabbingIdentifier() const {
  1270. if ([window_ tabbingMode] == NSWindowTabbingModeDisallowed)
  1271. return std::nullopt;
  1272. return base::SysNSStringToUTF8([window_ tabbingIdentifier]);
  1273. }
  1274. void NativeWindowMac::SetAspectRatio(double aspect_ratio,
  1275. const gfx::Size& extra_size) {
  1276. NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
  1277. // Reset the behaviour to default if aspect_ratio is set to 0 or less.
  1278. if (aspect_ratio > 0.0) {
  1279. NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0);
  1280. if (has_frame())
  1281. [window_ setContentAspectRatio:aspect_ratio_size];
  1282. else
  1283. [window_ setAspectRatio:aspect_ratio_size];
  1284. } else {
  1285. [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)];
  1286. }
  1287. }
  1288. void NativeWindowMac::PreviewFile(const std::string& path,
  1289. const std::string& display_name) {
  1290. preview_item_ = [[ElectronPreviewItem alloc]
  1291. initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)]
  1292. title:base::SysUTF8ToNSString(display_name)];
  1293. [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
  1294. }
  1295. void NativeWindowMac::CloseFilePreview() {
  1296. if ([QLPreviewPanel sharedPreviewPanelExists]) {
  1297. [[QLPreviewPanel sharedPreviewPanel] close];
  1298. }
  1299. }
  1300. gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds(
  1301. const gfx::Rect& bounds) const {
  1302. if (has_frame()) {
  1303. gfx::Rect window_bounds(
  1304. [window_ frameRectForContentRect:bounds.ToCGRect()]);
  1305. int frame_height = window_bounds.height() - bounds.height();
  1306. window_bounds.set_y(window_bounds.y() - frame_height);
  1307. return window_bounds;
  1308. } else {
  1309. return bounds;
  1310. }
  1311. }
  1312. gfx::Rect NativeWindowMac::WindowBoundsToContentBounds(
  1313. const gfx::Rect& bounds) const {
  1314. if (has_frame()) {
  1315. gfx::Rect content_bounds(
  1316. [window_ contentRectForFrameRect:bounds.ToCGRect()]);
  1317. int frame_height = bounds.height() - content_bounds.height();
  1318. content_bounds.set_y(content_bounds.y() + frame_height);
  1319. return content_bounds;
  1320. } else {
  1321. return bounds;
  1322. }
  1323. }
  1324. void NativeWindowMac::NotifyWindowEnterFullScreen() {
  1325. NativeWindow::NotifyWindowEnterFullScreen();
  1326. // Restore the window title under fullscreen mode.
  1327. if (buttons_proxy_)
  1328. [window_ setTitleVisibility:NSWindowTitleVisible];
  1329. if (transparent() || !has_frame())
  1330. [window_ setTitlebarAppearsTransparent:NO];
  1331. }
  1332. void NativeWindowMac::NotifyWindowLeaveFullScreen() {
  1333. NativeWindow::NotifyWindowLeaveFullScreen();
  1334. // Restore window buttons.
  1335. if (buttons_proxy_ && window_button_visibility_.value_or(true)) {
  1336. [buttons_proxy_ redraw];
  1337. [buttons_proxy_ setVisible:YES];
  1338. }
  1339. if (transparent() || !has_frame())
  1340. [window_ setTitlebarAppearsTransparent:YES];
  1341. }
  1342. void NativeWindowMac::NotifyWindowWillEnterFullScreen() {
  1343. UpdateVibrancyRadii(true);
  1344. }
  1345. void NativeWindowMac::NotifyWindowDidFailToEnterFullScreen() {
  1346. UpdateVibrancyRadii(false);
  1347. if (buttons_proxy_)
  1348. [buttons_proxy_ redraw];
  1349. }
  1350. void NativeWindowMac::NotifyWindowWillLeaveFullScreen() {
  1351. if (buttons_proxy_) {
  1352. // Hide window title when leaving fullscreen.
  1353. [window_ setTitleVisibility:NSWindowTitleHidden];
  1354. // Hide the container otherwise traffic light buttons jump.
  1355. [buttons_proxy_ setVisible:NO];
  1356. }
  1357. UpdateVibrancyRadii(false);
  1358. }
  1359. void NativeWindowMac::SetActive(bool is_key) {
  1360. is_active_ = is_key;
  1361. }
  1362. bool NativeWindowMac::IsActive() const {
  1363. return is_active_;
  1364. }
  1365. void NativeWindowMac::Cleanup() {
  1366. DCHECK(!IsClosed());
  1367. ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this);
  1368. display::Screen::GetScreen()->RemoveObserver(this);
  1369. }
  1370. class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac {
  1371. public:
  1372. NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window)
  1373. : views::NativeFrameViewMac(frame), native_window_(window) {}
  1374. NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete;
  1375. NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) =
  1376. delete;
  1377. ~NativeAppWindowFrameViewMac() override = default;
  1378. // NonClientFrameView:
  1379. int NonClientHitTest(const gfx::Point& point) override {
  1380. if (!bounds().Contains(point))
  1381. return HTNOWHERE;
  1382. if (GetWidget()->IsFullscreen())
  1383. return HTCLIENT;
  1384. // Check for possible draggable region in the client area for the frameless
  1385. // window.
  1386. int contents_hit_test = native_window_->NonClientHitTest(point);
  1387. if (contents_hit_test != HTNOWHERE)
  1388. return contents_hit_test;
  1389. return HTCLIENT;
  1390. }
  1391. private:
  1392. // Weak.
  1393. raw_ptr<NativeWindowMac> const native_window_;
  1394. };
  1395. std::unique_ptr<views::NonClientFrameView>
  1396. NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) {
  1397. return std::make_unique<NativeAppWindowFrameViewMac>(widget, this);
  1398. }
  1399. bool NativeWindowMac::HasStyleMask(NSUInteger flag) const {
  1400. return [window_ styleMask] & flag;
  1401. }
  1402. void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) {
  1403. // Changing the styleMask of a frameless windows causes it to change size so
  1404. // we explicitly disable resizing while setting it.
  1405. ScopedDisableResize disable_resize;
  1406. if (on)
  1407. [window_ setStyleMask:[window_ styleMask] | flag];
  1408. else
  1409. [window_ setStyleMask:[window_ styleMask] & (~flag)];
  1410. // Change style mask will make the zoom button revert to default, probably
  1411. // a bug of Cocoa or macOS.
  1412. SetMaximizable(maximizable_);
  1413. }
  1414. void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) {
  1415. if (on)
  1416. [window_ setCollectionBehavior:[window_ collectionBehavior] | flag];
  1417. else
  1418. [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)];
  1419. // Change collectionBehavior will make the zoom button revert to default,
  1420. // probably a bug of Cocoa or macOS.
  1421. SetMaximizable(maximizable_);
  1422. }
  1423. views::View* NativeWindowMac::GetContentsView() {
  1424. return root_view_.get();
  1425. }
  1426. bool NativeWindowMac::CanMaximize() const {
  1427. return maximizable_;
  1428. }
  1429. void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
  1430. content::GetUIThreadTaskRunner({})->PostTask(
  1431. FROM_HERE,
  1432. base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr()));
  1433. }
  1434. void NativeWindowMac::AddContentViewLayers() {
  1435. // Make sure the bottom corner is rounded for non-modal windows:
  1436. // http://crbug.com/396264.
  1437. if (!is_modal()) {
  1438. // For normal window, we need to explicitly set layer for contentView to
  1439. // make setBackgroundColor work correctly.
  1440. // There is no need to do so for frameless window, and doing so would make
  1441. // titleBarStyle stop working.
  1442. if (has_frame()) {
  1443. CALayer* background_layer = [[CALayer alloc] init];
  1444. [background_layer
  1445. setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable];
  1446. [[window_ contentView] setLayer:background_layer];
  1447. }
  1448. [[window_ contentView] setWantsLayer:YES];
  1449. }
  1450. }
  1451. void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) {
  1452. [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible];
  1453. [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible];
  1454. [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible];
  1455. }
  1456. void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent,
  1457. bool attach) {
  1458. if (is_modal())
  1459. return;
  1460. // Do not remove/add if we are already properly attached.
  1461. if (attach && new_parent &&
  1462. [window_ parentWindow] ==
  1463. new_parent->GetNativeWindow().GetNativeNSWindow())
  1464. return;
  1465. // Remove current parent window.
  1466. RemoveChildFromParentWindow();
  1467. // Set new parent window.
  1468. if (new_parent) {
  1469. new_parent->add_child_window(this);
  1470. if (attach)
  1471. new_parent->AttachChildren();
  1472. }
  1473. NativeWindow::SetParentWindow(new_parent);
  1474. }
  1475. void NativeWindowMac::SetForwardMouseMessages(bool forward) {
  1476. [window_ setAcceptsMouseMovedEvents:forward];
  1477. }
  1478. std::optional<gfx::Rect> NativeWindowMac::GetWindowControlsOverlayRect() {
  1479. if (!titlebar_overlay_)
  1480. return std::nullopt;
  1481. // On macOS, when in fullscreen mode, window controls (the menu bar, title
  1482. // bar, and toolbar) are attached to a separate NSView that slides down from
  1483. // the top of the screen, independent of, and overlapping the WebContents.
  1484. // Disable WCO when in fullscreen, because this space is inaccessible to
  1485. // WebContents. https://crbug.com/915110.
  1486. if (IsFullscreen())
  1487. return gfx::Rect();
  1488. if (buttons_proxy_ && window_button_visibility_.value_or(true)) {
  1489. NSRect buttons = [buttons_proxy_ getButtonsContainerBounds];
  1490. gfx::Rect overlay;
  1491. overlay.set_width(GetContentSize().width() - NSWidth(buttons));
  1492. overlay.set_height([buttons_proxy_ useCustomHeight]
  1493. ? titlebar_overlay_height()
  1494. : NSHeight(buttons));
  1495. if (!base::i18n::IsRTL())
  1496. overlay.set_x(NSMaxX(buttons));
  1497. return overlay;
  1498. }
  1499. return std::nullopt;
  1500. }
  1501. // static
  1502. NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options,
  1503. NativeWindow* parent) {
  1504. return new NativeWindowMac(options, parent);
  1505. }
  1506. } // namespace electron