native_window_mac.mm 59 KB

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