A macOS-style dock, widget bar and desktop widgets for Windows (WPF, .NET 10)
Release 0.4.0
QiDock contributors3d31c3301533
diff --git a/App.xaml.cs b/App.xaml.csindex fd0221a..06016f4 100644--- a/App.xaml.cs+++ b/App.xaml.cs@@ -52,6 +52,15 @@ public partial class App : ApplicationDesktopWidgets.DeskSheet.Render(sheet, () => Preferences.Current.WidgetOptions, () => Shutdown());return;}+ if (e.Args is ["--promo-shots", var promoFolder, var promoLanguage, .. var promoSteps])+ {+ // The pictures of the promotional videos, with made-up data (QIDOCK_PROMO=1); see PromoShots.+ ShutdownMode = ShutdownMode.OnExplicitShutdown;+ UiText.Current.SetLanguage(promoLanguage == "en" ? Models.AppLanguage.English : Models.AppLanguage.Turkish);+ ThemeManager.Apply(Models.AppTheme.Dark, Preferences.Current.SurfaceOpacity, ThemeStyles.Glass);+ PromoShots.Render(promoFolder, promoSteps.FirstOrDefault(), () => 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.diff --git a/AppGrid.cs b/AppGrid.csindex 4d45198..766b1b2 100644--- a/AppGrid.cs+++ b/AppGrid.cs@@ -220,12 +220,33 @@ public sealed class AppGridWindow : OverlayWindow/// 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();+ private static (double Dip, int Pixels) _iconSize;++ /// <summary>The icons' size, measured again each time: when the screen's scale changes the cached icons go.</summary>+ private static (double Dip, int Pixels) IconSize+ {+ get+ {+ var now = MeasureIcon();+ if (now != _iconSize)+ {+ _iconSize = now;+ Icons.Clear();+ }+ return _iconSize;+ }+ }/// <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;+ // Asked of Windows for the main screen itself: QiDock's own windows may not be on screen yet when the first+ // icons are read, and a guess of 100% made every icon a blurred enlargement of a picture half its size.+ private static double ScreenScale =>+ GetDpiForMonitor(MonitorFromPoint(0 /* the point 0,0 */, 1 /* primary */), 0 /* effective */, out var dpi, out _) == 0 && dpi > 0+ ? dpi / 96.0+ : VisualTreeHelper.GetDpi(Application.Current?.MainWindow ?? (Visual)new DrawingVisual()).DpiScaleX;++ [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern nint MonitorFromPoint(long point, uint flags);+ [System.Runtime.InteropServices.DllImport("shcore.dll")] private static extern int GetDpiForMonitor(nint monitor, int type, out uint dpiX, out uint dpiY);private static (double, int) MeasureIcon(){@@ -326,9 +347,11 @@ public sealed class AppGridWindow : OverlayWindow{AppList.RefreshAsync().ContinueWith(t =>{- var ids = LaunchStore.Merge(LaunchStore.Load(), t.Result)- .Take(80)- .SelectMany(e => e.IsFolder ? e.Apps!.Take(9) : [e.App!])+ // What the first view shows: the folders and the most used apps (the rest load when a tab shows them).+ var scores = AppUsage.Scores();+ var entries = LaunchStore.Merge(LaunchStore.Load(), t.Result);+ var ids = entries.Where(e => e.IsFolder).SelectMany(e => e.Apps!.Take(9))+ .Concat(entries.Where(e => !e.IsFolder).Select(e => e.App!).OrderByDescending(id => scores.GetValueOrDefault(id)).Take(30)).Where(id => !Icons.ContainsKey(id)).ToList();if (ids.Count == 0) return;@@ -347,8 +370,10 @@ public sealed class AppGridWindow : OverlayWindow/// <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){+ Services.Widgets.WallpaperGlass.Refresh(); // as the running dock has itvar window = new AppGridWindow { ShowActivated = false };window.Show();+ if (Services.Promo.On) window.Left = -30000; // drawn for a picture only, never seenwindow.Root.Opacity = 1;var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(4) };timer.Tick += (_, _) =>@@ -555,14 +580,14 @@ public sealed class AppGridWindow : OverlayWindow}/// <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+ /// The panel becomes neutral frosted glass: the desktop picture behind it, softened and almost without colour+ /// (a pink wallpaper dyed the whole panel), 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)+ var veil = Color.FromArgb(0x66, 0x0C, 0x0C, 0x10);+ if (Services.Widgets.GlassLook.Surface(new Rect(panel.Size), panel, veil, sheen: true, frost: true) is { } wallpaper){_panel.Background = wallpaper;return;@@ -663,15 +688,26 @@ public sealed class AppGridWindow : OverlayWindowprivate void Load(IReadOnlyList<InstalledApp> apps){+#if DEBUG+ if (Services.Promo.On) apps = Services.Promo.Named(apps.Where(a => Services.Promo.IsWindowsApp(a.Id)).ToList());+#endif_known.Clear();foreach (var app in apps) _known.TryAdd(app.Id, app);_items = LaunchStore.Merge(LaunchStore.Load(), apps);var scores = AppUsage.Scores();+#if DEBUG+ if (Services.Promo.On)+ {+ _items = LaunchStore.Merge([], apps);+ scores = Services.Promo.AppScores(apps);+ }+#endif+ // "Tümü" shows only these (with the folders): the most used apps, at most two rows. Every other app is+ // under its category or found by typing, so the first view stays short and quick to draw._frequent = apps- .Where(a => scores.ContainsKey(a.Id))+ .Where(a => scores.GetValueOrDefault(a.Id) > 0).OrderByDescending(a => scores[a.Id]).ThenBy(a => a.Name, StringComparer.CurrentCultureIgnoreCase)- // 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();@@ -802,13 +838,9 @@ public sealed class AppGridWindow : OverlayWindowvar 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);+ // The rest only while nothing has been used yet (a new computer): otherwise the panel would be empty.+ if (_frequent.Count == 0)+ foreach (var entry in Sorted(_items.Where(e => !e.IsFolder))) Put(entry);}EndRow();_contentHeight = y + 10;diff --git a/Assets/QiDock.ico b/Assets/QiDock.iconew file mode 100644index 0000000..665464cBinary files /dev/null and b/Assets/QiDock.ico differdiff --git a/Assets/QiDock.svg b/Assets/QiDock.svgnew file mode 100644index 0000000..48bef7d--- /dev/null+++ b/Assets/QiDock.svg@@ -0,0 +1,16 @@+<svg viewBox="0 0 1024 1024" width="1024" height="1024" xmlns="http://www.w3.org/2000/svg">+ <defs>+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0" stop-color="#62AEFF"/>+ <stop offset="0.5" stop-color="#8A62F6"/>+ <stop offset="1" stop-color="#F86CA6"/>+ </linearGradient>+ </defs>+ <rect x="40" y="40" width="944" height="944" rx="212" fill="url(#bg)"/>+ <g fill="#F7F3FF">+ <rect x="268" y="372" width="152" height="152" rx="34"/>+ <rect x="436" y="372" width="152" height="152" rx="34"/>+ <rect x="604" y="372" width="152" height="152" rx="34"/>+ <rect x="180" y="610" width="664" height="176" rx="88"/>+ </g>+</svg>diff --git a/Browser/NotchBrowser.cs b/Browser/NotchBrowser.csdeleted file mode 100644index ceccd7b..0000000--- a/Browser/NotchBrowser.cs+++ /dev/null@@ -1,119 +0,0 @@-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.csdeleted file mode 100644index ca13542..0000000--- a/Browser/NotchBrowserStore.cs+++ /dev/null@@ -1,48 +0,0 @@-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.csdeleted file mode 100644index 93aa1a0..0000000--- a/Browser/NotchBrowserWindow.cs+++ /dev/null@@ -1,854 +0,0 @@-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/ControlCenter.cs b/ControlCenter.csindex acad5cf..740b996 100644--- a/ControlCenter.cs+++ b/ControlCenter.cs@@ -32,7 +32,8 @@ public sealed partial class ControlCenter : EdgePanelprivate readonly AudioEndpoint _audio = new();private readonly RadioControls _radios = new();private readonly DispatcherTimer _brightnessDelay = new() { Interval = TimeSpan.FromMilliseconds(120) };- private bool _radiosStarted;+ private Task? _radiosReady;+ private bool _builtWithRadios;private int _pendingBrightness = -1;private Slider? _volumeSlider;private AudioEndpoint.State? _shownVolume;@@ -56,13 +57,8 @@ public sealed partial class ControlCenter : EdgePanelprotected override async void OnOpened(){var shown = Brightness.Current;- var work = new List<Task> { Brightness.RefreshAsync(), Task.Delay(480) };- var firstRadios = !_radiosStarted;- if (firstRadios)- {- _radiosStarted = true;- work.Add(_radios.InitializeAsync());- }+ _radiosReady ??= _radios.InitializeAsync();+ var work = new List<Task> { Brightness.RefreshAsync(), Task.Delay(480), _radiosReady };try { await Task.WhenAll(work); }catch (Exception ex){@@ -73,7 +69,17 @@ public sealed partial class ControlCenter : EdgePanelAudioEndpoint.State? volume;try { volume = await AudioEndpoint.ReadInBackgroundAsync(); }catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or InvalidCastException) { volume = _shownVolume; }- if (firstRadios || Brightness.Current != shown || volume != _shownVolume) Refresh();+ if (!_builtWithRadios || Brightness.Current != shown || volume != _shownVolume) Refresh();+ }++ /// <summary>+ /// Reads what the panel shows (brightness, the radios) ahead of time, when the pointer comes onto the button: the+ /// panel then opens complete instead of growing a row a moment later.+ /// </summary>+ public static void Prepare()+ {+ if (!Brightness.Known) _ = Brightness.RefreshAsync();+ Shared._radiosReady ??= Shared._radios.InitializeAsync();}/// <summary>The volume keys (or another app) changed the volume: the open panel's slider follows.</summary>@@ -113,6 +119,7 @@ public sealed partial class ControlCenter : EdgePanelprotected override void Build(){Cards.Children.Clear();+ _builtWithRadios = _radiosReady?.IsCompleted == true;var top = new Grid { Width = CardWidth, Margin = new Thickness(0, 0, 0, 10), Tag = "top" };top.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(Half) });top.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(10) });@@ -142,8 +149,12 @@ public sealed partial class ControlCenter : EdgePanelif (_showNetworks) Cards.Children.Add(Keyed("networks", NetworksCard()));Cards.Children.Add(Keyed("volume", VolumeCard()));- if (Brightness.Current is { } level) Cards.Children.Add(Keyed("brightness", BrightnessCard(level)));- if (BatteryStatus.Read() is { } battery) Cards.Children.Add(Keyed("battery", BatteryCard(battery)));+ var battery = BatteryStatus.Read();+ // Not read yet on a laptop (its screen has a brightness): the row keeps its place from the start, so the+ // panel does not jump when the level arrives.+ var level = Brightness.Current ?? (!Brightness.Known && battery is not null ? 100 : null);+ if (level is { } shownLevel) Cards.Children.Add(Keyed("brightness", BrightnessCard(shownLevel)));+ if (battery is { } state) Cards.Children.Add(Keyed("battery", BatteryCard(state)));Cards.Children.Add(Keyed("shortcuts", Shortcuts()));}@@ -409,6 +420,9 @@ internal static class Brightness/// <summary>The last level read, or null when there is no adjustable display.</summary>public static int? Current { get; private set; }+ /// <summary>Whether it has been read at least once (until then <see cref="Current"/> says nothing).</summary>+ public static bool Known { get; private set; }+public static Task RefreshAsync() => _unsupported ? Task.CompletedTask : Task.Run(() =>{try@@ -416,6 +430,7 @@ internal static class Brightnessforeach (dynamic item in Query("SELECT CurrentBrightness FROM WmiMonitorBrightness WHERE Active=TRUE")){Current = Convert.ToInt32(item.Properties_.Item("CurrentBrightness").Value);+ Known = true;return;}_unsupported = true;@@ -425,6 +440,7 @@ internal static class BrightnessSystem.Diagnostics.Trace.TraceWarning("Brightness unavailable: {0}", ex.Message);}Current = null;+ Known = true;});private static readonly object Gate = new();diff --git a/Design/Theme.xaml b/Design/Theme.xamlindex 7cade61..384c974 100644--- a/Design/Theme.xaml+++ b/Design/Theme.xaml@@ -29,6 +29,10 @@<Thickness x:Key="DockPadding">8,0,8,0</Thickness><Thickness x:Key="ControlStroke">1</Thickness><CornerRadius x:Key="DockRadius">18</CornerRadius>+ <!-- A theme's own texture and bottom band on the dock (Services/ThemePatterns.cs); none for Glass. -->+ <SolidColorBrush x:Key="DockPattern" Color="Transparent" />+ <SolidColorBrush x:Key="DockBand" Color="Transparent" />+ <sys:Double x:Key="DockBandHeight">0</sys:Double><CornerRadius x:Key="ControlRadius">12</CornerRadius><CornerRadius x:Key="PopupRadius">10</CornerRadius><Style TargetType="ToolTip">diff --git a/DesktopWidgets/DeskHubs.cs b/DesktopWidgets/DeskHubs.csindex c1518fa..4633199 100644--- a/DesktopWidgets/DeskHubs.cs+++ b/DesktopWidgets/DeskHubs.cs@@ -1,4 +1,4 @@-using System.Globalization;+using System.Globalization;using System.IO;using System.Net.NetworkInformation;using System.Runtime.InteropServices;@@ -89,6 +89,14 @@ internal sealed class SystemHub : HubBase_lastIdle = idle;_lastTotal = total;}+#if DEBUG+ if (Services.Promo.On)+ {+ if (CpuHistory.Count == 0)+ for (var i = 0; i < HistoryLength; i++) Push(CpuHistory, Services.Promo.NextCpu());+ Cpu = Services.Promo.NextCpu();+ }+#endifPush(CpuHistory, Cpu);var memory = new MemoryStatus { Length = (uint)Marshal.SizeOf<MemoryStatus>() };diff --git a/DesktopWidgets/DeskWidgetManager.cs b/DesktopWidgets/DeskWidgetManager.csindex b8cbf57..346b1da 100644--- a/DesktopWidgets/DeskWidgetManager.cs+++ b/DesktopWidgets/DeskWidgetManager.cs@@ -1,4 +1,4 @@-using System.Windows;+using System.Windows;using System.Windows.Threading;using QiDock.Services.Widgets;@@ -69,6 +69,12 @@ internal sealed class DeskWidgetManager : IDisposable_wallpaperTimer.Start();}+ private void OnWallpaperChosen()+ {+ _wallpaperTimer.Stop();+ _wallpaperTimer.Start();+ }+public IReadOnlyList<DeskItem> Items => _layout.Items;public void Start()@@ -82,6 +88,7 @@ internal sealed class DeskWidgetManager : IDisposableDeskCardFace.GlassEnabled = _layout.Glass;WallpaperGlass.Refresh();Microsoft.Win32.SystemEvents.UserPreferenceChanged += OnPreferenceChanged;+ Services.WallpaperGallery.Applied += OnWallpaperChosen;foreach (var item in _layout.Items.ToList()) Open(item);}@@ -294,6 +301,7 @@ internal sealed class DeskWidgetManager : IDisposable{_disposed = true;Microsoft.Win32.SystemEvents.UserPreferenceChanged -= OnPreferenceChanged;+ Services.WallpaperGallery.Applied -= OnWallpaperChosen;_saveTimer.Stop();_recreateTimer.Stop();_wallpaperTimer.Stop();diff --git a/DockHud.cs b/DockHud.csindex 2ded32c..7186108 100644--- a/DockHud.cs+++ b/DockHud.cs@@ -69,6 +69,13 @@ public sealed class DockHud : EdgePanel#if DEBUGinternal void RehearseLevel(string iconKey, string label, int percent, Brush accent) => SetLevel(iconKey, label, percent, accent, false);++ internal void RehearseMessage(string iconKey, string text)+ {+ _icon.Content = Ui.Icon(iconKey, 20);+ _label.Text = text;+ _track.Visibility = _value.Visibility = Visibility.Collapsed;+ }#endifprivate void SetLevel(string iconKey, string label, int percent, Brush accent, bool dimmed)diff --git a/EdgePanel.cs b/EdgePanel.csindex cb54f68..9b9b2cb 100644--- a/EdgePanel.cs+++ b/EdgePanel.cs@@ -445,6 +445,46 @@ public abstract class EdgePanel : Windowreturn stage;}+ /// <summary>+ /// Debug snapshot run: the panel placed on a dock drawn elsewhere (screen DIPs in <paramref name="dock"/>), as+ /// opening it there would place it. Returns its frame (for the caller to put at <c>Bounds</c>) and draw with+ /// <see cref="RehearseDockMorph"/>.+ /// </summary>+ internal (FrameworkElement Frame, Rect Bounds) RehearseOnDock(DockAnchor dock)+ {+ Build();+ TrimLastGap();+ Content = null;+ _dock = dock;+ _sheetMax = 4000;+ PlaceOnDock(dock, CardWidth + 2 * Pad, ContentHeight());+ _frame.Width = _frameSize.Width;+ _frame.Height = _frameSize.Height;+ _frame.HorizontalAlignment = HorizontalAlignment.Left;+ _frame.VerticalAlignment = VerticalAlignment.Top;+ _sheet.Background = Brushes.Transparent;+ _sheet.BorderThickness = new Thickness(0);+ PaintDockShape();+ _shape.Visibility = Visibility.Visible;+ _outline.Visibility = Visibility.Collapsed;+ return (_frame, new Rect(Left, Top, _frameSize.Width, _frameSize.Height));+ }++ /// <summary>+ /// Debug snapshot run: the panel from <see cref="RehearseOnDock"/> at <paramref name="progress"/> (0 = inside the+ /// tile, 1 = open), its content at <paramref name="content"/> opacity and <paramref name="rise"/> points low.+ /// Returns the stretch of the dock's top edge (screen DIPs) the dock leaves out under it.+ /// </summary>+ internal (double Left, double Right)? RehearseDockMorph(double progress, double content, double rise)+ {+ if (_dock is not { } dock) return null;+ (double Left, double Right)? seam = null;+ ApplyMorph(progress, _frameSize.Width, _frameSize.Height, dock.TileCenter - Left, dock.TileWidth, Fillet + Slack, range => seam = range);+ _scroll.Opacity = content;+ foreach (UIElement card in Cards.Children) Motion.Shift(card).Y = rise;+ return seam is { } r ? (r.Left + Left, r.Right + Left) : null;+ }+/// <summary>Draws the rehearsed dock-grown panel at <paramref name="progress"/> (0 = inside the tile, 1 = open).</summary>internal void RehearseMorph(double progress){diff --git a/Files/FilesWindow.Panels.cs b/Files/FilesWindow.Panels.csindex 38fa061..99787c6 100644--- a/Files/FilesWindow.Panels.cs+++ b/Files/FilesWindow.Panels.cs@@ -1,4 +1,4 @@-using System.Globalization;+using System.Globalization;using System.IO;using System.Windows;using System.Windows.Controls;@@ -59,6 +59,10 @@ internal sealed partial class FilesWindowAddPlace(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));+#if DEBUG+ if (Services.Promo.On) AddPlace(list, GlyphHome, L("Kişisel klasör", "Home"), home);+ else+#endifAddPlace(list, GlyphHome, Path.GetFileName(home), home);list.Children.Add(SectionTitle(L("Konumlar", "Locations")));@@ -189,6 +193,9 @@ internal sealed partial class FilesWindow}catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }}+#if DEBUG+ if (Services.Promo.On) found = found.Where(f => f.Path.Length <= 3 && f.Path.StartsWith("C", StringComparison.OrdinalIgnoreCase)).ToList();+#endifreturn found;});if (_locations is null) return;diff --git a/Files/ShellThumbnails.cs b/Files/ShellThumbnails.csindex 23a769e..28e3169 100644--- a/Files/ShellThumbnails.cs+++ b/Files/ShellThumbnails.cs@@ -164,7 +164,15 @@ internal static class ShellThumbnails}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);+ // Icons usually come with plain (not premultiplied) transparency; read as premultiplied their soft edges glow+ // white or pink. A colour stronger than its own opacity can only be plain transparency.+ var plain = false;+ for (var i = 0; i < pixels.Length && !plain; i += 4)+ {+ var alpha = pixels[i + 3];+ plain = pixels[i] > alpha || pixels[i + 1] > alpha || pixels[i + 2] > alpha;+ }+ var source = BitmapSource.Create(width, height, 96, 96, plain ? PixelFormats.Bgra32 : PixelFormats.Pbgra32, null, pixels, width * 4);source.Freeze();return source;}diff --git a/MainWindow.DockGlass.cs b/MainWindow.DockGlass.csindex ee7734e..3e14e60 100644--- a/MainWindow.DockGlass.cs+++ b/MainWindow.DockGlass.cs@@ -1,4 +1,4 @@-using System.Windows;+using System.Windows;using System.Windows.Media;using System.Windows.Threading;using QiDock.Services;@@ -44,15 +44,20 @@ public partial class MainWindow_dockGlassWallpaper.Start();});};+ WallpaperGallery.Applied += () =>+ {+ _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+ /// Glass when it is on and the theme is "Cam" (the other themes bring their own colours to the dock: under glass+ /// only their writing changed), 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()@@ -60,7 +65,9 @@ public partial class MainWindowvar 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)+ var glass = _dockGlassOn && ThemeManager.CurrentStyle == ThemeStyles.Glass;+ if (glass && WallpaperGlass.Image is null) WallpaperGlass.Refresh();+ if (!glass || WallpaperGlass.Image is null || DockToScreen() is not { } toScreen){GlassLook.DockVeil = null;GlassLook.Tiles(Resources, false);diff --git a/MainWindow.DockMenu.cs b/MainWindow.DockMenu.csindex da10dde..7d25cab 100644--- a/MainWindow.DockMenu.cs+++ b/MainWindow.DockMenu.cs@@ -196,10 +196,6 @@ public partial class MainWindowpeek.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);diff --git a/MainWindow.TopBar.cs b/MainWindow.TopBar.csindex 5eacad3..96d51ce 100644--- a/MainWindow.TopBar.cs+++ b/MainWindow.TopBar.cs@@ -37,7 +37,6 @@ 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();diff --git a/MainWindow.xaml b/MainWindow.xamlindex be9fb99..2221109 100644--- a/MainWindow.xaml+++ b/MainWindow.xaml@@ -177,6 +177,11 @@<Border.Effect><DropShadowEffect Color="#000000" BlurRadius="20" ShadowDepth="3" Direction="270" Opacity="0.38" RenderingBias="Performance" /></Border.Effect>+ <Grid>+ <!-- The theme's own texture and bottom band (none for Glass), under the icons, over the dock's colour. -->+ <Border Margin="-8,0,-8,0" CornerRadius="17" Background="{DynamicResource DockPattern}" IsHitTestVisible="False" />+ <Border Margin="-8,0,-8,0" CornerRadius="0,0,17,17" VerticalAlignment="Bottom" Height="{DynamicResource DockBandHeight}"+ Background="{DynamicResource DockBand}" IsHitTestVisible="False" /><ctl:UnclippedStackPanel x:Name="DockRow" Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center"><ctl:UnclippedStackPanel x:Name="DockContents" Orientation="Horizontal" HorizontalAlignment="Left"VerticalAlignment="Center">@@ -395,6 +400,7 @@</ctl:UnclippedStackPanel><ContentControl x:Name="WidgetHost" VerticalAlignment="Top" Margin="2,1,0,0" Focusable="False" Visibility="Collapsed" /></ctl:UnclippedStackPanel>+ </Grid></Border><Border x:Name="DockEdgeTrigger" Grid.Row="1" VerticalAlignment="Bottom" Height="2" Background="#01000000"MouseEnter="DockEdgeTrigger_MouseEnter" MouseLeave="DockEdgeTrigger_MouseLeave" />diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.csindex 76e3dab..f10cb3c 100644--- a/MainWindow.xaml.cs+++ b/MainWindow.xaml.cs@@ -1778,7 +1778,6 @@ public partial class MainWindow : WindowApplyWidgetPlacement();ApplyDockEdge();_topBar?.SetPeekEnabled(_preferences.Current.TopBarPeek);- ApplyNotchBrowser();ApplyDockGlass();_deskWidgets?.SettingsChanged();ApplyToastHiding();@@ -1948,16 +1947,9 @@ public partial class MainWindow : Windowif (_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();diff --git a/Models/DockSettings.cs b/Models/DockSettings.csindex 826dd33..87585c1 100644--- a/Models/DockSettings.cs+++ b/Models/DockSettings.cs@@ -43,7 +43,6 @@ public sealed record DockSettings(bool Magnify = false,double MagnifyScale = 1.85,bool LowMemory = false,- bool NotchBrowser = true,bool DockGlass = true,double DockScale = 1.0){diff --git a/PromoShots.cs b/PromoShots.csnew file mode 100644index 0000000..2f6e572--- /dev/null+++ b/PromoShots.cs@@ -0,0 +1,685 @@+#if DEBUG+using System.IO;+using System.Text.Json;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Media;+using System.Windows.Media.Animation;+using System.Windows.Media.Effects;+using System.Windows.Media.Imaging;+using System.Windows.Shapes;+using QiDock.DesktopWidgets;+using QiDock.Models;+using QiDock.Services;+using QiDock.Services.Notifications;+using QiDock.Services.Widgets;+using QiDock.Widgets;++namespace QiDock;++/// <summary>+/// Debug builds only (<c>--promo-shots <folder> <tr|en> [steps]</c>, with QIDOCK_PROMO=1): the pictures the+/// promotional videos are made of, drawn by QiDock's own code with made-up data (see <see cref="Promo"/>): the dock in+/// every look, the dock's messages, the music card growing out of the dock, icons, desktop scenes, the settings pages, the Files+/// window and the app screen. Twice the screen's size, transparent around floating parts.+/// </summary>+internal static class PromoShots+{+ private const double Scale = 2;+ private static string _folder = "";+ private static readonly Dictionary<string, object> Layout = [];++ /// <summary>Apps everyone knows (and Windows' own): nothing personal or little known appears in the videos.</summary>+ private static readonly string[] DockApps =+ [+ "Microsoft.Windows.Explorer", "Chrome", "MSEdge", "5319275A.WhatsAppDesktop_cv1g1gvanyjgm!App", "Telegram.TelegramDesktop",+ "Microsoft.Office.WINWORD.EXE.15", "Microsoft.Office.EXCEL.EXE.15", "Microsoft.OutlookForWindows_8wekyb3d8bbwe!Microsoft.OutlookforWindows",+ "Microsoft.Windows.Photos_8wekyb3d8bbwe!App", "Microsoft.WindowsCalculator_8wekyb3d8bbwe!App", "Microsoft.WindowsStore_8wekyb3d8bbwe!App",+ "windows.immersivecontrolpanel_cw5n1h2txyewy!microsoft.windows.immersivecontrolpanel"+ ];++ public static async void Render(string folder, string? only, Action done)+ {+ _folder = folder;+ Directory.CreateDirectory(folder);+ var steps = new (string Name, Func<Task> Run)[]+ {+ ("dock", Docks), ("hud", Huds), ("music", MusicDesk), ("icons", Icons), ("desk", Desks),+ ("settings", Settings), ("files", Files), ("apps", Apps)+ };+ var wanted = only?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);+ foreach (var (name, run) in steps)+ {+ if (wanted is { Length: > 0 } && !wanted.Contains(name)) continue;+ try+ {+ await run();+ }+ catch (Exception ex)+ {+ File.WriteAllText(System.IO.Path.Combine(folder, $"{name}.error.txt"), ex.ToString());+ }+ }+ var layoutFile = System.IO.Path.Combine(folder, "layout.json");+ var merged = new Dictionary<string, JsonElement>();+ if (File.Exists(layoutFile))+ foreach (var pair in JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(File.ReadAllText(layoutFile)) ?? []) merged[pair.Key] = pair.Value;+ foreach (var pair in Layout) merged[pair.Key] = JsonSerializer.SerializeToElement(pair.Value);+ File.WriteAllText(layoutFile, JsonSerializer.Serialize(merged, new JsonSerializerOptions { WriteIndented = true }));+ done();+ }++ /// <summary>The widgets' settings with a well-known city for the weather (not this computer owner's).</summary>+ private static WidgetSettings Options => ((App)Application.Current).Preferences.Current.WidgetOptions with+ {+ WeatherCity = UiText.Current.Language == AppLanguage.English ? "Paris" : "İstanbul"+ };+ private static double Opacity => ((App)Application.Current).Preferences.Current.SurfaceOpacity;++ // ---- Dock -------------------------------------------------------------------------------------------------++ private static async Task Docks()+ {+ var widgets = LiveWidgets();+ await Task.Delay(7000);+ var (dock, ring) = BuildDock(widgets);+ var host = Pad(dock, 36);+ // In a window (out of sight), so a new theme reaches every part of the dock as it does on the screen.+ var stage = Stage(host);+ foreach (var look in ThemeStyles.All)+ {+ ThemeManager.Apply(AppTheme.Dark, Opacity, look.Id);+ await Task.Delay(250);+ Save(host, $"dock-{look.Id}.png");+ }+ ThemeManager.Apply(AppTheme.Dark, Opacity, ThemeStyles.Glass);+ ring.Visibility = Visibility.Visible;+ await Task.Delay(250);+ Save(host, "dock-keyboard.png");+ ring.Visibility = Visibility.Collapsed;+ stage.Close();+ foreach (var widget in widgets) widget.Dispose();+ }++ private static DockWidget[] LiveWidgets()+ {+ DockWidget[] widgets = [new ClockWidget(), new WeatherWidget(), new ControlCenterWidget()];+ foreach (var widget in widgets)+ {+ widget.Current = Options;+ widget.ApplySettings(Options);+ widget.Start();+ widget.SetLive(true);+ }+ return widgets;+ }++ /// <summary>The dock as it stands on the screen: its material, the theme's pattern and band, app icons with running dots, and widget tiles.</summary>+ private static (Border Dock, Border Ring) BuildDock(IEnumerable<DockWidget> widgets, int apps = 12)+ {+ const double tile = 50, icon = 44;+ var row = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };+ var ring = new Border();+ var index = 0;+ foreach (var id in DockApps.Take(apps))+ {+ if (NotificationApps.LoadIcon(id, 128, exact: true) is not { } image) continue;+ var cell = new Grid { Width = tile, Height = tile + 6, Margin = new Thickness(1.5, 0, 1.5, 0) };+ var picture = new Image { Source = image, Width = icon, Height = icon, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(0, 4, 0, 0) };+ RenderOptions.SetBitmapScalingMode(picture, BitmapScalingMode.HighQuality);+ cell.Children.Add(picture);+ if (index is 0 or 1 or 3 or 6)+ {+ var dot = new Ellipse { Width = 4, Height = 4, VerticalAlignment = VerticalAlignment.Bottom, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 0, 0, 1) };+ dot.SetResourceReference(Shape.FillProperty, "IndicatorBrush");+ cell.Children.Add(dot);+ }+ if (index == 2)+ {+ ring = new Border+ {+ Width = icon + 10, Height = icon + 10, CornerRadius = new CornerRadius(13), BorderThickness = new Thickness(2.5),+ VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(0, -1, 0, 0), Visibility = Visibility.Collapsed+ };+ ring.SetResourceReference(Border.BorderBrushProperty, "AccentBrush");+ cell.Children.Add(ring);+ }+ row.Children.Add(cell);+ index++;+ }+ var list = widgets.ToList();+ if (list.Count > 0)+ {+ var line = new Border { Width = 1, Height = 34, Margin = new Thickness(9, 0, 9, 0), Opacity = 0.35 };+ line.SetResourceReference(Border.BackgroundProperty, "TextSecondary");+ row.Children.Add(line);+ foreach (var widget in list) row.Children.Add(new Border { Height = 44, Margin = new Thickness(2, 0, 2, 0), Child = widget.View });+ }+ var layers = new Grid();+ var pattern = new Border { Margin = new Thickness(-10, -6, -10, -6), CornerRadius = new CornerRadius(17), IsHitTestVisible = false };+ pattern.SetResourceReference(Border.BackgroundProperty, "DockPattern");+ var band = new Border { Margin = new Thickness(-10, 0, -10, -6), CornerRadius = new CornerRadius(0, 0, 17, 17), VerticalAlignment = VerticalAlignment.Bottom };+ band.SetResourceReference(Border.BackgroundProperty, "DockBand");+ band.SetResourceReference(FrameworkElement.HeightProperty, "DockBandHeight");+ layers.Children.Add(pattern);+ layers.Children.Add(band);+ layers.Children.Add(row);+ var dock = new Border+ {+ CornerRadius = new CornerRadius(18), BorderThickness = new Thickness(1), Padding = new Thickness(10, 6, 10, 6), Child = layers,+ Effect = new DropShadowEffect { Color = Colors.Black, BlurRadius = 20, ShadowDepth = 3, Direction = 270, Opacity = 0.38 }+ };+ dock.SetResourceReference(Border.BackgroundProperty, "DockMaterial");+ dock.SetResourceReference(Border.BorderBrushProperty, "DockBorderMaterial");+ dock.SetResourceReference(System.Windows.Documents.TextElement.FontFamilyProperty, "InterfaceFont");+ return (dock, ring);+ }++ // ---- The dock's messages (updates, keyboard) ------------------------------------------------------------++ private static Task Huds()+ {+ var hud = DockHud.Shared;+ (string Name, string Icon, string Text)[] messages =+ [+ ("hud-update-check", "IconRotate", UiText.Get("UpdateChecking")),+ ("hud-update-ready", "IconArrowDown", UiText.Format("UpdateAvailableHud", "0.4.0")),+ ("hud-update-download", "IconArrowDown", UiText.Format("UpdateDownloading", 64)),+ ("hud-update-done", "IconCheck", UiText.Format("UpdateUpToDate", "0.4.0")),+ ("hud-keyboard", "IconKeyboard", UiText.Get("DockKeysHint"))+ ];+ foreach (var (name, icon, text) in messages)+ {+ hud.RehearseMessage(icon, text);+ var panel = hud.RehearseDock();+ hud.RehearseMorph(1.0);+ Save(Pad(panel, 24), name + ".png");+ if (panel.Parent is Border border) border.Child = null;+ }+ return Task.CompletedTask;+ }++ // ---- Music card ---------------------------------------------------------------------------------------++ /// <summary>Made-up songs for the music card (no real artists).</summary>+ private static (string Title, string Channel, Color From, Color To)[] PromoSongs() =>+ [+ ("Midnight Drive", "Neon Harbor", Rgb(0x5B, 0x3C, 0xC4), Rgb(0xF2, 0x5C, 0x9A)),+ ("Golden Hour", "Lumen Trio", Rgb(0xFF, 0xB3, 0x47), Rgb(0xE8, 0x4A, 0x5F)),+ ("Ocean Lights", "Blue Atlas", Rgb(0x1F, 0x8E, 0xD6), Rgb(0x3E, 0xE0, 0xC8)),+ ("Paper Planes", "Kite & Cloud", Rgb(0x8E, 0xC5, 0x5A), Rgb(0x2E, 0x8B, 0x6E)),+ ("Velvet Rain", "Mira Sol", Rgb(0x7A, 0x4E, 0xD8), Rgb(0x34, 0x2A, 0x7A)),+ ("Slow Motion", "The Paper Moons", Rgb(0xF5, 0x7C, 0x51), Rgb(0x8A, 0x2B, 0x52)),+ ("Northern Sky", "Aurora Lane", Rgb(0x34, 0xD3, 0xA0), Rgb(0x2B, 0x5B, 0xD9)),+ ("City of Glass", "Echo Park", Rgb(0x9A, 0xA8, 0xBF), Rgb(0x3B, 0x47, 0x60))+ ];++ /// <summary>A made-up album cover: a soft two-colour blend with a ring and a wave.</summary>+ private static BitmapSource Cover(Color from, Color to, int seed)+ {+ const int size = 168;+ var visual = new DrawingVisual();+ using (var dc = visual.RenderOpen())+ {+ dc.DrawRectangle(new LinearGradientBrush(from, to, new Point(0, 0), new Point(1, 1)), null, new Rect(0, 0, size, size));+ var light = new SolidColorBrush(Color.FromArgb(0x55, 0xFF, 0xFF, 0xFF));+ switch (seed % 4)+ {+ case 0:+ dc.DrawEllipse(null, new Pen(light, 10), new Point(size * 0.5, size * 0.5), size * 0.28, size * 0.28);+ break;+ case 1:+ dc.DrawEllipse(light, null, new Point(size * 0.68, size * 0.36), size * 0.2, size * 0.2);+ break;+ case 2:+ for (var i = 0; i < 4; i++) dc.DrawRectangle(light, null, new Rect(0, size * (0.52 + i * 0.1), size, size * 0.035));+ break;+ default:+ var wave = new StreamGeometry();+ using (var g = wave.Open())+ {+ g.BeginFigure(new Point(0, size * 0.7), true, true);+ for (var x = 0; x <= size; x += 4) g.LineTo(new Point(x, size * 0.62 + Math.Sin(x / 22.0) * 10), true, false);+ g.LineTo(new Point(size, size), true, false);+ g.LineTo(new Point(0, size), true, false);+ }+ dc.DrawGeometry(light, null, wave);+ break;+ }+ }+ var bitmap = new RenderTargetBitmap(size, size, 96, 96, PixelFormats.Pbgra32);+ bitmap.Render(visual);+ bitmap.Freeze();+ return bitmap;+ }++ // ---- Icons: a small icon blown up next to the full-resolution one -------------------------------------++ /// <summary>Well-known apps for the icon comparison.</summary>+ private static readonly string[] IconApps =+ [+ "Chrome", "MSEdge", "5319275A.WhatsAppDesktop_cv1g1gvanyjgm!App", "Telegram.TelegramDesktop",+ "Microsoft.Office.WINWORD.EXE.15", "Microsoft.Office.EXCEL.EXE.15"+ ];++ private static Task Icons()+ {+ const double size = 96;+ foreach (var sharp in new[] { false, true })+ {+ var pictures = new List<FrameworkElement>();+ foreach (var id in IconApps)+ {+ var image = sharp ? NotificationApps.LoadIcon(id, (int)(size * Scale), exact: true) : Small(NotificationApps.LoadIcon(id, 32), 32);+ if (image is null) continue;+ var picture = new Image { Source = image, Width = size, Height = size, Margin = new Thickness(14) };+ RenderOptions.SetBitmapScalingMode(picture, sharp ? BitmapScalingMode.HighQuality : BitmapScalingMode.Linear);+ pictures.Add(picture);+ }+ var tag = sharp ? "after" : "before";+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ foreach (var picture in pictures) row.Children.Add(Copy(picture));+ Save(row, $"icons-{tag}.png");+ var grid = new UniformGrid { Columns = 3 };+ foreach (var picture in pictures) grid.Children.Add(Copy(picture));+ Save(grid, $"icons-grid-{tag}.png");+ }+ return Task.CompletedTask;++ static Image Copy(FrameworkElement from)+ {+ var source = (Image)from;+ var image = new Image { Source = source.Source, Width = source.Width, Height = source.Height, Margin = source.Margin };+ RenderOptions.SetBitmapScalingMode(image, RenderOptions.GetBitmapScalingMode(source));+ return image;+ }+ }++ /// <summary>The icon at <paramref name="pixels"/> pixels at most (Windows may hand over a bigger one).</summary>+ private static BitmapSource? Small(BitmapSource? image, int pixels)+ {+ if (image is null || image.PixelWidth <= pixels) return image;+ var scale = (double)pixels / image.PixelWidth;+ var small = new CachedBitmap(new TransformedBitmap(image, new ScaleTransform(scale, scale)), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);+ small.Freeze();+ return small;+ }++ // ---- The music card growing out of its tile in the dock, over the wallpaper -----------------------------++ /// <summary>+ /// The dock with the music tile, then the card growing out of it frame by frame (30 a second, with the real+ /// timings), turning to the playlist, and another song chosen. Frames are cut to the card's region+ /// (<c>desk-music</c> in the layout); the whole screen is saved closed, open, on the playlist and after the choice.+ /// </summary>+ private static async Task MusicDesk()+ {+ var songs = PromoSongs();+ var covers = songs.Select((s, i) => Cover(s.From, s.To, i)).ToList();+ var list = songs.Select((s, i) => (s.Title, s.Channel, (ImageSource)covers[i])).ToList();+ Desk.Settings = () => Options;+ WallpaperGlass.Refresh();+ var width = SystemParameters.PrimaryScreenWidth;+ var height = SystemParameters.PrimaryScreenHeight;+ Layout["screen"] = new { width, height };+ var clock = new ClockWidget();+ var weather = new WeatherWidget();+ var media = new MediaWidget { Current = Options };+ DockWidget[] widgets = [clock, media, weather];+ foreach (var widget in widgets)+ {+ widget.Current = Options;+ widget.ApplySettings(Options);+ }+ clock.Start();+ weather.Start();+ clock.SetLive(true);+ weather.SetLive(true);+ var popups = new List<WidgetPopup>();+ WidgetPopup.Rehearsal = popups;+ try+ {+ media.RehearsePromo(songs[2].Title, songs[2].Channel, covers[2]);+ }+ finally+ {+ WidgetPopup.Rehearsal = null;+ }+ var canvas = DeskCanvas(width, height);+ var (dock, _) = BuildDock(widgets, 8);+ var (left, top) = PlaceDock(canvas, dock, width, height, true);+ await Task.Delay(7000);+ Arrange(canvas);+ var tile = media.View.TransformToAncestor(canvas).TransformBounds(new Rect(0, 0, media.View.ActualWidth, media.View.ActualHeight));+ Save(canvas, "desk-music-closed.png");+ if (popups.FirstOrDefault() is not { } popup) return;++ // the card in the sheet it grows out of the dock in, placed as opening it there would place it+ var sheet = popup.RehearseSheet();+ var anchor = new EdgePanel.DockAnchor(DockEdge.Bottom, tile.X + tile.Width / 2, tile.Width, top, left + 18, left + dock.ActualWidth - 18);+ var (frame, bounds) = sheet.RehearseOnDock(anchor);+ Canvas.SetLeft(frame, bounds.X);+ Canvas.SetTop(frame, bounds.Y);+ canvas.Children.Add(frame);+ var region = new Rect(Math.Floor(bounds.X - 30), Math.Floor(bounds.Y - 30), Math.Ceiling(bounds.Width + 60), Math.Ceiling(top + dock.ActualHeight + 6 - bounds.Y + 30));+ Layout["desk-music"] = new object[]+ {+ new { kind = "dock", x = left, y = top, w = dock.ActualWidth, h = dock.ActualHeight },+ new { kind = "tile", x = tile.X, y = tile.Y, w = tile.Width, h = tile.Height },+ new { kind = "card", x = bounds.X, y = bounds.Y, w = bounds.Width, h = bounds.Height },+ new { kind = "region", x = region.X, y = region.Y, w = region.Width, h = region.Height }+ };++ void Pose(double progress, double content, double rise)+ {+ var seam = sheet.RehearseDockMorph(progress, content, rise);+ dock.OpacityMask = seam is { } r ? EdgePanel.NotchMask(new Size(dock.ActualWidth, dock.ActualHeight), r.Left - left, r.Right - left, EdgePanel.SeamDepth) : null;+ Arrange(canvas);+ }+ static double Part(double value) => Math.Clamp(value, 0, 1);++ // opening: the shape swells in 430 ms (soft overshoot); the content fades in after 170 ms and rises 12 points in 380 ms+ const int open = 18;+ for (var i = 0; i <= open; i++)+ {+ var ms = i * 1000.0 / 30;+ var shape = ms >= 430 ? 1 : Motion.Settle.Ease(ms / 430);+ Pose(shape, Part((ms - 170) / 220), 12 * (1 - Motion.Out.Ease(Part((ms - 170) / 380))));+ SaveRegion(canvas, region, $"music-open-{i:00}.png");+ }+ Save(canvas, "desk-music-front.png");++ // turning to the playlist: folds in 140 ms, the back unfolds in 170 ms+ var fold = new CubicEase { EasingMode = EasingMode.EaseIn };+ var unfold = new CubicEase { EasingMode = EasingMode.EaseOut };+ var turn = 0;+ for (var i = 1; i <= 4; i++)+ {+ media.RehearseTurn(1 - fold.Ease(Part(i * 1000.0 / 30 / 140)));+ Arrange(canvas);+ SaveRegion(canvas, region, $"music-turn-{turn++:00}.png");+ }+ // the list is scrolled before the turn (a card turned edge on cannot be measured)+ media.RehearseTurn(1);+ media.RehearsePlaylist(list, 2, scroll: false);+ for (var pass = 0; pass < 2; pass++)+ {+ Arrange(canvas);+ media.RehearseScrollToCurrent();+ await Task.Delay(150);+ }+ media.RehearseTurn(0);+ Arrange(canvas);+ for (var i = 0; i <= 6; i++)+ {+ media.RehearseTurn(unfold.Ease(Part(i * 1000.0 / 30 / 170)));+ Arrange(canvas);+ SaveRegion(canvas, region, $"music-turn-{turn++:00}.png");+ }+ Layout["music-turn"] = new { frames = turn };+ Save(canvas, "desk-music-back.png");++ // another song chosen: it plays, the tile and the list follow+ media.RehearseNowPlaying(songs[3].Title, songs[3].Channel, covers[3]);+ media.RehearsePlaylist(list, 3, scroll: false);+ Arrange(canvas);+ media.RehearseScrollToCurrent(2);+ await Task.Delay(300);+ Arrange(canvas);+ Save(canvas, "desk-music-next.png");+ foreach (var widget in widgets) widget.Dispose();+ }++ private static void Arrange(Canvas canvas)+ {+ canvas.Measure(new Size(canvas.Width, canvas.Height));+ canvas.Arrange(new Rect(0, 0, canvas.Width, canvas.Height));+ canvas.UpdateLayout();+ }++ /// <summary>Part of the canvas (DIPs), at the pictures' scale.</summary>+ private static void SaveRegion(Canvas canvas, Rect region, string name)+ {+ var bitmap = new RenderTargetBitmap((int)Math.Ceiling(canvas.Width * Scale), (int)Math.Ceiling(canvas.Height * Scale), 96 * Scale, 96 * Scale, PixelFormats.Pbgra32);+ bitmap.Render(canvas);+ int x = (int)(region.X * Scale), y = (int)(region.Y * Scale);+ var cut = new CroppedBitmap(bitmap, new Int32Rect(x, y, Math.Min((int)(region.Width * Scale), bitmap.PixelWidth - x), Math.Min((int)(region.Height * Scale), bitmap.PixelHeight - y)));+ var png = new PngBitmapEncoder();+ png.Frames.Add(BitmapFrame.Create(cut));+ using var file = File.Create(System.IO.Path.Combine(_folder, name));+ png.Save(file);+ }++ // ---- Desktop scenes over the promotional wallpaper ------------------------------------------------++ private sealed record Card(string Kind, DeskSize Size, double X, double Y, string? Style = null, string? Tint = null);++ private static async Task Desks()+ {+ Desk.Settings = () => Options;+ WallpaperGlass.Refresh();+ var width = SystemParameters.PrimaryScreenWidth;+ var height = SystemParameters.PrimaryScreenHeight;+ Layout["screen"] = new { width, height };+ var u = Desk.Unit;+ var g = Desk.Gap;+ var scenes = new List<(string Name, Card[] Cards, bool Glass, bool Dock)>+ {+ ("desk-glass", [+ new("bigclock", DeskSize.Hero, 64, 60, "lock", "white"),+ new("weather", DeskSize.Medium, width - 64 - 2 * u - g, 60),+ new("claude", DeskSize.Small, width - 64 - 2 * u - g, 60 + u + g),+ new("cpu", DeskSize.Small, width - 64 - u, 60 + u + g),+ new("devicebattery", DeskSize.Medium, width - 64 - 2 * u - g, 60 + 2 * (u + g))], true, true),+ ("desk-dark", [+ new("bigclock", DeskSize.Hero, 64, 60, "lock", "white"),+ new("weather", DeskSize.Medium, width - 64 - 2 * u - g, 60),+ new("claude", DeskSize.Small, width - 64 - 2 * u - g, 60 + u + g),+ new("cpu", DeskSize.Small, width - 64 - u, 60 + u + g),+ new("devicebattery", DeskSize.Medium, width - 64 - 2 * u - g, 60 + 2 * (u + g))], false, true),+ ("desk-battery", [+ new("devicebattery", DeskSize.Tall, width / 2 - 1.5 * u - g, height / 2 - u - g / 2 - 60),+ new("devicebattery", DeskSize.Medium, width / 2 - 0.5 * u, height / 2 - u - g / 2 - 60),+ new("devicebattery", DeskSize.Strip, width / 2 - 0.5 * u, height / 2 + g / 2 - 60)], true, false),+ ("desk-cpu", [+ new("cpu", DeskSize.Tall, width / 2 - 1.5 * u - g, height / 2 - u - g / 2 - 60),+ new("cpu", DeskSize.Medium, width / 2 - 0.5 * u, height / 2 - u - g / 2 - 60),+ new("cpu", DeskSize.Small, width / 2 - 0.5 * u, height / 2 + g / 2 - 60),+ new("ram", DeskSize.Small, width / 2 + 0.5 * u + g, height / 2 + g / 2 - 60)], true, false),+ ("desk-ai", [+ new("claude", DeskSize.Medium, width / 2 - 2 * u - 1.5 * g, height / 2 - u - g / 2 - 60),+ new("opencode", DeskSize.Tall, width / 2 + g / 2 + u + g, height / 2 - u - g / 2 - 60),+ new("codex", DeskSize.Small, width / 2 - 2 * u - 1.5 * g, height / 2 + g / 2 - 60),+ new("gemini", DeskSize.Small, width / 2 - u - 0.5 * g, height / 2 + g / 2 - 60),+ new("gemini", DeskSize.Medium, width / 2 - 2 * u - 1.5 * g, height / 2 + u + 1.5 * g - 60),+ new("claude", DeskSize.Small, width / 2 + g / 2, height / 2 - u - g / 2 - 60),+ new("codex", DeskSize.Small, width / 2 + g / 2, height / 2 + g / 2 - 60)], true, false)+ };+ foreach (var style in new[] { "lock", "thin", "stacked", "neon", "twotone", "serif" })+ {+ var tint = style switch { "neon" => "pink", "twotone" => "sunset", "serif" => "cream", "thin" => "white", "stacked" => "ocean", _ => "white" };+ scenes.Add(($"desk-bigclock-{style}", [new("bigclock", DeskSize.Hero, width / 2 - (4 * u + 3 * g) / 2, height / 2 - 230 - 70, style, tint)], true, false));+ }+ foreach (var scene in scenes)+ {+ DeskCardFace.GlassEnabled = scene.Glass;+ var canvas = DeskCanvas(width, height);+ var hosts = new List<PromoHost>();+ var rects = new List<object>();+ foreach (var card in scene.Cards)+ {+ if (DeskCatalog.Find(card.Kind) is not { } kind) continue;+ var item = new DeskItem { Kind = card.Kind, Size = card.Size, X = card.X, Y = card.Y };+ if (card.Style is not null) item.Options["style"] = card.Style;+ if (card.Tint is not null) item.Options["tint"] = card.Tint;+ var host = new PromoHost(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 dims = Desk.Dimensions(card.Size);+ rects.Add(new { kind = card.Kind, x = card.X, y = card.Y, w = dims.Width, h = dims.Height });+ }+ if (scene.Dock)+ {+ var (dock, _) = BuildDock([], 10);+ var (left, top) = PlaceDock(canvas, dock, width, height, scene.Glass);+ rects.Add(new { kind = "dock", x = left, y = top, w = dock.DesiredSize.Width, h = dock.DesiredSize.Height });+ }+ Layout[scene.Name] = rects;+ canvas.Measure(new Size(width, height));+ canvas.Arrange(new Rect(0, 0, width, height));+ await Task.Delay(scene.Name == "desk-glass" ? 7000 : 2500);+ for (var pass = 0; pass < 2; pass++)+ {+ foreach (var host in hosts) host.Widget.Tick();+ canvas.Measure(new Size(width, height));+ canvas.Arrange(new Rect(0, 0, width, height));+ canvas.UpdateLayout();+ }+ Save(canvas, scene.Name + ".png");+ foreach (var host in hosts) host.Widget.Detach();+ }+ DeskCardFace.GlassEnabled = true;+ }++ /// <summary>A screen-sized canvas showing the wallpaper, in QiDock's font.</summary>+ private static Canvas DeskCanvas(double width, double height)+ {+ var canvas = new Canvas { Width = width, Height = height };+ if (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);+ return canvas;+ }++ /// <summary>The dock at the bottom centre of the screen, as glass over the wallpaper when asked.</summary>+ private static (double Left, double Top) PlaceDock(Canvas canvas, Border dock, double width, double height, bool glass)+ {+ dock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));+ var left = Math.Round((width - dock.DesiredSize.Width) / 2);+ var top = height - 6 - dock.DesiredSize.Height;+ if (glass)+ {+ var area = new Rect(left, top, dock.DesiredSize.Width, dock.DesiredSize.Height);+ GlassLook.DockVeil = GlassLook.Veil(WallpaperGlass.Light(area));+ GlassLook.Tiles(dock.Resources, true);+ if (GlassLook.Dock(new Matrix(1, 0, 0, 1, left, top)) is { } material) dock.Background = material;+ dock.BorderBrush = GlassLook.Rim;+ }+ Canvas.SetLeft(dock, left);+ Canvas.SetTop(dock, top);+ canvas.Children.Add(dock);+ return (left, top);+ }++ private sealed class PromoHost : IDeskHost+ {+ public PromoHost(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();+ }++ // ---- Settings pages ---------------------------------------------------------------------------------++ private static async Task Settings()+ {+ foreach (var (tab, name, wait) in new[] { (1, "settings-look.png", 1500), (3, "settings-wallpaper.png", 10000) })+ {+ var settings = new SettingsWindow(((App)Application.Current).Preferences)+ {+ Left = -30000, Top = 0, ShowInTaskbar = false, WindowStartupLocation = WindowStartupLocation.Manual, ShowActivated = false+ };+ settings.PreviewHost.Visibility = Visibility.Collapsed;+ settings.Show();+ settings.SettingsTabs.SelectedIndex = tab;+ await Task.Delay(wait);+ Save((FrameworkElement)settings.Content, name);+ settings.Close();+ }+ }++ // ---- Files window over a folder of sample files ---------------------------------------------------++ private static async Task Files()+ {+ if (Environment.GetEnvironmentVariable("QIDOCK_PROMO_FILES") is not { Length: > 0 } folder || !Directory.Exists(folder)) return;+ QiDock.Files.FilesWindow.Open(folder);+ var window = Application.Current.Windows.OfType<QiDock.Files.FilesWindow>().FirstOrDefault();+ if (window is null) return;+ window.Left = -30000;+ window.Width = 1180;+ window.Height = 720;+ await Task.Delay(7000);+ Save((FrameworkElement)window.Content, "files.png");+ window.Close();+ }++ // ---- App screen ----------------------------------------------------------------------------------++ private static Task Apps()+ {+ var finished = new TaskCompletionSource();+ AppGridWindow.RenderTo(System.IO.Path.Combine(_folder, "apps.png"), finished.SetResult);+ return finished.Task;+ }++ // ---- Helpers ------------------------------------------------------------------------------------++ private static Window Stage(FrameworkElement content)+ {+ var window = new Window+ {+ WindowStyle = WindowStyle.None, AllowsTransparency = true, Background = Brushes.Transparent, ShowInTaskbar = false, ShowActivated = false,+ WindowStartupLocation = WindowStartupLocation.Manual, Left = -30000, Top = 0, SizeToContent = SizeToContent.WidthAndHeight, Content = content+ };+ window.Show();+ return window;+ }++ private static Border Pad(FrameworkElement element, double room) => new() { Padding = new Thickness(room), Background = Brushes.Transparent, Child = element };++ private static Color Rgb(byte r, byte g, byte b) => Color.FromRgb(r, g, b);++ private static void Save(FrameworkElement element, string name)+ {+ if (element is not Canvas)+ {+ element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));+ element.Arrange(new Rect(element.DesiredSize));+ }+ element.UpdateLayout();+ var bitmap = new RenderTargetBitmap((int)Math.Ceiling(element.ActualWidth * Scale), (int)Math.Ceiling(element.ActualHeight * Scale), 96 * Scale, 96 * Scale, PixelFormats.Pbgra32);+ bitmap.Render(element);+ var png = new PngBitmapEncoder();+ png.Frames.Add(BitmapFrame.Create(bitmap));+ using var file = File.Create(System.IO.Path.Combine(_folder, name));+ png.Save(file);+ }+}+#endifdiff --git a/QiDock.csproj b/QiDock.csprojindex 18a1728..7188729 100644--- a/QiDock.csproj+++ b/QiDock.csproj@@ -9,8 +9,9 @@<UseWPF>true</UseWPF><AssemblyName>QiDock</AssemblyName><RootNamespace>QiDock</RootNamespace>- <Version>0.3.0</Version>+ <Version>0.4.0</Version><ApplicationManifest>app.manifest</ApplicationManifest>+ <ApplicationIcon>Assets/QiDock.ico</ApplicationIcon><Product>QiDock</Product><AssemblyTitle>QiDock</AssemblyTitle><Company>QiDock</Company>@@ -26,7 +27,6 @@</PropertyGroup><ItemGroup>- <PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2903.40" /></ItemGroup></Project>diff --git a/README.md b/README.mdindex b00e961..c537ffa 100644--- a/README.md+++ b/README.md@@ -15,6 +15,27 @@ QiDock turns the Windows 10 and 11 taskbar into a floating glass dock with a wid|  |  || **14 dock styles** | **AI limits** for Claude, with Gemini and Codex a click away |+### New in 0.4.0++| | |+|:---:|:---:|+|  |  |+| **Apps screen**: all your apps, the ones you use most up front | **Files**: a fast file manager that shows what takes up space |+|  |  |+| **Wallpaper gallery**: fresh 4K pictures every day | **Updater**: finds, downloads and installs new versions |+|  |  |+| **14 themes** for the dock, panels and tools | **Glass look** that takes on your wallpaper's colours |+|  |  |+| **Keyboard dock**: Alt+Shift+D, arrows, Enter | **Sharp icons** at your screen's full resolution |+|  |  |+| **Playlist** of what's playing, right in the music card | **Big clock** on the desktop in six styles |+|  |  |+| **Bluetooth batteries** of your mouse, keyboard and headphones | **CPU usage**: the apps using your processor most |+|  | |+| **AI limits** for Claude, Codex, Gemini and OpenCode | |++Portrait versions of these pictures (for phones and stories) are in [docs/images/features](docs/images/features).+---## Featuresdiff --git a/Services/Notifications/NotificationFeed.cs b/Services/Notifications/NotificationFeed.csindex 25af850..617b9e9 100644--- a/Services/Notifications/NotificationFeed.cs+++ b/Services/Notifications/NotificationFeed.cs@@ -1,4 +1,4 @@-using System.Diagnostics;+using System.Diagnostics;using System.IO;using System.Runtime.InteropServices;using System.Text;@@ -355,6 +355,16 @@ public static class NotificationAppsfinally { Marshal.ReleaseComObject(item); }}+#if DEBUG+ /// <summary>A program file's icon as the dock would show it (debug pictures of old programs' icons).</summary>+ internal static BitmapSource? LoadFileIcon(string path, int size, bool exact)+ {+ if (SHCreateItemFromParsingName(path, 0, typeof(IShellItem).GUID, out var item) != 0 || item is null) return null;+ try { return ImageOf(item, size, exact); }+ finally { Marshal.ReleaseComObject(item); }+ }+#endif+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.@@ -362,7 +372,62 @@ public static class NotificationAppsBitmapSource? image;try { image = FromHBitmap(bitmap); }finally { DeleteObject(bitmap); }- return exact && image is not null ? Fit(image, size) : image;+ if (!exact || image is null) return image;+ // An old program with no large icon: Windows blows its small icon up (in coarse squares) inside a thin grey+ // frame. Its own small picture, sharp, goes on a light tile instead, as macOS shows such apps.+ if (size > 64 && Framed(image) && Natural(factory) is { } small) return Plate(small, size);+ return Fit(image, size);+ }++ /// <summary>Whether this is Windows' grey frame around a small icon: a faint dark line, a white one, then nothing.</summary>+ private static bool Framed(BitmapSource image)+ {+ int width = image.PixelWidth, height = image.PixelHeight;+ if (width < 16 || height < 16) return false;+ var pixels = new byte[width * height * 4];+ var bgra = image.Format == System.Windows.Media.PixelFormats.Bgra32 || image.Format == System.Windows.Media.PixelFormats.Pbgra32 ? image : new FormatConvertedBitmap(image, System.Windows.Media.PixelFormats.Bgra32, null, 0);+ bgra.CopyPixels(pixels, width * 4, 0);+ byte Alpha(int x, int y) => pixels[(y * width + x) * 4 + 3];+ bool Dark(int x, int y) { var i = (y * width + x) * 4; return pixels[i + 3] is >= 20 and <= 70 && pixels[i] < 40 && pixels[i + 1] < 40 && pixels[i + 2] < 40; }+ int midX = width / 2, midY = height / 2;+ return Dark(0, midY) && Dark(width - 1, midY) && Dark(midX, 0) && Dark(midX, height - 1)+ && Alpha(5, midY) == 0 && Alpha(width - 6, midY) == 0 && Alpha(midX, 5) == 0 && Alpha(midX, height - 6) == 0;+ }++ /// <summary>The largest picture of the icon that Windows gives without the frame (the icon's own pixels).</summary>+ private static BitmapSource? Natural(IShellItemImageFactory factory)+ {+ foreach (var size in (ReadOnlySpan<int>)[96, 64, 48, 32])+ {+ if (factory.GetImage(new NativeSize(size, size), 0x4 /* icon only */, out var bitmap) != 0 || bitmap == 0) continue;+ BitmapSource? image;+ try { image = FromHBitmap(bitmap); }+ finally { DeleteObject(bitmap); }+ if (image is not null && !Framed(image)) return image;+ }+ return null;+ }++ /// <summary>A small icon on a light rounded tile of <paramref name="size"/> pixels, enlarged at most twice.</summary>+ private static BitmapSource Plate(BitmapSource icon, int size)+ {+ var inset = Math.Round(size * 0.045);+ var tile = new System.Windows.Rect(inset, inset, size - 2 * inset, size - 2 * inset);+ var inner = Math.Min(icon.PixelWidth * 2.0, Math.Round(tile.Width * 0.64));+ var fill = new System.Windows.Media.LinearGradientBrush(System.Windows.Media.Color.FromRgb(0xFB, 0xFB, 0xFC), System.Windows.Media.Color.FromRgb(0xE6, 0xE6, 0xEA), 90);+ var visual = new System.Windows.Media.DrawingVisual();+ System.Windows.Media.RenderOptions.SetBitmapScalingMode(visual, System.Windows.Media.BitmapScalingMode.HighQuality);+ using (var dc = visual.RenderOpen())+ {+ var radius = tile.Width * 0.225;+ dc.DrawRoundedRectangle(fill, new System.Windows.Media.Pen(new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(0x30, 0, 0, 0)), 1), tile, radius, radius);+ var place = Math.Round((size - inner) / 2);+ dc.DrawImage(Fit(icon, (int)inner), new System.Windows.Rect(place, place, inner, inner));+ }+ var result = new RenderTargetBitmap(size, size, 96, 96, System.Windows.Media.PixelFormats.Pbgra32);+ result.Render(visual);+ result.Freeze();+ return result;}/// <summary>@@ -412,7 +477,17 @@ public static class NotificationAppsfor (var row = 0; row < height; row++) Buffer.BlockCopy(pixels, row * stride, flipped, (height - 1 - row) * stride, stride);pixels = flipped;}- var source = BitmapSource.Create(width, height, 96, 96, System.Windows.Media.PixelFormats.Pbgra32, null, pixels, stride);+ // Windows hands most icons over with plain (not premultiplied) transparency. Read as premultiplied, the soft+ // edge pixels came out far too bright: a white or pink rim around every icon. A colour stronger than its own+ // opacity can only be plain transparency, so that decides how the pixels are read.+ var plain = false;+ for (var i = 0; i < pixels.Length && !plain; i += 4)+ {+ var alpha = pixels[i + 3];+ plain = pixels[i] > alpha || pixels[i + 1] > alpha || pixels[i + 2] > alpha;+ }+ var format = plain ? System.Windows.Media.PixelFormats.Bgra32 : System.Windows.Media.PixelFormats.Pbgra32;+ var source = BitmapSource.Create(width, height, 96, 96, format, null, pixels, stride);source.Freeze();return source;}diff --git a/Services/Promo.cs b/Services/Promo.csnew file mode 100644index 0000000..5835939--- /dev/null+++ b/Services/Promo.cs@@ -0,0 +1,114 @@+#if DEBUG+using System.IO;+using QiDock.Services.Widgets;++namespace QiDock.Services;++/// <summary>+/// Debug builds only: sample data for the promotional pictures and videos (QIDOCK_PROMO=1), so they show lively,+/// made-up numbers instead of this computer's own (an idle processor, no Bluetooth devices, real songs and files).+/// </summary>+internal static class Promo+{+ public static bool On { get; } = Environment.GetEnvironmentVariable("QIDOCK_PROMO") == "1";++ /// <summary>A picture to treat as the wallpaper (QIDOCK_PROMO_WALLPAPER), so the glass matches the video's background.</summary>+ public static string? Wallpaper { get; } = Environment.GetEnvironmentVariable("QIDOCK_PROMO_WALLPAPER") is { Length: > 0 } file && File.Exists(file) ? file : null;++ public static IReadOnlyList<DeviceBattery> Batteries { get; } =+ [+ new("MX Master 3S", 82, "mouse"),+ new("MX Keys", 64, "keyboard"),+ new("WH-1000XM5", 41, "headphones")+ ];++ private static readonly double[] Wave = [22, 26, 31, 28, 35, 41, 38, 44, 52, 47, 39, 36, 42, 48, 55, 51, 46, 40, 37, 43];+ private static int _step;++ /// <summary>The next value of a made-up processor load that rises and falls like real work.</summary>+ public static double NextCpu() => Wave[_step++ % Wave.Length];++ public static IReadOnlyList<CpuUser> CpuUsers()+ {+ static string? Find(params string[] paths) => paths.FirstOrDefault(File.Exists);+ var programsX86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);+ var windows = Environment.GetFolderPath(Environment.SpecialFolder.Windows);+ var english = UiText.Current.Language == Models.AppLanguage.English;+ // Windows' own programs only: nothing this computer's owner installed.+ return+ [+ new("Microsoft Edge", Find(Path.Combine(programsX86, @"Microsoft\Edge\Application\msedge.exe")), 14.2),+ new(english ? "File Explorer" : "Windows Gezgini", Find(Path.Combine(windows, "explorer.exe")), 6.3),+ new(english ? "Desktop Window Manager" : "Masaüstü Pencere Yöneticisi", Find(Path.Combine(windows, @"System32\dwm.exe")), 3.4),+ new("QiDock", Environment.ProcessPath, 1.1)+ ];+ }++ /// <summary>Apps everyone knows and Windows' own (Microsoft's packages, Edge), never little-known ones this computer's owner added.</summary>+ public static bool IsWindowsApp(string id) =>+ id is "MSEdge" or "Microsoft.Windows.Explorer" or "Chrome" or "Telegram.TelegramDesktop" or "Microsoft.Office.WINWORD.EXE.15"+ or "Microsoft.Office.EXCEL.EXE.15" or "Microsoft.Office.POWERPNT.EXE.15"+ || id.StartsWith("5319275A.WhatsAppDesktop", StringComparison.OrdinalIgnoreCase)+ || (id.Contains("_8wekyb3d8bbwe!", StringComparison.OrdinalIgnoreCase) || id.Contains("_cw5n1h2txyewy!", StringComparison.OrdinalIgnoreCase));++ private static readonly string[] Favourites =+ ["Microsoft.Windows.Explorer", "Chrome", "5319275A.WhatsAppDesktop", "Microsoft.Office.WINWORD", "Microsoft.Office.EXCEL",+ "Telegram.TelegramDesktop", "MSEdge", "Microsoft.Windows.Photos", "Microsoft.WindowsTerminal", "Microsoft.WindowsCalculator",+ "Microsoft.WindowsNotepad", "Microsoft.Paint", "Microsoft.WindowsStore", "windows.immersivecontrolpanel", "Microsoft.WindowsAlarms",+ "Microsoft.OutlookForWindows", "Microsoft.ScreenSketch", "Microsoft.WindowsCamera", "Microsoft.ZuneMusic"];++ private static readonly Dictionary<string, string> EnglishNames = new(StringComparer.OrdinalIgnoreCase)+ {+ ["Microsoft.Windows.Explorer"] = "File Explorer", ["Microsoft.WindowsCalculator"] = "Calculator", ["Microsoft.WindowsNotepad"] = "Notepad",+ ["Microsoft.Windows.Photos"] = "Photos", ["windows.immersivecontrolpanel"] = "Settings", ["Microsoft.WindowsAlarms"] = "Clock",+ ["Microsoft.ScreenSketch"] = "Snipping Tool", ["Microsoft.WindowsCamera"] = "Camera", ["Microsoft.ZuneMusic"] = "Media Player",+ ["Microsoft.WindowsSoundRecorder"] = "Sound Recorder", ["Microsoft.BingWeather"] = "Weather", ["Microsoft.GetHelp"] = "Get Help",+ ["Microsoft.Getstarted"] = "Tips", ["Microsoft.WindowsFeedbackHub"] = "Feedback Hub", ["Microsoft.Todos"] = "To Do",+ ["Microsoft.MicrosoftStickyNotes"] = "Sticky Notes", ["Microsoft.People"] = "People", ["Microsoft.WindowsMaps"] = "Maps",+ ["Microsoft.XboxGamingOverlay"] = "Game Bar", ["Microsoft.Windows.DevHome"] = "Dev Home", ["MicrosoftWindows.Client.CBS"] = "Phone Link",+ ["Microsoft.YourPhone"] = "Phone Link", ["Microsoft.WindowsStore"] = "Microsoft Store", ["Microsoft.MicrosoftOfficeHub"] = "Microsoft 365",+ ["Microsoft.WindowsTerminal"] = "Terminal", ["Microsoft.Paint"] = "Paint", ["Microsoft.BingNews"] = "News"+ };++ /// <summary>In the English pictures, Windows' own apps under their English names (this Windows speaks Turkish).</summary>+ public static IReadOnlyList<InstalledApp> Named(IReadOnlyList<InstalledApp> apps) =>+ UiText.Current.Language != Models.AppLanguage.English ? apps : apps.Select(a =>+ {+ var key = EnglishNames.Keys.FirstOrDefault(k => a.Id.StartsWith(k, StringComparison.OrdinalIgnoreCase));+ return key is null ? a : a with { Name = EnglishNames[key] };+ }).ToList();++ /// <summary>A made-up "most used" order for the app screen.</summary>+ public static Dictionary<string, double> AppScores(IEnumerable<InstalledApp> apps)+ {+ var scores = new Dictionary<string, double>();+ foreach (var app in apps)+ {+ var rank = Array.FindIndex(Favourites, f => app.Id.StartsWith(f, StringComparison.OrdinalIgnoreCase));+ if (rank >= 0) scores[app.Id] = Favourites.Length - rank;+ }+ return scores;+ }++ public static IReadOnlyList<ProviderUsage> Ai()+ {+ var now = DateTime.Now;+ return+ [+ new(AiUsageService.ClaudeId, "Claude", "Max", [+ new UsageWindow(UiText.Get("AiSession"), 46, now.AddHours(2.4), TimeSpan.FromHours(5), "session"),+ new UsageWindow(UiText.Get("AiWeekly"), 23, now.AddDays(4.2), TimeSpan.FromDays(7), "weekly")], now, null),+ new(AiUsageService.CodexId, "Codex", "Plus", [+ new UsageWindow(UiText.Get("AiSession"), 31, now.AddHours(3.1), TimeSpan.FromHours(5), "session"),+ new UsageWindow(UiText.Get("AiWeekly"), 12, now.AddDays(5.5), TimeSpan.FromDays(7), "weekly")], now, null),+ new(AiUsageService.GeminiId, "Gemini", "AI Ultra", [+ new UsageWindow("Gemini", 18, now.AddHours(3.6), TimeSpan.FromHours(5), "gemini"),+ new UsageWindow(UiText.Get("AiGeminiOthers"), 9, now.AddHours(3.6), TimeSpan.FromHours(5), "others")], now, null),+ new(AiUsageService.OpenCodeId, "OpenCode", "Go", [+ new UsageWindow(UiText.Format("AiHoursWindow", 5), 27, now.AddHours(1.8), TimeSpan.FromHours(5), "session"),+ new UsageWindow(UiText.Get("AiWeekly"), 34, now.AddDays(2.4), TimeSpan.FromDays(7), "weekly"),+ new UsageWindow(UiText.Get("AiMonthly"), 58, now.AddDays(15), TimeSpan.FromDays(30), "monthly")], now, null)+ ];+ }+}+#endifdiff --git a/Services/ThemePatterns.cs b/Services/ThemePatterns.csnew file mode 100644index 0000000..066a5de--- /dev/null+++ b/Services/ThemePatterns.cs@@ -0,0 +1,225 @@+using System.Windows;+using System.Windows.Media;+using System.Windows.Media.Imaging;++namespace QiDock.Services;++/// <summary>+/// What makes each theme's dock its own beyond its colours: a faint texture over the whole dock (snow, film grain,+/// brushed metal, ruled paper…) and a band along its bottom edge (waves, pine trees, sunset lines, 70s stripes…).+/// Each is one small tile drawn once when the theme is chosen and repeated by the dock, so it costs a few kilobytes+/// and nothing while the dock moves.+/// </summary>+internal static class ThemePatterns+{+ /// <summary>Puts the theme's texture ("DockPattern") and bottom band ("DockBand", "DockBandHeight") into <paramref name="d"/>.</summary>+ public static void Add(ResourceDictionary d, ThemeStyle style)+ {+ var (texture, band, bandHeight) = Make(style);+ d["DockPattern"] = texture ?? Brushes.Transparent;+ d["DockBand"] = band ?? Brushes.Transparent;+ d["DockBandHeight"] = band is null ? 0.0 : bandHeight;+ }++ private static (Brush? Texture, Brush? Band, double BandHeight) Make(ThemeStyle s)+ {+ var accent = C(s.Accent);+ var one = C(s.Swatch[0]);+ var two = C(s.Swatch.Length > 1 ? s.Swatch[1] : s.Accent);+ var three = C(s.Swatch.Length > 2 ? s.Swatch[2] : s.Accent);+ var text = C(s.Text);+ switch (s.Id)+ {+ case "black": // piano black: a glossy sheen across the top+ return (Tile(4, 120, dc => dc.DrawRectangle(Vertical(A(Colors.White, 0x2A), A(Colors.White, 0x00), 0, 0.16), null, new Rect(0, 0, 4, 120))), null, 0);++ case "lofi": // film grain+ return (Tile(48, 48, dc => Scatter(dc, 48, 48, 70, 7, (x, y, r, i) => dc.DrawEllipse(Solid(A(text, (byte)(0x16 + i % 3 * 6))), null, new Point(x, y), r * 0.45 + 0.35, r * 0.45 + 0.35))), null, 0);++ case "pixelnight": // pixel stars, and a stepped pixel skyline along the bottom+ return (Tile(64, 40, dc =>+ {+ Scatter(dc, 64, 40, 7, 11, (x, y, r, i) =>+ {+ var colour = (i % 3) switch { 0 => three, 1 => two, _ => Colors.White };+ var size = i % 4 == 0 ? 2.0 : 1.4;+ dc.DrawRectangle(Solid(A(colour, 0x8C)), null, new Rect(Math.Round(x), Math.Round(y), size, size));+ });+ }),+ Tile(36, 9, dc =>+ {+ double[] heights = [3, 6, 4, 8, 5, 3, 7, 4, 6, 3, 5, 8];+ for (var i = 0; i < heights.Length; i++)+ dc.DrawRectangle(Solid(A(one, 0x46)), null, new Rect(i * 3, 9 - heights[i], 3, heights[i]));+ }), 9);++ case "christmas": // falling snow, and a candy-cane stripe along the bottom+ return (Tile(56, 44, dc => Scatter(dc, 56, 44, 9, 23, (x, y, r, i) => dc.DrawEllipse(Solid(A(Colors.White, (byte)(0x40 + i % 3 * 0x14))), null, new Point(x, y), 0.8 + r * 0.5, 0.8 + r * 0.5))),+ Tile(12, 4, dc =>+ {+ dc.DrawRectangle(Solid(A(Colors.White, 0xB0)), null, new Rect(0, 0, 12, 4));+ var stripe = new StreamGeometry();+ using (var g = stripe.Open())+ {+ g.BeginFigure(new Point(0, 4), true, true);+ g.LineTo(new Point(4, 0), true, false);+ g.LineTo(new Point(10, 0), true, false);+ g.LineTo(new Point(6, 4), true, false);+ }+ stripe.Freeze();+ dc.DrawGeometry(Solid(A(one, 0xE0)), null, stripe);+ }), 4);++ case "ocean": // two waves along the bottom+ return (null, Tile(48, 14, dc =>+ {+ dc.DrawGeometry(Solid(A(three, 0x26)), null, Wave(48, 14, 5, 2.4, 12));+ dc.DrawGeometry(Solid(A(one, 0x3A)), null, Wave(48, 14, 9, 1.8, 0));+ }), 14);++ case "sunset": // the striped lower half of a retro sun+ return (null, Tile(4, 16, dc =>+ {+ dc.DrawRectangle(Solid(A(three, 0x55)), null, new Rect(0, 3, 4, 1.2));+ dc.DrawRectangle(Solid(A(one, 0x60)), null, new Rect(0, 7, 4, 2));+ dc.DrawRectangle(Solid(A(two, 0x70)), null, new Rect(0, 11.5, 4, 3));+ }), 16);++ case "forest": // a row of pine trees+ return (null, Tile(46, 17, dc =>+ {+ (double X, double H)[] trees = [(5, 12), (13, 16), (21, 9), (30, 14), (39, 11)];+ foreach (var (x, h) in trees)+ {+ var tree = new StreamGeometry();+ using (var g = tree.Open())+ {+ g.BeginFigure(new Point(x, 17 - h), true, true);+ g.LineTo(new Point(x + h * 0.36, 17), true, false);+ g.LineTo(new Point(x - h * 0.36, 17), true, false);+ }+ tree.Freeze();+ dc.DrawGeometry(Solid(A(two, 0x70)), null, tree);+ }+ }), 17);++ case "graphite": // brushed metal+ return (Tile(140, 7, dc => Scatter(dc, 140, 7, 9, 5, (x, y, r, i) => dc.DrawRectangle(Solid(A(Colors.White, (byte)(0x08 + i % 3 * 4))), null, new Rect(x, Math.Round(y), 20 + r * 30, 0.6)))), null, 0);++ case "neon": // a faint synthwave grid, and a glowing magenta line along the bottom+ return (Tile(22, 22, dc =>+ {+ var line = Solid(A(accent, 0x1C));+ dc.DrawRectangle(line, null, new Rect(0, 21.4, 22, 0.6));+ dc.DrawRectangle(line, null, new Rect(21.4, 0, 0.6, 22));+ }),+ Tile(4, 5, dc =>+ {+ dc.DrawRectangle(Solid(A(two, 0x30)), null, new Rect(0, 1, 4, 4));+ dc.DrawRectangle(Solid(A(two, 0xD0)), null, new Rect(0, 2.6, 4, 1.4));+ }), 5);++ case "retro": // three 70s stripes+ return (null, Tile(4, 10, dc =>+ {+ dc.DrawRectangle(Solid(A(one, 0xC0)), null, new Rect(0, 0.5, 4, 2.4));+ dc.DrawRectangle(Solid(A(two, 0xC0)), null, new Rect(0, 3.7, 4, 2.4));+ dc.DrawRectangle(Solid(A(three, 0xC0)), null, new Rect(0, 6.9, 4, 2.4));+ }), 10);++ case "mocha": // soft polka dots+ return (Tile(18, 18, dc =>+ {+ dc.DrawEllipse(Solid(A(one, 0x26)), null, new Point(4.5, 4.5), 1.5, 1.5);+ dc.DrawEllipse(Solid(A(two, 0x1E)), null, new Point(13.5, 13.5), 1.5, 1.5);+ }), null, 0);++ case "paper": // ruled paper with its red margin line+ return (Tile(8, 9, dc => dc.DrawRectangle(Solid(A(accent, 0x22)), null, new Rect(0, 8.3, 8, 0.7))),+ Tile(4, 3, dc => dc.DrawRectangle(Solid(A(Color.FromRgb(0xE0, 0x4B, 0x4B), 0x55)), null, new Rect(0, 1, 4, 1))), 3);++ case "sakura": // falling blossoms and petals+ return (Tile(60, 46, dc =>+ {+ Blossom(dc, new Point(12, 13), 3.2, A(accent, 0x55));+ Blossom(dc, new Point(43, 31), 2.6, A(accent, 0x44));+ dc.DrawEllipse(Solid(A(accent, 0x3A)), null, new Point(32, 8), 1.6, 1.0);+ dc.DrawEllipse(Solid(A(accent, 0x30)), null, new Point(9, 37), 1.4, 0.9);+ dc.DrawEllipse(Solid(A(accent, 0x36)), null, new Point(53, 18), 1.2, 0.8);+ }), null, 0);++ default:+ return (null, null, 0);+ }+ }++ /// <summary>One tile, drawn at twice the size so it stays sharp on a high-density screen, repeated by the brush.</summary>+ private static ImageBrush Tile(double width, double height, Action<DrawingContext> draw)+ {+ var visual = new DrawingVisual();+ using (var dc = visual.RenderOpen()) draw(dc);+ var bitmap = new RenderTargetBitmap((int)Math.Ceiling(width * 2), (int)Math.Ceiling(height * 2), 192, 192, PixelFormats.Pbgra32);+ bitmap.Render(visual);+ bitmap.Freeze();+ var brush = new ImageBrush(bitmap)+ {+ TileMode = TileMode.Tile,+ Stretch = Stretch.Fill,+ ViewportUnits = BrushMappingMode.Absolute,+ Viewport = new Rect(0, 0, width, height)+ };+ brush.Freeze();+ return brush;+ }++ /// <summary>Points spread over a tile the same way every time (a fixed seed), so the texture never flickers.</summary>+ private static void Scatter(DrawingContext dc, double width, double height, int count, int seed, Action<double, double, double, int> each)+ {+ var random = new Random(seed);+ for (var i = 0; i < count; i++) each(random.NextDouble() * width, random.NextDouble() * height, random.NextDouble(), i);+ }++ private static Geometry Wave(double width, double height, double baseline, double amplitude, double shift)+ {+ var wave = new StreamGeometry();+ using (var g = wave.Open())+ {+ g.BeginFigure(new Point(0, height), true, true);+ for (var x = 0.0; x <= width; x += 1)+ g.LineTo(new Point(x, baseline + amplitude * Math.Sin((x + shift) / width * 2 * Math.PI)), true, false);+ g.LineTo(new Point(width, height), true, false);+ }+ wave.Freeze();+ return wave;+ }++ private static void Blossom(DrawingContext dc, Point centre, double size, Color colour)+ {+ var fill = Solid(colour);+ for (var i = 0; i < 5; i++)+ {+ var angle = i * 2 * Math.PI / 5 - Math.PI / 2;+ dc.DrawEllipse(fill, null, new Point(centre.X + Math.Cos(angle) * size * 0.75, centre.Y + Math.Sin(angle) * size * 0.75), size * 0.55, size * 0.55);+ }+ dc.DrawEllipse(Solid(A(Colors.White, 0x70)), null, centre, size * 0.3, size * 0.3);+ }++ private static Color C(string hex) => (Color)ColorConverter.ConvertFromString(hex);+ private static Color A(Color colour, byte alpha) => Color.FromArgb(alpha, colour.R, colour.G, colour.B);++ private static Brush Solid(Color colour)+ {+ var brush = new SolidColorBrush(colour);+ brush.Freeze();+ return brush;+ }++ private static Brush Vertical(Color top, Color bottom, double from, double to)+ {+ var brush = new LinearGradientBrush { StartPoint = new Point(0, 0), EndPoint = new Point(0, 1) };+ brush.GradientStops.Add(new GradientStop(top, from));+ brush.GradientStops.Add(new GradientStop(bottom, to));+ brush.Freeze();+ return brush;+ }+}diff --git a/Services/ThemeStyles.cs b/Services/ThemeStyles.csindex 1eae30c..3a29fba 100644--- a/Services/ThemeStyles.cs+++ b/Services/ThemeStyles.cs@@ -101,6 +101,7 @@ public static class ThemeStylesd["PanelTile"] = S(Alpha(style.Tile, 0xE6));d["PanelTileHover"] = S(style.Tile);d["PanelTileStroke"] = S(style.TileStroke);+ ThemePatterns.Add(d, style);return d;}}diff --git a/Services/UiText.cs b/Services/UiText.csindex 6e60149..98c4423 100644--- a/Services/UiText.cs+++ b/Services/UiText.cs@@ -15,7 +15,19 @@ public sealed class UiText : INotifyPropertyChanged["General"] = ("Genel", "General"),["Appearance"] = ("Görünüm", "Appearance"),["Widgets"] = ("Widget’lar", "Widgets"),- ["WidgetsDescription"] = ("Üst çubukta gösterilecek widget’ları seçin ve sıralayın.", "Choose which widgets appear in the top bar and in what order."),+ ["Wallpaper"] = ("Duvar kâğıdı", "Wallpaper"),+ ["WallpaperDescription"] = ("Bir resme tıklayın, masaüstü hemen değişsin. İnternetteki resimler yalnızca seçildiğinde 4K olarak indirilir; QiDock son birkaçını saklar.", "Click a picture and the desktop changes at once. Online pictures are downloaded in 4K only when chosen; QiDock keeps the last few."),+ ["WallpaperDaily"] = ("Günün resimleri (Bing)", "Pictures of the day (Bing)"),+ ["WallpaperWindowsOwn"] = ("Windows'un duvar kâğıtları", "Windows wallpapers"),+ ["WallpaperMore"] = ("Daha fazla göster", "Show more"),+ ["WallpaperPick"] = ("Bilgisayardan seç…", "Choose a file…"),+ ["WallpaperFiles"] = ("Resimler", "Pictures"),+ ["WallpaperLoading"] = ("Resimler yükleniyor…", "Loading pictures…"),+ ["WallpaperDownloading"] = ("İndiriliyor…", "Downloading…"),+ ["WallpaperSet"] = ("Duvar kâğıdı değişti.", "Wallpaper changed."),+ ["WallpaperFailed"] = ("Windows bu resmi duvar kâğıdı yapamadı.", "Windows could not use this picture as the wallpaper."),+ ["WallpaperOffline"] = ("İnternetteki resimlere ulaşılamadı. Bağlantınızı kontrol edin.", "The online pictures could not be reached. Check your connection."),+ ["WidgetsDescription"] =("Üst çubukta gösterilecek widget’ları seçin ve sıralayın.", "Choose which widgets appear in the top bar and in what order."),["Widget_profile"] = ("Profil", "Profile"),["Widget_currency"] = ("Döviz çevirici", "Currency converter"),["Widget_stopwatch"] = ("Kronometre ve sayaç", "Stopwatch and timer"),@@ -152,7 +164,6 @@ 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"),@@ -578,10 +589,8 @@ 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/WallpaperGallery.cs b/Services/WallpaperGallery.csnew file mode 100644index 0000000..63a27ac--- /dev/null+++ b/Services/WallpaperGallery.cs@@ -0,0 +1,242 @@+using System.IO;+using System.Net.Http;+using System.Runtime.InteropServices;+using System.Text.Json;+using System.Windows.Media.Imaging;+using QiDock.Services.Widgets;++namespace QiDock.Services;++/// <summary>One picture the gallery offers: from Bing's picture of the day, from Windows, or a file on this computer.</summary>+internal sealed record WallpaperChoice(string Key, string Title, string ThumbnailSource, string FullSource, bool Online);++/// <summary>+/// The wallpaper gallery behind Settings → Wallpaper. Nothing is bundled with QiDock: the online pictures are Bing's+/// pictures of the day (several countries have different ones), listed and shown as small previews only while the+/// gallery is open; a picture is downloaded in full (4K) only when it is chosen, and kept in a small folder that+/// holds the last few. Windows' own wallpapers and any picture file can be chosen too.+/// </summary>+internal static class WallpaperGallery+{+ private const string Bing = "https://www.bing.com";+ private const int KeepDownloads = 8;++ /// <summary>The countries whose pictures of the day are listed, a few at a time ("more" asks the next ones).</summary>+ private static readonly string[] Markets = ["tr-TR", "en-US", "ja-JP", "en-GB", "de-DE", "fr-FR", "en-IN", "pt-BR", "en-AU", "it-IT", "es-ES", "zh-CN"];++ public static int MarketCount => Markets.Length;++ /// <summary>A 4K picture is a few megabytes: the widgets' client gives up after twenty seconds, this one waits longer.</summary>+ private static readonly Lazy<HttpClient> Download = new(() =>+ {+ var client = new HttpClient { Timeout = TimeSpan.FromMinutes(3) };+ client.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("QiDock", "0.3"));+ return client;+ });++ public static string Folder => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock", "Wallpapers");++ /// <summary>The pictures of the day of markets [<paramref name="from"/>, from + count): the last fifteen days of each, without the ones in <paramref name="seen"/>.</summary>+ public static async Task<List<WallpaperChoice>> BingAsync(int from, int count, HashSet<string> seen, CancellationToken cancel)+ {+ var found = new List<WallpaperChoice>();+ foreach (var market in Markets.Skip(from).Take(count))+ foreach (var index in new[] { 0, 7 }) // Bing gives eight days at a time and fifteen in all+ {+ try+ {+ var json = await WidgetHttp.Client.GetStringAsync($"{Bing}/HPImageArchive.aspx?format=js&idx={index}&n=8&mkt={market}", cancel);+ using var document = JsonDocument.Parse(json);+ foreach (var image in document.RootElement.GetProperty("images").EnumerateArray())+ {+ if (image.TryGetProperty("wp", out var allowed) && allowed.ValueKind == JsonValueKind.False) continue; // not offered as a wallpaper+ if (image.GetProperty("urlbase").GetString() is not { Length: > 0 } urlBase || !urlBase.StartsWith("/th?id=OHR.", StringComparison.Ordinal)) continue;+ if (!seen.Add(urlBase)) continue;+ var title = image.TryGetProperty("copyright", out var copyright) ? copyright.GetString() ?? "" : "";+ found.Add(new WallpaperChoice(urlBase, title, $"{Bing}{urlBase}_320x180.jpg", $"{Bing}{urlBase}_UHD.jpg", true));+ }+ }+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException or KeyNotFoundException or InvalidOperationException)+ {+ if (cancel.IsCancellationRequested) throw new OperationCanceledException(cancel);+ AppLog.Write($"Wallpaper gallery: Bing {market} could not be read ({ex.GetType().Name})");+ }+ }+ return found;+ }++ /// <summary>The wallpapers that come with Windows.</summary>+ public static List<WallpaperChoice> Windows()+ {+ var root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Web", "Wallpaper");+ try+ {+ return Directory.EnumerateFiles(root, "*.*", SearchOption.AllDirectories)+ .Where(file => file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || file.EndsWith(".png", StringComparison.OrdinalIgnoreCase))+ .Order(StringComparer.OrdinalIgnoreCase)+ .Select(file => new WallpaperChoice(file, $"{Path.GetFileName(Path.GetDirectoryName(file))} · {Path.GetFileNameWithoutExtension(file)}", file, file, false))+ .ToList();+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ return [];+ }+ }++ /// <summary>A small preview (320 pixels wide), read away from the screen's thread.</summary>+ public static async Task<BitmapSource?> ThumbnailAsync(WallpaperChoice choice, CancellationToken cancel)+ {+ try+ {+ var bytes = choice.Online+ ? await WidgetHttp.Client.GetByteArrayAsync(choice.ThumbnailSource, cancel)+ : await File.ReadAllBytesAsync(choice.ThumbnailSource, cancel);+ return await Task.Run(() => Decode(bytes, 320), cancel);+ }+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or IOException or UnauthorizedAccessException+ or NotSupportedException or ArgumentException or FileFormatException or COMException)+ {+ return null;+ }+ }++ private static BitmapSource Decode(byte[] bytes, int width)+ {+ var image = new BitmapImage();+ using (var stream = new MemoryStream(bytes))+ {+ image.BeginInit();+ image.CacheOption = BitmapCacheOption.OnLoad;+ image.DecodePixelWidth = width;+ image.StreamSource = stream;+ image.EndInit();+ }+ image.Freeze();+ return image;+ }++ /// <summary>+ /// Makes <paramref name="choice"/> the desktop wallpaper: an online picture is downloaded in full first. The dock,+ /// the cards and the app screen follow by themselves (Windows tells them the desktop changed).+ /// </summary>+ public static async Task<string?> ApplyAsync(WallpaperChoice choice, CancellationToken cancel = default)+ {+ string file;+ if (choice.Online)+ {+ Directory.CreateDirectory(Folder);+ file = FileOf(choice);+ if (!File.Exists(file))+ {+ var bytes = await Download.Value.GetByteArrayAsync(choice.FullSource, cancel);+ var part = file + ".part";+ await File.WriteAllBytesAsync(part, bytes, cancel);+ File.Move(part, file, overwrite: true);+ }+ File.SetLastWriteTimeUtc(file, DateTime.UtcNow); // the newest is kept when old ones are cleared+ }+ else+ {+ file = choice.FullSource;+ }+ var faded = await Task.Run(() => Fade(file));+ if (!faded && !await Task.Run(() => SystemParametersInfo(SetDesktopWallpaper, 0, file, UpdateProfile | SendChange)))+ {+ AppLog.Write($"Wallpaper gallery: Windows did not take the wallpaper ({Marshal.GetLastWin32Error()})");+ return null;+ }+ AppLog.Write($"Wallpaper gallery: wallpaper set ({(choice.Online ? "Bing" : "file")}, {(faded ? "faded in" : "at once")})");+ if (choice.Online) ClearOld(file);+ Applied?.Invoke();+ _ = AgainAfterFadeAsync();+ return file;+ }++ /// <summary>Once more when the fade is over: Windows may write the new picture only then.</summary>+ private static async Task AgainAfterFadeAsync()+ {+ await Task.Delay(TimeSpan.FromSeconds(3));+ Applied?.Invoke();+ }++ /// <summary>+ /// Raised on the screen's thread after the gallery changed the wallpaper. The faded change does not always tell+ /// every program that the desktop changed, so the dock and the cards hear it here as well.+ /// </summary>+ public static event Action? Applied;++ /// <summary>+ /// Sets the wallpaper the way Windows' own slideshow does, so the old picture fades into the new one (Windows+ /// draws it; QiDock holds nothing for it). Asking the desktop for its background layer first is what turns the+ /// fade on. False when it did not work: the caller then sets the wallpaper at once.+ /// </summary>+ private static bool Fade(string file)+ {+ var done = false;+ var worker = new Thread(() =>+ {+ try+ {+ var desktopWindow = FindWindow("Progman", null);+ if (desktopWindow != 0) SendMessageTimeout(desktopWindow, 0x052C, 0, 0, 0, 1000, out _);+ using var desktop = ShellComObject.Create(ActiveDesktopClass, ActiveDesktopInterface);+ if (desktop.Method<SetWallpaperProc>(5)(desktop.Handle, file, 0) < 0) return;+ done = desktop.Method<ApplyChangesProc>(3)(desktop.Handle, ApplyAll | ApplyForce | ApplyBufferedRefresh) >= 0;+ }+ catch (Exception ex) when (ex is COMException or InvalidCastException or ArgumentException or MarshalDirectiveException)+ {+ AppLog.Write($"Wallpaper gallery: fade not available ({ex.GetType().Name})");+ }+ }) { IsBackground = true };+ worker.SetApartmentState(ApartmentState.STA);+ worker.Start();+ return worker.Join(TimeSpan.FromSeconds(10)) && done;+ }++ private static readonly Guid ActiveDesktopClass = new("75048700-EF1F-11D0-9888-006097DEACF9");+ private static readonly Guid ActiveDesktopInterface = new("F490EB00-1240-11D1-9888-006097DEACF9");+ private const int ApplyAll = 0x07, ApplyForce = 0x08, ApplyBufferedRefresh = 0x10;++ [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode)]+ private delegate int SetWallpaperProc(nint self, [MarshalAs(UnmanagedType.LPWStr)] string file, int reserved);++ [UnmanagedFunctionPointer(CallingConvention.StdCall)]+ private delegate int ApplyChangesProc(nint self, int flags);++ [DllImport("user32.dll", CharSet = CharSet.Unicode)]+ private static extern nint FindWindow(string className, string? windowName);++ [DllImport("user32.dll")]+ private static extern nint SendMessageTimeout(nint window, uint message, nint wParam, nint lParam, uint flags, uint timeout, out nint result);++ /// <summary>Keeps the last few downloaded pictures, so the folder never grows past a few tens of megabytes.</summary>+ private static void ClearOld(string keep)+ {+ try+ {+ foreach (var old in new DirectoryInfo(Folder).EnumerateFiles("*.jpg").OrderByDescending(f => f.LastWriteTimeUtc).Skip(KeepDownloads))+ if (!string.Equals(old.FullName, keep, StringComparison.OrdinalIgnoreCase)) old.Delete();+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ }+ }++ /// <summary>Where the picture is (or would be) on this computer: an online one in the download folder.</summary>+ public static string FileOf(WallpaperChoice choice)+ {+ if (!choice.Online) return choice.FullSource;+ var name = string.Concat(choice.Key.Replace("/th?id=OHR.", "", StringComparison.Ordinal).Where(c => char.IsLetterOrDigit(c) || c is '_' or '-'));+ return Path.Combine(Folder, name + ".jpg");+ }++ /// <summary>The picture the desktop shows now, as Windows recorded it (to mark it in the gallery).</summary>+ public static string? Current() =>+ Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Control Panel\Desktop", "WallPaper", null) as string;++ private const uint SetDesktopWallpaper = 0x0014; // SPI_SETDESKWALLPAPER+ private const uint UpdateProfile = 0x01, SendChange = 0x02;++ [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]+ private static extern bool SystemParametersInfo(uint action, uint param, string value, uint winIni);+}diff --git a/Services/Widgets/AiUsageService.cs b/Services/Widgets/AiUsageService.csindex c24e652..34f32a9 100644--- a/Services/Widgets/AiUsageService.cs+++ b/Services/Widgets/AiUsageService.cs@@ -1,4 +1,4 @@-using System.Globalization;+using System.Globalization;using System.IO;using System.Net;using System.Net.Http;@@ -43,6 +43,9 @@ public sealed partial class AiUsageServicepublic AiUsageService(){Cached = LastKnown();+#if DEBUG+ if (Promo.On) Cached = Promo.Ai();+#endif_claude = Cached.FirstOrDefault(u => u.Provider == ClaudeId);_gemini = Cached.FirstOrDefault(u => u.Provider == GeminiId);_openCode = Cached.FirstOrDefault(u => u.Provider == OpenCodeId);@@ -56,6 +59,9 @@ public sealed partial class AiUsageServicepublic async Task<IReadOnlyList<ProviderUsage>> FetchAsync(bool force, CancellationToken token){+#if DEBUG+ if (Promo.On) return Promo.Ai();+#endifvar results = new List<ProviderUsage>();var claude = await GetClaudeAsync(force, token).ConfigureAwait(false);if (claude is not null) results.Add(claude);diff --git a/Services/Widgets/BluetoothBatteries.cs b/Services/Widgets/BluetoothBatteries.csindex b91e555..6171573 100644--- a/Services/Widgets/BluetoothBatteries.cs+++ b/Services/Widgets/BluetoothBatteries.cs@@ -1,4 +1,4 @@-using System.Text.RegularExpressions;+using System.Text.RegularExpressions;using Windows.Devices.Bluetooth;using Windows.Devices.Enumeration;@@ -23,6 +23,9 @@ public static partial class BluetoothBatteriespublic static async Task<IReadOnlyList<DeviceBattery>> ReadAsync(){+#if DEBUG+ if (Promo.On) return Promo.Batteries;+#endif// 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[]diff --git a/Services/Widgets/BrowserPlaylist.cs b/Services/Widgets/BrowserPlaylist.csindex 5c112b9..84c8485 100644--- a/Services/Widgets/BrowserPlaylist.cs+++ b/Services/Widgets/BrowserPlaylist.cs@@ -36,13 +36,71 @@ internal static partial class BrowserPlaylistpublic 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(() =>+ /// <summary>+ /// Plays a song of the list: the same as clicking it in the browser. The song's links are looked up again first+ /// (the page may have redrawn the list since it was read); the entry has two (picture and title), and when the+ /// first does not start the song within a moment the other is tried. What happened goes to the log.+ /// </summary>+ public static Task<bool> PlayAsync(PlaylistSong song) => Task.Run(async () =>{- if (!song.Link.TryGetCurrentPattern(InvokePattern.Pattern, out var pattern)) return false;- ((InvokePattern)pattern).Invoke();- return true;- }));+ var links = Try(() => LinksOf(song)) ?? [];+ if (links.Count == 0) links.Add((song.Link, null));+ var step = 0;+ foreach (var (link, window) in links)+ {+ step++;+ var before = window is null ? "" : Try(() => window.Current.Name) ?? "";+ string outcome;+ try+ {+ if (!link.TryGetCurrentPattern(InvokePattern.Pattern, out var pattern))+ {+ AppLog.Write($"Playlist: song {song.Index} link {step} cannot be clicked");+ continue;+ }+ ((InvokePattern)pattern).Invoke();+ outcome = "clicked";+ }+ catch (Exception ex) when (ex is ElementNotAvailableException or InvalidOperationException or COMException or ArgumentException or TimeoutException)+ {+ AppLog.Write($"Playlist: song {song.Index} link {step} failed: {ex.GetType().Name} {ex.Message}");+ continue;+ }+ if (window is null) return true;+ // The window's title follows the video: once it changes, the song has started.+ for (var wait = 0; wait < 8; wait++)+ {+ await Task.Delay(250);+ var now = Try(() => window.Current.Name) ?? "";+ if (now != before && now.Length > 0)+ {+ AppLog.Write($"Playlist: song {song.Index} started ({outcome}, link {step})");+ return true;+ }+ }+ AppLog.Write($"Playlist: song {song.Index} link {step} {outcome}, but the page did not change");+ }+ return false;+ });++ /// <summary>The links of a song in the browser now, with the window they are in.</summary>+ private static List<(AutomationElement Link, AutomationElement? Window)> LinksOf(PlaylistSong song)+ {+ var found = new List<(AutomationElement, AutomationElement?)>();+ foreach (AutomationElement window in AutomationElement.RootElement.FindAll(TreeScope.Children, Windows))+ {+ if (!(Try(() => window.Current.Name) ?? "").Contains("YouTube", StringComparison.OrdinalIgnoreCase)) continue;+ foreach (AutomationElement link in window.FindAll(TreeScope.Descendants, Links))+ {+ var url = link.TryGetCurrentPattern(ValuePattern.Pattern, out var value) ? ((ValuePattern)value).Current.Value : "";+ var query = Query(url);+ if (query.GetValueOrDefault("v") == song.VideoId && query.GetValueOrDefault("index") == song.Index.ToString(System.Globalization.CultureInfo.InvariantCulture))+ found.Add((link, window));+ }+ if (found.Count > 0) break;+ }+ return found;+ }/// <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(() =>@@ -112,14 +170,20 @@ internal static partial class BrowserPlaylistwords.Add(word);if (words.Count == 2) break;}- return words.Count switch+ if (words.Count >= 2) return (words[0], words[1]);+ // Chrome usually gives only the link's whole name: "Title 3 dakika 33 saniye Channel". The spoken length+ // (in the browser's language) sits between the title and the channel.+ foreach (var whole in new[] { label.Trim(), words.Count == 1 ? words[0] : "" }){- 0 => (label.Trim(), ""),- 1 => (words[0], ""),- _ => (words[0], words[1])- };+ var parts = Spoken().Match(whole);+ if (parts.Success) return (parts.Groups[1].Value.Trim(), parts.Groups[3].Value.Trim());+ }+ return (words.Count == 1 ? words[0] : label.Trim(), "");}+ [GeneratedRegex(@"^(.+?)\s+((?:\d+\s+(?:saat|dakika|saniye|hours?|minutes?|seconds?),?\s*)+)(.*)$", RegexOptions.IgnoreCase)]+ private static partial Regex Spoken();+/// <summary>The video in the address bar of the window, the one playing.</summary>private static string? CurrentVideo(AutomationElement window){diff --git a/Services/Widgets/CpuTop.cs b/Services/Widgets/CpuTop.csindex a8373b9..e3c0dca 100644--- a/Services/Widgets/CpuTop.cs+++ b/Services/Widgets/CpuTop.cs@@ -1,4 +1,4 @@-using System.ComponentModel;+using System.ComponentModel;using System.Diagnostics;using System.IO;using System.Runtime.InteropServices;@@ -22,6 +22,9 @@ internal static class CpuTop/// <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){+#if DEBUG+ if (Promo.On) return Promo.CpuUsers();+#endifvar now = DateTime.UtcNow;var elapsed = (now - _previousAt).TotalMilliseconds;var first = _previousAt == default || elapsed > 30000;diff --git a/Services/Widgets/GlassLook.cs b/Services/Widgets/GlassLook.csindex 7529336..dd58704 100644--- a/Services/Widgets/GlassLook.cs+++ b/Services/Widgets/GlassLook.cs@@ -41,11 +41,12 @@ internal static class GlassLook{if (DockVeil is not { } veil) return null;if (WindowBehind) return Neutral;- if (WallpaperGlass.Image is not { } image || !localToScreen.HasInverse) return null;+ if (WallpaperGlass.Grey 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;+ // Nearly grey: in the wallpaper's own colours a pink or purple picture dyed the whole dock.+ if (Surface(area, area, veil, sheen: false, frost: true) is not { } baked) return null;_screen = screen = (veil, image, baked);}localToScreen.Invert();@@ -101,11 +102,12 @@ internal static class GlassLook/// <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).+ /// picture (the dock, what grows out of it, the app screen); otherwise the wallpaper's own colours, toned down+ /// (the desktop cards)./// </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;+ if ((frost ? WallpaperGlass.Grey : 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 shapevar area = Rect.Inflate(local, Bleed, Bleed);diff --git a/Services/Widgets/WallpaperGlass.cs b/Services/Widgets/WallpaperGlass.csindex 57563e9..0e5bfb5 100644--- a/Services/Widgets/WallpaperGlass.cs+++ b/Services/Widgets/WallpaperGlass.cs@@ -6,7 +6,7 @@ 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,+/// The wallpaper as frosted glass sees it: read once, small (256 pixels wide), softened and with its colours toned down,/// 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>@@ -20,6 +20,9 @@ internal static class WallpaperGlass/// <summary>The softened wallpaper, or null when there is none to read (a plain colour).</summary>public static BitmapSource? Image { get; private set; }+ /// <summary>The same picture with almost no colour left: neutral frosted glass (the app screen).</summary>+ public static BitmapSource? Grey { 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; }@@ -31,6 +34,7 @@ internal static class WallpaperGlass{var had = Image is not null;Image = null;+ Grey = null;if (had) Version++;_pixels = null;_stamp = "";@@ -54,15 +58,21 @@ internal static class WallpaperGlassint 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.+ // Three box passes come close to a gaussian blur. The colours are toned down, as frosted glass mutes what+ // is behind it: at full strength a pink or purple wallpaper dyed every card, the dock and the app screen.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);+ Saturate(pixels, 0.7);var bitmap = BitmapSource.Create(w, h, 96, 96, PixelFormats.Bgra32, null, pixels, w * 4);bitmap.Freeze();+ var greyPixels = (byte[])pixels.Clone();+ Saturate(greyPixels, 0.12);+ var grey = BitmapSource.Create(w, h, 96, 96, PixelFormats.Bgra32, null, greyPixels, w * 4);+ grey.Freeze();+ Grey = grey;Image = bitmap;Version++;_pixels = pixels;diff --git a/Services/Widgets/WallpaperTint.cs b/Services/Widgets/WallpaperTint.csindex 2c81247..2ab0365 100644--- a/Services/Widgets/WallpaperTint.cs+++ b/Services/Widgets/WallpaperTint.cs@@ -1,4 +1,4 @@-using System.IO;+using System.IO;using System.Windows;using System.Windows.Media;using System.Windows.Media.Imaging;@@ -19,6 +19,9 @@ internal static class WallpaperTint/// <summary>The current wallpaper as Windows stores it for the desktop (also when a slideshow changes it).</summary>internal static string? WallpaperFile(){+#if DEBUG+ if (Promo.Wallpaper is { } promo) return promo;+#endifvar 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;diff --git a/SettingsWindow.Wallpapers.cs b/SettingsWindow.Wallpapers.csnew file mode 100644index 0000000..908903b--- /dev/null+++ b/SettingsWindow.Wallpapers.cs@@ -0,0 +1,178 @@+using System.IO;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Media;+using QiDock.Services;++namespace QiDock;++/// <summary>+/// Settings → Wallpaper: a gallery of pictures for the desktop. It is built the first time the tab is opened, so the+/// rest of the time it costs nothing; its small previews leave memory with the settings window.+/// </summary>+public partial class SettingsWindow+{+ private const int MarketsPerStep = 2;+ private bool _wallpapersStarted;+ private int _marketsShown;+ private readonly HashSet<string> _wallpapersSeen = new(StringComparer.Ordinal);+ private readonly List<(Border Tile, WallpaperChoice Choice)> _wallpaperTiles = [];+ private readonly CancellationTokenSource _wallpaperCancel = new();+ private readonly SemaphoreSlim _previewSlots = new(6);+ private bool _wallpaperBusy;++ private void StartWallpaperGallery()+ {+ if (_wallpapersStarted) return;+ _wallpapersStarted = true;+ Closed += (_, _) => _wallpaperCancel.Cancel();+ foreach (var choice in WallpaperGallery.Windows()) WindowsWallpapers.Children.Add(Tile(choice));+ _ = MoreDailyAsync();+ }++ private void SettingsTabs_SelectionChanged(object sender, SelectionChangedEventArgs e)+ {+ if (e.Source == SettingsTabs && SettingsTabs.SelectedItem == WallpaperTab) StartWallpaperGallery();+ }++ private async Task MoreDailyAsync()+ {+ MoreWallpapersButton.IsEnabled = false;+ if (_marketsShown == 0) WallpaperStatus.Text = UiText.Get("WallpaperLoading");+ try+ {+ var found = await WallpaperGallery.BingAsync(_marketsShown, MarketsPerStep, _wallpapersSeen, _wallpaperCancel.Token);+ _marketsShown += MarketsPerStep;+ foreach (var choice in found) DailyWallpapers.Children.Add(Tile(choice));+ if (WallpaperStatus.Text == UiText.Get("WallpaperLoading")) WallpaperStatus.Text = "";+ if (DailyWallpapers.Children.Count == 0) WallpaperStatus.Text = UiText.Get("WallpaperOffline");+ }+ catch (OperationCanceledException)+ {+ return;+ }+ MoreWallpapersButton.IsEnabled = true;+ MoreWallpapersButton.Visibility = DailyWallpapers.Children.Count > 0 && _marketsShown < WallpaperGallery.MarketCount ? Visibility.Visible : Visibility.Collapsed;+ }++ private void MoreWallpapers_Click(object sender, RoutedEventArgs e) => _ = MoreDailyAsync();++ private Border Tile(WallpaperChoice choice)+ {+ var tile = new Border+ {+ CornerRadius = new CornerRadius(8),+ Margin = new Thickness(4),+ BorderThickness = new Thickness(2),+ BorderBrush = Brushes.Transparent,+ Cursor = Cursors.Hand,+ Focusable = true,+ ToolTip = choice.Title,+ Child = new TextBlock+ {+ Visibility = Visibility.Collapsed,+ HorizontalAlignment = HorizontalAlignment.Center,+ VerticalAlignment = VerticalAlignment.Center,+ Foreground = Brushes.White,+ FontWeight = FontWeights.SemiBold,+ Text = UiText.Get("WallpaperDownloading")+ }+ };+ tile.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ System.Windows.Automation.AutomationProperties.SetName(tile, choice.Title);+ tile.SizeChanged += (_, e) =>+ {+ if (e.WidthChanged) tile.Height = Math.Round(e.NewSize.Width * 9 / 16);+ };+ tile.MouseLeftButtonUp += (_, _) => _ = ChooseAsync(tile, choice);+ tile.KeyDown += (_, e) =>+ {+ if (e.Key is not (Key.Enter or Key.Space)) return;+ e.Handled = true;+ _ = ChooseAsync(tile, choice);+ };+ _wallpaperTiles.Add((tile, choice));+ MarkCurrent(tile, choice, WallpaperGallery.Current());+ _ = PreviewAsync(tile, choice);+ return tile;+ }++ private async Task PreviewAsync(Border tile, WallpaperChoice choice)+ {+ try+ {+ await _previewSlots.WaitAsync(_wallpaperCancel.Token);+ }+ catch (OperationCanceledException)+ {+ return;+ }+ try+ {+ if (await WallpaperGallery.ThumbnailAsync(choice, _wallpaperCancel.Token) is { } picture)+ tile.Background = new ImageBrush(picture) { Stretch = Stretch.UniformToFill };+ }+ finally+ {+ _previewSlots.Release();+ }+ }++ private async Task ChooseAsync(Border tile, WallpaperChoice choice)+ {+ if (_wallpaperBusy) return;+ _wallpaperBusy = true;+ var label = (TextBlock)tile.Child;+ if (choice.Online)+ {+ label.Visibility = Visibility.Visible;+ tile.Opacity = 0.75;+ }+ WallpaperStatus.Text = choice.Online ? UiText.Get("WallpaperDownloading") : "";+ try+ {+ var file = await WallpaperGallery.ApplyAsync(choice, _wallpaperCancel.Token);+ WallpaperStatus.Text = UiText.Get(file is null ? "WallpaperFailed" : "WallpaperSet");+ if (file is not null)+ foreach (var (other, otherChoice) in _wallpaperTiles) MarkCurrent(other, otherChoice, file);+ }+ catch (OperationCanceledException)+ {+ return;+ }+ catch (Exception ex) when (ex is System.Net.Http.HttpRequestException or IOException or UnauthorizedAccessException)+ {+ AppLog.Write($"Wallpaper gallery: picture could not be downloaded ({ex.GetType().Name})");+ WallpaperStatus.Text = UiText.Get("WallpaperOffline");+ }+ finally+ {+ _wallpaperBusy = false;+ label.Visibility = Visibility.Collapsed;+ tile.Opacity = 1;+ }+ }++ private async void PickWallpaper_Click(object sender, RoutedEventArgs e)+ {+ var dialog = new Microsoft.Win32.OpenFileDialog+ {+ Filter = $"{UiText.Get("WallpaperFiles")}|*.jpg;*.jpeg;*.png;*.bmp;*.webp",+ InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)+ };+ if (dialog.ShowDialog(this) != true) return;+ var file = await WallpaperGallery.ApplyAsync(new WallpaperChoice(dialog.FileName, Path.GetFileName(dialog.FileName), dialog.FileName, dialog.FileName, false));+ WallpaperStatus.Text = UiText.Get(file is null ? "WallpaperFailed" : "WallpaperSet");+ if (file is not null)+ foreach (var (tile, choice) in _wallpaperTiles) MarkCurrent(tile, choice, file);+ }++ /// <summary>A ring in the accent colour around the picture the desktop shows.</summary>+ private static void MarkCurrent(Border tile, WallpaperChoice choice, string? current)+ {+ var shown = current is not null && string.Equals(current, WallpaperGallery.FileOf(choice), StringComparison.OrdinalIgnoreCase);+ if (shown) tile.SetResourceReference(Border.BorderBrushProperty, "AccentBrush");+ else tile.BorderBrush = Brushes.Transparent;+ }+}diff --git a/SettingsWindow.xaml b/SettingsWindow.xamlindex fe0b553..00e5641 100644--- a/SettingsWindow.xaml+++ b/SettingsWindow.xaml@@ -47,7 +47,7 @@</Grid><!-- A picture of the dock as the choices below would make it, on every tab; nothing changes on screen until Apply. --><Border x:Name="PreviewHost" Grid.Row="1" BorderBrush="{DynamicResource MenuDivider}" BorderThickness="0,0,0,1" />- <TabControl x:Name="SettingsTabs" Grid.Row="2" TabStripPlacement="Left" SelectedIndex="0">+ <TabControl x:Name="SettingsTabs" Grid.Row="2" TabStripPlacement="Left" SelectedIndex="0" SelectionChanged="SettingsTabs_SelectionChanged"><TabItem Header="{local:Loc General}"><ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" CanContentScroll="False"><StackPanel Margin="{StaticResource SettingsPageInset}">@@ -95,11 +95,6 @@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}" />@@ -223,6 +218,25 @@</StackPanel></ScrollViewer></TabItem>+ <TabItem x:Name="WallpaperTab" Header="{local:Loc Wallpaper}">+ <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" CanContentScroll="False">+ <StackPanel Margin="{StaticResource SettingsPageInset}">+ <TextBlock Text="{local:Loc Wallpaper}" Style="{StaticResource SettingsHeading}" />+ <TextBlock Text="{local:Loc WallpaperDescription}" Foreground="{DynamicResource TextSecondary}" TextWrapping="Wrap" Margin="0,-4,0,12" />+ <DockPanel Margin="0,0,0,16">+ <Button x:Name="PickWallpaperButton" DockPanel.Dock="Right" Content="{local:Loc WallpaperPick}" Style="{StaticResource SettingsButton}" Click="PickWallpaper_Click" />+ <TextBlock x:Name="WallpaperStatus" TextWrapping="Wrap" VerticalAlignment="Center" Margin="0,0,12,0"+ Foreground="{DynamicResource TextSecondary}" AutomationProperties.LiveSetting="Polite" />+ </DockPanel>+ <TextBlock Text="{local:Loc WallpaperDaily}" FontWeight="SemiBold" Margin="0,0,0,8" />+ <UniformGrid x:Name="DailyWallpapers" Columns="3" Margin="-4,0" />+ <Button x:Name="MoreWallpapersButton" Content="{local:Loc WallpaperMore}" Style="{StaticResource SettingsButton}"+ HorizontalAlignment="Left" Margin="0,10,0,0" Visibility="Collapsed" Click="MoreWallpapers_Click" />+ <TextBlock Text="{local:Loc WallpaperWindowsOwn}" FontWeight="SemiBold" Margin="0,22,0,8" />+ <UniformGrid x:Name="WindowsWallpapers" Columns="3" Margin="-4,0" />+ </StackPanel>+ </ScrollViewer>+ </TabItem></TabControl><Border Grid.Row="3" Padding="20,12" BorderBrush="{DynamicResource MenuDivider}" BorderThickness="0,1,0,0"><Grid><Grid.ColumnDefinitions><ColumnDefinition Width="*" /><ColumnDefinition Width="Auto" /></Grid.ColumnDefinitions>diff --git a/SettingsWindow.xaml.cs b/SettingsWindow.xaml.csindex 8283d90..bb52993 100644--- a/SettingsWindow.xaml.cs+++ b/SettingsWindow.xaml.cs@@ -65,6 +65,12 @@ public partial class SettingsWindow : WindowAddHandler(ToggleButton.CheckedEvent, new RoutedEventHandler(PreferenceEdited));AddHandler(ToggleButton.UncheckedEvent, new RoutedEventHandler(PreferenceEdited));_initializing = false;+ // The look (dark or light, and the theme) changes the dock at once, without Apply: one tap shows it on the+ // real dock, which is how a theme is judged.+ foreach (var choice in StylePicker.Children.OfType<System.Windows.Controls.RadioButton>())+ choice.Checked += (_, _) => SaveLook(_preferences.Current with { Style = (string)choice.Tag }, _applied with { Style = (string)choice.Tag });+ DarkTheme.Checked += (_, _) => SaveLook(_preferences.Current with { Theme = AppTheme.Dark }, _applied with { Theme = AppTheme.Dark });+ LightTheme.Checked += (_, _) => SaveLook(_preferences.Current with { Theme = AppTheme.Light }, _applied with { Theme = AppTheme.Light });UpdateApplyState();}@@ -120,7 +126,6 @@ public partial class SettingsWindow : WindowAnimationsToggle.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;@@ -264,7 +269,6 @@ public partial class SettingsWindow : WindowAnimationsEnabled = 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),@@ -395,27 +399,12 @@ public partial class SettingsWindow : WindowMessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) != MessageBoxResult.Yes;}- /// <summary>One chip per look: three dots of its colours and its name.</summary>+ /// <summary>One chip per look: a tiny dock in its colours (its strip, its edge, four app squares) and its name.</summary>private void BuildStylePicker(){foreach (var look in ThemeStyles.All){- var dots = new System.Windows.Controls.Border- {- CornerRadius = new CornerRadius(6),- Padding = new Thickness(4, 3, 4, 3),- Margin = new Thickness(0, 0, 8, 0),- Background = new System.Windows.Media.SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(- look.Id == ThemeStyles.Glass ? "#33FFFFFF" : look.DockTop))- };- var row = new System.Windows.Controls.StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal };- foreach (var hex in look.Swatch)- row.Children.Add(new System.Windows.Shapes.Ellipse- {- Width = 7, Height = 7, Margin = new Thickness(1, 0, 1, 0),- Fill = new System.Windows.Media.SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(hex))- });- dots.Child = row;+ var dots = MiniDock(look);var content = new System.Windows.Controls.StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal };content.Children.Add(dots);content.Children.Add(new System.Windows.Controls.TextBlock { Text = look.Name, VerticalAlignment = VerticalAlignment.Center });@@ -426,6 +415,47 @@ public partial class SettingsWindow : Window}}+ private static System.Windows.Controls.Border MiniDock(ThemeStyle look)+ {+ static System.Windows.Media.Color C(string hex) => (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(hex);+ static System.Windows.Media.Brush Solid(string hex) => new System.Windows.Media.SolidColorBrush(C(hex));+ var glass = look.Id == ThemeStyles.Glass;+ // Glass: a grey frost with a light rim, as the dock shows it.+ var (top, bottom, edge) = glass ? ("#FF6A7079", "#FF464B52", "#66FFFFFF") : (look.DockTop, look.DockBottom, look.Edge);+ var row = new System.Windows.Controls.StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };+ foreach (var hex in look.Swatch.Append(glass ? "#FFFF6B8B" : look.Accent).Take(4))+ row.Children.Add(new System.Windows.Controls.Border+ {+ Width = 8, Height = 8, CornerRadius = new CornerRadius(2.2), Margin = new Thickness(1.5, 0, 1.5, 0),+ Background = Solid(hex),+ BorderBrush = Solid(look.Base == Models.AppTheme.Light && !glass ? "#22000000" : "#00000000"),+ BorderThickness = new Thickness(0.6)+ });+ return new System.Windows.Controls.Border+ {+ CornerRadius = new CornerRadius(5.5),+ Padding = new Thickness(3.5, 4, 3.5, 4),+ Margin = new Thickness(0, 0, 9, 0),+ VerticalAlignment = VerticalAlignment.Center,+ Background = new System.Windows.Media.LinearGradientBrush(C(top), C(bottom), 90),+ BorderBrush = Solid(edge),+ BorderThickness = new Thickness(1),+ Child = row+ };+ }++ private void SaveLook(DockSettings saved, DockSettings shown)+ {+ if (_initializing || saved == _preferences.Current) return;+ _applied = shown; // what this window shows as saved, so the look no longer counts as an unapplied edit+ if (_preferences.Save(saved) is { } error)+ {+ ShowResult(UiText.LocalizeError(error), error: true);+ return;+ }+ UpdateApplyState();+ }+private string SelectedStyle() =>StylePicker.Children.OfType<System.Windows.Controls.RadioButton>().FirstOrDefault(c => c.IsChecked == true)?.Tag as string ?? ThemeStyles.Glass;diff --git a/TopBarWindow.cs b/TopBarWindow.csindex c9fa6ea..d048e36 100644--- a/TopBarWindow.cs+++ b/TopBarWindow.cs@@ -327,8 +327,6 @@ public sealed class TopBarWindow : Windowprivate 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/ControlCenterWidget.cs b/Widgets/ControlCenterWidget.csindex 94589af..b05e762 100644--- a/Widgets/ControlCenterWidget.cs+++ b/Widgets/ControlCenterWidget.cs@@ -18,6 +18,7 @@ public sealed class ControlCenterWidget : DockWidget_tile = Ui.Tile(icon, (_, _) => ControlCenter.Shared.ToggleFrom(_tile!), horizontalPadding: 0);_tile.SetResourceReference(FrameworkElement.WidthProperty, "WidgetTileHeight");_tile.ToolTip = UiText.Get("ControlCenterTitle");+ _tile.MouseEnter += (_, _) => ControlCenter.Prepare(); // read ahead, so the panel opens completeSystem.Windows.Automation.AutomationProperties.SetName(_tile, UiText.Get("ControlCenterTitle"));}diff --git a/Widgets/MediaWidget.Card.cs b/Widgets/MediaWidget.Card.csindex 56c5879..35250b1 100644--- a/Widgets/MediaWidget.Card.cs+++ b/Widgets/MediaWidget.Card.cs@@ -1,4 +1,4 @@-using System.Runtime.InteropServices;+using System.Runtime.InteropServices;using System.Windows;using System.Windows.Controls;using System.Windows.Controls.Primitives;@@ -44,6 +44,89 @@ public sealed partial class MediaWidgetOpenAudio();FillCard();}++ /// <summary>+ /// Debug pictures for the promotional videos: the card with a made-up song (its cover given here, nothing read from+ /// the browser or the player), tinted from the cover as on the screen.+ /// </summary>+ internal void RehearsePromo(string title, string artist, BitmapSource cover)+ {+ _playPause.Content = Ui.Glyph("GlyphPause", 11);+ _idle = false;+ SetVisible(true);+ ToggleCard();+ RehearseNowPlaying(title, artist, cover);+ }++ /// <summary>Debug pictures: another made-up song is playing now.</summary>+ internal void RehearseNowPlaying(string title, string artist, BitmapSource cover)+ {+ _title.Text = title;+ _artist.Text = artist;+ _art.Source = cover;+ _playing = true;+ TintCard(cover);+ FillCard();+ RehearseState(72, 228, 0.64);+ }++ /// <summary>Debug pictures: a made-up place in the song and volume (no player or speaker is asked).</summary>+ private void RehearseState(double position, double length, double volume)+ {+ if (_seek is null || _volume is null) return;+ _seek.Visibility = _times!.Visibility = Visibility.Visible;+ _seek.Maximum = length;+ _seek.Value = position;+ _elapsed!.Text = Clock(position);+ _remaining!.Text = "-" + Clock(length - position);+ _settingVolume = true;+ _volume.Value = Math.Round(volume * 100);+ _settingVolume = false;+ _volumeText!.Text = UiText.Percent((int)_volume.Value);+ _volumeLabel!.Text = UiText.Get("MediaSystemVolume");+ _volumeIcon!.Data = (Geometry)Application.Current.FindResource("IconVolume");+ }++ /// <summary>Debug pictures: the playlist scrolled as <see cref="FillBack"/> scrolls it (the playing song, or+ /// <paramref name="song"/>, near the top).</summary>+ internal void RehearseScrollToCurrent(int? song = null)+ {+ if (_playedList is null || _backScroll is null) return;+ var index = song ?? _playlist.ToList().FindIndex(item => item.Current);+ if (index < 0 || index >= _playedList.Children.Count) return;+ var offset = Math.Max(0, _playedList.Children[index].TranslatePoint(new Point(), _playedList).Y - 50);+ _backScroll.ScrollToVerticalOffset(offset);+ // Off screen the scroll request waits for a layout pass that never comes: move the content at once.+ _backScroll.ApplyTemplate();+ if (_backScroll.Template?.FindName("PART_ScrollContentPresenter", _backScroll) is System.Windows.Controls.Primitives.IScrollInfo presenter)+ presenter.SetVerticalOffset(offset);+ _backScroll.UpdateLayout();+ }++ /// <summary>Debug pictures: the card turned to a made-up playlist, as <see cref="Flip"/> does (same size, the+ /// playing song near the top when <paramref name="scroll"/>).</summary>+ internal void RehearsePlaylist(IReadOnlyList<(string Title, string Channel, ImageSource Cover)> songs, int current, bool scroll)+ {+ if (_front is null || _back is null) return;+ _playlist = songs.Select((song, index) =>+ {+ var id = $"promo{index}";+ Thumbnails[id] = song.Cover;+ return new PlaylistSong(id, index + 1, song.Title, song.Channel, index == current, null!);+ }).ToList();+ _flipped = true;+ FillBack(scrollToCurrent: scroll);+ _back.Height = _front.ActualHeight;+ _front.Visibility = Visibility.Hidden;+ _back.Visibility = Visibility.Visible;+ }++ /// <summary>Debug pictures: the card part-way through its turn (1 = flat, 0 = edge on).</summary>+ internal void RehearseTurn(double scaleX)+ {+ _turn.BeginAnimation(ScaleTransform.ScaleXProperty, null);+ _turn.ScaleX = scaleX;+ }#endifprivate bool CardOpen => _popup?.IsOpen == true;@@ -234,6 +317,7 @@ public sealed partial class MediaWidgetprivate IReadOnlyList<PlaylistSong> _playlist = [];private System.Windows.Automation.AutomationElement? _hiddenTab;private int _playlistRead;+ private static bool _wheelSeen;// 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 = [];@@ -257,7 +341,7 @@ public sealed partial class MediaWidgetif (_played.Count > 20) _played.RemoveAt(_played.Count - 1);if (!_flipped) return;FillBack();- if (index != 0) ReadPlaylist(); // another song: the list moved on+ if (index != 0) ReadPlaylist(tries: 3); // another song: the list moved on}/// <summary>@@ -289,6 +373,7 @@ public sealed partial class MediaWidgetprivate async void PlaySong(PlaylistSong song){+ AppLog.Write($"Playlist: song {song.Index} chosen on the music card");if (!await BrowserPlaylist.PlayAsync(song)) return;_playlist = _playlist.Select(s => s with { Current = s.Index == song.Index }).ToList();FillBack();@@ -359,8 +444,45 @@ public sealed partial class MediaWidgetscroll.PreviewMouseWheel += (_, e) =>{e.Handled = true;+ if (!_wheelSeen)+ {+ _wheelSeen = true;+ Services.AppLog.Write($"Music card: wheel works (step {e.Delta})");+ }scroll.ScrollToVerticalOffset(Math.Clamp(scroll.VerticalOffset - e.Delta * 0.6, 0, scroll.ScrollableHeight));};+ // The list can also be dragged up and down (a touchpad that sends no wheel steps, or a finger). A press that+ // hardly moves stays a click on the song.+ Point? pressed = null;+ var startOffset = 0.0;+ var dragging = false;+ scroll.PreviewMouseLeftButtonDown += (_, e) =>+ {+ pressed = e.GetPosition(scroll);+ startOffset = scroll.VerticalOffset;+ dragging = false;+ };+ scroll.PreviewMouseMove += (_, e) =>+ {+ if (pressed is not { } start || e.LeftButton != MouseButtonState.Pressed) return;+ var moved = e.GetPosition(scroll).Y - start.Y;+ if (!dragging && Math.Abs(moved) < 6) return;+ if (!dragging)+ {+ dragging = true;+ scroll.CaptureMouse();+ }+ scroll.ScrollToVerticalOffset(Math.Clamp(startOffset - moved, 0, scroll.ScrollableHeight));+ };+ scroll.PreviewMouseLeftButtonUp += (_, e) =>+ {+ pressed = null;+ if (!dragging) return;+ dragging = false;+ scroll.ReleaseMouseCapture();+ e.Handled = true; // a drag is not a click on the song under the pointer+ };+ scroll.LostMouseCapture += (_, _) => dragging = false;var panel = new DockPanel { LastChildFill = true };panel.Children.Add(top);panel.Children.Add(scroll);@@ -479,7 +601,8 @@ public sealed partial class MediaWidgetif (_flipped){FillBack(scrollToCurrent: true);- ReadPlaylist();+ // Chrome builds its screen-reader view of the page only when first asked: the first look can be empty.+ ReadPlaylist(tries: 4);_back.Height = _front.ActualHeight; // the card keeps its size_front.Visibility = Visibility.Hidden;_back.Visibility = Visibility.Visible;@@ -489,6 +612,7 @@ public sealed partial class MediaWidget_front.Visibility = Visibility.Visible;_back.Visibility = Visibility.Collapsed;}+ WheelHook(_flipped);}if (!animate){diff --git a/Widgets/MediaWidget.Wheel.cs b/Widgets/MediaWidget.Wheel.csnew file mode 100644index 0000000..07f1a2c--- /dev/null+++ b/Widgets/MediaWidget.Wheel.cs@@ -0,0 +1,72 @@+using System.Diagnostics;+using System.Runtime.InteropServices;+using System.Windows;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>+/// Two-finger scrolling on a touchpad over the song list. The card stands in a window that never takes the focus+/// (so the app in front keeps it), and a touchpad's scrolling then never reaches the card. While the list is open,+/// Windows' scroll steps are heard directly: a step with the pointer over the list scrolls the list (and goes+/// nowhere else); every other step passes on untouched. Nothing is listened to while the list is closed.+/// </summary>+public sealed partial class MediaWidget+{+ private const int MouseHook = 14; // WH_MOUSE_LL+ private const int WheelMessage = 0x020A;+ private nint _wheelHook;+ private HookProc? _wheelProc; // kept alive while Windows holds it++ private void WheelHook(bool on)+ {+ if (on == (_wheelHook != 0)) return;+ if (!on)+ {+ UnhookWindowsHookEx(_wheelHook);+ _wheelHook = 0;+ return;+ }+ _wheelProc ??= OnWheel;+ using var process = Process.GetCurrentProcess();+ _wheelHook = SetWindowsHookEx(MouseHook, _wheelProc, GetModuleHandle(process.MainModule?.ModuleName), 0);+ if (_wheelHook == 0) AppLog.Write($"Music card: wheel listener could not start ({Marshal.GetLastWin32Error()})");+ }++ private nint OnWheel(int code, nint message, nint data)+ {+ if (code >= 0 && message == WheelMessage && _backScroll is { IsVisible: true } scroll && PresentationSource.FromVisual(scroll) is not null)+ {+ var info = Marshal.PtrToStructure<LowLevelMouse>(data);+ var topLeft = scroll.PointToScreen(new Point(0, 0));+ var bottomRight = scroll.PointToScreen(new Point(scroll.ActualWidth, scroll.ActualHeight));+ if (info.X >= topLeft.X && info.X < bottomRight.X && info.Y >= topLeft.Y && info.Y < bottomRight.Y)+ {+ var delta = (short)((info.MouseData >> 16) & 0xFFFF);+ if (!_wheelSeen)+ {+ _wheelSeen = true;+ AppLog.Write($"Music card: scrolling heard (step {delta})");+ }+ scroll.ScrollToVerticalOffset(Math.Clamp(scroll.VerticalOffset - delta * 0.6, 0, scroll.ScrollableHeight));+ return 1; // handled here: the window under the list does not scroll as well+ }+ }+ return CallNextHookEx(0, code, message, data);+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct LowLevelMouse+ {+ public int X, Y;+ public uint MouseData, Flags, Time;+ public nint ExtraInfo;+ }++ private delegate nint HookProc(int code, nint message, nint data);++ [DllImport("user32.dll", SetLastError = true)] private static extern nint SetWindowsHookEx(int id, HookProc proc, nint module, uint thread);+ [DllImport("user32.dll")] private static extern bool UnhookWindowsHookEx(nint hook);+ [DllImport("user32.dll")] private static extern nint CallNextHookEx(nint hook, int code, nint message, nint data);+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern nint GetModuleHandle(string? name);+}diff --git a/Widgets/MediaWidget.cs b/Widgets/MediaWidget.csindex b8c6a9a..f52d6a8 100644--- a/Widgets/MediaWidget.cs+++ b/Widgets/MediaWidget.cs@@ -131,6 +131,8 @@ public sealed partial class MediaWidget : DockWidget_popup?.Close();_progressTimer.Stop();Detach();+ foreach (var watched in _watched) watched.PlaybackInfoChanged -= Other_Changed;+ _watched.Clear();_manager = null;}@@ -181,7 +183,7 @@ public sealed partial class MediaWidget : DockWidgetGlobalSystemMediaTransportControlsSession? session;try{- session = _manager.GetCurrentSession() ?? _manager.GetSessions().FirstOrDefault();+ session = Choose(_manager);}catch (COMException){@@ -201,6 +203,57 @@ public sealed partial class MediaWidget : DockWidget_ = RefreshAsync();}+ /// <summary>+ /// Which player the tile follows. Windows' own "current" player is often a stale one (a paused video left open+ /// in another app), so: the one playing (Windows' choice first), else the one that played last here, else the+ /// one most recently active, else Windows' choice. Every player is watched, so starting one switches the tile.+ /// </summary>+ private GlobalSystemMediaTransportControlsSession? Choose(GlobalSystemMediaTransportControlsSessionManager manager)+ {+ var current = manager.GetCurrentSession();+ var all = manager.GetSessions().ToList();+ Watch(all);+ if (current is not null && IsPlaying(current)) return current;+ if (all.FirstOrDefault(IsPlaying) is { } playing) return playing;+ if (_lastPlayed is not null && all.FirstOrDefault(s => PlayerId(s) == _lastPlayed) is { } last) return last;+ return all.OrderByDescending(Active).FirstOrDefault() ?? current;++ static bool IsPlaying(GlobalSystemMediaTransportControlsSession s)+ {+ try { return s.GetPlaybackInfo()?.PlaybackStatus == GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing; }+ catch (COMException) { return false; }+ }+ static DateTimeOffset Active(GlobalSystemMediaTransportControlsSession s)+ {+ try { return s.GetTimelineProperties()?.LastUpdatedTime ?? DateTimeOffset.MinValue; }+ catch (COMException) { return DateTimeOffset.MinValue; }+ }+ }++ private static string? PlayerId(GlobalSystemMediaTransportControlsSession s)+ {+ try { return s.SourceAppUserModelId; }+ catch (COMException) { return null; }+ }++ private string? _lastPlayed;+ private readonly List<GlobalSystemMediaTransportControlsSession> _watched = [];++ /// <summary>Hears every player start or stop (not only the one shown), so the tile can move to it.</summary>+ private void Watch(List<GlobalSystemMediaTransportControlsSession> sessions)+ {+ foreach (var old in _watched) old.PlaybackInfoChanged -= Other_Changed;+ _watched.Clear();+ foreach (var session in sessions)+ {+ session.PlaybackInfoChanged += Other_Changed;+ _watched.Add(session);+ }+ }++ private void Other_Changed(GlobalSystemMediaTransportControlsSession sender, object args) =>+ _dispatcher.InvokeAsync(AttachCurrentSession);+private void Detach(){if (_session is null) return;@@ -241,6 +294,7 @@ public sealed partial class MediaWidget : DockWidget_artist.Text = string.IsNullOrWhiteSpace(title) ? "" : artist;_tile.ToolTip = text;var playing = _playing = playback?.PlaybackStatus == GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing;+ if (playing) _lastPlayed = PlayerId(session);_playPause.Content = Ui.Glyph(playing ? "GlyphPause" : "GlyphPlay", 11);_previous.IsEnabled = playback?.Controls?.IsPreviousEnabled != false;_next.IsEnabled = playback?.Controls?.IsNextEnabled != false;diff --git a/Widgets/WidgetUi.cs b/Widgets/WidgetUi.csindex ebb3be5..b564754 100644--- a/Widgets/WidgetUi.cs+++ b/Widgets/WidgetUi.cs@@ -189,6 +189,15 @@ public sealed class WidgetPopup_surface.Margin = new Thickness(0);return _surface;}++ /// <summary>Debug snapshot run: the card in the sheet it grows out of the dock in (as <see cref="ToggleSheet"/> does).</summary>+ internal DockSheet RehearseSheet()+ {+ var sheet = new DockSheet(_width);+ _surface.Child = null;+ sheet.Body = _content;+ return sheet;+ }#endifpublic void Toggle()diff --git a/docs/images/features/01-apps-screen-horizontal.png b/docs/images/features/01-apps-screen-horizontal.pngnew file mode 100644index 0000000..8344bccBinary files /dev/null and b/docs/images/features/01-apps-screen-horizontal.png differdiff --git a/docs/images/features/01-apps-screen-vertical.png b/docs/images/features/01-apps-screen-vertical.pngnew file mode 100644index 0000000..943e223Binary files /dev/null and b/docs/images/features/01-apps-screen-vertical.png differdiff --git a/docs/images/features/02-files-horizontal.png b/docs/images/features/02-files-horizontal.pngnew file mode 100644index 0000000..af146a0Binary files /dev/null and b/docs/images/features/02-files-horizontal.png differdiff --git a/docs/images/features/02-files-vertical.png b/docs/images/features/02-files-vertical.pngnew file mode 100644index 0000000..002b790Binary files /dev/null and b/docs/images/features/02-files-vertical.png differdiff --git a/docs/images/features/03-wallpaper-gallery-horizontal.png b/docs/images/features/03-wallpaper-gallery-horizontal.pngnew file mode 100644index 0000000..f5a533aBinary files /dev/null and b/docs/images/features/03-wallpaper-gallery-horizontal.png differdiff --git a/docs/images/features/03-wallpaper-gallery-vertical.png b/docs/images/features/03-wallpaper-gallery-vertical.pngnew file mode 100644index 0000000..7f73ffaBinary files /dev/null and b/docs/images/features/03-wallpaper-gallery-vertical.png differdiff --git a/docs/images/features/04-updater-horizontal.png b/docs/images/features/04-updater-horizontal.pngnew file mode 100644index 0000000..c46a28eBinary files /dev/null and b/docs/images/features/04-updater-horizontal.png differdiff --git a/docs/images/features/04-updater-vertical.png b/docs/images/features/04-updater-vertical.pngnew file mode 100644index 0000000..cced33bBinary files /dev/null and b/docs/images/features/04-updater-vertical.png differdiff --git a/docs/images/features/05-themes-horizontal.png b/docs/images/features/05-themes-horizontal.pngnew file mode 100644index 0000000..8f1b5b7Binary files /dev/null and b/docs/images/features/05-themes-horizontal.png differdiff --git a/docs/images/features/05-themes-vertical.png b/docs/images/features/05-themes-vertical.pngnew file mode 100644index 0000000..92d50d0Binary files /dev/null and b/docs/images/features/05-themes-vertical.png differdiff --git a/docs/images/features/06-glass-look-horizontal.png b/docs/images/features/06-glass-look-horizontal.pngnew file mode 100644index 0000000..f3396a4Binary files /dev/null and b/docs/images/features/06-glass-look-horizontal.png differdiff --git a/docs/images/features/06-glass-look-vertical.png b/docs/images/features/06-glass-look-vertical.pngnew file mode 100644index 0000000..701f31eBinary files /dev/null and b/docs/images/features/06-glass-look-vertical.png differdiff --git a/docs/images/features/07-keyboard-dock-horizontal.png b/docs/images/features/07-keyboard-dock-horizontal.pngnew file mode 100644index 0000000..2c525f3Binary files /dev/null and b/docs/images/features/07-keyboard-dock-horizontal.png differdiff --git a/docs/images/features/07-keyboard-dock-vertical.png b/docs/images/features/07-keyboard-dock-vertical.pngnew file mode 100644index 0000000..23b81a7Binary files /dev/null and b/docs/images/features/07-keyboard-dock-vertical.png differdiff --git a/docs/images/features/08-sharp-icons-horizontal.png b/docs/images/features/08-sharp-icons-horizontal.pngnew file mode 100644index 0000000..6802b52Binary files /dev/null and b/docs/images/features/08-sharp-icons-horizontal.png differdiff --git a/docs/images/features/08-sharp-icons-vertical.png b/docs/images/features/08-sharp-icons-vertical.pngnew file mode 100644index 0000000..da9046bBinary files /dev/null and b/docs/images/features/08-sharp-icons-vertical.png differdiff --git a/docs/images/features/09-playlist-horizontal.png b/docs/images/features/09-playlist-horizontal.pngnew file mode 100644index 0000000..35361eaBinary files /dev/null and b/docs/images/features/09-playlist-horizontal.png differdiff --git a/docs/images/features/09-playlist-vertical.png b/docs/images/features/09-playlist-vertical.pngnew file mode 100644index 0000000..99b60b8Binary files /dev/null and b/docs/images/features/09-playlist-vertical.png differdiff --git a/docs/images/features/10-big-clock-horizontal.png b/docs/images/features/10-big-clock-horizontal.pngnew file mode 100644index 0000000..3aa9d68Binary files /dev/null and b/docs/images/features/10-big-clock-horizontal.png differdiff --git a/docs/images/features/10-big-clock-vertical.png b/docs/images/features/10-big-clock-vertical.pngnew file mode 100644index 0000000..df89b2fBinary files /dev/null and b/docs/images/features/10-big-clock-vertical.png differdiff --git a/docs/images/features/11-bluetooth-batteries-horizontal.png b/docs/images/features/11-bluetooth-batteries-horizontal.pngnew file mode 100644index 0000000..2706a9dBinary files /dev/null and b/docs/images/features/11-bluetooth-batteries-horizontal.png differdiff --git a/docs/images/features/11-bluetooth-batteries-vertical.png b/docs/images/features/11-bluetooth-batteries-vertical.pngnew file mode 100644index 0000000..841cc6dBinary files /dev/null and b/docs/images/features/11-bluetooth-batteries-vertical.png differdiff --git a/docs/images/features/12-cpu-usage-horizontal.png b/docs/images/features/12-cpu-usage-horizontal.pngnew file mode 100644index 0000000..9f13c54Binary files /dev/null and b/docs/images/features/12-cpu-usage-horizontal.png differdiff --git a/docs/images/features/12-cpu-usage-vertical.png b/docs/images/features/12-cpu-usage-vertical.pngnew file mode 100644index 0000000..15a931dBinary files /dev/null and b/docs/images/features/12-cpu-usage-vertical.png differdiff --git a/docs/images/features/13-ai-limits-horizontal.png b/docs/images/features/13-ai-limits-horizontal.pngnew file mode 100644index 0000000..7d0bc8aBinary files /dev/null and b/docs/images/features/13-ai-limits-horizontal.png differdiff --git a/docs/images/features/13-ai-limits-vertical.png b/docs/images/features/13-ai-limits-vertical.pngnew file mode 100644index 0000000..c880cc5Binary files /dev/null and b/docs/images/features/13-ai-limits-vertical.png differ