tray_icon_cocoa.mm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. // Copyright (c) 2014 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 "atom/browser/ui/tray_icon_cocoa.h"
  5. #include "atom/browser/mac/atom_application.h"
  6. #include "atom/browser/ui/cocoa/NSString+ANSI.h"
  7. #include "atom/browser/ui/cocoa/atom_menu_controller.h"
  8. #include "base/mac/sdk_forward_declarations.h"
  9. #include "base/message_loop/message_loop.h"
  10. #include "base/strings/sys_string_conversions.h"
  11. #include "base/task/post_task.h"
  12. #include "content/public/browser/browser_task_traits.h"
  13. #include "content/public/browser/browser_thread.h"
  14. #include "ui/display/screen.h"
  15. #include "ui/events/cocoa/cocoa_event_utils.h"
  16. #include "ui/gfx/image/image.h"
  17. #include "ui/gfx/mac/coordinate_conversion.h"
  18. #include "ui/native_theme/native_theme.h"
  19. namespace {
  20. // By default, macOS sets 4px to tray image as left and right padding margin.
  21. const CGFloat kHorizontalMargin = 4;
  22. // macOS tends to make the title 2px lower.
  23. const CGFloat kVerticalTitleMargin = 2;
  24. } // namespace
  25. @interface StatusItemView : NSView {
  26. atom::TrayIconCocoa* trayIcon_; // weak
  27. AtomMenuController* menuController_; // weak
  28. atom::TrayIcon::HighlightMode highlight_mode_;
  29. BOOL ignoreDoubleClickEvents_;
  30. BOOL forceHighlight_;
  31. BOOL inMouseEventSequence_;
  32. BOOL ANSI_;
  33. base::scoped_nsobject<NSImage> image_;
  34. base::scoped_nsobject<NSImage> alternateImage_;
  35. base::scoped_nsobject<NSString> title_;
  36. base::scoped_nsobject<NSMutableAttributedString> attributedTitle_;
  37. base::scoped_nsobject<NSStatusItem> statusItem_;
  38. base::scoped_nsobject<NSTrackingArea> trackingArea_;
  39. }
  40. @end // @interface StatusItemView
  41. @implementation StatusItemView
  42. - (void)dealloc {
  43. trayIcon_ = nil;
  44. menuController_ = nil;
  45. [super dealloc];
  46. }
  47. - (id)initWithIcon:(atom::TrayIconCocoa*)icon {
  48. trayIcon_ = icon;
  49. menuController_ = nil;
  50. highlight_mode_ = atom::TrayIcon::HighlightMode::SELECTION;
  51. ignoreDoubleClickEvents_ = NO;
  52. forceHighlight_ = NO;
  53. inMouseEventSequence_ = NO;
  54. if ((self = [super initWithFrame:CGRectZero])) {
  55. [self registerForDraggedTypes:@[
  56. NSFilenamesPboardType,
  57. NSStringPboardType,
  58. ]];
  59. // Create the status item.
  60. NSStatusItem* item = [[NSStatusBar systemStatusBar]
  61. statusItemWithLength:NSVariableStatusItemLength];
  62. statusItem_.reset([item retain]);
  63. [statusItem_ setView:self];
  64. // Finalize setup by sizing our views
  65. [self updateDimensions];
  66. // Add NSTrackingArea for listening to mouseEnter, mouseExit, and mouseMove
  67. // events
  68. trackingArea_.reset([[NSTrackingArea alloc]
  69. initWithRect:[self bounds]
  70. options:NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved |
  71. NSTrackingActiveAlways
  72. owner:self
  73. userInfo:nil]);
  74. [self addTrackingArea:trackingArea_];
  75. }
  76. return self;
  77. }
  78. - (void)updateDimensions {
  79. NSStatusBar* bar = [NSStatusBar systemStatusBar];
  80. [self setFrame:NSMakeRect(0, 0, [self fullWidth], [bar thickness])];
  81. [self setNeedsDisplay:YES];
  82. }
  83. - (void)removeItem {
  84. // Turn off tracking events to prevent crash
  85. if (trackingArea_) {
  86. [self removeTrackingArea:trackingArea_];
  87. trackingArea_.reset();
  88. }
  89. [[NSStatusBar systemStatusBar] removeStatusItem:statusItem_];
  90. [statusItem_ setView:nil];
  91. statusItem_.reset();
  92. }
  93. - (void)drawRect:(NSRect)dirtyRect {
  94. // Draw the tray icon and title that align with NSStatusItem, layout:
  95. // ----------------
  96. // | icon | title |
  97. /// ----------------
  98. CGFloat thickness = [[statusItem_ statusBar] thickness];
  99. // Draw the system bar background.
  100. [statusItem_ drawStatusBarBackgroundInRect:self.bounds
  101. withHighlight:[self shouldHighlight]];
  102. // Determine which image to use.
  103. NSImage* image = image_.get();
  104. if (inMouseEventSequence_ && alternateImage_) {
  105. image = alternateImage_.get();
  106. }
  107. // Apply the higlight color if the image is a template image. When this moves
  108. // to using the new [NSStatusItem button] API, this should work automagically.
  109. if ([image isTemplate] == YES) {
  110. NSImage* imageWithColor = [[image copy] autorelease];
  111. [imageWithColor lockFocus];
  112. [[self colorWithHighlight:[self isHighlighted]] set];
  113. CGRect imageBounds = CGRectMake(0, 0, image.size.width, image.size.height);
  114. NSRectFillUsingOperation(imageBounds, NSCompositeSourceAtop);
  115. [imageWithColor unlockFocus];
  116. image = imageWithColor;
  117. }
  118. // Draw the image
  119. [image
  120. drawInRect:CGRectMake(roundf(([self iconWidth] - image.size.width) / 2),
  121. roundf((thickness - image.size.height) / 2),
  122. image.size.width, image.size.height)];
  123. if (title_) {
  124. // Draw title.
  125. NSRect titleDrawRect = NSMakeRect([self iconWidth], -kVerticalTitleMargin,
  126. [self titleWidth], thickness);
  127. [attributedTitle_ drawInRect:titleDrawRect];
  128. }
  129. }
  130. - (BOOL)isDarkMode {
  131. if (@available(macOS 10.15, *)) {
  132. return ui::NativeTheme::GetInstanceForNativeUi()->SystemDarkModeEnabled();
  133. }
  134. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  135. NSString* mode = [defaults stringForKey:@"AppleInterfaceStyle"];
  136. return mode && [mode isEqualToString:@"Dark"];
  137. }
  138. - (BOOL)isHighlighted {
  139. BOOL highlight = [self shouldHighlight];
  140. return highlight | [self isDarkMode];
  141. }
  142. // The width of the full status item.
  143. - (CGFloat)fullWidth {
  144. if (title_)
  145. return [self iconWidth] + [self titleWidth] + kHorizontalMargin;
  146. else
  147. return [self iconWidth];
  148. }
  149. // The width of the icon.
  150. - (CGFloat)iconWidth {
  151. if (!image_ && title_)
  152. return kHorizontalMargin;
  153. CGFloat thickness = [[NSStatusBar systemStatusBar] thickness];
  154. CGFloat imageHeight = [image_ size].height;
  155. CGFloat imageWidth = [image_ size].width;
  156. CGFloat iconWidth = imageWidth;
  157. if (imageWidth < thickness) {
  158. // Image's width must be larger than menu bar's height.
  159. iconWidth = thickness;
  160. } else {
  161. CGFloat verticalMargin = thickness - imageHeight;
  162. // Image must have same horizontal vertical margin.
  163. if (verticalMargin > 0 && imageWidth != imageHeight)
  164. iconWidth = imageWidth + verticalMargin;
  165. CGFloat horizontalMargin = thickness - imageWidth;
  166. // Image must have at least kHorizontalMargin horizontal margin on each
  167. // side.
  168. if (horizontalMargin < 2 * kHorizontalMargin)
  169. iconWidth = imageWidth + 2 * kHorizontalMargin;
  170. }
  171. return iconWidth;
  172. }
  173. // The width of the title.
  174. - (CGFloat)titleWidth {
  175. if (!title_)
  176. return 0;
  177. return [attributedTitle_ size].width;
  178. }
  179. - (NSColor*)colorWithHighlight:(BOOL)highlight {
  180. return highlight ? [NSColor whiteColor]
  181. : [NSColor colorWithRed:0.265625
  182. green:0.25390625
  183. blue:0.234375
  184. alpha:1.0];
  185. }
  186. - (void)setImage:(NSImage*)image {
  187. image_.reset([image copy]);
  188. [self updateDimensions];
  189. }
  190. - (void)setAlternateImage:(NSImage*)image {
  191. alternateImage_.reset([image copy]);
  192. }
  193. - (void)setHighlight:(atom::TrayIcon::HighlightMode)mode {
  194. highlight_mode_ = mode;
  195. [self setNeedsDisplay:YES];
  196. }
  197. - (void)setIgnoreDoubleClickEvents:(BOOL)ignore {
  198. ignoreDoubleClickEvents_ = ignore;
  199. }
  200. - (BOOL)getIgnoreDoubleClickEvents {
  201. return ignoreDoubleClickEvents_;
  202. }
  203. - (void)setTitle:(NSString*)title {
  204. if (title.length > 0) {
  205. title_.reset([title copy]);
  206. ANSI_ = [title containsANSICodes];
  207. } else {
  208. title_.reset();
  209. ANSI_ = NO;
  210. }
  211. [self updateAttributedTitle];
  212. [self updateDimensions];
  213. }
  214. - (void)updateAttributedTitle {
  215. NSDictionary* attributes =
  216. @{NSFontAttributeName : [NSFont menuBarFontOfSize:0]};
  217. if (ANSI_) {
  218. NSCharacterSet* whites = [NSCharacterSet whitespaceCharacterSet];
  219. NSString* title = [title_ stringByTrimmingCharactersInSet:whites];
  220. attributedTitle_.reset([title attributedStringParsingANSICodes]);
  221. [attributedTitle_ addAttributes:attributes
  222. range:NSMakeRange(0, [attributedTitle_ length])];
  223. return;
  224. }
  225. // check title_ being nil
  226. NSString* title = @"";
  227. if (title_)
  228. title = title_;
  229. attributedTitle_.reset([[NSMutableAttributedString alloc]
  230. initWithString:title
  231. attributes:attributes]);
  232. // NSFontAttributeName:[NSFont menuBarFontOfSize:0],
  233. // NSForegroundColorAttributeName:[self colorWithHighlight: highlight]
  234. [attributedTitle_ addAttributes:attributes
  235. range:NSMakeRange(0, [attributedTitle_ length])];
  236. [attributedTitle_ addAttribute:NSForegroundColorAttributeName
  237. value:[self colorWithHighlight:[self isHighlighted]]
  238. range:NSMakeRange(0, [attributedTitle_ length])];
  239. }
  240. - (void)setMenuController:(AtomMenuController*)menu {
  241. menuController_ = menu;
  242. }
  243. - (void)mouseDown:(NSEvent*)event {
  244. inMouseEventSequence_ = YES;
  245. [self setNeedsDisplay:YES];
  246. }
  247. - (void)mouseUp:(NSEvent*)event {
  248. if (!inMouseEventSequence_) {
  249. // If the menu is showing, when user clicked the tray icon, the `mouseDown`
  250. // event will be dissmissed, we need to close the menu at this time.
  251. [self setNeedsDisplay:YES];
  252. return;
  253. }
  254. inMouseEventSequence_ = NO;
  255. // Show menu when there is a context menu.
  256. // NB(hokein): Make tray's behavior more like official one's.
  257. // When the tray icon gets clicked quickly multiple times, the
  258. // event.clickCount doesn't always return 1. Instead, it returns a value that
  259. // counts the clicked times.
  260. // So we don't check the clickCount here, just pop up the menu for each click
  261. // event.
  262. if (menuController_)
  263. [statusItem_ popUpStatusItemMenu:[menuController_ menu]];
  264. // Don't emit click events when menu is showing.
  265. if (menuController_)
  266. return;
  267. // If we are ignoring double click events, we should ignore the `clickCount`
  268. // value and immediately emit a click event.
  269. BOOL shouldBeHandledAsASingleClick =
  270. (event.clickCount == 1) || ignoreDoubleClickEvents_;
  271. if (shouldBeHandledAsASingleClick)
  272. trayIcon_->NotifyClicked(
  273. gfx::ScreenRectFromNSRect(event.window.frame),
  274. gfx::ScreenPointFromNSPoint([event locationInWindow]),
  275. ui::EventFlagsFromModifiers([event modifierFlags]));
  276. // Double click event.
  277. BOOL shouldBeHandledAsADoubleClick =
  278. (event.clickCount == 2) && !ignoreDoubleClickEvents_;
  279. if (shouldBeHandledAsADoubleClick)
  280. trayIcon_->NotifyDoubleClicked(
  281. gfx::ScreenRectFromNSRect(event.window.frame),
  282. ui::EventFlagsFromModifiers([event modifierFlags]));
  283. [self setNeedsDisplay:YES];
  284. }
  285. - (void)popUpContextMenu:(atom::AtomMenuModel*)menu_model {
  286. // Make sure events can be pumped while the menu is up.
  287. base::MessageLoopCurrent::ScopedNestableTaskAllower allow;
  288. // Show a custom menu.
  289. if (menu_model) {
  290. base::scoped_nsobject<AtomMenuController> menuController([
  291. [AtomMenuController alloc] initWithModel:menu_model
  292. useDefaultAccelerator:NO]);
  293. forceHighlight_ = YES; // Should highlight when showing menu.
  294. [self setNeedsDisplay:YES];
  295. [statusItem_ popUpStatusItemMenu:[menuController menu]];
  296. forceHighlight_ = NO;
  297. [self setNeedsDisplay:YES];
  298. return;
  299. }
  300. if (menuController_ && ![menuController_ isMenuOpen]) {
  301. // Ensure the UI can update while the menu is fading out.
  302. base::ScopedPumpMessagesInPrivateModes pump_private;
  303. // Redraw the tray icon to show highlight if it is enabled.
  304. [self setNeedsDisplay:YES];
  305. [statusItem_ popUpStatusItemMenu:[menuController_ menu]];
  306. // The popUpStatusItemMenu returns only after the showing menu is closed.
  307. // When it returns, we need to redraw the tray icon to not show highlight.
  308. [self setNeedsDisplay:YES];
  309. }
  310. }
  311. - (void)rightMouseUp:(NSEvent*)event {
  312. trayIcon_->NotifyRightClicked(
  313. gfx::ScreenRectFromNSRect(event.window.frame),
  314. ui::EventFlagsFromModifiers([event modifierFlags]));
  315. }
  316. - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
  317. trayIcon_->NotifyDragEntered();
  318. return NSDragOperationCopy;
  319. }
  320. - (void)mouseExited:(NSEvent*)event {
  321. trayIcon_->NotifyMouseExited(
  322. gfx::ScreenPointFromNSPoint([event locationInWindow]),
  323. ui::EventFlagsFromModifiers([event modifierFlags]));
  324. }
  325. - (void)mouseEntered:(NSEvent*)event {
  326. trayIcon_->NotifyMouseEntered(
  327. gfx::ScreenPointFromNSPoint([event locationInWindow]),
  328. ui::EventFlagsFromModifiers([event modifierFlags]));
  329. }
  330. - (void)mouseMoved:(NSEvent*)event {
  331. trayIcon_->NotifyMouseMoved(
  332. gfx::ScreenPointFromNSPoint([event locationInWindow]),
  333. ui::EventFlagsFromModifiers([event modifierFlags]));
  334. }
  335. - (void)draggingExited:(id<NSDraggingInfo>)sender {
  336. trayIcon_->NotifyDragExited();
  337. }
  338. - (void)draggingEnded:(id<NSDraggingInfo>)sender {
  339. trayIcon_->NotifyDragEnded();
  340. if (NSPointInRect([sender draggingLocation], self.frame)) {
  341. trayIcon_->NotifyDrop();
  342. }
  343. }
  344. - (BOOL)handleDrop:(id<NSDraggingInfo>)sender {
  345. NSPasteboard* pboard = [sender draggingPasteboard];
  346. if ([[pboard types] containsObject:NSFilenamesPboardType]) {
  347. std::vector<std::string> dropFiles;
  348. NSArray* files = [pboard propertyListForType:NSFilenamesPboardType];
  349. for (NSString* file in files)
  350. dropFiles.push_back(base::SysNSStringToUTF8(file));
  351. trayIcon_->NotifyDropFiles(dropFiles);
  352. return YES;
  353. } else if ([[pboard types] containsObject:NSStringPboardType]) {
  354. NSString* dropText = [pboard stringForType:NSStringPboardType];
  355. trayIcon_->NotifyDropText(base::SysNSStringToUTF8(dropText));
  356. return YES;
  357. }
  358. return NO;
  359. }
  360. - (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender {
  361. return YES;
  362. }
  363. - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
  364. [self handleDrop:sender];
  365. return YES;
  366. }
  367. - (void)setNeedsDisplay:(BOOL)display {
  368. [self updateAttributedTitle];
  369. [super setNeedsDisplay:display];
  370. }
  371. - (BOOL)shouldHighlight {
  372. switch (highlight_mode_) {
  373. case atom::TrayIcon::HighlightMode::ALWAYS:
  374. return true;
  375. case atom::TrayIcon::HighlightMode::NEVER:
  376. return false;
  377. case atom::TrayIcon::HighlightMode::SELECTION:
  378. BOOL isMenuOpen = menuController_ && [menuController_ isMenuOpen];
  379. return forceHighlight_ || inMouseEventSequence_ || isMenuOpen;
  380. }
  381. }
  382. @end
  383. namespace atom {
  384. TrayIconCocoa::TrayIconCocoa() : weak_factory_(this) {
  385. status_item_view_.reset([[StatusItemView alloc] initWithIcon:this]);
  386. }
  387. TrayIconCocoa::~TrayIconCocoa() {
  388. [status_item_view_ removeItem];
  389. if (menu_model_)
  390. menu_model_->RemoveObserver(this);
  391. }
  392. void TrayIconCocoa::SetImage(const gfx::Image& image) {
  393. [status_item_view_ setImage:image.IsEmpty() ? nil : image.AsNSImage()];
  394. }
  395. void TrayIconCocoa::SetPressedImage(const gfx::Image& image) {
  396. [status_item_view_ setAlternateImage:image.AsNSImage()];
  397. }
  398. void TrayIconCocoa::SetToolTip(const std::string& tool_tip) {
  399. [status_item_view_ setToolTip:base::SysUTF8ToNSString(tool_tip)];
  400. }
  401. void TrayIconCocoa::SetTitle(const std::string& title) {
  402. [status_item_view_ setTitle:base::SysUTF8ToNSString(title)];
  403. }
  404. void TrayIconCocoa::SetHighlightMode(TrayIcon::HighlightMode mode) {
  405. [status_item_view_ setHighlight:mode];
  406. }
  407. void TrayIconCocoa::SetIgnoreDoubleClickEvents(bool ignore) {
  408. [status_item_view_ setIgnoreDoubleClickEvents:ignore];
  409. }
  410. bool TrayIconCocoa::GetIgnoreDoubleClickEvents() {
  411. return [status_item_view_ getIgnoreDoubleClickEvents];
  412. }
  413. void TrayIconCocoa::PopUpOnUI(AtomMenuModel* menu_model) {
  414. [status_item_view_ popUpContextMenu:menu_model];
  415. }
  416. void TrayIconCocoa::PopUpContextMenu(const gfx::Point& pos,
  417. AtomMenuModel* menu_model) {
  418. base::PostTaskWithTraits(
  419. FROM_HERE, {content::BrowserThread::UI},
  420. base::BindOnce(&TrayIconCocoa::PopUpOnUI, weak_factory_.GetWeakPtr(),
  421. base::Unretained(menu_model)));
  422. }
  423. void TrayIconCocoa::SetContextMenu(AtomMenuModel* menu_model) {
  424. // Substribe to MenuClosed event.
  425. if (menu_model_)
  426. menu_model_->RemoveObserver(this);
  427. menu_model_ = menu_model;
  428. if (menu_model) {
  429. menu_model->AddObserver(this);
  430. // Create native menu.
  431. menu_.reset([[AtomMenuController alloc] initWithModel:menu_model
  432. useDefaultAccelerator:NO]);
  433. } else {
  434. menu_.reset();
  435. }
  436. [status_item_view_ setMenuController:menu_.get()];
  437. }
  438. gfx::Rect TrayIconCocoa::GetBounds() {
  439. auto bounds = gfx::ScreenRectFromNSRect([status_item_view_ window].frame);
  440. return bounds;
  441. }
  442. void TrayIconCocoa::OnMenuWillClose() {
  443. [status_item_view_ setNeedsDisplay:YES];
  444. }
  445. // static
  446. TrayIcon* TrayIcon::Create() {
  447. return new TrayIconCocoa;
  448. }
  449. } // namespace atom