Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 2 additions & 17 deletions CollapseLauncher/XAMLs/MainApp/TrayIcon.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,9 @@
mc:Ignorable="d">
<tb:TaskbarIcon x:Name="CollapseTaskbar"
x:FieldModifier="internal"
ContextMenuMode="PopupMenu"
DoubleClickCommand="{x:Bind ToggleAllVisibilityInvokeCommand}"
LeftClickCommand="{x:Bind BringToForegroundInvokeCommand}"
Logger="{x:Bind LoggerInstance}"
MenuActivation="RightClick"
RightClickCommand="{x:Bind UpdateContextMenuInvokeCommand}"
Visibility="Collapsed">
<tb:TaskbarIcon.ContextFlyout>
<MenuFlyout>
<MenuFlyoutItem x:Name="MainTaskbarToggle"
Command="{x:Bind ToggleMainVisibilityButtonCommand}" />
<MenuFlyoutItem x:Name="ConsoleTaskbarToggle"
Command="{x:Bind ToggleConsoleVisibilityButtonCommand}"
IsEnabled="False" />
<MenuFlyoutSeparator />
<MenuFlyoutItem x:Name="CloseButton"
Command="{x:Bind CloseAppCommand}" />
</MenuFlyout>
</tb:TaskbarIcon.ContextFlyout>
</tb:TaskbarIcon>
MenuActivation="None"
Visibility="Collapsed" />
</UserControl>
123 changes: 77 additions & 46 deletions CollapseLauncher/XAMLs/MainApp/TrayIcon.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Hi3Helper.Win32.Native.LibraryImport;
using Microsoft.Extensions.Logging;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.Win32;
using System;
using System.Drawing;
Expand All @@ -24,6 +25,14 @@ public sealed partial class TrayIcon
{
internal static TrayIcon Current { get; private set; }

private const string HideWindowGlyph = "\uE949"; // CalculatorSubtract
private const string ShowWindowGlyph = "\uE744"; // ResizeMouseMedium

private TrayMenuHost _menuHost;
private MenuFlyoutItem _mainToggle;
private MenuFlyoutItem _consoleToggle;
private MenuFlyoutItem _exitItem;

internal bool IsCreated
{
get
Expand Down Expand Up @@ -114,35 +123,77 @@ private void Initializer(int instanceCount)
CollapseTaskbar.SetValue(TaskbarIcon.CustomNameProperty, $"Collapse Launcher{instanceIndicator}");
}

// Bug in W10: Weird border issue
// Verdict: disable SecondWindow ContextMenuMode, use classic.
// if (isPreview) CollapseTaskbar.ContextMenuMode = ContextMenuMode.SecondWindow;
#if DEBUG
CollapseTaskbar.ToolTipText =
$"Collapse Launcher{instanceIndicator}\r\n" +
$"{_popupHelp1}\r\n" +
$"{_popupHelp2}";
#else
CollapseTaskbar.ToolTipText =
$"Collapse Launcher{instanceIndicator}\r\n" +
$"{_popupHelp1}\r\n" +
$"{_popupHelp2}";
#endif
CloseButton.Text = _exitApp;

// Switch toggle text to see if it's started with Start
MainTaskbarToggle.Text = (m_appMode == AppMode.StartOnTray) ? _showApp : _hideApp;
ConsoleTaskbarToggle.Text = (m_appMode == AppMode.StartOnTray) ? _showConsole : _hideConsole;
MessageWindow messageWindow = CollapseTaskbar.TrayIcon.MessageWindow;
messageWindow.KeyboardEventReceived += OnTrayContextMenu;

CollapseTaskbar.Icon = Icon.FromHandle(LauncherConfig.AppIconSmall);
CollapseTaskbar.Visibility = Visibility.Visible;

CollapseTaskbar.TrayIcon.MessageWindow.BalloonToolTipChanged += BalloonChangedEvent;
messageWindow.BalloonToolTipChanged += BalloonChangedEvent;
}

public void Dispose()
{
CollapseTaskbar.Dispose();
CollapseTaskbar.TrayIcon.MessageWindow.KeyboardEventReceived -= OnTrayContextMenu;
TrayMenuHost host = _menuHost;
_menuHost = null;
try
{
host?.Dispose();
}
finally
{
CollapseTaskbar.Dispose();
}
}

private async void OnTrayContextMenu(object sender, MessageWindow.KeyboardEventReceivedEventArgs args)
{
if (args.KeyboardEvent != KeyboardEvent.ContextMenu || !CollapseTaskbar.IsCreated) return;

// H.NotifyIcon exposes the packed screen coordinates as unsigned words.
Point point = new((short)args.Point.X, (short)args.Point.Y);
TrayMenuHost host = _menuHost;
try
{
// The WinUI menu must acquire its XamlRoot from the tray host.
host = _menuHost ??= new TrayMenuHost(CreateTrayMenu(), CollapseTaskbar.TrayIcon, UpdateContextMenu);
await host.ShowAsync(point, ActualTheme, FlowDirection);
}
catch (Exception ex)
{
if (_menuHost != host) return;
_menuHost = null;
try
{
host?.Dispose();
}
catch (Exception cleanupException)
{
ex = new AggregateException(ex, cleanupException);
}
Logger.WriteLine($"[TrayIcon] Could not open the tray menu.\r\n{ex}", LogType.Warning, true);
}
}

