native_window_mac.mm 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948
  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 "shell/browser/native_window_mac.h"
  5. #include <AvailabilityMacros.h>
  6. #include <objc/objc-runtime.h>
  7. #include <algorithm>
  8. #include <string>
  9. #include <utility>
  10. #include <vector>
  11. #include "base/mac/mac_util.h"
  12. #include "base/mac/scoped_cftyperef.h"
  13. #include "base/numerics/ranges.h"
  14. #include "base/strings/sys_string_conversions.h"
  15. #include "base/task/post_task.h"
  16. #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
  17. #include "content/public/browser/browser_accessibility_state.h"
  18. #include "content/public/browser/browser_task_traits.h"
  19. #include "content/public/browser/browser_thread.h"
  20. #include "content/public/browser/desktop_media_id.h"
  21. #include "shell/browser/native_browser_view_mac.h"
  22. #include "shell/browser/ui/cocoa/electron_native_widget_mac.h"
  23. #include "shell/browser/ui/cocoa/electron_ns_window.h"
  24. #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h"
  25. #include "shell/browser/ui/cocoa/electron_preview_item.h"
  26. #include "shell/browser/ui/cocoa/electron_touch_bar.h"
  27. #include "shell/browser/ui/cocoa/root_view_mac.h"
  28. #include "shell/browser/ui/inspectable_web_contents.h"
  29. #include "shell/browser/ui/inspectable_web_contents_view.h"
  30. #include "shell/browser/window_list.h"
  31. #include "shell/common/gin_converters/gfx_converter.h"
  32. #include "shell/common/gin_helper/dictionary.h"
  33. #include "shell/common/options_switches.h"
  34. #include "shell/common/process_util.h"
  35. #include "skia/ext/skia_utils_mac.h"
  36. #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h"
  37. #include "ui/display/screen.h"
  38. #include "ui/gfx/skia_util.h"
  39. #include "ui/gl/gpu_switching_manager.h"
  40. #include "ui/views/background.h"
  41. #include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
  42. #include "ui/views/widget/widget.h"
  43. // This view would inform Chromium to resize the hosted views::View.
  44. //
  45. // The overrided methods should behave the same with BridgedContentView.
  46. @interface ElectronAdaptedContentView : NSView {
  47. @private
  48. views::NativeWidgetMacNSWindowHost* bridge_host_;
  49. }
  50. @end
  51. @implementation ElectronAdaptedContentView
  52. - (id)initWithShell:(electron::NativeWindowMac*)shell {
  53. if ((self = [self init])) {
  54. bridge_host_ = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow(
  55. shell->GetNativeWindow());
  56. }
  57. return self;
  58. }
  59. - (void)viewDidMoveToWindow {
  60. // When this view is added to a window, AppKit calls setFrameSize before it is
  61. // added to the window, so the behavior in setFrameSize is not triggered.
  62. NSWindow* window = [self window];
  63. if (window)
  64. [self setFrameSize:NSZeroSize];
  65. }
  66. - (void)setFrameSize:(NSSize)newSize {
  67. // The size passed in here does not always use
  68. // -[NSWindow contentRectForFrameRect]. The following ensures that the
  69. // contentView for a frameless window can extend over the titlebar of the new
  70. // window containing it, since AppKit requires a titlebar to give frameless
  71. // windows correct shadows and rounded corners.
  72. NSWindow* window = [self window];
  73. if (window && [window contentView] == self) {
  74. newSize = [window contentRectForFrameRect:[window frame]].size;
  75. // Ensure that the window geometry be updated on the host side before the
  76. // view size is updated.
  77. bridge_host_->GetInProcessNSWindowBridge()->UpdateWindowGeometry();
  78. }
  79. [super setFrameSize:newSize];
  80. // The OnViewSizeChanged is marked private in derived class.
  81. static_cast<remote_cocoa::mojom::NativeWidgetNSWindowHost*>(bridge_host_)
  82. ->OnViewSizeChanged(gfx::Size(newSize.width, newSize.height));
  83. }
  84. @end
  85. // This view always takes the size of its superview. It is intended to be used
  86. // as a NSWindow's contentView. It is needed because NSWindow's implementation
  87. // explicitly resizes the contentView at inopportune times.
  88. @interface FullSizeContentView : NSView
  89. @end
  90. @implementation FullSizeContentView
  91. // This method is directly called by NSWindow during a window resize on OSX
  92. // 10.10.0, beta 2. We must override it to prevent the content view from
  93. // shrinking.
  94. - (void)setFrameSize:(NSSize)size {
  95. if ([self superview])
  96. size = [[self superview] bounds].size;
  97. [super setFrameSize:size];
  98. }
  99. // The contentView gets moved around during certain full-screen operations.
  100. // This is less than ideal, and should eventually be removed.
  101. - (void)viewDidMoveToSuperview {
  102. [self setFrame:[[self superview] bounds]];
  103. }
  104. @end
  105. // Custom Quit, Minimize and Full Screen button container for frameless
  106. // windows.
  107. @interface CustomWindowButtonView : NSView {
  108. @private
  109. BOOL mouse_inside_;
  110. }
  111. @end
  112. @implementation CustomWindowButtonView
  113. - (id)initWithFrame:(NSRect)frame {
  114. self = [super initWithFrame:frame];
  115. NSButton* close_button =
  116. [NSWindow standardWindowButton:NSWindowCloseButton
  117. forStyleMask:NSWindowStyleMaskTitled];
  118. [close_button setTag:1];
  119. NSButton* miniaturize_button =
  120. [NSWindow standardWindowButton:NSWindowMiniaturizeButton
  121. forStyleMask:NSWindowStyleMaskTitled];
  122. [miniaturize_button setTag:2];
  123. CGFloat x = 0;
  124. const CGFloat space_between = 20;
  125. [close_button setFrameOrigin:NSMakePoint(x, 0)];
  126. x += space_between;
  127. [self addSubview:close_button];
  128. [miniaturize_button setFrameOrigin:NSMakePoint(x, 0)];
  129. x += space_between;
  130. [self addSubview:miniaturize_button];
  131. const auto last_button_frame = miniaturize_button.frame;
  132. [self setFrameSize:NSMakeSize(last_button_frame.origin.x +
  133. last_button_frame.size.width,
  134. last_button_frame.size.height)];
  135. mouse_inside_ = NO;
  136. [self setNeedsDisplayForButtons];
  137. return self;
  138. }
  139. - (void)viewDidMoveToWindow {
  140. if (!self.window) {
  141. return;
  142. }
  143. // Stay in upper left corner.
  144. const CGFloat top_margin = 3;
  145. const CGFloat left_margin = 7;
  146. [self setAutoresizingMask:NSViewMaxXMargin | NSViewMinYMargin];
  147. [self setFrameOrigin:NSMakePoint(left_margin, self.window.frame.size.height -
  148. self.frame.size.height -
  149. top_margin)];
  150. }
  151. - (BOOL)_mouseInGroup:(NSButton*)button {
  152. return mouse_inside_;
  153. }
  154. - (void)updateTrackingAreas {
  155. auto tracking_area = [[[NSTrackingArea alloc]
  156. initWithRect:NSZeroRect
  157. options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways |
  158. NSTrackingInVisibleRect
  159. owner:self
  160. userInfo:nil] autorelease];
  161. [self addTrackingArea:tracking_area];
  162. }
  163. - (void)mouseEntered:(NSEvent*)event {
  164. [super mouseEntered:event];
  165. mouse_inside_ = YES;
  166. [self setNeedsDisplayForButtons];
  167. }
  168. - (void)mouseExited:(NSEvent*)event {
  169. [super mouseExited:event];
  170. mouse_inside_ = NO;
  171. [self setNeedsDisplayForButtons];
  172. }
  173. - (void)setNeedsDisplayForButtons {
  174. for (NSView* subview in self.subviews) {
  175. [subview setHidden:!mouse_inside_];
  176. [subview setNeedsDisplay:YES];
  177. }
  178. }
  179. @end
  180. @interface ElectronProgressBar : NSProgressIndicator
  181. @end
  182. @implementation ElectronProgressBar
  183. - (void)drawRect:(NSRect)dirtyRect {
  184. if (self.style != NSProgressIndicatorBarStyle)
  185. return;
  186. // Draw edges of rounded rect.
  187. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0);
  188. CGFloat radius = rect.size.height / 2;
  189. NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
  190. xRadius:radius
  191. yRadius:radius];
  192. [bezier_path setLineWidth:2.0];
  193. [[NSColor grayColor] set];
  194. [bezier_path stroke];
  195. // Fill the rounded rect.
  196. rect = NSInsetRect(rect, 2.0, 2.0);
  197. radius = rect.size.height / 2;
  198. bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
  199. xRadius:radius
  200. yRadius:radius];
  201. [bezier_path setLineWidth:1.0];
  202. [bezier_path addClip];
  203. // Calculate the progress width.
  204. rect.size.width =
  205. floor(rect.size.width * ([self doubleValue] / [self maxValue]));
  206. // Fill the progress bar with color blue.
  207. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set];
  208. NSRectFill(rect);
  209. }
  210. @end
  211. namespace gin {
  212. template <>
  213. struct Converter<electron::NativeWindowMac::TitleBarStyle> {
  214. static bool FromV8(v8::Isolate* isolate,
  215. v8::Handle<v8::Value> val,
  216. electron::NativeWindowMac::TitleBarStyle* out) {
  217. using TitleBarStyle = electron::NativeWindowMac::TitleBarStyle;
  218. std::string title_bar_style;
  219. if (!ConvertFromV8(isolate, val, &title_bar_style))
  220. return false;
  221. if (title_bar_style == "hidden") {
  222. *out = TitleBarStyle::kHidden;
  223. } else if (title_bar_style == "hiddenInset") {
  224. *out = TitleBarStyle::kHiddenInset;
  225. } else if (title_bar_style == "customButtonsOnHover") {
  226. *out = TitleBarStyle::kCustomButtonsOnHover;
  227. } else {
  228. return false;
  229. }
  230. return true;
  231. }
  232. };
  233. template <>
  234. struct Converter<electron::NativeWindowMac::VisualEffectState> {
  235. static bool FromV8(v8::Isolate* isolate,
  236. v8::Handle<v8::Value> val,
  237. electron::NativeWindowMac::VisualEffectState* out) {
  238. using VisualEffectState = electron::NativeWindowMac::VisualEffectState;
  239. std::string visual_effect_state;
  240. if (!ConvertFromV8(isolate, val, &visual_effect_state))
  241. return false;
  242. if (visual_effect_state == "followWindow") {
  243. *out = VisualEffectState::kFollowWindow;
  244. } else if (visual_effect_state == "active") {
  245. *out = VisualEffectState::kActive;
  246. } else if (visual_effect_state == "inactive") {
  247. *out = VisualEffectState::kInactive;
  248. } else {
  249. return false;
  250. }
  251. return true;
  252. }
  253. };
  254. } // namespace gin
  255. namespace electron {
  256. namespace {
  257. bool IsFramelessWindow(NSView* view) {
  258. NSWindow* nswindow = [view window];
  259. if (![nswindow respondsToSelector:@selector(shell)])
  260. return false;
  261. NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell];
  262. return window && !window->has_frame();
  263. }
  264. IMP original_set_frame_size = nullptr;
  265. IMP original_view_did_move_to_superview = nullptr;
  266. // This method is directly called by NSWindow during a window resize on OSX
  267. // 10.10.0, beta 2. We must override it to prevent the content view from
  268. // shrinking.
  269. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) {
  270. if (!IsFramelessWindow(self)) {
  271. auto original =
  272. reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size);
  273. return original(self, _cmd, size);
  274. }
  275. // For frameless window, resize the view to cover full window.
  276. if ([self superview])
  277. size = [[self superview] bounds].size;
  278. auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>(
  279. [[self superclass] instanceMethodForSelector:_cmd]);
  280. super_impl(self, _cmd, size);
  281. }
  282. // The contentView gets moved around during certain full-screen operations.
  283. // This is less than ideal, and should eventually be removed.
  284. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) {
  285. if (!IsFramelessWindow(self)) {
  286. // [BridgedContentView viewDidMoveToSuperview];
  287. auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>(
  288. original_view_did_move_to_superview);
  289. if (original)
  290. original(self, _cmd);
  291. return;
  292. }
  293. [self setFrame:[[self superview] bounds]];
  294. }
  295. } // namespace
  296. NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options,
  297. NativeWindow* parent)
  298. : NativeWindow(options, parent), root_view_(new RootViewMac(this)) {
  299. ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this);
  300. display::Screen::GetScreen()->AddObserver(this);
  301. int width = 800, height = 600;
  302. options.Get(options::kWidth, &width);
  303. options.Get(options::kHeight, &height);
  304. NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame];
  305. gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2),
  306. round((NSHeight(main_screen_rect) - height) / 2), width,
  307. height);
  308. options.Get(options::kResizable, &resizable_);
  309. options.Get(options::kTitleBarStyle, &title_bar_style_);
  310. options.Get(options::kZoomToPageWidth, &zoom_to_page_width_);
  311. options.Get(options::kFullscreenWindowTitle, &fullscreen_window_title_);
  312. options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_);
  313. options.Get(options::kTrafficLightPosition, &traffic_light_position_);
  314. options.Get(options::kVisualEffectState, &visual_effect_state_);
  315. bool minimizable = true;
  316. options.Get(options::kMinimizable, &minimizable);
  317. bool maximizable = true;
  318. options.Get(options::kMaximizable, &maximizable);
  319. bool closable = true;
  320. options.Get(options::kClosable, &closable);
  321. std::string tabbingIdentifier;
  322. options.Get(options::kTabbingIdentifier, &tabbingIdentifier);
  323. std::string windowType;
  324. options.Get(options::kType, &windowType);
  325. bool useStandardWindow = true;
  326. // eventually deprecate separate "standardWindow" option in favor of
  327. // standard / textured window types
  328. options.Get(options::kStandardWindow, &useStandardWindow);
  329. if (windowType == "textured") {
  330. useStandardWindow = false;
  331. }
  332. NSUInteger styleMask = NSWindowStyleMaskTitled;
  333. if (minimizable)
  334. styleMask |= NSMiniaturizableWindowMask;
  335. if (closable)
  336. styleMask |= NSWindowStyleMaskClosable;
  337. if (resizable_)
  338. styleMask |= NSResizableWindowMask;
  339. // The window without titlebar is treated the same with frameless window.
  340. if (title_bar_style_ != TitleBarStyle::kNormal)
  341. set_has_frame(false);
  342. if (!useStandardWindow || transparent() || !has_frame())
  343. styleMask |= NSTexturedBackgroundWindowMask;
  344. // Create views::Widget and assign window_ with it.
  345. // TODO(zcbenz): Get rid of the window_ in future.
  346. views::Widget::InitParams params;
  347. params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  348. params.bounds = bounds;
  349. params.delegate = this;
  350. params.type = views::Widget::InitParams::TYPE_WINDOW;
  351. params.native_widget = new ElectronNativeWidgetMac(this, styleMask, widget());
  352. widget()->Init(std::move(params));
  353. window_ = static_cast<ElectronNSWindow*>(
  354. widget()->GetNativeWindow().GetNativeNSWindow());
  355. [window_ setEnableLargerThanScreen:enable_larger_than_screen()];
  356. window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]);
  357. [window_ setDelegate:window_delegate_];
  358. // Only use native parent window for non-modal windows.
  359. if (parent && !is_modal()) {
  360. SetParentWindow(parent);
  361. }
  362. if (transparent()) {
  363. // Setting the background color to clear will also hide the shadow.
  364. [window_ setBackgroundColor:[NSColor clearColor]];
  365. }
  366. if (windowType == "desktop") {
  367. [window_ setLevel:kCGDesktopWindowLevel - 1];
  368. [window_ setDisableKeyOrMainWindow:YES];
  369. [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces |
  370. NSWindowCollectionBehaviorStationary |
  371. NSWindowCollectionBehaviorIgnoresCycle)];
  372. }
  373. bool focusable;
  374. if (options.Get(options::kFocusable, &focusable) && !focusable)
  375. [window_ setDisableKeyOrMainWindow:YES];
  376. if (transparent() || !has_frame()) {
  377. // Don't show title bar.
  378. [window_ setTitlebarAppearsTransparent:YES];
  379. [window_ setTitleVisibility:NSWindowTitleHidden];
  380. // Remove non-transparent corners, see http://git.io/vfonD.
  381. [window_ setOpaque:NO];
  382. }
  383. // Create a tab only if tabbing identifier is specified and window has
  384. // a native title bar.
  385. if (tabbingIdentifier.empty() || transparent() || !has_frame()) {
  386. if (@available(macOS 10.12, *)) {
  387. [window_ setTabbingMode:NSWindowTabbingModeDisallowed];
  388. }
  389. } else {
  390. if (@available(macOS 10.12, *)) {
  391. [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)];
  392. }
  393. }
  394. // Hide the title bar background
  395. if (title_bar_style_ != TitleBarStyle::kNormal) {
  396. [window_ setTitlebarAppearsTransparent:YES];
  397. }
  398. // Hide the title bar.
  399. if (title_bar_style_ == TitleBarStyle::kHiddenInset) {
  400. base::scoped_nsobject<NSToolbar> toolbar(
  401. [[NSToolbar alloc] initWithIdentifier:@"titlebarStylingToolbar"]);
  402. [toolbar setShowsBaselineSeparator:NO];
  403. [window_ setToolbar:toolbar];
  404. }
  405. // Resize to content bounds.
  406. bool use_content_size = false;
  407. options.Get(options::kUseContentSize, &use_content_size);
  408. if (!has_frame() || use_content_size)
  409. SetContentSize(gfx::Size(width, height));
  410. // Enable the NSView to accept first mouse event.
  411. bool acceptsFirstMouse = false;
  412. options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse);
  413. [window_ setAcceptsFirstMouse:acceptsFirstMouse];
  414. // Disable auto-hiding cursor.
  415. bool disableAutoHideCursor = false;
  416. options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor);
  417. [window_ setDisableAutoHideCursor:disableAutoHideCursor];
  418. // Use an NSEvent monitor to listen for the wheel event.
  419. BOOL __block began = NO;
  420. wheel_event_monitor_ = [NSEvent
  421. addLocalMonitorForEventsMatchingMask:NSEventMaskScrollWheel
  422. handler:^(NSEvent* event) {
  423. if ([[event window] windowNumber] !=
  424. [window_ windowNumber])
  425. return event;
  426. if (!began && (([event phase] ==
  427. NSEventPhaseMayBegin) ||
  428. ([event phase] ==
  429. NSEventPhaseBegan))) {
  430. this->NotifyWindowScrollTouchBegin();
  431. began = YES;
  432. } else if (began &&
  433. (([event phase] ==
  434. NSEventPhaseEnded) ||
  435. ([event phase] ==
  436. NSEventPhaseCancelled))) {
  437. this->NotifyWindowScrollTouchEnd();
  438. began = NO;
  439. }
  440. return event;
  441. }];
  442. // Set maximizable state last to ensure zoom button does not get reset
  443. // by calls to other APIs.
  444. SetMaximizable(maximizable);
  445. // Default content view.
  446. SetContentView(new views::View());
  447. AddContentViewLayers(minimizable, closable);
  448. original_frame_ = [window_ frame];
  449. original_level_ = [window_ level];
  450. }
  451. NativeWindowMac::~NativeWindowMac() {}
  452. void NativeWindowMac::Cleanup() {
  453. DCHECK(!IsClosed());
  454. ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this);
  455. display::Screen::GetScreen()->RemoveObserver(this);
  456. if (wheel_event_monitor_) {
  457. [NSEvent removeMonitor:wheel_event_monitor_];
  458. wheel_event_monitor_ = nil;
  459. }
  460. }
  461. void NativeWindowMac::RedrawTrafficLights() {
  462. // Ensure maximizable options retain pre-existing state.
  463. SetMaximizable(maximizable_);
  464. if (!traffic_light_position_.x() && !traffic_light_position_.y()) {
  465. return;
  466. }
  467. if (IsFullscreen())
  468. return;
  469. NSWindow* window = window_;
  470. NSButton* close = [window standardWindowButton:NSWindowCloseButton];
  471. NSButton* miniaturize =
  472. [window standardWindowButton:NSWindowMiniaturizeButton];
  473. NSButton* zoom = [window standardWindowButton:NSWindowZoomButton];
  474. // Safety check just in case apple changes the view structure in a macOS
  475. // update
  476. DCHECK(close.superview);
  477. DCHECK(close.superview.superview);
  478. if (!close.superview || !close.superview.superview)
  479. return;
  480. NSView* titleBarContainerView = close.superview.superview;
  481. // Hide the container when exiting fullscreen, otherwise traffic light buttons
  482. // jump
  483. if (fullscreen_transition_state_ == FullScreenTransitionState::EXITING) {
  484. [titleBarContainerView setHidden:YES];
  485. return;
  486. }
  487. [titleBarContainerView setHidden:NO];
  488. CGFloat buttonHeight = [close frame].size.height;
  489. CGFloat titleBarFrameHeight = buttonHeight + traffic_light_position_.y();
  490. CGRect titleBarRect = titleBarContainerView.frame;
  491. CGFloat titleBarWidth = NSWidth(titleBarRect);
  492. titleBarRect.size.height = titleBarFrameHeight;
  493. titleBarRect.origin.y = window.frame.size.height - titleBarFrameHeight;
  494. [titleBarContainerView setFrame:titleBarRect];
  495. BOOL isRTL = [titleBarContainerView userInterfaceLayoutDirection] ==
  496. NSUserInterfaceLayoutDirectionRightToLeft;
  497. NSArray* windowButtons = @[ close, miniaturize, zoom ];
  498. const CGFloat space_between =
  499. [miniaturize frame].origin.x - [close frame].origin.x;
  500. for (NSUInteger i = 0; i < windowButtons.count; i++) {
  501. NSView* view = [windowButtons objectAtIndex:i];
  502. CGRect rect = [view frame];
  503. if (isRTL) {
  504. CGFloat buttonWidth = NSWidth(rect);
  505. // origin is always top-left, even in RTL
  506. rect.origin.x = titleBarWidth - traffic_light_position_.x() +
  507. (i * space_between) - buttonWidth;
  508. } else {
  509. rect.origin.x = traffic_light_position_.x() + (i * space_between);
  510. }
  511. rect.origin.y = (titleBarFrameHeight - rect.size.height) / 2;
  512. [view setFrameOrigin:rect.origin];
  513. }
  514. }
  515. void NativeWindowMac::SetContentView(views::View* view) {
  516. views::View* root_view = GetContentsView();
  517. if (content_view())
  518. root_view->RemoveChildView(content_view());
  519. set_content_view(view);
  520. root_view->AddChildView(content_view());
  521. if (buttons_view_) {
  522. // Ensure the buttons view are always floated on the top.
  523. [buttons_view_ removeFromSuperview];
  524. [[window_ contentView] addSubview:buttons_view_];
  525. }
  526. root_view->Layout();
  527. }
  528. void NativeWindowMac::Close() {
  529. if (!IsClosable()) {
  530. WindowList::WindowCloseCancelled(this);
  531. return;
  532. }
  533. // If a sheet is attached to the window when we call
  534. // [window_ performClose:nil], the window won't close properly
  535. // even after the user has ended the sheet.
  536. // Ensure it's closed before calling [window_ performClose:nil].
  537. SetEnabled(true);
  538. [window_ performClose:nil];
  539. // Closing a sheet doesn't trigger windowShouldClose,
  540. // so we need to manually call it ourselves here.
  541. if (is_modal() && parent() && IsVisible()) {
  542. NotifyWindowCloseButtonClicked();
  543. }
  544. }
  545. void NativeWindowMac::CloseImmediately() {
  546. // Retain the child window before closing it. If the last reference to the
  547. // NSWindow goes away inside -[NSWindow close], then bad stuff can happen.
  548. // See e.g. http://crbug.com/616701.
  549. base::scoped_nsobject<NSWindow> child_window(window_,
  550. base::scoped_policy::RETAIN);
  551. [window_ close];
  552. }
  553. void NativeWindowMac::Focus(bool focus) {
  554. if (!IsVisible())
  555. return;
  556. if (focus) {
  557. [[NSApplication sharedApplication] activateIgnoringOtherApps:NO];
  558. [window_ makeKeyAndOrderFront:nil];
  559. } else {
  560. [window_ orderBack:nil];
  561. }
  562. }
  563. bool NativeWindowMac::IsFocused() {
  564. return [window_ isKeyWindow];
  565. }
  566. void NativeWindowMac::Show() {
  567. if (is_modal() && parent()) {
  568. NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow();
  569. if ([window_ sheetParent] == nil)
  570. [window beginSheet:window_
  571. completionHandler:^(NSModalResponse){
  572. }];
  573. return;
  574. }
  575. // Reattach the window to the parent to actually show it.
  576. if (parent())
  577. InternalSetParentWindow(parent(), true);
  578. // This method is supposed to put focus on window, however if the app does not
  579. // have focus then "makeKeyAndOrderFront" will only show the window.
  580. [NSApp activateIgnoringOtherApps:YES];
  581. [window_ makeKeyAndOrderFront:nil];
  582. }
  583. void NativeWindowMac::ShowInactive() {
  584. // Reattach the window to the parent to actually show it.
  585. if (parent())
  586. InternalSetParentWindow(parent(), true);
  587. [window_ orderFrontRegardless];
  588. }
  589. void NativeWindowMac::Hide() {
  590. // If a sheet is attached to the window when we call [window_ orderOut:nil],
  591. // the sheet won't be able to show again on the same window.
  592. // Ensure it's closed before calling [window_ orderOut:nil].
  593. SetEnabled(true);
  594. if (is_modal() && parent()) {
  595. [window_ orderOut:nil];
  596. [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_];
  597. return;
  598. }
  599. // Hide all children of the current window before hiding the window.
  600. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm
  601. // expects this when window visibility changes.
  602. if ([window_ childWindows]) {
  603. for (NSWindow* child in [window_ childWindows]) {
  604. [child orderOut:nil];
  605. }
  606. }
  607. // Deattach the window from the parent before.
  608. if (parent())
  609. InternalSetParentWindow(parent(), false);
  610. [window_ orderOut:nil];
  611. }
  612. bool NativeWindowMac::IsVisible() {
  613. bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible;
  614. // For a window to be visible, it must be visible to the user in the
  615. // foreground of the app, which means that it should not be minimized or
  616. // occluded
  617. return [window_ isVisible] && !occluded && !IsMinimized();
  618. }
  619. void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
  620. base::PostTask(
  621. FROM_HERE, {content::BrowserThread::UI},
  622. base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr()));
  623. }
  624. void NativeWindowMac::SetFullScreenTransitionState(
  625. FullScreenTransitionState state) {
  626. fullscreen_transition_state_ = state;
  627. }
  628. bool NativeWindowMac::IsEnabled() {
  629. return [window_ attachedSheet] == nil;
  630. }
  631. void NativeWindowMac::SetEnabled(bool enable) {
  632. if (!enable) {
  633. [window_ beginSheet:window_
  634. completionHandler:^(NSModalResponse returnCode) {
  635. NSLog(@"modal enabled");
  636. return;
  637. }];
  638. } else if ([window_ attachedSheet]) {
  639. [window_ endSheet:[window_ attachedSheet]];
  640. }
  641. }
  642. void NativeWindowMac::Maximize() {
  643. if (IsMaximized())
  644. return;
  645. // Take note of the current window size
  646. if (IsNormal())
  647. original_frame_ = [window_ frame];
  648. [window_ zoom:nil];
  649. }
  650. void NativeWindowMac::Unmaximize() {
  651. if (!IsMaximized())
  652. return;
  653. [window_ zoom:nil];
  654. }
  655. bool NativeWindowMac::IsMaximized() {
  656. if (([window_ styleMask] & NSWindowStyleMaskResizable) != 0) {
  657. return [window_ isZoomed];
  658. } else {
  659. NSRect rectScreen = [[NSScreen mainScreen] visibleFrame];
  660. NSRect rectWindow = [window_ frame];
  661. return (rectScreen.origin.x == rectWindow.origin.x &&
  662. rectScreen.origin.y == rectWindow.origin.y &&
  663. rectScreen.size.width == rectWindow.size.width &&
  664. rectScreen.size.height == rectWindow.size.height);
  665. }
  666. }
  667. void NativeWindowMac::Minimize() {
  668. if (IsMinimized())
  669. return;
  670. // Take note of the current window size
  671. if (IsNormal())
  672. original_frame_ = [window_ frame];
  673. [window_ miniaturize:nil];
  674. }
  675. void NativeWindowMac::Restore() {
  676. [window_ deminiaturize:nil];
  677. }
  678. bool NativeWindowMac::IsMinimized() {
  679. return [window_ isMiniaturized];
  680. }
  681. void NativeWindowMac::HandlePendingFullscreenTransitions() {
  682. if (pending_transitions_.empty())
  683. return;
  684. bool next_transition = pending_transitions_.front();
  685. pending_transitions_.pop();
  686. SetFullScreen(next_transition);
  687. }
  688. void NativeWindowMac::SetFullScreen(bool fullscreen) {
  689. // [NSWindow -toggleFullScreen] is an asynchronous operation, which means
  690. // that it's possible to call it while a fullscreen transition is currently
  691. // in process. This can create weird behavior (incl. phantom windows),
  692. // so we want to schedule a transition for when the current one has completed.
  693. if (fullscreen_transition_state() != FullScreenTransitionState::NONE) {
  694. if (!pending_transitions_.empty()) {
  695. bool last_pending = pending_transitions_.back();
  696. // Only push new transitions if they're different than the last transition
  697. // in the queue.
  698. if (last_pending != fullscreen)
  699. pending_transitions_.push(fullscreen);
  700. } else {
  701. pending_transitions_.push(fullscreen);
  702. }
  703. return;
  704. }
  705. if (fullscreen == IsFullscreen())
  706. return;
  707. // Take note of the current window size
  708. if (IsNormal())
  709. original_frame_ = [window_ frame];
  710. // This needs to be set here because it can be the case that
  711. // SetFullScreen is called by a user before windowWillEnterFullScreen
  712. // or windowWillExitFullScreen are invoked, and so a potential transition
  713. // could be dropped.
  714. fullscreen_transition_state_ = fullscreen
  715. ? FullScreenTransitionState::ENTERING
  716. : FullScreenTransitionState::EXITING;
  717. [window_ toggleFullScreenMode:nil];
  718. }
  719. bool NativeWindowMac::IsFullscreen() const {
  720. return [window_ styleMask] & NSWindowStyleMaskFullScreen;
  721. }
  722. void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) {
  723. // Do nothing if in fullscreen mode.
  724. if (IsFullscreen())
  725. return;
  726. // Check size constraints since setFrame does not check it.
  727. gfx::Size size = bounds.size();
  728. size.SetToMax(GetMinimumSize());
  729. gfx::Size max_size = GetMaximumSize();
  730. if (!max_size.IsEmpty())
  731. size.SetToMin(max_size);
  732. NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height());
  733. // Flip coordinates based on the primary screen.
  734. NSScreen* screen = [[NSScreen screens] firstObject];
  735. cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y();
  736. [window_ setFrame:cocoa_bounds display:YES animate:animate];
  737. }
  738. gfx::Rect NativeWindowMac::GetBounds() {
  739. NSRect frame = [window_ frame];
  740. gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
  741. NSScreen* screen = [[NSScreen screens] firstObject];
  742. bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
  743. return bounds;
  744. }
  745. bool NativeWindowMac::IsNormal() {
  746. return NativeWindow::IsNormal() && !IsSimpleFullScreen();
  747. }
  748. gfx::Rect NativeWindowMac::GetNormalBounds() {
  749. if (IsNormal()) {
  750. return GetBounds();
  751. }
  752. NSRect frame = original_frame_;
  753. gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
  754. NSScreen* screen = [[NSScreen screens] firstObject];
  755. bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
  756. return bounds;
  757. // Works on OS_WIN !
  758. // return widget()->GetRestoredBounds();
  759. }
  760. void NativeWindowMac::SetContentSizeConstraints(
  761. const extensions::SizeConstraints& size_constraints) {
  762. auto convertSize = [this](const gfx::Size& size) {
  763. // Our frameless window still has titlebar attached, so setting contentSize
  764. // will result in actual content size being larger.
  765. if (!has_frame()) {
  766. NSRect frame = NSMakeRect(0, 0, size.width(), size.height());
  767. NSRect content = [window_ originalContentRectForFrameRect:frame];
  768. return content.size;
  769. } else {
  770. return NSMakeSize(size.width(), size.height());
  771. }
  772. };
  773. NSView* content = [window_ contentView];
  774. if (size_constraints.HasMinimumSize()) {
  775. NSSize min_size = convertSize(size_constraints.GetMinimumSize());
  776. [window_ setContentMinSize:[content convertSize:min_size toView:nil]];
  777. }
  778. if (size_constraints.HasMaximumSize()) {
  779. NSSize max_size = convertSize(size_constraints.GetMaximumSize());
  780. [window_ setContentMaxSize:[content convertSize:max_size toView:nil]];
  781. }
  782. NativeWindow::SetContentSizeConstraints(size_constraints);
  783. }
  784. bool NativeWindowMac::MoveAbove(const std::string& sourceId) {
  785. const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId);
  786. if (id.type != content::DesktopMediaID::TYPE_WINDOW)
  787. return false;
  788. // Check if the window source is valid.
  789. const CGWindowID window_id = id.id;
  790. if (!webrtc::GetWindowOwnerPid(window_id))
  791. return false;
  792. [window_ orderWindow:NSWindowAbove relativeTo:id.id];
  793. return true;
  794. }
  795. void NativeWindowMac::MoveTop() {
  796. [window_ orderWindow:NSWindowAbove relativeTo:0];
  797. }
  798. void NativeWindowMac::SetResizable(bool resizable) {
  799. SetStyleMask(resizable, NSWindowStyleMaskResizable);
  800. }
  801. bool NativeWindowMac::IsResizable() {
  802. return [window_ styleMask] & NSWindowStyleMaskResizable;
  803. }
  804. void NativeWindowMac::SetAspectRatio(double aspect_ratio,
  805. const gfx::Size& extra_size) {
  806. NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
  807. // Reset the behaviour to default if aspect_ratio is set to 0 or less.
  808. if (aspect_ratio > 0.0)
  809. [window_ setContentAspectRatio:NSMakeSize(aspect_ratio, 1.0)];
  810. else
  811. [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)];
  812. }
  813. void NativeWindowMac::PreviewFile(const std::string& path,
  814. const std::string& display_name) {
  815. preview_item_.reset([[ElectronPreviewItem alloc]
  816. initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)]
  817. title:base::SysUTF8ToNSString(display_name)]);
  818. [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
  819. }
  820. void NativeWindowMac::CloseFilePreview() {
  821. if ([QLPreviewPanel sharedPreviewPanelExists]) {
  822. [[QLPreviewPanel sharedPreviewPanel] close];
  823. }
  824. }
  825. void NativeWindowMac::SetMovable(bool movable) {
  826. [window_ setMovable:movable];
  827. }
  828. bool NativeWindowMac::IsMovable() {
  829. return [window_ isMovable];
  830. }
  831. void NativeWindowMac::SetMinimizable(bool minimizable) {
  832. SetStyleMask(minimizable, NSMiniaturizableWindowMask);
  833. }
  834. bool NativeWindowMac::IsMinimizable() {
  835. return [window_ styleMask] & NSMiniaturizableWindowMask;
  836. }
  837. void NativeWindowMac::SetMaximizable(bool maximizable) {
  838. maximizable_ = maximizable;
  839. [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable];
  840. }
  841. bool NativeWindowMac::IsMaximizable() {
  842. return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled];
  843. }
  844. void NativeWindowMac::SetFullScreenable(bool fullscreenable) {
  845. SetCollectionBehavior(fullscreenable,
  846. NSWindowCollectionBehaviorFullScreenPrimary);
  847. // On EL Capitan this flag is required to hide fullscreen button.
  848. SetCollectionBehavior(!fullscreenable,
  849. NSWindowCollectionBehaviorFullScreenAuxiliary);
  850. }
  851. bool NativeWindowMac::IsFullScreenable() {
  852. NSUInteger collectionBehavior = [window_ collectionBehavior];
  853. return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary;
  854. }
  855. void NativeWindowMac::SetClosable(bool closable) {
  856. SetStyleMask(closable, NSWindowStyleMaskClosable);
  857. }
  858. bool NativeWindowMac::IsClosable() {
  859. return [window_ styleMask] & NSWindowStyleMaskClosable;
  860. }
  861. void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order,
  862. const std::string& level_name,
  863. int relative_level) {
  864. if (z_order == ui::ZOrderLevel::kNormal) {
  865. SetWindowLevel(NSNormalWindowLevel);
  866. return;
  867. }
  868. int level = NSNormalWindowLevel;
  869. if (level_name == "floating") {
  870. level = NSFloatingWindowLevel;
  871. } else if (level_name == "torn-off-menu") {
  872. level = NSTornOffMenuWindowLevel;
  873. } else if (level_name == "modal-panel") {
  874. level = NSModalPanelWindowLevel;
  875. } else if (level_name == "main-menu") {
  876. level = NSMainMenuWindowLevel;
  877. } else if (level_name == "status") {
  878. level = NSStatusWindowLevel;
  879. } else if (level_name == "pop-up-menu") {
  880. level = NSPopUpMenuWindowLevel;
  881. } else if (level_name == "screen-saver") {
  882. level = NSScreenSaverWindowLevel;
  883. } else if (level_name == "dock") {
  884. // Deprecated by macOS, but kept for backwards compatibility
  885. level = NSDockWindowLevel;
  886. }
  887. SetWindowLevel(level + relative_level);
  888. }
  889. std::string NativeWindowMac::GetAlwaysOnTopLevel() {
  890. std::string level_name = "normal";
  891. int level = [window_ level];
  892. if (level == NSFloatingWindowLevel) {
  893. level_name = "floating";
  894. } else if (level == NSTornOffMenuWindowLevel) {
  895. level_name = "torn-off-menu";
  896. } else if (level == NSModalPanelWindowLevel) {
  897. level_name = "modal-panel";
  898. } else if (level == NSMainMenuWindowLevel) {
  899. level_name = "main-menu";
  900. } else if (level == NSStatusWindowLevel) {
  901. level_name = "status";
  902. } else if (level == NSPopUpMenuWindowLevel) {
  903. level_name = "pop-up-menu";
  904. } else if (level == NSScreenSaverWindowLevel) {
  905. level_name = "screen-saver";
  906. } else if (level == NSDockWindowLevel) {
  907. level_name = "dock";
  908. }
  909. return level_name;
  910. }
  911. void NativeWindowMac::SetWindowLevel(int unbounded_level) {
  912. int level = std::min(
  913. std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)),
  914. CGWindowLevelForKey(kCGMaximumWindowLevelKey));
  915. ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel
  916. ? ui::ZOrderLevel::kNormal
  917. : ui::ZOrderLevel::kFloatingWindow;
  918. bool did_z_order_level_change = z_order_level != GetZOrderLevel();
  919. was_maximizable_ = IsMaximizable();
  920. // We need to explicitly keep the NativeWidget up to date, since it stores the
  921. // window level in a local variable, rather than reading it from the NSWindow.
  922. // Unfortunately, it results in a second setLevel call. It's not ideal, but we
  923. // don't expect this to cause any user-visible jank.
  924. widget()->SetZOrderLevel(z_order_level);
  925. [window_ setLevel:level];
  926. // Set level will make the zoom button revert to default, probably
  927. // a bug of Cocoa or macOS.
  928. SetMaximizable(was_maximizable_);
  929. // This must be notified at the very end or IsAlwaysOnTop
  930. // will not yet have been updated to reflect the new status
  931. if (did_z_order_level_change)
  932. NativeWindow::NotifyWindowAlwaysOnTopChanged();
  933. }
  934. ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() {
  935. return widget()->GetZOrderLevel();
  936. }
  937. void NativeWindowMac::Center() {
  938. [window_ center];
  939. }
  940. void NativeWindowMac::Invalidate() {
  941. [window_ flushWindow];
  942. [[window_ contentView] setNeedsDisplay:YES];
  943. }
  944. void NativeWindowMac::SetTitle(const std::string& title) {
  945. [window_ setTitle:base::SysUTF8ToNSString(title)];
  946. if (title_bar_style_ == TitleBarStyle::kHidden) {
  947. RedrawTrafficLights();
  948. }
  949. }
  950. std::string NativeWindowMac::GetTitle() {
  951. return base::SysNSStringToUTF8([window_ title]);
  952. }
  953. void NativeWindowMac::FlashFrame(bool flash) {
  954. if (flash) {
  955. attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest];
  956. } else {
  957. [NSApp cancelUserAttentionRequest:attention_request_id_];
  958. attention_request_id_ = 0;
  959. }
  960. }
  961. void NativeWindowMac::SetSkipTaskbar(bool skip) {}
  962. bool NativeWindowMac::IsExcludedFromShownWindowsMenu() {
  963. NSWindow* window = GetNativeWindow().GetNativeNSWindow();
  964. return [window isExcludedFromWindowsMenu];
  965. }
  966. void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) {
  967. NSWindow* window = GetNativeWindow().GetNativeNSWindow();
  968. [window setExcludedFromWindowsMenu:excluded];
  969. }
  970. void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display,
  971. uint32_t changed_metrics) {
  972. // We only want to force screen recalibration if we're in simpleFullscreen
  973. // mode.
  974. if (!is_simple_fullscreen_)
  975. return;
  976. base::PostTask(FROM_HERE, {content::BrowserThread::UI},
  977. base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr()));
  978. }
  979. void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) {
  980. NSWindow* window = GetNativeWindow().GetNativeNSWindow();
  981. if (simple_fullscreen && !is_simple_fullscreen_) {
  982. is_simple_fullscreen_ = true;
  983. // Take note of the current window size and level
  984. if (IsNormal()) {
  985. original_frame_ = [window_ frame];
  986. original_level_ = [window_ level];
  987. }
  988. simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions];
  989. simple_fullscreen_mask_ = [window styleMask];
  990. // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu
  991. // bar
  992. NSApplicationPresentationOptions options =
  993. NSApplicationPresentationAutoHideDock |
  994. NSApplicationPresentationAutoHideMenuBar;
  995. [NSApp setPresentationOptions:options];
  996. was_maximizable_ = IsMaximizable();
  997. was_movable_ = IsMovable();
  998. NSRect fullscreenFrame = [window.screen frame];
  999. // If our app has dock hidden, set the window level higher so another app's
  1000. // menu bar doesn't appear on top of our fullscreen app.
  1001. if ([[NSRunningApplication currentApplication] activationPolicy] !=
  1002. NSApplicationActivationPolicyRegular) {
  1003. window.level = NSPopUpMenuWindowLevel;
  1004. }
  1005. if (!fullscreen_window_title()) {
  1006. // Hide the titlebar
  1007. SetStyleMask(false, NSWindowStyleMaskTitled);
  1008. // Resize the window to accommodate the _entire_ screen size
  1009. fullscreenFrame.size.height -=
  1010. [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
  1011. } else if (!window_button_visibility_.has_value()) {
  1012. // Lets keep previous behaviour - hide window controls in titled
  1013. // fullscreen mode when not specified otherwise.
  1014. [[window standardWindowButton:NSWindowZoomButton] setHidden:YES];
  1015. [[window standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];
  1016. [[window standardWindowButton:NSWindowCloseButton] setHidden:YES];
  1017. }
  1018. [window setFrame:fullscreenFrame display:YES animate:YES];
  1019. // Fullscreen windows can't be resized, minimized, maximized, or moved
  1020. SetMinimizable(false);
  1021. SetResizable(false);
  1022. SetMaximizable(false);
  1023. SetMovable(false);
  1024. } else if (!simple_fullscreen && is_simple_fullscreen_) {
  1025. is_simple_fullscreen_ = false;
  1026. if (!fullscreen_window_title()) {
  1027. // Restore the titlebar
  1028. SetStyleMask(true, NSWindowStyleMaskTitled);
  1029. }
  1030. // Restore window controls visibility state
  1031. const bool window_button_hidden =
  1032. !window_button_visibility_.value_or(true) || !has_frame();
  1033. [[window standardWindowButton:NSWindowZoomButton]
  1034. setHidden:window_button_hidden];
  1035. [[window standardWindowButton:NSWindowMiniaturizeButton]
  1036. setHidden:window_button_hidden];
  1037. [[window standardWindowButton:NSWindowCloseButton]
  1038. setHidden:window_button_hidden];
  1039. [window setFrame:original_frame_ display:YES animate:YES];
  1040. window.level = original_level_;
  1041. [NSApp setPresentationOptions:simple_fullscreen_options_];
  1042. // Restore original style mask
  1043. ScopedDisableResize disable_resize;
  1044. [window_ setStyleMask:simple_fullscreen_mask_];
  1045. // Restore window manipulation abilities
  1046. SetMaximizable(was_maximizable_);
  1047. SetMovable(was_movable_);
  1048. }
  1049. }
  1050. bool NativeWindowMac::IsSimpleFullScreen() {
  1051. return is_simple_fullscreen_;
  1052. }
  1053. void NativeWindowMac::SetKiosk(bool kiosk) {
  1054. if (kiosk && !is_kiosk_) {
  1055. kiosk_options_ = [NSApp currentSystemPresentationOptions];
  1056. NSApplicationPresentationOptions options =
  1057. NSApplicationPresentationHideDock |
  1058. NSApplicationPresentationHideMenuBar |
  1059. NSApplicationPresentationDisableAppleMenu |
  1060. NSApplicationPresentationDisableProcessSwitching |
  1061. NSApplicationPresentationDisableForceQuit |
  1062. NSApplicationPresentationDisableSessionTermination |
  1063. NSApplicationPresentationDisableHideApplication;
  1064. [NSApp setPresentationOptions:options];
  1065. is_kiosk_ = true;
  1066. SetFullScreen(true);
  1067. } else if (!kiosk && is_kiosk_) {
  1068. [NSApp setPresentationOptions:kiosk_options_];
  1069. is_kiosk_ = false;
  1070. SetFullScreen(false);
  1071. }
  1072. }
  1073. bool NativeWindowMac::IsKiosk() {
  1074. return is_kiosk_;
  1075. }
  1076. void NativeWindowMac::SetBackgroundColor(SkColor color) {
  1077. base::ScopedCFTypeRef<CGColorRef> cgcolor(
  1078. skia::CGColorCreateFromSkColor(color));
  1079. [[[window_ contentView] layer] setBackgroundColor:cgcolor];
  1080. }
  1081. SkColor NativeWindowMac::GetBackgroundColor() {
  1082. CGColorRef color = [[[window_ contentView] layer] backgroundColor];
  1083. if (!color)
  1084. return SK_ColorTRANSPARENT;
  1085. return skia::CGColorRefToSkColor(color);
  1086. }
  1087. void NativeWindowMac::SetHasShadow(bool has_shadow) {
  1088. [window_ setHasShadow:has_shadow];
  1089. }
  1090. bool NativeWindowMac::HasShadow() {
  1091. return [window_ hasShadow];
  1092. }
  1093. void NativeWindowMac::SetOpacity(const double opacity) {
  1094. const double boundedOpacity = base::ClampToRange(opacity, 0.0, 1.0);
  1095. [window_ setAlphaValue:boundedOpacity];
  1096. }
  1097. double NativeWindowMac::GetOpacity() {
  1098. return [window_ alphaValue];
  1099. }
  1100. void NativeWindowMac::SetRepresentedFilename(const std::string& filename) {
  1101. [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)];
  1102. }
  1103. std::string NativeWindowMac::GetRepresentedFilename() {
  1104. return base::SysNSStringToUTF8([window_ representedFilename]);
  1105. }
  1106. void NativeWindowMac::SetDocumentEdited(bool edited) {
  1107. [window_ setDocumentEdited:edited];
  1108. }
  1109. bool NativeWindowMac::IsDocumentEdited() {
  1110. return [window_ isDocumentEdited];
  1111. }
  1112. void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) {
  1113. [window_ setIgnoresMouseEvents:ignore];
  1114. if (!ignore) {
  1115. SetForwardMouseMessages(NO);
  1116. } else {
  1117. SetForwardMouseMessages(forward);
  1118. }
  1119. }
  1120. void NativeWindowMac::SetContentProtection(bool enable) {
  1121. [window_
  1122. setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly];
  1123. }
  1124. void NativeWindowMac::SetFocusable(bool focusable) {
  1125. // No known way to unfocus the window if it had the focus. Here we do not
  1126. // want to call Focus(false) because it moves the window to the back, i.e.
  1127. // at the bottom in term of z-order.
  1128. [window_ setDisableKeyOrMainWindow:!focusable];
  1129. }
  1130. void NativeWindowMac::AddBrowserView(NativeBrowserView* view) {
  1131. [CATransaction begin];
  1132. [CATransaction setDisableActions:YES];
  1133. if (!view) {
  1134. [CATransaction commit];
  1135. return;
  1136. }
  1137. add_browser_view(view);
  1138. if (view->GetInspectableWebContentsView()) {
  1139. auto* native_view = view->GetInspectableWebContentsView()
  1140. ->GetNativeView()
  1141. .GetNativeNSView();
  1142. [[window_ contentView] addSubview:native_view
  1143. positioned:NSWindowAbove
  1144. relativeTo:nil];
  1145. native_view.hidden = NO;
  1146. }
  1147. [CATransaction commit];
  1148. }
  1149. void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) {
  1150. [CATransaction begin];
  1151. [CATransaction setDisableActions:YES];
  1152. if (!view) {
  1153. [CATransaction commit];
  1154. return;
  1155. }
  1156. if (view->GetInspectableWebContentsView())
  1157. [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView()
  1158. removeFromSuperview];
  1159. remove_browser_view(view);
  1160. [CATransaction commit];
  1161. }
  1162. void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) {
  1163. [CATransaction begin];
  1164. [CATransaction setDisableActions:YES];
  1165. if (!view) {
  1166. [CATransaction commit];
  1167. return;
  1168. }
  1169. remove_browser_view(view);
  1170. add_browser_view(view);
  1171. if (view->GetInspectableWebContentsView()) {
  1172. auto* native_view = view->GetInspectableWebContentsView()
  1173. ->GetNativeView()
  1174. .GetNativeNSView();
  1175. [[window_ contentView] addSubview:native_view
  1176. positioned:NSWindowAbove
  1177. relativeTo:nil];
  1178. native_view.hidden = NO;
  1179. }
  1180. [CATransaction commit];
  1181. }
  1182. void NativeWindowMac::SetParentWindow(NativeWindow* parent) {
  1183. InternalSetParentWindow(parent, IsVisible());
  1184. }
  1185. gfx::NativeView NativeWindowMac::GetNativeView() const {
  1186. return [window_ contentView];
  1187. }
  1188. gfx::NativeWindow NativeWindowMac::GetNativeWindow() const {
  1189. return window_;
  1190. }
  1191. gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const {
  1192. return [window_ windowNumber];
  1193. }
  1194. content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const {
  1195. return content::DesktopMediaID(content::DesktopMediaID::TYPE_WINDOW,
  1196. GetAcceleratedWidget());
  1197. }
  1198. NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const {
  1199. return [window_ contentView];
  1200. }
  1201. void NativeWindowMac::SetProgressBar(double progress,
  1202. const NativeWindow::ProgressState state) {
  1203. NSDockTile* dock_tile = [NSApp dockTile];
  1204. // Sometimes macOS would install a default contentView for dock, we must
  1205. // verify whether NSProgressIndicator has been installed.
  1206. bool first_time = !dock_tile.contentView ||
  1207. [[dock_tile.contentView subviews] count] == 0 ||
  1208. ![[[dock_tile.contentView subviews] lastObject]
  1209. isKindOfClass:[NSProgressIndicator class]];
  1210. // For the first time API invoked, we need to create a ContentView in
  1211. // DockTile.
  1212. if (first_time) {
  1213. NSImageView* image_view = [[[NSImageView alloc] init] autorelease];
  1214. [image_view setImage:[NSApp applicationIconImage]];
  1215. [dock_tile setContentView:image_view];
  1216. NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0);
  1217. NSProgressIndicator* progress_indicator =
  1218. [[[ElectronProgressBar alloc] initWithFrame:frame] autorelease];
  1219. [progress_indicator setStyle:NSProgressIndicatorBarStyle];
  1220. [progress_indicator setIndeterminate:NO];
  1221. [progress_indicator setBezeled:YES];
  1222. [progress_indicator setMinValue:0];
  1223. [progress_indicator setMaxValue:1];
  1224. [progress_indicator setHidden:NO];
  1225. [dock_tile.contentView addSubview:progress_indicator];
  1226. }
  1227. NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>(
  1228. [[[dock_tile contentView] subviews] lastObject]);
  1229. if (progress < 0) {
  1230. [progress_indicator setHidden:YES];
  1231. } else if (progress > 1) {
  1232. [progress_indicator setHidden:NO];
  1233. [progress_indicator setIndeterminate:YES];
  1234. [progress_indicator setDoubleValue:1];
  1235. } else {
  1236. [progress_indicator setHidden:NO];
  1237. [progress_indicator setDoubleValue:progress];
  1238. }
  1239. [dock_tile display];
  1240. }
  1241. void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay,
  1242. const std::string& description) {}
  1243. void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible,
  1244. bool visibleOnFullScreen) {
  1245. // In order for NSWindows to be visible on fullscreen we need to functionally
  1246. // mimic app.dock.hide() since Apple changed the underlying functionality of
  1247. // NSWindows starting with 10.14 to disallow NSWindows from floating on top of
  1248. // fullscreen apps.
  1249. ProcessSerialNumber psn = {0, kCurrentProcess};
  1250. if (visibleOnFullScreen) {
  1251. [window_ setCanHide:NO];
  1252. TransformProcessType(&psn, kProcessTransformToUIElementApplication);
  1253. } else {
  1254. [window_ setCanHide:YES];
  1255. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  1256. }
  1257. SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces);
  1258. SetCollectionBehavior(visibleOnFullScreen,
  1259. NSWindowCollectionBehaviorFullScreenAuxiliary);
  1260. }
  1261. bool NativeWindowMac::IsVisibleOnAllWorkspaces() {
  1262. NSUInteger collectionBehavior = [window_ collectionBehavior];
  1263. return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces;
  1264. }
  1265. void NativeWindowMac::SetAutoHideCursor(bool auto_hide) {
  1266. [window_ setDisableAutoHideCursor:!auto_hide];
  1267. }
  1268. void NativeWindowMac::SelectPreviousTab() {
  1269. if (@available(macOS 10.12, *)) {
  1270. [window_ selectPreviousTab:nil];
  1271. }
  1272. }
  1273. void NativeWindowMac::SelectNextTab() {
  1274. if (@available(macOS 10.12, *)) {
  1275. [window_ selectNextTab:nil];
  1276. }
  1277. }
  1278. void NativeWindowMac::MergeAllWindows() {
  1279. if (@available(macOS 10.12, *)) {
  1280. [window_ mergeAllWindows:nil];
  1281. }
  1282. }
  1283. void NativeWindowMac::MoveTabToNewWindow() {
  1284. if (@available(macOS 10.12, *)) {
  1285. [window_ moveTabToNewWindow:nil];
  1286. }
  1287. }
  1288. void NativeWindowMac::ToggleTabBar() {
  1289. if (@available(macOS 10.12, *)) {
  1290. [window_ toggleTabBar:nil];
  1291. }
  1292. }
  1293. bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) {
  1294. if (window_ == window->GetNativeWindow().GetNativeNSWindow()) {
  1295. return false;
  1296. } else {
  1297. if (@available(macOS 10.12, *))
  1298. [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow()
  1299. ordered:NSWindowAbove];
  1300. }
  1301. return true;
  1302. }
  1303. bool NativeWindowMac::SetWindowButtonVisibility(bool visible) {
  1304. if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) {
  1305. return false;
  1306. }
  1307. window_button_visibility_ = visible;
  1308. [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible];
  1309. [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible];
  1310. [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible];
  1311. return true;
  1312. }
  1313. void NativeWindowMac::SetVibrancy(const std::string& type) {
  1314. NSView* vibrant_view = [window_ vibrantView];
  1315. if (type.empty()) {
  1316. if (background_color_before_vibrancy_) {
  1317. [window_ setBackgroundColor:background_color_before_vibrancy_];
  1318. [window_ setTitlebarAppearsTransparent:transparency_before_vibrancy_];
  1319. }
  1320. if (vibrant_view == nil)
  1321. return;
  1322. [vibrant_view removeFromSuperview];
  1323. [window_ setVibrantView:nil];
  1324. return;
  1325. }
  1326. background_color_before_vibrancy_.reset([[window_ backgroundColor] retain]);
  1327. transparency_before_vibrancy_ = [window_ titlebarAppearsTransparent];
  1328. if (title_bar_style_ != TitleBarStyle::kNormal) {
  1329. [window_ setTitlebarAppearsTransparent:YES];
  1330. [window_ setBackgroundColor:[NSColor clearColor]];
  1331. }
  1332. NSVisualEffectView* effect_view = (NSVisualEffectView*)vibrant_view;
  1333. if (effect_view == nil) {
  1334. effect_view = [[[NSVisualEffectView alloc]
  1335. initWithFrame:[[window_ contentView] bounds]] autorelease];
  1336. [window_ setVibrantView:(NSView*)effect_view];
  1337. [effect_view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
  1338. [effect_view setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
  1339. if (visual_effect_state_ == VisualEffectState::kActive) {
  1340. [effect_view setState:NSVisualEffectStateActive];
  1341. } else if (visual_effect_state_ == VisualEffectState::kInactive) {
  1342. [effect_view setState:NSVisualEffectStateInactive];
  1343. } else {
  1344. [effect_view setState:NSVisualEffectStateFollowsWindowActiveState];
  1345. }
  1346. // Make frameless Vibrant windows have rounded corners.
  1347. if (!has_frame() && !is_modal()) {
  1348. CGFloat radius;
  1349. if (@available(macOS 11.0, *)) {
  1350. radius = 9.0f;
  1351. } else {
  1352. radius = 5.0f; // smaller corner radius on older versions
  1353. }
  1354. CGFloat dimension = 2 * radius + 1;
  1355. NSSize size = NSMakeSize(dimension, dimension);
  1356. NSImage* maskImage = [NSImage imageWithSize:size
  1357. flipped:NO
  1358. drawingHandler:^BOOL(NSRect rect) {
  1359. NSBezierPath* bezierPath = [NSBezierPath
  1360. bezierPathWithRoundedRect:rect
  1361. xRadius:radius
  1362. yRadius:radius];
  1363. [[NSColor blackColor] set];
  1364. [bezierPath fill];
  1365. return YES;
  1366. }];
  1367. [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)];
  1368. [maskImage setResizingMode:NSImageResizingModeStretch];
  1369. [effect_view setMaskImage:maskImage];
  1370. [window_ setCornerMask:maskImage];
  1371. }
  1372. [[window_ contentView] addSubview:effect_view
  1373. positioned:NSWindowBelow
  1374. relativeTo:nil];
  1375. }
  1376. std::string dep_warn = " has been deprecated and removed as of macOS 10.15.";
  1377. node::Environment* env =
  1378. node::Environment::GetCurrent(v8::Isolate::GetCurrent());
  1379. NSVisualEffectMaterial vibrancyType;
  1380. if (type == "appearance-based") {
  1381. EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn,
  1382. "electron");
  1383. vibrancyType = NSVisualEffectMaterialAppearanceBased;
  1384. } else if (type == "light") {
  1385. EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron");
  1386. vibrancyType = NSVisualEffectMaterialLight;
  1387. } else if (type == "dark") {
  1388. EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron");
  1389. vibrancyType = NSVisualEffectMaterialDark;
  1390. } else if (type == "titlebar") {
  1391. vibrancyType = NSVisualEffectMaterialTitlebar;
  1392. }
  1393. if (@available(macOS 10.11, *)) {
  1394. if (type == "selection") {
  1395. vibrancyType = NSVisualEffectMaterialSelection;
  1396. } else if (type == "menu") {
  1397. vibrancyType = NSVisualEffectMaterialMenu;
  1398. } else if (type == "popover") {
  1399. vibrancyType = NSVisualEffectMaterialPopover;
  1400. } else if (type == "sidebar") {
  1401. vibrancyType = NSVisualEffectMaterialSidebar;
  1402. } else if (type == "medium-light") {
  1403. EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn,
  1404. "electron");
  1405. vibrancyType = NSVisualEffectMaterialMediumLight;
  1406. } else if (type == "ultra-dark") {
  1407. EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn,
  1408. "electron");
  1409. vibrancyType = NSVisualEffectMaterialUltraDark;
  1410. }
  1411. }
  1412. if (@available(macOS 10.14, *)) {
  1413. if (type == "header") {
  1414. vibrancyType = NSVisualEffectMaterialHeaderView;
  1415. } else if (type == "sheet") {
  1416. vibrancyType = NSVisualEffectMaterialSheet;
  1417. } else if (type == "window") {
  1418. vibrancyType = NSVisualEffectMaterialWindowBackground;
  1419. } else if (type == "hud") {
  1420. vibrancyType = NSVisualEffectMaterialHUDWindow;
  1421. } else if (type == "fullscreen-ui") {
  1422. vibrancyType = NSVisualEffectMaterialFullScreenUI;
  1423. } else if (type == "tooltip") {
  1424. vibrancyType = NSVisualEffectMaterialToolTip;
  1425. } else if (type == "content") {
  1426. vibrancyType = NSVisualEffectMaterialContentBackground;
  1427. } else if (type == "under-window") {
  1428. vibrancyType = NSVisualEffectMaterialUnderWindowBackground;
  1429. } else if (type == "under-page") {
  1430. vibrancyType = NSVisualEffectMaterialUnderPageBackground;
  1431. }
  1432. }
  1433. if (vibrancyType)
  1434. [effect_view setMaterial:vibrancyType];
  1435. }
  1436. void NativeWindowMac::SetTrafficLightPosition(const gfx::Point& position) {
  1437. traffic_light_position_ = position;
  1438. RedrawTrafficLights();
  1439. }
  1440. gfx::Point NativeWindowMac::GetTrafficLightPosition() const {
  1441. return traffic_light_position_;
  1442. }
  1443. // In simpleFullScreen mode, update the frame for new bounds.
  1444. void NativeWindowMac::UpdateFrame() {
  1445. NSWindow* window = GetNativeWindow().GetNativeNSWindow();
  1446. NSRect fullscreenFrame = [window.screen frame];
  1447. [window setFrame:fullscreenFrame display:YES animate:YES];
  1448. }
  1449. void NativeWindowMac::SetTouchBar(
  1450. std::vector<gin_helper::PersistentDictionary> items) {
  1451. if (@available(macOS 10.12.2, *)) {
  1452. touch_bar_.reset([[ElectronTouchBar alloc]
  1453. initWithDelegate:window_delegate_.get()
  1454. window:this
  1455. settings:std::move(items)]);
  1456. [window_ setTouchBar:nil];
  1457. }
  1458. }
  1459. void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) {
  1460. if (@available(macOS 10.12.2, *)) {
  1461. if (touch_bar_ && [window_ touchBar])
  1462. [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id];
  1463. }
  1464. }
  1465. void NativeWindowMac::SetEscapeTouchBarItem(
  1466. gin_helper::PersistentDictionary item) {
  1467. if (@available(macOS 10.12.2, *)) {
  1468. if (touch_bar_ && [window_ touchBar])
  1469. [touch_bar_ setEscapeTouchBarItem:std::move(item)
  1470. forTouchBar:[window_ touchBar]];
  1471. }
  1472. }
  1473. gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds(
  1474. const gfx::Rect& bounds) const {
  1475. if (has_frame()) {
  1476. gfx::Rect window_bounds(
  1477. [window_ frameRectForContentRect:bounds.ToCGRect()]);
  1478. int frame_height = window_bounds.height() - bounds.height();
  1479. window_bounds.set_y(window_bounds.y() - frame_height);
  1480. return window_bounds;
  1481. } else {
  1482. return bounds;
  1483. }
  1484. }
  1485. gfx::Rect NativeWindowMac::WindowBoundsToContentBounds(
  1486. const gfx::Rect& bounds) const {
  1487. if (has_frame()) {
  1488. gfx::Rect content_bounds(
  1489. [window_ contentRectForFrameRect:bounds.ToCGRect()]);
  1490. int frame_height = bounds.height() - content_bounds.height();
  1491. content_bounds.set_y(content_bounds.y() + frame_height);
  1492. return content_bounds;
  1493. } else {
  1494. return bounds;
  1495. }
  1496. }
  1497. void NativeWindowMac::SetActive(bool is_key) {
  1498. is_active_ = is_key;
  1499. }
  1500. bool NativeWindowMac::IsActive() const {
  1501. return is_active_;
  1502. }
  1503. bool NativeWindowMac::CanResize() const {
  1504. return resizable_;
  1505. }
  1506. views::View* NativeWindowMac::GetContentsView() {
  1507. return root_view_.get();
  1508. }
  1509. void NativeWindowMac::AddContentViewLayers(bool minimizable, bool closable) {
  1510. // Make sure the bottom corner is rounded for non-modal windows:
  1511. // http://crbug.com/396264.
  1512. if (!is_modal()) {
  1513. // For normal window, we need to explicitly set layer for contentView to
  1514. // make setBackgroundColor work correctly.
  1515. // There is no need to do so for frameless window, and doing so would make
  1516. // titleBarStyle stop working.
  1517. if (has_frame()) {
  1518. base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]);
  1519. [background_layer
  1520. setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable];
  1521. [[window_ contentView] setLayer:background_layer];
  1522. }
  1523. [[window_ contentView] setWantsLayer:YES];
  1524. }
  1525. if (!has_frame()) {
  1526. // In OSX 10.10, adding subviews to the root view for the NSView hierarchy
  1527. // produces warnings. To eliminate the warnings, we resize the contentView
  1528. // to fill the window, and add subviews to that.
  1529. // http://crbug.com/380412
  1530. if (!original_set_frame_size) {
  1531. Class cl = [[window_ contentView] class];
  1532. original_set_frame_size = class_replaceMethod(
  1533. cl, @selector(setFrameSize:), (IMP)SetFrameSize, "v@:{_NSSize=ff}");
  1534. original_view_did_move_to_superview =
  1535. class_replaceMethod(cl, @selector(viewDidMoveToSuperview),
  1536. (IMP)ViewDidMoveToSuperview, "v@:");
  1537. [[window_ contentView] viewDidMoveToWindow];
  1538. }
  1539. // The fullscreen button should always be hidden for frameless window.
  1540. [[window_ standardWindowButton:NSWindowFullScreenButton] setHidden:YES];
  1541. // Create a custom window buttons view for kCustomButtonsOnHover.
  1542. if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) {
  1543. buttons_view_.reset(
  1544. [[CustomWindowButtonView alloc] initWithFrame:NSZeroRect]);
  1545. if (!minimizable)
  1546. [[buttons_view_ viewWithTag:2] removeFromSuperview];
  1547. if (!closable)
  1548. [[buttons_view_ viewWithTag:1] removeFromSuperview];
  1549. [[window_ contentView] addSubview:buttons_view_];
  1550. }
  1551. // Hide the window buttons except for kHidden and kHiddenInset.
  1552. if (title_bar_style_ == TitleBarStyle::kNormal ||
  1553. title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) {
  1554. [[window_ standardWindowButton:NSWindowZoomButton] setHidden:YES];
  1555. [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];
  1556. [[window_ standardWindowButton:NSWindowCloseButton] setHidden:YES];
  1557. // Some third-party macOS utilities check the zoom button's enabled state
  1558. // to determine whether to show custom UI on hover, so we disable it here
  1559. // to prevent them from doing so in a frameless app window.
  1560. SetMaximizable(false);
  1561. }
  1562. }
  1563. }
  1564. void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent,
  1565. bool attach) {
  1566. if (is_modal())
  1567. return;
  1568. NativeWindow::SetParentWindow(parent);
  1569. // Do not remove/add if we are already properly attached.
  1570. if (attach && parent &&
  1571. [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow())
  1572. return;
  1573. // Remove current parent window.
  1574. if ([window_ parentWindow])
  1575. [[window_ parentWindow] removeChildWindow:window_];
  1576. // Set new parent window.
  1577. // Note that this method will force the window to become visible.
  1578. if (parent && attach) {
  1579. // Attaching a window as a child window resets its window level, so
  1580. // save and restore it afterwards.
  1581. NSInteger level = window_.level;
  1582. [parent->GetNativeWindow().GetNativeNSWindow()
  1583. addChildWindow:window_
  1584. ordered:NSWindowAbove];
  1585. [window_ setLevel:level];
  1586. }
  1587. }
  1588. void NativeWindowMac::SetForwardMouseMessages(bool forward) {
  1589. [window_ setAcceptsMouseMovedEvents:forward];
  1590. }
  1591. void NativeWindowMac::OverrideNSWindowContentView() {
  1592. // When using `views::Widget` to hold WebContents, Chromium would use
  1593. // `BridgedContentView` as content view, which does not support draggable
  1594. // regions. In order to make draggable regions work, we have to replace the
  1595. // content view with a simple NSView.
  1596. if (has_frame()) {
  1597. container_view_.reset(
  1598. [[ElectronAdaptedContentView alloc] initWithShell:this]);
  1599. } else {
  1600. container_view_.reset([[FullSizeContentView alloc] init]);
  1601. [container_view_ setFrame:[[[window_ contentView] superview] bounds]];
  1602. }
  1603. [container_view_
  1604. setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
  1605. [window_ setContentView:container_view_];
  1606. AddContentViewLayers(IsMinimizable(), IsClosable());
  1607. }
  1608. void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) {
  1609. // Changing the styleMask of a frameless windows causes it to change size so
  1610. // we explicitly disable resizing while setting it.
  1611. ScopedDisableResize disable_resize;
  1612. bool was_maximizable = IsMaximizable();
  1613. if (on)
  1614. [window_ setStyleMask:[window_ styleMask] | flag];
  1615. else
  1616. [window_ setStyleMask:[window_ styleMask] & (~flag)];
  1617. // Change style mask will make the zoom button revert to default, probably
  1618. // a bug of Cocoa or macOS.
  1619. SetMaximizable(was_maximizable);
  1620. }
  1621. void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) {
  1622. bool was_maximizable = IsMaximizable();
  1623. if (on)
  1624. [window_ setCollectionBehavior:[window_ collectionBehavior] | flag];
  1625. else
  1626. [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)];
  1627. // Change collectionBehavior will make the zoom button revert to default,
  1628. // probably a bug of Cocoa or macOS.
  1629. SetMaximizable(was_maximizable);
  1630. }
  1631. // static
  1632. NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options,
  1633. NativeWindow* parent) {
  1634. return new NativeWindowMac(options, parent);
  1635. }
  1636. } // namespace electron