Skip to content

A macOS-style dock, widget bar and desktop widgets for Windows (WPF, .NET 10)

Apps screen, Files window, notch browser, glass surfaces and updater

QiDock contributorse6f8ea40300d
diff --git a/App.xaml.cs b/App.xaml.cs
index 4a11b9d..fd0221a 100644
--- a/App.xaml.cs
+++ b/App.xaml.cs
@@ -52,6 +52,14 @@ public partial class App : Application
DesktopWidgets.DeskSheet.Render(sheet, () => Preferences.Current.WidgetOptions, () => Shutdown());
return;
}
+ if (e.Args is ["--render-apps", var appsPicture])
+ {
+ // The app screen as the low-memory (software) drawing shows it, saved as a picture at the screen's scale.
+ ShutdownMode = ShutdownMode.OnExplicitShutdown;
+ System.Windows.Media.RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;
+ AppGridWindow.RenderTo(appsPicture, () => Shutdown());
+ return;
+ }
if (e.Args is ["--snapshot-dock", var snapshots]) DockSnapshotFolder = snapshots;
if (e.Args is ["--snapshot-cycle", var cycle]) { DockSnapshotFolder = cycle; DockCycle = true; }
if (e.Args is ["--claude-activity", var report])
@@ -289,7 +297,17 @@ public partial class App : Application
try { using var old = Process.GetProcessById(previousId); old.WaitForExit(15000); }
catch (ArgumentException) { } // already gone
}
+ string? filesRequest = e.Args is ["--files", .. var filesArgs] ? (filesArgs.Length > 0 ? filesArgs[0] : "") : null;
_instanceMutex = new Mutex(initiallyOwned: true, name: "Local\\QiDock.Singleton", out var createdNew);
+ if (!createdNew && filesRequest is not null)
+ {
+ // "QiDock.exe --files [folder]" while QiDock runs: the running copy opens its Files window.
+ Files.FilesLauncher.Signal(filesRequest);
+ _instanceMutex.Dispose();
+ _instanceMutex = null;
+ Shutdown();
+ return;
+ }
if (!createdNew)
{
MessageBox.Show(UiText.Get("AlreadyRunning"), "QiDock", MessageBoxButton.OK, MessageBoxImage.Information);
@@ -340,6 +358,9 @@ public partial class App : Application
MainWindow = window;
AppLog.Write($"Başladı (önceki ana pencere: {firstWindow}, kendiliğinden atanan: {assigned})");
window.Show();
+ Files.FilesLauncher.Listen(Dispatcher);
+ if (filesRequest is not null)
+ Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.ApplicationIdle, () => Files.FilesWindow.Open(filesRequest.Length > 0 ? filesRequest : null));
}
/// <summary>Whether this run draws on the processor (low-memory mode was on at start).</summary>
diff --git a/AppGrid.cs b/AppGrid.cs
index abb55f3..4d45198 100644
--- a/AppGrid.cs
+++ b/AppGrid.cs
@@ -1,4 +1,4 @@
-using System.IO;
+using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows;
@@ -173,23 +173,70 @@ internal static class AppUsage
}
/// <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.
+/// Every installed app in a glass panel over the blurred desktop: a large search pill on top, category chips, the
+/// user's folders and most used apps first, then every app from A to Z below a thin line. Scroll with the wheel,
+/// the touchpad or the keys; type to search; drop an icon on another to make a folder. Only the rows in view (and a
+/// few around them) are built, and icons stay cached between openings.
/// </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");
+ // Around the panel the screen goes almost black, as behind a sheet of dark glass.
+ private static readonly Brush Dim = Ui.Solid("#EB040405");
+ private static readonly Brush PanelFill = Vertical("#FA202023", "#FA161618");
+ private static readonly Brush PanelEdge = Vertical("#38FFFFFF", "#17FFFFFF");
+ private static readonly Brush PillFill = Vertical("#FF3B3B3F", "#FF1B1B1E");
+ private static readonly Brush PillEdge = Vertical("#66FFFFFF", "#1AFFFFFF");
+ private static readonly Brush PillText = Ui.Solid("#FFDCDCDE");
+ private static readonly Brush PillGlyph = Ui.Solid("#FFBDBDC1");
+ private static readonly Brush SortFill = Ui.Solid("#80FFFFFF");
+ private static readonly Brush SortHover = Ui.Solid("#B3FFFFFF");
+ private static readonly Brush SortGlyph = Ui.Solid("#FF26262A");
+ private static readonly Brush ChipFill = Ui.Solid("#2BFFFFFF");
+ private static readonly Brush ChipHover = Ui.Solid("#40FFFFFF");
+ private static readonly Brush ChipEdge = Ui.Solid("#1AFFFFFF");
+ private static readonly Brush ChipOn = Ui.Solid("#FFE4E4E6");
+ private static readonly Brush ChipOnText = Ui.Solid("#FF1A1A1C");
+ private static readonly Brush ChipText = Ui.Solid("#FFE8E8EA");
+ private static readonly Brush LabelText = Ui.Solid("#FFF2F2F4");
+ private static readonly Brush FolderFill = Vertical("#66FFFFFF", "#4DFFFFFF");
+ private static readonly Brush FolderEdge = Ui.Solid("#33FFFFFF");
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 Brush LineFill = Ui.Solid("#2EFFFFFF");
+ private static readonly Brush ThumbFill = Ui.Solid("#33FFFFFF");
+
+ private static Brush Vertical(string top, string bottom)
+ {
+ var brush = new LinearGradientBrush(((SolidColorBrush)Ui.Solid(top)).Color, ((SolidColorBrush)Ui.Solid(bottom)).Color, 90);
+ brush.Freeze();
+ return brush;
+ }
+
+ private readonly double _k;
+ private readonly double _panelTop;
+ private const double GridTop = 2;
+
+ /// <summary>
+ /// How large the icons are: their size in points, and the screen pixels that covers. Icons are read at exactly
+ /// those pixels and drawn on whole pixels, so they are never scaled again (scaling them made them grainy).
+ /// </summary>
+ private static readonly (double Dip, int Pixels) IconSize = MeasureIcon();
+
+ /// <summary>Screen pixels per point on the main screen.</summary>
+ private static double ScreenScale => Application.Current?.MainWindow is { } main && PresentationSource.FromVisual(main) is not null
+ ? VisualTreeHelper.GetDpi(main).DpiScaleX
+ : VisualTreeHelper.GetDpi(new DrawingVisual()).DpiScaleX;
+
+ private static (double, int) MeasureIcon()
+ {
+ var k = Math.Clamp(SystemParameters.PrimaryScreenHeight / 1080, 0.78, 1.4);
+ var dpi = ScreenScale;
+ var pixels = (int)Math.Round(90 * k * dpi);
+ return (pixels / dpi, pixels);
+ }
+
+ private static ImageSource? ReadIcon(string id) => NotificationApps.LoadIcon(id, IconSize.Pixels, exact: true);
+ // Icons stay cached between openings (about 64 KB each) so the panel fills at once next time.
private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, ImageSource?> Icons = new(StringComparer.OrdinalIgnoreCase);
private sealed class TileParts
@@ -199,64 +246,60 @@ public sealed class AppGridWindow : OverlayWindow
public required Border Backdrop;
}
- /// <summary>A press on a tile or on the empty page, until the button goes up.</summary>
+ /// <summary>A press on a tile, until the button goes up.</summary>
private sealed class Press
{
public Point Start;
- public LaunchEntry? Entry; // a tile on the pages
+ public LaunchEntry? Entry; // a tile in the panel
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;
+ public bool Fixed; // opens, never moves (most used row, folders, filtered views)
}
/// <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 LaunchEntry Entry;
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 double _cols, _cellW, _cellH, _icon, _gridLeft;
+ private readonly Border _pill;
+ private readonly Border _panel;
+ private readonly Grid _host = new() { ClipToBounds = true, Background = Brushes.Transparent };
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 Border _line = new() { Height = 1, Background = LineFill, IsHitTestVisible = false, Visibility = Visibility.Collapsed };
+ private readonly Border _thumb = new() { Width = 4, CornerRadius = new CornerRadius(2), Background = ThumbFill, Opacity = 0, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(0, 0, 7, 0), IsHitTestVisible = false, Visibility = Visibility.Collapsed };
+ private readonly StackPanel _chips = new() { Orientation = Orientation.Horizontal };
+ private readonly ScrollViewer _chipScroll;
+ private readonly Border _sortButton;
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 Dictionary<LaunchEntry, Point> _slots = [];
+ private readonly Dictionary<string, LaunchEntry> _viewEntries = 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 List<LaunchEntry> _items = []; // the arrangement: folders and the apps outside them
+ private List<LaunchEntry> _frequent = []; // the most used apps, after the folders on top
+ private List<LaunchEntry> _order = []; // what the panel shows, in reading order
+ private string _category = AppCategories.All;
+ private double _scroll, _contentHeight, _lineY = -1, _thumbAt;
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 LaunchEntry? _selected; // the icon the arrow keys are on
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;
@@ -276,8 +319,8 @@ public sealed class AppGridWindow : OverlayWindow
}
/// <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.
+ /// Loads the app list and the first icons 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()
{
@@ -291,61 +334,200 @@ public sealed class AppGridWindow : OverlayWindow
if (ids.Count == 0) return;
var thread = new Thread(() =>
{
- foreach (var id in ids) Icons.GetOrAdd(id, key => NotificationApps.LoadIcon(key, 128));
+ foreach (var id in ids) Icons.GetOrAdd(id, ReadIcon);
}) { 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;
+ private static string L(string turkish, string english) => DesktopWidgets.Desk.L(turkish, english);
- _strip.RenderTransform = _stripShift;
- _strip.Height = Height;
- _host.Children.Add(_strip);
- _host.Children.Add(_note);
- Root.Children.Add(_host);
+#if DEBUG
+ /// <summary>Opens the app screen without taking the keyboard, waits for the icons and saves it as a picture.</summary>
+ internal static void RenderTo(string path, Action done)
+ {
+ var window = new AppGridWindow { ShowActivated = false };
+ window.Show();
+ window.Root.Opacity = 1;
+ var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(4) };
+ timer.Tick += (_, _) =>
+ {
+ timer.Stop();
+ var dpi = VisualTreeHelper.GetDpi(window);
+ var bitmap = new System.Windows.Media.Imaging.RenderTargetBitmap(
+ (int)Math.Ceiling(window.Root.ActualWidth * dpi.DpiScaleX), (int)Math.Ceiling(window.Root.ActualHeight * dpi.DpiScaleY),
+ dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
+ bitmap.Render(window.Root);
+ var png = new System.Windows.Media.Imaging.PngBitmapEncoder();
+ png.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmap));
+ using (var file = File.Create(path)) png.Save(file);
+ window.Close();
+ done();
+ };
+ timer.Start();
+ }
+#endif
- 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 += (_, _) =>
+ private AppGridWindow() : base(Dim)
+ {
+ // The screen darkens; the search pill (660 × 108) stands near the top and the glass panel (1114 wide) below
+ // it, down to just above the dock, seven columns of 90-point icons. Sizes are measured on a 1080-line screen.
+ var screenWidth = Width;
+ var screenHeight = Height;
+ _k = Math.Clamp(screenHeight / 1080, 0.78, 1.4);
+ var k = _k;
+ var pillTop = Math.Round(76 * k);
+ var pillHeight = Math.Round(108 * k);
+ var panelWidth = Math.Round(Math.Min(1114 * k, screenWidth - 80));
+ _panelTop = Math.Round(204 * k);
+ var dockRoom = Math.Max(135 * k, TaskbarReplacementSession.DockHeightDips + 40 * k);
+ var panelHeight = Math.Round(Math.Max(320, screenHeight - _panelTop - dockRoom));
+ Root.UseLayoutRounding = true; // icons on whole pixels stay sharp
+ var inner = panelWidth - 2 - 48 * k;
+ _cols = Math.Clamp(Math.Round(inner / (152 * k)), 4, 9);
+ _cellW = Math.Floor(inner / _cols);
+ _icon = IconSize.Dip;
+ _cellH = Math.Round(144 * k);
+ _gridLeft = Math.Round((panelWidth - 2 - _cols * _cellW) / 2);
+
+ // ---- Search pill ------------------------------------------------------------------------
+ _box = new TextBox
+ {
+ FontSize = 44 * k,
+ FontWeight = FontWeights.Light,
+ Background = Brushes.Transparent,
+ BorderThickness = new Thickness(0),
+ Foreground = PillText,
+ CaretBrush = PillText,
+ VerticalContentAlignment = VerticalAlignment.Center,
+ Padding = new Thickness(0)
+ };
+ var hint = new TextBlock { Text = L("Uygulamalar", "Applications"), FontSize = 44 * k, FontWeight = FontWeights.Light, Foreground = PillText, VerticalAlignment = VerticalAlignment.Center, IsHitTestVisible = false, Margin = new Thickness(2, 0, 0, 0) };
+ _box.TextChanged += (_, _) =>
{
- _page = 0;
+ hint.Visibility = _box.Text.Length == 0 ? Visibility.Visible : Visibility.Collapsed;
Refill();
- SnapStrip();
};
- box.PreviewKeyDown += (_, e) =>
+ _box.PreviewKeyDown += (_, e) =>
+ {
+ if (e.Key != Key.Enter || (_order.Count == 0 && _selected is null)) return;
+ e.Handled = true;
+ Open(_selected ?? _order[0]);
+ };
+ var pillWidth = Math.Round(Math.Min(660 * k, panelWidth));
+ var glyph = Ui.Icon("IconApps", 44 * k, PillGlyph, null, 2.2);
+ glyph.VerticalAlignment = VerticalAlignment.Center;
+ glyph.Margin = new Thickness(0, 0, 30 * k, 0);
+ var sortIcon = Ui.Icon("IconArrowUpDown", 17 * k, SortGlyph, null, 2.4);
+ sortIcon.HorizontalAlignment = HorizontalAlignment.Center;
+ sortIcon.VerticalAlignment = VerticalAlignment.Center;
+ _sortButton = new Border
+ {
+ Width = 40 * k,
+ Height = 40 * k,
+ CornerRadius = new CornerRadius(20 * k),
+ Background = SortFill,
+ VerticalAlignment = VerticalAlignment.Center,
+ Cursor = Cursors.Hand,
+ Child = sortIcon
+ };
+ _sortButton.MouseEnter += (_, _) => _sortButton.Background = SortHover;
+ _sortButton.MouseLeave += (_, _) => _sortButton.Background = SortFill;
+ _sortButton.MouseLeftButtonUp += (_, e) =>
{
- if (e.Key != Key.Enter || (_shown.Count == 0 && _selected is null)) return;
e.Handled = true;
- Open(_selected ?? _shown[0]);
+ AppCategories.SortByUse = !AppCategories.SortByUse;
+ ShowSortTip();
+ Refill();
+ };
+ ShowSortTip();
+ var text = new Grid();
+ text.Children.Add(hint);
+ text.Children.Add(_box);
+ var pillRow = new DockPanel();
+ DockPanel.SetDock(glyph, Dock.Left);
+ DockPanel.SetDock(_sortButton, Dock.Right);
+ pillRow.Children.Add(glyph);
+ pillRow.Children.Add(_sortButton);
+ pillRow.Children.Add(text);
+ _pill = new Border
+ {
+ Child = pillRow,
+ Width = pillWidth,
+ Height = pillHeight,
+ CornerRadius = new CornerRadius(pillHeight / 2),
+ Background = PillFill,
+ BorderBrush = PillEdge,
+ BorderThickness = new Thickness(1.5),
+ Padding = new Thickness(34 * k, 0, 32 * k, 0),
+ HorizontalAlignment = HorizontalAlignment.Center,
+ VerticalAlignment = VerticalAlignment.Top,
+ Margin = new Thickness(0, pillTop, 0, 0)
};
- Root.Children.Add(field);
- _dots.Margin = new Thickness(0, 0, 0, Math.Max(40, Height - (_gridTop + _rows * _cellH) - 64));
- Root.Children.Add(_dots);
+ // ---- Panel: chips on top, the icons below ---------------------------------------------
+ _chipScroll = new ScrollViewer
+ {
+ Content = _chips,
+ HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden,
+ VerticalScrollBarVisibility = ScrollBarVisibility.Disabled,
+ Focusable = false,
+ Margin = new Thickness(24 * k, 18 * k, 24 * k, 14 * k)
+ };
+ _strip.RenderTransform = _stripShift;
+ _strip.Width = panelWidth - 2;
+ _strip.Children.Add(_line);
+ _host.Children.Add(_strip);
+ _host.Children.Add(_thumb);
+ _host.Children.Add(_note);
+ _host.SizeChanged += (_, _) => Realize();
+ var body = new Grid();
+ body.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
+ body.RowDefinitions.Add(new RowDefinition());
+ body.Children.Add(_chipScroll);
+ Grid.SetRow(_host, 1);
+ body.Children.Add(_host);
+ _panel = new Border
+ {
+ Child = body,
+ Width = panelWidth,
+ Height = panelHeight,
+ CornerRadius = new CornerRadius(28 * k),
+ Background = PanelFill,
+ BorderBrush = PanelEdge,
+ BorderThickness = new Thickness(1),
+ HorizontalAlignment = HorizontalAlignment.Center,
+ VerticalAlignment = VerticalAlignment.Top,
+ Margin = new Thickness(0, _panelTop, 0, 0)
+ };
+ // The icons are cut off by the panel's rounded bottom, as in a scrolling list.
+ _host.Margin = new Thickness(0, 0, 0, 2);
+ _host.Clip = null;
+ body.ClipToBounds = false;
+ _panel.SizeChanged += (_, _) =>
+ {
+ var radius = 28 * k - 1;
+ _host.Clip = new RectangleGeometry(new Rect(0, -_chipScroll.ActualHeight, _host.ActualWidth, _host.ActualHeight + _chipScroll.ActualHeight), radius, radius);
+ };
+ Root.Children.Add(_panel);
+ Root.Children.Add(_pill);
Root.Children.Add(_folderLayer);
Root.Children.Add(_dragLayer);
+ Frost(new Rect((screenWidth - panelWidth) / 2, _panelTop, panelWidth, panelHeight));
- _edgeTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(550) };
- _edgeTimer.Tick += (_, _) => FlipWhileDragging();
+ // Holding a dragged icon near the top or bottom of the panel scrolls it.
+ _edgeTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(30) };
+ _edgeTimer.Tick += (_, _) =>
+ {
+ if (_drag is null || _edgeDirection == 0)
+ {
+ _edgeTimer.Stop();
+ return;
+ }
+ ScrollTo(_scroll + _edgeDirection * 14, animate: false);
+ DragTo(_lastPoint);
+ };
PreviewMouseLeftButtonDown += OnPressDown;
PreviewMouseMove += OnPressMove;
@@ -354,9 +536,9 @@ public sealed class AppGridWindow : OverlayWindow
PreviewMouseWheel += (_, e) =>
{
// In an open folder the wheel scrolls the folder's own list.
- if (_openFolder is not null) return;
+ if (_openFolder is not null || _drag is not null) return;
e.Handled = true;
- Wheel(-e.Delta);
+ ScrollTo(_scroll - e.Delta * 0.9);
};
PreviewKeyDown += OnKey;
PreviewMouseRightButtonUp += OnMenu;
@@ -365,40 +547,86 @@ public sealed class AppGridWindow : OverlayWindow
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).
+ // Rebuilding 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;
+ /// <summary>
+ /// The panel becomes frosted glass: the desktop picture behind it, softened, with its own colours (as the
+ /// widgets show it) under a light veil. Without a desktop picture, what is on the screen behind it, blurred
+ /// (read here, before the window shows). Where neither can be had it keeps its solid fill.
+ /// </summary>
+ private void Frost(Rect panel)
+ {
+ var veil = Color.FromArgb(0x5C, 0x0C, 0x0C, 0x10);
+ if (Services.Widgets.GlassLook.Surface(new Rect(panel.Size), panel, veil, sheen: true, frost: false) is { } wallpaper)
+ {
+ _panel.Background = wallpaper;
+ return;
+ }
+ var dpi = ScreenScale;
+ const double Margin = 24; // read a little more than the window, so the blur at the edges has something to blend
+ var screenPixels = new Rect(0, 0, Math.Round(SystemParameters.PrimaryScreenWidth * dpi), Math.Round(SystemParameters.PrimaryScreenHeight * dpi));
+ var wanted = new Rect((Left - Margin) * dpi, (Top - Margin) * dpi, (Width + 2 * Margin) * dpi, (Height + 2 * Margin) * dpi);
+ wanted.Intersect(screenPixels);
+ if (wanted.IsEmpty) return;
+ var area = new Int32Rect((int)wanted.X, (int)wanted.Y, (int)wanted.Width, (int)wanted.Height);
+ if (ScreenGlass.Capture(area, Colors.Transparent) is not { } glass) return;
+ // Where the picture lies, in the window's own points.
+ var picture = new Rect(area.X / dpi - Left, area.Y / dpi - Top, area.Width / dpi, area.Height / dpi);
+ _panel.Background = Glass(glass, picture, panel, Color.FromArgb(0xA6, 0x16, 0x16, 0x19));
+ }
+
+ private static Brush Glass(ImageSource glass, Rect picture, Rect element, Color veil)
+ {
+ var drawing = new DrawingGroup();
+ // Drawn in the element's own points: the picture shifted by where the element stands, the veil over it.
+ drawing.Children.Add(new ImageDrawing(glass, new Rect(picture.X - element.X, picture.Y - element.Y, picture.Width, picture.Height)));
+ drawing.Children.Add(new GeometryDrawing(new SolidColorBrush(veil), null, new RectangleGeometry(new Rect(0, 0, element.Width, element.Height))));
+ var box = new Rect(0, 0, element.Width, element.Height);
+ var brush = new DrawingBrush(drawing)
+ {
+ Stretch = Stretch.Fill,
+ ViewboxUnits = BrushMappingMode.Absolute, Viewbox = box,
+ ViewportUnits = BrushMappingMode.Absolute, Viewport = box
+ };
+ RenderOptions.SetBitmapScalingMode(brush, BitmapScalingMode.Linear);
+ brush.Freeze();
+ return brush;
+ }
- protected override bool IsBackground(object source) => ReferenceEquals(source, _strip) || ReferenceEquals(source, _host);
+ protected override void OnShown()
+ {
+ _box.Focus();
+ // The dock and the menu bar stay on top of the darkened screen, as in macOS.
+ foreach (Window window in Application.Current.Windows)
+ {
+ if (window is OverlayWindow || !window.IsVisible || !window.Topmost) continue;
+ if (PresentationSource.FromVisual(window) is HwndSource source)
+ SetWindowPos(source.Handle, -1 /* topmost */, 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010 /* no size, no move, no activate */);
+ }
+ }
- protected override void OnShown() => _box.Focus();
+ [System.Runtime.InteropServices.DllImport("user32.dll")]
+ private static extern bool SetWindowPos(nint window, nint after, int x, int y, int width, int height, uint flags);
/// <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.
+ /// The pill and the panel rise a few points into place while they fade in. Nothing is scaled, so the icons are
+ /// as sharp while it moves as after.
/// </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 });
+ foreach (var part in new FrameworkElement[] { _pill, _panel })
+ {
+ var shift = new TranslateTransform(0, Math.Round(10 * _k));
+ part.RenderTransform = shift;
+ var rise = new DoubleAnimation(0, TimeSpan.FromMilliseconds(220)) { EasingFunction = Motion.Out };
+ rise.Completed += (_, _) => part.RenderTransform = Transform.Identity;
+ shift.BeginAnimation(TranslateTransform.YProperty, rise);
+ }
}
protected override void OnDismissing()
@@ -419,23 +647,17 @@ public sealed class AppGridWindow : OverlayWindow
_box.Clear();
return true;
}
+ if (_category != AppCategories.All)
+ {
+ SetCategory(AppCategories.All);
+ 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;
- });
- }
+ private void ShowSortTip() => _sortButton.ToolTip = AppCategories.SortByUse
+ ? L("Kullanıma göre sıralı (tıklayınca ada göre)", "Sorted by use (click for name)")
+ : L("Ada göre sıralı (tıklayınca kullanıma göre)", "Sorted by name (click for use)");
// ───────────────────────── Content ─────────────────────────
@@ -444,224 +666,255 @@ public sealed class AppGridWindow : OverlayWindow
_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)
+ // Two rows on top with the folders, as many as the folders leave room for.
+ .Take(Math.Max((int)_cols, 2 * (int)_cols - _items.Count(e => e.IsFolder)))
.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();
+ _viewEntries.Clear();
+ BuildChips();
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()
+ /// <summary>A search or a category: a view of the apps, not the arrangement (icons stay put there).</summary>
+ private bool Filtered => Searching || _category != AppCategories.All;
+
+ /// <summary>"Tümü" and one chip per category that has apps.</summary>
+ private void BuildChips()
+ {
+ _chips.Children.Clear();
+ var present = _known.Values.Select(AppCategories.Of).ToHashSet();
+ if (_category != AppCategories.All && !present.Contains(_category)) _category = AppCategories.All;
+ foreach (var id in new[] { AppCategories.All }.Concat(AppCategories.Order.Where(present.Contains)))
+ {
+ var on = id == _category;
+ var label = new TextBlock { Text = AppCategories.Name(id), FontSize = 16.5 * _k, Foreground = on ? ChipOnText : ChipText, FontWeight = FontWeights.Medium };
+ var chip = new Border
+ {
+ Child = label,
+ CornerRadius = new CornerRadius(18 * _k),
+ Padding = new Thickness(17 * _k, 6 * _k, 17 * _k, 7 * _k),
+ Margin = new Thickness(0, 0, 10 * _k, 0),
+ Background = on ? ChipOn : ChipFill,
+ BorderBrush = on ? ChipOn : ChipEdge,
+ BorderThickness = new Thickness(1),
+ Cursor = Cursors.Hand,
+ Tag = id
+ };
+ if (!on)
+ {
+ chip.MouseEnter += (_, _) => chip.Background = ChipHover;
+ chip.MouseLeave += (_, _) => chip.Background = ChipFill;
+ }
+ chip.MouseLeftButtonUp += (_, e) =>
+ {
+ e.Handled = true;
+ SetCategory(id);
+ };
+ _chips.Children.Add(chip);
+ }
+ }
+
+ private void SetCategory(string id)
+ {
+ if (_category == id) return;
+ _category = id;
+ BuildChips();
+ Refill();
+ if (_chips.Children.OfType<Border>().FirstOrDefault(c => Equals(c.Tag, id)) is { } chip) chip.BringIntoView();
+ }
+
+ private void NextCategory(int step)
+ {
+ var ids = _chips.Children.OfType<Border>().Select(c => (string)c.Tag).ToList();
+ if (ids.Count == 0) return;
+ var at = ids.IndexOf(_category);
+ SetCategory(ids[((at + step) % ids.Count + ids.Count) % ids.Count]);
+ }
+
+ private string NameOfApp(string id) => _known.TryGetValue(id, out var app) ? app.Name : "";
+
+ private List<LaunchEntry> Sorted(IEnumerable<LaunchEntry> entries)
+ {
+ if (!AppCategories.SortByUse)
+ return entries.OrderBy(e => NameOfApp(e.App!), StringComparer.CurrentCultureIgnoreCase).ToList();
+ var scores = AppUsage.Scores();
+ return entries.OrderByDescending(e => scores.GetValueOrDefault(e.App!)).ThenBy(e => NameOfApp(e.App!), StringComparer.CurrentCultureIgnoreCase).ToList();
+ }
+
+ /// <summary>An app wherever it sits (inside a folder too) as its own tile, for searches and categories.</summary>
+ private LaunchEntry ViewEntry(string id) =>
+ _items.FirstOrDefault(e => !e.IsFolder && string.Equals(e.App, id, StringComparison.OrdinalIgnoreCase))
+ ?? (_viewEntries.TryGetValue(id, out var known) ? known : _viewEntries[id] = new LaunchEntry { App = id });
+
+ private IEnumerable<string> AllApps() => _items.SelectMany(e => e.IsFolder ? e.Apps! : [e.App!]);
+
+ /// <summary>Works out what the panel shows and where every icon stands; then builds the rows in view.</summary>
+ private void Refill(bool keepScroll = false)
{
Select(null);
+ _slots.Clear();
+ _order = [];
+ _lineY = -1;
+ var y = GridTop;
+ var column = 0;
+ void Put(LaunchEntry entry)
+ {
+ if (column == (int)_cols)
+ {
+ column = 0;
+ y += _cellH;
+ }
+ _slots[entry] = new Point(_gridLeft + column * _cellW, y);
+ _order.Add(entry);
+ column++;
+ }
+ void EndRow()
+ {
+ if (column == 0) return;
+ column = 0;
+ y += _cellH;
+ }
+
var query = _box.Text.Trim();
- if (query.Length == 0)
+ if (query.Length > 0)
+ {
+ foreach (var id in AllApps().Where(id => _known.TryGetValue(id, out var app) && Matches(app.Name, query)).Distinct(StringComparer.OrdinalIgnoreCase))
+ Put(ViewEntry(id));
+ }
+ else if (_category != AppCategories.All)
{
- _shown = _items;
+ foreach (var entry in Sorted(AllApps().Distinct(StringComparer.OrdinalIgnoreCase)
+ .Where(id => _known.TryGetValue(id, out var app) && AppCategories.Of(app) == _category).Select(ViewEntry)))
+ Put(entry);
}
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();
+ var top = _items.Where(e => e.IsFolder).Concat(_frequent).ToList();
+ foreach (var entry in top) Put(entry);
+ EndRow();
+ var rest = Sorted(_items.Where(e => !e.IsFolder));
+ if (top.Count > 0 && rest.Count > 0)
+ {
+ _lineY = y + 14 * _k;
+ y += 30 * _k;
+ }
+ foreach (var entry in rest) Put(entry);
}
- _note.Text = _known.Count == 0 ? UiText.Get("AppGridLoading") : _shown.Count == 0 ? UiText.Get("AppGridNoMatch") : "";
- Arrange(false);
+ EndRow();
+ _contentHeight = y + 10;
+ _note.Text = _known.Count == 0 ? UiText.Get("AppGridLoading") : _order.Count == 0 ? UiText.Get("AppGridNoMatch") : "";
+ foreach (var gone in _tiles.Keys.Where(k => !_slots.ContainsKey(k)).ToList()) Forget(gone);
+ ScrollTo(keepScroll ? _scroll : 0, animate: 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()
+ private double ViewHeight => _host.ActualHeight > 0 ? _host.ActualHeight : Math.Max(200, _panel.Height - 80);
+
+ private double MaxScroll => Math.Max(0, _contentHeight - ViewHeight);
+
+ private void ScrollTo(double target, bool animate = true)
{
- var lead = Lead;
- var list = new List<LaunchEntry?>(lead + _shown.Count + 1);
- if (lead > 0)
+ target = Math.Clamp(target, 0, MaxScroll);
+ if (PresentationSource.FromVisual(this) is { } source) // on a whole screen pixel, or every icon is drawn between two
{
- list.AddRange(_frequent);
- while (list.Count < lead) list.Add(null);
+ var dpi = source.CompositionTarget.TransformToDevice.M22;
+ target = Math.Min(Math.Round(target * dpi) / dpi, MaxScroll);
}
- if (_drag is null || _drag.Folder is not null)
+ _scroll = target;
+ Realize();
+ if (!animate)
{
- list.AddRange(_shown);
- return list;
+ _stripShift.BeginAnimation(TranslateTransform.YProperty, null);
+ _stripShift.Y = -target;
+ return;
}
- 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);
+ _stripShift.BeginAnimation(TranslateTransform.YProperty, new DoubleAnimation(-target, TimeSpan.FromMilliseconds(200)) { EasingFunction = Motion.Out });
}
/// <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.
+ /// Builds the tiles of the rows in view and two rows around them, and lets the others go. Tiles are kept between
+ /// calls, so with <paramref name="animate"/> the ones whose place changed glide there.
/// </summary>
- private void Arrange(bool animate)
+ private void Realize(bool animate = false)
{
- var list = Display();
- _pageCount = Math.Max(1, (list.Count + PerPage - 1) / PerPage);
- _strip.Width = _pageCount * Width;
- if (_page >= _pageCount)
+ if (_closed) return;
+ _strip.Height = Math.Max(_contentHeight, ViewHeight);
+ var from = _scroll - _cellH * 2;
+ var to = _scroll + ViewHeight + _cellH * 2;
+ foreach (var gone in _tiles.Keys.Where(k => !_slots.TryGetValue(k, out var at) || at.Y + _cellH < from || at.Y > to).ToList())
{
- _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);
+ if (_drag is not null && ReferenceEquals(gone, _drag.Entry)) continue;
+ Forget(gone);
}
var pending = new List<(Image, string)>();
- for (var i = first; i < last; i++)
+ foreach (var entry in _order)
{
- if (list[i] is not { } entry) continue;
- var to = Slot(i);
+ var at = _slots[entry];
+ if (at.Y + _cellH < from || at.Y > to) continue;
if (!_tiles.TryGetValue(entry, out var tile))
{
tile = MakeTile(entry, pending);
if (ReferenceEquals(entry, _selected)) Highlight(tile, true);
+ if (_drag is not null && ReferenceEquals(entry, _drag.Entry)) tile.Element.Opacity = 0.25;
_tiles[entry] = tile;
_strip.Children.Add(tile.Element);
- Canvas.SetLeft(tile.Element, to.X);
- Canvas.SetTop(tile.Element, to.Y);
+ Canvas.SetLeft(tile.Element, at.X);
+ Canvas.SetTop(tile.Element, at.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);
+ var old = new Point(Canvas.GetLeft(tile.Element), Canvas.GetTop(tile.Element));
+ if (old == at) continue;
+ Canvas.SetLeft(tile.Element, at.X);
+ Canvas.SetTop(tile.Element, at.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 });
+ shift.BeginAnimation(TranslateTransform.XProperty, new DoubleAnimation(old.X - at.X + shift.X, 0, TimeSpan.FromMilliseconds(240)) { EasingFunction = Motion.Out });
+ shift.BeginAnimation(TranslateTransform.YProperty, new DoubleAnimation(old.Y - at.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);
- }
+ _line.Visibility = _lineY >= 0 ? Visibility.Visible : Visibility.Collapsed;
+ _line.Width = _cols * _cellW - 8;
+ Canvas.SetLeft(_line, _gridLeft + 4);
+ Canvas.SetTop(_line, _lineY);
- private void GoTo(int page, bool animate = true)
- {
- _page = Math.Clamp(page, 0, _pageCount - 1);
- _neighborsReady = true;
- PaintDots();
- if (!animate)
+ // A thin bar at the right shows where in the list the panel is.
+ var view = ViewHeight;
+ if (_contentHeight <= view + 1)
{
- SnapStrip();
- Arrange(false);
+ _thumb.Visibility = Visibility.Collapsed;
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)
+ _thumb.Visibility = Visibility.Visible;
+ // Shown only while the list moves, then it fades away.
+ if (_scroll != _thumbAt)
+ _thumb.BeginAnimation(OpacityProperty, new DoubleAnimationUsingKeyFrames
{
- 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) =>
+ KeyFrames =
{
- 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;
- }
+ new LinearDoubleKeyFrame(1, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(80))),
+ new LinearDoubleKeyFrame(1, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(900))),
+ new LinearDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(1300)))
+ }
+ });
+ _thumb.Height = Math.Max(36, view * view / _contentHeight);
+ _thumb.Margin = new Thickness(0, (view - _thumb.Height) * (_scroll / MaxScroll), 7, 0);
+ _thumbAt = _scroll;
}
// ───────────────────────── 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 : "";
+ entry.IsFolder ? (string.IsNullOrWhiteSpace(entry.Folder) ? UiText.Get("AppGridFolder") : entry.Folder!) : NameOfApp(entry.App!);
private TileParts MakeTile(LaunchEntry entry, List<(Image, string)> pending)
{
@@ -669,15 +922,15 @@ public sealed class AppGridWindow : OverlayWindow
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) };
+ var minis = new UniformGrid { Rows = 3, Columns = 3, Margin = new Thickness(_icon * 0.11), VerticalAlignment = VerticalAlignment.Top };
foreach (var id in entry.Apps!.Take(9))
{
- var mini = new Image { Width = _icon * 0.22, Height = _icon * 0.22, Stretch = Stretch.Uniform };
+ var mini = new Image { Width = _icon * 0.2, Height = _icon * 0.2, Stretch = Stretch.Uniform, Margin = new Thickness(_icon * 0.02) };
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 };
+ icon = new Border { Width = _icon, Height = _icon, CornerRadius = new CornerRadius(_icon * 0.23), Background = FolderFill, BorderBrush = FolderEdge, BorderThickness = new Thickness(1), Child = minis };
}
else
{
@@ -694,14 +947,14 @@ public sealed class AppGridWindow : OverlayWindow
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);
+ return Assemble(image, NameOfApp(id), 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 };
+ var iconHost = new Grid { Width = Math.Round(_icon + 12 * _k), Height = Math.Round(_icon + 12 * _k), HorizontalAlignment = HorizontalAlignment.Center };
iconHost.Children.Add(backdrop);
icon.HorizontalAlignment = HorizontalAlignment.Center;
icon.VerticalAlignment = VerticalAlignment.Center;
@@ -709,16 +962,15 @@ public sealed class AppGridWindow : OverlayWindow
var label = new TextBlock
{
Text = name,
- Foreground = Ui.White,
- FontSize = 12,
+ Foreground = LabelText,
+ FontSize = 17 * _k,
TextAlignment = TextAlignment.Center,
TextTrimming = TextTrimming.CharacterEllipsis,
- MaxWidth = _cellW - 14,
+ MaxWidth = _cellW - 4,
HorizontalAlignment = HorizontalAlignment.Center,
- Margin = new Thickness(0, 2, 0, 0)
+ Margin = new Thickness(0, 3 * _k, 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 };
+ var column = new StackPanel { VerticalAlignment = VerticalAlignment.Top, 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 };
@@ -754,7 +1006,7 @@ public sealed class AppGridWindow : OverlayWindow
foreach (var (image, id) in work)
{
if (_closed) return;
- batch.Add((image, Icons.GetOrAdd(id, key => NotificationApps.LoadIcon(key, 128))));
+ batch.Add((image, Icons.GetOrAdd(id, ReadIcon)));
if (batch.Count >= 16) Flush();
}
Flush();
@@ -786,7 +1038,6 @@ public sealed class AppGridWindow : OverlayWindow
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)
@@ -797,16 +1048,13 @@ public sealed class AppGridWindow : OverlayWindow
}
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 };
+ _press = new Press { Start = point, Entry = entry, Icon = parts.IconHost, Fixed = Filtered || entry.IsFolder || _frequent.Contains(entry) };
}
else
{
return;
}
+ Select(null);
if (_press.Icon is not null) _press.Icon.Opacity = 0.65;
Root.CaptureMouse();
}
@@ -821,27 +1069,8 @@ public sealed class AppGridWindow : OverlayWindow
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;
- }
+ if ((point - _press.Start).Length < DragThreshold || _press.Fixed) return;
+ if (_press.Entry is not null || _press.FolderApp is not null) StartDrag(point);
}
private void OnPressUp(object sender, MouseButtonEventArgs e)
@@ -851,132 +1080,83 @@ public sealed class AppGridWindow : OverlayWindow
_press = null;
if (Root.IsMouseCaptured) Root.ReleaseMouseCapture();
if (press.Icon is not null) press.Icon.Opacity = 1;
+ e.Handled = true;
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.
+ if ((e.GetPosition(Root) - press.Start).Length >= DragThreshold * 2) return;
+ if (press.Entry is not null) Open(press.Entry);
+ else if (press.FolderApp is not null) Launch(press.FolderApp);
}
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;
+ // ───────────────────────── Keyboard ─────────────────────────
/// <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.
+ /// 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 scroll; Tab and Shift+Tab change the
+ /// category.
/// </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
+ switch (e.Key)
{
- 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;
+ case Key.Left when !typing: Step(-1); break;
+ case Key.Right when !typing: Step(1); break;
+ case Key.Up: Vertical(-1); break;
+ case Key.Down: Vertical(1); break;
+ case Key.PageDown: ScrollTo(_scroll + ViewHeight * 0.9); break;
+ case Key.PageUp: ScrollTo(_scroll - ViewHeight * 0.9); break;
+ case Key.Tab: NextCategory((Keyboard.Modifiers & ModifierKeys.Shift) != 0 ? -1 : 1); break;
+ default: 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)
+ private LaunchEntry? FirstInView() => _order.FirstOrDefault(entry => _slots[entry].Y >= _scroll - 1) ?? _order.FirstOrDefault();
+
+ private void Step(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 (_order.Count == 0) return;
+ var at = _selected is null ? -1 : _order.IndexOf(_selected);
+ Select(at < 0 ? FirstInView() : _order[Math.Clamp(at + move, 0, _order.Count - 1)]);
+ }
+
+ /// <summary>Up and down go to the nearest icon in the row above or below (the rows above and below the line differ in length).</summary>
+ private void Vertical(int move)
+ {
+ if (_order.Count == 0) return;
+ if (_selected is null || !_slots.TryGetValue(_selected, out var current))
+ {
+ Select(FirstInView());
+ return;
}
- if (found < 0 || found >= list.Count || list[found] is not { } entry) return;
- Select(entry, found / PerPage);
+ var rows = _order.Select(entry => _slots[entry].Y).Distinct().OrderBy(y => y).ToList();
+ var row = rows.IndexOf(current.Y) + move;
+ if (row < 0 || row >= rows.Count) return;
+ Select(_order.Where(entry => _slots[entry].Y == rows[row]).MinBy(entry => Math.Abs(_slots[entry].X - current.X)));
}
- /// <summary>Highlights the icon the keyboard is on (turning to its page), or none.</summary>
- private void Select(LaunchEntry? entry, int page = -1)
+ /// <summary>Highlights the icon the keyboard is on (scrolling it into view), or none.</summary>
+ private void Select(LaunchEntry? entry)
{
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 (entry is null || !_slots.TryGetValue(entry, out var at)) return;
+ if (at.Y < _scroll) ScrollTo(at.Y - 8);
+ else if (at.Y + _cellH > _scroll + ViewHeight) ScrollTo(at.Y + _cellH - ViewHeight + 8);
if (_tiles.TryGetValue(entry, out var parts)) Highlight(parts, true);
}
@@ -988,7 +1168,7 @@ public sealed class AppGridWindow : OverlayWindow
/// <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>
+ /// <summary>A right click on an icon: open it, as administrator, its file location, pin it, its category; on a folder: open or ungroup it.</summary>
private void OnMenu(object sender, MouseButtonEventArgs e)
{
if (_drag is not null) return;
@@ -1007,7 +1187,7 @@ public sealed class AppGridWindow : OverlayWindow
if (cell.Tag is LaunchEntry { IsFolder: true } folder)
{
Add("AppGridOpenFolder", () => OpenFolder(folder));
- if (!Searching && _items.Contains(folder)) Add("AppGridUngroup", () => Ungroup(folder));
+ if (_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))
{
@@ -1031,6 +1211,21 @@ public sealed class AppGridWindow : OverlayWindow
Add(pinned ? "AppGridPinned" : "AppGridPin", () => pin(target, app.Name), !pinned);
}
}
+ // The category is a guess from the app's name; it can be put right here.
+ var current = AppCategories.Of(app);
+ var category = new MenuItem { Header = L("Kategori", "Category") };
+ foreach (var choice in AppCategories.Order)
+ {
+ var item = new MenuItem { Header = AppCategories.Name(choice), IsChecked = choice == current };
+ item.Click += (_, _) =>
+ {
+ AppCategories.Choose(app.Id, choice);
+ BuildChips();
+ Refill(keepScroll: true);
+ };
+ category.Items.Add(item);
+ }
+ menu.Items.Add(category);
}
else
{
@@ -1040,7 +1235,7 @@ public sealed class AppGridWindow : OverlayWindow
menu.IsOpen = true;
}
- /// <summary>A folder's apps go back onto the pages where the folder was.</summary>
+ /// <summary>A folder's apps go back among the others.</summary>
private void Ungroup(LaunchEntry folder)
{
var index = _items.IndexOf(folder);
@@ -1049,7 +1244,7 @@ public sealed class AppGridWindow : OverlayWindow
_items.RemoveAt(index);
_items.InsertRange(index, folder.Apps!.Select(id => new LaunchEntry { App = id }));
Forget(folder);
- Refill();
+ Refill(keepScroll: true);
Save();
}
@@ -1090,11 +1285,11 @@ public sealed class AppGridWindow : OverlayWindow
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);
+ var tile = _tiles[entry].Element;
+ var origin = tile.TranslatePoint(new Point(), Root);
_drag = new Drag { Entry = entry, Ghost = Ghost(entry), Grab = point - origin };
- Arrange(false);
+ // Its place stays, faint, until it lands somewhere.
+ tile.Opacity = 0.25;
}
DragTo(point);
}
@@ -1137,8 +1332,8 @@ public sealed class AppGridWindow : OverlayWindow
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;
+ var inHost = Root.TranslatePoint(point, _host);
+ var edge = inHost.Y < 48 ? -1 : inHost.Y > _host.ActualHeight - 48 ? 1 : 0;
if (edge != _edgeDirection)
{
_edgeDirection = edge;
@@ -1146,28 +1341,21 @@ public sealed class AppGridWindow : OverlayWindow
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();
+ // Over the middle of another icon (or a folder): a folder would be made there.
+ var inStrip = Root.TranslatePoint(point, _strip);
LaunchEntry? target = null;
- if (gx >= 0 && gx < _cols * _cellW && gy >= 0 && gy < _rows * _cellH && slotIndex < display.Count && display[slotIndex] is { } under && !drag.Entry.IsFolder)
+ var iconMiddle = (_icon + 12 * _k) / 2;
+ foreach (var entry in _order)
{
- // 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;
+ if (ReferenceEquals(entry, drag.Entry) || string.Equals(entry.App, drag.Entry.App, StringComparison.OrdinalIgnoreCase)) continue;
+ var at = _slots[entry];
+ if (Math.Abs(inStrip.X - (at.X + _cellW / 2)) < _icon * 0.5 && Math.Abs(inStrip.Y - (at.Y + iconMiddle)) < _icon * 0.5)
+ {
+ target = entry;
+ break;
+ }
}
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)
@@ -1187,19 +1375,6 @@ public sealed class AppGridWindow : OverlayWindow
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!;
@@ -1215,7 +1390,7 @@ public sealed class AppGridWindow : OverlayWindow
ArrangeFolder(true);
Land(drag.Ghost, _folderTiles.TryGetValue(drag.Entry.App!, out var inFolder) ? inFolder.Element : null);
Forget(drag.Folder);
- Arrange(false);
+ Refill(keepScroll: true);
Save();
return;
}
@@ -1223,30 +1398,37 @@ public sealed class AppGridWindow : OverlayWindow
if (_folderTarget is { } target)
{
SetFolderTarget(null);
- if (target.IsFolder)
+ // The most used row shows copies; the folder is made where the app itself stands.
+ var real = target.IsFolder ? target
+ : _items.FirstOrDefault(e => !e.IsFolder && string.Equals(e.App, target.App, StringComparison.OrdinalIgnoreCase))
+ ?? _items.FirstOrDefault(e => e.IsFolder && e.Apps!.Contains(target.App!, StringComparer.OrdinalIgnoreCase))
+ ?? target;
+ _items.Remove(drag.Entry);
+ Forget(drag.Entry);
+ if (real.IsFolder)
{
- target.Apps!.Add(drag.Entry.App!);
+ real.Apps!.Add(drag.Entry.App!);
+ Forget(real);
}
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;
+ // App on app: the two become a folder (folders stand on top).
+ var folder = new LaunchEntry { Folder = UiText.Get("AppGridFolder"), Apps = [real.App!, drag.Entry.App!] };
+ var at = _items.IndexOf(real);
+ if (at >= 0) _items[at] = folder;
+ else _items.Add(folder);
+ Forget(real);
+ real = folder;
}
- _items = _others;
- Forget(target);
- Arrange(true);
- Land(drag.Ghost, _tiles.TryGetValue(target, out var into) ? into.Element : null, shrink: true);
+ Refill(keepScroll: true);
+ Land(drag.Ghost, _tiles.TryGetValue(real, out var into) ? into.Element : null, shrink: true);
Save();
return;
}
- _items = [.. _others];
- _items.Insert(Math.Clamp(_dropIndex, 0, _items.Count), drag.Entry);
- Refill();
+ // Nowhere in particular: back to its place.
+ Refill(keepScroll: true);
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>
@@ -1258,12 +1440,8 @@ public sealed class AppGridWindow : OverlayWindow
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 target = tile.Parent is Canvas canvas ? canvas.TranslatePoint(at, Root) : at;
var time = TimeSpan.FromMilliseconds(220);
var left = new DoubleAnimation(target.X, time) { EasingFunction = Motion.Out };
left.Completed += (_, _) =>
@@ -1280,7 +1458,7 @@ public sealed class AppGridWindow : OverlayWindow
if (shrink) ghost.BeginAnimation(OpacityProperty, new DoubleAnimation(0, time));
}
- /// <summary>Drops a tile so it is drawn again (a folder whose apps changed).</summary>
+ /// <summary>Drops a tile so it is drawn again (a folder whose apps changed) or because it went out of view.</summary>
private void Forget(LaunchEntry entry)
{
if (!_tiles.TryGetValue(entry, out var tile)) return;
@@ -1290,7 +1468,6 @@ public sealed class AppGridWindow : OverlayWindow
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());
}
@@ -1298,6 +1475,7 @@ public sealed class AppGridWindow : OverlayWindow
private void OpenFolder(LaunchEntry folder)
{
+ Select(null);
_openFolder = folder;
_folderLayer.Children.Clear();
_folderTiles.Clear();
@@ -1330,7 +1508,7 @@ public sealed class AppGridWindow : OverlayWindow
if (text.Length == 0 || text == NameOf(folder)) return;
folder.Folder = text;
Forget(folder);
- Arrange(false);
+ Realize();
Save();
}
name.LostKeyboardFocus += (_, _) => Rename();
@@ -1351,10 +1529,10 @@ public sealed class AppGridWindow : OverlayWindow
_folderPanel = new Border
{
Child = column,
- Background = Ui.Solid("#C2303236"),
+ Background = Ui.Solid("#E62A2C30"),
BorderBrush = FolderEdge,
BorderThickness = new Thickness(1),
- CornerRadius = new CornerRadius(30),
+ CornerRadius = new CornerRadius(30 * _k),
Padding = new Thickness(24, 22, 24, 18),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
@@ -1366,7 +1544,7 @@ public sealed class AppGridWindow : OverlayWindow
_folderLayer.Children.Add(_folderPanel);
ArrangeFolder(false);
_folderLayer.Visibility = Visibility.Visible;
- // Typing would otherwise go on filtering the pages behind the folder.
+ // Typing would otherwise go on filtering the panel behind the folder.
_folderPanel.Focusable = true;
_folderPanel.FocusVisualStyle = null;
Dispatcher.BeginInvoke(() => _folderPanel?.Focus(), DispatcherPriority.Loaded);
@@ -1376,7 +1554,7 @@ public sealed class AppGridWindow : OverlayWindow
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));
+ _panel.BeginAnimation(OpacityProperty, new DoubleAnimation(0.45, time));
}
private void CloseFolder(bool quick = false)
@@ -1401,7 +1579,7 @@ public sealed class AppGridWindow : OverlayWindow
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));
+ _panel.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>
@@ -1464,8 +1642,8 @@ public sealed class AppGridWindow : OverlayWindow
}
/// <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.
+ /// The dragged app left the folder panel: it comes out of the folder (back among the other apps), the folder
+ /// closes and the drag carries on over the panel, where it can still be dropped on another icon.
/// </summary>
private void LeaveFolder()
{
@@ -1474,20 +1652,16 @@ public sealed class AppGridWindow : OverlayWindow
drag.Folder = null;
folder.Apps = [.. _folderOthers];
var at = _items.IndexOf(folder);
- if (folder.Apps.Count == 1)
+ Forget(folder);
+ if (folder.Apps.Count == 1 && at >= 0)
{
// A folder of one is just that app again.
- Forget(folder);
_items[at] = new LaunchEntry { App = folder.Apps[0] };
}
- else
- {
- Forget(folder);
- }
+ _items.Insert(at < 0 ? _items.Count : at + 1, drag.Entry);
CloseFolder(quick: true);
- _others = [.. _items];
- _dropIndex = at + 1;
- Arrange(false);
+ Refill(keepScroll: true);
+ if (_tiles.TryGetValue(drag.Entry, out var placed)) placed.Element.Opacity = 0.25;
Save();
}
}
diff --git a/Browser/NotchBrowser.cs b/Browser/NotchBrowser.cs
new file mode 100644
index 0000000..ceccd7b
--- /dev/null
+++ b/Browser/NotchBrowser.cs
@@ -0,0 +1,119 @@
+using System.Runtime.InteropServices;
+using System.Windows;
+using System.Windows.Threading;
+
+namespace QiDock.Browser;
+
+/// <summary>
+/// Opens the notch browser when the pointer rests on the top edge of the main screen, in the middle (where a
+/// MacBook has its notch). Only the pointer position is read, ten times a second; the browser itself is created on
+/// first use and gives its memory back a few minutes after it is put away.
+/// </summary>
+internal static class NotchBrowser
+{
+ /// <summary>Half the width of the spot on the top edge that opens the browser (screen units).</summary>
+ public const double ZoneHalfWidth = 110;
+
+ private static readonly TimeSpan Dwell = TimeSpan.FromMilliseconds(220);
+ private static readonly DispatcherTimer Watch = new(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(100) };
+ private static NotchBrowserWindow? _window;
+ private static DateTime _since;
+
+ static NotchBrowser()
+ {
+ Watch.Tick += (_, _) => Poll();
+ }
+
+ public static bool Enabled { get; private set; }
+
+ /// <summary>Follows the dock's "animations" setting: off, the browser simply appears and disappears.</summary>
+ public static bool Animations { get; set; } = true;
+
+ /// <summary>A full-screen app (game, video) is in front: the top edge belongs to it.</summary>
+ public static bool Suppressed { get; set; }
+
+ public static bool IsOpen => _window?.IsExpanded == true;
+
+ public static void SetEnabled(bool enabled)
+ {
+ Enabled = enabled;
+ _since = default;
+ if (enabled) Watch.Start();
+ else
+ {
+ Watch.Stop();
+ _window?.Collapse();
+ }
+ }
+
+ public static void Open()
+ {
+ _window ??= new NotchBrowserWindow();
+ _window.Expand();
+ }
+
+ public static void Toggle()
+ {
+ if (IsOpen) _window!.Collapse();
+ else Open();
+ }
+
+ /// <summary>True when screen pixel x on the top edge is the browser's spot (the widget bar leaves it alone).</summary>
+ public static bool InZone(int x)
+ {
+ if (!Enabled) return false;
+ var width = GetSystemMetrics(0);
+ return Math.Abs(x - width / 2.0) <= ZoneHalfWidth * Scale();
+ }
+
+ public static void Shutdown() => _window?.SaveState();
+
+ private static double Scale()
+ {
+ var dpi = GetDpiForSystem();
+ return dpi > 0 ? dpi / 96.0 : 1;
+ }
+
+ private static void Poll()
+ {
+ if (Suppressed || IsOpen || !GetCursorPos(out var cursor) || AnyMouseButtonDown())
+ {
+ _since = default;
+ return;
+ }
+ // The very top row of the main screen only (browser tabs and title bars sit just below it).
+ if (cursor.Y > 1 || cursor.Y < 0 || !InZone(cursor.X))
+ {
+ _since = default;
+ return;
+ }
+ var now = DateTime.UtcNow;
+ if (_since == default)
+ {
+ _since = now;
+ return;
+ }
+ if (now - _since < Dwell) return;
+ _since = default;
+ Open();
+ }
+
+ private static bool AnyMouseButtonDown() =>
+ (GetAsyncKeyState(0x01) & 0x8000) != 0 || (GetAsyncKeyState(0x02) & 0x8000) != 0;
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct NativePoint { public int X, Y; }
+
+ [DllImport("user32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool GetCursorPos(out NativePoint point);
+
+ [DllImport("user32.dll")]
+ private static extern short GetAsyncKeyState(int key);
+
+ [DllImport("user32.dll")]
+ private static extern int GetSystemMetrics(int index);
+
+ [DllImport("user32.dll")]
+ private static extern uint GetDpiForSystem();
+}
diff --git a/Browser/NotchBrowserStore.cs b/Browser/NotchBrowserStore.cs
new file mode 100644
index 0000000..ca13542
--- /dev/null
+++ b/Browser/NotchBrowserStore.cs
@@ -0,0 +1,48 @@
+using System.IO;
+using System.Text.Json;
+
+namespace QiDock.Browser;
+
+internal sealed record BrowserBookmark(string Title, string Url);
+
+/// <summary>What the notch browser keeps between uses: its open tabs, its bookmarks and the capture choice.</summary>
+internal sealed record NotchBrowserState(
+ IReadOnlyList<string>? Tabs = null,
+ int Active = 0,
+ IReadOnlyList<BrowserBookmark>? Bookmarks = null,
+ bool HideFromCapture = false)
+{
+ private static string Folder => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock");
+ private static string FilePath => Path.Combine(Folder, "browser.json");
+
+ /// <summary>Where the browser keeps its cookies and sign-ins (its own profile, separate from Chrome or Edge).</summary>
+ public static string ProfileFolder => Path.Combine(Folder, "Browser");
+
+ public static NotchBrowserState Load()
+ {
+ try
+ {
+ if (File.Exists(FilePath)) return JsonSerializer.Deserialize<NotchBrowserState>(File.ReadAllText(FilePath)) ?? new();
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
+ {
+ System.Diagnostics.Trace.TraceWarning("Browser state not read: {0}", ex.Message);
+ }
+ return new();
+ }
+
+ public void Save()
+ {
+ try
+ {
+ Directory.CreateDirectory(Folder);
+ var temporary = FilePath + ".tmp";
+ File.WriteAllText(temporary, JsonSerializer.Serialize(this));
+ File.Move(temporary, FilePath, true);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ System.Diagnostics.Trace.TraceWarning("Browser state not saved: {0}", ex.Message);
+ }
+ }
+}
diff --git a/Browser/NotchBrowserWindow.cs b/Browser/NotchBrowserWindow.cs
new file mode 100644
index 0000000..93aa1a0
--- /dev/null
+++ b/Browser/NotchBrowserWindow.cs
@@ -0,0 +1,854 @@
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Interop;
+using System.Windows.Media.Animation;
+using System.Windows.Media;
+using System.Windows.Shapes;
+using System.Windows.Threading;
+using Microsoft.Web.WebView2.Core;
+using Microsoft.Web.WebView2.Wpf;
+using QiDock.Services;
+
+namespace QiDock.Browser;
+
+/// <summary>
+/// A small browser that drops out of the top edge of the screen, as from a MacBook's notch: tabs, an address bar and
+/// the page, on black with rounded lower corners. It grows from the notch and folds back into it. Pages run in
+/// WebView2 (the Chromium engine Windows already has); the engine is let go a few minutes after the browser is put
+/// away, so it costs nothing while unused. Its cookies and sign-ins live in its own profile under QiDock's folder.
+/// </summary>
+internal sealed class NotchBrowserWindow : Window
+{
+ private const string Home = "https://www.google.com/";
+ private const double NotchWidth = 220, Corner = 22, Fillet = 14, TabWidth = 210;
+
+ private static readonly Brush Ink = Solid(0xFF, 0x0A, 0x0A, 0x0B);
+ private static readonly Brush TabSelected = Solid(0xFF, 0x22, 0x22, 0x25);
+ private static readonly Brush TabHover = Solid(0xFF, 0x17, 0x17, 0x19);
+ private static readonly Brush Field = Solid(0xFF, 0x13, 0x13, 0x15);
+ private static readonly Brush FieldBorder = Solid(0xFF, 0x2A, 0x2A, 0x2E);
+ private static readonly Brush Bright = Solid(0xF2, 0xFF, 0xFF, 0xFF);
+ private static readonly Brush Dim = Solid(0x99, 0xFF, 0xFF, 0xFF);
+ private static readonly Brush Hover = Solid(0x24, 0xFF, 0xFF, 0xFF);
+ private static readonly Brush Gold = Solid(0xFF, 0xF5, 0xC5, 0x42);
+
+ private sealed class Tab
+ {
+ public string Url = Home;
+ public string Title = "";
+ public WebView2? View;
+ public Border Chip = null!;
+ public TextBlock Caption = null!;
+ }
+
+ private readonly List<Tab> _tabs = [];
+ private readonly System.Windows.Controls.Primitives.UniformGrid _strip = new() { Rows = 1, HorizontalAlignment = HorizontalAlignment.Left };
+ private readonly Grid _stripHost = new();
+ private readonly TextBox _address;
+ private readonly Grid _pages = new();
+ private readonly Grid _chrome;
+ private readonly Border _back, _forward, _star, _capture;
+ private readonly Path _starPath, _capturePath;
+ private readonly DispatcherTimer _pointerWatch = new(DispatcherPriority.Input) { Interval = TimeSpan.FromMilliseconds(100) };
+ private static readonly TimeSpan LeaveDelay = TimeSpan.FromMilliseconds(700);
+ private DateTime _outsideSince;
+ private ContextMenu? _menu;
+ private Tab? _active;
+ private NotchBrowserState _state;
+ private Task<CoreWebView2Environment>? _environment;
+ private nint _handle;
+ private double _progress;
+ private bool _expanded, _fullScreen;
+ private DateTime _animationStart;
+ private double _animationFrom, _animationTo, _animationLength;
+ private IEasingFunction _animationEase = Motion.Out;
+ private Action? _animationDone;
+ private readonly Grid _layout = new();
+ private readonly DispatcherTimer _showPages = new(DispatcherPriority.Render) { Interval = TimeSpan.FromMilliseconds(150) };
+ private Rect _restore;
+
+ public NotchBrowserWindow()
+ {
+ WindowStyle = WindowStyle.None;
+ ResizeMode = ResizeMode.NoResize;
+ ShowInTaskbar = false;
+ Topmost = true;
+ Background = Ink;
+ Title = "QiDock Browser";
+ UseLayoutRounding = true;
+ WindowStartupLocation = WindowStartupLocation.Manual;
+ SetResourceReference(FontFamilyProperty, "InterfaceFont");
+ _state = NotchBrowserState.Load();
+
+ // Row 1: the tabs, a new-tab button and the fold-away arrow.
+ var newTab = Button(Icon("M12 5v14 M5 12h14", 15), () => AddTab(Home, true, focusAddress: true), Desk("Yeni sekme (Ctrl+T)", "New tab (Ctrl+T)"));
+ var fold = Button(Icon("M6 15l6-6 6 6", 15), Collapse, Desk("Kapat (Esc)", "Put away (Esc)"));
+ _stripHost.Children.Add(_strip);
+ _stripHost.SizeChanged += (_, _) => FitStrip();
+ var tabsRow = new Grid { Margin = new Thickness(14, 10, 10, 0), Height = 32 };
+ tabsRow.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
+ tabsRow.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
+ tabsRow.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
+ tabsRow.Children.Add(_stripHost);
+ Grid.SetColumn(newTab, 1);
+ tabsRow.Children.Add(newTab);
+ Grid.SetColumn(fold, 2);
+ fold.Margin = new Thickness(4, 0, 0, 0);
+ tabsRow.Children.Add(fold);
+
+ // Row 2: back, forward, reload, the address, the bookmark star and "hide from screen sharing".
+ _back = Button(Icon("M15 18l-6-6 6-6", 16), () => Core()?.GoBack(), Desk("Geri (Alt+←)", "Back (Alt+←)"));
+ _forward = Button(Icon("M9 18l6-6-6-6", 16), () => Core()?.GoForward(), Desk("İleri (Alt+→)", "Forward (Alt+→)"));
+ var reload = Button(Icon("M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8 M21 3v5h-5 M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16 M8 16H3v5", 14), () => Core()?.Reload(), Desk("Yenile (F5)", "Reload (F5)"));
+ _address = new TextBox
+ {
+ Background = Brushes.Transparent,
+ BorderThickness = new Thickness(0),
+ Foreground = Bright,
+ CaretBrush = Bright,
+ SelectionBrush = Solid(0xFF, 0x3A, 0x6E, 0xD8),
+ FontSize = 13,
+ VerticalContentAlignment = VerticalAlignment.Center,
+ Padding = new Thickness(10, 0, 10, 0)
+ };
+ _address.KeyDown += Address_KeyDown;
+ _address.GotKeyboardFocus += (_, _) => Dispatcher.BeginInvoke(_address.SelectAll, DispatcherPriority.Input);
+ _address.PreviewMouseLeftButtonDown += (_, e) =>
+ {
+ if (_address.IsKeyboardFocusWithin) return;
+ e.Handled = true;
+ _address.Focus();
+ };
+ var field = new Border { Background = Field, BorderBrush = FieldBorder, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(15), Height = 32, Child = _address, Margin = new Thickness(8, 0, 6, 0) };
+ _starPath = Icon("M12 3.5l2.6 5.3 5.9.9-4.3 4.1 1 5.8L12 16.9l-5.2 2.7 1-5.8-4.3-4.1 5.9-.9z", 16);
+ _star = Button(_starPath, ShowBookmarks, Desk("Yer imleri", "Bookmarks"));
+ _capturePath = Icon("M3 3l18 18 M10.6 10.6a2 2 0 0 0 2.8 2.8 M9.9 5.1A9.8 9.8 0 0 1 12 5c5 0 9 4.5 10 7-.4 1-1.2 2.3-2.4 3.5 M6.6 6.6C4.4 8 2.8 10.2 2 12c1 2.5 5 7 10 7 1.7 0 3.3-.5 4.6-1.3", 16);
+ _capture = Button(_capturePath, ToggleCapture, Desk("Ekran kaydında ve paylaşımında gizle", "Hide from screen recording and sharing"));
+ var toolRow = new Grid { Margin = new Thickness(12, 8, 12, 10), Height = 34 };
+ foreach (var width in new[] { GridLength.Auto, GridLength.Auto, GridLength.Auto, new GridLength(1, GridUnitType.Star), GridLength.Auto, new GridLength(1, GridUnitType.Star), GridLength.Auto })
+ toolRow.ColumnDefinitions.Add(new ColumnDefinition { Width = width });
+ // The address takes about two thirds, as in the reference; the rest stays empty before the right-hand button.
+ toolRow.ColumnDefinitions[3].Width = new GridLength(3, GridUnitType.Star);
+ Place(toolRow, _back, 0);
+ Place(toolRow, _forward, 1);
+ Place(toolRow, reload, 2);
+ Place(toolRow, field, 3);
+ Place(toolRow, _star, 4);
+ Place(toolRow, _capture, 6);
+
+ _chrome = new Grid();
+ _chrome.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
+ _chrome.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
+ _chrome.Children.Add(tabsRow);
+ Grid.SetRow(toolRow, 1);
+ _chrome.Children.Add(toolRow);
+
+ var layout = _layout;
+ // Room left and right for the curves that join the panel to the screen edge.
+ layout.Margin = new Thickness(Fillet, 0, Fillet, 0);
+ layout.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
+ layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
+ layout.Children.Add(_chrome);
+ _pages.Margin = new Thickness(10, 0, 10, 10);
+ Grid.SetRow(_pages, 1);
+ layout.Children.Add(_pages);
+ Content = layout;
+ _showPages.Tick += (_, _) =>
+ {
+ _showPages.Stop();
+ if (_expanded) _pages.Visibility = Visibility.Visible;
+ };
+
+ PreviewKeyDown += Window_PreviewKeyDown;
+ Deactivated += (_, _) => Dispatcher.BeginInvoke(CollapseIfLeft, DispatcherPriority.Background);
+ SizeChanged += (_, _) => ApplyRegion();
+ _pointerWatch.Tick += (_, _) => WatchPointer();
+ Application.Current.Exit += (_, _) => SaveState();
+ }
+
+ public bool IsExpanded => _expanded;
+
+ // ---- Opening and closing ------------------------------------------------------------------
+
+ public void Expand()
+ {
+ if (_expanded) return;
+ _expanded = true;
+ Place();
+ if (_handle == 0)
+ {
+ _handle = new WindowInteropHelper(this).EnsureHandle();
+ // A tool window: no Alt+Tab entry and no dock button of its own.
+ var style = GetWindowLongPtr(_handle, -20).ToInt64();
+ SetWindowLongPtr(_handle, -20, new nint(style | 0x80));
+ ApplyCapture();
+ }
+ if (_tabs.Count == 0) RestoreTabs();
+ _progress = 0;
+ ApplyRegion();
+ if (!IsVisible) Show();
+ Activate();
+ _outsideSince = default;
+ _pointerWatch.Start();
+ if (_active is { } tab) _ = ShowTab(tab);
+ Wake();
+ // As the cards on the dock open: a narrow bump grows out of the edge to the full panel, settling with a
+ // little give; the bars follow once it is nearly full, coming down a few pixels; the page shows last.
+ _pages.Visibility = Visibility.Hidden;
+ _showPages.Start();
+ _chrome.BeginAnimation(OpacityProperty, Motion.FromTo(0, 1, 220, delay: 170));
+ _chrome.Opacity = 1;
+ Motion.Shift(_chrome).BeginAnimation(TranslateTransform.YProperty, Motion.FromTo(-12, 0, 380, delay: 170));
+ Animate(1, 430, Motion.Settle, 0, () =>
+ {
+ if (_active?.View?.CoreWebView2 is null || string.IsNullOrEmpty(_active.Url) || _active.Url == Home) _address.Focus();
+ else _active.View.Focus();
+ });
+ }
+
+ public void Collapse()
+ {
+ if (!_expanded) return;
+ _expanded = false;
+ _pointerWatch.Stop();
+ if (_menu is not null) _menu.IsOpen = false;
+ if (_fullScreen) LeaveFullScreen();
+ SaveState();
+ // Content first, then the shape sinks back into the edge.
+ _showPages.Stop();
+ _pages.Visibility = Visibility.Hidden;
+ _chrome.BeginAnimation(OpacityProperty, new DoubleAnimation(0, TimeSpan.FromMilliseconds(110)) { EasingFunction = Motion.In });
+ Animate(0, 250, Motion.In, 60, () =>
+ {
+ if (_expanded) return;
+ Hide();
+ _pages.Visibility = Visibility.Visible;
+ Rest();
+ });
+ }
+
+ /// <summary>
+ /// Like the notch it comes from, the browser goes away when the pointer leaves it for a moment or clicks elsewhere;
+ /// it stays while the address is being typed, its bookmark menu is open or a page shows a video full screen.
+ /// </summary>
+ private void WatchPointer()
+ {
+ if (!_expanded || _fullScreen || _menu?.IsOpen == true || !GetCursorPos(out var cursor))
+ {
+ _outsideSince = default;
+ return;
+ }
+ var scale = VisualTreeHelper.GetDpi(this).DpiScaleX;
+ var margin = 24 * scale;
+ var inside = cursor.X >= Left * scale - margin && cursor.X <= (Left + Width) * scale + margin
+ && cursor.Y <= (Top + Height) * scale + margin;
+ if (inside)
+ {
+ _outsideSince = default;
+ return;
+ }
+ var clicked = (GetAsyncKeyState(0x01) & 0x8000) != 0 || (GetAsyncKeyState(0x02) & 0x8000) != 0;
+ if (clicked && !OwnDialogInFront())
+ {
+ Collapse();
+ return;
+ }
+ if (_address.IsKeyboardFocusWithin && IsActive) return;
+ var now = DateTime.UtcNow;
+ if (_outsideSince == default) _outsideSince = now;
+ else if (now - _outsideSince >= LeaveDelay && !OwnDialogInFront()) Collapse();
+ }
+
+ /// <summary>A page's own window (an alert, a sign-in pop-up) is in front; it belongs to the browser.</summary>
+ private static bool OwnDialogInFront()
+ {
+ var foreground = GetForegroundWindow();
+ if (foreground == 0) return false;
+ GetWindowThreadProcessId(foreground, out var processId);
+ if (processId == Environment.ProcessId) return false;
+ try
+ {
+ using var process = Process.GetProcessById((int)processId);
+ return process.ProcessName.Equals("msedgewebview2", StringComparison.OrdinalIgnoreCase);
+ }
+ catch (ArgumentException)
+ {
+ return false;
+ }
+ }
+
+ /// <summary>Clicking elsewhere puts the browser away; its own dialogs (alerts, sign-in pop-ups) do not.</summary>
+ private void CollapseIfLeft()
+ {
+ if (!_expanded || IsActive) return;
+ var foreground = GetForegroundWindow();
+ if (foreground == 0) return;
+ GetWindowThreadProcessId(foreground, out var processId);
+ if (processId == Environment.ProcessId) return;
+ try
+ {
+ using var process = Process.GetProcessById((int)processId);
+ if (process.ProcessName.Equals("msedgewebview2", StringComparison.OrdinalIgnoreCase)) return;
+ }
+ catch (ArgumentException)
+ {
+ }
+ Collapse();
+ }
+
+ private void Place()
+ {
+ if (_fullScreen) return;
+ var screenWidth = SystemParameters.PrimaryScreenWidth;
+ var screenHeight = SystemParameters.PrimaryScreenHeight;
+ Width = Math.Round(Math.Clamp(screenWidth * 0.66, Math.Min(760, screenWidth - 40), 1320)) + 2 * Fillet;
+ Height = Math.Round(Math.Max(420, Math.Min(screenHeight * 0.76, screenHeight - 150)));
+ Left = Math.Round((screenWidth - Width) / 2);
+ Top = 0;
+ }
+
+ private void Animate(double to, double milliseconds, IEasingFunction ease, double delay, Action? done)
+ {
+ CompositionTarget.Rendering -= Animation_Frame;
+ if (!NotchBrowser.Animations)
+ {
+ _progress = to;
+ ApplyRegion();
+ _showPages.Stop();
+ if (_expanded) _pages.Visibility = Visibility.Visible;
+ done?.Invoke();
+ return;
+ }
+ _animationFrom = _progress;
+ _animationTo = to;
+ _animationLength = milliseconds;
+ _animationEase = ease;
+ _animationStart = DateTime.UtcNow.AddMilliseconds(delay);
+ _animationDone = done;
+ CompositionTarget.Rendering += Animation_Frame;
+ }
+
+ private void Animation_Frame(object? sender, EventArgs e)
+ {
+ var t = Math.Clamp((DateTime.UtcNow - _animationStart).TotalMilliseconds / _animationLength, 0, 1);
+ var eased = _animationEase.Ease(t);
+ _progress = _animationFrom + (_animationTo - _animationFrom) * eased;
+ ApplyRegion();
+ if (t < 1) return;
+ CompositionTarget.Rendering -= Animation_Frame;
+ var done = _animationDone;
+ _animationDone = null;
+ done?.Invoke();
+ }
+
+ /// <summary>
+ /// The visible shape for the progress (0 closed, 1 open; a little over 1 while it settles): as the cards on the
+ /// dock, a bump half as wide as the notch growing to the whole panel, hanging from the screen edge, rounded
+ /// below, with inward curves where it meets the edge. Cutting the window this way also cuts the page inside it.
+ /// </summary>
+ private void ApplyRegion()
+ {
+ if (_handle == 0) return;
+ if (_fullScreen)
+ {
+ SetWindowRgn(_handle, 0, true);
+ return;
+ }
+ var scale = VisualTreeHelper.GetDpi(this).DpiScaleX;
+ var fullWidth = Width - 2 * Fillet;
+ var fullHeight = Height;
+ var p = Math.Max(0, _progress);
+ var startWidth = NotchWidth * 0.62;
+ var w = Math.Clamp(startWidth + (fullWidth - startWidth) * p, 0, fullWidth + 2 * Fillet - 4);
+ var h = Math.Clamp(fullHeight * p, 0, fullHeight);
+ if (h < 0.5)
+ {
+ SetWindowRgn(_handle, CreateRectRgn(0, 0, 0, 0), true);
+ return;
+ }
+ var fillet = Math.Max(0, Math.Min(Fillet, h * 0.45));
+ var corner = Math.Max(0, Math.Min(Math.Min(Corner, w / 2), h - fillet));
+ var left = (Width - w) / 2;
+ var right = left + w;
+
+ var geometry = new StreamGeometry();
+ using (var g = geometry.Open())
+ {
+ g.BeginFigure(new Point(left - fillet, 0), true, true);
+ if (fillet > 0) g.ArcTo(new Point(left, fillet), new Size(fillet, fillet), 0, false, SweepDirection.Clockwise, true, false);
+ g.LineTo(new Point(left, h - corner), true, false);
+ if (corner > 0) g.ArcTo(new Point(left + corner, h), new Size(corner, corner), 0, false, SweepDirection.Counterclockwise, true, false);
+ g.LineTo(new Point(right - corner, h), true, false);
+ if (corner > 0) g.ArcTo(new Point(right, h - corner), new Size(corner, corner), 0, false, SweepDirection.Counterclockwise, true, false);
+ g.LineTo(new Point(right, fillet), true, false);
+ if (fillet > 0) g.ArcTo(new Point(right + fillet, 0), new Size(fillet, fillet), 0, false, SweepDirection.Clockwise, true, false);
+ }
+ var points = new List<NativePoint>();
+ foreach (var figure in geometry.GetFlattenedPathGeometry(0.2, ToleranceType.Absolute).Figures)
+ {
+ points.Add(Pixel(figure.StartPoint, scale));
+ foreach (var segment in figure.Segments)
+ {
+ if (segment is PolyLineSegment poly) points.AddRange(poly.Points.Select(point => Pixel(point, scale)));
+ else if (segment is LineSegment line) points.Add(Pixel(line.Point, scale));
+ }
+ }
+ if (points.Count < 3) return;
+ SetWindowRgn(_handle, CreatePolygonRgn(points.ToArray(), points.Count, 2), true);
+ }
+
+ private static NativePoint Pixel(Point point, double scale) => new() { X = (int)Math.Round(point.X * scale), Y = (int)Math.Round(point.Y * scale) };
+
+ // ---- Tabs -----------------------------------------------------------------------------------
+
+ private void RestoreTabs()
+ {
+ var urls = _state.Tabs is { Count: > 0 } saved ? saved : [Home];
+ foreach (var url in urls) AddTab(url, false);
+ Select(_tabs[Math.Clamp(_state.Active, 0, _tabs.Count - 1)]);
+ }
+
+ private Tab AddTab(string url, bool select, bool focusAddress = false)
+ {
+ var tab = new Tab { Url = url, Title = TitleOf(url) };
+ tab.Caption = new TextBlock { Text = tab.Title, FontSize = 12.5, Foreground = Dim, TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center };
+ var close = Button(Icon("M6 6l12 12 M18 6L6 18", 10), () => CloseTab(tab), Desk("Sekmeyi kapat (Ctrl+W)", "Close tab (Ctrl+W)"), 22, 22);
+ var inner = new Grid();
+ inner.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
+ inner.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
+ inner.Children.Add(tab.Caption);
+ Grid.SetColumn(close, 1);
+ inner.Children.Add(close);
+ tab.Chip = new Border { Child = inner, CornerRadius = new CornerRadius(9), Padding = new Thickness(12, 0, 4, 0), Margin = new Thickness(0, 0, 6, 0), Background = Brushes.Transparent, Cursor = Cursors.Arrow };
+ tab.Chip.MouseEnter += (_, _) => { if (tab != _active) tab.Chip.Background = TabHover; };
+ tab.Chip.MouseLeave += (_, _) => { if (tab != _active) tab.Chip.Background = Brushes.Transparent; };
+ tab.Chip.MouseLeftButtonUp += (_, e) =>
+ {
+ if (e.OriginalSource is DependencyObject source && close.IsAncestorOf(source)) return;
+ Select(tab);
+ };
+ tab.Chip.MouseUp += (_, e) =>
+ {
+ if (e.ChangedButton == MouseButton.Middle) CloseTab(tab);
+ };
+ _tabs.Add(tab);
+ _strip.Children.Add(tab.Chip);
+ FitStrip();
+ if (select) Select(tab);
+ if (focusAddress) Dispatcher.BeginInvoke(() => _address.Focus(), DispatcherPriority.Input);
+ return tab;
+ }
+
+ private void FitStrip()
+ {
+ var room = Math.Max(0, _stripHost.ActualWidth);
+ _strip.Width = Math.Min(room, _tabs.Count * (TabWidth + 6));
+ }
+
+ private void Select(Tab tab)
+ {
+ _active = tab;
+ foreach (var other in _tabs)
+ {
+ var on = other == tab;
+ other.Chip.Background = on ? TabSelected : Brushes.Transparent;
+ other.Caption.Foreground = on ? Bright : Dim;
+ if (other.View is not null) other.View.Visibility = on ? Visibility.Visible : Visibility.Collapsed;
+ }
+ UpdateAddress();
+ UpdateButtons();
+ if (_expanded) _ = ShowTab(tab);
+ }
+
+ private void CloseTab(Tab tab)
+ {
+ var index = _tabs.IndexOf(tab);
+ if (index < 0) return;
+ _tabs.RemoveAt(index);
+ _strip.Children.Remove(tab.Chip);
+ if (tab.View is not null)
+ {
+ _pages.Children.Remove(tab.View);
+ tab.View.Dispose();
+ }
+ if (_tabs.Count == 0)
+ {
+ AddTab(Home, true);
+ Collapse();
+ return;
+ }
+ FitStrip();
+ if (tab == _active) Select(_tabs[Math.Min(index, _tabs.Count - 1)]);
+ }
+
+ /// <summary>Creates the tab's page on first view (restored tabs load only when opened).</summary>
+ private async Task ShowTab(Tab tab)
+ {
+ if (tab.View is not null) return;
+ var view = new WebView2 { DefaultBackgroundColor = System.Drawing.Color.FromArgb(255, 10, 10, 11), Visibility = tab == _active ? Visibility.Visible : Visibility.Collapsed };
+ tab.View = view;
+ _pages.Children.Add(view);
+ try
+ {
+ _environment ??= CoreWebView2Environment.CreateAsync(null, NotchBrowserState.ProfileFolder);
+ await view.EnsureCoreWebView2Async(await _environment);
+ }
+ catch (Exception ex) when (ex is WebView2RuntimeNotFoundException or COMException or InvalidOperationException or ObjectDisposedException)
+ {
+ AppLog.Write("Tarayıcı açılamadı: " + ex.Message);
+ if (tab.View == view)
+ {
+ _pages.Children.Remove(view);
+ tab.View = null;
+ view.Dispose();
+ }
+ ShowEngineMissing();
+ return;
+ }
+ if (tab.View != view) return; // closed or released while starting
+ var core = view.CoreWebView2;
+ core.Settings.IsStatusBarEnabled = false;
+ core.Profile.PreferredColorScheme = CoreWebView2PreferredColorScheme.Dark;
+ core.DocumentTitleChanged += (_, _) =>
+ {
+ tab.Title = string.IsNullOrWhiteSpace(core.DocumentTitle) ? TitleOf(tab.Url) : core.DocumentTitle;
+ tab.Caption.Text = tab.Title;
+ tab.Chip.ToolTip = tab.Title;
+ };
+ core.SourceChanged += (_, _) =>
+ {
+ tab.Url = core.Source;
+ if (tab == _active) UpdateAddress();
+ SaveState();
+ };
+ core.HistoryChanged += (_, _) =>
+ {
+ if (tab == _active) UpdateButtons();
+ };
+ // Links that would open a window open a tab here instead.
+ core.NewWindowRequested += (_, e) =>
+ {
+ e.Handled = true;
+ AddTab(e.Uri, true);
+ };
+ core.ContainsFullScreenElementChanged += (_, _) =>
+ {
+ if (tab != _active) return;
+ if (core.ContainsFullScreenElement) EnterFullScreen();
+ else LeaveFullScreen();
+ };
+ core.Navigate(tab.Url);
+ }
+
+ private void ShowEngineMissing()
+ {
+ if (_pages.Children.OfType<TextBlock>().Any()) return;
+ _pages.Children.Add(new TextBlock
+ {
+ Text = Desk("Sayfaları göstermek için Microsoft Edge WebView2 gerekli; Windows Update ile gelir.", "Pages need Microsoft Edge WebView2; it comes with Windows Update."),
+ Foreground = Dim,
+ FontSize = 14,
+ TextWrapping = TextWrapping.Wrap,
+ HorizontalAlignment = HorizontalAlignment.Center,
+ VerticalAlignment = VerticalAlignment.Center
+ });
+ }
+
+ /// <summary>
+ /// Put away: the pages stay as they are (scroll, sign-ins, a half-written form) but are paused and asked to give
+ /// back what memory they can until the browser opens again. Sound that is playing keeps playing.
+ /// </summary>
+ private void Rest()
+ {
+ foreach (var core in _tabs.Select(t => t.View?.CoreWebView2).OfType<CoreWebView2>())
+ {
+ try
+ {
+ core.MemoryUsageTargetLevel = CoreWebView2MemoryUsageTargetLevel.Low;
+ _ = core.TrySuspendAsync();
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or COMException)
+ {
+ // Still visible, or playing sound: it simply stays awake.
+ }
+ }
+ }
+
+ private void Wake()
+ {
+ foreach (var core in _tabs.Select(t => t.View?.CoreWebView2).OfType<CoreWebView2>())
+ {
+ try
+ {
+ core.MemoryUsageTargetLevel = CoreWebView2MemoryUsageTargetLevel.Normal;
+ if (core.IsSuspended) core.Resume();
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or COMException)
+ {
+ }
+ }
+ }
+
+ public void SaveState()
+ {
+ if (_tabs.Count == 0) return;
+ _state = _state with
+ {
+ Tabs = _tabs.Select(t => t.Url).Where(u => !string.IsNullOrWhiteSpace(u)).ToList(),
+ Active = _active is null ? 0 : Math.Max(0, _tabs.IndexOf(_active))
+ };
+ _state.Save();
+ }
+
+ // ---- Address, buttons, bookmarks ------------------------------------------------------------
+
+ private CoreWebView2? Core() => _active?.View?.CoreWebView2;
+
+ private void UpdateAddress()
+ {
+ if (_active is null || _address.IsKeyboardFocusWithin) return;
+ _address.Text = _active.Url == Home && _active.View?.CoreWebView2 is null ? "" : _active.Url;
+ var marked = _state.Bookmarks?.Any(b => SameUrl(b.Url, _active.Url)) == true;
+ _starPath.Fill = marked ? Gold : null;
+ _starPath.Stroke = marked ? Gold : Bright;
+ }
+
+ private void UpdateButtons()
+ {
+ _back.Opacity = Core()?.CanGoBack == true ? 1 : 0.35;
+ _forward.Opacity = Core()?.CanGoForward == true ? 1 : 0.35;
+ }
+
+ private void Address_KeyDown(object sender, KeyEventArgs e)
+ {
+ if (e.Key == Key.Enter)
+ {
+ e.Handled = true;
+ Go(_address.Text);
+ }
+ else if (e.Key == Key.Escape)
+ {
+ e.Handled = true;
+ _address.Text = _active?.Url ?? "";
+ _active?.View?.Focus();
+ }
+ }
+
+ private void Go(string text)
+ {
+ var url = UrlOf(text);
+ if (url is null || _active is null) return;
+ _active.Url = url;
+ if (_active.View?.CoreWebView2 is { } core) core.Navigate(url);
+ else _ = ShowTab(_active);
+ _active.View?.Focus();
+ }
+
+ /// <summary>An address as typed ("github.com", "https://…") or, for anything else, a Google search.</summary>
+ private static string? UrlOf(string text)
+ {
+ text = text.Trim();
+ if (text.Length == 0) return null;
+ if (Uri.TryCreate(text, UriKind.Absolute, out var absolute) && absolute.Scheme is "http" or "https" or "file" or "edge" or "about") return absolute.ToString();
+ var looksLikeHost = !text.Contains(' ') && (text.Contains('.') || text.StartsWith("localhost", StringComparison.OrdinalIgnoreCase));
+ if (looksLikeHost && Uri.TryCreate("https://" + text, UriKind.Absolute, out var host)) return host.ToString();
+ return "https://www.google.com/search?q=" + Uri.EscapeDataString(text);
+ }
+
+ private static string TitleOf(string url) =>
+ Uri.TryCreate(url, UriKind.Absolute, out var uri) && !string.IsNullOrEmpty(uri.Host) ? uri.Host.Replace("www.", "") : Desk("Yeni sekme", "New tab");
+
+ private static bool SameUrl(string a, string b) => string.Equals(a.TrimEnd('/'), b.TrimEnd('/'), StringComparison.OrdinalIgnoreCase);
+
+ private void ShowBookmarks()
+ {
+ var menu = new ContextMenu { PlacementTarget = _star, Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom };
+ _menu = menu;
+ var bookmarks = (_state.Bookmarks ?? []).ToList();
+ if (_active is { } tab && !string.IsNullOrWhiteSpace(tab.Url))
+ {
+ var marked = bookmarks.FindIndex(b => SameUrl(b.Url, tab.Url));
+ var toggle = new MenuItem { Header = marked >= 0 ? Desk("Yer imlerinden çıkar", "Remove bookmark") : Desk("Yer imlerine ekle", "Add bookmark") };
+ toggle.Click += (_, _) =>
+ {
+ if (marked >= 0) bookmarks.RemoveAt(marked);
+ else bookmarks.Insert(0, new BrowserBookmark(tab.Title, tab.Url));
+ _state = _state with { Bookmarks = bookmarks };
+ _state.Save();
+ UpdateAddress();
+ };
+ menu.Items.Add(toggle);
+ }
+ if (bookmarks.Count > 0) menu.Items.Add(new Separator());
+ foreach (var bookmark in bookmarks.Take(30))
+ {
+ var item = new MenuItem { Header = bookmark.Title.Length > 60 ? bookmark.Title[..60] + "…" : bookmark.Title, ToolTip = bookmark.Url };
+ item.Click += (_, _) => Go(bookmark.Url);
+ menu.Items.Add(item);
+ }
+ menu.IsOpen = true;
+ }
+
+ private void ToggleCapture()
+ {
+ _state = _state with { HideFromCapture = !_state.HideFromCapture };
+ _state.Save();
+ ApplyCapture();
+ }
+
+ /// <summary>Hidden from screen recording and sharing (others see nothing where the browser is).</summary>
+ private void ApplyCapture()
+ {
+ if (_handle != 0) SetWindowDisplayAffinity(_handle, _state.HideFromCapture ? 0x11u : 0u);
+ _capturePath.Stroke = _state.HideFromCapture ? Gold : Dim;
+ _capture.ToolTip = _state.HideFromCapture
+ ? Desk("Ekran kaydında ve paylaşımında gizli (göstermek için tıklayın)", "Hidden from screen recording and sharing (click to show)")
+ : Desk("Ekran kaydında ve paylaşımında gizle", "Hide from screen recording and sharing");
+ }
+
+ // ---- Full screen video ----------------------------------------------------------------------
+
+ private void EnterFullScreen()
+ {
+ if (_fullScreen) return;
+ _fullScreen = true;
+ _restore = new Rect(Left, Top, Width, Height);
+ _chrome.Visibility = Visibility.Collapsed;
+ _layout.Margin = new Thickness(0);
+ _pages.Margin = new Thickness(0);
+ Left = 0;
+ Top = 0;
+ Width = SystemParameters.PrimaryScreenWidth;
+ Height = SystemParameters.PrimaryScreenHeight;
+ ApplyRegion();
+ }
+
+ private void LeaveFullScreen()
+ {
+ if (!_fullScreen) return;
+ _fullScreen = false;
+ _chrome.Visibility = Visibility.Visible;
+ _layout.Margin = new Thickness(Fillet, 0, Fillet, 0);
+ _pages.Margin = new Thickness(10, 0, 10, 10);
+ Left = _restore.Left;
+ Top = _restore.Top;
+ Width = _restore.Width;
+ Height = _restore.Height;
+ ApplyRegion();
+ }
+
+ // ---- Keys -----------------------------------------------------------------------------------
+
+ private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
+ {
+ var key = e.Key == Key.System ? e.SystemKey : e.Key;
+ var control = Keyboard.Modifiers.HasFlag(ModifierKeys.Control);
+ var shift = Keyboard.Modifiers.HasFlag(ModifierKeys.Shift);
+ var alt = Keyboard.Modifiers.HasFlag(ModifierKeys.Alt);
+ var handled = true;
+ if (control && key == Key.T) AddTab(Home, true, focusAddress: true);
+ else if (control && key == Key.W && _active is { } tab) CloseTab(tab);
+ else if ((control && key == Key.L) || key == Key.F6) _address.Focus();
+ else if (control && key == Key.Tab && _tabs.Count > 1 && _active is { } current)
+ Select(_tabs[(_tabs.IndexOf(current) + (shift ? _tabs.Count - 1 : 1)) % _tabs.Count]);
+ else if (key == Key.F5 || (control && key == Key.R)) Core()?.Reload();
+ else if (alt && key == Key.Left) Core()?.GoBack();
+ else if (alt && key == Key.Right) Core()?.GoForward();
+ else if (key == Key.Escape && !_address.IsKeyboardFocusWithin)
+ {
+ if (_fullScreen) LeaveFullScreen();
+ else Collapse();
+ }
+ else handled = false;
+ e.Handled = handled;
+ }
+
+ // ---- Small helpers ---------------------------------------------------------------------------
+
+ private static string Desk(string turkish, string english) => QiDock.DesktopWidgets.Desk.L(turkish, english);
+
+ private static SolidColorBrush Solid(byte a, byte r, byte g, byte b)
+ {
+ var brush = new SolidColorBrush(Color.FromArgb(a, r, g, b));
+ brush.Freeze();
+ return brush;
+ }
+
+ /// <summary>A 24-unit outline icon kept at its own proportions.</summary>
+ private static Path Icon(string data, double size)
+ {
+ var path = new Path
+ {
+ Data = Geometry.Parse(data),
+ Stroke = Bright,
+ StrokeThickness = 2,
+ StrokeStartLineCap = PenLineCap.Round,
+ StrokeEndLineCap = PenLineCap.Round,
+ StrokeLineJoin = PenLineJoin.Round
+ };
+ var canvas = new Canvas { Width = 24, Height = 24 };
+ canvas.Children.Add(path);
+ _ = new Viewbox { Width = size, Height = size, Child = canvas };
+ return path;
+ }
+
+ private static Border Button(UIElement content, Action click, string tooltip, double width = 32, double height = 30)
+ {
+ if (content is Path { Parent: Canvas { Parent: Viewbox box } }) content = box;
+ var button = new Border { Width = width, Height = height, CornerRadius = new CornerRadius(8), Background = Brushes.Transparent, Child = content, ToolTip = tooltip, VerticalAlignment = VerticalAlignment.Center };
+ System.Windows.Automation.AutomationProperties.SetName(button, tooltip);
+ button.MouseEnter += (_, _) => button.Background = Hover;
+ button.MouseLeave += (_, _) => button.Background = Brushes.Transparent;
+ button.MouseLeftButtonDown += (_, e) => e.Handled = true;
+ button.MouseLeftButtonUp += (_, e) =>
+ {
+ e.Handled = true;
+ click();
+ };
+ return button;
+ }
+
+ private static void Place(Grid grid, UIElement element, int column)
+ {
+ Grid.SetColumn(element, column);
+ grid.Children.Add(element);
+ }
+
+ [DllImport("gdi32.dll")]
+ private static extern nint CreatePolygonRgn(NativePoint[] points, int count, int fillMode);
+
+ [DllImport("gdi32.dll")]
+ private static extern nint CreateRectRgn(int left, int top, int right, int bottom);
+
+ [DllImport("user32.dll")]
+ private static extern int SetWindowRgn(nint window, nint region, [MarshalAs(UnmanagedType.Bool)] bool redraw);
+
+ [DllImport("user32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool SetWindowDisplayAffinity(nint window, uint affinity);
+
+ [DllImport("user32.dll")]
+ private static extern nint GetForegroundWindow();
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct NativePoint { public int X, Y; }
+
+ [DllImport("user32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool GetCursorPos(out NativePoint point);
+
+ [DllImport("user32.dll")]
+ private static extern short GetAsyncKeyState(int key);
+
+ [DllImport("user32.dll")]
+ private static extern uint GetWindowThreadProcessId(nint window, out uint processId);
+
+ [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW")]
+ private static extern nint GetWindowLongPtr(nint window, int index);
+
+ [DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW")]
+ private static extern nint SetWindowLongPtr(nint window, int index, nint value);
+}
diff --git a/Design/Widgets.xaml b/Design/Widgets.xaml
index 3ae3da6..13b6797 100644
--- a/Design/Widgets.xaml
+++ b/Design/Widgets.xaml
@@ -314,6 +314,7 @@
<StreamGeometry x:Key="IconTrash">M3 6h18 M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6 M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2</StreamGeometry>
<StreamGeometry x:Key="IconCamera">M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z M12 13m-3 0a3 3 0 1 0 6 0a3 3 0 1 0-6 0</StreamGeometry>
<StreamGeometry x:Key="IconClipboard">M9 2h6a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2</StreamGeometry>
+ <StreamGeometry x:Key="IconPerson">M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2 M12 7m-4 0a4 4 0 1 0 8 0a4 4 0 1 0-8 0</StreamGeometry>
<StreamGeometry x:Key="IconSmile">M12 12m-10 0a10 10 0 1 0 20 0a10 10 0 1 0-20 0 M8 14s1.5 2 4 2 4-2 4-2 M9 9h0.01 M15 9h0.01</StreamGeometry>
<StreamGeometry x:Key="IconCalculator">M6 2h12a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z M8 6h8 M16 14v4 M16 10h0.01 M12 10h0.01 M8 10h0.01 M12 14h0.01 M8 14h0.01 M12 18h0.01 M8 18h0.01</StreamGeometry>
<StreamGeometry x:Key="IconLock">M5 11h14a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2z M7 11V7a5 5 0 0 1 10 0v4</StreamGeometry>
@@ -339,6 +340,12 @@
<StreamGeometry x:Key="IconSwap">M21 16l-4 4-4-4 M17 20V4 M3 8l4-4 4 4 M7 4v16</StreamGeometry>
<StreamGeometry x:Key="IconFolderOpen">M6 14l1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69 0.9l0.81 1.2a2 2 0 0 0 1.67 0.9H18a2 2 0 0 1 2 2v2</StreamGeometry>
<StreamGeometry x:Key="IconCopy">M10 8h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H10a2 2 0 0 1-2-2V10a2 2 0 0 1 2-2z M4 16c-1.1 0-2-0.9-2-2V4c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2</StreamGeometry>
+ <StreamGeometry x:Key="IconScissors">M6 6m-3 0a3 3 0 1 0 6 0a3 3 0 1 0-6 0 M6 18m-3 0a3 3 0 1 0 6 0a3 3 0 1 0-6 0 M20 4L8.12 15.88 M14.47 14.48L20 20 M8.12 8.12L12 12</StreamGeometry>
+ <StreamGeometry x:Key="IconTerminal">M4 17l6-6-6-6 M12 19h8</StreamGeometry>
+ <StreamGeometry x:Key="IconArchive">M3 3h18v5H3z M5 8v11a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8 M10 12h4</StreamGeometry>
+ <StreamGeometry x:Key="IconArrowUpDown">M3 16l4 4 4-4 M7 20V4 M21 8l-4-4-4 4 M17 4v16</StreamGeometry>
+ <StreamGeometry x:Key="IconMouse">M12 2a7 7 0 0 1 7 7v6a7 7 0 0 1-14 0V9a7 7 0 0 1 7-7z M12 6v4</StreamGeometry>
+ <StreamGeometry x:Key="IconHeadphones">M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3</StreamGeometry>
<StreamGeometry x:Key="IconRotate">M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8 M3 3v5h5</StreamGeometry>
<StreamGeometry x:Key="IconLink">M10 13a5 5 0 0 0 7.54 0.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71 M14 11a5 5 0 0 0-7.54-0.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71</StreamGeometry>
<StreamGeometry x:Key="IconWifi">M12 20h0.01 M2 8.82a15 15 0 0 1 20 0 M5 12.86a10 10 0 0 1 14 0 M8.5 16.43a5 5 0 0 1 7 0</StreamGeometry>
diff --git a/DesktopWidgets/DeskCardFace.cs b/DesktopWidgets/DeskCardFace.cs
new file mode 100644
index 0000000..b8d3cee
--- /dev/null
+++ b/DesktopWidgets/DeskCardFace.cs
@@ -0,0 +1,140 @@
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using System.Windows.Media.Effects;
+using QiDock.Services.Widgets;
+
+namespace QiDock.DesktopWidgets;
+
+/// <summary>
+/// The surface of one desktop card. As glass (the default): the wallpaper behind it, softened, under a veil that is
+/// darker where the picture is bright so white text stays readable, a soft sheen from above, and a thin rim that
+/// catches the light on the top-left and bottom-right edges. Without glass, or with no wallpaper to read: the dark
+/// card. The layers are plain fills; the shadow is its own layer so a ticking widget never redraws its blur.
+/// </summary>
+internal sealed class DeskCardFace
+{
+ public const double Radius = 24;
+
+ /// <summary>Glass or the dark card, for every widget on the desktop (kept in the widget layout).</summary>
+ public static bool GlassEnabled { get; set; } = true;
+
+ private static readonly Brush Rim = GlassLook.Rim;
+ private static readonly Brush Sheen = GlassLook.Sheen;
+ private static readonly Brush Bare = QiDock.Widgets.Ui.Solid("#01000000");
+
+ private readonly Border _shadow;
+ private readonly Border _glass;
+ private readonly Border _veil;
+ private readonly ImageBrush _picture = new() { Stretch = Stretch.Fill, ViewboxUnits = BrushMappingMode.Absolute };
+ private readonly DropShadowEffect _shadowEffect;
+ private bool _bare;
+
+ /// <summary>The widget covers the card with its own picture: no glass, veil or light rim (they showed at its edge).</summary>
+ public bool Covered { get; set; }
+ private Rect _area;
+
+ public DeskCardFace()
+ {
+ RenderOptions.SetBitmapScalingMode(_picture, BitmapScalingMode.HighQuality);
+ _shadowEffect = new DropShadowEffect { Color = Colors.Black, BlurRadius = 24, ShadowDepth = 5, Direction = 270, Opacity = 0.38, RenderingBias = RenderingBias.Performance };
+ _shadow = new Border { CornerRadius = new CornerRadius(Radius), Background = DeskUi.CardFill, Effect = _shadowEffect };
+ _glass = new Border { CornerRadius = new CornerRadius(Radius), Background = _picture };
+ _veil = new Border { CornerRadius = new CornerRadius(Radius), Child = new Border { CornerRadius = new CornerRadius(Radius), Background = Sheen } };
+ Card = new Border { CornerRadius = new CornerRadius(Radius), BorderThickness = new Thickness(1), Padding = new Thickness(14) };
+ Card.SizeChanged += (_, e) => Card.Clip = new RectangleGeometry(new Rect(e.NewSize), Radius, Radius);
+ Root = new Grid();
+ Root.Children.Add(_shadow);
+ Root.Children.Add(_glass);
+ Root.Children.Add(_veil);
+ Root.Children.Add(Card);
+ Apply();
+ }
+
+ public Grid Root { get; }
+
+ /// <summary>The card itself: its child is the widget.</summary>
+ public Border Card { get; }
+
+ public void SetSize(Size size, Thickness padding, bool bare)
+ {
+ foreach (var layer in new[] { _shadow, _glass, _veil, Card })
+ {
+ layer.Width = size.Width;
+ layer.Height = size.Height;
+ }
+ Card.Padding = bare ? new Thickness(0) : padding;
+ _bare = bare;
+ Apply();
+ }
+
+ /// <summary>Where the card is on the screen (screen units), so the glass shows the wallpaper behind it.</summary>
+ public void Place(Rect area)
+ {
+ if (_area == area) return;
+ _area = area;
+ if (_glass.Visibility == Visibility.Visible) Look();
+ }
+
+ /// <summary>The wallpaper or the glass setting changed.</summary>
+ public void Apply()
+ {
+ if (_bare)
+ {
+ // Straight on the wallpaper: no card, no shadow. An almost invisible fill keeps the whole area draggable
+ // (fully clear pixels of a layered window let clicks through).
+ _shadow.Visibility = _glass.Visibility = _veil.Visibility = Visibility.Collapsed;
+ Card.Background = Bare;
+ Card.BorderBrush = Brushes.Transparent;
+ return;
+ }
+ _shadow.Visibility = Visibility.Visible;
+ var glass = GlassEnabled && WallpaperGlass.Image is not null;
+ if (!glass)
+ {
+ _glass.Visibility = _veil.Visibility = Visibility.Collapsed;
+ Card.Background = DeskUi.CardFill;
+ Card.BorderBrush = DeskUi.CardStroke;
+ _shadowEffect.Opacity = 0.38;
+ _shadowEffect.BlurRadius = 24;
+ return;
+ }
+ if (Covered)
+ {
+ _glass.Visibility = _veil.Visibility = Visibility.Collapsed;
+ Card.Background = Brushes.Transparent;
+ Card.BorderBrush = Brushes.Transparent;
+ _shadowEffect.Opacity = 0.3;
+ _shadowEffect.BlurRadius = 26;
+ return;
+ }
+ _glass.Visibility = _veil.Visibility = Visibility.Visible;
+ Card.Background = Brushes.Transparent;
+ Card.BorderBrush = Rim;
+ // Glass casts a lighter, wider shadow than a solid card.
+ _shadowEffect.Opacity = 0.24;
+ _shadowEffect.BlurRadius = 30;
+ Look();
+ }
+
+ private void Look()
+ {
+ if (WallpaperGlass.Image is null || _area.Width <= 0 || double.IsNaN(_area.X) || double.IsNaN(_area.Y)) return;
+ // Darker over a bright picture, lighter over a dark one: white text keeps about the same contrast.
+ var veil = GlassLook.Veil(WallpaperGlass.Light(_area));
+ var size = new Size(_glass.Width, _glass.Height);
+ if (double.IsNaN(size.Width) || size.Width <= 0) size = _area.Size;
+ if (GlassLook.Surface(new Rect(size), _area, veil, sheen: false, frost: false) is { } glass)
+ {
+ _glass.Background = glass;
+ _veil.Background = null;
+ return;
+ }
+ // Could not draw the glass picture: the veil over the picture brush, as before.
+ _picture.ImageSource = WallpaperGlass.Image;
+ _picture.Viewbox = WallpaperGlass.Behind(_area);
+ _glass.Background = _picture;
+ _veil.Background = new SolidColorBrush(veil);
+ }
+
+}
diff --git a/DesktopWidgets/DeskCatalog.cs b/DesktopWidgets/DeskCatalog.cs
index 7383a4f..4f8f4c9 100644
--- a/DesktopWidgets/DeskCatalog.cs
+++ b/DesktopWidgets/DeskCatalog.cs
@@ -8,8 +8,10 @@ internal static class DeskCatalog
{
public static readonly IReadOnlyList<DeskKind> All =
[
+ new("bigclock", DeskCategory.Time, "Büyük saat", "Big clock", "Duvar kâğıdının üstünde kocaman saat, tarih ve gün; kartsız.", "A huge clock, date and weekday right on the wallpaper; no card.",
+ [Medium, Large, Hero], Hero, () => new BigClockWidget()),
new("clock", DeskCategory.Time, "Dijital saat", "Digital clock", "Saat, gün ve tarih; orta boyda hava durumu da var.", "Time, weekday and date; the medium size adds the weather.",
- [Mini, Small, Strip, Medium], Small, () => new DigitalClockWidget()),
+ [Mini, Small, Strip, Medium, Tall], Small, () => new DigitalClockWidget()),
new("analog", DeskCategory.Time, "Analog saat", "Analog clock", "Akrep, yelkovan ve saniye; açık ya da koyu kadran.", "Hour, minute and second hands; light or dark face.",
[Small, Large], Small, () => new AnalogClockWidget()),
new("flip", DeskCategory.Time, "Rakam kartları", "Flip clock", "Saat ve dakika büyük kartlarda.", "Hours and minutes on large tiles.",
@@ -17,61 +19,65 @@ internal static class DeskCatalog
new("date", DeskCategory.Time, "Tarih", "Date", "Takvim yaprağı gibi bugünün tarihi.", "Today's date like a calendar page.",
[Mini, Small, Strip], Small, () => new DateWidget()),
new("calendar", DeskCategory.Time, "Takvim", "Calendar", "Bu hafta, ay görünümü ve iCal takviminizdeki etkinlikler.", "This week, the month and events from your iCal calendar.",
- [Small, Strip, Medium, Large], Medium, () => new CalendarDeskWidget()),
+ [Small, Strip, Medium, Large, Tall], Medium, () => new CalendarDeskWidget()),
new("progress", DeskCategory.Time, "Yıl ilerlemesi", "Year progress", "Yılın, ayın, haftanın ya da günün ne kadarı geçti.", "How much of the year, month, week or day has passed.",
[Small, Strip, Medium], Strip, () => new ProgressWidget()),
new("worldclock", DeskCategory.Time, "Dünya saati", "World clock", "Üç şehrin saati ve farkı.", "Three cities' time and offset.",
- [Small, Strip, Medium], Strip, () => new WorldClockDeskWidget()),
+ [Small, Strip, Medium, Tall], Strip, () => new WorldClockDeskWidget()),
new("timer", DeskCategory.Time, "Zamanlayıcı", "Timer", "Geri sayım; süre dolunca haber verir.", "Countdown that tells you when time is up.",
[Mini, Small, Strip], Strip, () => new TimerWidget()),
new("stopwatch", DeskCategory.Time, "Kronometre", "Stopwatch", "Saniyenin onda biri hassasiyetinde.", "Down to a tenth of a second.",
[Mini, Strip], Strip, () => new StopwatchWidget()),
new("weather", DeskCategory.Weather, "Hava durumu", "Weather", "Şu an, saatlik ve günlük tahmin (Ayarlar'daki şehir).", "Now, hourly and daily forecast (city from Settings).",
- [Mini, Small, Strip, Medium, Large], Medium, () => new WeatherDeskWidget()),
+ [Mini, Small, Strip, Medium, Large, Tall], Medium, () => new WeatherDeskWidget()),
new("sun", DeskCategory.Weather, "Gün doğumu ve batımı", "Sunrise & sunset", "Güneşin gökyüzündeki yeri ve gün uzunluğu.", "The sun's place in the sky and day length.",
[Small, Strip], Strip, () => new SunWidget()),
new("wind", DeskCategory.Weather, "Rüzgâr", "Wind", "Rüzgâr hızı, hamle ve yön pusulası.", "Wind speed, gusts and a direction compass.",
[Small, Strip], Strip, () => new WindWidget()),
new("cpu", DeskCategory.System, "İşlemci", "CPU", "İşlemci yükü halka ya da canlı grafik olarak.", "CPU load as a ring or a live graph.",
- [Mini, Small, Strip, Medium], Strip, () => new MetricWidget(Metric.Cpu)),
+ [Mini, Small, Strip, Medium, Tall], Strip, () => new MetricWidget(Metric.Cpu)),
new("ram", DeskCategory.System, "Bellek", "Memory", "Kullanılan RAM.", "Memory in use.",
[Mini, Small, Strip], Mini, () => new MetricWidget(Metric.Ram)),
new("disk", DeskCategory.System, "Disk", "Disk", "Sistem diskinin doluluğu ve boş alan.", "System drive usage and free space.",
[Mini, Small, Strip], Mini, () => new MetricWidget(Metric.Disk)),
new("battery", DeskCategory.System, "Pil", "Battery", "Pil yüzdesi, şarj durumu ve kalan süre.", "Battery level, charging and time left.",
[Mini, Small, Strip], Mini, () => new MetricWidget(Metric.Battery)),
+ new("devicebattery", DeskCategory.System, "Cihaz pilleri", "Device batteries", "Bağlı fare, klavye ve kulaklığın pil seviyesi (Bluetooth).", "Battery of the connected mouse, keyboard and headphones (Bluetooth).",
+ [Mini, Small, Strip, Medium, Tall], Small, () => new DeviceBatteryWidget()),
new("network", DeskCategory.System, "Ağ hızı", "Network", "İndirme ve yükleme hızı, canlı grafik.", "Download and upload speed with a live graph.",
[Mini, Strip, Medium], Strip, () => new NetworkWidget()),
new("music", DeskCategory.Media, "Müzik", "Music", "Çalan şarkı, kapak ve kontroller (Spotify, tarayıcı…).", "Now playing, artwork and controls (Spotify, browsers…).",
- [Mini, Small, Strip, Medium, Large], Strip, () => new MusicWidget()),
+ [Mini, Small, Strip, Medium, Large, Tall], Strip, () => new MusicWidget()),
new("sound", DeskCategory.Media, "Ses", "Sound", "Ses düzeyi ve sessize alma.", "Volume level and mute.",
[Mini, Strip], Strip, () => new SoundWidget()),
new("todo", DeskCategory.Productivity, "Yapılacaklar", "To-do", "Üst çubuktaki listeyle aynı; işaretle, ekle, sil.", "Same list as the bar; check, add, remove.",
- [Strip, Small, Medium, Large], Small, () => new TodoDeskWidget()),
+ [Strip, Small, Medium, Large, Tall], Small, () => new TodoDeskWidget()),
new("notes", DeskCategory.Productivity, "Not", "Note", "Yapışkan not; yazdığınız saklanır.", "Sticky note; your text is kept.",
- [Small, Medium, Large], Small, () => new NotesWidget()),
+ [Small, Medium, Large, Tall], Small, () => new NotesWidget()),
new("focus", DeskCategory.Productivity, "Odak (Pomodoro)", "Focus (Pomodoro)", "Üst çubuktaki odak sayacıyla aynı; 5 dk mola, 4 turda uzun mola.", "Same timer as the bar; 5 min breaks, a long one every 4 rounds.",
[Small, Strip], Strip, () => new FocusDeskWidget()),
new("reminder", DeskCategory.Productivity, "Hatırlatıcı", "Reminder", "Su iç, mola ver, gözlerini dinlendir… belirli aralıklarla.", "Drink water, take a break, rest your eyes… on a schedule.",
[Small, Strip], Strip, () => new ReminderWidget()),
new("claude", DeskCategory.Ai, "Claude", "Claude", "Claude kullanım sınırları (oturum ve haftalık) ve ne zaman yenileneceği; simgesi uygulamayı açar.", "Claude usage limits (session and weekly) and when they reset; the icon opens the app.",
- [Mini, Small, Strip, Medium], Strip, () => new AiAssistantWidget(AiAssistant.Claude)),
+ [Mini, Small, Strip, Medium, Tall], Strip, () => new AiAssistantWidget(AiAssistant.Claude)),
new("codex", DeskCategory.Ai, "Codex", "Codex", "Codex (ChatGPT) kullanım sınırları ve ne zaman yenileneceği; simgesi uygulamayı açar.", "Codex (ChatGPT) usage limits and when they reset; the icon opens the app.",
- [Mini, Small, Strip, Medium], Strip, () => new AiAssistantWidget(AiAssistant.Codex)),
- new("gemini", DeskCategory.Ai, "Gemini", "Gemini", "Gemini uygulamasını tek tıkla açar.", "Opens the Gemini app in one click.",
- [Mini, Small, Strip, Medium], Strip, () => new AiAssistantWidget(AiAssistant.Gemini)),
+ [Mini, Small, Strip, Medium, Tall], Strip, () => new AiAssistantWidget(AiAssistant.Codex)),
+ new("gemini", DeskCategory.Ai, "Gemini", "Gemini", "Gemini (Antigravity) 5 saatlik kullanım sınırları ve ne zaman yenileneceği; simgesi uygulamayı açar.", "Gemini (Antigravity) five-hour usage limits and when they reset; the icon opens the app.",
+ [Mini, Small, Strip, Medium, Tall], Strip, () => new AiAssistantWidget(AiAssistant.Gemini)),
+ new("opencode", DeskCategory.Ai, "OpenCode", "OpenCode", "OpenCode Go sınırları: 5 saatlik, haftalık ve aylık; simgesi uygulamayı açar.", "OpenCode Go limits: five-hour, weekly and monthly; the icon opens the app.",
+ [Mini, Small, Strip, Medium, Tall], Strip, () => new AiAssistantWidget(AiAssistant.OpenCode)),
new("apps", DeskCategory.Tools, "Uygulamalar", "Apps", "Sık kullandığınız uygulamalar tek tıkla.", "Your favourite apps one click away.",
- [Mini, Small, Strip, Medium, Large], Small, () => new AppsWidget()),
+ [Mini, Small, Strip, Medium, Large, Tall], Small, () => new AppsWidget()),
new("actions", DeskCategory.Tools, "Hızlı eylemler", "Quick actions", "Ekran alıntısı, pano, emoji, hesap makinesi, kilit…", "Screenshot, clipboard, emoji, calculator, lock…",
- [Mini, Small, Strip, Medium], Strip, () => new ActionsWidget()),
+ [Mini, Small, Strip, Medium, Tall], Strip, () => new ActionsWidget()),
new("toggles", DeskCategory.Tools, "Hızlı ayarlar", "Quick settings", "Wi-Fi, Bluetooth, gece ışığı, bildirimler.", "Wi-Fi, Bluetooth, night light, notifications.",
- [Small, Strip], Strip, () => new TogglesWidget()),
+ [Small, Strip, Tall], Strip, () => new TogglesWidget()),
new("websearch", DeskCategory.Tools, "Web'de ara", "Web search", "Yazıp Enter'a basın; varsayılan tarayıcıda açılır.", "Type and press Enter; opens in your browser.",
[Strip], Strip, () => new SearchBoxWidget(true)),
new("filesearch", DeskCategory.Tools, "Windows’ta ara", "Windows search", "Kullanıcı klasörünüzde Windows aramasıyla.", "Windows search in your user folder.",
diff --git a/DesktopWidgets/DeskCore.cs b/DesktopWidgets/DeskCore.cs
index 42aaf41..b84dd62 100644
--- a/DesktopWidgets/DeskCore.cs
+++ b/DesktopWidgets/DeskCore.cs
@@ -10,7 +10,8 @@ using QiDock.Services;
namespace QiDock.DesktopWidgets;
/// <summary>Desktop widget sizes on a 164 DIP grid with 16 DIP gaps (two smalls side by side = one medium).</summary>
-public enum DeskSize { Mini, Small, Strip, Medium, Large }
+/// <remarks>Hero: one very large piece (the big clock), drawn without a card. Tall: a medium stood upright.</remarks>
+public enum DeskSize { Mini, Small, Strip, Medium, Large, Hero, Tall }
/// <summary>One widget placed on the desktop.</summary>
public sealed class DeskItem
@@ -26,6 +27,9 @@ public sealed class DeskItem
public sealed class DeskLayout
{
public bool Initialized { get; set; }
+
+ /// <summary>Cards of frosted glass over the wallpaper (true) or the dark cards.</summary>
+ public bool Glass { get; set; } = true;
public List<DeskItem> Items { get; set; } = [];
}
@@ -83,6 +87,8 @@ internal static class Desk
DeskSize.Small => new Size(Unit, Unit),
DeskSize.Strip => new Size(Unit * 2 + Gap, StripHeight),
DeskSize.Medium => new Size(Unit * 2 + Gap, Unit),
+ DeskSize.Hero => new Size(Unit * 4 + Gap * 3, 460),
+ DeskSize.Tall => new Size(Unit, Unit * 2 + Gap),
_ => new Size(Unit * 2 + Gap, Unit * 2 + Gap)
};
@@ -96,6 +102,8 @@ internal static class Desk
DeskSize.Small => L("Küçük", "Small"),
DeskSize.Strip => L("Şerit", "Strip"),
DeskSize.Medium => L("Orta", "Medium"),
+ DeskSize.Hero => L("Dev", "Huge"),
+ DeskSize.Tall => L("Dikey", "Tall"),
_ => L("Büyük", "Large")
};
@@ -159,6 +167,17 @@ public abstract class DeskWidget : IDisposable
/// <summary>How often <see cref="Tick"/> runs while visible (null: only on data events).</summary>
public virtual TimeSpan? Interval => null;
+
+ /// <summary>Drawn straight on the wallpaper, without the card behind it (the big clock).</summary>
+ public virtual bool Bare => false;
+
+ /// <summary>The widget paints the whole card itself (a song's cover): the card then shows no glass under it.</summary>
+ public virtual bool Covers => false;
+
+ /// <summary>Raised when <see cref="Covers"/> changes.</summary>
+ public event Action? CoversChanged;
+
+ protected void RaiseCoversChanged() => CoversChanged?.Invoke();
public virtual void Tick() { }
private bool _attached;
diff --git a/DesktopWidgets/DeskSheet.cs b/DesktopWidgets/DeskSheet.cs
index 1494ff7..0b1eaa5 100644
--- a/DesktopWidgets/DeskSheet.cs
+++ b/DesktopWidgets/DeskSheet.cs
@@ -16,16 +16,28 @@ internal static class DeskSheet
public static void Render(string path, Func<WidgetSettings> settings, Action done)
{
Desk.Settings = settings;
+ // QIDOCK_SHEET_DESKTOP=1 draws the user's own desktop instead: wallpaper and widgets where they are.
+ if (Environment.GetEnvironmentVariable("QIDOCK_SHEET_DESKTOP") == "1")
+ {
+ RenderDesktop(path, done);
+ return;
+ }
var panel = new WrapPanel { Width = 2300, Background = QiDock.Widgets.Ui.Vertical("#FF5B86C5", "#FF2A4C8C") };
panel.SetResourceReference(System.Windows.Documents.TextElement.FontFamilyProperty, "InterfaceFont");
TextOptions.SetTextFormattingMode(panel, TextFormattingMode.Ideal);
var hosts = new List<SheetHost>();
- foreach (var kind in DeskCatalog.All)
- foreach (var size in kind.Sizes)
+ // QIDOCK_SHEET_ONLY=bigclock,devicebattery renders just those kinds.
+ var only = Environment.GetEnvironmentVariable("QIDOCK_SHEET_ONLY")?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
+ foreach (var kind in DeskCatalog.All.Where(k => only is not { Length: > 0 } || only.Contains(k.Id)))
+ foreach (var (size, style) in kind.Id == "bigclock"
+ ? Kinds.BigClockWidget.Styles.Select(style => (DeskSize.Hero, (string?)style.Id))
+ : kind.Sizes.Select(size => (size, (string?)null)))
{
- var host = new SheetHost(kind, size);
+ // QIDOCK_SHEET_SIZE=Tall renders only that size.
+ if (Environment.GetEnvironmentVariable("QIDOCK_SHEET_SIZE") is { Length: > 0 } onlySize && size.ToString() != onlySize) continue;
+ var host = new SheetHost(kind, size, style);
hosts.Add(host);
- var label = DeskUi.T($"{kind.Id} / {size}", 13, FontWeights.SemiBold, Brushes.White);
+ var label = DeskUi.T($"{kind.Id} / {size} {style}", 13, FontWeights.SemiBold, Brushes.White);
var cell = new StackPanel { Margin = new Thickness(14) };
cell.Children.Add(label);
cell.Children.Add(DeskUi.Margin(host.Card, 0, 6));
@@ -55,11 +67,94 @@ internal static class DeskSheet
timer.Start();
}
+ private static void RenderDesktop(string path, Action done)
+ {
+ Services.Widgets.WallpaperGlass.Refresh();
+ DeskCardFace.GlassEnabled = Environment.GetEnvironmentVariable("QIDOCK_SHEET_GLASS") != "0";
+ var width = SystemParameters.PrimaryScreenWidth;
+ var height = SystemParameters.PrimaryScreenHeight;
+ var canvas = new Canvas { Width = width, Height = height, Background = Brushes.Black };
+ if (Services.Widgets.WallpaperTint.WallpaperFile() is { } file)
+ {
+ var image = new BitmapImage();
+ image.BeginInit();
+ image.CacheOption = BitmapCacheOption.OnLoad;
+ image.UriSource = new Uri(file);
+ image.EndInit();
+ canvas.Background = new ImageBrush(image) { Stretch = Stretch.UniformToFill };
+ }
+ canvas.SetResourceReference(System.Windows.Documents.TextElement.FontFamilyProperty, "InterfaceFont");
+ TextOptions.SetTextFormattingMode(canvas, TextFormattingMode.Ideal);
+ var hosts = new List<DesktopHost>();
+ foreach (var item in DeskStore.Load().Items)
+ {
+ if (DeskCatalog.Find(item.Kind) is not { } kind) continue;
+ var host = new DesktopHost(item, kind);
+ hosts.Add(host);
+ Canvas.SetLeft(host.Face.Root, item.X);
+ Canvas.SetTop(host.Face.Root, item.Y);
+ canvas.Children.Add(host.Face.Root);
+ }
+ var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(6) };
+ timer.Tick += (_, _) =>
+ {
+ timer.Stop();
+ foreach (var host in hosts) host.Widget.Tick();
+ canvas.Measure(new Size(width, height));
+ canvas.Arrange(new Rect(0, 0, width, height));
+ canvas.UpdateLayout();
+ var bitmap = new RenderTargetBitmap((int)width * 2, (int)height * 2, 192, 192, PixelFormats.Pbgra32);
+ bitmap.Render(canvas);
+ var encoder = new PngBitmapEncoder();
+ encoder.Frames.Add(BitmapFrame.Create(bitmap));
+ using (var stream = File.Create(path)) encoder.Save(stream);
+ foreach (var host in hosts) host.Widget.Detach();
+ done();
+ };
+ canvas.Measure(new Size(width, height));
+ canvas.Arrange(new Rect(0, 0, width, height));
+ timer.Start();
+ }
+
+ private sealed class DesktopHost : IDeskHost
+ {
+ public DesktopHost(DeskItem item, DeskKind kind)
+ {
+ Item = item;
+ Widget = kind.Create();
+ Widget.Host = this;
+ var dims = Desk.Dimensions(item.Size);
+ Face.SetSize(dims, Desk.Padding(item.Size), Widget.Bare);
+ Face.Place(new Rect(item.X, item.Y, dims.Width, dims.Height));
+ Face.Card.Child = Widget.Build();
+ Widget.Attach();
+ }
+
+ public DeskCardFace Face { get; } = new();
+ public DeskItem Item { get; }
+ public DeskWidget Widget { get; }
+ public bool IsLive => true;
+ public void Save() { }
+ public void FocusInput(IInputElement element) { }
+ public void Rebuild() => Face.Card.Child = Widget.Build();
+ }
+
private sealed class SheetHost : IDeskHost
{
- public SheetHost(DeskKind kind, DeskSize size)
+ private static int _count;
+
+ public SheetHost(DeskKind kind, DeskSize size, string? style = null)
{
Item = new DeskItem { Kind = kind.Id, Size = size };
+ if (style is not null) Item.Options["style"] = style;
+ // QIDOCK_SHEET_LANG=de writes the big clocks' dates in that language.
+ if (style is not null && Environment.GetEnvironmentVariable("QIDOCK_SHEET_LANG") is { Length: > 0 } lang) Item.Options["lang"] = lang;
+ // QIDOCK_SHEET_TINT=cycle gives each big clock a different colour from the palette.
+ if (style is not null && Environment.GetEnvironmentVariable("QIDOCK_SHEET_TINT") == "cycle")
+ {
+ var palette = Kinds.BigClockWidget.Palette;
+ Item.Options["tint"] = palette[(_count++ + 2) % palette.Length].Id;
+ }
Widget = kind.Create();
Widget.Host = this;
var dims = Desk.Dimensions(size);
@@ -75,6 +170,12 @@ internal static class DeskSheet
Child = Widget.Build()
};
Card.Clip = new RectangleGeometry(new Rect(0, 0, dims.Width, dims.Height), 24, 24);
+ if (Widget.Bare)
+ {
+ Card.Background = Brushes.Transparent;
+ Card.BorderBrush = Brushes.Transparent;
+ Card.Padding = new Thickness(0);
+ }
Widget.Attach();
}
diff --git a/DesktopWidgets/DeskVisuals.cs b/DesktopWidgets/DeskVisuals.cs
index 40c8e94..2422258 100644
--- a/DesktopWidgets/DeskVisuals.cs
+++ b/DesktopWidgets/DeskVisuals.cs
@@ -14,8 +14,8 @@ internal static class DeskUi
public static readonly Brush CardFill = Ui.Solid("#F21C1C1F");
public static readonly Brush CardStroke = Ui.Solid("#1EFFFFFF");
public static readonly Brush Text = Ui.Solid("#FFF5F5F7");
- public static readonly Brush Secondary = Ui.Solid("#FF8E8E93");
- public static readonly Brush Tertiary = Ui.Solid("#FF5E5E63");
+ public static readonly Brush Secondary = Ui.Solid("#99EBEBF5");
+ public static readonly Brush Tertiary = Ui.Solid("#4DEBEBF5");
public static readonly Brush Track = Ui.Solid("#24FFFFFF");
public static readonly Brush Inset = Ui.Solid("#14FFFFFF");
public static readonly Brush InsetHover = Ui.Solid("#24FFFFFF");
diff --git a/DesktopWidgets/DeskWidgetManager.cs b/DesktopWidgets/DeskWidgetManager.cs
index 8e4f19c..b8cbf57 100644
--- a/DesktopWidgets/DeskWidgetManager.cs
+++ b/DesktopWidgets/DeskWidgetManager.cs
@@ -1,5 +1,6 @@
using System.Windows;
using System.Windows.Threading;
+using QiDock.Services.Widgets;
namespace QiDock.DesktopWidgets;
@@ -13,6 +14,8 @@ internal sealed class DeskWidgetManager : IDisposable
private readonly List<DeskWidgetWindow> _windows = [];
private readonly DispatcherTimer _saveTimer = new(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(400) };
private readonly DispatcherTimer _recreateTimer = new(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(3) };
+ // Windows writes the new wallpaper file a moment after it says the desktop changed.
+ private readonly DispatcherTimer _wallpaperTimer = new(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(1.5) };
private IReadOnlyList<Rect> _covers = [];
private DeskGallery? _gallery;
private bool _disposed;
@@ -30,6 +33,40 @@ internal sealed class DeskWidgetManager : IDisposable
_recreateTimer.Stop();
Reopen();
};
+ _wallpaperTimer.Tick += (_, _) =>
+ {
+ _wallpaperTimer.Stop();
+ CheckWallpaper();
+ };
+ }
+
+ private int _glassVersion = -1;
+
+ public bool Glass => _layout.Glass;
+
+ public void SetGlass(bool glass)
+ {
+ _layout.Glass = glass;
+ DeskCardFace.GlassEnabled = glass;
+ foreach (var window in _windows) window.RefreshGlass();
+ Save();
+ }
+
+ private void CheckWallpaper()
+ {
+ if (_disposed) return;
+ WallpaperGlass.Refresh();
+ // Compared with what the cards show, not with Refresh's answer: the dock may have read the new picture first.
+ if (WallpaperGlass.Version == _glassVersion) return;
+ _glassVersion = WallpaperGlass.Version;
+ foreach (var window in _windows) window.RefreshGlass();
+ }
+
+ private void OnPreferenceChanged(object? sender, Microsoft.Win32.UserPreferenceChangedEventArgs e)
+ {
+ if (e.Category != Microsoft.Win32.UserPreferenceCategory.Desktop) return;
+ _wallpaperTimer.Stop();
+ _wallpaperTimer.Start();
}
public IReadOnlyList<DeskItem> Items => _layout.Items;
@@ -42,6 +79,9 @@ internal sealed class DeskWidgetManager : IDisposable
_layout.Initialized = true;
Save();
}
+ DeskCardFace.GlassEnabled = _layout.Glass;
+ WallpaperGlass.Refresh();
+ Microsoft.Win32.SystemEvents.UserPreferenceChanged += OnPreferenceChanged;
foreach (var item in _layout.Items.ToList()) Open(item);
}
@@ -142,6 +182,8 @@ internal sealed class DeskWidgetManager : IDisposable
window.SetLive(IsUncovered(window));
}
}
+ // A slideshow may have moved on while they were away.
+ if (!hidden) CheckWallpaper();
}
private bool IsUncovered(DeskWidgetWindow window)
@@ -251,8 +293,10 @@ internal sealed class DeskWidgetManager : IDisposable
public void Dispose()
{
_disposed = true;
+ Microsoft.Win32.SystemEvents.UserPreferenceChanged -= OnPreferenceChanged;
_saveTimer.Stop();
_recreateTimer.Stop();
+ _wallpaperTimer.Stop();
DeskStore.Save(_layout);
_gallery?.Close();
foreach (var window in _windows.ToList())
diff --git a/DesktopWidgets/DeskWidgetWindow.cs b/DesktopWidgets/DeskWidgetWindow.cs
index 018cc7c..46cdf72 100644
--- a/DesktopWidgets/DeskWidgetWindow.cs
+++ b/DesktopWidgets/DeskWidgetWindow.cs
@@ -19,8 +19,7 @@ internal sealed class DeskWidgetWindow : Window, IDeskHost
{
public const double Shadow = 16;
private readonly DeskWidgetManager _manager;
- private readonly Border _card;
- private readonly Border _shadow;
+ private readonly DeskCardFace _face = new();
private readonly DispatcherTimer _timer = new(DispatcherPriority.Background);
private NativePoint? _press;
private double _pressLeft, _pressTop;
@@ -56,30 +55,17 @@ internal sealed class DeskWidgetWindow : Window, IDeskHost
SetResourceReference(FontFamilyProperty, "InterfaceFont");
TextOptions.SetTextFormattingMode(this, TextFormattingMode.Ideal);
- // The shadow is a separate layer so content updates (a ticking clock) never re-render the blur.
- _shadow = new Border
- {
- CornerRadius = new CornerRadius(24),
- Background = DeskUi.CardFill,
- Effect = new DropShadowEffect { Color = Colors.Black, BlurRadius = 24, ShadowDepth = 5, Direction = 270, Opacity = 0.38, RenderingBias = RenderingBias.Performance }
- };
- _card = new Border
- {
- CornerRadius = new CornerRadius(24),
- Background = DeskUi.CardFill,
- BorderBrush = DeskUi.CardStroke,
- BorderThickness = new Thickness(1),
- Padding = new Thickness(14)
- };
- _card.SizeChanged += (_, e) => _card.Clip = new RectangleGeometry(new Rect(e.NewSize), 24, 24);
- var layers = new Grid { Margin = new Thickness(Shadow) };
- layers.Children.Add(_shadow);
- layers.Children.Add(_card);
- Content = layers;
+ _face.Root.Margin = new Thickness(Shadow);
+ Content = _face.Root;
ApplySize();
Left = item.X - Shadow;
Top = item.Y - Shadow;
+ // The glass shows the wallpaper behind the card, also while it is being dragged.
+ LocationChanged += (_, _) => PlaceGlass();
+ // Placed before the window had its place (Left/Top not set yet): place it again once it is on screen.
+ SourceInitialized += (_, _) => PlaceGlass();
+ IsVisibleChanged += (_, _) => { if (IsVisible) PlaceGlass(); };
_timer.Tick += (_, _) => Widget.Tick();
PreviewMouseLeftButtonDown += OnPress;
@@ -94,18 +80,46 @@ internal sealed class DeskWidgetWindow : Window, IDeskHost
Rebuild();
}
+ private bool _coverHooked;
+
+ /// <summary>A widget that paints the whole card (music with a cover) gets a card without glass under it.</summary>
+ private void CoverFace()
+ {
+ if (!_coverHooked)
+ {
+ _coverHooked = true;
+ Widget.CoversChanged += CoverFace;
+ }
+ if (_face.Covered == Widget.Covers) return;
+ _face.Covered = Widget.Covers;
+ _face.Apply();
+ }
+
private void ApplySize()
{
- var size = Desk.Dimensions(Item.Size);
- _card.Width = _shadow.Width = size.Width;
- _card.Height = _shadow.Height = size.Height;
// Strips are short; keep their content from touching the edges but use the height.
- _card.Padding = Desk.Padding(Item.Size);
+ _face.SetSize(Desk.Dimensions(Item.Size), Desk.Padding(Item.Size), Widget.Bare);
+ PlaceGlass();
+ }
+
+ private void PlaceGlass()
+ {
+ if (double.IsNaN(Left) || double.IsNaN(Top)) return;
+ var size = Desk.Dimensions(Item.Size);
+ _face.Place(new Rect(Left + Shadow, Top + Shadow, size.Width, size.Height));
+ }
+
+ /// <summary>The wallpaper or the glass setting changed.</summary>
+ public void RefreshGlass()
+ {
+ _face.Apply();
+ PlaceGlass();
}
public void Rebuild()
{
- _card.Child = Widget.Build();
+ _face.Card.Child = Widget.Build();
+ CoverFace();
if (IsLive) Widget.Tick();
}
@@ -181,9 +195,25 @@ internal sealed class DeskWidgetWindow : Window, IDeskHost
}
menu.Items.Add(sizes);
}
+ if (CanTurn)
+ {
+ // Lying (wide) or standing (tall): the widget turns in place and keeps its last wide size for the way back.
+ var turn = Entry("Yön", "Orientation", null);
+ var wide = new MenuItem { Header = Desk.L("Yatay", "Landscape"), IsChecked = Item.Size != DeskSize.Tall };
+ wide.Click += (_, _) => Turn(false);
+ var tall = new MenuItem { Header = Desk.L("Dikey", "Portrait"), IsChecked = Item.Size == DeskSize.Tall };
+ tall.Click += (_, _) => Turn(true);
+ turn.Items.Add(wide);
+ turn.Items.Add(tall);
+ menu.Items.Add(turn);
+ }
var before = menu.Items.Count;
Widget.AddMenuItems(menu);
menu.Items.Add(new Separator());
+ var glass = Entry("Cam görünüm", "Glass look", null);
+ glass.IsChecked = _manager.Glass;
+ glass.Click += (_, _) => _manager.SetGlass(!_manager.Glass);
+ menu.Items.Add(glass);
var add = Entry("Widget ekle…", "Add widget…", "IconPlus");
add.Click += (_, _) => _manager.ShowGallery();
menu.Items.Add(add);
@@ -194,6 +224,23 @@ internal sealed class DeskWidgetWindow : Window, IDeskHost
menu.IsOpen = true;
}
+ private bool CanTurn => Kind.Sizes.Contains(DeskSize.Tall) && Kind.Sizes.Any(s => s is DeskSize.Strip or DeskSize.Medium or DeskSize.Large);
+
+ public void Turn(bool upright)
+ {
+ if (upright == (Item.Size == DeskSize.Tall)) return;
+ if (upright)
+ {
+ Item.Options["wide"] = Item.Size.ToString();
+ ChangeSize(DeskSize.Tall);
+ return;
+ }
+ var back = Item.Options.TryGetValue("wide", out var stored) && Enum.TryParse<DeskSize>(stored, out var size) && size != DeskSize.Tall && Kind.Sizes.Contains(size)
+ ? size
+ : Kind.Sizes.Contains(DeskSize.Medium) ? DeskSize.Medium : Kind.Sizes.Contains(DeskSize.Strip) ? DeskSize.Strip : Kind.DefaultSize;
+ ChangeSize(back);
+ }
+
private static MenuItem Entry(string tr, string en, string? icon)
{
var item = new MenuItem { Header = Desk.L(tr, en) };
diff --git a/DesktopWidgets/Kinds/AiWidgets.cs b/DesktopWidgets/Kinds/AiWidgets.cs
index 19dc4c8..d4bb2b8 100644
--- a/DesktopWidgets/Kinds/AiWidgets.cs
+++ b/DesktopWidgets/Kinds/AiWidgets.cs
@@ -13,14 +13,17 @@ namespace QiDock.DesktopWidgets.Kinds;
/// <summary>An AI assistant on the desktop: its app (icon, name, colour) and, when known, its usage provider.</summary>
/// <param name="Plate">A light tile drawn behind an icon that is dark itself (Codex's black knot).</param>
-internal sealed record AiAssistant(string Name, string AppId, string? UsageProvider, Color From, Color To, bool Plate = false)
+/// <param name="Windows">How many limits the large tile lists (OpenCode Go has three: 5 hours, week, month).</param>
+internal sealed record AiAssistant(string Name, string AppId, string? UsageProvider, Color From, Color To, bool Plate = false, int Windows = 2)
{
public static readonly AiAssistant Claude = new("Claude", "Claude_pzs8sxrjxfjjc!Claude", AiUsageService.ClaudeId,
Color.FromRgb(0xE0, 0x86, 0x5F), Color.FromRgb(0xC1, 0x5F, 0x3C));
public static readonly AiAssistant Codex = new("Codex", "OpenAI.Codex_2p2nqsd0c76g0!App", AiUsageService.CodexId,
Color.FromRgb(0x5B, 0x8C, 0xFF), Color.FromRgb(0x2F, 0x5B, 0xD8), Plate: true);
- public static readonly AiAssistant Gemini = new("Gemini", "com.google.gemini.windows", null,
+ public static readonly AiAssistant Gemini = new("Gemini", "com.google.gemini.windows", AiUsageService.GeminiId,
Color.FromRgb(0x4F, 0x9B, 0xF5), Color.FromRgb(0xA4, 0x6B, 0xE8));
+ public static readonly AiAssistant OpenCode = new("OpenCode", "ai.opencode.desktop", AiUsageService.OpenCodeId,
+ Color.FromRgb(0x9A, 0xA3, 0xB5), Color.FromRgb(0x5E, 0x67, 0x7A), Windows: 3);
public Brush Accent => new SolidColorBrush(From);
@@ -46,7 +49,7 @@ internal sealed record AiAssistant(string Name, string AppId, string? UsageProvi
}
/// <summary>
-/// Claude and Codex usage shared by every AI widget on the desktop: read once, every two minutes, only while one of
+/// Claude, Codex, Gemini and OpenCode usage shared by every AI widget on the desktop: read once, every two minutes, only while one of
/// them is visible.
/// </summary>
internal sealed class AiUsageHub
@@ -106,7 +109,7 @@ internal sealed class AiUsageHub
/// <summary>
/// One AI assistant on the desktop with its own icon and colour. Claude and Codex show how much of their usage limits
-/// is spent and when it resets; Gemini (which keeps no usage on this PC) opens the app. The icon opens the app.
+/// is spent and when it resets (Gemini through Antigravity, OpenCode Go through its console). The icon opens the app.
/// </summary>
internal sealed class AiAssistantWidget(AiAssistant assistant) : DeskWidget
{
@@ -200,14 +203,50 @@ internal sealed class AiAssistantWidget(AiAssistant assistant) : DeskWidget
grid.Children.Add(At(UsageRow(), 0, 3));
return grid;
}
- default:
+ case DeskSize.Tall:
{
+ // Upright: icon and name, the first limit as a large ring, then every limit with its reset time.
var header = Grid(columns: "Auto,*");
- header.Children.Add(AppIcon(34));
- header.Children.Add(At(Margin(Column(Name(15), _status), 10), 0, 1));
- var grid = Grid("Auto,*");
+ header.Children.Add(AppIcon(30));
+ header.Children.Add(At(Margin(Column(Name(14), _status), 9), 0, 1));
+ _ring = new RingGauge { Width = 104, Height = 104, Thickness = 10, Stroke = assistant.Accent };
+ _headline = Digits("", 26, FontWeights.Bold);
+ _headline.HorizontalAlignment = HorizontalAlignment.Center;
+ var ring = new Grid { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
+ ring.Children.Add(_ring);
+ ring.Children.Add(_headline);
+ var rows = Column(UsageRow());
+ for (var extra = 1; extra < assistant.Windows; extra++) rows.Children.Add(Margin(UsageRow(), 0, 9));
+ var grid = Grid("Auto,*,Auto");
grid.Children.Add(header);
- var rows = Column(UsageRow(), Margin(UsageRow(), 0, 12));
+ grid.Children.Add(At(ring, 1));
+ grid.Children.Add(At(rows, 2));
+ return grid;
+ }
+ default:
+ {
+ var grid = Grid("Auto,*");
+ if (assistant.Windows > 2)
+ {
+ // Three limits: a one-line header (icon, name, plan) leaves room for the third row.
+ var line = Grid(columns: "Auto,Auto,*");
+ line.Children.Add(AppIcon(26));
+ var name = Name(14);
+ name.VerticalAlignment = VerticalAlignment.Center;
+ line.Children.Add(At(Margin(name, 9), 0, 1));
+ _status.VerticalAlignment = VerticalAlignment.Center;
+ line.Children.Add(At(Margin(_status, 8), 0, 2));
+ grid.Children.Add(line);
+ }
+ else
+ {
+ var header = Grid(columns: "Auto,*");
+ header.Children.Add(AppIcon(34));
+ header.Children.Add(At(Margin(Column(Name(15), _status), 10), 0, 1));
+ grid.Children.Add(header);
+ }
+ var rows = Column(UsageRow(), Margin(UsageRow(), 0, assistant.Windows > 2 ? 7 : 12));
+ for (var extra = 2; extra < assistant.Windows; extra++) rows.Children.Add(Margin(UsageRow(), 0, 7));
rows.VerticalAlignment = VerticalAlignment.Bottom;
grid.Children.Add(At(rows, 1));
return grid;
@@ -253,7 +292,7 @@ internal sealed class AiAssistantWidget(AiAssistant assistant) : DeskWidget
if (!HasUsage) return;
var hub = AiUsageHub.Instance;
var usage = hub.For(assistant.UsageProvider!);
- var windows = usage?.Windows.Take(2).ToList() ?? [];
+ var windows = usage?.Windows.Take(Math.Max(2, _rows.Count)).ToList() ?? [];
var status = usage switch
{
null when !hub.Loaded => Desk.L("Okunuyor…", "Loading…"),
@@ -274,7 +313,7 @@ internal sealed class AiAssistantWidget(AiAssistant assistant) : DeskWidget
{
var (label, value, fill, bar, reset) = _rows[i];
var window = i < windows.Count ? windows[i] : null;
- label.Text = window?.Label ?? (i == 0 ? UiText.Get("AiSession") : UiText.Get("AiWeekly"));
+ label.Text = window?.Label ?? (i == 0 ? UiText.Get("AiSession") : i == 1 ? UiText.Get("AiWeekly") : UiText.Get("AiMonthly"));
value.Text = window is null ? "—" : Percent(window.UsedPercent);
value.Foreground = window is { UsedPercent: >= 85 } ? Red : window is { UsedPercent: >= 70 } ? Orange : Text;
var width = bar.ActualWidth > 0 ? bar.ActualWidth : 0;
diff --git a/DesktopWidgets/Kinds/BigClockWidget.cs b/DesktopWidgets/Kinds/BigClockWidget.cs
new file mode 100644
index 0000000..23c4f3f
--- /dev/null
+++ b/DesktopWidgets/Kinds/BigClockWidget.cs
@@ -0,0 +1,452 @@
+using System.Globalization;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Documents;
+using System.Windows.Media;
+using System.Windows.Media.Effects;
+using System.Windows.Shapes;
+using QiDock.Services.Widgets;
+
+namespace QiDock.DesktopWidgets.Kinds;
+
+/// <summary>
+/// A large clock straight on the wallpaper, in one of several styles (as on a phone's lock screen), coloured from
+/// the wallpaper behind it, in a chosen colour or in a two-colour blend. No card behind it; it scales to the chosen
+/// size. Redrawn once a minute.
+/// </summary>
+internal sealed class BigClockWidget : DeskWidget
+{
+ private const double DesignWidth = 700;
+
+ /// <summary>The styles, in menu order: id, Turkish and English name.</summary>
+ public static readonly (string Id, string Tr, string En)[] Styles =
+ [
+ ("glass", "Cam", "Glass"),
+ ("lock", "Kilit ekranı", "Lock screen"),
+ ("thin", "İnce", "Thin"),
+ ("heavy", "Kalın", "Heavy"),
+ ("stacked", "Üst üste", "Stacked"),
+ ("split", "Yan yana", "Side by side"),
+ ("twotone", "İki renk", "Two-tone"),
+ ("serif", "Zarif", "Elegant"),
+ ("outline", "Dış hat", "Outline"),
+ ("neon", "Neon", "Neon"),
+ ("mono", "Daktilo", "Typewriter"),
+ ("words", "Yazıyla", "In words")
+ ];
+
+ /// <summary>Colours: id (stored), Turkish and English name, and one colour or two for a blend.</summary>
+ public static readonly (string Id, string Tr, string En, Color From, Color? To)[] Palette =
+ [
+ ("white", "Beyaz", "White", Colors.White, null),
+ ("black", "Siyah", "Black", Rgb(0x16, 0x16, 0x18), null),
+ ("cream", "Krem", "Cream", Rgb(0xF6, 0xEB, 0xD9), null),
+ ("pink", "Pembe", "Pink", Rgb(0xFF, 0xA6, 0xC9), null),
+ ("orange", "Turuncu", "Orange", Rgb(0xFF, 0xB3, 0x6B), null),
+ ("yellow", "Sarı", "Yellow", Rgb(0xFF, 0xE0, 0x71), null),
+ ("green", "Yeşil", "Green", Rgb(0x9B, 0xE8, 0x9B), null),
+ ("teal", "Turkuaz", "Teal", Rgb(0x7F, 0xE3, 0xD8), null),
+ ("blue", "Mavi", "Blue", Rgb(0x8E, 0xC5, 0xFF), null),
+ ("purple", "Mor", "Purple", Rgb(0xC6, 0xA8, 0xFF), null),
+ ("red", "Kırmızı", "Red", Rgb(0xFF, 0x7A, 0x7A), null),
+ ("sunset", "Gün batımı", "Sunset", Rgb(0xFF, 0xC0, 0x6B), Rgb(0xFF, 0x6F, 0xA8)),
+ ("ocean", "Okyanus", "Ocean", Rgb(0x7F, 0xE8, 0xF0), Rgb(0x5C, 0x8D, 0xFF)),
+ ("aurora", "Kuzey ışığı", "Aurora", Rgb(0x8C, 0xF5, 0xC0), Rgb(0xB0, 0x8C, 0xFF))
+ ];
+
+ private static readonly FontFamily Thin = new("Bahnschrift Light, Segoe UI Variable Display Light, Segoe UI Light");
+ private static readonly FontFamily Display = new("Segoe UI Variable Display, Segoe UI");
+ private static readonly FontFamily Black = new("Segoe UI Black, Segoe UI Variable Display, Segoe UI");
+ private static readonly FontFamily Condensed = new("Bahnschrift SemiBold Condensed, Bahnschrift, Segoe UI");
+ private static readonly FontFamily Serif = new("Sitka Display, Georgia, Cambria");
+ private static readonly FontFamily Mono = new("Cascadia Mono, Consolas, Courier New");
+
+ private TextBlock? _date, _time, _minutes, _words, _side;
+ private UniformGrid? _day;
+ private Path? _outline;
+ private string _shown = "";
+ private Color _tint = Colors.White;
+ private Color? _blend;
+
+ public override bool Bare => true;
+
+ public override TimeSpan? Interval => TimeSpan.FromSeconds(1);
+
+ private string Style => Styles.Any(s => s.Id == Option("style")) ? Option("style")! : "glass";
+
+ /// <summary>Null: from the wallpaper. Older layouts stored "white" the same way.</summary>
+ private string? ColorId => Palette.Any(p => p.Id == Option("tint")) ? Option("tint") : null;
+
+ private static Color Rgb(byte r, byte g, byte b) => Color.FromRgb(r, g, b);
+
+ /// <summary>Languages the date can be written in, each named in its own language.</summary>
+ public static readonly (string Code, string Name)[] Languages =
+ [
+ ("tr", "Türkçe"), ("en", "English"), ("de", "Deutsch"), ("fr", "Français"), ("es", "Español"),
+ ("it", "Italiano"), ("pt", "Português"), ("nl", "Nederlands"), ("ru", "Русский"), ("ar", "العربية"),
+ ("ja", "日本語"), ("zh", "中文"), ("ko", "한국어")
+ ];
+
+ /// <summary>Null: the app's language.</summary>
+ private string? LanguageId => Languages.Any(l => l.Code == Option("lang")) ? Option("lang") : null;
+
+ private CultureInfo DateCulture()
+ {
+ if (LanguageId is not { } code) return Desk.Culture;
+ try
+ {
+ return CultureInfo.GetCultureInfo(code == "zh" ? "zh-CN" : code);
+ }
+ catch (CultureNotFoundException)
+ {
+ return Desk.Culture;
+ }
+ }
+
+ public override FrameworkElement Build()
+ {
+ _shown = "";
+ _date = _time = _minutes = _words = _side = null;
+ _day = null;
+ _outline = null;
+ var shadow = new DropShadowEffect { Color = Colors.Black, BlurRadius = 28, ShadowDepth = 0, Opacity = 0.2, RenderingBias = RenderingBias.Performance };
+ var stack = new StackPanel { Width = DesignWidth, Effect = Style == "neon" ? null : shadow };
+ switch (Style)
+ {
+ case "lock":
+ stack.Children.Add(_date = Line(Display, 46, FontWeights.SemiBold, new Thickness(0, 0, 0, -18)));
+ stack.Children.Add(_time = Digits(Display, 270, FontWeights.Bold));
+ break;
+ case "thin":
+ stack.Children.Add(_date = Line(Display, 44, FontWeights.Normal, new Thickness(0, 0, 0, -22)));
+ stack.Children.Add(_time = Digits(Display, 290, FontWeights.Light));
+ break;
+ case "heavy":
+ stack.Children.Add(_date = Line(Display, 42, FontWeights.Bold, new Thickness(0, 0, 0, -6)));
+ stack.Children.Add(_time = Digits(Black, 250, FontWeights.Black, 1.0));
+ break;
+ case "stacked":
+ // Hours over minutes in tall, narrow numbers.
+ stack.Children.Add(_date = Line(Display, 40, FontWeights.SemiBold, new Thickness(0, 0, 0, -6)));
+ stack.Children.Add(_time = Digits(Condensed, 250, FontWeights.Normal, 1.0));
+ stack.Children.Add(_minutes = Digits(Condensed, 250, FontWeights.Normal, 1.0));
+ _minutes.Margin = new Thickness(0, -34, 0, 0);
+ break;
+ case "split":
+ {
+ // The time on the left, the weekday and date beside it behind a thin line.
+ var row = new Grid { HorizontalAlignment = HorizontalAlignment.Center };
+ row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
+ row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
+ row.Children.Add(_time = Digits(Display, 190, FontWeights.SemiBold, 1.0));
+ var side = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(26, 0, 0, 0) };
+ side.Children.Add(_side = Line(Display, 40, FontWeights.Bold, new Thickness(0)));
+ side.Children.Add(_date = Line(Display, 34, FontWeights.Normal, new Thickness(0, 2, 0, 0)));
+ _side.HorizontalAlignment = _date.HorizontalAlignment = HorizontalAlignment.Left;
+ var bar = new Border { BorderThickness = new Thickness(3, 0, 0, 0), Padding = new Thickness(22, 6, 0, 6), Child = side, VerticalAlignment = VerticalAlignment.Center };
+ side.Margin = new Thickness(0);
+ Grid.SetColumn(bar, 1);
+ row.Children.Add(bar);
+ stack.Children.Add(row);
+ break;
+ }
+ case "twotone":
+ stack.Children.Add(_date = Line(Display, 44, FontWeights.SemiBold, new Thickness(0, 0, 0, -20)));
+ stack.Children.Add(_time = Digits(Display, 270, FontWeights.Bold));
+ break;
+ case "serif":
+ stack.Children.Add(_date = Line(Serif, 44, FontWeights.Normal, new Thickness(0, 0, 0, -56)));
+ stack.Children.Add(_time = Digits(Serif, 270, FontWeights.Normal));
+ break;
+ case "outline":
+ stack.Children.Add(_date = Line(Display, 44, FontWeights.SemiBold, new Thickness(0, 0, 0, 6)));
+ stack.Children.Add(_outline = new Path { HorizontalAlignment = HorizontalAlignment.Center, StrokeThickness = 5, StrokeLineJoin = PenLineJoin.Round });
+ break;
+ case "neon":
+ stack.Children.Add(_date = Line(Thin, 46, FontWeights.Normal, new Thickness(0, 0, 0, -2)));
+ stack.Children.Add(_time = Digits(Thin, 280, FontWeights.Normal));
+ break;
+ case "mono":
+ stack.Children.Add(_time = Digits(Mono, 200, FontWeights.SemiBold, 1.0));
+ stack.Children.Add(_date = Line(Mono, 36, FontWeights.Normal, new Thickness(0, 4, 0, 0)));
+ break;
+ case "words":
+ stack.Children.Add(_words = new TextBlock
+ {
+ FontFamily = Display,
+ FontSize = 104,
+ FontWeight = FontWeights.Bold,
+ TextAlignment = TextAlignment.Left,
+ LineStackingStrategy = LineStackingStrategy.BlockLineHeight,
+ LineHeight = 108,
+ HorizontalAlignment = HorizontalAlignment.Center
+ });
+ stack.Children.Add(_date = Line(Display, 38, FontWeights.SemiBold, new Thickness(0, 22, 0, 0)));
+ break;
+ default:
+ stack.Children.Add(_date = Line(Thin, 50, FontWeights.Normal, new Thickness(150, 0, 0, -26)));
+ stack.Children.Add(_time = Digits(Display, 250, FontWeights.SemiBold));
+ stack.Children.Add(_day = new UniformGrid { Rows = 1, Width = DesignWidth * 0.74, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, -6, 0, 0) });
+ break;
+ }
+ return new Viewbox { Child = stack, Stretch = Stretch.Uniform };
+ }
+
+ private static TextBlock Line(FontFamily font, double size, FontWeight weight, Thickness margin) => new()
+ {
+ FontFamily = font,
+ FontSize = size,
+ FontWeight = weight,
+ HorizontalAlignment = HorizontalAlignment.Center,
+ Margin = margin
+ };
+
+ private static TextBlock Digits(FontFamily font, double size, FontWeight weight, double lineHeight = 1.02)
+ {
+ var block = new TextBlock
+ {
+ FontFamily = font,
+ FontSize = size,
+ FontWeight = weight,
+ HorizontalAlignment = HorizontalAlignment.Center,
+ LineStackingStrategy = LineStackingStrategy.BlockLineHeight,
+ LineHeight = size * lineHeight
+ };
+ block.Typography.NumeralAlignment = FontNumeralAlignment.Tabular;
+ return block;
+ }
+
+ public override void Tick()
+ {
+ var now = DateTime.Now;
+ var key = now.ToString("yyyyMMddHHmm", CultureInfo.InvariantCulture) + Style + ColorId + LanguageId;
+ if (key == _shown || _date is null) return;
+ _shown = key;
+ var culture = DateCulture();
+ var turkish = culture.Name.StartsWith("tr", StringComparison.OrdinalIgnoreCase);
+ var english = culture.Name.StartsWith("en", StringComparison.OrdinalIgnoreCase);
+ // Day and month in the language's own order ("19 November", "November 19", "11月19日").
+ var monthDay = now.ToString(culture.DateTimeFormat.MonthDayPattern, culture);
+ PickColours();
+
+ var solid = Brush(0xF2);
+ var digits = DigitsBrush();
+ _date.Foreground = solid;
+ _date.Text = Style switch
+ {
+ // "19.Kas.2026"
+ // Languages that write months as numbers ("11月") get "19.11.2026".
+ "glass" => culture.DateTimeFormat.GetAbbreviatedMonthName(now.Month) is var month && month.Any(char.IsDigit)
+ ? now.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture)
+ : $"{now:dd}.{month.TrimEnd('.')}.{now:yyyy}",
+ // The weekday is already beside it: the language's long date without it.
+ "split" => turkish ? now.ToString("d MMMM yyyy", culture) : english ? now.ToString("MMMM d, yyyy", culture)
+ : now.ToString(culture.DateTimeFormat.LongDatePattern.Replace("dddd", "").Trim(' ', ','), culture),
+ "mono" => culture.TextInfo.ToLower(now.ToString("dddd", culture)) + " · " + now.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture),
+ _ => turkish ? now.ToString("dddd d MMMM", culture) : english ? now.ToString("dddd, MMMM d", culture) : now.ToString("dddd", culture) + ", " + monthDay
+ };
+ if (_side is not null)
+ {
+ _side.Text = now.ToString("dddd", culture);
+ _side.Foreground = solid;
+ if (_side.Parent is StackPanel { Parent: Border bar }) bar.BorderBrush = Brush(0xB0);
+ }
+
+ if (_time is not null)
+ {
+ _time.Effect = null;
+ if (_minutes is not null)
+ {
+ _time.Text = now.ToString("HH", culture);
+ _minutes.Text = now.ToString("mm", culture);
+ _minutes.Foreground = digits;
+ }
+ else if (Style == "twotone")
+ {
+ // Hours in the colour, minutes in white (black over a light picture), the colon faint between them.
+ _time.Inlines.Clear();
+ var other = new SolidColorBrush(Luminance(_tint) > 0.75 ? Rgb(0x1C, 0x1C, 0x1E) : Colors.White);
+ _time.Inlines.Add(new Run(now.ToString("HH", culture)) { Foreground = digits });
+ _time.Inlines.Add(new Run(":") { Foreground = Brush(0x80) });
+ _time.Inlines.Add(new Run(now.ToString("mm", culture)) { Foreground = other });
+ }
+ else _time.Text = now.ToString("HH:mm", culture);
+ if (Style != "twotone") _time.Foreground = digits;
+ if (Style == "neon")
+ {
+ // A pale core with the colour glowing round it.
+ _time.Foreground = new SolidColorBrush(Mix(_tint, Colors.White, 0.55));
+ _time.Effect = new DropShadowEffect { Color = _tint, BlurRadius = 46, ShadowDepth = 0, Opacity = 1, RenderingBias = RenderingBias.Performance };
+ _date.Effect = new DropShadowEffect { Color = _tint, BlurRadius = 22, ShadowDepth = 0, Opacity = 0.9, RenderingBias = RenderingBias.Performance };
+ }
+ }
+
+ if (_outline is not null)
+ {
+ var text = new FormattedText(now.ToString("HH:mm", culture), culture, FlowDirection.LeftToRight,
+ new Typeface(Display, FontStyles.Normal, FontWeights.Bold, FontStretches.Normal), 270, Brushes.White, 1.0);
+ var geometry = text.BuildGeometry(new Point(0, 0));
+ geometry.Freeze();
+ _outline.Data = geometry;
+ _outline.Stroke = digits;
+ _outline.Fill = Brush(0x14);
+ _outline.Margin = new Thickness(0, -geometry.Bounds.Top + 4, 0, 0);
+ }
+
+ if (_words is not null)
+ {
+ var lines = turkish ? TurkishWords(now) : EnglishWords(now);
+ _words.Inlines.Clear();
+ for (var i = 0; i < lines.Count; i++)
+ {
+ if (i > 0) _words.Inlines.Add(new LineBreak());
+ // The last line (geçiyor / var) quieter, as the phrase settles.
+ _words.Inlines.Add(new Run(lines[i]) { Foreground = i == lines.Count - 1 && lines.Count > 1 ? Brush(0x99) : digits });
+ }
+ }
+
+ if (_day is null) return;
+ // The weekday in capitals, its letters spread evenly under the numbers.
+ var day = culture.TextInfo.ToUpper(now.ToString("dddd", culture));
+ _day.Children.Clear();
+ var letters = Brush(0xE6);
+ foreach (var letter in day)
+ _day.Children.Add(new TextBlock { Text = letter.ToString(), FontFamily = Thin, FontSize = 64, Foreground = letters, HorizontalAlignment = HorizontalAlignment.Center });
+ }
+
+ private void PickColours()
+ {
+ _blend = null;
+ if (ColorId is { } id && Palette.FirstOrDefault(p => p.Id == id) is { Id: not null } chosen)
+ {
+ _tint = chosen.From;
+ _blend = chosen.To;
+ return;
+ }
+ _tint = WallpaperTint.For(Area()) is { } tint ? tint : Colors.White;
+ }
+
+ private SolidColorBrush Brush(byte alpha) => new(Color.FromArgb(alpha, _tint.R, _tint.G, _tint.B));
+
+ /// <summary>The numbers: a blend runs across them; the glass style fades its colour towards the bottom.</summary>
+ private Brush DigitsBrush()
+ {
+ if (_blend is { } to)
+ return Style == "glass"
+ ? new LinearGradientBrush(Color.FromArgb(0xF7, _tint.R, _tint.G, _tint.B), Color.FromArgb(0x88, to.R, to.G, to.B), 90)
+ : new LinearGradientBrush(_tint, to, new Point(0, 0), new Point(1, 1));
+ return Style == "glass"
+ ? new LinearGradientBrush(Color.FromArgb(0xF7, _tint.R, _tint.G, _tint.B), Color.FromArgb(0x66, _tint.R, _tint.G, _tint.B), 90)
+ : Brush(0xF2);
+ }
+
+ private static double Luminance(Color c) => (0.2126 * c.R + 0.7152 * c.G + 0.0722 * c.B) / 255;
+
+ private static Color Mix(Color a, Color b, double amount) => Color.FromRgb(
+ (byte)(a.R + (b.R - a.R) * amount), (byte)(a.G + (b.G - a.G) * amount), (byte)(a.B + (b.B - a.B) * amount));
+
+ // ---- The time in words -----------------------------------------------------------------------
+
+ private static readonly string[] HourTr = ["on iki", "bir", "iki", "üç", "dört", "beş", "altı", "yedi", "sekiz", "dokuz", "on", "on bir", "on iki"];
+ // "…i geçiyor" and "…e var": the hour with its ending.
+ private static readonly string[] HourPastTr = ["on ikiyi", "biri", "ikiyi", "üçü", "dördü", "beşi", "altıyı", "yediyi", "sekizi", "dokuzu", "onu", "on biri", "on ikiyi"];
+ private static readonly string[] HourToTr = ["on ikiye", "bire", "ikiye", "üçe", "dörde", "beşe", "altıya", "yediye", "sekize", "dokuza", "ona", "on bire", "on ikiye"];
+ private static readonly string[] MinuteTr = ["", "beş", "on", "çeyrek", "yirmi", "yirmi beş"];
+
+ /// <summary>"saat / on bir", "on biri / çeyrek / geçiyor", "on ikiye / beş / var" (to the nearest five minutes).</summary>
+ private static List<string> TurkishWords(DateTime now)
+ {
+ var rounded = (int)Math.Round(now.Minute / 5.0) * 5;
+ var hour = now.Hour % 12;
+ if (rounded == 60)
+ {
+ rounded = 0;
+ hour = (hour + 1) % 12;
+ }
+ if (rounded == 0) return ["saat", HourTr[hour]];
+ if (rounded == 30) return [HourTr[hour], "buçuk"];
+ if (rounded < 30) return [HourPastTr[hour], MinuteTr[rounded / 5], "geçiyor"];
+ return [HourToTr[(hour + 1) % 12], MinuteTr[(60 - rounded) / 5], "var"];
+ }
+
+ private static readonly string[] HourEn = ["twelve", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve"];
+ private static readonly string[] MinuteEn = ["", "five", "ten", "quarter", "twenty", "twenty-five"];
+
+ private static List<string> EnglishWords(DateTime now)
+ {
+ var rounded = (int)Math.Round(now.Minute / 5.0) * 5;
+ var hour = now.Hour % 12;
+ if (rounded == 60)
+ {
+ rounded = 0;
+ hour = (hour + 1) % 12;
+ }
+ if (rounded == 0) return [HourEn[hour], "o'clock"];
+ if (rounded == 30) return ["half past", HourEn[hour]];
+ if (rounded < 30) return [MinuteEn[rounded / 5], "past", HourEn[hour]];
+ return [MinuteEn[(60 - rounded) / 5], "to", HourEn[(hour + 1) % 12]];
+ }
+
+ /// <summary>Where the clock stands on the screen (the wallpaper behind it decides the colour).</summary>
+ private Rect Area()
+ {
+ var size = Desk.Dimensions(Size);
+ return new Rect(Host.Item.X, Host.Item.Y, size.Width, size.Height);
+ }
+
+ public override void AddMenuItems(ItemsControl menu)
+ {
+ var style = new MenuItem { Header = Desk.L("Saat stili", "Clock style") };
+ foreach (var (id, tr, en) in Styles)
+ style.Items.Add(MenuEntry(Desk.L(tr, en), () =>
+ {
+ SetOption("style", id == "glass" ? null : id);
+ Host.Rebuild();
+ }, Style == id));
+ menu.Items.Add(style);
+
+ var color = new MenuItem { Header = Desk.L("Renk", "Colour") };
+ color.Items.Add(MenuEntry(Desk.L("Duvar kâğıdından", "From the wallpaper"), () =>
+ {
+ SetOption("tint", null);
+ Host.Rebuild();
+ }, ColorId is null));
+ color.Items.Add(new Separator());
+ foreach (var (id, tr, en, from, to) in Palette)
+ {
+ if (id == "sunset") color.Items.Add(new Separator());
+ var item = MenuEntry(Desk.L(tr, en), () =>
+ {
+ SetOption("tint", id);
+ Host.Rebuild();
+ }, ColorId == id);
+ // A swatch of the colour (or the blend) beside its name.
+ item.Icon = new Ellipse
+ {
+ Width = 14,
+ Height = 14,
+ Stroke = new SolidColorBrush(Color.FromArgb(0x55, 0x80, 0x80, 0x80)),
+ StrokeThickness = 1,
+ Fill = to is { } end ? new LinearGradientBrush(from, end, new Point(0, 0), new Point(1, 1)) : new SolidColorBrush(from)
+ };
+ color.Items.Add(item);
+ }
+ menu.Items.Add(color);
+
+ var language = new MenuItem { Header = Desk.L("Tarih dili", "Date language") };
+ language.Items.Add(MenuEntry(Desk.L("Uygulama dili", "App language"), () =>
+ {
+ SetOption("lang", null);
+ Host.Rebuild();
+ }, LanguageId is null));
+ language.Items.Add(new Separator());
+ foreach (var (code, name) in Languages)
+ language.Items.Add(MenuEntry(name, () =>
+ {
+ SetOption("lang", code);
+ Host.Rebuild();
+ }, LanguageId == code));
+ menu.Items.Add(language);
+ }
+}
diff --git a/DesktopWidgets/Kinds/DeviceBatteryWidget.cs b/DesktopWidgets/Kinds/DeviceBatteryWidget.cs
new file mode 100644
index 0000000..6cb2487
--- /dev/null
+++ b/DesktopWidgets/Kinds/DeviceBatteryWidget.cs
@@ -0,0 +1,146 @@
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using QiDock.Services.Widgets;
+using static QiDock.DesktopWidgets.DeskUi;
+
+namespace QiDock.DesktopWidgets.Kinds;
+
+/// <summary>
+/// The battery of connected Bluetooth devices (mouse, keyboard, headphones), as Windows reports it. Read when the
+/// widget shows and every two minutes while it stays visible.
+/// </summary>
+internal sealed class DeviceBatteryWidget : DeskWidget
+{
+ private Panel? _list;
+ private IReadOnlyList<DeviceBattery> _devices = [];
+ private bool _loaded, _reading;
+
+ public override TimeSpan? Interval => TimeSpan.FromMinutes(2);
+
+ private int Capacity => Size switch
+ {
+ DeskSize.Mini => 1,
+ DeskSize.Strip => 2,
+ DeskSize.Small => 3,
+ _ => 4
+ };
+
+ public override FrameworkElement Build()
+ {
+ if (Size == DeskSize.Strip)
+ {
+ var grid = Grid(columns: "*,14,*");
+ _list = grid;
+ }
+ else
+ {
+ _list = new StackPanel { VerticalAlignment = VerticalAlignment.Center };
+ }
+ var root = new System.Windows.Controls.Grid();
+ root.Children.Add(_list);
+ Draw();
+ return root;
+ }
+
+ protected override void OnAttach() => Read();
+
+ public override void Tick() => Read();
+
+ private async void Read()
+ {
+ if (_reading) return;
+ _reading = true;
+ try { _devices = await BluetoothBatteries.ReadAsync(); }
+ catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or UnauthorizedAccessException or InvalidOperationException)
+ {
+ System.Diagnostics.Trace.TraceWarning("Bluetooth batteries: {0}", ex.Message);
+ }
+ finally
+ {
+ _reading = false;
+ _loaded = true;
+ }
+ Draw();
+ }
+
+ private static string IconOf(string kind) => kind switch
+ {
+ "mouse" => "IconMouse",
+ "keyboard" => "IconKeyboard",
+ "headphones" => "IconHeadphones",
+ _ => "IconBluetooth"
+ };
+
+ private static Brush LevelBrush(int percent) => percent <= 15 ? Red : percent <= 30 ? Orange : Green;
+
+ private void Draw()
+ {
+ if (_list is null) return;
+ _list.Children.Clear();
+ if (_devices.Count == 0)
+ {
+ var empty = Size is DeskSize.Mini or DeskSize.Strip
+ ? Row(Icon("IconBluetooth", 18, Secondary), Margin(T(_loaded ? Desk.L("Pil bildiren bağlı cihaz yok", "No connected device reports a battery") : Desk.L("Okunuyor…", "Reading…"), 12, brush: Secondary), 8))
+ : Empty("IconBluetooth", _loaded ? Desk.L("Pil bildiren bağlı Bluetooth cihazı yok", "No connected Bluetooth device reports its battery") : Desk.L("Okunuyor…", "Reading…"));
+ if (_list is System.Windows.Controls.Grid) System.Windows.Controls.Grid.SetColumnSpan(empty, 3);
+ _list.Children.Add(empty);
+ return;
+ }
+
+ if (Size == DeskSize.Mini)
+ {
+ var device = _devices[0];
+ var grid = Grid(columns: "Auto,*");
+ grid.Children.Add(Icon(IconOf(device.Kind), 26, LevelBrush(device.Percent)));
+ grid.Children.Add(At(Margin(Column(Digits(Percent(device.Percent), 22, FontWeights.Bold), T(device.Name, 11.5, FontWeights.SemiBold, Secondary)), 12), 0, 1));
+ _list.Children.Add(grid);
+ return;
+ }
+
+ var index = 0;
+ foreach (var device in _devices.Take(Capacity))
+ {
+ var row = Size == DeskSize.Tall ? DeviceRing(device) : DeviceRow(device);
+ if (_list is System.Windows.Controls.Grid) At(row, 0, index * 2);
+ else if (index > 0) row.Margin = new Thickness(0, 12, 0, 0);
+ _list.Children.Add(row);
+ index++;
+ }
+ }
+
+ /// <summary>Upright: a ring per device with its icon inside, as a phone's batteries widget.</summary>
+ private static FrameworkElement DeviceRing(DeviceBattery device)
+ {
+ var ring = new Grid { Width = 52, Height = 52 };
+ ring.Children.Add(new RingGauge { Thickness = 5, Stroke = LevelBrush(device.Percent), Value = device.Percent });
+ var icon = Icon(IconOf(device.Kind), 20, Text);
+ icon.HorizontalAlignment = HorizontalAlignment.Center;
+ icon.VerticalAlignment = VerticalAlignment.Center;
+ ring.Children.Add(icon);
+ var grid = Grid(columns: "Auto,*");
+ grid.Children.Add(ring);
+ grid.Children.Add(At(Margin(Column(Digits(Percent(device.Percent), 18, FontWeights.Bold, device.Percent <= 15 ? Red : Text), T(device.Name, 11.5, FontWeights.SemiBold, Secondary)), 10), 0, 1));
+ grid.ToolTip = $"{device.Name}: {Percent(device.Percent)}";
+ return grid;
+ }
+
+ private static FrameworkElement DeviceRow(DeviceBattery device)
+ {
+ var name = T(device.Name, 12.5, FontWeights.SemiBold);
+ name.Margin = new Thickness(8, 0, 6, 0);
+ var value = Digits(Percent(device.Percent), 12.5, FontWeights.Bold, device.Percent <= 15 ? Red : Text);
+ var top = Grid(columns: "Auto,*,Auto");
+ top.Children.Add(Icon(IconOf(device.Kind), 16, Secondary));
+ top.Children.Add(At(name, 0, 1));
+ top.Children.Add(At(value, 0, 2));
+ var fill = new Border { CornerRadius = new CornerRadius(3), Background = LevelBrush(device.Percent), HorizontalAlignment = HorizontalAlignment.Left };
+ var bar = new Grid { Height = 6, Margin = new Thickness(0, 6, 0, 0) };
+ bar.Children.Add(new Border { CornerRadius = new CornerRadius(3), Background = Track });
+ bar.Children.Add(fill);
+ bar.SizeChanged += (_, e) => fill.Width = Math.Max(6, e.NewSize.Width * device.Percent / 100.0);
+ var column = Column(top, bar);
+ column.ToolTip = $"{device.Name}: {Percent(device.Percent)}";
+ return column;
+ }
+}
diff --git a/DesktopWidgets/Kinds/MusicWidget.cs b/DesktopWidgets/Kinds/MusicWidget.cs
index 56daaa6..a81364e 100644
--- a/DesktopWidgets/Kinds/MusicWidget.cs
+++ b/DesktopWidgets/Kinds/MusicWidget.cs
@@ -15,6 +15,9 @@ internal sealed class MusicWidget : DeskWidget
private Grid? _progress;
private DeskButton? _play;
private string? _shownKey;
+ private bool _covers;
+
+ public override bool Covers => _covers;
public override TimeSpan? Interval => TimeSpan.FromSeconds(1);
@@ -22,7 +25,14 @@ internal sealed class MusicWidget : DeskWidget
{
_shownKey = null;
var padding = Desk.Padding(Size);
- _root = new Border { Margin = new Thickness(-padding.Left, -padding.Top, -padding.Right, -padding.Bottom), Padding = padding };
+ // The cover's colours reach the card's very edge, over its light rim too (the rim made a white line around a
+ // dark cover); the card's rounded clip cuts the corners.
+ _root = new Border
+ {
+ Margin = new Thickness(-padding.Left - 1, -padding.Top - 1, -padding.Right - 1, -padding.Bottom - 1),
+ Padding = new Thickness(padding.Left + 1, padding.Top + 1, padding.Right + 1, padding.Bottom + 1),
+ CornerRadius = new CornerRadius(DeskCardFace.Radius)
+ };
Render();
return _root;
}
@@ -42,16 +52,58 @@ internal sealed class MusicWidget : DeskWidget
if (key != _shownKey)
{
_shownKey = key;
- _root.Background = hub.HasMedia ? Tint(hub.ArtColor) : null;
+ _root.Background = hub.HasMedia ? Backdrop(hub) : null;
+ if (_covers != (_root.Background is not null))
+ {
+ _covers = _root.Background is not null;
+ RaiseCoversChanged();
+ }
_root.Child = hub.HasMedia ? Layout(hub) : Idle();
}
Tick();
}
+ /// <summary>
+ /// The cover itself, blurred to soft colour fields behind the card (as the music widget on a phone), darker
+ /// towards the bottom so the title and controls stay readable. Drawn once per song into a small picture.
+ /// </summary>
+ private static Brush Backdrop(MediaHub hub)
+ {
+ if (hub.Art is not System.Windows.Media.Imaging.BitmapSource art || art.PixelWidth < 2 || art.PixelHeight < 2) return Tint(hub.ArtColor);
+ try
+ {
+ const int Tiny = 18, Out = 96;
+ var small = new System.Windows.Media.Imaging.TransformedBitmap(art, new ScaleTransform((double)Tiny / art.PixelWidth, (double)Tiny / art.PixelHeight));
+ var visual = new DrawingVisual();
+ RenderOptions.SetBitmapScalingMode(visual, BitmapScalingMode.HighQuality);
+ using (var dc = visual.RenderOpen())
+ {
+ // Drawn a little larger than the picture, so its soft edges fall outside.
+ dc.DrawImage(small, new Rect(-10, -10, Out + 20, Out + 20));
+ var shade = new LinearGradientBrush(Color.FromArgb(0x26, 0, 0, 0), Color.FromArgb(0x9C, 0, 0, 0), 90);
+ dc.DrawRectangle(shade, null, new Rect(0, 0, Out, Out));
+ }
+ var bitmap = new System.Windows.Media.Imaging.RenderTargetBitmap(Out, Out, 96, 96, PixelFormats.Pbgra32);
+ bitmap.Render(visual);
+ bitmap.Freeze();
+ var brush = new ImageBrush(bitmap) { Stretch = Stretch.UniformToFill };
+ RenderOptions.SetBitmapScalingMode(brush, BitmapScalingMode.Linear);
+ brush.Freeze();
+ return brush;
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or ArgumentException or NotSupportedException or System.Runtime.InteropServices.COMException)
+ {
+ return Tint(hub.ArtColor);
+ }
+ }
+
private static Brush Tint(Color c)
{
- static Color Scale(Color color, double f) => Color.FromRgb((byte)(color.R * f), (byte)(color.G * f), (byte)(color.B * f));
- var brush = new LinearGradientBrush(Scale(c, 0.55), Scale(c, 0.22), new Point(0, 0), new Point(1, 1));
+ // On glass the cover's colour is a tint over the glass (the glass and its rim still show through);
+ // on the dark card it is solid.
+ var glass = DeskCardFace.GlassEnabled && QiDock.Services.Widgets.WallpaperGlass.Image is not null;
+ Color Scale(Color color, double f, byte alpha) => Color.FromArgb(glass ? alpha : (byte)255, (byte)(color.R * f), (byte)(color.G * f), (byte)(color.B * f));
+ var brush = new LinearGradientBrush(Scale(c, 0.55, 0xA8), Scale(c, 0.22, 0xD0), new Point(0, 0), new Point(1, 1));
brush.Freeze();
return brush;
}
@@ -166,12 +218,14 @@ internal sealed class MusicWidget : DeskWidget
}
default:
{
- _title.FontSize = 18;
+ // Large, or upright (Tall): the cover as wide as the card, the song below it.
+ var tall = Size == DeskSize.Tall;
+ _title.FontSize = tall ? 15 : 18;
_title.HorizontalAlignment = HorizontalAlignment.Center;
_artist.HorizontalAlignment = HorizontalAlignment.Center;
- var art = Art(hub, 168, 18);
+ var art = Art(hub, tall ? 132 : 168, tall ? 16 : 18);
art.HorizontalAlignment = HorizontalAlignment.Center;
- var controls = Controls(44);
+ var controls = Controls(tall ? 38 : 44);
controls.HorizontalAlignment = HorizontalAlignment.Center;
return Column(art, Margin(_title, 0, 14), _artist, Margin(ProgressBar(true), 0, 12), Margin(controls, 0, 6));
}
diff --git a/DesktopWidgets/Kinds/ProductivityWidgets.cs b/DesktopWidgets/Kinds/ProductivityWidgets.cs
index c6f96a4..68b6af1 100644
--- a/DesktopWidgets/Kinds/ProductivityWidgets.cs
+++ b/DesktopWidgets/Kinds/ProductivityWidgets.cs
@@ -75,9 +75,9 @@ internal sealed class TodoDeskWidget : DeskWidget
public override FrameworkElement Build()
{
var items = Items.Where(t => !t.Done).Concat(Items.Where(t => t.Done)).ToList();
- var capacity = Size switch { DeskSize.Strip => 3, DeskSize.Small => 4, DeskSize.Medium => 3, _ => 10 };
- var withHeader = Size is DeskSize.Small or DeskSize.Medium or DeskSize.Large;
- var withInput = Size is DeskSize.Medium or DeskSize.Large || _adding;
+ var capacity = Size switch { DeskSize.Strip => 3, DeskSize.Small => 4, DeskSize.Medium => 3, DeskSize.Tall => 8, _ => 10 };
+ var withHeader = Size is DeskSize.Small or DeskSize.Medium or DeskSize.Large or DeskSize.Tall;
+ var withInput = Size is DeskSize.Medium or DeskSize.Large or DeskSize.Tall || _adding;
if (_adding && Size is DeskSize.Strip or DeskSize.Small) capacity -= 1;
var stack = new StackPanel();
@@ -296,6 +296,7 @@ internal sealed class CalendarDeskWidget : DeskWidget
DeskSize.Strip => Week(),
DeskSize.Small => Today(3, compact: true),
DeskSize.Medium => TodayWide(),
+ DeskSize.Tall => TodayTall(),
_ => Month()
};
}
@@ -390,6 +391,18 @@ internal sealed class CalendarDeskWidget : DeskWidget
return stack;
}
+ /// <summary>Upright: today's page on top, the coming events below.</summary>
+ private static FrameworkElement TodayTall()
+ {
+ var stack = (StackPanel)Today(0, compact: false);
+ stack.VerticalAlignment = VerticalAlignment.Top;
+ stack.Children.Add(new Border { Height = 1, Background = Track, Margin = new Thickness(0, 10, 0, 10) });
+ var upcoming = Upcoming(4);
+ if (upcoming.Count == 0) stack.Children.Add(NoEvents());
+ for (var i = 0; i < upcoming.Count; i++) stack.Children.Add(EventRow(upcoming[i], i, true));
+ return stack;
+ }
+
private static FrameworkElement TodayWide()
{
var grid = Grid(columns: "110,*");
diff --git a/DesktopWidgets/Kinds/SystemWidgets.cs b/DesktopWidgets/Kinds/SystemWidgets.cs
index d75c88a..0af6b12 100644
--- a/DesktopWidgets/Kinds/SystemWidgets.cs
+++ b/DesktopWidgets/Kinds/SystemWidgets.cs
@@ -17,6 +17,8 @@ internal sealed class MetricWidget(Metric metric) : DeskWidget
private Border? _barFill;
private Grid? _bar;
private ContentControl? _icon;
+ private StackPanel? _top;
+ private DateTime _lastTop;
private Brush Color => metric switch
{
@@ -80,6 +82,34 @@ internal sealed class MetricWidget(Metric metric) : DeskWidget
grid.Children.Add(At(_detail, 2));
return grid;
}
+ case DeskSize.Tall:
+ {
+ // Upright: the load now and over the last minutes, then what is using it, program by program.
+ var header = Grid(columns: "Auto,*,Auto");
+ header.Children.Add(_icon);
+ header.Children.Add(At(Margin(T(Label, 13, FontWeights.SemiBold), 6), 0, 1));
+ _value.FontSize = 20;
+ header.Children.Add(At(_value, 0, 2));
+ // Scaled to its own peak so small changes still show; the number gives the real figure.
+ _graph = new Sparkline { Stroke = Color, Height = 50, Margin = new Thickness(0, 10, 0, 0) };
+ var heading = T(Desk.L("En çok kullananlar", "Using it most"), 11, FontWeights.SemiBold, Secondary);
+ heading.Margin = new Thickness(0, 12, 0, 4);
+ _top = new StackPanel { VerticalAlignment = VerticalAlignment.Top };
+ _top.Children.Add(T(Desk.L("Ölçülüyor…", "Measuring…"), 12, brush: Secondary));
+ _lastTop = default;
+ var footer = Grid(columns: "*,Auto");
+ footer.Children.Add(T(Desk.L($"{Environment.ProcessorCount} çekirdek", $"{Environment.ProcessorCount} cores"), 10.5, FontWeights.SemiBold, Tertiary));
+ _detail.FontSize = 10.5;
+ _detail.Foreground = Tertiary;
+ footer.Children.Add(At(_detail, 0, 1));
+ var grid = Grid("Auto,Auto,Auto,*,Auto");
+ grid.Children.Add(header);
+ grid.Children.Add(At(_graph, 1));
+ grid.Children.Add(At(heading, 2));
+ grid.Children.Add(At(_top, 3));
+ grid.Children.Add(At(footer, 4));
+ return grid;
+ }
default:
{
var header = Grid(columns: "Auto,*,Auto");
@@ -107,6 +137,50 @@ internal sealed class MetricWidget(Metric metric) : DeskWidget
}
}
+ /// <summary>The busiest programs, with their icons; the first reading only sets the baseline.</summary>
+ private void ShowTop()
+ {
+ if (_top is null) return;
+ _lastTop = DateTime.UtcNow;
+ var all = QiDock.Services.Widgets.CpuTop.Sample(6);
+ if (all.Count == 0) return;
+ // Programs that round to nothing only fill the list; three rows always stay.
+ var users = all.Where((u, i) => i < 3 || u.Percent >= 0.5).ToList();
+ _top.Children.Clear();
+ foreach (var user in users)
+ {
+ FrameworkElement icon = user.Path is { } path && QiDock.Services.ApplicationIconProvider.GetForFile(path) is { } picture
+ ? new System.Windows.Controls.Image { Source = picture }
+ : Letter(user.Name);
+ icon.Width = icon.Height = 18;
+ icon.VerticalAlignment = VerticalAlignment.Center;
+ var name = T(user.Name, 12, FontWeights.SemiBold);
+ name.Margin = new Thickness(8, 0, 6, 0);
+ var share = Digits(Percent(user.Percent), 12, FontWeights.SemiBold, user.Percent >= 25 ? Orange : Secondary);
+ var row = Grid(columns: "Auto,*,Auto");
+ row.Height = 25;
+ row.Children.Add(icon);
+ row.Children.Add(At(name, 0, 1));
+ row.Children.Add(At(share, 0, 2));
+ row.ToolTip = $"{user.Name}: {Percent(user.Percent)}";
+ _top.Children.Add(row);
+ }
+ }
+
+ /// <summary>A small tile with the program's first letter, for programs without an icon of their own.</summary>
+ private static FrameworkElement Letter(string name)
+ {
+ var letter = T(name.Length > 0 ? name[..1].ToUpperInvariant() : "?", 10.5, FontWeights.Bold, Text);
+ letter.HorizontalAlignment = HorizontalAlignment.Center;
+ return new Border { CornerRadius = new CornerRadius(5), Background = Inset, Child = letter };
+ }
+
+ public override void AddMenuItems(ItemsControl menu)
+ {
+ if (metric == Metric.Cpu)
+ menu.Items.Add(MenuEntry(Desk.L("Görev Yöneticisini aç", "Open Task Manager"), () => QiDock.Widgets.Ui.Open("taskmgr.exe")));
+ }
+
protected override void OnAttach() => SystemHub.Instance.Subscribe(Tick);
protected override void OnDetach() => SystemHub.Instance.Unsubscribe(Tick);
@@ -120,7 +194,9 @@ internal sealed class MetricWidget(Metric metric) : DeskWidget
case Metric.Cpu:
percent = hub.Cpu;
var uptime = TimeSpan.FromMilliseconds(Environment.TickCount64);
- detail = Size == DeskSize.Small
+ detail = Size == DeskSize.Tall
+ ? Desk.L($"açık {(int)uptime.TotalDays} g {uptime.Hours} sa", $"up {(int)uptime.TotalDays} d {uptime.Hours} h")
+ : Size == DeskSize.Small
? Desk.L($"{Environment.ProcessorCount} çekirdek", $"{Environment.ProcessorCount} cores")
: Desk.L($"{Environment.ProcessorCount} çekirdek · açık {(int)uptime.TotalDays} g {uptime.Hours} sa", $"{Environment.ProcessorCount} cores · up {(int)uptime.TotalDays} d {uptime.Hours} h");
break;
@@ -151,6 +227,7 @@ internal sealed class MetricWidget(Metric metric) : DeskWidget
if (Size != DeskSize.Mini) _value.Foreground = Size == DeskSize.Small ? Text : QiDock.Widgets.Ui.UsageBrush(metric == Metric.Battery ? 100 - percent : percent);
_detail!.Text = detail;
_graph?.SetValues([.. hub.CpuHistory]);
+ if (_top is not null && DateTime.UtcNow - _lastTop >= TimeSpan.FromSeconds(3)) ShowTop();
if (_bar is not null && _barFill is not null)
_barFill.Width = Math.Max(8, (_bar.ActualWidth > 0 ? _bar.ActualWidth : 312) * percent / 100);
}
diff --git a/DesktopWidgets/Kinds/TimeWidgets.cs b/DesktopWidgets/Kinds/TimeWidgets.cs
index 2512c25..e759e4e 100644
--- a/DesktopWidgets/Kinds/TimeWidgets.cs
+++ b/DesktopWidgets/Kinds/TimeWidgets.cs
@@ -57,6 +57,24 @@ internal sealed class DigitalClockWidget : DeskWidget
grid.Children.Add(At(right, 0, 1));
return grid;
}
+ case DeskSize.Tall:
+ {
+ // Upright: hours over minutes, large, the weather at the foot.
+ _day = T("", 14, FontWeights.SemiBold, Orange);
+ _time = Digits("", 78, FontWeights.SemiBold);
+ _time.LineStackingStrategy = LineStackingStrategy.BlockLineHeight;
+ _time.LineHeight = 80;
+ _time.VerticalAlignment = VerticalAlignment.Center;
+ _date = T("", 12.5, brush: Secondary);
+ _weatherIcon = new ContentControl { Width = 26, Height = 26 };
+ _temp = T("", 17, FontWeights.SemiBold);
+ var grid = Grid("Auto,*,Auto,Auto");
+ grid.Children.Add(_day);
+ grid.Children.Add(At(_time, 1));
+ grid.Children.Add(At(_date, 2));
+ grid.Children.Add(At(Margin(Row(_weatherIcon, Margin(_temp, 6)), 0, 8), 3));
+ return grid;
+ }
default:
{
_day = T("", 14, FontWeights.SemiBold, Orange);
@@ -76,7 +94,7 @@ internal sealed class DigitalClockWidget : DeskWidget
protected override void OnAttach()
{
- if (Size == DeskSize.Medium) WeatherHub.Instance.Subscribe(UpdateWeather);
+ if (Size is DeskSize.Medium or DeskSize.Tall) WeatherHub.Instance.Subscribe(UpdateWeather);
}
protected override void OnDetach() => WeatherHub.Instance.Unsubscribe(UpdateWeather);
@@ -86,7 +104,9 @@ internal sealed class DigitalClockWidget : DeskWidget
var now = DateTime.Now;
var culture = Desk.Culture;
if (_time is not null)
- _time.Text = now.ToString(ShowSeconds && Size is DeskSize.Strip or DeskSize.Mini ? "HH:mm:ss" : "HH:mm", culture);
+ _time.Text = Size == DeskSize.Tall
+ ? now.ToString("HH", culture) + "\n" + now.ToString("mm", culture)
+ : now.ToString(ShowSeconds && Size is DeskSize.Strip or DeskSize.Mini ? "HH:mm:ss" : "HH:mm", culture);
if (Size == DeskSize.Mini && ShowSeconds && _time is not null) _time.FontSize = 26;
if (_seconds is not null) _seconds.Text = now.ToString(":ss", culture);
if (_day is not null) _day.Text = Size == DeskSize.Mini ? now.ToString("ddd", culture) : now.ToString("dddd", culture);
@@ -102,7 +122,7 @@ internal sealed class DigitalClockWidget : DeskWidget
if (_weatherIcon.Tag as string != $"{report.Code}{report.IsDay}")
{
_weatherIcon.Tag = $"{report.Code}{report.IsDay}";
- _weatherIcon.Content = WeatherArt.Create(report.Code, report.IsDay, 44);
+ _weatherIcon.Content = WeatherArt.Create(report.Code, report.IsDay, _weatherIcon.Width);
}
}
@@ -565,7 +585,7 @@ internal sealed class WorldClockDeskWidget : DeskWidget
{
private readonly List<(string Zone, TextBlock Time, TextBlock? Offset, AnalogFace? Face)> _cells = [];
- public override TimeSpan? Interval => TimeSpan.FromSeconds(Size == DeskSize.Medium ? 1 : 20);
+ public override TimeSpan? Interval => TimeSpan.FromSeconds(Size is DeskSize.Medium or DeskSize.Tall ? 1 : 20);
private static IEnumerable<(string Name, string Zone)> Cities()
{
@@ -582,6 +602,24 @@ internal sealed class WorldClockDeskWidget : DeskWidget
{
_cells.Clear();
var cities = Cities().ToList();
+ if (Size == DeskSize.Tall)
+ {
+ // Upright: one city per row, its clock face beside the time.
+ var column = new StackPanel { VerticalAlignment = VerticalAlignment.Center };
+ foreach (var (name, zone) in cities)
+ {
+ var face = new AnalogFace { Width = 50, Height = 50, Light = true, Numbers = false };
+ var time = Digits("", 20);
+ var offset = T("", 10.5, brush: Secondary);
+ var row = Grid(columns: "Auto,*");
+ row.Children.Add(face);
+ row.Children.Add(At(Margin(Column(T(name, 12.5, FontWeights.SemiBold), time, offset), 10), 0, 1));
+ row.Margin = new Thickness(0, 7, 0, 7);
+ column.Children.Add(row);
+ _cells.Add((zone, time, offset, face));
+ }
+ return column;
+ }
if (Size == DeskSize.Small)
{
var stack = new StackPanel { VerticalAlignment = VerticalAlignment.Center };
diff --git a/DesktopWidgets/Kinds/ToolWidgets.cs b/DesktopWidgets/Kinds/ToolWidgets.cs
index a0d43ba..a0636ba 100644
--- a/DesktopWidgets/Kinds/ToolWidgets.cs
+++ b/DesktopWidgets/Kinds/ToolWidgets.cs
@@ -32,6 +32,7 @@ internal sealed class AppsWidget : DeskWidget
DeskSize.Small => (2, 2, 52),
DeskSize.Strip => (6, 1, 44),
DeskSize.Medium => (5, 2, 50),
+ DeskSize.Tall => (2, 4, 54),
_ => (4, 4, 54)
};
var apps = Apps.Take(columns * rows).ToList();
@@ -109,6 +110,7 @@ internal sealed class ActionsWidget : DeskWidget
DeskSize.Mini => (3, 3, 40),
DeskSize.Small => (4, 2, 48),
DeskSize.Strip => (6, 6, 42),
+ DeskSize.Tall => (8, 2, 50),
_ => (8, 4, 50)
};
var grid = new UniformGrid { Columns = columns };
@@ -475,6 +477,25 @@ internal sealed class TogglesWidget : DeskWidget
var night = Toggle("IconMoon", Orange, () => Ui.Open("ms-settings:nightlight"), Desk.L("Gece ışığı", "Night light"));
var focus = Toggle("IconBell", Purple, () => Ui.Open("ms-settings:quiethours"), Desk.L("Bildirimler / odak", "Notifications / focus"));
var keyboard = Toggle("IconKeyboard", Secondary, () => Ui.Open("osk.exe"), Desk.L("Ekran klavyesi", "On-screen keyboard"));
+ if (Size == DeskSize.Tall)
+ {
+ // Upright: one switch per row with its name, as a phone's control centre.
+ var list = new UniformGrid { Columns = 1, Rows = 5 };
+ foreach (var (button, name) in new[]
+ {
+ (_wifi, "Wi-Fi"), (_bluetooth, "Bluetooth"), (night, Desk.L("Gece ışığı", "Night light")),
+ (focus, Desk.L("Odak", "Focus")), (keyboard, Desk.L("Klavye", "Keyboard"))
+ })
+ {
+ button.Width = button.Height = 44;
+ button.HorizontalAlignment = HorizontalAlignment.Left;
+ var row = Grid(columns: "Auto,*");
+ row.Children.Add(button);
+ row.Children.Add(At(Margin(T(name, 13, FontWeights.SemiBold), 11), 0, 1));
+ list.Children.Add(row);
+ }
+ return list;
+ }
var grid = new UniformGrid { Columns = Size == DeskSize.Small ? 2 : 5, Rows = Size == DeskSize.Small ? 2 : 1 };
grid.Children.Add(_wifi);
grid.Children.Add(_bluetooth);
diff --git a/DesktopWidgets/Kinds/WeatherWidgets.cs b/DesktopWidgets/Kinds/WeatherWidgets.cs
index 41ea328..b8a6420 100644
--- a/DesktopWidgets/Kinds/WeatherWidgets.cs
+++ b/DesktopWidgets/Kinds/WeatherWidgets.cs
@@ -47,6 +47,7 @@ internal sealed class WeatherDeskWidget : DeskWidget
DeskSize.Small => Small(r),
DeskSize.Strip => Hours(r, r.Hours.Count),
DeskSize.Medium => Medium(r),
+ DeskSize.Tall => Tall(r),
_ => Large(r)
};
}
@@ -121,6 +122,34 @@ internal sealed class WeatherDeskWidget : DeskWidget
return grid;
}
+ /// <summary>Upright: now on top, the next days below.</summary>
+ private static FrameworkElement Tall(WeatherReport r)
+ {
+ var grid = Grid("Auto,Auto,*");
+ grid.Children.Add(Small(r));
+ grid.Children.Add(At(new Border { Height = 1, Background = Track, Margin = new Thickness(0, 10, 0, 6) }, 1));
+ var days = new StackPanel { VerticalAlignment = VerticalAlignment.Top };
+ var i = 0;
+ foreach (var day in r.Days.Take(5))
+ {
+ var row = Grid(columns: "*,26,34,32");
+ row.Margin = new Thickness(0, 2, 0, 2);
+ row.Children.Add(T(i++ == 0 ? Desk.L("Bugün", "Today") : day.Date.ToString("ddd", Desk.Culture), 12.5, FontWeights.SemiBold));
+ var icon = WeatherArt.Create(day.Code, true, 18);
+ icon.HorizontalAlignment = HorizontalAlignment.Center;
+ row.Children.Add(At(icon, 0, 1));
+ var min = T(WeatherHub.Temp(day.Min), 12.5, FontWeights.SemiBold, Secondary);
+ min.HorizontalAlignment = HorizontalAlignment.Right;
+ row.Children.Add(At(min, 0, 2));
+ var max = T(WeatherHub.Temp(day.Max), 12.5, FontWeights.SemiBold);
+ max.HorizontalAlignment = HorizontalAlignment.Right;
+ row.Children.Add(At(max, 0, 3));
+ days.Children.Add(row);
+ }
+ grid.Children.Add(At(days, 2));
+ return grid;
+ }
+
private static FrameworkElement Large(WeatherReport r)
{
var grid = Grid("Auto,Auto,Auto,*");
diff --git a/EdgePanel.cs b/EdgePanel.cs
index ba9cbf3..cb54f68 100644
--- a/EdgePanel.cs
+++ b/EdgePanel.cs
@@ -470,6 +470,7 @@ public abstract class EdgePanel : Window
return;
}
_shape.Visibility = _outline.Visibility = Visibility.Collapsed;
+ Services.Widgets.GlassLook.Tiles(Resources, false); // the glass tiles belong to the card on the dock
_sheet.Margin = new Thickness(0);
_sheet.Clip = null;
var area = SystemParameters.WorkArea;
@@ -515,8 +516,26 @@ public abstract class EdgePanel : Window
}
/// <summary>The panel rises out of the tile: a small bump on the dock swells into the full panel.</summary>
+ private bool _glassHooked;
+
+ /// <summary>The card on the dock keeps its glass in place while it moves, grows or the dock's glass changes.</summary>
+ private void HookDockGlass()
+ {
+ if (_glassHooked) return;
+ _glassHooked = true;
+ void Repaint()
+ {
+ if (ReferenceEquals(_onDock, this) && Services.Widgets.GlassLook.DockVeil is not null) PaintDockShape();
+ }
+ LocationChanged += (_, _) => Repaint();
+ SizeChanged += (_, _) => Repaint();
+ Services.Widgets.GlassLook.DockChanged += Repaint;
+ Closed += (_, _) => Services.Widgets.GlassLook.DockChanged -= Repaint;
+ }
+
private void OpenFromDock(DockAnchor dock)
{
+ HookDockGlass();
var area = SystemParameters.WorkArea;
var top = area.Top + Math.Max(0, TopInset());
var side = Fillet + Slack;
@@ -587,6 +606,14 @@ public abstract class EdgePanel : Window
/// <summary>The dock's material for the shape (its gradient turned over so the colours meet at the seam) and its edge.</summary>
private void PaintDockShape()
{
+ var dockGlass = DockGlass();
+ Services.Widgets.GlassLook.Tiles(Resources, dockGlass is not null);
+ if (dockGlass is { } glass)
+ {
+ _shape.Fill = glass;
+ _outline.Stroke = Services.Widgets.GlassLook.Rim;
+ return;
+ }
if (TryFindResource("DockMaterial") is GradientBrush { GradientStops.Count: > 0 } dock)
{
var stops = dock.GradientStops.OrderBy(stop => stop.Offset).ToList();
@@ -602,6 +629,22 @@ public abstract class EdgePanel : Window
else _outline.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, "DockBorderMaterial");
}
+ /// <summary>
+ /// The dock's glass for the grown shape: the wallpaper behind this window under the dock's own veil, so card and
+ /// dock read as one piece of glass. Drawn in window coordinates and turned into the frame's (the shape is drawn as
+ /// if the dock were at the bottom). Null when the dock is not glass.
+ /// </summary>
+ private Brush? DockGlass()
+ {
+ if (Services.Widgets.GlassLook.DockVeil is null || _frameSize.Width <= 0 || _frameSize.Height <= 0) return null;
+ var o = ToWindow(new Point(0, 0));
+ var x = ToWindow(new Point(1, 0));
+ var y = ToWindow(new Point(0, 1));
+ var toScreen = new Matrix(x.X - o.X, x.Y - o.Y, y.X - o.X, y.Y - o.Y, o.X, o.Y);
+ toScreen.Translate(Left, Top);
+ return Services.Widgets.GlassLook.Dock(toScreen);
+ }
+
private void Morph(double to, double milliseconds, IEasingFunction ease, double delay = 0, Action? done = null)
{
_morphTween = new Tween(_morph, to, _clock.Elapsed.TotalMilliseconds + delay, milliseconds, ease, done);
@@ -811,6 +854,8 @@ public abstract class EdgePanel : Window
var width = CardWidth + 2 * Pad;
if (dock.Edge is Models.DockEdge.Left or Models.DockEdge.Right) PlaceOnDock(dock, contentHeight, width);
else PlaceOnDock(dock, width, contentHeight);
+ // The card grew or shrank: its glass is placed again for the new shape.
+ if (ReferenceEquals(_onDock, this) && Services.Widgets.GlassLook.DockVeil is not null) PaintDockShape();
}
private void StartTicking()
diff --git a/Files/FileKinds.cs b/Files/FileKinds.cs
new file mode 100644
index 0000000..c8cd0b5
--- /dev/null
+++ b/Files/FileKinds.cs
@@ -0,0 +1,211 @@
+using Path = System.Windows.Shapes.Path;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using System.Windows.Shapes;
+
+namespace QiDock.Files;
+
+/// <summary>What a file (or most of a folder) holds, as far as its extension tells.</summary>
+internal enum FileKind { Other, Code, Image, Video, Audio, Document, Archive, App }
+
+internal static class FileKinds
+{
+ private static readonly Dictionary<string, FileKind> ByExtension = Build();
+
+ private static Dictionary<string, FileKind> Build()
+ {
+ var map = new Dictionary<string, FileKind>(StringComparer.OrdinalIgnoreCase);
+ void Add(FileKind kind, string list)
+ {
+ foreach (var extension in list.Split(' ', StringSplitOptions.RemoveEmptyEntries)) map["." + extension] = kind;
+ }
+ Add(FileKind.Code, "cs csproj sln xaml js jsx ts tsx mjs cjs json py ipynb java kt kts go rs c h cpp hpp cc m mm swift rb php html htm css scss sass less vue svelte sql sh ps1 psm1 bat cmd yml yaml toml ini xml gradle lua dart r pl ex exs fs fsx vb md mdx editorconfig gitignore dockerfile");
+ Add(FileKind.Image, "png jpg jpeg gif bmp webp heic heif tif tiff svg ico raw cr2 nef arw dng psd ai afphoto afdesign xcf avif jxl");
+ Add(FileKind.Video, "mp4 mov mkv avi wmv webm m4v flv mpg mpeg 3gp mts m2ts drp braw");
+ Add(FileKind.Audio, "mp3 wav flac aac m4a ogg opus wma aiff aif mid midi");
+ Add(FileKind.Document, "pdf doc docx xls xlsx xlsm csv ppt pptx odt ods odp rtf txt log epub pages numbers key one msg eml");
+ Add(FileKind.Archive, "zip rar 7z tar gz tgz bz2 xz iso img cab zst");
+ Add(FileKind.App, "exe msi msix appx appinstaller lnk url dll sys");
+ return map;
+ }
+
+ public static FileKind Of(string path) =>
+ ByExtension.TryGetValue(System.IO.Path.GetExtension(path), out var kind) ? kind : FileKind.Other;
+
+ /// <summary>The folder colour for what it mostly holds (an empty folder is grey).</summary>
+ public static Color FolderColor(FileKind? kind) => kind switch
+ {
+ null => Color.FromRgb(0x8A, 0x8F, 0x9A),
+ FileKind.Code => Color.FromRgb(0x7C, 0x5C, 0xF6),
+ FileKind.Image => Color.FromRgb(0xE0, 0x56, 0x9B),
+ FileKind.Video => Color.FromRgb(0xE5, 0x4D, 0x4D),
+ FileKind.Audio => Color.FromRgb(0xF2, 0x8C, 0x28),
+ FileKind.Document => Color.FromRgb(0x3E, 0x8C, 0xF0),
+ FileKind.Archive => Color.FromRgb(0xA9, 0x7C, 0x50),
+ FileKind.App => Color.FromRgb(0x2F, 0xB3, 0x7C),
+ _ => Color.FromRgb(0x6A, 0x66, 0xEE)
+ };
+
+ public static string Name(FileKind kind) => kind switch
+ {
+ FileKind.Code => L("Kod", "Code"),
+ FileKind.Image => L("Resim", "Image"),
+ FileKind.Video => L("Video", "Video"),
+ FileKind.Audio => L("Ses", "Audio"),
+ FileKind.Document => L("Belge", "Document"),
+ FileKind.Archive => L("Arşiv", "Archive"),
+ FileKind.App => L("Uygulama", "App"),
+ _ => L("Dosya", "File")
+ };
+
+ public static string L(string turkish, string english) => DesktopWidgets.Desk.L(turkish, english);
+
+ // ---- Line icons (24×24, drawn as strokes) --------------------------------------------------
+
+ public static readonly Geometry GlyphCode = Freeze("M16 18l6-6-6-6 M8 6l-6 6 6 6");
+ public static readonly Geometry GlyphImage = Freeze("M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z M8.5 7a1.5 1.5 0 1 0 0 3a1.5 1.5 0 1 0 0-3z M21 15l-5-5L5 21");
+ public static readonly Geometry GlyphVideo = Freeze("M4 5h11a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z M22 8l-5 4 5 4z");
+ public static readonly Geometry GlyphAudio = Freeze("M9 18V5l12-2v13 M6 15a3 3 0 1 0 0 6a3 3 0 1 0 0-6z M18 13a3 3 0 1 0 0 6a3 3 0 1 0 0-6z");
+ public static readonly Geometry GlyphDocument = Freeze("M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M16 13H8 M16 17H8 M10 9H8");
+ public static readonly Geometry GlyphArchive = Freeze("M3 4h18v4H3z M5 8v11a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8 M10 12h4");
+ public static readonly Geometry GlyphApp = Freeze("M3 3h7v7H3z M14 3h7v7h-7z M14 14h7v7h-7z M3 14h7v7H3z");
+ public static readonly Geometry GlyphBox = Freeze("M3 7h18v13a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1z M5 3h14l2 4H3z M10 11h4");
+ public static readonly Geometry GlyphDownload = Freeze("M12 3v12 M7 10l5 5 5-5 M5 21h14");
+ public static readonly Geometry GlyphDesktop = Freeze("M4 3h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z M8 21h8 M12 17v4");
+ public static readonly Geometry GlyphHome = Freeze("M3 10l9-7 9 7v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z M9 22V12h6v10");
+ public static readonly Geometry GlyphCloud = Freeze("M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9z");
+ public static readonly Geometry GlyphDrive = Freeze("M22 12H2 M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z M6 16h.01 M10 16h.01");
+ public static readonly Geometry GlyphUsb = Freeze("M7 2h10v6H7z M5 8h14v12a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2z M10 4v2 M14 4v2");
+ public static readonly Geometry GlyphTrash = Freeze("M3 6h18 M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6 M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2");
+ public static readonly Geometry GlyphFolder = Freeze("M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2z");
+ public static readonly Geometry GlyphList = Freeze("M8 6h13 M8 12h13 M8 18h13 M3 6h.01 M3 12h.01 M3 18h.01");
+ public static readonly Geometry GlyphGrid = Freeze("M3 3h7v7H3z M14 3h7v7h-7z M14 14h7v7h-7z M3 14h7v7H3z");
+ public static readonly Geometry GlyphPanel = Freeze("M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z M15 3v18");
+ public static readonly Geometry GlyphSort = Freeze("M3 6h18 M6 12h12 M10 18h4");
+ public static readonly Geometry GlyphStar = Freeze("M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01z");
+ public static readonly Geometry GlyphEye = Freeze("M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z M12 9a3 3 0 1 0 0 6a3 3 0 1 0 0-6z");
+
+ public static Geometry Glyph(FileKind kind) => kind switch
+ {
+ FileKind.Code => GlyphCode,
+ FileKind.Image => GlyphImage,
+ FileKind.Video => GlyphVideo,
+ FileKind.Audio => GlyphAudio,
+ FileKind.Document => GlyphDocument,
+ FileKind.Archive => GlyphArchive,
+ FileKind.App => GlyphApp,
+ _ => GlyphBox
+ };
+
+ private static Geometry Freeze(string data)
+ {
+ var geometry = Geometry.Parse(data);
+ geometry.Freeze();
+ return geometry;
+ }
+
+ public static Path Line(Geometry geometry, double size, Brush stroke, double thickness = 1.8) => new()
+ {
+ Data = geometry,
+ Width = size,
+ Height = size,
+ Stretch = Stretch.Uniform,
+ Stroke = stroke,
+ StrokeThickness = thickness,
+ StrokeStartLineCap = PenLineCap.Round,
+ StrokeEndLineCap = PenLineCap.Round,
+ StrokeLineJoin = PenLineJoin.Round,
+ SnapsToDevicePixels = true,
+ VerticalAlignment = VerticalAlignment.Center,
+ HorizontalAlignment = HorizontalAlignment.Center
+ };
+
+ public static string Size(long bytes)
+ {
+ string[] units = ["B", "KB", "MB", "GB", "TB"];
+ double value = bytes;
+ var unit = 0;
+ while (value >= 1000 && unit < units.Length - 1)
+ {
+ value /= 1024;
+ unit++;
+ }
+ var culture = UiTextCulture;
+ return unit == 0 ? $"{bytes} {units[0]}" : value.ToString(value >= 100 ? "0" : "0.#", culture) + " " + units[unit];
+ }
+
+ private static System.Globalization.CultureInfo UiTextCulture =>
+ Services.UiText.Current.Language == Models.AppLanguage.Turkish ? System.Globalization.CultureInfo.GetCultureInfo("tr-TR") : System.Globalization.CultureInfo.InvariantCulture;
+
+ public static string Date(DateTime time)
+ {
+ var culture = UiTextCulture;
+ if (time.Date == DateTime.Today) return L("Bugün ", "Today ") + time.ToString("HH:mm", culture);
+ if (time.Date == DateTime.Today.AddDays(-1)) return L("Dün ", "Yesterday ") + time.ToString("HH:mm", culture);
+ return time.ToString(time.Year == DateTime.Today.Year ? "d MMM HH:mm" : "d MMM yyyy", culture);
+ }
+}
+
+/// <summary>
+/// The colourful folder picture: a darker back with its tab, a sheet of paper peeking out and a lighter front
+/// carrying the item count and a line icon for what the folder mostly holds.
+/// </summary>
+internal static class FolderArt
+{
+ private static readonly Geometry Back = Geometry.Parse("M10 22 Q10 12 20 12 H44 Q50 12 54 17 L58 22 H100 Q110 22 110 32 V86 Q110 96 100 96 H20 Q10 96 10 86 Z");
+ private static readonly Geometry Front = Geometry.Parse("M10 46 Q10 38 18 38 H102 Q110 38 110 46 V86 Q110 96 100 96 H20 Q10 96 10 86 Z");
+ private static readonly Geometry Paper = Geometry.Parse("M18 26 H102 Q104 26 104 28 V60 H16 V28 Q16 26 18 26 Z");
+ private static readonly Dictionary<Color, (Brush Back, Brush Front, Brush Edge)> Brushes = [];
+ private static readonly Brush PaperFill = Frozen(new SolidColorBrush(Color.FromArgb(0xF2, 0xFF, 0xFF, 0xFF)));
+ private static readonly Brush Ink = Frozen(new SolidColorBrush(Color.FromArgb(0xE6, 0xFF, 0xFF, 0xFF)));
+
+ static FolderArt()
+ {
+ Back.Freeze();
+ Front.Freeze();
+ Paper.Freeze();
+ }
+
+ public static FrameworkElement Create(Color color, string? count, Geometry glyph, double width)
+ {
+ var (back, front, edge) = BrushesFor(color);
+ var canvas = new Canvas { Width = 120, Height = 104 };
+ canvas.Children.Add(new Path { Data = Back, Fill = back });
+ canvas.Children.Add(new Path { Data = Paper, Fill = PaperFill, RenderTransform = new RotateTransform(-1.5, 60, 40) });
+ canvas.Children.Add(new Path { Data = Front, Fill = front, Stroke = edge, StrokeThickness = 0.8 });
+ if (count is not null)
+ {
+ var label = new TextBlock { Text = count, FontSize = 9.5, FontWeight = FontWeights.SemiBold, Foreground = Ink };
+ Canvas.SetLeft(label, 18);
+ Canvas.SetTop(label, 44);
+ canvas.Children.Add(label);
+ }
+ var icon = FileKinds.Line(glyph, 22, Ink, 1.7);
+ Canvas.SetLeft(icon, 49);
+ Canvas.SetTop(icon, 63);
+ canvas.Children.Add(icon);
+ return new Viewbox { Width = width, Height = width * 104 / 120, Child = canvas, Stretch = Stretch.Uniform };
+ }
+
+ private static (Brush, Brush, Brush) BrushesFor(Color color)
+ {
+ if (Brushes.TryGetValue(color, out var cached)) return cached;
+ var back = Frozen(new SolidColorBrush(Shade(color, 0.72)));
+ var front = Frozen(new LinearGradientBrush(Shade(color, 1.18), color, 90));
+ var edge = Frozen(new SolidColorBrush(Color.FromArgb(0x55, 0xFF, 0xFF, 0xFF)));
+ return Brushes[color] = (back, front, edge);
+ }
+
+ private static Color Shade(Color color, double factor)
+ {
+ static byte Channel(byte value, double factor) => (byte)Math.Clamp(factor >= 1 ? value + (255 - value) * (factor - 1) : value * factor, 0, 255);
+ return Color.FromRgb(Channel(color.R, factor), Channel(color.G, factor), Channel(color.B, factor));
+ }
+
+ private static Brush Frozen(Brush brush)
+ {
+ brush.Freeze();
+ return brush;
+ }
+}
diff --git a/Files/FileOperations.cs b/Files/FileOperations.cs
new file mode 100644
index 0000000..af8e887
--- /dev/null
+++ b/Files/FileOperations.cs
@@ -0,0 +1,201 @@
+using System.Collections.Specialized;
+using System.IO;
+using System.IO.Compression;
+using System.Runtime.InteropServices;
+using System.Windows;
+
+namespace QiDock.Files;
+
+/// <summary>
+/// Copy, move, delete and rename through Windows' own file engine: its progress window, its "replace or skip"
+/// questions, the Recycle Bin and undo all work as in Explorer. Each runs on its own thread so a long copy never
+/// freezes the dock (which shares QiDock's window thread).
+/// </summary>
+internal static class FileOperations
+{
+ private const uint Move = 1, Copy = 2, Delete = 3;
+ private const ushort AllowUndo = 0x40, RenameOnCollision = 0x8, NoConfirmMakeFolder = 0x200, WantNukeWarning = 0x4000;
+
+ public static Task<bool> CopyAsync(IReadOnlyList<string> paths, string target, nint owner)
+ {
+ // Copying into the folder the items are already in makes "name - Kopya" instead of asking to replace.
+ var sameFolder = paths.All(p => string.Equals(Path.GetDirectoryName(p), Path.TrimEndingDirectorySeparator(target), StringComparison.OrdinalIgnoreCase));
+ return RunAsync(Copy, paths, target, owner, (ushort)(AllowUndo | NoConfirmMakeFolder | (sameFolder ? RenameOnCollision : 0)));
+ }
+
+ public static Task<bool> MoveAsync(IReadOnlyList<string> paths, string target, nint owner) =>
+ RunAsync(Move, paths, target, owner, AllowUndo | NoConfirmMakeFolder);
+
+ /// <summary>To the Recycle Bin, or gone for good when <paramref name="permanently"/> (Windows asks first).</summary>
+ public static Task<bool> DeleteAsync(IReadOnlyList<string> paths, bool permanently, nint owner) =>
+ RunAsync(Delete, paths, null, owner, permanently ? (ushort)0 : (ushort)(AllowUndo | WantNukeWarning));
+
+ private static Task<bool> RunAsync(uint function, IReadOnlyList<string> paths, string? target, nint owner, ushort flags)
+ {
+ var done = new TaskCompletionSource<bool>();
+ if (paths.Count == 0)
+ {
+ done.SetResult(false);
+ return done.Task;
+ }
+ var thread = new Thread(() =>
+ {
+ var operation = new FileOperation
+ {
+ Window = owner,
+ Function = function,
+ From = string.Join('\0', paths) + "\0\0",
+ To = target is null ? null : target + "\0\0",
+ Flags = flags
+ };
+ var result = SHFileOperation(ref operation);
+ done.SetResult(result == 0 && !operation.AnyOperationsAborted);
+ }) { IsBackground = true, Name = "QiDock file operation" };
+ thread.SetApartmentState(ApartmentState.STA);
+ thread.Start();
+ return done.Task;
+ }
+
+ /// <summary>Renames in place; returns the new path, or an error text.</summary>
+ public static (string? Path, string? Error) Rename(string path, string name)
+ {
+ name = name.Trim();
+ if (name.Length == 0 || name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || name is "." or "..")
+ return (null, FileKinds.L("Bu ad kullanılamaz (\\ / : * ? \" < > | olamaz).", "That name can't be used (no \\ / : * ? \" < > |)."));
+ var folder = Path.GetDirectoryName(path)!;
+ var target = Path.Combine(folder, name);
+ if (string.Equals(target, path, StringComparison.Ordinal)) return (path, null);
+ var caseOnly = string.Equals(target, path, StringComparison.OrdinalIgnoreCase);
+ if (!caseOnly && (File.Exists(target) || Directory.Exists(target)))
+ return (null, FileKinds.L($"Bu klasörde zaten \"{name}\" var.", $"\"{name}\" already exists here."));
+ try
+ {
+ if (Directory.Exists(path))
+ {
+ if (caseOnly)
+ {
+ // Windows ignores a change of letter case alone; go through a temporary name.
+ var step = path + ".qidock-rename";
+ Directory.Move(path, step);
+ Directory.Move(step, target);
+ }
+ else Directory.Move(path, target);
+ }
+ else File.Move(path, target);
+ return (target, null);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return (null, FileKinds.L("Yeniden adlandırılamadı: ", "Could not rename: ") + ex.Message);
+ }
+ }
+
+ /// <summary>A free name in a folder: "Yeni klasör", "Yeni klasör (2)"…</summary>
+ public static string FreeName(string folder, string name, string extension = "")
+ {
+ var candidate = Path.Combine(folder, name + extension);
+ for (var i = 2; File.Exists(candidate) || Directory.Exists(candidate); i++)
+ candidate = Path.Combine(folder, $"{name} ({i}){extension}");
+ return candidate;
+ }
+
+ // ---- Clipboard (understood by Explorer both ways) -------------------------------------------
+
+ public static void ToClipboard(IReadOnlyList<string> paths, bool cut)
+ {
+ var list = new StringCollection();
+ list.AddRange(paths.ToArray());
+ var data = new DataObject();
+ data.SetFileDropList(list);
+ data.SetData("Preferred DropEffect", new MemoryStream(BitConverter.GetBytes(cut ? 2 : 5)));
+ try { Clipboard.SetDataObject(data, true); }
+ catch (COMException) { }
+ }
+
+ public static (List<string> Paths, bool Cut) FromClipboard()
+ {
+ try
+ {
+ if (Clipboard.GetDataObject() is not { } data || !data.GetDataPresent(DataFormats.FileDrop)) return ([], false);
+ var paths = (data.GetData(DataFormats.FileDrop) as string[])?.ToList() ?? [];
+ var cut = false;
+ if (data.GetData("Preferred DropEffect") is MemoryStream stream && stream.Length >= 4)
+ {
+ var bytes = new byte[4];
+ stream.Position = 0;
+ _ = stream.Read(bytes, 0, 4);
+ var effect = BitConverter.ToInt32(bytes, 0);
+ cut = (effect & 2) != 0 && (effect & 1) == 0;
+ }
+ return (paths, cut);
+ }
+ catch (Exception ex) when (ex is COMException or ExternalException or InvalidOperationException)
+ {
+ return ([], false);
+ }
+ }
+
+ public static bool ClipboardHasFiles()
+ {
+ try { return Clipboard.ContainsFileDropList(); }
+ catch (COMException) { return false; }
+ }
+
+ // ---- Zip (built into .NET, no extra code shipped) -------------------------------------------
+
+ public static Task<string?> ZipAsync(IReadOnlyList<string> paths, string folder) => Task.Run(() =>
+ {
+ try
+ {
+ var name = paths.Count == 1 ? Path.GetFileNameWithoutExtension(paths[0].TrimEnd('\\')) : FileKinds.L("Arşiv", "Archive");
+ var target = FreeName(folder, name, ".zip");
+ using var archive = ZipFile.Open(target, ZipArchiveMode.Create);
+ foreach (var path in paths)
+ {
+ if (Directory.Exists(path))
+ {
+ var root = Path.GetDirectoryName(Path.TrimEndingDirectorySeparator(path))!;
+ foreach (var file in Directory.EnumerateFiles(path, "*", new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true }))
+ archive.CreateEntryFromFile(file, Path.GetRelativePath(root, file).Replace('\\', '/'), CompressionLevel.Optimal);
+ }
+ else if (File.Exists(path))
+ archive.CreateEntryFromFile(path, Path.GetFileName(path), CompressionLevel.Optimal);
+ }
+ return target;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
+ {
+ return null;
+ }
+ });
+
+ public static Task<string?> UnzipAsync(string zip) => Task.Run(() =>
+ {
+ try
+ {
+ var target = FreeName(Path.GetDirectoryName(zip)!, Path.GetFileNameWithoutExtension(zip));
+ ZipFile.ExtractToDirectory(zip, target);
+ return target;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
+ {
+ return (string?)null;
+ }
+ });
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ private struct FileOperation
+ {
+ public nint Window;
+ public uint Function;
+ [MarshalAs(UnmanagedType.LPWStr)] public string From;
+ [MarshalAs(UnmanagedType.LPWStr)] public string? To;
+ public ushort Flags;
+ [MarshalAs(UnmanagedType.Bool)] public bool AnyOperationsAborted;
+ public nint NameMappings;
+ [MarshalAs(UnmanagedType.LPWStr)] public string? ProgressTitle;
+ }
+
+ [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
+ private static extern int SHFileOperation(ref FileOperation operation);
+}
diff --git a/Files/FilesLauncher.cs b/Files/FilesLauncher.cs
new file mode 100644
index 0000000..baf33ec
--- /dev/null
+++ b/Files/FilesLauncher.cs
@@ -0,0 +1,49 @@
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Windows.Threading;
+
+namespace QiDock.Files;
+
+/// <summary>
+/// Lets "QiDock.exe --files [folder]" open the Files window of the copy that is already running: the new copy
+/// leaves the folder in a small file and rings a named event the running copy waits on.
+/// </summary>
+internal static class FilesLauncher
+{
+ private const string EventName = "Local\\QiDock.OpenFiles";
+ private static readonly string RequestPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock", "open-files.txt");
+ private static EventWaitHandle? _event;
+ private static RegisteredWaitHandle? _wait;
+
+ public static void Signal(string folder)
+ {
+ try
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(RequestPath)!);
+ File.WriteAllText(RequestPath, folder);
+ // The user started this copy, so it may hand the right to come to the front to the running one.
+ AllowSetForegroundWindow(-1);
+ if (EventWaitHandle.TryOpenExisting(EventName, out var ring))
+ {
+ using (ring) ring.Set();
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or WaitHandleCannotBeOpenedException) { }
+ }
+
+ public static void Listen(Dispatcher dispatcher)
+ {
+ if (_event is not null) return;
+ _event = new EventWaitHandle(false, EventResetMode.AutoReset, EventName);
+ _wait = ThreadPool.RegisterWaitForSingleObject(_event, (_, _) =>
+ {
+ string folder;
+ try { folder = File.Exists(RequestPath) ? File.ReadAllText(RequestPath).Trim() : ""; }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { folder = ""; }
+ dispatcher.BeginInvoke(() => FilesWindow.Open(folder.Length > 0 ? folder : null));
+ }, null, Timeout.Infinite, executeOnlyOnce: false);
+ }
+
+ [DllImport("user32.dll")]
+ private static extern bool AllowSetForegroundWindow(int processId);
+}
diff --git a/Files/FilesWindow.Content.cs b/Files/FilesWindow.Content.cs
new file mode 100644
index 0000000..3fc6ca0
--- /dev/null
+++ b/Files/FilesWindow.Content.cs
@@ -0,0 +1,691 @@
+using System.Globalization;
+using System.IO;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Threading;
+using static QiDock.Files.FileKinds;
+
+namespace QiDock.Files;
+
+internal sealed partial class FilesWindow
+{
+ // ---- Rows: only the rows on screen are built (the list virtualizes them) -----------------------
+
+ private abstract class Row(FilesWindow owner)
+ {
+ public FilesWindow Owner { get; } = owner;
+ }
+
+ private sealed class HeaderRow(FilesWindow owner, string title, int count) : Row(owner)
+ {
+ public string Title { get; } = title;
+ public int Count { get; } = count;
+ }
+
+ private sealed class TileRow(FilesWindow owner, FileEntry[] items, double cell) : Row(owner)
+ {
+ public FileEntry[] Items { get; } = items;
+ public double Cell { get; } = cell;
+ }
+
+ private sealed class ListHeaderRow(FilesWindow owner) : Row(owner);
+
+ private sealed class ListRow(FilesWindow owner, FileEntry item) : Row(owner)
+ {
+ public FileEntry Item { get; } = item;
+ }
+
+ private sealed class EmptyRow(FilesWindow owner, string text) : Row(owner)
+ {
+ public string Text { get; } = text;
+ }
+
+ /// <summary>The list's container for one row: builds its picture when it is shown and whenever asked to.</summary>
+ private sealed class RowHost : Border
+ {
+ public RowHost()
+ {
+ DataContextChanged += (_, _) => Rebuild();
+ Loaded += (_, _) => (DataContext as Row)?.Owner._realized.Add(this);
+ Unloaded += (_, _) => (DataContext as Row)?.Owner._realized.Remove(this);
+ }
+
+ public void Rebuild()
+ {
+ if (DataContext is not Row row) return;
+ row.Owner._realized.Add(this);
+ Child = row.Owner.BuildRow(row);
+ }
+ }
+
+ private const double TileCell = 124;
+ private const double SidePadding = 18;
+ private static readonly Brush SelectedFill = Frozen(new SolidColorBrush(Color.FromArgb(0x40, 0x0A, 0x84, 0xFF)));
+ private static readonly Brush SelectedStroke = Frozen(new SolidColorBrush(Color.FromArgb(0x80, 0x0A, 0x84, 0xFF)));
+ private static readonly Brush SelectedName = Frozen(new SolidColorBrush(Color.FromRgb(0x0A, 0x84, 0xFF)));
+ private List<FileEntry[]> _tileRows = [];
+ private VirtualizingStackPanel? _panel;
+
+ private ScrollViewer? Scroller => _list.Template?.FindName("Scroller", _list) as ScrollViewer;
+
+ private ItemsControl CreateList()
+ {
+ var scroller = new FrameworkElementFactory(typeof(ScrollViewer), "Scroller");
+ scroller.SetValue(ScrollViewer.CanContentScrollProperty, true);
+ scroller.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);
+ scroller.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Auto);
+ scroller.SetValue(FocusableProperty, false);
+ scroller.AppendChild(new FrameworkElementFactory(typeof(ItemsPresenter)));
+ var panel = new FrameworkElementFactory(typeof(VirtualizingStackPanel));
+ panel.AddHandler(LoadedEvent, new RoutedEventHandler((sender, _) => _panel = sender as VirtualizingStackPanel));
+ var list = new ItemsControl
+ {
+ Template = new ControlTemplate(typeof(ItemsControl)) { VisualTree = scroller },
+ ItemsPanel = new ItemsPanelTemplate(panel),
+ ItemTemplate = new DataTemplate { VisualTree = new FrameworkElementFactory(typeof(RowHost)) },
+ Focusable = true,
+ FocusVisualStyle = null,
+ Background = Brushes.Transparent,
+ Padding = new Thickness(0, 6, 0, 16)
+ };
+ VirtualizingPanel.SetIsVirtualizing(list, true);
+ VirtualizingPanel.SetVirtualizationMode(list, VirtualizationMode.Recycling);
+ VirtualizingPanel.SetScrollUnit(list, ScrollUnit.Pixel);
+ list.SizeChanged += (_, e) =>
+ {
+ if (_state.Grid && e.WidthChanged && Columns() != _columns)
+ {
+ var offset = Scroller?.VerticalOffset ?? 0;
+ Rebuild();
+ Scroller?.ScrollToVerticalOffset(offset);
+ }
+ };
+ // A click on empty space clears the selection.
+ list.MouseLeftButtonDown += (_, _) =>
+ {
+ list.Focus();
+ if (_selected.Count == 0) return;
+ _selected.Clear();
+ SelectionChanged();
+ };
+ list.MouseRightButtonUp += (_, e) =>
+ {
+ e.Handled = true;
+ FolderMenu();
+ };
+ return list;
+ }
+
+ private int Columns()
+ {
+ var width = (_list.ActualWidth > 0 ? _list.ActualWidth : 800) - SidePadding * 2 - 12;
+ return Math.Max(1, (int)(width / TileCell));
+ }
+
+ private static readonly Func<string, string, int> CompareNames = MakeNameComparison();
+
+ /// <summary>"Bölüm 2" before "Bölüm 10", in Turkish order, when the system can do it.</summary>
+ private static Func<string, string, int> MakeNameComparison()
+ {
+ var compare = CultureInfo.CurrentCulture.CompareInfo;
+ try
+ {
+ compare.Compare("a2", "a10", CompareOptions.IgnoreCase | CompareOptions.NumericOrdering);
+ return (a, b) => compare.Compare(a, b, CompareOptions.IgnoreCase | CompareOptions.NumericOrdering);
+ }
+ catch (ArgumentException)
+ {
+ return (a, b) => compare.Compare(a, b, CompareOptions.IgnoreCase);
+ }
+ }
+
+ private void Rebuild()
+ {
+ IEnumerable<FileEntry> items = _entries;
+ if (_filter.Length > 0) items = items.Where(e => e.Name.Contains(_filter, StringComparison.CurrentCultureIgnoreCase));
+ int Compare(FileEntry a, FileEntry b)
+ {
+ var result = _state.Sort switch
+ {
+ FileSort.Kind => a.Kind != b.Kind ? Name(a.Kind).CompareTo(Name(b.Kind)) : string.Compare(Path.GetExtension(a.Name), Path.GetExtension(b.Name), StringComparison.OrdinalIgnoreCase),
+ FileSort.Date => a.Modified.CompareTo(b.Modified),
+ FileSort.Size => a.SizeOrLength.CompareTo(b.SizeOrLength),
+ _ => 0
+ };
+ if (result == 0) result = CompareNames(a.Name, b.Name);
+ return _state.Descending ? -result : result;
+ }
+ var folders = items.Where(e => e.IsFolder).ToList();
+ var files = items.Where(e => !e.IsFolder).ToList();
+ folders.Sort(Compare);
+ files.Sort(Compare);
+ _shown = [.. folders, .. files];
+
+ var rows = new List<object>();
+ _tileRows = [];
+ if (_state.Grid)
+ {
+ _columns = Columns();
+ var cell = Math.Floor(((_list.ActualWidth > 0 ? _list.ActualWidth : 800) - SidePadding * 2 - 12) / _columns);
+ void Section(string title, List<FileEntry> section)
+ {
+ if (section.Count == 0) return;
+ rows.Add(new HeaderRow(this, title, section.Count));
+ for (var i = 0; i < section.Count; i += _columns)
+ {
+ var chunk = section.Skip(i).Take(_columns).ToArray();
+ _tileRows.Add(chunk);
+ rows.Add(new TileRow(this, chunk, cell));
+ }
+ }
+ Section(L("Klasörler", "Folders"), folders);
+ Section(L("Dosyalar", "Files"), files);
+ }
+ else
+ {
+ if (_shown.Count > 0) rows.Add(new ListHeaderRow(this));
+ foreach (var entry in _shown)
+ {
+ _tileRows.Add([entry]);
+ rows.Add(new ListRow(this, entry));
+ }
+ }
+ if (_shown.Count == 0)
+ rows.Add(new EmptyRow(this, _filter.Length > 0 ? L($"\"{_filter}\" ile eşleşen bir şey yok", $"Nothing matches \"{_filter}\"") : L("Bu klasör boş", "This folder is empty")));
+ _realized.Clear();
+ _list.ItemsSource = rows;
+ UpdateStatus();
+ UpdateDetails();
+ }
+
+ private void RedrawVisible()
+ {
+ foreach (var host in _realized.ToList())
+ if (_renameBox is null || !_renameBox.IsDescendantOf(host)) host.Rebuild();
+ }
+
+ private FrameworkElement BuildRow(Row row) => row switch
+ {
+ HeaderRow header => BuildHeader(header),
+ TileRow tiles => BuildTiles(tiles),
+ ListHeaderRow => BuildListHeader(),
+ ListRow line => BuildListRow(line.Item),
+ EmptyRow empty => new TextBlock
+ {
+ Text = empty.Text,
+ Margin = new Thickness(0, 60, 0, 0),
+ HorizontalAlignment = HorizontalAlignment.Center,
+ Foreground = (Brush)FindResource("TextSecondary"),
+ FontSize = 14
+ },
+ _ => new Border()
+ };
+
+ private FrameworkElement BuildHeader(HeaderRow header)
+ {
+ var line = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(SidePadding + 6, 14, 0, 8) };
+ line.Children.Add(Text(header.Title, 12.5, FontWeights.SemiBold, "TextSecondary"));
+ var count = Text(header.Count.ToString(CultureInfo.CurrentCulture), 12, brushKey: "TextSecondary");
+ count.Margin = new Thickness(7, 0, 0, 0);
+ count.Opacity = 0.7;
+ line.Children.Add(count);
+ return line;
+ }
+
+ private FrameworkElement BuildTiles(TileRow row)
+ {
+ var line = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(SidePadding, 0, 0, 6) };
+ foreach (var entry in row.Items)
+ line.Children.Add(new Border { Width = row.Cell, Child = BuildTile(entry) });
+ return line;
+ }
+
+ private FrameworkElement BuildTile(FileEntry entry)
+ {
+ var selected = _selected.Contains(entry.Path);
+ var stack = new StackPanel { Width = 112 };
+ FrameworkElement picture = entry.IsFolder ? FolderPicture(entry, 92) : FilePicture(entry, 80);
+ picture.HorizontalAlignment = HorizontalAlignment.Center;
+ picture.Height = 80;
+ stack.Children.Add(picture);
+ var name = new TextBlock
+ {
+ Text = SpecialNames.TryGetValue(entry.Path, out var shown) ? shown : entry.Name,
+ FontSize = 12.5,
+ TextAlignment = TextAlignment.Center,
+ TextWrapping = TextWrapping.Wrap,
+ TextTrimming = TextTrimming.CharacterEllipsis,
+ MaxHeight = 34,
+ Margin = new Thickness(2, 6, 2, 0),
+ FontWeight = selected ? FontWeights.SemiBold : FontWeights.Normal
+ };
+ if (selected) name.Foreground = SelectedName;
+ else name.SetResourceReference(TextBlock.ForegroundProperty, "TextPrimary");
+ if (entry.Hidden) stack.Opacity = 0.55;
+ stack.Children.Add(string.Equals(_renaming, entry.Path, StringComparison.OrdinalIgnoreCase) ? RenameBox(entry, centered: true) : name);
+ var tile = new Border
+ {
+ Child = stack,
+ Padding = new Thickness(4, 8, 4, 8),
+ CornerRadius = new CornerRadius(12),
+ HorizontalAlignment = HorizontalAlignment.Center,
+ Background = selected ? SelectedFill : Brushes.Transparent,
+ BorderBrush = selected ? SelectedStroke : Brushes.Transparent,
+ BorderThickness = new Thickness(1),
+ ToolTip = Describe(entry)
+ };
+ if (!selected)
+ {
+ tile.MouseEnter += (_, _) => tile.SetResourceReference(Border.BackgroundProperty, "SurfaceHover");
+ tile.MouseLeave += (_, _) => tile.Background = Brushes.Transparent;
+ }
+ Interactive(tile, entry);
+ return tile;
+ }
+
+ private FrameworkElement BuildListHeader()
+ {
+ var grid = ListColumns();
+ grid.Margin = new Thickness(SidePadding, 4, SidePadding, 4);
+ void Head(string text, int column, FileSort sort, bool right = false)
+ {
+ var label = Text(text + (_state.Sort == sort ? (_state.Descending ? " ↓" : " ↑") : ""), 11.5, FontWeights.SemiBold, "TextSecondary");
+ label.HorizontalAlignment = right ? HorizontalAlignment.Right : HorizontalAlignment.Left;
+ var cell = new Border { Background = Brushes.Transparent, Child = label, Cursor = Cursors.Hand, Padding = new Thickness(column == 0 ? 30 : 8, 4, 8, 4) };
+ cell.MouseLeftButtonDown += (_, e) =>
+ {
+ e.Handled = true;
+ _state.Descending = _state.Sort == sort ? !_state.Descending : sort is FileSort.Date or FileSort.Size;
+ _state.Sort = sort;
+ _state.Save();
+ Rebuild();
+ };
+ Grid.SetColumn(cell, column);
+ grid.Children.Add(cell);
+ }
+ Head(L("Ad", "Name"), 0, FileSort.Name);
+ Head(L("Değiştirilme", "Modified"), 1, FileSort.Date);
+ Head(L("Tür", "Kind"), 2, FileSort.Kind);
+ Head(L("Boyut", "Size"), 3, FileSort.Size, right: true);
+ var line = new Border { BorderThickness = new Thickness(0, 0, 0, 1), Child = grid };
+ line.SetResourceReference(Border.BorderBrushProperty, "MenuDivider");
+ return line;
+ }
+
+ private static Grid ListColumns()
+ {
+ var grid = new Grid();
+ grid.ColumnDefinitions.Add(new ColumnDefinition());
+ grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(150) });
+ grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(110) });
+ grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(90) });
+ return grid;
+ }
+
+ private FrameworkElement BuildListRow(FileEntry entry)
+ {
+ var selected = _selected.Contains(entry.Path);
+ var grid = ListColumns();
+ var icon = entry.IsFolder ? FolderPicture(entry, 22, small: true) : FilePicture(entry, 20);
+ icon.Margin = new Thickness(0, 0, 10, 0);
+ FrameworkElement name = string.Equals(_renaming, entry.Path, StringComparison.OrdinalIgnoreCase)
+ ? RenameBox(entry, centered: false)
+ : Text(entry.Name, 13, selected ? FontWeights.SemiBold : FontWeights.Normal);
+ var first = new DockPanel { Margin = new Thickness(6, 0, 8, 0) };
+ DockPanel.SetDock(icon, Dock.Left);
+ first.Children.Add(icon);
+ first.Children.Add(name);
+ grid.Children.Add(first);
+ void Cell(string text, int column, bool right = false)
+ {
+ var block = Text(text, 12, brushKey: "TextSecondary");
+ block.Margin = new Thickness(8, 0, 8, 0);
+ block.HorizontalAlignment = right ? HorizontalAlignment.Right : HorizontalAlignment.Left;
+ Grid.SetColumn(block, column);
+ grid.Children.Add(block);
+ }
+ Cell(Date(entry.Modified), 1);
+ Cell(entry.IsFolder ? L("Klasör", "Folder") : KindLabel(entry), 2);
+ Cell(entry.IsFolder ? (entry.Size is { } size ? FileKinds.Size(size) : Count(entry.Peek) ?? "—") : FileKinds.Size(entry.Length), 3, right: true);
+ var row = new Border
+ {
+ Child = grid,
+ Height = 32,
+ Margin = new Thickness(SidePadding - 6, 0, SidePadding - 6, 0),
+ CornerRadius = new CornerRadius(8),
+ Background = selected ? SelectedFill : Brushes.Transparent,
+ Opacity = entry.Hidden ? 0.55 : 1
+ };
+ if (!selected)
+ {
+ row.MouseEnter += (_, _) => row.SetResourceReference(Border.BackgroundProperty, "SurfaceHover");
+ row.MouseLeave += (_, _) => row.Background = Brushes.Transparent;
+ }
+ Interactive(row, entry);
+ return row;
+ }
+
+ private static string KindLabel(FileEntry entry)
+ {
+ var extension = Path.GetExtension(entry.Name).TrimStart('.').ToUpperInvariant();
+ return entry.Kind == FileKind.Other && extension.Length > 0 ? extension + " " + L("dosyası", "file") : Name(entry.Kind);
+ }
+
+ private static string? Count(FolderPeek? peek) => peek switch
+ {
+ null => null,
+ { More: true } => L($"{peek.Count}+ öğe", $"{peek.Count}+ items"),
+ _ => L($"{peek.Count} öğe", peek.Count == 1 ? "1 item" : $"{peek.Count} items")
+ };
+
+ private static string Describe(FileEntry entry)
+ {
+ var parts = new List<string> { entry.Name };
+ if (entry.IsFolder)
+ {
+ if (Count(entry.Peek) is { } count) parts.Add(count);
+ if (entry.Size is { } size) parts.Add(FileKinds.Size(size));
+ }
+ else
+ {
+ parts.Add(KindLabel(entry) + " · " + FileKinds.Size(entry.Length));
+ }
+ parts.Add(Date(entry.Modified));
+ return string.Join("\n", parts);
+ }
+
+ // ---- Pictures -------------------------------------------------------------------------------
+
+ private static readonly Dictionary<string, Geometry> SpecialFolders = BuildSpecialFolders();
+
+ private static Dictionary<string, Geometry> BuildSpecialFolders()
+ {
+ var map = new Dictionary<string, Geometry>(StringComparer.OrdinalIgnoreCase);
+ void Add(string? path, Geometry glyph)
+ {
+ if (!string.IsNullOrEmpty(path)) map[Path.TrimEndingDirectorySeparator(path)] = glyph;
+ }
+ Add(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), GlyphDesktop);
+ Add(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), GlyphDocument);
+ Add(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), GlyphImage);
+ Add(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), GlyphAudio);
+ Add(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos), GlyphVideo);
+ Add(KnownFolders.Downloads, GlyphDownload);
+ return map;
+ }
+
+ private static FrameworkElement FolderPicture(FileEntry entry, double width, bool small = false)
+ {
+ var peek = entry.Peek;
+ var color = peek is null ? FolderColor(FileKind.Other) : FolderColor(peek.Count == 0 ? null : peek.Kind);
+ var glyph = SpecialFolders.TryGetValue(entry.Path, out var special) ? special : peek is { Count: > 0 } ? Glyph(peek.Kind ?? FileKind.Other) : GlyphBox;
+ return FolderArt.Create(color, small ? null : Count(peek), glyph, width);
+ }
+
+ private FrameworkElement FilePicture(FileEntry entry, double size)
+ {
+ var color = FolderColor(entry.Kind == FileKind.Other ? FileKind.Other : entry.Kind);
+ var placeholder = new Border
+ {
+ Width = size * 0.78,
+ Height = size * 0.92,
+ CornerRadius = new CornerRadius(size * 0.12),
+ Background = Frozen(new SolidColorBrush(Color.FromArgb(0x33, color.R, color.G, color.B))),
+ BorderBrush = Frozen(new SolidColorBrush(Color.FromArgb(0x66, color.R, color.G, color.B))),
+ BorderThickness = new Thickness(1),
+ Child = FileKinds.Line(Glyph(entry.Kind), size * 0.36, Frozen(new SolidColorBrush(color)), 1.8)
+ };
+ var image = new Image { Width = size, Height = size, Stretch = Stretch.Uniform, Tag = entry.Path };
+ RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality);
+ var host = new Grid { Width = size, Height = size };
+ host.Children.Add(placeholder);
+ host.Children.Add(image);
+ var pixels = (int)Math.Ceiling(size * DpiScale());
+ void Show(BitmapSource? source)
+ {
+ if (source is null || !Equals(image.Tag, entry.Path)) return;
+ image.Source = source;
+ placeholder.Visibility = Visibility.Collapsed;
+ }
+ if (ShellThumbnails.Cached(entry.Path, pixels) is { } cached) Show(cached);
+ else ShellThumbnails.Load(entry.Path, pixels, Show);
+ return host;
+ }
+
+ private double DpiScale() => PresentationSource.FromVisual(this)?.CompositionTarget?.TransformToDevice.M11 ?? 1.5;
+
+ private static Brush Frozen(Brush brush)
+ {
+ brush.Freeze();
+ return brush;
+ }
+
+ // ---- Selection ------------------------------------------------------------------------------
+
+ private void Interactive(FrameworkElement element, FileEntry entry)
+ {
+ element.MouseLeftButtonDown += (_, e) =>
+ {
+ e.Handled = true;
+ _list.Focus();
+ if (e.ClickCount >= 2)
+ {
+ Open(entry);
+ return;
+ }
+ // Pressing one of several selected items keeps them all, so they can be dragged together.
+ if (_selected.Contains(entry.Path) && _selected.Count > 1 && Keyboard.Modifiers == ModifierKeys.None)
+ {
+ _selectOnRelease = true;
+ return;
+ }
+ Click(entry);
+ };
+ element.MouseRightButtonUp += (_, e) =>
+ {
+ e.Handled = true;
+ ItemMenu(element, entry);
+ };
+ DragAndDrop(element, entry);
+ }
+
+ private void Click(FileEntry entry)
+ {
+ var control = (Keyboard.Modifiers & ModifierKeys.Control) != 0;
+ var shift = (Keyboard.Modifiers & ModifierKeys.Shift) != 0;
+ if (shift && _anchor is not null)
+ {
+ var from = _shown.FindIndex(s => string.Equals(s.Path, _anchor, StringComparison.OrdinalIgnoreCase));
+ var to = _shown.IndexOf(entry);
+ if (from >= 0 && to >= 0)
+ {
+ if (!control) _selected.Clear();
+ for (var i = Math.Min(from, to); i <= Math.Max(from, to); i++) _selected.Add(_shown[i].Path);
+ SelectionChanged();
+ return;
+ }
+ }
+ if (control)
+ {
+ if (!_selected.Remove(entry.Path)) _selected.Add(entry.Path);
+ }
+ else
+ {
+ _selected.Clear();
+ _selected.Add(entry.Path);
+ }
+ _anchor = entry.Path;
+ SelectionChanged();
+ }
+
+ private void SelectionChanged()
+ {
+ RedrawVisible();
+ UpdateStatus();
+ UpdateDetails();
+ }
+
+ /// <summary>Arrow keys move through the grid (up/down by a whole row) or the list; Shift extends the selection.</summary>
+ private void MoveSelection(Key key, bool extend)
+ {
+ if (_tileRows.Count == 0) return;
+ var current = _anchor ?? _selected.FirstOrDefault();
+ int row = 0, column = 0;
+ var found = false;
+ for (var r = 0; r < _tileRows.Count && !found; r++)
+ for (var c = 0; c < _tileRows[r].Length; c++)
+ if (string.Equals(_tileRows[r][c].Path, current, StringComparison.OrdinalIgnoreCase))
+ {
+ (row, column, found) = (r, c, true);
+ break;
+ }
+ if (found)
+ {
+ switch (key)
+ {
+ case Key.Left: if (column > 0) column--; else if (row > 0) column = _tileRows[--row].Length - 1; break;
+ case Key.Right: if (column < _tileRows[row].Length - 1) column++; else if (row < _tileRows.Count - 1) (row, column) = (row + 1, 0); break;
+ case Key.Up: if (row > 0) row--; break;
+ case Key.Down: if (row < _tileRows.Count - 1) row++; break;
+ case Key.Home: (row, column) = (0, 0); break;
+ case Key.End: row = _tileRows.Count - 1; column = _tileRows[row].Length - 1; break;
+ }
+ column = Math.Min(column, _tileRows[row].Length - 1);
+ }
+ var target = _tileRows[row][column];
+ if (!extend) _selected.Clear();
+ _selected.Add(target.Path);
+ _anchor = target.Path;
+ SelectionChanged();
+ BringIntoView(target.Path);
+ }
+
+ private void BringIntoView(string path)
+ {
+ if (_list.ItemsSource is not List<object> rows || _panel is null) return;
+ var index = rows.FindIndex(r => r switch
+ {
+ TileRow tiles => tiles.Items.Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase)),
+ ListRow line => string.Equals(line.Item.Path, path, StringComparison.OrdinalIgnoreCase),
+ _ => false
+ });
+ if (index >= 0) _panel.BringIndexIntoViewPublic(index);
+ }
+
+ private void UpdateStatus()
+ {
+ var parts = new List<string> { L($"{_shown.Count} öğe", _shown.Count == 1 ? "1 item" : $"{_shown.Count} items") };
+ var selected = _shown.Where(s => _selected.Contains(s.Path)).ToList();
+ if (selected.Count > 0)
+ {
+ var size = selected.Sum(s => s.SizeOrLength);
+ parts.Add(L($"{selected.Count} seçili", $"{selected.Count} selected") + (size > 0 ? $" ({FileKinds.Size(size)})" : ""));
+ }
+ try
+ {
+ if (Path.GetPathRoot(_path) is { Length: > 0 } root && new DriveInfo(root) is { IsReady: true } drive)
+ parts.Add(L($"{FileKinds.Size(drive.AvailableFreeSpace)} boş", $"{FileKinds.Size(drive.AvailableFreeSpace)} free"));
+ }
+ catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException) { }
+ _status.Text = string.Join(" · ", parts);
+ }
+
+ // ---- Path bar -------------------------------------------------------------------------------
+
+ private void BuildCrumbs()
+ {
+ _crumbHost.Child = _crumbs;
+ _crumbs.Children.Clear();
+ var parts = new List<(string Name, string Path)>();
+ for (var path = _path; path is not null; path = Path.GetDirectoryName(path))
+ parts.Insert(0, (DisplayName(path), path));
+ var start = Math.Max(0, parts.Count - 6);
+ if (start > 0)
+ {
+ var more = Text("…", 13, brushKey: "TextSecondary");
+ more.Margin = new Thickness(0, 0, 4, 0);
+ _crumbs.Children.Add(more);
+ }
+ for (var i = start; i < parts.Count; i++)
+ {
+ var (name, path) = parts[i];
+ var last = i == parts.Count - 1;
+ var label = Text(name, 13, last ? FontWeights.SemiBold : FontWeights.Normal, last ? "TextPrimary" : "TextSecondary");
+ var crumb = new Border { Child = label, Padding = new Thickness(6, 3, 6, 3), CornerRadius = new CornerRadius(6), Background = Brushes.Transparent, Cursor = Cursors.Hand };
+ crumb.MouseEnter += (_, _) => crumb.SetResourceReference(Border.BackgroundProperty, "SurfaceHover");
+ crumb.MouseLeave += (_, _) => crumb.Background = Brushes.Transparent;
+ crumb.MouseLeftButtonDown += (_, e) =>
+ {
+ e.Handled = true;
+ if (!last) Navigate(path);
+ };
+ _crumbs.Children.Add(crumb);
+ if (last) continue;
+ var arrow = FileKinds.Line(Geometry.Parse("M9 18l6-6-6-6"), 10, (Brush)FindResource("TextSecondary"), 2);
+ arrow.Opacity = 0.6;
+ arrow.Margin = new Thickness(2, 0, 2, 0);
+ _crumbs.Children.Add(arrow);
+ }
+ var hint = Text(L("Ctrl+L ile yol yazın", "Ctrl+L to type a path"), 11, brushKey: "TextSecondary");
+ hint.Opacity = 0.6;
+ hint.Margin = new Thickness(18, 0, 0, 0);
+ _crumbs.Children.Add(hint);
+ }
+
+ private void EditPath()
+ {
+ var box = new TextBox
+ {
+ Text = _path,
+ Background = Brushes.Transparent,
+ BorderThickness = new Thickness(0),
+ VerticalContentAlignment = VerticalAlignment.Center,
+ FontSize = 13
+ };
+ box.SetResourceReference(ForegroundProperty, "TextPrimary");
+ box.SetResourceReference(System.Windows.Controls.Primitives.TextBoxBase.CaretBrushProperty, "TextPrimary");
+ var done = false;
+ void Finish(bool go)
+ {
+ if (done) return;
+ done = true;
+ var text = box.Text;
+ BuildCrumbs();
+ if (go && !string.Equals(text, _path, StringComparison.OrdinalIgnoreCase)) Navigate(text);
+ _list.Focus();
+ }
+ box.KeyDown += (_, e) =>
+ {
+ if (e.Key == Key.Enter) Finish(true);
+ else if (e.Key == Key.Escape) Finish(false);
+ else return;
+ e.Handled = true;
+ };
+ box.LostKeyboardFocus += (_, _) => Finish(false);
+ _crumbHost.Child = box;
+ Dispatcher.BeginInvoke(DispatcherPriority.Input, () =>
+ {
+ box.Focus();
+ box.SelectAll();
+ });
+ }
+}
+
+/// <summary>Folders Windows knows by id (Downloads has no SpecialFolder value).</summary>
+internal static class KnownFolders
+{
+ public static readonly string? Downloads = Get(new Guid("374DE290-123F-4565-9164-39C4925E467B"));
+
+ private static string? Get(Guid id)
+ {
+ if (SHGetKnownFolderPath(ref id, 0, 0, out var path) != 0) return null;
+ try { return System.Runtime.InteropServices.Marshal.PtrToStringUni(path); }
+ finally { System.Runtime.InteropServices.Marshal.FreeCoTaskMem(path); }
+ }
+
+ [System.Runtime.InteropServices.DllImport("shell32.dll")]
+ private static extern int SHGetKnownFolderPath(ref Guid id, uint flags, nint token, out nint path);
+}
diff --git a/Files/FilesWindow.Operations.cs b/Files/FilesWindow.Operations.cs
new file mode 100644
index 0000000..004ca93
--- /dev/null
+++ b/Files/FilesWindow.Operations.cs
@@ -0,0 +1,450 @@
+using System.Diagnostics;
+using System.IO;
+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.Threading;
+using static QiDock.Files.FileKinds;
+
+namespace QiDock.Files;
+
+/// <summary>
+/// What can be done with files: copy, cut, paste, delete, rename, new folder, drag and drop, and QiDock's own
+/// right-click menu. The Windows right-click menu is left out on purpose: it loads other programs' add-ons (archivers,
+/// cloud drives…) into QiDock's process, which costs memory and can take the dock down when one of them crashes.
+/// </summary>
+internal sealed partial class FilesWindow
+{
+ private string? _renaming;
+ private TextBox? _renameBox;
+ private Point _pressedAt;
+ private FileEntry? _pressed;
+ private bool _selectOnRelease;
+
+ private nint Handle => new WindowInteropHelper(this).Handle;
+
+ private List<FileEntry> SelectedEntries() => _shown.Where(s => _selected.Contains(s.Path)).ToList();
+
+ private List<string> SelectedPaths() => SelectedEntries().Select(s => s.Path).ToList();
+
+ /// <summary>Keys for file work; returns whether the key was used.</summary>
+ private bool OnOperationKey(Key key)
+ {
+ var control = (Keyboard.Modifiers & ModifierKeys.Control) != 0;
+ var shift = (Keyboard.Modifiers & ModifierKeys.Shift) != 0;
+ switch (key)
+ {
+ case Key.C when control && shift: CopyPaths(); return true;
+ case Key.C when control: ToClipboard(cut: false); return true;
+ case Key.X when control: ToClipboard(cut: true); return true;
+ case Key.V when control: Paste(_path); return true;
+ case Key.Delete: Delete(permanently: shift); return true;
+ case Key.F2: BeginRename(); return true;
+ case Key.N when control && shift: NewFolder(); return true;
+ default: return false;
+ }
+ }
+
+ // ---- Clipboard ------------------------------------------------------------------------------
+
+ private void ToClipboard(bool cut)
+ {
+ var paths = SelectedPaths();
+ if (paths.Count == 0) return;
+ FileOperations.ToClipboard(paths, cut);
+ ShowStatusMessage(cut
+ ? L($"{paths.Count} öğe kesildi; yapıştırınca taşınacak.", $"{paths.Count} cut; they move when pasted.")
+ : L($"{paths.Count} öğe kopyalandı.", $"{paths.Count} copied."));
+ }
+
+ private void CopyPaths()
+ {
+ var paths = SelectedPaths();
+ if (paths.Count == 0) paths = [_path];
+ try
+ {
+ Clipboard.SetText(string.Join(Environment.NewLine, paths.Select(p => p.Contains(' ') ? $"\"{p}\"" : p)));
+ ShowStatusMessage(L("Yol kopyalandı.", "Path copied."));
+ }
+ catch (System.Runtime.InteropServices.COMException) { }
+ }
+
+ private async void Paste(string target)
+ {
+ var (paths, cut) = FileOperations.FromClipboard();
+ if (paths.Count == 0) return;
+ if (cut && paths.Any(p => IsInside(target, p)))
+ {
+ ShowStatusMessage(L("Bir klasör kendi içine taşınamaz.", "A folder can't be moved into itself."));
+ return;
+ }
+ var done = cut ? await FileOperations.MoveAsync(paths, target, Handle) : await FileOperations.CopyAsync(paths, target, Handle);
+ if (done && cut)
+ {
+ try { Clipboard.Clear(); }
+ catch (System.Runtime.InteropServices.COMException) { }
+ }
+ AfterChange(target, paths);
+ }
+
+ /// <summary>Refreshes and selects what just arrived (when it landed in the open folder).</summary>
+ private void AfterChange(string target, IEnumerable<string> arrived)
+ {
+ FolderScanner.Forget(target);
+ if (!string.Equals(Path.TrimEndingDirectorySeparator(target), _path, StringComparison.OrdinalIgnoreCase)) return;
+ _selected.Clear();
+ foreach (var path in arrived) _selected.Add(Path.Combine(_path, Path.GetFileName(path)));
+ Load(keepScroll: true);
+ }
+
+ private static bool IsInside(string target, string path) =>
+ string.Equals(target, path, StringComparison.OrdinalIgnoreCase)
+ || target.StartsWith(Path.TrimEndingDirectorySeparator(path) + "\\", StringComparison.OrdinalIgnoreCase);
+
+ // ---- Delete, new folder, rename -------------------------------------------------------------
+
+ private async void Delete(bool permanently)
+ {
+ var paths = SelectedPaths();
+ if (paths.Count == 0) return;
+ // Move the selection on to the next item, so a run of deletes goes smoothly.
+ var next = _shown.FirstOrDefault(s => !_selected.Contains(s.Path) && _shown.IndexOf(s) > _shown.FindIndex(x => _selected.Contains(x.Path)));
+ if (await FileOperations.DeleteAsync(paths, permanently, Handle))
+ {
+ _selected.Clear();
+ if (next is not null) _selected.Add(next.Path);
+ }
+ FolderScanner.Forget(_path);
+ Load(keepScroll: true);
+ }
+
+ private void NewFolder()
+ {
+ var path = FileOperations.FreeName(_path, L("Yeni klasör", "New folder"));
+ try
+ {
+ Directory.CreateDirectory(path);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ ShowStatusMessage(L("Klasör oluşturulamadı: ", "Could not create the folder: ") + ex.Message);
+ return;
+ }
+ if (_search.Text.Length > 0) _search.Text = "";
+ _selected.Clear();
+ _selected.Add(path);
+ _anchor = path;
+ _renaming = path;
+ Load(keepScroll: true, select: path);
+ }
+
+ private void BeginRename()
+ {
+ var selected = SelectedEntries();
+ if (selected.Count != 1) return;
+ _renaming = selected[0].Path;
+ BringIntoView(_renaming);
+ RedrawVisible();
+ }
+
+ /// <summary>The name box shown in place of a name while renaming.</summary>
+ private TextBox RenameBox(FileEntry entry, bool centered)
+ {
+ var box = new TextBox
+ {
+ Text = entry.Name,
+ FontSize = centered ? 12.5 : 13,
+ TextAlignment = centered ? TextAlignment.Center : TextAlignment.Left,
+ TextWrapping = centered ? TextWrapping.Wrap : TextWrapping.NoWrap,
+ MaxHeight = 52,
+ Padding = new Thickness(2, 1, 2, 1),
+ Margin = centered ? new Thickness(0, 4, 0, 0) : new Thickness(0),
+ BorderThickness = new Thickness(1),
+ BorderBrush = SelectedName,
+ VerticalContentAlignment = VerticalAlignment.Center
+ };
+ box.SetResourceReference(BackgroundProperty, "SettingsBackground");
+ box.SetResourceReference(ForegroundProperty, "TextPrimary");
+ box.SetResourceReference(TextBoxBase.CaretBrushProperty, "TextPrimary");
+ var done = false;
+ void Finish(bool keep)
+ {
+ if (done) return;
+ done = true;
+ _renaming = null;
+ _renameBox = null;
+ if (keep && box.Text.Trim() != entry.Name)
+ {
+ var (renamed, error) = FileOperations.Rename(entry.Path, box.Text);
+ if (error is not null) ShowStatusMessage(error);
+ if (renamed is not null)
+ {
+ _selected.Clear();
+ _selected.Add(renamed);
+ _anchor = renamed;
+ FolderScanner.Forget(_path);
+ Load(keepScroll: true, select: renamed);
+ _list.Focus();
+ return;
+ }
+ }
+ RedrawVisible();
+ _list.Focus();
+ }
+ box.PreviewKeyDown += (_, e) =>
+ {
+ if (e.Key == Key.Enter) Finish(true);
+ else if (e.Key == Key.Escape) Finish(false);
+ else return;
+ e.Handled = true;
+ };
+ box.LostKeyboardFocus += (_, _) => Finish(true);
+ box.MouseLeftButtonDown += (_, e) => e.Handled = true;
+ _renameBox = box;
+ Dispatcher.BeginInvoke(DispatcherPriority.Input, () =>
+ {
+ box.Focus();
+ // The name without its extension, as Explorer does.
+ var stem = entry.IsFolder ? entry.Name.Length : Path.GetFileNameWithoutExtension(entry.Name).Length;
+ box.Select(0, stem > 0 ? stem : entry.Name.Length);
+ });
+ return box;
+ }
+
+ // ---- Drag and drop --------------------------------------------------------------------------
+
+ /// <summary>Press, drag out (to Explorer, a mail, the desktop…) and drop onto folders.</summary>
+ private void DragAndDrop(FrameworkElement element, FileEntry entry)
+ {
+ element.PreviewMouseLeftButtonDown += (_, e) =>
+ {
+ _pressed = entry;
+ _pressedAt = e.GetPosition(this);
+ };
+ element.MouseMove += (_, e) =>
+ {
+ if (e.LeftButton != MouseButtonState.Pressed || _pressed != entry || _renaming is not null) return;
+ var moved = e.GetPosition(this) - _pressedAt;
+ if (Math.Abs(moved.X) < SystemParameters.MinimumHorizontalDragDistance && Math.Abs(moved.Y) < SystemParameters.MinimumVerticalDragDistance) return;
+ _pressed = null;
+ _selectOnRelease = false;
+ if (!_selected.Contains(entry.Path))
+ {
+ _selected.Clear();
+ _selected.Add(entry.Path);
+ SelectionChanged();
+ }
+ var paths = SelectedPaths().ToArray();
+ if (paths.Length == 0) return;
+ var data = new DataObject(DataFormats.FileDrop, paths);
+ try { DragDrop.DoDragDrop(element, data, DragDropEffects.Copy | DragDropEffects.Move | DragDropEffects.Link); }
+ catch (System.Runtime.InteropServices.COMException) { }
+ };
+ element.MouseLeftButtonUp += (_, _) =>
+ {
+ if (_selectOnRelease && _pressed == entry)
+ {
+ _selectOnRelease = false;
+ _selected.Clear();
+ _selected.Add(entry.Path);
+ _anchor = entry.Path;
+ SelectionChanged();
+ }
+ _pressed = null;
+ };
+ if (!entry.IsFolder) return;
+ element.AllowDrop = true;
+ element.DragEnter += (_, e) =>
+ {
+ if (DropEffect(e, entry.Path) != DragDropEffects.None && element is Border border) border.SetResourceReference(Border.BackgroundProperty, "SurfaceHover");
+ };
+ element.DragLeave += (_, _) =>
+ {
+ if (element is Border border && !_selected.Contains(entry.Path)) border.Background = Brushes.Transparent;
+ };
+ element.DragOver += (_, e) =>
+ {
+ e.Effects = DropEffect(e, entry.Path);
+ e.Handled = true;
+ };
+ element.Drop += (_, e) =>
+ {
+ e.Handled = true;
+ if (element is Border border && !_selected.Contains(entry.Path)) border.Background = Brushes.Transparent;
+ DropInto(e, entry.Path);
+ };
+ }
+
+ /// <summary>Drops onto empty space go into the open folder.</summary>
+ private void AcceptDrops()
+ {
+ _list.AllowDrop = true;
+ _list.DragOver += (_, e) =>
+ {
+ e.Effects = DropEffect(e, _path);
+ e.Handled = true;
+ };
+ _list.Drop += (_, e) =>
+ {
+ e.Handled = true;
+ DropInto(e, _path);
+ };
+ }
+
+ private static string[] DroppedPaths(DragEventArgs e) =>
+ e.Data.GetDataPresent(DataFormats.FileDrop) ? e.Data.GetData(DataFormats.FileDrop) as string[] ?? [] : [];
+
+ /// <summary>Same drive moves, another drive copies; Ctrl copies, Shift moves (as in Explorer).</summary>
+ private static DragDropEffects DropEffect(DragEventArgs e, string target)
+ {
+ var paths = DroppedPaths(e);
+ if (paths.Length == 0) return DragDropEffects.None;
+ // Not into itself, and not back into the folder it came from.
+ if (paths.Any(p => IsInside(target, p))) return DragDropEffects.None;
+ if (paths.All(p => string.Equals(Path.GetDirectoryName(p), Path.TrimEndingDirectorySeparator(target), StringComparison.OrdinalIgnoreCase))
+ && (e.KeyStates & DragDropKeyStates.ControlKey) == 0) return DragDropEffects.None;
+ DragDropEffects wanted;
+ if ((e.KeyStates & DragDropKeyStates.ControlKey) != 0) wanted = DragDropEffects.Copy;
+ else if ((e.KeyStates & DragDropKeyStates.ShiftKey) != 0) wanted = DragDropEffects.Move;
+ else wanted = string.Equals(Path.GetPathRoot(paths[0]), Path.GetPathRoot(target), StringComparison.OrdinalIgnoreCase) ? DragDropEffects.Move : DragDropEffects.Copy;
+ return (e.AllowedEffects & wanted) != 0 ? wanted : e.AllowedEffects & DragDropEffects.Copy;
+ }
+
+ private async void DropInto(DragEventArgs e, string target)
+ {
+ var effect = DropEffect(e, target);
+ var paths = DroppedPaths(e).ToList();
+ if (effect == DragDropEffects.None || paths.Count == 0) return;
+ var done = effect == DragDropEffects.Move
+ ? await FileOperations.MoveAsync(paths, target, Handle)
+ : await FileOperations.CopyAsync(paths, target, Handle);
+ if (done) AfterChange(target, paths);
+ }
+
+ // ---- Right-click menu -----------------------------------------------------------------------
+
+ private void ItemMenu(FrameworkElement anchor, FileEntry entry)
+ {
+ if (!_selected.Contains(entry.Path))
+ {
+ _selected.Clear();
+ _selected.Add(entry.Path);
+ _anchor = entry.Path;
+ SelectionChanged();
+ }
+ var selected = SelectedEntries();
+ if (selected.Count == 0) return;
+ var single = selected.Count == 1 ? selected[0] : null;
+ var menu = NewMenu(anchor);
+
+ Add(menu, L("Aç", "Open"), "IconOpen", () =>
+ {
+ if (single is not null) Open(single);
+ else foreach (var file in selected.Where(s => !s.IsFolder)) OpenItem(file.Path);
+ });
+ if (single is { IsFolder: false })
+ Add(menu, L("Birlikte aç…", "Open with…"), "IconApps", () => Run("rundll32.exe", $"shell32.dll,OpenAs_RunDLL {single.Path}"));
+ if (single is { IsFolder: true })
+ Add(menu, L("Terminalde aç", "Open in Terminal"), "IconTerminal", () => OpenTerminal(single.Path));
+ menu.Items.Add(new Separator());
+ Add(menu, L("Kes", "Cut"), "IconScissors", () => ToClipboard(cut: true));
+ Add(menu, L("Kopyala", "Copy"), "IconCopy", () => ToClipboard(cut: false));
+ if (single is { IsFolder: true })
+ Add(menu, L("Bu klasöre yapıştır", "Paste into folder"), "IconClipboard", () => Paste(single.Path), FileOperations.ClipboardHasFiles());
+ Add(menu, L("Yolu kopyala", "Copy path"), "IconLink", CopyPaths);
+ menu.Items.Add(new Separator());
+ if (single is not null) Add(menu, L("Yeniden adlandır", "Rename"), "IconEdit", BeginRename);
+ if (single is { IsFolder: false } && single.Name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
+ Add(menu, L("Buraya çıkar", "Extract here"), "IconArchive", () => Unzip(single.Path));
+ else
+ Add(menu, L("Sıkıştır (zip)", "Compress (zip)"), "IconArchive", () => Zip(selected.Select(s => s.Path).ToList()));
+ Add(menu, L("Dock'a sabitle", "Pin to dock"), "IconPin", () => (Application.Current.MainWindow as MainWindow)?.PinToDock(selected.Select(s => s.Path)));
+ Add(menu, L("Gezgin'de göster", "Show in Explorer"), "IconFolderOpen", () => Run("explorer.exe", $"/select,\"{selected[0].Path}\""));
+ menu.Items.Add(new Separator());
+ var trash = Add(menu, L("Çöp kutusuna taşı", "Move to Recycle Bin"), "IconTrash", () => Delete(permanently: false));
+ trash.SetResourceReference(StyleProperty, "DestructiveMenuItem");
+ menu.IsOpen = true;
+ }
+
+ private void FolderMenu()
+ {
+ if (_selected.Count > 0)
+ {
+ _selected.Clear();
+ SelectionChanged();
+ }
+ var menu = NewMenu(_list);
+ Add(menu, L("Yapıştır", "Paste"), "IconClipboard", () => Paste(_path), FileOperations.ClipboardHasFiles());
+ Add(menu, L("Yeni klasör", "New folder"), "IconPlus", NewFolder);
+ menu.Items.Add(new Separator());
+ Add(menu, L("Terminalde aç", "Open in Terminal"), "IconTerminal", () => OpenTerminal(_path));
+ Add(menu, L("Gezgin'de aç", "Open in Explorer"), "IconFolderOpen", () => Run("explorer.exe", $"\"{_path}\""));
+ Add(menu, L("Yolu kopyala", "Copy path"), "IconLink", CopyPaths);
+ menu.Items.Add(new Separator());
+ Add(menu, L("Yenile", "Refresh"), "IconRotate", () =>
+ {
+ FolderScanner.Forget(_path);
+ Load(keepScroll: true);
+ });
+ menu.IsOpen = true;
+ }
+
+ private static ContextMenu NewMenu(UIElement anchor) => new() { PlacementTarget = anchor, Placement = PlacementMode.MousePoint };
+
+ private static MenuItem Add(ContextMenu menu, string header, string icon, Action click, bool enabled = true)
+ {
+ var item = new MenuItem { Header = header, IsEnabled = enabled };
+ if (Application.Current.TryFindResource(icon) is Geometry geometry) item.Icon = geometry;
+ item.Click += (_, _) => click();
+ menu.Items.Add(item);
+ return item;
+ }
+
+ private async void Zip(List<string> paths)
+ {
+ ShowStatusMessage(L("Sıkıştırılıyor…", "Compressing…"));
+ var zip = await FileOperations.ZipAsync(paths, _path);
+ if (zip is null)
+ {
+ ShowStatusMessage(L("Sıkıştırılamadı.", "Could not compress."));
+ return;
+ }
+ AfterChange(_path, [zip]);
+ }
+
+ private async void Unzip(string path)
+ {
+ ShowStatusMessage(L("Çıkarılıyor…", "Extracting…"));
+ var folder = await FileOperations.UnzipAsync(path);
+ if (folder is null)
+ {
+ ShowStatusMessage(L("Arşiv açılamadı.", "Could not extract."));
+ return;
+ }
+ AfterChange(_path, [folder]);
+ }
+
+ private void OpenTerminal(string folder)
+ {
+ // Windows Terminal when there is one, otherwise PowerShell.
+ if (!Run("wt.exe", $"-d \"{folder.TrimEnd('\\')}\\.\"", quiet: true))
+ Run("powershell.exe", "-NoExit", workingDirectory: folder);
+ }
+
+ private bool Run(string file, string arguments, bool quiet = false, string? workingDirectory = null)
+ {
+ try
+ {
+ Process.Start(new ProcessStartInfo(file, arguments) { UseShellExecute = true, WorkingDirectory = workingDirectory ?? _path })?.Dispose();
+ return true;
+ }
+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)
+ {
+ if (!quiet) ShowStatusMessage(L("Açılamadı: ", "Could not open: ") + file);
+ return false;
+ }
+ }
+}
diff --git a/Files/FilesWindow.Panels.cs b/Files/FilesWindow.Panels.cs
new file mode 100644
index 0000000..38fa061
--- /dev/null
+++ b/Files/FilesWindow.Panels.cs
@@ -0,0 +1,376 @@
+using System.Globalization;
+using System.IO;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using System.Windows.Shell;
+using static QiDock.Files.FileKinds;
+
+namespace QiDock.Files;
+
+internal sealed partial class FilesWindow
+{
+ private readonly List<(Border Item, string Path)> _places = [];
+ private StackPanel? _locations;
+ private Border? _diskCard;
+
+ // ---- Sidebar --------------------------------------------------------------------------------
+
+ private FrameworkElement BuildSidebar(TextBox search)
+ {
+ var tint = new Border { Opacity = 0.5 };
+ tint.SetResourceReference(Border.BackgroundProperty, "SurfaceHover");
+ var edge = new Border { BorderThickness = new Thickness(0, 0, 1, 0) };
+ edge.SetResourceReference(Border.BorderBrushProperty, "MenuDivider");
+
+ var header = new StackPanel { Orientation = Orientation.Horizontal, Height = 52, Margin = new Thickness(18, 0, 0, 0) };
+ var logo = FolderArt.Create(FolderColor(FileKind.Other), null, GlyphBox, 24);
+ logo.VerticalAlignment = VerticalAlignment.Center;
+ header.Children.Add(logo);
+ var title = Text(L("Dosyalar", "Files"), 16, FontWeights.Bold);
+ title.Margin = new Thickness(10, 0, 0, 0);
+ header.Children.Add(title);
+
+ var searchIcon = FileKinds.Line(Geometry.Parse("M11 3a8 8 0 1 0 0 16a8 8 0 1 0 0-16z M21 21l-4.35-4.35"), 14, (Brush)FindResource("TextSecondary"), 2);
+ searchIcon.Margin = new Thickness(0, 0, 8, 0);
+ var hint = Text(L("Bu klasörde ara", "Search this folder"), 13, brushKey: "TextSecondary");
+ hint.IsHitTestVisible = false;
+ search.TextChanged += (_, _) => hint.Visibility = search.Text.Length == 0 ? Visibility.Visible : Visibility.Collapsed;
+ var keys = Text("Ctrl+F", 10.5, brushKey: "TextSecondary");
+ keys.Opacity = 0.6;
+ var field = new DockPanel();
+ DockPanel.SetDock(searchIcon, Dock.Left);
+ DockPanel.SetDock(keys, Dock.Right);
+ field.Children.Add(searchIcon);
+ field.Children.Add(keys);
+ var input = new Grid();
+ input.Children.Add(hint);
+ input.Children.Add(search);
+ field.Children.Add(input);
+ var searchBox = new Border { Height = 34, Margin = new Thickness(12, 0, 12, 10), Padding = new Thickness(10, 0, 10, 0), CornerRadius = new CornerRadius(9), Child = field };
+ searchBox.SetResourceReference(Border.BackgroundProperty, "SurfaceHover");
+
+ var list = new StackPanel { Margin = new Thickness(8, 0, 8, 12) };
+ list.Children.Add(SectionTitle(L("Sık kullanılanlar", "Favourites")));
+ var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
+ AddPlace(list, GlyphDesktop, L("Masaüstü", "Desktop"), Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
+ AddPlace(list, GlyphDocument, L("Belgeler", "Documents"), Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
+ AddPlace(list, GlyphDownload, L("İndirilenler", "Downloads"), KnownFolders.Downloads);
+ AddPlace(list, GlyphImage, L("Resimler", "Pictures"), Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
+ AddPlace(list, GlyphAudio, L("Müzik", "Music"), Environment.GetFolderPath(Environment.SpecialFolder.MyMusic));
+ AddPlace(list, GlyphVideo, L("Videolar", "Videos"), Environment.GetFolderPath(Environment.SpecialFolder.MyVideos));
+ AddPlace(list, GlyphHome, Path.GetFileName(home), home);
+
+ list.Children.Add(SectionTitle(L("Konumlar", "Locations")));
+ _locations = new StackPanel();
+ list.Children.Add(_locations);
+ var trash = Place(GlyphTrash, L("Çöp Kutusu", "Recycle Bin"), null);
+ trash.MouseLeftButtonDown += (_, e) =>
+ {
+ e.Handled = true;
+ OpenItem("shell:RecycleBinFolder");
+ };
+ list.Children.Add(trash);
+ _ = LoadLocationsAsync();
+
+ var scroller = new ScrollViewer { Content = list, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled, Focusable = false };
+ _diskCard = new Border { Margin = new Thickness(12, 6, 12, 12) };
+
+ var column = new Grid();
+ column.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
+ column.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
+ column.RowDefinitions.Add(new RowDefinition());
+ column.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
+ column.Children.Add(header);
+ Grid.SetRow(searchBox, 1);
+ column.Children.Add(searchBox);
+ Grid.SetRow(scroller, 2);
+ column.Children.Add(scroller);
+ Grid.SetRow(_diskCard, 3);
+ column.Children.Add(_diskCard);
+
+ var sidebar = new Grid();
+ sidebar.Children.Add(tint);
+ sidebar.Children.Add(edge);
+ sidebar.Children.Add(column);
+ return sidebar;
+ }
+
+ private static FrameworkElement SectionTitle(string text)
+ {
+ var title = Text(text, 11.5, FontWeights.SemiBold, "TextSecondary");
+ title.Margin = new Thickness(10, 14, 0, 6);
+ title.Opacity = 0.85;
+ return title;
+ }
+
+ private void AddPlace(Panel list, Geometry glyph, string name, string? path)
+ {
+ if (string.IsNullOrEmpty(path) || !Directory.Exists(path)) return;
+ list.Children.Add(Place(glyph, name, path));
+ }
+
+ private Border Place(Geometry glyph, string name, string? path, string? note = null)
+ {
+ var line = new DockPanel();
+ var icon = FileKinds.Line(glyph, 16, (Brush)FindResource("WidgetAccent"), 1.8);
+ icon.Margin = new Thickness(0, 0, 11, 0);
+ DockPanel.SetDock(icon, Dock.Left);
+ line.Children.Add(icon);
+ if (note is not null)
+ {
+ var extra = Text(note, 11, brushKey: "TextSecondary");
+ extra.Margin = new Thickness(8, 0, 0, 0);
+ DockPanel.SetDock(extra, Dock.Right);
+ line.Children.Add(extra);
+ }
+ line.Children.Add(Text(name, 13.5));
+ var item = new Border { Child = line, Height = 34, Padding = new Thickness(10, 0, 10, 0), CornerRadius = new CornerRadius(8), Background = Brushes.Transparent, Cursor = System.Windows.Input.Cursors.Hand, ToolTip = path };
+ item.MouseEnter += (_, _) =>
+ {
+ if (!IsCurrentPlace(path)) item.SetResourceReference(Border.BackgroundProperty, "SurfaceHover");
+ };
+ item.MouseLeave += (_, _) =>
+ {
+ if (!IsCurrentPlace(path)) item.Background = Brushes.Transparent;
+ };
+ if (path is not null)
+ {
+ item.MouseLeftButtonDown += (_, e) =>
+ {
+ e.Handled = true;
+ Navigate(path);
+ };
+ _places.Add((item, path));
+ }
+ return item;
+ }
+
+ private bool IsCurrentPlace(string? path) => path is not null && string.Equals(Path.TrimEndingDirectorySeparator(path), Path.TrimEndingDirectorySeparator(_path), StringComparison.OrdinalIgnoreCase);
+
+ private void HighlightSidebar()
+ {
+ foreach (var (item, path) in _places)
+ item.Background = IsCurrentPlace(path) ? SelectedFill : Brushes.Transparent;
+ UpdateDiskCard();
+ }
+
+ /// <summary>Drives and cloud folders, read in the background (a sleeping network drive can take seconds).</summary>
+ private async Task LoadLocationsAsync()
+ {
+ var places = await Task.Run(() =>
+ {
+ var found = new List<(Geometry Glyph, string Name, string Path, string? Note)>();
+ var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
+ foreach (var variable in new[] { "OneDriveCommercial", "OneDriveConsumer", "OneDrive" })
+ {
+ var path = Environment.GetEnvironmentVariable(variable);
+ if (!string.IsNullOrEmpty(path) && Directory.Exists(path) && found.All(f => !string.Equals(f.Path, path, StringComparison.OrdinalIgnoreCase)))
+ found.Add((GlyphCloud, Path.GetFileName(path).Replace(" - ", " · "), path, null));
+ }
+ var iCloud = Path.Combine(home, "iCloudDrive");
+ if (Directory.Exists(iCloud)) found.Add((GlyphCloud, "iCloud Drive", iCloud, null));
+ foreach (var drive in DriveInfo.GetDrives())
+ {
+ try
+ {
+ if (drive.DriveType is DriveType.CDRom or DriveType.NoRootDirectory or DriveType.Unknown || !drive.IsReady) continue;
+ var letter = drive.Name.TrimEnd('\\');
+ var label = drive.VolumeLabel;
+ if (label.Equals("Google Drive", StringComparison.OrdinalIgnoreCase))
+ {
+ var mine = Directory.GetDirectories(drive.Name).FirstOrDefault(d => Path.GetFileName(d) is "My Drive" or "Drive'ım");
+ found.Add((GlyphCloud, "Google Drive", mine ?? drive.Name, null));
+ continue;
+ }
+ var glyph = drive.DriveType == DriveType.Removable ? GlyphUsb : GlyphDrive;
+ var name = label.Length > 0 ? $"{label} ({letter})" : drive.DriveType == DriveType.Removable ? L($"USB bellek ({letter})", $"USB drive ({letter})") : L($"Yerel Disk ({letter})", $"Local Disk ({letter})");
+ found.Add((glyph, name, drive.Name, FileKinds.Size(drive.AvailableFreeSpace)));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
+ }
+ return found;
+ });
+ if (_locations is null) return;
+ foreach (var (glyph, name, path, note) in places) _locations.Children.Add(Place(glyph, name, path, note));
+ HighlightSidebar();
+ }
+
+ /// <summary>The bottom card: the open folder's drive with its free space as a bar.</summary>
+ private void UpdateDiskCard()
+ {
+ if (_diskCard is null) return;
+ try
+ {
+ if (Path.GetPathRoot(_path) is not { Length: > 0 } root || new DriveInfo(root) is not { IsReady: true } drive || drive.TotalSize <= 0)
+ {
+ _diskCard.Child = null;
+ return;
+ }
+ var used = 1 - (double)drive.AvailableFreeSpace / drive.TotalSize;
+ var name = Text(drive.VolumeLabel.Length > 0 ? drive.VolumeLabel : L("Yerel Disk", "Local Disk") + $" ({root.TrimEnd('\\')})", 12.5, FontWeights.SemiBold);
+ var free = Text(L($"{FileKinds.Size(drive.AvailableFreeSpace)} boş · {FileKinds.Size(drive.TotalSize)}", $"{FileKinds.Size(drive.AvailableFreeSpace)} free of {FileKinds.Size(drive.TotalSize)}"), 11, brushKey: "TextSecondary");
+ var bar = Bar(used, used > 0.9 ? Color.FromRgb(0xFF, 0x45, 0x3A) : Color.FromRgb(0x0A, 0x84, 0xFF));
+ bar.Margin = new Thickness(0, 7, 0, 5);
+ var stack = new StackPanel();
+ stack.Children.Add(name);
+ stack.Children.Add(bar);
+ stack.Children.Add(free);
+ _diskCard.Child = stack;
+ }
+ catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException)
+ {
+ _diskCard.Child = null;
+ }
+ }
+
+ private static Grid Bar(double share, Color color)
+ {
+ var grid = new Grid { Height = 5 };
+ var track = new Border { CornerRadius = new CornerRadius(2.5) };
+ track.SetResourceReference(Border.BackgroundProperty, "SurfaceHover");
+ grid.Children.Add(track);
+ var fill = new Border
+ {
+ CornerRadius = new CornerRadius(2.5),
+ Background = Frozen(new SolidColorBrush(color)),
+ HorizontalAlignment = HorizontalAlignment.Left
+ };
+ grid.SizeChanged += (_, _) => fill.Width = Math.Max(share > 0 ? 5 : 0, grid.ActualWidth * Math.Clamp(share, 0, 1));
+ grid.Children.Add(fill);
+ return grid;
+ }
+
+ // ---- Details panel --------------------------------------------------------------------------
+
+ private void UpdateDetails()
+ {
+ if (!_state.Details || _details is null) return;
+ var selected = _shown.Where(s => _selected.Contains(s.Path)).ToList();
+ _details.Child = selected.Count == 1 ? ItemDetails(selected[0]) : FolderDetails(selected.Count > 1 ? selected : null);
+ }
+
+ /// <summary>The open folder (or several selected items): their total size and what takes the space.</summary>
+ private FrameworkElement FolderDetails(List<FileEntry>? selection)
+ {
+ var items = selection ?? _entries;
+ var stack = new StackPanel();
+ var heading = Text(selection is null ? _title.Text : L($"{selection.Count} öğe seçili", $"{selection.Count} items selected"), 16, FontWeights.SemiBold);
+ stack.Children.Add(heading);
+
+ var folders = items.Where(e => e.IsFolder).ToList();
+ var pending = folders.Count(f => f.Size is null);
+ var total = items.Sum(e => e.SizeOrLength);
+ var size = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 6, 0, 0) };
+ size.Children.Add(Text(FileKinds.Size(total), 26, FontWeights.SemiBold));
+ var waiting = pending > 0 && !_sizesWanted;
+ var suffix = Text(waiting ? L(" dosyalar", " in files") : pending > 0 ? L(" hesaplanıyor…", " adding up…") : L(" toplam", " in all"), 13, brushKey: "TextSecondary");
+ suffix.VerticalAlignment = VerticalAlignment.Bottom;
+ suffix.Margin = new Thickness(0, 0, 0, 5);
+ size.Children.Add(suffix);
+ stack.Children.Add(size);
+ var files = items.Count - folders.Count;
+ var counts = new List<string>();
+ if (folders.Count > 0) counts.Add(L($"{folders.Count} klasör", folders.Count == 1 ? "1 folder" : $"{folders.Count} folders"));
+ if (files > 0) counts.Add(L($"{files} dosya", files == 1 ? "1 file" : $"{files} files"));
+ if (counts.Count > 0) stack.Children.Add(Text(string.Join(" · ", counts), 12.5, brushKey: "TextSecondary"));
+ if (waiting)
+ {
+ var note = new TextBlock
+ {
+ Text = L("Burada klasör boyutları kendiliğinden hesaplanmaz: tüm diski okumak dakikalar sürebilir.",
+ "Folder sizes are not added up here by themselves: reading the whole disk can take minutes."),
+ TextWrapping = TextWrapping.Wrap,
+ FontSize = 12,
+ Margin = new Thickness(0, 14, 0, 10)
+ };
+ note.SetResourceReference(TextBlock.ForegroundProperty, "TextSecondary");
+ stack.Children.Add(note);
+ var start = Widgets.Ui.Pill(L("Boyutları hesapla", "Add up sizes"), (_, _) => AddUpSizesNow());
+ start.HorizontalAlignment = HorizontalAlignment.Left;
+ stack.Children.Add(start);
+ }
+
+ var biggest = items.Where(e => e.SizeOrLength > 0).OrderByDescending(e => e.SizeOrLength).ToList();
+ if (biggest.Count > 0)
+ {
+ var title = Text(L("YERİ NE KAPLIYOR", "WHAT TAKES THE SPACE"), 11, FontWeights.SemiBold, "TextSecondary");
+ title.Margin = new Thickness(0, 24, 0, 10);
+ stack.Children.Add(title);
+ var largest = Math.Max(1, biggest[0].SizeOrLength);
+ foreach (var entry in biggest.Take(7))
+ {
+ var line = new DockPanel();
+ var icon = entry.IsFolder ? FolderPicture(entry, 18, small: true) : FilePicture(entry, 16);
+ icon.Margin = new Thickness(0, 0, 9, 0);
+ DockPanel.SetDock(icon, Dock.Left);
+ line.Children.Add(icon);
+ var amount = Text(FileKinds.Size(entry.SizeOrLength), 12, brushKey: "TextSecondary");
+ amount.Margin = new Thickness(8, 0, 0, 0);
+ DockPanel.SetDock(amount, Dock.Right);
+ line.Children.Add(amount);
+ line.Children.Add(Text(entry.Name, 13, FontWeights.Medium));
+ var color = entry.IsFolder ? FolderColor(entry.Peek is { Count: 0 } ? null : entry.Peek?.Kind ?? FileKind.Other) : FolderColor(entry.Kind);
+ var bar = Bar((double)entry.SizeOrLength / largest, color);
+ bar.Margin = new Thickness(0, 6, 0, 0);
+ var row = new StackPanel { Margin = new Thickness(0, 0, 0, 12), Background = Brushes.Transparent, Cursor = System.Windows.Input.Cursors.Hand, ToolTip = entry.Path };
+ row.Children.Add(line);
+ row.Children.Add(bar);
+ Interactive(row, entry);
+ stack.Children.Add(row);
+ }
+ if (biggest.Count > 7)
+ stack.Children.Add(Text(L($"ve {biggest.Count - 7} tane daha", $"and {biggest.Count - 7} more"), 12, brushKey: "TextSecondary"));
+ }
+ return new ScrollViewer { Content = stack, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Focusable = false };
+ }
+
+ /// <summary>One selected item: a big picture and its facts.</summary>
+ private FrameworkElement ItemDetails(FileEntry entry)
+ {
+ var stack = new StackPanel();
+ FrameworkElement picture = entry.IsFolder ? FolderPicture(entry, 170) : FilePicture(entry, 200);
+ picture.HorizontalAlignment = HorizontalAlignment.Center;
+ picture.Margin = new Thickness(0, 6, 0, 16);
+ stack.Children.Add(picture);
+ var name = new TextBlock { Text = entry.Name, FontSize = 16, FontWeight = FontWeights.SemiBold, TextWrapping = TextWrapping.Wrap, TextAlignment = TextAlignment.Center };
+ name.SetResourceReference(TextBlock.ForegroundProperty, "TextPrimary");
+ stack.Children.Add(name);
+ var kind = Text(entry.IsFolder ? L("Klasör", "Folder") : KindLabel(entry), 12.5, brushKey: "TextSecondary");
+ kind.HorizontalAlignment = HorizontalAlignment.Center;
+ kind.Margin = new Thickness(0, 3, 0, 18);
+ stack.Children.Add(kind);
+ void Fact(string label, string value)
+ {
+ var line = new DockPanel { Margin = new Thickness(0, 0, 0, 9) };
+ var key = Text(label, 12.5, brushKey: "TextSecondary");
+ DockPanel.SetDock(key, Dock.Left);
+ line.Children.Add(key);
+ var text = Text(value, 12.5);
+ text.HorizontalAlignment = HorizontalAlignment.Right;
+ text.Margin = new Thickness(12, 0, 0, 0);
+ line.Children.Add(text);
+ stack.Children.Add(line);
+ }
+ if (entry.IsFolder)
+ {
+ if (Count(entry.Peek) is { } count) Fact(L("İçinde", "Contains"), count);
+ Fact(L("Boyut", "Size"), entry.Size is { } size ? FileKinds.Size(size) : _sizesWanted ? L("hesaplanıyor…", "adding up…") : "—");
+ }
+ else Fact(L("Boyut", "Size"), FileKinds.Size(entry.Length));
+ Fact(L("Değiştirilme", "Modified"), Date(entry.Modified));
+ try
+ {
+ var created = entry.IsFolder ? Directory.GetCreationTime(entry.Path) : File.GetCreationTime(entry.Path);
+ Fact(L("Oluşturulma", "Created"), Date(created));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
+ var where = new TextBlock { Text = Path.GetDirectoryName(entry.Path), FontSize = 11.5, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 6, 0, 16), Opacity = 0.8 };
+ where.SetResourceReference(TextBlock.ForegroundProperty, "TextSecondary");
+ stack.Children.Add(where);
+ var open = Widgets.Ui.Pill(L("Aç", "Open"), (_, _) => Open(entry));
+ open.HorizontalAlignment = HorizontalAlignment.Stretch;
+ stack.Children.Add(open);
+ return new ScrollViewer { Content = stack, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Focusable = false };
+ }
+}
diff --git a/Files/FilesWindow.cs b/Files/FilesWindow.cs
new file mode 100644
index 0000000..1d6a9ad
--- /dev/null
+++ b/Files/FilesWindow.cs
@@ -0,0 +1,764 @@
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.IO;
+using System.IO.Enumeration;
+using System.Runtime.InteropServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Shell;
+using System.Windows.Threading;
+using QiDock.Services;
+using static QiDock.Files.FileKinds;
+
+namespace QiDock.Files;
+
+/// <summary>One file or folder in the open folder.</summary>
+internal sealed class FileEntry
+{
+ public required string Path { get; init; }
+ public required string Name { get; init; }
+ public bool IsFolder { get; init; }
+ public long Length { get; init; }
+ public DateTime Modified { get; init; }
+ public FileKind Kind { get; init; }
+ public bool Hidden { get; init; }
+
+ /// <summary>For a folder: its count and main kind, once looked at.</summary>
+ public FolderPeek? Peek { get; set; }
+
+ /// <summary>For a folder: its full size, once added up.</summary>
+ public long? Size { get; set; }
+
+ public long SizeOrLength => IsFolder ? Size ?? 0 : Length;
+}
+
+/// <summary>
+/// QiDock's own file window: favourites and drives on the left, a path bar, colourful folders with their item counts
+/// (coloured by what they mostly hold) and file thumbnails in a grid or a list, and a panel showing what takes the
+/// space. Everything slow (listing, thumbnails, sizes) happens in the background; only visible rows are drawn.
+/// </summary>
+internal sealed partial class FilesWindow : Window
+{
+ private static FilesWindow? _shared;
+
+ public static void Open(string? path = null)
+ {
+ if (_shared is null)
+ {
+ _shared = new FilesWindow();
+ _shared.Closed += (_, _) => _shared = null;
+ _shared.Show();
+ _shared.Navigate(path ?? FilesState.Load().LastFolder ?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
+ }
+ else
+ {
+ if (_shared.WindowState == WindowState.Minimized) _shared.WindowState = WindowState.Normal;
+ if (path is not null) _shared.Navigate(path);
+ }
+ _shared.Activate();
+ }
+
+ private readonly FilesState _state = FilesState.Load();
+ private readonly Stack<string> _back = new();
+ private readonly Stack<string> _forward = new();
+ private readonly ObservableCollection<object> _rows = [];
+ private readonly HashSet<string> _selected = new(StringComparer.OrdinalIgnoreCase);
+ private readonly HashSet<RowHost> _realized = [];
+ private readonly DispatcherTimer _refreshSoon = new(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(400) };
+ private readonly DispatcherTimer _redrawSoon = new(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(120) };
+ private List<FileEntry> _entries = [];
+ private List<FileEntry> _shown = [];
+ private string _path = "";
+ private string _filter = "";
+ private string? _anchor;
+ private int _columns;
+ private CancellationTokenSource? _load;
+ private FileSystemWatcher? _watcher;
+
+ private readonly Border _frame;
+ private readonly ItemsControl _list;
+ private readonly TextBlock _title;
+ private readonly StackPanel _crumbs;
+ private readonly Border _crumbHost;
+ private readonly TextBlock _status;
+ private readonly TextBox _search;
+ private readonly Button _backButton, _forwardButton, _upButton, _gridButton, _listButton, _detailsButton;
+ private readonly Border _details;
+ private readonly ColumnDefinition _detailsColumn;
+
+ private FilesWindow()
+ {
+ Title = L("Dosyalar", "Files");
+ Width = Math.Min(1220, SystemParameters.WorkArea.Width * 0.9);
+ Height = Math.Min(780, SystemParameters.WorkArea.Height * 0.88);
+ MinWidth = 760;
+ MinHeight = 480;
+ WindowStartupLocation = WindowStartupLocation.CenterScreen;
+ WindowStyle = WindowStyle.None;
+ ResizeMode = ResizeMode.CanResize;
+ Background = Brushes.Transparent;
+ UseLayoutRounding = true;
+ SnapsToDevicePixels = true;
+ FontFamily = (FontFamily)FindResource("InterfaceFont");
+ FontSize = 13;
+ SetResourceReference(ForegroundProperty, "TextPrimary");
+ Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("/QiDock;component/Design/SettingsControls.xaml", UriKind.Relative) });
+ WindowChrome.SetWindowChrome(this, new WindowChrome
+ {
+ CaptionHeight = 52,
+ ResizeBorderThickness = new Thickness(6),
+ GlassFrameThickness = new Thickness(-1),
+ UseAeroCaptionButtons = false
+ });
+
+ // ---- Right side: toolbar, path bar, content + details, status line ----------------------
+ _backButton = ToolButton(GlyphChevron(left: true), L("Geri (Alt+←)", "Back (Alt+←)"), GoBack);
+ _forwardButton = ToolButton(GlyphChevron(left: false), L("İleri (Alt+→)", "Forward (Alt+→)"), GoForward);
+ _upButton = ToolButton(GlyphUp, L("Üst klasör (Alt+↑)", "Up (Alt+↑)"), GoUp);
+ _title = Text("", 15, FontWeights.SemiBold);
+ _title.Margin = new Thickness(10, 0, 0, 0);
+ var navigation = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(12, 0, 0, 0) };
+ navigation.Children.Add(Chrome(_backButton));
+ navigation.Children.Add(Chrome(_forwardButton));
+ navigation.Children.Add(Chrome(_upButton));
+ navigation.Children.Add(_title);
+
+ _gridButton = ToolButton(GlyphGrid, L("Izgara", "Grid"), () => SetView(grid: true));
+ _listButton = ToolButton(GlyphList, L("Liste", "List"), () => SetView(grid: false));
+ var sort = ToolButton(GlyphSort, L("Sırala", "Sort"), () => { });
+ sort.Click += (_, _) => ShowSortMenu(sort);
+ _detailsButton = ToolButton(GlyphPanel, L("Ayrıntı paneli", "Details panel"), ToggleDetails);
+ var views = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };
+ foreach (var button in new[] { _gridButton, _listButton, sort, _detailsButton }) views.Children.Add(Chrome(button));
+ var captions = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(8, 5, 6, 5) };
+ captions.Children.Add(Chrome(Caption("", L("Simge durumuna küçült", "Minimize"), "CaptionButton", () => WindowState = WindowState.Minimized)));
+ captions.Children.Add(Chrome(Caption(null, null, "MaximizeCaptionButton", () => WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized)));
+ captions.Children.Add(Chrome(Caption("", L("Kapat", "Close"), "CloseCaptionButton", Close)));
+ var toolbar = new DockPanel { Height = 52 };
+ DockPanel.SetDock(captions, Dock.Right);
+ DockPanel.SetDock(views, Dock.Right);
+ toolbar.Children.Add(captions);
+ toolbar.Children.Add(views);
+ toolbar.Children.Add(navigation);
+
+ _crumbs = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };
+ _crumbHost = new Border { Height = 34, Padding = new Thickness(14, 0, 14, 0), Background = Brushes.Transparent, Child = _crumbs, Cursor = Cursors.IBeam };
+ _crumbHost.MouseLeftButtonDown += (_, e) =>
+ {
+ if (e.OriginalSource == _crumbHost || e.OriginalSource == _crumbs) EditPath();
+ };
+ var crumbLine = new Border { BorderThickness = new Thickness(0, 0, 0, 1), Child = _crumbHost };
+ crumbLine.SetResourceReference(Border.BorderBrushProperty, "MenuDivider");
+
+ _list = CreateList();
+ _details = new Border { BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(20, 18, 20, 18) };
+ _details.SetResourceReference(Border.BorderBrushProperty, "MenuDivider");
+ var body = new Grid();
+ body.ColumnDefinitions.Add(new ColumnDefinition());
+ _detailsColumn = new ColumnDefinition { Width = new GridLength(300) };
+ body.ColumnDefinitions.Add(_detailsColumn);
+ body.Children.Add(_list);
+ Grid.SetColumn(_details, 1);
+ body.Children.Add(_details);
+
+ _status = Text("", 11.5, brushKey: "TextSecondary");
+ var statusLine = new Border { Height = 30, Padding = new Thickness(16, 0, 16, 0), BorderThickness = new Thickness(0, 1, 0, 0), Child = _status };
+ statusLine.SetResourceReference(Border.BorderBrushProperty, "MenuDivider");
+
+ var main = new Grid();
+ main.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
+ main.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
+ main.RowDefinitions.Add(new RowDefinition());
+ main.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
+ main.Children.Add(toolbar);
+ Grid.SetRow(crumbLine, 1);
+ main.Children.Add(crumbLine);
+ Grid.SetRow(body, 2);
+ main.Children.Add(body);
+ Grid.SetRow(statusLine, 3);
+ main.Children.Add(statusLine);
+
+ // ---- Left side: search, favourites, places --------------------------------------------
+ _search = new TextBox
+ {
+ Background = Brushes.Transparent,
+ BorderThickness = new Thickness(0),
+ VerticalContentAlignment = VerticalAlignment.Center,
+ FontSize = 13
+ };
+ _search.SetResourceReference(ForegroundProperty, "TextPrimary");
+ _search.SetResourceReference(TextBoxBase.CaretBrushProperty, "TextPrimary");
+ _search.TextChanged += (_, _) =>
+ {
+ _filter = _search.Text.Trim();
+ Rebuild();
+ };
+ var sidebar = BuildSidebar(_search);
+
+ var root = new Grid();
+ root.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(232) });
+ root.ColumnDefinitions.Add(new ColumnDefinition());
+ root.Children.Add(sidebar);
+ Grid.SetColumn(main, 1);
+ root.Children.Add(main);
+
+ _frame = new Border { BorderThickness = new Thickness(1), Child = root };
+ _frame.SetResourceReference(Border.BorderBrushProperty, "MenuStroke");
+ _frame.SetResourceReference(Border.BackgroundProperty, "SettingsBackground");
+ Content = _frame;
+
+ SourceInitialized += (_, _) =>
+ {
+ var glass = SettingsBackdrop.TryEnable(this, ThemeManager.CurrentTheme);
+ _frame.SetResourceReference(Border.BackgroundProperty, glass ? "SettingsGlassMaterial" : "SettingsBackground");
+ if (!glass) WindowChrome.GetWindowChrome(this).GlassFrameThickness = new Thickness(0);
+ };
+ PreviewKeyDown += OnKey;
+ PreviewMouseDown += (_, e) =>
+ {
+ if (e.ChangedButton == MouseButton.XButton1) GoBack();
+ else if (e.ChangedButton == MouseButton.XButton2) GoForward();
+ };
+ Closed += (_, _) =>
+ {
+ _load?.Cancel();
+ _watcher?.Dispose();
+ _state.LastFolder = _path;
+ _state.Save();
+ // Nothing of the window stays behind: pictures and the visual tree go, and the memory is handed back.
+ ShellThumbnails.Clear();
+ _list.ItemsSource = null;
+ Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, () =>
+ {
+ // Thumbnail pixels live in the large-object heap, which .NET never shrinks unless asked.
+ System.Runtime.GCSettings.LargeObjectHeapCompactionMode = System.Runtime.GCLargeObjectHeapCompactionMode.CompactOnce;
+ GC.Collect();
+ GC.WaitForPendingFinalizers();
+ using var self = Process.GetCurrentProcess();
+ SetProcessWorkingSetSize(self.Handle, -1, -1);
+ });
+ };
+ _refreshSoon.Tick += (_, _) =>
+ {
+ _refreshSoon.Stop();
+ // Not under someone typing a new name; it refreshes once they are done.
+ if (_renaming is not null)
+ {
+ _refreshSoon.Start();
+ return;
+ }
+ Load(keepScroll: true);
+ };
+ _redrawSoon.Tick += (_, _) =>
+ {
+ _redrawSoon.Stop();
+ RedrawVisible();
+ UpdateDetails();
+ };
+ AcceptDrops();
+ ApplyViewButtons();
+ ApplyDetailsVisibility();
+ }
+
+ // ---- Navigation -----------------------------------------------------------------------------
+
+ public void Navigate(string path, bool remember = true)
+ {
+ path = Path.TrimEndingDirectorySeparator(Environment.ExpandEnvironmentVariables(path.Trim().Trim('"')));
+ if (path.Length == 2 && path[1] == ':') path += "\\";
+ if (!Directory.Exists(path))
+ {
+ if (File.Exists(path))
+ {
+ OpenItem(path);
+ return;
+ }
+ ShowStatusMessage(L("Klasör bulunamadı: ", "Folder not found: ") + path);
+ return;
+ }
+ if (remember && _path.Length > 0 && !string.Equals(_path, path, StringComparison.OrdinalIgnoreCase))
+ {
+ _back.Push(_path);
+ _forward.Clear();
+ }
+ var cameFrom = _path;
+ _path = path;
+ _sizesWanted = SizesByThemselves(path);
+ _selected.Clear();
+ _anchor = null;
+ if (_search.Text.Length > 0) _search.Text = "";
+ _title.Text = DisplayName(path);
+ Title = _title.Text + " – " + L("Dosyalar", "Files");
+ BuildCrumbs();
+ HighlightSidebar();
+ Watch(path);
+ Load(keepScroll: false, select: cameFrom.Length > 0 && string.Equals(Path.GetDirectoryName(cameFrom), path, StringComparison.OrdinalIgnoreCase) ? cameFrom : null);
+ _backButton.IsEnabled = _back.Count > 0;
+ _forwardButton.IsEnabled = _forward.Count > 0;
+ _upButton.IsEnabled = Path.GetDirectoryName(path) is not null;
+ }
+
+ private void GoBack()
+ {
+ if (_back.Count == 0) return;
+ _forward.Push(_path);
+ Navigate(_back.Pop(), remember: false);
+ _forwardButton.IsEnabled = _forward.Count > 0;
+ }
+
+ private void GoForward()
+ {
+ if (_forward.Count == 0) return;
+ _back.Push(_path);
+ Navigate(_forward.Pop(), remember: false);
+ }
+
+ private void GoUp()
+ {
+ if (Path.GetDirectoryName(_path) is { } parent) Navigate(parent);
+ }
+
+ private static string DisplayName(string path)
+ {
+ if (Path.GetPathRoot(path) is { } root && string.Equals(root, path, StringComparison.OrdinalIgnoreCase))
+ {
+ try
+ {
+ var drive = new DriveInfo(root);
+ var label = drive.IsReady && drive.VolumeLabel.Length > 0 ? drive.VolumeLabel : L("Yerel Disk", "Local Disk");
+ return $"{label} ({root.TrimEnd('\\')})";
+ }
+ catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException)
+ {
+ return root;
+ }
+ }
+ return SpecialNames.TryGetValue(Path.TrimEndingDirectorySeparator(path), out var special) ? special : Path.GetFileName(path);
+ }
+
+ /// <summary>Windows' own folders by the names Windows shows for them ("Belgeler", not "Documents").</summary>
+ private static readonly Dictionary<string, string> SpecialNames = BuildSpecialNames();
+
+ private static Dictionary<string, string> BuildSpecialNames()
+ {
+ var names = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ void Add(string? path, string turkish, string english)
+ {
+ if (!string.IsNullOrEmpty(path)) names[Path.TrimEndingDirectorySeparator(path)] = L(turkish, english);
+ }
+ Add(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Masaüstü", "Desktop");
+ Add(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Belgeler", "Documents");
+ Add(KnownFolders.Downloads, "İndirilenler", "Downloads");
+ Add(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Resimler", "Pictures");
+ Add(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), "Müzik", "Music");
+ Add(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos), "Videolar", "Videos");
+ var users = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
+ Add(users, "Kullanıcılar", "Users");
+ return names;
+ }
+
+ private void OpenItem(string path)
+ {
+ try
+ {
+ Process.Start(new ProcessStartInfo(path) { UseShellExecute = true, WorkingDirectory = Path.GetDirectoryName(path) ?? "" })?.Dispose();
+ }
+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)
+ {
+ ShowStatusMessage(L("Açılamadı: ", "Could not open: ") + Path.GetFileName(path));
+ }
+ }
+
+ private void Open(FileEntry entry)
+ {
+ if (entry.IsFolder) Navigate(entry.Path);
+ else OpenItem(entry.Path);
+ }
+
+ // ---- Loading --------------------------------------------------------------------------------
+
+ private void Load(bool keepScroll, string? select = null)
+ {
+ _load?.Cancel();
+ ShellThumbnails.CancelPending();
+ var load = _load = new CancellationTokenSource();
+ var token = load.Token;
+ var path = _path;
+ var showHidden = _state.ShowHidden;
+ _ = Task.Run(() => Read(path, showHidden, token), token).ContinueWith(task =>
+ {
+ if (token.IsCancellationRequested || task.IsCanceled) return;
+ if (task.IsFaulted)
+ {
+ _entries = [];
+ Rebuild();
+ ShowStatusMessage(L("Bu klasör okunamadı.", "This folder could not be read."));
+ return;
+ }
+ // Keep what was already found out about folders that are still there.
+ var known = _entries.Where(e => e.IsFolder).ToDictionary(e => e.Path, StringComparer.OrdinalIgnoreCase);
+ foreach (var entry in task.Result.Where(e => e.IsFolder))
+ {
+ if (!known.TryGetValue(entry.Path, out var old)) continue;
+ entry.Peek = old.Peek;
+ entry.Size = old.Size;
+ }
+ _entries = task.Result;
+ _selected.IntersectWith(_entries.Select(e => e.Path));
+ if (select is not null && _entries.Any(e => string.Equals(e.Path, select, StringComparison.OrdinalIgnoreCase))) _selected.Add(select);
+ var offset = keepScroll ? Scroller?.VerticalOffset ?? 0 : 0;
+ Rebuild();
+ if (keepScroll) Scroller?.ScrollToVerticalOffset(offset);
+ else Scroller?.ScrollToTop();
+ if (select is not null) Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => BringIntoView(select));
+ var entries = task.Result;
+ _ = Task.Run(() => LookInside(entries, token), token);
+ }, TaskScheduler.FromCurrentSynchronizationContext());
+ }
+
+ private static List<FileEntry> Read(string path, bool showHidden, CancellationToken token)
+ {
+ var options = new EnumerationOptions
+ {
+ IgnoreInaccessible = true,
+ AttributesToSkip = showHidden ? 0 : FileAttributes.Hidden | FileAttributes.System
+ };
+ var entries = new FileSystemEnumerable<FileEntry>(path, (ref FileSystemEntry entry) =>
+ {
+ var full = entry.ToFullPath();
+ var name = entry.FileName.ToString();
+ return new FileEntry
+ {
+ Path = full,
+ Name = name,
+ IsFolder = entry.IsDirectory,
+ Length = entry.IsDirectory ? 0 : entry.Length,
+ Modified = entry.LastWriteTimeUtc.LocalDateTime,
+ Kind = entry.IsDirectory ? FileKind.Other : FileKinds.Of(name),
+ Hidden = (entry.Attributes & FileAttributes.Hidden) != 0
+ };
+ }, options);
+ var list = new List<FileEntry>();
+ foreach (var entry in entries)
+ {
+ list.Add(entry);
+ if ((list.Count & 255) == 0) token.ThrowIfCancellationRequested();
+ }
+ return list;
+ }
+
+ /// <summary>Counts what is inside each folder, then (for the panel) adds up every folder's size.</summary>
+ private void LookInside(List<FileEntry> entries, CancellationToken token)
+ {
+ var folders = entries.Where(e => e.IsFolder).ToList();
+ var showHidden = _state.ShowHidden;
+ foreach (var folder in folders)
+ {
+ if (token.IsCancellationRequested) return;
+ if (folder.Peek is not null) continue;
+ folder.Peek = FolderScanner.Peek(folder.Path, showHidden);
+ Dispatcher.BeginInvoke(DispatcherPriority.Background, () => { if (!token.IsCancellationRequested) _redrawSoon.Start(); });
+ }
+ if (_sizesWanted) AddUpSizes(folders, token);
+ }
+
+ /// <summary>
+ /// Whether sizes are added up without asking: not for a whole drive or Windows' own folders, where reading every
+ /// file keeps the disk busy for minutes (the panel offers a button there instead).
+ /// </summary>
+ private static bool SizesByThemselves(string path)
+ {
+ if (string.Equals(Path.GetPathRoot(path), Path.TrimEndingDirectorySeparator(path) + "\\", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(Path.GetPathRoot(path), path, StringComparison.OrdinalIgnoreCase)) return false;
+ // These and everything inside them.
+ var heavy = new[]
+ {
+ Environment.GetFolderPath(Environment.SpecialFolder.Windows),
+ Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
+ Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
+ Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
+ Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)) ?? "" // AppData
+ };
+ // Only these themselves: the user folder holds AppData, the users folder holds every user's.
+ var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
+ var exact = new[] { home, Path.GetDirectoryName(home) ?? "" };
+ return !exact.Any(e => string.Equals(path, e, StringComparison.OrdinalIgnoreCase))
+ && !heavy.Any(h => h.Length > 0 && (string.Equals(path, h, StringComparison.OrdinalIgnoreCase)
+ || path.StartsWith(h + "\\", StringComparison.OrdinalIgnoreCase)));
+ }
+
+ private bool _sizesWanted;
+
+ /// <summary>The panel's "add up sizes" button for heavy places.</summary>
+ private void AddUpSizesNow()
+ {
+ if (_sizesWanted || _load is null) return;
+ _sizesWanted = true;
+ var token = _load.Token;
+ var folders = _entries.Where(e => e.IsFolder).ToList();
+ _ = Task.Run(() => AddUpSizes(folders, token), token);
+ UpdateDetails();
+ }
+
+ private void AddUpSizes(List<FileEntry> folders, CancellationToken token)
+ {
+ foreach (var folder in folders.Where(f => f.Size is null).OrderBy(f => f.Peek?.Count ?? 0))
+ {
+ if (token.IsCancellationRequested) return;
+ try { folder.Size = FolderScanner.Size(folder.Path, token); }
+ catch (OperationCanceledException) { return; }
+ Dispatcher.BeginInvoke(DispatcherPriority.Background, () => { if (!token.IsCancellationRequested) _redrawSoon.Start(); });
+ }
+ }
+
+ private void Watch(string path)
+ {
+ _watcher?.Dispose();
+ _watcher = null;
+ try
+ {
+ var watcher = new FileSystemWatcher(path)
+ {
+ NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size | NotifyFilters.LastWrite,
+ IncludeSubdirectories = false
+ };
+ void Changed(object? sender, FileSystemEventArgs e) => Dispatcher.BeginInvoke(() =>
+ {
+ FolderScanner.Forget(path);
+ _refreshSoon.Stop();
+ _refreshSoon.Start();
+ });
+ watcher.Created += Changed;
+ watcher.Deleted += Changed;
+ watcher.Renamed += (s, e) => Changed(s, e);
+ watcher.Changed += Changed;
+ watcher.EnableRaisingEvents = true;
+ _watcher = watcher;
+ }
+ catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException or PlatformNotSupportedException) { }
+ }
+
+ // ---- Keyboard -------------------------------------------------------------------------------
+
+ private void OnKey(object sender, KeyEventArgs e)
+ {
+ var key = e.Key == Key.System ? e.SystemKey : e.Key;
+ var alt = (Keyboard.Modifiers & ModifierKeys.Alt) != 0;
+ var control = (Keyboard.Modifiers & ModifierKeys.Control) != 0;
+ var typing = Keyboard.FocusedElement is TextBox;
+ if (!typing && !alt && OnOperationKey(key))
+ {
+ e.Handled = true;
+ return;
+ }
+ switch (key)
+ {
+ case Key.Left when alt: GoBack(); break;
+ case Key.Right when alt: GoForward(); break;
+ case Key.Up when alt: GoUp(); break;
+ case Key.Back when !typing: GoBack(); break;
+ case Key.F5: FolderScanner.Forget(_path); Load(keepScroll: true); break;
+ case Key.F when control: _search.Focus(); _search.SelectAll(); break;
+ case Key.L when control: EditPath(); break;
+ case Key.A when control && !typing:
+ _selected.UnionWith(_shown.Select(s => s.Path));
+ SelectionChanged();
+ break;
+ case Key.Escape when typing && Keyboard.FocusedElement == _search:
+ _search.Text = "";
+ _list.Focus();
+ break;
+ case Key.Escape when !typing && _selected.Count > 0:
+ _selected.Clear();
+ SelectionChanged();
+ break;
+ case Key.Enter when !typing:
+ var selected = _shown.Where(s => _selected.Contains(s.Path)).ToList();
+ if (selected.Count == 1) Open(selected[0]);
+ else foreach (var file in selected.Where(s => !s.IsFolder)) OpenItem(file.Path);
+ break;
+ case Key.Left or Key.Right or Key.Up or Key.Down or Key.Home or Key.End when !typing && !alt:
+ MoveSelection(key, (Keyboard.Modifiers & ModifierKeys.Shift) != 0);
+ break;
+ default: return;
+ }
+ e.Handled = true;
+ }
+
+ private void ShowStatusMessage(string text) => _status.Text = text;
+
+ // ---- Small pieces ---------------------------------------------------------------------------
+
+ [DllImport("kernel32.dll")] private static extern bool SetProcessWorkingSetSize(nint process, nint minimum, nint maximum);
+
+ private static readonly Geometry GlyphUp = Geometry.Parse("M12 19V5 M5 12l7-7 7 7");
+
+ private static Geometry GlyphChevron(bool left) => Geometry.Parse(left ? "M15 18l-6-6 6-6" : "M9 18l6-6-6-6");
+
+ internal static TextBlock Text(string text, double size, FontWeight? weight = null, string brushKey = "TextPrimary")
+ {
+ var block = new TextBlock
+ {
+ Text = text,
+ FontSize = size,
+ FontWeight = weight ?? FontWeights.Normal,
+ TextTrimming = TextTrimming.CharacterEllipsis,
+ VerticalAlignment = VerticalAlignment.Center
+ };
+ block.SetResourceReference(TextBlock.ForegroundProperty, brushKey);
+ return block;
+ }
+
+ private static T Chrome<T>(T element) where T : UIElement
+ {
+ WindowChrome.SetIsHitTestVisibleInChrome(element, true);
+ return element;
+ }
+
+ private Button ToolButton(Geometry glyph, string tip, Action click)
+ {
+ var icon = new System.Windows.Shapes.Path
+ {
+ Data = glyph,
+ Width = 16,
+ Height = 16,
+ Stretch = Stretch.Uniform,
+ StrokeThickness = 1.9,
+ StrokeStartLineCap = PenLineCap.Round,
+ StrokeEndLineCap = PenLineCap.Round,
+ StrokeLineJoin = PenLineJoin.Round
+ };
+ icon.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, "TextPrimary");
+ var button = new Button { Content = icon, Width = 34, Height = 32, ToolTip = tip, Margin = new Thickness(1, 0, 1, 0) };
+ button.SetResourceReference(StyleProperty, "WidgetIconButton");
+ System.Windows.Automation.AutomationProperties.SetName(button, tip);
+ button.Click += (_, _) => click();
+ return button;
+ }
+
+ private static Button Caption(string? glyph, string? tip, string style, Action click)
+ {
+ var button = new Button { Height = 32 };
+ if (glyph is not null) button.Content = glyph;
+ if (tip is not null)
+ {
+ button.ToolTip = tip;
+ System.Windows.Automation.AutomationProperties.SetName(button, tip);
+ }
+ button.SetResourceReference(StyleProperty, style);
+ button.Click += (_, _) => click();
+ return button;
+ }
+
+ private void SetView(bool grid)
+ {
+ if (_state.Grid == grid) return;
+ _state.Grid = grid;
+ _state.Save();
+ ApplyViewButtons();
+ Rebuild();
+ }
+
+ private void ApplyViewButtons()
+ {
+ var (on, off) = _state.Grid ? (_gridButton, _listButton) : (_listButton, _gridButton);
+ on.SetResourceReference(BackgroundProperty, "SurfaceHover");
+ off.Background = Brushes.Transparent;
+ }
+
+ private void ToggleDetails()
+ {
+ _state.Details = !_state.Details;
+ _state.Save();
+ ApplyDetailsVisibility();
+ }
+
+ private void ApplyDetailsVisibility()
+ {
+ _details.Visibility = _state.Details ? Visibility.Visible : Visibility.Collapsed;
+ _detailsColumn.Width = _state.Details ? new GridLength(300) : new GridLength(0);
+ if (_state.Details) _detailsButton.SetResourceReference(BackgroundProperty, "SurfaceHover");
+ else _detailsButton.Background = Brushes.Transparent;
+ UpdateDetails();
+ }
+
+ private void ShowSortMenu(FrameworkElement anchor)
+ {
+ var menu = new ContextMenu { PlacementTarget = anchor, Placement = PlacementMode.Bottom };
+ void Choice(string label, FileSort sort)
+ {
+ var item = new MenuItem { Header = label, IsCheckable = true, IsChecked = _state.Sort == sort };
+ item.Click += (_, _) =>
+ {
+ _state.Descending = _state.Sort == sort ? !_state.Descending : sort is FileSort.Date or FileSort.Size;
+ _state.Sort = sort;
+ _state.Save();
+ Rebuild();
+ };
+ menu.Items.Add(item);
+ }
+ Choice(L("Ada göre", "Name"), FileSort.Name);
+ Choice(L("Türe göre", "Kind"), FileSort.Kind);
+ Choice(L("Tarihe göre", "Date"), FileSort.Date);
+ Choice(L("Boyuta göre", "Size"), FileSort.Size);
+ menu.Items.Add(new Separator());
+ var descending = new MenuItem { Header = L("Ters sırada", "Descending"), IsCheckable = true, IsChecked = _state.Descending };
+ descending.Click += (_, _) =>
+ {
+ _state.Descending = !_state.Descending;
+ _state.Save();
+ Rebuild();
+ };
+ menu.Items.Add(descending);
+ var hidden = new MenuItem { Header = L("Gizli öğeleri göster", "Show hidden items"), IsCheckable = true, IsChecked = _state.ShowHidden };
+ hidden.Click += (_, _) =>
+ {
+ _state.ShowHidden = !_state.ShowHidden;
+ _state.Save();
+ foreach (var entry in _entries) entry.Peek = null;
+ Load(keepScroll: true);
+ };
+ menu.Items.Add(hidden);
+ menu.IsOpen = true;
+ }
+}
+
+internal enum FileSort { Name, Kind, Date, Size }
+
+/// <summary>The file window's own choices, kept between runs (view, sort, panel, last folder).</summary>
+internal sealed class FilesState
+{
+ public bool Grid { get; set; } = true;
+ public bool Details { get; set; } = true;
+ public bool ShowHidden { get; set; }
+ public FileSort Sort { get; set; } = FileSort.Name;
+ public bool Descending { get; set; }
+ public string? LastFolder { get; set; }
+
+ private static string StorePath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock", "files.json");
+
+ public static FilesState Load()
+ {
+ try
+ {
+ return File.Exists(StorePath) ? System.Text.Json.JsonSerializer.Deserialize<FilesState>(File.ReadAllText(StorePath)) ?? new() : new();
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Text.Json.JsonException)
+ {
+ return new();
+ }
+ }
+
+ public void Save()
+ {
+ try
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(StorePath)!);
+ File.WriteAllText(StorePath, System.Text.Json.JsonSerializer.Serialize(this));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
+ }
+}
diff --git a/Files/FolderScanner.cs b/Files/FolderScanner.cs
new file mode 100644
index 0000000..f84013e
--- /dev/null
+++ b/Files/FolderScanner.cs
@@ -0,0 +1,101 @@
+using System.Collections.Concurrent;
+using System.IO;
+using System.IO.Enumeration;
+
+namespace QiDock.Files;
+
+/// <summary>How many items a folder holds and what most of its files are.</summary>
+internal sealed record FolderPeek(int Count, bool More, FileKind? Kind);
+
+/// <summary>
+/// Reads folders without slowing the window: a quick look inside each folder (count and main kind) and, for the
+/// "what takes the space" panel, the full size of every folder. Sizes are remembered for the session.
+/// </summary>
+internal static class FolderScanner
+{
+ private const int PeekLimit = 999;
+ private static readonly ConcurrentDictionary<string, (long Size, DateTime At)> Sizes = new(StringComparer.OrdinalIgnoreCase);
+
+ public static readonly EnumerationOptions Visible = new()
+ {
+ IgnoreInaccessible = true,
+ AttributesToSkip = FileAttributes.Hidden | FileAttributes.System,
+ RecurseSubdirectories = false
+ };
+
+ public static FolderPeek Peek(string folder, bool showHidden)
+ {
+ try
+ {
+ var options = showHidden ? new EnumerationOptions { IgnoreInaccessible = true, AttributesToSkip = 0 } : Visible;
+ var count = 0;
+ var kinds = new int[8];
+ var files = 0;
+ var entries = new FileSystemEnumerable<(bool Folder, string Name)>(folder,
+ (ref FileSystemEntry entry) => (entry.IsDirectory, entry.FileName.ToString()), options);
+ foreach (var (isFolder, name) in entries)
+ {
+ if (++count > PeekLimit) return new FolderPeek(PeekLimit, true, Dominant(kinds, files));
+ if (isFolder) continue;
+ files++;
+ kinds[(int)FileKinds.Of(name)]++;
+ }
+ return new FolderPeek(count, false, count == 0 ? null : Dominant(kinds, files));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException)
+ {
+ return new FolderPeek(0, false, null);
+ }
+ }
+
+ /// <summary>The kind most files share; "other" when nothing stands out (or only folders inside).</summary>
+ private static FileKind Dominant(int[] kinds, int files)
+ {
+ if (files == 0) return FileKind.Other;
+ var best = 0;
+ for (var i = 1; i < kinds.Length; i++)
+ if (kinds[i] > kinds[best]) best = i;
+ return best != (int)FileKind.Other && kinds[best] * 10 >= files * 4 ? (FileKind)best : FileKind.Other;
+ }
+
+ /// <summary>A size worked out earlier in this session (and not older than ten minutes).</summary>
+ public static long? KnownSize(string folder) =>
+ Sizes.TryGetValue(folder, out var known) && DateTime.Now - known.At < TimeSpan.FromMinutes(10) ? known.Size : null;
+
+ public static long Size(string folder, CancellationToken token)
+ {
+ if (KnownSize(folder) is { } known) return known;
+ long total = 0;
+ try
+ {
+ var options = new EnumerationOptions
+ {
+ IgnoreInaccessible = true,
+ RecurseSubdirectories = true,
+ AttributesToSkip = FileAttributes.ReparsePoint // links and cloud placeholders that point elsewhere
+ };
+ var lengths = new FileSystemEnumerable<long>(folder, (ref FileSystemEntry entry) => entry.Length, options)
+ {
+ ShouldIncludePredicate = (ref FileSystemEntry entry) => !entry.IsDirectory
+ };
+ var step = 0;
+ foreach (var length in lengths)
+ {
+ total += length;
+ if ((++step & 1023) == 0) token.ThrowIfCancellationRequested();
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException) { }
+ token.ThrowIfCancellationRequested();
+ Sizes[folder] = (total, DateTime.Now);
+ return total;
+ }
+
+ /// <summary>Forgets sizes inside a folder that just changed.</summary>
+ public static void Forget(string folder)
+ {
+ foreach (var key in Sizes.Keys)
+ if (key.StartsWith(folder, StringComparison.OrdinalIgnoreCase) || folder.StartsWith(key, StringComparison.OrdinalIgnoreCase))
+ Sizes.TryRemove(key, out _);
+ }
+}
diff --git a/Files/ShellThumbnails.cs b/Files/ShellThumbnails.cs
new file mode 100644
index 0000000..23a769e
--- /dev/null
+++ b/Files/ShellThumbnails.cs
@@ -0,0 +1,205 @@
+using System.Collections.Concurrent;
+using System.Runtime.InteropServices;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Threading;
+
+namespace QiDock.Files;
+
+/// <summary>
+/// Thumbnails (photos, videos, PDFs…) and sharp icons for files, the way Explorer draws them, read by two background
+/// threads so a big folder never stalls the window. The newest requests are served first (what is on screen now).
+/// </summary>
+internal static class ShellThumbnails
+{
+ private sealed record Request(string Path, int Size, Action<BitmapSource?> Done, Dispatcher Dispatcher);
+
+ private static readonly ConcurrentStack<Request> Queue = new();
+ private static readonly SemaphoreSlim Signal = new(0);
+ private static readonly Dictionary<string, BitmapSource?> Cache = new(StringComparer.OrdinalIgnoreCase);
+ private static readonly LinkedList<string> Order = new();
+ // Kept small on purpose: about 24 MB of pictures at most (a 160-pixel thumbnail is ~100 KB), dropped when the
+ // window closes.
+ private const long CacheBytes = 24L * 1024 * 1024;
+ private static long _bytes;
+ private static bool _started;
+
+ private static long BytesOf(BitmapSource? image) => image is null ? 0 : (long)image.PixelWidth * image.PixelHeight * 4;
+
+ /// <summary>Lets every picture go (the window closed).</summary>
+ public static void Clear()
+ {
+ Queue.Clear();
+ lock (Cache)
+ {
+ Cache.Clear();
+ Order.Clear();
+ _bytes = 0;
+ }
+ }
+
+ public static BitmapSource? Cached(string path, int size)
+ {
+ lock (Cache) return Cache.TryGetValue(Key(path, size), out var image) ? image : null;
+ }
+
+ public static void Load(string path, int size, Action<BitmapSource?> done)
+ {
+ lock (Cache)
+ {
+ if (Cache.TryGetValue(Key(path, size), out var cached))
+ {
+ done(cached);
+ return;
+ }
+ if (!_started)
+ {
+ _started = true;
+ for (var i = 0; i < 2; i++)
+ {
+ var thread = new Thread(Work) { IsBackground = true, Name = "QiDock thumbnails", Priority = ThreadPriority.BelowNormal };
+ thread.SetApartmentState(ApartmentState.STA);
+ thread.Start();
+ }
+ }
+ }
+ Queue.Push(new Request(path, size, done, Dispatcher.CurrentDispatcher));
+ Signal.Release();
+ }
+
+ /// <summary>Drops what has not been read yet (the folder changed).</summary>
+ public static void CancelPending() => Queue.Clear();
+
+ private static string Key(string path, int size) => size + "|" + path;
+
+ private static void Work()
+ {
+ while (true)
+ {
+ Signal.Wait();
+ if (!Queue.TryPop(out var request)) continue;
+ var key = Key(request.Path, request.Size);
+ BitmapSource? image;
+ lock (Cache) Cache.TryGetValue(key, out image);
+ image ??= Read(request.Path, request.Size);
+ lock (Cache)
+ {
+ if (!Cache.ContainsKey(key))
+ {
+ Cache[key] = image;
+ Order.AddLast(key);
+ _bytes += BytesOf(image);
+ while (_bytes > CacheBytes && Order.Count > 1)
+ {
+ var oldest = Order.First!.Value;
+ _bytes -= BytesOf(Cache.GetValueOrDefault(oldest));
+ Cache.Remove(oldest);
+ Order.RemoveFirst();
+ }
+ }
+ }
+ request.Dispatcher.BeginInvoke(DispatcherPriority.Background, () => request.Done(image));
+ }
+ }
+
+ private static BitmapSource? Read(string path, int size)
+ {
+ var bitmap = nint.Zero;
+ try
+ {
+ var id = typeof(IShellItemImageFactory).GUID;
+ if (SHCreateItemFromParsingName(path, 0, ref id, out var factory) != 0 || factory is null) return null;
+ try
+ {
+ if (factory.GetImage(new NativeSize { Width = size, Height = size }, 0 /* SIIGBF_RESIZETOFIT */, out bitmap) != 0 || bitmap == 0)
+ return null;
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(factory);
+ }
+ return ToBitmapSource(bitmap);
+ }
+ catch (Exception ex) when (ex is COMException or InvalidCastException or ArgumentException or OutOfMemoryException)
+ {
+ return null;
+ }
+ finally
+ {
+ if (bitmap != 0) DeleteObject(bitmap);
+ }
+ }
+
+ /// <summary>Copies the bitmap's pixels top-down with their transparency (WPF's own conversion drops it).</summary>
+ private static BitmapSource? ToBitmapSource(nint bitmap)
+ {
+ if (GetObject(bitmap, Marshal.SizeOf<NativeBitmap>(), out var info) == 0 || info.Width <= 0 || info.Height <= 0) return null;
+ var width = info.Width;
+ var height = info.Height;
+ var header = new BitmapInfoHeader
+ {
+ Size = Marshal.SizeOf<BitmapInfoHeader>(),
+ Width = width,
+ Height = -height, // top-down rows
+ Planes = 1,
+ BitCount = 32
+ };
+ var pixels = new byte[width * height * 4];
+ var screen = GetDC(0);
+ try
+ {
+ if (GetDIBits(screen, bitmap, 0, (uint)height, pixels, ref header, 0) == 0) return null;
+ }
+ finally
+ {
+ ReleaseDC(0, screen);
+ }
+ // A bitmap without transparency (most photo thumbnails) comes back with every alpha at zero.
+ var anyAlpha = false;
+ for (var i = 3; i < pixels.Length; i += 4)
+ {
+ if (pixels[i] == 0) continue;
+ anyAlpha = true;
+ break;
+ }
+ if (!anyAlpha)
+ for (var i = 3; i < pixels.Length; i += 4) pixels[i] = 255;
+ var source = BitmapSource.Create(width, height, 96, 96, PixelFormats.Pbgra32, null, pixels, width * 4);
+ source.Freeze();
+ return source;
+ }
+
+ [ComImport, Guid("bcc18b79-ba16-442f-80c4-8a59c30c463b"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IShellItemImageFactory
+ {
+ [PreserveSig] int GetImage(NativeSize size, int flags, out nint bitmap);
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct NativeSize { public int Width, Height; }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct NativeBitmap
+ {
+ public int Type, Width, Height, WidthBytes;
+ public ushort Planes, BitsPixel;
+ public nint Bits;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct BitmapInfoHeader
+ {
+ public int Size, Width, Height;
+ public ushort Planes, BitCount;
+ public int Compression, SizeImage, XPelsPerMeter, YPelsPerMeter, ClrUsed, ClrImportant;
+ }
+
+ [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
+ private static extern int SHCreateItemFromParsingName(string path, nint bindContext, ref Guid id, [MarshalAs(UnmanagedType.Interface)] out IShellItemImageFactory? item);
+
+ [DllImport("gdi32.dll")] private static extern int GetObject(nint handle, int size, out NativeBitmap bitmap);
+ [DllImport("gdi32.dll")] private static extern int GetDIBits(nint dc, nint bitmap, uint start, uint lines, [Out] byte[] bits, ref BitmapInfoHeader info, uint usage);
+ [DllImport("gdi32.dll")] private static extern bool DeleteObject(nint handle);
+ [DllImport("user32.dll")] private static extern nint GetDC(nint window);
+ [DllImport("user32.dll")] private static extern int ReleaseDC(nint window, nint dc);
+}
diff --git a/MainWindow.DockGlass.cs b/MainWindow.DockGlass.cs
new file mode 100644
index 0000000..ee7734e
--- /dev/null
+++ b/MainWindow.DockGlass.cs
@@ -0,0 +1,99 @@
+using System.Windows;
+using System.Windows.Media;
+using System.Windows.Threading;
+using QiDock.Services;
+using QiDock.Services.Widgets;
+
+namespace QiDock;
+
+/// <summary>
+/// The dock as frosted glass. The dock keeps its own strip of the screen, so behind it is the wallpaper: the dock
+/// shows that part of the wallpaper, softened (the same picture the desktop cards use), under its own colour made
+/// thinner. Nothing is blurred live; the picture is only placed again when the dock changes size or place. With
+/// auto-hide a window can be behind the dock: it then shows the wallpaper's colours, as a tint, not that window.
+/// </summary>
+public partial class MainWindow
+{
+ private bool _dockGlassHooked;
+ private bool _dockGlassOn;
+ private DispatcherTimer? _dockGlassWallpaper;
+
+ private void ApplyDockGlass()
+ {
+ if (!_dockGlassHooked)
+ {
+ _dockGlassHooked = true;
+ DockSurface.SizeChanged += (_, _) => RefreshDockGlass();
+ DockSurface.IsVisibleChanged += (_, _) => RefreshDockGlass();
+ LocationChanged += (_, _) => RefreshDockGlass();
+ ThemeManager.MaterialsChanged += (_, _) => RefreshDockGlass();
+ // Windows writes the new wallpaper a moment after it says the desktop changed.
+ _dockGlassWallpaper = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(1.6) };
+ _dockGlassWallpaper.Tick += (_, _) =>
+ {
+ _dockGlassWallpaper.Stop();
+ WallpaperGlass.Refresh();
+ RefreshDockGlass();
+ };
+ Microsoft.Win32.SystemEvents.UserPreferenceChanged += (_, e) =>
+ {
+ if (e.Category != Microsoft.Win32.UserPreferenceCategory.Desktop) return;
+ Dispatcher.BeginInvoke(() =>
+ {
+ _dockGlassWallpaper.Stop();
+ _dockGlassWallpaper.Start();
+ });
+ };
+ Closed += (_, _) => _dockGlassWallpaper.Stop();
+ }
+ _dockGlassOn = _preferences.Current.DockGlass;
+ if (_dockGlassOn) WallpaperGlass.Refresh();
+ RefreshDockGlass();
+ }
+
+ /// <summary>
+ /// Glass when it is on (the same look as the desktop cards), the theme's material otherwise. The dock places the
+ /// one picture of the screen behind itself, so its growing, shrinking and sliding never draw the glass again.
+ /// </summary>
+ private void RefreshDockGlass()
+ {
+ var standing = EdgePanel.StandsOnDock && !_panelOnTopBar;
+ var before = (GlassLook.DockVeil, GlassLook.WindowBehind);
+ GlassLook.WindowBehind = _autoHideController?.WindowBehind == true;
+ if (!_dockGlassOn || WallpaperGlass.Image is null || DockToScreen() is not { } toScreen)
+ {
+ GlassLook.DockVeil = null;
+ GlassLook.Tiles(Resources, false);
+ if (before.DockVeil is not null) GlassLook.RaiseDockChanged();
+ if (standing) return; // the solid piece the card set up stays
+ DockSurface.SetResourceReference(System.Windows.Controls.Border.BackgroundProperty, "DockMaterial");
+ DockSurface.SetResourceReference(System.Windows.Controls.Border.BorderBrushProperty, "DockBorderMaterial");
+ return;
+ }
+ var area = toScreen.Bounds;
+ GlassLook.DockVeil = GlassLook.Veil(WallpaperGlass.Light(area));
+ GlassLook.Tiles(Resources, true);
+ DockSurface.Background = GlassLook.Dock(toScreen.Matrix);
+ DockSurface.BorderBrush = GlassLook.Rim;
+ if (before != (GlassLook.DockVeil, GlassLook.WindowBehind)) GlassLook.RaiseDockChanged();
+ }
+
+ /// <summary>
+ /// How the dock's surface maps onto the screen (screen units) where it rests, also while it is slid away and on
+ /// any edge (the dock is turned for the side and top edges), and the screen area it covers.
+ /// </summary>
+ private (Matrix Matrix, Rect Bounds)? DockToScreen()
+ {
+ if (DockSurface.ActualWidth <= 0 || DockSurface.ActualHeight <= 0 || !DockSurface.IsVisible) return null;
+ if (PresentationSource.FromVisual(this)?.CompositionTarget is not { } target) return null;
+ if (DockSurface.TransformToAncestor(this) is not Transform toWindow) return null;
+ // Without the slide of hiding: where the dock rests.
+ var matrix = new Matrix(1, 0, 0, 1, -DockSurfaceTranslate.X, -DockSurfaceTranslate.Y);
+ matrix.Append(toWindow.Value);
+ var origin = target.TransformFromDevice.Transform(PointToScreen(new Point(0, 0)));
+ matrix.Translate(origin.X, origin.Y);
+ var bounds = new Rect(0, 0, DockSurface.ActualWidth, DockSurface.ActualHeight);
+ bounds.Transform(matrix);
+ return (matrix, bounds);
+ }
+}
diff --git a/MainWindow.DockMenu.cs b/MainWindow.DockMenu.cs
index 830545b..da10dde 100644
--- a/MainWindow.DockMenu.cs
+++ b/MainWindow.DockMenu.cs
@@ -99,6 +99,7 @@ public partial class MainWindow
widgets.Items.Add(item);
}
menu.Items.Add(widgets);
+ menu.Items.Add(ProfileMenu(options));
var edit = Item(UiText.Get(_widgetBar.IsEditing ? "MenuEditDone" : "MenuEditDock"), "IconEdit");
@@ -118,6 +119,10 @@ public partial class MainWindow
shortcuts.Items.Add(hint);
menu.Items.Add(shortcuts);
+ var files = Item(DesktopWidgets.Desk.L("Dosyalar (Alt+Shift+E)", "Files (Alt+Shift+E)"), "IconFolderOpen");
+ files.Click += (_, _) => Files.FilesWindow.Open();
+ menu.Items.Add(files);
+
var desktopWidgets = Item(DesktopWidgets.Desk.L("Masaüstüne widget ekle…", "Add desktop widgets…"), "IconApps");
desktopWidgets.Click += (_, _) => ShowDesktopWidgetGallery();
menu.Items.Add(desktopWidgets);
@@ -147,6 +152,15 @@ public partial class MainWindow
}
menu.Items.Add(position);
+ var size = Item(UiText.Get("MenuDockSize"), "IconMaximize");
+ foreach (var (value, key) in new[] { (1.0, "DockSizeNormal"), (1.15, "DockSizeLarge"), (1.3, "DockSizeLarger"), (1.45, "DockSizeHuge") })
+ {
+ var item = Item(UiText.Get(key), null, Math.Abs(current.DockScale - value) < 0.01);
+ item.Click += (_, _) => SavePreferences(_preferences.Current with { DockScale = value });
+ size.Items.Add(item);
+ }
+ menu.Items.Add(size);
+
var autoHide = Item(UiText.Get("MenuAutoHide"), "IconDock");
foreach (var (value, key) in new[] { (AutoHideMode.Disabled, "MenuAutoHideOff"), (AutoHideMode.Smart, "MenuAutoHideSmart"), (AutoHideMode.Always, "MenuAutoHideAlways") })
{
@@ -182,6 +196,14 @@ public partial class MainWindow
peek.IsEnabled = current.WidgetPlacement == WidgetPlacement.TopBar;
menu.Items.Add(peek);
+ var notch = Item(UiText.Get("MenuNotchBrowser"), "IconGlobe", current.NotchBrowser);
+ notch.Click += (_, _) => SavePreferences(_preferences.Current with { NotchBrowser = !_preferences.Current.NotchBrowser });
+ menu.Items.Add(notch);
+
+ var glass = Item(UiText.Get("MenuDockGlass"), "IconSparkle", current.DockGlass);
+ glass.Click += (_, _) => SavePreferences(_preferences.Current with { DockGlass = !_preferences.Current.DockGlass });
+ menu.Items.Add(glass);
+
var genie = Item(UiText.Get("GenieEffect"), "IconSparkle", current.GenieEffectEnabled);
genie.Click += (_, _) => SavePreferences(_preferences.Current with { GenieEffectEnabled = !_preferences.Current.GenieEffectEnabled });
genie.IsEnabled = current.AnimationsEnabled; // the effect needs animations; on without them it would do nothing
@@ -191,6 +213,9 @@ public partial class MainWindow
var settings = Item(UiText.Get("Settings"), "IconSettings");
settings.Click += OpenSettings_Click;
menu.Items.Add(settings);
+ var update = Item(UiText.Format("UpdateMenu", Updater.Current), "IconRotate");
+ update.Click += (_, _) => CheckForUpdates_Click();
+ menu.Items.Add(update);
menu.Items.Add(new Separator());
var exit = Item(UiText.Get("Exit"), "IconExit");
exit.Click += ExitQiDock_Click;
diff --git a/MainWindow.Extras.cs b/MainWindow.Extras.cs
index a231c32..3159247 100644
--- a/MainWindow.Extras.cs
+++ b/MainWindow.Extras.cs
@@ -20,7 +20,7 @@ public partial class MainWindow
// Alt+Shift+Space: QuickSearch · Ctrl+Alt+↑: Window Overview · Ctrl+Alt+↓: AppGrid ·
// Ctrl+Alt+←: notification center · Ctrl+Alt+→: control center.
// (Alt+Space and Ctrl+Alt+Space are usually taken by other apps' quick launchers.)
- private const int HotkeyQuickSearch = 0xB001, HotkeyWindowOverview = 0xB002, HotkeyAppGrid = 0xB003, HotkeyNotifications = 0xB004, HotkeyControlCenter = 0xB005, HotkeyProfileFirst = 0xB011;
+ private const int HotkeyQuickSearch = 0xB001, HotkeyWindowOverview = 0xB002, HotkeyAppGrid = 0xB003, HotkeyNotifications = 0xB004, HotkeyControlCenter = 0xB005, HotkeyFiles = 0xB006, HotkeyDockKeys = 0xB007, HotkeyProfileFirst = 0xB011;
private static readonly TimeSpan IdleBeforeTrim = TimeSpan.FromMinutes(2);
private readonly DispatcherTimer _fullScreenWatch = new(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(1) };
@@ -39,6 +39,12 @@ public partial class MainWindow
RegisterHotKey(_extrasHandle, HotkeyAppGrid, ModControl | ModAlt | ModNoRepeat, 0x28 /* Down */);
RegisterHotKey(_extrasHandle, HotkeyNotifications, ModControl | ModAlt | ModNoRepeat, 0x25 /* Left */);
RegisterHotKey(_extrasHandle, HotkeyControlCenter, ModControl | ModAlt | ModNoRepeat, 0x27 /* Right */);
+ // Alt+Shift+E: the Files window (Ctrl+Alt+E would type € on Turkish keyboards).
+ RegisterHotKey(_extrasHandle, HotkeyFiles, ModAlt | ModShift | ModNoRepeat, 0x45 /* E */);
+ // Alt+Shift+D: the keyboard on the dock.
+ RegisterHotKey(_extrasHandle, HotkeyDockKeys, ModAlt | ModShift | ModNoRepeat, 0x44 /* D */);
+ PreviewKeyDown += (_, e) => { if (OnDockKey(e)) e.Handled = true; };
+ Deactivated += (_, _) => EndDockKeyboard(restore: false);
// Ctrl+Alt+Shift+1…9: widget profiles (Ctrl+Alt alone is AltGr, which types # $ { [ on Turkish keyboards).
for (var i = 0; i < 9; i++)
RegisterHotKey(_extrasHandle, HotkeyProfileFirst + i, ModControl | ModAlt | ModShift | ModNoRepeat, (uint)(0x31 + i));
@@ -55,6 +61,7 @@ public partial class MainWindow
AppGridWindow.Prewarm();
};
prewarm.Start();
+ StartDailyUpdateCheck();
_fullScreenWatch.Tick += (_, _) => UpdateFullScreenAwareness(GetForegroundWindow());
_fullScreenWatch.Start();
_memoryTrim.Tick += (_, _) => TrimMemoryWhenIdle();
@@ -80,12 +87,14 @@ public partial class MainWindow
case HotkeyAppGrid: AppGridWindow.Toggle(); break;
case HotkeyNotifications: NotificationCenter.Shared.Toggle(); break;
case HotkeyControlCenter: ControlCenter.Shared.Toggle(); break;
+ case HotkeyFiles: Files.FilesWindow.Open(); break;
+ case HotkeyDockKeys: BeginDockKeyboard(); break;
case >= HotkeyProfileFirst and < HotkeyProfileFirst + 9:
var options = _preferences.Current.WidgetOptions;
var index = (int)wParam - HotkeyProfileFirst;
if (index >= options.EffectiveProfiles.Count) return 0;
if (index != options.EffectiveActiveProfile) SaveWidgetOptions(options.SwitchProfile(index));
- Widgets.Ui.ShowHud("IconLayout", options.EffectiveProfiles[index].Name);
+ Widgets.Ui.ShowHud("IconPerson", options.EffectiveProfiles[index].Name);
break;
default: return 0;
}
@@ -106,6 +115,8 @@ public partial class MainWindow
UnregisterHotKey(_extrasHandle, HotkeyAppGrid);
UnregisterHotKey(_extrasHandle, HotkeyNotifications);
UnregisterHotKey(_extrasHandle, HotkeyControlCenter);
+ UnregisterHotKey(_extrasHandle, HotkeyFiles);
+ UnregisterHotKey(_extrasHandle, HotkeyDockKeys);
for (var i = 0; i < 9; i++) UnregisterHotKey(_extrasHandle, HotkeyProfileFirst + i);
}
// Never leave a window off the screen when QiDock closes.
diff --git a/MainWindow.Keyboard.cs b/MainWindow.Keyboard.cs
new file mode 100644
index 0000000..0c92a45
--- /dev/null
+++ b/MainWindow.Keyboard.cs
@@ -0,0 +1,133 @@
+using System.Runtime.InteropServices;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Threading;
+using QiDock.Services;
+
+namespace QiDock;
+
+/// <summary>
+/// Alt+Shift+D puts the keyboard on the dock: the arrow keys (or Tab) move along the icons, Enter or Space opens one,
+/// the menu key or Shift+F10 opens its menu, Esc goes back to the window that was in front. Nothing runs until the
+/// keys are pressed.
+/// </summary>
+public partial class MainWindow
+{
+ private bool _keyboardOnDock;
+ private nint _foregroundBeforeKeys;
+ private Button? _lastKeyButton;
+
+ private void BeginDockKeyboard()
+ {
+ if (_keyboardOnDock)
+ {
+ EndDockKeyboard(restore: true);
+ return;
+ }
+ var buttons = DockKeyButtons();
+ if (buttons.Count == 0) return;
+ _foregroundBeforeKeys = KeyNative.GetForegroundWindow();
+ _keyboardOnDock = true;
+ _autoHideController?.OnMouseEnterDock();
+ // The dock never takes focus from a click; for the keyboard it has to.
+ Activate();
+ KeyNative.SetForegroundWindow(new System.Windows.Interop.WindowInteropHelper(this).Handle);
+ var start = _lastKeyButton is { IsVisible: true } last && buttons.Contains(last)
+ ? last
+ : buttons.FirstOrDefault(b => b.DataContext is Models.DockApp) ?? buttons[0];
+ Dispatcher.BeginInvoke(DispatcherPriority.Input, () => FocusDockButton(start));
+ Widgets.Ui.ShowHud("IconKeyboard", UiText.Get("DockKeysHint"));
+ }
+
+ private void EndDockKeyboard(bool restore)
+ {
+ if (!_keyboardOnDock) return;
+ _keyboardOnDock = false;
+ Keyboard.ClearFocus();
+ FocusManager.SetFocusedElement(this, null);
+ _autoHideController?.OnMouseLeaveDock();
+ if (restore && _foregroundBeforeKeys != 0) KeyNative.SetForegroundWindow(_foregroundBeforeKeys);
+ _foregroundBeforeKeys = 0;
+ }
+
+ /// <summary>The dock's buttons in the order they stand (start, apps, downloads, bin…).</summary>
+ private List<Button> DockKeyButtons()
+ {
+ var found = new List<Button>();
+ var style = TryFindResource("DockButton");
+ void Walk(DependencyObject parent)
+ {
+ for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
+ {
+ var child = VisualTreeHelper.GetChild(parent, i);
+ if (child is Button { IsVisible: true, IsEnabled: true } button && ReferenceEquals(button.Style, style))
+ {
+ found.Add(button);
+ continue;
+ }
+ Walk(child);
+ }
+ }
+ Walk(DockContents);
+ return found;
+ }
+
+ private void FocusDockButton(Button button)
+ {
+ _lastKeyButton = button;
+ button.Focusable = true;
+ Keyboard.Focus(button);
+ // A keyboard focus ring even though the last thing WPF saw may have been the mouse.
+ if (!button.IsKeyboardFocused) button.Focus();
+ }
+
+ /// <summary>Called from the window's key handler; returns whether the key was the dock's.</summary>
+ private bool OnDockKey(KeyEventArgs e)
+ {
+ if (!_keyboardOnDock) return false;
+ var key = e.Key == Key.System ? e.SystemKey : e.Key;
+ var buttons = DockKeyButtons();
+ if (buttons.Count == 0) return false;
+ var current = Keyboard.FocusedElement as Button;
+ var at = current is null ? -1 : buttons.IndexOf(current);
+ var shift = (Keyboard.Modifiers & ModifierKeys.Shift) != 0;
+ int? next = key switch
+ {
+ Key.Left or Key.Up => at - 1,
+ Key.Right or Key.Down => at + 1,
+ Key.Tab => shift ? at - 1 : at + 1,
+ Key.Home => 0,
+ Key.End => buttons.Count - 1,
+ _ => null
+ };
+ if (next is { } index)
+ {
+ // Round the ends, as a menu does.
+ FocusDockButton(buttons[(index % buttons.Count + buttons.Count) % buttons.Count]);
+ return true;
+ }
+ switch (key)
+ {
+ case Key.Enter or Key.Space when current is not null:
+ var button = current;
+ EndDockKeyboard(restore: false);
+ button.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent, button));
+ return true;
+ case Key.Escape:
+ EndDockKeyboard(restore: true);
+ return true;
+ default:
+ // Shift+F10 and the menu key open the focused icon's menu the usual way.
+ return false;
+ }
+ }
+
+ private static class KeyNative
+ {
+ [DllImport("user32.dll")] public static extern nint GetForegroundWindow();
+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(nint window);
+ }
+}
diff --git a/MainWindow.Notifications.cs b/MainWindow.Notifications.cs
index 37449e5..f33aacc 100644
--- a/MainWindow.Notifications.cs
+++ b/MainWindow.Notifications.cs
@@ -46,15 +46,19 @@ public partial class MainWindow
_topBar?.Update(); // the bar stays down while a card stands on it
if (standing is { } solid && !_panelOnTopBar)
{
- DockSurface.Background = solid;
- DockSurface.BorderBrush = solid;
+ // Glass: the card wears the dock's glass, so both stay glass; otherwise both turn solid.
+ RefreshDockGlass();
+ if (Services.Widgets.GlassLook.DockVeil is null)
+ {
+ DockSurface.Background = solid;
+ DockSurface.BorderBrush = solid;
+ }
_dockShadow ??= DockSurface.Effect;
DockSurface.Effect = null;
}
else
{
- DockSurface.SetResourceReference(System.Windows.Controls.Border.BackgroundProperty, "DockMaterial");
- DockSurface.SetResourceReference(System.Windows.Controls.Border.BorderBrushProperty, "DockBorderMaterial");
+ RefreshDockGlass();
if (_dockShadow is not null && App.Shadows) DockSurface.Effect = _dockShadow;
}
};
diff --git a/MainWindow.Shortcuts.cs b/MainWindow.Shortcuts.cs
index 0699a06..afb3ca2 100644
--- a/MainWindow.Shortcuts.cs
+++ b/MainWindow.Shortcuts.cs
@@ -316,6 +316,9 @@ public partial class MainWindow
if (dialog.ShowDialog() == true) AddShortcuts(dialog.FolderNames);
}
+ /// <summary>Pins files or folders chosen in the Files window.</summary>
+ internal void PinToDock(IEnumerable<string> paths) => AddShortcuts(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)
{
diff --git a/MainWindow.TopBar.cs b/MainWindow.TopBar.cs
index 01b0e55..5eacad3 100644
--- a/MainWindow.TopBar.cs
+++ b/MainWindow.TopBar.cs
@@ -29,6 +29,7 @@ public partial class MainWindow
PreferControlCenterTile();
BellToCorner();
SecondBatchHidden();
+ ProfileToMenu();
ApplyDockBell();
_topBar = new TopBarWindow { Tabs = _widgetBar.ProfileStrip };
_widgetBar.ProfileMenuRequested += (_, target) => ShowProfileMenu(target.Index, target.Anchor);
@@ -36,6 +37,8 @@ public partial class MainWindow
_topBar.LiveChanged += (_, live) => _widgetBar.SetLive(live || WidgetsInDock && DockOnScreen);
_topBar.MenuRequested += (_, _) => ShowDockMenu(PlacementMode.MousePoint, null);
_topBar.SetPeekEnabled(_preferences.Current.TopBarPeek);
+ ApplyNotchBrowser();
+ ApplyDockGlass();
_widgetBar.SetLive(false);
ApplyWidgetPlacement();
UpdateTopBarContent();
@@ -497,7 +500,9 @@ public partial class MainWindow
private void ApplyWidgetHostTransform()
{
var matrix = Matrix.Identity;
- matrix.Scale(_dockWidgetScale, _dockWidgetScale);
+ // In the dock the widget tiles grow with the dock's size, as the app icons do.
+ var grow = WidgetsInDock ? Services.TaskbarReplacementSession.Scale : 1;
+ matrix.Scale(_dockWidgetScale * grow, _dockWidgetScale * grow);
if (Edge == Models.DockEdge.Top) matrix.Append(Services.DockGeometry.FrameToScreen(Models.DockEdge.Top));
WidgetHost.LayoutTransform = matrix.IsIdentity ? Transform.Identity : new MatrixTransform(matrix);
}
@@ -618,6 +623,63 @@ public partial class MainWindow
});
}
+ /// <summary>Once: the profile tile leaves the bar; profiles are switched from the dock's menu.</summary>
+ private void ProfileToMenu()
+ {
+ var options = _preferences.Current.WidgetOptions;
+ if (options.LayoutRevision >= 5) return;
+ List<string> Hide(IReadOnlyList<string>? hidden) => (hidden ?? []).Append(Models.WidgetIds.Profile).Distinct().ToList();
+ var profiles = options.EffectiveProfiles.Select(profile => profile with { Hidden = Hide(profile.Hidden) }).ToList();
+ SavePreferences(_preferences.Current with
+ {
+ Widgets = options with { Hidden = Hide(options.Hidden), Profiles = profiles, LayoutRevision = 5 }
+ });
+ }
+
+ /// <summary>"Profil" in the dock's menu: switch, add, rename or remove the widget profiles.</summary>
+ private MenuItem ProfileMenu(Models.WidgetSettings options)
+ {
+ var profiles = options.EffectiveProfiles;
+ var active = options.EffectiveActiveProfile;
+ var root = Item(Services.UiText.Get("MenuProfile"), "IconPerson");
+ 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 now = _preferences.Current.WidgetOptions;
+ if (index == now.EffectiveActiveProfile || index >= now.EffectiveProfiles.Count) return;
+ SaveWidgetOptions(now.SwitchProfile(index));
+ Widgets.Ui.ShowHud("IconPerson", now.EffectiveProfiles[index].Name);
+ };
+ root.Items.Add(item);
+ }
+ root.Items.Add(new Separator());
+ var add = Item(Services.UiText.Get("ProfileAdd"), "IconPlus");
+ add.Click += (_, _) =>
+ {
+ var now = _preferences.Current.WidgetOptions;
+ SaveWidgetOptions(now.AddProfile(Services.UiText.Format("ProfileNew", now.EffectiveProfiles.Count + 1)));
+ };
+ root.Items.Add(add);
+ var rename = Item(Services.UiText.Get("ProfileRename"), "IconEdit");
+ foreach (var key in new[] { "ProfileDefault", "ProfileWork", "ProfileHome", "ProfileFocus", "ProfileGame", "ProfileSchool", "ProfileCreative", "ProfileTools" })
+ {
+ var name = Services.UiText.Get(key);
+ var item = Item(name, null, profiles[active].Name == name);
+ item.Click += (_, _) => SaveWidgetOptions(_preferences.Current.WidgetOptions.RenameProfile(active, name));
+ rename.Items.Add(item);
+ }
+ root.Items.Add(rename);
+ var remove = Item(Services.UiText.Get("ProfileRemove"), "IconClose");
+ remove.IsEnabled = profiles.Count > 1;
+ remove.Click += (_, _) => SaveWidgetOptions(_preferences.Current.WidgetOptions.RemoveProfile(active));
+ root.Items.Add(remove);
+ return root;
+ }
+
private void ShowProfileMenu(int index, FrameworkElement anchor)
{
var options = _preferences.Current.WidgetOptions;
diff --git a/MainWindow.Updates.cs b/MainWindow.Updates.cs
new file mode 100644
index 0000000..7137d2f
--- /dev/null
+++ b/MainWindow.Updates.cs
@@ -0,0 +1,70 @@
+using System.Net.Http;
+using System.Text.Json;
+using System.Windows;
+using System.Windows.Threading;
+using QiDock.Services;
+
+namespace QiDock;
+
+/// <summary>"Güncellemeleri denetle" in the dock menu, and the quiet once-a-day check.</summary>
+public partial class MainWindow
+{
+ private bool _updating;
+
+ private void StartDailyUpdateCheck()
+ {
+ Updater.CleanUp();
+ // Well after start-up, so it never competes with the dock appearing.
+ var later = new DispatcherTimer(DispatcherPriority.ApplicationIdle) { Interval = TimeSpan.FromSeconds(90) };
+ later.Tick += (_, _) =>
+ {
+ later.Stop();
+ Updater.CheckDaily(release => Widgets.Ui.ShowHud("IconArrowDown", UiText.Format("UpdateAvailableHud", release.Version)));
+ };
+ later.Start();
+ }
+
+ private async void CheckForUpdates_Click()
+ {
+ if (_updating) return;
+ _updating = true;
+ try
+ {
+ Widgets.Ui.ShowHud("IconRotate", UiText.Get("UpdateChecking"));
+ Updater.Release? release;
+ try
+ {
+ release = await Updater.CheckAsync();
+ }
+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException or KeyNotFoundException or InvalidOperationException)
+ {
+ Widgets.Ui.ShowHud("IconWifiOff", UiText.Get("UpdateCheckFailed"));
+ return;
+ }
+ if (release is null)
+ {
+ Widgets.Ui.ShowHud("IconCheck", UiText.Format("UpdateUpToDate", Updater.Current));
+ return;
+ }
+ var answer = MessageBox.Show(
+ UiText.Format("UpdatePrompt", release.Version, Updater.Current, Math.Max(1, release.Size / (1024 * 1024))),
+ "QiDock",
+ MessageBoxButton.YesNo,
+ MessageBoxImage.Question,
+ MessageBoxResult.Yes);
+ if (answer != MessageBoxResult.Yes) return;
+ var progress = new Progress<int>(percent => Widgets.Ui.ShowHud("IconArrowDown", UiText.Format("UpdateDownloading", percent)));
+ var error = await Updater.InstallAsync(release, progress);
+ if (error is not null)
+ {
+ MessageBox.Show(error, "QiDock", MessageBoxButton.OK, MessageBoxImage.Warning);
+ return;
+ }
+ ((App)Application.Current).Restart();
+ }
+ finally
+ {
+ _updating = false;
+ }
+ }
+}
diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.cs
index b1f0495..76e3dab 100644
--- a/MainWindow.xaml.cs
+++ b/MainWindow.xaml.cs
@@ -97,6 +97,13 @@ public partial class MainWindow : Window
_preferences.Changed += Preferences_Changed;
LoadPinnedApps(_preferences.Current.PinOrder);
_widgetBar.LayoutInvalidated += WidgetBar_LayoutInvalidated;
+ _widgetBar.WidgetExpanding += (_, on) =>
+ {
+ if (!WidgetsInDock) return;
+ // Opening out: the widgets keep their width and clip what is pushed past the dock's end.
+ WidgetHost.Width = on ? WidgetHost.ActualWidth : double.NaN;
+ WidgetHost.ClipToBounds = on;
+ };
WidgetHost.SizeChanged += (_, e) =>
{
if (!WidgetsInDock || Math.Abs(e.NewSize.Width - e.PreviousSize.Width) < 0.5 || _dockRefitQueued) return;
@@ -142,6 +149,7 @@ public partial class MainWindow : Window
{
await Task.Delay(TimeSpan.FromSeconds(10));
new StartupRegistration().UpgradeToTask();
+ StartupRegistration.EnsureStartMenuShortcut();
});
if (!ExcludeFromTaskSwitcher(source.Handle))
{
@@ -184,8 +192,11 @@ public partial class MainWindow : Window
DockSurfaceTranslate,
DockSurface,
() => _holdDockUp || (_openContextMenu?.IsOpen == true) || _thumbnailPreview.IsVisible || _draggedApp is not null || (_settingsWindow?.IsVisible == true) || _genie.IsBusy
- || NotificationCenterOpen || _downloadsPopup?.IsOpen == true);
+ || NotificationCenterOpen || _downloadsPopup?.IsOpen == true || _widgetBar.IsAnyPopupOpen);
+ // A widget card or the AI strip was open past the dock's edge: once it closes the dock may hide again.
+ Widgets.WidgetPopup.AnyClosed += (_, _) => Dispatcher.BeginInvoke(() => _autoHideController?.EvaluateState(), DispatcherPriority.Background);
_autoHideController.SetMode(_preferences.Current.AutoHide);
+ _autoHideController.WindowBehindChanged += RefreshDockGlass;
AttachHudToAutoHide();
ApplyAutoHideHitArea();
@@ -1130,6 +1141,13 @@ public partial class MainWindow : Window
{
var current = _preferences.Current;
Application.Current.Resources["DockHoverScale"] = current.Magnify ? Math.Clamp(current.MagnifyScale, 1.1, 2.2) : 1.0;
+ var scale = Math.Clamp(current.DockScale, 0.8, 1.6);
+ if (Math.Abs(scale - TaskbarReplacementSession.Scale) < 0.001) return;
+ TaskbarReplacementSession.Scale = scale;
+ ApplyWidgetHostTransform();
+ // A bigger dock needs a taller strip of the screen: the session reserves it and lays the dock out again.
+ if (_replacementSession is not null) _replacementSession.RefreshPosition();
+ else if (_dockArea.Width > 0) ApplyTaskbarLayout(_dockArea);
}
private void DockApp_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
@@ -1760,6 +1778,8 @@ public partial class MainWindow : Window
ApplyWidgetPlacement();
ApplyDockEdge();
_topBar?.SetPeekEnabled(_preferences.Current.TopBarPeek);
+ ApplyNotchBrowser();
+ ApplyDockGlass();
_deskWidgets?.SettingsChanged();
ApplyToastHiding();
ApplyDesktopIcons(_preferences.Current.HideDesktopIcons);
@@ -1900,16 +1920,19 @@ public partial class MainWindow : Window
// otherwise the bottom of the window clips it.
var stripHeight = Math.Max(36, area.Height);
var bottomGap = stripHeight >= 56 ? 6.0 : stripHeight >= 44 ? 4.0 : 2.0;
- var barHeight = Math.Min(66, stripHeight - bottomGap);
+ var scale = TaskbarReplacementSession.Scale;
+ var barHeight = Math.Min(Math.Round(66 * scale), stripHeight - bottomGap);
DockSurface.Margin = new Thickness(12, 0, 12, bottomGap);
var verticalChrome = DockSurface.Padding.Top + DockSurface.Padding.Bottom
+ DockSurface.BorderThickness.Top + DockSurface.BorderThickness.Bottom;
var cellHeight = Math.Max(26, barHeight - verticalChrome);
+ _dockFullCell = cellHeight;
+ _dockChrome = verticalChrome;
DockSurface.Height = cellHeight + verticalChrome;
Application.Current.Resources["DockCellHeight"] = cellHeight;
// Tile on top, a small strip under it for the running dot.
// The same tile size as before; the 13 DIP left over is split above and below it (the dot sits below).
- _tileSizeForHeight = Math.Clamp(cellHeight - 13, 22, 50);
+ _tileSizeForHeight = Math.Clamp(cellHeight - Math.Round(13 * scale), 22, Math.Round(50 * scale));
ApplyTileSize(_tileSizeForHeight);
ResizeDockToContent();
}
@@ -1925,9 +1948,16 @@ public partial class MainWindow : Window
if (_appliedEdge is { } edge && edge != Models.DockEdge.Bottom) OrientAllIcons();
}
+ private void ApplyNotchBrowser()
+ {
+ Browser.NotchBrowser.Animations = _preferences.Current.AnimationsEnabled;
+ Browser.NotchBrowser.SetEnabled(_preferences.Current.NotchBrowser);
+ }
+
private void OnFullScreenChanged(bool suppressed)
{
_topBar?.SetSuppressed(suppressed);
+ Browser.NotchBrowser.Suppressed = suppressed;
if (!suppressed) return;
_widgetBar.ClosePopups();
_previewCloseTimer.Stop();
@@ -1936,6 +1966,40 @@ public partial class MainWindow : Window
ResetMagnification();
}
+ private string? _lastFitNote;
+ private double _dockFullCell, _dockChrome;
+
+ /// <summary>
+ /// When the row is too wide and the icons shrink, the dock gets lower with them (from the top), so no empty band
+ /// stands above the icons.
+ /// </summary>
+ private void FitDockHeight()
+ {
+ if (_dockFullCell <= 0 || Application.Current.Resources["DockTileSize"] is not double tile) return;
+ var cell = Math.Min(_dockFullCell, tile + Math.Round(13 * TaskbarReplacementSession.Scale));
+ if (Application.Current.Resources["DockCellHeight"] is double now && Math.Abs(now - cell) < 0.5) return;
+ Application.Current.Resources["DockCellHeight"] = cell;
+ DockSurface.Height = cell + _dockChrome;
+ }
+
+ /// <summary>
+ /// Widget tiles in the dock stand as tall as the dock allows (a narrow row shrinks them, but not their height),
+ /// so a full dock has no empty band above and below them.
+ /// </summary>
+ private void FillDockHeight()
+ {
+ var scale = _dockWidgetScale * (WidgetsInDock ? TaskbarReplacementSession.Scale : 1);
+ if (!WidgetsInDock || scale <= 0 || Application.Current.Resources["DockCellHeight"] is not double cell)
+ {
+ WidgetHost.Resources.Remove("WidgetTileHeight");
+ return;
+ }
+ var standard = (double)Application.Current.Resources["WidgetTileHeight"];
+ var tall = Math.Max(standard, Math.Round((cell - 10) * 0.75 / scale, 1));
+ if (WidgetHost.Resources["WidgetTileHeight"] is double now && Math.Abs(now - tall) < 0.5) return;
+ WidgetHost.Resources["WidgetTileHeight"] = tall;
+ }
+
private void ResizeDockToContent()
{
// Fit cells explicitly; a Viewbox would scale every control after transient layout changes.
@@ -1966,6 +2030,13 @@ public partial class MainWindow : Window
cellSize = Math.Min(fullCell, Math.Max(24, (availableWidth - frameWidth - statusWidth - widgetWidth) / count));
}
SetDockWidgetScale(widgetScale);
+ FillDockHeight();
+ var fitNote = $"{count}|{Math.Round(widgetWidth)}|{Math.Round(availableWidth)}|{widgetScale:0.00}|{cellSize:0.0}|{_tileSizeForHeight}";
+ if (fitNote != _lastFitNote)
+ {
+ _lastFitNote = fitNote;
+ Services.AppLog.Write("Dock sığdırma (simge|widget gen.|alan|widget ölçek|hücre|tam simge): " + fitNote);
+ }
var previousCell = Application.Current.Resources["DockCellSize"] is double cell ? cell : double.NaN;
if (Math.Abs(previousCell - cellSize) > 0.01)
{
@@ -1974,6 +2045,8 @@ public partial class MainWindow : Window
Application.Current.Resources["DockCellSize"] = cellSize;
ApplyTileSize(Math.Max(20, Math.Min(_tileSizeForHeight, cellSize - 6)));
}
+ FitDockHeight();
+ FillDockHeight();
// A new tile size reaches the tiles through resources: lay them out first, or the row is measured at the old size.
DockRow.InvalidateMeasure();
UpdateLayout();
diff --git a/Models/DockSettings.cs b/Models/DockSettings.cs
index 5d9059a..826dd33 100644
--- a/Models/DockSettings.cs
+++ b/Models/DockSettings.cs
@@ -42,7 +42,10 @@ public sealed record DockSettings(
bool ClaudeActivity = true,
bool Magnify = false,
double MagnifyScale = 1.85,
- bool LowMemory = false)
+ bool LowMemory = false,
+ bool NotchBrowser = true,
+ bool DockGlass = true,
+ double DockScale = 1.0)
{
[System.Text.Json.Serialization.JsonIgnore]
public WidgetSettings WidgetOptions => Widgets ?? new WidgetSettings();
diff --git a/QiDock.csproj b/QiDock.csproj
index ab9a692..18a1728 100644
--- a/QiDock.csproj
+++ b/QiDock.csproj
@@ -25,4 +25,8 @@
<DebugSymbols>false</DebugSymbols>
</PropertyGroup>
+ <ItemGroup>
+ <PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2903.40" />
+ </ItemGroup>
+
</Project>
diff --git a/Services/AppCategories.cs b/Services/AppCategories.cs
new file mode 100644
index 0000000..9d099d3
--- /dev/null
+++ b/Services/AppCategories.cs
@@ -0,0 +1,146 @@
+using System.Globalization;
+using System.IO;
+using System.Text;
+using System.Text.Json;
+
+namespace QiDock.Services;
+
+/// <summary>
+/// Which shelf of the app screen an app belongs on. Windows keeps no categories for desktop apps, so the guess comes
+/// from the words in the app's name and program file (a small table, read once); a choice made from the app's
+/// right-click menu wins and is kept in app-categories.json.
+/// </summary>
+internal static class AppCategories
+{
+ public const string All = "All", Other = "Other";
+
+ /// <summary>The shelves in the order their chips stand.</summary>
+ public static readonly string[] Order = ["Productivity", "Creativity", "Development", "Communication", "Internet", "Media", "Games", "Utilities", Other];
+
+ public static string Name(string id) => id switch
+ {
+ All => L("Tümü", "All"),
+ "Productivity" => L("Verimlilik", "Productivity"),
+ "Creativity" => L("Yaratıcılık", "Creativity"),
+ "Development" => L("Geliştirme", "Development"),
+ "Communication" => L("İletişim", "Communication"),
+ "Internet" => L("İnternet", "Internet"),
+ "Media" => L("Eğlence", "Entertainment"),
+ "Games" => L("Oyunlar", "Games"),
+ "Utilities" => L("Araçlar", "Utilities"),
+ _ => L("Diğer", "Other")
+ };
+
+ private static string L(string turkish, string english) => DesktopWidgets.Desk.L(turkish, english);
+
+ // Whole words (or word runs) of a lower-case name. Checked from top to bottom: the first match wins.
+ private static readonly (string Category, string[] Words)[] Rules =
+ [
+ ("Games", ["steam", "epic games", "xbox", "gog galaxy", "battle net", "ea app", "origin", "ubisoft connect", "riot client", "valorant", "league of legends",
+ "minecraft", "roblox", "game", "games", "oyun", "solitaire", "playnite", "rockstar games", "bluestacks", "geforce now", "fortnite", "counter strike"]),
+ ("Development", ["visual studio", "code", "vscode", "git", "github", "github desktop", "gitkraken", "terminal", "powershell", "python", "node js", "nodejs", "docker",
+ "android studio", "intellij", "pycharm", "webstorm", "rider", "clion", "goland", "jetbrains", "postman", "insomnia", "wsl", "ubuntu", "debian", "antigravity",
+ "cursor", "windsurf", "zed", "notepad++", "sublime text", "unity", "unity hub", "unreal", "arduino", "putty", "winscp", "filezilla", "dbeaver", "heidisql",
+ "sql server", "mysql", "pgadmin", "ssms", "command prompt", "komut istemi", "developer", "sdk", "git bash", "claude code", "codex", "ollama", "lm studio"]),
+ ("Creativity", ["adobe", "photoshop", "illustrator", "premiere", "after effects", "lightroom", "indesign", "davinci", "resolve", "blender", "gimp", "inkscape",
+ "krita", "figma", "canva", "obs", "obs studio", "audacity", "fl studio", "ableton", "reaper", "capcut", "clipchamp", "paint", "paint net", "affinity",
+ "bambu studio", "cura", "prusaslicer", "orcaslicer", "fusion 360", "sketchup", "autocad", "kicad", "freecad", "handbrake", "shotcut", "kdenlive",
+ "blip", "procreate", "photopea", "darktable", "rawtherapee", "musescore", "cubase", "logic", "vegas", "filmora"]),
+ ("Communication", ["whatsapp", "telegram", "discord", "slack", "teams", "microsoft teams", "zoom", "skype", "signal", "messenger", "outlook", "thunderbird",
+ "mail", "posta", "e posta", "webex", "viber", "wechat", "element", "mattermost", "gmail"]),
+ ("Internet", ["chrome", "google chrome", "edge", "microsoft edge", "firefox", "brave", "opera", "opera gx", "vivaldi", "tor browser", "browser", "tarayıcı",
+ "vpn", "proton vpn", "protonvpn", "nordvpn", "expressvpn", "windscribe", "qbittorrent", "utorrent", "bittorrent", "download manager", "free download manager",
+ "internet download manager", "idm", "onedrive", "dropbox", "google drive", "mega", "megasync", "localsend", "arc", "zen browser", "librewolf"]),
+ ("Media", ["spotify", "vlc", "netflix", "youtube", "youtube music", "media player", "medya oynatıcı", "music", "müzik", "movies", "filmler", "tv", "plex", "kodi",
+ "mpc hc", "mpc be", "potplayer", "itunes", "apple music", "apple tv", "deezer", "prime video", "disney", "twitch", "stremio", "nuvio", "foobar2000",
+ "winamp", "photos", "fotoğraflar", "audible", "kindle", "podcasts", "jellyfin", "mpv"]),
+ ("Productivity", ["word", "excel", "powerpoint", "onenote", "office", "access", "publisher", "visio", "project", "libreoffice", "writer", "calc", "impress",
+ "notion", "obsidian", "evernote", "todo", "to do", "microsoft to do", "yapılacaklar", "calendar", "takvim", "acrobat", "pdf", "reader", "sumatrapdf",
+ "foxit", "chatgpt", "copilot", "claude", "gemini", "perplexity", "notepad", "not defteri", "sticky notes", "yapışkan notlar", "wps office", "trello",
+ "clickup", "anki", "zotero", "joplin", "logseq", "todoist", "ticktick", "onlyoffice", "keepass", "bitwarden", "1password", "kişiler", "contacts"]),
+ ("Utilities", ["calculator", "hesap makinesi", "7 zip", "7zip", "winrar", "peazip", "everything", "powertoys", "ccleaner", "snipping tool", "ekran alıntısı",
+ "uninstall", "uninstaller", "kaldır", "clock", "saat", "alarms", "camera", "kamera", "settings", "ayarlar", "control panel", "denetim masası",
+ "task manager", "görev yöneticisi", "logi options", "logitech", "lenovo", "vantage", "hp", "dell", "asus", "armoury crate", "msi", "nvidia", "amd",
+ "radeon", "realtek", "intel", "driver", "backup", "yedekleme", "file explorer", "dosya gezgini", "windows tools", "windows araçları", "registry",
+ "regedit", "disk", "iriun", "phone link", "telefon bağlantısı", "quick assist", "hızlı yardım", "remote desktop", "uzak masaüstü", "teamviewer",
+ "anydesk", "rufus", "cpu z", "hwinfo", "crystaldiskinfo", "crystaldiskmark", "speedtest", "qidock", "microsoft store", "store", "weather", "hava durumu",
+ "maps", "haritalar", "recorder", "kaydedici", "ses kaydedici", "magnifier", "büyüteç", "narrator", "ekran okuyucu", "on screen keyboard", "dosyalar",
+ "files", "explorer", "windows security", "windows güvenliği", "get help", "yardım al", "tips", "ipuçları", "feedback hub", "geri bildirim"])
+ ];
+
+ private static Dictionary<string, string>? _choices;
+
+ private static string FilePath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock", "app-categories.json");
+
+ private static Dictionary<string, string> Choices()
+ {
+ if (_choices is not null) return _choices;
+ try
+ {
+ if (File.Exists(FilePath) && JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText(FilePath)) is { } saved)
+ return _choices = new Dictionary<string, string>(saved, StringComparer.OrdinalIgnoreCase);
+ }
+ catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) { }
+ return _choices = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ }
+
+ /// <summary>Puts an app on a shelf by hand (null: back to the guess).</summary>
+ public static void Choose(string appId, string? category)
+ {
+ var choices = Choices();
+ if (category is null) choices.Remove(appId);
+ else choices[appId] = category;
+ try
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
+ File.WriteAllText(FilePath, JsonSerializer.Serialize(choices));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
+ }
+
+ public static bool IsChosen(string appId) => Choices().ContainsKey(appId);
+
+ /// <summary>The app screen lists the apps by use instead of by name (kept while QiDock runs).</summary>
+ public static bool SortByUse { get; set; }
+
+ private static readonly Dictionary<string, string> Guesses = new(StringComparer.OrdinalIgnoreCase);
+
+ public static string Of(InstalledApp app)
+ {
+ if (Choices().TryGetValue(app.Id, out var chosen)) return chosen;
+ lock (Guesses)
+ {
+ if (Guesses.TryGetValue(app.Id, out var known)) return known;
+ return Guesses[app.Id] = Guess(app);
+ }
+ }
+
+ private static string Guess(InstalledApp app)
+ {
+ var words = Words(app.Name);
+ if (app.Target is { } target) words += Words(Path.GetFileNameWithoutExtension(target));
+ // Games installed through a launcher live under its folder.
+ if (app.Target is { } path && (path.Contains(@"\steamapps\", StringComparison.OrdinalIgnoreCase) || path.Contains(@"\Epic Games\", StringComparison.OrdinalIgnoreCase)
+ || path.Contains(@"\GOG Galaxy\Games\", StringComparison.OrdinalIgnoreCase)))
+ return "Games";
+ foreach (var (category, list) in Rules)
+ foreach (var word in list)
+ if (words.Contains(" " + word + " ", StringComparison.Ordinal)) return category;
+ return Other;
+ }
+
+ /// <summary>" adobe premiere pro 2025 ": lower case, anything but letters and digits as single spaces.</summary>
+ private static string Words(string text)
+ {
+ var builder = new StringBuilder(" ");
+ // Invariant lower case keeps "Intel" as "intel"; the dot that "İ" leaves behind is dropped.
+ foreach (var c in text.ToLowerInvariant())
+ {
+ if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.NonSpacingMark) continue;
+ if (char.IsLetterOrDigit(c) || c == '+') builder.Append(c);
+ else if (builder[^1] != ' ') builder.Append(' ');
+ }
+ if (builder[^1] != ' ') builder.Append(' ');
+ return builder.ToString();
+ }
+}
diff --git a/Services/DockAutoHideController.cs b/Services/DockAutoHideController.cs
index de9cfe2..081f23a 100644
--- a/Services/DockAutoHideController.cs
+++ b/Services/DockAutoHideController.cs
@@ -111,10 +111,25 @@ public sealed class DockAutoHideController : IDisposable
EvaluateState();
}
+ /// <summary>The window in front reaches behind the dock (the dock's glass then turns plain grey).</summary>
+ public bool WindowBehind { get; private set; }
+
+ public event Action? WindowBehindChanged;
+
public void CheckForegroundWindow(nint foregroundHwnd)
{
+ // QiDock's own windows (the app grid, cards, menus) come and go over the dock: the window behind it is still
+ // the one that was there, so the dock's glass does not flash between grey and the wallpaper.
+ GetWindowThreadProcessId(foregroundHwnd, out var process);
+ var own = process == (uint)Environment.ProcessId;
+ var behind = own ? WindowBehind : EvaluateWindowOverlap(foregroundHwnd);
+ if (behind != WindowBehind)
+ {
+ WindowBehind = behind;
+ WindowBehindChanged?.Invoke();
+ }
if (Mode != AutoHideMode.Smart) return;
- HasOverlap = EvaluateWindowOverlap(foregroundHwnd);
+ HasOverlap = behind;
EvaluateState();
}
@@ -210,13 +225,14 @@ public sealed class DockAutoHideController : IDisposable
if (GetWindowRect(hwnd, out var winRect) && GetWindowRect(_windowHandle, out var dockRect))
{
- // The dock window's inner 16 px are headroom, not dock: a window may reach into them.
+ // The dock window's inner part is headroom (room for grown icons), not dock: a window may reach into it.
+ var headroom = (int)Math.Round(TaskbarReplacementSession.DockHeadroomDips * GetDpiForWindow(_windowHandle) / 96d);
switch (DockGeometry.Edge)
{
- case Models.DockEdge.Top: dockRect.Bottom -= 16; break;
- case Models.DockEdge.Left: dockRect.Right -= 16; break;
- case Models.DockEdge.Right: dockRect.Left += 16; break;
- default: dockRect.Top += 16; break;
+ case Models.DockEdge.Top: dockRect.Bottom -= headroom; break;
+ case Models.DockEdge.Left: dockRect.Right -= headroom; break;
+ case Models.DockEdge.Right: dockRect.Left += headroom; break;
+ default: dockRect.Top += headroom; break;
}
return winRect.Left < dockRect.Right
&& winRect.Right > dockRect.Left
@@ -253,6 +269,12 @@ public sealed class DockAutoHideController : IDisposable
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsZoomed(nint hWnd);
+ [System.Runtime.InteropServices.DllImport("user32.dll")]
+ private static extern uint GetDpiForWindow(nint hWnd);
+
+ [System.Runtime.InteropServices.DllImport("user32.dll")]
+ private static extern uint GetWindowThreadProcessId(nint hWnd, out uint processId);
+
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWindow(nint hWnd);
diff --git a/Services/Notifications/NotificationFeed.cs b/Services/Notifications/NotificationFeed.cs
index e006038..25af850 100644
--- a/Services/Notifications/NotificationFeed.cs
+++ b/Services/Notifications/NotificationFeed.cs
@@ -343,19 +343,50 @@ public static class NotificationApps
return result;
}
- /// <summary>An app's icon at the given pixel size, not cached (the launcher loads them while it is open).</summary>
- public static BitmapSource? LoadIcon(string appId, int size)
+ /// <summary>
+ /// An app's icon at the given pixel size, not cached (the launcher loads them while it is open). With
+ /// <paramref name="exact"/> the picture is brought to exactly that size here (smoothly, on the calling thread),
+ /// so nothing scales it again while it is drawn.
+ /// </summary>
+ public static BitmapSource? LoadIcon(string appId, int size, bool exact = false)
{
if (SHCreateItemFromParsingName(@"shell:AppsFolder\" + appId, 0, typeof(IShellItem).GUID, out var item) != 0 || item is null) return null;
- try { return ImageOf(item, size); }
+ try { return ImageOf(item, size, exact); }
finally { Marshal.ReleaseComObject(item); }
}
- private static BitmapSource? ImageOf(IShellItem item, int size)
+ private static BitmapSource? ImageOf(IShellItem item, int size, bool exact = false)
{
+ // "Bigger is fine": Windows hands over the icon's own largest picture, scaled here afterwards.
if (item is not IShellItemImageFactory factory || factory.GetImage(new NativeSize(size, size), 0x1 | 0x4 /* bigger ok, icon only */, out var bitmap) != 0 || bitmap == 0) return null;
- try { return FromHBitmap(bitmap); }
+ BitmapSource? image;
+ try { image = FromHBitmap(bitmap); }
finally { DeleteObject(bitmap); }
+ return exact && image is not null ? Fit(image, size) : image;
+ }
+
+ /// <summary>
+ /// The picture brought to <paramref name="size"/> pixels, worked out at once: made smaller by averaging (Fant),
+ /// made larger by blending neighbours (averaging would only repeat pixels and show them as squares).
+ /// </summary>
+ private static BitmapSource Fit(BitmapSource image, int size)
+ {
+ var scale = (double)size / Math.Max(image.PixelWidth, image.PixelHeight);
+ if (Math.Abs(scale - 1) < 0.001) return image;
+ if (scale < 1)
+ {
+ var smaller = new CachedBitmap(new TransformedBitmap(image, new System.Windows.Media.ScaleTransform(scale, scale)), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
+ smaller.Freeze();
+ return smaller;
+ }
+ int width = (int)Math.Round(image.PixelWidth * scale), height = (int)Math.Round(image.PixelHeight * scale);
+ var visual = new System.Windows.Media.DrawingVisual();
+ System.Windows.Media.RenderOptions.SetBitmapScalingMode(visual, System.Windows.Media.BitmapScalingMode.Linear);
+ using (var dc = visual.RenderOpen()) dc.DrawImage(image, new System.Windows.Rect(0, 0, width, height));
+ var larger = new RenderTargetBitmap(width, height, 96, 96, System.Windows.Media.PixelFormats.Pbgra32);
+ larger.Render(visual);
+ larger.Freeze();
+ return larger;
}
private static string Fallback(string appId)
diff --git a/Services/ScreenGlass.cs b/Services/ScreenGlass.cs
new file mode 100644
index 0000000..25c1b32
--- /dev/null
+++ b/Services/ScreenGlass.cs
@@ -0,0 +1,95 @@
+using System.Runtime.InteropServices;
+using System.Windows;
+using System.Windows.Media;
+using System.Windows.Media.Effects;
+using System.Windows.Media.Imaging;
+
+namespace QiDock.Services;
+
+/// <summary>
+/// Frosted glass made from what is on the screen right now: the pixels under a surface are copied once, made small
+/// and blurred, and darkened by a veil. The picture is about a sixth of the size (it is soft anyway), so a whole
+/// panel's glass costs a few hundred kilobytes and is drawn once, when the surface opens.
+/// </summary>
+internal static class ScreenGlass
+{
+ private const int Shrink = 6;
+
+ /// <summary>
+ /// The blurred, veiled picture of <paramref name="area"/> (screen pixels), or null when the screen could not be
+ /// read. Call it before the surface itself is on the screen, or the picture shows the surface.
+ /// </summary>
+ public static BitmapSource? Capture(Int32Rect area, Color veil, double blur = 9)
+ {
+ if (area.Width < Shrink || area.Height < Shrink) return null;
+ var sharp = Copy(area);
+ if (sharp is null) return null;
+ try
+ {
+ var small = new CachedBitmap(new TransformedBitmap(sharp, new ScaleTransform(1.0 / Shrink, 1.0 / Shrink)), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
+ int width = small.PixelWidth, height = small.PixelHeight;
+ var picture = new DrawingVisual { Effect = new BlurEffect { Radius = blur, KernelType = KernelType.Gaussian, RenderingBias = RenderingBias.Quality } };
+ using (var dc = picture.RenderOpen())
+ {
+ // Drawn a little larger, so the blur does not pull the dark outside into the edges.
+ dc.DrawImage(small, new Rect(-blur, -blur, width + 2 * blur, height + 2 * blur));
+ }
+ var tint = new DrawingVisual();
+ using (var dc = tint.RenderOpen()) dc.DrawRectangle(new SolidColorBrush(veil), null, new Rect(0, 0, width, height));
+ var both = new ContainerVisual();
+ both.Children.Add(picture);
+ both.Children.Add(tint);
+ var result = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
+ result.Render(both);
+ result.Freeze();
+ return result;
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or ArgumentException or COMException or OutOfMemoryException)
+ {
+ return null;
+ }
+ }
+
+ private static BitmapSource? Copy(Int32Rect area)
+ {
+ var screen = GetDC(0);
+ if (screen == 0) return null;
+ var memory = CreateCompatibleDC(screen);
+ var header = new BitmapInfoHeader { Size = 40, Width = area.Width, Height = -area.Height, Planes = 1, BitCount = 32 };
+ var dib = CreateDIBSection(screen, ref header, 0, out var bits, 0, 0);
+ var previous = dib != 0 ? SelectObject(memory, dib) : 0;
+ try
+ {
+ if (dib == 0 || bits == 0 || !BitBlt(memory, 0, 0, area.Width, area.Height, screen, area.X, area.Y, 0x00CC0020 /* SRCCOPY */)) return null;
+ GdiFlush();
+ var image = BitmapSource.Create(area.Width, area.Height, 96, 96, PixelFormats.Bgr32, null, bits, area.Width * area.Height * 4, area.Width * 4);
+ image.Freeze();
+ return image;
+ }
+ finally
+ {
+ if (previous != 0) SelectObject(memory, previous);
+ if (dib != 0) DeleteObject(dib);
+ DeleteDC(memory);
+ ReleaseDC(0, screen);
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct BitmapInfoHeader
+ {
+ public int Size, Width, Height;
+ public short Planes, BitCount;
+ public int Compression, SizeImage, XPelsPerMeter, YPelsPerMeter, ClrUsed, ClrImportant;
+ }
+
+ [DllImport("user32.dll")] private static extern nint GetDC(nint window);
+ [DllImport("user32.dll")] private static extern int ReleaseDC(nint window, nint dc);
+ [DllImport("gdi32.dll")] private static extern nint CreateCompatibleDC(nint dc);
+ [DllImport("gdi32.dll")] private static extern bool DeleteDC(nint dc);
+ [DllImport("gdi32.dll")] private static extern nint CreateDIBSection(nint dc, ref BitmapInfoHeader header, uint usage, out nint bits, nint section, uint offset);
+ [DllImport("gdi32.dll")] private static extern nint SelectObject(nint dc, nint item);
+ [DllImport("gdi32.dll")] private static extern bool DeleteObject(nint item);
+ [DllImport("gdi32.dll")] private static extern bool BitBlt(nint target, int x, int y, int width, int height, nint source, int sx, int sy, uint op);
+ [DllImport("gdi32.dll")] private static extern bool GdiFlush();
+}
diff --git a/Services/StartupRegistration.cs b/Services/StartupRegistration.cs
index 02c152d..ae768ec 100644
--- a/Services/StartupRegistration.cs
+++ b/Services/StartupRegistration.cs
@@ -66,6 +66,10 @@ public sealed class StartupRegistration
{
try
{
+ // Before the rename the dock started as "OpenTaskbar"; that entry now points at a file that is gone.
+ using (var old = Registry.CurrentUser.OpenSubKey(RunKey, writable: true))
+ if (old?.GetValue("OpenTaskbar") is string legacy && !File.Exists(legacy.Trim().Trim('"')))
+ old.DeleteValue("OpenTaskbar", throwOnMissingValue: false);
string? runValue;
using (var key = Registry.CurrentUser.OpenSubKey(RunKey)) runValue = key?.GetValue(ValueName) as string;
if (string.IsNullOrWhiteSpace(runValue) || TaskExists()) return;
@@ -86,6 +90,46 @@ public sealed class StartupRegistration
}
}
+ /// <summary>
+ /// A "QiDock" entry in the Start menu that points at this copy, so a closed dock is always one search away. Made
+ /// (or pointed at a moved exe) quietly; nothing happens when it is already right.
+ /// </summary>
+ public static void EnsureStartMenuShortcut()
+ {
+ var executable = Environment.ProcessPath;
+ if (string.IsNullOrWhiteSpace(executable) || !File.Exists(executable)
+ || !string.Equals(Path.GetFileName(executable), "QiDock.exe", StringComparison.OrdinalIgnoreCase)) return;
+ var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), "QiDock.lnk");
+ object? shell = null, link = null;
+ try
+ {
+ if (Type.GetTypeFromProgID("WScript.Shell") is not { } type) return;
+ shell = Activator.CreateInstance(type);
+ if (shell is null) return;
+ const System.Reflection.BindingFlags Get = System.Reflection.BindingFlags.GetProperty, Set = System.Reflection.BindingFlags.SetProperty;
+ link = type.InvokeMember("CreateShortcut", System.Reflection.BindingFlags.InvokeMethod, null, shell, [path]);
+ if (link is null) return;
+ var linkType = link.GetType();
+ var current = linkType.InvokeMember("TargetPath", Get, null, link, null) as string;
+ if (File.Exists(path) && string.Equals(current, executable, StringComparison.OrdinalIgnoreCase)) return;
+ linkType.InvokeMember("TargetPath", Set, null, link, [executable]);
+ linkType.InvokeMember("WorkingDirectory", Set, null, link, [Path.GetDirectoryName(executable) ?? ""]);
+ linkType.InvokeMember("IconLocation", Set, null, link, [executable + ",0"]);
+ linkType.InvokeMember("Description", Set, null, link, ["QiDock"]);
+ linkType.InvokeMember("Save", System.Reflection.BindingFlags.InvokeMethod, null, link, null);
+ AppLog.Write("Başlat menüsüne QiDock kısayolu eklendi");
+ }
+ catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or System.Reflection.TargetInvocationException or UnauthorizedAccessException or IOException)
+ {
+ AppLog.Write($"Başlat menüsü kısayolu yapılamadı: {ex.Message}");
+ }
+ finally
+ {
+ if (link is not null && System.Runtime.InteropServices.Marshal.IsComObject(link)) System.Runtime.InteropServices.Marshal.ReleaseComObject(link);
+ if (shell is not null && System.Runtime.InteropServices.Marshal.IsComObject(shell)) System.Runtime.InteropServices.Marshal.ReleaseComObject(shell);
+ }
+ }
+
private static void SetRunValue(string? executable)
{
using var key = Registry.CurrentUser.CreateSubKey(RunKey, writable: true);
diff --git a/Services/TaskbarReplacementSession.cs b/Services/TaskbarReplacementSession.cs
index 1660806..206e1de 100644
--- a/Services/TaskbarReplacementSession.cs
+++ b/Services/TaskbarReplacementSession.cs
@@ -44,9 +44,11 @@ public sealed class TaskbarReplacementSession : IDisposable
private bool _disposed;
private bool _fullScreenSuppressed;
private double _nativeTaskbarHeight = 66;
- private const double DockHeadroomDips = 44;
+ /// <summary>The dock's size (1 = normal, 1.3 = 30% larger), from the preferences.</summary>
+ public static double Scale { get; set; } = 1;
+ internal static double DockHeadroomDips => Math.Round(44 * Scale);
/// <summary>Height of the dock strip (bar + gap), taller than Windows' own 48 DIP taskbar.</summary>
- public const double DockHeightDips = 64;
+ public static double DockHeightDips => Math.Round(64 * Scale);
private Rect _reservedRect;
private bool _hasReservation;
private bool _autoHideEnabled;
diff --git a/Services/ThemeManager.cs b/Services/ThemeManager.cs
index 2d3f423..0ba2a52 100644
--- a/Services/ThemeManager.cs
+++ b/Services/ThemeManager.cs
@@ -14,6 +14,9 @@ public static class ThemeManager
/// <summary>The style last applied ("glass", "black"…).</summary>
public static string CurrentStyle => _styleId;
+ /// <summary>The palette last applied (dark or light), after a style's own base has been taken into account.</summary>
+ public static AppTheme CurrentTheme { get; private set; } = AppTheme.Dark;
+
/// <summary>
/// Loads the dark or light palette, lays the chosen style over it (a style brings its own base: the light
/// styles always sit on the light palette) and sets the materials' opacity.
@@ -22,6 +25,7 @@ public static class ThemeManager
{
var look = ThemeStyles.Find(style ?? _styleId);
if (look.Id != ThemeStyles.Glass) theme = look.Base;
+ CurrentTheme = theme;
var source = $"/QiDock;component/Design/Palettes/{theme}.xaml";
var dictionaries = Application.Current.Resources.MergedDictionaries;
if (_palette?.Source?.OriginalString != source)
@@ -48,6 +52,9 @@ public static class ThemeManager
SetSurfaceOpacity(opacity);
}
+ /// <summary>The dock and menu materials were made again (another theme, style or opacity).</summary>
+ public static event EventHandler? MaterialsChanged;
+
public static void SetSurfaceOpacity(double opacity)
{
if (!double.IsFinite(opacity) || opacity is < 0.6 or > 1) throw new ArgumentOutOfRangeException(nameof(opacity));
@@ -71,5 +78,6 @@ public static class ThemeManager
material.Freeze();
Materials[key] = material;
}
+ MaterialsChanged?.Invoke(null, EventArgs.Empty);
}
}
diff --git a/Services/UiText.cs b/Services/UiText.cs
index ca0d74d..6e60149 100644
--- a/Services/UiText.cs
+++ b/Services/UiText.cs
@@ -51,6 +51,12 @@ public sealed class UiText : INotifyPropertyChanged
["MediaMute"] = ("Sesi kapat / aç", "Mute / unmute"),
["MediaAppVolume"] = ("{0} sesi", "{0} volume"),
["MediaSystemVolume"] = ("Bilgisayarın sesi", "Computer volume"),
+ ["MediaRecent"] = ("Son çalınanlar", "Recently played"),
+ ["MediaRecentEmpty"] = ("Çalınan şarkılar burada sıralanır.", "Songs you play are listed here."),
+ ["MediaShowPlaying"] = ("Şimdi çalan", "Now playing"),
+ ["MediaShowRecent"] = ("Çalma listesini göster", "Show the playlist"),
+ ["MediaPlaylist"] = ("Çalma listesi", "Playlist"),
+ ["MediaShowTab"] = ("Listeyi görmek için YouTube sekmesini öne getir", "Bring the YouTube tab forward to see its list"),
["MediaIdle"] = ("Çalan bir şey yok", "Nothing playing"),
["MediaIdleHint"] = ("Oynat düğmesi en son çalan uygulamayı (Spotify, tarayıcı…) sürdürür", "Play resumes the app that last played (Spotify, the browser…)"),
["CurrencyTitle"] = ("Döviz çevirici", "Currency converter"),
@@ -119,6 +125,12 @@ public sealed class UiText : INotifyPropertyChanged
["Desktop"] = ("Temiz masaüstü", "Clean desktop"),
["DesktopFiles"] = ("Klasörlü masaüstü", "Desktop with files"),
["MenuWidgets"] = ("Widget’lar", "Widgets"),
+ ["MenuProfile"] = ("Profil", "Profile"),
+ ["MenuDockSize"] = ("Dock boyutu", "Dock size"),
+ ["DockSizeNormal"] = ("Normal", "Normal"),
+ ["DockSizeLarge"] = ("Büyük (%15)", "Large (15%)"),
+ ["DockSizeLarger"] = ("Daha büyük (%30)", "Larger (30%)"),
+ ["DockSizeHuge"] = ("En büyük (%45)", "Largest (45%)"),
["MenuEditDock"] = ("Widget’ları düzenle (taşı, kaldır, ekle)", "Edit widgets (move, remove, add)"),
["MenuEditDone"] = ("Düzenlemeyi bitir", "Finish editing"),
["MenuCity"] = ("Hava durumu şehri: {0}", "Weather city: {0}"),
@@ -140,6 +152,8 @@ public sealed class UiText : INotifyPropertyChanged
["WidgetPlacementTop"] = ("Dock'ta yalnızca uygulamalar, araçlar üstte ayrı çubukta (eski düzen)", "Apps only in the dock, widgets in a separate top bar (classic)"),
["WidgetPlacementDockLeft"] = ("Araçlar dock'un içinde, uygulamaların solunda", "Widgets inside the dock, left of the apps"),
["WidgetPlacementDockRight"] = ("Araçlar dock'un içinde, uygulamaların sağında", "Widgets inside the dock, right of the apps"),
+ ["MenuNotchBrowser"] = ("Üst ortaya gelince tarayıcıyı aç", "Open the browser at the top centre"),
+ ["MenuDockGlass"] = ("Dock'ta cam görünüm", "Glass dock"),
["MenuTopBarPeek"] = ("Üst kenara gelince widget çubuğunu göster", "Show the widget bar at the top edge"),
["EditAddWidget"] = ("Ekle", "Add"),
["EditDone"] = ("Bitti", "Done"),
@@ -264,6 +278,14 @@ public sealed class UiText : INotifyPropertyChanged
["CcWindowsSettings"] = ("Windows", "Windows"),
["AppGridTitle"] = ("Tüm uygulamalar (Ctrl+Alt+↓)", "All apps (Ctrl+Alt+↓)"),
["AppGridSearch"] = ("Ara", "Search"),
+ ["UpdateMenu"] = ("Güncellemeleri denetle (sürüm {0})", "Check for updates (version {0})"),
+ ["UpdateChecking"] = ("Güncelleme denetleniyor…", "Checking for updates…"),
+ ["UpdateCheckFailed"] = ("GitHub'a ulaşılamadı", "Couldn’t reach GitHub"),
+ ["UpdateUpToDate"] = ("QiDock güncel (sürüm {0})", "QiDock is up to date ({0})"),
+ ["UpdateAvailableHud"] = ("QiDock {0} çıktı · dock menüsünden güncelleyin", "QiDock {0} is out · update from the dock menu"),
+ ["UpdatePrompt"] = ("QiDock {0} çıktı (sizdeki {1}).\n\nİndirip yeniden başlatayım mı? Yaklaşık {2} MB; ayarlarınız ve sabitledikleriniz olduğu gibi kalır.", "QiDock {0} is out (you have {1}).\n\nDownload it and restart? About {2} MB; your settings and pins stay as they are."),
+ ["UpdateDownloading"] = ("Güncelleme indiriliyor… %{0}", "Downloading update… {0}%"),
+ ["DockKeysHint"] = ("Oklarla seçin, Enter ile açın, Esc ile çıkın", "Arrows to move, Enter to open, Esc to leave"),
["AppGridLoading"] = ("Uygulamalar yükleniyor…", "Loading apps…"),
["AppGridFolder"] = ("Klasör", "Folder"),
["AppGridNoMatch"] = ("Sonuç yok", "No results"),
@@ -499,6 +521,11 @@ public sealed class UiText : INotifyPropertyChanged
["AiUpdated"] = ("Güncelleme {0} · {1}", "Updated {0} · {1}"),
["AiSourceClaude"] = ("Claude Code oturumu", "Claude Code session"),
["AiSourceCodex"] = ("Codex kayıtları", "Codex logs"),
+ ["AiSourceGemini"] = ("Antigravity girişi", "Antigravity sign-in"),
+ ["AiSourceOpenCode"] = ("OpenCode konsolu", "OpenCode console"),
+ ["AiGeminiOthers"] = ("Claude · GPT", "Claude · GPT"),
+ ["AiGeminiExpired"] = ("Giriş yenilenemedi; terminalde agy yazıp giriş yapın.", "Couldn’t renew the sign-in; run agy in a terminal and sign in."),
+ ["AiOpenCodeExpired"] = ("Giriş süresi doldu; OpenCode’u açıp yeniden giriş yapın.", "The sign-in expired; open OpenCode and sign in again."),
["AiShortHM"] = ("{0}sa {1}dk", "{0}h {1}m"),
["AiShortM"] = ("{0}dk", "{0}m"),
["AiResetsShort"] = ("{0} sonra sıfırlanır", "resets in {0}"),
@@ -551,6 +578,10 @@ public sealed class UiText : INotifyPropertyChanged
["GenieEffect"] = ("Cin efekti", "Genie effect"),
["GenieEffectDescription"] = ("Pencere açılırken simgeden çıkar, küçültülürken simgeye akar.", "Windows pour out of and back into their dock icon."),
["Previews"] = ("Pencere önizlemeleri", "Window previews"),
+ ["NotchBrowserSetting"] = ("Üstten inen tarayıcı", "Browser from the top edge"),
+ ["DockGlassSetting"] = ("Cam görünüm", "Glass look"),
+ ["DockGlassSettingHelp"] = ("Dock, arkasındaki duvar kâğıdını buzlu cam gibi gösterir.", "The dock shows the wallpaper behind it as frosted glass."),
+ ["NotchBrowserSettingHelp"] = ("Fareyi ekranın en üstünde ortaya götürünce küçük bir tarayıcı aşağı iner.", "Resting the pointer at the middle of the top edge drops down a small browser."),
["PreviewsDescription"] = ("Simgenin üzerine geldiğinde açık pencereleri göster.", "Show open windows when you hover over an icon."),
["Badges"] = ("Bildirim göstergeleri", "Notification indicators"),
["BadgesDescription"] = ("Windows’un bildirdiği uyarıları simgelerde göster.", "Show alerts reported by Windows on application icons."),
diff --git a/Services/Updater.cs b/Services/Updater.cs
new file mode 100644
index 0000000..b3c2aa4
--- /dev/null
+++ b/Services/Updater.cs
@@ -0,0 +1,181 @@
+using System.IO;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Reflection;
+using System.Security.Cryptography;
+using System.Text.Json;
+using System.Windows;
+
+namespace QiDock.Services;
+
+/// <summary>
+/// Looks for a newer QiDock on GitHub and installs it in place: the new exe is downloaded next to the running one,
+/// checked against the SHA-256 GitHub publishes for it, swapped in, and QiDock restarts. One small request when asked,
+/// and at most one a day by itself; nothing keeps running in between.
+/// </summary>
+internal static class Updater
+{
+ private const string LatestRelease = "https://api.github.com/repos/qidock/qidock/releases/latest";
+
+ internal sealed record Release(Version Version, string Page, string Download, long Size, string? Sha256);
+
+ public static Version Current { get; } = Assembly.GetExecutingAssembly().GetName().Version is { } v ? new Version(v.Major, v.Minor, Math.Max(0, v.Build)) : new Version(0, 0, 0);
+
+ private static readonly HttpClient Http = CreateClient();
+
+ private static HttpClient CreateClient()
+ {
+ // A generic name only: nothing about the user goes with the request.
+ var client = new HttpClient { Timeout = TimeSpan.FromMinutes(10) };
+ client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("QiDock", Current.ToString()));
+ return client;
+ }
+
+ /// <summary>The newest release when it is newer than this copy; null when this copy is up to date.</summary>
+ public static async Task<Release?> CheckAsync(CancellationToken token = default)
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Get, LatestRelease);
+ request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));
+ using var response = await Http.SendAsync(request, token).ConfigureAwait(false);
+ response.EnsureSuccessStatusCode();
+ using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(token).ConfigureAwait(false));
+ var root = json.RootElement;
+ var tag = root.GetProperty("tag_name").GetString() ?? "";
+ if (!Version.TryParse(tag.TrimStart('v', 'V'), out var version)) return null;
+ version = new Version(version.Major, version.Minor, Math.Max(0, version.Build));
+ if (version <= Current) return null;
+ foreach (var asset in root.GetProperty("assets").EnumerateArray())
+ {
+ if (!string.Equals(asset.GetProperty("name").GetString(), "QiDock.exe", StringComparison.OrdinalIgnoreCase)) continue;
+ var digest = asset.TryGetProperty("digest", out var d) ? d.GetString() : null;
+ return new Release(
+ version,
+ root.GetProperty("html_url").GetString() ?? "",
+ asset.GetProperty("browser_download_url").GetString() ?? "",
+ asset.GetProperty("size").GetInt64(),
+ digest is not null && digest.StartsWith("sha256:", StringComparison.OrdinalIgnoreCase) ? digest[7..] : null);
+ }
+ return null;
+ }
+
+ /// <summary>Downloads, checks and swaps in the new exe; returns an error text, or null when QiDock can restart.</summary>
+ public static async Task<string?> InstallAsync(Release release, IProgress<int>? progress, CancellationToken token = default)
+ {
+ if (Environment.ProcessPath is not { } exe) return "QiDock'un dosyası bulunamadı.";
+ var download = exe + ".download";
+ var old = exe + ".old";
+ try
+ {
+ using (var response = await Http.GetAsync(release.Download, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false))
+ {
+ response.EnsureSuccessStatusCode();
+ await using var source = await response.Content.ReadAsStreamAsync(token).ConfigureAwait(false);
+ await using var target = new FileStream(download, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, useAsync: true);
+ var buffer = new byte[1 << 16];
+ long done = 0;
+ var lastPercent = -1;
+ int read;
+ while ((read = await source.ReadAsync(buffer, token).ConfigureAwait(false)) > 0)
+ {
+ await target.WriteAsync(buffer.AsMemory(0, read), token).ConfigureAwait(false);
+ done += read;
+ var percent = release.Size > 0 ? (int)(done * 100 / release.Size) : 0;
+ if (percent / 10 != lastPercent / 10)
+ {
+ lastPercent = percent;
+ progress?.Report(percent);
+ }
+ }
+ }
+ if (new FileInfo(download).Length != release.Size)
+ return Fail("İndirilen dosya eksik geldi.");
+ if (release.Sha256 is { } expected)
+ {
+ await using var check = File.OpenRead(download);
+ var actual = Convert.ToHexString(await SHA256.HashDataAsync(check, token).ConfigureAwait(false));
+ if (!string.Equals(actual, expected, StringComparison.OrdinalIgnoreCase))
+ return Fail("İndirilen dosya GitHub'daki ile aynı değil; güncelleme yapılmadı.");
+ }
+ // A running exe can be renamed but not overwritten: the old one steps aside and is deleted at the next start.
+ File.Move(exe, old, overwrite: true);
+ try
+ {
+ File.Move(download, exe);
+ }
+ catch
+ {
+ File.Move(old, exe);
+ throw;
+ }
+ return null;
+ }
+ catch (Exception ex) when (ex is HttpRequestException or IOException or UnauthorizedAccessException or TaskCanceledException)
+ {
+ return Fail("Güncelleme indirilemedi: " + ex.Message);
+ }
+
+ string Fail(string message)
+ {
+ try { File.Delete(download); }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
+ return message;
+ }
+ }
+
+ /// <summary>Deletes what the last update left behind (the old exe, a broken download).</summary>
+ public static void CleanUp()
+ {
+ if (Environment.ProcessPath is not { } exe) return;
+ foreach (var leftover in new[] { exe + ".old", exe + ".download" })
+ {
+ try { if (File.Exists(leftover)) File.Delete(leftover); }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
+ }
+ }
+
+ // ---- Once a day by itself ---------------------------------------------------------------------
+
+ private sealed class State
+ {
+ public DateTime LastCheck { get; set; }
+ public string? Announced { get; set; }
+ }
+
+ private static string StatePath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock", "update-check.json");
+
+ private static State LoadState()
+ {
+ try { return File.Exists(StatePath) ? JsonSerializer.Deserialize<State>(File.ReadAllText(StatePath)) ?? new() : new(); }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) { return new(); }
+ }
+
+ private static void SaveState(State state)
+ {
+ try
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(StatePath)!);
+ File.WriteAllText(StatePath, JsonSerializer.Serialize(state));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
+ }
+
+ /// <summary>
+ /// Checks quietly when the last check is more than a day old; a new version is announced once (a short card on
+ /// the dock), never installed without asking.
+ /// </summary>
+ public static async void CheckDaily(Action<Release> announce)
+ {
+ var state = LoadState();
+ if (DateTime.UtcNow - state.LastCheck < TimeSpan.FromDays(1)) return;
+ Release? release;
+ try { release = await CheckAsync(); }
+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException or KeyNotFoundException or InvalidOperationException) { return; }
+ state.LastCheck = DateTime.UtcNow;
+ if (release is not null && state.Announced != release.Version.ToString())
+ {
+ state.Announced = release.Version.ToString();
+ Application.Current?.Dispatcher.BeginInvoke(() => announce(release));
+ }
+ SaveState(state);
+ }
+}
diff --git a/Services/Widgets/AiUsageService.More.cs b/Services/Widgets/AiUsageService.More.cs
new file mode 100644
index 0000000..f526cde
--- /dev/null
+++ b/Services/Widgets/AiUsageService.More.cs
@@ -0,0 +1,401 @@
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Text.Json;
+
+namespace QiDock.Services.Widgets;
+
+/// <summary>
+/// Gemini (through the Antigravity CLI's sign-in) and OpenCode Go (through the OpenCode app's console sign-in).
+/// Both sign-ins are only read from where their own app keeps them and sent to their own provider; nothing is stored.
+/// </summary>
+public sealed partial class AiUsageService
+{
+ public const string GeminiId = "gemini";
+ public const string OpenCodeId = "opencode";
+
+ private static readonly TimeSpan OtherMinimumInterval = TimeSpan.FromMinutes(2);
+
+ // ---- Gemini (Antigravity) ----------------------------------------------------------------
+
+ private const string CodeAssist = "https://daily-cloudcode-pa.googleapis.com/v1internal:";
+ private ProviderUsage? _gemini;
+ private DateTime _geminiFetchedAt = DateTime.MinValue;
+ private string? _geminiProject, _geminiPlan;
+ private static DateTime _agyRenewedAt = DateTime.MinValue;
+
+ private static string AgyPath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "agy", "bin", "agy.exe");
+
+ private async Task<ProviderUsage?> GetGeminiAsync(CancellationToken token)
+ {
+ var now = DateTime.Now;
+ if (_gemini is not null && now - _geminiFetchedAt < OtherMinimumInterval) return _gemini;
+ var signIn = ReadAntigravitySignIn();
+ if (signIn is null)
+ {
+ if (_gemini is null && File.Exists(AgyPath)) AppLog.Write("Gemini: Antigravity girişi bulunamadı");
+ return null;
+ }
+ var (accessToken, expiresAt) = signIn.Value;
+ // The sign-in lasts an hour; Antigravity renews it whenever it runs, so a short "agy models" does it here.
+ if (expiresAt <= now.AddMinutes(1))
+ {
+ if (now - _agyRenewedAt > TimeSpan.FromMinutes(30) && File.Exists(AgyPath))
+ {
+ _agyRenewedAt = now;
+ await RenewAntigravityAsync(token).ConfigureAwait(false);
+ if (ReadAntigravitySignIn() is { } renewed) (accessToken, expiresAt) = renewed;
+ }
+ if (expiresAt <= now.AddMinutes(1)) return KeepGemini(now, UiText.Get("AiGeminiExpired"));
+ }
+
+ try
+ {
+ if (_geminiProject is null)
+ {
+ using var load = await PostCodeAssistAsync("loadCodeAssist", """{"metadata":{"ideType":"ANTIGRAVITY","pluginType":"GEMINI"}}""", accessToken, token).ConfigureAwait(false);
+ if (load.RootElement.TryGetProperty("cloudaicompanionProject", out var project))
+ _geminiProject = project.ValueKind == JsonValueKind.String ? project.GetString()
+ : project.ValueKind == JsonValueKind.Object && project.TryGetProperty("id", out var id) ? id.GetString() : null;
+ _geminiPlan = TierName(load.RootElement, "paidTier") ?? TierName(load.RootElement, "currentTier");
+ }
+ using var quota = await PostCodeAssistAsync("retrieveUserQuota", JsonSerializer.Serialize(new { project = _geminiProject }), accessToken, token).ConfigureAwait(false);
+ var windows = ReadGeminiBuckets(quota.RootElement);
+ _gemini = new ProviderUsage(GeminiId, "Gemini", _geminiPlan, windows, now, null);
+ _geminiFetchedAt = now;
+ return _gemini;
+ }
+ catch (OperationCanceledException) when (token.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
+ {
+ return KeepGemini(now, UiText.Get("AiGeminiExpired"));
+ }
+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException or InvalidOperationException or KeyNotFoundException)
+ {
+ AppLog.Write($"Gemini kullanımı okunamadı: {ex.GetType().Name} {(ex as HttpRequestException)?.StatusCode}");
+ return KeepGemini(now, UiText.Get("AiFetchError"));
+ }
+ }
+
+ private ProviderUsage KeepGemini(DateTime now, string error)
+ {
+ _gemini = new ProviderUsage(GeminiId, "Gemini", _geminiPlan, _gemini?.Windows ?? [], now, error);
+ _geminiFetchedAt = now;
+ return _gemini;
+ }
+
+ private static string? TierName(JsonElement root, string property)
+ {
+ if (!root.TryGetProperty(property, out var tier) || tier.ValueKind != JsonValueKind.Object) return null;
+ var id = tier.TryGetProperty("id", out var i) && i.ValueKind == JsonValueKind.String ? i.GetString() ?? "" : "";
+ if (id.Contains("ultra", StringComparison.OrdinalIgnoreCase)) return "AI Ultra";
+ if (id.Contains("pro", StringComparison.OrdinalIgnoreCase)) return "AI Pro";
+ return tier.TryGetProperty("name", out var n) && n.ValueKind == JsonValueKind.String ? n.GetString() : null;
+ }
+
+ private static async Task<JsonDocument> PostCodeAssistAsync(string method, string body, string accessToken, CancellationToken token)
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Post, CodeAssist + method)
+ {
+ Content = new StringContent(body, Encoding.UTF8, "application/json")
+ };
+ request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
+ // The service answers only Antigravity's own client (anything else gets "no valid licence"); this is its sign-in.
+ request.Headers.UserAgent.ParseAdd("antigravity");
+ using var response = await WidgetHttp.Client.SendAsync(request, token).ConfigureAwait(false);
+ response.EnsureSuccessStatusCode();
+ await using var stream = await response.Content.ReadAsStreamAsync(token).ConfigureAwait(false);
+ return await JsonDocument.ParseAsync(stream, cancellationToken: token).ConfigureAwait(false);
+ }
+
+ /// <summary>
+ /// Each model has its own five-hour allowance; the tile shows the most used Gemini model and the most used of the
+ /// others Antigravity offers (Claude, GPT-OSS). A spent allowance comes without "remainingFraction" (zero is left out).
+ /// </summary>
+ private static List<UsageWindow> ReadGeminiBuckets(JsonElement root)
+ {
+ (double Used, DateTime? Reset)? gemini = null, other = null;
+ if (root.TryGetProperty("buckets", out var buckets) && buckets.ValueKind == JsonValueKind.Array)
+ foreach (var bucket in buckets.EnumerateArray())
+ {
+ var model = bucket.TryGetProperty("modelId", out var m) && m.ValueKind == JsonValueKind.String ? m.GetString() ?? "" : "";
+ if (model.Length == 0 || model.StartsWith("tab_", StringComparison.Ordinal)) continue;
+ if (!bucket.TryGetProperty("resetTime", out var r) || r.ValueKind != JsonValueKind.String
+ || !DateTimeOffset.TryParse(r.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.None, out var reset)) continue;
+ var left = bucket.TryGetProperty("remainingFraction", out var f) && f.ValueKind == JsonValueKind.Number ? f.GetDouble() : 0;
+ var used = Math.Clamp((1 - left) * 100, 0, 100);
+ ref var slot = ref model.StartsWith("gemini", StringComparison.OrdinalIgnoreCase) ? ref gemini : ref other;
+ if (slot is null || used > slot.Value.Used) slot = (used, reset.LocalDateTime);
+ }
+ var windows = new List<UsageWindow>();
+ if (gemini is { } g) windows.Add(new UsageWindow("Gemini", g.Used, g.Reset, TimeSpan.FromHours(5), "gemini"));
+ if (other is { } o) windows.Add(new UsageWindow(UiText.Get("AiGeminiOthers"), o.Used, o.Reset, TimeSpan.FromHours(5), "others"));
+ return windows;
+ }
+
+ private static async Task RenewAntigravityAsync(CancellationToken token)
+ {
+ try
+ {
+ using var process = Process.Start(new ProcessStartInfo(AgyPath, "models")
+ {
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ WorkingDirectory = Path.GetTempPath()
+ });
+ if (process is null) return;
+ _ = process.StandardOutput.ReadToEndAsync(token);
+ _ = process.StandardError.ReadToEndAsync(token);
+ using var limit = CancellationTokenSource.CreateLinkedTokenSource(token);
+ limit.CancelAfter(TimeSpan.FromSeconds(25));
+ try { await process.WaitForExitAsync(limit.Token).ConfigureAwait(false); }
+ catch (OperationCanceledException)
+ {
+ try { process.Kill(true); } catch (InvalidOperationException) { }
+ }
+ }
+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException or IOException)
+ {
+ Trace.TraceWarning("Antigravity sign-in not renewed: {0}", ex.Message);
+ }
+ }
+
+ /// <summary>Antigravity keeps its Google sign-in in Windows Credential Manager under "gemini:antigravity".</summary>
+ private static (string AccessToken, DateTime ExpiresAt)? ReadAntigravitySignIn()
+ {
+ var blob = Credentials.Read("gemini:antigravity");
+ if (blob is null) return null;
+ try
+ {
+ using var json = JsonDocument.Parse(blob);
+ if (!json.RootElement.TryGetProperty("token", out var t) || t.ValueKind != JsonValueKind.Object) return null;
+ var access = t.TryGetProperty("access_token", out var a) && a.ValueKind == JsonValueKind.String ? a.GetString() : null;
+ if (string.IsNullOrEmpty(access)) return null;
+ var expires = t.TryGetProperty("expiry", out var e) && e.ValueKind == JsonValueKind.String
+ && DateTimeOffset.TryParse(e.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.None, out var at) ? at.LocalDateTime : DateTime.MinValue;
+ return (access, expires);
+ }
+ catch (JsonException)
+ {
+ return null;
+ }
+ }
+
+ private static class Credentials
+ {
+ [StructLayout(LayoutKind.Sequential)]
+ private struct Credential
+ {
+ public int Flags, Type;
+ public IntPtr TargetName, Comment;
+ public long LastWritten;
+ public int BlobSize;
+ public IntPtr Blob;
+ public int Persist, AttributeCount;
+ public IntPtr Attributes, TargetAlias, UserName;
+ }
+
+ [DllImport("advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool CredRead(string target, int type, int flags, out IntPtr credential);
+
+ [DllImport("advapi32.dll", EntryPoint = "CredFree")]
+ private static extern void CredFree(IntPtr buffer);
+
+ public static string? Read(string target)
+ {
+ if (!CredRead(target, 1, 0, out var pointer)) return null;
+ try
+ {
+ var credential = Marshal.PtrToStructure<Credential>(pointer);
+ if (credential.BlobSize <= 0 || credential.Blob == IntPtr.Zero) return null;
+ var bytes = new byte[credential.BlobSize];
+ Marshal.Copy(credential.Blob, bytes, 0, bytes.Length);
+ return Encoding.UTF8.GetString(bytes);
+ }
+ finally
+ {
+ CredFree(pointer);
+ }
+ }
+ }
+
+ // ---- OpenCode Go -------------------------------------------------------------------------
+
+ private ProviderUsage? _openCode;
+ private DateTime _openCodeFetchedAt = DateTime.MinValue;
+
+ private static string OpenCodeDatabase => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share", "opencode", "opencode.db");
+
+ private async Task<ProviderUsage?> GetOpenCodeAsync(CancellationToken token)
+ {
+ var now = DateTime.Now;
+ if (_openCode is not null && now - _openCodeFetchedAt < OtherMinimumInterval) return _openCode;
+ var signIn = await Task.Run(ReadOpenCodeSignIn, token).ConfigureAwait(false);
+ if (signIn is null) return null;
+ var (access, expiresAt, server, org) = signIn.Value;
+ if (expiresAt <= now) return KeepOpenCode(now, UiText.Get("AiOpenCodeExpired"));
+ try
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Get, server.TrimEnd('/') + "/api/go/status");
+ request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", access);
+ if (!string.IsNullOrEmpty(org)) request.Headers.Add("x-org-id", org);
+ using var response = await WidgetHttp.Client.SendAsync(request, token).ConfigureAwait(false);
+ if (response.StatusCode == HttpStatusCode.NotFound) return null; // no Go subscription
+ if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) return KeepOpenCode(now, UiText.Get("AiOpenCodeExpired"));
+ response.EnsureSuccessStatusCode();
+ await using var stream = await response.Content.ReadAsStreamAsync(token).ConfigureAwait(false);
+ using var json = await JsonDocument.ParseAsync(stream, cancellationToken: token).ConfigureAwait(false);
+ var windows = new List<UsageWindow>();
+ if (json.RootElement.TryGetProperty("access", out var accessInfo) && accessInfo.ValueKind == JsonValueKind.Object
+ && accessInfo.TryGetProperty("meters", out var meters) && meters.ValueKind == JsonValueKind.Object)
+ {
+ AddMeter(meters, "fiveHour", UiText.Format("AiHoursWindow", 5), TimeSpan.FromHours(5), "session", windows, now);
+ AddMeter(meters, "week", UiText.Get("AiWeekly"), TimeSpan.FromDays(7), "weekly", windows, now);
+ AddMeter(meters, "month", UiText.Get("AiMonthly"), TimeSpan.FromDays(30), "monthly", windows, now);
+ }
+ _openCode = new ProviderUsage(OpenCodeId, "OpenCode", "Go", windows, now, null);
+ _openCodeFetchedAt = now;
+ return _openCode;
+ }
+ catch (OperationCanceledException) when (token.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException or InvalidOperationException or FormatException)
+ {
+ AppLog.Write($"OpenCode kullanımı okunamadı: {ex.GetType().Name} {(ex as HttpRequestException)?.StatusCode}");
+ return KeepOpenCode(now, UiText.Get("AiFetchError"));
+ }
+ }
+
+ private ProviderUsage KeepOpenCode(DateTime now, string error)
+ {
+ _openCode = new ProviderUsage(OpenCodeId, "OpenCode", "Go", _openCode?.Windows ?? [], now, error);
+ _openCodeFetchedAt = now;
+ return _openCode;
+ }
+
+ private static double Number(JsonElement value) => value.ValueKind switch
+ {
+ JsonValueKind.Number => value.GetDouble(),
+ JsonValueKind.String => double.Parse(value.GetString()!, CultureInfo.InvariantCulture),
+ _ => 0
+ };
+
+ /// <summary>A meter in millionths of a cent; a five-hour window that has run out starts again on the next use.</summary>
+ private static void AddMeter(JsonElement meters, string property, string label, TimeSpan length, string key, List<UsageWindow> windows, DateTime now)
+ {
+ if (!meters.TryGetProperty(property, out var meter) || meter.ValueKind != JsonValueKind.Object) return;
+ var limit = meter.TryGetProperty("limitMicroCents", out var l) ? Number(l) : 0;
+ if (limit <= 0) return;
+ var used = meter.TryGetProperty("usedMicroCents", out var u) ? Number(u) : 0;
+ DateTime? reset = meter.TryGetProperty("resetsAt", out var r) && r.ValueKind == JsonValueKind.String
+ && DateTimeOffset.TryParse(r.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.None, out var at) ? at.LocalDateTime : null;
+ if (reset is { } passed && passed <= now) (used, reset) = (0, null);
+ windows.Add(new UsageWindow(label, Math.Clamp(used / limit * 100, 0, 100), reset, length, key));
+ }
+
+ /// <summary>The OpenCode app's console sign-in, kept in its own database (read-only, through Windows' SQLite).</summary>
+ private static (string Access, DateTime ExpiresAt, string Server, string? Org)? ReadOpenCodeSignIn()
+ {
+ if (!File.Exists(OpenCodeDatabase)) return null;
+ var value = Sqlite.ReadText(OpenCodeDatabase, "SELECT value FROM credential WHERE integration_id = 'opencode' ORDER BY active DESC, time_updated DESC LIMIT 1");
+ if (value is null) return null;
+ try
+ {
+ using var json = JsonDocument.Parse(value);
+ var root = json.RootElement;
+ var access = root.TryGetProperty("access", out var a) && a.ValueKind == JsonValueKind.String ? a.GetString() : null;
+ if (string.IsNullOrEmpty(access)) return null;
+ var expires = root.TryGetProperty("expires", out var e) && e.ValueKind == JsonValueKind.Number
+ ? DateTimeOffset.FromUnixTimeMilliseconds(e.GetInt64()).LocalDateTime : DateTime.MaxValue;
+ string server = "https://opencode.ai/console";
+ string? org = null;
+ if (root.TryGetProperty("metadata", out var metadata) && metadata.ValueKind == JsonValueKind.Object)
+ {
+ if (metadata.TryGetProperty("server", out var s) && s.ValueKind == JsonValueKind.String
+ && Uri.TryCreate(s.GetString(), UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps && uri.Host.EndsWith("opencode.ai", StringComparison.OrdinalIgnoreCase))
+ server = uri.ToString();
+ if (metadata.TryGetProperty("orgID", out var o) && o.ValueKind == JsonValueKind.String) org = o.GetString();
+ }
+ return (access, expires, server, org);
+ }
+ catch (JsonException)
+ {
+ return null;
+ }
+ }
+
+ /// <summary>The SQLite that ships with Windows (winsqlite3.dll), so reading one value adds nothing to QiDock.</summary>
+ private static class Sqlite
+ {
+ private const int OpenReadOnly = 0x1, Row = 100;
+
+ [DllImport("winsqlite3.dll", EntryPoint = "sqlite3_open_v2")]
+ private static extern int Open(byte[] path, out IntPtr db, int flags, IntPtr vfs);
+
+ [DllImport("winsqlite3.dll", EntryPoint = "sqlite3_busy_timeout")]
+ private static extern int BusyTimeout(IntPtr db, int milliseconds);
+
+ [DllImport("winsqlite3.dll", EntryPoint = "sqlite3_prepare_v2")]
+ private static extern int Prepare(IntPtr db, byte[] sql, int length, out IntPtr statement, IntPtr tail);
+
+ [DllImport("winsqlite3.dll", EntryPoint = "sqlite3_step")]
+ private static extern int Step(IntPtr statement);
+
+ [DllImport("winsqlite3.dll", EntryPoint = "sqlite3_column_text")]
+ private static extern IntPtr ColumnText(IntPtr statement, int column);
+
+ [DllImport("winsqlite3.dll", EntryPoint = "sqlite3_finalize")]
+ private static extern int Finalize(IntPtr statement);
+
+ [DllImport("winsqlite3.dll", EntryPoint = "sqlite3_close")]
+ private static extern int Close(IntPtr db);
+
+ private static byte[] Utf8(string text) => Encoding.UTF8.GetBytes(text + '\u0000'.ToString()); // C strings end in a zero byte
+
+ public static string? ReadText(string path, string sql)
+ {
+ try
+ {
+ if (Open(Utf8(path), out var db, OpenReadOnly, IntPtr.Zero) != 0)
+ {
+ if (db != IntPtr.Zero) Close(db);
+ return null;
+ }
+ try
+ {
+ BusyTimeout(db, 2000);
+ if (Prepare(db, Utf8(sql), -1, out var statement, IntPtr.Zero) != 0) return null;
+ try
+ {
+ return Step(statement) == Row ? Marshal.PtrToStringUTF8(ColumnText(statement, 0)) : null;
+ }
+ finally
+ {
+ Finalize(statement);
+ }
+ }
+ finally
+ {
+ Close(db);
+ }
+ }
+ catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException)
+ {
+ return null;
+ }
+ }
+ }
+}
diff --git a/Services/Widgets/AiUsageService.cs b/Services/Widgets/AiUsageService.cs
index 4d6fa79..c24e652 100644
--- a/Services/Widgets/AiUsageService.cs
+++ b/Services/Widgets/AiUsageService.cs
@@ -30,7 +30,7 @@ public sealed record ProviderUsage(
/// ChatGPT: reads the latest rate-limit snapshot Codex CLI writes into its local session logs (no network).
/// Tokens are only read from disk and sent to their own provider; they are never stored or logged.
/// </summary>
-public sealed class AiUsageService
+public sealed partial class AiUsageService
{
public const string ClaudeId = "claude";
public const string CodexId = "chatgpt";
@@ -44,6 +44,8 @@ public sealed class AiUsageService
{
Cached = LastKnown();
_claude = Cached.FirstOrDefault(u => u.Provider == ClaudeId);
+ _gemini = Cached.FirstOrDefault(u => u.Provider == GeminiId);
+ _openCode = Cached.FirstOrDefault(u => u.Provider == OpenCodeId);
}
/// <summary>
@@ -59,6 +61,10 @@ public sealed class AiUsageService
if (claude is not null) results.Add(claude);
var codex = await Task.Run(ReadCodex, token).ConfigureAwait(false);
if (codex is not null) results.Add(codex);
+ var gemini = GetGeminiAsync(token);
+ var openCode = GetOpenCodeAsync(token);
+ if (await gemini.ConfigureAwait(false) is { } g) results.Add(g);
+ if (await openCode.ConfigureAwait(false) is { } o) results.Add(o);
SaveLastKnown(results);
return results;
}
diff --git a/Services/Widgets/BluetoothBatteries.cs b/Services/Widgets/BluetoothBatteries.cs
new file mode 100644
index 0000000..b91e555
--- /dev/null
+++ b/Services/Widgets/BluetoothBatteries.cs
@@ -0,0 +1,78 @@
+using System.Text.RegularExpressions;
+using Windows.Devices.Bluetooth;
+using Windows.Devices.Enumeration;
+
+namespace QiDock.Services.Widgets;
+
+/// <param name="Kind">"mouse", "keyboard", "headphones" or "other", guessed from the name.</param>
+public sealed record DeviceBattery(string Name, int Percent, string Kind);
+
+/// <summary>
+/// The battery level Windows keeps for connected Bluetooth devices (mice, keyboards, headphones), the same number the
+/// Bluetooth settings page shows. Read on request only: two short device queries, no background work.
+/// </summary>
+public static partial class BluetoothBatteries
+{
+ private const string BatteryKey = "{104EA319-6EE2-4701-BD47-8DDBF425BBE5} 2";
+ private const string InstanceKey = "System.Devices.DeviceInstanceId";
+ private const string LastConnectedKey = "{2BD67D8B-8BEB-48D5-87E0-6CDA3428040A} 11";
+
+ /// <summary>A Bluetooth mouse drops its link while it sleeps; one used in the last hours still counts.</summary>
+ private static readonly TimeSpan Recent = TimeSpan.FromHours(12);
+ private const string BluetoothClass = "System.Devices.ClassGuid:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\"";
+
+ public static async Task<IReadOnlyList<DeviceBattery>> ReadAsync()
+ {
+ // Windows also keeps the last level of devices paired long ago; only those connected now (or lately) are shown.
+ var connected = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+ foreach (var selector in new[]
+ {
+ BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected),
+ BluetoothDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected)
+ })
+ {
+ foreach (var device in await DeviceInformation.FindAllAsync(selector))
+ if (AddressOfId(device.Id) is { } address) connected.Add(address);
+ }
+ var found = new Dictionary<string, DeviceBattery>(StringComparer.OrdinalIgnoreCase);
+ var nodes = await DeviceInformation.FindAllAsync(BluetoothClass, [BatteryKey, InstanceKey, LastConnectedKey], DeviceInformationKind.Device);
+ foreach (var node in nodes)
+ {
+ if (!node.Properties.TryGetValue(BatteryKey, out var level) || level is not byte percent) continue;
+ if (!node.Properties.TryGetValue(InstanceKey, out var instance) || instance is not string id) continue;
+ if (AddressOfInstance(id) is not { } address || found.ContainsKey(address)) continue;
+ var recent = node.Properties.TryGetValue(LastConnectedKey, out var last) && last is DateTimeOffset when && DateTimeOffset.Now - when < Recent;
+ if (!connected.Contains(address) && !recent) continue;
+ var name = string.IsNullOrWhiteSpace(node.Name) ? "Bluetooth" : node.Name.Trim();
+ found[address] = new DeviceBattery(name, Math.Clamp((int)percent, 0, 100), KindOf(name, id));
+ }
+ return found.Values.OrderBy(d => d.Kind switch { "mouse" => 0, "keyboard" => 1, "headphones" => 2, _ => 3 }).ThenBy(d => d.Name).ToList();
+ }
+
+ /// <summary>"BluetoothLE#BluetoothLE00:11:…-ed:de:c1:01:98:3d" → "EDDEC101983D".</summary>
+ private static string? AddressOfId(string id)
+ {
+ var dash = id.LastIndexOf('-');
+ if (dash < 0) return null;
+ var address = id[(dash + 1)..].Replace(":", "");
+ return address.Length == 12 ? address.ToUpperInvariant() : null;
+ }
+
+ /// <summary>"BTHLE\DEV_EDDEC101983D\…" or "BTHENUM\{…}_…\7&amp;…&amp;0&amp;E65D27240913_C00000000" → the address.</summary>
+ private static string? AddressOfInstance(string instance) =>
+ AddressPattern().Match(instance) is { Success: true } match ? match.Groups[1].Value.ToUpperInvariant() : null;
+
+ [GeneratedRegex(@"(?:DEV_|&)([0-9A-Fa-f]{12})(?:\\|_|$)")]
+ private static partial Regex AddressPattern();
+
+ private static string KindOf(string name, string instance)
+ {
+ var lower = name.ToLowerInvariant();
+ if (lower.Contains("mouse") || lower.Contains("fare") || lower.Contains("mx master") || lower.Contains("mx anywhere")) return "mouse";
+ if (lower.Contains("key") || lower.Contains("klavye")) return "keyboard";
+ if (lower.Contains("bud") || lower.Contains("pod") || lower.Contains("phone") || lower.Contains("kulaklık") || lower.Contains("headset")
+ || lower.Contains("wh-") || lower.Contains("wf-") || lower.Contains("jbl") || lower.Contains("beats")) return "headphones";
+ // Classic Bluetooth devices that report a level are almost always headsets (the hands-free profile carries it).
+ return instance.StartsWith("BTHENUM", StringComparison.OrdinalIgnoreCase) ? "headphones" : "other";
+ }
+}
diff --git a/Services/Widgets/BrowserPlaylist.cs b/Services/Widgets/BrowserPlaylist.cs
new file mode 100644
index 0000000..5c112b9
--- /dev/null
+++ b/Services/Widgets/BrowserPlaylist.cs
@@ -0,0 +1,173 @@
+using System.Runtime.InteropServices;
+using System.Text.RegularExpressions;
+using System.Windows.Automation;
+
+namespace QiDock.Services.Widgets;
+
+/// <summary>A song in the list a browser shows beside the video (a YouTube mix or playlist).</summary>
+internal sealed record PlaylistSong(string VideoId, int Index, string Title, string Channel, bool Current, AutomationElement Link)
+{
+ /// <summary>YouTube's small picture of the video (320 × 180).</summary>
+ public Uri Thumbnail => new($"https://i.ytimg.com/vi/{VideoId}/mqdefault.jpg");
+}
+
+/// <summary>What could be read: the songs, or (when there are none) a YouTube tab that is not in front.</summary>
+internal sealed record PlaylistView(IReadOnlyList<PlaylistSong> Songs, AutomationElement? HiddenTab);
+
+/// <summary>
+/// Reads the list of songs beside a YouTube video in Chrome (or another Chromium browser) through Windows' screen
+/// reader interface, the way a screen reader would; Windows does not tell other apps a player's queue. A browser
+/// shows the page of the tab in front only, so a YouTube tab behind another tab can be brought forward first.
+/// Everything here runs on a worker thread and only when the music card's back is open.
+/// </summary>
+internal static partial class BrowserPlaylist
+{
+ private static readonly Condition Windows = new PropertyCondition(AutomationElement.ClassNameProperty, "Chrome_WidgetWin_1");
+ private static readonly Condition Links = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Hyperlink);
+ private static readonly Condition Texts = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text);
+ private static readonly Condition Tabs = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TabItem);
+ private static readonly Condition Fields = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit);
+
+ /// <summary>Whether the player is a Chromium browser (the only kind whose list can be read).</summary>
+ public static bool IsBrowser(string? appId) =>
+ appId is not null && (appId.Contains("chrome", StringComparison.OrdinalIgnoreCase) || appId.Contains("msedge", StringComparison.OrdinalIgnoreCase)
+ || appId.Contains("brave", StringComparison.OrdinalIgnoreCase) || appId.Contains("vivaldi", StringComparison.OrdinalIgnoreCase)
+ || appId.Contains("opera", StringComparison.OrdinalIgnoreCase));
+
+ public static Task<PlaylistView> ReadAsync(string nowTitle) => Task.Run(() => Read(nowTitle));
+
+ /// <summary>Plays a song of the list: the same as clicking it in the browser.</summary>
+ public static Task<bool> PlayAsync(PlaylistSong song) => Task.Run(() => Try(() =>
+ {
+ if (!song.Link.TryGetCurrentPattern(InvokePattern.Pattern, out var pattern)) return false;
+ ((InvokePattern)pattern).Invoke();
+ return true;
+ }));
+
+ /// <summary>Brings a browser tab to the front of its window (the window itself stays where it is).</summary>
+ public static Task<bool> ShowTabAsync(AutomationElement tab) => Task.Run(() => Try(() =>
+ {
+ if (tab.TryGetCurrentPattern(SelectionItemPattern.Pattern, out var select))
+ {
+ ((SelectionItemPattern)select).Select();
+ return true;
+ }
+ if (!tab.TryGetCurrentPattern(InvokePattern.Pattern, out var invoke)) return false;
+ ((InvokePattern)invoke).Invoke();
+ return true;
+ }));
+
+ private static PlaylistView Read(string nowTitle)
+ {
+ AutomationElement? hidden = null;
+ Try(() =>
+ {
+ foreach (AutomationElement window in AutomationElement.RootElement.FindAll(TreeScope.Children, Windows))
+ {
+ var name = Try(() => window.Current.Name) ?? "";
+ if (name.Contains("YouTube", StringComparison.OrdinalIgnoreCase))
+ {
+ var songs = Try(() => Songs(window, nowTitle)) ?? [];
+ if (songs.Count > 0) return new PlaylistView(songs, null);
+ }
+ else
+ {
+ hidden ??= Try(() => YouTubeTab(window, nowTitle));
+ }
+ }
+ return null;
+ }, out var found);
+ return found ?? new PlaylistView([], hidden);
+ }
+
+ private static List<PlaylistSong> Songs(AutomationElement window, string nowTitle)
+ {
+ var current = CurrentVideo(window);
+ var byIndex = new SortedDictionary<int, (string Id, string Title, string Channel, AutomationElement Link)>();
+ foreach (AutomationElement link in window.FindAll(TreeScope.Descendants, Links))
+ {
+ var url = link.TryGetCurrentPattern(ValuePattern.Pattern, out var value) ? ((ValuePattern)value).Current.Value : "";
+ if (!url.Contains("/watch?", StringComparison.Ordinal) || !url.Contains("list=", StringComparison.Ordinal)) continue;
+ var query = Query(url);
+ if (!query.TryGetValue("v", out var id) || !query.TryGetValue("index", out var indexText) || !int.TryParse(indexText, out var index)) continue;
+ if (byIndex.ContainsKey(index)) continue;
+ var label = link.Current.Name ?? "";
+ if (label.Contains("SHIFT", StringComparison.OrdinalIgnoreCase)) continue; // the player's "next" button
+ var (title, channel) = Words(link, label);
+ if (title.Length > 0) byIndex[index] = (id, title, channel, link);
+ }
+ var anyCurrent = current is not null && byIndex.Values.Any(s => s.Id == current);
+ return byIndex.Select(pair => new PlaylistSong(pair.Value.Id, pair.Key, pair.Value.Title, pair.Value.Channel,
+ anyCurrent ? pair.Value.Id == current : string.Equals(pair.Value.Title, nowTitle, StringComparison.OrdinalIgnoreCase), pair.Value.Link)).ToList();
+ }
+
+ /// <summary>The title and the channel of a list entry: its first two texts that are not a number or a duration.</summary>
+ private static (string Title, string Channel) Words(AutomationElement link, string label)
+ {
+ var words = new List<string>();
+ foreach (AutomationElement text in link.FindAll(TreeScope.Descendants, Texts))
+ {
+ var word = (text.Current.Name ?? "").Trim();
+ if (word.Length == 0 || Counter().IsMatch(word) || words.Contains(word)) continue;
+ words.Add(word);
+ if (words.Count == 2) break;
+ }
+ return words.Count switch
+ {
+ 0 => (label.Trim(), ""),
+ 1 => (words[0], ""),
+ _ => (words[0], words[1])
+ };
+ }
+
+ /// <summary>The video in the address bar of the window, the one playing.</summary>
+ private static string? CurrentVideo(AutomationElement window)
+ {
+ var field = window.FindFirst(TreeScope.Descendants, Fields);
+ if (field is null || !field.TryGetCurrentPattern(ValuePattern.Pattern, out var value)) return null;
+ return Query(((ValuePattern)value).Current.Value).GetValueOrDefault("v");
+ }
+
+ /// <summary>A YouTube tab of the window, the one playing this song if it can be told.</summary>
+ private static AutomationElement? YouTubeTab(AutomationElement window, string nowTitle)
+ {
+ AutomationElement? any = null;
+ foreach (AutomationElement tab in window.FindAll(TreeScope.Descendants, Tabs))
+ {
+ var name = tab.Current.Name ?? "";
+ if (!name.Contains("YouTube", StringComparison.OrdinalIgnoreCase)) continue;
+ if (nowTitle.Length > 0 && name.Contains(nowTitle, StringComparison.OrdinalIgnoreCase)) return tab;
+ any ??= tab;
+ }
+ return any;
+ }
+
+ private static Dictionary<string, string> Query(string url)
+ {
+ var result = new Dictionary<string, string>(StringComparer.Ordinal);
+ var start = url.IndexOf('?');
+ if (start < 0) return result;
+ var end = url.IndexOf('#', start);
+ foreach (var part in url[(start + 1)..(end < 0 ? url.Length : end)].Split('&', StringSplitOptions.RemoveEmptyEntries))
+ {
+ var equals = part.IndexOf('=');
+ if (equals > 0) result.TryAdd(part[..equals], Uri.UnescapeDataString(part[(equals + 1)..]));
+ }
+ return result;
+ }
+
+ [GeneratedRegex(@"^[\d\s:.,•▶►|/-]+$")]
+ private static partial Regex Counter();
+
+ // The browser can close a tab or change the page at any moment; then there is simply nothing to read.
+ private static T? Try<T>(Func<T> read)
+ {
+ try { return read(); }
+ catch (Exception ex) when (ex is ElementNotAvailableException or InvalidOperationException or COMException or ArgumentException or TimeoutException)
+ {
+ return default;
+ }
+ }
+
+ private static void Try<T>(Func<T?> read, out T? result) where T : class => result = Try(read);
+}
diff --git a/Services/Widgets/CpuTop.cs b/Services/Widgets/CpuTop.cs
new file mode 100644
index 0000000..a8373b9
--- /dev/null
+++ b/Services/Widgets/CpuTop.cs
@@ -0,0 +1,109 @@
+using System.ComponentModel;
+using System.Diagnostics;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace QiDock.Services.Widgets;
+
+/// <summary>One program's share of the processor (all its processes together, e.g. every Chrome tab).</summary>
+internal sealed record CpuUser(string Name, string? Path, double Percent);
+
+/// <summary>
+/// Which programs use the processor most: each sample compares every process's processor time with the previous
+/// sample. Only read while someone shows it (the upright CPU widget), every few seconds.
+/// </summary>
+internal static class CpuTop
+{
+ private static readonly Dictionary<int, TimeSpan> Previous = [];
+ private static readonly Dictionary<string, (string Name, string? Path)> Names = new(StringComparer.OrdinalIgnoreCase);
+ private static DateTime _previousAt;
+
+ /// <summary>The busiest programs since the last call (empty on the first call, which only takes the baseline).</summary>
+ public static IReadOnlyList<CpuUser> Sample(int count)
+ {
+ var now = DateTime.UtcNow;
+ var elapsed = (now - _previousAt).TotalMilliseconds;
+ var first = _previousAt == default || elapsed > 30000;
+ _previousAt = now;
+ var totals = new Dictionary<string, (double Ms, int Pid)>(StringComparer.OrdinalIgnoreCase);
+ var seen = new HashSet<int>();
+ foreach (var process in Process.GetProcesses())
+ {
+ using (process)
+ {
+ if (process.Id is 0 or 4) continue; // idle and the kernel
+ TimeSpan time;
+ try { time = process.TotalProcessorTime; }
+ catch (Exception ex) when (ex is Win32Exception or InvalidOperationException or NotSupportedException) { continue; }
+ seen.Add(process.Id);
+ var before = Previous.TryGetValue(process.Id, out var last) ? last : time;
+ Previous[process.Id] = time;
+ if (first) continue;
+ var used = (time - before).TotalMilliseconds;
+ if (used <= 0) continue;
+ var key = process.ProcessName;
+ totals[key] = totals.TryGetValue(key, out var sum) ? (sum.Ms + used, sum.Pid) : (used, process.Id);
+ }
+ }
+ foreach (var gone in Previous.Keys.Where(id => !seen.Contains(id)).ToList()) Previous.Remove(gone);
+ if (first || elapsed <= 0) return [];
+ var capacity = elapsed * Environment.ProcessorCount;
+ return totals
+ .OrderByDescending(t => t.Value.Ms)
+ .Take(count)
+ .Select(t =>
+ {
+ var (name, path) = Describe(t.Key, t.Value.Pid);
+ return new CpuUser(name, path, Math.Min(100, t.Value.Ms / capacity * 100));
+ })
+ .ToList();
+ }
+
+ /// <summary>A readable name ("Google Chrome" rather than "chrome") and the program file for its icon.</summary>
+ private static (string Name, string? Path) Describe(string processName, int pid)
+ {
+ if (Names.TryGetValue(processName, out var known)) return known;
+ var path = ImagePath(pid);
+ var name = processName;
+ if (path is not null)
+ {
+ try
+ {
+ var description = FileVersionInfo.GetVersionInfo(path).FileDescription?.Trim();
+ if (!string.IsNullOrEmpty(description) && description.Length <= 40) name = description;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) { }
+ }
+ if (name == processName && name.Length > 0) name = char.ToUpperInvariant(name[0]) + name[1..];
+ return Names[processName] = (name, path);
+ }
+
+ private static string? ImagePath(int pid)
+ {
+ const uint QueryLimitedInformation = 0x1000;
+ var handle = OpenProcess(QueryLimitedInformation, false, pid);
+ if (handle == 0) return null;
+ try
+ {
+ var buffer = new StringBuilder(1024);
+ var size = buffer.Capacity;
+ return QueryFullProcessImageName(handle, 0, buffer, ref size) ? buffer.ToString(0, size) : null;
+ }
+ finally
+ {
+ CloseHandle(handle);
+ }
+ }
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern nint OpenProcess(uint access, bool inherit, int processId);
+
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool QueryFullProcessImageName(nint process, int flags, StringBuilder name, ref int size);
+
+ [DllImport("kernel32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool CloseHandle(nint handle);
+}
diff --git a/Services/Widgets/GlassLook.cs b/Services/Widgets/GlassLook.cs
new file mode 100644
index 0000000..7529336
--- /dev/null
+++ b/Services/Widgets/GlassLook.cs
@@ -0,0 +1,158 @@
+using System.Windows;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+
+namespace QiDock.Services.Widgets;
+
+/// <summary>
+/// One recipe for frosted glass, shared by the desktop cards, the dock and the cards that grow out of the dock: the
+/// softened wallpaper behind the surface, a dark veil (thicker over a bright picture so white text and icons keep
+/// their contrast), a soft sheen from above and a thin rim that catches the light.
+/// </summary>
+internal static class GlassLook
+{
+ public static readonly Brush Rim = MakeRim();
+ public static readonly Brush Sheen = MakeSheen();
+
+ /// <summary>The veil the dock wears now, or null when the dock is not glass; the cards on the dock wear the same.</summary>
+ public static Color? DockVeil { get; set; }
+
+ /// <summary>
+ /// A window stands behind the dock. The dock cannot see it (it only knows the wallpaper), so it then wears a plain
+ /// grey frost instead of the wallpaper's colours, which would not match what is behind it.
+ /// </summary>
+ public static bool WindowBehind { get; set; }
+
+ /// <summary>The dock's glass changed (veil, wallpaper or a window behind it): cards standing on it repaint.</summary>
+ public static event Action? DockChanged;
+
+ public static void RaiseDockChanged() => DockChanged?.Invoke();
+
+ private static readonly Brush Neutral = MakeNeutral();
+ private static (Color Veil, BitmapSource Image, Brush Brush)? _screen;
+
+ /// <summary>
+ /// Glass for the dock and what grows out of it, the same picture the desktop cards show: the wallpaper of the
+ /// whole screen is drawn once (half size) under the dock's veil, and each surface only places that picture with
+ /// <paramref name="localToScreen"/> (its own coordinates to screen units), so moving, growing or animating a
+ /// surface never draws the glass again. Null when the dock is not glass.
+ /// </summary>
+ public static Brush? Dock(Matrix localToScreen)
+ {
+ if (DockVeil is not { } veil) return null;
+ if (WindowBehind) return Neutral;
+ if (WallpaperGlass.Image is not { } image || !localToScreen.HasInverse) return null;
+ if (_screen is not { } screen || screen.Veil != veil || !ReferenceEquals(screen.Image, image))
+ {
+ var area = new Rect(0, 0, SystemParameters.PrimaryScreenWidth, SystemParameters.PrimaryScreenHeight);
+ if (Surface(area, area, veil, sheen: false, frost: false) is not { } baked) return null;
+ _screen = screen = (veil, image, baked);
+ }
+ localToScreen.Invert();
+ var brush = screen.Brush.CloneCurrentValue();
+ brush.Transform = new MatrixTransform(localToScreen);
+ brush.Freeze();
+ return brush;
+ }
+
+ private static Brush MakeNeutral()
+ {
+ var brush = new SolidColorBrush(Color.FromArgb(0xD0, 0x30, 0x30, 0x35));
+ brush.Freeze();
+ return brush;
+ }
+
+ // The theme's tiles are solid (black for the Black style); on glass they turn into a thin frost of white.
+ private static readonly (string Key, Brush Brush)[] GlassTiles =
+ [
+ ("WidgetTileFill", Frozen(0x1A)), ("WidgetTileStroke", Frozen(0x1F)),
+ ("DockTileFill", Frozen(0x1C)), ("DockTileStroke", Frozen(0x14)),
+ ("PanelTile", Frozen(0x1A)), ("PanelTileHover", Frozen(0x2B)), ("PanelTileStroke", Frozen(0x1F)),
+ ];
+
+ /// <summary>Glass tiles in <paramref name="resources"/> (a window's own), or the theme's tiles again.</summary>
+ public static void Tiles(ResourceDictionary resources, bool glass)
+ {
+ if (resources.Contains(GlassTiles[0].Key) == glass) return;
+ foreach (var (key, brush) in GlassTiles)
+ {
+ if (glass) resources[key] = brush;
+ else resources.Remove(key);
+ }
+ }
+
+ private static Brush Frozen(byte alpha)
+ {
+ var brush = new SolidColorBrush(Color.FromArgb(alpha, 0xFF, 0xFF, 0xFF));
+ brush.Freeze();
+ return brush;
+ }
+
+ public static Color Veil(double light)
+ {
+ var alpha = Math.Clamp(0.16 + 0.55 * light, 0.16, 0.62);
+ // In steps, so a slightly different patch of wallpaper does not mean drawing the glass again.
+ var step = Math.Round(alpha * 255 / 6) * 6;
+ return Color.FromArgb((byte)Math.Clamp(step, 0, 255), 0x0C, 0x0C, 0x10);
+ }
+
+ /// <summary>
+ /// Glass for a surface whose own coordinates cover <paramref name="local"/> and which sits at
+ /// <paramref name="screen"/> on the screen; null when there is no wallpaper to show. The layers are drawn once
+ /// into a small picture (half size: it is soft anyway), so an animated shape or a growing icon only copies
+ /// pixels instead of scaling the wallpaper again on every frame. <paramref name="frost"/>: the nearly grey
+ /// picture (dock and its cards); otherwise the wallpaper's own colours (cards on the desktop).
+ /// </summary>
+ public static Brush? Surface(Rect local, Rect screen, Color veil, bool sheen, Transform? transform = null, bool frost = true)
+ {
+ if (WallpaperGlass.Image is not { } image || local.Width <= 0 || local.Height <= 0) return null;
+ const double Resolution = 0.5;
+ const double Bleed = 4; // drawn a little larger, so the soft edge of the scaled picture stays outside the shape
+ var area = Rect.Inflate(local, Bleed, Bleed);
+ var behind = Rect.Inflate(screen, Bleed, Bleed);
+ var visual = new DrawingVisual();
+ RenderOptions.SetBitmapScalingMode(visual, BitmapScalingMode.HighQuality);
+ using (var dc = visual.RenderOpen())
+ {
+ dc.PushTransform(new ScaleTransform(Resolution, Resolution));
+ dc.PushTransform(new TranslateTransform(-area.X, -area.Y));
+ dc.DrawRectangle(new ImageBrush(image) { ViewboxUnits = BrushMappingMode.Absolute, Viewbox = WallpaperGlass.Behind(behind), Stretch = Stretch.Fill }, null, area);
+ dc.DrawRectangle(new SolidColorBrush(veil), null, area);
+ if (sheen) dc.DrawRectangle(Sheen, null, local);
+ }
+ var bitmap = new RenderTargetBitmap(Math.Max(1, (int)Math.Ceiling(area.Width * Resolution)), Math.Max(1, (int)Math.Ceiling(area.Height * Resolution)), 96, 96, PixelFormats.Pbgra32);
+ bitmap.Render(visual);
+ bitmap.Freeze();
+ var brush = new ImageBrush(bitmap)
+ {
+ Stretch = Stretch.Fill,
+ ViewportUnits = BrushMappingMode.Absolute,
+ Viewport = new Rect(area.X, area.Y, bitmap.PixelWidth / Resolution, bitmap.PixelHeight / Resolution)
+ };
+ RenderOptions.SetBitmapScalingMode(brush, BitmapScalingMode.Linear);
+ if (transform is not null) brush.Transform = transform;
+ brush.Freeze();
+ return brush;
+ }
+
+ private static Brush MakeRim()
+ {
+ var brush = new LinearGradientBrush { StartPoint = new Point(0, 0), EndPoint = new Point(1, 1) };
+ brush.GradientStops.Add(new GradientStop(Color.FromArgb(0xA6, 0xFF, 0xFF, 0xFF), 0));
+ brush.GradientStops.Add(new GradientStop(Color.FromArgb(0x26, 0xFF, 0xFF, 0xFF), 0.32));
+ brush.GradientStops.Add(new GradientStop(Color.FromArgb(0x12, 0xFF, 0xFF, 0xFF), 0.62));
+ brush.GradientStops.Add(new GradientStop(Color.FromArgb(0x59, 0xFF, 0xFF, 0xFF), 1));
+ brush.Freeze();
+ return brush;
+ }
+
+ private static Brush MakeSheen()
+ {
+ var brush = new LinearGradientBrush { StartPoint = new Point(0, 0), EndPoint = new Point(0, 1) };
+ brush.GradientStops.Add(new GradientStop(Color.FromArgb(0x24, 0xFF, 0xFF, 0xFF), 0));
+ brush.GradientStops.Add(new GradientStop(Color.FromArgb(0x08, 0xFF, 0xFF, 0xFF), 0.45));
+ brush.GradientStops.Add(new GradientStop(Color.FromArgb(0x00, 0xFF, 0xFF, 0xFF), 1));
+ brush.Freeze();
+ return brush;
+ }
+}
diff --git a/Services/Widgets/WallpaperGlass.cs b/Services/Widgets/WallpaperGlass.cs
new file mode 100644
index 0000000..57563e9
--- /dev/null
+++ b/Services/Widgets/WallpaperGlass.cs
@@ -0,0 +1,156 @@
+using System.IO;
+using System.Windows;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+
+namespace QiDock.Services.Widgets;
+
+/// <summary>
+/// The wallpaper as frosted glass sees it: read once, small (256 pixels wide), softened and a little more colourful,
+/// shared by every desktop card. A card shows the part of it that lies behind the card, so the glass looks through
+/// to the picture without any live blur (nothing is redrawn while the desktop stays the same).
+/// </summary>
+internal static class WallpaperGlass
+{
+ private const int DecodeWidth = 256;
+ private static string _stamp = "";
+ private static byte[]? _pixels;
+ private static int _width, _height;
+
+ /// <summary>The softened wallpaper, or null when there is none to read (a plain colour).</summary>
+ public static BitmapSource? Image { get; private set; }
+
+ /// <summary>Goes up each time the picture changes, so every user of it can tell (not only the first to ask).</summary>
+ public static int Version { get; private set; }
+
+ /// <summary>Reads the wallpaper again if Windows changed it. True when the picture is new.</summary>
+ public static bool Refresh()
+ {
+ var file = WallpaperTint.WallpaperFile();
+ if (file is null)
+ {
+ var had = Image is not null;
+ Image = null;
+ if (had) Version++;
+ _pixels = null;
+ _stamp = "";
+ return had;
+ }
+ try
+ {
+ var info = new FileInfo(file);
+ var stamp = file + info.LastWriteTimeUtc.Ticks + info.Length;
+ if (stamp == _stamp && Image is not null) return false;
+ var image = new BitmapImage();
+ using (var stream = new MemoryStream(File.ReadAllBytes(file)))
+ {
+ image.BeginInit();
+ image.CacheOption = BitmapCacheOption.OnLoad;
+ image.DecodePixelWidth = DecodeWidth;
+ image.StreamSource = stream;
+ image.EndInit();
+ }
+ var converted = new FormatConvertedBitmap(image, PixelFormats.Bgra32, null, 0);
+ int w = converted.PixelWidth, h = converted.PixelHeight;
+ var pixels = new byte[w * h * 4];
+ converted.CopyPixels(pixels, w * 4, 0);
+ // Three box passes come close to a gaussian blur; then a touch more colour, as glass over a picture has.
+ for (var pass = 0; pass < 3; pass++)
+ {
+ BoxBlur(pixels, w, h, 2, horizontal: true);
+ BoxBlur(pixels, w, h, 2, horizontal: false);
+ }
+ Saturate(pixels, 1.3);
+ var bitmap = BitmapSource.Create(w, h, 96, 96, PixelFormats.Bgra32, null, pixels, w * 4);
+ bitmap.Freeze();
+ Image = bitmap;
+ Version++;
+ _pixels = pixels;
+ _width = w;
+ _height = h;
+ _stamp = stamp;
+ return true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or InvalidOperationException
+ or ArgumentException or FormatException or System.Runtime.InteropServices.COMException)
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// The part of <see cref="Image"/> behind <paramref name="area"/> (screen units of the primary screen), for an
+ /// image brush's viewbox. The wallpaper fills the screen: scaled to cover it, the overflow cut off equally.
+ /// </summary>
+ public static Rect Behind(Rect area)
+ {
+ var (scale, offsetX, offsetY) = Mapping();
+ return new Rect((area.Left + offsetX) / scale, (area.Top + offsetY) / scale, area.Width / scale, area.Height / scale);
+ }
+
+ /// <summary>How bright the glass behind <paramref name="area"/> is, 0 (black) to 1 (white).</summary>
+ public static double Light(Rect area)
+ {
+ if (_pixels is null || _width == 0) return 0.3;
+ var box = Behind(area);
+ int x0 = Math.Clamp((int)box.Left, 0, _width - 1), x1 = Math.Clamp((int)Math.Ceiling(box.Right), 0, _width - 1);
+ int y0 = Math.Clamp((int)box.Top, 0, _height - 1), y1 = Math.Clamp((int)Math.Ceiling(box.Bottom), 0, _height - 1);
+ double light = 0;
+ var count = 0;
+ for (var y = y0; y <= y1; y++)
+ for (var x = x0; x <= x1; x++)
+ {
+ var i = (y * _width + x) * 4;
+ light += (0.0722 * _pixels[i] + 0.7152 * _pixels[i + 1] + 0.2126 * _pixels[i + 2]) / 255;
+ count++;
+ }
+ return count == 0 ? 0.3 : light / count;
+ }
+
+ private static (double Scale, double OffsetX, double OffsetY) Mapping()
+ {
+ var screen = new Size(SystemParameters.PrimaryScreenWidth, SystemParameters.PrimaryScreenHeight);
+ if (_width == 0 || _height == 0) return (1, 0, 0);
+ var scale = Math.Max(screen.Width / _width, screen.Height / _height);
+ return (scale, (_width * scale - screen.Width) / 2, (_height * scale - screen.Height) / 2);
+ }
+
+ private static void BoxBlur(byte[] pixels, int width, int height, int radius, bool horizontal)
+ {
+ var lines = horizontal ? height : width;
+ var length = horizontal ? width : height;
+ var line = new int[length * 4];
+ for (var l = 0; l < lines; l++)
+ {
+ int Index(int p) => horizontal ? (l * width + p) * 4 : (p * width + l) * 4;
+ for (var p = 0; p < length; p++)
+ {
+ var i = Index(p);
+ for (var c = 0; c < 4; c++) line[p * 4 + c] = pixels[i + c];
+ }
+ for (var p = 0; p < length; p++)
+ {
+ var i = Index(p);
+ for (var c = 0; c < 4; c++)
+ {
+ var sum = 0;
+ for (var k = -radius; k <= radius; k++) sum += line[Math.Clamp(p + k, 0, length - 1) * 4 + c];
+ pixels[i + c] = (byte)(sum / (2 * radius + 1));
+ }
+ }
+ }
+ }
+
+ private static void Saturate(byte[] pixels, double amount)
+ {
+ for (var i = 0; i < pixels.Length; i += 4)
+ {
+ double b = pixels[i], g = pixels[i + 1], r = pixels[i + 2];
+ var grey = 0.0722 * b + 0.7152 * g + 0.2126 * r;
+ pixels[i] = (byte)Math.Clamp(grey + (b - grey) * amount, 0, 255);
+ pixels[i + 1] = (byte)Math.Clamp(grey + (g - grey) * amount, 0, 255);
+ pixels[i + 2] = (byte)Math.Clamp(grey + (r - grey) * amount, 0, 255);
+ pixels[i + 3] = 255;
+ }
+ }
+}
diff --git a/Services/Widgets/WallpaperTint.cs b/Services/Widgets/WallpaperTint.cs
new file mode 100644
index 0000000..2c81247
--- /dev/null
+++ b/Services/Widgets/WallpaperTint.cs
@@ -0,0 +1,124 @@
+using System.IO;
+using System.Windows;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+
+namespace QiDock.Services.Widgets;
+
+/// <summary>
+/// A text colour taken from the wallpaper behind a spot of the screen, as a phone's lock screen tints its clock: a
+/// soft, light shade of the picture's own colour (a dark one over a very bright picture). The wallpaper is read once
+/// at 96 pixels wide and again only when Windows changes it.
+/// </summary>
+internal static class WallpaperTint
+{
+ private static string _stamp = "";
+ private static byte[]? _pixels;
+ private static int _width, _height;
+
+ /// <summary>The current wallpaper as Windows stores it for the desktop (also when a slideshow changes it).</summary>
+ internal static string? WallpaperFile()
+ {
+ var transcoded = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft", "Windows", "Themes", "TranscodedWallpaper");
+ if (File.Exists(transcoded)) return transcoded;
+ var path = Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Control Panel\Desktop", "WallPaper", null) as string;
+ return !string.IsNullOrWhiteSpace(path) && File.Exists(path) ? path : null;
+ }
+
+ private static bool Load()
+ {
+ var file = WallpaperFile();
+ if (file is null) return false;
+ try
+ {
+ var info = new FileInfo(file);
+ var stamp = file + info.LastWriteTimeUtc.Ticks + info.Length;
+ if (stamp == _stamp && _pixels is not null) return true;
+ var image = new BitmapImage();
+ using (var stream = new MemoryStream(File.ReadAllBytes(file)))
+ {
+ image.BeginInit();
+ image.CacheOption = BitmapCacheOption.OnLoad;
+ image.DecodePixelWidth = 96;
+ image.StreamSource = stream;
+ image.EndInit();
+ }
+ var pixels = new FormatConvertedBitmap(image, PixelFormats.Bgra32, null, 0);
+ _width = pixels.PixelWidth;
+ _height = pixels.PixelHeight;
+ _pixels = new byte[_width * _height * 4];
+ pixels.CopyPixels(_pixels, _width * 4, 0);
+ _stamp = stamp;
+ return true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or InvalidOperationException or ArgumentException)
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// The tint for text over <paramref name="area"/> (screen units of the primary screen), or null when the wallpaper
+ /// cannot be read (a plain colour, a picture that was removed).
+ /// </summary>
+ public static Color? For(Rect area)
+ {
+ if (!Load() || _pixels is null || _width == 0 || _height == 0) return null;
+ // The wallpaper fills the screen ("fill"): scaled to cover it, the overflow cut off equally on both sides.
+ var screen = new Size(SystemParameters.PrimaryScreenWidth, SystemParameters.PrimaryScreenHeight);
+ var scale = Math.Max(screen.Width / _width, screen.Height / _height);
+ var offsetX = (_width * scale - screen.Width) / 2;
+ var offsetY = (_height * scale - screen.Height) / 2;
+ int Px(double x) => Math.Clamp((int)((x + offsetX) / scale), 0, _width - 1);
+ int Py(double y) => Math.Clamp((int)((y + offsetY) / scale), 0, _height - 1);
+ int x0 = Px(area.Left), x1 = Px(area.Right), y0 = Py(area.Top), y1 = Py(area.Bottom);
+
+ double r = 0, g = 0, b = 0, count = 0, light = 0;
+ // The most colourful pixels decide the hue (a grey sky over a blue sea still reads as blue).
+ double cr = 0, cg = 0, cb = 0, weight = 0;
+ for (var y = y0; y <= y1; y++)
+ for (var x = x0; x <= x1; x++)
+ {
+ var i = (y * _width + x) * 4;
+ double pb = _pixels[i] / 255.0, pg = _pixels[i + 1] / 255.0, pr = _pixels[i + 2] / 255.0;
+ r += pr; g += pg; b += pb; count++;
+ light += 0.2126 * pr + 0.7152 * pg + 0.0722 * pb;
+ var saturation = Math.Max(pr, Math.Max(pg, pb)) - Math.Min(pr, Math.Min(pg, pb));
+ var w = saturation * saturation;
+ cr += pr * w; cg += pg * w; cb += pb * w; weight += w;
+ }
+ if (count == 0) return null;
+ light /= count;
+ var (hue, sat, _) = weight > 0.02 * count / 50 ? Hsl(cr / weight, cg / weight, cb / weight) : Hsl(r / count, g / count, b / count);
+ // Light text over most pictures; over a very bright one, a deep shade of the same colour.
+ return light > 0.72
+ ? FromHsl(hue, Math.Min(0.55, sat * 1.1), 0.24)
+ : FromHsl(hue, Math.Min(0.6, sat * 1.2 + 0.08), 0.86);
+ }
+
+ private static (double H, double S, double L) Hsl(double r, double g, double b)
+ {
+ var max = Math.Max(r, Math.Max(g, b));
+ var min = Math.Min(r, Math.Min(g, b));
+ var l = (max + min) / 2;
+ if (max - min < 1e-6) return (0, 0, l);
+ var d = max - min;
+ var s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+ double h = max == r ? (g - b) / d + (g < b ? 6 : 0) : max == g ? (b - r) / d + 2 : (r - g) / d + 4;
+ return (h / 6, s, l);
+ }
+
+ private static Color FromHsl(double h, double s, double l)
+ {
+ double Channel(double t)
+ {
+ var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
+ var p = 2 * l - q;
+ if (t < 0) t += 1;
+ if (t > 1) t -= 1;
+ return t < 1.0 / 6 ? p + (q - p) * 6 * t : t < 0.5 ? q : t < 2.0 / 3 ? p + (q - p) * (2.0 / 3 - t) * 6 : p;
+ }
+ byte B(double v) => (byte)Math.Round(Math.Clamp(v, 0, 1) * 255);
+ return s <= 0 ? Color.FromRgb(B(l), B(l), B(l)) : Color.FromRgb(B(Channel(h + 1.0 / 3)), B(Channel(h)), B(Channel(h - 1.0 / 3)));
+ }
+}
diff --git a/SettingsWindow.xaml b/SettingsWindow.xaml
index 05f6bbb..fe0b553 100644
--- a/SettingsWindow.xaml
+++ b/SettingsWindow.xaml
@@ -90,6 +90,16 @@
AutomationProperties.Name="{local:Loc Previews}" AutomationProperties.HelpText="{local:Loc PreviewsDescription}" />
<TextBlock Text="{local:Loc Previews}" Style="{StaticResource SettingsRowLabel}" />
</DockPanel></Border>
+ <Border Style="{StaticResource SettingsRow}"><DockPanel>
+ <CheckBox x:Name="DockGlassToggle" DockPanel.Dock="Right" Style="{StaticResource SettingsSwitch}"
+ AutomationProperties.Name="{local:Loc DockGlassSetting}" AutomationProperties.HelpText="{local:Loc DockGlassSettingHelp}" />
+ <TextBlock Text="{local:Loc DockGlassSetting}" Style="{StaticResource SettingsRowLabel}" ToolTip="{local:Loc DockGlassSettingHelp}" />
+ </DockPanel></Border>
+ <Border Style="{StaticResource SettingsRow}"><DockPanel>
+ <CheckBox x:Name="NotchBrowserToggle" DockPanel.Dock="Right" Style="{StaticResource SettingsSwitch}"
+ AutomationProperties.Name="{local:Loc NotchBrowserSetting}" AutomationProperties.HelpText="{local:Loc NotchBrowserSettingHelp}" />
+ <TextBlock Text="{local:Loc NotchBrowserSetting}" Style="{StaticResource SettingsRowLabel}" ToolTip="{local:Loc NotchBrowserSettingHelp}" />
+ </DockPanel></Border>
<Border Style="{StaticResource SettingsRow}"><DockPanel>
<CheckBox x:Name="BadgesToggle" DockPanel.Dock="Right" Style="{StaticResource SettingsSwitch}"
AutomationProperties.Name="{local:Loc Badges}" AutomationProperties.HelpText="{local:Loc BadgesDescription}" />
diff --git a/SettingsWindow.xaml.cs b/SettingsWindow.xaml.cs
index ec2696f..8283d90 100644
--- a/SettingsWindow.xaml.cs
+++ b/SettingsWindow.xaml.cs
@@ -120,6 +120,8 @@ public partial class SettingsWindow : Window
AnimationsToggle.IsChecked = settings.AnimationsEnabled;
GenieToggle.IsChecked = settings.GenieEffectEnabled;
PreviewsToggle.IsChecked = settings.PreviewsEnabled;
+ NotchBrowserToggle.IsChecked = settings.NotchBrowser;
+ DockGlassToggle.IsChecked = settings.DockGlass;
BadgesToggle.IsChecked = settings.NotificationBadgesEnabled;
DockHudToggle.IsChecked = settings.DockHud;
ClaudeActivityToggle.IsChecked = settings.ClaudeActivity;
@@ -262,6 +264,8 @@ public partial class SettingsWindow : Window
AnimationsEnabled = Pick(AnimationsToggle.IsChecked == true, shown.AnimationsEnabled, now.AnimationsEnabled),
GenieEffectEnabled = Pick(GenieToggle.IsChecked == true, shown.GenieEffectEnabled, now.GenieEffectEnabled),
PreviewsEnabled = Pick(PreviewsToggle.IsChecked == true, shown.PreviewsEnabled, now.PreviewsEnabled),
+ NotchBrowser = Pick(NotchBrowserToggle.IsChecked == true, shown.NotchBrowser, now.NotchBrowser),
+ DockGlass = Pick(DockGlassToggle.IsChecked == true, shown.DockGlass, now.DockGlass),
NotificationBadgesEnabled = Pick(BadgesToggle.IsChecked == true, shown.NotificationBadgesEnabled, now.NotificationBadgesEnabled),
DockHud = Pick(DockHudToggle.IsChecked == true, shown.DockHud, now.DockHud),
ClaudeActivity = Pick(ClaudeActivityToggle.IsChecked == true, shown.ClaudeActivity, now.ClaudeActivity),
diff --git a/TopBarWindow.cs b/TopBarWindow.cs
index d048e36..c9fa6ea 100644
--- a/TopBarWindow.cs
+++ b/TopBarWindow.cs
@@ -327,6 +327,8 @@ public sealed class TopBarWindow : Window
private bool WithinBarSpan(int x)
{
+ // The middle of the edge opens the notch browser instead.
+ if (Browser.NotchBrowser.InZone(x)) return false;
var screenWidth = GetSystemMetrics(0);
var halfSpan = Math.Max(screenWidth * 0.18, ActualWidth * DpiScale() / 2);
return Math.Abs(x - screenWidth / 2.0) <= halfSpan;
diff --git a/Widgets/AiLimitsWidget.cs b/Widgets/AiLimitsWidget.cs
index d6a4025..fb9ee88 100644
--- a/Widgets/AiLimitsWidget.cs
+++ b/Widgets/AiLimitsWidget.cs
@@ -35,18 +35,40 @@ public sealed class AiLimitsWidget : DockWidget
private IReadOnlyList<ProviderUsage> _usage = [];
private CancellationTokenSource? _load;
private string _layoutSignature = "";
+ // In the dock: one small tile (the logos stacked, the highest use); on hover the rings slide out sideways
+ // over the dock, so the dock itself never changes width.
+ private readonly StackPanel _summary = new() { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(7, 0, 9, 0) };
+ private readonly Grid _face = new() { ClipToBounds = true };
+ private readonly DispatcherTimer _hoverOpen = new(DispatcherPriority.Input) { Interval = TimeSpan.FromMilliseconds(140) };
+ private readonly DispatcherTimer _hoverClose = new(DispatcherPriority.Input) { Interval = TimeSpan.FromMilliseconds(300) };
+ private bool _expanded;
public AiLimitsWidget()
{
_cards = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };
// A plain tile: each ring inside is its own button.
- _tile = new Border { Child = _cards, Padding = new Thickness(3, 0, 3, 0), Margin = new Thickness(3, 0, 3, 0), BorderThickness = new Thickness(1), VerticalAlignment = VerticalAlignment.Center };
+ _tile = new Border { Child = _face, Padding = new Thickness(3, 0, 3, 0), Margin = new Thickness(3, 0, 3, 0), BorderThickness = new Thickness(1), VerticalAlignment = VerticalAlignment.Center };
_tile.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");
_tile.SetResourceReference(Border.BorderBrushProperty, "WidgetTileStroke");
_tile.SetResourceReference(FrameworkElement.HeightProperty, "WidgetTileHeight");
_tile.CornerRadius = new CornerRadius(11);
_popup = new WidgetPopup(_tile);
_popup.Closed += (_, _) => StopSessions();
+ _summary.HorizontalAlignment = HorizontalAlignment.Left;
+ _cards.HorizontalAlignment = HorizontalAlignment.Left;
+ _cards.Opacity = 0;
+ _cards.Visibility = Visibility.Collapsed;
+ _face.Children.Add(_summary);
+ _face.Children.Add(_cards);
+ _hoverOpen.Tick += (_, _) => { _hoverOpen.Stop(); Expand(); };
+ _hoverClose.Tick += (_, _) =>
+ {
+ _hoverClose.Stop();
+ if (!_tile.IsMouseOver) Collapse(instant: false);
+ };
+ _tile.MouseEnter += (_, _) => { _hoverClose.Stop(); if (!_expanded) _hoverOpen.Start(); };
+ _tile.MouseLeave += (_, _) => { _hoverOpen.Stop(); if (_expanded) _hoverClose.Start(); };
+ _tile.MouseLeftButtonUp += (_, _) => { if (!_expanded && Busiest() is { } busiest) ToggleProvider(busiest); };
_claudeWatch.Changed += () => _ = LoadSessionsAsync();
_sessionTick.Tick += (_, _) => _ = LoadSessionsAsync(); // "3 dk önce" and sessions going quiet
_timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMinutes(1) };
@@ -71,10 +93,15 @@ public sealed class AiLimitsWidget : DockWidget
_timer.Stop();
_load?.Cancel();
_popup.Close();
+ Collapse(instant: true);
StopSessions();
}
- public override void ClosePopup() => _popup.Close();
+ public override void ClosePopup()
+ {
+ _popup.Close();
+ Collapse(instant: true);
+ }
private async Task RefreshAsync(bool force)
{
@@ -99,8 +126,91 @@ public sealed class AiLimitsWidget : DockWidget
// ---- Dock tile ---------------------------------------------------------------------------
+ private string? Busiest() =>
+ _usage.Count == 0 ? AiUsageService.ClaudeId
+ : _usage.OrderByDescending(p => p.Error is null && p.Windows.Count > 0 ? p.Windows.Max(w => w.UsedPercent) : -1).First().Provider;
+
+ /// <summary>The tile: the providers' logos overlapping, and the highest use among them.</summary>
+ private void RenderSummary()
+ {
+ _summary.Children.Clear();
+ var providers = _usage.Count == 0 ? [AiUsageService.ClaudeId] : _usage.Select(p => p.Provider).ToList();
+ const double Mark = 20, Step = 12;
+ var stack = new Grid { Width = Mark + 2 + (providers.Count - 1) * Step, Height = Mark + 4, VerticalAlignment = VerticalAlignment.Center };
+ for (var i = providers.Count - 1; i >= 0; i--)
+ {
+ // A thin dark ring keeps overlapping logos apart.
+ stack.Children.Add(new Border
+ {
+ Width = Mark + 2, Height = Mark + 2, CornerRadius = new CornerRadius(7), Background = Ui.Solid("#E61C1C1F"), Padding = new Thickness(1),
+ HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center,
+ Margin = new Thickness(i * Step, 0, 0, 0), Child = Logo(providers[i], Mark)
+ });
+ }
+ _summary.Children.Add(stack);
+ var used = _usage.Where(p => p.Error is null && p.Windows.Count > 0).Select(p => p.Windows.Max(w => w.UsedPercent)).DefaultIfEmpty(-1).Max();
+ var text = Ui.Text(used >= 0 ? UiText.Percent(used) : "—", 11.5, FontWeights.SemiBold, brush: used >= 0 ? Ui.UsageBrush(used) : null);
+ text.Margin = new Thickness(6, 0, 0, 0);
+ text.VerticalAlignment = VerticalAlignment.Center;
+ _summary.Children.Add(text);
+ }
+
+ /// <summary>
+ /// The tile opens out to the right into one ring per provider. The dock keeps its width meanwhile, so what
+ /// stands after the tile slides out of the dock's end, and comes back when the tile closes.
+ /// </summary>
+ private void Expand()
+ {
+ if (_expanded || _popup.IsOpen || !_tile.IsVisible) return;
+ _expanded = true;
+ var chrome = _tile.Padding.Left + _tile.Padding.Right + _tile.BorderThickness.Left + _tile.BorderThickness.Right;
+ var from = _tile.ActualWidth;
+ _cards.Visibility = Visibility.Visible;
+ _cards.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
+ var to = Math.Max(from, _cards.DesiredSize.Width + chrome);
+ RaiseExpanding(true);
+ var ease = new System.Windows.Media.Animation.CubicEase { EasingMode = System.Windows.Media.Animation.EasingMode.EaseOut };
+ _tile.BeginAnimation(FrameworkElement.WidthProperty, new System.Windows.Media.Animation.DoubleAnimation(from, to, TimeSpan.FromMilliseconds(240)) { EasingFunction = ease });
+ _summary.BeginAnimation(UIElement.OpacityProperty, new System.Windows.Media.Animation.DoubleAnimation(0, TimeSpan.FromMilliseconds(120)));
+ _cards.BeginAnimation(UIElement.OpacityProperty, new System.Windows.Media.Animation.DoubleAnimation(1, TimeSpan.FromMilliseconds(200)) { BeginTime = TimeSpan.FromMilliseconds(50) });
+ }
+
+ private void Collapse(bool instant)
+ {
+ _hoverOpen.Stop();
+ _hoverClose.Stop();
+ if (!_expanded) return;
+ _expanded = false;
+ void Done()
+ {
+ if (_expanded) return; // opened again meanwhile
+ _tile.BeginAnimation(FrameworkElement.WidthProperty, null);
+ _tile.Width = double.NaN;
+ _summary.BeginAnimation(UIElement.OpacityProperty, null);
+ _summary.Opacity = 1;
+ _cards.BeginAnimation(UIElement.OpacityProperty, null);
+ _cards.Opacity = 0;
+ _cards.Visibility = Visibility.Collapsed;
+ RaiseExpanding(false);
+ }
+ if (instant)
+ {
+ Done();
+ return;
+ }
+ var chrome = _tile.Padding.Left + _tile.Padding.Right + _tile.BorderThickness.Left + _tile.BorderThickness.Right;
+ var to = _summary.DesiredSize.Width + chrome;
+ var ease = new System.Windows.Media.Animation.CubicEase { EasingMode = System.Windows.Media.Animation.EasingMode.EaseIn };
+ var shrink = new System.Windows.Media.Animation.DoubleAnimation(_tile.ActualWidth, to, TimeSpan.FromMilliseconds(200)) { EasingFunction = ease };
+ shrink.Completed += (_, _) => Done();
+ _tile.BeginAnimation(FrameworkElement.WidthProperty, shrink);
+ _cards.BeginAnimation(UIElement.OpacityProperty, new System.Windows.Media.Animation.DoubleAnimation(0, TimeSpan.FromMilliseconds(110)));
+ _summary.BeginAnimation(UIElement.OpacityProperty, new System.Windows.Media.Animation.DoubleAnimation(1, TimeSpan.FromMilliseconds(160)) { BeginTime = TimeSpan.FromMilliseconds(60) });
+ }
+
private void Render()
{
+ RenderSummary();
_cards.Children.Clear();
if (_usage.Count == 0)
{
@@ -177,6 +287,7 @@ public sealed class AiLimitsWidget : DockWidget
/// <summary>A ring was clicked: its provider's card opens (another provider's card on show switches over).</summary>
private void ToggleProvider(string provider)
{
+ Collapse(instant: true);
if (_popup.IsOpen && _shown != provider)
{
_shown = provider;
@@ -361,7 +472,13 @@ public sealed class AiLimitsWidget : DockWidget
}
var updated = Ui.Text(UiText.Format("AiUpdated", When(provider.UpdatedAt),
- provider.Provider == AiUsageService.CodexId ? UiText.Get("AiSourceCodex") : UiText.Get("AiSourceClaude")), 10, brushKey: "TextSecondary");
+ provider.Provider switch
+ {
+ AiUsageService.CodexId => UiText.Get("AiSourceCodex"),
+ AiUsageService.GeminiId => UiText.Get("AiSourceGemini"),
+ AiUsageService.OpenCodeId => UiText.Get("AiSourceOpenCode"),
+ _ => UiText.Get("AiSourceClaude")
+ }), 10, brushKey: "TextSecondary");
updated.Opacity = 0.8;
updated.Margin = new Thickness(0, 8, 0, 0);
content.Children.Add(updated);
@@ -518,7 +635,23 @@ public sealed class AiLimitsWidget : DockWidget
internal static FrameworkElement Logo(string provider, double size)
{
var canvas = new Canvas { Width = 24, Height = 24 };
- if (provider == AiUsageService.CodexId)
+ if (provider == AiUsageService.GeminiId)
+ {
+ // A four-pointed spark on Gemini's blue-to-violet.
+ canvas.Children.Add(new Rectangle
+ {
+ Width = 24, Height = 24, RadiusX = 6, RadiusY = 6,
+ Fill = new LinearGradientBrush(Color.FromRgb(0x4F, 0x9B, 0xF5), Color.FromRgb(0xA4, 0x6B, 0xE8), new Point(0, 0), new Point(1, 1))
+ });
+ canvas.Children.Add(new Path { Data = Geometry.Parse("M12,4 C12.6,9 15,11.4 20,12 C15,12.6 12.6,15 12,20 C11.4,15 9,12.6 4,12 C9,11.4 11.4,9 12,4 Z"), Fill = Brushes.White });
+ }
+ else if (provider == AiUsageService.OpenCodeId)
+ {
+ // OpenCode's dark square with a light frame.
+ canvas.Children.Add(new Rectangle { Width = 24, Height = 24, RadiusX = 6, RadiusY = 6, Fill = Ui.Solid("#FF1E1E22") });
+ canvas.Children.Add(new Path { Data = Geometry.Parse("M7,6 H17 V18 H7 Z M9.5,8.5 V15.5 H14.5 V8.5 Z"), Fill = Ui.Solid("#FFEDEDED") });
+ }
+ else if (provider == AiUsageService.CodexId)
{
canvas.Children.Add(new Rectangle { Width = 24, Height = 24, RadiusX = 6, RadiusY = 6, Fill = Ui.Solid("#FFF4F4F4") });
var ring = new Ellipse { Width = 14, Height = 14, Stroke = Ui.Solid("#FF111111"), StrokeThickness = 2.2 };
diff --git a/Widgets/MediaWidget.Card.cs b/Widgets/MediaWidget.Card.cs
index c468abd..56c5879 100644
--- a/Widgets/MediaWidget.Card.cs
+++ b/Widgets/MediaWidget.Card.cs
@@ -75,8 +75,10 @@ public sealed partial class MediaWidget
};
_popup.Closed += (_, _) =>
{
+ Flip(animate: false); // opens on the song again next time
CloseAudio();
UpdateProgressTimer();
+ if (_idle && !_editing) SetVisible(false); // the music stopped while the card was open
};
}
FillCard();
@@ -153,7 +155,7 @@ public sealed partial class MediaWidget
controls.Children.Add(button);
}
- // The player's own volume (Spotify, the browser…), or the computer's when the player cannot be found.
+ // The computer's volume.
_volumeIcon = Ui.Icon("IconVolume", 14);
var mute = Ui.IconButton(_volumeIcon, (_, _) => ToggleMute(), UiText.Get("MediaMute"), 28, 26);
DockPanel.SetDock(mute, Dock.Left);
@@ -184,7 +186,29 @@ public sealed partial class MediaWidget
body.Children.Add(_volumeLabel);
body.Children.Add(volumeRow);
- _card = new Border { CornerRadius = new CornerRadius(14), Padding = new Thickness(16, 16, 16, 12), Background = fill, Child = body };
+ // The back of the card: the songs played lately, each with its small cover. A click on the cover or the
+ // title turns the card over (and back).
+ _front = body;
+ _back = BuildBack();
+ _back.Visibility = Visibility.Collapsed;
+ foreach (var face in new FrameworkElement[] { artFrame, words })
+ {
+ face.Cursor = Cursors.Hand;
+ face.ToolTip = UiText.Get("MediaShowRecent");
+ face.MouseLeftButtonUp += (_, e) =>
+ {
+ e.Handled = true;
+ Flip();
+ };
+ }
+ var faces = new Grid();
+ faces.Children.Add(_front);
+ faces.Children.Add(_back);
+ _card = new Border
+ {
+ CornerRadius = new CornerRadius(14), Padding = new Thickness(16, 16, 16, 12), Background = fill, Child = faces,
+ RenderTransformOrigin = new Point(0.5, 0.5), RenderTransform = _turn
+ };
_card.Resources["TextPrimary"] = Ui.White;
_card.Resources["TextSecondary"] = Ui.Solid("#B8FFFFFF");
_card.Resources["WidgetTrack"] = Ui.Solid("#38FFFFFF");
@@ -194,6 +218,294 @@ public sealed partial class MediaWidget
return _card;
}
+ // ---- The back of the card: the browser's playlist, or the songs played lately ----
+
+ private sealed record Played(string Key, string Title, string Artist, ImageSource? Cover);
+
+ private readonly List<Played> _played = [];
+ private readonly ScaleTransform _turn = new(1, 1);
+ private FrameworkElement? _front;
+ private DockPanel? _back;
+ private StackPanel? _playedList;
+ private ScrollViewer? _backScroll;
+ private TextBlock? _backHeading;
+ private bool _flipped;
+ private object? _rememberedArt;
+ private IReadOnlyList<PlaylistSong> _playlist = [];
+ private System.Windows.Automation.AutomationElement? _hiddenTab;
+ private int _playlistRead;
+ // YouTube's small pictures, kept while QiDock runs (a few kilobytes each) so the list does not load them again.
+ private static readonly Dictionary<string, ImageSource> Thumbnails = [];
+
+ /// <summary>
+ /// Keeps the songs played lately (newest first, at most twenty) with a small copy of each cover. Windows does
+ /// not tell other apps a player's queue, so the back of the card shows what was played, not what comes next.
+ /// </summary>
+ private void Remember(string title, string artist, ImageSource? art)
+ {
+ var key = $"{title}|{artist}";
+ var index = _played.FindIndex(p => p.Key == key);
+ var cover = index >= 0 ? _played[index].Cover : null;
+ if (art is not null && !ReferenceEquals(art, _rememberedArt))
+ {
+ _rememberedArt = art;
+ cover = SmallCover(art) ?? cover;
+ }
+ if (index == 0 && ReferenceEquals(_played[0].Cover, cover)) return;
+ if (index >= 0) _played.RemoveAt(index);
+ _played.Insert(0, new Played(key, title, artist, cover));
+ if (_played.Count > 20) _played.RemoveAt(_played.Count - 1);
+ if (!_flipped) return;
+ FillBack();
+ if (index != 0) ReadPlaylist(); // another song: the list moved on
+ }
+
+ /// <summary>
+ /// Reads the list beside the video in the browser (only while the back is open; reading it makes the browser
+ /// keep its screen-reader view of the page). <paramref name="tries"/>: a tab just brought forward needs a moment.
+ /// </summary>
+ private async void ReadPlaylist(int tries = 1)
+ {
+ if (!BrowserPlaylist.IsBrowser(_session?.SourceAppUserModelId))
+ {
+ _playlist = [];
+ _hiddenTab = null;
+ return;
+ }
+ var read = ++_playlistRead;
+ var view = await BrowserPlaylist.ReadAsync(_title.Text);
+ if (read != _playlistRead || !_flipped) return;
+ if (view.Songs.Count == 0 && tries > 1)
+ {
+ await Task.Delay(900);
+ if (read == _playlistRead && _flipped) ReadPlaylist(tries - 1);
+ return;
+ }
+ var first = _playlist.Count == 0 && view.Songs.Count > 0;
+ _playlist = view.Songs;
+ _hiddenTab = view.HiddenTab;
+ FillBack(scrollToCurrent: first);
+ }
+
+ private async void PlaySong(PlaylistSong song)
+ {
+ if (!await BrowserPlaylist.PlayAsync(song)) return;
+ _playlist = _playlist.Select(s => s with { Current = s.Index == song.Index }).ToList();
+ FillBack();
+ }
+
+ private async void ShowHiddenTab()
+ {
+ if (_hiddenTab is not { } tab || !await BrowserPlaylist.ShowTabAsync(tab)) return;
+ _hiddenTab = null;
+ FillBack();
+ await Task.Delay(700);
+ ReadPlaylist(tries: 4);
+ }
+
+ private static ImageSource Thumbnail(PlaylistSong song)
+ {
+ if (Thumbnails.TryGetValue(song.VideoId, out var known)) return known;
+ if (Thumbnails.Count > 120) Thumbnails.Clear();
+ var image = new BitmapImage();
+ image.BeginInit();
+ image.UriSource = song.Thumbnail;
+ image.DecodePixelHeight = 84; // the cover is 42 points; enough for a 200% screen
+ image.CacheOption = BitmapCacheOption.OnLoad;
+ image.EndInit();
+ Thumbnails[song.VideoId] = image;
+ return image;
+ }
+
+ private static ImageSource? SmallCover(ImageSource art)
+ {
+ if (art is not BitmapSource bitmap || bitmap.PixelWidth < 1 || bitmap.PixelHeight < 1) return null;
+ try
+ {
+ var scale = Math.Min(1, 96.0 / Math.Max(bitmap.PixelWidth, bitmap.PixelHeight));
+ var small = new CachedBitmap(new TransformedBitmap(bitmap, new ScaleTransform(scale, scale)), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
+ small.Freeze();
+ return small;
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or ArgumentException or NotSupportedException or COMException)
+ {
+ return null;
+ }
+ }
+
+ private DockPanel BuildBack()
+ {
+ var back = Ui.Icon("IconChevronLeft", 13, Ui.White, null, 2.2);
+ var backText = Ui.Text(UiText.Get("MediaShowPlaying"), 12, FontWeights.SemiBold);
+ backText.Margin = new Thickness(5, 0, 0, 0);
+ var backRow = new StackPanel { Orientation = Orientation.Horizontal };
+ backRow.Children.Add(back);
+ backRow.Children.Add(backText);
+ var backButton = new Border { Background = Brushes.Transparent, Cursor = Cursors.Hand, Padding = new Thickness(2, 4, 8, 4), Child = backRow, HorizontalAlignment = HorizontalAlignment.Left };
+ backButton.MouseLeftButtonUp += (_, e) =>
+ {
+ e.Handled = true;
+ Flip();
+ };
+ var heading = _backHeading = Ui.Text(UiText.Get("MediaRecent"), 15.5, FontWeights.SemiBold);
+ heading.Margin = new Thickness(2, 6, 0, 10);
+ var top = new StackPanel();
+ top.Children.Add(backButton);
+ top.Children.Add(heading);
+ DockPanel.SetDock(top, Dock.Top);
+ _playedList = new StackPanel();
+ // A slim bar shows there is more below; the wheel moves the list (and never anything behind the card).
+ var scroll = _backScroll = new ScrollViewer { Content = _playedList, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled };
+ scroll.PreviewMouseWheel += (_, e) =>
+ {
+ e.Handled = true;
+ scroll.ScrollToVerticalOffset(Math.Clamp(scroll.VerticalOffset - e.Delta * 0.6, 0, scroll.ScrollableHeight));
+ };
+ var panel = new DockPanel { LastChildFill = true };
+ panel.Children.Add(top);
+ panel.Children.Add(scroll);
+ return panel;
+ }
+
+ /// <summary>The back: the browser's list when it could be read, otherwise the songs played lately.</summary>
+ private void FillBack(bool scrollToCurrent = false)
+ {
+ if (_playedList is null) return;
+ _playedList.Children.Clear();
+ if (_playlist.Count > 0)
+ {
+ _backHeading!.Text = UiText.Get("MediaPlaylist");
+ Border? now = null;
+ foreach (var song in _playlist)
+ {
+ var row = Row(Thumbnail(song), song.Title, song.Channel, song.Current, song.Current ? () => Flip() : () => PlaySong(song));
+ if (song.Current) now = row;
+ _playedList.Children.Add(row);
+ }
+ if (scrollToCurrent && now is not null)
+ {
+ // The playing song near the top, the ones coming after it below.
+ _playedList.Dispatcher.BeginInvoke(() => _backScroll?.ScrollToVerticalOffset(Math.Max(0, now.TranslatePoint(new Point(), _playedList).Y - 50)),
+ System.Windows.Threading.DispatcherPriority.Loaded);
+ }
+ return;
+ }
+ _backHeading!.Text = UiText.Get("MediaRecent");
+ if (_hiddenTab is not null)
+ {
+ var hint = Ui.Text(UiText.Get("MediaShowTab"), 12, FontWeights.SemiBold);
+ hint.TextWrapping = TextWrapping.Wrap;
+ var button = new Border
+ {
+ CornerRadius = new CornerRadius(10), Padding = new Thickness(10, 8, 10, 8), Margin = new Thickness(0, 0, 0, 8),
+ Background = Ui.Solid("#2EFFFFFF"), Cursor = Cursors.Hand, Child = hint
+ };
+ button.MouseEnter += (_, _) => button.Background = Ui.Solid("#40FFFFFF");
+ button.MouseLeave += (_, _) => button.Background = Ui.Solid("#2EFFFFFF");
+ button.MouseLeftButtonUp += (_, e) =>
+ {
+ e.Handled = true;
+ ShowHiddenTab();
+ };
+ _playedList.Children.Add(button);
+ }
+ if (_played.Count == 0)
+ {
+ var empty = Ui.Text(UiText.Get("MediaRecentEmpty"), 12, brushKey: "TextSecondary");
+ empty.Margin = new Thickness(2, 8, 0, 0);
+ _playedList.Children.Add(empty);
+ return;
+ }
+ var nowKey = $"{_title.Text}|{_artist.Text}";
+ foreach (var song in _played)
+ {
+ var playing = song.Key == nowKey || _played.IndexOf(song) == 0 && !_idle;
+ _playedList.Children.Add(Row(song.Cover, song.Title, song.Artist, playing, playing ? () => Flip() : null));
+ }
+ }
+
+ /// <summary>One song: its small cover, the title and the artist; the playing one is lit and marked.</summary>
+ private static Border Row(ImageSource? coverImage, string title, string artist, bool playing, Action? click)
+ {
+ var cover = new Border { Width = 42, Height = 42, CornerRadius = new CornerRadius(8), Background = Ui.Solid("#26FFFFFF") };
+ if (coverImage is not null) cover.Background = new ImageBrush(coverImage) { Stretch = Stretch.UniformToFill };
+ else cover.Child = new ContentControl { Content = Ui.Icon("IconMusic", 16, Ui.WhiteSoft), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
+ var name = Ui.Text(title, 12.5, FontWeights.SemiBold);
+ name.TextTrimming = TextTrimming.CharacterEllipsis;
+ var by = Ui.Text(artist, 11, brushKey: "TextSecondary");
+ by.TextTrimming = TextTrimming.CharacterEllipsis;
+ var words = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(10, 0, 6, 0) };
+ words.Children.Add(name);
+ if (artist.Length > 0) words.Children.Add(by);
+ var line = new DockPanel();
+ DockPanel.SetDock(cover, Dock.Left);
+ line.Children.Add(cover);
+ if (playing)
+ {
+ var mark = Ui.Icon("IconVolume", 13, Ui.White, null);
+ mark.VerticalAlignment = VerticalAlignment.Center;
+ DockPanel.SetDock(mark, Dock.Right);
+ line.Children.Add(mark);
+ }
+ line.Children.Add(words);
+ var idle = playing ? Ui.Solid("#24FFFFFF") : Brushes.Transparent;
+ var row = new Border
+ {
+ CornerRadius = new CornerRadius(10), Padding = new Thickness(6, 5, 8, 5), Margin = new Thickness(0, 0, 0, 3), Child = line,
+ Background = idle
+ };
+ if (click is null) return row;
+ row.Cursor = Cursors.Hand;
+ if (!playing)
+ {
+ row.MouseEnter += (_, _) => row.Background = Ui.Solid("#14FFFFFF");
+ row.MouseLeave += (_, _) => row.Background = idle;
+ }
+ row.MouseLeftButtonUp += (_, e) =>
+ {
+ e.Handled = true;
+ click();
+ };
+ return row;
+ }
+
+ /// <summary>Turns the card over: it narrows to an edge, the other face comes up, it widens again.</summary>
+ private void Flip(bool animate = true)
+ {
+ if (_front is null || _back is null) return;
+ void Swap()
+ {
+ _flipped = !_flipped;
+ if (_flipped)
+ {
+ FillBack(scrollToCurrent: true);
+ ReadPlaylist();
+ _back.Height = _front.ActualHeight; // the card keeps its size
+ _front.Visibility = Visibility.Hidden;
+ _back.Visibility = Visibility.Visible;
+ }
+ else
+ {
+ _front.Visibility = Visibility.Visible;
+ _back.Visibility = Visibility.Collapsed;
+ }
+ }
+ if (!animate)
+ {
+ _turn.BeginAnimation(ScaleTransform.ScaleXProperty, null);
+ _turn.ScaleX = 1;
+ if (_flipped) Swap();
+ return;
+ }
+ var fold = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(140)) { EasingFunction = new CubicEase { EasingMode = EasingMode.EaseIn } };
+ fold.Completed += (_, _) =>
+ {
+ Swap();
+ _turn.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(170)) { EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut } });
+ };
+ _turn.BeginAnimation(ScaleTransform.ScaleXProperty, fold);
+ }
+
/// <summary>The round arrow of a ten-second jump, with "10" in its middle.</summary>
private static Grid Jump(bool forward)
{
@@ -305,20 +617,9 @@ public sealed partial class MediaWidget
private void OpenAudio()
{
+ // The computer's own volume (what the keyboard's volume keys change), not the player's.
CloseAudio();
_endpoint = new AudioEndpoint();
- _sessions = new AudioSessions();
- var id = (_session?.SourceAppUserModelId ?? "").ToLowerInvariant();
- if (id.Length == 0) return;
- try
- {
- _playerAudio = _sessions.Read().FirstOrDefault(app =>
- {
- var exe = System.IO.Path.GetFileNameWithoutExtension(app.ExecutablePath ?? "").ToLowerInvariant();
- return exe.Length > 1 && id.Contains(exe) || id.Contains(app.Name.ToLowerInvariant().Replace(" ", ""));
- });
- }
- catch (Exception ex) when (ex is COMException or InvalidCastException) { _playerAudio = null; }
}
private void CloseAudio()
diff --git a/Widgets/MediaWidget.cs b/Widgets/MediaWidget.cs
index 758a08c..b8c6a9a 100644
--- a/Widgets/MediaWidget.cs
+++ b/Widgets/MediaWidget.cs
@@ -254,6 +254,8 @@ public sealed partial class MediaWidget : DockWidget
await LoadArtworkAsync(properties?.Thumbnail, version, newSong);
if (version != _refreshVersion) return;
if (newSong) RefreshAgainSoon();
+ Remember(title, artist, _art.Source);
+ _idle = false;
SetVisible(true);
UpdateProgressTimer();
if (CardOpen) FillCard();
@@ -318,12 +320,13 @@ public sealed partial class MediaWidget : DockWidget
}
/// <summary>
- /// Nothing playing: the tile stays (it used to vanish, and then it could be found neither in the dock nor in
- /// the add list) and says so; its play button sends the keyboard's play key, which resumes the last player.
+ /// Nothing playing: the tile leaves the dock (it comes back with the next song). While the dock is being edited it
+ /// stays, so it can still be moved or removed; its play button sends the keyboard's play key.
/// </summary>
private void ShowIdle()
{
_playing = false;
+ _idle = true;
_thumbnailKey = null;
_artSignature = null;
_art.Source = null;
@@ -334,7 +337,8 @@ public sealed partial class MediaWidget : DockWidget
_tile.ToolTip = UiText.Get("MediaIdleHint");
_playPause.Content = Ui.Glyph("GlyphPlay", 11);
_previous.IsEnabled = _next.IsEnabled = false;
- SetVisible(true);
+ // Nothing playing: no tile (it comes back with the next song); an open card keeps it until it closes.
+ SetVisible(CardOpen || _editing);
UpdateProgressTimer();
if (CardOpen) FillCard();
}
@@ -361,6 +365,15 @@ public sealed partial class MediaWidget : DockWidget
}
}
+ private bool _idle;
+ private bool _editing;
+
+ public override void SetEditing(bool editing)
+ {
+ _editing = editing;
+ if (_idle) SetVisible(editing || CardOpen);
+ }
+
private void SetVisible(bool visible)
{
var target = visible ? Visibility.Visible : Visibility.Collapsed;
diff --git a/Widgets/ProfileWidget.cs b/Widgets/ProfileWidget.cs
index 3c1071a..0df85e5 100644
--- a/Widgets/ProfileWidget.cs
+++ b/Widgets/ProfileWidget.cs
@@ -30,7 +30,7 @@ public sealed class ProfileWidget : DockWidget
public ProfileWidget()
{
- var icon = Ui.Icon("IconLayout", 15);
+ var icon = Ui.Icon("IconPerson", 15);
icon.Margin = new Thickness(0, 0, 8, 0);
var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };
_caption = Ui.Text("", 10, brushKey: "TextSecondary");
@@ -110,7 +110,7 @@ public sealed class ProfileWidget : DockWidget
{
_popup.Close();
if (index != Current.EffectiveActiveProfile) UpdateSettings(s => s.SwitchProfile(index));
- Ui.ShowHud("IconLayout", profiles[index].Name);
+ Ui.ShowHud("IconPerson", profiles[index].Name);
}));
}
@@ -126,7 +126,7 @@ public sealed class ProfileWidget : DockWidget
{
_popup.Close();
UpdateSettings(s => s.AddProfile(name));
- Ui.ShowHud("IconLayout", UiText.Format("ProfileCreated", name));
+ Ui.ShowHud("IconPerson", UiText.Format("ProfileCreated", name));
}));
}
diff --git a/Widgets/WidgetBar.cs b/Widgets/WidgetBar.cs
index 97c996e..37918ea 100644
--- a/Widgets/WidgetBar.cs
+++ b/Widgets/WidgetBar.cs
@@ -21,6 +21,11 @@ public sealed class WidgetBar : StackPanel, IDisposable
private string _signature = "";
public event EventHandler? LayoutInvalidated;
+
+ /// <summary>A tile opens out (true) or has closed again (false).</summary>
+ public event EventHandler<bool>? WidgetExpanding;
+
+ private readonly HashSet<DockWidget> _expanding = [];
public event EventHandler? SettingsRequested;
/// <summary>Raised in edit mode with the new widget settings (order or hidden list changed).</summary>
@@ -109,6 +114,13 @@ public sealed class WidgetBar : StackPanel, IDisposable
foreach (var widget in all)
{
widget.LayoutChanged += (_, _) => LayoutInvalidated?.Invoke(this, EventArgs.Empty);
+ widget.Expanding += (_, on) =>
+ {
+ if (on) _expanding.Add(widget);
+ else _expanding.Remove(widget);
+ WidgetExpanding?.Invoke(this, on);
+ if (!on && _expanding.Count == 0) 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)
@@ -119,6 +131,7 @@ public sealed class WidgetBar : StackPanel, IDisposable
}
SizeChanged += (_, e) =>
{
+ if (_expanding.Count > 0) return; // a tile opening out: the dock keeps its width meanwhile
if (Math.Abs(e.NewSize.Width - e.PreviousSize.Width) > 0.5) LayoutInvalidated?.Invoke(this, EventArgs.Empty);
};
}
@@ -147,6 +160,7 @@ public sealed class WidgetBar : StackPanel, IDisposable
if (IsEditing == editing) return;
IsEditing = editing;
ClosePopups();
+ foreach (var widget in _widgets.Values) widget.SetEditing(editing);
_signature = "";
Apply(_settings);
EditingChanged?.Invoke(this, EventArgs.Empty);
diff --git a/Widgets/WidgetUi.cs b/Widgets/WidgetUi.cs
index 6e72426..ebb3be5 100644
--- a/Widgets/WidgetUi.cs
+++ b/Widgets/WidgetUi.cs
@@ -40,6 +40,17 @@ public abstract class DockWidget : IDisposable
public virtual void Dispose() => Stop();
protected void RaiseLayoutChanged() => LayoutChanged?.Invoke(this, EventArgs.Empty);
+
+ /// <summary>The dock is being edited (or no longer).</summary>
+ public virtual void SetEditing(bool editing) { }
+
+ /// <summary>
+ /// The tile opens out sideways for a moment (true) or has closed again (false). Meanwhile the dock keeps its
+ /// width: what stands after the tile slides out of the dock's end and comes back when it closes.
+ /// </summary>
+ public event EventHandler<bool>? Expanding;
+
+ protected void RaiseExpanding(bool expanding) => Expanding?.Invoke(this, expanding);
protected void RequestSettings() => SettingsRequested?.Invoke(this, EventArgs.Empty);
}
@@ -69,6 +80,11 @@ public sealed class WidgetPopup
/// <summary>Any widget card opened (the bar hides its profile tabs so they do not cover it).</summary>
public static event EventHandler? AnyOpened;
+ /// <summary>Any widget card or strip closed (a dock that hides itself may go now).</summary>
+ public static event EventHandler? AnyClosed;
+
+ internal static void RaiseAnyClosed() => AnyClosed?.Invoke(null, EventArgs.Empty);
+
public WidgetPopup(FrameworkElement target)
{
_target = target;
@@ -97,6 +113,7 @@ public sealed class WidgetPopup
{
_outsideClickWatch.Stop();
Closed?.Invoke(this, EventArgs.Empty);
+ AnyClosed?.Invoke(this, EventArgs.Empty);
};
// Keep the card centered above the tile when its size changes while open.
_surface.SizeChanged += (_, _) =>
@@ -149,7 +166,11 @@ public sealed class WidgetPopup
Opened?.Invoke(this, EventArgs.Empty);
AnyOpened?.Invoke(this, EventArgs.Empty);
};
- sheet.SheetHidden += (_, _) => Closed?.Invoke(this, EventArgs.Empty);
+ sheet.SheetHidden += (_, _) =>
+ {
+ Closed?.Invoke(this, EventArgs.Empty);
+ AnyClosed?.Invoke(this, EventArgs.Empty);
+ };
}
_surface.Child = null;
_sheet.Body = _content;