native_window_mac.mm 51 KB

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