native_window_mac.mm 61 KB

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