tray_icon_cocoa.mm 16 KB

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