native_window_mac.mm 64 KB

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