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; 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 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("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; } ProcessStartInfo startInfo = new() { FileName = item.Target, Arguments = item.Arguments ?? "", UseShellExecute = true, WorkingDirectory = Directory.Exists(item.Target) ? item.Target : ConfigService.AppFolder }; Process.Start(startInfo); popup?.Close(); } }