native_window_mac.mm 63 KB

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