using MonoMac.AppKit;
using System.Diagnostics.CodeAnalysis;
namespace System.Application.UI
{
///
/// Represents a Notification Tray Icon (on a OSxMac StatusBarItem)
///
public class NotifyIcon : INotifyIcon
{
NSStatusItem? _item;
[NotNull, DisallowNull] // C# 8 not null
NSStatusItem? StatusBarItem
{
get => _item ?? throw new ArgumentNullException(nameof(_item));
set
{
_item = value;
UpdateMenu();
}
}
public event EventHandler? Click;
public event EventHandler? DoubleClick;
public event EventHandler? RightClick;
///
/// Updates the Tray Menu Item settings, ToolTip, ContextMenu, Image etc on MacOSX
///
void UpdateMenu()
{
if (_item != null)
{
var f = DI.Get.IUIFrameworkHelper>();
_item.Image = NSImage.FromStream(f.OpenAsset(new Uri(IconPath)));
_item.ToolTip = ToolTipText;
if (StatusBarItem.Menu == null)
{
StatusBarItem.Menu = new NSMenu();
}
else
{
StatusBarItem.Menu.RemoveAllItems();
}
if (_menu == null) throw new ArgumentNullException(nameof(_menu));
f.ForEachMenuItems(_menu, item =>
{
NSMenuItem menuItem = new NSMenuItem(item.header);
menuItem.Activated += (_, _) => { item.activated(); };
StatusBarItem.Menu.AddItem(menuItem);
});
StatusBarItem.DoubleClick += (s, e) => { DoubleClick?.Invoke(this, new EventArgs()); };
}
}
///
/// Gets or sets the icon for the notify icon. Either a file system path
/// or a resm: manifest resource path can be specified.
///
string _iconPath = "";
public string IconPath { get => _iconPath; set { _iconPath = value; UpdateMenu(); } }
string _toolTip = "";
///
/// Gets or sets the tooltip text for the notify icon.
///
public string ToolTipText { get => _toolTip; set { _toolTip = value; UpdateMenu(); } }
TContextMenu? _menu;
///
/// Gets or sets the context menu for the notify icon.
///
public TContextMenu? ContextMenu
{
get => _menu;
set
{
_menu = value;
UpdateMenu();
}
}
///
/// Gets or sets if the notify icon is visible in the
/// taskbar notification area or not.
///
public bool Visible { get; set; }
public void Remove()
{
StatusBarItem?.Dispose();
}
void Init()
{
var systemStatusBar = NSStatusBar.SystemStatusBar;
StatusBarItem = systemStatusBar.CreateStatusItem(30);
StatusBarItem.ToolTip = ToolTipText;
}
///
/// Creates a new NotifyIcon instance and sets up some
/// required resources.
///
public NotifyIcon()
{
MainThreadDesktop.BeginInvokeOnMainThread(Init,
MainThreadDesktop.DispatcherPriority.MaxValue, true);
}
}
}