native_window_mac.mm 63 KB

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