native_window_mac.mm 65 KB

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