native_window_mac.mm 49 KB

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