native_window_mac.mm 61 KB

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