A macOS-style dock, widget bar and desktop widgets for Windows (WPF, .NET 10)
Faster All Apps grid, profile card, steadier desktop button and AI limits
QiDock contributors29421871e80a
diff --git a/App.xaml.cs b/App.xaml.csindex ef02fe6..4a11b9d 100644--- a/App.xaml.cs+++ b/App.xaml.cs@@ -11,6 +11,27 @@ namespace QiDock;public partial class App : Application{private Mutex? _instanceMutex;++ /// <summary>+ /// The circle Windows draws where a finger or pen taps a WPF window could stay behind on the screen+ /// when the window under it hid or closed at once (the dock hiding, an overlay closing after a tap).+ /// QiDock's windows answer every tap themselves, so that circle is turned off for all of them before+ /// the first one is made. Press and hold (a right click by touch) keeps working.+ /// </summary>+ private static void TurnOffTouchRings()+ {+ foreach (var property in new[] { System.Windows.Input.Stylus.IsTapFeedbackEnabledProperty, System.Windows.Input.Stylus.IsTouchFeedbackEnabledProperty, System.Windows.Input.Stylus.IsFlicksEnabledProperty })+ {+ try+ {+ property.OverrideMetadata(typeof(Window), new FrameworkPropertyMetadata(false));+ }+ catch (ArgumentException ex)+ {+ Trace.TraceWarning("Touch feedback stays on: {0}", ex.Message);+ }+ }+ }public ApplicationPreferences Preferences { get; } = new(new DockSettingsStore());#if DEBUG@@ -21,6 +42,7 @@ public partial class App : Applicationprotected override void OnStartup(StartupEventArgs e){+ TurnOffTouchRings();UiText.Current.SetLanguage(Preferences.Current.Language);ThemeManager.Apply(Preferences.Current.Theme, Preferences.Current.SurfaceOpacity, Preferences.Current.Style);#if DEBUGdiff --git a/AppGrid.cs b/AppGrid.csnew file mode 100644index 0000000..abb55f3--- /dev/null+++ b/AppGrid.cs@@ -0,0 +1,1493 @@+using System.IO;+using System.Text.Json;+using System.Text.Json.Serialization;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Input;+using System.Windows.Interop;+using System.Windows.Media;+using System.Windows.Media.Animation;+using System.Windows.Shapes;+using System.Windows.Threading;+using QiDock.Services;+using QiDock.Services.Notifications;+using QiDock.Widgets;++namespace QiDock;++/// <summary>One spot in the app screen: an app, or a folder holding two or more apps.</summary>+internal sealed class LaunchEntry+{+ public string? App { get; set; }+ public string? Folder { get; set; }+ public List<string>? Apps { get; set; }++ [JsonIgnore] public bool IsFolder => Apps is not null;+}++/// <summary>The user's arrangement of the app screen, kept in launchpad.json next to the settings.</summary>+internal static class LaunchStore+{+ private sealed class Data+ {+ public List<LaunchEntry> Items { get; set; } = [];+ }++ private static readonly JsonSerializerOptions Json = new() { WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull };++ private static string FilePath => System.IO.Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock", "launchpad.json");++ /// <summary>The saved arrangement, or null while the user has never moved anything (alphabetical then).</summary>+ public static List<LaunchEntry>? Load()+ {+ try+ {+ return File.Exists(FilePath) ? JsonSerializer.Deserialize<Data>(File.ReadAllText(FilePath), Json)?.Items : null;+ }+ catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException)+ {+ System.Diagnostics.Trace.TraceWarning("App screen layout could not be read: {0}", ex.Message);+ return null;+ }+ }++ public static void Save(List<LaunchEntry> items)+ {+ try+ {+ Directory.CreateDirectory(System.IO.Path.GetDirectoryName(FilePath)!);+ var temp = FilePath + ".tmp";+ File.WriteAllText(temp, JsonSerializer.Serialize(new Data { Items = items }, Json));+ File.Move(temp, FilePath, true);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ System.Diagnostics.Trace.TraceWarning("App screen layout could not be saved: {0}", ex.Message);+ }+ }++ /// <summary>+ /// The saved arrangement with uninstalled apps dropped and new apps added at the end (all apps+ /// alphabetically when nothing was saved). A folder left with one app becomes that app.+ /// </summary>+ public static List<LaunchEntry> Merge(List<LaunchEntry>? saved, IReadOnlyList<InstalledApp> apps)+ {+ var known = new HashSet<string>(apps.Select(a => a.Id), StringComparer.OrdinalIgnoreCase);+ var used = new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ var result = new List<LaunchEntry>();+ foreach (var entry in saved ?? [])+ {+ if (entry.IsFolder)+ {+ var inside = entry.Apps!.Where(id => known.Contains(id) && used.Add(id)).ToList();+ if (inside.Count >= 2) result.Add(new LaunchEntry { Folder = entry.Folder, Apps = inside });+ else if (inside.Count == 1) result.Add(new LaunchEntry { App = inside[0] });+ }+ else if (entry.App is { } id && known.Contains(id) && used.Add(id))+ {+ result.Add(new LaunchEntry { App = id });+ }+ }+ foreach (var app in apps)+ {+ if (used.Add(app.Id)) result.Add(new LaunchEntry { App = app.Id });+ }+ return result;+ }+}++/// <summary>+/// How much each app is used, for the row of most used apps: what Windows itself counts (how+/// often an app was started and how long it was in front, kept for the Start menu) plus the+/// launches from the app screen, which QiDock counts in app-usage.json.+/// </summary>+internal static class AppUsage+{+ private const string UserAssist = @"Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{CEBFF5CD-ACE2-4F4F-9178-9926F41749EA}\Count";++ private static string FilePath => System.IO.Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock", "app-usage.json");++ /// <summary>A score per app id: starts (at most 50, so one app started by a shortcut key all day does not crowd out the rest) plus minutes in front / 20.</summary>+ public static Dictionary<string, double> Scores()+ {+ var scores = new Dictionary<string, double>(StringComparer.OrdinalIgnoreCase);+ try+ {+ using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(UserAssist);+ foreach (var name in key?.GetValueNames() ?? [])+ {+ if (key!.GetValue(name) is not byte[] { Length: >= 16 } data) continue;+ var starts = BitConverter.ToInt32(data, 4);+ var focusMinutes = BitConverter.ToInt32(data, 12) / 60000.0;+ var score = Math.Min(Math.Max(starts, 0), 50) + Math.Max(focusMinutes, 0) / 20;+ if (score > 0) scores[Rot13(name)] = score;+ }+ }+ catch (Exception ex) when (ex is System.Security.SecurityException or IOException or UnauthorizedAccessException)+ {+ System.Diagnostics.Trace.TraceWarning("App usage could not be read: {0}", ex.Message);+ }+ foreach (var (id, launches) in Own())+ scores[id] = scores.GetValueOrDefault(id) + launches * 2;+ return scores;+ }++ /// <summary>Counts a launch from the app screen.</summary>+ public static void Record(string id)+ {+ var own = Own();+ own[id] = own.GetValueOrDefault(id) + 1;+ try+ {+ Directory.CreateDirectory(System.IO.Path.GetDirectoryName(FilePath)!);+ File.WriteAllText(FilePath, JsonSerializer.Serialize(own));+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }+ }++ private static Dictionary<string, int> Own()+ {+ try+ {+ if (File.Exists(FilePath) && JsonSerializer.Deserialize<Dictionary<string, int>>(File.ReadAllText(FilePath)) is { } saved)+ return new Dictionary<string, int>(saved, StringComparer.OrdinalIgnoreCase);+ }+ catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) { }+ return new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);+ }++ // Windows keeps these names with every letter moved 13 places along the alphabet.+ private static string Rot13(string text) => string.Create(text.Length, text, (span, source) =>+ {+ for (var i = 0; i < source.Length; i++)+ {+ var c = source[i];+ span[i] = c is >= 'a' and <= 'z' ? (char)('a' + (c - 'a' + 13) % 26)+ : c is >= 'A' and <= 'Z' ? (char)('A' + (c - 'A' + 13) % 26)+ : c;+ }+ });+}++/// <summary>+/// Every installed app on pages of large icons over the blurred desktop, like a phone's home+/// screen: swipe, scroll or use the arrow keys to turn pages, type to search, drag an icon to move+/// it and drop it on another to make a folder. The arrangement is remembered.+/// </summary>+public sealed class AppGridWindow : OverlayWindow+{+ private const double SearchTop = 56;+ private const double DragThreshold = 6;+ // Without the blur the screen is darkened almost fully; over the blur a light shade is enough.+ private static readonly Brush Dim = Ui.Solid("#F00E0F13");+ private static readonly Brush FrostedDim = Ui.Solid("#2E000000");+ private static readonly Brush FolderFill = Ui.Solid("#38FFFFFF");+ private static readonly Brush FolderEdge = Ui.Solid("#2EFFFFFF");+ private static readonly Brush TargetFill = Ui.Solid("#4DFFFFFF");+ private static readonly Brush DotOn = Ui.Solid("#F2FFFFFF");+ private static readonly Brush DotOff = Ui.Solid("#59FFFFFF");+ // Icons stay cached between openings (about 64 KB each) so the pages fill at once next time.+ private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, ImageSource?> Icons = new(StringComparer.OrdinalIgnoreCase);++ private sealed class TileParts+ {+ public required FrameworkElement Element;+ public required FrameworkElement IconHost;+ public required Border Backdrop;+ }++ /// <summary>A press on a tile or on the empty page, until the button goes up.</summary>+ private sealed class Press+ {+ public Point Start;+ public LaunchEntry? Entry; // a tile on the pages+ public string? FolderApp; // an app tile inside the open folder+ public FrameworkElement? Icon;+ public bool Swiping;+ public bool Fixed; // a tile in the row of most used apps: opens, never moves+ public double SwipeFrom;+ }++ /// <summary>An icon being dragged.</summary>+ private sealed class Drag+ {+ public required LaunchEntry Entry; // what moves on the pages (an app or a folder)+ public required FrameworkElement Ghost;+ public Vector Grab;+ public LaunchEntry? Folder; // set while the app is still inside the open folder+ }++ private readonly double _cols, _rows, _cellW, _cellH, _icon, _gridLeft, _gridTop;+ private readonly Grid _host = new() { ClipToBounds = true };+ private readonly Canvas _strip = new() { Background = Brushes.Transparent };+ private readonly TranslateTransform _stripShift = new();+ private readonly StackPanel _dots = new() { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Bottom };+ private readonly Grid _folderLayer = new() { Visibility = Visibility.Collapsed };+ private readonly Canvas _dragLayer = new() { IsHitTestVisible = false };+ private readonly TextBlock _note = new() { Foreground = Ui.WhiteSoft, FontSize = 14, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, IsHitTestVisible = false };+ private readonly TextBox _box;+ private readonly Dictionary<string, InstalledApp> _known = new(StringComparer.OrdinalIgnoreCase);+ private readonly Dictionary<LaunchEntry, TileParts> _tiles = [];+ private readonly Dictionary<string, LaunchEntry> _searchEntries = new(StringComparer.OrdinalIgnoreCase);+ private readonly DispatcherTimer _edgeTimer;+ private readonly Queue<(Image Image, string Id)> _iconQueue = new();+ private bool _iconLoaderRunning;+ private bool _closed;++ private List<LaunchEntry> _items = [];+ private List<LaunchEntry> _shown = []; // what the pages show now (the search results while searching)+ private List<LaunchEntry> _others = []; // the pages without the dragged icon+ private List<LaunchEntry> _frequent = []; // the most used apps, a row at the top of the first page+ private readonly Border _shelf = new() { CornerRadius = new CornerRadius(22), Background = Ui.Solid("#14FFFFFF"), BorderBrush = Ui.Solid("#1AFFFFFF"), BorderThickness = new Thickness(1), IsHitTestVisible = false };+ private readonly TextBlock _shelfName = new() { Text = UiText.Get("AppGridFrequent"), Foreground = Ui.Solid("#B3FFFFFF"), FontSize = 12, FontWeight = FontWeights.SemiBold, IsHitTestVisible = false };+ private int _dropIndex;+ private LaunchEntry? _folderTarget;+ private LaunchEntry? _selected; // the icon the arrow keys are on+ private int _page;+ private int _pageCount = 1;+ private (int From, int To) _livePages; // the pages that have tiles+ private bool _neighborsReady; // false while opening: only the first page is made+ private Press? _press;+ private Drag? _drag;+ private Point _lastPoint;+ private int _edgeDirection;+ private double _wheel;+ private DateTime _wheelLock;+ private DateTime _wheelLast;++ // The open folder.+ private LaunchEntry? _openFolder;+ private Border? _folderPanel;+ private Canvas? _folderCanvas;+ private int _folderCols;+ private readonly Dictionary<string, TileParts> _folderTiles = new(StringComparer.OrdinalIgnoreCase);+ private List<string> _folderOthers = [];+ private int _folderDropIndex;++ public static bool IsOpen => Application.Current?.Windows.OfType<AppGridWindow>().Any(w => w.IsVisible) == true;++ public static void Toggle()+ {+ if (CloseIfOpen<AppGridWindow>()) return;+ new AppGridWindow().Present();+ }++ /// <summary>+ /// Loads the app list and the icons of the first pages quietly in the background (some time+ /// after QiDock starts), so the first opening already shows every icon instead of filling in.+ /// </summary>+ public static void Prewarm()+ {+ AppList.RefreshAsync().ContinueWith(t =>+ {+ var ids = LaunchStore.Merge(LaunchStore.Load(), t.Result)+ .Take(80)+ .SelectMany(e => e.IsFolder ? e.Apps!.Take(9) : [e.App!])+ .Where(id => !Icons.ContainsKey(id))+ .ToList();+ if (ids.Count == 0) return;+ var thread = new Thread(() =>+ {+ foreach (var id in ids) Icons.GetOrAdd(id, key => NotificationApps.LoadIcon(key, 128));+ }) { IsBackground = true, Priority = ThreadPriority.BelowNormal, Name = "AppGrid icon prewarm" };+ thread.SetApartmentState(ApartmentState.STA);+ thread.Start();+ }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());+ }++ private AppGridWindow() : base(Dim)+ {+ // Pages of up to 7 × 5 icons, fewer on small screens; the grid sits between the search field and the page dots.+ const double top = 120, bottom = 110;+ var usable = Height - top - bottom;+ _cols = Math.Clamp((int)((Width - 240) / 140), 4, 7);+ _rows = Math.Clamp((int)(usable / 128), 3, 5);+ _cellW = Math.Min(156, (Width - 240) / _cols);+ _cellH = Math.Min(132, usable / _rows);+ // Icons are loaded at 128 pixels: never drawn larger than that on screen, so they stay sharp.+ var scale = Application.Current?.MainWindow is { } main && PresentationSource.FromVisual(main)?.CompositionTarget is { } target ? target.TransformToDevice.M11 : 1.5;+ _icon = Math.Floor(Math.Min(Math.Clamp(Math.Min(_cellW, _cellH) * 0.46, 44, 60), 128 / scale));+ _gridLeft = (Width - _cols * _cellW) / 2;+ _gridTop = top + (usable - _rows * _cellH) / 2;++ _strip.RenderTransform = _stripShift;+ _strip.Height = Height;+ _host.Children.Add(_strip);+ _host.Children.Add(_note);+ Root.Children.Add(_host);++ var (field, box) = SearchField(UiText.Get("AppGridSearch"), 15, Ui.White, Ui.Solid("#A6FFFFFF"), Ui.Solid("#33FFFFFF"));+ _box = box;+ field.Width = 300;+ field.HorizontalAlignment = HorizontalAlignment.Center;+ field.VerticalAlignment = VerticalAlignment.Top;+ field.Margin = new Thickness(0, SearchTop, 0, 0);+ box.TextChanged += (_, _) =>+ {+ _page = 0;+ Refill();+ SnapStrip();+ };+ box.PreviewKeyDown += (_, e) =>+ {+ if (e.Key != Key.Enter || (_shown.Count == 0 && _selected is null)) return;+ e.Handled = true;+ Open(_selected ?? _shown[0]);+ };+ Root.Children.Add(field);++ _dots.Margin = new Thickness(0, 0, 0, Math.Max(40, Height - (_gridTop + _rows * _cellH) - 64));+ Root.Children.Add(_dots);+ Root.Children.Add(_folderLayer);+ Root.Children.Add(_dragLayer);++ _edgeTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(550) };+ _edgeTimer.Tick += (_, _) => FlipWhileDragging();++ PreviewMouseLeftButtonDown += OnPressDown;+ PreviewMouseMove += OnPressMove;+ PreviewMouseLeftButtonUp += OnPressUp;+ LostMouseCapture += (_, _) => { if (_press is not null && !Root.IsMouseCaptured) CancelPress(); };+ PreviewMouseWheel += (_, e) =>+ {+ // In an open folder the wheel scrolls the folder's own list.+ if (_openFolder is not null) return;+ e.Handled = true;+ Wheel(-e.Delta);+ };+ PreviewKeyDown += OnKey;+ PreviewMouseRightButtonUp += OnMenu;+ Closed += (_, _) => _closed = true;++ Load(AppList.Cached ?? []);+ AppList.RefreshAsync().ContinueWith(t =>+ {+ // Rebuilding the pages takes a moment, so only when the list really changed (and nothing is in hand).+ if (_closed || _drag is not null || _openFolder is not null) return;+ if (t.Result.Count == _known.Count && t.Result.All(a => _known.ContainsKey(a.Id))) return;+ Load(t.Result);+ }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());+ }++ protected override bool Frosted => true;++ protected override bool IsBackground(object source) => ReferenceEquals(source, _strip) || ReferenceEquals(source, _host);++ protected override void OnShown() => _box.Focus();++ /// <summary>+ /// The page settles from slightly large to its size. It moves as one cached picture (so the+ /// graphics card only scales it), and the pages beside it are made once it has stopped.+ /// </summary>+ protected override void OnPresented()+ {+ var scale = new ScaleTransform(1.06, 1.06, Width / 2, Height / 2);+ _host.RenderTransform = scale;+ _host.CacheMode = new BitmapCache { SnapsToDevicePixels = true };+ var time = TimeSpan.FromMilliseconds(280);+ var grow = new DoubleAnimation(1, time) { EasingFunction = Motion.Out };+ grow.Completed += (_, _) =>+ {+ _host.CacheMode = null;+ _host.RenderTransform = Transform.Identity;+ if (_closed) return;+ _neighborsReady = true;+ Dispatcher.BeginInvoke(() => { if (!_closed && _drag is null) Arrange(false); }, DispatcherPriority.Background);+ };+ scale.BeginAnimation(ScaleTransform.ScaleXProperty, grow);+ scale.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(1, time) { EasingFunction = Motion.Out });+ }++ protected override void OnDismissing()+ {+ _edgeTimer.Stop();+ if (Root.IsMouseCaptured) Root.ReleaseMouseCapture();+ }++ protected override bool OnEscape()+ {+ if (_openFolder is not null)+ {+ CloseFolder();+ return true;+ }+ if (_box.Text.Length > 0)+ {+ _box.Clear();+ return true;+ }+ return false;+ }++ protected override void OnSourceInitialized(EventArgs e)+ {+ base.OnSourceInitialized(e);+ if (IsFrosted) Root.Background = FrostedDim;+ // Sideways scrolling (a tilting wheel or two fingers on a touchpad) turns pages too.+ (PresentationSource.FromVisual(this) as HwndSource)?.AddHook((nint _, int message, nint wParam, nint _, ref bool handled) =>+ {+ const int wmMouseHWheel = 0x020E;+ if (message != wmMouseHWheel) return 0;+ Wheel((short)((wParam.ToInt64() >> 16) & 0xFFFF));+ handled = true;+ return 0;+ });+ }++ // ───────────────────────── Content ─────────────────────────++ private void Load(IReadOnlyList<InstalledApp> apps)+ {+ _known.Clear();+ foreach (var app in apps) _known.TryAdd(app.Id, app);+ _items = LaunchStore.Merge(LaunchStore.Load(), apps);+ // The most used apps open the first page, on a row of their own; the arrangement below stays as the user left it.+ var scores = AppUsage.Scores();+ _frequent = apps+ .Where(a => scores.ContainsKey(a.Id))+ .OrderByDescending(a => scores[a.Id])+ .ThenBy(a => a.Name, StringComparer.CurrentCultureIgnoreCase)+ .Take((int)_cols)+ .Select(a => new LaunchEntry { App = a.Id })+ .ToList();+ if (_frequent.Count < 3) _frequent = [];+ foreach (var tile in _tiles.Values) _strip.Children.Remove(tile.Element);+ _tiles.Clear();+ Refill();+ SnapStrip();+ }++ /// <summary>The slots the row of most used apps takes at the start of the first page (none while searching).</summary>+ private int Lead => Searching || _frequent.Count == 0 ? 0 : (int)_cols;++ private bool Searching => _box.Text.Trim().Length > 0;++ /// <summary>Works out what the pages show (everything, or what matches the search) and lays it out.</summary>+ private void Refill()+ {+ Select(null);+ var query = _box.Text.Trim();+ if (query.Length == 0)+ {+ _shown = _items;+ }+ else+ {+ // Apps inside folders are found too, in the order they sit on the pages.+ _shown = _items+ .SelectMany(e => e.IsFolder ? e.Apps! : [e.App!])+ .Where(id => _known.TryGetValue(id, out var app) && Matches(app.Name, query))+ .Select(id => _searchEntries.TryGetValue(id, out var known) ? known : _searchEntries[id] = new LaunchEntry { App = id })+ .ToList();+ }+ _note.Text = _known.Count == 0 ? UiText.Get("AppGridLoading") : _shown.Count == 0 ? UiText.Get("AppGridNoMatch") : "";+ Arrange(false);+ }++ /// <summary>+ /// The icons in the order they stand on the pages: first the row of most used apps, then the+ /// arrangement. Null is an empty slot (the rest of that row, or where a dragged icon would land).+ /// </summary>+ private List<LaunchEntry?> Display()+ {+ var lead = Lead;+ var list = new List<LaunchEntry?>(lead + _shown.Count + 1);+ if (lead > 0)+ {+ list.AddRange(_frequent);+ while (list.Count < lead) list.Add(null);+ }+ if (_drag is null || _drag.Folder is not null)+ {+ list.AddRange(_shown);+ return list;+ }+ var rest = new List<LaunchEntry?>(_others);+ rest.Insert(Math.Clamp(_dropIndex, 0, rest.Count), null);+ list.AddRange(rest);+ return list;+ }++ private int PerPage => (int)(_cols * _rows);++ private Point Slot(int index)+ {+ var page = index / PerPage;+ var at = index % PerPage;+ return new Point(page * Width + _gridLeft + at % (int)_cols * _cellW, _gridTop + at / (int)_cols * _cellH);+ }++ /// <summary>+ /// Puts the icons of the shown page and the pages beside it in their places (the other pages+ /// have no tiles until they come near). Tiles are kept between calls, so with+ /// <paramref name="animate"/> the ones whose place changed glide there.+ /// </summary>+ private void Arrange(bool animate)+ {+ var list = Display();+ _pageCount = Math.Max(1, (list.Count + PerPage - 1) / PerPage);+ _strip.Width = _pageCount * Width;+ if (_page >= _pageCount)+ {+ _page = _pageCount - 1;+ SnapStrip();+ }+ _livePages = (_neighborsReady ? Math.Max(0, _page - 1) : _page, _neighborsReady ? Math.Min(_pageCount - 1, _page + 1) : _page);+ var first = _livePages.From * PerPage;+ var last = Math.Min(list.Count, (_livePages.To + 1) * PerPage);+ var wanted = new HashSet<LaunchEntry>();+ for (var i = first; i < last; i++)+ if (list[i] is { } entry) wanted.Add(entry);+ foreach (var gone in _tiles.Keys.Where(k => !wanted.Contains(k)).ToList())+ {+ _strip.Children.Remove(_tiles[gone].Element);+ _tiles.Remove(gone);+ }+ var pending = new List<(Image, string)>();+ for (var i = first; i < last; i++)+ {+ if (list[i] is not { } entry) continue;+ var to = Slot(i);+ if (!_tiles.TryGetValue(entry, out var tile))+ {+ tile = MakeTile(entry, pending);+ if (ReferenceEquals(entry, _selected)) Highlight(tile, true);+ _tiles[entry] = tile;+ _strip.Children.Add(tile.Element);+ Canvas.SetLeft(tile.Element, to.X);+ Canvas.SetTop(tile.Element, to.Y);+ continue;+ }+ var from = new Point(Canvas.GetLeft(tile.Element), Canvas.GetTop(tile.Element));+ if (from == to) continue;+ Canvas.SetLeft(tile.Element, to.X);+ Canvas.SetTop(tile.Element, to.Y);+ if (!animate) continue;+ var shift = Motion.Shift(tile.Element);+ shift.BeginAnimation(TranslateTransform.XProperty, new DoubleAnimation(from.X - to.X + shift.X, 0, TimeSpan.FromMilliseconds(240)) { EasingFunction = Motion.Out });+ shift.BeginAnimation(TranslateTransform.YProperty, new DoubleAnimation(from.Y - to.Y + shift.Y, 0, TimeSpan.FromMilliseconds(240)) { EasingFunction = Motion.Out });+ }+ RequestIcons(pending);+ PlaceShelf();+ BuildDots();+ }++ /// <summary>A soft band behind the row of most used apps, with its name above it.</summary>+ private void PlaceShelf()+ {+ var show = Lead > 0;+ if (show && _shelf.Parent is null)+ {+ _strip.Children.Insert(0, _shelf);+ _strip.Children.Insert(0, _shelfName);+ }+ _shelf.Visibility = _shelfName.Visibility = show ? Visibility.Visible : Visibility.Collapsed;+ if (!show) return;+ _shelf.Width = _cols * _cellW + 16;+ _shelf.Height = _cellH - 4;+ Canvas.SetLeft(_shelf, _gridLeft - 8);+ Canvas.SetTop(_shelf, _gridTop + 2);+ Canvas.SetLeft(_shelfName, _gridLeft + 6);+ Canvas.SetTop(_shelfName, _gridTop - 22);+ }++ private void GoTo(int page, bool animate = true)+ {+ _page = Math.Clamp(page, 0, _pageCount - 1);+ _neighborsReady = true;+ PaintDots();+ if (!animate)+ {+ SnapStrip();+ Arrange(false);+ return;+ }+ // The page arrives with its tiles already made (it was beside the old one); the pages+ // beside it are made after the slide, so making them never holds the movement up.+ if (_page < _livePages.From || _page > _livePages.To) Arrange(false);+ var slide = new DoubleAnimation(-_page * Width, TimeSpan.FromMilliseconds(360)) { EasingFunction = Motion.Out };+ slide.Completed += (_, _) =>+ {+ if (!_closed && _drag is null && _press is null) Arrange(false);+ };+ _stripShift.BeginAnimation(TranslateTransform.XProperty, slide);+ }++ /// <summary>Shows the current page at once, without sliding.</summary>+ private void SnapStrip()+ {+ _stripShift.BeginAnimation(TranslateTransform.XProperty, null);+ _stripShift.X = -_page * Width;+ PaintDots();+ }++ private void BuildDots()+ {+ if (_dots.Children.Count == _pageCount)+ {+ PaintDots();+ return;+ }+ _dots.Children.Clear();+ for (var i = 0; i < _pageCount; i++)+ {+ var page = i;+ var dot = new Ellipse { Width = 8, Height = 8 };+ // A wider transparent target than the dot itself, so it is easy to hit.+ var hit = new Border { Child = dot, Padding = new Thickness(6), Background = Brushes.Transparent, Cursor = Cursors.Hand };+ hit.MouseLeftButtonUp += (_, e) =>+ {+ e.Handled = true;+ GoTo(page);+ };+ _dots.Children.Add(hit);+ }+ _dots.Visibility = _pageCount > 1 ? Visibility.Visible : Visibility.Hidden;+ PaintDots();+ }++ private void PaintDots()+ {+ for (var i = 0; i < _dots.Children.Count; i++)+ {+ if (_dots.Children[i] is Border { Child: Ellipse dot }) dot.Fill = i == _page ? DotOn : DotOff;+ }+ }++ // ───────────────────────── Tiles ─────────────────────────++ private string NameOf(LaunchEntry entry) =>+ entry.IsFolder ? (string.IsNullOrWhiteSpace(entry.Folder) ? UiText.Get("AppGridFolder") : entry.Folder!)+ : _known.TryGetValue(entry.App!, out var app) ? app.Name : "";++ private TileParts MakeTile(LaunchEntry entry, List<(Image, string)> pending)+ {+ FrameworkElement icon;+ if (entry.IsFolder)+ {+ // A frosted rounded square showing the first nine apps.+ var minis = new UniformGrid { Rows = 3, Columns = 3, Margin = new Thickness(_icon * 0.1) };+ foreach (var id in entry.Apps!.Take(9))+ {+ var mini = new Image { Width = _icon * 0.22, Height = _icon * 0.22, Stretch = Stretch.Uniform };+ RenderOptions.SetBitmapScalingMode(mini, BitmapScalingMode.HighQuality);+ pending.Add((mini, id));+ minis.Children.Add(mini);+ }+ icon = new Border { Width = _icon, Height = _icon, CornerRadius = new CornerRadius(_icon * 0.24), Background = FolderFill, BorderBrush = FolderEdge, BorderThickness = new Thickness(1), Child = minis };+ }+ else+ {+ var image = new Image { Width = _icon, Height = _icon, Stretch = Stretch.Uniform };+ RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality);+ pending.Add((image, entry.App!));+ icon = image;+ }+ return Assemble(icon, NameOf(entry), entry);+ }++ private TileParts MakeAppTile(string id, List<(Image, string)> pending)+ {+ var image = new Image { Width = _icon, Height = _icon, Stretch = Stretch.Uniform };+ RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality);+ pending.Add((image, id));+ return Assemble(image, _known.TryGetValue(id, out var app) ? app.Name : "", id);+ }++ /// <summary>The icon over its name, in a cell of the grid. No per-icon shadows: a hundred of them made the screen stutter.</summary>+ private TileParts Assemble(FrameworkElement icon, string name, object tag)+ {+ var backdrop = new Border { CornerRadius = new CornerRadius(_icon * 0.3), Background = Brushes.Transparent, RenderTransformOrigin = new Point(0.5, 0.5), RenderTransform = new ScaleTransform(0.8, 0.8) };+ var iconHost = new Grid { Width = _icon * 1.24, Height = _icon * 1.24, HorizontalAlignment = HorizontalAlignment.Center };+ iconHost.Children.Add(backdrop);+ icon.HorizontalAlignment = HorizontalAlignment.Center;+ icon.VerticalAlignment = VerticalAlignment.Center;+ iconHost.Children.Add(icon);+ var label = new TextBlock+ {+ Text = name,+ Foreground = Ui.White,+ FontSize = 12,+ TextAlignment = TextAlignment.Center,+ TextTrimming = TextTrimming.CharacterEllipsis,+ MaxWidth = _cellW - 14,+ HorizontalAlignment = HorizontalAlignment.Center,+ Margin = new Thickness(0, 2, 0, 0)+ };+ // Only the icon and its name take clicks; the gaps between icons are the page, so a click there closes the screen.+ var column = new StackPanel { VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center, Background = Brushes.Transparent, Cursor = Cursors.Hand };+ column.Children.Add(iconHost);+ column.Children.Add(label);+ var cell = new Grid { Width = _cellW, Height = _cellH, Tag = tag };+ cell.Children.Add(column);+ return new TileParts { Element = cell, IconHost = iconHost, Backdrop = backdrop };+ }++ /// <summary>Icons load on one background thread and drop into their tiles in small batches.</summary>+ private void RequestIcons(List<(Image Image, string Id)> pending)+ {+ foreach (var (image, id) in pending)+ {+ if (Icons.TryGetValue(id, out var known)) image.Source = known;+ else _iconQueue.Enqueue((image, id));+ }+ if (_iconLoaderRunning || _iconQueue.Count == 0) return;+ _iconLoaderRunning = true;+ var work = _iconQueue.ToList();+ _iconQueue.Clear();+ var thread = new Thread(() =>+ {+ var batch = new List<(Image Image, ImageSource? Source)>();+ void Flush()+ {+ if (batch.Count == 0) return;+ var ready = batch.ToArray();+ batch.Clear();+ Dispatcher.BeginInvoke(() =>+ {+ foreach (var (image, source) in ready) image.Source = source;+ }, DispatcherPriority.Background);+ }+ foreach (var (image, id) in work)+ {+ if (_closed) return;+ batch.Add((image, Icons.GetOrAdd(id, key => NotificationApps.LoadIcon(key, 128))));+ if (batch.Count >= 16) Flush();+ }+ Flush();+ Dispatcher.BeginInvoke(() =>+ {+ // Tiles made while this thread ran wait in the queue; start again for them.+ _iconLoaderRunning = false;+ if (_iconQueue.Count > 0) RequestIcons([]);+ });+ }) { IsBackground = true, Name = "AppGrid icons" };+ thread.SetApartmentState(ApartmentState.STA);+ thread.Start();+ }++ // ───────────────────────── Pointer ─────────────────────────++ private static T? Ancestor<T>(DependencyObject? from, Func<T, bool> match) where T : DependencyObject+ {+ while (from is not null)+ {+ if (from is T found && match(found)) return found;+ from = from is Visual or System.Windows.Media.Media3D.Visual3D ? VisualTreeHelper.GetParent(from) : LogicalTreeHelper.GetParent(from);+ }+ return null;+ }++ private void OnPressDown(object sender, MouseButtonEventArgs e)+ {+ if (_drag is not null) return;+ var source = e.OriginalSource as DependencyObject;+ if (Ancestor<TextBox>(source, _ => true) is not null) return;+ Select(null);+ var cell = Ancestor<FrameworkElement>(source, f => f.Tag is LaunchEntry or string && f is Grid);+ var point = e.GetPosition(Root);+ if (_openFolder is not null)+ {+ // In a folder only its own apps can be picked up; the dim around it closes it on its own.+ if (cell?.Tag is not string id || !_folderTiles.TryGetValue(id, out var parts)) return;+ _press = new Press { Start = point, FolderApp = id, Icon = parts.IconHost };+ }+ else if (cell?.Tag is LaunchEntry entry && _tiles.TryGetValue(entry, out var parts))+ {+ _press = new Press { Start = point, Entry = entry, Icon = parts.IconHost, Fixed = _frequent.Contains(entry) };+ }+ else if (ReferenceEquals(source, _strip) || ReferenceEquals(source, _host))+ {+ _press = new Press { Start = point };+ }+ else+ {+ return;+ }+ if (_press.Icon is not null) _press.Icon.Opacity = 0.65;+ Root.CaptureMouse();+ }++ private void OnPressMove(object sender, MouseEventArgs e)+ {+ if (_press is null || e.LeftButton != MouseButtonState.Pressed) return;+ var point = e.GetPosition(Root);+ _lastPoint = point;+ if (_drag is not null)+ {+ DragTo(point);+ return;+ }+ var moved = point - _press.Start;+ if (_press.Swiping)+ {+ _stripShift.X = _press.SwipeFrom + moved.X;+ return;+ }+ if (moved.Length < DragThreshold) return;+ if (_press.Entry is not null || _press.FolderApp is not null)+ {+ // While searching the results are a view, not the arrangement, so icons stay put.+ if (Searching || _press.Fixed) return;+ StartDrag(point);+ }+ else if (Math.Abs(moved.X) > Math.Abs(moved.Y))+ {+ _press.Swiping = true;+ var current = _stripShift.X;+ _stripShift.BeginAnimation(TranslateTransform.XProperty, null);+ _stripShift.X = current;+ _press.SwipeFrom = current - moved.X;+ }+ }++ private void OnPressUp(object sender, MouseButtonEventArgs e)+ {+ var press = _press;+ if (press is null) return;+ _press = null;+ if (Root.IsMouseCaptured) Root.ReleaseMouseCapture();+ if (press.Icon is not null) press.Icon.Opacity = 1;+ if (_drag is not null)+ {+ e.Handled = true;+ LetGo();+ return;+ }+ if (press.Swiping)+ {+ e.Handled = true;+ var moved = e.GetPosition(Root).X - press.Start.X;+ GoTo(Math.Abs(moved) > Width * 0.12 ? _page - Math.Sign(moved) : _page);+ return;+ }+ if (press.Entry is not null)+ {+ e.Handled = true;+ Open(press.Entry);+ }+ else if (press.FolderApp is not null)+ {+ e.Handled = true;+ Launch(press.FolderApp);+ }+ else if ((e.GetPosition(Root) - press.Start).Length >= DragThreshold)+ {+ // An up-and-down drag on the empty page is not a click.+ e.Handled = true;+ }+ // A plain click on the empty page goes on to the overlay, which closes.+ }++ private void CancelPress()+ {+ if (_press?.Icon is not null) _press.Icon.Opacity = 1;+ var swiping = _press?.Swiping == true;+ _press = null;+ if (_drag is not null) LetGo();+ else if (swiping) GoTo(_page);+ }++ private void Wheel(double towardsNext)+ {+ if (_openFolder is not null || _drag is not null) return;+ var now = DateTime.UtcNow;+ // A touchpad sends a stream of small steps that keeps going after the fingers lift:+ // one page per gesture, then wait for the stream to stop.+ if (now < _wheelLock)+ {+ if (now - _wheelLast < TimeSpan.FromMilliseconds(120)) _wheelLock = Min(now.AddMilliseconds(120), _wheelLock.AddMilliseconds(60));+ _wheelLast = now;+ return;+ }+ if (now - _wheelLast > TimeSpan.FromMilliseconds(400)) _wheel = 0;+ _wheelLast = now;+ _wheel += towardsNext;+ if (Math.Abs(_wheel) < 100) return;+ var step = Math.Sign(_wheel);+ _wheel = 0;+ _wheelLock = now.AddMilliseconds(380);+ if (_page + step >= 0 && _page + step < _pageCount) GoTo(_page + step);+ }++ private static DateTime Min(DateTime a, DateTime b) => a < b ? a : b;++ /// <summary>+ /// The arrow keys move a highlight over the icons (left and right only while the search field is+ /// empty, so they still move the cursor in typed text) and Enter opens it; Page Up / Down turn pages.+ /// </summary>+ private void OnKey(object sender, KeyEventArgs e)+ {+ if (_openFolder is not null || _drag is not null) return;+ var typing = _box.Text.Length > 0;+ var move = e.Key switch+ {+ Key.Left when !typing => -1,+ Key.Right when !typing => 1,+ Key.Up => -(int)_cols,+ Key.Down => (int)_cols,+ _ => 0+ };+ if (move != 0)+ {+ e.Handled = true;+ MoveSelection(move);+ return;+ }+ var step = e.Key switch+ {+ Key.PageDown => 1,+ Key.PageUp => -1,+ _ => 0+ };+ if (step == 0) return;+ e.Handled = true;+ GoTo(_page + step);+ }++ private void MoveSelection(int move)+ {+ var list = Display();+ if (list.Count == 0) return;+ var at = _selected is null ? -1 : list.IndexOf(_selected);+ // The first press picks the first icon of the page in view.+ var index = at < 0 ? Math.Min(_page * PerPage, list.Count - 1) : Math.Clamp(at + move, 0, list.Count - 1);+ // Empty slots (the end of the row of most used apps) are stepped over.+ var direction = move < 0 ? -1 : 1;+ var found = index;+ while (found >= 0 && found < list.Count && list[found] is null) found += direction;+ if (found < 0 || found >= list.Count)+ {+ found = index;+ while (found >= 0 && found < list.Count && list[found] is null) found -= direction;+ }+ if (found < 0 || found >= list.Count || list[found] is not { } entry) return;+ Select(entry, found / PerPage);+ }++ /// <summary>Highlights the icon the keyboard is on (turning to its page), or none.</summary>+ private void Select(LaunchEntry? entry, int page = -1)+ {+ if (_selected is not null && !ReferenceEquals(_selected, entry) && !ReferenceEquals(_selected, _folderTarget)+ && _tiles.TryGetValue(_selected, out var old))+ Highlight(old, false);+ _selected = entry;+ if (entry is null) return;+ if (page >= 0 && page != _page) GoTo(page);+ if (_tiles.TryGetValue(entry, out var parts)) Highlight(parts, true);+ }++ // ───────────────────────── Menu ─────────────────────────++ /// <summary>Set by the dock: pins a program file to it.</summary>+ public static Action<string, string>? PinToDock { get; set; }++ /// <summary>Set by the dock: whether a program file is already pinned.</summary>+ public static Func<string, bool>? IsPinned { get; set; }++ /// <summary>A right click on an icon: open it, as administrator, its file location, pin it; on a folder: open or ungroup it.</summary>+ private void OnMenu(object sender, MouseButtonEventArgs e)+ {+ if (_drag is not null) return;+ var source = e.OriginalSource as DependencyObject;+ if (Ancestor<TextBox>(source, _ => true) is not null) return;+ var cell = Ancestor<FrameworkElement>(source, f => f.Tag is LaunchEntry or string && f is Grid);+ if (cell is null) return;+ var menu = new ContextMenu { PlacementTarget = cell, Placement = PlacementMode.MousePoint };+ void Add(string text, Action action, bool enabled = true)+ {+ var item = new MenuItem { Header = UiText.Get(text), IsEnabled = enabled };+ item.Click += (_, _) => action();+ menu.Items.Add(item);+ }++ if (cell.Tag is LaunchEntry { IsFolder: true } folder)+ {+ Add("AppGridOpenFolder", () => OpenFolder(folder));+ if (!Searching && _items.Contains(folder)) Add("AppGridUngroup", () => Ungroup(folder));+ }+ else if (((cell.Tag as LaunchEntry)?.App ?? (cell.Tag as string)) is { } id && _known.TryGetValue(id, out var app))+ {+ Add("AppGridOpen", () => Launch(id));+ if (app.Target is { } target)+ {+ Add("AppGridRunAsAdmin", () =>+ {+ Dismiss();+ app.LaunchAsAdministrator();+ AppUsage.Record(id);+ });+ Add("AppGridShowLocation", () =>+ {+ Dismiss();+ app.ShowFileLocation();+ });+ if (PinToDock is { } pin)+ {+ var pinned = IsPinned?.Invoke(target) == true;+ Add(pinned ? "AppGridPinned" : "AppGridPin", () => pin(target, app.Name), !pinned);+ }+ }+ }+ else+ {+ return;+ }+ e.Handled = true;+ menu.IsOpen = true;+ }++ /// <summary>A folder's apps go back onto the pages where the folder was.</summary>+ private void Ungroup(LaunchEntry folder)+ {+ var index = _items.IndexOf(folder);+ if (index < 0) return;+ if (ReferenceEquals(_openFolder, folder)) CloseFolder(quick: true);+ _items.RemoveAt(index);+ _items.InsertRange(index, folder.Apps!.Select(id => new LaunchEntry { App = id }));+ Forget(folder);+ Refill();+ Save();+ }++ private void Open(LaunchEntry entry)+ {+ if (entry.IsFolder) OpenFolder(entry);+ else Launch(entry.App!);+ }++ private void Launch(string id)+ {+ if (!_known.TryGetValue(id, out var app)) return;+ // After the press has fully ended (a finger on a touch screen too), so the window under it is+ // never pulled away mid-touch.+ Dispatcher.BeginInvoke(() =>+ {+ Dismiss();+ app.Launch();+ AppUsage.Record(id);+ }, DispatcherPriority.Input);+ }++ // ───────────────────────── Dragging ─────────────────────────++ private void StartDrag(Point point)+ {+ var press = _press!;+ if (press.Icon is not null) press.Icon.Opacity = 1;+ if (press.FolderApp is { } id)+ {+ var parts = _folderTiles[id];+ var origin = parts.Element.TranslatePoint(new Point(), Root);+ _folderOthers = _openFolder!.Apps!.Where(a => !string.Equals(a, id, StringComparison.OrdinalIgnoreCase)).ToList();+ _folderDropIndex = _openFolder.Apps!.FindIndex(a => string.Equals(a, id, StringComparison.OrdinalIgnoreCase));+ _drag = new Drag { Entry = new LaunchEntry { App = id }, Ghost = Ghost(new LaunchEntry { App = id }), Grab = point - origin, Folder = _openFolder };+ ArrangeFolder(false);+ }+ else+ {+ var entry = press.Entry!;+ var origin = _tiles[entry].Element.TranslatePoint(new Point(), Root);+ _others = _items.Where(x => !ReferenceEquals(x, entry)).ToList();+ _dropIndex = _items.IndexOf(entry);+ _drag = new Drag { Entry = entry, Ghost = Ghost(entry), Grab = point - origin };+ Arrange(false);+ }+ DragTo(point);+ }++ /// <summary>A copy of the tile that follows the pointer, a little larger, over everything else.</summary>+ private FrameworkElement Ghost(LaunchEntry entry)+ {+ var pending = new List<(Image, string)>();+ var parts = entry.IsFolder ? MakeTile(entry, pending) : MakeAppTile(entry.App!, pending);+ RequestIcons(pending);+ var ghost = parts.Element;+ ghost.Opacity = 0.95;+ ghost.RenderTransformOrigin = new Point(0.5, 0.45);+ var scale = new ScaleTransform(1, 1);+ ghost.RenderTransform = scale;+ scale.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(1.12, TimeSpan.FromMilliseconds(140)) { EasingFunction = Motion.Out });+ scale.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(1.12, TimeSpan.FromMilliseconds(140)) { EasingFunction = Motion.Out });+ _dragLayer.Children.Add(ghost);+ return ghost;+ }++ private void DragTo(Point point)+ {+ var drag = _drag!;+ Canvas.SetLeft(drag.Ghost, point.X - drag.Grab.X);+ Canvas.SetTop(drag.Ghost, point.Y - drag.Grab.Y);++ if (drag.Folder is not null)+ {+ if (InsideFolderPanel(point))+ {+ var slot = FolderSlotAt(point);+ if (slot != _folderDropIndex)+ {+ _folderDropIndex = slot;+ ArrangeFolder(true);+ }+ return;+ }+ LeaveFolder();+ }++ // Holding the icon at the left or right edge turns the page.+ var edge = point.X < 36 ? -1 : point.X > Width - 36 ? 1 : 0;+ if (edge != _edgeDirection)+ {+ _edgeDirection = edge;+ _edgeTimer.Stop();+ if (edge != 0) _edgeTimer.Start();+ }++ var gx = point.X - _gridLeft;+ var gy = point.Y - _gridTop;+ var col = Math.Clamp((int)Math.Floor(gx / _cellW), 0, (int)_cols - 1);+ var row = Math.Clamp((int)Math.Floor(gy / _cellH), 0, (int)_rows - 1);+ // The row of most used apps is not a place to drop on.+ var slotIndex = Math.Max(Lead, _page * PerPage + row * (int)_cols + col);+ var display = Display();+ LaunchEntry? target = null;+ if (gx >= 0 && gx < _cols * _cellW && gy >= 0 && gy < _rows * _cellH && slotIndex < display.Count && display[slotIndex] is { } under && !drag.Entry.IsFolder)+ {+ // Over the middle of another icon: a folder would be made there.+ var iconTop = (_cellH - (_icon * 1.24 + 20)) / 2;+ var cx = (col + 0.5) * _cellW;+ var cy = row * _cellH + iconTop + _icon * 0.62;+ if (Math.Abs(gx - cx) < _icon * 0.42 && Math.Abs(gy - cy) < _icon * 0.42) target = under;+ }+ SetFolderTarget(target);+ if (target is not null) return;+ var index = Math.Min(slotIndex - Lead, _others.Count);+ if (index == _dropIndex) return;+ _dropIndex = index;+ Arrange(true);+ }++ private void SetFolderTarget(LaunchEntry? target)+ {+ if (ReferenceEquals(target, _folderTarget)) return;+ if (_folderTarget is not null && _tiles.TryGetValue(_folderTarget, out var old)) Highlight(old, false);+ _folderTarget = target;+ if (target is not null && _tiles.TryGetValue(target, out var parts)) Highlight(parts, true);+ }++ private static void Highlight(TileParts parts, bool on)+ {+ parts.Backdrop.Background = on ? TargetFill : Brushes.Transparent;+ var scale = (ScaleTransform)parts.Backdrop.RenderTransform;+ var to = on ? 1.0 : 0.8;+ scale.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(to, TimeSpan.FromMilliseconds(160)) { EasingFunction = Motion.Out });+ scale.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(to, TimeSpan.FromMilliseconds(160)) { EasingFunction = Motion.Out });+ }++ private void FlipWhileDragging()+ {+ if (_drag is null || _edgeDirection == 0)+ {+ _edgeTimer.Stop();+ return;+ }+ var next = _page + _edgeDirection;+ if (next < 0 || next >= _pageCount) return;+ GoTo(next);+ DragTo(_lastPoint);+ }++ private void LetGo()+ {+ var drag = _drag!;+ _drag = null;+ _edgeTimer.Stop();+ _edgeDirection = 0;++ if (drag.Folder is not null)+ {+ // Let go inside the folder: the app takes its new place there.+ drag.Folder.Apps = [.. _folderOthers];+ drag.Folder.Apps.Insert(Math.Clamp(_folderDropIndex, 0, drag.Folder.Apps.Count), drag.Entry.App!);+ ArrangeFolder(true);+ Land(drag.Ghost, _folderTiles.TryGetValue(drag.Entry.App!, out var inFolder) ? inFolder.Element : null);+ Forget(drag.Folder);+ Arrange(false);+ Save();+ return;+ }++ if (_folderTarget is { } target)+ {+ SetFolderTarget(null);+ if (target.IsFolder)+ {+ target.Apps!.Add(drag.Entry.App!);+ }+ else+ {+ // App on app: the two become a folder where the one underneath was.+ var folder = new LaunchEntry { Folder = UiText.Get("AppGridFolder"), Apps = [target.App!, drag.Entry.App!] };+ _others[_others.IndexOf(target)] = folder;+ target = folder;+ }+ _items = _others;+ Forget(target);+ Arrange(true);+ Land(drag.Ghost, _tiles.TryGetValue(target, out var into) ? into.Element : null, shrink: true);+ Save();+ return;+ }++ _items = [.. _others];+ _items.Insert(Math.Clamp(_dropIndex, 0, _items.Count), drag.Entry);+ Refill();+ Land(drag.Ghost, _tiles.TryGetValue(drag.Entry, out var placed) ? placed.Element : null);+ Save();+ }++ /// <summary>The ghost glides into the tile's place (or shrinks into a folder) and the real tile shows again.</summary>+ private void Land(FrameworkElement ghost, FrameworkElement? tile, bool shrink = false)+ {+ if (tile is null)+ {+ _dragLayer.Children.Remove(ghost);+ return;+ }+ if (!shrink) tile.Opacity = 0;+ // The new tile is not laid out yet, so its place comes from its canvas position:+ // on the pages, where the page will stop sliding; in a folder, inside the folder's grid.+ var at = new Point(Canvas.GetLeft(tile), Canvas.GetTop(tile));+ var target = ReferenceEquals(tile.Parent, _strip)+ ? new Point(at.X - _page * Width, at.Y)+ : tile.Parent is Canvas grid ? grid.TranslatePoint(at, Root) : at;+ var time = TimeSpan.FromMilliseconds(220);+ var left = new DoubleAnimation(target.X, time) { EasingFunction = Motion.Out };+ left.Completed += (_, _) =>+ {+ _dragLayer.Children.Remove(ghost);+ tile.Opacity = 1;+ };+ ghost.BeginAnimation(Canvas.LeftProperty, left);+ ghost.BeginAnimation(Canvas.TopProperty, new DoubleAnimation(target.Y, time) { EasingFunction = Motion.Out });+ var scale = (ScaleTransform)ghost.RenderTransform;+ var size = shrink ? 0.3 : 1;+ scale.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(size, time) { EasingFunction = Motion.Out });+ scale.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(size, time) { EasingFunction = Motion.Out });+ if (shrink) ghost.BeginAnimation(OpacityProperty, new DoubleAnimation(0, time));+ }++ /// <summary>Drops a tile so it is drawn again (a folder whose apps changed).</summary>+ private void Forget(LaunchEntry entry)+ {+ if (!_tiles.TryGetValue(entry, out var tile)) return;+ _strip.Children.Remove(tile.Element);+ _tiles.Remove(entry);+ }++ private void Save()+ {+ // The search results are a view; only the real arrangement is written.+ LaunchStore.Save(_items.Select(e => e.IsFolder ? new LaunchEntry { Folder = e.Folder, Apps = [.. e.Apps!] } : new LaunchEntry { App = e.App }).ToList());+ }++ // ───────────────────────── Folders ─────────────────────────++ private void OpenFolder(LaunchEntry folder)+ {+ _openFolder = folder;+ _folderLayer.Children.Clear();+ _folderTiles.Clear();++ var dim = new Border { Background = Ui.Solid("#59000000") };+ dim.MouseLeftButtonUp += (_, e) =>+ {+ e.Handled = true;+ CloseFolder();+ };+ _folderLayer.Children.Add(dim);++ var name = new TextBox+ {+ Text = NameOf(folder),+ FontSize = 26,+ FontWeight = FontWeights.SemiBold,+ Foreground = Ui.White,+ CaretBrush = Ui.White,+ Background = Brushes.Transparent,+ BorderThickness = new Thickness(0),+ TextAlignment = TextAlignment.Center,+ HorizontalAlignment = HorizontalAlignment.Stretch,+ Margin = new Thickness(0, 0, 0, 18),+ MaxLength = 40+ };+ void Rename()+ {+ var text = name.Text.Trim();+ if (text.Length == 0 || text == NameOf(folder)) return;+ folder.Folder = text;+ Forget(folder);+ Arrange(false);+ Save();+ }+ name.LostKeyboardFocus += (_, _) => Rename();+ name.PreviewKeyDown += (_, e) =>+ {+ if (e.Key != Key.Enter) return;+ e.Handled = true;+ Rename();+ _box.Focus();+ };++ _folderCols = Math.Clamp(folder.Apps!.Count, 3, Math.Min(6, (int)_cols));+ _folderCanvas = new Canvas { Width = _folderCols * _cellW, Background = Brushes.Transparent };+ var scroll = new ScrollViewer { Content = _folderCanvas, VerticalScrollBarVisibility = ScrollBarVisibility.Hidden, MaxHeight = _cellH * 3.5, Focusable = false };+ var column = new StackPanel();+ column.Children.Add(name);+ column.Children.Add(scroll);+ _folderPanel = new Border+ {+ Child = column,+ Background = Ui.Solid("#C2303236"),+ BorderBrush = FolderEdge,+ BorderThickness = new Thickness(1),+ CornerRadius = new CornerRadius(30),+ Padding = new Thickness(24, 22, 24, 18),+ HorizontalAlignment = HorizontalAlignment.Center,+ VerticalAlignment = VerticalAlignment.Center,+ RenderTransformOrigin = new Point(0.5, 0.5),+ RenderTransform = new ScaleTransform(0.86, 0.86),+ Opacity = 0+ };+ _folderPanel.MouseLeftButtonUp += (_, e) => e.Handled = true;+ _folderLayer.Children.Add(_folderPanel);+ ArrangeFolder(false);+ _folderLayer.Visibility = Visibility.Visible;+ // Typing would otherwise go on filtering the pages behind the folder.+ _folderPanel.Focusable = true;+ _folderPanel.FocusVisualStyle = null;+ Dispatcher.BeginInvoke(() => _folderPanel?.Focus(), DispatcherPriority.Loaded);++ var time = TimeSpan.FromMilliseconds(240);+ var scale = (ScaleTransform)_folderPanel.RenderTransform;+ scale.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(1, time) { EasingFunction = Motion.Out });+ scale.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(1, time) { EasingFunction = Motion.Out });+ _folderPanel.BeginAnimation(OpacityProperty, new DoubleAnimation(1, time) { EasingFunction = Motion.Out });+ _host.BeginAnimation(OpacityProperty, new DoubleAnimation(0.45, time));+ }++ private void CloseFolder(bool quick = false)+ {+ if (_openFolder is null || _folderPanel is null) return;+ _openFolder = null;+ var panel = _folderPanel;+ _folderPanel = null;+ _folderCanvas = null;+ Keyboard.Focus(_box);+ var time = TimeSpan.FromMilliseconds(quick ? 120 : 180);+ var fade = new DoubleAnimation(0, time) { EasingFunction = Motion.In };+ fade.Completed += (_, _) =>+ {+ if (_openFolder is not null) return;+ _folderLayer.Visibility = Visibility.Collapsed;+ _folderLayer.Children.Clear();+ _folderTiles.Clear();+ };+ var scale = (ScaleTransform)panel.RenderTransform;+ scale.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(0.9, time) { EasingFunction = Motion.In });+ scale.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(0.9, time) { EasingFunction = Motion.In });+ panel.BeginAnimation(OpacityProperty, fade);+ _folderLayer.Children[0].BeginAnimation(OpacityProperty, new DoubleAnimation(0, time));+ _host.BeginAnimation(OpacityProperty, new DoubleAnimation(1, time));+ }++ /// <summary>Lays out the apps of the open folder; while one is dragged, a gap stands where it would land.</summary>+ private void ArrangeFolder(bool animate)+ {+ if (_openFolder is null || _folderCanvas is null) return;+ var dragging = _drag?.Folder is not null ? _drag.Entry.App : null;+ var list = new List<string?>();+ if (dragging is null) list.AddRange(_openFolder.Apps!);+ else+ {+ list.AddRange(_folderOthers);+ list.Insert(Math.Clamp(_folderDropIndex, 0, list.Count), null);+ }+ foreach (var gone in _folderTiles.Keys.Where(k => !list.Contains(k, StringComparer.OrdinalIgnoreCase)).ToList())+ {+ _folderCanvas.Children.Remove(_folderTiles[gone].Element);+ _folderTiles.Remove(gone);+ }+ var pending = new List<(Image, string)>();+ for (var i = 0; i < list.Count; i++)+ {+ if (list[i] is not { } id) continue;+ var to = new Point(i % _folderCols * _cellW, i / _folderCols * _cellH);+ if (!_folderTiles.TryGetValue(id, out var tile))+ {+ tile = MakeAppTile(id, pending);+ _folderTiles[id] = tile;+ _folderCanvas.Children.Add(tile.Element);+ Canvas.SetLeft(tile.Element, to.X);+ Canvas.SetTop(tile.Element, to.Y);+ continue;+ }+ var from = new Point(Canvas.GetLeft(tile.Element), Canvas.GetTop(tile.Element));+ if (from == to) continue;+ Canvas.SetLeft(tile.Element, to.X);+ Canvas.SetTop(tile.Element, to.Y);+ if (!animate) continue;+ var shift = Motion.Shift(tile.Element);+ shift.BeginAnimation(TranslateTransform.XProperty, new DoubleAnimation(from.X - to.X + shift.X, 0, TimeSpan.FromMilliseconds(220)) { EasingFunction = Motion.Out });+ shift.BeginAnimation(TranslateTransform.YProperty, new DoubleAnimation(from.Y - to.Y + shift.Y, 0, TimeSpan.FromMilliseconds(220)) { EasingFunction = Motion.Out });+ }+ RequestIcons(pending);+ _folderCanvas.Height = Math.Max(1, (list.Count + _folderCols - 1) / _folderCols) * _cellH;+ }++ private bool InsideFolderPanel(Point point)+ {+ if (_folderPanel is null) return false;+ var origin = _folderPanel.TranslatePoint(new Point(), Root);+ return new Rect(origin, new Size(_folderPanel.ActualWidth, _folderPanel.ActualHeight)).Contains(point);+ }++ private int FolderSlotAt(Point point)+ {+ var origin = _folderCanvas!.TranslatePoint(new Point(), Root);+ var col = Math.Clamp((int)Math.Floor((point.X - origin.X) / _cellW), 0, _folderCols - 1);+ var row = Math.Max(0, (int)Math.Floor((point.Y - origin.Y) / _cellH));+ return Math.Min(row * _folderCols + col, _folderOthers.Count);+ }++ /// <summary>+ /// The dragged app left the folder panel: it comes out of the folder, the folder closes and+ /// the drag carries on over the pages, starting just after the folder.+ /// </summary>+ private void LeaveFolder()+ {+ var drag = _drag!;+ var folder = drag.Folder!;+ drag.Folder = null;+ folder.Apps = [.. _folderOthers];+ var at = _items.IndexOf(folder);+ if (folder.Apps.Count == 1)+ {+ // A folder of one is just that app again.+ Forget(folder);+ _items[at] = new LaunchEntry { App = folder.Apps[0] };+ }+ else+ {+ Forget(folder);+ }+ CloseFolder(quick: true);+ _others = [.. _items];+ _dropIndex = at + 1;+ Arrange(false);+ Save();+ }+}diff --git a/Design/Widgets.xaml b/Design/Widgets.xamlindex 65d77d4..3ae3da6 100644--- a/Design/Widgets.xaml+++ b/Design/Widgets.xaml@@ -99,6 +99,37 @@</Setter></Style>+ <!-- Full-width row inside a card (the profile list and its actions): a soft tint on hover, like a menu item. -->+ <Style x:Key="WidgetRowButton" TargetType="Button">+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter Property="Padding" Value="10,0" />+ <Setter Property="Height" Value="34" />+ <Setter Property="HorizontalContentAlignment" Value="Stretch" />+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="Button">+ <Border x:Name="Surface" Background="{TemplateBinding Background}" CornerRadius="9" Padding="{TemplateBinding Padding}">+ <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Stretch" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Surface" Property="Background" Value="{DynamicResource SurfaceHover}" />+ </Trigger>+ <Trigger Property="IsPressed" Value="True">+ <Setter TargetName="Surface" Property="Background" Value="{DynamicResource SurfacePressed}" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter TargetName="Surface" Property="Opacity" Value="0.4" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+<!-- Rounded pill button (Refresh, New event…). --><Style x:Key="WidgetPillButton" TargetType="Button"><Setter Property="Background" Value="{DynamicResource WidgetTileFill}" />diff --git a/DesktopWidgets/DeskHubs.cs b/DesktopWidgets/DeskHubs.csindex b8e036a..c1518fa 100644--- a/DesktopWidgets/DeskHubs.cs+++ b/DesktopWidgets/DeskHubs.cs@@ -304,6 +304,7 @@ internal sealed class MediaHub : HubBaseprivate bool _active;private int _version;private string? _artKey;+ private string? _artSignature;public string Title { get; private set; } = "";public string Artist { get; private set; } = "";@@ -410,11 +411,21 @@ internal sealed class MediaHub : HubBaseDuration = timeline.EndTime - timeline.StartTime;PositionAt = timeline.LastUpdatedTime.UtcDateTime == default ? DateTime.UtcNow : timeline.LastUpdatedTime.UtcDateTime;if (PositionAt > DateTime.UtcNow) PositionAt = DateTime.UtcNow;+ // Browsers send their logo first and the real cover a moment later for the same song:+ // read the cover on every change, and once more shortly after a new song.var key = $"{Title}|{Artist}|{properties?.AlbumTitle}";- if (key != _artKey)+ var newSong = key != _artKey;+ _artKey = key;+ await LoadArtAsync(properties?.Thumbnail, version, newSong);+ if (newSong && version == _version){- _artKey = key;- await LoadArtAsync(properties?.Thumbnail, version);+ var again = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(2) };+ again.Tick += (_, _) =>+ {+ again.Stop();+ if (_active) _ = RefreshAsync();+ };+ again.Start();}}catch (Exception ex) when (ex is COMException or InvalidOperationException or UnauthorizedAccessException)@@ -438,11 +449,13 @@ internal sealed class MediaHub : HubBasereturn name.Length > 0 ? char.ToUpper(name[0], CultureInfo.CurrentCulture) + name[1..] : name;}- private async Task LoadArtAsync(Windows.Storage.Streams.IRandomAccessStreamReference? reference, int version)+ private async Task LoadArtAsync(Windows.Storage.Streams.IRandomAccessStreamReference? reference, int version, bool newSong){if (reference is null){+ if (!newSong) return;Art = null;+ _artSignature = null;return;}try@@ -453,6 +466,9 @@ internal sealed class MediaHub : HubBaseawait source.CopyToAsync(memory);memory.Position = 0;if (version != _version) return;+ var signature = Convert.ToHexString(System.Security.Cryptography.SHA1.HashData(memory.GetBuffer().AsSpan(0, (int)memory.Length)));+ if (signature == _artSignature && Art is not null) return;+ _artSignature = signature;var image = new BitmapImage();image.BeginInit();image.CacheOption = BitmapCacheOption.OnLoad;diff --git a/DesktopWidgets/Kinds/AiWidgets.cs b/DesktopWidgets/Kinds/AiWidgets.csindex 9b0a9bc..19dc4c8 100644--- a/DesktopWidgets/Kinds/AiWidgets.cs+++ b/DesktopWidgets/Kinds/AiWidgets.cs@@ -61,7 +61,11 @@ internal sealed class AiUsageHubpublic IReadOnlyList<ProviderUsage> Usage { get; private set; } = [];public bool Loaded { get; private set; }- private AiUsageHub() => _timer.Tick += (_, _) => _ = RefreshAsync();+ private AiUsageHub()+ {+ Usage = _service.Cached;+ _timer.Tick += (_, _) => _ = RefreshAsync();+ }public ProviderUsage? For(string provider) => Usage.FirstOrDefault(u => u.Provider == provider);@@ -109,6 +113,7 @@ internal sealed class AiAssistantWidget(AiAssistant assistant) : DeskWidgetprivate readonly List<(TextBlock Label, TextBlock Value, Border Fill, Grid Bar, TextBlock Reset)> _rows = [];private TextBlock? _headline, _status;private RingGauge? _ring;+ private bool _statusOnlyWhenEmpty;private bool HasUsage => assistant.UsageProvider is not null;@@ -118,6 +123,7 @@ internal sealed class AiAssistantWidget(AiAssistant assistant) : DeskWidget_headline = null;_status = null;_ring = null;+ _statusOnlyWhenEmpty = false;return HasUsage ? BuildUsage() : BuildLauncher();}@@ -163,9 +169,12 @@ internal sealed class AiAssistantWidget(AiAssistant assistant) : DeskWidgeticon.HorizontalAlignment = HorizontalAlignment.Center;host.Children.Add(icon);_headline = Digits("", 20, FontWeights.Bold);+ // No room for a status line: the reason shows only while there is no number to show.+ _status.FontSize = 10.5;+ _statusOnlyWhenEmpty = true;var grid = Grid(columns: "Auto,*");grid.Children.Add(host);- grid.Children.Add(At(Margin(Column(_headline, Name(12)), 12), 0, 1));+ grid.Children.Add(At(Margin(Column(_headline, Name(12), _status), 12), 0, 1));return grid;}case DeskSize.Small:@@ -253,7 +262,12 @@ internal sealed class AiAssistantWidget(AiAssistant assistant) : DeskWidget{ Plan: { Length: > 0 } plan } => plan,_ => Desk.L("Kullanım sınırları", "Usage limits")};- if (_status is not null) _status.Text = status;+ if (_status is not null)+ {+ _status.Text = status;+ _status.ToolTip = status;+ _status.Visibility = _statusOnlyWhenEmpty && windows.Count > 0 && usage?.Error is null ? Visibility.Collapsed : Visibility.Visible;+ }if (_headline is not null) _headline.Text = windows.Count > 0 ? Percent(windows[0].UsedPercent) : "—";if (_ring is not null) _ring.Value = windows.Count > 0 ? windows[0].UsedPercent : 0;for (var i = 0; i < _rows.Count; i++)diff --git a/MainWindow.Extras.cs b/MainWindow.Extras.csindex 4f950bb..a231c32 100644--- a/MainWindow.Extras.cs+++ b/MainWindow.Extras.cs@@ -45,6 +45,16 @@ public partial class MainWindowControlCenter.OpenAppSettings = () => OpenSettings_Click(this, new RoutedEventArgs());_downloadsPopup = new WidgetPopup(DownloadsButton);_downloadsPopup.Closed += (_, _) => _autoHideController?.EvaluateState();+ AppGridWindow.PinToDock = (target, name) => AddShortcuts([target], name);+ AppGridWindow.IsPinned = target => _pinnedApps.Any(a => string.Equals(a.ExecutablePath, target, StringComparison.OrdinalIgnoreCase));+ // The app grid's icons are read once the desktop has settled, so its first opening is instant.+ var prewarm = new DispatcherTimer(DispatcherPriority.ApplicationIdle) { Interval = TimeSpan.FromSeconds(20) };+ prewarm.Tick += (_, _) =>+ {+ prewarm.Stop();+ AppGridWindow.Prewarm();+ };+ prewarm.Start();_fullScreenWatch.Tick += (_, _) => UpdateFullScreenAwareness(GetForegroundWindow());_fullScreenWatch.Start();_memoryTrim.Tick += (_, _) => TrimMemoryWhenIdle();@@ -98,6 +108,8 @@ public partial class MainWindowUnregisterHotKey(_extrasHandle, HotkeyControlCenter);for (var i = 0; i < 9; i++) UnregisterHotKey(_extrasHandle, HotkeyProfileFirst + i);}+ // Never leave a window off the screen when QiDock closes.+ BringBackForcedAside(activate: false);_downloadsPopup?.Close();if (ControlCenter.IsCreated) ControlCenter.Shared.Close();}diff --git a/MainWindow.Shortcuts.cs b/MainWindow.Shortcuts.csindex b5266c8..0699a06 100644--- a/MainWindow.Shortcuts.cs+++ b/MainWindow.Shortcuts.cs@@ -55,15 +55,19 @@ public partial class MainWindowvar here = files ? _desktopShown : _cleanShown;if (here && _windowsAside && ComputeDesktopClean()){- ToggleDesktop();+ if (_desktopToggled) ToggleDesktop();+ BringBackForcedAside(activate: !_desktopToggled);LeaveDesktop();return;}+ _desktopToggled = false;if (!ComputeDesktopClean()){ToggleDesktop();_windowsAside = true;+ _desktopToggled = true;}+ SweepStubbornWindows();_desktopShownAt = DateTime.UtcNow;_cleanShown = !files;SetDesktopFilesMode(files);@@ -73,12 +77,118 @@ public partial class MainWindow/// <summary>Back from either desktop: the icons return to what the settings ask for.</summary>private void LeaveDesktop(){+ // Another window came forward: the stepped-aside ones come back behind it, as they were.+ BringBackForcedAside(activate: false);_windowsAside = false;_cleanShown = false;SetDesktopFilesMode(false);if (!_preferences.Current.HideDesktopIcons) ApplyDesktopIcons(false);}+ // Whether the desktop button used Win+D (so pressing it again uses Win+D to bring the windows back).+ private bool _desktopToggled;+ // Windows Win+D leaves standing, which QiDock moved off the screen itself, top one first, with where they were.+ private readonly List<(nint Window, DesktopNative.Rect Bounds)> _forcedAside = [];++ /// <summary>Whether QiDock moved this window off the screen to show the desktop.</summary>+ private bool IsForcedAside(nint window) => _forcedAside.Any(f => f.Window == window);++ /// <summary>+ /// Win+D leaves windows without a minimize button where they are, so a program that fills the+ /// whole screen that way (a till or a kiosk program, often several such windows on top of each other)+ /// kept the desktop out of reach. Once Win+D has done its part, those still covering the screen are+ /// moved off the screen here. They are not minimized: such programs often close a screen that gets+ /// minimized and go back to their main menu, while a move leaves them exactly as they were.+ /// </summary>+ private void SweepStubbornWindows()+ {+ var timer = new DispatcherTimer(DispatcherPriority.Input) { Interval = TimeSpan.FromMilliseconds(350) };+ timer.Tick += (_, _) =>+ {+ timer.Stop();+ var primary = DesktopNative.MonitorFromPoint(default, 1 /* MONITOR_DEFAULTTOPRIMARY */);+ var info = new DesktopNative.MonitorInfo { Size = (uint)Marshal.SizeOf<DesktopNative.MonitorInfo>() };+ if (!DesktopNative.GetMonitorInfo(primary, ref info)) return;+ var screen = info.Bounds;+ var screenArea = (double)(screen.Right - screen.Left) * (screen.Bottom - screen.Top);+ var own = (uint)Environment.ProcessId;+ var found = new List<(nint, DesktopNative.Rect)>();+ DesktopNative.EnumWindows((window, _) =>+ {+ if (!DesktopNative.IsWindowVisible(window) || DesktopNative.IsIconic(window)) return true;+ var style = DesktopNative.GetWindowLongPtr(window, -16).ToInt64();+ var exStyle = DesktopNative.GetWindowLongPtr(window, -20).ToInt64();+ if ((style & 0x00020000 /* WS_MINIMIZEBOX */) != 0 || (exStyle & 0x00000080 /* WS_EX_TOOLWINDOW */) != 0) return true;+ if (DesktopNative.GetAncestor(window, 2 /* GA_ROOT */) != window) return true;+ DesktopNative.GetWindowThreadProcessId(window, out var process);+ if (process == own) return true;+ if (DesktopNative.DwmGetWindowAttribute(window, 14 /* DWMWA_CLOAKED */, out var cloaked, sizeof(int)) == 0 && cloaked != 0) return true;+ var name = new StringBuilder(64);+ DesktopNative.GetClassName(window, name, name.Capacity);+ if (name.ToString() is "Progman" or "WorkerW" or "Shell_TrayWnd" or "Shell_SecondaryTrayWnd" or "Windows.UI.Core.CoreWindow") return true;+ if (DesktopNative.MonitorFromWindow(window, 2 /* MONITOR_DEFAULTTONEAREST */) != primary || !DesktopNative.GetWindowRect(window, out var rect)) return true;+ var width = Math.Min(rect.Right, screen.Right) - Math.Max(rect.Left, screen.Left);+ var height = Math.Min(rect.Bottom, screen.Bottom) - Math.Max(rect.Top, screen.Top);+ // Only windows that hide most of the desktop; small dialogs and floating tools stay.+ if (width > 0 && height > 0 && width * (double)height >= screenArea * 0.5) found.Add((window, rect));+ return true;+ }, 0);+ if (found.Count == 0) return;+ var foreground = DesktopNative.GetForegroundWindow();+ foreach (var (window, _) in found) DesktopNative.SetWindowPos(window, 0, OffScreen, OffScreen, 0, 0, MoveOnly);+ _forcedAside.AddRange(found);+ _windowsAside = true;+ // The keyboard goes to the desktop, as with Win+D, not to a window that is out of sight.+ if (found.Any(f => f.Item1 == foreground) && DesktopNative.FindWindow("Progman", null) is var desktop and not 0)+ DesktopNative.SetForegroundWindow(desktop);+ };+ timer.Start();+ }++ private const int OffScreen = -32000;+ private const uint MoveOnly = 0x0001 /* NOSIZE */ | 0x0004 /* NOZORDER */ | 0x0010 /* NOACTIVATE */ | 0x4000 /* ASYNCWINDOWPOS */;++ /// <summary>+ /// Puts the windows moved by <see cref="SweepStubbornWindows"/> back where they were, in the same+ /// order on top of each other; with <paramref name="activate"/> the top one takes the keyboard again.+ /// </summary>+ private void BringBackForcedAside(bool activate)+ {+ if (_forcedAside.Count == 0) return;+ foreach (var (window, bounds) in _forcedAside)+ if (DesktopNative.IsWindow(window)) DesktopNative.SetWindowPos(window, 0, bounds.Left, bounds.Top, 0, 0, MoveOnly);+ var top = _forcedAside[0].Window;+ _forcedAside.Clear();+ if (activate && DesktopNative.IsWindow(top)) NativeWindowTracker.Activate(top);+ }++ private static class DesktopNative+ {+ public delegate bool EnumWindowsProc(nint window, nint parameter);++ [StructLayout(LayoutKind.Sequential)] public struct Rect { public int Left, Top, Right, Bottom; }+ [StructLayout(LayoutKind.Sequential)] public struct Point { public int X, Y; }+ [StructLayout(LayoutKind.Sequential)] public struct MonitorInfo { public uint Size; public Rect Bounds; public Rect Work; public uint Flags; }++ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumWindows(EnumWindowsProc callback, nint parameter);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWindow(nint window);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWindowVisible(nint window);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsIconic(nint window);+ [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW")] public static extern nint GetWindowLongPtr(nint window, int index);+ [DllImport("user32.dll")] public static extern nint GetAncestor(nint window, uint flags);+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(nint window, out uint process);+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassName(nint window, StringBuilder name, int capacity);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetWindowRect(nint window, out Rect rect);+ [DllImport("user32.dll")] public static extern nint MonitorFromWindow(nint window, uint flags);+ [DllImport("user32.dll")] public static extern nint MonitorFromPoint(Point point, uint flags);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetMonitorInfo(nint monitor, ref MonitorInfo info);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetWindowPos(nint window, nint after, int x, int y, int width, int height, uint flags);+ [DllImport("user32.dll")] public static extern nint GetForegroundWindow();+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetForegroundWindow(nint window);+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern nint FindWindow(string? className, string? title);+ [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(nint window, int attribute, out int value, int size);+ }+private void SetDesktopFilesMode(bool on){_desktopShown = on;@@ -206,12 +316,14 @@ public partial class MainWindowif (dialog.ShowDialog() == true) AddShortcuts(dialog.FolderNames);}- private void AddShortcuts(IEnumerable<string> paths)+ /// <param name="displayName">The name to show (an app pinned from the app screen keeps its Start menu name).</param>+ private void AddShortcuts(IEnumerable<string> paths, string? displayName = null){var added = 0;foreach (var path in paths){- var (target, arguments, name) = Describe(path);+ var (target, arguments, described) = Describe(path);+ var name = displayName ?? described;if (target is null) continue;if (_pinnedApps.Any(a => string.Equals(a.ExecutablePath, target, StringComparison.OrdinalIgnoreCase))) continue;var app = new DockApp(name, target) { LaunchArguments = arguments, IsCustomShortcut = true, Icon = ShortcutIcon(target) };diff --git a/MainWindow.TopBar.cs b/MainWindow.TopBar.csindex 559a47b..01b0e55 100644--- a/MainWindow.TopBar.cs+++ b/MainWindow.TopBar.cs@@ -32,7 +32,6 @@ public partial class MainWindowApplyDockBell();_topBar = new TopBarWindow { Tabs = _widgetBar.ProfileStrip };_widgetBar.ProfileMenuRequested += (_, target) => ShowProfileMenu(target.Index, target.Anchor);- _widgetBar.ProfilesRequested += (_, anchor) => ShowProfilesMenu(anchor);_topBar.SetLock(() => _widgetBar.IsAnyPopupOpen || _widgetBar.IsEditing || _openContextMenu?.IsOpen == true || EdgePanel.StandsOnDock || _holdDockUp);_topBar.LiveChanged += (_, live) => _widgetBar.SetLive(live || WidgetsInDock && DockOnScreen);_topBar.MenuRequested += (_, _) => ShowDockMenu(PlacementMode.MousePoint, null);@@ -619,71 +618,6 @@ public partial class MainWindow});}- /// <summary>Preset profile names offered for a new profile or a rename.</summary>- private static readonly string[] ProfileNames = ["ProfileWork", "ProfileCode", "ProfileHome", "ProfileFocus", "ProfileGame", "ProfileSchool", "ProfileCreative", "ProfileTools", "ProfileDefault"];-- /// <summary>The profile tile's menu: switch profile, make a new one, rename or remove the active one.</summary>- private void ShowProfilesMenu(FrameworkElement anchor)- {- var options = _preferences.Current.WidgetOptions;- var profiles = options.EffectiveProfiles;- var active = options.EffectiveActiveProfile;- var menu = new ContextMenu { PlacementTarget = anchor, Placement = Services.DockGeometry.Inward };- menu.Opened += DockContextMenu_Opened;- menu.Closed += DockContextMenu_Closed;- for (var i = 0; i < profiles.Count; i++)- {- var index = i;- var item = Item(profiles[i].Name, null, i == active);- if (i < 9) item.InputGestureText = "Ctrl+Alt+Shift+" + (i + 1);- item.Click += (_, _) =>- {- var current = _preferences.Current.WidgetOptions;- if (index != current.EffectiveActiveProfile) SaveWidgetOptions(current.SwitchProfile(index));- Widgets.Ui.ShowHud("IconLayout", current.EffectiveProfiles[index].Name);- };- menu.Items.Add(item);- }- menu.Items.Add(new Separator());- var create = Item(Services.UiText.Get("ProfileNewMenu"), "IconPlus");- var taken = profiles.Select(p => p.Name).ToHashSet(StringComparer.CurrentCultureIgnoreCase);- foreach (var key in ProfileNames)- {- var name = Services.UiText.Get(key);- if (taken.Contains(name)) continue;- var item = Item(name, null);- item.Click += (_, _) =>- {- SaveWidgetOptions(_preferences.Current.WidgetOptions.AddProfile(name));- Widgets.Ui.ShowHud("IconLayout", Services.UiText.Format("ProfileCreated", name));- };- create.Items.Add(item);- }- var numbered = Item(Services.UiText.Format("ProfileNew", profiles.Count + 1), null);- numbered.Click += (_, _) => SaveWidgetOptions(_preferences.Current.WidgetOptions.AddProfile(Services.UiText.Format("ProfileNew", profiles.Count + 1)));- create.Items.Add(numbered);- menu.Items.Add(create);- var rename = Item(Services.UiText.Get("ProfileRename"), "IconEdit");- foreach (var key in ProfileNames)- {- var name = Services.UiText.Get(key);- var item = Item(name, null, profiles[active].Name == name);- item.IsEnabled = !taken.Contains(name) || profiles[active].Name == name;- item.Click += (_, _) => SaveWidgetOptions(_preferences.Current.WidgetOptions.RenameProfile(active, name));- rename.Items.Add(item);- }- menu.Items.Add(rename);- var remove = Item(Services.UiText.Format("ProfileRemoveNamed", profiles[active].Name), "IconClose");- remove.IsEnabled = profiles.Count > 1;- remove.Click += (_, _) => SaveWidgetOptions(_preferences.Current.WidgetOptions.RemoveProfile(active));- menu.Items.Add(remove);- menu.Items.Add(new Separator());- var edit = Item(Services.UiText.Get(_widgetBar.IsEditing ? "MenuEditDone" : "ProfileEditWidgets"), "IconLayout");- edit.Click += (_, _) => _widgetBar.SetEditing(!_widgetBar.IsEditing);- menu.Items.Add(edit);- menu.IsOpen = true;- }-private void ShowProfileMenu(int index, FrameworkElement anchor){var options = _preferences.Current.WidgetOptions;@@ -746,7 +680,8 @@ public partial class MainWindow{if (_windowTracker?.Snapshot is not { } windows) return false;var primary = TopNative.MonitorFromPoint(new TopNative.Point(), 1 /* MONITOR_DEFAULTTOPRIMARY */);- return !windows.Any(window => IsOpenOn(window.Handle, primary));+ // Windows the desktop button moved off the screen count as put away.+ return !windows.Any(window => !IsForcedAside(window.Handle) && IsOpenOn(window.Handle, primary));}private static bool IsOpenOn(nint window, nint monitor) =>diff --git a/Overlays.cs b/Overlays.csindex 3b50222..dccd80c 100644--- a/Overlays.cs+++ b/Overlays.cs@@ -50,7 +50,7 @@ public abstract class OverlayWindow : Window{if (e.Key != Key.Escape) return;e.Handled = true;- Dismiss();+ if (!OnEscape()) Dismiss();};Deactivated += (_, _) => Dismiss();}@@ -73,6 +73,15 @@ public abstract class OverlayWindow : Window/// <summary>Whether the desktop behind is blurred (AppGrid), not just dimmed.</summary>protected virtual bool Frosted => false;+ /// <summary>The colour laid over the blurred desktop (alpha = how strongly).</summary>+ protected virtual Color FrostTint => Color.FromArgb(0x73, 0x10, 0x11, 0x16);++ /// <summary>Whether the blur really is on (false where Windows can't; then draw a dark background).</summary>+ protected bool IsFrosted { get; private set; }++ /// <summary>Esc closes an inner layer first (an open folder); true when it did, so the overlay stays.</summary>+ protected virtual bool OnEscape() => false;+/// <summary>Clicks on these elements count as clicks on the empty background.</summary>protected virtual bool IsBackground(object source) => false;@@ -107,7 +116,6 @@ public abstract class OverlayWindow : Window_dismissing = true;if (ReferenceEquals(_open, this)) _open = null;OnDismissing();- if (Frosted) GpuTransparency.Blur(this, false);var fade = new DoubleAnimation(0, TimeSpan.FromMilliseconds(150)) { EasingFunction = Motion.In };fade.Completed += (_, _) =>{@@ -122,7 +130,8 @@ public abstract class OverlayWindow : Windowbase.OnSourceInitialized(e);if (PresentationSource.FromVisual(this) is not HwndSource source) return;GpuTransparency.Apply(this);- if (Frosted) GpuTransparency.Blur(this, true);+ // The blurred desktop stays until the window closes, under the fading content.+ if (Frosted) IsFrosted = GpuTransparency.Frost(this, FrostTint, rounded: false);// Keep the overlay out of Alt+Tab.var style = GetWindowLongPtr(source.Handle, -20).ToInt64();SetWindowLongPtr(source.Handle, -20, new nint((style | 0x80) & ~0x40000));@@ -182,162 +191,6 @@ internal static class AppList}}-/// <summary>Every installed app as a grid of large icons over the dimmed screen; type to filter.</summary>-public sealed class AppGridWindow : OverlayWindow-{- private const double Cell = 132;- // Over the blurred desktop a lighter tint is enough; without blur the screen is darkened more.- private static readonly Brush Dim = Ui.Solid(GpuTransparency.CanBlur ? "#8C0E0F13" : "#F00E0F13");- // Icons stay cached between openings (about 64 KB each) so the grid fills at once next time.- private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, ImageSource?> Icons = new(StringComparer.OrdinalIgnoreCase);- private readonly WrapPanel _grid = new() { HorizontalAlignment = HorizontalAlignment.Center };- private readonly ScrollViewer _scroll;- private readonly TextBox _box;- private List<InstalledApp> _apps = [];- private List<InstalledApp> _shown = [];- private volatile int _iconBuild;-- public static void Toggle()- {- if (CloseIfOpen<AppGridWindow>()) return;- new AppGridWindow().Present();- }-- private AppGridWindow() : base(Dim)- {- var (field, box) = SearchField(UiText.Get("AppGridSearch"), 15, Ui.White, Ui.Solid("#A6FFFFFF"), Ui.Solid("#33FFFFFF"));- _box = box;- field.Width = 300;- field.HorizontalAlignment = HorizontalAlignment.Center;- field.Margin = new Thickness(0, 56, 0, 30);- box.TextChanged += (_, _) => Fill();- box.PreviewKeyDown += (_, e) =>- {- if (e.Key != Key.Enter || _shown.Count == 0) return;- e.Handled = true;- Launch(_shown[0]);- };- var columns = Math.Max(4, Math.Min(8, (int)((Width - 160) / Cell)));- _grid.MaxWidth = columns * Cell;- _scroll = new ScrollViewer { Content = _grid, VerticalScrollBarVisibility = ScrollBarVisibility.Hidden, Focusable = false, Padding = new Thickness(0, 0, 0, 60) };- var layout = new DockPanel();- DockPanel.SetDock(field, Dock.Top);- layout.Children.Add(field);- layout.Children.Add(_scroll);- Root.Children.Add(layout);- _apps = AppList.Cached ?? [];- Fill();- AppList.RefreshAsync().ContinueWith(t =>- {- // Rebuilding a hundred tiles takes a moment, so only when the list really changed.- if (!IsVisible || t.Result.SequenceEqual(_apps)) return;- _apps = t.Result;- Fill();- }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());- }-- protected override bool IsBackground(object source) => ReferenceEquals(source, _grid) || source is ScrollViewer || source is DockPanel { Parent: Grid };-- protected override bool Frosted => true;-- /// <summary>The grid settles from slightly large to its size.</summary>- protected override void OnShown() => _box.Focus();-- protected override void OnPresented()- {- var scale = new ScaleTransform(1.05, 1.05, Width / 2, Height / 2);- _scroll.RenderTransform = scale;- scale.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(320)) { EasingFunction = Motion.Out });- scale.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(320)) { EasingFunction = Motion.Out });- }-- private void Fill()- {- var query = _box.Text.Trim();- _shown = query.Length == 0 ? _apps : _apps.Where(a => Matches(a.Name, query)).ToList();- _grid.Children.Clear();- if (_apps.Count == 0)- {- _grid.Children.Add(new TextBlock { Text = UiText.Get("AppGridLoading"), Foreground = Ui.WhiteSoft, FontSize = 14, Margin = new Thickness(0, 40, 0, 0) });- return;- }- var images = new List<(Image Image, string Id)>();- foreach (var app in _shown)- {- var image = new Image { Width = 72, Height = 72, Stretch = Stretch.Uniform };- if (Icons.TryGetValue(app.Id, out var known)) image.Source = known;- else images.Add((image, app.Id));- _grid.Children.Add(Tile(app, image));- }- LoadIcons(images);- }-- /// <summary>Loads missing icons on a background thread and drops each into the grid as it arrives.</summary>- private void LoadIcons(List<(Image Image, string Id)> pending)- {- var build = ++_iconBuild;- if (pending.Count == 0) return;- var thread = new Thread(() =>- {- // Icons are handed over in small batches so the grid redraws a few times, not once per icon.- var batch = new List<(Image Image, ImageSource? Source)>();- void Flush()- {- if (batch.Count == 0) return;- var ready = batch.ToArray();- batch.Clear();- Dispatcher.BeginInvoke(() =>- {- foreach (var (image, source) in ready) image.Source = source;- }, DispatcherPriority.Background);- }- foreach (var (image, id) in pending)- {- if (build != _iconBuild) return;- batch.Add((image, Icons.GetOrAdd(id, key => NotificationApps.LoadIcon(key, 128))));- if (batch.Count >= 16) Flush();- }- Flush();- }) { IsBackground = true, Name = "AppGrid icons" };- thread.SetApartmentState(ApartmentState.STA);- thread.Start();- }-- private FrameworkElement Tile(InstalledApp app, Image image)- {- var name = new TextBlock- {- Text = app.Name,- Foreground = Ui.White,- FontSize = 12,- TextAlignment = TextAlignment.Center,- TextTrimming = TextTrimming.CharacterEllipsis,- Margin = new Thickness(0, 8, 0, 0)- };- // No per-icon shadows: a hundred of them made opening and scrolling stutter.- var column = new StackPanel { VerticalAlignment = VerticalAlignment.Center };- RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality);- column.Children.Add(image);- column.Children.Add(name);- var hover = Ui.Solid("#1FFFFFFF");- var tile = new Border { Width = Cell - 12, Height = Cell - 8, Margin = new Thickness(6, 4, 6, 4), Padding = new Thickness(8, 10, 8, 6), CornerRadius = new CornerRadius(16), Background = Brushes.Transparent, Child = column, ToolTip = app.Name, Cursor = Cursors.Hand };- tile.MouseEnter += (_, _) => tile.Background = hover;- tile.MouseLeave += (_, _) => tile.Background = Brushes.Transparent;- tile.MouseLeftButtonUp += (_, e) =>- {- e.Handled = true;- Launch(app);- };- return tile;- }-- private void Launch(InstalledApp app)- {- Dismiss();- app.Launch();- }-}-/// <summary>A search box in the middle of the screen for apps, files and quick sums.</summary>public sealed class QuickSearchWindow : OverlayWindow{diff --git a/README.md b/README.mdindex 63e27c3..b00e961 100644--- a/README.md+++ b/README.md@@ -33,14 +33,14 @@ QiDock turns the Windows 10 and 11 taskbar into a floating glass dock with a wid- **Dock Edge:** The dock can stand on the bottom, top, left or right edge of the screen (dock menu "Dock'un kenarı" or Settings → General). Icons stay upright, the running dots sit on the screen-edge side, magnification and hiding work on every edge, and panels, widget cards and window previews open inward. On the left and right edges the widgets stay in the top bar; on the top edge they move into the dock.- **Widget Placement:** The widgets can also sit inside the dock, left of the apps or right of them (before Downloads and the bin), with a thin divider between the groups. Choose it from the dock menu ("Araçların yeri") or in Settings → Widgets. When the row is wider than the screen, icons and widgets shrink together so they stay in proportion. In the dock the widgets stay live, and each widget's card grows out of the dock the way the bell's list does (the dock keeps still while it stands there). The Control Center tile sits at the end of the row and replaces the Quick controls tile (Wi-Fi, Bluetooth, volume and brightness are all in the Control Center).- **Widget Profiles:** Tabs under the bar (shown on hover) switch between widget sets such as "Varsayılan", "İş" and "Araçlar"; Ctrl+Alt+Shift+1…9 switch from anywhere (each tab shows its key), and "Kendinizinkini oluşturun" adds one. Each profile keeps its own order and hidden widgets; right-click a tab to rename or delete it, "+" adds one. The **Profile** tile (in the dock or the bar) shows the active profile; a click lists the profiles to switch to, makes a new one from ready names (İş, Kod, Ev, Odak, Oyun, Okul, Tasarım, Araçlar), renames or deletes the active one, and edits its widgets. It is how profiles are reached while the widgets sit in the dock, where the tabs are not shown.-- **Two Desktop Buttons:** The blue tile next to Start goes straight to the clean desktop (open windows step aside, desktop icons hidden, the widgets stay). The orange folder tile goes straight to the desktop with its folders and files; the desktop widgets and the widget bar step out of the way there. Either button switches to the other desktop directly; pressing the same one again brings the windows back.+- **Two Desktop Buttons:** The blue tile next to Start goes straight to the clean desktop (open windows step aside, desktop icons hidden, the widgets stay). The orange folder tile goes straight to the desktop with its folders and files; the desktop widgets and the widget bar step out of the way there. Either button switches to the other desktop directly; pressing the same one again brings the windows back. Full-screen windows that Windows itself cannot minimize are moved aside and put back exactly where they were, without closing the screen they show.- **Dock Shortcuts:** Add apps, files, folders or web links to the dock from the dock menu (Kısayol ekle) or by dropping them on the dock. Remove them with "Unpin" like any pinned app.- **Recycle Bin:** A Recycle Bin tile at the end of the dock shows whether it is empty; drop files on it to delete them (undoable), click to open, right-click to empty.- **Notifications at the Top:** New Windows notifications slide down from the top center of the screen as small cards of frosted glass (app icon, app name, time, title and text; the desktop behind is blurred and tinted). Up to three stack, newest on top, the others gliding down to make room; they slide back up after a few seconds; hovering keeps them, a click opens the app (or the notification's link), dragging a card up or its × dismisses it. They stay out of the way of full-screen apps. Windows' own pop-up at the bottom right is moved off screen while it shows, so each notification appears once (nothing in Windows' settings changes; turn "Windows balonlarını gizle" off to get it back). Notifications are read from Windows' own notification database (`wpndatabase.db`, through the `winsqlite3.dll` that ships with Windows) on a private copy, so the original is never written.- **Notification Center:** Clicking the bell on the dock (with a red unread badge) grows the list out of the dock itself: a small bump rises from the bell and swells, with a soft overshoot, into a panel in the dock's own material, joined to the dock by inward curves (the dock leaves out its edge line there and the grown shape draws no rim of its own, so the two read as one piece); clicking outside pulls it back into the bell. The bell tile next to the battery opens it the same way. Ctrl+Alt+← slides a sheet of frosted glass in from the right edge instead (the desktop behind is blurred and tinted, with rounded corners). The sheet is only as tall as its cards (at most about 60% of the screen, then it scrolls smoothly under the fixed title row). Notifications of one app sit in a single stack (the newest card with the others peeking out below, "+N daha"); click the stack and the cards fan out of it, "Daha az göster" folds them back, × clears the group. Click a single card to open its app; hover it for the × that slides it away. Every change moves the cards from where they were to where they go. The gear holds switches for the top banners, hiding Windows' pop-up and a sound.- **Smooth Motion:** Panels and overlays are see-through without WPF's layered-window mode (which copies every frame back to memory); cards only move and fade, the glass is resized once per change rather than every frame, and each movement starts after its first frame is drawn, so animations stay fluid on large, high-DPI screens. Set the environment variable `QIDOCK_FRAMES=1` to log frame times to `%LOCALAPPDATA%\QiDock\frames.log`.- **Control Center:** Ctrl+Alt+→, any part of the Quick Controls tile, the battery tile or the round "Denetim Merkezi" button opens the same frosted sheet with tiles: Wi-Fi (with the network name) and Bluetooth toggles, power mode, unread notifications, volume and built-in display brightness sliders, battery, and shortcuts for screen snip, lock, Windows settings and QiDock settings. The chevron on the Wi-Fi row opens the networks in range (signal, padlock, a tick on the joined one); click one to join it, and a network Windows has not joined before asks for its password right there. "Windows ağ listesi" opens Windows' own list (also the way in when Windows does not let apps list networks).-- **All Apps ("Tüm uygulamalar"):** The dock's colored-grid button or Ctrl+Alt+↓ shows every installed app (desktop and Store apps, as in "All apps") as a large-icon grid over the blurred screen (dimmed on Windows 10); type to filter, Enter opens the first match, Esc or a click on the background closes it.+- **All Apps ("Tüm uygulamalar"):** The dock's colored-grid button or Ctrl+Alt+↓ shows every installed app (desktop and Store apps, as in "All apps") as a sharp-icon grid over frosted glass (dimmed on Windows 10). It opens instantly (icons are prepared in the background and only the visible page is built), and a "Most used" row on top follows how often and how long you use each app, as recorded by Windows. Type to filter; arrow keys move the selection, Page Up/Down turn pages, Enter opens the selected app (or the first match), Esc or a click on the background closes it. Right-click an app to open it, run it as administrator, open its file location or pin it to the dock; right-click a folder to open or ungroup it.- **QuickSearch:** Alt+Shift+Space or the "Ara" bar tile opens a search box in the middle of the screen for apps and files in your user folders, with arrow-key selection. Simple sums ("12*4+3") show their result (Enter copies it); the last row searches the web.- **Window Overview:** Ctrl+Alt+↑ shows all open windows side by side as live thumbnails (minimized ones as their app icon); click one to switch to it.- **Downloads Stack:** The blue arrow next to the Recycle Bin shows the 12 newest files in your Downloads folder; click to open, drag them into other apps, or open the folder.@@ -59,7 +59,7 @@ QiDock turns the Windows 10 and 11 taskbar into a floating glass dock with a wid- **Notifications:** A square bell with the red unread badge, always the last tile of the row, in the corner next to the battery; the list grows out of it. While this tile is shown the dock's own bell stays hidden (so there is always exactly one).- **CPU & RAM:** Two small rings with the load inside; click for details.- **Clock & Calendar:** Large time with the date under it; click for a month view and the selected day's events from any iCal (.ics) address — Google Calendar's "secret address in iCal format", Outlook or iCloud. Common recurrence rules are supported.- - **AI Limits:** Claude and ChatGPT as two small rings (logo inside, the busier limit's use around it, percent beside). Nothing shows on hover; click a ring for that provider's own card (bars, reset times, this week's curve and pace), and click the other ring to switch to it. Claude uses the Claude Code sign-in on this PC (the same usage endpoint as `/usage`); ChatGPT reads the latest rate-limit snapshot from Codex's local session logs, without network access. Tokens are read from disk only to call their own provider and are never stored.+ - **AI Limits:** Claude and ChatGPT as two small rings (logo inside, the busier limit's use around it, percent beside). Nothing shows on hover; click a ring for that provider's own card (bars, reset times, this week's curve and pace), and click the other ring to switch to it. Claude uses the Claude Code sign-in on this PC (the same usage endpoint as `/usage`); ChatGPT reads the latest rate-limit snapshot from Codex's local session logs, without network access. Tokens are read from disk only to call their own provider. When the Claude Code sign-in has expired (for example because Claude is used from the desktop app), QiDock renews it the same way Claude Code does and writes the new keys back into Claude Code's own file, so Claude Code keeps working; QiDock keeps no copy. The last readings (percentages and reset times only) are kept so the rings show numbers right after start.- **Quick Controls:** Wi-Fi and Bluetooth status (the capsules, their chevrons and the battery open the Control Center), a volume slider for the default output device (drag, click or scroll; click the speaker to mute) and a battery tile on laptops.- **Folder:** The Desktop (or a folder you pick) as a tile; the card shows its files in a grid you can browse, open or drag out.- **Search:** A search field that opens QuickSearch (the same search as Alt+Shift+Space).@@ -69,7 +69,7 @@ QiDock turns the Windows 10 and 11 taskbar into a floating glass dock with a wid- **World Clock:** Up to three cities with their time difference.- **To-Do:** A short task list; the tile shows the next open task.- **Tools:** Screenshot, clipboard history, emoji panel, calculator and lock screen.- - **Profile:** The active widget profile; click to switch, add, rename or delete profiles (see Widget Profiles).+ - **Profile:** The active widget profile; click for its card (grown out of the dock like the other widgets) to switch, add, rename or delete profiles or edit the profile's widgets (see Widget Profiles).- **Currency Converter:** One unit of a currency in another (1 USD = … ₺) on the tile; the card converts any amount between TRY, USD, EUR, GBP, CHF and JPY (click a currency to step to the next, ⇅ swaps). European Central Bank rates via [Frankfurter](https://www.frankfurter.app), fetched at most every six hours and only while the tile is shown.- **Stopwatch & Timer:** A stopwatch to the tenth of a second, or a countdown of 1–60 minutes that chimes and shows a message at the top of the screen when it ends. The display ticks only while running and on screen.- **Quick Note:** A small note that is saved as you type (after a short pause); the tile shows its first line.diff --git a/Services/AppCatalog.cs b/Services/AppCatalog.csindex 58bc70a..81e973a 100644--- a/Services/AppCatalog.cs+++ b/Services/AppCatalog.cs@@ -5,8 +5,38 @@ using System.Runtime.InteropServices;namespace QiDock.Services;/// <summary>An installed app as Windows lists it in "All apps": its name and shell parsing name.</summary>-public sealed record InstalledApp(string Name, string Id)+/// <param name="Target">The program file a desktop app starts (null for Store apps, which have none).</param>+public sealed record InstalledApp(string Name, string Id, string? Target = null){+ /// <summary>Starts the app's program file as administrator (Windows asks for permission first).</summary>+ public void LaunchAsAdministrator()+ {+ if (Target is null) return;+ try+ {+ Process.Start(new ProcessStartInfo(Target) { UseShellExecute = true, Verb = "runas", WorkingDirectory = Path.GetDirectoryName(Target) ?? "" })?.Dispose();+ }+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)+ {+ // Declining the permission prompt lands here too.+ Trace.TraceWarning("Could not start {0} as administrator: {1}", Target, ex.Message);+ }+ }++ /// <summary>Opens the folder of the app's program file with the file selected.</summary>+ public void ShowFileLocation()+ {+ if (Target is null) return;+ try+ {+ Process.Start(new ProcessStartInfo("explorer.exe", $"/select,\"{Target}\"") { UseShellExecute = true })?.Dispose();+ }+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)+ {+ Trace.TraceWarning("Could not show {0}: {1}", Target, ex.Message);+ }+ }+public void Launch(){try@@ -66,7 +96,12 @@ public static class AppCatalogstring name = item.Name ?? "";string id = item.Path ?? "";if (name.Length == 0 || id.Length == 0 || IsNoise(name, id) || !seen.Add(name)) continue;- list.Add(new InstalledApp(name, id));+ // The program a desktop app's Start menu entry points at (empty for Store apps).+ string? target = null;+ try { target = item.ExtendedProperty("System.Link.TargetParsingPath") as string; }+ catch (COMException) { }+ if (string.IsNullOrWhiteSpace(target) || !target.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) target = null;+ list.Add(new InstalledApp(name, id, target));}}finallydiff --git a/Services/ApplicationIconProvider.cs b/Services/ApplicationIconProvider.csindex cff00ff..ea1e7cd 100644--- a/Services/ApplicationIconProvider.cs+++ b/Services/ApplicationIconProvider.cs@@ -22,7 +22,7 @@ public static class ApplicationIconProviderreturn executableIcon;}- return null;+ return GetFolderLogo(path);}if (File.Exists(path))@@ -51,6 +51,44 @@ public static class ApplicationIconProvider}}+ /// <summary>+ /// For a program file without an icon of its own (some business programs ship their logo as a+ /// separate .ico next to it, often in a pictures folder): the sharpest square .ico in the program's+ /// folder or the folders right inside it, or null when there is none.+ /// </summary>+ private static BitmapSource? GetFolderLogo(string executablePath)+ {+ try+ {+ if (Path.GetDirectoryName(executablePath) is not { } folder || !Directory.Exists(folder)) return null;+ // Windows' own folders hold hundreds of unrelated icons.+ if (folder.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.Windows), StringComparison.OrdinalIgnoreCase)) return null;+ var files = Directory.EnumerateFiles(folder, "*.ico")+ .Concat(Directory.EnumerateDirectories(folder).SelectMany(sub => Directory.EnumerateFiles(sub, "*.ico")))+ .Take(40);+ BitmapSource? best = null;+ foreach (var file in files)+ {+ try+ {+ using var stream = File.OpenRead(file);+ var decoder = new IconBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);+ // Square pictures only: odd sizes are banners or broken files, not app icons.+ var frame = decoder.Frames.Where(f => f.PixelWidth == f.PixelHeight).MaxBy(f => f.PixelWidth);+ if (frame is null || frame.PixelWidth < 32 || frame.PixelWidth <= (best?.PixelWidth ?? 0)) continue;+ frame.Freeze();+ best = frame;+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or FileFormatException or ArgumentException or OverflowException) { }+ }+ return best;+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ return null;+ }+ }+public static BitmapSource? GetForResource(string path, int index){var expanded = Environment.ExpandEnvironmentVariables(path);diff --git a/Services/GpuTransparency.cs b/Services/GpuTransparency.csindex 5840f56..9263ce4 100644--- a/Services/GpuTransparency.cs+++ b/Services/GpuTransparency.cs@@ -29,19 +29,6 @@ public static class GpuTransparencywindow.Background = Brushes.Transparent;}- /// <summary>Whether Windows can blur what lies behind a window (Windows 11 22H2 and later).</summary>- public static bool CanBlur => Supported && Environment.OSVersion.Version.Build >= 22621;-- /// <summary>Turns the frosted blur behind the whole window on or off.</summary>- public static void Blur(Window window, bool on)- {- if (!CanBlur || PresentationSource.FromVisual(window) is not HwndSource source) return;- var value = on ? 3 /* DWMSBT_TRANSIENTWINDOW */ : 1 /* DWMSBT_NONE */;- DwmSetWindowAttribute(source.Handle, 38, ref value, sizeof(int));- value = 1; // dark material- DwmSetWindowAttribute(source.Handle, 20, ref value, sizeof(int));- }-public static void Apply(Window window){if (window.AllowsTransparency || !Supported || PresentationSource.FromVisual(window) is not HwndSource source) return;@@ -62,8 +49,9 @@ public static class GpuTransparency/// thin edge and soft shadow Windows gives its own flyouts. Unlike the system backdrop this/// stays frosted while the window is not the active one (the panels never take focus)./// Returns false where Windows can't (then the caller draws an opaque background).+ /// A full-screen window passes <paramref name="rounded"/> false: square corners, no edge./// </summary>- public static bool Frost(Window window, Color tint)+ public static bool Frost(Window window, Color tint, bool rounded = true){if (window.AllowsTransparency || !Supported || PresentationSource.FromVisual(window) is not HwndSource source) return false;var policy = new AccentPolicy@@ -81,7 +69,7 @@ public static class GpuTransparency}catch (EntryPointNotFoundException) { return false; }finally { Marshal.FreeHGlobal(memory); }- if (Environment.OSVersion.Version.Build >= 22000)+ if (rounded && Environment.OSVersion.Version.Build >= 22000){var value = 2; // DWMWCP_ROUNDDwmSetWindowAttribute(source.Handle, 33, ref value, sizeof(int));diff --git a/Services/NativeWindowTracker.cs b/Services/NativeWindowTracker.csindex c0bae0e..c29f865 100644--- a/Services/NativeWindowTracker.cs+++ b/Services/NativeWindowTracker.cs@@ -21,6 +21,9 @@ public sealed class NativeWindowTracker : IDisposableprivate const int ChildIdSelf = 0;private const int WindowOwner = 4;private const int GwlExStyle = -20;+ private const int GwlStyle = -16;+ private const long WsPopup = 0x80000000;+ private const long WsMinimizeBox = 0x00020000;private const long WsExAppWindow = 0x00040000;private const long WsExToolWindow = 0x00000080;private const uint GaRootOwner = 3;@@ -218,8 +221,7 @@ public sealed class NativeWindowTracker : IDisposableprivate bool CollectWindow(nint windowHandle, nint state){- if (windowHandle == _excludedWindow || !IsWindowVisible(windowHandle)- || GetWindow(windowHandle, WindowOwner) != 0)+ if (windowHandle == _excludedWindow || !IsWindowVisible(windowHandle)){return true;}@@ -230,6 +232,16 @@ public sealed class NativeWindowTracker : IDisposablereturn true;}+ // Owned windows are dialogs of another window, except when they ask for a taskbar button or their+ // owner is hidden: many business programs (WinForms, Delphi) keep a hidden main window that owns+ // every screen they show, and those screens are the program as far as the user can see.+ var owner = GetWindow(windowHandle, WindowOwner);+ if (owner != 0 && (extendedStyle & WsExAppWindow) == 0+ && (IsWindowVisible(owner) || (GetWindowLongPtr(windowHandle, GwlStyle).ToInt64() & WsPopup) != 0))+ {+ return true;+ }+var titleLength = GetWindowTextLength(windowHandle);if (titleLength <= 0){@@ -331,9 +343,17 @@ public sealed class NativeWindowTracker : IDisposable}var foregroundRoot = GetAncestor(foregroundWindow, GaRootOwner);- if (foregroundRoot == 0)+ if (foregroundRoot == 0 || !IsWindowVisible(foregroundRoot)){- foregroundRoot = foregroundWindow;+ // A program whose hidden main window owns its screens: the screen itself, not the hidden window.+ foregroundRoot = GetAncestor(foregroundWindow, GaRoot) is var root and not 0 ? root : foregroundWindow;+ }++ // A window without a minimize button is not minimized from the dock either: programs made that way+ // (tills, kiosks) often close the screen when it is minimized.+ if ((GetWindowLongPtr(foregroundRoot, GwlStyle).ToInt64() & WsMinimizeBox) == 0)+ {+ return 0;}return IsWindow(foregroundRoot) && !IsIconic(foregroundRoot)diff --git a/Services/UiText.cs b/Services/UiText.csindex e269bc8..ca0d74d 100644--- a/Services/UiText.cs+++ b/Services/UiText.cs@@ -40,6 +40,7 @@ public sealed class UiText : INotifyPropertyChanged["ProfileTileHint"] = ("Profil değiştir, yeni profil ekle (İş, Kod…). Her profil hangi bileşenlerin görüneceğini ayrı saklar.", "Switch profile or add one (Work, Code…). Each profile keeps its own set of widgets."),["ProfileCode"] = ("Kod", "Code"),["ProfileNewMenu"] = ("Yeni profil", "New profile"),+ ["ProfilesTitle"] = ("Profiller", "Profiles"),["ProfileCreated"] = ("\"{0}\" profili oluşturuldu", "Profile \"{0}\" created"),["ProfileRemoveNamed"] = ("\"{0}\" profilini sil", "Delete profile \"{0}\""),["ProfileEditWidgets"] = ("Bu profilin bileşenlerini düzenle", "Edit this profile's widgets"),@@ -264,6 +265,16 @@ public sealed class UiText : INotifyPropertyChanged["AppGridTitle"] = ("Tüm uygulamalar (Ctrl+Alt+↓)", "All apps (Ctrl+Alt+↓)"),["AppGridSearch"] = ("Ara", "Search"),["AppGridLoading"] = ("Uygulamalar yükleniyor…", "Loading apps…"),+ ["AppGridFolder"] = ("Klasör", "Folder"),+ ["AppGridNoMatch"] = ("Sonuç yok", "No results"),+ ["AppGridFrequent"] = ("Sık kullanılanlar", "Most used"),+ ["AppGridOpen"] = ("Aç", "Open"),+ ["AppGridRunAsAdmin"] = ("Yönetici olarak çalıştır", "Run as administrator"),+ ["AppGridShowLocation"] = ("Dosya konumunu aç", "Open file location"),+ ["AppGridPin"] = ("Dock'a sabitle", "Pin to dock"),+ ["AppGridPinned"] = ("Dock'ta sabitli", "Pinned to dock"),+ ["AppGridOpenFolder"] = ("Klasörü aç", "Open folder"),+ ["AppGridUngroup"] = ("Klasörü dağıt", "Ungroup folder"),["QuickSearchHint"] = ("Uygulama, dosya ara ya da hesapla", "Search apps and files, or calculate"),["QuickSearchCopy"] = ("Enter ile kopyala", "Press Enter to copy"),["QuickSearchWeb"] = ("Web'de ara: “{0}”", "Search the web for “{0}”"),@@ -474,7 +485,7 @@ public sealed class UiText : INotifyPropertyChanged["AiDaysWindow"] = ("{0} gün", "{0} days"),["AiNoData"] = ("Veri yok", "No data"),["AiNoDataHelp"] = ("Claude için Claude Code’da oturum açın; ChatGPT için Codex’i bir kez kullanın. Limitler burada görünür.", "Sign in to Claude Code for Claude, or use Codex once for ChatGPT. Limits will appear here."),- ["AiClaudeExpired"] = ("Oturum süresi doldu; Claude Code’u bir kez açın.", "Session expired; open Claude Code once."),+ ["AiClaudeExpired"] = ("Giriş yenilenemedi; terminalde claude yazıp giriş yapın.", "Couldn’t renew the sign-in; run claude in a terminal and sign in."),["AiRateLimited"] = ("Çok sık soruldu; birkaç dakika sonra yenilenecek.", "Asked too often; will refresh in a few minutes."),["AiFetchError"] = ("Kullanım bilgisi alınamadı.", "Couldn’t read usage."),["AiRefresh"] = ("Yenile", "Refresh"),diff --git a/Services/Widgets/AiUsageService.cs b/Services/Widgets/AiUsageService.csindex ae9368d..4d6fa79 100644--- a/Services/Widgets/AiUsageService.cs+++ b/Services/Widgets/AiUsageService.cs@@ -5,6 +5,7 @@ using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Text.Json;+using System.Text.Json.Nodes;namespace QiDock.Services.Widgets;@@ -39,6 +40,18 @@ public sealed class AiUsageServiceprivate DateTime _claudeFetchedAt = DateTime.MinValue;private DateTime _claudeBackoffUntil = DateTime.MinValue;+ public AiUsageService()+ {+ Cached = LastKnown();+ _claude = Cached.FirstOrDefault(u => u.Provider == ClaudeId);+ }++ /// <summary>+ /// The last readings saved on this PC (percentages and reset times only), so the tiles show numbers the moment+ /// QiDock starts instead of a dash until the first answer arrives. Limits that have reset since are left out.+ /// </summary>+ public IReadOnlyList<ProviderUsage> Cached { get; }+public async Task<IReadOnlyList<ProviderUsage>> FetchAsync(bool force, CancellationToken token){var results = new List<ProviderUsage>();@@ -46,9 +59,63 @@ public sealed class AiUsageServiceif (claude is not null) results.Add(claude);var codex = await Task.Run(ReadCodex, token).ConfigureAwait(false);if (codex is not null) results.Add(codex);+ SaveLastKnown(results);return results;}+ private static readonly string LastKnownPath = Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock", "ai-usage-last.json");+ private static readonly object LastKnownLock = new();++ private static IReadOnlyList<ProviderUsage> LastKnown()+ {+ try+ {+ lock (LastKnownLock)+ {+ if (!File.Exists(LastKnownPath)) return [];+ var saved = JsonSerializer.Deserialize<List<ProviderUsage>>(File.ReadAllText(LastKnownPath)) ?? [];+ var now = DateTime.Now;+ return saved+ .Select(u => u with { Windows = u.Windows.Where(w => w.ResetsAt is not { } reset || reset > now).ToList(), Error = null })+ .Where(u => u.Windows.Count > 0)+ .ToList();+ }+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or NotSupportedException)+ {+ return [];+ }+ }++ /// <summary>Keeps each provider's latest good reading; a failed reading leaves the saved one as it was.</summary>+ private static void SaveLastKnown(IReadOnlyList<ProviderUsage> results)+ {+ var good = results.Where(u => u.Error is null && u.Windows.Count > 0).ToList();+ if (good.Count == 0) return;+ try+ {+ lock (LastKnownLock)+ {+ List<ProviderUsage> saved = [];+ if (File.Exists(LastKnownPath))+ {+ try { saved = JsonSerializer.Deserialize<List<ProviderUsage>>(File.ReadAllText(LastKnownPath)) ?? []; }+ catch (JsonException) { }+ }+ var merged = saved.Where(s => good.All(g => g.Provider != s.Provider)).Concat(good).ToList();+ Directory.CreateDirectory(Path.GetDirectoryName(LastKnownPath)!);+ var temporary = LastKnownPath + ".tmp";+ File.WriteAllText(temporary, JsonSerializer.Serialize(merged));+ File.Move(temporary, LastKnownPath, true);+ }+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException)+ {+ System.Diagnostics.Trace.TraceWarning("AI usage not saved: {0}", ex.Message);+ }+ }+// ---- Claude ----------------------------------------------------------------------------private async Task<ProviderUsage?> GetClaudeAsync(bool force, CancellationToken token)@@ -61,19 +128,30 @@ public sealed class AiUsageServicevar credentials = ReadClaudeCredentials();if (credentials is null) return null;var (accessToken, expiresAt, plan) = credentials.Value;- if (expiresAt is { } expiry && expiry <= DateTime.Now)+ // Claude used from the desktop app keeps its own sign-in, so this file's key runs out unless renewed here.+ if (expiresAt is { } expiry && expiry <= DateTime.Now.AddMinutes(1)){- _claude = new ProviderUsage(ClaudeId, "Claude", plan, _claude?.Windows ?? [], now, UiText.Get("AiClaudeExpired"));- _claudeFetchedAt = now;- return _claude;+ if (await RenewClaudeSignInAsync(false, token).ConfigureAwait(false) && ReadClaudeCredentials() is { } renewed)+ (accessToken, expiresAt, plan) = renewed;+ else+ {+ _claude = new ProviderUsage(ClaudeId, "Claude", plan, _claude?.Windows ?? [], now, UiText.Get("AiClaudeExpired"));+ _claudeFetchedAt = now;+ return _claude;+ }}try{- using var request = new HttpRequestMessage(HttpMethod.Get, "https://api.anthropic.com/api/oauth/usage");- request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);- request.Headers.Add("anthropic-beta", "oauth-2025-04-20");- using var response = await WidgetHttp.Client.SendAsync(request, token).ConfigureAwait(false);+ var response = await AskUsageAsync(accessToken, token).ConfigureAwait(false);+ if (response.StatusCode is HttpStatusCode.Unauthorized && await RenewClaudeSignInAsync(true, token).ConfigureAwait(false)+ && ReadClaudeCredentials() is { } fresh)+ {+ response.Dispose();+ accessToken = fresh.AccessToken;+ response = await AskUsageAsync(accessToken, token).ConfigureAwait(false);+ }+ using var _ = response;if (response.StatusCode == HttpStatusCode.TooManyRequests){_claudeBackoffUntil = now.AddMinutes(10);@@ -168,12 +246,105 @@ public sealed class AiUsageServicewindows.Add(new UsageWindow(label, Math.Clamp(used, 0, 100), resets, length, key));}- private static (string AccessToken, DateTime? ExpiresAt, string? Plan)? ReadClaudeCredentials()+ private static async Task<HttpResponseMessage> AskUsageAsync(string accessToken, CancellationToken token)+ {+ using var request = new HttpRequestMessage(HttpMethod.Get, "https://api.anthropic.com/api/oauth/usage");+ request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);+ request.Headers.Add("anthropic-beta", "oauth-2025-04-20");+ return await WidgetHttp.Client.SendAsync(request, token).ConfigureAwait(false);+ }++ private static string ClaudeCredentialsPath(){var directory = Environment.GetEnvironmentVariable("CLAUDE_CONFIG_DIR");if (string.IsNullOrWhiteSpace(directory))directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".claude");- var path = Path.Combine(directory, ".credentials.json");+ return Path.Combine(directory, ".credentials.json");+ }++ // The same renewal Claude Code does itself: its public app id and Anthropic's token address.+ private const string ClaudeTokenUrl = "https://platform.claude.com/v1/oauth/token";+ private const string ClaudeClientId = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";+ private static readonly SemaphoreSlim RenewLock = new(1, 1);+ private static DateTime _renewFailedAt = DateTime.MinValue;++ /// <summary>+ /// Renews Claude Code's expired sign-in with its refresh key and writes the new keys back into the same file, so+ /// Claude Code keeps working with them. True when the file now holds a usable key (also when Claude Code or the+ /// other usage reader renewed it meanwhile). A failed attempt waits ten minutes before the next one.+ /// </summary>+ private static async Task<bool> RenewClaudeSignInAsync(bool force, CancellationToken token)+ {+ await RenewLock.WaitAsync(token).ConfigureAwait(false);+ try+ {+ var path = ClaudeCredentialsPath();+ if (!File.Exists(path)) return false;+ if (JsonNode.Parse(await File.ReadAllTextAsync(path, token).ConfigureAwait(false)) is not JsonObject root+ || root["claudeAiOauth"] is not JsonObject oauth) return false;+ var nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();+ if (!force && oauth["expiresAt"] is JsonValue e && e.TryGetValue<long>(out var expires) && expires > nowMs + 60_000) return true;+ if (DateTime.Now - _renewFailedAt < TimeSpan.FromMinutes(10)) return false;+ if (oauth["refreshToken"] is not JsonValue r || !r.TryGetValue<string>(out var refreshToken) || string.IsNullOrEmpty(refreshToken)) return false;++ var body = new JsonObject+ {+ ["grant_type"] = "refresh_token",+ ["refresh_token"] = refreshToken,+ ["client_id"] = ClaudeClientId+ };+ if (oauth["scopes"] is JsonArray scopes && scopes.Count > 0)+ body["scope"] = string.Join(' ', scopes.Select(s => s?.GetValue<string>()).Where(s => !string.IsNullOrEmpty(s)));+ using var request = new HttpRequestMessage(HttpMethod.Post, ClaudeTokenUrl)+ {+ Content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json")+ };+ using var response = await WidgetHttp.Client.SendAsync(request, token).ConfigureAwait(false);+ if (!response.IsSuccessStatusCode)+ {+ _renewFailedAt = DateTime.Now;+ System.Diagnostics.Trace.TraceWarning("Claude sign-in renewal failed: {0}", (int)response.StatusCode);+ return false;+ }+ using var json = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(token).ConfigureAwait(false), cancellationToken: token).ConfigureAwait(false);+ var answer = json.RootElement;+ if (!answer.TryGetProperty("access_token", out var access) || access.ValueKind != JsonValueKind.String+ || !answer.TryGetProperty("expires_in", out var lifetime) || lifetime.ValueKind != JsonValueKind.Number)+ {+ _renewFailedAt = DateTime.Now;+ return false;+ }+ oauth["accessToken"] = access.GetString();+ if (answer.TryGetProperty("refresh_token", out var nextRefresh) && nextRefresh.ValueKind == JsonValueKind.String)+ oauth["refreshToken"] = nextRefresh.GetString();+ oauth["expiresAt"] = nowMs + (long)(lifetime.GetDouble() * 1000);+ if (answer.TryGetProperty("refresh_token_expires_in", out var refreshLifetime) && refreshLifetime.ValueKind == JsonValueKind.Number)+ oauth["refreshTokenExpiresAt"] = nowMs + (long)(refreshLifetime.GetDouble() * 1000);+ if (answer.TryGetProperty("scope", out var granted) && granted.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(granted.GetString()))+ oauth["scopes"] = new JsonArray(granted.GetString()!.Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(s => (JsonNode?)s).ToArray());++ // Written beside it first and then swapped in, so Claude Code never reads a half-written file.+ var temporary = path + ".qidock-renew";+ await File.WriteAllTextAsync(temporary, root.ToJsonString(), token).ConfigureAwait(false);+ File.Move(temporary, path, overwrite: true);+ return true;+ }+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException or IOException or UnauthorizedAccessException or InvalidOperationException or FormatException)+ {+ if (ex is TaskCanceledException && token.IsCancellationRequested) throw;+ _renewFailedAt = DateTime.Now;+ System.Diagnostics.Trace.TraceWarning("Claude sign-in renewal failed: {0}", ex.GetType().Name);+ return false;+ }+ finally+ {+ RenewLock.Release();+ }+ }++ private static (string AccessToken, DateTime? ExpiresAt, string? Plan)? ReadClaudeCredentials()+ {+ var path = ClaudeCredentialsPath();if (!File.Exists(path)) return null;try{diff --git a/Widgets/AiLimitsWidget.cs b/Widgets/AiLimitsWidget.csindex 2f29d48..d6a4025 100644--- a/Widgets/AiLimitsWidget.cs+++ b/Widgets/AiLimitsWidget.cs@@ -52,6 +52,7 @@ public sealed class AiLimitsWidget : DockWidget_timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMinutes(1) };_timer.Tick += (_, _) => _ = RefreshAsync(false);UiText.Current.PropertyChanged += (_, _) => Render();+ _usage = _service.Cached;Render();}diff --git a/Widgets/MediaWidget.cs b/Widgets/MediaWidget.csindex 50a4b37..758a08c 100644--- a/Widgets/MediaWidget.cs+++ b/Widgets/MediaWidget.cs@@ -34,6 +34,7 @@ public sealed partial class MediaWidget : DockWidgetprivate bool _live = true;private bool _playing;private string? _thumbnailKey;+ private string? _artSignature; // which picture the cover shows, so an unchanged one is not redrawnprivate string _album = "";public MediaWidget()@@ -245,12 +246,14 @@ public sealed partial class MediaWidget : DockWidget_next.IsEnabled = playback?.Controls?.IsNextEnabled != false;_album = properties?.AlbumTitle ?? "";+ // Browsers first send their own logo as the cover and the real one a moment later for the same+ // song, so the cover is read again on every change (and once more shortly after a new song).var key = $"{title}|{artist}|{properties?.AlbumTitle}";- if (key != _thumbnailKey)- {- _thumbnailKey = key;- await LoadArtworkAsync(properties?.Thumbnail, version);- }+ var newSong = key != _thumbnailKey;+ _thumbnailKey = key;+ await LoadArtworkAsync(properties?.Thumbnail, version, newSong);+ if (version != _refreshVersion) return;+ if (newSong) RefreshAgainSoon();SetVisible(true);UpdateProgressTimer();if (CardOpen) FillCard();@@ -261,11 +264,25 @@ public sealed partial class MediaWidget : DockWidget}}- private async Task LoadArtworkAsync(Windows.Storage.Streams.IRandomAccessStreamReference? reference, int version)+ private void RefreshAgainSoon()+ {+ var timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(2) };+ timer.Tick += (_, _) =>+ {+ timer.Stop();+ _ = RefreshAsync();+ };+ timer.Start();+ }++ private async Task LoadArtworkAsync(Windows.Storage.Streams.IRandomAccessStreamReference? reference, int version, bool newSong){if (reference is null){+ // A player may leave the cover out for a moment (pausing); the last one stays for the same song.+ if (!newSong) return;_art.Source = null;+ _artSignature = null;TintCard(null);return;}@@ -278,6 +295,10 @@ public sealed partial class MediaWidget : DockWidgetawait source.CopyToAsync(memory);memory.Position = 0;if (version != _refreshVersion) return;+ // The same picture again: nothing to redraw.+ var signature = Convert.ToHexString(System.Security.Cryptography.SHA1.HashData(memory.GetBuffer().AsSpan(0, (int)memory.Length)));+ if (signature == _artSignature && _art.Source is not null) return;+ _artSignature = signature;var image = new BitmapImage();image.BeginInit();@@ -304,6 +325,7 @@ public sealed partial class MediaWidget : DockWidget{_playing = false;_thumbnailKey = null;+ _artSignature = null;_art.Source = null;_album = "";TintCard(null);diff --git a/Widgets/ProfileWidget.cs b/Widgets/ProfileWidget.csindex f05cb62..3c1071a 100644--- a/Widgets/ProfileWidget.cs+++ b/Widgets/ProfileWidget.cs@@ -1,22 +1,32 @@using System.Windows;using System.Windows.Controls;+using System.Windows.Media;using QiDock.Models;using QiDock.Services;namespace QiDock.Widgets;/// <summary>-/// The active widget profile ("İş", "Kod"…) as a tile; a click opens the profile menu (switch, new, rename, remove).-/// The menu itself is built by the dock window, so it keeps the dock up while it is open.+/// The active widget profile ("İş", "Kod"…) as a tile; a click opens the profiles card (switch, new, rename, remove,+/// edit this profile's widgets). The card opens like every other widget's card: it grows out of the dock./// </summary>public sealed class ProfileWidget : DockWidget{+ /// <summary>Preset names offered for a new profile or a rename.</summary>+ private static readonly string[] PresetNames = ["ProfileWork", "ProfileCode", "ProfileHome", "ProfileFocus", "ProfileGame", "ProfileSchool", "ProfileCreative", "ProfileTools", "ProfileDefault"];+private readonly Button _tile;private readonly TextBlock _name;private readonly TextBlock _caption;+ private readonly WidgetPopup _popup;++ /// <summary>Which name list is unfolded in the card: none, the new-profile names or the rename names.</summary>+ private enum Fold { None, Create, Rename }+ private Fold _fold;- /// <summary>Raised on a click; the argument is the tile to anchor the menu to.</summary>- public event EventHandler<FrameworkElement>? MenuRequested;+ /// <summary>Set by the bar: whether its widgets are being arranged, and the switch for it.</summary>+ internal Func<bool>? IsEditing { get; set; }+ internal Action? ToggleEditing { get; set; }public ProfileWidget(){@@ -31,21 +41,178 @@ public sealed class ProfileWidget : DockWidgetvar row = new StackPanel { Orientation = Orientation.Horizontal };row.Children.Add(icon);row.Children.Add(text);- _tile = Ui.Tile(row, (sender, _) => MenuRequested?.Invoke(this, (FrameworkElement)sender));+ _tile = Ui.Tile(row, (_, _) => Toggle());+ _popup = new WidgetPopup(_tile);+ _popup.Closed += (_, _) => _fold = Fold.None;UiText.Current.PropertyChanged += (_, _) => Render();Render();}public override string Id => WidgetIds.Profile;public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();- public override void ApplySettings(WidgetSettings settings) => Render();+ public override void Stop() => _popup.Close();++ public override void ApplySettings(WidgetSettings settings)+ {+ Render();+ if (_popup.IsOpen) BuildCard();+ }private void Render(){var profiles = Current.EffectiveProfiles;_caption.Text = UiText.Get("ProfileCaption");_name.Text = profiles[Current.EffectiveActiveProfile].Name;- _tile.ToolTip = UiText.Get("ProfileTileHint");+ _tile.ToolTip = _popup?.IsOpen == true ? null : UiText.Get("ProfileTileHint");+ }++ private void Toggle()+ {+ if (!_popup.IsOpen)+ {+ _fold = Fold.None;+ BuildCard();+ }+ _popup.Toggle();+ }++ private void BuildCard()+ {+ var settings = Current;+ var profiles = settings.EffectiveProfiles;+ var active = settings.EffectiveActiveProfile;+ var root = new StackPanel();+ root.Children.Add(Ui.Header(UiText.Get("ProfilesTitle"), _popup.Close));++ for (var i = 0; i < profiles.Count; i++)+ {+ var index = i;+ var line = new DockPanel();+ if (index == active)+ {+ var check = Ui.Icon("IconCheck", 13, brushKey: "WidgetAccent", stroke: 2.4);+ check.Margin = new Thickness(10, 0, 0, 0);+ DockPanel.SetDock(check, Dock.Right);+ line.Children.Add(check);+ }+ if (index < 9)+ {+ var keys = Ui.Text(UiText.Format("ProfileShortcut", index + 1), 10.5, brushKey: "TextSecondary");+ keys.Margin = new Thickness(10, 0, 0, 0);+ DockPanel.SetDock(keys, Dock.Right);+ line.Children.Add(keys);+ }+ line.Children.Add(Ui.Text(profiles[index].Name, 13, index == active ? FontWeights.SemiBold : FontWeights.Normal));+ root.Children.Add(Row(line, () =>+ {+ _popup.Close();+ if (index != Current.EffectiveActiveProfile) UpdateSettings(s => s.SwitchProfile(index));+ Ui.ShowHud("IconLayout", profiles[index].Name);+ }));+ }++ root.Children.Add(Divider());+ var taken = profiles.Select(p => p.Name).ToHashSet(StringComparer.CurrentCultureIgnoreCase);++ root.Children.Add(Row(Action("IconPlus", UiText.Get("ProfileNewMenu"), _fold == Fold.Create), () => Unfold(Fold.Create)));+ if (_fold == Fold.Create)+ {+ var names = PresetNames.Select(UiText.Get).Where(name => !taken.Contains(name))+ .Append(UiText.Format("ProfileNew", profiles.Count + 1));+ root.Children.Add(Chips(names.Select(name => (name, true, false)), name =>+ {+ _popup.Close();+ UpdateSettings(s => s.AddProfile(name));+ Ui.ShowHud("IconLayout", UiText.Format("ProfileCreated", name));+ }));+ }++ root.Children.Add(Row(Action("IconEdit", UiText.Get("ProfileRename"), _fold == Fold.Rename), () => Unfold(Fold.Rename)));+ if (_fold == Fold.Rename)+ {+ var current = profiles[active].Name;+ root.Children.Add(Chips(PresetNames.Select(UiText.Get).Select(name => (name, !taken.Contains(name) || name == current, name == current)), name =>+ {+ _popup.Close();+ UpdateSettings(s => s.RenameProfile(active, name));+ }));+ }++ var remove = Row(Action("IconClose", UiText.Format("ProfileRemoveNamed", profiles[active].Name), null), () =>+ {+ _popup.Close();+ UpdateSettings(s => s.RemoveProfile(active));+ });+ remove.IsEnabled = profiles.Count > 1;+ root.Children.Add(remove);++ root.Children.Add(Divider());+ var editing = IsEditing?.Invoke() == true;+ root.Children.Add(Row(Action("IconLayout", UiText.Get(editing ? "MenuEditDone" : "ProfileEditWidgets"), null), () =>+ {+ _popup.Close();+ ToggleEditing?.Invoke();+ }));++ _popup.SetContent(root, 300);+ }++ private void Unfold(Fold fold)+ {+ _fold = _fold == fold ? Fold.None : fold;+ BuildCard();+ }++ private static Button Row(UIElement content, Action click)+ {+ var button = new Button { Content = content };+ button.SetResourceReference(FrameworkElement.StyleProperty, "WidgetRowButton");+ button.Click += (_, _) => click();+ return button;+ }++ /// <summary>An action line: icon, label and, for the ones that unfold a name list, a chevron that turns.</summary>+ private static DockPanel Action(string iconKey, string label, bool? unfolded)+ {+ var line = new DockPanel();+ var icon = Ui.Icon(iconKey, 14);+ icon.Margin = new Thickness(0, 0, 10, 0);+ DockPanel.SetDock(icon, Dock.Left);+ line.Children.Add(icon);+ if (unfolded is { } open)+ {+ var chevron = Ui.Icon("IconChevronRight", 12, brushKey: "TextSecondary");+ chevron.RenderTransformOrigin = new Point(0.5, 0.5);+ chevron.RenderTransform = new RotateTransform(open ? 90 : 0);+ DockPanel.SetDock(chevron, Dock.Right);+ line.Children.Add(chevron);+ }+ line.Children.Add(Ui.Text(label, 13));+ return line;+ }++ /// <summary>The unfolded names as small pills under their action; the current one is marked, taken ones are dimmed.</summary>+ private static WrapPanel Chips(IEnumerable<(string Name, bool Enabled, bool Current)> names, Action<string> pick)+ {+ var panel = new WrapPanel { Margin = new Thickness(34, 2, 0, 6) };+ foreach (var (name, enabled, current) in names)+ {+ var chip = Ui.Pill(name, (_, _) => pick(name), current ? "IconCheck" : null);+ chip.Margin = new Thickness(0, 0, 6, 6);+ chip.IsEnabled = enabled && !current;+ if (!enabled) chip.Opacity = 0.4;+ panel.Children.Add(chip);+ }+ return panel;+ }++ private static Border Divider()+ {+ var line = new Border { Height = 1, Margin = new Thickness(4, 6, 4, 6) };+ line.SetResourceReference(Border.BackgroundProperty, "MenuStroke");+ return line;}}diff --git a/Widgets/WidgetBar.cs b/Widgets/WidgetBar.csindex 196c9b4..97c996e 100644--- a/Widgets/WidgetBar.cs+++ b/Widgets/WidgetBar.cs@@ -34,9 +34,6 @@ public sealed class WidgetBar : StackPanel, IDisposable/// <summary>Right-click on a profile tab: the argument is the profile index and the tab.</summary>public event EventHandler<(int Index, FrameworkElement Anchor)>? ProfileMenuRequested;- /// <summary>The profile tile was clicked; the argument is the tile.</summary>- public event EventHandler<FrameworkElement>? ProfilesRequested;-/// <summary>Profile tabs ("Varsayılan", "İş", "+"), shown under the bar by its window.</summary>public StackPanel ProfileStrip { get; } = new() { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Center };@@ -114,7 +111,11 @@ public sealed class WidgetBar : StackPanel, IDisposablewidget.LayoutChanged += (_, _) => LayoutInvalidated?.Invoke(this, EventArgs.Empty);widget.SettingsRequested += (_, _) => SettingsRequested?.Invoke(this, EventArgs.Empty);widget.SettingsUpdateRequested += (_, change) => SettingsEdited?.Invoke(this, change(_settings));- if (widget is ProfileWidget profile) profile.MenuRequested += (_, anchor) => ProfilesRequested?.Invoke(this, anchor);+ if (widget is ProfileWidget profile)+ {+ profile.IsEditing = () => IsEditing;+ profile.ToggleEditing = () => SetEditing(!IsEditing);+ }}SizeChanged += (_, e) =>{