native_window_mac.mm 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522
  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. bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible;
  489. // For a window to be visible, it must be visible to the user in the
  490. // foreground of the app, which means that it should not be minimized or
  491. // occluded
  492. return [window_ isVisible] && !occluded && !IsMinimized();
  493. }
  494. bool NativeWindowMac::IsEnabled() {
  495. return [window_ attachedSheet] == nil;
  496. }
  497. void NativeWindowMac::SetEnabled(bool enable) {
  498. if (enable) {
  499. [window_ endSheet:[window_ attachedSheet]];
  500. } else {
  501. [window_ beginSheet:window_
  502. completionHandler:^(NSModalResponse returnCode) {
  503. NSLog(@"modal enabled");
  504. return;
  505. }];
  506. }
  507. }
  508. void NativeWindowMac::Maximize() {
  509. if (IsMaximized())
  510. return;
  511. // Take note of the current window size
  512. if (IsNormal())
  513. original_frame_ = [window_ frame];
  514. [window_ zoom:nil];
  515. }
  516. void NativeWindowMac::Unmaximize() {
  517. if (!IsMaximized())
  518. return;
  519. [window_ zoom:nil];
  520. }
  521. bool NativeWindowMac::IsMaximized() {
  522. if (([window_ styleMask] & NSWindowStyleMaskResizable) != 0) {
  523. return [window_ isZoomed];
  524. } else {
  525. NSRect rectScreen = [[NSScreen mainScreen] visibleFrame];
  526. NSRect rectWindow = [window_ frame];
  527. return (rectScreen.origin.x == rectWindow.origin.x &&
  528. rectScreen.origin.y == rectWindow.origin.y &&
  529. rectScreen.size.width == rectWindow.size.width &&
  530. rectScreen.size.height == rectWindow.size.height);
  531. }
  532. }
  533. void NativeWindowMac::Minimize() {
  534. if (IsMinimized())
  535. return;
  536. // Take note of the current window size
  537. if (IsNormal())
  538. original_frame_ = [window_ frame];
  539. [window_ miniaturize:nil];
  540. }
  541. void NativeWindowMac::Restore() {
  542. [window_ deminiaturize:nil];
  543. }
  544. bool NativeWindowMac::IsMinimized() {
  545. return [window_ isMiniaturized];
  546. }
  547. void NativeWindowMac::SetFullScreen(bool fullscreen) {
  548. if (fullscreen == IsFullscreen())
  549. return;
  550. // Take note of the current window size
  551. if (IsNormal())
  552. original_frame_ = [window_ frame];
  553. [window_ toggleFullScreenMode:nil];
  554. }
  555. bool NativeWindowMac::IsFullscreen() const {
  556. return [window_ styleMask] & NSWindowStyleMaskFullScreen;
  557. }
  558. void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) {
  559. // Do nothing if in fullscreen mode.
  560. if (IsFullscreen())
  561. return;
  562. // Check size constraints since setFrame does not check it.
  563. gfx::Size size = bounds.size();
  564. size.SetToMax(GetMinimumSize());
  565. gfx::Size max_size = GetMaximumSize();
  566. if (!max_size.IsEmpty())
  567. size.SetToMin(max_size);
  568. NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height());
  569. // Flip coordinates based on the primary screen.
  570. NSScreen* screen = [[NSScreen screens] firstObject];
  571. cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y();
  572. [window_ setFrame:cocoa_bounds display:YES animate:animate];
  573. }
  574. gfx::Rect NativeWindowMac::GetBounds() {
  575. NSRect frame = [window_ frame];
  576. gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
  577. NSScreen* screen = [[NSScreen screens] firstObject];
  578. bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
  579. return bounds;
  580. }
  581. bool NativeWindowMac::IsNormal() {
  582. return NativeWindow::IsNormal() && !IsSimpleFullScreen();
  583. }
  584. gfx::Rect NativeWindowMac::GetNormalBounds() {
  585. if (IsNormal()) {
  586. return GetBounds();
  587. }
  588. NSRect frame = original_frame_;
  589. gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
  590. NSScreen* screen = [[NSScreen screens] firstObject];
  591. bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
  592. return bounds;
  593. // Works on OS_WIN !
  594. // return widget()->GetRestoredBounds();
  595. }
  596. void NativeWindowMac::SetContentSizeConstraints(
  597. const extensions::SizeConstraints& size_constraints) {
  598. auto convertSize = [this](const gfx::Size& size) {
  599. // Our frameless window still has titlebar attached, so setting contentSize
  600. // will result in actual content size being larger.
  601. if (!has_frame()) {
  602. NSRect frame = NSMakeRect(0, 0, size.width(), size.height());
  603. NSRect content = [window_ originalContentRectForFrameRect:frame];
  604. return content.size;
  605. } else {
  606. return NSMakeSize(size.width(), size.height());
  607. }
  608. };
  609. NSView* content = [window_ contentView];
  610. if (size_constraints.HasMinimumSize()) {
  611. NSSize min_size = convertSize(size_constraints.GetMinimumSize());
  612. [window_ setContentMinSize:[content convertSize:min_size toView:nil]];
  613. }
  614. if (size_constraints.HasMaximumSize()) {
  615. NSSize max_size = convertSize(size_constraints.GetMaximumSize());
  616. [window_ setContentMaxSize:[content convertSize:max_size toView:nil]];
  617. }
  618. NativeWindow::SetContentSizeConstraints(size_constraints);
  619. }
  620. void NativeWindowMac::MoveTop() {
  621. [window_ orderWindow:NSWindowAbove relativeTo:0];
  622. }
  623. void NativeWindowMac::SetResizable(bool resizable) {
  624. SetStyleMask(resizable, NSWindowStyleMaskResizable);
  625. }
  626. bool NativeWindowMac::IsResizable() {
  627. return [window_ styleMask] & NSWindowStyleMaskResizable;
  628. }
  629. void NativeWindowMac::SetAspectRatio(double aspect_ratio,
  630. const gfx::Size& extra_size) {
  631. NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
  632. // Reset the behaviour to default if aspect_ratio is set to 0 or less.
  633. if (aspect_ratio > 0.0)
  634. [window_ setAspectRatio:NSMakeSize(aspect_ratio, 1.0)];
  635. else
  636. [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)];
  637. }
  638. void NativeWindowMac::PreviewFile(const std::string& path,
  639. const std::string& display_name) {
  640. preview_item_.reset([[AtomPreviewItem alloc]
  641. initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)]
  642. title:base::SysUTF8ToNSString(display_name)]);
  643. [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
  644. }
  645. void NativeWindowMac::CloseFilePreview() {
  646. if ([QLPreviewPanel sharedPreviewPanelExists]) {
  647. [[QLPreviewPanel sharedPreviewPanel] close];
  648. }
  649. }
  650. void NativeWindowMac::SetMovable(bool movable) {
  651. [window_ setMovable:movable];
  652. }
  653. bool NativeWindowMac::IsMovable() {
  654. return [window_ isMovable];
  655. }
  656. void NativeWindowMac::SetMinimizable(bool minimizable) {
  657. SetStyleMask(minimizable, NSMiniaturizableWindowMask);
  658. }
  659. bool NativeWindowMac::IsMinimizable() {
  660. return [window_ styleMask] & NSMiniaturizableWindowMask;
  661. }
  662. void NativeWindowMac::SetMaximizable(bool maximizable) {
  663. [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable];
  664. }
  665. bool NativeWindowMac::IsMaximizable() {
  666. return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled];
  667. }
  668. void NativeWindowMac::SetFullScreenable(bool fullscreenable) {
  669. SetCollectionBehavior(fullscreenable,
  670. NSWindowCollectionBehaviorFullScreenPrimary);
  671. // On EL Capitan this flag is required to hide fullscreen button.
  672. SetCollectionBehavior(!fullscreenable,
  673. NSWindowCollectionBehaviorFullScreenAuxiliary);
  674. }
  675. bool NativeWindowMac::IsFullScreenable() {
  676. NSUInteger collectionBehavior = [window_ collectionBehavior];
  677. return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary;
  678. }
  679. void NativeWindowMac::SetClosable(bool closable) {
  680. SetStyleMask(closable, NSWindowStyleMaskClosable);
  681. }
  682. bool NativeWindowMac::IsClosable() {
  683. return [window_ styleMask] & NSWindowStyleMaskClosable;
  684. }
  685. void NativeWindowMac::SetAlwaysOnTop(bool top,
  686. const std::string& level,
  687. int relativeLevel,
  688. std::string* error) {
  689. int windowLevel = NSNormalWindowLevel;
  690. CGWindowLevel maxWindowLevel = CGWindowLevelForKey(kCGMaximumWindowLevelKey);
  691. CGWindowLevel minWindowLevel = CGWindowLevelForKey(kCGMinimumWindowLevelKey);
  692. if (top) {
  693. if (level == "floating") {
  694. windowLevel = NSFloatingWindowLevel;
  695. } else if (level == "torn-off-menu") {
  696. windowLevel = NSTornOffMenuWindowLevel;
  697. } else if (level == "modal-panel") {
  698. windowLevel = NSModalPanelWindowLevel;
  699. } else if (level == "main-menu") {
  700. windowLevel = NSMainMenuWindowLevel;
  701. } else if (level == "status") {
  702. windowLevel = NSStatusWindowLevel;
  703. } else if (level == "pop-up-menu") {
  704. windowLevel = NSPopUpMenuWindowLevel;
  705. } else if (level == "screen-saver") {
  706. windowLevel = NSScreenSaverWindowLevel;
  707. } else if (level == "dock") {
  708. // Deprecated by macOS, but kept for backwards compatibility
  709. windowLevel = NSDockWindowLevel;
  710. }
  711. }
  712. NSInteger newLevel = windowLevel + relativeLevel;
  713. if (newLevel >= minWindowLevel && newLevel <= maxWindowLevel) {
  714. [window_ setLevel:newLevel];
  715. } else {
  716. *error = std::string([
  717. [NSString stringWithFormat:@"relativeLevel must be between %d and %d",
  718. minWindowLevel, maxWindowLevel] UTF8String]);
  719. }
  720. }
  721. bool NativeWindowMac::IsAlwaysOnTop() {
  722. return [window_ level] != NSNormalWindowLevel;
  723. }
  724. void NativeWindowMac::Center() {
  725. [window_ center];
  726. }
  727. void NativeWindowMac::Invalidate() {
  728. [window_ flushWindow];
  729. [[window_ contentView] setNeedsDisplay:YES];
  730. }
  731. void NativeWindowMac::SetTitle(const std::string& title) {
  732. // For macOS <= 10.9, the setTitleVisibility API is not available, we have
  733. // to avoid calling setTitle for frameless window.
  734. if (!base::mac::IsAtLeastOS10_10() && (transparent() || !has_frame()))
  735. return;
  736. [window_ setTitle:base::SysUTF8ToNSString(title)];
  737. }
  738. std::string NativeWindowMac::GetTitle() {
  739. return base::SysNSStringToUTF8([window_ title]);
  740. ;
  741. }
  742. void NativeWindowMac::FlashFrame(bool flash) {
  743. if (flash) {
  744. attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest];
  745. } else {
  746. [NSApp cancelUserAttentionRequest:attention_request_id_];
  747. attention_request_id_ = 0;
  748. }
  749. }
  750. void NativeWindowMac::SetSkipTaskbar(bool skip) {}
  751. void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) {
  752. NSWindow* window = GetNativeWindow();
  753. if (simple_fullscreen && !is_simple_fullscreen_) {
  754. is_simple_fullscreen_ = true;
  755. // Take note of the current window size and level
  756. if (IsNormal()) {
  757. original_frame_ = [window_ frame];
  758. original_level_ = [window_ level];
  759. }
  760. simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions];
  761. simple_fullscreen_mask_ = [window styleMask];
  762. // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu
  763. // bar
  764. NSApplicationPresentationOptions options =
  765. NSApplicationPresentationAutoHideDock +
  766. NSApplicationPresentationAutoHideMenuBar;
  767. [NSApp setPresentationOptions:options];
  768. was_maximizable_ = IsMaximizable();
  769. was_movable_ = IsMovable();
  770. NSRect fullscreenFrame = [window.screen frame];
  771. // If our app has dock hidden, set the window level higher so another app's
  772. // menu bar doesn't appear on top of our fullscreen app.
  773. if ([[NSRunningApplication currentApplication] activationPolicy] !=
  774. NSApplicationActivationPolicyRegular) {
  775. window.level = NSPopUpMenuWindowLevel;
  776. }
  777. if (!fullscreen_window_title()) {
  778. // Hide the titlebar
  779. SetStyleMask(false, NSWindowStyleMaskTitled);
  780. // Resize the window to accomodate the _entire_ screen size
  781. fullscreenFrame.size.height -=
  782. [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
  783. } else if (!window_button_visibility_.has_value()) {
  784. // Lets keep previous behaviour - hide window controls in titled
  785. // fullscreen mode when not specified otherwise.
  786. [[window standardWindowButton:NSWindowZoomButton] setHidden:YES];
  787. [[window standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];
  788. [[window standardWindowButton:NSWindowCloseButton] setHidden:YES];
  789. }
  790. [window setFrame:fullscreenFrame display:YES animate:YES];
  791. // Fullscreen windows can't be resized, minimized, maximized, or moved
  792. SetMinimizable(false);
  793. SetResizable(false);
  794. SetMaximizable(false);
  795. SetMovable(false);
  796. } else if (!simple_fullscreen && is_simple_fullscreen_) {
  797. is_simple_fullscreen_ = false;
  798. if (!fullscreen_window_title()) {
  799. // Restore the titlebar
  800. SetStyleMask(true, NSWindowStyleMaskTitled);
  801. }
  802. // Restore window controls visibility state
  803. const bool window_button_hidden = !window_button_visibility_.value_or(true);
  804. [[window standardWindowButton:NSWindowZoomButton]
  805. setHidden:window_button_hidden];
  806. [[window standardWindowButton:NSWindowMiniaturizeButton]
  807. setHidden:window_button_hidden];
  808. [[window standardWindowButton:NSWindowCloseButton]
  809. setHidden:window_button_hidden];
  810. [window setFrame:original_frame_ display:YES animate:YES];
  811. window.level = original_level_;
  812. [NSApp setPresentationOptions:simple_fullscreen_options_];
  813. // Restore original style mask
  814. ScopedDisableResize disable_resize;
  815. [window_ setStyleMask:simple_fullscreen_mask_];
  816. // Restore window manipulation abilities
  817. SetMaximizable(was_maximizable_);
  818. SetMovable(was_movable_);
  819. }
  820. }
  821. bool NativeWindowMac::IsSimpleFullScreen() {
  822. return is_simple_fullscreen_;
  823. }
  824. void NativeWindowMac::SetKiosk(bool kiosk) {
  825. if (kiosk && !is_kiosk_) {
  826. kiosk_options_ = [NSApp currentSystemPresentationOptions];
  827. NSApplicationPresentationOptions options =
  828. NSApplicationPresentationHideDock +
  829. NSApplicationPresentationHideMenuBar +
  830. NSApplicationPresentationDisableAppleMenu +
  831. NSApplicationPresentationDisableProcessSwitching +
  832. NSApplicationPresentationDisableForceQuit +
  833. NSApplicationPresentationDisableSessionTermination +
  834. NSApplicationPresentationDisableHideApplication;
  835. [NSApp setPresentationOptions:options];
  836. is_kiosk_ = true;
  837. was_fullscreen_ = IsFullscreen();
  838. if (!was_fullscreen_)
  839. SetFullScreen(true);
  840. } else if (!kiosk && is_kiosk_) {
  841. is_kiosk_ = false;
  842. if (!was_fullscreen_)
  843. SetFullScreen(false);
  844. [NSApp setPresentationOptions:kiosk_options_];
  845. }
  846. }
  847. bool NativeWindowMac::IsKiosk() {
  848. return is_kiosk_;
  849. }
  850. void NativeWindowMac::SetBackgroundColor(SkColor color) {
  851. base::ScopedCFTypeRef<CGColorRef> cgcolor(
  852. skia::CGColorCreateFromSkColor(color));
  853. [[[window_ contentView] layer] setBackgroundColor:cgcolor];
  854. }
  855. void NativeWindowMac::SetHasShadow(bool has_shadow) {
  856. [window_ setHasShadow:has_shadow];
  857. }
  858. bool NativeWindowMac::HasShadow() {
  859. return [window_ hasShadow];
  860. }
  861. void NativeWindowMac::SetOpacity(const double opacity) {
  862. [window_ setAlphaValue:opacity];
  863. }
  864. double NativeWindowMac::GetOpacity() {
  865. return [window_ alphaValue];
  866. }
  867. void NativeWindowMac::SetRepresentedFilename(const std::string& filename) {
  868. [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)];
  869. }
  870. std::string NativeWindowMac::GetRepresentedFilename() {
  871. return base::SysNSStringToUTF8([window_ representedFilename]);
  872. }
  873. void NativeWindowMac::SetDocumentEdited(bool edited) {
  874. [window_ setDocumentEdited:edited];
  875. }
  876. bool NativeWindowMac::IsDocumentEdited() {
  877. return [window_ isDocumentEdited];
  878. }
  879. void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) {
  880. [window_ setIgnoresMouseEvents:ignore];
  881. if (!ignore) {
  882. SetForwardMouseMessages(NO);
  883. } else {
  884. SetForwardMouseMessages(forward);
  885. }
  886. }
  887. void NativeWindowMac::SetContentProtection(bool enable) {
  888. [window_
  889. setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly];
  890. }
  891. void NativeWindowMac::SetBrowserView(NativeBrowserView* view) {
  892. [CATransaction begin];
  893. [CATransaction setDisableActions:YES];
  894. if (browser_view()) {
  895. [browser_view()->GetInspectableWebContentsView()->GetNativeView()
  896. removeFromSuperview];
  897. set_browser_view(nullptr);
  898. }
  899. if (!view) {
  900. [CATransaction commit];
  901. return;
  902. }
  903. set_browser_view(view);
  904. auto* native_view = view->GetInspectableWebContentsView()->GetNativeView();
  905. [[window_ contentView] addSubview:native_view
  906. positioned:NSWindowAbove
  907. relativeTo:nil];
  908. native_view.hidden = NO;
  909. [CATransaction commit];
  910. }
  911. void NativeWindowMac::SetParentWindow(NativeWindow* parent) {
  912. InternalSetParentWindow(parent, IsVisible());
  913. }
  914. gfx::NativeView NativeWindowMac::GetNativeView() const {
  915. return [window_ contentView];
  916. }
  917. gfx::NativeWindow NativeWindowMac::GetNativeWindow() const {
  918. return window_;
  919. }
  920. gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const {
  921. return gfx::kNullAcceleratedWidget;
  922. }
  923. NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const {
  924. return [window_ contentView];
  925. }
  926. void NativeWindowMac::SetProgressBar(double progress,
  927. const NativeWindow::ProgressState state) {
  928. NSDockTile* dock_tile = [NSApp dockTile];
  929. // Sometimes macOS would install a default contentView for dock, we must
  930. // verify whether NSProgressIndicator has been installed.
  931. bool first_time = !dock_tile.contentView ||
  932. [[dock_tile.contentView subviews] count] == 0 ||
  933. ![[[dock_tile.contentView subviews] lastObject]
  934. isKindOfClass:[NSProgressIndicator class]];
  935. // For the first time API invoked, we need to create a ContentView in
  936. // DockTile.
  937. if (first_time) {
  938. NSImageView* image_view = [[[NSImageView alloc] init] autorelease];
  939. [image_view setImage:[NSApp applicationIconImage]];
  940. [dock_tile setContentView:image_view];
  941. NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0);
  942. NSProgressIndicator* progress_indicator =
  943. [[[AtomProgressBar alloc] initWithFrame:frame] autorelease];
  944. [progress_indicator setStyle:NSProgressIndicatorBarStyle];
  945. [progress_indicator setIndeterminate:NO];
  946. [progress_indicator setBezeled:YES];
  947. [progress_indicator setMinValue:0];
  948. [progress_indicator setMaxValue:1];
  949. [progress_indicator setHidden:NO];
  950. [dock_tile.contentView addSubview:progress_indicator];
  951. }
  952. NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>(
  953. [[[dock_tile contentView] subviews] lastObject]);
  954. if (progress < 0) {
  955. [progress_indicator setHidden:YES];
  956. } else if (progress > 1) {
  957. [progress_indicator setHidden:NO];
  958. [progress_indicator setIndeterminate:YES];
  959. [progress_indicator setDoubleValue:1];
  960. } else {
  961. [progress_indicator setHidden:NO];
  962. [progress_indicator setDoubleValue:progress];
  963. }
  964. [dock_tile display];
  965. }
  966. void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay,
  967. const std::string& description) {}
  968. void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible,
  969. bool visibleOnFullScreen) {
  970. SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces);
  971. SetCollectionBehavior(visibleOnFullScreen,
  972. NSWindowCollectionBehaviorFullScreenAuxiliary);
  973. }
  974. bool NativeWindowMac::IsVisibleOnAllWorkspaces() {
  975. NSUInteger collectionBehavior = [window_ collectionBehavior];
  976. return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces;
  977. }
  978. void NativeWindowMac::SetAutoHideCursor(bool auto_hide) {
  979. [window_ setDisableAutoHideCursor:!auto_hide];
  980. }
  981. void NativeWindowMac::SelectPreviousTab() {
  982. if (@available(macOS 10.12, *)) {
  983. [window_ selectPreviousTab:nil];
  984. }
  985. }
  986. void NativeWindowMac::SelectNextTab() {
  987. if (@available(macOS 10.12, *)) {
  988. [window_ selectNextTab:nil];
  989. }
  990. }
  991. void NativeWindowMac::MergeAllWindows() {
  992. if (@available(macOS 10.12, *)) {
  993. [window_ mergeAllWindows:nil];
  994. }
  995. }
  996. void NativeWindowMac::MoveTabToNewWindow() {
  997. if (@available(macOS 10.12, *)) {
  998. [window_ moveTabToNewWindow:nil];
  999. }
  1000. }
  1001. void NativeWindowMac::ToggleTabBar() {
  1002. if (@available(macOS 10.12, *)) {
  1003. [window_ toggleTabBar:nil];
  1004. }
  1005. }
  1006. bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) {
  1007. if (window_ == window->GetNativeWindow()) {
  1008. return false;
  1009. } else {
  1010. if (@available(macOS 10.12, *))
  1011. [window_ addTabbedWindow:window->GetNativeWindow() ordered:NSWindowAbove];
  1012. }
  1013. return true;
  1014. }
  1015. bool NativeWindowMac::SetWindowButtonVisibility(bool visible) {
  1016. if (title_bar_style_ == CUSTOM_BUTTONS_ON_HOVER) {
  1017. return false;
  1018. }
  1019. window_button_visibility_ = visible;
  1020. [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible];
  1021. [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible];
  1022. [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible];
  1023. return true;
  1024. }
  1025. void NativeWindowMac::SetVibrancy(const std::string& type) {
  1026. if (@available(macOS 10.10, *)) {
  1027. NSView* vibrant_view = [window_ vibrantView];
  1028. if (type.empty()) {
  1029. if (background_color_before_vibrancy_) {
  1030. [window_ setBackgroundColor:background_color_before_vibrancy_];
  1031. [window_ setTitlebarAppearsTransparent:transparency_before_vibrancy_];
  1032. }
  1033. if (vibrant_view == nil)
  1034. return;
  1035. [vibrant_view removeFromSuperview];
  1036. [window_ setVibrantView:nil];
  1037. ui::GpuSwitchingManager::SetTransparent(transparent());
  1038. return;
  1039. }
  1040. background_color_before_vibrancy_.reset([[window_ backgroundColor] retain]);
  1041. transparency_before_vibrancy_ = [window_ titlebarAppearsTransparent];
  1042. ui::GpuSwitchingManager::SetTransparent(true);
  1043. if (title_bar_style_ != NORMAL) {
  1044. [window_ setTitlebarAppearsTransparent:YES];
  1045. [window_ setBackgroundColor:[NSColor clearColor]];
  1046. }
  1047. NSVisualEffectView* effect_view = (NSVisualEffectView*)vibrant_view;
  1048. if (effect_view == nil) {
  1049. effect_view = [[[NSVisualEffectView alloc]
  1050. initWithFrame:[[window_ contentView] bounds]] autorelease];
  1051. [window_ setVibrantView:(NSView*)effect_view];
  1052. [effect_view
  1053. setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
  1054. [effect_view setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
  1055. [effect_view setState:NSVisualEffectStateActive];
  1056. [[window_ contentView] addSubview:effect_view
  1057. positioned:NSWindowBelow
  1058. relativeTo:nil];
  1059. }
  1060. NSVisualEffectMaterial vibrancyType = NSVisualEffectMaterialLight;
  1061. if (type == "appearance-based") {
  1062. vibrancyType = NSVisualEffectMaterialAppearanceBased;
  1063. } else if (type == "light") {
  1064. vibrancyType = NSVisualEffectMaterialLight;
  1065. } else if (type == "dark") {
  1066. vibrancyType = NSVisualEffectMaterialDark;
  1067. } else if (type == "titlebar") {
  1068. vibrancyType = NSVisualEffectMaterialTitlebar;
  1069. }
  1070. if (@available(macOS 10.11, *)) {
  1071. // TODO(kevinsawicki): Use NSVisualEffectMaterial* constants directly once
  1072. // they are available in the minimum SDK version
  1073. if (type == "selection") {
  1074. // NSVisualEffectMaterialSelection
  1075. vibrancyType = static_cast<NSVisualEffectMaterial>(4);
  1076. } else if (type == "menu") {
  1077. // NSVisualEffectMaterialMenu
  1078. vibrancyType = static_cast<NSVisualEffectMaterial>(5);
  1079. } else if (type == "popover") {
  1080. // NSVisualEffectMaterialPopover
  1081. vibrancyType = static_cast<NSVisualEffectMaterial>(6);
  1082. } else if (type == "sidebar") {
  1083. // NSVisualEffectMaterialSidebar
  1084. vibrancyType = static_cast<NSVisualEffectMaterial>(7);
  1085. } else if (type == "medium-light") {
  1086. // NSVisualEffectMaterialMediumLight
  1087. vibrancyType = static_cast<NSVisualEffectMaterial>(8);
  1088. } else if (type == "ultra-dark") {
  1089. // NSVisualEffectMaterialUltraDark
  1090. vibrancyType = static_cast<NSVisualEffectMaterial>(9);
  1091. }
  1092. }
  1093. [effect_view setMaterial:vibrancyType];
  1094. }
  1095. }
  1096. void NativeWindowMac::SetTouchBar(
  1097. const std::vector<mate::PersistentDictionary>& items) {
  1098. if (@available(macOS 10.12.2, *)) {
  1099. touch_bar_.reset([[AtomTouchBar alloc]
  1100. initWithDelegate:window_delegate_.get()
  1101. window:this
  1102. settings:items]);
  1103. [window_ setTouchBar:nil];
  1104. }
  1105. }
  1106. void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) {
  1107. if (@available(macOS 10.12.2, *)) {
  1108. if (touch_bar_ && [window_ touchBar])
  1109. [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id];
  1110. }
  1111. }
  1112. void NativeWindowMac::SetEscapeTouchBarItem(
  1113. const mate::PersistentDictionary& item) {
  1114. if (@available(macOS 10.12.2, *)) {
  1115. if (touch_bar_ && [window_ touchBar])
  1116. [touch_bar_ setEscapeTouchBarItem:item forTouchBar:[window_ touchBar]];
  1117. }
  1118. }
  1119. gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds(
  1120. const gfx::Rect& bounds) const {
  1121. if (has_frame()) {
  1122. gfx::Rect window_bounds(
  1123. [window_ frameRectForContentRect:bounds.ToCGRect()]);
  1124. int frame_height = window_bounds.height() - bounds.height();
  1125. window_bounds.set_y(window_bounds.y() - frame_height);
  1126. return window_bounds;
  1127. } else {
  1128. return bounds;
  1129. }
  1130. }
  1131. gfx::Rect NativeWindowMac::WindowBoundsToContentBounds(
  1132. const gfx::Rect& bounds) const {
  1133. if (has_frame()) {
  1134. gfx::Rect content_bounds(
  1135. [window_ contentRectForFrameRect:bounds.ToCGRect()]);
  1136. int frame_height = bounds.height() - content_bounds.height();
  1137. content_bounds.set_y(content_bounds.y() + frame_height);
  1138. return content_bounds;
  1139. } else {
  1140. return bounds;
  1141. }
  1142. }
  1143. bool NativeWindowMac::CanResize() const {
  1144. return resizable_;
  1145. }
  1146. views::View* NativeWindowMac::GetContentsView() {
  1147. return root_view_.get();
  1148. }
  1149. void NativeWindowMac::AddContentViewLayers() {
  1150. // Make sure the bottom corner is rounded for non-modal windows:
  1151. // http://crbug.com/396264. But do not enable it on OS X 10.9 for transparent
  1152. // window, otherwise a semi-transparent frame would show.
  1153. if (!(transparent() && base::mac::IsOS10_9()) && !is_modal()) {
  1154. // For normal window, we need to explicitly set layer for contentView to
  1155. // make setBackgroundColor work correctly.
  1156. // There is no need to do so for frameless window, and doing so would make
  1157. // titleBarStyle stop working.
  1158. if (has_frame()) {
  1159. base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]);
  1160. [background_layer
  1161. setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable];
  1162. [[window_ contentView] setLayer:background_layer];
  1163. }
  1164. [[window_ contentView] setWantsLayer:YES];
  1165. }
  1166. if (!has_frame()) {
  1167. // In OSX 10.10, adding subviews to the root view for the NSView hierarchy
  1168. // produces warnings. To eliminate the warnings, we resize the contentView
  1169. // to fill the window, and add subviews to that.
  1170. // http://crbug.com/380412
  1171. if (!original_set_frame_size) {
  1172. Class cl = [[window_ contentView] class];
  1173. original_set_frame_size = class_replaceMethod(
  1174. cl, @selector(setFrameSize:), (IMP)SetFrameSize, "v@:{_NSSize=ff}");
  1175. original_view_did_move_to_superview =
  1176. class_replaceMethod(cl, @selector(viewDidMoveToSuperview),
  1177. (IMP)ViewDidMoveToSuperview, "v@:");
  1178. [[window_ contentView] viewDidMoveToWindow];
  1179. }
  1180. // The fullscreen button should always be hidden for frameless window.
  1181. [[window_ standardWindowButton:NSWindowFullScreenButton] setHidden:YES];
  1182. if (title_bar_style_ == CUSTOM_BUTTONS_ON_HOVER) {
  1183. buttons_view_.reset(
  1184. [[CustomWindowButtonView alloc] initWithFrame:NSZeroRect]);
  1185. // NSWindowStyleMaskFullSizeContentView does not work with zoom button
  1186. SetFullScreenable(false);
  1187. [[window_ contentView] addSubview:buttons_view_];
  1188. } else {
  1189. if (title_bar_style_ != NORMAL) {
  1190. if (base::mac::IsOS10_9()) {
  1191. ShowWindowButton(NSWindowZoomButton);
  1192. ShowWindowButton(NSWindowMiniaturizeButton);
  1193. ShowWindowButton(NSWindowCloseButton);
  1194. }
  1195. return;
  1196. }
  1197. // Hide the window buttons.
  1198. [[window_ standardWindowButton:NSWindowZoomButton] setHidden:YES];
  1199. [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];
  1200. [[window_ standardWindowButton:NSWindowCloseButton] setHidden:YES];
  1201. }
  1202. // Some third-party macOS utilities check the zoom button's enabled state to
  1203. // determine whether to show custom UI on hover, so we disable it here to
  1204. // prevent them from doing so in a frameless app window.
  1205. [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:NO];
  1206. }
  1207. }
  1208. void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent,
  1209. bool attach) {
  1210. if (is_modal())
  1211. return;
  1212. NativeWindow::SetParentWindow(parent);
  1213. // Do not remove/add if we are already properly attached.
  1214. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow())
  1215. return;
  1216. // Remove current parent window.
  1217. if ([window_ parentWindow])
  1218. [[window_ parentWindow] removeChildWindow:window_];
  1219. // Set new parent window.
  1220. // Note that this method will force the window to become visible.
  1221. if (parent && attach)
  1222. [parent->GetNativeWindow() addChildWindow:window_ ordered:NSWindowAbove];
  1223. }
  1224. void NativeWindowMac::ShowWindowButton(NSWindowButton button) {
  1225. auto view = [window_ standardWindowButton:button];
  1226. [view.superview addSubview:view positioned:NSWindowAbove relativeTo:nil];
  1227. }
  1228. void NativeWindowMac::SetForwardMouseMessages(bool forward) {
  1229. [window_ setAcceptsMouseMovedEvents:forward];
  1230. }
  1231. void NativeWindowMac::OverrideNSWindowContentView() {
  1232. // When using `views::Widget` to hold WebContents, Chromium would use
  1233. // `BridgedContentView` as content view, which does not support draggable
  1234. // regions. In order to make draggable regions work, we have to replace the
  1235. // content view with a simple NSView.
  1236. container_view_.reset([[FullSizeContentView alloc] init]);
  1237. [container_view_
  1238. setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
  1239. [container_view_ setFrame:[[[window_ contentView] superview] bounds]];
  1240. [window_ setContentView:container_view_];
  1241. AddContentViewLayers();
  1242. }
  1243. void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) {
  1244. // Changing the styleMask of a frameless windows causes it to change size so
  1245. // we explicitly disable resizing while setting it.
  1246. ScopedDisableResize disable_resize;
  1247. bool was_maximizable = IsMaximizable();
  1248. if (on)
  1249. [window_ setStyleMask:[window_ styleMask] | flag];
  1250. else
  1251. [window_ setStyleMask:[window_ styleMask] & (~flag)];
  1252. // Change style mask will make the zoom button revert to default, probably
  1253. // a bug of Cocoa or macOS.
  1254. SetMaximizable(was_maximizable);
  1255. }
  1256. void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) {
  1257. bool was_maximizable = IsMaximizable();
  1258. if (on)
  1259. [window_ setCollectionBehavior:[window_ collectionBehavior] | flag];
  1260. else
  1261. [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)];
  1262. // Change collectionBehavior will make the zoom button revert to default,
  1263. // probably a bug of Cocoa or macOS.
  1264. SetMaximizable(was_maximizable);
  1265. }
  1266. // static
  1267. NativeWindow* NativeWindow::Create(const mate::Dictionary& options,
  1268. NativeWindow* parent) {
  1269. return new NativeWindowMac(options, parent);
  1270. }
  1271. } // namespace atom