native_window_mac.mm 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688
  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 <Quartz/Quartz.h>
  6. #include <string>
  7. #include "atom/browser/native_browser_view_mac.h"
  8. #include "atom/browser/ui/cocoa/atom_touch_bar.h"
  9. #include "atom/browser/window_list.h"
  10. #include "atom/common/color_util.h"
  11. #include "atom/common/draggable_region.h"
  12. #include "atom/common/options_switches.h"
  13. #include "base/mac/mac_util.h"
  14. #include "base/mac/scoped_cftyperef.h"
  15. #include "base/strings/sys_string_conversions.h"
  16. #include "brightray/browser/inspectable_web_contents.h"
  17. #include "brightray/browser/inspectable_web_contents_view.h"
  18. #include "brightray/browser/mac/event_dispatching_window.h"
  19. #include "content/public/browser/browser_accessibility_state.h"
  20. #include "content/public/browser/render_view_host.h"
  21. #include "content/public/browser/render_widget_host_view.h"
  22. #include "content/public/browser/web_contents.h"
  23. #include "native_mate/dictionary.h"
  24. #include "skia/ext/skia_utils_mac.h"
  25. #include "third_party/skia/include/core/SkRegion.h"
  26. #include "ui/gfx/skia_util.h"
  27. namespace {
  28. // Prevents window from resizing during the scope.
  29. class ScopedDisableResize {
  30. public:
  31. ScopedDisableResize() { disable_resize_ = true; }
  32. ~ScopedDisableResize() { disable_resize_ = false; }
  33. static bool IsResizeDisabled() { return disable_resize_; }
  34. private:
  35. static bool disable_resize_;
  36. };
  37. bool ScopedDisableResize::disable_resize_ = false;
  38. } // namespace
  39. // This view always takes the size of its superview. It is intended to be used
  40. // as a NSWindow's contentView. It is needed because NSWindow's implementation
  41. // explicitly resizes the contentView at inopportune times.
  42. @interface FullSizeContentView : NSView
  43. @end
  44. @implementation FullSizeContentView
  45. // This method is directly called by NSWindow during a window resize on OSX
  46. // 10.10.0, beta 2. We must override it to prevent the content view from
  47. // shrinking.
  48. - (void)setFrameSize:(NSSize)size {
  49. if ([self superview])
  50. size = [[self superview] bounds].size;
  51. [super setFrameSize:size];
  52. }
  53. // The contentView gets moved around during certain full-screen operations.
  54. // This is less than ideal, and should eventually be removed.
  55. - (void)viewDidMoveToSuperview {
  56. [self setFrame:[[self superview] bounds]];
  57. }
  58. @end
  59. @interface AtomNSWindowDelegate : NSObject<NSWindowDelegate> {
  60. @private
  61. atom::NativeWindowMac* shell_;
  62. bool is_zooming_;
  63. }
  64. - (id)initWithShell:(atom::NativeWindowMac*)shell;
  65. @end
  66. @implementation AtomNSWindowDelegate
  67. - (id)initWithShell:(atom::NativeWindowMac*)shell {
  68. if ((self = [super init])) {
  69. shell_ = shell;
  70. is_zooming_ = false;
  71. }
  72. return self;
  73. }
  74. - (void)windowDidChangeOcclusionState:(NSNotification *)notification {
  75. // notification.object is the window that changed its state.
  76. // It's safe to use self.window instead if you don't assign one delegate to many windows
  77. NSWindow *window = notification.object;
  78. // check occlusion binary flag
  79. if (window.occlusionState & NSWindowOcclusionStateVisible) {
  80. // The app is visible
  81. shell_->NotifyWindowShow();
  82. } else {
  83. // The app is not visible
  84. shell_->NotifyWindowHide();
  85. }
  86. }
  87. // Called when the user clicks the zoom button or selects it from the Window
  88. // menu to determine the "standard size" of the window.
  89. - (NSRect)windowWillUseStandardFrame:(NSWindow*)window
  90. defaultFrame:(NSRect)frame {
  91. if (!shell_->zoom_to_page_width())
  92. return frame;
  93. // If the shift key is down, maximize.
  94. if ([[NSApp currentEvent] modifierFlags] & NSShiftKeyMask)
  95. return frame;
  96. content::WebContents* web_contents = shell_->web_contents();
  97. if (!web_contents)
  98. return frame;
  99. CGFloat page_width = static_cast<CGFloat>(
  100. web_contents->GetPreferredSize().width());
  101. NSRect window_frame = [window frame];
  102. // Never shrink from the current size on zoom.
  103. CGFloat zoomed_width = std::max(page_width, NSWidth(window_frame));
  104. // |frame| determines our maximum extents. We need to set the origin of the
  105. // frame -- and only move it left if necessary.
  106. if (window_frame.origin.x + zoomed_width > NSMaxX(frame))
  107. frame.origin.x = NSMaxX(frame) - zoomed_width;
  108. else
  109. frame.origin.x = window_frame.origin.x;
  110. // Set the width. Don't touch y or height.
  111. frame.size.width = zoomed_width;
  112. return frame;
  113. }
  114. - (void)windowDidBecomeMain:(NSNotification*)notification {
  115. content::WebContents* web_contents = shell_->web_contents();
  116. if (!web_contents)
  117. return;
  118. web_contents->RestoreFocus();
  119. content::RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
  120. if (rwhv)
  121. rwhv->SetActive(true);
  122. shell_->NotifyWindowFocus();
  123. }
  124. - (void)windowDidResignMain:(NSNotification*)notification {
  125. content::WebContents* web_contents = shell_->web_contents();
  126. if (!web_contents)
  127. return;
  128. web_contents->StoreFocus();
  129. content::RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
  130. if (rwhv)
  131. rwhv->SetActive(false);
  132. shell_->NotifyWindowBlur();
  133. }
  134. - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)frameSize {
  135. NSSize newSize = frameSize;
  136. double aspectRatio = shell_->GetAspectRatio();
  137. if (aspectRatio > 0.0) {
  138. gfx::Size windowSize = shell_->GetSize();
  139. gfx::Size contentSize = shell_->GetContentSize();
  140. gfx::Size extraSize = shell_->GetAspectRatioExtraSize();
  141. double extraWidthPlusFrame =
  142. windowSize.width() - contentSize.width() + extraSize.width();
  143. double extraHeightPlusFrame =
  144. windowSize.height() - contentSize.height() + extraSize.height();
  145. newSize.width =
  146. roundf((frameSize.height - extraHeightPlusFrame) * aspectRatio +
  147. extraWidthPlusFrame);
  148. newSize.height =
  149. roundf((newSize.width - extraWidthPlusFrame) / aspectRatio +
  150. extraHeightPlusFrame);
  151. }
  152. return newSize;
  153. }
  154. - (void)windowDidResize:(NSNotification*)notification {
  155. shell_->UpdateDraggableRegionViews();
  156. shell_->NotifyWindowResize();
  157. }
  158. - (void)windowDidMove:(NSNotification*)notification {
  159. // TODO(zcbenz): Remove the alias after figuring out a proper
  160. // way to dispatch move.
  161. shell_->NotifyWindowMove();
  162. shell_->NotifyWindowMoved();
  163. }
  164. - (void)windowDidMiniaturize:(NSNotification*)notification {
  165. shell_->NotifyWindowMinimize();
  166. }
  167. - (void)windowDidDeminiaturize:(NSNotification*)notification {
  168. shell_->NotifyWindowRestore();
  169. }
  170. - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)newFrame {
  171. is_zooming_ = true;
  172. return YES;
  173. }
  174. - (void)windowDidEndLiveResize:(NSNotification*)notification {
  175. if (is_zooming_) {
  176. if (shell_->IsMaximized())
  177. shell_->NotifyWindowMaximize();
  178. else
  179. shell_->NotifyWindowUnmaximize();
  180. is_zooming_ = false;
  181. }
  182. }
  183. - (void)windowWillEnterFullScreen:(NSNotification*)notification {
  184. // Hide the native toolbar before entering fullscreen, so there is no visual
  185. // artifacts.
  186. if (base::mac::IsAtLeastOS10_10() &&
  187. shell_->title_bar_style() == atom::NativeWindowMac::HIDDEN_INSET) {
  188. NSWindow* window = shell_->GetNativeWindow();
  189. [window setToolbar:nil];
  190. }
  191. }
  192. - (void)windowDidEnterFullScreen:(NSNotification*)notification {
  193. shell_->NotifyWindowEnterFullScreen();
  194. // For frameless window we don't show set title for normal mode since the
  195. // titlebar is expected to be empty, but after entering fullscreen mode we
  196. // have to set one, because title bar is visible here.
  197. NSWindow* window = shell_->GetNativeWindow();
  198. if ((shell_->transparent() || !shell_->has_frame()) &&
  199. base::mac::IsAtLeastOS10_10() &&
  200. // FIXME(zcbenz): Showing titlebar for hiddenInset window is weird under
  201. // fullscreen mode.
  202. shell_->title_bar_style() != atom::NativeWindowMac::HIDDEN_INSET) {
  203. [window setTitleVisibility:NSWindowTitleVisible];
  204. }
  205. // Restore the native toolbar immediately after entering fullscreen, if we do
  206. // this before leaving fullscreen, traffic light buttons will be jumping.
  207. if (base::mac::IsAtLeastOS10_10() &&
  208. shell_->title_bar_style() == atom::NativeWindowMac::HIDDEN_INSET) {
  209. base::scoped_nsobject<NSToolbar> toolbar(
  210. [[NSToolbar alloc] initWithIdentifier:@"titlebarStylingToolbar"]);
  211. [toolbar setShowsBaselineSeparator:NO];
  212. [window setToolbar:toolbar];
  213. // Set window style to hide the toolbar, otherwise the toolbar will show in
  214. // fullscreen mode.
  215. shell_->SetStyleMask(true, NSFullSizeContentViewWindowMask);
  216. }
  217. }
  218. - (void)windowWillExitFullScreen:(NSNotification*)notification {
  219. // Restore the titlebar visibility.
  220. NSWindow* window = shell_->GetNativeWindow();
  221. if ((shell_->transparent() || !shell_->has_frame()) &&
  222. base::mac::IsAtLeastOS10_10() &&
  223. shell_->title_bar_style() != atom::NativeWindowMac::HIDDEN_INSET) {
  224. [window setTitleVisibility:NSWindowTitleHidden];
  225. }
  226. // Turn off the style for toolbar.
  227. if (base::mac::IsAtLeastOS10_10() &&
  228. shell_->title_bar_style() == atom::NativeWindowMac::HIDDEN_INSET) {
  229. shell_->SetStyleMask(false, NSFullSizeContentViewWindowMask);
  230. }
  231. }
  232. - (void)windowDidExitFullScreen:(NSNotification*)notification {
  233. shell_->NotifyWindowLeaveFullScreen();
  234. }
  235. - (void)windowWillClose:(NSNotification*)notification {
  236. shell_->NotifyWindowClosed();
  237. // Clears the delegate when window is going to be closed, since EL Capitan it
  238. // is possible that the methods of delegate would get called after the window
  239. // has been closed.
  240. [shell_->GetNativeWindow() setDelegate:nil];
  241. }
  242. - (BOOL)windowShouldClose:(id)window {
  243. // When user tries to close the window by clicking the close button, we do
  244. // not close the window immediately, instead we try to close the web page
  245. // fisrt, and when the web page is closed the window will also be closed.
  246. shell_->RequestToClosePage();
  247. return NO;
  248. }
  249. - (NSRect)window:(NSWindow*)window
  250. willPositionSheet:(NSWindow*)sheet usingRect:(NSRect)rect {
  251. NSView* view = window.contentView;
  252. rect.origin.x = shell_->GetSheetOffsetX();
  253. rect.origin.y = view.frame.size.height - shell_->GetSheetOffsetY();
  254. return rect;
  255. }
  256. - (void)windowWillBeginSheet:(NSNotification *)notification {
  257. shell_->NotifyWindowSheetBegin();
  258. }
  259. - (void)windowDidEndSheet:(NSNotification *)notification {
  260. shell_->NotifyWindowSheetEnd();
  261. }
  262. @end
  263. @interface AtomPreviewItem : NSObject <QLPreviewItem>
  264. @property (nonatomic, retain) NSURL* previewItemURL;
  265. @property (nonatomic, retain) NSString* previewItemTitle;
  266. - (id)initWithURL:(NSURL*)url title:(NSString*)title;
  267. @end
  268. @implementation AtomPreviewItem
  269. - (id)initWithURL:(NSURL*)url title:(NSString*)title {
  270. self = [super init];
  271. if (self) {
  272. self.previewItemURL = url;
  273. self.previewItemTitle = title;
  274. }
  275. return self;
  276. }
  277. @end
  278. #if !defined(MAC_OS_X_VERSION_10_12)
  279. enum {
  280. NSWindowTabbingModeDisallowed = 2
  281. };
  282. @interface NSWindow (SierraSDK)
  283. - (void)setTabbingMode:(NSInteger)mode;
  284. - (void)setTabbingIdentifier:(NSString*)identifier;
  285. @end
  286. #endif // MAC_OS_X_VERSION_10_12
  287. @interface AtomNSWindow : EventDispatchingWindow<QLPreviewPanelDataSource, QLPreviewPanelDelegate, NSTouchBarDelegate> {
  288. @private
  289. atom::NativeWindowMac* shell_;
  290. bool enable_larger_than_screen_;
  291. base::scoped_nsobject<AtomTouchBar> atom_touch_bar_;
  292. CGFloat windowButtonsInterButtonSpacing_;
  293. }
  294. @property BOOL acceptsFirstMouse;
  295. @property BOOL disableAutoHideCursor;
  296. @property BOOL disableKeyOrMainWindow;
  297. @property NSPoint windowButtonsOffset;
  298. @property (nonatomic, retain) AtomPreviewItem* quickLookItem;
  299. @property (nonatomic, retain) NSView* vibrantView;
  300. - (void)setShell:(atom::NativeWindowMac*)shell;
  301. - (void)setEnableLargerThanScreen:(bool)enable;
  302. - (void)enableWindowButtonsOffset;
  303. - (void)resetTouchBar:(const std::vector<mate::PersistentDictionary>&)settings;
  304. - (void)refreshTouchBarItem:(const std::string&)item_id;
  305. - (void)setEscapeTouchBarItem:(const mate::PersistentDictionary&)item;
  306. @end
  307. @implementation AtomNSWindow
  308. - (void)setShell:(atom::NativeWindowMac*)shell {
  309. shell_ = shell;
  310. }
  311. - (void)setEnableLargerThanScreen:(bool)enable {
  312. enable_larger_than_screen_ = enable;
  313. }
  314. - (void)resetTouchBar:(const std::vector<mate::PersistentDictionary>&)settings {
  315. if (![self respondsToSelector:@selector(touchBar)]) return;
  316. atom_touch_bar_.reset([[AtomTouchBar alloc] initWithDelegate:self
  317. window:shell_
  318. settings:settings]);
  319. self.touchBar = nil;
  320. }
  321. - (void)refreshTouchBarItem:(const std::string&)item_id {
  322. if (atom_touch_bar_ && self.touchBar)
  323. [atom_touch_bar_ refreshTouchBarItem:self.touchBar id:item_id];
  324. }
  325. - (NSTouchBar*)makeTouchBar {
  326. if (atom_touch_bar_)
  327. return [atom_touch_bar_ makeTouchBar];
  328. else
  329. return nil;
  330. }
  331. - (NSTouchBarItem*)touchBar:(NSTouchBar*)touchBar
  332. makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier {
  333. if (touchBar && atom_touch_bar_)
  334. return [atom_touch_bar_ makeItemForIdentifier:identifier];
  335. else
  336. return nil;
  337. }
  338. - (void)setEscapeTouchBarItem:(const mate::PersistentDictionary&)item {
  339. if (atom_touch_bar_ && self.touchBar)
  340. [atom_touch_bar_ setEscapeTouchBarItem:item forTouchBar:self.touchBar];
  341. }
  342. // NSWindow overrides.
  343. - (void)swipeWithEvent:(NSEvent *)event {
  344. if (event.deltaY == 1.0) {
  345. shell_->NotifyWindowSwipe("up");
  346. } else if (event.deltaX == -1.0) {
  347. shell_->NotifyWindowSwipe("right");
  348. } else if (event.deltaY == -1.0) {
  349. shell_->NotifyWindowSwipe("down");
  350. } else if (event.deltaX == 1.0) {
  351. shell_->NotifyWindowSwipe("left");
  352. }
  353. }
  354. - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen*)screen {
  355. // Resizing is disabled.
  356. if (ScopedDisableResize::IsResizeDisabled())
  357. return [self frame];
  358. // Enable the window to be larger than screen.
  359. if (enable_larger_than_screen_)
  360. return frameRect;
  361. else
  362. return [super constrainFrameRect:frameRect toScreen:screen];
  363. }
  364. - (void)setFrame:(NSRect)windowFrame display:(BOOL)displayViews {
  365. // constrainFrameRect is not called on hidden windows so disable adjusting
  366. // the frame directly when resize is disabled
  367. if (!ScopedDisableResize::IsResizeDisabled())
  368. [super setFrame:windowFrame display:displayViews];
  369. }
  370. - (id)accessibilityAttributeValue:(NSString*)attribute {
  371. if (![attribute isEqualToString:@"AXChildren"])
  372. return [super accessibilityAttributeValue:attribute];
  373. // Filter out objects that aren't the title bar buttons. This has the effect
  374. // of removing the window title, which VoiceOver already sees.
  375. // * when VoiceOver is disabled, this causes Cmd+C to be used for TTS but
  376. // still leaves the buttons available in the accessibility tree.
  377. // * when VoiceOver is enabled, the full accessibility tree is used.
  378. // Without removing the title and with VO disabled, the TTS would always read
  379. // the window title instead of using Cmd+C to get the selected text.
  380. NSPredicate *predicate = [NSPredicate predicateWithFormat:
  381. @"(self isKindOfClass: %@) OR (self.className == %@)",
  382. [NSButtonCell class],
  383. @"RenderWidgetHostViewCocoa"];
  384. NSArray *children = [super accessibilityAttributeValue:attribute];
  385. return [children filteredArrayUsingPredicate:predicate];
  386. }
  387. - (BOOL)canBecomeMainWindow {
  388. return !self.disableKeyOrMainWindow;
  389. }
  390. - (BOOL)canBecomeKeyWindow {
  391. return !self.disableKeyOrMainWindow;
  392. }
  393. - (void)enableWindowButtonsOffset {
  394. auto closeButton = [self standardWindowButton:NSWindowCloseButton];
  395. auto miniaturizeButton = [self standardWindowButton:NSWindowMiniaturizeButton];
  396. auto zoomButton = [self standardWindowButton:NSWindowZoomButton];
  397. [closeButton setPostsFrameChangedNotifications:YES];
  398. [miniaturizeButton setPostsFrameChangedNotifications:YES];
  399. [zoomButton setPostsFrameChangedNotifications:YES];
  400. windowButtonsInterButtonSpacing_ =
  401. NSMinX([miniaturizeButton frame]) - NSMaxX([closeButton frame]);
  402. auto center = [NSNotificationCenter defaultCenter];
  403. [center addObserver:self
  404. selector:@selector(adjustCloseButton:)
  405. name:NSViewFrameDidChangeNotification
  406. object:closeButton];
  407. [center addObserver:self
  408. selector:@selector(adjustMiniaturizeButton:)
  409. name:NSViewFrameDidChangeNotification
  410. object:miniaturizeButton];
  411. [center addObserver:self
  412. selector:@selector(adjustZoomButton:)
  413. name:NSViewFrameDidChangeNotification
  414. object:zoomButton];
  415. }
  416. - (void)adjustCloseButton:(NSNotification*)notification {
  417. [self adjustButton:[notification object]
  418. ofKind:NSWindowCloseButton];
  419. }
  420. - (void)adjustMiniaturizeButton:(NSNotification*)notification {
  421. [self adjustButton:[notification object]
  422. ofKind:NSWindowMiniaturizeButton];
  423. }
  424. - (void)adjustZoomButton:(NSNotification*)notification {
  425. [self adjustButton:[notification object]
  426. ofKind:NSWindowZoomButton];
  427. }
  428. - (void)adjustButton:(NSButton*)button
  429. ofKind:(NSWindowButton)kind {
  430. NSRect buttonFrame = [button frame];
  431. NSRect frameViewBounds = [[self frameView] bounds];
  432. NSPoint offset = self.windowButtonsOffset;
  433. buttonFrame.origin = NSMakePoint(
  434. offset.x,
  435. (NSHeight(frameViewBounds) - NSHeight(buttonFrame) - offset.y));
  436. switch (kind) {
  437. case NSWindowZoomButton:
  438. buttonFrame.origin.x += NSWidth(
  439. [[self standardWindowButton:NSWindowMiniaturizeButton] frame]);
  440. buttonFrame.origin.x += windowButtonsInterButtonSpacing_;
  441. // fallthrough
  442. case NSWindowMiniaturizeButton:
  443. buttonFrame.origin.x += NSWidth(
  444. [[self standardWindowButton:NSWindowCloseButton] frame]);
  445. buttonFrame.origin.x += windowButtonsInterButtonSpacing_;
  446. // fallthrough
  447. default:
  448. break;
  449. }
  450. BOOL didPost = [button postsBoundsChangedNotifications];
  451. [button setPostsFrameChangedNotifications:NO];
  452. [button setFrame:buttonFrame];
  453. [button setPostsFrameChangedNotifications:didPost];
  454. }
  455. - (NSView*)frameView {
  456. return [[self contentView] superview];
  457. }
  458. // Quicklook methods
  459. - (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel*)panel {
  460. return YES;
  461. }
  462. - (void)beginPreviewPanelControl:(QLPreviewPanel*)panel {
  463. panel.delegate = self;
  464. panel.dataSource = self;
  465. }
  466. - (void)endPreviewPanelControl:(QLPreviewPanel*)panel {
  467. panel.delegate = nil;
  468. panel.dataSource = nil;
  469. }
  470. - (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel*)panel {
  471. return 1;
  472. }
  473. - (id <QLPreviewItem>)previewPanel:(QLPreviewPanel*)panel previewItemAtIndex:(NSInteger)index {
  474. return [self quickLookItem];
  475. }
  476. - (void)previewFileAtPath:(NSString*)path withName:(NSString*) fileName {
  477. NSURL* url = [[[NSURL alloc] initFileURLWithPath:path] autorelease];
  478. [self setQuickLookItem:[[[AtomPreviewItem alloc] initWithURL:url title:fileName] autorelease]];
  479. [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
  480. }
  481. @end
  482. @interface ControlRegionView : NSView
  483. @end
  484. @implementation ControlRegionView
  485. - (BOOL)mouseDownCanMoveWindow {
  486. return NO;
  487. }
  488. - (NSView*)hitTest:(NSPoint)aPoint {
  489. return nil;
  490. }
  491. @end
  492. @interface NSView (WebContentsView)
  493. - (void)setMouseDownCanMoveWindow:(BOOL)can_move;
  494. @end
  495. @interface AtomProgressBar : NSProgressIndicator
  496. @end
  497. @implementation AtomProgressBar
  498. - (void)drawRect:(NSRect)dirtyRect {
  499. if (self.style != NSProgressIndicatorBarStyle)
  500. return;
  501. // Draw edges of rounded rect.
  502. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0);
  503. CGFloat radius = rect.size.height / 2;
  504. NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius];
  505. [bezier_path setLineWidth:2.0];
  506. [[NSColor grayColor] set];
  507. [bezier_path stroke];
  508. // Fill the rounded rect.
  509. rect = NSInsetRect(rect, 2.0, 2.0);
  510. radius = rect.size.height / 2;
  511. bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius];
  512. [bezier_path setLineWidth:1.0];
  513. [bezier_path addClip];
  514. // Calculate the progress width.
  515. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue]));
  516. // Fill the progress bar with color blue.
  517. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set];
  518. NSRectFill(rect);
  519. }
  520. @end
  521. namespace mate {
  522. template<>
  523. struct Converter<atom::NativeWindowMac::TitleBarStyle> {
  524. static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val,
  525. atom::NativeWindowMac::TitleBarStyle* out) {
  526. std::string title_bar_style;
  527. if (!ConvertFromV8(isolate, val, &title_bar_style))
  528. return false;
  529. if (title_bar_style == "hidden") {
  530. *out = atom::NativeWindowMac::HIDDEN;
  531. } else if (title_bar_style == "hidden-inset" || // Deprecate this after 2.0
  532. title_bar_style == "hiddenInset") {
  533. *out = atom::NativeWindowMac::HIDDEN_INSET;
  534. } else {
  535. return false;
  536. }
  537. return true;
  538. }
  539. };
  540. } // namespace mate
  541. namespace atom {
  542. NativeWindowMac::NativeWindowMac(
  543. brightray::InspectableWebContents* web_contents,
  544. const mate::Dictionary& options,
  545. NativeWindow* parent)
  546. : NativeWindow(web_contents, options, parent),
  547. browser_view_(nullptr),
  548. is_kiosk_(false),
  549. was_fullscreen_(false),
  550. zoom_to_page_width_(false),
  551. attention_request_id_(0),
  552. title_bar_style_(NORMAL) {
  553. int width = 800, height = 600;
  554. options.Get(options::kWidth, &width);
  555. options.Get(options::kHeight, &height);
  556. NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame];
  557. NSRect cocoa_bounds = NSMakeRect(
  558. round((NSWidth(main_screen_rect) - width) / 2) ,
  559. round((NSHeight(main_screen_rect) - height) / 2),
  560. width,
  561. height);
  562. bool resizable = true;
  563. options.Get(options::kResizable, &resizable);
  564. bool minimizable = true;
  565. options.Get(options::kMinimizable, &minimizable);
  566. bool maximizable = true;
  567. options.Get(options::kMaximizable, &maximizable);
  568. bool closable = true;
  569. options.Get(options::kClosable, &closable);
  570. options.Get(options::kTitleBarStyle, &title_bar_style_);
  571. std::string tabbingIdentifier;
  572. options.Get(options::kTabbingIdentifier, &tabbingIdentifier);
  573. std::string windowType;
  574. options.Get(options::kType, &windowType);
  575. bool useStandardWindow = true;
  576. // eventually deprecate separate "standardWindow" option in favor of
  577. // standard / textured window types
  578. options.Get(options::kStandardWindow, &useStandardWindow);
  579. if (windowType == "textured") {
  580. useStandardWindow = false;
  581. }
  582. NSUInteger styleMask = NSTitledWindowMask;
  583. if (minimizable) {
  584. styleMask |= NSMiniaturizableWindowMask;
  585. }
  586. if (closable) {
  587. styleMask |= NSClosableWindowMask;
  588. }
  589. if (title_bar_style_ != NORMAL) {
  590. // The window without titlebar is treated the same with frameless window.
  591. set_has_frame(false);
  592. }
  593. if (!useStandardWindow || transparent() || !has_frame()) {
  594. styleMask |= NSTexturedBackgroundWindowMask;
  595. }
  596. if (resizable) {
  597. styleMask |= NSResizableWindowMask;
  598. }
  599. window_.reset([[AtomNSWindow alloc]
  600. initWithContentRect:cocoa_bounds
  601. styleMask:styleMask
  602. backing:NSBackingStoreBuffered
  603. defer:YES]);
  604. [window_ setShell:this];
  605. [window_ setEnableLargerThanScreen:enable_larger_than_screen()];
  606. window_delegate_.reset([[AtomNSWindowDelegate alloc] initWithShell:this]);
  607. [window_ setDelegate:window_delegate_];
  608. // Only use native parent window for non-modal windows.
  609. if (parent && !is_modal()) {
  610. SetParentWindow(parent);
  611. }
  612. if (transparent()) {
  613. // Setting the background color to clear will also hide the shadow.
  614. [window_ setBackgroundColor:[NSColor clearColor]];
  615. }
  616. if (windowType == "desktop") {
  617. [window_ setLevel:kCGDesktopWindowLevel - 1];
  618. [window_ setDisableKeyOrMainWindow:YES];
  619. [window_ setCollectionBehavior:
  620. (NSWindowCollectionBehaviorCanJoinAllSpaces |
  621. NSWindowCollectionBehaviorStationary |
  622. NSWindowCollectionBehaviorIgnoresCycle)];
  623. }
  624. bool focusable;
  625. if (options.Get(options::kFocusable, &focusable) && !focusable)
  626. [window_ setDisableKeyOrMainWindow:YES];
  627. if (transparent() || !has_frame()) {
  628. if (base::mac::IsAtLeastOS10_10()) {
  629. // Don't show title bar.
  630. [window_ setTitleVisibility:NSWindowTitleHidden];
  631. }
  632. // Remove non-transparent corners, see http://git.io/vfonD.
  633. [window_ setOpaque:NO];
  634. }
  635. // Create a tab only if tabbing identifier is specified and window has
  636. // a native title bar.
  637. if (tabbingIdentifier.empty() || transparent() || !has_frame()) {
  638. if ([window_ respondsToSelector:@selector(tabbingMode)]) {
  639. [window_ setTabbingMode:NSWindowTabbingModeDisallowed];
  640. }
  641. } else {
  642. if ([window_ respondsToSelector:@selector(tabbingIdentifier)]) {
  643. [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)];
  644. }
  645. }
  646. // We will manage window's lifetime ourselves.
  647. [window_ setReleasedWhenClosed:NO];
  648. // Hide the title bar.
  649. if (title_bar_style_ == HIDDEN_INSET) {
  650. if (base::mac::IsAtLeastOS10_10()) {
  651. [window_ setTitlebarAppearsTransparent:YES];
  652. base::scoped_nsobject<NSToolbar> toolbar(
  653. [[NSToolbar alloc] initWithIdentifier:@"titlebarStylingToolbar"]);
  654. [toolbar setShowsBaselineSeparator:NO];
  655. [window_ setToolbar:toolbar];
  656. } else {
  657. [window_ enableWindowButtonsOffset];
  658. [window_ setWindowButtonsOffset:NSMakePoint(12, 10)];
  659. }
  660. }
  661. // On macOS the initial window size doesn't include window frame.
  662. bool use_content_size = false;
  663. options.Get(options::kUseContentSize, &use_content_size);
  664. if (!has_frame() || !use_content_size)
  665. SetSize(gfx::Size(width, height));
  666. options.Get(options::kZoomToPageWidth, &zoom_to_page_width_);
  667. // Enable the NSView to accept first mouse event.
  668. bool acceptsFirstMouse = false;
  669. options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse);
  670. [window_ setAcceptsFirstMouse:acceptsFirstMouse];
  671. // Disable auto-hiding cursor.
  672. bool disableAutoHideCursor = false;
  673. options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor);
  674. [window_ setDisableAutoHideCursor:disableAutoHideCursor];
  675. NSView* view = inspectable_web_contents()->GetView()->GetNativeView();
  676. [view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
  677. // Use an NSEvent monitor to listen for the wheel event.
  678. BOOL __block began = NO;
  679. wheel_event_monitor_ = [NSEvent
  680. addLocalMonitorForEventsMatchingMask:NSScrollWheelMask
  681. handler:^(NSEvent* event) {
  682. if ([[event window] windowNumber] != [window_ windowNumber])
  683. return event;
  684. if (!web_contents)
  685. return event;
  686. if (!began && (([event phase] == NSEventPhaseMayBegin) ||
  687. ([event phase] == NSEventPhaseBegan))) {
  688. this->NotifyWindowScrollTouchBegin();
  689. began = YES;
  690. } else if (began && (([event phase] == NSEventPhaseEnded) ||
  691. ([event phase] == NSEventPhaseCancelled))) {
  692. this->NotifyWindowScrollTouchEnd();
  693. began = NO;
  694. }
  695. return event;
  696. }];
  697. InstallView();
  698. std::string type;
  699. if (options.Get(options::kVibrancyType, &type)) {
  700. SetVibrancy(type);
  701. }
  702. // Set maximizable state last to ensure zoom button does not get reset
  703. // by calls to other APIs.
  704. SetMaximizable(maximizable);
  705. RegisterInputEventObserver(
  706. web_contents->GetWebContents()->GetRenderViewHost());
  707. }
  708. NativeWindowMac::~NativeWindowMac() {
  709. [NSEvent removeMonitor:wheel_event_monitor_];
  710. Observe(nullptr);
  711. }
  712. void NativeWindowMac::Close() {
  713. // When this is a sheet showing, performClose won't work.
  714. if (is_modal() && parent() && IsVisible()) {
  715. [parent()->GetNativeWindow() endSheet:window_];
  716. CloseImmediately();
  717. return;
  718. }
  719. if (!IsClosable()) {
  720. WindowList::WindowCloseCancelled(this);
  721. return;
  722. }
  723. [window_ performClose:nil];
  724. }
  725. void NativeWindowMac::CloseImmediately() {
  726. [window_ close];
  727. }
  728. void NativeWindowMac::Focus(bool focus) {
  729. if (!IsVisible())
  730. return;
  731. if (focus) {
  732. [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
  733. [window_ makeKeyAndOrderFront:nil];
  734. } else {
  735. [window_ orderBack:nil];
  736. }
  737. }
  738. bool NativeWindowMac::IsFocused() {
  739. return [window_ isKeyWindow];
  740. }
  741. void NativeWindowMac::Show() {
  742. if (is_modal() && parent()) {
  743. if ([window_ sheetParent] == nil)
  744. [parent()->GetNativeWindow() beginSheet:window_
  745. completionHandler:^(NSModalResponse) {}];
  746. return;
  747. }
  748. // This method is supposed to put focus on window, however if the app does not
  749. // have focus then "makeKeyAndOrderFront" will only show the window.
  750. [NSApp activateIgnoringOtherApps:YES];
  751. [window_ makeKeyAndOrderFront:nil];
  752. }
  753. void NativeWindowMac::ShowInactive() {
  754. [window_ orderFrontRegardless];
  755. }
  756. void NativeWindowMac::Hide() {
  757. if (is_modal() && parent()) {
  758. [window_ orderOut:nil];
  759. [parent()->GetNativeWindow() endSheet:window_];
  760. return;
  761. }
  762. [window_ orderOut:nil];
  763. }
  764. bool NativeWindowMac::IsVisible() {
  765. return [window_ isVisible];
  766. }
  767. bool NativeWindowMac::IsEnabled() {
  768. return [window_ attachedSheet] == nil;
  769. }
  770. void NativeWindowMac::Maximize() {
  771. if (IsMaximized())
  772. return;
  773. [window_ zoom:nil];
  774. }
  775. void NativeWindowMac::Unmaximize() {
  776. if (!IsMaximized())
  777. return;
  778. [window_ zoom:nil];
  779. }
  780. bool NativeWindowMac::IsMaximized() {
  781. if (([window_ styleMask] & NSResizableWindowMask) != 0) {
  782. return [window_ isZoomed];
  783. } else {
  784. NSRect rectScreen = [[NSScreen mainScreen] visibleFrame];
  785. NSRect rectWindow = [window_ frame];
  786. return (rectScreen.origin.x == rectWindow.origin.x &&
  787. rectScreen.origin.y == rectWindow.origin.y &&
  788. rectScreen.size.width == rectWindow.size.width &&
  789. rectScreen.size.height == rectWindow.size.height);
  790. }
  791. }
  792. void NativeWindowMac::Minimize() {
  793. [window_ miniaturize:nil];
  794. }
  795. void NativeWindowMac::Restore() {
  796. [window_ deminiaturize:nil];
  797. }
  798. bool NativeWindowMac::IsMinimized() {
  799. return [window_ isMiniaturized];
  800. }
  801. void NativeWindowMac::SetFullScreen(bool fullscreen) {
  802. if (fullscreen == IsFullscreen())
  803. return;
  804. [window_ toggleFullScreen:nil];
  805. }
  806. bool NativeWindowMac::IsFullscreen() const {
  807. return [window_ styleMask] & NSFullScreenWindowMask;
  808. }
  809. void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) {
  810. // Do nothing if in fullscreen mode.
  811. if (IsFullscreen())
  812. return;
  813. // Check size constraints since setFrame does not check it.
  814. gfx::Size size = bounds.size();
  815. size.SetToMax(GetMinimumSize());
  816. gfx::Size max_size = GetMaximumSize();
  817. if (!max_size.IsEmpty())
  818. size.SetToMin(max_size);
  819. NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height());
  820. // Flip coordinates based on the primary screen.
  821. NSScreen* screen = [[NSScreen screens] firstObject];
  822. cocoa_bounds.origin.y =
  823. NSHeight([screen frame]) - size.height() - bounds.y();
  824. [window_ setFrame:cocoa_bounds display:YES animate:animate];
  825. }
  826. gfx::Rect NativeWindowMac::GetBounds() {
  827. NSRect frame = [window_ frame];
  828. gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
  829. NSScreen* screen = [[NSScreen screens] firstObject];
  830. bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
  831. return bounds;
  832. }
  833. void NativeWindowMac::SetContentSizeConstraints(
  834. const extensions::SizeConstraints& size_constraints) {
  835. auto convertSize = [this](const gfx::Size& size) {
  836. // Our frameless window still has titlebar attached, so setting contentSize
  837. // will result in actual content size being larger.
  838. if (!has_frame()) {
  839. NSRect frame = NSMakeRect(0, 0, size.width(), size.height());
  840. NSRect content = [window_ contentRectForFrameRect:frame];
  841. return content.size;
  842. } else {
  843. return NSMakeSize(size.width(), size.height());
  844. }
  845. };
  846. NSView* content = [window_ contentView];
  847. if (size_constraints.HasMinimumSize()) {
  848. NSSize min_size = convertSize(size_constraints.GetMinimumSize());
  849. [window_ setContentMinSize:[content convertSize:min_size toView:nil]];
  850. }
  851. if (size_constraints.HasMaximumSize()) {
  852. NSSize max_size = convertSize(size_constraints.GetMaximumSize());
  853. [window_ setContentMaxSize:[content convertSize:max_size toView:nil]];
  854. }
  855. NativeWindow::SetContentSizeConstraints(size_constraints);
  856. }
  857. void NativeWindowMac::SetResizable(bool resizable) {
  858. SetStyleMask(resizable, NSResizableWindowMask);
  859. }
  860. bool NativeWindowMac::IsResizable() {
  861. return [window_ styleMask] & NSResizableWindowMask;
  862. }
  863. void NativeWindowMac::SetAspectRatio(double aspect_ratio,
  864. const gfx::Size& extra_size) {
  865. NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
  866. // Reset the behaviour to default if aspect_ratio is set to 0 or less.
  867. if (aspect_ratio > 0.0)
  868. [window_ setAspectRatio:NSMakeSize(aspect_ratio, 1.0)];
  869. else
  870. [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)];
  871. }
  872. void NativeWindowMac::PreviewFile(const std::string& path,
  873. const std::string& display_name) {
  874. NSString* path_ns = [NSString stringWithUTF8String:path.c_str()];
  875. NSString* name_ns = [NSString stringWithUTF8String:display_name.c_str()];
  876. [window_ previewFileAtPath:path_ns withName:name_ns];
  877. }
  878. void NativeWindowMac::CloseFilePreview() {
  879. if ([QLPreviewPanel sharedPreviewPanelExists]) {
  880. [[QLPreviewPanel sharedPreviewPanel] close];
  881. }
  882. }
  883. void NativeWindowMac::SetMovable(bool movable) {
  884. [window_ setMovable:movable];
  885. }
  886. bool NativeWindowMac::IsMovable() {
  887. return [window_ isMovable];
  888. }
  889. void NativeWindowMac::SetMinimizable(bool minimizable) {
  890. SetStyleMask(minimizable, NSMiniaturizableWindowMask);
  891. }
  892. bool NativeWindowMac::IsMinimizable() {
  893. return [window_ styleMask] & NSMiniaturizableWindowMask;
  894. }
  895. void NativeWindowMac::SetMaximizable(bool maximizable) {
  896. [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable];
  897. }
  898. bool NativeWindowMac::IsMaximizable() {
  899. return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled];
  900. }
  901. void NativeWindowMac::SetFullScreenable(bool fullscreenable) {
  902. SetCollectionBehavior(
  903. fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary);
  904. // On EL Capitan this flag is required to hide fullscreen button.
  905. SetCollectionBehavior(
  906. !fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary);
  907. }
  908. bool NativeWindowMac::IsFullScreenable() {
  909. NSUInteger collectionBehavior = [window_ collectionBehavior];
  910. return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary;
  911. }
  912. void NativeWindowMac::SetClosable(bool closable) {
  913. SetStyleMask(closable, NSClosableWindowMask);
  914. }
  915. bool NativeWindowMac::IsClosable() {
  916. return [window_ styleMask] & NSClosableWindowMask;
  917. }
  918. void NativeWindowMac::SetAlwaysOnTop(bool top, const std::string& level,
  919. int relativeLevel, std::string* error) {
  920. int windowLevel = NSNormalWindowLevel;
  921. CGWindowLevel maxWindowLevel = CGWindowLevelForKey(kCGMaximumWindowLevelKey);
  922. CGWindowLevel minWindowLevel = CGWindowLevelForKey(kCGMinimumWindowLevelKey);
  923. if (top) {
  924. if (level == "floating") {
  925. windowLevel = NSFloatingWindowLevel;
  926. } else if (level == "torn-off-menu") {
  927. windowLevel = NSTornOffMenuWindowLevel;
  928. } else if (level == "modal-panel") {
  929. windowLevel = NSModalPanelWindowLevel;
  930. } else if (level == "main-menu") {
  931. windowLevel = NSMainMenuWindowLevel;
  932. } else if (level == "status") {
  933. windowLevel = NSStatusWindowLevel;
  934. } else if (level == "pop-up-menu") {
  935. windowLevel = NSPopUpMenuWindowLevel;
  936. } else if (level == "screen-saver") {
  937. windowLevel = NSScreenSaverWindowLevel;
  938. } else if (level == "dock") {
  939. // Deprecated by macOS, but kept for backwards compatibility
  940. windowLevel = NSDockWindowLevel;
  941. }
  942. }
  943. NSInteger newLevel = windowLevel + relativeLevel;
  944. if (newLevel >= minWindowLevel && newLevel <= maxWindowLevel) {
  945. [window_ setLevel:newLevel];
  946. } else {
  947. *error = std::string([[NSString stringWithFormat:
  948. @"relativeLevel must be between %d and %d", minWindowLevel,
  949. maxWindowLevel] UTF8String]);
  950. }
  951. }
  952. bool NativeWindowMac::IsAlwaysOnTop() {
  953. return [window_ level] != NSNormalWindowLevel;
  954. }
  955. void NativeWindowMac::Center() {
  956. [window_ center];
  957. }
  958. void NativeWindowMac::Invalidate() {
  959. [window_ flushWindow];
  960. [[window_ contentView] setNeedsDisplay:YES];
  961. }
  962. void NativeWindowMac::SetTitle(const std::string& title) {
  963. // For macOS <= 10.9, the setTitleVisibility API is not available, we have
  964. // to avoid calling setTitle for frameless window.
  965. if (!base::mac::IsAtLeastOS10_10() && (transparent() || !has_frame()))
  966. return;
  967. [window_ setTitle:base::SysUTF8ToNSString(title)];
  968. }
  969. std::string NativeWindowMac::GetTitle() {
  970. return base::SysNSStringToUTF8([window_ title]);;
  971. }
  972. void NativeWindowMac::FlashFrame(bool flash) {
  973. if (flash) {
  974. attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest];
  975. } else {
  976. [NSApp cancelUserAttentionRequest:attention_request_id_];
  977. attention_request_id_ = 0;
  978. }
  979. }
  980. void NativeWindowMac::SetSkipTaskbar(bool skip) {
  981. }
  982. void NativeWindowMac::SetKiosk(bool kiosk) {
  983. if (kiosk && !is_kiosk_) {
  984. kiosk_options_ = [NSApp currentSystemPresentationOptions];
  985. NSApplicationPresentationOptions options =
  986. NSApplicationPresentationHideDock +
  987. NSApplicationPresentationHideMenuBar +
  988. NSApplicationPresentationDisableAppleMenu +
  989. NSApplicationPresentationDisableProcessSwitching +
  990. NSApplicationPresentationDisableForceQuit +
  991. NSApplicationPresentationDisableSessionTermination +
  992. NSApplicationPresentationDisableHideApplication;
  993. [NSApp setPresentationOptions:options];
  994. is_kiosk_ = true;
  995. was_fullscreen_ = IsFullscreen();
  996. if (!was_fullscreen_) SetFullScreen(true);
  997. } else if (!kiosk && is_kiosk_) {
  998. is_kiosk_ = false;
  999. if (!was_fullscreen_) SetFullScreen(false);
  1000. [NSApp setPresentationOptions:kiosk_options_];
  1001. }
  1002. }
  1003. bool NativeWindowMac::IsKiosk() {
  1004. return is_kiosk_;
  1005. }
  1006. void NativeWindowMac::SetBackgroundColor(const std::string& color_name) {
  1007. SkColor color = ParseHexColor(color_name);
  1008. base::ScopedCFTypeRef<CGColorRef> cgcolor(
  1009. skia::CGColorCreateFromSkColor(color));
  1010. [[[window_ contentView] layer] setBackgroundColor:cgcolor];
  1011. const auto view = web_contents()->GetRenderWidgetHostView();
  1012. if (view)
  1013. view->SetBackgroundColor(color);
  1014. }
  1015. void NativeWindowMac::SetHasShadow(bool has_shadow) {
  1016. [window_ setHasShadow:has_shadow];
  1017. }
  1018. bool NativeWindowMac::HasShadow() {
  1019. return [window_ hasShadow];
  1020. }
  1021. void NativeWindowMac::SetRepresentedFilename(const std::string& filename) {
  1022. [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)];
  1023. }
  1024. std::string NativeWindowMac::GetRepresentedFilename() {
  1025. return base::SysNSStringToUTF8([window_ representedFilename]);
  1026. }
  1027. void NativeWindowMac::SetDocumentEdited(bool edited) {
  1028. [window_ setDocumentEdited:edited];
  1029. }
  1030. bool NativeWindowMac::IsDocumentEdited() {
  1031. return [window_ isDocumentEdited];
  1032. }
  1033. void NativeWindowMac::SetIgnoreMouseEvents(bool ignore) {
  1034. [window_ setIgnoresMouseEvents:ignore];
  1035. }
  1036. void NativeWindowMac::SetContentProtection(bool enable) {
  1037. [window_ setSharingType:enable ? NSWindowSharingNone
  1038. : NSWindowSharingReadOnly];
  1039. }
  1040. void NativeWindowMac::SetBrowserView(NativeBrowserView* browser_view) {
  1041. if (browser_view_) {
  1042. [browser_view_->GetInspectableWebContentsView()->GetNativeView()
  1043. removeFromSuperview];
  1044. browser_view_ = nullptr;
  1045. }
  1046. if (!browser_view) {
  1047. return;
  1048. }
  1049. browser_view_ = browser_view;
  1050. auto* native_view =
  1051. browser_view->GetInspectableWebContentsView()->GetNativeView();
  1052. [[window_ contentView] addSubview:native_view
  1053. positioned:NSWindowAbove
  1054. relativeTo:nil];
  1055. native_view.hidden = NO;
  1056. }
  1057. void NativeWindowMac::SetParentWindow(NativeWindow* parent) {
  1058. if (is_modal())
  1059. return;
  1060. NativeWindow::SetParentWindow(parent);
  1061. // Remove current parent window.
  1062. if ([window_ parentWindow])
  1063. [[window_ parentWindow] removeChildWindow:window_];
  1064. // Set new current window.
  1065. if (parent)
  1066. [parent->GetNativeWindow() addChildWindow:window_ ordered:NSWindowAbove];
  1067. }
  1068. gfx::NativeWindow NativeWindowMac::GetNativeWindow() {
  1069. return window_;
  1070. }
  1071. gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() {
  1072. return inspectable_web_contents()->GetView()->GetNativeView();
  1073. }
  1074. void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) {
  1075. NSDockTile* dock_tile = [NSApp dockTile];
  1076. // For the first time API invoked, we need to create a ContentView in DockTile.
  1077. if (dock_tile.contentView == nullptr) {
  1078. NSImageView* image_view = [[NSImageView alloc] init];
  1079. [image_view setImage:[NSApp applicationIconImage]];
  1080. [dock_tile setContentView:image_view];
  1081. }
  1082. if ([[dock_tile.contentView subviews] count] == 0) {
  1083. NSProgressIndicator* progress_indicator = [[AtomProgressBar alloc]
  1084. initWithFrame:NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0)];
  1085. [progress_indicator setStyle:NSProgressIndicatorBarStyle];
  1086. [progress_indicator setIndeterminate:NO];
  1087. [progress_indicator setBezeled:YES];
  1088. [progress_indicator setMinValue:0];
  1089. [progress_indicator setMaxValue:1];
  1090. [progress_indicator setHidden:NO];
  1091. [dock_tile.contentView addSubview:progress_indicator];
  1092. }
  1093. NSProgressIndicator* progress_indicator =
  1094. static_cast<NSProgressIndicator*>([[[dock_tile contentView] subviews]
  1095. objectAtIndex:0]);
  1096. if (progress < 0) {
  1097. [progress_indicator setHidden:YES];
  1098. } else if (progress > 1) {
  1099. [progress_indicator setHidden:NO];
  1100. [progress_indicator setIndeterminate:YES];
  1101. [progress_indicator setDoubleValue:1];
  1102. } else {
  1103. [progress_indicator setHidden:NO];
  1104. [progress_indicator setDoubleValue:progress];
  1105. }
  1106. [dock_tile display];
  1107. }
  1108. void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay,
  1109. const std::string& description) {
  1110. }
  1111. void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible) {
  1112. SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces);
  1113. }
  1114. bool NativeWindowMac::IsVisibleOnAllWorkspaces() {
  1115. NSUInteger collectionBehavior = [window_ collectionBehavior];
  1116. return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces;
  1117. }
  1118. void NativeWindowMac::SetAutoHideCursor(bool auto_hide) {
  1119. [window_ setDisableAutoHideCursor:!auto_hide];
  1120. }
  1121. void NativeWindowMac::SetVibrancy(const std::string& type) {
  1122. if (!base::mac::IsAtLeastOS10_10()) return;
  1123. NSView* vibrant_view = [window_ vibrantView];
  1124. if (type.empty()) {
  1125. if (vibrant_view == nil) return;
  1126. [vibrant_view removeFromSuperview];
  1127. [window_ setVibrantView:nil];
  1128. return;
  1129. }
  1130. NSVisualEffectView* effect_view = (NSVisualEffectView*)vibrant_view;
  1131. if (effect_view == nil) {
  1132. effect_view = [[[NSVisualEffectView alloc]
  1133. initWithFrame: [[window_ contentView] bounds]] autorelease];
  1134. [window_ setVibrantView:(NSView*)effect_view];
  1135. [effect_view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
  1136. [effect_view setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
  1137. [effect_view setState:NSVisualEffectStateActive];
  1138. [[window_ contentView] addSubview:effect_view
  1139. positioned:NSWindowBelow
  1140. relativeTo:nil];
  1141. }
  1142. NSVisualEffectMaterial vibrancyType = NSVisualEffectMaterialLight;
  1143. if (type == "appearance-based") {
  1144. vibrancyType = NSVisualEffectMaterialAppearanceBased;
  1145. } else if (type == "light") {
  1146. vibrancyType = NSVisualEffectMaterialLight;
  1147. } else if (type == "dark") {
  1148. vibrancyType = NSVisualEffectMaterialDark;
  1149. } else if (type == "titlebar") {
  1150. vibrancyType = NSVisualEffectMaterialTitlebar;
  1151. }
  1152. if (base::mac::IsAtLeastOS10_11()) {
  1153. // TODO(kevinsawicki): Use NSVisualEffectMaterial* constants directly once
  1154. // they are available in the minimum SDK version
  1155. if (type == "selection") {
  1156. // NSVisualEffectMaterialSelection
  1157. vibrancyType = static_cast<NSVisualEffectMaterial>(4);
  1158. } else if (type == "menu") {
  1159. // NSVisualEffectMaterialMenu
  1160. vibrancyType = static_cast<NSVisualEffectMaterial>(5);
  1161. } else if (type == "popover") {
  1162. // NSVisualEffectMaterialPopover
  1163. vibrancyType = static_cast<NSVisualEffectMaterial>(6);
  1164. } else if (type == "sidebar") {
  1165. // NSVisualEffectMaterialSidebar
  1166. vibrancyType = static_cast<NSVisualEffectMaterial>(7);
  1167. } else if (type == "medium-light") {
  1168. // NSVisualEffectMaterialMediumLight
  1169. vibrancyType = static_cast<NSVisualEffectMaterial>(8);
  1170. } else if (type == "ultra-dark") {
  1171. // NSVisualEffectMaterialUltraDark
  1172. vibrancyType = static_cast<NSVisualEffectMaterial>(9);
  1173. }
  1174. }
  1175. [effect_view setMaterial:vibrancyType];
  1176. }
  1177. void NativeWindowMac::SetTouchBar(
  1178. const std::vector<mate::PersistentDictionary>& items) {
  1179. [window_ resetTouchBar:items];
  1180. }
  1181. void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) {
  1182. [window_ refreshTouchBarItem:item_id];
  1183. }
  1184. void NativeWindowMac::SetEscapeTouchBarItem(const mate::PersistentDictionary& item) {
  1185. [window_ setEscapeTouchBarItem:item];
  1186. }
  1187. void NativeWindowMac::OnInputEvent(const blink::WebInputEvent& event) {
  1188. switch (event.type) {
  1189. case blink::WebInputEvent::GestureScrollBegin:
  1190. case blink::WebInputEvent::GestureScrollUpdate:
  1191. case blink::WebInputEvent::GestureScrollEnd:
  1192. this->NotifyWindowScrollTouchEdge();
  1193. break;
  1194. default:
  1195. break;
  1196. }
  1197. }
  1198. void NativeWindowMac::RenderViewHostChanged(
  1199. content::RenderViewHost* old_host,
  1200. content::RenderViewHost* new_host) {
  1201. UnregisterInputEventObserver(old_host);
  1202. RegisterInputEventObserver(new_host);
  1203. }
  1204. std::vector<gfx::Rect> NativeWindowMac::CalculateNonDraggableRegions(
  1205. const std::vector<DraggableRegion>& regions, int width, int height) {
  1206. std::vector<gfx::Rect> result;
  1207. if (regions.empty()) {
  1208. result.push_back(gfx::Rect(0, 0, width, height));
  1209. } else {
  1210. std::unique_ptr<SkRegion> draggable(DraggableRegionsToSkRegion(regions));
  1211. std::unique_ptr<SkRegion> non_draggable(new SkRegion);
  1212. non_draggable->op(0, 0, width, height, SkRegion::kUnion_Op);
  1213. non_draggable->op(*draggable, SkRegion::kDifference_Op);
  1214. for (SkRegion::Iterator it(*non_draggable); !it.done(); it.next()) {
  1215. result.push_back(gfx::SkIRectToRect(it.rect()));
  1216. }
  1217. }
  1218. return result;
  1219. }
  1220. gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds(
  1221. const gfx::Rect& bounds) {
  1222. if (has_frame()) {
  1223. gfx::Rect window_bounds(
  1224. [window_ frameRectForContentRect:bounds.ToCGRect()]);
  1225. int frame_height = window_bounds.height() - bounds.height();
  1226. window_bounds.set_y(window_bounds.y() - frame_height);
  1227. return window_bounds;
  1228. } else {
  1229. return bounds;
  1230. }
  1231. }
  1232. gfx::Rect NativeWindowMac::WindowBoundsToContentBounds(
  1233. const gfx::Rect& bounds) {
  1234. if (has_frame()) {
  1235. gfx::Rect content_bounds(
  1236. [window_ contentRectForFrameRect:bounds.ToCGRect()]);
  1237. int frame_height = bounds.height() - content_bounds.height();
  1238. content_bounds.set_y(content_bounds.y() + frame_height);
  1239. return content_bounds;
  1240. } else {
  1241. return bounds;
  1242. }
  1243. }
  1244. void NativeWindowMac::UpdateDraggableRegions(
  1245. const std::vector<DraggableRegion>& regions) {
  1246. NativeWindow::UpdateDraggableRegions(regions);
  1247. draggable_regions_ = regions;
  1248. UpdateDraggableRegionViews(regions);
  1249. }
  1250. void NativeWindowMac::ShowWindowButton(NSWindowButton button) {
  1251. auto view = [window_ standardWindowButton:button];
  1252. [view.superview addSubview:view positioned:NSWindowAbove relativeTo:nil];
  1253. }
  1254. void NativeWindowMac::InstallView() {
  1255. // Make sure the bottom corner is rounded for non-modal windows: http://crbug.com/396264.
  1256. // But do not enable it on OS X 10.9 for transparent window, otherwise a
  1257. // semi-transparent frame would show.
  1258. if (!(transparent() && base::mac::IsOS10_9()) && !is_modal())
  1259. [[window_ contentView] setWantsLayer:YES];
  1260. NSView* view = inspectable_web_contents()->GetView()->GetNativeView();
  1261. if (has_frame()) {
  1262. [view setFrame:[[window_ contentView] bounds]];
  1263. [[window_ contentView] addSubview:view];
  1264. } else {
  1265. // In OSX 10.10, adding subviews to the root view for the NSView hierarchy
  1266. // produces warnings. To eliminate the warnings, we resize the contentView
  1267. // to fill the window, and add subviews to that.
  1268. // http://crbug.com/380412
  1269. content_view_.reset([[FullSizeContentView alloc] init]);
  1270. [content_view_
  1271. setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
  1272. [content_view_ setFrame:[[[window_ contentView] superview] bounds]];
  1273. [window_ setContentView:content_view_];
  1274. [view setFrame:[content_view_ bounds]];
  1275. [content_view_ addSubview:view];
  1276. // The fullscreen button should always be hidden for frameless window.
  1277. [[window_ standardWindowButton:NSWindowFullScreenButton] setHidden:YES];
  1278. if (title_bar_style_ != NORMAL) {
  1279. if (base::mac::IsOS10_9()) {
  1280. ShowWindowButton(NSWindowZoomButton);
  1281. ShowWindowButton(NSWindowMiniaturizeButton);
  1282. ShowWindowButton(NSWindowCloseButton);
  1283. }
  1284. return;
  1285. }
  1286. // Hide the window buttons.
  1287. [[window_ standardWindowButton:NSWindowZoomButton] setHidden:YES];
  1288. [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];
  1289. [[window_ standardWindowButton:NSWindowCloseButton] setHidden:YES];
  1290. // Some third-party macOS utilities check the zoom button's enabled state to
  1291. // determine whether to show custom UI on hover, so we disable it here to
  1292. // prevent them from doing so in a frameless app window.
  1293. [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:NO];
  1294. }
  1295. }
  1296. void NativeWindowMac::UninstallView() {
  1297. NSView* view = inspectable_web_contents()->GetView()->GetNativeView();
  1298. [view removeFromSuperview];
  1299. }
  1300. void NativeWindowMac::UpdateDraggableRegionViews(
  1301. const std::vector<DraggableRegion>& regions) {
  1302. if (has_frame())
  1303. return;
  1304. // All ControlRegionViews should be added as children of the WebContentsView,
  1305. // because WebContentsView will be removed and re-added when entering and
  1306. // leaving fullscreen mode.
  1307. NSView* webView = web_contents()->GetNativeView();
  1308. NSInteger webViewWidth = NSWidth([webView bounds]);
  1309. NSInteger webViewHeight = NSHeight([webView bounds]);
  1310. if ([webView respondsToSelector:@selector(setMouseDownCanMoveWindow:)]) {
  1311. [webView setMouseDownCanMoveWindow:YES];
  1312. }
  1313. // Remove all ControlRegionViews that are added last time.
  1314. // Note that [webView subviews] returns the view's mutable internal array and
  1315. // it should be copied to avoid mutating the original array while enumerating
  1316. // it.
  1317. base::scoped_nsobject<NSArray> subviews([[webView subviews] copy]);
  1318. for (NSView* subview in subviews.get())
  1319. if ([subview isKindOfClass:[ControlRegionView class]])
  1320. [subview removeFromSuperview];
  1321. // Draggable regions is implemented by having the whole web view draggable
  1322. // (mouseDownCanMoveWindow) and overlaying regions that are not draggable.
  1323. std::vector<gfx::Rect> system_drag_exclude_areas =
  1324. CalculateNonDraggableRegions(regions, webViewWidth, webViewHeight);
  1325. // Create and add a ControlRegionView for each region that needs to be
  1326. // excluded from the dragging.
  1327. for (std::vector<gfx::Rect>::const_iterator iter =
  1328. system_drag_exclude_areas.begin();
  1329. iter != system_drag_exclude_areas.end();
  1330. ++iter) {
  1331. base::scoped_nsobject<NSView> controlRegion(
  1332. [[ControlRegionView alloc] initWithFrame:NSZeroRect]);
  1333. [controlRegion setFrame:NSMakeRect(iter->x(),
  1334. webViewHeight - iter->bottom(),
  1335. iter->width(),
  1336. iter->height())];
  1337. [webView addSubview:controlRegion];
  1338. }
  1339. // AppKit will not update its cache of mouseDownCanMoveWindow unless something
  1340. // changes. Previously we tried adding an NSView and removing it, but for some
  1341. // reason it required reposting the mouse-down event, and didn't always work.
  1342. // Calling the below seems to be an effective solution.
  1343. [window_ setMovableByWindowBackground:NO];
  1344. [window_ setMovableByWindowBackground:YES];
  1345. }
  1346. void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) {
  1347. // Changing the styleMask of a frameless windows causes it to change size so
  1348. // we explicitly disable resizing while setting it.
  1349. ScopedDisableResize disable_resize;
  1350. bool was_maximizable = IsMaximizable();
  1351. if (on)
  1352. [window_ setStyleMask:[window_ styleMask] | flag];
  1353. else
  1354. [window_ setStyleMask:[window_ styleMask] & (~flag)];
  1355. // Change style mask will make the zoom button revert to default, probably
  1356. // a bug of Cocoa or macOS.
  1357. SetMaximizable(was_maximizable);
  1358. }
  1359. void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) {
  1360. bool was_maximizable = IsMaximizable();
  1361. if (on)
  1362. [window_ setCollectionBehavior:[window_ collectionBehavior] | flag];
  1363. else
  1364. [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)];
  1365. // Change collectionBehavior will make the zoom button revert to default,
  1366. // probably a bug of Cocoa or macOS.
  1367. SetMaximizable(was_maximizable);
  1368. }
  1369. void NativeWindowMac::RegisterInputEventObserver(
  1370. content::RenderViewHost* host) {
  1371. if (host)
  1372. host->GetWidget()->AddInputEventObserver(this);
  1373. }
  1374. void NativeWindowMac::UnregisterInputEventObserver(
  1375. content::RenderViewHost* host) {
  1376. if (host)
  1377. host->GetWidget()->RemoveInputEventObserver(this);
  1378. }
  1379. // static
  1380. NativeWindow* NativeWindow::Create(
  1381. brightray::InspectableWebContents* inspectable_web_contents,
  1382. const mate::Dictionary& options,
  1383. NativeWindow* parent) {
  1384. return new NativeWindowMac(inspectable_web_contents, options, parent);
  1385. }
  1386. } // namespace atom