native_window_mac.mm 63 KB

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