private MenuFlyout CreateTrayMenu()
{
_mainToggle = CreateItem(ToggleMainVisibilityButtonCommand, HideWindowGlyph);
_consoleToggle = CreateItem(ToggleConsoleVisibilityButtonCommand, "\uE756"); // CommandPrompt
_exitItem = CreateItem(CloseAppCommand, "\uE7E8"); // PowerButton
return new MenuFlyout { Items = { _mainToggle, _consoleToggle, new MenuFlyoutSeparator(), _exitItem } };

MenuFlyoutItem CreateItem(IRelayCommand command, string glyph) => new()
{
Command = command,
Padding = new Thickness(11, 4, 11, 7), // Match the template's NarrowPadding state.
Icon = new FontIcon { Glyph = glyph }
};
}

/// <summary>
Expand Down Expand Up @@ -235,12 +286,6 @@ private async void NotificationOnMouseEventReceived(object o, MessageWindow.Mous
[RelayCommand]
private void BringToForegroundInvoke() => BringToForeground();

/// <summary>
/// Update tray context menu
/// </summary>
[RelayCommand]
private void UpdateContextMenuInvoke() => UpdateContextMenu();

/// <summary>
/// Close app
/// </summary>
Expand All @@ -262,14 +307,12 @@ public void ToggleConsoleVisibility(bool forceShow = false)
if (PInvoke.IsWindowVisible(consoleWindowHandle) && !forceShow)
{
LoggerConsole.DisposeConsole();
ConsoleTaskbarToggle.Text = _showConsole;
Logger.WriteLine("Console is hidden!");
}
else
{
LoggerConsole.AllocateConsole();
PInvoke.SetForegroundWindow(PInvoke.GetConsoleWindow());
ConsoleTaskbarToggle.Text = _hideConsole;
Logger.WriteLine("Console is visible!");
}
}
Expand All @@ -287,7 +330,6 @@ public void ToggleMainVisibility(bool forceShow = false)
{
WindowUtility.CurrentWindow?.Hide(false);
EfficiencyModeWrapper(true);
MainTaskbarToggle.Text = _showApp;
// Increase refresh rate to 1000ms when main window is hidden
RefreshRate = RefreshRateSlow;
m_homePage?.StopCarouselSlideshow();
Expand All @@ -304,7 +346,6 @@ public void ToggleMainVisibility(bool forceShow = false)
WindowUtility.CurrentWindow?.Show(false);
EfficiencyModeWrapper(false);
PInvoke.SetForegroundWindow(mainWindowHandle);
MainTaskbarToggle.Text = _hideApp;
m_homePage?.StartCarouselSlideshow();
// Revert refresh rate to its default
RefreshRate = RefreshRateDefault;
Expand Down Expand Up @@ -374,27 +415,17 @@ public void BringToForeground()
// ReSharper disable once MemberCanBePrivate.Global
public void UpdateContextMenu()
{
if (!IsCreated) return;
// Enable visibility toggle for console if the console is enabled
if (LauncherConfig.GetAppConfigValue("EnableConsole").ToBool())
{
ConsoleTaskbarToggle.IsEnabled = true;
}
else
{
ConsoleTaskbarToggle.IsEnabled = false;
ConsoleTaskbarToggle.Text = _hideConsole;
}

// Force refresh all text based on their respective window state
nint consoleWindowHandle = PInvoke.GetConsoleWindow();
nint mainWindowHandle = WindowUtility.CurrentWindowPtr;

bool isMainWindowVisible = PInvoke.IsWindowVisible(mainWindowHandle);
bool isConsoleVisible = LauncherConfig.GetAppConfigValue("EnableConsole").ToBool() && PInvoke.IsWindowVisible(consoleWindowHandle);
if (!IsCreated || _mainToggle is null) return;

bool consoleEnabled = LauncherConfig.GetAppConfigValue("EnableConsole").ToBool();
bool isConsoleVisible = consoleEnabled && PInvoke.IsWindowVisible(PInvoke.GetConsoleWindow());
bool isMainWindowVisible = PInvoke.IsWindowVisible(WindowUtility.CurrentWindowPtr);

ConsoleTaskbarToggle.Text = isConsoleVisible ? _hideConsole : _showConsole;
MainTaskbarToggle.Text = isMainWindowVisible ? _hideApp : _showApp;
_exitItem.Text = _exitApp;
_consoleToggle.IsEnabled = consoleEnabled;
_consoleToggle.Text = isConsoleVisible ? _hideConsole : _showConsole;
_mainToggle.Text = isMainWindowVisible ? _hideApp : _showApp;
((FontIcon)_mainToggle.Icon).Glyph = isMainWindowVisible ? HideWindowGlyph : ShowWindowGlyph;
}

/// <summary>
Expand Down
Loading
Loading