native_window_mac.mm 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  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 "atom/browser/native_window_mac.h"
  5. #include <AvailabilityMacros.h>
  6. #include <objc/objc-runtime.h>
  7. #include <string>
  8. #include "atom/browser/native_browser_view_mac.h"
  9. #include "atom/browser/ui/cocoa/atom_native_widget_mac.h"
  10. #include "atom/browser/ui/cocoa/atom_ns_window.h"
  11. #include "atom/browser/ui/cocoa/atom_ns_window_delegate.h"
  12. #include "atom/browser/ui/cocoa/atom_preview_item.h"
  13. #include "atom/browser/ui/cocoa/atom_touch_bar.h"
  14. #include "atom/browser/ui/cocoa/root_view_mac.h"
  15. #include "atom/browser/ui/inspectable_web_contents.h"
  16. #include "atom/browser/ui/inspectable_web_contents_view.h"
  17. #include "atom/browser/window_list.h"
  18. #include "atom/common/options_switches.h"
  19. #include "base/mac/mac_util.h"
  20. #include "base/mac/scoped_cftyperef.h"
  21. #include "base/numerics/ranges.h"
  22. #include "base/strings/sys_string_conversions.h"
  23. #include "content/public/browser/browser_accessibility_state.h"
  24. #include "native_mate/dictionary.h"
  25. #include "skia/ext/skia_utils_mac.h"
  26. #include "ui/gfx/skia_util.h"
  27. #include "ui/gl/gpu_switching_manager.h"
  28. #include "ui/views/background.h"
  29. #include "ui/views/cocoa/bridged_native_widget_host_impl.h"
  30. #include "ui/views/widget/widget.h"
  31. #include "ui/views_bridge_mac/bridged_native_widget_impl.h"
  32. // This view would inform Chromium to resize the hosted views::View.
  33. //
  34. // The overrided methods should behave the same with BridgedContentView.
  35. @interface ElectronAdapatedContentView : NSView {
  36. @private
  37. views::BridgedNativeWidgetHostImpl* bridge_host_;
  38. }
  39. @end
  40. @implementation ElectronAdapatedContentView
  41. - (id)initWithShell:(atom::NativeWindowMac*)shell {
  42. if ((self = [self init])) {
  43. bridge_host_ = views::BridgedNativeWidgetHostImpl::GetFromNativeWindow(
  44. shell->GetNativeWindow());
  45. }
  46. return self;
  47. }
  48. - (void)viewDidMoveToWindow {
  49. // When this view is added to a window, AppKit calls setFrameSize before it is
  50. // added to the window, so the behavior in setFrameSize is not triggered.
  51. NSWindow* window = [self window];
  52. if (window)
  53. [self setFrameSize:NSZeroSize];
  54. }
  55. - (void)setFrameSize:(NSSize)newSize {
  56. // The size passed in here does not always use
  57. // -[NSWindow contentRectForFrameRect]. The following ensures that the
  58. // contentView for a frameless window can extend over the titlebar of the new
  59. // window containing it, since AppKit requires a titlebar to give frameless
  60. // windows correct shadows and rounded corners.
  61. NSWindow* window = [self window];
  62. if (window && [window contentView] == self) {
  63. newSize = [window contentRectForFrameRect:[window frame]].size;
  64. // Ensure that the window geometry be updated on the host side before the
  65. // view size is updated.
  66. bridge_host_->bridge_impl()->UpdateWindowGeometry();
  67. }
  68. [super setFrameSize:newSize];
  69. // The OnViewSizeChanged is marked private in derived class.
  70. static_cast<views_bridge_mac::mojom::BridgedNativeWidgetHost*>(bridge_host_)
  71. ->OnViewSizeChanged(gfx::Size(newSize.width, newSize.height));
  72. }
  73. @end
  74. // This view always takes the size of its superview. It is intended to be used
  75. // as a NSWindow's contentView. It is needed because NSWindow's implementation
  76. // explicitly resizes the contentView at inopportune times.
  77. @interface FullSizeContentView : NSView
  78. @end
  79. @implementation FullSizeContentView
  80. // This method is directly called by NSWindow during a window resize on OSX
  81. // 10.10.0, beta 2. We must override it to prevent the content view from
  82. // shrinking.
  83. - (void)setFrameSize:(NSSize)size {
  84. if ([self superview])
  85. size = [[self superview] bounds].size;
  86. [super setFrameSize:size];
  87. }
  88. // The contentView gets moved around during certain full-screen operations.
  89. // This is less than ideal, and should eventually be removed.
  90. - (void)viewDidMoveToSuperview {
  91. [self setFrame:[[self superview] bounds]];
  92. }
  93. @end
  94. // Custom Quit, Minimize and Full Screen button container for frameless
  95. // windows.
  96. @interface CustomWindowButtonView : NSView {
  97. @private
  98. BOOL mouse_inside_;
  99. }
  100. @end
  101. @implementation CustomWindowButtonView
  102. - (id)initWithFrame:(NSRect)frame {
  103. self = [super initWithFrame:frame];
  104. NSButton* close_button =
  105. [NSWindow standardWindowButton:NSWindowCloseButton
  106. forStyleMask:NSWindowStyleMaskTitled];
  107. [close_button setTag:1];
  108. NSButton* miniaturize_button =
  109. [NSWindow standardWindowButton:NSWindowMiniaturizeButton
  110. forStyleMask:NSWindowStyleMaskTitled];
  111. [miniaturize_button setTag:2];
  112. CGFloat x = 0;
  113. const CGFloat space_between = 20;
  114. [close_button setFrameOrigin:NSMakePoint(x, 0)];
  115. x += space_between;
  116. [self addSubview:close_button];
  117. [miniaturize_button setFrameOrigin:NSMakePoint(x, 0)];
  118. x += space_between;
  119. [self addSubview:miniaturize_button];
  120. const auto last_button_frame = miniaturize_button.frame;
  121. [self setFrameSize:NSMakeSize(last_button_frame.origin.x +
  122. last_button_frame.size.width,
  123. last_button_frame.size.height)];
  124. mouse_inside_ = NO;
  125. [self setNeedsDisplayForButtons];
  126. return self;
  127. }
  128. - (void)viewDidMoveToWindow {
  129. if (!self.window) {
  130. return;
  131. }
  132. // Stay in upper left corner.
  133. const CGFloat top_margin = 3;
  134. const CGFloat left_margin = 7;
  135. [self setAutoresizingMask:NSViewMaxXMargin | NSViewMinYMargin];
  136. [self setFrameOrigin:NSMakePoint(left_margin, self.window.frame.size.height -
  137. self.frame.size.height -
  138. top_margin)];
  139. }
  140. - (BOOL)_mouseInGroup:(NSButton*)button {
  141. return mouse_inside_;
  142. }
  143. - (void)updateTrackingAreas {
  144. auto tracking_area = [[[NSTrackingArea alloc]
  145. initWithRect:NSZeroRect
  146. options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways |
  147. NSTrackingInVisibleRect
  148. owner:self
  149. userInfo:nil] autorelease];
  150. [self addTrackingArea:tracking_area];
  151. }
  152. - (void)mouseEntered:(NSEvent*)event {
  153. [super mouseEntered:event];
  154. mouse_inside_ = YES;
  155. [self setNeedsDisplayForButtons];
  156. }
  157. - (void)mouseExited:(NSEvent*)event {
  158. [super mouseExited:event];
  159. mouse_inside_ = NO;
  160. [self setNeedsDisplayForButtons];
  161. }
  162. - (void)setNeedsDisplayForButtons {
  163. for (NSView* subview in self.subviews) {
  164. [subview setHidden:!mouse_inside_];
  165. [subview setNeedsDisplay:YES];
  166. }
  167. }
  168. @end
  169. #if !defined(AVAILABLE_MAC_OS_X_VERSION_10_12_AND_LATER)
  170. enum { NSWindowTabbingModeDisallowed = 2 };
  171. @interface NSWindow (SierraSDK)
  172. - (void)setTabbingMode:(NSInteger)mode;
  173. - (void)setTabbingIdentifier:(NSString*)identifier;
  174. - (void)addTabbedWindow:(NSWindow*)window ordered:(NSWindowOrderingMode)ordered;
  175. - (IBAction)selectPreviousTab:(id)sender;
  176. - (IBAction)selectNextTab:(id)sender;
  177. - (IBAction)mergeAllWindows:(id)sender;
  178. - (IBAction)moveTabToNewWindow:(id)sender;
  179. - (IBAction)toggleTabBar:(id)sender;
  180. @end
  181. #endif
  182. @interface AtomProgressBar : NSProgressIndicator
  183. @end
  184. @implementation AtomProgressBar
  185. - (void)drawRect:(NSRect)dirtyRect {
  186. if (self.style != NSProgressIndicatorBarStyle)
  187. return;
  188. // Draw edges of rounded rect.
  189. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0);
  190. CGFloat radius = rect.size.height / 2;
  191. NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
  192. xRadius:radius
  193. yRadius:radius];
  194. [bezier_path setLineWidth:2.0];
  195. [[NSColor grayColor] set];
  196. [bezier_path stroke];
  197. // Fill the rounded rect.
  198. rect = NSInsetRect(rect, 2.0, 2.0);
  199. radius = rect.size.height / 2;
  200. bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
  201. xRadius:radius
  202. yRadius:radius];
  203. [bezier_path setLineWidth:1.0];
  204. [bezier_path addClip];
  205. // Calculate the progress width.
  206. rect.size.width =
  207. floor(rect.size.width * ([self doubleValue] / [self maxValue]));
  208. // Fill the progress bar with color blue.
  209. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set];
  210. NSRectFill(rect);
  211. }
  212. @end
  213. namespace mate {
  214. template <>
  215. struct Converter<atom::NativeWindowMac::TitleBarStyle> {
  216. static bool FromV8(v8::Isolate* isolate,
  217. v8::Handle<v8::Value> val,
  218. atom::NativeWindowMac::TitleBarStyle* out) {
  219. std::string title_bar_style;
  220. if (!ConvertFromV8(isolate, val, &title_bar_style))
  221. return false;
  222. if (title_bar_style == "hidden") {
  223. *out = atom::NativeWindowMac::HIDDEN;
  224. } else if (title_bar_style == "hiddenInset") {
  225. *out = atom::NativeWindowMac::HIDDEN_INSET;
  226. } else if (title_bar_style == "customButtonsOnHover") {
  227. *out = atom::NativeWindowMac::CUSTOM_BUTTONS_ON_HOVER;
  228. } else {
  229. return false;
  230. }
  231. return true;
  232. }
  233. };
  234. } // namespace mate
  235. namespace atom {
  236. namespace {
  237. bool IsFramelessWindow(NSView* view) {
  238. NSWindow* nswindow = [view window];
  239. if (![nswindow respondsToSelector:@selector(shell)])
  240. return false;
  241. NativeWindow* window = [static_cast<AtomNSWindow*>(nswindow) shell];
  242. return window && !window->has_frame();
  243. }
  244. IMP original_set_frame_size = nullptr;
  245. IMP original_view_did_move_to_superview = nullptr;
  246. // This method is directly called by NSWindow during a window resize on OSX
  247. // 10.10.0, beta 2. We must override it to prevent the content view from
  248. // shrinking.
  249. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) {
  250. if (!IsFramelessWindow(self)) {
  251. auto original =
  252. reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size);
  253. return original(self, _cmd, size);
  254. }
  255. // For frameless window, resize the view to cover full window.
  256. if ([self superview])
  257. size = [[self superview] bounds].size;
  258. auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>(
  259. [[self superclass] instanceMethodForSelector:_cmd]);
  260. super_impl(self, _cmd, size);
  261. }
  262. // The contentView gets moved around during certain full-screen operations.
  263. // This is less than ideal, and should eventually be removed.
  264. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) {
  265. if (!IsFramelessWindow(self)) {
  266. // [BridgedContentView viewDidMoveToSuperview];
  267. auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>(
  268. original_view_did_move_to_superview);
  269. if (original)
  270. original(self, _cmd);
  271. return;
  272. }
  273. [self setFrame:[[self superview] bounds]];
  274. }
  275. } // namespace
  276. NativeWindowMac::NativeWindowMac(const mate::Dictionary& options,
  277. NativeWindow* parent)
  278. : NativeWindow(options, parent), root_view_(new RootViewMac(this)) {
  279. int width = 800, height = 600;
  280. options.Get(options::kWidth, &width);
  281. options.Get(options::kHeight, &height);
  282. NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame];
  283. gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2),
  284. round((NSHeight(main_screen_rect) - height) / 2), width,
  285. height);
  286. options.Get(options::kResizable, &resizable_);
  287. options.Get(options::kTitleBarStyle, &title_bar_style_);
  288. options.Get(options::kZoomToPageWidth, &zoom_to_page_width_);
  289. options.Get(options::kFullscreenWindowTitle, &fullscreen_window_title_);
  290. options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_);
  291. bool minimizable = true;
  292. options.Get(options::kMinimizable, &minimizable);
  293. bool maximizable = true;
  294. options.Get(options::kMaximizable, &maximizable);
  295. bool closable = true;
  296. options.Get(options::kClosable, &closable);
  297. std::string tabbingIdentifier;
  298. options.Get(options::kTabbingIdentifier, &tabbingIdentifier);
  299. std::string windowType;
  300. options.Get(options::kType, &windowType);
  301. bool useStandardWindow = true;
  302. // eventually deprecate separate "standardWindow" option in favor of
  303. // standard / textured window types
  304. options.Get(options::kStandardWindow, &useStandardWindow);
  305. if (windowType == "textured") {
  306. useStandardWindow = false;
  307. }
  308. NSUInteger styleMask = NSWindowStyleMaskTitled;
  309. if (title_bar_style_ == CUSTOM_BUTTONS_ON_HOVER &&
  310. (!useStandardWindow || transparent() || !has_frame())) {
  311. styleMask = NSWindowStyleMaskFullSizeContentView;
  312. }
  313. if (minimizable) {
  314. styleMask |= NSMiniaturizableWindowMask;
  315. }
  316. if (closable) {
  317. styleMask |= NSWindowStyleMaskClosable;
  318. }
  319. if (title_bar_style_ != NORMAL) {
  320. // The window without titlebar is treated the same with frameless window.
  321. set_has_frame(false);
  322. }
  323. if (!useStandardWindow || transparent() || !has_frame()) {
  324. styleMask |= NSTexturedBackgroundWindowMask;
  325. }
  326. if (resizable_) {
  327. styleMask |= NSResizableWindowMask;
  328. }
  329. // Create views::Widget and assign window_ with it.
  330. // TODO(zcbenz): Get rid of the window_ in future.
  331. views::Widget::InitParams params;
  332. params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  333. params.bounds = bounds;
  334. params.delegate = this;
  335. params.type = views::Widget::InitParams::TYPE_WINDOW;
  336. params.native_widget = new AtomNativeWidgetMac(this, styleMask, widget());
  337. widget()->Init(params);
  338. window_ = static_cast<AtomNSWindow*>(
  339. widget()->GetNativeWindow().GetNativeNSWindow());
  340. [window_ setEnableLargerThanScreen:enable_larger_than_screen()];
  341. window_delegate_.reset([[AtomNSWindowDelegate alloc] initWithShell:this]);
  342. [window_ setDelegate:window_delegate_];
  343. // Only use native parent window for non-modal windows.
  344. if (parent && !is_modal()) {
  345. SetParentWindow(parent);
  346. }
  347. if (transparent()) {
  348. // Setting the background color to clear will also hide the shadow.
  349. [window_ setBackgroundColor:[NSColor clearColor]];
  350. }
  351. if (windowType == "desktop") {
  352. [window_ setLevel:kCGDesktopWindowLevel - 1];
  353. [window_ setDisableKeyOrMainWindow:YES];
  354. [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces |
  355. NSWindowCollectionBehaviorStationary |
  356. NSWindowCollectionBehaviorIgnoresCycle)];
  357. }
  358. bool focusable;
  359. if (options.Get(options::kFocusable, &focusable) && !focusable)
  360. [window_ setDisableKeyOrMainWindow:YES];
  361. if (transparent() || !has_frame()) {
  362. // Don't show title bar.
  363. [window_ setTitlebarAppearsTransparent:YES];
  364. [window_ setTitleVisibility:NSWindowTitleHidden];
  365. // Remove non-transparent corners, see http://git.io/vfonD.
  366. [window_ setOpaque:NO];
  367. }
  368. // Create a tab only if tabbing identifier is specified and window has
  369. // a native title bar.
  370. if (tabbingIdentifier.empty() || transparent() || !has_frame()) {
  371. if (@available(macOS 10.12, *)) {
  372. [window_ setTabbingMode:NSWindowTabbingModeDisallowed];
  373. }
  374. } else {
  375. if (@available(macOS 10.12, *)) {
  376. [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)];
  377. }
  378. }
  379. // Hide the title bar background
  380. if (title_bar_style_ != NORMAL) {
  381. [window_ setTitlebarAppearsTransparent:YES];
  382. }
  383. // Hide the title bar.
  384. if (title_bar_style_ == HIDDEN_INSET) {
  385. base::scoped_nsobject<NSToolbar> toolbar(
  386. [[NSToolbar alloc] initWithIdentifier:@"titlebarStylingToolbar"]);
  387. [toolbar setShowsBaselineSeparator:NO];
  388. [window_ setToolbar:toolbar];
  389. }
  390. // Resize to content bounds.
  391. bool use_content_size = false;
  392. options.Get(options::kUseContentSize, &use_content_size);
  393. if (!has_frame() || use_content_size)
  394. SetContentSize(gfx::Size(width, height));
  395. // Enable the NSView to accept first mouse event.
  396. bool acceptsFirstMouse = false;
  397. options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse);
  398. [window_ setAcceptsFirstMouse:acceptsFirstMouse];
  399. // Disable auto-hiding cursor.
  400. bool disableAutoHideCursor = false;
  401. options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor);
  402. [window_ setDisableAutoHideCursor:disableAutoHideCursor];
  403. // Use an NSEvent monitor to listen for the wheel event.
  404. BOOL __block began = NO;
  405. wheel_event_monitor_ = [NSEvent
  406. addLocalMonitorForEventsMatchingMask:NSScrollWheelMask
  407. handler:^(NSEvent* event) {
  408. if ([[event window] windowNumber] !=
  409. [window_ windowNumber])
  410. return event;
  411. if (!began && (([event phase] ==
  412. NSEventPhaseMayBegin) ||
  413. ([event phase] ==
  414. NSEventPhaseBegan))) {
  415. this->NotifyWindowScrollTouchBegin();
  416. began = YES;
  417. } else if (began &&
  418. (([event phase] ==
  419. NSEventPhaseEnded) ||
  420. ([event phase] ==
  421. NSEventPhaseCancelled))) {
  422. this->NotifyWindowScrollTouchEnd();
  423. began = NO;
  424. }
  425. return event;
  426. }];
  427. // Set maximizable state last to ensure zoom button does not get reset
  428. // by calls to other APIs.
  429. SetMaximizable(maximizable);
  430. // Default content view.
  431. SetContentView(new views::View());
  432. AddContentViewLayers(minimizable, closable);
  433. original_frame_ = [window_ frame];
  434. original_level_ = [window_ level];
  435. }
  436. NativeWindowMac::~NativeWindowMac() {
  437. if (wheel_event_monitor_)
  438. [NSEvent removeMonitor:wheel_event_monitor_];
  439. }
  440. void NativeWindowMac::SetContentView(views::View* view) {
  441. views::View* root_view = GetContentsView();
  442. if (content_view())
  443. root_view->RemoveChildView(content_view());
  444. set_content_view(view);
  445. root_view->AddChildView(content_view());
  446. if (buttons_view_) {
  447. // Ensure the buttons view are always floated on the top.
  448. [buttons_view_ removeFromSuperview];
  449. [[window_ contentView] addSubview:buttons_view_];
  450. }
  451. root_view->Layout();
  452. }
  453. void NativeWindowMac::Close() {
  454. // When this is a sheet showing, performClose won't work.
  455. if (is_modal() && parent() && IsVisible()) {
  456. [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_];
  457. CloseImmediately();
  458. return;
  459. }
  460. if (!IsClosable()) {
  461. WindowList::WindowCloseCancelled(this);
  462. return;
  463. }
  464. [window_ performClose:nil];
  465. }
  466. void NativeWindowMac::CloseImmediately() {
  467. // Remove event monitor before destroying window, otherwise the monitor may
  468. // call its callback after window has been destroyed.
  469. if (wheel_event_monitor_) {
  470. [NSEvent removeMonitor:wheel_event_monitor_];
  471. wheel_event_monitor_ = nil;
  472. }
  473. // Retain the child window before closing it. If the last reference to the
  474. // NSWindow goes away inside -[NSWindow close], then bad stuff can happen.
  475. // See e.g. http://crbug.com/616701.
  476. base::scoped_nsobject<NSWindow> child_window(window_,
  477. base::scoped_policy::RETAIN);
  478. [window_ close];
  479. }
  480. void NativeWindowMac::Focus(bool focus) {
  481. if (!IsVisible())
  482. return;
  483. if (focus) {
  484. [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
  485. [window_ makeKeyAndOrderFront:nil];
  486. } else {
  487. [window_ orderBack:nil];
  488. }
  489. }
  490. bool NativeWindowMac::IsFocused() {
  491. return [window_ isKeyWindow];
  492. }
  493. void NativeWindowMac::Show() {
  494. if (is_modal() && parent()) {
  495. if ([window_ sheetParent] == nil)
  496. [parent()->GetNativeWindow().GetNativeNSWindow()
  497. beginSheet:window_
  498. completionHandler:^(NSModalResponse){
  499. }];
  500. return;
  501. }
  502. // Reattach the window to the parent to actually show it.
  503. if (parent())
  504. InternalSetParentWindow(parent(), true);
  505. // This method is supposed to put focus on window, however if the app does not
  506. // have focus then "makeKeyAndOrderFront" will only show the window.
  507. [NSApp activateIgnoringOtherApps:YES];
  508. [window_ makeKeyAndOrderFront:nil];
  509. }
  510. void NativeWindowMac::ShowInactive() {
  511. // Reattach the window to the parent to actually show it.
  512. if (parent())
  513. InternalSetParentWindow(parent(), true);
  514. [window_ orderFrontRegardless];
  515. }
  516. void NativeWindowMac::Hide() {
  517. if (is_modal() && parent()) {
  518. [window_ orderOut:nil];
  519. [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_];
  520. return;
  521. }
  522. // Deattach the window from the parent before.
  523. if (parent())
  524. InternalSetParentWindow(parent(), false);
  525. [window_ orderOut:nil];
  526. }
  527. bool NativeWindowMac::IsVisible() {
  528. bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible;
  529. // For a window to be visible, it must be visible to the user in the
  530. // foreground of the app, which means that it should not be minimized or
  531. // occluded
  532. return [window_ isVisible] && !occluded && !IsMinimized();
  533. }
  534. bool NativeWindowMac::IsEnabled() {
  535. return [window_ attachedSheet] == nil;
  536. }
  537. void NativeWindowMac::SetEnabled(bool enable) {
  538. if (enable) {
  539. [window_ endSheet:[window_ attachedSheet]];
  540. } else {
  541. [window_ beginSheet:window_
  542. completionHandler:^(NSModalResponse returnCode) {
  543. NSLog(@"modal enabled");
  544. return;
  545. }];
  546. }
  547. }
  548. void NativeWindowMac::Maximize() {
  549. if (IsMaximized())
  550. return;
  551. // Take note of the current window size
  552. if (IsNormal())
  553. original_frame_ = [window_ frame];
  554. [window_ zoom:nil];
  555. }
  556. void NativeWindowMac::Unmaximize() {
  557. if (!IsMaximized())
  558. return;
  559. [window_ zoom:nil];
  560. }
  561. bool NativeWindowMac::IsMaximized() {
  562. if (([window_ styleMask] & NSWindowStyleMaskResizable) != 0) {
  563. return [window_ isZoomed];
  564. } else {
  565. NSRect rectScreen = [[NSScreen mainScreen] visibleFrame];
  566. NSRect rectWindow = [window_ frame];
  567. return (rectScreen.origin.x == rectWindow.origin.x &&
  568. rectScreen.origin.y == rectWindow.origin.y &&
  569. rectScreen.size.width == rectWindow.size.width &&
  570. rectScreen.size.height == rectWindow.size.height);
  571. }
  572. }
  573. void NativeWindowMac::Minimize() {
  574. if (IsMinimized())
  575. return;
  576. // Take note of the current window size
  577. if (IsNormal())
  578. original_frame_ = [window_ frame];
  579. [window_ miniaturize:nil];
  580. }
  581. void NativeWindowMac::Restore() {
  582. [window_ deminiaturize:nil];
  583. }
  584. bool NativeWindowMac::IsMinimized() {
  585. return [window_ isMiniaturized];
  586. }
  587. void NativeWindowMac::SetFullScreen(bool fullscreen) {
  588. if (fullscreen == IsFullscreen())
  589. return;
  590. // Take note of the current window size
  591. if (IsNormal())
  592. original_frame_ = [window_ frame];
  593. [window_ toggleFullScreenMode:nil];
  594. }
  595. bool NativeWindowMac::IsFullscreen() const {
  596. return [window_ styleMask] & NSWindowStyleMaskFullScreen;
  597. }
  598. void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) {
  599. // Do nothing if in fullscreen mode.
  600. if (IsFullscreen())
  601. return;
  602. // Check size constraints since setFrame does not check it.
  603. gfx::Size size = bounds.size();
  604. size.SetToMax(GetMinimumSize());
  605. gfx::Size max_size = GetMaximumSize();
  606. if (!max_size.IsEmpty())
  607. size.SetToMin(max_size);
  608. NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height());
  609. // Flip coordinates based on the primary screen.
  610. NSScreen* screen = [[NSScreen screens] firstObject];
  611. cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y();
  612. [window_ setFrame:cocoa_bounds display:YES animate:animate];
  613. }
  614. gfx::Rect NativeWindowMac::GetBounds() {
  615. NSRect frame = [window_ frame];
  616. gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
  617. NSScreen* screen = [[NSScreen screens] firstObject];
  618. bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
  619. return bounds;
  620. }
  621. bool NativeWindowMac::IsNormal() {
  622. return NativeWindow::IsNormal() && !IsSimpleFullScreen();
  623. }
  624. gfx::Rect NativeWindowMac::GetNormalBounds() {
  625. if (IsNormal()) {
  626. return GetBounds();
  627. }
  628. NSRect frame = original_frame_;
  629. gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
  630. NSScreen* screen = [[NSScreen screens] firstObject];
  631. bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
  632. return bounds;
  633. // Works on OS_WIN !
  634. // return widget()->GetRestoredBounds();
  635. }
  636. void NativeWindowMac::SetContentSizeConstraints(
  637. const extensions::SizeConstraints& size_constraints) {
  638. auto convertSize = [this](const gfx::Size& size) {
  639. // Our frameless window still has titlebar attached, so setting contentSize
  640. // will result in actual content size being larger.
  641. if (!has_frame()) {
  642. NSRect frame = NSMakeRect(0, 0, size.width(), size.height());
  643. NSRect content = [window_ originalContentRectForFrameRect:frame];
  644. return content.size;
  645. } else {
  646. return NSMakeSize(size.width(), size.height());
  647. }
  648. };
  649. NSView* content = [window_ contentView];
  650. if (size_constraints.HasMinimumSize()) {
  651. NSSize min_size = convertSize(size_constraints.GetMinimumSize());
  652. [window_ setContentMinSize:[content convertSize:min_size toView:nil]];
  653. }
  654. if (size_constraints.HasMaximumSize()) {
  655. NSSize max_size = convertSize(size_constraints.GetMaximumSize());
  656. [window_ setContentMaxSize:[content convertSize:max_size toView:nil]];
  657. }
  658. NativeWindow::SetContentSizeConstraints(size_constraints);
  659. }
  660. void NativeWindowMac::MoveTop() {
  661. [window_ orderWindow:NSWindowAbove relativeTo:0];
  662. }
  663. void NativeWindowMac::SetResizable(bool resizable) {
  664. SetStyleMask(resizable, NSWindowStyleMaskResizable);
  665. }
  666. bool NativeWindowMac::IsResizable() {
  667. return [window_ styleMask] & NSWindowStyleMaskResizable;
  668. }
  669. void NativeWindowMac::SetAspectRatio(double aspect_ratio,
  670. const gfx::Size& extra_size) {
  671. NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
  672. // Reset the behaviour to default if aspect_ratio is set to 0 or less.
  673. if (aspect_ratio > 0.0)
  674. [window_ setAspectRatio:NSMakeSize(aspect_ratio, 1.0)];
  675. else
  676. [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)];
  677. }
  678. void NativeWindowMac::PreviewFile(const std::string& path,
  679. const std::string& display_name) {
  680. preview_item_.reset([[AtomPreviewItem alloc]
  681. initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)]
  682. title:base::SysUTF8ToNSString(display_name)]);
  683. [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
  684. }
  685. void NativeWindowMac::CloseFilePreview() {
  686. if ([QLPreviewPanel sharedPreviewPanelExists]) {
  687. [[QLPreviewPanel sharedPreviewPanel] close];
  688. }
  689. }
  690. void NativeWindowMac::SetMovable(bool movable) {
  691. [window_ setMovable:movable];
  692. }
  693. bool NativeWindowMac::IsMovable() {
  694. return [window_ isMovable];
  695. }
  696. void NativeWindowMac::SetMinimizable(bool minimizable) {
  697. SetStyleMask(minimizable, NSMiniaturizableWindowMask);
  698. }
  699. bool NativeWindowMac::IsMinimizable() {
  700. return [window_ styleMask] & NSMiniaturizableWindowMask;
  701. }
  702. void NativeWindowMac::SetMaximizable(bool maximizable) {
  703. [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable];
  704. }
  705. bool NativeWindowMac::IsMaximizable() {
  706. return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled];
  707. }
  708. void NativeWindowMac::SetFullScreenable(bool fullscreenable) {
  709. SetCollectionBehavior(fullscreenable,
  710. NSWindowCollectionBehaviorFullScreenPrimary);
  711. // On EL Capitan this flag is required to hide fullscreen button.
  712. SetCollectionBehavior(!fullscreenable,
  713. NSWindowCollectionBehaviorFullScreenAuxiliary);
  714. }
  715. bool NativeWindowMac::IsFullScreenable() {
  716. NSUInteger collectionBehavior = [window_ collectionBehavior];
  717. return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary;
  718. }
  719. void NativeWindowMac::SetClosable(bool closable) {
  720. SetStyleMask(closable, NSWindowStyleMaskClosable);
  721. }
  722. bool NativeWindowMac::IsClosable() {
  723. return [window_ styleMask] & NSWindowStyleMaskClosable;
  724. }
  725. void NativeWindowMac::SetAlwaysOnTop(bool top,
  726. const std::string& level,
  727. int relativeLevel,
  728. std::string* error) {
  729. int windowLevel = NSNormalWindowLevel;
  730. bool level_changed = top != widget()->IsAlwaysOnTop();
  731. CGWindowLevel maxWindowLevel = CGWindowLevelForKey(kCGMaximumWindowLevelKey);
  732. CGWindowLevel minWindowLevel = CGWindowLevelForKey(kCGMinimumWindowLevelKey);
  733. if (top) {
  734. if (level == "floating") {
  735. windowLevel = NSFloatingWindowLevel;
  736. } else if (level == "torn-off-menu") {
  737. windowLevel = NSTornOffMenuWindowLevel;
  738. } else if (level == "modal-panel") {
  739. windowLevel = NSModalPanelWindowLevel;
  740. } else if (level == "main-menu") {
  741. windowLevel = NSMainMenuWindowLevel;
  742. } else if (level == "status") {
  743. windowLevel = NSStatusWindowLevel;
  744. } else if (level == "pop-up-menu") {
  745. windowLevel = NSPopUpMenuWindowLevel;
  746. } else if (level == "screen-saver") {
  747. windowLevel = NSScreenSaverWindowLevel;
  748. } else if (level == "dock") {
  749. // Deprecated by macOS, but kept for backwards compatibility
  750. windowLevel = NSDockWindowLevel;
  751. }
  752. }
  753. NSInteger newLevel = windowLevel + relativeLevel;
  754. if (newLevel >= minWindowLevel && newLevel <= maxWindowLevel) {
  755. was_maximizable_ = IsMaximizable();
  756. [window_ setLevel:newLevel];
  757. // Set level will make the zoom button revert to default, probably
  758. // a bug of Cocoa or macOS.
  759. [[window_ standardWindowButton:NSWindowZoomButton]
  760. setEnabled:was_maximizable_];
  761. } else {
  762. *error = std::string([[NSString
  763. stringWithFormat:@"relativeLevel must be between %d and %d",
  764. minWindowLevel, maxWindowLevel] UTF8String]);
  765. }
  766. // This must be notified at the very end or IsAlwaysOnTop
  767. // will not yet have been updated to reflect the new status
  768. if (level_changed)
  769. NativeWindow::NotifyWindowAlwaysOnTopChanged();
  770. }
  771. bool NativeWindowMac::IsAlwaysOnTop() {
  772. return [window_ level] != NSNormalWindowLevel;
  773. }
  774. void NativeWindowMac::Center() {
  775. [window_ center];
  776. }
  777. void NativeWindowMac::Invalidate() {
  778. [window_ flushWindow];
  779. [[window_ contentView] setNeedsDisplay:YES];
  780. }
  781. void NativeWindowMac::SetTitle(const std::string& title) {
  782. [window_ setTitle:base::SysUTF8ToNSString(title)];
  783. }
  784. std::string NativeWindowMac::GetTitle() {
  785. return base::SysNSStringToUTF8([window_ title]);
  786. }
  787. void NativeWindowMac::FlashFrame(bool flash) {
  788. if (flash) {
  789. attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest];
  790. } else {
  791. [NSApp cancelUserAttentionRequest:attention_request_id_];
  792. attention_request_id_ = 0;
  793. }
  794. }
  795. void NativeWindowMac::SetSkipTaskbar(bool skip) {}
  796. void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) {
  797. NSWindow* window = GetNativeWindow().GetNativeNSWindow();
  798. if (simple_fullscreen && !is_simple_fullscreen_) {
  799. is_simple_fullscreen_ = true;
  800. // Take note of the current window size and level
  801. if (IsNormal()) {
  802. original_frame_ = [window_ frame];
  803. original_level_ = [window_ level];
  804. }
  805. simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions];
  806. simple_fullscreen_mask_ = [window styleMask];
  807. // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu
  808. // bar
  809. NSApplicationPresentationOptions options =
  810. NSApplicationPresentationAutoHideDock +
  811. NSApplicationPresentationAutoHideMenuBar;
  812. [NSApp setPresentationOptions:options];
  813. was_maximizable_ = IsMaximizable();
  814. was_movable_ = IsMovable();
  815. NSRect fullscreenFrame = [window.screen frame];
  816. // If our app has dock hidden, set the window level higher so another app's
  817. // menu bar doesn't appear on top of our fullscreen app.
  818. if ([[NSRunningApplication currentApplication] activationPolicy] !=
  819. NSApplicationActivationPolicyRegular) {
  820. window.level = NSPopUpMenuWindowLevel;
  821. }
  822. if (!fullscreen_window_title()) {
  823. // Hide the titlebar
  824. SetStyleMask(false, NSWindowStyleMaskTitled);
  825. // Resize the window to accomodate the _entire_ screen size
  826. fullscreenFrame.size.height -=
  827. [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
  828. } else if (!window_button_visibility_.has_value()) {
  829. // Lets keep previous behaviour - hide window controls in titled
  830. // fullscreen mode when not specified otherwise.
  831. [[window standardWindowButton:NSWindowZoomButton] setHidden:YES];
  832. [[window standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];
  833. [[window standardWindowButton:NSWindowCloseButton] setHidden:YES];
  834. }
  835. [window setFrame:fullscreenFrame display:YES animate:YES];
  836. // Fullscreen windows can't be resized, minimized, maximized, or moved
  837. SetMinimizable(false);
  838. SetResizable(false);
  839. SetMaximizable(false);
  840. SetMovable(false);
  841. } else if (!simple_fullscreen && is_simple_fullscreen_) {
  842. is_simple_fullscreen_ = false;
  843. if (!fullscreen_window_title()) {
  844. // Restore the titlebar
  845. SetStyleMask(true, NSWindowStyleMaskTitled);
  846. }
  847. // Restore window controls visibility state
  848. const bool window_button_hidden = !window_button_visibility_.value_or(true);
  849. [[window standardWindowButton:NSWindowZoomButton]
  850. setHidden:window_button_hidden];
  851. [[window standardWindowButton:NSWindowMiniaturizeButton]
  852. setHidden:window_button_hidden];
  853. [[window standardWindowButton:NSWindowCloseButton]
  854. setHidden:window_button_hidden];
  855. [window setFrame:original_frame_ display:YES animate:YES];
  856. window.level = original_level_;
  857. [NSApp setPresentationOptions:simple_fullscreen_options_];
  858. // Restore original style mask
  859. ScopedDisableResize disable_resize;
  860. [window_ setStyleMask:simple_fullscreen_mask_];
  861. // Restore window manipulation abilities
  862. SetMaximizable(was_maximizable_);
  863. SetMovable(was_movable_);
  864. }
  865. }
  866. bool NativeWindowMac::IsSimpleFullScreen() {
  867. return is_simple_fullscreen_;
  868. }
  869. void NativeWindowMac::SetKiosk(bool kiosk) {
  870. if (kiosk && !is_kiosk_) {
  871. kiosk_options_ = [NSApp currentSystemPresentationOptions];
  872. NSApplicationPresentationOptions options =
  873. NSApplicationPresentationHideDock +
  874. NSApplicationPresentationHideMenuBar +
  875. NSApplicationPresentationDisableAppleMenu +
  876. NSApplicationPresentationDisableProcessSwitching +
  877. NSApplicationPresentationDisableForceQuit +
  878. NSApplicationPresentationDisableSessionTermination +
  879. NSApplicationPresentationDisableHideApplication;
  880. [NSApp setPresentationOptions:options];
  881. is_kiosk_ = true;
  882. was_fullscreen_ = IsFullscreen();
  883. if (!was_fullscreen_)
  884. SetFullScreen(true);
  885. } else if (!kiosk && is_kiosk_) {
  886. is_kiosk_ = false;
  887. if (!was_fullscreen_)
  888. SetFullScreen(false);
  889. [NSApp setPresentationOptions:kiosk_options_];
  890. }
  891. }
  892. bool NativeWindowMac::IsKiosk() {
  893. return is_kiosk_;
  894. }
  895. void NativeWindowMac::SetBackgroundColor(SkColor color) {
  896. base::ScopedCFTypeRef<CGColorRef> cgcolor(
  897. skia::CGColorCreateFromSkColor(color));
  898. [[[window_ contentView] layer] setBackgroundColor:cgcolor];
  899. }
  900. void NativeWindowMac::SetHasShadow(bool has_shadow) {
  901. [window_ setHasShadow:has_shadow];
  902. }
  903. bool NativeWindowMac::HasShadow() {
  904. return [window_ hasShadow];
  905. }
  906. void NativeWindowMac::SetOpacity(const double opacity) {
  907. const double boundedOpacity = base::ClampToRange(opacity, 0.0, 1.0);
  908. [window_ setAlphaValue:boundedOpacity];
  909. }
  910. double NativeWindowMac::GetOpacity() {
  911. return [window_ alphaValue];
  912. }
  913. void NativeWindowMac::SetRepresentedFilename(const std::string& filename) {
  914. [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)];
  915. }
  916. std::string NativeWindowMac::GetRepresentedFilename() {
  917. return base::SysNSStringToUTF8([window_ representedFilename]);
  918. }
  919. void NativeWindowMac::SetDocumentEdited(bool edited) {
  920. [window_ setDocumentEdited:edited];
  921. }
  922. bool NativeWindowMac::IsDocumentEdited() {
  923. return [window_ isDocumentEdited];
  924. }
  925. void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) {
  926. [window_ setIgnoresMouseEvents:ignore];
  927. if (!ignore) {
  928. SetForwardMouseMessages(NO);
  929. } else {
  930. SetForwardMouseMessages(forward);
  931. }
  932. }
  933. void NativeWindowMac::SetContentProtection(bool enable) {
  934. [window_
  935. setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly];
  936. }
  937. void NativeWindowMac::AddBrowserView(NativeBrowserView* view) {
  938. [CATransaction begin];
  939. [CATransaction setDisableActions:YES];
  940. if (!view) {
  941. [CATransaction commit];
  942. return;
  943. }
  944. add_browser_view(view);
  945. auto* native_view =
  946. view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView();
  947. [[window_ contentView] addSubview:native_view
  948. positioned:NSWindowAbove
  949. relativeTo:nil];
  950. native_view.hidden = NO;
  951. [CATransaction commit];
  952. }
  953. void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) {
  954. [CATransaction begin];
  955. [CATransaction setDisableActions:YES];
  956. if (!view) {
  957. [CATransaction commit];
  958. return;
  959. }
  960. [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView()
  961. removeFromSuperview];
  962. remove_browser_view(view);
  963. [CATransaction commit];
  964. }
  965. void NativeWindowMac::SetParentWindow(NativeWindow* parent) {
  966. InternalSetParentWindow(parent, IsVisible());
  967. }
  968. gfx::NativeView NativeWindowMac::GetNativeView() const {
  969. return [window_ contentView];
  970. }
  971. gfx::NativeWindow NativeWindowMac::GetNativeWindow() const {
  972. return window_;
  973. }
  974. gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const {
  975. return gfx::kNullAcceleratedWidget;
  976. }
  977. NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const {
  978. return [window_ contentView];
  979. }
  980. void NativeWindowMac::SetProgressBar(double progress,
  981. const NativeWindow::ProgressState state) {
  982. NSDockTile* dock_tile = [NSApp dockTile];
  983. // Sometimes macOS would install a default contentView for dock, we must
  984. // verify whether NSProgressIndicator has been installed.
  985. bool first_time = !dock_tile.contentView ||
  986. [[dock_tile.contentView subviews] count] == 0 ||
  987. ![[[dock_tile.contentView subviews] lastObject]
  988. isKindOfClass:[NSProgressIndicator class]];
  989. // For the first time API invoked, we need to create a ContentView in
  990. // DockTile.
  991. if (first_time) {
  992. NSImageView* image_view = [[[NSImageView alloc] init] autorelease];
  993. [image_view setImage:[NSApp applicationIconImage]];
  994. [dock_tile setContentView:image_view];
  995. NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0);
  996. NSProgressIndicator* progress_indicator =
  997. [[[AtomProgressBar alloc] initWithFrame:frame] autorelease];
  998. [progress_indicator setStyle:NSProgressIndicatorBarStyle];
  999. [progress_indicator setIndeterminate:NO];
  1000. [progress_indicator setBezeled:YES];
  1001. [progress_indicator setMinValue:0];
  1002. [progress_indicator setMaxValue:1];
  1003. [progress_indicator setHidden:NO];
  1004. [dock_tile.contentView addSubview:progress_indicator];
  1005. }
  1006. NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>(
  1007. [[[dock_tile contentView] subviews] lastObject]);
  1008. if (progress < 0) {
  1009. [progress_indicator setHidden:YES];
  1010. } else if (progress > 1) {
  1011. [progress_indicator setHidden:NO];
  1012. [progress_indicator setIndeterminate:YES];
  1013. [progress_indicator setDoubleValue:1];
  1014. } else {
  1015. [progress_indicator setHidden:NO];
  1016. [progress_indicator setDoubleValue:progress];
  1017. }
  1018. [dock_tile display];
  1019. }
  1020. void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay,
  1021. const std::string& description) {}
  1022. void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible,
  1023. bool visibleOnFullScreen) {
  1024. SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces);
  1025. SetCollectionBehavior(visibleOnFullScreen,
  1026. NSWindowCollectionBehaviorFullScreenAuxiliary);
  1027. }
  1028. bool NativeWindowMac::IsVisibleOnAllWorkspaces() {
  1029. NSUInteger collectionBehavior = [window_ collectionBehavior];
  1030. return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces;
  1031. }
  1032. void NativeWindowMac::SetAutoHideCursor(bool auto_hide) {
  1033. [window_ setDisableAutoHideCursor:!auto_hide];
  1034. }
  1035. void NativeWindowMac::SelectPreviousTab() {
  1036. if (@available(macOS 10.12, *)) {
  1037. [window_ selectPreviousTab:nil];
  1038. }
  1039. }
  1040. void NativeWindowMac::SelectNextTab() {
  1041. if (@available(macOS 10.12, *)) {
  1042. [window_ selectNextTab:nil];
  1043. }
  1044. }
  1045. void NativeWindowMac::MergeAllWindows() {
  1046. if (@available(macOS 10.12, *)) {
  1047. [window_ mergeAllWindows:nil];
  1048. }
  1049. }
  1050. void NativeWindowMac::MoveTabToNewWindow() {
  1051. if (@available(macOS 10.12, *)) {
  1052. [window_ moveTabToNewWindow:nil];
  1053. }
  1054. }
  1055. void NativeWindowMac::ToggleTabBar() {
  1056. if (@available(macOS 10.12, *)) {
  1057. [window_ toggleTabBar:nil];
  1058. }
  1059. }
  1060. bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) {
  1061. if (window_ == window->GetNativeWindow().GetNativeNSWindow()) {
  1062. return false;
  1063. } else {
  1064. if (@available(macOS 10.12, *))
  1065. [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow()
  1066. ordered:NSWindowAbove];
  1067. }
  1068. return true;
  1069. }
  1070. bool NativeWindowMac::SetWindowButtonVisibility(bool visible) {
  1071. if (title_bar_style_ == CUSTOM_BUTTONS_ON_HOVER) {
  1072. return false;
  1073. }
  1074. window_button_visibility_ = visible;
  1075. [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible];
  1076. [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible];
  1077. [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible];
  1078. return true;
  1079. }
  1080. void NativeWindowMac::SetVibrancy(const std::string& type) {
  1081. NSView* vibrant_view = [window_ vibrantView];
  1082. if (type.empty()) {
  1083. if (background_color_before_vibrancy_) {
  1084. [window_ setBackgroundColor:background_color_before_vibrancy_];
  1085. [window_ setTitlebarAppearsTransparent:transparency_before_vibrancy_];
  1086. }
  1087. if (vibrant_view == nil)
  1088. return;
  1089. [vibrant_view removeFromSuperview];
  1090. [window_ setVibrantView:nil];
  1091. return;
  1092. }
  1093. background_color_before_vibrancy_.reset([[window_ backgroundColor] retain]);
  1094. transparency_before_vibrancy_ = [window_ titlebarAppearsTransparent];
  1095. if (title_bar_style_ != NORMAL) {
  1096. [window_ setTitlebarAppearsTransparent:YES];
  1097. [window_ setBackgroundColor:[NSColor clearColor]];
  1098. }
  1099. NSVisualEffectView* effect_view = (NSVisualEffectView*)vibrant_view;
  1100. if (effect_view == nil) {
  1101. effect_view = [[[NSVisualEffectView alloc]
  1102. initWithFrame:[[window_ contentView] bounds]] autorelease];
  1103. [window_ setVibrantView:(NSView*)effect_view];
  1104. [effect_view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
  1105. [effect_view setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
  1106. [effect_view setState:NSVisualEffectStateActive];
  1107. [[window_ contentView] addSubview:effect_view
  1108. positioned:NSWindowBelow
  1109. relativeTo:nil];
  1110. }
  1111. NSVisualEffectMaterial vibrancyType = NSVisualEffectMaterialLight;
  1112. if (type == "appearance-based") {
  1113. vibrancyType = NSVisualEffectMaterialAppearanceBased;
  1114. } else if (type == "light") {
  1115. vibrancyType = NSVisualEffectMaterialLight;
  1116. } else if (type == "dark") {
  1117. vibrancyType = NSVisualEffectMaterialDark;
  1118. } else if (type == "titlebar") {
  1119. vibrancyType = NSVisualEffectMaterialTitlebar;
  1120. }
  1121. if (@available(macOS 10.11, *)) {
  1122. // TODO(kevinsawicki): Use NSVisualEffectMaterial* constants directly once
  1123. // they are available in the minimum SDK version
  1124. if (type == "selection") {
  1125. // NSVisualEffectMaterialSelection
  1126. vibrancyType = static_cast<NSVisualEffectMaterial>(4);
  1127. } else if (type == "menu") {
  1128. // NSVisualEffectMaterialMenu
  1129. vibrancyType = static_cast<NSVisualEffectMaterial>(5);
  1130. } else if (type == "popover") {
  1131. // NSVisualEffectMaterialPopover
  1132. vibrancyType = static_cast<NSVisualEffectMaterial>(6);
  1133. } else if (type == "sidebar") {
  1134. // NSVisualEffectMaterialSidebar
  1135. vibrancyType = static_cast<NSVisualEffectMaterial>(7);
  1136. } else if (type == "medium-light") {
  1137. // NSVisualEffectMaterialMediumLight
  1138. vibrancyType = static_cast<NSVisualEffectMaterial>(8);
  1139. } else if (type == "ultra-dark") {
  1140. // NSVisualEffectMaterialUltraDark
  1141. vibrancyType = static_cast<NSVisualEffectMaterial>(9);
  1142. }
  1143. }
  1144. [effect_view setMaterial:vibrancyType];
  1145. }
  1146. void NativeWindowMac::SetTouchBar(
  1147. const std::vector<mate::PersistentDictionary>& items) {
  1148. if (@available(macOS 10.12.2, *)) {
  1149. touch_bar_.reset([[AtomTouchBar alloc]
  1150. initWithDelegate:window_delegate_.get()
  1151. window:this
  1152. settings:items]);
  1153. [window_ setTouchBar:nil];
  1154. }
  1155. }
  1156. void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) {
  1157. if (@available(macOS 10.12.2, *)) {
  1158. if (touch_bar_ && [window_ touchBar])
  1159. [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id];
  1160. }
  1161. }
  1162. void NativeWindowMac::SetEscapeTouchBarItem(
  1163. const mate::PersistentDictionary& item) {
  1164. if (@available(macOS 10.12.2, *)) {
  1165. if (touch_bar_ && [window_ touchBar])
  1166. [touch_bar_ setEscapeTouchBarItem:item forTouchBar:[window_ touchBar]];
  1167. }
  1168. }
  1169. gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds(
  1170. const gfx::Rect& bounds) const {
  1171. if (has_frame()) {
  1172. gfx::Rect window_bounds(
  1173. [window_ frameRectForContentRect:bounds.ToCGRect()]);
  1174. int frame_height = window_bounds.height() - bounds.height();
  1175. window_bounds.set_y(window_bounds.y() - frame_height);
  1176. return window_bounds;
  1177. } else {
  1178. return bounds;
  1179. }
  1180. }
  1181. gfx::Rect NativeWindowMac::WindowBoundsToContentBounds(
  1182. const gfx::Rect& bounds) const {
  1183. if (has_frame()) {
  1184. gfx::Rect content_bounds(
  1185. [window_ contentRectForFrameRect:bounds.ToCGRect()]);
  1186. int frame_height = bounds.height() - content_bounds.height();
  1187. content_bounds.set_y(content_bounds.y() + frame_height);
  1188. return content_bounds;
  1189. } else {
  1190. return bounds;
  1191. }
  1192. }
  1193. bool NativeWindowMac::CanResize() const {
  1194. return resizable_;
  1195. }
  1196. views::View* NativeWindowMac::GetContentsView() {
  1197. return root_view_.get();
  1198. }
  1199. void NativeWindowMac::AddContentViewLayers(bool minimizable, bool closable) {
  1200. // Make sure the bottom corner is rounded for non-modal windows:
  1201. // http://crbug.com/396264.
  1202. if (!is_modal()) {
  1203. // For normal window, we need to explicitly set layer for contentView to
  1204. // make setBackgroundColor work correctly.
  1205. // There is no need to do so for frameless window, and doing so would make
  1206. // titleBarStyle stop working.
  1207. if (has_frame()) {
  1208. base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]);
  1209. [background_layer
  1210. setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable];
  1211. [[window_ contentView] setLayer:background_layer];
  1212. }
  1213. [[window_ contentView] setWantsLayer:YES];
  1214. }
  1215. if (!has_frame()) {
  1216. // In OSX 10.10, adding subviews to the root view for the NSView hierarchy
  1217. // produces warnings. To eliminate the warnings, we resize the contentView
  1218. // to fill the window, and add subviews to that.
  1219. // http://crbug.com/380412
  1220. if (!original_set_frame_size) {
  1221. Class cl = [[window_ contentView] class];
  1222. original_set_frame_size = class_replaceMethod(
  1223. cl, @selector(setFrameSize:), (IMP)SetFrameSize, "v@:{_NSSize=ff}");
  1224. original_view_did_move_to_superview =
  1225. class_replaceMethod(cl, @selector(viewDidMoveToSuperview),
  1226. (IMP)ViewDidMoveToSuperview, "v@:");
  1227. [[window_ contentView] viewDidMoveToWindow];
  1228. }
  1229. // The fullscreen button should always be hidden for frameless window.
  1230. [[window_ standardWindowButton:NSWindowFullScreenButton] setHidden:YES];
  1231. if (title_bar_style_ == CUSTOM_BUTTONS_ON_HOVER) {
  1232. buttons_view_.reset(
  1233. [[CustomWindowButtonView alloc] initWithFrame:NSZeroRect]);
  1234. // NSWindowStyleMaskFullSizeContentView does not work with zoom button
  1235. SetFullScreenable(false);
  1236. if (!minimizable)
  1237. [[buttons_view_ viewWithTag:2] removeFromSuperview];
  1238. if (!closable)
  1239. [[buttons_view_ viewWithTag:1] removeFromSuperview];
  1240. [[window_ contentView] addSubview:buttons_view_];
  1241. } else {
  1242. if (title_bar_style_ != NORMAL)
  1243. return;
  1244. // Hide the window buttons.
  1245. [[window_ standardWindowButton:NSWindowZoomButton] setHidden:YES];
  1246. [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];
  1247. [[window_ standardWindowButton:NSWindowCloseButton] setHidden:YES];
  1248. }
  1249. // Some third-party macOS utilities check the zoom button's enabled state to
  1250. // determine whether to show custom UI on hover, so we disable it here to
  1251. // prevent them from doing so in a frameless app window.
  1252. [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:NO];
  1253. }
  1254. }
  1255. void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent,
  1256. bool attach) {
  1257. if (is_modal())
  1258. return;
  1259. NativeWindow::SetParentWindow(parent);
  1260. // Do not remove/add if we are already properly attached.
  1261. if (attach && parent &&
  1262. [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow())
  1263. return;
  1264. // Remove current parent window.
  1265. if ([window_ parentWindow])
  1266. [[window_ parentWindow] removeChildWindow:window_];
  1267. // Set new parent window.
  1268. // Note that this method will force the window to become visible.
  1269. if (parent && attach)
  1270. [parent->GetNativeWindow().GetNativeNSWindow()
  1271. addChildWindow:window_
  1272. ordered:NSWindowAbove];
  1273. }
  1274. void NativeWindowMac::SetForwardMouseMessages(bool forward) {
  1275. [window_ setAcceptsMouseMovedEvents:forward];
  1276. }
  1277. void NativeWindowMac::OverrideNSWindowContentView() {
  1278. // When using `views::Widget` to hold WebContents, Chromium would use
  1279. // `BridgedContentView` as content view, which does not support draggable
  1280. // regions. In order to make draggable regions work, we have to replace the
  1281. // content view with a simple NSView.
  1282. if (has_frame()) {
  1283. container_view_.reset(
  1284. [[ElectronAdapatedContentView alloc] initWithShell:this]);
  1285. } else {
  1286. container_view_.reset([[FullSizeContentView alloc] init]);
  1287. [container_view_ setFrame:[[[window_ contentView] superview] bounds]];
  1288. }
  1289. [container_view_
  1290. setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
  1291. [window_ setContentView:container_view_];
  1292. AddContentViewLayers(IsMinimizable(), IsClosable());
  1293. }
  1294. void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) {
  1295. // Changing the styleMask of a frameless windows causes it to change size so
  1296. // we explicitly disable resizing while setting it.
  1297. ScopedDisableResize disable_resize;
  1298. bool was_maximizable = IsMaximizable();
  1299. if (on)
  1300. [window_ setStyleMask:[window_ styleMask] | flag];
  1301. else
  1302. [window_ setStyleMask:[window_ styleMask] & (~flag)];
  1303. // Change style mask will make the zoom button revert to default, probably
  1304. // a bug of Cocoa or macOS.
  1305. SetMaximizable(was_maximizable);
  1306. }
  1307. void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) {
  1308. bool was_maximizable = IsMaximizable();
  1309. if (on)
  1310. [window_ setCollectionBehavior:[window_ collectionBehavior] | flag];
  1311. else
  1312. [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)];
  1313. // Change collectionBehavior will make the zoom button revert to default,
  1314. // probably a bug of Cocoa or macOS.
  1315. SetMaximizable(was_maximizable);
  1316. }
  1317. // static
  1318. NativeWindow* NativeWindow::Create(const mate::Dictionary& options,
  1319. NativeWindow* parent) {
  1320. return new NativeWindowMac(options, parent);
  1321. }
  1322. } // namespace atom