Files
Taskbar-Launcher/Services/LauncherController.cs
2026-06-02 18:57:04 -04:00

128 lines
3.5 KiB
C#

using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using TaskbarLauncher.Models;
using TaskbarLauncher.Views;
namespace TaskbarLauncher.Services;
public sealed class LauncherController : IDisposable
{
private readonly HotkeyService hotkeyService = new();
private NotifyIcon? notifyIcon;
private LauncherPopup? popup;
private MainWindow? settingsWindow;
private AboutWindow? aboutWindow;
public LauncherConfig Config { get; private set; } = new();
public void Start()
{
Config = ConfigService.Load();
CreateTrayIcon();
RegisterHotkey();
}
public void ReloadConfig()
{
Config = ConfigService.Load();
RegisterHotkey();
popup?.Close();
popup = null;
}
public void ShowSettings()
{
settingsWindow ??= new MainWindow(this);
settingsWindow.Show();
settingsWindow.Activate();
}
public void ShowAbout()
{
if (aboutWindow?.IsVisible == true)
{
aboutWindow.Activate();
return;
}
aboutWindow = new AboutWindow();
aboutWindow.Closed += (_, _) => aboutWindow = null;
aboutWindow.Show();
aboutWindow.Activate();
}
public void TogglePopup()
{
if (popup?.IsVisible == true)
{
popup.Close();
popup = null;
return;
}
popup = new LauncherPopup(Config, LaunchItem, ShowSettings);
popup.Closed += (_, _) => popup = null;
popup.ShowNearTaskbar();
}
public void Dispose()
{
hotkeyService.Dispose();
notifyIcon?.Dispose();
}
private void RegisterHotkey()
{
hotkeyService.Pressed -= HotkeyPressed;
hotkeyService.Register(Config.Hotkey);
hotkeyService.Pressed += HotkeyPressed;
}
private void HotkeyPressed(object? sender, EventArgs e)
{
System.Windows.Application.Current.Dispatcher.Invoke(TogglePopup);
}
private void CreateTrayIcon()
{
notifyIcon = new NotifyIcon
{
Text = "Taskbar Launcher",
Icon = SystemIcons.Application,
Visible = true,
ContextMenuStrip = new ContextMenuStrip()
};
notifyIcon.DoubleClick += (_, _) => TogglePopup();
notifyIcon.ContextMenuStrip.Items.Add("Open Launcher", null, (_, _) => TogglePopup());
notifyIcon.ContextMenuStrip.Items.Add("Settings", null, (_, _) => ShowSettings());
notifyIcon.ContextMenuStrip.Items.Add("About", null, (_, _) => ShowAbout());
notifyIcon.ContextMenuStrip.Items.Add("Reload Config", null, (_, _) => ReloadConfig());
notifyIcon.ContextMenuStrip.Items.Add("Open Config Folder", null, (_, _) => ConfigService.OpenConfigFolder());
notifyIcon.ContextMenuStrip.Items.Add("Exit", null, (_, _) => System.Windows.Application.Current.Shutdown());
}
private void LaunchItem(LauncherItem item)
{
if (item.Type == LauncherItemType.Menu || string.IsNullOrWhiteSpace(item.Target))
{
return;
}
string target = Environment.ExpandEnvironmentVariables(item.Target);
ProcessStartInfo startInfo = new()
{
FileName = target,
Arguments = item.Arguments ?? "",
UseShellExecute = true,
WorkingDirectory = Directory.Exists(target) ? target : ConfigService.AppFolder
};
Process.Start(startInfo);
popup?.Close();
}
}