using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; using TaskbarLauncher.Models; using TaskbarLauncher.Services; namespace TaskbarLauncher.Views; public partial class LauncherPopup : Window { private const double ScreenMargin = 12; private const double HeaderAndChromeHeight = 118; private bool isRepositionQueued; private readonly List visibleLaunchButtons = []; private readonly List visibleNavigationControls = []; private readonly LauncherConfig config; private readonly Action launchItem; private readonly Action openAllItems; private readonly Action showSettings; private readonly Action editItem; private readonly Action openContainingFolder; private sealed record SearchMatch(LauncherItem Item, string ParentPath); public LauncherPopup(LauncherConfig config, Action launchItem, Action openAllItems, Action showSettings, Action editItem, Action openContainingFolder) { InitializeComponent(); this.config = config; this.launchItem = launchItem; this.openAllItems = openAllItems; this.showSettings = showSettings; this.editItem = editItem; this.openContainingFolder = openContainingFolder; BuildItems(); SizeChanged += (_, _) => QueueReposition(); } public void ShowNearTaskbar() { WindowStartupLocation = WindowStartupLocation.Manual; ApplyScreenBounds(); Show(); UpdateLayout(); RepositionAboveTaskbar(); Activate(); SearchBox.Focus(); } private void QueueReposition() { if (isRepositionQueued) { return; } isRepositionQueued = true; Dispatcher.BeginInvoke(() => { isRepositionQueued = false; ApplyScreenBounds(); RepositionAboveTaskbar(); }, DispatcherPriority.Loaded); } private void ApplyScreenBounds() { Rect workArea = SystemParameters.WorkArea; double maxPopupHeight = Math.Max(240, workArea.Height - (ScreenMargin * 2)); MaxHeight = maxPopupHeight; ItemsScrollViewer.MaxHeight = Math.Max(160, maxPopupHeight - HeaderAndChromeHeight); Left = Math.Max(workArea.Left + ScreenMargin, workArea.Right - Width - ScreenMargin); } private void RepositionAboveTaskbar() { Rect workArea = SystemParameters.WorkArea; double height = ActualHeight > 0 ? ActualHeight : DesiredSize.Height; double clampedHeight = Math.Min(height, MaxHeight); if (height > MaxHeight && !double.IsNaN(MaxHeight) && MaxHeight > 0) { Height = MaxHeight; clampedHeight = MaxHeight; } else if (Height > 0 && height < MaxHeight) { ClearValue(HeightProperty); } Top = Math.Max(workArea.Top + ScreenMargin, workArea.Bottom - clampedHeight - ScreenMargin); } private void BuildItems() { ItemsPanel.Children.Clear(); visibleLaunchButtons.Clear(); visibleNavigationControls.Clear(); if (config.RecentItems.Any(item => !item.IsDisabled)) { ItemsPanel.Children.Add(CreateRecentItemsControl()); } bool expandMenusByDefault = config.Items.Count <= 2; foreach (LauncherItem item in GetDisplayItems(config.Items)) { ItemsPanel.Children.Add(CreateItemControl(item, 0, expandMenusByDefault)); } RebuildNavigationLists(); } private Expander CreateRecentItemsControl() { Expander expander = new() { Header = new TextBlock { Text = "Recent" }, IsExpanded = true, Margin = new Thickness(0, 4, 0, 8), Focusable = true }; expander.KeyDown += NavigationControl_KeyDown; expander.Expanded += (_, _) => RebuildNavigationAndReposition(); expander.Collapsed += (_, _) => RebuildNavigationAndReposition(); StackPanel recentItems = new(); foreach (LauncherItem item in config.RecentItems.Where(item => !item.IsDisabled)) { recentItems.Children.Add(CreateItemControl(item, 1, expandMenusByDefault: false, allowEdit: false)); } expander.Content = recentItems; return expander; } private FrameworkElement CreateItemControl(LauncherItem item, int depth, bool expandMenusByDefault, bool allowEdit = true) { if (item.Type == LauncherItemType.Menu) { Expander expander = new() { Header = CreateMenuHeader(item), IsExpanded = expandMenusByDefault, Margin = new Thickness(depth * 12, 4, 0, 4), Focusable = true, Tag = item, ToolTip = CreateItemToolTip(item) }; expander.KeyDown += NavigationControl_KeyDown; expander.Expanded += (_, _) => RebuildNavigationAndReposition(); expander.Collapsed += (_, _) => RebuildNavigationAndReposition(); StackPanel children = new(); foreach (LauncherItem child in GetDisplayItems(item.Children)) { children.Children.Add(CreateItemControl(child, depth + 1, expandMenusByDefault, allowEdit)); } expander.Content = children; return expander; } System.Windows.Controls.Button button = new() { Content = CreateButtonContent(item), Margin = new Thickness(depth * 12, 2, 0, 2), MinHeight = DisplayModeMetrics.GetRowHeight(GetEffectiveDisplayMode(item)), HorizontalContentAlignment = System.Windows.HorizontalAlignment.Left, Tag = item, ToolTip = CreateItemToolTip(item) }; button.Click += (_, _) => launchItem(item); if (allowEdit) { button.ContextMenu = CreateItemContextMenu(item); } button.KeyDown += LaunchButton_KeyDown; return button; } private TextBlock CreateMenuHeader(LauncherItem item) { System.Windows.Controls.MenuItem openAllMenuItem = new() { Header = "Open All", IsEnabled = item.Children.Any(IsLaunchable) }; openAllMenuItem.Click += (_, e) => { openAllItems(item); e.Handled = true; }; System.Windows.Controls.ContextMenu contextMenu = new(); contextMenu.Items.Add(openAllMenuItem); contextMenu.Items.Add(new Separator()); contextMenu.Items.Add(CreatePinMenuItem(item)); contextMenu.Items.Add(CreateDisableMenuItem(item)); contextMenu.Items.Add(CreateEditMenuItem(item)); return new TextBlock { Text = item.Title, ContextMenu = contextMenu, ToolTip = CreateItemToolTip(item) }; } private System.Windows.Controls.ContextMenu CreateItemContextMenu(LauncherItem item) { System.Windows.Controls.ContextMenu contextMenu = new(); contextMenu.Items.Add(CreatePinMenuItem(item)); contextMenu.Items.Add(CreateDisableMenuItem(item)); contextMenu.Items.Add(CreateRunAsAdminMenuItem(item)); contextMenu.Items.Add(CreateOpenContainingFolderMenuItem(item)); contextMenu.Items.Add(CreateEditMenuItem(item)); return contextMenu; } private System.Windows.Controls.MenuItem CreatePinMenuItem(LauncherItem item) { System.Windows.Controls.MenuItem pinMenuItem = new() { Header = item.IsFavorite ? "Unpin from Top" : "Pin to Top" }; pinMenuItem.Click += (_, e) => { item.IsFavorite = !item.IsFavorite; ConfigService.Save(config); BuildItems(); QueueReposition(); e.Handled = true; }; return pinMenuItem; } private System.Windows.Controls.MenuItem CreateDisableMenuItem(LauncherItem item) { System.Windows.Controls.MenuItem disableMenuItem = new() { Header = item.IsDisabled ? "Enable Item" : "Disable Item" }; disableMenuItem.Click += (_, e) => { item.IsDisabled = !item.IsDisabled; ConfigService.Save(config); BuildItems(); QueueReposition(); e.Handled = true; }; return disableMenuItem; } private System.Windows.Controls.MenuItem CreateRunAsAdminMenuItem(LauncherItem item) { System.Windows.Controls.MenuItem runAsAdminMenuItem = new() { Header = item.RunAsAdmin ? "Run as Admin: On" : "Run as Admin: Off", IsEnabled = LauncherController.CanRunAsAdmin(item.Type) }; runAsAdminMenuItem.Click += (_, e) => { item.RunAsAdmin = !item.RunAsAdmin; ConfigService.Save(config); BuildItems(); QueueReposition(); e.Handled = true; }; return runAsAdminMenuItem; } private System.Windows.Controls.MenuItem CreateOpenContainingFolderMenuItem(LauncherItem item) { System.Windows.Controls.MenuItem openFolderMenuItem = new() { Header = "Open Containing Folder", IsEnabled = CanOpenContainingFolder(item) }; openFolderMenuItem.Click += (_, e) => { openContainingFolder(item); e.Handled = true; }; return openFolderMenuItem; } private System.Windows.Controls.MenuItem CreateEditMenuItem(LauncherItem item) { System.Windows.Controls.MenuItem editMenuItem = new() { Header = "Edit in Settings" }; editMenuItem.Click += (_, e) => { editItem(item); Close(); e.Handled = true; }; return editMenuItem; } private static bool IsLaunchable(LauncherItem item) { return item.Type != LauncherItemType.Menu && !item.IsDisabled && !string.IsNullOrWhiteSpace(item.Target); } private static bool CanOpenContainingFolder(LauncherItem item) { return item.Type is LauncherItemType.App or LauncherItemType.File && !string.IsNullOrWhiteSpace(item.Target); } private static IEnumerable GetDisplayItems(IEnumerable items) { return items .Where(item => !item.IsDisabled) .OrderByDescending(item => item.IsFavorite); } private void SearchBox_TextChanged(object sender, TextChangedEventArgs e) { string query = SearchBox.Text.Trim(); if (string.IsNullOrWhiteSpace(query)) { BuildItems(); } else { BuildSearchResults(query); } QueueReposition(); } private void BuildSearchResults(string query) { ItemsPanel.Children.Clear(); visibleLaunchButtons.Clear(); List matches = []; CollectMatches(config.Items, query, [], matches); if (matches.Count == 0) { ItemsPanel.Children.Add(new TextBlock { Text = "No matches", Foreground = (System.Windows.Media.Brush)System.Windows.Application.Current.Resources["AppMutedTextBrush"], Margin = new Thickness(4, 8, 4, 8) }); return; } foreach (SearchMatch match in matches) { ItemsPanel.Children.Add(CreateSearchResultControl(match)); } RebuildNavigationLists(); } private FrameworkElement CreateSearchResultControl(SearchMatch match) { System.Windows.Controls.Button button = new() { Content = CreateSearchResultContent(match), Margin = new Thickness(0, 2, 0, 2), MinHeight = Math.Max(DisplayModeMetrics.GetRowHeight(GetEffectiveDisplayMode(match.Item)), 48), HorizontalContentAlignment = System.Windows.HorizontalAlignment.Left, Tag = match.Item, ContextMenu = CreateItemContextMenu(match.Item), ToolTip = CreateItemToolTip(match.Item, match.ParentPath) }; button.Click += (_, _) => launchItem(match.Item); button.KeyDown += LaunchButton_KeyDown; return button; } private void RebuildNavigationAndReposition() { RebuildNavigationLists(); QueueReposition(); } private void RebuildNavigationLists() { visibleLaunchButtons.Clear(); visibleNavigationControls.Clear(); AddVisibleNavigationControls(ItemsPanel.Children); } private void AddVisibleNavigationControls(UIElementCollection elements) { foreach (UIElement element in elements) { switch (element) { case Expander expander: visibleNavigationControls.Add(expander); if (expander.IsExpanded && expander.Content is System.Windows.Controls.Panel panel) { AddVisibleNavigationControls(panel.Children); } break; case System.Windows.Controls.Button button: visibleNavigationControls.Add(button); if (button.Tag is LauncherItem) { visibleLaunchButtons.Add(button); } break; } } } private object CreateSearchResultContent(SearchMatch match) { StackPanel panel = new(); panel.Children.Add((UIElement)CreateButtonContent(match.Item)); if (!string.IsNullOrWhiteSpace(match.ParentPath)) { panel.Children.Add(new TextBlock { Text = match.ParentPath, FontSize = 11, Foreground = (System.Windows.Media.Brush)System.Windows.Application.Current.Resources["AppMutedTextBrush"], Margin = new Thickness(0, 3, 0, 0), TextTrimming = TextTrimming.CharacterEllipsis }); } return panel; } private static System.Windows.Controls.ToolTip CreateItemToolTip(LauncherItem item, string? parentPath = null) { StackPanel panel = new() { MaxWidth = 520 }; AddToolTipLine(panel, item.Title, bold: true); AddToolTipLine(panel, $"Type: {item.Type}"); if (!string.IsNullOrWhiteSpace(parentPath)) { AddToolTipLine(panel, $"Menu: {parentPath}"); } if (!string.IsNullOrWhiteSpace(item.Target)) { AddToolTipLine(panel, $"Target: {item.Target}"); } if (!string.IsNullOrWhiteSpace(item.Arguments)) { AddToolTipLine(panel, $"Arguments: {item.Arguments}"); } if (!string.IsNullOrWhiteSpace(item.WorkingFolder)) { AddToolTipLine(panel, $"Working folder: {item.WorkingFolder}"); } if (item.IsFavorite) { AddToolTipLine(panel, "Pinned to top"); } if (item.RunAsAdmin) { AddToolTipLine(panel, "Runs as administrator"); } if (item.StartMinimized) { AddToolTipLine(panel, "Starts minimized"); } return new System.Windows.Controls.ToolTip { Content = panel }; } private static void AddToolTipLine(StackPanel panel, string text, bool bold = false) { panel.Children.Add(new TextBlock { Text = text, FontWeight = bold ? FontWeights.SemiBold : FontWeights.Normal, TextWrapping = TextWrapping.Wrap, Margin = panel.Children.Count == 0 ? new Thickness(0) : new Thickness(0, 3, 0, 0) }); } private static void CollectMatches(IEnumerable items, string query, List parentNames, List matches) { foreach (LauncherItem item in GetDisplayItems(items)) { bool isLaunchable = item.Type != LauncherItemType.Menu && !item.IsDisabled; string parentPath = string.Join(" > ", parentNames); if (isLaunchable && Matches(item, query, parentPath)) { matches.Add(new SearchMatch(item, parentPath)); } if (item.Children.Count > 0) { string menuName = string.IsNullOrWhiteSpace(item.Title) ? "Untitled" : item.Title; CollectMatches(item.Children, query, [.. parentNames, menuName], matches); } } } private static bool Matches(LauncherItem item, string query, string parentPath) { return item.Title.Contains(query, StringComparison.OrdinalIgnoreCase) || item.Target.Contains(query, StringComparison.OrdinalIgnoreCase) || (item.Arguments?.Contains(query, StringComparison.OrdinalIgnoreCase) ?? false) || parentPath.Contains(query, StringComparison.OrdinalIgnoreCase); } private void SearchBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key == Key.Escape) { Close(); e.Handled = true; return; } if (e.Key == Key.Enter && visibleLaunchButtons.FirstOrDefault()?.Tag is LauncherItem item) { launchItem(item); e.Handled = true; return; } if (e.Key == Key.Down) { FocusNavigationControl(0); e.Handled = true; return; } if (e.Key == Key.Up) { FocusNavigationControl(visibleNavigationControls.Count - 1); e.Handled = true; return; } if (e.Key == Key.Home) { SearchBox.CaretIndex = 0; e.Handled = true; return; } if (e.Key == Key.End) { SearchBox.CaretIndex = SearchBox.Text.Length; e.Handled = true; } } private void LaunchButton_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (sender is not System.Windows.Controls.Button button) { return; } if (e.Key == Key.Enter && button.Tag is LauncherItem item) { launchItem(item); e.Handled = true; return; } if (e.Key == Key.Escape) { Close(); e.Handled = true; return; } HandleNavigationControlKey(button, e); } private void NavigationControl_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (sender is not System.Windows.Controls.Control control) { return; } if (e.Key == Key.Enter && control is Expander expander) { expander.IsExpanded = !expander.IsExpanded; QueueReposition(); e.Handled = true; return; } if (e.Key == Key.Escape) { Close(); e.Handled = true; return; } HandleNavigationControlKey(control, e); } private void HandleNavigationControlKey(System.Windows.Controls.Control control, System.Windows.Input.KeyEventArgs e) { int index = visibleNavigationControls.IndexOf(control); if (index < 0) { return; } if (e.Key == Key.Down) { FocusNavigationControl(index + 1); e.Handled = true; return; } if (e.Key == Key.Up) { if (index == 0) { SearchBox.Focus(); SearchBox.CaretIndex = SearchBox.Text.Length; } else { FocusNavigationControl(index - 1); } e.Handled = true; return; } if (e.Key == Key.Home) { FocusNavigationControl(0); e.Handled = true; return; } if (e.Key == Key.End) { FocusNavigationControl(visibleNavigationControls.Count - 1); e.Handled = true; } } private void FocusNavigationControl(int index) { if (visibleNavigationControls.Count == 0) { return; } int clampedIndex = Math.Clamp(index, 0, visibleNavigationControls.Count - 1); System.Windows.Controls.Control control = visibleNavigationControls[clampedIndex]; Keyboard.ClearFocus(); control.Focus(); control.BringIntoView(); } protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e) { if (e.Key == Key.Escape) { Close(); e.Handled = true; return; } base.OnKeyDown(e); } private object CreateButtonContent(LauncherItem item) { LauncherDisplayMode displayMode = GetEffectiveDisplayMode(item); if (displayMode == LauncherDisplayMode.LargeIconOnly) { ImageSource? iconOnly = IconService.GetIcon(item, large: true); if (iconOnly is not null) { double iconOnlySize = DisplayModeMetrics.GetIconSize(displayMode); return new System.Windows.Controls.Image { Source = iconOnly, Width = iconOnlySize, Height = iconOnlySize, HorizontalAlignment = System.Windows.HorizontalAlignment.Center }; } return new TextBlock { Text = GetLabel(item), FontSize = 20, HorizontalAlignment = System.Windows.HorizontalAlignment.Center }; } StackPanel panel = new() { Orientation = System.Windows.Controls.Orientation.Horizontal }; bool large = displayMode is LauncherDisplayMode.LargeIconOnly or LauncherDisplayMode.LargeIconWithText; ImageSource? icon = IconService.GetIcon(item, large); if (icon is not null) { double size = DisplayModeMetrics.GetIconSize(displayMode); panel.Children.Add(new System.Windows.Controls.Image { Source = icon, Width = size, Height = size, Margin = new Thickness(0, 0, 10, 0), VerticalAlignment = VerticalAlignment.Center }); } else { panel.Children.Add(new TextBlock { Text = GetLabel(item), FontSize = displayMode == LauncherDisplayMode.SmallIconWithText ? 12 : 14, Width = displayMode == LauncherDisplayMode.SmallIconWithText ? 64 : 74, VerticalAlignment = VerticalAlignment.Center }); } panel.Children.Add(new TextBlock { Text = item.Title, FontSize = displayMode == LauncherDisplayMode.CompactList ? 12 : 14, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis }); return panel; } private LauncherDisplayMode GetEffectiveDisplayMode(LauncherItem item) { return item.DisplayMode; } private static string GetLabel(LauncherItem item) { return item.Type switch { LauncherItemType.Folder => "[Folder]", LauncherItemType.Website => "[Web]", LauncherItemType.File => "[File]", _ => "[App]" }; } private void Settings_Click(object sender, RoutedEventArgs e) { showSettings(); } }