12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084 |
- // Copyright (c) 2013 GitHub, Inc.
- // Use of this source code is governed by the MIT license that can be
- // found in the LICENSE file.
- #include "atom/browser/native_window_mac.h"
- #include <AvailabilityMacros.h>
- #include <Quartz/Quartz.h>
- #include <string>
- #include "atom/browser/browser.h"
- #include "atom/browser/native_browser_view_mac.h"
- #include "atom/browser/ui/cocoa/atom_touch_bar.h"
- #include "atom/browser/window_list.h"
- #include "atom/common/color_util.h"
- #include "atom/common/draggable_region.h"
- #include "atom/common/options_switches.h"
- #include "base/mac/mac_util.h"
- #include "base/mac/scoped_cftyperef.h"
- #include "base/strings/sys_string_conversions.h"
- #include "brightray/browser/inspectable_web_contents.h"
- #include "brightray/browser/inspectable_web_contents_view.h"
- #include "brightray/browser/mac/event_dispatching_window.h"
- #include "content/browser/renderer_host/render_widget_host_impl.h"
- #include "content/public/browser/browser_accessibility_state.h"
- #include "content/public/browser/render_process_host.h"
- #include "content/public/browser/render_view_host.h"
- #include "content/public/browser/render_widget_host_view.h"
- #include "content/public/browser/web_contents.h"
- #include "native_mate/dictionary.h"
- #include "skia/ext/skia_utils_mac.h"
- #include "third_party/skia/include/core/SkRegion.h"
- #include "ui/gfx/skia_util.h"
- #include "ui/gl/gpu_switching_manager.h"
- namespace {
- // Prevents window from resizing during the scope.
- class ScopedDisableResize {
- public:
- ScopedDisableResize() { disable_resize_ = true; }
- ~ScopedDisableResize() { disable_resize_ = false; }
- static bool IsResizeDisabled() { return disable_resize_; }
- private:
- static bool disable_resize_;
- };
- bool ScopedDisableResize::disable_resize_ = false;
- } // namespace
- // Custom Quit, Minimize and Full Screen button container for frameless
- // windows.
- @interface CustomWindowButtonView : NSView {
- @private
- BOOL mouse_inside_;
- }
- @end
- @implementation CustomWindowButtonView
- - (id)initWithFrame:(NSRect)frame {
- self = [super initWithFrame:frame];
- NSButton* close_button = [NSWindow standardWindowButton:NSWindowCloseButton
- forStyleMask:NSTitledWindowMask];
- NSButton* miniaturize_button =
- [NSWindow standardWindowButton:NSWindowMiniaturizeButton
- forStyleMask:NSTitledWindowMask];
- NSButton* zoom_button = [NSWindow standardWindowButton:NSWindowZoomButton
- forStyleMask:NSTitledWindowMask];
- CGFloat x = 0;
- const CGFloat space_between = 20;
- [close_button setFrameOrigin:NSMakePoint(x, 0)];
- x += space_between;
- [self addSubview:close_button];
- [miniaturize_button setFrameOrigin:NSMakePoint(x, 0)];
- x += space_between;
- [self addSubview:miniaturize_button];
- [zoom_button setFrameOrigin:NSMakePoint(x, 0)];
- x += space_between;
- [self addSubview:zoom_button];
- const auto last_button_frame = zoom_button.frame;
- [self setFrameSize:NSMakeSize(last_button_frame.origin.x +
- last_button_frame.size.width,
- last_button_frame.size.height)];
- mouse_inside_ = NO;
- [self setNeedsDisplayForButtons];
- return self;
- }
- - (void)viewDidMoveToWindow {
- if (!self.window) {
- return;
- }
- // Stay in upper left corner.
- const CGFloat top_margin = 3;
- const CGFloat left_margin = 7;
- [self setAutoresizingMask:NSViewMaxXMargin | NSViewMinYMargin];
- [self setFrameOrigin:NSMakePoint(left_margin, self.window.frame.size.height -
- self.frame.size.height -
- top_margin)];
- }
- - (BOOL)_mouseInGroup:(NSButton*)button {
- return mouse_inside_;
- }
- - (void)updateTrackingAreas {
- auto tracking_area = [[[NSTrackingArea alloc]
- initWithRect:NSZeroRect
- options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways |
- NSTrackingInVisibleRect
- owner:self
- userInfo:nil] autorelease];
- [self addTrackingArea:tracking_area];
- }
- - (void)mouseEntered:(NSEvent*)event {
- [super mouseEntered:event];
- mouse_inside_ = YES;
- [self setNeedsDisplayForButtons];
- }
- - (void)mouseExited:(NSEvent*)event {
- [super mouseExited:event];
- mouse_inside_ = NO;
- [self setNeedsDisplayForButtons];
- }
- - (void)setNeedsDisplayForButtons {
- for (NSView* subview in self.subviews) {
- [subview setHidden:!mouse_inside_];
- [subview setNeedsDisplay:YES];
- }
- }
- @end
- // This view always takes the size of its superview. It is intended to be used
- // as a NSWindow's contentView. It is needed because NSWindow's implementation
- // explicitly resizes the contentView at inopportune times.
- @interface FullSizeContentView : NSView
- @end
- @implementation FullSizeContentView
- // This method is directly called by NSWindow during a window resize on OSX
- // 10.10.0, beta 2. We must override it to prevent the content view from
- // shrinking.
- - (void)setFrameSize:(NSSize)size {
- if ([self superview])
- size = [[self superview] bounds].size;
- [super setFrameSize:size];
- }
- // The contentView gets moved around during certain full-screen operations.
- // This is less than ideal, and should eventually be removed.
- - (void)viewDidMoveToSuperview {
- [self setFrame:[[self superview] bounds]];
- }
- @end
- @interface AtomNSWindowDelegate : NSObject<NSWindowDelegate> {
- @private
- atom::NativeWindowMac* shell_;
- bool is_zooming_;
- int level_;
- bool is_resizable_;
- }
- - (id)initWithShell:(atom::NativeWindowMac*)shell;
- @end
- @implementation AtomNSWindowDelegate
- - (id)initWithShell:(atom::NativeWindowMac*)shell {
- if ((self = [super init])) {
- shell_ = shell;
- is_zooming_ = false;
- level_ = [shell_->GetNativeWindow() level];
- }
- return self;
- }
- - (void)windowDidChangeOcclusionState:(NSNotification *)notification {
- // notification.object is the window that changed its state.
- // It's safe to use self.window instead if you don't assign one delegate to many windows
- NSWindow *window = notification.object;
- // check occlusion binary flag
- if (window.occlusionState & NSWindowOcclusionStateVisible) {
- // The app is visible
- shell_->NotifyWindowShow();
- } else {
- // The app is not visible
- shell_->NotifyWindowHide();
- }
- }
- // Called when the user clicks the zoom button or selects it from the Window
- // menu to determine the "standard size" of the window.
- - (NSRect)windowWillUseStandardFrame:(NSWindow*)window
- defaultFrame:(NSRect)frame {
- if (!shell_->zoom_to_page_width())
- return frame;
- // If the shift key is down, maximize.
- if ([[NSApp currentEvent] modifierFlags] & NSShiftKeyMask)
- return frame;
- content::WebContents* web_contents = shell_->web_contents();
- if (!web_contents)
- return frame;
- CGFloat page_width = static_cast<CGFloat>(
- web_contents->GetPreferredSize().width());
- NSRect window_frame = [window frame];
- // Never shrink from the current size on zoom.
- CGFloat zoomed_width = std::max(page_width, NSWidth(window_frame));
- // |frame| determines our maximum extents. We need to set the origin of the
- // frame -- and only move it left if necessary.
- if (window_frame.origin.x + zoomed_width > NSMaxX(frame))
- frame.origin.x = NSMaxX(frame) - zoomed_width;
- else
- frame.origin.x = window_frame.origin.x;
- // Set the width. Don't touch y or height.
- frame.size.width = zoomed_width;
- return frame;
- }
- - (void)windowDidBecomeMain:(NSNotification*)notification {
- content::WebContents* web_contents = shell_->web_contents();
- if (!web_contents)
- return;
- web_contents->RestoreFocus();
- content::RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
- if (rwhv)
- rwhv->SetActive(true);
- shell_->NotifyWindowFocus();
- }
- - (void)windowDidResignMain:(NSNotification*)notification {
- content::WebContents* web_contents = shell_->web_contents();
- if (!web_contents)
- return;
- web_contents->StoreFocus();
- content::RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
- if (rwhv)
- rwhv->SetActive(false);
- shell_->NotifyWindowBlur();
- }
- - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)frameSize {
- NSSize newSize = frameSize;
- double aspectRatio = shell_->GetAspectRatio();
- if (aspectRatio > 0.0) {
- gfx::Size windowSize = shell_->GetSize();
- gfx::Size contentSize = shell_->GetContentSize();
- gfx::Size extraSize = shell_->GetAspectRatioExtraSize();
- double extraWidthPlusFrame =
- windowSize.width() - contentSize.width() + extraSize.width();
- double extraHeightPlusFrame =
- windowSize.height() - contentSize.height() + extraSize.height();
- newSize.width =
- roundf((frameSize.height - extraHeightPlusFrame) * aspectRatio +
- extraWidthPlusFrame);
- newSize.height =
- roundf((newSize.width - extraWidthPlusFrame) / aspectRatio +
- extraHeightPlusFrame);
- }
- return newSize;
- }
- - (void)windowDidResize:(NSNotification*)notification {
- shell_->UpdateDraggableRegionViews();
- shell_->NotifyWindowResize();
- }
- - (void)windowDidMove:(NSNotification*)notification {
- // TODO(zcbenz): Remove the alias after figuring out a proper
- // way to dispatch move.
- shell_->NotifyWindowMove();
- shell_->NotifyWindowMoved();
- }
- - (void)windowWillMiniaturize:(NSNotification*)notification {
- NSWindow* window = shell_->GetNativeWindow();
- // store the current status window level to be restored in windowDidDeminiaturize
- level_ = [window level];
- [window setLevel:NSNormalWindowLevel];
- }
- - (void)windowDidMiniaturize:(NSNotification*)notification {
- shell_->NotifyWindowMinimize();
- }
- - (void)windowDidDeminiaturize:(NSNotification*)notification {
- [shell_->GetNativeWindow() setLevel:level_];
- shell_->NotifyWindowRestore();
- }
- - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)newFrame {
- is_zooming_ = true;
- return YES;
- }
- - (void)windowDidEndLiveResize:(NSNotification*)notification {
- if (is_zooming_) {
- if (shell_->IsMaximized())
- shell_->NotifyWindowMaximize();
- else
- shell_->NotifyWindowUnmaximize();
- is_zooming_ = false;
- }
- }
- - (void)windowWillEnterFullScreen:(NSNotification*)notification {
- // Setting resizable to true before entering fullscreen
- is_resizable_ = shell_->IsResizable();
- shell_->SetResizable(true);
- // Hide the native toolbar before entering fullscreen, so there is no visual
- // artifacts.
- if (base::mac::IsAtLeastOS10_10() &&
- shell_->title_bar_style() == atom::NativeWindowMac::HIDDEN_INSET) {
- NSWindow* window = shell_->GetNativeWindow();
- [window setToolbar:nil];
- }
- }
- - (void)windowDidEnterFullScreen:(NSNotification*)notification {
- shell_->NotifyWindowEnterFullScreen();
- // For frameless window we don't show set title for normal mode since the
- // titlebar is expected to be empty, but after entering fullscreen mode we
- // have to set one, because title bar is visible here.
- NSWindow* window = shell_->GetNativeWindow();
- if ((shell_->transparent() || !shell_->has_frame()) &&
- base::mac::IsAtLeastOS10_10() &&
- // FIXME(zcbenz): Showing titlebar for hiddenInset window is weird under
- // fullscreen mode.
- // Show title if fullscreen_window_title flag is set
- (shell_->title_bar_style() != atom::NativeWindowMac::HIDDEN_INSET ||
- shell_->fullscreen_window_title())) {
- [window setTitleVisibility:NSWindowTitleVisible];
- }
- // Restore the native toolbar immediately after entering fullscreen, if we do
- // this before leaving fullscreen, traffic light buttons will be jumping.
- if (base::mac::IsAtLeastOS10_10() &&
- shell_->title_bar_style() == atom::NativeWindowMac::HIDDEN_INSET) {
- base::scoped_nsobject<NSToolbar> toolbar(
- [[NSToolbar alloc] initWithIdentifier:@"titlebarStylingToolbar"]);
- [toolbar setShowsBaselineSeparator:NO];
- [window setToolbar:toolbar];
- // Set window style to hide the toolbar, otherwise the toolbar will show in
- // fullscreen mode.
- [window setTitlebarAppearsTransparent:NO];
- shell_->SetStyleMask(true, NSFullSizeContentViewWindowMask);
- }
- }
- - (void)windowWillExitFullScreen:(NSNotification*)notification {
- // Restore the titlebar visibility.
- NSWindow* window = shell_->GetNativeWindow();
- if ((shell_->transparent() || !shell_->has_frame()) &&
- base::mac::IsAtLeastOS10_10() &&
- (shell_->title_bar_style() != atom::NativeWindowMac::HIDDEN_INSET ||
- shell_->fullscreen_window_title())) {
- [window setTitleVisibility:NSWindowTitleHidden];
- }
- // Turn off the style for toolbar.
- if (base::mac::IsAtLeastOS10_10() &&
- shell_->title_bar_style() == atom::NativeWindowMac::HIDDEN_INSET) {
- [window setTitlebarAppearsTransparent:YES];
- shell_->SetStyleMask(false, NSFullSizeContentViewWindowMask);
- }
- }
- - (void)windowDidExitFullScreen:(NSNotification*)notification {
- shell_->SetResizable(is_resizable_);
- shell_->NotifyWindowLeaveFullScreen();
- }
- - (void)windowWillClose:(NSNotification*)notification {
- shell_->NotifyWindowClosed();
- // Clears the delegate when window is going to be closed, since EL Capitan it
- // is possible that the methods of delegate would get called after the window
- // has been closed.
- [shell_->GetNativeWindow() setDelegate:nil];
- }
- - (BOOL)windowShouldClose:(id)window {
- // When user tries to close the window by clicking the close button, we do
- // not close the window immediately, instead we try to close the web page
- // first, and when the web page is closed the window will also be closed.
- shell_->RequestToClosePage();
- return NO;
- }
- - (NSRect)window:(NSWindow*)window
- willPositionSheet:(NSWindow*)sheet usingRect:(NSRect)rect {
- NSView* view = window.contentView;
- rect.origin.x = shell_->GetSheetOffsetX();
- rect.origin.y = view.frame.size.height - shell_->GetSheetOffsetY();
- return rect;
- }
- - (void)windowWillBeginSheet:(NSNotification *)notification {
- shell_->NotifyWindowSheetBegin();
- }
- - (void)windowDidEndSheet:(NSNotification *)notification {
- shell_->NotifyWindowSheetEnd();
- }
- - (IBAction)newWindowForTab:(id)sender {
- shell_->NotifyNewWindowForTab();
- atom::Browser::Get()->NewWindowForTab();
- }
- @end
- @interface AtomPreviewItem : NSObject <QLPreviewItem>
- @property (nonatomic, retain) NSURL* previewItemURL;
- @property (nonatomic, retain) NSString* previewItemTitle;
- - (id)initWithURL:(NSURL*)url title:(NSString*)title;
- @end
- @implementation AtomPreviewItem
- - (id)initWithURL:(NSURL*)url title:(NSString*)title {
- self = [super init];
- if (self) {
- self.previewItemURL = url;
- self.previewItemTitle = title;
- }
- return self;
- }
- @end
- #if !defined(AVAILABLE_MAC_OS_X_VERSION_10_12_AND_LATER)
- enum {
- NSWindowTabbingModeDisallowed = 2
- };
- @interface NSWindow (SierraSDK)
- - (void)setTabbingMode:(NSInteger)mode;
- - (void)setTabbingIdentifier:(NSString*)identifier;
- - (void)addTabbedWindow:(NSWindow*)window ordered:(NSWindowOrderingMode)ordered;
- - (IBAction)selectPreviousTab:(id)sender;
- - (IBAction)selectNextTab:(id)sender;
- - (IBAction)mergeAllWindows:(id)sender;
- - (IBAction)moveTabToNewWindow:(id)sender;
- - (IBAction)toggleTabBar:(id)sender;
- @end
- #endif
- @interface AtomNSWindow : EventDispatchingWindow<QLPreviewPanelDataSource, QLPreviewPanelDelegate, NSTouchBarDelegate> {
- @private
- atom::NativeWindowMac* shell_;
- bool enable_larger_than_screen_;
- base::scoped_nsobject<AtomTouchBar> atom_touch_bar_;
- CGFloat windowButtonsInterButtonSpacing_;
- }
- @property BOOL acceptsFirstMouse;
- @property BOOL disableAutoHideCursor;
- @property BOOL disableKeyOrMainWindow;
- @property NSPoint windowButtonsOffset;
- @property (nonatomic, retain) AtomPreviewItem* quickLookItem;
- @property (nonatomic, retain) NSView* vibrantView;
- - (void)setShell:(atom::NativeWindowMac*)shell;
- - (void)setEnableLargerThanScreen:(bool)enable;
- - (void)enableWindowButtonsOffset;
- - (void)resetTouchBar:(const std::vector<mate::PersistentDictionary>&)settings;
- - (void)refreshTouchBarItem:(const std::string&)item_id;
- - (void)setEscapeTouchBarItem:(const mate::PersistentDictionary&)item;
- @end
- @implementation AtomNSWindow
- - (void)setShell:(atom::NativeWindowMac*)shell {
- shell_ = shell;
- }
- - (void)setEnableLargerThanScreen:(bool)enable {
- enable_larger_than_screen_ = enable;
- }
- - (void)resetTouchBar:(const std::vector<mate::PersistentDictionary>&)settings {
- if (![self respondsToSelector:@selector(touchBar)]) return;
- atom_touch_bar_.reset([[AtomTouchBar alloc] initWithDelegate:self
- window:shell_
- settings:settings]);
- self.touchBar = nil;
- }
- - (void)refreshTouchBarItem:(const std::string&)item_id {
- if (atom_touch_bar_ && self.touchBar)
- [atom_touch_bar_ refreshTouchBarItem:self.touchBar id:item_id];
- }
- - (NSTouchBar*)makeTouchBar {
- if (atom_touch_bar_)
- return [atom_touch_bar_ makeTouchBar];
- else
- return nil;
- }
- - (NSTouchBarItem*)touchBar:(NSTouchBar*)touchBar
- makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier {
- if (touchBar && atom_touch_bar_)
- return [atom_touch_bar_ makeItemForIdentifier:identifier];
- else
- return nil;
- }
- - (void)setEscapeTouchBarItem:(const mate::PersistentDictionary&)item {
- if (atom_touch_bar_ && self.touchBar)
- [atom_touch_bar_ setEscapeTouchBarItem:item forTouchBar:self.touchBar];
- }
- // NSWindow overrides.
- - (void)swipeWithEvent:(NSEvent *)event {
- if (event.deltaY == 1.0) {
- shell_->NotifyWindowSwipe("up");
- } else if (event.deltaX == -1.0) {
- shell_->NotifyWindowSwipe("right");
- } else if (event.deltaY == -1.0) {
- shell_->NotifyWindowSwipe("down");
- } else if (event.deltaX == 1.0) {
- shell_->NotifyWindowSwipe("left");
- }
- }
- - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen*)screen {
- // Resizing is disabled.
- if (ScopedDisableResize::IsResizeDisabled())
- return [self frame];
- // Enable the window to be larger than screen.
- if (enable_larger_than_screen_)
- return frameRect;
- else
- return [super constrainFrameRect:frameRect toScreen:screen];
- }
- - (void)setFrame:(NSRect)windowFrame display:(BOOL)displayViews {
- // constrainFrameRect is not called on hidden windows so disable adjusting
- // the frame directly when resize is disabled
- if (!ScopedDisableResize::IsResizeDisabled())
- [super setFrame:windowFrame display:displayViews];
- }
- - (id)accessibilityAttributeValue:(NSString*)attribute {
- if (![attribute isEqualToString:@"AXChildren"])
- return [super accessibilityAttributeValue:attribute];
- // Filter out objects that aren't the title bar buttons. This has the effect
- // of removing the window title, which VoiceOver already sees.
- // * when VoiceOver is disabled, this causes Cmd+C to be used for TTS but
- // still leaves the buttons available in the accessibility tree.
- // * when VoiceOver is enabled, the full accessibility tree is used.
- // Without removing the title and with VO disabled, the TTS would always read
- // the window title instead of using Cmd+C to get the selected text.
- NSPredicate *predicate = [NSPredicate predicateWithFormat:
- @"(self isKindOfClass: %@) OR (self.className == %@)",
- [NSButtonCell class],
- @"RenderWidgetHostViewCocoa"];
- NSArray *children = [super accessibilityAttributeValue:attribute];
- return [children filteredArrayUsingPredicate:predicate];
- }
- - (BOOL)canBecomeMainWindow {
- return !self.disableKeyOrMainWindow;
- }
- - (BOOL)canBecomeKeyWindow {
- return !self.disableKeyOrMainWindow;
- }
- - (void)enableWindowButtonsOffset {
- auto closeButton = [self standardWindowButton:NSWindowCloseButton];
- auto miniaturizeButton = [self standardWindowButton:NSWindowMiniaturizeButton];
- auto zoomButton = [self standardWindowButton:NSWindowZoomButton];
- [closeButton setPostsFrameChangedNotifications:YES];
- [miniaturizeButton setPostsFrameChangedNotifications:YES];
- [zoomButton setPostsFrameChangedNotifications:YES];
- windowButtonsInterButtonSpacing_ =
- NSMinX([miniaturizeButton frame]) - NSMaxX([closeButton frame]);
- auto center = [NSNotificationCenter defaultCenter];
- [center addObserver:self
- selector:@selector(adjustCloseButton:)
- name:NSViewFrameDidChangeNotification
- object:closeButton];
- [center addObserver:self
- selector:@selector(adjustMiniaturizeButton:)
- name:NSViewFrameDidChangeNotification
- object:miniaturizeButton];
- [center addObserver:self
- selector:@selector(adjustZoomButton:)
- name:NSViewFrameDidChangeNotification
- object:zoomButton];
- }
- - (void)adjustCloseButton:(NSNotification*)notification {
- [self adjustButton:[notification object]
- ofKind:NSWindowCloseButton];
- }
- - (void)adjustMiniaturizeButton:(NSNotification*)notification {
- [self adjustButton:[notification object]
- ofKind:NSWindowMiniaturizeButton];
- }
- - (void)adjustZoomButton:(NSNotification*)notification {
- [self adjustButton:[notification object]
- ofKind:NSWindowZoomButton];
- }
- - (void)adjustButton:(NSButton*)button
- ofKind:(NSWindowButton)kind {
- NSRect buttonFrame = [button frame];
- NSRect frameViewBounds = [[self frameView] bounds];
- NSPoint offset = self.windowButtonsOffset;
- buttonFrame.origin = NSMakePoint(
- offset.x,
- (NSHeight(frameViewBounds) - NSHeight(buttonFrame) - offset.y));
- switch (kind) {
- case NSWindowZoomButton:
- buttonFrame.origin.x += NSWidth(
- [[self standardWindowButton:NSWindowMiniaturizeButton] frame]);
- buttonFrame.origin.x += windowButtonsInterButtonSpacing_;
- // fallthrough
- case NSWindowMiniaturizeButton:
- buttonFrame.origin.x += NSWidth(
- [[self standardWindowButton:NSWindowCloseButton] frame]);
- buttonFrame.origin.x += windowButtonsInterButtonSpacing_;
- // fallthrough
- default:
- break;
- }
- BOOL didPost = [button postsBoundsChangedNotifications];
- [button setPostsFrameChangedNotifications:NO];
- [button setFrame:buttonFrame];
- [button setPostsFrameChangedNotifications:didPost];
- }
- - (NSView*)frameView {
- return [[self contentView] superview];
- }
- // Quicklook methods
- - (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel*)panel {
- return YES;
- }
- - (void)beginPreviewPanelControl:(QLPreviewPanel*)panel {
- panel.delegate = self;
- panel.dataSource = self;
- }
- - (void)endPreviewPanelControl:(QLPreviewPanel*)panel {
- panel.delegate = nil;
- panel.dataSource = nil;
- }
- - (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel*)panel {
- return 1;
- }
- - (id <QLPreviewItem>)previewPanel:(QLPreviewPanel*)panel previewItemAtIndex:(NSInteger)index {
- return [self quickLookItem];
- }
- - (void)previewFileAtPath:(NSString*)path withName:(NSString*) fileName {
- NSURL* url = [[[NSURL alloc] initFileURLWithPath:path] autorelease];
- [self setQuickLookItem:[[[AtomPreviewItem alloc] initWithURL:url title:fileName] autorelease]];
- [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
- }
- // Custom window button methods
- - (BOOL)windowShouldClose:(id)sender { return YES; }
- - (void)performClose:(id)sender {
- if (shell_->title_bar_style() ==
- atom::NativeWindowMac::CUSTOM_BUTTONS_ON_HOVER) {
- [[self delegate] windowShouldClose:self];
- } else if (shell_->IsSimpleFullScreen()) {
- if([[self delegate] respondsToSelector:@selector(windowShouldClose:)]) {
- if(![[self delegate] windowShouldClose:self]) return;
- } else if([self respondsToSelector:@selector(windowShouldClose:)]) {
- if(![self windowShouldClose:self]) return;
- }
- [self close];
- } else
- [super performClose:sender];
- }
- - (void)toggleFullScreenMode:(id)sender {
- if (shell_->simple_fullscreen())
- shell_->SetSimpleFullScreen(!shell_->IsSimpleFullScreen());
- else
- [super toggleFullScreen:sender];
- }
- - (void)performMiniaturize:(id)sender {
- if (shell_->title_bar_style() == atom::NativeWindowMac::CUSTOM_BUTTONS_ON_HOVER)
- [self miniaturize:self];
- else
- [super performMiniaturize:sender];
- }
- @end
- @interface ControlRegionView : NSView
- @end
- @implementation ControlRegionView
- - (BOOL)mouseDownCanMoveWindow {
- return NO;
- }
- - (NSView*)hitTest:(NSPoint)aPoint {
- return nil;
- }
- @end
- @interface NSView (WebContentsView)
- - (void)setMouseDownCanMoveWindow:(BOOL)can_move;
- @end
- @interface AtomProgressBar : NSProgressIndicator
- @end
- @implementation AtomProgressBar
- - (void)drawRect:(NSRect)dirtyRect {
- if (self.style != NSProgressIndicatorBarStyle)
- return;
- // Draw edges of rounded rect.
- NSRect rect = NSInsetRect([self bounds], 1.0, 1.0);
- CGFloat radius = rect.size.height / 2;
- NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius];
- [bezier_path setLineWidth:2.0];
- [[NSColor grayColor] set];
- [bezier_path stroke];
- // Fill the rounded rect.
- rect = NSInsetRect(rect, 2.0, 2.0);
- radius = rect.size.height / 2;
- bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius];
- [bezier_path setLineWidth:1.0];
- [bezier_path addClip];
- // Calculate the progress width.
- rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue]));
- // Fill the progress bar with color blue.
- [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set];
- NSRectFill(rect);
- }
- @end
- namespace mate {
- template<>
- struct Converter<atom::NativeWindowMac::TitleBarStyle> {
- static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val,
- atom::NativeWindowMac::TitleBarStyle* out) {
- std::string title_bar_style;
- if (!ConvertFromV8(isolate, val, &title_bar_style))
- return false;
- if (title_bar_style == "hidden") {
- *out = atom::NativeWindowMac::HIDDEN;
- } else if (title_bar_style == "hiddenInset") {
- *out = atom::NativeWindowMac::HIDDEN_INSET;
- } else if (title_bar_style == "customButtonsOnHover") {
- *out = atom::NativeWindowMac::CUSTOM_BUTTONS_ON_HOVER;
- } else {
- return false;
- }
- return true;
- }
- };
- } // namespace mate
- namespace atom {
- NativeWindowMac::NativeWindowMac(
- brightray::InspectableWebContents* web_contents,
- const mate::Dictionary& options,
- NativeWindow* parent)
- : NativeWindow(web_contents, options, parent),
- browser_view_(nullptr),
- is_kiosk_(false),
- was_fullscreen_(false),
- zoom_to_page_width_(false),
- fullscreen_window_title_(false),
- attention_request_id_(0),
- title_bar_style_(NORMAL),
- always_simple_fullscreen_(false),
- is_simple_fullscreen_(false) {
- int width = 800, height = 600;
- options.Get(options::kWidth, &width);
- options.Get(options::kHeight, &height);
- NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame];
- NSRect cocoa_bounds = NSMakeRect(
- round((NSWidth(main_screen_rect) - width) / 2) ,
- round((NSHeight(main_screen_rect) - height) / 2),
- width,
- height);
- bool resizable = true;
- options.Get(options::kResizable, &resizable);
- bool minimizable = true;
- options.Get(options::kMinimizable, &minimizable);
- bool maximizable = true;
- options.Get(options::kMaximizable, &maximizable);
- bool closable = true;
- options.Get(options::kClosable, &closable);
- options.Get(options::kTitleBarStyle, &title_bar_style_);
- std::string tabbingIdentifier;
- options.Get(options::kTabbingIdentifier, &tabbingIdentifier);
- std::string windowType;
- options.Get(options::kType, &windowType);
- bool useStandardWindow = true;
- // eventually deprecate separate "standardWindow" option in favor of
- // standard / textured window types
- options.Get(options::kStandardWindow, &useStandardWindow);
- if (windowType == "textured") {
- useStandardWindow = false;
- }
- NSUInteger styleMask = NSTitledWindowMask;
- if (title_bar_style_ == CUSTOM_BUTTONS_ON_HOVER &&
- base::mac::IsAtLeastOS10_10() &&
- (!useStandardWindow || transparent() || !has_frame())) {
- styleMask = NSFullSizeContentViewWindowMask;
- }
- if (minimizable) {
- styleMask |= NSMiniaturizableWindowMask;
- }
- if (closable) {
- styleMask |= NSClosableWindowMask;
- }
- if (title_bar_style_ != NORMAL) {
- // The window without titlebar is treated the same with frameless window.
- set_has_frame(false);
- }
- if (!useStandardWindow || transparent() || !has_frame()) {
- styleMask |= NSTexturedBackgroundWindowMask;
- }
- if (resizable) {
- styleMask |= NSResizableWindowMask;
- }
- window_.reset([[AtomNSWindow alloc]
- initWithContentRect:cocoa_bounds
- styleMask:styleMask
- backing:NSBackingStoreBuffered
- defer:YES]);
- [window_ setShell:this];
- [window_ setEnableLargerThanScreen:enable_larger_than_screen()];
- window_delegate_.reset([[AtomNSWindowDelegate alloc] initWithShell:this]);
- [window_ setDelegate:window_delegate_];
- // Only use native parent window for non-modal windows.
- if (parent && !is_modal()) {
- SetParentWindow(parent);
- }
- if (transparent()) {
- // Setting the background color to clear will also hide the shadow.
- [window_ setBackgroundColor:[NSColor clearColor]];
- }
- if (windowType == "desktop") {
- [window_ setLevel:kCGDesktopWindowLevel - 1];
- [window_ setDisableKeyOrMainWindow:YES];
- [window_ setCollectionBehavior:
- (NSWindowCollectionBehaviorCanJoinAllSpaces |
- NSWindowCollectionBehaviorStationary |
- NSWindowCollectionBehaviorIgnoresCycle)];
- }
- bool focusable;
- if (options.Get(options::kFocusable, &focusable) && !focusable)
- [window_ setDisableKeyOrMainWindow:YES];
- if (transparent() || !has_frame()) {
- if (base::mac::IsAtLeastOS10_10()) {
- // Don't show title bar.
- [window_ setTitlebarAppearsTransparent:YES];
- [window_ setTitleVisibility:NSWindowTitleHidden];
- }
- // Remove non-transparent corners, see http://git.io/vfonD.
- [window_ setOpaque:NO];
- }
- // Create a tab only if tabbing identifier is specified and window has
- // a native title bar.
- if (tabbingIdentifier.empty() || transparent() || !has_frame()) {
- if ([window_ respondsToSelector:@selector(tabbingMode)]) {
- [window_ setTabbingMode:NSWindowTabbingModeDisallowed];
- }
- } else {
- if ([window_ respondsToSelector:@selector(tabbingIdentifier)]) {
- [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)];
- }
- }
- // We will manage window's lifetime ourselves.
- [window_ setReleasedWhenClosed:NO];
- // Hide the title bar background
- if (title_bar_style_ != NORMAL) {
- if (base::mac::IsAtLeastOS10_10()) {
- [window_ setTitlebarAppearsTransparent:YES];
- }
- }
- // Hide the title bar.
- if (title_bar_style_ == HIDDEN_INSET) {
- if (base::mac::IsAtLeastOS10_10()) {
- base::scoped_nsobject<NSToolbar> toolbar(
- [[NSToolbar alloc] initWithIdentifier:@"titlebarStylingToolbar"]);
- [toolbar setShowsBaselineSeparator:NO];
- [window_ setToolbar:toolbar];
- } else {
- [window_ enableWindowButtonsOffset];
- [window_ setWindowButtonsOffset:NSMakePoint(12, 10)];
- }
- }
- // On macOS the initial window size doesn't include window frame.
- bool use_content_size = false;
- options.Get(options::kUseContentSize, &use_content_size);
- if (!has_frame() || !use_content_size)
- SetSize(gfx::Size(width, height));
- options.Get(options::kZoomToPageWidth, &zoom_to_page_width_);
- options.Get(options::kFullscreenWindowTitle, &fullscreen_window_title_);
- options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_);
- // Enable the NSView to accept first mouse event.
- bool acceptsFirstMouse = false;
- options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse);
- [window_ setAcceptsFirstMouse:acceptsFirstMouse];
- // Disable auto-hiding cursor.
- bool disableAutoHideCursor = false;
- options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor);
- [window_ setDisableAutoHideCursor:disableAutoHideCursor];
- NSView* view = inspectable_web_contents()->GetView()->GetNativeView();
- [view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
- // Use an NSEvent monitor to listen for the wheel event.
- BOOL __block began = NO;
- wheel_event_monitor_ = [NSEvent
- addLocalMonitorForEventsMatchingMask:NSScrollWheelMask
- handler:^(NSEvent* event) {
- if ([[event window] windowNumber] != [window_ windowNumber])
- return event;
- if (!web_contents)
- return event;
- if (!began && (([event phase] == NSEventPhaseMayBegin) ||
- ([event phase] == NSEventPhaseBegan))) {
- this->NotifyWindowScrollTouchBegin();
- began = YES;
- } else if (began && (([event phase] == NSEventPhaseEnded) ||
- ([event phase] == NSEventPhaseCancelled))) {
- this->NotifyWindowScrollTouchEnd();
- began = NO;
- }
- return event;
- }];
- InstallView();
- std::string type;
- if (options.Get(options::kVibrancyType, &type)) {
- SetVibrancy(type);
- }
- // Set maximizable state last to ensure zoom button does not get reset
- // by calls to other APIs.
- SetMaximizable(maximizable);
- RegisterInputEventObserver(
- web_contents->GetWebContents()->GetRenderViewHost());
- original_frame_ = [window_ frame];
- original_level_ = [window_ level];
- }
- NativeWindowMac::~NativeWindowMac() {
- [NSEvent removeMonitor:wheel_event_monitor_];
- Observe(nullptr);
- }
- void NativeWindowMac::Close() {
- // When this is a sheet showing, performClose won't work.
- if (is_modal() && parent() && IsVisible()) {
- [parent()->GetNativeWindow() endSheet:window_];
- CloseImmediately();
- return;
- }
- if (!IsClosable()) {
- WindowList::WindowCloseCancelled(this);
- return;
- }
- [window_ performClose:nil];
- }
- void NativeWindowMac::CloseImmediately() {
- // Retain the child window before closing it. If the last reference to the
- // NSWindow goes away inside -[NSWindow close], then bad stuff can happen.
- // See e.g. http://crbug.com/616701.
- base::scoped_nsobject<NSWindow> child_window(window_,
- base::scoped_policy::RETAIN);
- [window_ close];
- }
- void NativeWindowMac::Focus(bool focus) {
- if (!IsVisible())
- return;
- if (focus) {
- [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
- [window_ makeKeyAndOrderFront:nil];
- } else {
- [window_ orderBack:nil];
- }
- }
- bool NativeWindowMac::IsFocused() {
- return [window_ isKeyWindow];
- }
- void NativeWindowMac::Show() {
- if (is_modal() && parent()) {
- if ([window_ sheetParent] == nil)
- [parent()->GetNativeWindow() beginSheet:window_
- completionHandler:^(NSModalResponse) {}];
- return;
- }
- // Reattach the window to the parent to actually show it.
- if (parent())
- InternalSetParentWindow(parent(), true);
- // This method is supposed to put focus on window, however if the app does not
- // have focus then "makeKeyAndOrderFront" will only show the window.
- [NSApp activateIgnoringOtherApps:YES];
- [window_ makeKeyAndOrderFront:nil];
- }
- void NativeWindowMac::ShowInactive() {
- // Reattach the window to the parent to actually show it.
- if (parent())
- InternalSetParentWindow(parent(), true);
- [window_ orderFrontRegardless];
- }
- void NativeWindowMac::Hide() {
- if (is_modal() && parent()) {
- [window_ orderOut:nil];
- [parent()->GetNativeWindow() endSheet:window_];
- return;
- }
- // Deattach the window from the parent before.
- if (parent())
- InternalSetParentWindow(parent(), false);
- [window_ orderOut:nil];
- }
- bool NativeWindowMac::IsVisible() {
- return [window_ isVisible];
- }
- bool NativeWindowMac::IsEnabled() {
- return [window_ attachedSheet] == nil;
- }
- void NativeWindowMac::SetEnabled(bool enable) {
- if (enable) {
- [window_ endSheet: [window_ attachedSheet]];
- } else {
- [window_ beginSheet: window_ completionHandler:^(NSModalResponse returnCode) {
- NSLog(@"modal enabled");
- return;
- }];
- }
- }
- void NativeWindowMac::Maximize() {
- if (IsMaximized())
- return;
- [window_ zoom:nil];
- }
- void NativeWindowMac::Unmaximize() {
- if (!IsMaximized())
- return;
- [window_ zoom:nil];
- }
- bool NativeWindowMac::IsMaximized() {
- if (([window_ styleMask] & NSResizableWindowMask) != 0) {
- return [window_ isZoomed];
- } else {
- NSRect rectScreen = [[NSScreen mainScreen] visibleFrame];
- NSRect rectWindow = [window_ frame];
- return (rectScreen.origin.x == rectWindow.origin.x &&
- rectScreen.origin.y == rectWindow.origin.y &&
- rectScreen.size.width == rectWindow.size.width &&
- rectScreen.size.height == rectWindow.size.height);
- }
- }
- void NativeWindowMac::Minimize() {
- [window_ miniaturize:nil];
- }
- void NativeWindowMac::Restore() {
- [window_ deminiaturize:nil];
- }
- bool NativeWindowMac::IsMinimized() {
- return [window_ isMiniaturized];
- }
- void NativeWindowMac::SetFullScreen(bool fullscreen) {
- if (fullscreen == IsFullscreen())
- return;
- [window_ toggleFullScreenMode:nil];
- }
- bool NativeWindowMac::IsFullscreen() const {
- return [window_ styleMask] & NSFullScreenWindowMask;
- }
- void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) {
- // Do nothing if in fullscreen mode.
- if (IsFullscreen())
- return;
- // Check size constraints since setFrame does not check it.
- gfx::Size size = bounds.size();
- size.SetToMax(GetMinimumSize());
- gfx::Size max_size = GetMaximumSize();
- if (!max_size.IsEmpty())
- size.SetToMin(max_size);
- NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height());
- // Flip coordinates based on the primary screen.
- NSScreen* screen = [[NSScreen screens] firstObject];
- cocoa_bounds.origin.y =
- NSHeight([screen frame]) - size.height() - bounds.y();
- [window_ setFrame:cocoa_bounds display:YES animate:animate];
- }
- gfx::Rect NativeWindowMac::GetBounds() {
- NSRect frame = [window_ frame];
- gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
- NSScreen* screen = [[NSScreen screens] firstObject];
- bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
- return bounds;
- }
- void NativeWindowMac::SetContentSizeConstraints(
- const extensions::SizeConstraints& size_constraints) {
- auto convertSize = [this](const gfx::Size& size) {
- // Our frameless window still has titlebar attached, so setting contentSize
- // will result in actual content size being larger.
- if (!has_frame()) {
- NSRect frame = NSMakeRect(0, 0, size.width(), size.height());
- NSRect content = [window_ contentRectForFrameRect:frame];
- return content.size;
- } else {
- return NSMakeSize(size.width(), size.height());
- }
- };
- NSView* content = [window_ contentView];
- if (size_constraints.HasMinimumSize()) {
- NSSize min_size = convertSize(size_constraints.GetMinimumSize());
- [window_ setContentMinSize:[content convertSize:min_size toView:nil]];
- }
- if (size_constraints.HasMaximumSize()) {
- NSSize max_size = convertSize(size_constraints.GetMaximumSize());
- [window_ setContentMaxSize:[content convertSize:max_size toView:nil]];
- }
- NativeWindow::SetContentSizeConstraints(size_constraints);
- }
- void NativeWindowMac::SetResizable(bool resizable) {
- SetStyleMask(resizable, NSResizableWindowMask);
- }
- bool NativeWindowMac::IsResizable() {
- return [window_ styleMask] & NSResizableWindowMask;
- }
- void NativeWindowMac::SetAspectRatio(double aspect_ratio,
- const gfx::Size& extra_size) {
- NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
- // Reset the behaviour to default if aspect_ratio is set to 0 or less.
- if (aspect_ratio > 0.0)
- [window_ setAspectRatio:NSMakeSize(aspect_ratio, 1.0)];
- else
- [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)];
- }
- void NativeWindowMac::PreviewFile(const std::string& path,
- const std::string& display_name) {
- NSString* path_ns = [NSString stringWithUTF8String:path.c_str()];
- NSString* name_ns = [NSString stringWithUTF8String:display_name.c_str()];
- [window_ previewFileAtPath:path_ns withName:name_ns];
- }
- void NativeWindowMac::CloseFilePreview() {
- if ([QLPreviewPanel sharedPreviewPanelExists]) {
- [[QLPreviewPanel sharedPreviewPanel] close];
- }
- }
- void NativeWindowMac::SetMovable(bool movable) {
- [window_ setMovable:movable];
- }
- bool NativeWindowMac::IsMovable() {
- return [window_ isMovable];
- }
- void NativeWindowMac::SetMinimizable(bool minimizable) {
- SetStyleMask(minimizable, NSMiniaturizableWindowMask);
- }
- bool NativeWindowMac::IsMinimizable() {
- return [window_ styleMask] & NSMiniaturizableWindowMask;
- }
- void NativeWindowMac::SetMaximizable(bool maximizable) {
- [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable];
- }
- bool NativeWindowMac::IsMaximizable() {
- return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled];
- }
- void NativeWindowMac::SetFullScreenable(bool fullscreenable) {
- SetCollectionBehavior(
- fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary);
- // On EL Capitan this flag is required to hide fullscreen button.
- SetCollectionBehavior(
- !fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary);
- }
- bool NativeWindowMac::IsFullScreenable() {
- NSUInteger collectionBehavior = [window_ collectionBehavior];
- return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary;
- }
- void NativeWindowMac::SetClosable(bool closable) {
- SetStyleMask(closable, NSClosableWindowMask);
- }
- bool NativeWindowMac::IsClosable() {
- return [window_ styleMask] & NSClosableWindowMask;
- }
- void NativeWindowMac::SetAlwaysOnTop(bool top, const std::string& level,
- int relativeLevel, std::string* error) {
- int windowLevel = NSNormalWindowLevel;
- CGWindowLevel maxWindowLevel = CGWindowLevelForKey(kCGMaximumWindowLevelKey);
- CGWindowLevel minWindowLevel = CGWindowLevelForKey(kCGMinimumWindowLevelKey);
- if (top) {
- if (level == "floating") {
- windowLevel = NSFloatingWindowLevel;
- } else if (level == "torn-off-menu") {
- windowLevel = NSTornOffMenuWindowLevel;
- } else if (level == "modal-panel") {
- windowLevel = NSModalPanelWindowLevel;
- } else if (level == "main-menu") {
- windowLevel = NSMainMenuWindowLevel;
- } else if (level == "status") {
- windowLevel = NSStatusWindowLevel;
- } else if (level == "pop-up-menu") {
- windowLevel = NSPopUpMenuWindowLevel;
- } else if (level == "screen-saver") {
- windowLevel = NSScreenSaverWindowLevel;
- } else if (level == "dock") {
- // Deprecated by macOS, but kept for backwards compatibility
- windowLevel = NSDockWindowLevel;
- }
- }
- NSInteger newLevel = windowLevel + relativeLevel;
- if (newLevel >= minWindowLevel && newLevel <= maxWindowLevel) {
- [window_ setLevel:newLevel];
- } else {
- *error = std::string([[NSString stringWithFormat:
- @"relativeLevel must be between %d and %d", minWindowLevel,
- maxWindowLevel] UTF8String]);
- }
- }
- bool NativeWindowMac::IsAlwaysOnTop() {
- return [window_ level] != NSNormalWindowLevel;
- }
- void NativeWindowMac::Center() {
- [window_ center];
- }
- void NativeWindowMac::Invalidate() {
- [window_ flushWindow];
- [[window_ contentView] setNeedsDisplay:YES];
- }
- void NativeWindowMac::SetTitle(const std::string& title) {
- // For macOS <= 10.9, the setTitleVisibility API is not available, we have
- // to avoid calling setTitle for frameless window.
- if (!base::mac::IsAtLeastOS10_10() && (transparent() || !has_frame()))
- return;
- [window_ setTitle:base::SysUTF8ToNSString(title)];
- }
- std::string NativeWindowMac::GetTitle() {
- return base::SysNSStringToUTF8([window_ title]);;
- }
- void NativeWindowMac::FlashFrame(bool flash) {
- if (flash) {
- attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest];
- } else {
- [NSApp cancelUserAttentionRequest:attention_request_id_];
- attention_request_id_ = 0;
- }
- }
- void NativeWindowMac::SetSkipTaskbar(bool skip) {
- }
- void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) {
- NSWindow* window = GetNativeWindow();
- if (simple_fullscreen && !is_simple_fullscreen_) {
- is_simple_fullscreen_ = true;
- // Take note of the current window size and level
- original_frame_ = [window frame];
- original_level_ = [window level];
- simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions];
- simple_fullscreen_mask_ = [window styleMask];
- // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu bar
- NSApplicationPresentationOptions options =
- NSApplicationPresentationAutoHideDock +
- NSApplicationPresentationAutoHideMenuBar;
- [NSApp setPresentationOptions:options];
- was_maximizable_ = IsMaximizable();
- was_movable_ = IsMovable();
- NSRect fullscreenFrame = [window.screen frame];
- // If our app has dock hidden, set the window level higher so another app's
- // menu bar doesn't appear on top of our fullscreen app.
- if ([[NSRunningApplication currentApplication] activationPolicy] !=
- NSApplicationActivationPolicyRegular) {
- window.level = NSPopUpMenuWindowLevel;
- }
- if ( !fullscreen_window_title() ) {
- // Hide the titlebar
- SetStyleMask(false, NSTitledWindowMask);
- // Resize the window to accomodate the _entire_ screen size
- fullscreenFrame.size.height -= [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
- } else {
- // No need to hide the title, but we should still hide the window buttons
- [[window standardWindowButton:NSWindowZoomButton] setHidden:YES];
- [[window standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];
- [[window standardWindowButton:NSWindowCloseButton] setHidden:YES];
- }
- [window setFrame:fullscreenFrame display: YES animate: YES];
- // Fullscreen windows can't be resized, minimized, maximized, or moved
- SetMinimizable(false);
- SetResizable(false);
- SetMaximizable(false);
- SetMovable(false);
- } else if (!simple_fullscreen && is_simple_fullscreen_) {
- is_simple_fullscreen_ = false;
- if ( !fullscreen_window_title() ) {
- // Restore the titlebar
- SetStyleMask(true, NSTitledWindowMask);
- } else {
- // Show the window buttons
- [[window standardWindowButton:NSWindowZoomButton] setHidden:NO];
- [[window standardWindowButton:NSWindowMiniaturizeButton] setHidden:NO];
- [[window standardWindowButton:NSWindowCloseButton] setHidden:NO];
- }
- [window setFrame:original_frame_ display: YES animate: YES];
- window.level = original_level_;
- [NSApp setPresentationOptions:simple_fullscreen_options_];
- // Restore original style mask
- ScopedDisableResize disable_resize;
- [window_ setStyleMask:simple_fullscreen_mask_];
- // Restore window manipulation abilities
- SetMaximizable(was_maximizable_);
- SetMovable(was_movable_);
- }
- }
- bool NativeWindowMac::IsSimpleFullScreen() {
- return is_simple_fullscreen_;
- }
- void NativeWindowMac::SetKiosk(bool kiosk) {
- if (kiosk && !is_kiosk_) {
- kiosk_options_ = [NSApp currentSystemPresentationOptions];
- NSApplicationPresentationOptions options =
- NSApplicationPresentationHideDock +
- NSApplicationPresentationHideMenuBar +
- NSApplicationPresentationDisableAppleMenu +
- NSApplicationPresentationDisableProcessSwitching +
- NSApplicationPresentationDisableForceQuit +
- NSApplicationPresentationDisableSessionTermination +
- NSApplicationPresentationDisableHideApplication;
- [NSApp setPresentationOptions:options];
- is_kiosk_ = true;
- was_fullscreen_ = IsFullscreen();
- if (!was_fullscreen_) SetFullScreen(true);
- } else if (!kiosk && is_kiosk_) {
- is_kiosk_ = false;
- if (!was_fullscreen_) SetFullScreen(false);
- [NSApp setPresentationOptions:kiosk_options_];
- }
- }
- bool NativeWindowMac::IsKiosk() {
- return is_kiosk_;
- }
- void NativeWindowMac::SetBackgroundColor(const std::string& color_name) {
- SkColor color = ParseHexColor(color_name);
- base::ScopedCFTypeRef<CGColorRef> cgcolor(
- skia::CGColorCreateFromSkColor(color));
- [[[window_ contentView] layer] setBackgroundColor:cgcolor];
- const auto view = web_contents()->GetRenderWidgetHostView();
- if (view)
- view->SetBackgroundColor(color);
- }
- void NativeWindowMac::SetHasShadow(bool has_shadow) {
- [window_ setHasShadow:has_shadow];
- }
- bool NativeWindowMac::HasShadow() {
- return [window_ hasShadow];
- }
- void NativeWindowMac::SetOpacity(const double opacity) {
- [window_ setAlphaValue:opacity];
- }
- double NativeWindowMac::GetOpacity() {
- return [window_ alphaValue];
- }
- void NativeWindowMac::SetRepresentedFilename(const std::string& filename) {
- [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)];
- }
- std::string NativeWindowMac::GetRepresentedFilename() {
- return base::SysNSStringToUTF8([window_ representedFilename]);
- }
- void NativeWindowMac::SetDocumentEdited(bool edited) {
- [window_ setDocumentEdited:edited];
- }
- bool NativeWindowMac::IsDocumentEdited() {
- return [window_ isDocumentEdited];
- }
- void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool) {
- [window_ setIgnoresMouseEvents:ignore];
- }
- void NativeWindowMac::SetContentProtection(bool enable) {
- [window_ setSharingType:enable ? NSWindowSharingNone
- : NSWindowSharingReadOnly];
- }
- void NativeWindowMac::SetBrowserView(NativeBrowserView* browser_view) {
- if (browser_view_) {
- [browser_view_->GetInspectableWebContentsView()->GetNativeView()
- removeFromSuperview];
- browser_view_ = nullptr;
- }
- if (!browser_view) {
- return;
- }
- browser_view_ = browser_view;
- auto* native_view =
- browser_view->GetInspectableWebContentsView()->GetNativeView();
- [[window_ contentView] addSubview:native_view
- positioned:NSWindowAbove
- relativeTo:nil];
- native_view.hidden = NO;
- }
- void NativeWindowMac::SetParentWindow(NativeWindow* parent) {
- InternalSetParentWindow(parent, IsVisible());
- }
- gfx::NativeView NativeWindowMac::GetNativeView() const {
- return inspectable_web_contents()->GetView()->GetNativeView();
- }
- gfx::NativeWindow NativeWindowMac::GetNativeWindow() const {
- return window_;
- }
- gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const {
- return inspectable_web_contents()->GetView()->GetNativeView();
- }
- void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) {
- NSDockTile* dock_tile = [NSApp dockTile];
- // For the first time API invoked, we need to create a ContentView in DockTile.
- if (dock_tile.contentView == nullptr) {
- NSImageView* image_view = [[NSImageView alloc] init];
- [image_view setImage:[NSApp applicationIconImage]];
- [dock_tile setContentView:image_view];
- }
- if ([[dock_tile.contentView subviews] count] == 0) {
- NSProgressIndicator* progress_indicator = [[AtomProgressBar alloc]
- initWithFrame:NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0)];
- [progress_indicator setStyle:NSProgressIndicatorBarStyle];
- [progress_indicator setIndeterminate:NO];
- [progress_indicator setBezeled:YES];
- [progress_indicator setMinValue:0];
- [progress_indicator setMaxValue:1];
- [progress_indicator setHidden:NO];
- [dock_tile.contentView addSubview:progress_indicator];
- }
- NSProgressIndicator* progress_indicator =
- static_cast<NSProgressIndicator*>([[[dock_tile contentView] subviews]
- objectAtIndex:0]);
- if (progress < 0) {
- [progress_indicator setHidden:YES];
- } else if (progress > 1) {
- [progress_indicator setHidden:NO];
- [progress_indicator setIndeterminate:YES];
- [progress_indicator setDoubleValue:1];
- } else {
- [progress_indicator setHidden:NO];
- [progress_indicator setDoubleValue:progress];
- }
- [dock_tile display];
- }
- void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay,
- const std::string& description) {
- }
- void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible) {
- SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces);
- }
- bool NativeWindowMac::IsVisibleOnAllWorkspaces() {
- NSUInteger collectionBehavior = [window_ collectionBehavior];
- return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces;
- }
- void NativeWindowMac::SetAutoHideCursor(bool auto_hide) {
- [window_ setDisableAutoHideCursor:!auto_hide];
- }
- void NativeWindowMac::SelectPreviousTab() {
- if ([window_ respondsToSelector:@selector(selectPreviousTab:)]) {
- [window_ selectPreviousTab:nil];
- }
- }
- void NativeWindowMac::SelectNextTab() {
- if ([window_ respondsToSelector:@selector(selectNextTab:)]) {
- [window_ selectNextTab:nil];
- }
- }
- void NativeWindowMac::MergeAllWindows() {
- if ([window_ respondsToSelector:@selector(mergeAllWindows:)]) {
- [window_ mergeAllWindows:nil];
- }
- }
- void NativeWindowMac::MoveTabToNewWindow() {
- if ([window_ respondsToSelector:@selector(moveTabToNewWindow:)]) {
- [window_ moveTabToNewWindow:nil];
- }
- }
- void NativeWindowMac::ToggleTabBar() {
- if ([window_ respondsToSelector:@selector(toggleTabBar:)]) {
- [window_ toggleTabBar:nil];
- }
- }
- bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) {
- if (window_.get() == window->GetNativeWindow()) {
- return false;
- } else {
- if ([window_ respondsToSelector:@selector(addTabbedWindow:ordered:)])
- [window_ addTabbedWindow:window->GetNativeWindow() ordered:NSWindowAbove];
- }
- return true;
- }
- void NativeWindowMac::SetRenderWidgetHostOpaque(bool opaque) {
- if (!web_contents()) return;
- auto render_view_host = web_contents()->GetRenderViewHost();
- if (!render_view_host) return;
- content::RenderWidgetHostImpl* impl = content::RenderWidgetHostImpl::FromID(
- render_view_host->GetProcess()->GetID(),
- render_view_host->GetRoutingID());
- if (!impl) return;
- impl->SetBackgroundOpaque(opaque);
- }
- void NativeWindowMac::SetVibrancy(const std::string& type) {
- if (!base::mac::IsAtLeastOS10_10()) return;
- NSView* vibrant_view = [window_ vibrantView];
- if (type.empty()) {
- if (background_color_before_vibrancy_) {
- [window_ setBackgroundColor:background_color_before_vibrancy_];
- [window_ setTitlebarAppearsTransparent:transparency_before_vibrancy_];
- }
- SetRenderWidgetHostOpaque(!transparent());
- if (vibrant_view == nil) return;
- [vibrant_view removeFromSuperview];
- [window_ setVibrantView:nil];
- ui::GpuSwitchingManager::SetTransparent(transparent());
- return;
- }
- SetRenderWidgetHostOpaque(false);
- background_color_before_vibrancy_.reset([window_ backgroundColor]);
- transparency_before_vibrancy_ = [window_ titlebarAppearsTransparent];
- ui::GpuSwitchingManager::SetTransparent(true);
- if (title_bar_style_ != NORMAL) {
- [window_ setTitlebarAppearsTransparent:YES];
- [window_ setBackgroundColor:[NSColor clearColor]];
- }
- NSVisualEffectView* effect_view = (NSVisualEffectView*)vibrant_view;
- if (effect_view == nil) {
- effect_view = [[[NSVisualEffectView alloc]
- initWithFrame: [[window_ contentView] bounds]] autorelease];
- [window_ setVibrantView:(NSView*)effect_view];
- [effect_view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
- [effect_view setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
- [effect_view setState:NSVisualEffectStateActive];
- [[window_ contentView] addSubview:effect_view
- positioned:NSWindowBelow
- relativeTo:nil];
- }
- NSVisualEffectMaterial vibrancyType = NSVisualEffectMaterialLight;
- if (type == "appearance-based") {
- vibrancyType = NSVisualEffectMaterialAppearanceBased;
- } else if (type == "light") {
- vibrancyType = NSVisualEffectMaterialLight;
- } else if (type == "dark") {
- vibrancyType = NSVisualEffectMaterialDark;
- } else if (type == "titlebar") {
- vibrancyType = NSVisualEffectMaterialTitlebar;
- }
- if (base::mac::IsAtLeastOS10_11()) {
- // TODO(kevinsawicki): Use NSVisualEffectMaterial* constants directly once
- // they are available in the minimum SDK version
- if (type == "selection") {
- // NSVisualEffectMaterialSelection
- vibrancyType = static_cast<NSVisualEffectMaterial>(4);
- } else if (type == "menu") {
- // NSVisualEffectMaterialMenu
- vibrancyType = static_cast<NSVisualEffectMaterial>(5);
- } else if (type == "popover") {
- // NSVisualEffectMaterialPopover
- vibrancyType = static_cast<NSVisualEffectMaterial>(6);
- } else if (type == "sidebar") {
- // NSVisualEffectMaterialSidebar
- vibrancyType = static_cast<NSVisualEffectMaterial>(7);
- } else if (type == "medium-light") {
- // NSVisualEffectMaterialMediumLight
- vibrancyType = static_cast<NSVisualEffectMaterial>(8);
- } else if (type == "ultra-dark") {
- // NSVisualEffectMaterialUltraDark
- vibrancyType = static_cast<NSVisualEffectMaterial>(9);
- }
- }
- [effect_view setMaterial:vibrancyType];
- }
- void NativeWindowMac::SetTouchBar(
- const std::vector<mate::PersistentDictionary>& items) {
- [window_ resetTouchBar:items];
- }
- void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) {
- [window_ refreshTouchBarItem:item_id];
- }
- void NativeWindowMac::SetEscapeTouchBarItem(const mate::PersistentDictionary& item) {
- [window_ setEscapeTouchBarItem:item];
- }
- void NativeWindowMac::OnInputEvent(const blink::WebInputEvent& event) {
- switch (event.GetType()) {
- case blink::WebInputEvent::kGestureScrollBegin:
- case blink::WebInputEvent::kGestureScrollUpdate:
- case blink::WebInputEvent::kGestureScrollEnd:
- this->NotifyWindowScrollTouchEdge();
- break;
- default:
- break;
- }
- }
- void NativeWindowMac::RenderViewHostChanged(
- content::RenderViewHost* old_host,
- content::RenderViewHost* new_host) {
- UnregisterInputEventObserver(old_host);
- RegisterInputEventObserver(new_host);
- }
- std::vector<gfx::Rect> NativeWindowMac::CalculateNonDraggableRegions(
- const std::vector<DraggableRegion>& regions, int width, int height) {
- std::vector<gfx::Rect> result;
- if (regions.empty()) {
- result.push_back(gfx::Rect(0, 0, width, height));
- } else {
- std::unique_ptr<SkRegion> draggable(DraggableRegionsToSkRegion(regions));
- std::unique_ptr<SkRegion> non_draggable(new SkRegion);
- non_draggable->op(0, 0, width, height, SkRegion::kUnion_Op);
- non_draggable->op(*draggable, SkRegion::kDifference_Op);
- for (SkRegion::Iterator it(*non_draggable); !it.done(); it.next()) {
- result.push_back(gfx::SkIRectToRect(it.rect()));
- }
- }
- return result;
- }
- gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds(
- const gfx::Rect& bounds) const {
- if (has_frame()) {
- gfx::Rect window_bounds(
- [window_ frameRectForContentRect:bounds.ToCGRect()]);
- int frame_height = window_bounds.height() - bounds.height();
- window_bounds.set_y(window_bounds.y() - frame_height);
- return window_bounds;
- } else {
- return bounds;
- }
- }
- gfx::Rect NativeWindowMac::WindowBoundsToContentBounds(
- const gfx::Rect& bounds) const {
- if (has_frame()) {
- gfx::Rect content_bounds(
- [window_ contentRectForFrameRect:bounds.ToCGRect()]);
- int frame_height = bounds.height() - content_bounds.height();
- content_bounds.set_y(content_bounds.y() + frame_height);
- return content_bounds;
- } else {
- return bounds;
- }
- }
- void NativeWindowMac::UpdateDraggableRegions(
- content::RenderFrameHost* rfh,
- const std::vector<DraggableRegion>& regions) {
- NativeWindow::UpdateDraggableRegions(rfh, regions);
- draggable_regions_ = regions;
- UpdateDraggableRegionViews(regions);
- }
- void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) {
- if (is_modal())
- return;
- NativeWindow::SetParentWindow(parent);
- // Do not remove/add if we are already properly attached.
- if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow())
- return;
- // Remove current parent window.
- if ([window_ parentWindow])
- [[window_ parentWindow] removeChildWindow:window_];
- // Set new parent window.
- // Note that this method will force the window to become visible.
- if (parent && attach)
- [parent->GetNativeWindow() addChildWindow:window_ ordered:NSWindowAbove];
- }
- void NativeWindowMac::ShowWindowButton(NSWindowButton button) {
- auto view = [window_ standardWindowButton:button];
- [view.superview addSubview:view positioned:NSWindowAbove relativeTo:nil];
- }
- void NativeWindowMac::InstallView() {
- // Make sure the bottom corner is rounded for non-modal windows: http://crbug.com/396264.
- // But do not enable it on OS X 10.9 for transparent window, otherwise a
- // semi-transparent frame would show.
- if (!(transparent() && base::mac::IsOS10_9()) && !is_modal())
- [[window_ contentView] setWantsLayer:YES];
- NSView* view = inspectable_web_contents()->GetView()->GetNativeView();
- if (has_frame()) {
- [view setFrame:[[window_ contentView] bounds]];
- [[window_ contentView] addSubview:view];
- } else {
- // In OSX 10.10, adding subviews to the root view for the NSView hierarchy
- // produces warnings. To eliminate the warnings, we resize the contentView
- // to fill the window, and add subviews to that.
- // http://crbug.com/380412
- content_view_.reset([[FullSizeContentView alloc] init]);
- [content_view_
- setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
- [content_view_ setFrame:[[[window_ contentView] superview] bounds]];
- [window_ setContentView:content_view_];
- [view setFrame:[content_view_ bounds]];
- [content_view_ addSubview:view];
- // The fullscreen button should always be hidden for frameless window.
- [[window_ standardWindowButton:NSWindowFullScreenButton] setHidden:YES];
- if (title_bar_style_ == CUSTOM_BUTTONS_ON_HOVER) {
- NSView* window_button_view = [[[CustomWindowButtonView alloc]
- initWithFrame:NSZeroRect] autorelease];
- [content_view_ addSubview:window_button_view];
- } else {
- if (title_bar_style_ != NORMAL) {
- if (base::mac::IsOS10_9()) {
- ShowWindowButton(NSWindowZoomButton);
- ShowWindowButton(NSWindowMiniaturizeButton);
- ShowWindowButton(NSWindowCloseButton);
- }
- return;
- }
- // Hide the window buttons.
- [[window_ standardWindowButton:NSWindowZoomButton] setHidden:YES];
- [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];
- [[window_ standardWindowButton:NSWindowCloseButton] setHidden:YES];
- }
- // Some third-party macOS utilities check the zoom button's enabled state to
- // determine whether to show custom UI on hover, so we disable it here to
- // prevent them from doing so in a frameless app window.
- [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:NO];
- }
- }
- void NativeWindowMac::UninstallView() {
- NSView* view = inspectable_web_contents()->GetView()->GetNativeView();
- [view removeFromSuperview];
- }
- void NativeWindowMac::UpdateDraggableRegionViews(
- const std::vector<DraggableRegion>& regions) {
- if (has_frame())
- return;
- // All ControlRegionViews should be added as children of the WebContentsView,
- // because WebContentsView will be removed and re-added when entering and
- // leaving fullscreen mode.
- NSView* webView = web_contents()->GetNativeView();
- NSInteger webViewWidth = NSWidth([webView bounds]);
- NSInteger webViewHeight = NSHeight([webView bounds]);
- if ([webView respondsToSelector:@selector(setMouseDownCanMoveWindow:)]) {
- [webView setMouseDownCanMoveWindow:YES];
- }
- // Remove all ControlRegionViews that are added last time.
- // Note that [webView subviews] returns the view's mutable internal array and
- // it should be copied to avoid mutating the original array while enumerating
- // it.
- base::scoped_nsobject<NSArray> subviews([[webView subviews] copy]);
- for (NSView* subview in subviews.get())
- if ([subview isKindOfClass:[ControlRegionView class]])
- [subview removeFromSuperview];
- // Draggable regions is implemented by having the whole web view draggable
- // (mouseDownCanMoveWindow) and overlaying regions that are not draggable.
- std::vector<gfx::Rect> drag_exclude_rects =
- CalculateNonDraggableRegions(regions, webViewWidth, webViewHeight);
- if (browser_view_) {
- browser_view_->UpdateDraggableRegions(drag_exclude_rects);
- }
- // Create and add a ControlRegionView for each region that needs to be
- // excluded from the dragging.
- for (const auto& rect : drag_exclude_rects) {
- base::scoped_nsobject<NSView> controlRegion(
- [[ControlRegionView alloc] initWithFrame:NSZeroRect]);
- [controlRegion setFrame:NSMakeRect(rect.x(), webViewHeight - rect.bottom(),
- rect.width(), rect.height())];
- [webView addSubview:controlRegion];
- }
- // AppKit will not update its cache of mouseDownCanMoveWindow unless something
- // changes. Previously we tried adding an NSView and removing it, but for some
- // reason it required reposting the mouse-down event, and didn't always work.
- // Calling the below seems to be an effective solution.
- [window_ setMovableByWindowBackground:NO];
- [window_ setMovableByWindowBackground:YES];
- }
- void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) {
- // Changing the styleMask of a frameless windows causes it to change size so
- // we explicitly disable resizing while setting it.
- ScopedDisableResize disable_resize;
- bool was_maximizable = IsMaximizable();
- if (on)
- [window_ setStyleMask:[window_ styleMask] | flag];
- else
- [window_ setStyleMask:[window_ styleMask] & (~flag)];
- // Change style mask will make the zoom button revert to default, probably
- // a bug of Cocoa or macOS.
- SetMaximizable(was_maximizable);
- }
- void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) {
- bool was_maximizable = IsMaximizable();
- if (on)
- [window_ setCollectionBehavior:[window_ collectionBehavior] | flag];
- else
- [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)];
- // Change collectionBehavior will make the zoom button revert to default,
- // probably a bug of Cocoa or macOS.
- SetMaximizable(was_maximizable);
- }
- void NativeWindowMac::RegisterInputEventObserver(
- content::RenderViewHost* host) {
- if (host)
- host->GetWidget()->AddInputEventObserver(this);
- }
- void NativeWindowMac::UnregisterInputEventObserver(
- content::RenderViewHost* host) {
- if (host)
- host->GetWidget()->RemoveInputEventObserver(this);
- }
- // static
- NativeWindow* NativeWindow::Create(
- brightray::InspectableWebContents* inspectable_web_contents,
- const mate::Dictionary& options,
- NativeWindow* parent) {
- return new NativeWindowMac(inspectable_web_contents, options, parent);
- }
- } // namespace atom
|