A macOS-style dock, widget bar and desktop widgets for Windows (WPF, .NET 10)
QiDock: a macOS-style dock and widget bar for Windows
QiDock contributorscb3ae137e2f6
diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..12a1cbe--- /dev/null+++ b/.gitattributes@@ -0,0 +1,8 @@+* text=auto+*.cs text eol=crlf+*.xaml text eol=crlf+*.csproj text eol=crlf+*.ps1 text eol=crlf+*.md text eol=lf+*.png binary+*.ico binarydiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..6a35ff9--- /dev/null+++ b/.gitignore@@ -0,0 +1,13 @@+bin/+obj/+.vs/+*.user+*.suo+*.log+artifacts/+dist/+publish/+.vscode/+.idea/+.claude/+*.DotSettings.userdiff --git a/App.xaml b/App.xamlnew file mode 100644index 0000000..77968e3--- /dev/null+++ b/App.xaml@@ -0,0 +1,14 @@+<Application x:Class="QiDock.App"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ ShutdownMode="OnMainWindowClose">+ <Application.Resources>+ <ResourceDictionary>+ <ResourceDictionary.MergedDictionaries>+ <ResourceDictionary Source="Design/Theme.xaml" />+ <ResourceDictionary Source="Design/ContextMenus.xaml" />+ <ResourceDictionary Source="Design/Widgets.xaml" />+ </ResourceDictionary.MergedDictionaries>+ </ResourceDictionary>+ </Application.Resources>+</Application>diff --git a/App.xaml.cs b/App.xaml.csnew file mode 100644index 0000000..ef02fe6--- /dev/null+++ b/App.xaml.cs@@ -0,0 +1,368 @@+using System.Diagnostics;+using System.Threading;+using System.Windows;+using QiDock.Services;++namespace QiDock;++/// <summary>+/// Interaction logic for App.xaml+/// </summary>+public partial class App : Application+{+ private Mutex? _instanceMutex;+ public ApplicationPreferences Preferences { get; } = new(new DockSettingsStore());++#if DEBUG+ /// <summary>Debug: draw the running dock with the widgets in each dock placement, then quit.</summary>+ public static string? DockSnapshotFolder { get; private set; }+ public static bool DockCycle { get; private set; }+#endif++ protected override void OnStartup(StartupEventArgs e)+ {+ UiText.Current.SetLanguage(Preferences.Current.Language);+ ThemeManager.Apply(Preferences.Current.Theme, Preferences.Current.SurfaceOpacity, Preferences.Current.Style);+#if DEBUG+ if (e.Args is ["--render-desktop-widgets", var sheet])+ {+ ShutdownMode = ShutdownMode.OnExplicitShutdown;+ DesktopWidgets.DeskSheet.Render(sheet, () => Preferences.Current.WidgetOptions, () => Shutdown());+ return;+ }+ if (e.Args is ["--snapshot-dock", var snapshots]) DockSnapshotFolder = snapshots;+ if (e.Args is ["--snapshot-cycle", var cycle]) { DockSnapshotFolder = cycle; DockCycle = true; }+ if (e.Args is ["--claude-activity", var report])+ {+ // Lists the Claude Code sessions of the last 30 minutes into the report file, as the Claude card shows them.+ ShutdownMode = ShutdownMode.OnExplicitShutdown;+ ClaudeActivityWatcher.RecentAsync(TimeSpan.FromMinutes(30)).ContinueWith(task =>+ {+ System.IO.File.WriteAllLines(report, task.Result.Select(a => $"{a.UpdatedAt.ToLocalTime():HH:mm:ss} {a.Project} | {a.Detail} | done={a.Done} | working={a.Working}"));+ Shutdown();+ }, TaskScheduler.FromCurrentSynchronizationContext());+ return;+ }+ if (e.Args is ["--render-styles", var styles])+ {+ ShutdownMode = ShutdownMode.OnExplicitShutdown;+ UiSheet.RenderStyles(styles, Preferences.Current.WidgetOptions, Preferences.Current.SurfaceOpacity, () => Shutdown());+ return;+ }+ if (e.Args is ["--memory-probe", var probe, .. var probeMode])+ {+ if (probeMode is ["software"]) System.Windows.Media.RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;+ // How much memory the panel windows hold: none, open, hidden but kept, and destroyed.+ ShutdownMode = ShutdownMode.OnExplicitShutdown;+ void Note(string step)+ {+ GC.Collect();+ GC.WaitForPendingFinalizers();+ using var self = System.Diagnostics.Process.GetCurrentProcess();+ System.IO.File.AppendAllText(probe, $"{step,-34} özel {self.PrivateMemorySize64 >> 20,5} MB çalışma {self.WorkingSet64 >> 20,5} MB{Environment.NewLine}");+ }+ var dock = new Window { Width = 1600, Height = 110, WindowStyle = WindowStyle.None, ShowInTaskbar = false, Left = 100, Top = 100, Content = new System.Windows.Controls.Border { Background = System.Windows.Media.Brushes.DimGray } };+ EdgePanel[] panels = [];+ var steps = new Queue<(string Name, Action Run)>(+ [+ ("başlangıç (pencere yok)", () => { }),+ ("bir pencere açık", () => dock.Show()),+ ("paneller açık", () =>+ {+ panels = [NotificationCenter.Shared, ControlCenter.Shared, DockHud.Shared];+ foreach (var panel in panels) panel.Toggle();+ }),+ ("paneller gizli (bekliyor)", () => { foreach (var panel in panels) panel.Close(animated: false); }),+ ("paneller tamamen kapatıldı", () => { foreach (var panel in panels) ((Window)panel).Close(); }),+ ("pencere de kapatıldı", () => dock.Close())+ ]);+ var timer = new System.Windows.Threading.DispatcherTimer { Interval = TimeSpan.FromSeconds(2.5) };+ (string Name, Action Run)? pending = null;+ timer.Tick += (_, _) =>+ {+ if (pending is { } done) Note(done.Name);+ if (steps.Count == 0)+ {+ timer.Stop();+ Shutdown();+ return;+ }+ pending = steps.Dequeue();+ try { pending.Value.Run(); }+ catch (Exception ex) { System.IO.File.AppendAllText(probe, $"{pending.Value.Name}: {ex.Message}{Environment.NewLine}"); }+ };+ timer.Start();+ return;+ }+ if (e.Args is ["--frame-probe", var frames, .. var frameMode])+ {+ // How smoothly a dock-like see-through window slides, with and without its blurred shadow.+ if (frameMode is ["software"]) System.Windows.Media.RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;+ ShutdownMode = ShutdownMode.OnExplicitShutdown;+ var surfaceMove = new System.Windows.Media.TranslateTransform();+ var surface = new System.Windows.Controls.Border+ {+ Background = new System.Windows.Media.LinearGradientBrush(System.Windows.Media.Color.FromArgb(0xD0, 0x30, 0x30, 0x38), System.Windows.Media.Color.FromArgb(0xE0, 0x20, 0x20, 0x26), 90),+ CornerRadius = new CornerRadius(22), Margin = new Thickness(16, 44, 16, 8), RenderTransform = surfaceMove,+ BorderBrush = System.Windows.Media.Brushes.Gray, BorderThickness = new Thickness(1)+ };+ var row = new System.Windows.Controls.StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 0, 8, 0) };+ for (var i = 0; i < 18; i++)+ row.Children.Add(new System.Windows.Controls.Border { Width = 50, Height = 50, Margin = new Thickness(4), CornerRadius = new CornerRadius(12), Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(0x60, (byte)(40 * i % 255), 120, 200)) });+ surface.Child = row;+ var host = new Window { Width = 1200, Height = 120, WindowStyle = WindowStyle.None, AllowsTransparency = true, Background = System.Windows.Media.Brushes.Transparent, ShowInTaskbar = false, Topmost = true, Left = 200, Top = 300, Content = surface };+ host.Show();+ var cases = new Queue<(string Name, bool Shadow)>([("gölgeli", true), ("gölgesiz", false), ("gölgeli", true), ("gölgesiz", false)]);+ void RunNext()+ {+ if (cases.Count == 0) { host.Close(); Shutdown(); return; }+ var (name, shadow) = cases.Dequeue();+ surface.Effect = shadow ? new System.Windows.Media.Effects.DropShadowEffect { BlurRadius = 20, ShadowDepth = 3, Direction = 270, Opacity = 0.38, RenderingBias = System.Windows.Media.Effects.RenderingBias.Performance } : null;+ var frameCount = 0;+ var gaps = new List<double>();+ var last = Stopwatch.GetTimestamp();+ void Count(object? s, EventArgs a)+ {+ var now = Stopwatch.GetTimestamp();+ gaps.Add((now - last) * 1000.0 / Stopwatch.Frequency);+ last = now;+ frameCount++;+ }+ using var self = Process.GetCurrentProcess();+ var cpuBefore = self.TotalProcessorTime;+ var clock = Stopwatch.StartNew();+ System.Windows.Media.CompositionTarget.Rendering += Count;+ var slide = new System.Windows.Media.Animation.DoubleAnimation(0, 80, TimeSpan.FromMilliseconds(150)) { AutoReverse = true, RepeatBehavior = new System.Windows.Media.Animation.RepeatBehavior(10) };+ slide.Completed += (_, _) =>+ {+ System.Windows.Media.CompositionTarget.Rendering -= Count;+ clock.Stop();+ using var me = Process.GetCurrentProcess();+ var cpu = (me.TotalProcessorTime - cpuBefore).TotalMilliseconds / clock.Elapsed.TotalMilliseconds / Environment.ProcessorCount * 100;+ gaps.Sort();+ var worst = gaps.Count > 0 ? gaps[^1] : 0;+ var slow = gaps.Count(g => g > 25);+ System.IO.File.AppendAllText(frames, $"{(frameMode is ["software"] ? "işlemci" : "ekran kartı"),-12} {name,-9} saniyede {frameCount / clock.Elapsed.TotalSeconds,5:0} kare, 25 ms'yi aşan kare {slow,3}, en uzun {worst,5:0} ms, işlemci %{cpu:0.0}{Environment.NewLine}");+ surfaceMove.BeginAnimation(System.Windows.Media.TranslateTransform.YProperty, null);+ Dispatcher.BeginInvoke(RunNext, System.Windows.Threading.DispatcherPriority.ApplicationIdle);+ };+ surfaceMove.BeginAnimation(System.Windows.Media.TranslateTransform.YProperty, slide);+ }+ Dispatcher.BeginInvoke(RunNext, System.Windows.Threading.DispatcherPriority.ApplicationIdle);+ return;+ }+#if DEBUG+ if (e.Args is ["--audio-probe", var audioReport])+ {+ string result;+ try+ {+ using var endpoint = new QiDock.Services.Widgets.AudioEndpoint();+ var watcher = new QiDock.Services.Widgets.VolumeWatcher(Dispatcher);+ watcher.Start();+ var first = endpoint.Read();+ var firstProblem = endpoint.LastProblem;+ var second = endpoint.Read();+ result = $"izleyiciden sonra birinci: {first} {firstProblem}\nikinci: {second} {endpoint.LastProblem}\n";+ watcher.Dispose();+ }+ catch (Exception ex) { result = ex.ToString(); }+ System.IO.File.WriteAllText(audioReport, result);+ Shutdown();+ return;+ }+ if (e.Args is ["--wifi-probe", var wifiReport])+ {+ ShutdownMode = ShutdownMode.OnExplicitShutdown;+ Dispatcher.InvokeAsync(async () =>+ {+ string result;+ try+ {+ var wifi = new QiDock.Services.Widgets.WifiNetworks();+ var watch = System.Diagnostics.Stopwatch.StartNew();+ var (scan, networks) = await wifi.ScanAsync();+ result = $"{scan} ({watch.ElapsedMilliseconds} ms), {networks.Count} ağ\n"+ + string.Join("\n", networks.Select(n => $"{n.Ssid} çubuk={n.Bars} şifreli={n.Secured} bağlı={n.Connected}"));+ }+ catch (Exception ex) { result = ex.ToString(); }+ System.IO.File.WriteAllText(wifiReport, result);+ Shutdown();+ });+ return;+ }+ if (e.Args is ["--gallery-probe", var galleryReport, .. var galleryMode])+ {+ // How long the desktop widget gallery takes to open, and how smoothly it idles and scrolls.+ if (galleryMode is ["software"]) System.Windows.Media.RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;+ ShutdownMode = ShutdownMode.OnExplicitShutdown;+ var label = galleryMode is ["software"] ? "işlemci" : "ekran kartı";+ var opening = Stopwatch.StartNew();+ var gallery = new QiDock.DesktopWidgets.DeskGallery(new QiDock.DesktopWidgets.DeskWidgetManager());+ gallery.ContentRendered += (_, _) =>+ {+ opening.Stop();+ System.IO.File.AppendAllText(galleryReport, $"{label}: açılış {opening.ElapsedMilliseconds} ms{Environment.NewLine}");+ var shot = new System.Windows.Media.Imaging.RenderTargetBitmap((int)gallery.ActualWidth, (int)gallery.ActualHeight, 96, 96, System.Windows.Media.PixelFormats.Pbgra32);+ shot.Render((System.Windows.Media.Visual)gallery.Content);+ var png = new System.Windows.Media.Imaging.PngBitmapEncoder();+ png.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(shot));+ using (var file = System.IO.File.Create(System.IO.Path.ChangeExtension(galleryReport, ".png"))) png.Save(file);+ Measure("boşta", 5, null, () =>+ {+ var scroller = FindScroller(gallery);+ var offset = 0.0;+ Measure("kaydırırken", 4, () =>+ {+ offset += 9;+ if (offset > scroller?.ScrollableHeight) offset = 0;+ scroller?.ScrollToVerticalOffset(offset);+ }, () => { gallery.Close(); Shutdown(); });+ });+ };+ void Measure(string name, double seconds, Action? eachFrame, Action next)+ {+ var gaps = new List<double>();+ var last = Stopwatch.GetTimestamp();+ using var self = Process.GetCurrentProcess();+ var cpuBefore = self.TotalProcessorTime;+ var clock = Stopwatch.StartNew();+ void Count(object? s, EventArgs a)+ {+ var now = Stopwatch.GetTimestamp();+ gaps.Add((now - last) * 1000.0 / Stopwatch.Frequency);+ last = now;+ eachFrame?.Invoke();+ if (clock.Elapsed.TotalSeconds < seconds) return;+ System.Windows.Media.CompositionTarget.Rendering -= Count;+ using var me = Process.GetCurrentProcess();+ var cpu = (me.TotalProcessorTime - cpuBefore).TotalMilliseconds / clock.Elapsed.TotalMilliseconds / Environment.ProcessorCount * 100;+ gaps.Sort();+ System.IO.File.AppendAllText(galleryReport, $"{label}: {name,-12} saniyede {gaps.Count / clock.Elapsed.TotalSeconds,5:0} kare, 50 ms'yi aşan {gaps.Count(g => g > 50),3}, en uzun {(gaps.Count > 0 ? gaps[^1] : 0),5:0} ms, işlemci %{cpu:0.0}{Environment.NewLine}");+ Dispatcher.BeginInvoke(next, System.Windows.Threading.DispatcherPriority.ApplicationIdle);+ }+ System.Windows.Media.CompositionTarget.Rendering += Count;+ }+ static System.Windows.Controls.ScrollViewer? FindScroller(DependencyObject node)+ {+ if (node is System.Windows.Controls.ScrollViewer found) return found;+ for (var i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(node); i++)+ if (FindScroller(System.Windows.Media.VisualTreeHelper.GetChild(node, i)) is { } inner) return inner;+ return null;+ }+ gallery.Show();+ return;+ }+#endif+ if (e.Args is ["--render-ui", var folder])+ {+ ShutdownMode = ShutdownMode.OnExplicitShutdown;+ UiSheet.Render(folder, Preferences.Current.WidgetOptions, Preferences.Current.SurfaceOpacity, () => Shutdown());+ return;+ }+#endif+ // Started by Restart(): the old copy is still closing; give it a moment to let go of the taskbar and the lock.+ if (e.Args is ["--after", var previous] && int.TryParse(previous, out var previousId))+ {+ try { using var old = Process.GetProcessById(previousId); old.WaitForExit(15000); }+ catch (ArgumentException) { } // already gone+ }+ _instanceMutex = new Mutex(initiallyOwned: true, name: "Local\\QiDock.Singleton", out var createdNew);+ if (!createdNew)+ {+ MessageBox.Show(UiText.Get("AlreadyRunning"), "QiDock", MessageBoxButton.OK, MessageBoxImage.Information);+ _instanceMutex.Dispose();+ _instanceMutex = null;+ Shutdown();+ return;+ }++ base.OnStartup(e);+ DispatcherUnhandledException += (_, args) =>+ {+ // One failing click or timer must not take the dock (and the hidden Windows taskbar) down with it.+ AppLog.Write("Arayüz hatası (uygulama açık kaldı): " + args.Exception);+ args.Handled = true;+ };+ AppDomain.CurrentDomain.UnhandledException += (_, args) =>+ {+ AppLog.Write("Ölümcül hata: " + args.ExceptionObject);+ // The process is about to end: the Windows taskbar comes back now, not only at the next start.+ if (args.IsTerminating) Services.TaskbarReplacementSession.RestoreAfterCrash();+ };+ AppLog.StartMemoryReports();+ System.Threading.Tasks.TaskScheduler.UnobservedTaskException += (_, args) =>+ {+ AppLog.Write("Arka plan görevi hatası: " + args.Exception);+ args.SetObserved();+ };+ // Low-memory mode: everything is drawn by the processor. The graphics driver then never sets up its drawing+ // device, which alone holds about 300 MB on integrated graphics; animations cost a little more processor time.+ if (Preferences.Current.LowMemory)+ {+ System.Windows.Media.RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;+ SoftwareRendering = true;+ // Blurred shadows are what the processor draws slowest: a sliding dock with one drops from about 120 to+ // about 34 frames a second. Every shadow goes as soon as its element appears.+ EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.LoadedEvent, new RoutedEventHandler(static (sender, _) =>+ {+ if (sender is UIElement { Effect: System.Windows.Media.Effects.DropShadowEffect } element) element.Effect = null;+ }));+ AppLog.Write("Az bellek modu açık (çizim işlemcide, gölgesiz)");+ }+ var firstWindow = MainWindow?.GetType().Name ?? "yok";+ var window = new MainWindow();+ // The app ends when THIS window closes. Without this, the first window created (possibly a helper made+ // while the dock was being built) would count as the main one, and closing it would quit everything.+ var assigned = MainWindow?.GetType().Name ?? "yok";+ MainWindow = window;+ AppLog.Write($"Başladı (önceki ana pencere: {firstWindow}, kendiliğinden atanan: {assigned})");+ window.Show();+ }++ /// <summary>Whether this run draws on the processor (low-memory mode was on at start).</summary>+ public bool SoftwareRendering { get; private set; }++ /// <summary>Whether blurred shadows are drawn (not in low-memory mode, where they make animations stutter).</summary>+ public static bool Shadows => Current is not App { SoftwareRendering: true };++ /// <summary>Starts a fresh copy (which waits for this one to close) and closes this one.</summary>+ public void Restart()+ {+ if (Environment.ProcessPath is not { } path) return;+ try+ {+ Process.Start(new ProcessStartInfo(path, $"--after {Environment.ProcessId}") { UseShellExecute = false, WorkingDirectory = AppContext.BaseDirectory });+ }+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)+ {+ AppLog.Write("Yeniden başlatılamadı: " + ex.Message);+ return;+ }+ Shutdown();+ }++ protected override void OnExit(ExitEventArgs e)+ {+ AppLog.Write($"Kapandı (kod {e.ApplicationExitCode})");+ TrayHost.Shared.Stop();+ var error = (MainWindow as QiDock.MainWindow)?.RestoreWindowsTaskbar();+ if (error is not null)+ {+ Trace.TraceError(error);+ e.ApplicationExitCode = 1;+ }+ _instanceMutex?.ReleaseMutex();+ _instanceMutex?.Dispose();+ _instanceMutex = null;+ base.OnExit(e);+ }++ protected override void OnSessionEnding(SessionEndingCancelEventArgs e)+ {+ TrayHost.Shared.Stop();+ var error = (MainWindow as QiDock.MainWindow)?.RestoreWindowsTaskbar();+ if (error is not null) Trace.TraceError(error);+ base.OnSessionEnding(e);+ }+}diff --git a/AssemblyInfo.cs b/AssemblyInfo.csnew file mode 100644index 0000000..cc29e7f--- /dev/null+++ b/AssemblyInfo.cs@@ -0,0 +1,10 @@+using System.Windows;++[assembly:ThemeInfo(+ ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located+ //(used if a resource is not found in the page,+ // or application resource dictionaries)+ ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located+ //(used if a resource is not found in the page,+ // app, or any theme specific resource dictionaries)+)]diff --git a/ControlCenter.Wifi.cs b/ControlCenter.Wifi.csnew file mode 100644index 0000000..3dea019--- /dev/null+++ b/ControlCenter.Wifi.cs@@ -0,0 +1,281 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Threading;+using QiDock.Services;+using QiDock.Services.Widgets;+using QiDock.Widgets;++namespace QiDock;++/// <summary>+/// The Wi-Fi network list of the control center: opened from the Wi-Fi row, it shows the networks in range, joins+/// one with a click and asks for the password of a network Windows has not joined before.+/// </summary>+public sealed partial class ControlCenter+{+ private const int MaxNetworks = 12;+ private readonly WifiNetworks _wifi = new();+ private bool _showNetworks;+ private bool _scanning;+ private bool _scannedOnce;+ private WifiNetworks.Scan _scanResult;+ private IReadOnlyList<WifiNetworks.Network> _networks = [];+ private string? _joining;+ private string? _passwordFor;+ private string? _joinMessage;+ private PasswordBox? _passwordBox;++ private void ToggleNetworks()+ {+ _showNetworks = !_showNetworks;+ _passwordFor = null;+ _joinMessage = null;+ Rebuild(key => key == "networks" ? new Origin("top") : null);+ if (_showNetworks) _ = ScanNetworksAsync();+ }++ protected override void OnHidden()+ {+ _showNetworks = false;+ _passwordFor = null;+ _joinMessage = null;+ _passwordBox = null;+ }++#if DEBUG+ /// <summary>For the UI snapshot sheet: the open network list with a password being asked.</summary>+ internal FrameworkElement RehearseNetworks()+ {+ _showNetworks = true;+ _scannedOnce = true;+ _networks =+ [+ new("Home", 4, true, true, null),+ new("Home-Guest", 4, true, false, null),+ new("Office-5G", 3, true, false, null),+ new("Cafe", 2, false, false, null),+ new("Neighbor-2.4GHz", 1, true, false, null)+ ];+ _passwordFor = "Home-Guest";+ var sheet = Rehearse();+ _showNetworks = false;+ _passwordFor = null;+ return sheet;+ }+#endif++ private async Task ScanNetworksAsync()+ {+ if (_scanning) return;+ _scanning = true;+ try { (_scanResult, _networks) = await _wifi.ScanAsync(); }+ finally+ {+ _scanning = false;+ _scannedOnce = true;+ }+ if (_showNetworks) Refresh();+ }++ private async Task JoinAsync(WifiNetworks.Network network, string? password)+ {+ if (_joining is not null) return;+ _joining = network.Ssid;+ _joinMessage = null;+ Rebuild();+ WifiNetworks.Join result;+ try { result = await _wifi.ConnectAsync(network, password); }+ finally { _joining = null; }+ _passwordFor = result is WifiNetworks.Join.NeedsPassword or WifiNetworks.Join.WrongPassword ? network.Ssid : null;+ _joinMessage = result switch+ {+ WifiNetworks.Join.WrongPassword => UiText.Get("WifiWrongPassword"),+ WifiNetworks.Join.NotInRange => UiText.Get("WifiNotInRange"),+ WifiNetworks.Join.Unsupported => UiText.Get("WifiUnsupported"),+ WifiNetworks.Join.Failed => UiText.Get("WifiFailed"),+ _ => null+ };+ if (!IsOpen) return;+ if (result == WifiNetworks.Join.Connected)+ {+ await ScanNetworksAsync(); // the tick moves to the joined network+ return;+ }+ Rebuild();+ if (_passwordFor is not null && _passwordBox is { } box)+ {+ AllowTyping();+ _ = Dispatcher.InvokeAsync(() => Keyboard.Focus(box), DispatcherPriority.Input);+ }+ }++ private FrameworkElement NetworksCard()+ {+ var column = new StackPanel();+ var header = new DockPanel { Margin = new Thickness(4, 0, 0, 4) };+ var rescan = Ui.IconButton(Ui.Icon("IconRefresh", 13), (_, _) => _ = ScanNetworksAsync(), UiText.Get("WifiRescan"), 26, 24);+ rescan.IsEnabled = !_scanning;+ DockPanel.SetDock(rescan, Dock.Right);+ header.Children.Add(rescan);+ var title = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };+ title.Children.Add(Ui.Text(UiText.Get("WifiNetworks"), 12.5, FontWeights.SemiBold));+ if (_scanning && _networks.Count > 0)+ {+ var busy = Ui.Text(UiText.Get("WifiScanning"), 11, brushKey: "TextSecondary");+ busy.Margin = new Thickness(8, 0, 0, 0);+ busy.VerticalAlignment = VerticalAlignment.Center;+ title.Children.Add(busy);+ }+ header.Children.Add(title);+ column.Children.Add(header);++ _passwordBox = null;+ if (_scanResult == WifiNetworks.Scan.Denied && !_scanning)+ {+ column.Children.Add(Note(UiText.Get("WifiDenied")));+ }+ else if (_networks.Count == 0)+ {+ column.Children.Add(Note(UiText.Get(_scanning || !_scannedOnce ? "WifiScanning" : _scanResult == WifiNetworks.Scan.NoAdapter ? "WifiNoAdapter" : "WifiNone")));+ }+ else+ {+ foreach (var network in _networks.Take(MaxNetworks))+ {+ column.Children.Add(NetworkRow(network));+ if (network.Ssid == _passwordFor) column.Children.Add(PasswordRow(network));+ }+ }+ if (_joinMessage is not null && _passwordFor is null) column.Children.Add(Note(_joinMessage, error: true));++ var more = Ui.Pill(UiText.Get("WifiWindowsList"), (_, _) =>+ {+ Close(animated: true);+ Ui.Open("ms-availablenetworks:");+ });+ more.HorizontalAlignment = HorizontalAlignment.Left;+ more.Margin = new Thickness(4, 8, 0, 0);+ column.Children.Add(more);+ return Glass(column, new Thickness(10, 8, 10, 10), 16);+ }++ private static TextBlock Note(string text, bool error = false)+ {+ var note = Ui.Text(text, 11.5, brushKey: error ? null : "TextSecondary", brush: error ? Ui.Solid("#FFFF6961") : null);+ note.TextWrapping = TextWrapping.Wrap;+ note.Margin = new Thickness(4, 4, 4, 2);+ return note;+ }++ private FrameworkElement NetworkRow(WifiNetworks.Network network)+ {+ var signal = Ui.Icon("IconWifi", 14);+ signal.Opacity = network.Bars switch { >= 3 => 1, 2 => 0.75, _ => 0.5 };+ signal.VerticalAlignment = VerticalAlignment.Center;+ signal.Margin = new Thickness(0, 0, 10, 0);+ var row = new DockPanel { LastChildFill = true };+ DockPanel.SetDock(signal, Dock.Left);+ row.Children.Add(signal);+ if (network.Connected)+ {+ var tick = Ui.Icon("IconCheck", 12, On, null, 2.2);+ tick.VerticalAlignment = VerticalAlignment.Center;+ tick.Margin = new Thickness(8, 0, 0, 0);+ DockPanel.SetDock(tick, Dock.Right);+ row.Children.Add(tick);+ }+ if (network.Secured)+ {+ var padlock = Ui.Icon("IconLock", 11, brushKey: "TextSecondary");+ padlock.VerticalAlignment = VerticalAlignment.Center;+ padlock.Margin = new Thickness(8, 0, 0, 0);+ DockPanel.SetDock(padlock, Dock.Right);+ row.Children.Add(padlock);+ }+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ var name = Ui.Text(network.Ssid, 12.5, network.Connected ? FontWeights.SemiBold : FontWeights.Normal);+ name.TextTrimming = TextTrimming.CharacterEllipsis;+ text.Children.Add(name);+ if (network.Ssid == _joining)+ text.Children.Add(Ui.Text(UiText.Get("WifiJoining"), 10.5, brushKey: "TextSecondary"));+ row.Children.Add(text);++ var item = new Border+ {+ Child = row,+ MinHeight = 34,+ Padding = new Thickness(6, 3, 8, 3),+ CornerRadius = new CornerRadius(9),+ Background = Brushes.Transparent,+ Cursor = network.Connected ? null : Cursors.Hand,+ ToolTip = network.Connected ? UiText.Get("WifiConnectedHint") : null+ };+ item.MouseEnter += (_, _) => item.SetResourceReference(Border.BackgroundProperty, "SurfaceHover");+ item.MouseLeave += (_, _) => item.Background = Brushes.Transparent;+ item.MouseLeftButtonUp += (_, e) =>+ {+ e.Handled = true;+ if (network.Connected || _joining is not null) return;+ if (network.Ssid == _passwordFor) return;+ _passwordFor = null;+ _ = JoinAsync(network, null);+ };+ return item;+ }++ private FrameworkElement PasswordRow(WifiNetworks.Network network)+ {+ var box = new PasswordBox+ {+ Height = 30,+ FontSize = 12.5,+ Padding = new Thickness(8, 0, 8, 0),+ VerticalContentAlignment = VerticalAlignment.Center,+ BorderThickness = new Thickness(0),+ Background = Brushes.Transparent+ };+ box.SetResourceReference(Control.ForegroundProperty, "TextPrimary");+ box.SetResourceReference(PasswordBox.CaretBrushProperty, "TextPrimary");+ var frame = new Border { Child = box, CornerRadius = new CornerRadius(9), BorderThickness = new Thickness(1) };+ frame.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ frame.SetResourceReference(Border.BorderBrushProperty, "WidgetAccent");+ _passwordBox = box;++ void Join()+ {+ if (box.Password.Length == 0) return;+ _ = JoinAsync(network, box.Password);+ }+ void Cancel()+ {+ _passwordFor = null;+ _joinMessage = null;+ Rebuild();+ }+ box.KeyDown += (_, e) =>+ {+ if (e.Key == Key.Enter) Join();+ else if (e.Key == Key.Escape) Cancel();+ else return;+ e.Handled = true;+ };++ var column = new StackPanel { Margin = new Thickness(6, 2, 6, 8) };+ column.Children.Add(Note(_joinMessage ?? UiText.Format("WifiPasswordFor", network.Ssid), error: _joinMessage is not null));+ frame.Margin = new Thickness(0, 4, 0, 6);+ column.Children.Add(frame);+ var buttons = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right };+ var cancel = Ui.Pill(UiText.Get("WifiCancel"), (_, _) => Cancel());+ cancel.Margin = new Thickness(0, 0, 6, 0);+ buttons.Children.Add(cancel);+ var join = Ui.Pill(UiText.Get("WifiJoin"), (_, _) => Join());+ join.IsEnabled = _joining is null;+ buttons.Children.Add(join);+ column.Children.Add(buttons);+ // Clicking into the box lets the panel take the keyboard (it normally never takes the focus).+ box.PreviewMouseLeftButtonDown += (_, _) => AllowTyping();+ return column;+ }+}diff --git a/ControlCenter.cs b/ControlCenter.csnew file mode 100644index 0000000..7222e79--- /dev/null+++ b/ControlCenter.cs@@ -0,0 +1,475 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Threading;+using QiDock.Services;+using QiDock.Services.Notifications;+using QiDock.Services.Widgets;+using QiDock.Widgets;++namespace QiDock;++/// <summary>+/// Control center: Wi-Fi, Bluetooth, power mode, volume, brightness and battery in one panel on+/// the right edge, plus shortcuts (screen snip, lock, settings).+/// </summary>+public sealed partial class ControlCenter : EdgePanel+{+ private const double Half = 155;+ private static ControlCenter? _shared;+ private static readonly Brush On = Ui.Solid("#FF0A84FF");+ private static readonly Brush Off = Ui.Solid("#FF5A5A5E");++ public static ControlCenter Shared => _shared ??= new ControlCenter();+ public static bool IsCreated => _shared is not null;++ /// <summary>Opens QiDock's own settings (supplied by the main window).</summary>+ public static Action OpenAppSettings { get; set; } = () => { };++ private readonly AudioEndpoint _audio = new();+ private readonly RadioControls _radios = new();+ private readonly DispatcherTimer _brightnessDelay = new() { Interval = TimeSpan.FromMilliseconds(120) };+ private bool _radiosStarted;+ private int _pendingBrightness = -1;+ private Slider? _volumeSlider;+ private AudioEndpoint.State? _shownVolume;+ private bool _movingVolume;+ private string? _loggedVolumeProblem;++ private ControlCenter() : base(Half * 2 + 10, "QiDock Control Center")+ {+ _radios.Changed += (_, _) => Dispatcher.InvokeAsync(Refresh);+ _brightnessDelay.Tick += (_, _) =>+ {+ _brightnessDelay.Stop();+ if (_pendingBrightness >= 0) _ = Brightness.SetAsync(_pendingBrightness);+ };+ }++ /// <summary>+ /// Reads brightness (and the radios the first time) in the background and redraws once, after+ /// the panel has finished sliding in, and only if something changed.+ /// </summary>+ protected 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());+ }+ try { await Task.WhenAll(work); }+ catch (Exception ex)+ {+ System.Diagnostics.Trace.TraceWarning("Control center refresh failed: {0}", ex.Message);+ return;+ }+ // The volume is read again on every opening (off the window thread): what was shown may be out of date.+ AudioEndpoint.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();+ }++ /// <summary>The volume keys (or another app) changed the volume: the open panel's slider follows.</summary>+ public static void VolumeChanged(float level, bool muted)+ {+ if (_shared is not { IsOpen: true, _volumeSlider: { } slider } panel || slider.IsMouseCaptureWithin) return;+ if (panel._shownVolume is { } shown && shown.Muted != muted)+ {+ panel.Refresh(); // the mute icon changes too+ return;+ }+ panel._movingVolume = true;+ slider.Value = level * 100;+ panel._movingVolume = false;+ if (panel._shownVolume is { } was) panel._shownVolume = was with { Volume = level };+ }++ /// <summary>Redraws while open, but never under a slider being dragged (that would drop the drag).</summary>+ private void Refresh()+ {+ if (!IsOpen) return;+ if (_passwordBox is { IsKeyboardFocusWithin: true }) return; // a password being typed is never wiped away+ if (Mouse.Captured is DependencyObject held && Cards.IsAncestorOf(held))+ {+ Mouse.Captured.LostMouseCapture += Later;+ return;+ }+ Rebuild();++ void Later(object sender, MouseEventArgs e)+ {+ ((IInputElement)sender).LostMouseCapture -= Later;+ Dispatcher.BeginInvoke(Refresh, DispatcherPriority.Background);+ }+ }++ protected override void Build()+ {+ Cards.Children.Clear();+ 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) });+ top.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(Half) });+ // Centered in its tile, which is as tall as the two tiles beside it.+ var radios = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ if (_radios.HasWifi)+ {+ var network = _radios.WifiOn ? (RadioControls.IsOnWifi() ? RadioControls.CurrentNetworkName() : null) ?? UiText.Get("QcNotConnected") : UiText.Get("QcOff");+ if (!_radios.WifiOn) _showNetworks = false;+ radios.Children.Add(RadioRow(_radios.WifiOn ? "IconWifi" : "IconWifiOff", "Wi-Fi", network, _radios.WifiOn, () => _radios.ToggleWifiAsync(), _radios.WifiOn ? ToggleNetworks : null));+ }+ if (_radios.HasBluetooth)+ radios.Children.Add(RadioRow(_radios.BluetoothOn ? "IconBluetooth" : "IconBluetoothOff", "Bluetooth", UiText.Get(_radios.BluetoothOn ? "QcOn" : "QcOff"), _radios.BluetoothOn, () => _radios.ToggleBluetoothAsync()));+ if (radios.Children.Count == 0)+ radios.Children.Add(RadioRow("IconWifi", UiText.Get("CcNetwork"), RadioControls.CurrentNetworkName() ?? UiText.Get("QcNotConnected"), true, null, ToggleNetworks));+ var left = Glass(radios, new Thickness(12, 10, 10, 10), 16, Half);+ left.VerticalAlignment = VerticalAlignment.Stretch;+ top.Children.Add(left);++ var right = new StackPanel();+ Grid.SetColumn(right, 2);+ right.Children.Add(PowerTile());+ right.Children.Add(NotificationsTile());+ top.Children.Add(right);+ Cards.Children.Add(top);+ if (_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)));+ Cards.Children.Add(Keyed("shortcuts", Shortcuts()));+ }++ private static FrameworkElement Keyed(string key, FrameworkElement card)+ {+ Spaced(card).Tag = key;+ return card;+ }++ // ---- Connectivity and tiles ------------------------------------------------------------++ /// <summary>+ /// A radio's row. With <paramref name="open"/> (Wi-Fi) the round button switches the radio and the rest of the row+ /// opens the network list; otherwise the whole row switches it.+ /// </summary>+ private FrameworkElement RadioRow(string iconKey, string title, string status, bool on, Func<Task<bool>>? toggle, Action? open = null)+ {+ var circle = new Border { Width = 32, Height = 32, CornerRadius = new CornerRadius(16), Background = on ? On : Off, Child = Centered(Ui.Icon(iconKey, 15, Ui.White, null)), Margin = new Thickness(0, 0, 10, 0) };+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ text.Children.Add(Ui.Text(title, 12.5, FontWeights.SemiBold));+ var detail = Ui.Text(status, 11, brushKey: "TextSecondary");+ detail.TextTrimming = TextTrimming.CharacterEllipsis;+ text.Children.Add(detail);+ var row = new DockPanel { Margin = new Thickness(0, 5, 0, 5), Background = Brushes.Transparent, Cursor = toggle is null && open is null ? null : Cursors.Hand };+ DockPanel.SetDock(circle, Dock.Left);+ row.Children.Add(circle);+ if (open is not null)+ {+ var chevron = Ui.Icon("IconChevronRight", 10, brushKey: "TextSecondary");+ chevron.VerticalAlignment = VerticalAlignment.Center;+ chevron.Margin = new Thickness(6, 0, 0, 0);+ chevron.RenderTransformOrigin = new Point(0.5, 0.5);+ if (_showNetworks) chevron.RenderTransform = new RotateTransform(90);+ DockPanel.SetDock(chevron, Dock.Right);+ row.Children.Add(chevron);+ row.ToolTip = UiText.Get("WifiShowNetworks");+ }+ row.Children.Add(text);+ if (toggle is not null)+ {+ var target = open is null ? (UIElement)row : circle;+ circle.Cursor = Cursors.Hand;+ target.MouseLeftButtonUp += async (_, e) =>+ {+ e.Handled = true;+ if (!await toggle()) Ui.ShowHud(iconKey, UiText.Get("QcRadioDenied"));+ Rebuild();+ };+ }+ if (open is not null)+ row.MouseLeftButtonUp += (_, e) =>+ {+ if (e.Handled) return;+ e.Handled = true;+ open();+ };+ return row;+ }++ private FrameworkElement PowerTile()+ {+ var mode = PowerMode.Read();+ var name = mode switch+ {+ PowerMode.Mode.Efficiency => UiText.Get("CcModeEfficiency"),+ PowerMode.Mode.Performance => UiText.Get("CcModePerformance"),+ PowerMode.Mode.Balanced => UiText.Get("CcModeBalanced"),+ _ => "—"+ };+ return Tile("IconGauge", UiText.Get("CcPowerMode"), name, mode is not null, mode is null ? null : () =>+ {+ var next = mode switch { PowerMode.Mode.Efficiency => PowerMode.Mode.Balanced, PowerMode.Mode.Balanced => PowerMode.Mode.Performance, _ => PowerMode.Mode.Efficiency };+ if (!PowerMode.Set(next)) Ui.ShowHud("IconGauge", UiText.Get("QcPowerModeDenied"));+ Rebuild();+ });+ }++ private FrameworkElement NotificationsTile()+ {+ var unread = NotificationFeed.Shared.UnreadCount;+ var status = Widgets.NotificationsWidget.StatusText();+ var tile = Tile("IconBell", UiText.Get("NotificationsTitle"), status, unread > 0, () => NotificationCenter.Shared.Toggle());+ tile.Margin = new Thickness(0, 10, 0, 0);+ return tile;+ }++ private Border Tile(string iconKey, string title, string status, bool highlighted, Action? click)+ {+ var circle = new Border { Width = 32, Height = 32, CornerRadius = new CornerRadius(16), Background = highlighted ? On : Off, Child = Centered(Ui.Icon(iconKey, 15, Ui.White, null)), Margin = new Thickness(0, 0, 10, 0) };+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ var name = Ui.Text(title, 12.5, FontWeights.SemiBold);+ name.TextTrimming = TextTrimming.CharacterEllipsis;+ text.Children.Add(name);+ var detail = Ui.Text(status, 11, brushKey: "TextSecondary");+ detail.TextTrimming = TextTrimming.CharacterEllipsis;+ text.Children.Add(detail);+ var row = new DockPanel();+ DockPanel.SetDock(circle, Dock.Left);+ row.Children.Add(circle);+ row.Children.Add(text);+ var tile = Glass(row, new Thickness(12, 10, 10, 10), 16, Half);+ if (click is not null)+ {+ tile.Cursor = Cursors.Hand;+ tile.MouseLeftButtonUp += (_, e) =>+ {+ e.Handled = true;+ click();+ };+ }+ return tile;+ }++ // ---- Sliders ---------------------------------------------------------------------------++ private FrameworkElement VolumeCard()+ {+ var state = _audio.Read();+ _shownVolume = state;+ if (_audio.LastProblem is { } problem && problem != _loggedVolumeProblem)+ {+ _loggedVolumeProblem = problem;+ AppLog.Write($"Ses düzeyi okunamadı: {problem}");+ }+ var muted = state?.Muted == true;+ var mute = Ui.IconButton(Ui.Icon(muted ? "IconVolumeMute" : "IconVolume", 15), (_, _) =>+ {+ _audio.SetMute(!muted);+ Rebuild();+ }, UiText.Get("CcMute"), 30, 30);+ var slider = Slider(state is null ? 0 : state.Volume * 100, state is not null, value =>+ {+ if (_movingVolume) return;+ _audio.SetVolume((float)(value / 100));+ if (_shownVolume is { } was) _shownVolume = was with { Volume = (float)(value / 100), Muted = value > 0 ? false : was.Muted };+ });+ _volumeSlider = slider;+ return SliderCard(UiText.Get("CcVolume"), state?.DeviceName, mute, slider);+ }++ private FrameworkElement BrightnessCard(int level)+ {+ var icon = Centered(Ui.Icon("IconSun", 16));+ icon.Width = icon.Height = 30;+ var slider = Slider(level, true, value =>+ {+ // Applied every 120 ms while dragging (not only once the drag stops), newest value last.+ _pendingBrightness = (int)Math.Round(value);+ if (!_brightnessDelay.IsEnabled) _brightnessDelay.Start();+ });+ return SliderCard(UiText.Get("CcBrightness"), null, icon, slider);+ }++ private FrameworkElement SliderCard(string title, string? detail, FrameworkElement icon, Slider slider)+ {+ var header = new DockPanel { Margin = new Thickness(0, 0, 0, 4) };+ if (!string.IsNullOrWhiteSpace(detail))+ {+ var device = Ui.Text(detail, 11, brushKey: "TextSecondary");+ device.TextTrimming = TextTrimming.CharacterEllipsis;+ device.MaxWidth = 170;+ DockPanel.SetDock(device, Dock.Right);+ header.Children.Add(device);+ }+ header.Children.Add(Ui.Text(title, 12.5, FontWeights.SemiBold));+ var row = new DockPanel();+ icon.Margin = new Thickness(-4, 0, 6, 0);+ DockPanel.SetDock(icon, Dock.Left);+ row.Children.Add(icon);+ row.Children.Add(slider);+ var column = new StackPanel();+ column.Children.Add(header);+ column.Children.Add(row);+ return Glass(column, new Thickness(16, 10, 16, 8), 16);+ }++ private static Slider Slider(double value, bool enabled, Action<double> changed)+ {+ var slider = new Slider { Value = value, IsEnabled = enabled, VerticalAlignment = VerticalAlignment.Center, Height = 22 };+ slider.SetResourceReference(StyleProperty, "WidgetSlider");+ slider.ValueChanged += (_, e) => changed(e.NewValue);+ return slider;+ }++ // ---- Battery and shortcuts -------------------------------------------------------------++ private FrameworkElement BatteryCard(BatteryStatus.State battery)+ {+ var status = battery.Charging ? UiText.Get("CcCharging")+ : battery.OnAc ? UiText.Get("CcPlugged")+ : battery.Remaining is { } left ? UiText.Format("CcOnBattery", $"{(int)left.TotalHours} sa {left.Minutes} dk")+ : UiText.Get("CcBattery");+ var percent = Ui.Text($"%{battery.Percent}", 20, FontWeights.SemiBold);+ percent.VerticalAlignment = VerticalAlignment.Center;+ percent.Margin = new Thickness(0, 0, 14, 0);+ var fill = battery.Percent <= 20 && !battery.OnAc ? Ui.Solid("#FFFF453A") : battery.Charging ? Ui.Solid("#FF30D158") : On;+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ text.Children.Add(Ui.Text(UiText.Get("CcBattery"), 12.5, FontWeights.SemiBold));+ text.Children.Add(Ui.Text(status, 11, brushKey: "TextSecondary"));+ var bar = Ui.Bar(battery.Percent, 70, 8, fill);+ bar.VerticalAlignment = VerticalAlignment.Center;+ var row = new DockPanel();+ DockPanel.SetDock(percent, Dock.Left);+ DockPanel.SetDock(bar, Dock.Right);+ row.Children.Add(percent);+ row.Children.Add(bar);+ row.Children.Add(text);+ return Glass(row, new Thickness(16, 10, 16, 10), 16);+ }++ private FrameworkElement Shortcuts()+ {+ var row = new UniformGrid { Columns = 4 };+ row.Children.Add(Shortcut("IconCamera", UiText.Get("CcScreenshot"), () => Ui.Open("ms-screenclip:")));+ row.Children.Add(Shortcut("IconLock", UiText.Get("CcLock"), () => LockWorkStation()));+ var windowsSettings = Shortcut("IconSettings", UiText.Get("CcWindowsSettings"), () => Ui.Open("ms-settings:"));+ windowsSettings.ToolTip = UiText.Get("CcWindowsSettingsTip");+ row.Children.Add(windowsSettings);+ row.Children.Add(Shortcut("IconDock", UiText.Get("CcDockSettings"), () => OpenAppSettings()));+ return Glass(row, new Thickness(6, 10, 6, 8), 16);+ }++ private FrameworkElement Shortcut(string iconKey, string label, Action run)+ {+ var circle = new Border { Width = 36, Height = 36, CornerRadius = new CornerRadius(18), Child = Centered(Ui.Icon(iconKey, 15)), HorizontalAlignment = HorizontalAlignment.Center };+ circle.SetResourceReference(Border.BackgroundProperty, "SurfaceHover");+ var text = Ui.Text(label, 10.5, brushKey: "TextSecondary");+ text.HorizontalAlignment = HorizontalAlignment.Center;+ text.TextTrimming = TextTrimming.CharacterEllipsis;+ text.Margin = new Thickness(0, 5, 0, 0);+ var column = new StackPanel { Background = Brushes.Transparent, Cursor = Cursors.Hand };+ column.Children.Add(circle);+ column.Children.Add(text);+ column.MouseLeftButtonUp += (_, e) =>+ {+ e.Handled = true;+ Close(animated: true);+ run();+ };+ return column;+ }++ private static FrameworkElement Centered(FrameworkElement child)+ {+ child.HorizontalAlignment = HorizontalAlignment.Center;+ child.VerticalAlignment = VerticalAlignment.Center;+ var grid = new Grid();+ grid.Children.Add(child);+ return grid;+ }++ [DllImport("user32.dll")] private static extern bool LockWorkStation();+}++/// <summary>+/// Built-in display brightness through WMI (laptops and tablets; external monitors are not covered).+/// WMI is called on a worker thread so the panel never waits for it.+/// </summary>+internal static class Brightness+{+ private static bool _unsupported;++ /// <summary>The last level read, or null when there is no adjustable display.</summary>+ public static int? Current { get; private set; }++ public static Task RefreshAsync() => _unsupported ? Task.CompletedTask : Task.Run(() =>+ {+ try+ {+ foreach (dynamic item in Query("SELECT CurrentBrightness FROM WmiMonitorBrightness WHERE Active=TRUE"))+ {+ Current = Convert.ToInt32(item.Properties_.Item("CurrentBrightness").Value);+ return;+ }+ _unsupported = true;+ }+ catch (Exception ex) when (ex is COMException or InvalidCastException or FormatException or Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)+ {+ System.Diagnostics.Trace.TraceWarning("Brightness unavailable: {0}", ex.Message);+ }+ Current = null;+ });++ private static readonly object Gate = new();+ private static int _wanted = -1;++ /// <summary>+ /// Sets the level. Calls run one at a time and only the newest level is applied, so a fast+ /// drag never ends on an older value that finished last.+ /// </summary>+ public static Task SetAsync(int level)+ {+ Interlocked.Exchange(ref _wanted, Math.Clamp(level, 0, 100));+ return Task.Run(() =>+ {+ lock (Gate)+ {+ var target = Interlocked.Exchange(ref _wanted, -1);+ if (target < 0) return; // a newer call already applied it+ try+ {+ // Through ExecMethod_ with fresh parameters: calling WmiSetBrightness directly on+ // the object works once and then fails with "unspecified error" (stuck dimmed).+ foreach (dynamic item in Query("SELECT * FROM WmiMonitorBrightnessMethods WHERE Active=TRUE"))+ {+ dynamic parameters = item.Methods_.Item("WmiSetBrightness").InParameters.SpawnInstance_();+ parameters.Properties_.Item("Timeout").Value = 1;+ parameters.Properties_.Item("Brightness").Value = (byte)target;+ item.ExecMethod_("WmiSetBrightness", parameters);+ }+ Current = target;+ }+ catch (Exception ex) when (ex is COMException or InvalidCastException or UnauthorizedAccessException or Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)+ {+ System.Diagnostics.Trace.TraceWarning("Could not set brightness: {0}", ex.Message);+ }+ }+ });+ }++ private static dynamic Query(string wql)+ {+ var type = Type.GetTypeFromProgID("WbemScripting.SWbemLocator") ?? throw new COMException("WMI is not available.");+ dynamic locator = Activator.CreateInstance(type)!;+ dynamic service = locator.ConnectServer(".", @"root\wmi");+ service.Security_.ImpersonationLevel = 3; // impersonate+ return service.ExecQuery(wql);+ }+}diff --git a/Controls/UnclippedStackPanel.cs b/Controls/UnclippedStackPanel.csnew file mode 100644index 0000000..a7c6ab7--- /dev/null+++ b/Controls/UnclippedStackPanel.cs@@ -0,0 +1,15 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media;++namespace QiDock;++/// <summary>+/// A StackPanel that never applies WPF's layout clip. Magnified dock tiles grow above the dock and+/// briefly push the row wider than its arranged size; a normal panel would then clip the whole row+/// (including the scaled tiles) to its bounds.+/// </summary>+public sealed class UnclippedStackPanel : StackPanel+{+ protected override Geometry? GetLayoutClip(Size layoutSlotSize) => null;+}diff --git a/Design/ContextMenus.xaml b/Design/ContextMenus.xamlnew file mode 100644index 0000000..d157612--- /dev/null+++ b/Design/ContextMenus.xaml@@ -0,0 +1,136 @@+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">+ <Style TargetType="MenuItem">+ <Setter Property="Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="FontFamily" Value="{StaticResource InterfaceFont}" />+ <Setter Property="FontSize" Value="{StaticResource TextSizeBody}" />+ <Setter Property="Padding" Value="{StaticResource MenuRowPadding}" />+ <Setter Property="MinHeight" Value="34" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="HeaderTemplate">+ <Setter.Value><DataTemplate><TextBlock Text="{Binding}" MaxWidth="{StaticResource MenuLabelWidth}" TextTrimming="CharacterEllipsis" /></DataTemplate></Setter.Value>+ </Setter>+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="MenuItem">+ <Grid>+ <Border x:Name="ItemSurface" Background="{TemplateBinding Background}"+ CornerRadius="7" Padding="{TemplateBinding Padding}">+ <Grid>+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="26" />+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="22" />+ </Grid.ColumnDefinitions>+ <ContentPresenter x:Name="IconHost" Content="{TemplateBinding Icon}"+ TextElement.Foreground="{DynamicResource TextSecondary}"+ Width="16" Height="16"+ VerticalAlignment="Center" HorizontalAlignment="Center" />+ <ContentPresenter Grid.Column="1" ContentSource="Header" RecognizesAccessKey="True"+ VerticalAlignment="Center" />+ <Path x:Name="Checkmark" Grid.Column="2"+ Data="{StaticResource IconCheck}"+ Stroke="{DynamicResource TextPrimary}"+ StrokeThickness="1.8"+ StrokeStartLineCap="Round" StrokeEndLineCap="Round" StrokeLineJoin="Round"+ Width="12" Height="12" Stretch="Uniform" SnapsToDevicePixels="True"+ VerticalAlignment="Center" HorizontalAlignment="Right" Visibility="Collapsed" />+ <Path x:Name="SubmenuArrow" Grid.Column="2"+ Data="{StaticResource IconChevronRight}"+ Stroke="{DynamicResource TextSecondary}"+ StrokeThickness="1.6"+ StrokeStartLineCap="Round" StrokeEndLineCap="Round" StrokeLineJoin="Round"+ Width="10" Height="10" Stretch="Uniform" SnapsToDevicePixels="True"+ VerticalAlignment="Center" HorizontalAlignment="Right" Visibility="Collapsed" />+ </Grid>+ </Border>+ <Popup x:Name="PART_Popup" AllowsTransparency="True" Focusable="False"+ Placement="Right" PopupAnimation="None"+ IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}">+ <Border Background="{DynamicResource MenuMaterial}" BorderBrush="{DynamicResource MenuStroke}"+ BorderThickness="1" CornerRadius="{StaticResource PopupRadius}" Padding="5">+ <!-- Long submenus (81 provinces) scroll instead of running off screen. -->+ <ScrollViewer MaxHeight="440" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto" Focusable="False">+ <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Cycle" />+ </ScrollViewer>+ </Border>+ </Popup>+ </Grid>+ <ControlTemplate.Triggers>+ <Trigger Property="HasItems" Value="True">+ <Setter TargetName="SubmenuArrow" Property="Visibility" Value="Visible" />+ </Trigger>+ <Trigger Property="IsHighlighted" Value="True">+ <Setter TargetName="ItemSurface" Property="Background" Value="{DynamicResource SurfaceHover}" />+ <Setter TargetName="IconHost" Property="TextElement.Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter TargetName="SubmenuArrow" Property="Stroke" Value="{DynamicResource TextPrimary}" />+ </Trigger>+ <Trigger Property="IsChecked" Value="True">+ <Setter TargetName="Checkmark" Property="Visibility" Value="Visible" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter TargetName="ItemSurface" Property="Opacity" Value="0.42" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <Style x:Key="MenuSectionHeading" TargetType="MenuItem">+ <Setter Property="IsEnabled" Value="False" />+ <Setter Property="Focusable" Value="False" />+ <Setter Property="Foreground" Value="{DynamicResource TextSecondary}" />+ <Setter Property="FontFamily" Value="{StaticResource InterfaceFont}" />+ <Setter Property="FontSize" Value="{StaticResource TextSizeCaption}" />+ <Setter Property="FontWeight" Value="SemiBold" />+ <Setter Property="Padding" Value="10,5" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="MenuItem">+ <Border Padding="{TemplateBinding Padding}">+ <ContentPresenter ContentSource="Header" RecognizesAccessKey="True" />+ </Border>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <Style x:Key="{x:Static MenuItem.SeparatorStyleKey}" TargetType="Separator">+ <Setter Property="Margin" Value="{StaticResource MenuDividerInset}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="Separator">+ <Border Height="1" Background="{DynamicResource MenuDivider}" />+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <Style TargetType="Separator" BasedOn="{StaticResource {x:Static MenuItem.SeparatorStyleKey}}" />+ <Style TargetType="ContextMenu">+ <Setter Property="StaysOpen" Value="False" />+ <Setter Property="Background" Value="{DynamicResource MenuMaterial}" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter Property="BorderBrush" Value="{DynamicResource MenuStroke}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="Padding" Value="5" />+ <Setter Property="MinWidth" Value="244" />+ <Setter Property="MaxWidth" Value="380" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="ContextMenu">+ <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"+ BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="{StaticResource PopupRadius}"+ Padding="{TemplateBinding Padding}">+ <ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto"+ CanContentScroll="True" Focusable="False">+ <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Cycle" />+ </ScrollViewer>+ </Border>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <Style x:Key="DestructiveMenuItem" TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">+ <Setter Property="Foreground" Value="{DynamicResource DangerText}" />+ </Style>+</ResourceDictionary>diff --git a/Design/Palettes/Dark.xaml b/Design/Palettes/Dark.xamlnew file mode 100644index 0000000..7b0b379--- /dev/null+++ b/Design/Palettes/Dark.xaml@@ -0,0 +1,79 @@+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">+ <!-- Neutral materials preserve application icon colors and wallpaper visibility. -->+ <SolidColorBrush x:Key="TextPrimary" Color="#FFF1F3F5" />+ <SolidColorBrush x:Key="TextSecondary" Color="#FFADB5BF" />+ <SolidColorBrush x:Key="WindowsLogoBrush" Color="#FF54B6F5" />+ <SolidColorBrush x:Key="SurfaceKeyboardFocus" Color="#FF354652" />+ <SolidColorBrush x:Key="MenuStroke" Color="#30FFFFFF" />+ <LinearGradientBrush x:Key="MenuMaterial" StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#F5202227" Offset="0" />+ <GradientStop Color="#FA1B1D22" Offset="1" />+ </LinearGradientBrush>+ <!-- Frosted side panels (notification and control center): the tint over the blurred desktop and the tiles on it. -->+ <Color x:Key="PanelFrostTint">#C8191A1F</Color>+ <SolidColorBrush x:Key="PanelTile" Color="#1EFFFFFF" />+ <SolidColorBrush x:Key="PanelTileHover" Color="#2EFFFFFF" />+ <SolidColorBrush x:Key="PanelTileStroke" Color="#1AFFFFFF" />+ <!-- Widget popups stay nearly opaque regardless of the surface-opacity setting so text behind never shows through. -->+ <LinearGradientBrush x:Key="WidgetPopupFill" StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#FA1F2126" Offset="0" />+ <GradientStop Color="#FC1A1C21" Offset="1" />+ </LinearGradientBrush>+ <!-- Dock icon tiles (each app sits on a rounded glass square). -->+ <SolidColorBrush x:Key="DockTileFill" Color="#1CFFFFFF" />+ <SolidColorBrush x:Key="DockTileStroke" Color="#14FFFFFF" />+ <!-- Hover "liquid glass" bubble behind a dock icon: frosted fill, bright rim, top sheen. -->+ <LinearGradientBrush x:Key="GlassFill" StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#3DFFFFFF" Offset="0" />+ <GradientStop Color="#14FFFFFF" Offset="0.55" />+ <GradientStop Color="#2BFFFFFF" Offset="1" />+ </LinearGradientBrush>+ <LinearGradientBrush x:Key="GlassRim" StartPoint="0,0" EndPoint="1,1">+ <GradientStop Color="#E6FFFFFF" Offset="0" />+ <GradientStop Color="#33FFFFFF" Offset="0.4" />+ <GradientStop Color="#1AFFFFFF" Offset="0.62" />+ <GradientStop Color="#99FFFFFF" Offset="1" />+ </LinearGradientBrush>+ <LinearGradientBrush x:Key="GlassSheen" StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#59FFFFFF" Offset="0" />+ <GradientStop Color="#00FFFFFF" Offset="0.5" />+ </LinearGradientBrush>+ <SolidColorBrush x:Key="GlassShade" Color="#40000000" />+ <LinearGradientBrush x:Key="StartTileFill" StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#FF23252B" Offset="0" />+ <GradientStop Color="#FF0E0F12" Offset="1" />+ </LinearGradientBrush>+ <LinearGradientBrush x:Key="StartLogoBrush" StartPoint="0,0" EndPoint="1,1">+ <GradientStop Color="#FFFFFFFF" Offset="0" />+ <GradientStop Color="#FFB4BBC6" Offset="1" />+ </LinearGradientBrush>+ <SolidColorBrush x:Key="SurfacePopup" Color="#FF181C22" />+ <SolidColorBrush x:Key="StrokeSubtle" Color="#24FFFFFF" />+ <SolidColorBrush x:Key="StrokeFocus" Color="#FFD0E8FA" />+ <SolidColorBrush x:Key="SurfaceHover" Color="#22FFFFFF" />+ <SolidColorBrush x:Key="SurfacePressed" Color="#34FFFFFF" />+ <SolidColorBrush x:Key="SurfaceSelected" Color="#12FFFFFF" />+ <SolidColorBrush x:Key="SurfaceDanger" Color="#FFC43846" />+ <SolidColorBrush x:Key="NotificationBrush" Color="#FFFF6673" />+ <SolidColorBrush x:Key="IndicatorBrush" Color="#A8E4F3FF" />+ <SolidColorBrush x:Key="IndicatorForegroundBrush" Color="#FFFFFFFF" />+ <LinearGradientBrush x:Key="DockMaterial" StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#CC1E2530" Offset="0" />+ <GradientStop Color="#E210141C" Offset="1" />+ </LinearGradientBrush>+ <LinearGradientBrush x:Key="DockBorderMaterial" StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#4DFFFFFF" Offset="0" />+ <GradientStop Color="#16FFFFFF" Offset="1" />+ </LinearGradientBrush>+ <SolidColorBrush x:Key="SettingsBackground" Color="#FF181A1E" />+ <SolidColorBrush x:Key="SettingsSidebar" Color="#FF121417" />+ <SolidColorBrush x:Key="SettingsControl" Color="#FF22252A" />+ <SolidColorBrush x:Key="SettingsControlHover" Color="#FF2B2F35" />+ <SolidColorBrush x:Key="AccentBrush" Color="#FFB9D7EF" />+ <SolidColorBrush x:Key="AccentText" Color="#FF102332" />+ <SolidColorBrush x:Key="DangerText" Color="#FFFF9DA7" />+ <SolidColorBrush x:Key="MenuDivider" Color="#20FFFFFF" />+ <SolidColorBrush x:Key="SettingsSidebarOverlay" Color="#2410141A" />+ <SolidColorBrush x:Key="CaptionCloseForeground" Color="#FFFFFFFF" />+</ResourceDictionary>diff --git a/Design/Palettes/Light.xaml b/Design/Palettes/Light.xamlnew file mode 100644index 0000000..e7e8071--- /dev/null+++ b/Design/Palettes/Light.xaml@@ -0,0 +1,84 @@+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">+ <!-- Neutral materials preserve application icon colors and wallpaper visibility. -->+ <SolidColorBrush x:Key="TextPrimary" Color="#FF202329" />+ <SolidColorBrush x:Key="TextSecondary" Color="#FF5E6570" />+ <SolidColorBrush x:Key="WindowsLogoBrush" Color="#FF54B6F5" />+ <SolidColorBrush x:Key="SurfaceKeyboardFocus" Color="#FFCFDFEC" />+ <SolidColorBrush x:Key="MenuStroke" Color="#26000000" />+ <LinearGradientBrush x:Key="MenuMaterial" StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#F9FCFCFD" Offset="0" />+ <GradientStop Color="#FAF2F3F5" Offset="1" />+ </LinearGradientBrush>+ <!-- Frosted side panels (notification and control center): the tint over the blurred desktop and the tiles on it. -->+ <Color x:Key="PanelFrostTint">#C8F2F3F6</Color>+ <SolidColorBrush x:Key="PanelTile" Color="#A6FFFFFF" />+ <SolidColorBrush x:Key="PanelTileHover" Color="#D9FFFFFF" />+ <SolidColorBrush x:Key="PanelTileStroke" Color="#14000000" />+ <!-- Widget popups stay nearly opaque regardless of the surface-opacity setting so text behind never shows through. -->+ <LinearGradientBrush x:Key="WidgetPopupFill" StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#FCFCFCFD" Offset="0" />+ <GradientStop Color="#FDF2F3F5" Offset="1" />+ </LinearGradientBrush>+ <!-- Dock icon tiles (each app sits on a rounded glass square). -->+ <SolidColorBrush x:Key="DockTileFill" Color="#12000000" />+ <SolidColorBrush x:Key="DockTileStroke" Color="#14000000" />+ <!-- Hover "liquid glass" bubble behind a dock icon: frosted fill, bright rim, top sheen. -->+ <LinearGradientBrush x:Key="GlassFill" StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#80FFFFFF" Offset="0" />+ <GradientStop Color="#40FFFFFF" Offset="0.55" />+ <GradientStop Color="#66FFFFFF" Offset="1" />+ </LinearGradientBrush>+ <LinearGradientBrush x:Key="GlassRim" StartPoint="0,0" EndPoint="1,1">+ <GradientStop Color="#E6FFFFFF" Offset="0" />+ <GradientStop Color="#55FFFFFF" Offset="0.4" />+ <GradientStop Color="#26000000" Offset="0.62" />+ <GradientStop Color="#99FFFFFF" Offset="1" />+ </LinearGradientBrush>+ <LinearGradientBrush x:Key="GlassSheen" StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#59FFFFFF" Offset="0" />+ <GradientStop Color="#00FFFFFF" Offset="0.5" />+ </LinearGradientBrush>+ <SolidColorBrush x:Key="GlassShade" Color="#26000000" />+ <LinearGradientBrush x:Key="StartTileFill" StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#FF2A2D33" Offset="0" />+ <GradientStop Color="#FF14161A" Offset="1" />+ </LinearGradientBrush>+ <LinearGradientBrush x:Key="StartLogoBrush" StartPoint="0,0" EndPoint="1,1">+ <GradientStop Color="#FFFFFFFF" Offset="0" />+ <GradientStop Color="#FFB4BBC6" Offset="1" />+ </LinearGradientBrush>+ <SolidColorBrush x:Key="SurfacePopup" Color="#FFF8F9FB" />+ <SolidColorBrush x:Key="StrokeSubtle" Color="#20000000" />+ <SolidColorBrush x:Key="StrokeFocus" Color="#FF457DA8" />+ <SolidColorBrush x:Key="SurfaceHover" Color="#12000000" />+ <SolidColorBrush x:Key="SurfacePressed" Color="#20000000" />+ <SolidColorBrush x:Key="SurfaceSelected" Color="#0C000000" />+ <SolidColorBrush x:Key="SurfaceDanger" Color="#FFC43846" />+ <SolidColorBrush x:Key="NotificationBrush" Color="#FFD22D42" />+ <SolidColorBrush x:Key="IndicatorBrush" Color="#AA303A47" />+ <SolidColorBrush x:Key="IndicatorForegroundBrush" Color="#FF192A39" />+ <LinearGradientBrush x:Key="DockMaterial" StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#E2F6F7FA" Offset="0" />+ <GradientStop Color="#ECF3F4F7" Offset="1" />+ </LinearGradientBrush>+ <LinearGradientBrush x:Key="DockBorderMaterial" StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#B0FFFFFF" Offset="0" />+ <GradientStop Color="#22000000" Offset="1" />+ </LinearGradientBrush>+ <SolidColorBrush x:Key="SettingsBackground" Color="#FFF7F8FA" />+ <SolidColorBrush x:Key="SettingsSidebar" Color="#FFEEF0F3" />+ <SolidColorBrush x:Key="SettingsControl" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="SettingsControlHover" Color="#FFE8EBEF" />+ <SolidColorBrush x:Key="AccentBrush" Color="#FF245D87" />+ <SolidColorBrush x:Key="AccentText" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="DangerText" Color="#FFAF2338" />+ <SolidColorBrush x:Key="MenuDivider" Color="#20000000" />+ <SolidColorBrush x:Key="SettingsSidebarOverlay" Color="#24FFFFFF" />+ <SolidColorBrush x:Key="CaptionCloseForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="WidgetTileFill" Color="#0C000000" />+ <SolidColorBrush x:Key="WidgetTileStroke" Color="#14000000" />+ <SolidColorBrush x:Key="WidgetHoverOverlay" Color="#0E000000" />+ <SolidColorBrush x:Key="WidgetPressedOverlay" Color="#1C000000" />+ <SolidColorBrush x:Key="WidgetTrack" Color="#22000000" />+</ResourceDictionary>diff --git a/Design/README.md b/Design/README.mdnew file mode 100644index 0000000..5d86a8f--- /dev/null+++ b/Design/README.md@@ -0,0 +1,87 @@+# QiDock Design System++QiDock uses a lightweight, vector-driven design system implemented in pure WPF XAML without third-party UI dependencies.++---++## Design Tokens++### Layout & Dimensions++| Token | Value | Description |+| :--- | :--- | :--- |+| `DockWindowHeight` | `108 DIP` | Total height of the transparent window container |+| `DockHeadroom` | `44 DIP` | Transparent top headroom allowing unclipped icon magnification |+| `_nativeTaskbarHeight` | `66 DIP` | Base height of the floating dock container shelf |+| `DockCellSize` | `50 DIP` | Width of an individual dock application item cell (square proportion) |+| `DockCellHeight` | `52 DIP` | Height of an individual dock application item cell |+| `DockIconSize` | `32 DIP` | Prominent icon display size with balanced cell margins |+| `DockHoverScale` | `1.85x` | Peak magnification scale for the hovered dock item |+| `DockRadius` | `18 DIP` | Pill container corner radius (`CornerRadius="18"`) |+| `ControlRadius` | `12 DIP` | Standard control and button corner radius |+| `PopupRadius` | `10 DIP` | Context menu and window preview corner radius |+| `PreviewGap` | `18 DIP` | Vertical elevation gap between dock icons and thumbnail preview cards |+| `StatusDotSize` | `4 DIP / 5 DIP` | Running and active application indicator dot diameter |++### Typography++- **Font Family:** `Segoe UI` across all UI surfaces for native Windows consistency, legibility, and full Unicode/Turkish diacritic support.+- **Sizes:**+ - Body and menu items: `13 DIP`+ - Secondary labels, badges, and Jump List category headers: `12 DIP`+ - Titles and section headings: `15 DIP`++---++## Visual Materials++- **Settings Glass:** Native Desktop Acrylic (`DWMWA_SYSTEMBACKDROP_TYPE = DWMSBT_TRANSIENTWINDOW`) on Windows 11 build 22621+. `WindowChrome` provides the custom 48 DIP caption and native resize border. Text and icons remain opaque while settings, dock, and menu background brushes share the persisted surface opacity (60–100%, default 90%). No layered-window opacity or software blur is used. Unsupported systems and high-contrast mode use an opaque settings surface.+- **Compact Settings Layout:** One caption, a 148 DIP navigation column, 52 DIP general rows, and a fixed Apply footer. Remove introductory and persistent save-hint copy. Short auto-hide options form a vertical list. Uniform choice groups share aligned edges. The default 740 × 600 DIP window fits all general settings; smaller sizes scroll to the final option. Custom maximize sizing follows the current monitor work area and DPI.+- **Preference Feedback:** Enable Apply only for edited preferences or recoverable settings-load errors. Surface-opacity changes preview immediately and revert to saved preferences on close, including after pin reordering. Keep startup permission errors accessible on the disabled switch and show save errors/results in the footer.++- **Translucent Smoked Glass:** Deep translucent charcoal acrylic-style background (`#D916191F` in Dark theme, `#D9F3F4F6` in Light theme).+- **Specular Top Highlight:** 1 DIP top border highlight (`#4DFFFFFF`) simulating light reflection on glass edges.+- **Ambient Shadow:** Soft multi-layer drop shadow (`BlurRadius="24"`, `Direction="270"`, `Color="#000000"`, `Opacity="0.45"`) separating the dock from desktop wallpapers.+- **Status Indicators:**+ - Running application: Muted 4 DIP circular dot (`#94A3B8`).+ - Active (foreground) application: Bright illuminated 4 DIP dot (`#38BDF8`).+ - Alert / notification: Upper-right red badge (`#EF4444`).+- **Icons:** Vector outline paths based on the Lucide icon set (24x24 coordinate box, 1.6 DIP stroke width, rounded caps) for all context menus, tray items, and dock controls.++---++## Interaction & Motion++### Continuous Fisheye Magnification+- Pointer movement across the dock calculates a continuous parabolic/cosine wave scaling factor:+ $$S(d) = 1.0 + (S_{peak} - 1.0) \times \cos\left(\frac{\pi \cdot d}{2 \cdot R}\right)^2$$+- Magnification smoothly affects the hovered icon and immediate neighbors within a 90 DIP influence radius ($R$).+- Items scale anchored at `(0.5, 0.95)`, expanding upward into the 24 DIP transparent headroom without horizontal layout displacement or icon clipping.+- Status dots remain stationary at the dock base.++### Multi-Window Live Thumbnails+- Interactive live DWM thumbnails are created using `DwmRegisterThumbnail`.+- Thumbnails fade and scale in from 95% over 160 ms with cubic ease-out.+- The preview strip floats 18 DIPs (`PreviewGap`) above the dock to prevent overlapping magnified icons.+- Each preview card features the application icon, window title, close button, and live window preview.++### Smart Auto-Hide (IntelliHide)+- **Disabled:** Dock remains persistently visible.+- **Smart:** Dock stays visible on the desktop and behind non-overlapping windows. When an active or maximized window overlaps the bottom dock region, the dock smoothly translates down off-screen.+- **Always:** Dock remains hidden below the screen edge by default.+- **Edge Reveal:** Moving the mouse into the bottom 3 DIP trigger area instantly reveals the dock. Mouse leave triggers a 400 ms debounce before sliding down with a 220 ms cubic ease transition.++### Launch Bounce+- Clicking an application icon triggers a 420 ms damped vertical launch bounce animation (-12 DIP peak) on its translate transform to provide tactile feedback while the application opens.++---++## Project Structure++- `Theme.xaml`: Core design system definitions, standard sizing tokens, brushes, and base control templates.+- `Palettes/Dark.xaml`: Dark theme color palette and material brushes.+- `Palettes/Light.xaml`: Light theme color palette and material brushes.+- `ContextMenus.xaml`: Vector outline icon styles, Jump List headers, and menu item templates.+- `SettingsControls.xaml`: Segmented controls, toggles, radio buttons, and preferences layout.++References: [Microsoft WindowChrome](https://learn.microsoft.com/en-us/dotnet/api/system.windows.shell.windowchrome), [Microsoft DWM system backdrop types](https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_systembackdrop_type).diff --git a/Design/SettingsControls.xaml b/Design/SettingsControls.xamlnew file mode 100644index 0000000..659ef67--- /dev/null+++ b/Design/SettingsControls.xaml@@ -0,0 +1,264 @@+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="clr-namespace:QiDock.Services">+ <Thickness x:Key="SettingsPageInset">24,18</Thickness>+ <Thickness x:Key="SettingsRowInset">0,10</Thickness>+ <Style x:Key="SettingsHeading" TargetType="TextBlock">+ <Setter Property="FontSize" Value="20" />+ <Setter Property="FontWeight" Value="SemiBold" />+ <Setter Property="Margin" Value="0,0,0,12" />+ </Style>+ <Style x:Key="SettingsRow" TargetType="Border">+ <Setter Property="MinHeight" Value="52" />+ <Setter Property="Padding" Value="{StaticResource SettingsRowInset}" />+ <Setter Property="BorderThickness" Value="0,0,0,1" />+ <Setter Property="BorderBrush" Value="{DynamicResource MenuDivider}" />+ </Style>+ <Style x:Key="SettingsRowLabel" TargetType="TextBlock">+ <Setter Property="VerticalAlignment" Value="Center" />+ <Setter Property="TextWrapping" Value="Wrap" />+ </Style>+ <Style x:Key="SettingsChoiceLabel" TargetType="TextBlock">+ <Setter Property="FontWeight" Value="SemiBold" />+ <Setter Property="Margin" Value="0,0,0,10" />+ </Style>+ <Style x:Key="SettingsChoiceRow" TargetType="Border" BasedOn="{StaticResource SettingsRow}">+ <Setter Property="Padding" Value="0,14" />+ </Style>+ <Style x:Key="SettingsChoice" TargetType="RadioButton">+ <Setter Property="Foreground" Value="{DynamicResource TextSecondary}" />+ <Setter Property="Background" Value="{DynamicResource SettingsControl}" />+ <Setter Property="Padding" Value="12,9" />+ <Setter Property="MinWidth" Value="0" />+ <Setter Property="HorizontalContentAlignment" Value="Center" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Margin" Value="3,0" />+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="RadioButton">+ <Border x:Name="Surface" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}"+ BorderBrush="{DynamicResource StrokeSubtle}" BorderThickness="1" CornerRadius="7">+ <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="Center" RecognizesAccessKey="True" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True"><Setter TargetName="Surface" Property="Background" Value="{DynamicResource SettingsControlHover}" /></Trigger>+ <Trigger Property="IsChecked" Value="True">+ <Setter TargetName="Surface" Property="Background" Value="{DynamicResource SurfaceKeyboardFocus}" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter TargetName="Surface" Property="BorderBrush" Value="{DynamicResource AccentBrush}" />+ </Trigger>+ <Trigger Property="IsKeyboardFocused" Value="True"><Setter TargetName="Surface" Property="BorderBrush" Value="{DynamicResource AccentBrush}" /></Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <Style x:Key="SettingsListChoice" TargetType="RadioButton" BasedOn="{StaticResource SettingsChoice}">+ <Setter Property="HorizontalContentAlignment" Value="Left" />+ <Setter Property="Margin" Value="0,0,0,4" />+ <Setter Property="Padding" Value="12,6" />+ <Setter Property="Background" Value="{DynamicResource SurfaceSelected}" />+ </Style>+ <Style x:Key="SettingsSwitch" TargetType="CheckBox">+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="Margin" Value="16,0,0,0" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="VerticalAlignment" Value="Center" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="CheckBox">+ <Grid Width="48" Height="30">+ <Border x:Name="FocusRing" CornerRadius="15" BorderBrush="Transparent" BorderThickness="1" />+ <Border x:Name="Track" Width="42" Height="24" CornerRadius="12" Background="{DynamicResource SettingsControlHover}"+ BorderBrush="{DynamicResource TextSecondary}" BorderThickness="1" Padding="3">+ <Ellipse x:Name="Thumb" Width="16" Height="16" Fill="{DynamicResource TextSecondary}" HorizontalAlignment="Left" />+ </Border>+ </Grid>+ <ControlTemplate.Triggers>+ <Trigger Property="IsChecked" Value="True">+ <Setter TargetName="Track" Property="Background" Value="{DynamicResource AccentBrush}" />+ <Setter TargetName="Track" Property="BorderBrush" Value="{DynamicResource AccentBrush}" />+ <Setter TargetName="Thumb" Property="Fill" Value="{DynamicResource AccentText}" />+ <Setter TargetName="Thumb" Property="HorizontalAlignment" Value="Right" />+ </Trigger>+ <Trigger Property="IsKeyboardFocused" Value="True"><Setter TargetName="FocusRing" Property="BorderBrush" Value="{DynamicResource StrokeFocus}" /></Trigger>+ <Trigger Property="IsEnabled" Value="False"><Setter TargetName="Track" Property="Opacity" Value="0.4" /></Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <Style x:Key="SettingsButton" TargetType="Button">+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Padding" Value="18,10" />+ <Setter Property="Background" Value="{DynamicResource AccentBrush}" />+ <Setter Property="Foreground" Value="{DynamicResource AccentText}" />+ <Setter Property="FontWeight" Value="SemiBold" />+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="Button">+ <Border x:Name="Surface" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" CornerRadius="7"+ BorderBrush="Transparent" BorderThickness="1">+ <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True"><Setter TargetName="Surface" Property="Opacity" Value="0.88" /></Trigger>+ <Trigger Property="IsPressed" Value="True"><Setter TargetName="Surface" Property="Opacity" Value="0.72" /></Trigger>+ <Trigger Property="IsKeyboardFocused" Value="True"><Setter TargetName="Surface" Property="BorderBrush" Value="{DynamicResource TextPrimary}" /></Trigger>+ <Trigger Property="IsEnabled" Value="False"><Setter TargetName="Surface" Property="Opacity" Value="0.4" /></Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <Style x:Key="CaptionButton" TargetType="Button">+ <Setter Property="IsTabStop" Value="False" />+ <Setter Property="Width" Value="42" />+ <Setter Property="FontFamily" Value="Segoe MDL2 Assets" />+ <Setter Property="FontSize" Value="10" />+ <Setter Property="Foreground" Value="{DynamicResource TextSecondary}" />+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="Button">+ <Border x:Name="Surface" Background="{TemplateBinding Background}" CornerRadius="6" BorderBrush="Transparent" BorderThickness="1">+ <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsPressed" Value="True"><Setter TargetName="Surface" Property="Opacity" Value="0.75" /></Trigger>+ <Trigger Property="IsKeyboardFocused" Value="True"><Setter TargetName="Surface" Property="BorderBrush" Value="{DynamicResource StrokeFocus}" /></Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ <Style.Triggers>+ <Trigger Property="IsMouseOver" Value="True"><Setter Property="Background" Value="{DynamicResource SurfaceHover}" /><Setter Property="Foreground" Value="{DynamicResource TextPrimary}" /></Trigger>+ </Style.Triggers>+ </Style>+ <Style x:Key="CloseCaptionButton" TargetType="Button" BasedOn="{StaticResource CaptionButton}">+ <Style.Triggers>+ <Trigger Property="IsMouseOver" Value="True"><Setter Property="Background" Value="{DynamicResource SurfaceDanger}" /><Setter Property="Foreground" Value="{DynamicResource CaptionCloseForeground}" /></Trigger>+ </Style.Triggers>+ </Style>+ <Style x:Key="MaximizeCaptionButton" TargetType="Button" BasedOn="{StaticResource CaptionButton}">+ <Setter Property="Content" Value="" />+ <Setter Property="ToolTip" Value="{local:Loc Maximize}" />+ <Setter Property="AutomationProperties.Name" Value="{local:Loc Maximize}" />+ <Style.Triggers>+ <DataTrigger Binding="{Binding WindowState, RelativeSource={RelativeSource AncestorType=Window}}" Value="Maximized">+ <Setter Property="Content" Value="" />+ <Setter Property="ToolTip" Value="{local:Loc Restore}" />+ <Setter Property="AutomationProperties.Name" Value="{local:Loc Restore}" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ <Style x:Key="SettingsOpacitySlider" TargetType="Slider">+ <Setter Property="MinHeight" Value="28" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="Slider">+ <Grid>+ <Border Height="3" CornerRadius="2" Background="{DynamicResource MenuDivider}" VerticalAlignment="Center" />+ <Track x:Name="PART_Track" Minimum="{TemplateBinding Minimum}" Maximum="{TemplateBinding Maximum}" Value="{TemplateBinding Value}">+ <Track.DecreaseRepeatButton><RepeatButton Command="Slider.DecreaseLarge" Opacity="0" Focusable="False" /></Track.DecreaseRepeatButton>+ <Track.Thumb>+ <Thumb Width="18" Height="18">+ <Thumb.Template><ControlTemplate TargetType="Thumb"><Ellipse Fill="{DynamicResource AccentBrush}" /></ControlTemplate></Thumb.Template>+ </Thumb>+ </Track.Thumb>+ <Track.IncreaseRepeatButton><RepeatButton Command="Slider.IncreaseLarge" Opacity="0" Focusable="False" /></Track.IncreaseRepeatButton>+ </Track>+ <Border x:Name="FocusRing" BorderBrush="Transparent" BorderThickness="1" CornerRadius="6" IsHitTestVisible="False" />+ </Grid>+ <ControlTemplate.Triggers>+ <Trigger Property="IsKeyboardFocused" Value="True"><Setter TargetName="FocusRing" Property="BorderBrush" Value="{DynamicResource StrokeFocus}" /></Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <Style TargetType="TabItem">+ <Setter Property="Foreground" Value="{DynamicResource TextSecondary}" />+ <Setter Property="Padding" Value="12,10" />+ <Setter Property="Margin" Value="8,2" />+ <Setter Property="HorizontalContentAlignment" Value="Left" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="TabItem">+ <Border x:Name="Surface" Padding="{TemplateBinding Padding}" CornerRadius="7" Background="Transparent">+ <ContentPresenter ContentSource="Header" RecognizesAccessKey="True" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True"><Setter TargetName="Surface" Property="Background" Value="{DynamicResource SurfaceHover}" /></Trigger>+ <Trigger Property="IsSelected" Value="True"><Setter TargetName="Surface" Property="Background" Value="{DynamicResource SurfaceKeyboardFocus}" /><Setter Property="Foreground" Value="{DynamicResource TextPrimary}" /></Trigger>+ <Trigger Property="IsKeyboardFocused" Value="True"><Setter TargetName="Surface" Property="Background" Value="{DynamicResource SurfaceKeyboardFocus}" /></Trigger>+ <Trigger Property="IsEnabled" Value="False"><Setter TargetName="Surface" Property="Opacity" Value="0.4" /></Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <Style TargetType="TabControl">+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="TabControl">+ <Grid KeyboardNavigation.TabNavigation="Local">+ <Grid.ColumnDefinitions><ColumnDefinition Width="148" /><ColumnDefinition Width="*" /></Grid.ColumnDefinitions>+ <Border Background="{DynamicResource SettingsSidebarOverlay}" Padding="0,14">+ <TabPanel IsItemsHost="True" KeyboardNavigation.TabIndex="1" KeyboardNavigation.TabNavigation="Once" />+ </Border>+ <ContentPresenter Grid.Column="1" ContentSource="SelectedContent" KeyboardNavigation.TabIndex="2" />+ </Grid>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <Style x:Key="SettingsTextBox" TargetType="TextBox">+ <Setter Property="Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter Property="CaretBrush" Value="{DynamicResource TextPrimary}" />+ <Setter Property="Background" Value="{DynamicResource SettingsControl}" />+ <Setter Property="BorderBrush" Value="{DynamicResource MenuDivider}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="Padding" Value="10,7" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="TextBox">+ <Border x:Name="Surface" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"+ BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="7">+ <ScrollViewer x:Name="PART_ContentHost" Margin="{TemplateBinding Padding}" VerticalAlignment="Center" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsKeyboardFocused" Value="True"><Setter TargetName="Surface" Property="BorderBrush" Value="{DynamicResource StrokeFocus}" /></Trigger>+ <Trigger Property="IsMouseOver" Value="True"><Setter TargetName="Surface" Property="Background" Value="{DynamicResource SettingsControlHover}" /></Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <Style x:Key="SettingsOrderButton" TargetType="Button">+ <Setter Property="Width" Value="30" />+ <Setter Property="Height" Value="30" />+ <Setter Property="Margin" Value="4,0,0,0" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="Button">+ <Border x:Name="Surface" Background="{DynamicResource SurfaceSelected}" CornerRadius="7" BorderBrush="Transparent" BorderThickness="1">+ <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True"><Setter TargetName="Surface" Property="Background" Value="{DynamicResource SurfaceHover}" /></Trigger>+ <Trigger Property="IsKeyboardFocused" Value="True"><Setter TargetName="Surface" Property="BorderBrush" Value="{DynamicResource StrokeFocus}" /></Trigger>+ <Trigger Property="IsEnabled" Value="False"><Setter TargetName="Surface" Property="Opacity" Value="0.35" /></Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+</ResourceDictionary>diff --git a/Design/Theme.xaml b/Design/Theme.xamlnew file mode 100644index 0000000..7cade61--- /dev/null+++ b/Design/Theme.xaml@@ -0,0 +1,110 @@+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:sys="clr-namespace:System;assembly=System.Runtime">+ <ResourceDictionary.MergedDictionaries>+ <ResourceDictionary Source="Palettes/Dark.xaml" />+ </ResourceDictionary.MergedDictionaries>+ <FontFamily x:Key="InterfaceFont">Segoe UI</FontFamily>+ <sys:Double x:Key="MenuLabelWidth">286</sys:Double>+ <Thickness x:Key="MenuRowPadding">10,7</Thickness>+ <Thickness x:Key="MenuDividerInset">12,7</Thickness>+ <sys:Double x:Key="TextSizeBody">13</sys:Double>+ <sys:Double x:Key="TextSizeCaption">12</sys:Double>+ <sys:Double x:Key="DockHeadroom">44</sys:Double>+ <sys:Double x:Key="DockWindowHeight">108</sys:Double>+ <sys:Double x:Key="DockCellSize">50</sys:Double>+ <sys:Double x:Key="DockCellHeight">52</sys:Double>+ <sys:Double x:Key="DockTileSize">42</sys:Double>+ <CornerRadius x:Key="DockTileRadius">11</CornerRadius>+ <CornerRadius x:Key="DockGlassRadius">17</CornerRadius>+ <sys:Double x:Key="DockIconSize">32</sys:Double>+ <sys:Double x:Key="PreviewWidth">344</sys:Double>+ <sys:Double x:Key="PreviewHeight">236</sys:Double>+ <sys:Double x:Key="PreviewHeaderHeight">40</sys:Double>+ <sys:Double x:Key="PreviewGap">18</sys:Double>+ <sys:Double x:Key="DockHoverScale">1.85</sys:Double>+ <sys:Double x:Key="HoverDurationMs">120</sys:Double>+ <sys:Double x:Key="PreviewDurationMs">160</sys:Double>+ <Thickness x:Key="DockInset">12,0,12,6</Thickness>+ <Thickness x:Key="DockPadding">8,0,8,0</Thickness>+ <Thickness x:Key="ControlStroke">1</Thickness>+ <CornerRadius x:Key="DockRadius">18</CornerRadius>+ <CornerRadius x:Key="ControlRadius">12</CornerRadius>+ <CornerRadius x:Key="PopupRadius">10</CornerRadius>+ <Style TargetType="ToolTip">+ <Setter Property="Background" Value="{DynamicResource SurfacePopup}" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter Property="FontFamily" Value="{StaticResource InterfaceFont}" />+ <Setter Property="FontSize" Value="{DynamicResource TextSizeCaption}" />+ <Setter Property="BorderBrush" Value="{DynamicResource StrokeSubtle}" />+ <Setter Property="Padding" Value="10,6" />+ </Style>++ <Style TargetType="ScrollBar">+ <Setter Property="Width" Value="12" />+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="ScrollBar">+ <Track x:Name="PART_Track" IsDirectionReversed="True" Orientation="Vertical"+ Minimum="{TemplateBinding Minimum}" Maximum="{TemplateBinding Maximum}"+ Value="{TemplateBinding Value}" ViewportSize="{TemplateBinding ViewportSize}">+ <Track.DecreaseRepeatButton><RepeatButton Command="ScrollBar.PageUpCommand" Opacity="0" Focusable="False" /></Track.DecreaseRepeatButton>+ <Track.Thumb>+ <Thumb Margin="4,2" MinHeight="24">+ <Thumb.Style>+ <Style TargetType="Thumb">+ <Setter Property="Background" Value="{DynamicResource MenuDivider}" />+ <Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Thumb"><Border Background="{TemplateBinding Background}" CornerRadius="2" /></ControlTemplate></Setter.Value></Setter>+ <Style.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter Property="Background" Value="{DynamicResource TextSecondary}" /></Trigger></Style.Triggers>+ </Style>+ </Thumb.Style>+ </Thumb>+ </Track.Thumb>+ <Track.IncreaseRepeatButton><RepeatButton Command="ScrollBar.PageDownCommand" Opacity="0" Focusable="False" /></Track.IncreaseRepeatButton>+ </Track>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- Lucide Vector Icon Geometries (24x24 outline coordinate space) -->+ <StreamGeometry x:Key="IconOpen">M15 3h6v6 M10 14L21 3 M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6</StreamGeometry>+ <StreamGeometry x:Key="IconPin">M12 17v5 M9 10.76a2 2 0 0 1-1.11 1.79l-1.78 0.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-0.76a2 2 0 0 0-1.11-1.79l-1.78-0.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z</StreamGeometry>+ <StreamGeometry x:Key="IconUnpin">M12 17v5 M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89 M2 2l20 20 M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78 0.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11</StreamGeometry>+ <StreamGeometry x:Key="IconClose">M18 6L6 18 M6 6l12 12</StreamGeometry>+ <StreamGeometry x:Key="IconTerminate">M7.86 2h8.28L22 7.86v8.28L16.14 22H7.86L2 16.14V7.86L7.86 2z M12 8v4 M12 16h0.01</StreamGeometry>+ <StreamGeometry x:Key="IconSettings">M21 4h-7 M10 4H3 M14 2v4 M21 12h-9 M8 12H3 M12 10v4 M21 20h-5 M12 20H3 M16 18v4</StreamGeometry>+ <StreamGeometry x:Key="IconAlignLeft">M21 6H3 M15 12H3 M17 18H3</StreamGeometry>+ <StreamGeometry x:Key="IconAlignCenter">M21 6H3 M17 12H7 M19 18H5</StreamGeometry>+ <StreamGeometry x:Key="IconAlignRight">M21 6H3 M21 12H9 M21 18H7</StreamGeometry>+ <StreamGeometry x:Key="IconExit">M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4 M16 17l5-5-5-5 M21 12H9</StreamGeometry>+ <StreamGeometry x:Key="IconCheck">M20 6L9 17l-5-5</StreamGeometry>+ <StreamGeometry x:Key="IconLayout">M3 3h7v7H3z M14 3h7v7h-7z M14 14h7v7h-7z M3 14h7v7H3z</StreamGeometry>+ <StreamGeometry x:Key="IconEdit">M12 20h9 M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z</StreamGeometry>+ <StreamGeometry x:Key="IconDock">M3 17h18 M7 21h10 M12 3v9 M8 8l4 4 4-4</StreamGeometry>+ <StreamGeometry x:Key="IconMoon">M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z</StreamGeometry>+ <StreamGeometry x:Key="IconMonitor">M3 4h18v12H3z M8 20h8 M12 16v4</StreamGeometry>+ <StreamGeometry x:Key="IconSparkle">M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z M19 16l.8 2.2L22 19l-2.2.8L19 22l-.8-2.2L16 19l2.2-.8z</StreamGeometry>+ <StreamGeometry x:Key="IconPlus">M12 5v14 M5 12h14</StreamGeometry>+ <StreamGeometry x:Key="IconLeaf">M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.5 19 2c1 2 2 4.2 2 8 0 5.5-4.8 10-10 10z M2 21c0-3 1.9-5.4 5.1-6</StreamGeometry>+ <StreamGeometry x:Key="IconGauge">M12 14l4-4 M3.3 19a10 10 0 1 1 17.4 0</StreamGeometry>+ <StreamGeometry x:Key="IconSun">M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8 M12 2v2 M12 20v2 M4.9 4.9l1.4 1.4 M17.7 17.7l1.4 1.4 M2 12h2 M20 12h2 M4.9 19.1l1.4-1.4 M17.7 6.3l1.4-1.4</StreamGeometry>+ <StreamGeometry x:Key="IconChevronRight">M9 18l6-6-6-6</StreamGeometry>++ <!-- Vector Icon DataTemplate for MenuItems -->+ <DataTemplate DataType="{x:Type Geometry}">+ <Path Data="{Binding}"+ Stroke="{Binding (TextElement.Foreground), RelativeSource={RelativeSource AncestorType=ContentPresenter}}"+ StrokeThickness="1.6"+ StrokeStartLineCap="Round"+ StrokeEndLineCap="Round"+ StrokeLineJoin="Round"+ Width="14"+ Height="14"+ Stretch="Uniform"+ SnapsToDevicePixels="True"+ VerticalAlignment="Center"+ HorizontalAlignment="Center" />+ </DataTemplate>+</ResourceDictionary>diff --git a/Design/Widgets.xaml b/Design/Widgets.xamlnew file mode 100644index 0000000..65d77d4--- /dev/null+++ b/Design/Widgets.xaml@@ -0,0 +1,332 @@+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:sys="clr-namespace:System;assembly=System.Runtime">+ <!-- Widget tiles follow the dock cell height; MainWindow updates this with the taskbar layout. -->+ <sys:Double x:Key="WidgetTileHeight">44</sys:Double>+ <CornerRadius x:Key="WidgetRadius">11</CornerRadius>++ <SolidColorBrush x:Key="WidgetTileFill" Color="#14FFFFFF" />+ <SolidColorBrush x:Key="WidgetTileStroke" Color="#1CFFFFFF" />+ <SolidColorBrush x:Key="WidgetHoverOverlay" Color="#18FFFFFF" />+ <SolidColorBrush x:Key="WidgetPressedOverlay" Color="#2AFFFFFF" />+ <SolidColorBrush x:Key="WidgetAccent" Color="#FF0A84FF" />+ <SolidColorBrush x:Key="WidgetTrack" Color="#33FFFFFF" />++ <!-- A clickable tile: background comes from the Button, a hover overlay sits on top. -->+ <Style x:Key="WidgetTileButton" TargetType="Button">+ <Setter Property="Background" Value="{DynamicResource WidgetTileFill}" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter Property="BorderBrush" Value="{DynamicResource WidgetTileStroke}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="Padding" Value="10,0" />+ <Setter Property="Height" Value="{DynamicResource WidgetTileHeight}" />+ <Setter Property="Margin" Value="3,0" />+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="VerticalAlignment" Value="Center" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="Button">+ <Grid>+ <Border Background="{TemplateBinding Background}" CornerRadius="{StaticResource WidgetRadius}" />+ <Border x:Name="Overlay" Background="Transparent" BorderBrush="{TemplateBinding BorderBrush}"+ BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="{StaticResource WidgetRadius}" />+ <ContentPresenter Margin="{TemplateBinding Padding}" VerticalAlignment="Center" HorizontalAlignment="Stretch" />+ </Grid>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Overlay" Property="Background" Value="{DynamicResource WidgetHoverOverlay}" />+ </Trigger>+ <Trigger Property="IsPressed" Value="True">+ <Setter TargetName="Overlay" Property="Background" Value="{DynamicResource WidgetPressedOverlay}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- Small round icon button used inside tiles and popups. -->+ <Style x:Key="WidgetIconButton" TargetType="Button">+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter Property="Width" Value="26" />+ <Setter Property="Height" Value="24" />+ <Setter Property="Padding" Value="0" />+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="Button">+ <Border x:Name="Surface" Background="{TemplateBinding Background}" CornerRadius="8">+ <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Surface" Property="Background" Value="{DynamicResource SurfaceHover}" />+ </Trigger>+ <Trigger Property="IsPressed" Value="True">+ <Setter TargetName="Surface" Property="Background" Value="{DynamicResource SurfacePressed}" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter TargetName="Surface" Property="Opacity" Value="0.4" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- Text link inside popups. -->+ <Style x:Key="WidgetLinkButton" TargetType="Button">+ <Setter Property="Foreground" Value="{DynamicResource WidgetAccent}" />+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="FontSize" Value="12" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="Button">+ <Border x:Name="Surface" Background="Transparent" CornerRadius="6" Padding="6,2">+ <ContentPresenter />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Surface" Property="Background" Value="{DynamicResource SurfaceHover}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- Rounded pill button (Refresh, New event…). -->+ <Style x:Key="WidgetPillButton" TargetType="Button">+ <Setter Property="Background" Value="{DynamicResource WidgetTileFill}" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter Property="BorderBrush" Value="{DynamicResource WidgetTileStroke}" />+ <Setter Property="FontSize" Value="11.5" />+ <Setter Property="FontWeight" Value="SemiBold" />+ <Setter Property="Padding" Value="12,5" />+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="Button">+ <Grid>+ <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1" CornerRadius="13" />+ <Border x:Name="Overlay" Background="Transparent" CornerRadius="13" />+ <ContentPresenter Margin="{TemplateBinding Padding}" HorizontalAlignment="Center" VerticalAlignment="Center" />+ </Grid>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Overlay" Property="Background" Value="{DynamicResource WidgetHoverOverlay}" />+ </Trigger>+ <Trigger Property="IsPressed" Value="True">+ <Setter TargetName="Overlay" Property="Background" Value="{DynamicResource WidgetPressedOverlay}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- Day cell inside the calendar popup. -->+ <Style x:Key="WidgetDayButton" TargetType="Button">+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter Property="BorderBrush" Value="Transparent" />+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="Button">+ <!-- The day tile fills the whole cell (so it lines up with the weekday chips); the hover tint lies over it. -->+ <Grid Background="Transparent">+ <ContentPresenter HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />+ <Border x:Name="Surface" Background="Transparent" CornerRadius="10" Margin="2" IsHitTestVisible="False" />+ </Grid>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Surface" Property="Background" Value="{DynamicResource SurfaceHover}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <Style x:Key="WidgetPopupSurface" TargetType="Border">+ <Setter Property="Background" Value="{DynamicResource WidgetPopupFill}" />+ <Setter Property="BorderBrush" Value="{DynamicResource MenuStroke}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="CornerRadius" Value="16" />+ <Setter Property="Padding" Value="16,14" />+ <Setter Property="Margin" Value="18" />+ <Setter Property="TextElement.Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter Property="TextElement.FontFamily" Value="{StaticResource InterfaceFont}" />+ <Setter Property="Effect">+ <Setter.Value>+ <DropShadowEffect Color="#000000" BlurRadius="24" ShadowDepth="4" Direction="270" Opacity="0.42" RenderingBias="Performance" />+ </Setter.Value>+ </Setter>+ </Style>++ <!-- Text box inside widget popups (search, to-do, notes). -->+ <Style x:Key="WidgetTextBox" TargetType="TextBox">+ <Setter Property="Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter Property="CaretBrush" Value="{DynamicResource TextPrimary}" />+ <Setter Property="Background" Value="{DynamicResource WidgetTileFill}" />+ <Setter Property="BorderBrush" Value="{DynamicResource WidgetTileStroke}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="FontSize" Value="12.5" />+ <Setter Property="Padding" Value="9,6" />+ <Setter Property="VerticalContentAlignment" Value="Center" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="TextBox">+ <Border x:Name="Surface" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"+ BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="9">+ <Grid>+ <TextBlock x:Name="Hint" Text="{TemplateBinding Tag}" Foreground="{DynamicResource TextSecondary}" Margin="12,7,0,7"+ VerticalAlignment="{TemplateBinding VerticalContentAlignment}" IsHitTestVisible="False" Visibility="Collapsed" />+ <ScrollViewer x:Name="PART_ContentHost" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />+ </Grid>+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="Text" Value=""><Setter TargetName="Hint" Property="Visibility" Value="Visible" /></Trigger>+ <Trigger Property="IsKeyboardFocused" Value="True"><Setter TargetName="Surface" Property="BorderBrush" Value="{DynamicResource WidgetAccent}" /></Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- Thin slider used by the per-app volume list. -->+ <Style x:Key="WidgetSlider" TargetType="Slider">+ <Setter Property="Height" Value="18" />+ <Setter Property="Minimum" Value="0" />+ <Setter Property="Maximum" Value="100" />+ <Setter Property="IsMoveToPointEnabled" Value="True" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Focusable" Value="False" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="Slider">+ <Grid>+ <Border Height="5" CornerRadius="3" Background="{DynamicResource WidgetTrack}" VerticalAlignment="Center" />+ <Track x:Name="PART_Track" Minimum="{TemplateBinding Minimum}" Maximum="{TemplateBinding Maximum}" Value="{TemplateBinding Value}">+ <Track.DecreaseRepeatButton>+ <RepeatButton Command="Slider.DecreaseLarge" Focusable="False">+ <RepeatButton.Template>+ <ControlTemplate TargetType="RepeatButton"><Border Height="5" CornerRadius="3" Background="{DynamicResource WidgetAccent}" /></ControlTemplate>+ </RepeatButton.Template>+ </RepeatButton>+ </Track.DecreaseRepeatButton>+ <Track.Thumb>+ <Thumb Width="14" Height="14">+ <Thumb.Template><ControlTemplate TargetType="Thumb"><Ellipse Fill="White" Stroke="#33000000" StrokeThickness="1" /></ControlTemplate></Thumb.Template>+ </Thumb>+ </Track.Thumb>+ <Track.IncreaseRepeatButton>+ <RepeatButton Command="Slider.IncreaseLarge" Focusable="False">+ <RepeatButton.Template><ControlTemplate TargetType="RepeatButton"><Border Background="Transparent" /></ControlTemplate></RepeatButton.Template>+ </RepeatButton>+ </Track.IncreaseRepeatButton>+ </Track>+ </Grid>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- Profile tab under the widget bar. -->+ <Style x:Key="WidgetProfileTab" TargetType="ToggleButton">+ <Setter Property="Foreground" Value="{DynamicResource TextSecondary}" />+ <Setter Property="FontSize" Value="11" />+ <Setter Property="FontWeight" Value="SemiBold" />+ <Setter Property="Padding" Value="12,4" />+ <Setter Property="Margin" Value="3,0" />+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="ToggleButton">+ <Grid>+ <Border x:Name="Surface" Background="{DynamicResource WidgetTileFill}" BorderBrush="{DynamicResource WidgetTileStroke}" BorderThickness="1" CornerRadius="14" />+ <Border x:Name="Hover" Background="Transparent" CornerRadius="14" />+ <ContentPresenter Margin="{TemplateBinding Padding}" HorizontalAlignment="Center" VerticalAlignment="Center" />+ </Grid>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True"><Setter TargetName="Hover" Property="Background" Value="{DynamicResource WidgetHoverOverlay}" /></Trigger>+ <Trigger Property="IsChecked" Value="True">+ <Setter TargetName="Surface" Property="Background" Value="{DynamicResource WidgetAccent}" />+ <Setter TargetName="Surface" Property="BorderBrush" Value="Transparent" />+ <Setter Property="Foreground" Value="White" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- Lucide icon geometries (24x24) -->+ <StreamGeometry x:Key="IconFolder">M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-0.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2z</StreamGeometry>+ <StreamGeometry x:Key="IconSearch">M11 11m-8 0a8 8 0 1 0 16 0a8 8 0 1 0-16 0 M21 21l-4.3-4.3</StreamGeometry>+ <StreamGeometry x:Key="IconPipette">M2 22l1-1h3l9-9 M3 21v-3l9-9 M15 6l3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l0.4 0.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3z</StreamGeometry>+ <StreamGeometry x:Key="IconMixer">M4 21v-7 M4 10V3 M12 21v-9 M12 8V3 M20 21v-5 M20 12V3 M1 14h6 M9 8h6 M17 16h6</StreamGeometry>+ <StreamGeometry x:Key="IconTimer">M10 2h4 M12 14l3-3 M12 14m-8 0a8 8 0 1 0 16 0a8 8 0 1 0-16 0</StreamGeometry>+ <StreamGeometry x:Key="IconGlobe">M12 12m-10 0a10 10 0 1 0 20 0a10 10 0 1 0-20 0 M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20 M2 12h20</StreamGeometry>+ <StreamGeometry x:Key="IconListCheck">M11 18H3 M15 18l2 2 4-4 M16 12H3 M16 6H3</StreamGeometry>+ <StreamGeometry x:Key="IconInbox">M22 12h-6l-2 3h-4l-2-3H2 M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z</StreamGeometry>+ <StreamGeometry x:Key="IconTools">M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z</StreamGeometry>+ <StreamGeometry x:Key="IconTrash">M3 6h18 M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6 M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2</StreamGeometry>+ <StreamGeometry x:Key="IconCamera">M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z M12 13m-3 0a3 3 0 1 0 6 0a3 3 0 1 0-6 0</StreamGeometry>+ <StreamGeometry x:Key="IconClipboard">M9 2h6a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2</StreamGeometry>+ <StreamGeometry x:Key="IconSmile">M12 12m-10 0a10 10 0 1 0 20 0a10 10 0 1 0-20 0 M8 14s1.5 2 4 2 4-2 4-2 M9 9h0.01 M15 9h0.01</StreamGeometry>+ <StreamGeometry x:Key="IconCalculator">M6 2h12a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z M8 6h8 M16 14v4 M16 10h0.01 M12 10h0.01 M8 10h0.01 M12 14h0.01 M8 14h0.01 M12 18h0.01 M8 18h0.01</StreamGeometry>+ <StreamGeometry x:Key="IconLock">M5 11h14a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2z M7 11V7a5 5 0 0 1 10 0v4</StreamGeometry>+ <StreamGeometry x:Key="IconFile">M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z M14 2v4a2 2 0 0 0 2 2h4</StreamGeometry>+ <StreamGeometry x:Key="IconActivity">M22 12h-4l-3 9L9 3l-3 9H2</StreamGeometry>+ <StreamGeometry x:Key="IconApps">M5 3h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z M16 3h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2h-3a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z M16 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2h-3a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2z M5 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2z</StreamGeometry>+ <StreamGeometry x:Key="IconArrowDown">M12 5v14 M19 12l-7 7-7-7</StreamGeometry>+ <StreamGeometry x:Key="IconArrowUp">M12 19V5 M5 12l7-7 7 7</StreamGeometry>+ <StreamGeometry x:Key="IconArrowRight">M5 12h14 M12 5l7 7-7 7</StreamGeometry>+ <StreamGeometry x:Key="IconBattery">M16 7H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2z M22 11v2</StreamGeometry>+ <StreamGeometry x:Key="IconBell">M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9 M10.3 21a1.94 1.94 0 0 0 3.4 0</StreamGeometry>+ <StreamGeometry x:Key="IconBolt">M13 2L3 14h9l-1 8 10-12h-9l1-8z</StreamGeometry>+ <StreamGeometry x:Key="IconCoffee">M17 8h1a4 4 0 1 1 0 8h-1 M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4z M6 2v2 M10 2v2 M14 2v2</StreamGeometry>+ <StreamGeometry x:Key="IconCpu">M6 4h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z M9 9h6v6H9z M15 2v2 M15 20v2 M2 15h2 M2 9h2 M20 15h2 M20 9h2 M9 2v2 M9 20v2</StreamGeometry>+ <StreamGeometry x:Key="IconDroplet">M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-0.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z</StreamGeometry>+ <StreamGeometry x:Key="IconEye">M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z M12 12m-3 0a3 3 0 1 0 6 0a3 3 0 1 0-6 0</StreamGeometry>+ <StreamGeometry x:Key="IconHardDrive">M22 12H2 M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z M6 16h0.01 M10 16h0.01</StreamGeometry>+ <StreamGeometry x:Key="IconKeyboard">M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z M6 8h0.01 M10 8h0.01 M14 8h0.01 M18 8h0.01 M8 12h0.01 M12 12h0.01 M16 12h0.01 M7 16h10</StreamGeometry>+ <StreamGeometry x:Key="IconMaximize">M8 3H5a2 2 0 0 0-2 2v3 M21 8V5a2 2 0 0 0-2-2h-3 M3 16v3a2 2 0 0 0 2 2h3 M16 21h3a2 2 0 0 0 2-2v-3</StreamGeometry>+ <StreamGeometry x:Key="IconMemory">M6 19v-3 M10 19v-3 M14 19v-3 M18 19v-3 M8 11V9 M16 11V9 M12 11V9 M2 15h20 M4 5h16a2 2 0 0 1 2 2v1.1a2 2 0 0 0 0 3.84V17a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5.1a2 2 0 0 0 0-3.84V7a2 2 0 0 1 2-2z</StreamGeometry>+ <StreamGeometry x:Key="IconSunrise">M12 2v8 M4.93 10.93l1.41 1.41 M2 18h2 M20 18h2 M19.07 10.93l-1.41 1.41 M22 22H2 M8 6l4-4 4 4 M16 18a4 4 0 0 0-8 0</StreamGeometry>+ <StreamGeometry x:Key="IconSunset">M12 10V2 M4.93 10.93l1.41 1.41 M2 18h2 M20 18h2 M19.07 10.93l-1.41 1.41 M22 22H2 M16 6l-4 4-4-4 M16 18a4 4 0 0 0-8 0</StreamGeometry>+ <StreamGeometry x:Key="IconSwap">M21 16l-4 4-4-4 M17 20V4 M3 8l4-4 4 4 M7 4v16</StreamGeometry>+ <StreamGeometry x:Key="IconFolderOpen">M6 14l1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69 0.9l0.81 1.2a2 2 0 0 0 1.67 0.9H18a2 2 0 0 1 2 2v2</StreamGeometry>+ <StreamGeometry x:Key="IconCopy">M10 8h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H10a2 2 0 0 1-2-2V10a2 2 0 0 1 2-2z M4 16c-1.1 0-2-0.9-2-2V4c0-1.1 0.9-2 2-2h10c1.1 0 2 0.9 2 2</StreamGeometry>+ <StreamGeometry x:Key="IconRotate">M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8 M3 3v5h5</StreamGeometry>+ <StreamGeometry x:Key="IconLink">M10 13a5 5 0 0 0 7.54 0.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71 M14 11a5 5 0 0 0-7.54-0.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71</StreamGeometry>+ <StreamGeometry x:Key="IconWifi">M12 20h0.01 M2 8.82a15 15 0 0 1 20 0 M5 12.86a10 10 0 0 1 14 0 M8.5 16.43a5 5 0 0 1 7 0</StreamGeometry>+ <StreamGeometry x:Key="IconWifiOff">M12 20h0.01 M8.5 16.43a5 5 0 0 1 7 0 M5 12.86a10 10 0 0 1 5.17-2.69 M19 12.86a10 10 0 0 0-2-1.52 M2 8.82a15 15 0 0 1 4.18-2.64 M22 8.82a15 15 0 0 0-11.29-3.76 M2 2l20 20</StreamGeometry>+ <StreamGeometry x:Key="IconBluetooth">M7 7l10 10-5 5V2l5 5L7 17</StreamGeometry>+ <StreamGeometry x:Key="IconBluetoothOff">M17 17l-5 5V12l-5 5 M2 2l20 20 M14.5 9.5L17 7l-5-5v4.5</StreamGeometry>+ <StreamGeometry x:Key="IconVolume">M11 4.7a0.7 0.7 0 0 0-1.2-0.5L6.41 7.59A1.4 1.4 0 0 1 5.42 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.42a1.4 1.4 0 0 1 1 0.41l3.38 3.39A0.7 0.7 0 0 0 11 19.3z M16 9a5 5 0 0 1 0 6 M19.36 18.36a9 9 0 0 0 0-12.73</StreamGeometry>+ <StreamGeometry x:Key="IconVolumeMute">M11 4.7a0.7 0.7 0 0 0-1.2-0.5L6.41 7.59A1.4 1.4 0 0 1 5.42 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.42a1.4 1.4 0 0 1 1 0.41l3.38 3.39A0.7 0.7 0 0 0 11 19.3z M22 9l-6 6 M16 9l6 6</StreamGeometry>+ <StreamGeometry x:Key="IconChevronLeft">M15 18l-6-6 6-6</StreamGeometry>+ <StreamGeometry x:Key="IconRefresh">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</StreamGeometry>+ <StreamGeometry x:Key="IconMusic">M9 18V5l12-2v13 M9 18a3 3 0 1 1-6 0 3 3 0 0 1 6 0z M21 16a3 3 0 1 1-6 0 3 3 0 0 1 6 0z</StreamGeometry>+ <StreamGeometry x:Key="IconMic">M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z M19 10v2a7 7 0 0 1-14 0v-2 M12 19v3</StreamGeometry>+ <StreamGeometry x:Key="GlyphStop">M6 6h12v12H6z</StreamGeometry>+ <StreamGeometry x:Key="IconMapPin">M20 10c0 5-5.5 10.2-7.4 11.8a1 1 0 0 1-1.2 0C9.5 20.2 4 15 4 10a8 8 0 0 1 16 0 M12 10m-3 0a3 3 0 1 0 6 0a3 3 0 1 0-6 0</StreamGeometry>+ <StreamGeometry x:Key="IconCalendar">M8 2v4 M16 2v4 M3 10h18 M5 4h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z</StreamGeometry>+ <!-- Filled glyphs -->+ <StreamGeometry x:Key="GlyphPlay">M7 4.5v15a1 1 0 0 0 1.5 0.86l12.5-7.5a1 1 0 0 0 0-1.72L8.5 3.64A1 1 0 0 0 7 4.5z</StreamGeometry>+ <StreamGeometry x:Key="GlyphPause">M6 4h4v16H6z M14 4h4v16h-4z</StreamGeometry>+ <StreamGeometry x:Key="GlyphPrevious">M19 5.5v13a1 1 0 0 1-1.55 0.83L8 12.83a1 1 0 0 1 0-1.66l9.45-6.5A1 1 0 0 1 19 5.5z M5 5h2.4v14H5z</StreamGeometry>+ <StreamGeometry x:Key="GlyphNext">M5 5.5v13a1 1 0 0 0 1.55 0.83L16 12.83a1 1 0 0 0 0-1.66L6.55 4.67A1 1 0 0 0 5 5.5z M16.6 5H19v14h-2.4z</StreamGeometry>+ <StreamGeometry x:Key="GlyphBolt">M13 2L4 14h7l-1 8 9-12h-7z</StreamGeometry>+</ResourceDictionary>diff --git a/DesktopWidgets/DeskCatalog.cs b/DesktopWidgets/DeskCatalog.csnew file mode 100644index 0000000..7383a4f--- /dev/null+++ b/DesktopWidgets/DeskCatalog.cs@@ -0,0 +1,88 @@+using QiDock.DesktopWidgets.Kinds;+using static QiDock.DesktopWidgets.DeskSize;++namespace QiDock.DesktopWidgets;++/// <summary>Every desktop widget kind with its names, sizes and factory.</summary>+internal static class DeskCatalog+{+ public static readonly IReadOnlyList<DeskKind> All =+ [+ new("clock", DeskCategory.Time, "Dijital saat", "Digital clock", "Saat, gün ve tarih; orta boyda hava durumu da var.", "Time, weekday and date; the medium size adds the weather.",+ [Mini, Small, Strip, Medium], Small, () => new DigitalClockWidget()),+ new("analog", DeskCategory.Time, "Analog saat", "Analog clock", "Akrep, yelkovan ve saniye; açık ya da koyu kadran.", "Hour, minute and second hands; light or dark face.",+ [Small, Large], Small, () => new AnalogClockWidget()),+ new("flip", DeskCategory.Time, "Rakam kartları", "Flip clock", "Saat ve dakika büyük kartlarda.", "Hours and minutes on large tiles.",+ [Strip, Medium], Strip, () => new FlipClockWidget()),+ new("date", DeskCategory.Time, "Tarih", "Date", "Takvim yaprağı gibi bugünün tarihi.", "Today's date like a calendar page.",+ [Mini, Small, Strip], Small, () => new DateWidget()),+ new("calendar", DeskCategory.Time, "Takvim", "Calendar", "Bu hafta, ay görünümü ve iCal takviminizdeki etkinlikler.", "This week, the month and events from your iCal calendar.",+ [Small, Strip, Medium, Large], Medium, () => new CalendarDeskWidget()),+ new("progress", DeskCategory.Time, "Yıl ilerlemesi", "Year progress", "Yılın, ayın, haftanın ya da günün ne kadarı geçti.", "How much of the year, month, week or day has passed.",+ [Small, Strip, Medium], Strip, () => new ProgressWidget()),+ new("worldclock", DeskCategory.Time, "Dünya saati", "World clock", "Üç şehrin saati ve farkı.", "Three cities' time and offset.",+ [Small, Strip, Medium], Strip, () => new WorldClockDeskWidget()),+ new("timer", DeskCategory.Time, "Zamanlayıcı", "Timer", "Geri sayım; süre dolunca haber verir.", "Countdown that tells you when time is up.",+ [Mini, Small, Strip], Strip, () => new TimerWidget()),+ new("stopwatch", DeskCategory.Time, "Kronometre", "Stopwatch", "Saniyenin onda biri hassasiyetinde.", "Down to a tenth of a second.",+ [Mini, Strip], Strip, () => new StopwatchWidget()),++ new("weather", DeskCategory.Weather, "Hava durumu", "Weather", "Şu an, saatlik ve günlük tahmin (Ayarlar'daki şehir).", "Now, hourly and daily forecast (city from Settings).",+ [Mini, Small, Strip, Medium, Large], Medium, () => new WeatherDeskWidget()),+ new("sun", DeskCategory.Weather, "Gün doğumu ve batımı", "Sunrise & sunset", "Güneşin gökyüzündeki yeri ve gün uzunluğu.", "The sun's place in the sky and day length.",+ [Small, Strip], Strip, () => new SunWidget()),+ new("wind", DeskCategory.Weather, "Rüzgâr", "Wind", "Rüzgâr hızı, hamle ve yön pusulası.", "Wind speed, gusts and a direction compass.",+ [Small, Strip], Strip, () => new WindWidget()),++ new("cpu", DeskCategory.System, "İşlemci", "CPU", "İşlemci yükü halka ya da canlı grafik olarak.", "CPU load as a ring or a live graph.",+ [Mini, Small, Strip, Medium], Strip, () => new MetricWidget(Metric.Cpu)),+ new("ram", DeskCategory.System, "Bellek", "Memory", "Kullanılan RAM.", "Memory in use.",+ [Mini, Small, Strip], Mini, () => new MetricWidget(Metric.Ram)),+ new("disk", DeskCategory.System, "Disk", "Disk", "Sistem diskinin doluluğu ve boş alan.", "System drive usage and free space.",+ [Mini, Small, Strip], Mini, () => new MetricWidget(Metric.Disk)),+ new("battery", DeskCategory.System, "Pil", "Battery", "Pil yüzdesi, şarj durumu ve kalan süre.", "Battery level, charging and time left.",+ [Mini, Small, Strip], Mini, () => new MetricWidget(Metric.Battery)),+ new("network", DeskCategory.System, "Ağ hızı", "Network", "İndirme ve yükleme hızı, canlı grafik.", "Download and upload speed with a live graph.",+ [Mini, Strip, Medium], Strip, () => new NetworkWidget()),++ new("music", DeskCategory.Media, "Müzik", "Music", "Çalan şarkı, kapak ve kontroller (Spotify, tarayıcı…).", "Now playing, artwork and controls (Spotify, browsers…).",+ [Mini, Small, Strip, Medium, Large], Strip, () => new MusicWidget()),+ new("sound", DeskCategory.Media, "Ses", "Sound", "Ses düzeyi ve sessize alma.", "Volume level and mute.",+ [Mini, Strip], Strip, () => new SoundWidget()),++ new("todo", DeskCategory.Productivity, "Yapılacaklar", "To-do", "Üst çubuktaki listeyle aynı; işaretle, ekle, sil.", "Same list as the bar; check, add, remove.",+ [Strip, Small, Medium, Large], Small, () => new TodoDeskWidget()),+ new("notes", DeskCategory.Productivity, "Not", "Note", "Yapışkan not; yazdığınız saklanır.", "Sticky note; your text is kept.",+ [Small, Medium, Large], Small, () => new NotesWidget()),+ new("focus", DeskCategory.Productivity, "Odak (Pomodoro)", "Focus (Pomodoro)", "Üst çubuktaki odak sayacıyla aynı; 5 dk mola, 4 turda uzun mola.", "Same timer as the bar; 5 min breaks, a long one every 4 rounds.",+ [Small, Strip], Strip, () => new FocusDeskWidget()),+ new("reminder", DeskCategory.Productivity, "Hatırlatıcı", "Reminder", "Su iç, mola ver, gözlerini dinlendir… belirli aralıklarla.", "Drink water, take a break, rest your eyes… on a schedule.",+ [Small, Strip], Strip, () => new ReminderWidget()),++ new("claude", DeskCategory.Ai, "Claude", "Claude", "Claude kullanım sınırları (oturum ve haftalık) ve ne zaman yenileneceği; simgesi uygulamayı açar.", "Claude usage limits (session and weekly) and when they reset; the icon opens the app.",+ [Mini, Small, Strip, Medium], Strip, () => new AiAssistantWidget(AiAssistant.Claude)),+ new("codex", DeskCategory.Ai, "Codex", "Codex", "Codex (ChatGPT) kullanım sınırları ve ne zaman yenileneceği; simgesi uygulamayı açar.", "Codex (ChatGPT) usage limits and when they reset; the icon opens the app.",+ [Mini, Small, Strip, Medium], Strip, () => new AiAssistantWidget(AiAssistant.Codex)),+ new("gemini", DeskCategory.Ai, "Gemini", "Gemini", "Gemini uygulamasını tek tıkla açar.", "Opens the Gemini app in one click.",+ [Mini, Small, Strip, Medium], Strip, () => new AiAssistantWidget(AiAssistant.Gemini)),++ new("apps", DeskCategory.Tools, "Uygulamalar", "Apps", "Sık kullandığınız uygulamalar tek tıkla.", "Your favourite apps one click away.",+ [Mini, Small, Strip, Medium, Large], Small, () => new AppsWidget()),+ new("actions", DeskCategory.Tools, "Hızlı eylemler", "Quick actions", "Ekran alıntısı, pano, emoji, hesap makinesi, kilit…", "Screenshot, clipboard, emoji, calculator, lock…",+ [Mini, Small, Strip, Medium], Strip, () => new ActionsWidget()),+ new("toggles", DeskCategory.Tools, "Hızlı ayarlar", "Quick settings", "Wi-Fi, Bluetooth, gece ışığı, bildirimler.", "Wi-Fi, Bluetooth, night light, notifications.",+ [Small, Strip], Strip, () => new TogglesWidget()),+ new("websearch", DeskCategory.Tools, "Web'de ara", "Web search", "Yazıp Enter'a basın; varsayılan tarayıcıda açılır.", "Type and press Enter; opens in your browser.",+ [Strip], Strip, () => new SearchBoxWidget(true)),+ new("filesearch", DeskCategory.Tools, "Windows’ta ara", "Windows search", "Kullanıcı klasörünüzde Windows aramasıyla.", "Windows search in your user folder.",+ [Strip], Strip, () => new SearchBoxWidget(false)),+ new("emoji", DeskCategory.Tools, "Emoji", "Emoji", "Sık kullanılan emojiler; tıklayınca kopyalanır.", "Favourite emoji; click to copy.",+ [Small, Strip], Strip, () => new EmojiWidget()),+ new("colors", DeskCategory.Tools, "Renkler", "Colors", "Ekrandan renk seçin; tıklayınca kodu kopyalanır.", "Pick colors on screen; click to copy the code.",+ [Small, Strip], Small, () => new ColorsDeskWidget()),+ new("currency", DeskCategory.Tools, "Döviz çevirici", "Currency", "Avrupa Merkez Bankası kurlarıyla çeviri.", "Conversion with European Central Bank rates.",+ [Small, Strip], Strip, () => new CurrencyWidget()),+ ];++ public static DeskKind? Find(string id) => All.FirstOrDefault(k => k.Id == id);+}diff --git a/DesktopWidgets/DeskCore.cs b/DesktopWidgets/DeskCore.csnew file mode 100644index 0000000..42aaf41--- /dev/null+++ b/DesktopWidgets/DeskCore.cs@@ -0,0 +1,219 @@+using System.IO;+using System.Text.Json;+using System.Text.Json.Serialization;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.DesktopWidgets;++/// <summary>Desktop widget sizes on a 164 DIP grid with 16 DIP gaps (two smalls side by side = one medium).</summary>+public enum DeskSize { Mini, Small, Strip, Medium, Large }++/// <summary>One widget placed on the desktop.</summary>+public sealed class DeskItem+{+ public string Id { get; set; } = Guid.NewGuid().ToString("N");+ public string Kind { get; set; } = "";+ public DeskSize Size { get; set; } = DeskSize.Small;+ public double X { get; set; }+ public double Y { get; set; }+ public Dictionary<string, string> Options { get; set; } = new();+}++public sealed class DeskLayout+{+ public bool Initialized { get; set; }+ public List<DeskItem> Items { get; set; } = [];+}++/// <summary>Desktop widgets live in their own file next to settings.json so moving one never rewrites the preferences.</summary>+internal static class DeskStore+{+ private static readonly JsonSerializerOptions Json = new()+ {+ WriteIndented = true,+ Converters = { new JsonStringEnumConverter() }+ };++ private static string FilePath => System.IO.Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock", "desktop-widgets.json");++ public static DeskLayout Load()+ {+ try+ {+ if (!File.Exists(FilePath)) return new DeskLayout();+ return JsonSerializer.Deserialize<DeskLayout>(File.ReadAllText(FilePath), Json) ?? new DeskLayout();+ }+ catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException)+ {+ System.Diagnostics.Trace.TraceWarning("Desktop widgets could not be read: {0}", ex.Message);+ return new DeskLayout();+ }+ }++ public static void Save(DeskLayout layout)+ {+ try+ {+ Directory.CreateDirectory(System.IO.Path.GetDirectoryName(FilePath)!);+ var temp = FilePath + ".tmp";+ File.WriteAllText(temp, JsonSerializer.Serialize(layout, Json));+ File.Move(temp, FilePath, true);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ System.Diagnostics.Trace.TraceWarning("Desktop widgets could not be saved: {0}", ex.Message);+ }+ }+}++internal static class Desk+{+ public const double Unit = 164;+ public const double Gap = 16;+ public const double StripHeight = 74;++ public static Size Dimensions(DeskSize size) => size switch+ {+ DeskSize.Mini => new Size(Unit, StripHeight),+ DeskSize.Small => new Size(Unit, Unit),+ DeskSize.Strip => new Size(Unit * 2 + Gap, StripHeight),+ DeskSize.Medium => new Size(Unit * 2 + Gap, Unit),+ _ => new Size(Unit * 2 + Gap, Unit * 2 + Gap)+ };++ /// <summary>Turkish or English text, following the app language.</summary>+ public static string L(string turkish, string english) =>+ UiText.Current.Language == AppLanguage.Turkish ? turkish : english;++ public static string SizeName(DeskSize size) => size switch+ {+ DeskSize.Mini => L("Mini", "Mini"),+ DeskSize.Small => L("Küçük", "Small"),+ DeskSize.Strip => L("Şerit", "Strip"),+ DeskSize.Medium => L("Orta", "Medium"),+ _ => L("Büyük", "Large")+ };++ public static System.Globalization.CultureInfo Culture =>+ System.Globalization.CultureInfo.GetCultureInfo(UiText.Current.Language == AppLanguage.Turkish ? "tr-TR" : "en-US");++ public static Thickness Padding(DeskSize size) =>+ size is DeskSize.Mini or DeskSize.Strip ? new Thickness(14, 10, 14, 10) : new Thickness(16);++ /// <summary>A sound and the top-of-screen message (timer done, reminder due).</summary>+ public static void Notify(string iconKey, string text)+ {+ System.Media.SystemSounds.Asterisk.Play();+ QiDock.Widgets.Ui.ShowHud(iconKey, text);+ }++ /// <summary>Windows key shortcuts (Win+V clipboard history, Win+. emoji panel).</summary>+ public static void SendWinKey(byte key)+ {+ keybd_event(0x5B, 0, 0, 0);+ keybd_event(key, 0, 0, 0);+ keybd_event(key, 0, 2, 0);+ keybd_event(0x5B, 0, 2, 0);+ }++ [System.Runtime.InteropServices.DllImport("user32.dll")]+ private static extern void keybd_event(byte key, byte scan, int flags, int extra);++ [System.Runtime.InteropServices.DllImport("user32.dll")]+ [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]+ public static extern bool LockWorkStation();++ /// <summary>Shared access to the widget settings (city, calendar, to-dos, colors) kept in settings.json.</summary>+ public static Func<WidgetSettings> Settings { get; set; } = () => new WidgetSettings();+ public static Action<Func<WidgetSettings, WidgetSettings>> UpdateSettings { get; set; } = _ => { };+ public static Func<IReadOnlyList<string>> DockApps { get; set; } = () => [];+}++/// <summary>Context a widget gets from its desktop window.</summary>+public interface IDeskHost+{+ DeskItem Item { get; }+ bool IsLive { get; }+ void Save();+ void Rebuild();+ void FocusInput(IInputElement element);+}++/// <summary>+/// A desktop widget: builds its view for the chosen size and refreshes it while visible. Data that+/// several widgets share (weather, CPU, media) comes from hubs that only run while someone listens.+/// </summary>+public abstract class DeskWidget : IDisposable+{+ public IDeskHost Host { get; internal set; } = null!;+ public DeskSize Size => Host.Item.Size;+ protected bool Wide => Size is DeskSize.Strip or DeskSize.Medium or DeskSize.Large;++ /// <summary>The view for the current size; called again when the size changes.</summary>+ public abstract FrameworkElement Build();++ /// <summary>How often <see cref="Tick"/> runs while visible (null: only on data events).</summary>+ public virtual TimeSpan? Interval => null;+ public virtual void Tick() { }++ private bool _attached;++ /// <summary>Subscribe to hubs (visible) / unsubscribe (covered by windows or removed). Safe to call twice.</summary>+ public void Attach()+ {+ if (_attached) return;+ _attached = true;+ OnAttach();+ }++ public void Detach()+ {+ if (!_attached) return;+ _attached = false;+ OnDetach();+ }++ protected virtual void OnAttach() { }+ protected virtual void OnDetach() { }++ /// <summary>The shared widget settings changed (to-dos edited in the bar and so on).</summary>+ public virtual void SettingsChanged() { }++ /// <summary>Widget-specific entries for the right-click menu.</summary>+ public virtual void AddMenuItems(ItemsControl menu) { }++ protected string? Option(string key) => Host.Item.Options.TryGetValue(key, out var value) ? value : null;++ protected int OptionInt(string key, int fallback) => int.TryParse(Option(key), out var value) ? value : fallback;++ protected void SetOption(string key, string? value)+ {+ if (value is null) Host.Item.Options.Remove(key);+ else Host.Item.Options[key] = value;+ Host.Save();+ }++ protected static MenuItem MenuEntry(string header, Action click, bool? isChecked = null)+ {+ var item = new MenuItem { Header = header.Replace("_", "__") };+ if (isChecked is { } value) item.IsChecked = value;+ item.Click += (_, _) => click();+ return item;+ }++ public virtual void Dispose() => Detach();+}++public enum DeskCategory { Time, Weather, System, Media, Productivity, Ai, Tools }++public sealed record DeskKind(string Id, DeskCategory Category, string NameTr, string NameEn, string DescriptionTr, string DescriptionEn,+ DeskSize[] Sizes, DeskSize DefaultSize, Func<DeskWidget> Create)+{+ public string Name => Desk.L(NameTr, NameEn);+ public string Description => Desk.L(DescriptionTr, DescriptionEn);+}diff --git a/DesktopWidgets/DeskGallery.cs b/DesktopWidgets/DeskGallery.csnew file mode 100644index 0000000..de09385--- /dev/null+++ b/DesktopWidgets/DeskGallery.cs@@ -0,0 +1,281 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Interop;+using System.Windows.Media;+using System.Windows.Shell;+using System.Windows.Threading;++namespace QiDock.DesktopWidgets;++/// <summary>+/// Gallery of desktop widgets with live previews; pick a size and add it to the desktop.+/// It is a plain (not see-through) window with Windows' own rounded corners: a see-through window this large is+/// drawn whole on every frame, which in low-memory mode (drawing on the processor) froze scrolling to a few frames a+/// second. Cards are made a few at a time after the window shows, and only the previews in view tick.+/// </summary>+internal sealed class DeskGallery : Window+{+ private readonly DeskWidgetManager _manager;+ private readonly WrapPanel _cards = new() { Margin = new Thickness(18, 4, 6, 18) };+ private readonly StackPanel _chips = new() { Orientation = Orientation.Horizontal, Margin = new Thickness(24, 0, 24, 10) };+ private readonly List<PreviewHost> _previews = [];+ private readonly DispatcherTimer _tick = new(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(1) };+ private DeskCategory? _category;++ public DeskGallery(DeskWidgetManager manager)+ {+ _manager = manager;+ Title = Desk.L("Widget galerisi", "Widget gallery");+ Width = 1080;+ Height = Math.Min(960, SystemParameters.WorkArea.Height - 80);+ WindowStyle = WindowStyle.None;+ ResizeMode = ResizeMode.CanResize;+ Background = Ui("#FF18181B");+ // No title bar, but Windows still draws the frame: rounded corners, a thin border and resizing at the edges.+ WindowChrome.SetWindowChrome(this, new WindowChrome { CaptionHeight = 0, ResizeBorderThickness = new Thickness(6), GlassFrameThickness = new Thickness(0), CornerRadius = new CornerRadius(0), UseAeroCaptionButtons = false });+ SourceInitialized += (_, _) => RoundCorners();+ WindowStartupLocation = WindowStartupLocation.CenterScreen;+ SetResourceReference(FontFamilyProperty, "InterfaceFont");+ TextOptions.SetTextFormattingMode(this, TextFormattingMode.Ideal);++ var title = DeskUi.T(Title, 22, FontWeights.SemiBold);+ var subtitle = DeskUi.T(Desk.L(+ "Bir widget ve boyut seçip masaüstüne ekleyin. Masaüstünde sürükleyerek taşıyın, sağ tıklayarak boyutunu değiştirin ya da kaldırın.",+ "Pick a widget and a size to add it to the desktop. Drag widgets to move them; right-click to resize or remove."), 12.5, brush: DeskUi.Secondary);+ subtitle.TextWrapping = TextWrapping.Wrap;+ subtitle.Margin = new Thickness(0, 4, 0, 0);+ var close = DeskButton.Round("IconClose", Close, 32, DeskUi.Inset, outline: true, glyph: 13);+ var header = DeskUi.Grid(columns: "*,Auto");+ header.Margin = new Thickness(24, 20, 18, 14);+ header.Children.Add(DeskUi.Column(title, subtitle));+ header.Children.Add(DeskUi.At(close, 0, 1));+ close.VerticalAlignment = VerticalAlignment.Top;+ header.Background = Brushes.Transparent;+ header.MouseLeftButtonDown += (_, e) =>+ {+ if (e.ButtonState == MouseButtonState.Pressed) DragMove();+ };++ AddChip(null, Desk.L("Tümü", "All"));+ AddChip(DeskCategory.Time, Desk.L("Saat ve tarih", "Time & date"));+ AddChip(DeskCategory.Weather, Desk.L("Hava", "Weather"));+ AddChip(DeskCategory.System, Desk.L("Sistem", "System"));+ AddChip(DeskCategory.Media, Desk.L("Medya", "Media"));+ AddChip(DeskCategory.Productivity, Desk.L("Verimlilik", "Productivity"));+ AddChip(DeskCategory.Ai, Desk.L("Yapay zekâ", "AI"));+ AddChip(DeskCategory.Tools, Desk.L("Araçlar", "Tools"));++ var scroll = _scroll = new ScrollViewer { Content = _cards, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled };+ var layout = DeskUi.Grid("Auto,Auto,*");+ layout.Children.Add(header);+ layout.Children.Add(DeskUi.At(_chips, 1));+ layout.Children.Add(DeskUi.At(scroll, 2));++ Content = layout;+ UseLayoutRounding = true;+ KeyDown += (_, e) =>+ {+ if (e.Key == Key.Escape) Close();+ };+ // Only the previews in view move their hands and numbers; the rest wait until they are scrolled to.+ _tick.Tick += (_, _) =>+ {+ foreach (var preview in _previews)+ if (InView(preview.Card)) preview.Widget.Tick();+ };+ Loaded += (_, _) => Fill();+ Closed += (_, _) => Clear();+ }++ private static Brush Ui(string hex) => QiDock.Widgets.Ui.Solid(hex);++ private ScrollViewer? _scroll;+ private int _fillVersion;++ private bool InView(FrameworkElement card)+ {+ if (_scroll is null || !card.IsVisible || !card.IsDescendantOf(_scroll)) return false;+ var box = card.TransformToAncestor(_scroll).TransformBounds(new Rect(card.RenderSize));+ return box.Bottom > 0 && box.Top < _scroll.ViewportHeight;+ }++ /// <summary>Windows 11 rounds the window's corners and draws a dark hairline around it.</summary>+ private void RoundCorners()+ {+ var handle = new WindowInteropHelper(this).Handle;+ var round = 2; // DWMWCP_ROUND+ DwmSetWindowAttribute(handle, 33 /* DWMWA_WINDOW_CORNER_PREFERENCE */, ref round, sizeof(int));+ var border = 0x003A3A3F; // COLORREF 0x00BBGGRR+ DwmSetWindowAttribute(handle, 34 /* DWMWA_BORDER_COLOR */, ref border, sizeof(int));+ var dark = 1;+ DwmSetWindowAttribute(handle, 20 /* DWMWA_USE_IMMERSIVE_DARK_MODE */, ref dark, sizeof(int));+ }++ [DllImport("dwmapi.dll")]+ private static extern int DwmSetWindowAttribute(nint window, int attribute, ref int value, int size);++ private void AddChip(DeskCategory? category, string text)+ {+ var label = DeskUi.T(text, 12.5, FontWeights.SemiBold);+ label.Margin = new Thickness(14, 0, 14, 0);+ var chip = new DeskButton(label, () =>+ {+ _category = category;+ Fill();+ }, background: DeskUi.Inset, radius: 15) { Height = 30, Margin = new Thickness(0, 0, 8, 0), Tag = category };+ _chips.Children.Add(chip);+ }++ public void SettingsChanged()+ {+ foreach (var preview in _previews) preview.Widget.SettingsChanged();+ }++ /// <summary>The first row of cards shows at once; the others follow a few at a time, so the window never hangs.</summary>+ private void Fill()+ {+ Clear();+ var version = ++_fillVersion;+ foreach (DeskButton chip in _chips.Children)+ chip.Background = Equals(chip.Tag, _category) ? DeskUi.Blue : DeskUi.Inset;+ var kinds = new Queue<DeskKind>(DeskCatalog.All.Where(k => _category is null || k.Category == _category));+ void Next(int count)+ {+ if (version != _fillVersion) return;+ for (var i = 0; i < count && kinds.Count > 0; i++) _cards.Children.Add(Card(kinds.Dequeue()));+ if (kinds.Count > 0) Dispatcher.BeginInvoke(() => Next(3), DispatcherPriority.Background);+ }+ Next(6);+ _tick.Start();+ }++ private void Clear()+ {+ _fillVersion++; // cards still queued from an earlier fill are no longer made+ _tick.Stop();+ foreach (var preview in _previews) preview.Dispose();+ _previews.Clear();+ _cards.Children.Clear();+ }++ private FrameworkElement Card(DeskKind kind)+ {+ var selected = kind.DefaultSize;+ var previewBox = new Border { Height = 210, Margin = new Thickness(0, 0, 0, 12) };+ PreviewHost? preview = null;++ void ShowPreview()+ {+ if (preview is not null)+ {+ _previews.Remove(preview);+ preview.Dispose();+ }+ preview = new PreviewHost(kind, selected);+ _previews.Add(preview);+ previewBox.Child = new Viewbox { Child = preview.Card, Stretch = Stretch.Uniform, StretchDirection = StretchDirection.DownOnly, MaxHeight = 210, MaxWidth = 330 };+ }++ var sizes = new WrapPanel { Margin = new Thickness(0, 10, 0, 0) };+ void PaintSizes()+ {+ foreach (DeskButton chip in sizes.Children) chip.Background = Equals(chip.Tag, selected) ? DeskUi.Blue : DeskUi.Inset;+ }+ foreach (var size in kind.Sizes)+ {+ var label = DeskUi.T(Desk.SizeName(size), 11.5, FontWeights.SemiBold);+ label.Margin = new Thickness(10, 0, 10, 0);+ var chosen = size;+ var chip = new DeskButton(label, () =>+ {+ selected = chosen;+ PaintSizes();+ ShowPreview();+ }, background: DeskUi.Inset, radius: 12) { Height = 26, Margin = new Thickness(0, 0, 6, 6), Tag = size };+ sizes.Children.Add(chip);+ }+ PaintSizes();+ ShowPreview();++ var name = DeskUi.T(kind.Name, 15, FontWeights.SemiBold);+ var description = DeskUi.T(kind.Description, 12, brush: DeskUi.Secondary);+ description.TextWrapping = TextWrapping.Wrap;+ description.Height = 34;+ description.Margin = new Thickness(0, 3, 0, 0);+ var addLabel = DeskUi.Row(DeskUi.Icon("IconPlus", 13, Brushes.White), DeskUi.Margin(DeskUi.T(Desk.L("Ekle", "Add"), 12.5, FontWeights.SemiBold, Brushes.White), 6));+ addLabel.Margin = new Thickness(14, 0, 16, 0);+ var add = new DeskButton(addLabel, () =>+ {+ _manager.Add(kind, selected);+ Activate();+ }, background: DeskUi.Blue, radius: 15) { Height = 30, HorizontalAlignment = HorizontalAlignment.Left, Margin = new Thickness(0, 4, 0, 0) };++ var stack = new StackPanel();+ stack.Children.Add(previewBox);+ stack.Children.Add(name);+ stack.Children.Add(description);+ stack.Children.Add(sizes);+ stack.Children.Add(add);+ return new Border+ {+ Width = 326,+ Margin = new Thickness(6),+ Padding = new Thickness(16),+ CornerRadius = new CornerRadius(18),+ Background = Ui("#0DFFFFFF"),+ BorderBrush = Ui("#14FFFFFF"),+ BorderThickness = new Thickness(1),+ Child = stack+ };+ }++ /// <summary>A widget rendered in the gallery: same view as on the desktop, never interactive.</summary>+ private sealed class PreviewHost : IDeskHost, IDisposable+ {+ private readonly Border _card;++ public PreviewHost(DeskKind kind, DeskSize size)+ {+ Item = new DeskItem { Kind = kind.Id, Size = size };+ Widget = kind.Create();+ Widget.Host = this;+ var dims = Desk.Dimensions(size);+ _card = new Border+ {+ Width = dims.Width,+ Height = dims.Height,+ CornerRadius = new CornerRadius(24),+ Background = DeskUi.CardFill,+ BorderBrush = DeskUi.CardStroke,+ BorderThickness = new Thickness(1),+ Padding = Desk.Padding(size),+ IsHitTestVisible = false+ };+ _card.SizeChanged += (_, e) => _card.Clip = new RectangleGeometry(new Rect(e.NewSize), 24, 24);+ _card.Child = Widget.Build();+ Widget.Attach();+ Widget.Tick();+ }++ public DeskItem Item { get; }+ public DeskWidget Widget { get; }+ public FrameworkElement Card => _card;+ public bool IsLive => true;+ public void Save() { }+ public void FocusInput(IInputElement element) { }++ public void Rebuild()+ {+ _card.Child = Widget.Build();+ Widget.Tick();+ }++ public void Dispose()+ {+ Widget.Detach();+ Widget.Dispose();+ }+ }+}diff --git a/DesktopWidgets/DeskHubs.cs b/DesktopWidgets/DeskHubs.csnew file mode 100644index 0000000..b8e036a--- /dev/null+++ b/DesktopWidgets/DeskHubs.cs@@ -0,0 +1,530 @@+using System.Globalization;+using System.IO;+using System.Net.NetworkInformation;+using System.Runtime.InteropServices;+using System.Text.Json;+using System.Windows.Media;+using System.Windows.Media.Imaging;+using System.Windows.Threading;+using QiDock.Services.Widgets;+using QiDock.Widgets;+using Windows.Media.Control;++namespace QiDock.DesktopWidgets;++/// <summary>Counts listeners; the source only runs while at least one visible widget listens.</summary>+internal abstract class HubBase+{+ private int _listeners;+ public event Action? Updated;++ public void Subscribe(Action handler)+ {+ Updated += handler;+ if (++_listeners == 1) Activate();+ }++ public void Unsubscribe(Action handler)+ {+ Updated -= handler;+ if (_listeners > 0 && --_listeners == 0) Deactivate();+ }++ protected void Raise()+ {+ try { Updated?.Invoke(); }+ catch (Exception ex) when (ex is InvalidOperationException or NullReferenceException or ArgumentException or FormatException)+ {+ // One broken widget must not stop the others from updating.+ System.Diagnostics.Trace.TraceWarning("Desktop widget update failed: {0}", ex);+ }+ }+ protected abstract void Activate();+ protected abstract void Deactivate();+}++/// <summary>CPU, memory, network, disk and battery, sampled once a second while needed.</summary>+internal sealed class SystemHub : HubBase+{+ public static readonly SystemHub Instance = new();+ private const int HistoryLength = 40;+ private readonly DispatcherTimer _timer = new(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(1) };+ private ulong _lastIdle, _lastTotal;+ private long _lastDown = -1, _lastUp = -1;+ private DateTime _lastNet;+ private int _ticks;++ public double Cpu { get; private set; }+ public List<double> CpuHistory { get; } = [];+ public double RamPercent { get; private set; }+ public ulong RamUsed { get; private set; }+ public ulong RamTotal { get; private set; }+ public double Down { get; private set; }+ public double Up { get; private set; }+ public List<double> DownHistory { get; } = [];+ public List<double> UpHistory { get; } = [];+ public double DiskPercent { get; private set; }+ public ulong DiskFree { get; private set; }+ public ulong DiskTotal { get; private set; }+ public BatteryStatus.State? Battery { get; private set; }++ private SystemHub() => _timer.Tick += (_, _) => Sample();++ protected override void Activate()+ {+ _ticks = 0;+ Sample();+ _timer.Start();+ }++ protected override void Deactivate() => _timer.Stop();++ private void Sample()+ {+ if (GetSystemTimes(out var idle, out var kernel, out var user))+ {+ var total = kernel + user;+ if (_lastTotal != 0 && total > _lastTotal)+ Cpu = Math.Clamp((1 - (double)(idle - _lastIdle) / (total - _lastTotal)) * 100, 0, 100);+ _lastIdle = idle;+ _lastTotal = total;+ }+ Push(CpuHistory, Cpu);++ var memory = new MemoryStatus { Length = (uint)Marshal.SizeOf<MemoryStatus>() };+ if (GlobalMemoryStatusEx(ref memory))+ {+ RamPercent = memory.MemoryLoad;+ RamTotal = memory.TotalPhys;+ RamUsed = memory.TotalPhys - memory.AvailPhys;+ }++ SampleNetwork();++ if (_ticks % 30 == 0) SampleDisk();+ if (_ticks % 10 == 0) Battery = BatteryStatus.Read();+ _ticks++;+ Raise();+ }++ private void SampleNetwork()+ {+ long down = 0, up = 0;+ try+ {+ foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())+ {+ if (nic.OperationalStatus != OperationalStatus.Up) continue;+ if (nic.NetworkInterfaceType is NetworkInterfaceType.Loopback or NetworkInterfaceType.Tunnel) continue;+ var stats = nic.GetIPStatistics();+ down += stats.BytesReceived;+ up += stats.BytesSent;+ }+ }+ catch (NetworkInformationException) { return; }++ var now = DateTime.UtcNow;+ if (_lastDown >= 0)+ {+ var seconds = Math.Max(0.2, (now - _lastNet).TotalSeconds);+ Down = Math.Max(0, (down - _lastDown) / seconds);+ Up = Math.Max(0, (up - _lastUp) / seconds);+ }+ _lastDown = down;+ _lastUp = up;+ _lastNet = now;+ Push(DownHistory, Down);+ Push(UpHistory, Up);+ }++ private void SampleDisk()+ {+ try+ {+ var drive = new DriveInfo(Path.GetPathRoot(Environment.SystemDirectory) ?? "C:\\");+ DiskTotal = (ulong)drive.TotalSize;+ DiskFree = (ulong)drive.AvailableFreeSpace;+ DiskPercent = DiskTotal == 0 ? 0 : (1 - (double)DiskFree / DiskTotal) * 100;+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }+ }++ private static void Push(List<double> history, double value)+ {+ history.Add(value);+ if (history.Count > HistoryLength) history.RemoveAt(0);+ }++ public static string Speed(double bytesPerSecond)+ {+ var culture = CultureInfo.CurrentCulture;+ if (bytesPerSecond >= 1024 * 1024) return (bytesPerSecond / 1024 / 1024).ToString("0.0", culture) + " MB/s";+ if (bytesPerSecond >= 1024) return (bytesPerSecond / 1024).ToString("0", culture) + " KB/s";+ return bytesPerSecond.ToString("0", culture) + " B/s";+ }++ public static string Gb(ulong bytes) => (bytes / 1073741824d).ToString(bytes >= 100UL * 1073741824 ? "0" : "0.0", CultureInfo.CurrentCulture) + " GB";++ [StructLayout(LayoutKind.Sequential)]+ private struct MemoryStatus+ {+ public uint Length;+ public uint MemoryLoad;+ public ulong TotalPhys;+ public ulong AvailPhys;+ public ulong TotalPageFile;+ public ulong AvailPageFile;+ public ulong TotalVirtual;+ public ulong AvailVirtual;+ public ulong AvailExtendedVirtual;+ }++ [DllImport("kernel32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool GetSystemTimes(out ulong idleTime, out ulong kernelTime, out ulong userTime);++ [DllImport("kernel32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool GlobalMemoryStatusEx(ref MemoryStatus buffer);+}++/// <summary>Open-Meteo weather for the city set in the widget settings; refreshed every 15 minutes while shown.</summary>+internal sealed class WeatherHub : HubBase+{+ public static readonly WeatherHub Instance = new();+ private readonly WeatherService _service = new();+ private readonly DispatcherTimer _timer = new(DispatcherPriority.Background) { Interval = TimeSpan.FromMinutes(15) };+ private CancellationTokenSource? _load;+ private string? _city;++ public WeatherReport? Report { get; private set; }+ public string? Error { get; private set; }++ private WeatherHub() => _timer.Tick += (_, _) => _ = RefreshAsync();++ protected override void Activate()+ {+ _timer.Start();+ if (Report is null || DateTime.Now - Report.FetchedAt > TimeSpan.FromMinutes(15) || _city != City) _ = RefreshAsync();+ }++ protected override void Deactivate() => _timer.Stop();++ private static string City+ {+ get+ {+ var city = Desk.Settings().WeatherCity;+ return string.IsNullOrWhiteSpace(city) ? "İstanbul" : city.Trim();+ }+ }++ public void CityMayHaveChanged()+ {+ if (_city is not null && _city != City) _ = RefreshAsync();+ }++ public async Task RefreshAsync()+ {+ _load?.Cancel();+ var load = _load = new CancellationTokenSource(TimeSpan.FromSeconds(20));+ var city = City;+ try+ {+ var report = await _service.FetchAsync(city, load.Token);+ if (load.IsCancellationRequested) return;+ Report = report;+ _city = city;+ Error = null;+ }+ catch (Exception ex) when (ex is OperationCanceledException or System.Net.Http.HttpRequestException or InvalidOperationException or JsonException or KeyNotFoundException or FormatException)+ {+ if (load.IsCancellationRequested && ex is OperationCanceledException && !ReferenceEquals(load, _load)) return;+ Error = ex is InvalidOperationException ? ex.Message : Desk.L("Hava durumu alınamadı", "Weather unavailable");+ }+ Raise();+ }++ public static string Temp(double value) => double.IsNaN(value) ? "–" : Math.Round(value).ToString(CultureInfo.InvariantCulture) + "°";+}++/// <summary>The iCal feed from the widget settings, refreshed every 15 minutes while shown.</summary>+internal sealed class CalendarHub : HubBase+{+ public static readonly CalendarHub Instance = new();+ private readonly CalendarFeedService _feed = new();+ private readonly DispatcherTimer _timer = new(DispatcherPriority.Background) { Interval = TimeSpan.FromMinutes(15) };+ private string? _url;+ private DateTime _loaded;++ public bool HasFeed => _feed.HasFeed;++ private CalendarHub() => _timer.Tick += (_, _) => _ = RefreshAsync();++ protected override void Activate()+ {+ _timer.Start();+ if (_url != Desk.Settings().CalendarFeedUrl || DateTime.Now - _loaded > TimeSpan.FromMinutes(15)) _ = RefreshAsync();+ }++ protected override void Deactivate() => _timer.Stop();++ public void UrlMayHaveChanged()+ {+ if (_url != Desk.Settings().CalendarFeedUrl) _ = RefreshAsync();+ }++ public async Task RefreshAsync()+ {+ _url = Desk.Settings().CalendarFeedUrl;+ _loaded = DateTime.Now;+ using var load = new CancellationTokenSource(TimeSpan.FromSeconds(30));+ try+ {+ await _feed.RefreshAsync(_url, load.Token);+ }+ catch (Exception ex) when (ex is OperationCanceledException or System.Net.Http.HttpRequestException or IOException or InvalidOperationException)+ {+ System.Diagnostics.Trace.TraceWarning("Desktop calendar refresh failed: {0}", ex.Message);+ }+ Raise();+ }++ public IReadOnlyList<CalendarOccurrence> Between(DateTime from, DateTime to) =>+ _feed.HasFeed ? _feed.GetOccurrences(from, to) : [];+}++/// <summary>The system media session (Spotify, browsers, players) shared by the music widgets.</summary>+internal sealed class MediaHub : HubBase+{+ public static readonly MediaHub Instance = new();+ private readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;+ private GlobalSystemMediaTransportControlsSessionManager? _manager;+ private GlobalSystemMediaTransportControlsSession? _session;+ private bool _active;+ private int _version;+ private string? _artKey;++ public string Title { get; private set; } = "";+ public string Artist { get; private set; } = "";+ public string App { get; private set; } = "";+ public bool Playing { get; private set; }+ public bool HasMedia => Title.Length > 0 || Artist.Length > 0;+ public ImageSource? Art { get; private set; }+ public Color ArtColor { get; private set; } = Color.FromRgb(0x5E, 0x3A, 0x8C);+ public TimeSpan Position { get; private set; }+ public TimeSpan Duration { get; private set; }+ public DateTime PositionAt { get; private set; }++ /// <summary>Playback position now, moved on from the last update while playing.</summary>+ public TimeSpan LivePosition+ {+ get+ {+ var position = Playing ? Position + (DateTime.UtcNow - PositionAt) : Position;+ return Duration > TimeSpan.Zero && position > Duration ? Duration : position;+ }+ }++ protected override async void Activate()+ {+ _active = true;+ try+ {+ if (_manager is null)+ {+ _manager = await GlobalSystemMediaTransportControlsSessionManager.RequestAsync();+ _manager.CurrentSessionChanged += (_, _) => _dispatcher.InvokeAsync(AttachSession);+ _manager.SessionsChanged += (_, _) => _dispatcher.InvokeAsync(AttachSession);+ }+ AttachSession();+ }+ catch (Exception ex) when (ex is COMException or UnauthorizedAccessException or InvalidOperationException)+ {+ _manager = null;+ }+ }++ protected override void Deactivate()+ {+ _active = false;+ DetachSession();+ }++ private void AttachSession()+ {+ if (!_active || _manager is null) return;+ GlobalSystemMediaTransportControlsSession? session;+ try { session = _manager.GetCurrentSession() ?? _manager.GetSessions().FirstOrDefault(); }+ catch (COMException) { session = null; }+ if (!ReferenceEquals(session, _session))+ {+ DetachSession();+ _session = session;+ if (session is not null)+ {+ session.MediaPropertiesChanged += SessionChanged;+ session.PlaybackInfoChanged += SessionChanged;+ session.TimelinePropertiesChanged += SessionChanged;+ }+ }+ _ = RefreshAsync();+ }++ private void DetachSession()+ {+ if (_session is null) return;+ _session.MediaPropertiesChanged -= SessionChanged;+ _session.PlaybackInfoChanged -= SessionChanged;+ _session.TimelinePropertiesChanged -= SessionChanged;+ _session = null;+ }++ private void SessionChanged(GlobalSystemMediaTransportControlsSession sender, object args) =>+ _dispatcher.InvokeAsync(() => _ = RefreshAsync());++ private async Task RefreshAsync()+ {+ var version = ++_version;+ var session = _session;+ if (session is null)+ {+ Title = Artist = App = "";+ Playing = false;+ Art = null;+ _artKey = null;+ Raise();+ return;+ }+ try+ {+ var playback = session.GetPlaybackInfo();+ var properties = await session.TryGetMediaPropertiesAsync();+ if (version != _version) return;+ Title = properties?.Title ?? "";+ Artist = properties?.Artist ?? "";+ App = AppName(session.SourceAppUserModelId);+ Playing = playback?.PlaybackStatus == GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing;+ var timeline = session.GetTimelineProperties();+ Position = timeline.Position;+ Duration = timeline.EndTime - timeline.StartTime;+ PositionAt = timeline.LastUpdatedTime.UtcDateTime == default ? DateTime.UtcNow : timeline.LastUpdatedTime.UtcDateTime;+ if (PositionAt > DateTime.UtcNow) PositionAt = DateTime.UtcNow;+ var key = $"{Title}|{Artist}|{properties?.AlbumTitle}";+ if (key != _artKey)+ {+ _artKey = key;+ await LoadArtAsync(properties?.Thumbnail, version);+ }+ }+ catch (Exception ex) when (ex is COMException or InvalidOperationException or UnauthorizedAccessException)+ {+ if (version != _version) return;+ Title = Artist = "";+ }+ Raise();+ }++ private static string AppName(string? id)+ {+ if (string.IsNullOrEmpty(id)) return "";+ var name = id.Split('!')[0];+ name = Path.GetFileNameWithoutExtension(name);+ if (name.Contains("Spotify", StringComparison.OrdinalIgnoreCase)) return "Spotify";+ if (name.Contains("chrome", StringComparison.OrdinalIgnoreCase)) return "Chrome";+ if (name.Contains("msedge", StringComparison.OrdinalIgnoreCase)) return "Edge";+ if (name.Contains("firefox", StringComparison.OrdinalIgnoreCase)) return "Firefox";+ if (name.Contains("ZuneMusic", StringComparison.OrdinalIgnoreCase)) return Desk.L("Medya Oynatıcı", "Media Player");+ return name.Length > 0 ? char.ToUpper(name[0], CultureInfo.CurrentCulture) + name[1..] : name;+ }++ private async Task LoadArtAsync(Windows.Storage.Streams.IRandomAccessStreamReference? reference, int version)+ {+ if (reference is null)+ {+ Art = null;+ return;+ }+ try+ {+ using var winStream = await reference.OpenReadAsync();+ using var source = winStream.AsStreamForRead();+ var memory = new MemoryStream();+ await source.CopyToAsync(memory);+ memory.Position = 0;+ if (version != _version) return;+ var image = new BitmapImage();+ image.BeginInit();+ image.CacheOption = BitmapCacheOption.OnLoad;+ image.DecodePixelWidth = 300;+ image.StreamSource = memory;+ image.EndInit();+ image.Freeze();+ Art = image;+ ArtColor = Average(image);+ }+ catch (Exception ex) when (ex is COMException or IOException or NotSupportedException or InvalidOperationException or FileFormatException)+ {+ Art = null;+ }+ }++ private static Color Average(BitmapSource image)+ {+ var small = new FormatConvertedBitmap(new TransformedBitmap(image, new ScaleTransform(16.0 / image.PixelWidth, 16.0 / image.PixelHeight)), PixelFormats.Bgra32, null, 0);+ var pixels = new byte[small.PixelWidth * small.PixelHeight * 4];+ small.CopyPixels(pixels, small.PixelWidth * 4, 0);+ double r = 0, g = 0, b = 0;+ var count = Math.Max(1, pixels.Length / 4);+ for (var i = 0; i < pixels.Length; i += 4)+ {+ b += pixels[i];+ g += pixels[i + 1];+ r += pixels[i + 2];+ }+ return Color.FromRgb((byte)(r / count), (byte)(g / count), (byte)(b / count));+ }++ public async void Command(Func<GlobalSystemMediaTransportControlsSession, Windows.Foundation.IAsyncOperation<bool>> command)+ {+ if (_session is null) return;+ try { await command(_session); }+ catch (Exception ex) when (ex is COMException or InvalidOperationException)+ {+ System.Diagnostics.Trace.TraceWarning("Media command failed: {0}", ex.Message);+ }+ }+}++/// <summary>Exchange rates from the European Central Bank via Frankfurter (free, no key); cached for 6 hours.</summary>+internal static class RatesHub+{+ private static readonly Dictionary<string, (DateTime At, Dictionary<string, double> Rates)> Cache = new(StringComparer.OrdinalIgnoreCase);++ public static readonly string[] Currencies = ["TRY", "USD", "EUR", "GBP", "CHF", "JPY", "CNY", "RUB", "SAR", "AED", "AUD", "CAD"];++ public static async Task<double?> RateAsync(string from, string to)+ {+ if (string.Equals(from, to, StringComparison.OrdinalIgnoreCase)) return 1;+ if (!Cache.TryGetValue(from, out var entry) || DateTime.Now - entry.At > TimeSpan.FromHours(6))+ {+ try+ {+ using var token = new CancellationTokenSource(TimeSpan.FromSeconds(15));+ using var response = await WidgetHttp.Client.GetAsync("https://api.frankfurter.app/latest?from=" + Uri.EscapeDataString(from.ToUpperInvariant()), token.Token);+ response.EnsureSuccessStatusCode();+ await using var stream = await response.Content.ReadAsStreamAsync(token.Token);+ using var json = await JsonDocument.ParseAsync(stream, cancellationToken: token.Token);+ var rates = new Dictionary<string, double>(StringComparer.OrdinalIgnoreCase);+ foreach (var rate in json.RootElement.GetProperty("rates").EnumerateObject()) rates[rate.Name] = rate.Value.GetDouble();+ entry = (DateTime.Now, rates);+ Cache[from] = entry;+ }+ catch (Exception ex) when (ex is OperationCanceledException or System.Net.Http.HttpRequestException or JsonException or KeyNotFoundException or InvalidOperationException)+ {+ return Cache.TryGetValue(from, out var stale) && stale.Rates.TryGetValue(to, out var old) ? old : null;+ }+ }+ return entry.Rates.TryGetValue(to, out var value) ? value : null;+ }+}diff --git a/DesktopWidgets/DeskSheet.cs b/DesktopWidgets/DeskSheet.csnew file mode 100644index 0000000..1494ff7--- /dev/null+++ b/DesktopWidgets/DeskSheet.cs@@ -0,0 +1,90 @@+#if DEBUG+using System.IO;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Media.Imaging;+using System.Windows.Threading;+using QiDock.Models;++namespace QiDock.DesktopWidgets;++/// <summary>Debug builds only: renders every desktop widget in every size to one PNG for review.</summary>+internal static class DeskSheet+{+ public static void Render(string path, Func<WidgetSettings> settings, Action done)+ {+ Desk.Settings = settings;+ var panel = new WrapPanel { Width = 2300, Background = QiDock.Widgets.Ui.Vertical("#FF5B86C5", "#FF2A4C8C") };+ panel.SetResourceReference(System.Windows.Documents.TextElement.FontFamilyProperty, "InterfaceFont");+ TextOptions.SetTextFormattingMode(panel, TextFormattingMode.Ideal);+ var hosts = new List<SheetHost>();+ foreach (var kind in DeskCatalog.All)+ foreach (var size in kind.Sizes)+ {+ var host = new SheetHost(kind, size);+ hosts.Add(host);+ var label = DeskUi.T($"{kind.Id} / {size}", 13, FontWeights.SemiBold, Brushes.White);+ var cell = new StackPanel { Margin = new Thickness(14) };+ cell.Children.Add(label);+ cell.Children.Add(DeskUi.Margin(host.Card, 0, 6));+ panel.Children.Add(cell);+ }+ var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(9) };+ timer.Tick += (_, _) =>+ {+ timer.Stop();+ for (var pass = 0; pass < 2; pass++)+ {+ foreach (var host in hosts) host.Widget.Tick();+ panel.Measure(new Size(panel.Width, double.PositiveInfinity));+ panel.Arrange(new Rect(panel.DesiredSize));+ panel.UpdateLayout();+ }+ var bitmap = new RenderTargetBitmap((int)Math.Ceiling(panel.ActualWidth), (int)Math.Ceiling(panel.ActualHeight), 96, 96, PixelFormats.Pbgra32);+ bitmap.Render(panel);+ var encoder = new PngBitmapEncoder();+ encoder.Frames.Add(BitmapFrame.Create(bitmap));+ using (var stream = File.Create(path)) encoder.Save(stream);+ foreach (var host in hosts) host.Widget.Detach();+ done();+ };+ panel.Measure(new Size(panel.Width, double.PositiveInfinity));+ panel.Arrange(new Rect(panel.DesiredSize));+ timer.Start();+ }++ private sealed class SheetHost : IDeskHost+ {+ public SheetHost(DeskKind kind, DeskSize size)+ {+ Item = new DeskItem { Kind = kind.Id, Size = size };+ Widget = kind.Create();+ Widget.Host = this;+ var dims = Desk.Dimensions(size);+ Card = new Border+ {+ Width = dims.Width,+ Height = dims.Height,+ CornerRadius = new CornerRadius(24),+ Background = DeskUi.CardFill,+ BorderBrush = DeskUi.CardStroke,+ BorderThickness = new Thickness(1),+ Padding = Desk.Padding(size),+ Child = Widget.Build()+ };+ Card.Clip = new RectangleGeometry(new Rect(0, 0, dims.Width, dims.Height), 24, 24);+ Widget.Attach();+ }++ public DeskItem Item { get; }+ public DeskWidget Widget { get; }+ public Border Card { get; }+ public bool IsLive => true;+ public void Save() { }+ public void FocusInput(IInputElement element) { }+ public void Rebuild() => Card.Child = Widget.Build();+ }+}+#endifdiff --git a/DesktopWidgets/DeskVisuals.cs b/DesktopWidgets/DeskVisuals.csnew file mode 100644index 0000000..87666a1--- /dev/null+++ b/DesktopWidgets/DeskVisuals.cs@@ -0,0 +1,483 @@+using System.Globalization;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Shapes;+using QiDock.Widgets;++namespace QiDock.DesktopWidgets;++/// <summary>Colors and small building blocks shared by the desktop widgets (dark cards, like the reference).</summary>+internal static class DeskUi+{+ public static readonly Brush CardFill = Ui.Solid("#F21C1C1F");+ public static readonly Brush CardStroke = Ui.Solid("#1EFFFFFF");+ public static readonly Brush Text = Ui.Solid("#FFF5F5F7");+ public static readonly Brush Secondary = Ui.Solid("#FF8E8E93");+ public static readonly Brush Tertiary = Ui.Solid("#FF5E5E63");+ public static readonly Brush Track = Ui.Solid("#24FFFFFF");+ public static readonly Brush Inset = Ui.Solid("#14FFFFFF");+ public static readonly Brush InsetHover = Ui.Solid("#24FFFFFF");+ public static readonly Brush Blue = Ui.Solid("#FF0A84FF");+ public static readonly Brush Green = Ui.Solid("#FF30D158");+ public static readonly Brush Orange = Ui.Solid("#FFFF9F0A");+ public static readonly Brush Red = Ui.Solid("#FFFF453A");+ public static readonly Brush Yellow = Ui.Solid("#FFFFD60A");+ public static readonly Brush Purple = Ui.Solid("#FFBF5AF2");+ public static readonly Brush Cyan = Ui.Solid("#FF64D2FF");+ public static readonly Brush Pink = Ui.Solid("#FFFF375F");++ public static TextBlock T(string text, double size, FontWeight? weight = null, Brush? brush = null)+ {+ var block = new TextBlock+ {+ Text = text,+ FontSize = size,+ FontWeight = weight ?? FontWeights.Normal,+ Foreground = brush ?? Text,+ TextTrimming = TextTrimming.CharacterEllipsis,+ VerticalAlignment = VerticalAlignment.Center+ };+ return block;+ }++ /// <summary>Numbers that do not jump around as digits change.</summary>+ public static TextBlock Digits(string text, double size, FontWeight? weight = null, Brush? brush = null)+ {+ var block = T(text, size, weight ?? FontWeights.SemiBold, brush);+ block.Typography.NumeralAlignment = FontNumeralAlignment.Tabular;+ block.TextTrimming = TextTrimming.None;+ return block;+ }++ public static Path Icon(string key, double size, Brush? brush = null, double stroke = 1.9) => Ui.Icon(key, size, brush ?? Text, stroke: stroke);+ public static Path Glyph(string key, double size, Brush? brush = null) => Ui.Glyph(key, size, brush ?? Text);++ public static StackPanel Row(params UIElement[] children)+ {+ var row = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };+ foreach (var child in children) row.Children.Add(child);+ return row;+ }++ public static StackPanel Column(params UIElement[] children)+ {+ var column = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ foreach (var child in children) column.Children.Add(child);+ return column;+ }++ public static T2 At<T2>(T2 element, int row = 0, int column = 0, int rowSpan = 1, int columnSpan = 1) where T2 : UIElement+ {+ System.Windows.Controls.Grid.SetRow(element, row);+ System.Windows.Controls.Grid.SetColumn(element, column);+ if (rowSpan > 1) System.Windows.Controls.Grid.SetRowSpan(element, rowSpan);+ if (columnSpan > 1) System.Windows.Controls.Grid.SetColumnSpan(element, columnSpan);+ return element;+ }++ public static System.Windows.Controls.Grid Grid(string rows = "", string columns = "")+ {+ var grid = new System.Windows.Controls.Grid();+ foreach (var r in Split(rows)) grid.RowDefinitions.Add(new RowDefinition { Height = r });+ foreach (var c in Split(columns)) grid.ColumnDefinitions.Add(new ColumnDefinition { Width = c });+ return grid;+ }++ private static IEnumerable<GridLength> Split(string spec)+ {+ if (string.IsNullOrWhiteSpace(spec)) yield break;+ foreach (var part in spec.Split(','))+ {+ var p = part.Trim();+ if (p == "Auto") yield return GridLength.Auto;+ else if (p.EndsWith('*')) yield return new GridLength(p.Length == 1 ? 1 : double.Parse(p[..^1], CultureInfo.InvariantCulture), GridUnitType.Star);+ else yield return new GridLength(double.Parse(p, CultureInfo.InvariantCulture));+ }+ }++ public static T2 Margin<T2>(T2 element, double left, double top = 0, double right = 0, double bottom = 0) where T2 : FrameworkElement+ {+ element.Margin = new Thickness(left, top, right, bottom);+ return element;+ }++ /// <summary>Placeholder shown when there is nothing to display yet.</summary>+ public static FrameworkElement Empty(string iconKey, string text)+ {+ var icon = Icon(iconKey, 22, Secondary);+ var label = T(text, 12, brush: Secondary);+ label.TextWrapping = TextWrapping.Wrap;+ label.TextAlignment = TextAlignment.Center;+ label.Margin = new Thickness(0, 8, 0, 0);+ var stack = Column(icon, label);+ stack.HorizontalAlignment = HorizontalAlignment.Center;+ return stack;+ }++ public static string Percent(double value) => "%" + Math.Round(value).ToString(CultureInfo.InvariantCulture);+}++/// <summary>Clickable rounded area (round play buttons, toggles, list rows). Never takes focus.</summary>+internal sealed class DeskButton : Border+{+ public event EventHandler? Click;++ public DeskButton(UIElement content, Action? click = null, double size = double.NaN, Brush? background = null, double radius = -1)+ {+ Child = content;+ Width = size;+ Height = size;+ Background = background ?? Brushes.Transparent;+ CornerRadius = new CornerRadius(radius >= 0 ? radius : double.IsNaN(size) ? 10 : size / 2);+ Cursor = Cursors.Hand;+ if (click is not null) Click += (_, _) => click();+ MouseEnter += (_, _) => Opacity = 0.82;+ MouseLeave += (_, _) => Opacity = 1;+ MouseLeftButtonDown += (_, e) => e.Handled = true;+ MouseLeftButtonUp += (_, e) =>+ {+ e.Handled = true;+ if (IsMouseOver) Click?.Invoke(this, EventArgs.Empty);+ };+ }++ public static DeskButton Round(string glyphKey, Action click, double size, Brush background, Brush? foreground = null, double glyph = 0, bool outline = false)+ {+ UIElement content = outline+ ? DeskUi.Icon(glyphKey, glyph > 0 ? glyph : size * 0.42, foreground)+ : DeskUi.Glyph(glyphKey, glyph > 0 ? glyph : size * 0.36, foreground);+ return new DeskButton(content, click, size, background);+ }+}++/// <summary>Progress ring (CPU, battery, timers).</summary>+internal sealed class RingGauge : FrameworkElement+{+ private double _value;+ public double Thickness { get; init; } = 6;+ public Brush Stroke { get; set; } = DeskUi.Blue;+ public Brush TrackBrush { get; init; } = DeskUi.Track;++ public double Value+ {+ get => _value;+ set+ {+ var clamped = Math.Clamp(value, 0, 100);+ if (Math.Abs(clamped - _value) < 0.05) return;+ _value = clamped;+ InvalidateVisual();+ }+ }++ protected override void OnRender(DrawingContext dc)+ {+ var size = Math.Min(ActualWidth, ActualHeight);+ if (size <= 0) return;+ var center = new Point(ActualWidth / 2, ActualHeight / 2);+ var radius = (size - Thickness) / 2;+ dc.DrawEllipse(null, new Pen(TrackBrush, Thickness), center, radius, radius);+ if (_value <= 0) return;+ var pen = new Pen(Stroke, Thickness) { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round };+ if (_value >= 99.95)+ {+ dc.DrawEllipse(null, pen, center, radius, radius);+ return;+ }+ var angle = _value / 100 * 360;+ var start = new Point(center.X, center.Y - radius);+ var radians = (angle - 90) * Math.PI / 180;+ var end = new Point(center.X + radius * Math.Cos(radians), center.Y + radius * Math.Sin(radians));+ var figure = new PathFigure { StartPoint = start, IsClosed = false };+ figure.Segments.Add(new ArcSegment(end, new Size(radius, radius), 0, angle > 180, SweepDirection.Clockwise, true));+ dc.DrawGeometry(null, pen, new PathGeometry([figure]));+ }+}++/// <summary>Line graph with a soft fill (CPU, network, stocks-like curves).</summary>+internal sealed class Sparkline : FrameworkElement+{+ private IReadOnlyList<double> _values = [];+ private IReadOnlyList<double>? _second;+ public Brush Stroke { get; init; } = DeskUi.Blue;+ public Brush SecondStroke { get; init; } = DeskUi.Purple;+ public double? Maximum { get; init; }+ public double LineThickness { get; init; } = 2;++ public void SetValues(IReadOnlyList<double> values, IReadOnlyList<double>? second = null)+ {+ _values = values;+ _second = second;+ InvalidateVisual();+ }++ protected override void OnRender(DrawingContext dc)+ {+ if (ActualWidth <= 0 || ActualHeight <= 0) return;+ var max = Maximum ?? Math.Max(1, Math.Max(_values.DefaultIfEmpty(0).Max(), _second?.DefaultIfEmpty(0).Max() ?? 0) * 1.15);+ if (_second is { Count: > 1 }) Draw(dc, _second, max, SecondStroke, false);+ if (_values.Count > 1) Draw(dc, _values, max, Stroke, true);+ }++ private void Draw(DrawingContext dc, IReadOnlyList<double> values, double max, Brush stroke, bool fill)+ {+ var w = ActualWidth;+ var h = ActualHeight - LineThickness;+ var step = w / (values.Count - 1);+ var points = values.Select((v, i) => new Point(i * step, LineThickness / 2 + h - Math.Clamp(v / max, 0, 1) * h)).ToList();+ var line = new StreamGeometry();+ using (var ctx = line.Open())+ {+ ctx.BeginFigure(points[0], false, false);+ for (var i = 1; i < points.Count; i++)+ {+ // Smooth with midpoints so the curve looks drawn, not jagged.+ var mid = new Point((points[i - 1].X + points[i].X) / 2, (points[i - 1].Y + points[i].Y) / 2);+ ctx.QuadraticBezierTo(points[i - 1], mid, true, true);+ }+ ctx.LineTo(points[^1], true, true);+ }+ line.Freeze();+ if (fill && stroke is SolidColorBrush solid)+ {+ var area = new StreamGeometry();+ using (var ctx = area.Open())+ {+ ctx.BeginFigure(new Point(0, ActualHeight), true, true);+ ctx.LineTo(points[0], false, false);+ for (var i = 1; i < points.Count; i++)+ {+ var mid = new Point((points[i - 1].X + points[i].X) / 2, (points[i - 1].Y + points[i].Y) / 2);+ ctx.QuadraticBezierTo(points[i - 1], mid, false, false);+ }+ ctx.LineTo(points[^1], false, false);+ ctx.LineTo(new Point(w, ActualHeight), false, false);+ }+ area.Freeze();+ var color = solid.Color;+ var gradient = new LinearGradientBrush(Color.FromArgb(0x55, color.R, color.G, color.B), Color.FromArgb(0, color.R, color.G, color.B), 90);+ gradient.Freeze();+ dc.DrawGeometry(gradient, null, area);+ }+ dc.DrawGeometry(null, new Pen(stroke, LineThickness) { LineJoin = PenLineJoin.Round, StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round }, line);+ }+}++/// <summary>Grid of dots: days of the month or year gone by.</summary>+internal sealed class DotGrid : FrameworkElement+{+ public int Total { get; set; }+ public int Filled { get; set; }+ public int Columns { get; set; } = 10;+ public Brush FilledBrush { get; init; } = DeskUi.Text;+ public Brush EmptyBrush { get; init; } = DeskUi.Track;+ public Brush CurrentBrush { get; init; } = DeskUi.Orange;++ public void Set(int total, int filled, int columns)+ {+ Total = total;+ Filled = filled;+ Columns = columns;+ InvalidateVisual();+ }++ protected override void OnRender(DrawingContext dc)+ {+ if (Total <= 0 || Columns <= 0 || ActualWidth <= 0) return;+ var rows = (int)Math.Ceiling(Total / (double)Columns);+ var cellW = ActualWidth / Columns;+ var cellH = ActualHeight / rows;+ var radius = Math.Max(1, Math.Min(cellW, cellH) * 0.36);+ for (var i = 0; i < Total; i++)+ {+ var x = (i % Columns + 0.5) * cellW;+ var y = (i / Columns + 0.5) * cellH;+ var brush = i < Filled ? FilledBrush : i == Filled ? CurrentBrush : EmptyBrush;+ dc.DrawEllipse(brush, null, new Point(x, y), radius, radius);+ }+ }+}++/// <summary>Classic clock face with hour, minute and second hands.</summary>+internal sealed class AnalogFace : FrameworkElement+{+ private DateTime _time = DateTime.Now;+ public bool Light { get; init; } = true;+ public bool Numbers { get; init; } = true;++ public void SetTime(DateTime time)+ {+ _time = time;+ InvalidateVisual();+ }++ protected override void OnRender(DrawingContext dc)+ {+ var size = Math.Min(ActualWidth, ActualHeight);+ if (size <= 0) return;+ var c = new Point(ActualWidth / 2, ActualHeight / 2);+ var r = size / 2;+ var face = Light ? Ui.Solid("#FFF7F7F8") : Ui.Solid("#FF2C2C2E");+ var ink = Light ? Ui.Solid("#FF1C1C1E") : DeskUi.Text;+ var faint = Light ? Ui.Solid("#FF9A9AA0") : DeskUi.Secondary;+ dc.DrawEllipse(face, new Pen(Light ? Ui.Solid("#33000000") : DeskUi.CardStroke, 1), c, r - 0.5, r - 0.5);+ for (var i = 0; i < 60; i++)+ {+ var major = i % 5 == 0;+ var a = i * 6 * Math.PI / 180;+ var outer = r * 0.92;+ var inner = major ? r * 0.82 : r * 0.87;+ dc.DrawLine(new Pen(major ? ink : faint, major ? Math.Max(1.2, size / 70) : 0.8) { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round },+ new Point(c.X + Math.Sin(a) * inner, c.Y - Math.Cos(a) * inner),+ new Point(c.X + Math.Sin(a) * outer, c.Y - Math.Cos(a) * outer));+ }+ if (Numbers && size >= 110)+ {+ var typeface = new Typeface(new FontFamily("Segoe UI Variable Display, Segoe UI"), FontStyles.Normal, FontWeights.SemiBold, FontStretches.Normal);+ var dpi = VisualTreeHelper.GetDpi(this).PixelsPerDip;+ for (var h = 1; h <= 12; h++)+ {+ var a = h * 30 * Math.PI / 180;+ var text = new FormattedText(h.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture, FlowDirection.LeftToRight, typeface, size * 0.1, ink, dpi);+ var p = new Point(c.X + Math.Sin(a) * r * 0.66 - text.Width / 2, c.Y - Math.Cos(a) * r * 0.66 - text.Height / 2);+ dc.DrawText(text, p);+ }+ }+ var t = _time;+ Hand(dc, c, (t.Hour % 12 + t.Minute / 60.0) * 30, r * 0.5, Math.Max(2.5, size / 34), ink);+ Hand(dc, c, (t.Minute + t.Second / 60.0) * 6, r * 0.74, Math.Max(2, size / 48), ink);+ Hand(dc, c, t.Second * 6, r * 0.8, Math.Max(1, size / 120), DeskUi.Orange, r * 0.16);+ dc.DrawEllipse(DeskUi.Orange, null, c, Math.Max(2, size / 40), Math.Max(2, size / 40));+ }++ private static void Hand(DrawingContext dc, Point c, double degrees, double length, double width, Brush brush, double tail = 0)+ {+ var a = degrees * Math.PI / 180;+ var tip = new Point(c.X + Math.Sin(a) * length, c.Y - Math.Cos(a) * length);+ var back = new Point(c.X - Math.Sin(a) * tail, c.Y + Math.Cos(a) * tail);+ dc.DrawLine(new Pen(brush, width) { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round }, back, tip);+ }+}++/// <summary>The sun's path between sunrise and sunset with its current position.</summary>+internal sealed class SunArc : FrameworkElement+{+ private double _progress = -1;++ /// <summary>0 = sunrise, 1 = sunset; outside that range the sun is below the horizon.</summary>+ public void SetProgress(double progress)+ {+ _progress = progress;+ InvalidateVisual();+ }++ protected override void OnRender(DrawingContext dc)+ {+ if (ActualWidth <= 0 || ActualHeight <= 0) return;+ var w = ActualWidth;+ var h = ActualHeight;+ var horizon = h - 4;+ Point At(double p) => new(w * p, horizon - Math.Sin(Math.Clamp(p, 0, 1) * Math.PI) * (h - 12));+ var geometry = new StreamGeometry();+ using (var ctx = geometry.Open())+ {+ ctx.BeginFigure(At(0), false, false);+ for (var i = 1; i <= 40; i++) ctx.LineTo(At(i / 40.0), true, true);+ }+ geometry.Freeze();+ var gradient = new LinearGradientBrush(Color.FromRgb(0x8E, 0x8E, 0x93), Color.FromRgb(0xFF, 0x9F, 0x0A), 0);+ gradient.Freeze();+ dc.DrawGeometry(null, new Pen(gradient, 2) { DashStyle = _progress is >= 0 and <= 1 ? DashStyles.Solid : DashStyles.Dot }, geometry);+ dc.DrawLine(new Pen(DeskUi.Track, 1), new Point(0, horizon), new Point(w, horizon));+ if (_progress is < 0 or > 1) return;+ var sun = At(_progress);+ dc.DrawEllipse(Ui.Solid("#55FFC83D"), null, sun, 9, 9);+ dc.DrawEllipse(DeskUi.Yellow, null, sun, 5.5, 5.5);+ }+}++/// <summary>Wind direction compass.</summary>+internal sealed class Compass : FrameworkElement+{+ private double _direction = double.NaN;++ public void SetDirection(double degrees)+ {+ _direction = degrees;+ InvalidateVisual();+ }++ protected override void OnRender(DrawingContext dc)+ {+ var size = Math.Min(ActualWidth, ActualHeight);+ if (size <= 0) return;+ var c = new Point(ActualWidth / 2, ActualHeight / 2);+ var r = size / 2 - 1;+ dc.DrawEllipse(DeskUi.Inset, new Pen(DeskUi.Track, 1), c, r, r);+ var typeface = new Typeface(new FontFamily("Segoe UI"), FontStyles.Normal, FontWeights.SemiBold, FontStretches.Normal);+ var dpi = VisualTreeHelper.GetDpi(this).PixelsPerDip;+ string[] labels = [Desk.L("K", "N"), Desk.L("D", "E"), Desk.L("G", "S"), Desk.L("B", "W")];+ for (var i = 0; i < 4; i++)+ {+ var a = i * 90 * Math.PI / 180;+ var text = new FormattedText(labels[i], CultureInfo.InvariantCulture, FlowDirection.LeftToRight, typeface, Math.Max(7, size * 0.13), i == 0 ? DeskUi.Text : DeskUi.Secondary, dpi);+ dc.DrawText(text, new Point(c.X + Math.Sin(a) * r * 0.74 - text.Width / 2, c.Y - Math.Cos(a) * r * 0.74 - text.Height / 2));+ }+ if (double.IsNaN(_direction)) return;+ // Arrow points where the wind blows to (meteorological direction + 180°).+ var to = (_direction + 180) * Math.PI / 180;+ var tip = new Point(c.X + Math.Sin(to) * r * 0.45, c.Y - Math.Cos(to) * r * 0.45);+ var left = new Point(c.X + Math.Sin(to + 2.5) * r * 0.28, c.Y - Math.Cos(to + 2.5) * r * 0.28);+ var right = new Point(c.X + Math.Sin(to - 2.5) * r * 0.28, c.Y - Math.Cos(to - 2.5) * r * 0.28);+ var arrow = new StreamGeometry();+ using (var ctx = arrow.Open())+ {+ ctx.BeginFigure(tip, true, true);+ ctx.LineTo(left, false, false);+ ctx.LineTo(c, false, false);+ ctx.LineTo(right, false, false);+ }+ arrow.Freeze();+ dc.DrawGeometry(DeskUi.Text, null, arrow);+ }+}++/// <summary>Water that rises as the reminder interval passes.</summary>+internal sealed class WaveFill : FrameworkElement+{+ private double _fraction;+ public Brush Water { get; init; } = Ui.Vertical("#FF3BA7F5", "#FF1565C0");++ public void SetFraction(double fraction)+ {+ var f = Math.Clamp(fraction, 0, 1);+ if (Math.Abs(f - _fraction) < 0.002) return;+ _fraction = f;+ InvalidateVisual();+ }++ protected override void OnRender(DrawingContext dc)+ {+ if (ActualWidth <= 0 || ActualHeight <= 0 || _fraction <= 0) return;+ var w = ActualWidth;+ var h = ActualHeight;+ var level = h - h * _fraction;+ var wave = new StreamGeometry();+ using (var ctx = wave.Open())+ {+ ctx.BeginFigure(new Point(0, h), true, true);+ ctx.LineTo(new Point(0, level), false, false);+ const int steps = 24;+ for (var i = 1; i <= steps; i++)+ {+ var x = w * i / steps;+ ctx.LineTo(new Point(x, level + Math.Sin(i / (double)steps * Math.PI * 3) * 4), false, true);+ }+ ctx.LineTo(new Point(w, h), false, false);+ }+ wave.Freeze();+ dc.DrawGeometry(Water, null, wave);+ }+}diff --git a/DesktopWidgets/DeskWidgetManager.cs b/DesktopWidgets/DeskWidgetManager.csnew file mode 100644index 0000000..8e4f19c--- /dev/null+++ b/DesktopWidgets/DeskWidgetManager.cs@@ -0,0 +1,265 @@+using System.Windows;+using System.Windows.Threading;++namespace QiDock.DesktopWidgets;++/// <summary>+/// Keeps the desktop widgets: opens their windows, saves the layout, finds free spots, snaps them+/// to each other, and pauses the ones an app window fully covers.+/// </summary>+internal sealed class DeskWidgetManager : IDisposable+{+ private readonly DeskLayout _layout = DeskStore.Load();+ private readonly List<DeskWidgetWindow> _windows = [];+ private readonly DispatcherTimer _saveTimer = new(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(400) };+ private readonly DispatcherTimer _recreateTimer = new(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(3) };+ private IReadOnlyList<Rect> _covers = [];+ private DeskGallery? _gallery;+ private bool _disposed;+ private bool _hidden;++ public DeskWidgetManager()+ {+ _saveTimer.Tick += (_, _) =>+ {+ _saveTimer.Stop();+ DeskStore.Save(_layout);+ };+ _recreateTimer.Tick += (_, _) =>+ {+ _recreateTimer.Stop();+ Reopen();+ };+ }++ public IReadOnlyList<DeskItem> Items => _layout.Items;++ public void Start()+ {+ if (!_layout.Initialized)+ {+ AddDefaults();+ _layout.Initialized = true;+ Save();+ }+ foreach (var item in _layout.Items.ToList()) Open(item);+ }++ private DeskWidgetWindow? Open(DeskItem item)+ {+ if (DeskCatalog.Find(item.Kind) is not { } kind) return null;+ if (!kind.Sizes.Contains(item.Size)) item.Size = kind.DefaultSize;+ var window = new DeskWidgetWindow(this, item, kind);+ _windows.Add(window);+ window.Show();+ KeepOnScreen(window);+ window.SetLive(!_hidden && IsUncovered(window));+ if (_hidden) window.Hide();+ return window;+ }++ public void Add(DeskKind kind, DeskSize size)+ {+ var item = new DeskItem { Kind = kind.Id, Size = size };+ var spot = FindSpot(Desk.Dimensions(size));+ item.X = spot.X;+ item.Y = spot.Y;+ _layout.Items.Add(item);+ Open(item);+ Save();+ }++ public void Remove(DeskWidgetWindow window)+ {+ _layout.Items.Remove(window.Item);+ _windows.Remove(window);+ window.ClosingByManager = true;+ window.Close();+ Save();+ }++ public void Save()+ {+ _saveTimer.Stop();+ _saveTimer.Start();+ }++ /// <summary>The system closed a widget window (Explorer restarted and took its owner along).</summary>+ public void WindowLost(DeskWidgetWindow window)+ {+ _windows.Remove(window);+ if (_disposed) return;+ _recreateTimer.Stop();+ _recreateTimer.Start();+ }++ private void Reopen()+ {+ if (_disposed) return;+ foreach (var item in _layout.Items.Where(i => _windows.All(w => !ReferenceEquals(w.Item, i))).ToList()) Open(item);+ }++ /// <summary>Explorer came back (TaskbarCreated): hook the windows to the new desktop.</summary>+ public void Reattach()+ {+ foreach (var window in _windows) window.AttachToDesktop();+ Reopen();+ }++ public void SettingsChanged()+ {+ WeatherHub.Instance.CityMayHaveChanged();+ CalendarHub.Instance.UrlMayHaveChanged();+ foreach (var window in _windows) window.Widget.SettingsChanged();+ _gallery?.SettingsChanged();+ }++ /// <summary>App window rectangles (physical pixels) on screen; widgets under one of them pause.</summary>+ public void UpdateCovers(IReadOnlyList<Rect> covers)+ {+ _covers = covers;+ foreach (var window in _windows) window.SetLive(!_hidden && IsUncovered(window));+ }++ /// <summary>+ /// The desktop with files shows only its folders and files: the widgets step away (and pause) meanwhile and+ /// come back on the clean desktop.+ /// </summary>+ public void SetHidden(bool hidden)+ {+ if (_hidden == hidden) return;+ _hidden = hidden;+ foreach (var window in _windows)+ {+ if (hidden)+ {+ window.SetLive(false);+ window.Hide();+ }+ else+ {+ window.Show();+ window.SetLive(IsUncovered(window));+ }+ }+ }++ private bool IsUncovered(DeskWidgetWindow window)+ {+ if (_covers.Count == 0) return true;+ var scale = PresentationSource.FromVisual(window)?.CompositionTarget?.TransformToDevice.M11 ?? 1;+ var b = window.Bounds;+ var pixels = new Rect(b.X * scale, b.Y * scale, b.Width * scale, b.Height * scale);+ return !_covers.Any(cover => cover.Contains(pixels));+ }++ public void ShowGallery()+ {+ if (_gallery is { } open)+ {+ open.Activate();+ return;+ }+ _gallery = new DeskGallery(this);+ _gallery.Closed += (_, _) => _gallery = null;+ _gallery.Show();+ _gallery.Activate();+ }++ /// <summary>Lines a dragged widget up with its neighbours (edges or one gap apart) and keeps it on screen.</summary>+ public Point Snap(DeskWidgetWindow window, double x, double y)+ {+ const double Magnet = 14;+ var size = Desk.Dimensions(window.Item.Size);+ double? bestX = null, bestY = null;+ double distX = Magnet, distY = Magnet;+ foreach (var other in _windows.Where(w => !ReferenceEquals(w, window)).Select(w => w.Bounds))+ {+ foreach (var candidate in new[] { other.Left, other.Right + Desk.Gap, other.Left - Desk.Gap - size.Width, other.Right - size.Width })+ {+ var d = Math.Abs(x - candidate);+ if (d < distX) { distX = d; bestX = candidate; }+ }+ foreach (var candidate in new[] { other.Top, other.Bottom + Desk.Gap, other.Top - Desk.Gap - size.Height, other.Bottom - size.Height })+ {+ var d = Math.Abs(y - candidate);+ if (d < distY) { distY = d; bestY = candidate; }+ }+ }+ var point = new Point(bestX ?? Math.Round(x / 4) * 4, bestY ?? Math.Round(y / 4) * 4);+ return Clamp(point, size);+ }++ public void KeepOnScreen(DeskWidgetWindow window)+ {+ var clamped = Clamp(new Point(window.Item.X, window.Item.Y), Desk.Dimensions(window.Item.Size));+ if (clamped.X != window.Item.X || clamped.Y != window.Item.Y)+ {+ window.MoveTo(clamped);+ Save();+ }+ }++ private static Point Clamp(Point point, Size size)+ {+ var left = SystemParameters.VirtualScreenLeft;+ var top = SystemParameters.VirtualScreenTop;+ var right = left + SystemParameters.VirtualScreenWidth;+ var bottom = top + SystemParameters.VirtualScreenHeight;+ return new Point(+ Math.Clamp(point.X, left, Math.Max(left, right - size.Width)),+ Math.Clamp(point.Y, top, Math.Max(top, bottom - size.Height)));+ }++ /// <summary>First free place, filling columns from the left below the widget bar.</summary>+ private Point FindSpot(Size size)+ {+ var area = SystemParameters.WorkArea;+ var startX = area.Left + 32;+ var startY = area.Top + 96;+ var taken = _layout.Items.Select(i => new Rect(i.X - Desk.Gap / 2, i.Y - Desk.Gap / 2,+ Desk.Dimensions(i.Size).Width + Desk.Gap, Desk.Dimensions(i.Size).Height + Desk.Gap)).ToList();+ const double Step = (Desk.StripHeight + Desk.Gap) / 2;+ for (var x = startX; x + size.Width <= area.Right - 32; x += Desk.Unit + Desk.Gap)+ {+ for (var y = startY; y + size.Height <= area.Bottom - 40; y += Step)+ {+ var rect = new Rect(x, y, size.Width, size.Height);+ if (!taken.Any(t => t.IntersectsWith(rect))) return new Point(x, y);+ }+ }+ return new Point(area.Left + (area.Width - size.Width) / 2, area.Top + (area.Height - size.Height) / 2);+ }++ /// <summary>A first layout so the feature shows itself; everything can be moved or removed.</summary>+ private void AddDefaults()+ {+ var area = SystemParameters.WorkArea;+ var x = area.Left + 32;+ var y = area.Top + 96;+ var step = Desk.Unit + Desk.Gap;+ void Put(string kind, DeskSize size, double left, double top) =>+ _layout.Items.Add(new DeskItem { Kind = kind, Size = size, X = left, Y = top });+ Put("analog", DeskSize.Small, x, y);+ Put("weather", DeskSize.Small, x + step, y);+ Put("calendar", DeskSize.Medium, x, y + step);+ Put("music", DeskSize.Strip, x, y + step * 2);+ Put("cpu", DeskSize.Mini, x, y + step * 2 + Desk.StripHeight + Desk.Gap);+ Put("ram", DeskSize.Mini, x + step, y + step * 2 + Desk.StripHeight + Desk.Gap);+ }++ public void Dispose()+ {+ _disposed = true;+ _saveTimer.Stop();+ _recreateTimer.Stop();+ DeskStore.Save(_layout);+ _gallery?.Close();+ foreach (var window in _windows.ToList())+ {+ window.ClosingByManager = true;+ window.Close();+ }+ _windows.Clear();+ }+}diff --git a/DesktopWidgets/DeskWidgetWindow.cs b/DesktopWidgets/DeskWidgetWindow.csnew file mode 100644index 0000000..018cc7c--- /dev/null+++ b/DesktopWidgets/DeskWidgetWindow.cs@@ -0,0 +1,364 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Input;+using System.Windows.Interop;+using System.Windows.Media;+using System.Windows.Media.Effects;+using System.Windows.Threading;++namespace QiDock.DesktopWidgets;++/// <summary>+/// One desktop widget in its own small window. The window is owned by the desktop (Progman), so it+/// sits just above the wallpaper, under every app window, and survives "Show desktop". It never+/// takes focus unless a text box inside it is clicked. Drag anywhere that is not a control to move it.+/// </summary>+internal sealed class DeskWidgetWindow : Window, IDeskHost+{+ public const double Shadow = 16;+ private readonly DeskWidgetManager _manager;+ private readonly Border _card;+ private readonly Border _shadow;+ private readonly DispatcherTimer _timer = new(DispatcherPriority.Background);+ private NativePoint? _press;+ private double _pressLeft, _pressTop;+ private bool _dragging;+ private bool _allowActivate;++ public DeskItem Item { get; }+ public DeskWidget Widget { get; }+ public DeskKind Kind { get; }+ public nint Handle { get; private set; }+ public bool IsLive { get; private set; }+ public bool ClosingByManager { get; set; }++ public DeskWidgetWindow(DeskWidgetManager manager, DeskItem item, DeskKind kind)+ {+ _manager = manager;+ Item = item;+ Kind = kind;+ Widget = kind.Create();+ Widget.Host = this;++ WindowStyle = WindowStyle.None;+ ResizeMode = ResizeMode.NoResize;+ AllowsTransparency = true;+ Background = Brushes.Transparent;+ ShowInTaskbar = false;+ ShowActivated = false;+ SizeToContent = SizeToContent.WidthAndHeight;+ WindowStartupLocation = WindowStartupLocation.Manual;+ UseLayoutRounding = true;+ SnapsToDevicePixels = true;+ Title = "QiDock Desktop Widget";+ SetResourceReference(FontFamilyProperty, "InterfaceFont");+ TextOptions.SetTextFormattingMode(this, TextFormattingMode.Ideal);++ // The shadow is a separate layer so content updates (a ticking clock) never re-render the blur.+ _shadow = new Border+ {+ CornerRadius = new CornerRadius(24),+ Background = DeskUi.CardFill,+ Effect = new DropShadowEffect { Color = Colors.Black, BlurRadius = 24, ShadowDepth = 5, Direction = 270, Opacity = 0.38, RenderingBias = RenderingBias.Performance }+ };+ _card = new Border+ {+ CornerRadius = new CornerRadius(24),+ Background = DeskUi.CardFill,+ BorderBrush = DeskUi.CardStroke,+ BorderThickness = new Thickness(1),+ Padding = new Thickness(14)+ };+ _card.SizeChanged += (_, e) => _card.Clip = new RectangleGeometry(new Rect(e.NewSize), 24, 24);+ var layers = new Grid { Margin = new Thickness(Shadow) };+ layers.Children.Add(_shadow);+ layers.Children.Add(_card);+ Content = layers;+ ApplySize();++ Left = item.X - Shadow;+ Top = item.Y - Shadow;++ _timer.Tick += (_, _) => Widget.Tick();+ PreviewMouseLeftButtonDown += OnPress;+ PreviewMouseMove += OnMove;+ PreviewMouseLeftButtonUp += OnRelease;+ MouseRightButtonUp += (_, e) =>+ {+ e.Handled = true;+ ShowMenu();+ };+ Deactivated += (_, _) => _allowActivate = false;+ Rebuild();+ }++ private void ApplySize()+ {+ var size = Desk.Dimensions(Item.Size);+ _card.Width = _shadow.Width = size.Width;+ _card.Height = _shadow.Height = size.Height;+ // Strips are short; keep their content from touching the edges but use the height.+ _card.Padding = Desk.Padding(Item.Size);+ }++ public void Rebuild()+ {+ _card.Child = Widget.Build();+ if (IsLive) Widget.Tick();+ }++ public void Save() => _manager.Save();++ /// <summary>Starts (visible) or pauses (covered by a window) the widget's timers and data feeds.</summary>+ public void SetLive(bool live)+ {+ if (IsLive == live) return;+ IsLive = live;+ if (live)+ {+ Widget.Attach();+ Widget.Tick();+ if (Widget.Interval is { } interval)+ {+ _timer.Interval = interval;+ _timer.Start();+ }+ }+ else+ {+ _timer.Stop();+ Widget.Detach();+ }+ }++ /// <summary>The widget's tick interval changed (a stopwatch started running).</summary>+ public void RestartTimer()+ {+ _timer.Stop();+ if (IsLive && Widget.Interval is { } interval)+ {+ _timer.Interval = interval;+ _timer.Start();+ }+ }++ public void ChangeSize(DeskSize size)+ {+ if (Item.Size == size) return;+ Item.Size = size;+ ApplySize();+ Rebuild();+ _manager.KeepOnScreen(this);+ Save();+ }++ public Rect Bounds => new(Item.X, Item.Y, Desk.Dimensions(Item.Size).Width, Desk.Dimensions(Item.Size).Height);++ public void FocusInput(IInputElement element)+ {+ _allowActivate = true;+ if (Handle != 0) SetForegroundWindow(Handle);+ Dispatcher.BeginInvoke(DispatcherPriority.Input, () => Keyboard.Focus(element));+ }++ private void ShowMenu()+ {+ var menu = new ContextMenu { PlacementTarget = this, Placement = PlacementMode.MousePoint };+ var title = new MenuItem { Header = Kind.Name, IsEnabled = false };+ if (Application.Current.TryFindResource("MenuSectionHeading") is Style heading) title.Style = heading;+ menu.Items.Add(title);+ if (Kind.Sizes.Length > 1)+ {+ var sizes = Entry("Boyut", "Size", "IconMaximize");+ foreach (var size in Kind.Sizes)+ {+ var entry = new MenuItem { Header = Desk.SizeName(size), IsChecked = size == Item.Size };+ var chosen = size;+ entry.Click += (_, _) => ChangeSize(chosen);+ sizes.Items.Add(entry);+ }+ menu.Items.Add(sizes);+ }+ var before = menu.Items.Count;+ Widget.AddMenuItems(menu);+ menu.Items.Add(new Separator());+ var add = Entry("Widget ekle…", "Add widget…", "IconPlus");+ add.Click += (_, _) => _manager.ShowGallery();+ menu.Items.Add(add);+ var remove = Entry("Masaüstünden kaldır", "Remove from desktop", "IconTrash");+ if (Application.Current.TryFindResource("DestructiveMenuItem") is Style destructive) remove.Style = destructive;+ remove.Click += (_, _) => _manager.Remove(this);+ menu.Items.Add(remove);+ menu.IsOpen = true;+ }++ private static MenuItem Entry(string tr, string en, string? icon)+ {+ var item = new MenuItem { Header = Desk.L(tr, en) };+ if (icon is not null && Application.Current.TryFindResource(icon) is Geometry geometry) item.Icon = geometry;+ return item;+ }++ private void OnPress(object sender, MouseButtonEventArgs e)+ {+ if (IsInteractive(e.OriginalSource as DependencyObject) || !GetCursorPos(out var cursor)) return;+ _press = cursor;+ _pressLeft = Left;+ _pressTop = Top;+ _dragging = false;+ }++ private void OnMove(object sender, MouseEventArgs e)+ {+ if (_press is not { } press) return;+ if (e.LeftButton != MouseButtonState.Pressed)+ {+ EndDrag();+ return;+ }+ if (!GetCursorPos(out var cursor)) return;+ var dx = cursor.X - press.X;+ var dy = cursor.Y - press.Y;+ if (!_dragging)+ {+ if (Math.Abs(dx) < 5 && Math.Abs(dy) < 5) return;+ _dragging = true;+ CaptureMouse();+ Opacity = 0.88;+ }+ var scale = DpiScale();+ Left = _pressLeft + dx / scale;+ Top = _pressTop + dy / scale;+ }++ private void OnRelease(object sender, MouseButtonEventArgs e)+ {+ if (_dragging) e.Handled = true;+ EndDrag();+ }++ private void EndDrag()+ {+ var moved = _dragging;+ _press = null;+ _dragging = false;+ if (!moved) return;+ ReleaseMouseCapture();+ Opacity = 1;+ var snapped = _manager.Snap(this, Left + Shadow, Top + Shadow);+ Item.X = snapped.X;+ Item.Y = snapped.Y;+ MoveTo(snapped);+ Save();+ }++ public void MoveTo(Point position)+ {+ Item.X = position.X;+ Item.Y = position.Y;+ Left = position.X - Shadow;+ Top = position.Y - Shadow;+ }++ private static bool IsInteractive(DependencyObject? node)+ {+ while (node is not null and not Window)+ {+ if (node is DeskButton or ButtonBase or System.Windows.Controls.Primitives.TextBoxBase or Slider or Thumb or ScrollBar or ComboBox) return true;+ node = node is Visual or System.Windows.Media.Media3D.Visual3D ? VisualTreeHelper.GetParent(node) : LogicalTreeHelper.GetParent(node);+ }+ return false;+ }++ private double DpiScale() => PresentationSource.FromVisual(this)?.CompositionTarget?.TransformToDevice.M11 ?? 1;++ protected override void OnSourceInitialized(EventArgs e)+ {+ base.OnSourceInitialized(e);+ if (PresentationSource.FromVisual(this) is not HwndSource source) return;+ Handle = source.Handle;+ source.AddHook(WindowProc);+ var style = GetWindowLongPtr(Handle, GwlExStyle).ToInt64();+ SetWindowLongPtr(Handle, GwlExStyle, new nint((style | WsExToolWindow | WsExNoActivate) & ~WsExAppWindow));+ AttachToDesktop();+ }++ /// <summary>Owned by the desktop window: above the wallpaper, below apps, kept by Win+D.</summary>+ public void AttachToDesktop()+ {+ var progman = FindWindow("Progman", null);+ if (Handle != 0 && progman != 0) SetWindowLongPtr(Handle, GwlpHwndParent, progman);+ }++ private IntPtr WindowProc(IntPtr hwnd, int message, IntPtr wParam, IntPtr lParam, ref bool handled)+ {+ const int WmMouseActivate = 0x0021;+ const int WmWindowPosChanging = 0x0046;+ const int MaNoActivate = 3;+ if (message == WmMouseActivate && !_allowActivate)+ {+ handled = true;+ return new IntPtr(MaNoActivate);+ }+ if (message == WmWindowPosChanging)+ {+ // Stay at the bottom of the z-order: clicks or activation must not lift the widget over apps.+ var pos = Marshal.PtrToStructure<WindowPos>(lParam);+ if ((pos.Flags & SwpNoZOrder) == 0)+ {+ pos.InsertAfter = HwndBottom;+ Marshal.StructureToPtr(pos, lParam, false);+ }+ }+ return IntPtr.Zero;+ }++ protected override void OnClosed(EventArgs e)+ {+ _timer.Stop();+ if (IsLive) Widget.Detach();+ IsLive = false;+ Widget.Dispose();+ base.OnClosed(e);+ if (!ClosingByManager) _manager.WindowLost(this);+ }++ private const int GwlExStyle = -20;+ private const int GwlpHwndParent = -8;+ private const long WsExToolWindow = 0x00000080;+ private const long WsExNoActivate = 0x08000000;+ private const long WsExAppWindow = 0x00040000;+ private const uint SwpNoZOrder = 0x0004;+ private static readonly IntPtr HwndBottom = new(1);++ [StructLayout(LayoutKind.Sequential)]+ private struct WindowPos+ {+ public IntPtr Window;+ public IntPtr InsertAfter;+ public int X, Y, Width, Height;+ public uint Flags;+ }++ [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", CharSet = CharSet.Unicode)]+ private static extern nint FindWindow(string className, string? windowName);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool SetForegroundWindow(nint window);++ [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/DesktopWidgets/Kinds/AiWidgets.cs b/DesktopWidgets/Kinds/AiWidgets.csnew file mode 100644index 0000000..9b0a9bc--- /dev/null+++ b/DesktopWidgets/Kinds/AiWidgets.cs@@ -0,0 +1,322 @@+using System.Diagnostics;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media;+using System.Windows.Media.Imaging;+using System.Windows.Threading;+using QiDock.Services;+using QiDock.Services.Notifications;+using QiDock.Services.Widgets;+using static QiDock.DesktopWidgets.DeskUi;++namespace QiDock.DesktopWidgets.Kinds;++/// <summary>An AI assistant on the desktop: its app (icon, name, colour) and, when known, its usage provider.</summary>+/// <param name="Plate">A light tile drawn behind an icon that is dark itself (Codex's black knot).</param>+internal sealed record AiAssistant(string Name, string AppId, string? UsageProvider, Color From, Color To, bool Plate = false)+{+ public static readonly AiAssistant Claude = new("Claude", "Claude_pzs8sxrjxfjjc!Claude", AiUsageService.ClaudeId,+ Color.FromRgb(0xE0, 0x86, 0x5F), Color.FromRgb(0xC1, 0x5F, 0x3C));+ public static readonly AiAssistant Codex = new("Codex", "OpenAI.Codex_2p2nqsd0c76g0!App", AiUsageService.CodexId,+ Color.FromRgb(0x5B, 0x8C, 0xFF), Color.FromRgb(0x2F, 0x5B, 0xD8), Plate: true);+ public static readonly AiAssistant Gemini = new("Gemini", "com.google.gemini.windows", null,+ Color.FromRgb(0x4F, 0x9B, 0xF5), Color.FromRgb(0xA4, 0x6B, 0xE8));++ public Brush Accent => new SolidColorBrush(From);++ public Brush Gradient => new LinearGradientBrush(From, To, new Point(0, 0), new Point(1, 1));++ private static readonly Dictionary<string, BitmapSource?> Icons = [];++ /// <summary>The app's own icon as Windows shows it in Start (null when the app is not installed).</summary>+ public BitmapSource? Icon()+ {+ if (!Icons.TryGetValue(AppId, out var icon)) Icons[AppId] = icon = NotificationApps.LoadIcon(AppId, 96);+ return icon;+ }++ public void Open()+ {+ try { Process.Start(new ProcessStartInfo("explorer.exe", @"shell:AppsFolder\" + AppId) { UseShellExecute = true })?.Dispose(); }+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)+ {+ Trace.TraceWarning("Could not open {0}: {1}", Name, ex.Message);+ }+ }+}++/// <summary>+/// Claude and Codex usage shared by every AI widget on the desktop: read once, every two minutes, only while one of+/// them is visible.+/// </summary>+internal sealed class AiUsageHub+{+ public static AiUsageHub Instance { get; } = new();++ private readonly AiUsageService _service = new();+ private readonly List<Action> _listeners = [];+ private readonly DispatcherTimer _timer = new(DispatcherPriority.Background) { Interval = TimeSpan.FromMinutes(2) };+ private bool _loading;++ public IReadOnlyList<ProviderUsage> Usage { get; private set; } = [];+ public bool Loaded { get; private set; }++ private AiUsageHub() => _timer.Tick += (_, _) => _ = RefreshAsync();++ public ProviderUsage? For(string provider) => Usage.FirstOrDefault(u => u.Provider == provider);++ public void Subscribe(Action listener)+ {+ _listeners.Add(listener);+ if (_listeners.Count == 1)+ {+ _timer.Start();+ _ = RefreshAsync();+ }+ listener();+ }++ public void Unsubscribe(Action listener)+ {+ _listeners.Remove(listener);+ if (_listeners.Count == 0) _timer.Stop();+ }++ private async Task RefreshAsync()+ {+ if (_loading) return;+ _loading = true;+ try { Usage = await _service.FetchAsync(false, CancellationToken.None); }+ catch (Exception ex) when (ex is System.Net.Http.HttpRequestException or TaskCanceledException or System.IO.IOException)+ {+ Trace.TraceWarning("AI usage refresh failed: {0}", ex.Message);+ }+ finally+ {+ _loading = false;+ Loaded = true;+ }+ foreach (var listener in _listeners.ToList()) listener();+ }+}++/// <summary>+/// One AI assistant on the desktop with its own icon and colour. Claude and Codex show how much of their usage limits+/// is spent and when it resets; Gemini (which keeps no usage on this PC) opens the app. The icon opens the app.+/// </summary>+internal sealed class AiAssistantWidget(AiAssistant assistant) : DeskWidget+{+ private readonly List<(TextBlock Label, TextBlock Value, Border Fill, Grid Bar, TextBlock Reset)> _rows = [];+ private TextBlock? _headline, _status;+ private RingGauge? _ring;++ private bool HasUsage => assistant.UsageProvider is not null;++ public override FrameworkElement Build()+ {+ _rows.Clear();+ _headline = null;+ _status = null;+ _ring = null;+ return HasUsage ? BuildUsage() : BuildLauncher();+ }++ private FrameworkElement AppIcon(double size)+ {+ FrameworkElement picture;+ if (assistant.Icon() is { } icon)+ {+ var image = new Image { Source = icon, Width = assistant.Plate ? size * 0.72 : size, Height = assistant.Plate ? size * 0.72 : size };+ RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality);+ picture = assistant.Plate+ ? new Border { Width = size, Height = size, CornerRadius = new CornerRadius(size * 0.26), Background = Brushes.White, Child = image }+ : image;+ }+ else+ {+ var letter = T(assistant.Name[..1], size * 0.5, FontWeights.Bold, Brushes.White);+ letter.HorizontalAlignment = HorizontalAlignment.Center;+ letter.VerticalAlignment = VerticalAlignment.Center;+ picture = new Border { Width = size, Height = size, CornerRadius = new CornerRadius(size * 0.28), Background = assistant.Gradient, Child = letter };+ }+ var button = new DeskButton(picture, assistant.Open, double.NaN, null, size * 0.28) { ToolTip = Desk.L($"{assistant.Name} uygulamasını aç", $"Open {assistant.Name}") };+ button.VerticalAlignment = VerticalAlignment.Center;+ return button;+ }++ private TextBlock Name(double size) => T(assistant.Name, size, FontWeights.SemiBold);++ // ---- Claude and Codex: usage limits --------------------------------------------------------++ private FrameworkElement BuildUsage()+ {+ _status = T("", 11, FontWeights.SemiBold, Secondary);+ _status.TextTrimming = TextTrimming.CharacterEllipsis;+ switch (Size)+ {+ case DeskSize.Mini:+ {+ _ring = new RingGauge { Width = 50, Height = 50, Thickness = 5, Stroke = assistant.Accent };+ var host = new Grid();+ host.Children.Add(_ring);+ var icon = AppIcon(26);+ icon.HorizontalAlignment = HorizontalAlignment.Center;+ host.Children.Add(icon);+ _headline = Digits("", 20, FontWeights.Bold);+ var grid = Grid(columns: "Auto,*");+ grid.Children.Add(host);+ grid.Children.Add(At(Margin(Column(_headline, Name(12)), 12), 0, 1));+ return grid;+ }+ case DeskSize.Small:+ {+ var header = Grid(columns: "Auto,*");+ header.Children.Add(AppIcon(30));+ header.Children.Add(At(Margin(Column(Name(14), _status), 9), 0, 1));+ var grid = Grid("Auto,*");+ grid.Children.Add(header);+ var rows = Column(UsageRow(), Margin(UsageRow(), 0, 10));+ rows.VerticalAlignment = VerticalAlignment.Bottom;+ grid.Children.Add(At(rows, 1));+ return grid;+ }+ case DeskSize.Strip:+ {+ // A thin strip: the icon, then the two limits side by side.+ var grid = Grid(columns: "Auto,*,14,*");+ var icon = AppIcon(38);+ icon.ToolTip = assistant.Name;+ grid.Children.Add(icon);+ grid.Children.Add(At(Margin(UsageRow(), 14), 0, 1));+ grid.Children.Add(At(UsageRow(), 0, 3));+ return grid;+ }+ default:+ {+ var header = Grid(columns: "Auto,*");+ header.Children.Add(AppIcon(34));+ header.Children.Add(At(Margin(Column(Name(15), _status), 10), 0, 1));+ var grid = Grid("Auto,*");+ grid.Children.Add(header);+ var rows = Column(UsageRow(), Margin(UsageRow(), 0, 12));+ rows.VerticalAlignment = VerticalAlignment.Bottom;+ grid.Children.Add(At(rows, 1));+ return grid;+ }+ }+ }++ private FrameworkElement UsageRow()+ {+ var label = T("", 11.5, FontWeights.SemiBold, Secondary);+ var reset = T("", 10.5, brush: Tertiary);+ reset.TextTrimming = TextTrimming.CharacterEllipsis;+ reset.Margin = new Thickness(6, 0, 6, 0);+ reset.VerticalAlignment = VerticalAlignment.Center;+ var value = Digits("", 12.5, FontWeights.Bold);+ var fill = new Border { CornerRadius = new CornerRadius(3), Background = assistant.Gradient, HorizontalAlignment = HorizontalAlignment.Left, Width = 0 };+ var bar = new Grid { Height = 6, Margin = new Thickness(0, 5, 0, 0) };+ bar.Children.Add(new Border { CornerRadius = new CornerRadius(3), Background = Track });+ bar.Children.Add(fill);+ bar.SizeChanged += (_, _) => Tick();+ var top = Grid(columns: "Auto,*,Auto");+ top.Children.Add(label);+ top.Children.Add(At(reset, 0, 1));+ top.Children.Add(At(value, 0, 2));+ _rows.Add((label, value, fill, bar, reset));+ return Column(top, bar);+ }++ protected override void OnAttach()+ {+ if (HasUsage) AiUsageHub.Instance.Subscribe(Tick);+ }++ protected override void OnDetach()+ {+ if (HasUsage) AiUsageHub.Instance.Unsubscribe(Tick);+ }++ public override TimeSpan? Interval => HasUsage ? TimeSpan.FromMinutes(1) : null; // "2 sa 10 dk sonra" counts down++ public override void Tick()+ {+ if (!HasUsage) return;+ var hub = AiUsageHub.Instance;+ var usage = hub.For(assistant.UsageProvider!);+ var windows = usage?.Windows.Take(2).ToList() ?? [];+ var status = usage switch+ {+ null when !hub.Loaded => Desk.L("Okunuyor…", "Loading…"),+ null => Desk.L("Kullanım bilgisi bulunamadı", "No usage found"),+ { Error: { } error } => error,+ { Plan: { Length: > 0 } plan } => plan,+ _ => Desk.L("Kullanım sınırları", "Usage limits")+ };+ if (_status is not null) _status.Text = status;+ if (_headline is not null) _headline.Text = windows.Count > 0 ? Percent(windows[0].UsedPercent) : "—";+ if (_ring is not null) _ring.Value = windows.Count > 0 ? windows[0].UsedPercent : 0;+ for (var i = 0; i < _rows.Count; i++)+ {+ var (label, value, fill, bar, reset) = _rows[i];+ var window = i < windows.Count ? windows[i] : null;+ label.Text = window?.Label ?? (i == 0 ? UiText.Get("AiSession") : UiText.Get("AiWeekly"));+ value.Text = window is null ? "—" : Percent(window.UsedPercent);+ value.Foreground = window is { UsedPercent: >= 85 } ? Red : window is { UsedPercent: >= 70 } ? Orange : Text;+ var width = bar.ActualWidth > 0 ? bar.ActualWidth : 0;+ fill.Width = window is null || width <= 0 ? 0 : Math.Max(6, width * Math.Clamp(window.UsedPercent, 0, 100) / 100);+ fill.Background = window is { UsedPercent: >= 85 } ? Red : assistant.Gradient;+ reset.Text = window?.ResetsAt is { } at ? "↻ " + QiDock.Widgets.AiLimitsWidget.Remaining(at - DateTime.Now) : "";+ reset.ToolTip = window?.ResetsAt is { } when ? UiText.Format("AiResetsShort", QiDock.Widgets.AiLimitsWidget.Remaining(when - DateTime.Now)) : null;+ }+ }++ // ---- Gemini: the app ------------------------------------------------------------------------++ private FrameworkElement BuildLauncher()+ {+ var open = new DeskButton(Margin(T(Desk.L("Sohbet başlat", "Start a chat"), 12, FontWeights.SemiBold, Brushes.White), 14, 0, 14), assistant.Open, double.NaN, assistant.Gradient, 14)+ {+ Height = 28,+ HorizontalAlignment = HorizontalAlignment.Left+ };+ ((FrameworkElement)open.Child).VerticalAlignment = VerticalAlignment.Center;+ var subtitle = T(Desk.L("Google’ın yapay zekâsı", "Google’s AI assistant"), 11, FontWeights.SemiBold, Secondary);+ switch (Size)+ {+ case DeskSize.Mini:+ {+ var grid = Grid(columns: "Auto,*");+ grid.Children.Add(AppIcon(40));+ grid.Children.Add(At(Margin(Column(Name(15), T(Desk.L("Aç", "Open"), 11.5, FontWeights.SemiBold, Secondary)), 12), 0, 1));+ return grid;+ }+ case DeskSize.Small:+ {+ var grid = Grid("*,Auto");+ var top = Column(AppIcon(52), Margin(Name(15), 0, 8), subtitle);+ top.HorizontalAlignment = HorizontalAlignment.Left;+ top.VerticalAlignment = VerticalAlignment.Top;+ grid.Children.Add(top);+ grid.Children.Add(At(open, 1));+ return grid;+ }+ case DeskSize.Strip:+ {+ var grid = Grid(columns: "Auto,*,Auto");+ grid.Children.Add(AppIcon(42));+ grid.Children.Add(At(Margin(Column(Name(15), Margin(subtitle, 0, 1)), 12), 0, 1));+ open.VerticalAlignment = VerticalAlignment.Center;+ grid.Children.Add(At(open, 0, 2));+ return grid;+ }+ default:+ {+ var grid = Grid(columns: "Auto,*");+ grid.Children.Add(AppIcon(64));+ grid.Children.Add(At(Margin(Column(Name(16), Margin(subtitle, 0, 2), Margin(open, 0, 10)), 16), 0, 1));+ return grid;+ }+ }+ }+}diff --git a/DesktopWidgets/Kinds/MusicWidget.cs b/DesktopWidgets/Kinds/MusicWidget.csnew file mode 100644index 0000000..56daaa6--- /dev/null+++ b/DesktopWidgets/Kinds/MusicWidget.cs@@ -0,0 +1,195 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media;+using System.Windows.Media.Effects;+using static QiDock.DesktopWidgets.DeskUi;++namespace QiDock.DesktopWidgets.Kinds;++/// <summary>Now playing from any app with a media session (Spotify, browsers, Media Player).</summary>+internal sealed class MusicWidget : DeskWidget+{+ private Border? _root;+ private TextBlock? _title, _artist, _elapsed, _total;+ private Border? _progressFill;+ private Grid? _progress;+ private DeskButton? _play;+ private string? _shownKey;++ public override TimeSpan? Interval => TimeSpan.FromSeconds(1);++ public override FrameworkElement Build()+ {+ _shownKey = null;+ var padding = Desk.Padding(Size);+ _root = new Border { Margin = new Thickness(-padding.Left, -padding.Top, -padding.Right, -padding.Bottom), Padding = padding };+ Render();+ return _root;+ }++ protected override void OnAttach()+ {+ MediaHub.Instance.Subscribe(Render);+ Render();+ }+ protected override void OnDetach() => MediaHub.Instance.Unsubscribe(Render);++ private void Render()+ {+ if (_root is null) return;+ var hub = MediaHub.Instance;+ var key = hub.HasMedia ? $"{hub.Title}|{hub.Artist}|{hub.Art?.GetHashCode()}" : "";+ if (key != _shownKey)+ {+ _shownKey = key;+ _root.Background = hub.HasMedia ? Tint(hub.ArtColor) : null;+ _root.Child = hub.HasMedia ? Layout(hub) : Idle();+ }+ Tick();+ }++ private static Brush Tint(Color c)+ {+ static Color Scale(Color color, double f) => Color.FromRgb((byte)(color.R * f), (byte)(color.G * f), (byte)(color.B * f));+ var brush = new LinearGradientBrush(Scale(c, 0.55), Scale(c, 0.22), new Point(0, 0), new Point(1, 1));+ brush.Freeze();+ return brush;+ }++ private FrameworkElement Idle()+ {+ _title = _artist = _elapsed = _total = null;+ _progress = null;+ _play = null;+ return Empty("IconMusic", Size is DeskSize.Mini or DeskSize.Strip ? Desk.L("Çalan bir şey yok", "Nothing playing") : Desk.L("Şu an bir şey çalmıyor.\nSpotify ya da tarayıcıda müzik açın.", "Nothing is playing.\nStart music in Spotify or a browser."));+ }++ private FrameworkElement Art(MediaHub hub, double size, double radius)+ {+ var border = new Border { Width = size, Height = size, CornerRadius = new CornerRadius(radius), Background = Inset };+ if (hub.Art is { } art)+ border.Background = new ImageBrush(art) { Stretch = Stretch.UniformToFill };+ else+ border.Child = DeskUi.Icon("IconMusic", size * 0.36, Secondary);+ border.Effect = size >= 100 ? new DropShadowEffect { BlurRadius = 16, ShadowDepth = 3, Direction = 270, Opacity = 0.4, RenderingBias = RenderingBias.Performance } : null;+ return border;+ }++ private FrameworkElement Controls(double size)+ {+ _play = DeskButton.Round("GlyphPlay", () => MediaHub.Instance.Command(s => s.TryTogglePlayPauseAsync()), size, Brushes.White, Brushes.Black, size * 0.38);+ var previous = new DeskButton(Glyph("GlyphPrevious", size * 0.34), () => MediaHub.Instance.Command(s => s.TrySkipPreviousAsync()), size * 0.86);+ var next = new DeskButton(Glyph("GlyphNext", size * 0.34), () => MediaHub.Instance.Command(s => s.TrySkipNextAsync()), size * 0.86);+ return Row(previous, Margin(_play, 4, 0, 4), next);+ }++ private FrameworkElement ProgressBar(bool times)+ {+ _progressFill = new Border { CornerRadius = new CornerRadius(2), Background = Brushes.White, HorizontalAlignment = HorizontalAlignment.Left };+ _progress = new Grid { Height = 4 };+ _progress.Children.Add(new Border { CornerRadius = new CornerRadius(2), Background = Ui("#40FFFFFF") });+ _progress.Children.Add(_progressFill);+ if (!times)+ {+ _elapsed = _total = null;+ return _progress;+ }+ _elapsed = Digits("", 11, FontWeights.SemiBold, Ui("#B3FFFFFF"));+ _total = Digits("", 11, FontWeights.SemiBold, Ui("#B3FFFFFF"));+ var labels = Grid(columns: "*,Auto");+ labels.Children.Add(_elapsed);+ labels.Children.Add(At(_total, 0, 1));+ labels.Margin = new Thickness(0, 4, 0, 0);+ return Column(_progress, labels);+ }++ private static Brush Ui(string hex) => QiDock.Widgets.Ui.Solid(hex);++ private FrameworkElement Layout(MediaHub hub)+ {+ _title = T(hub.Title, 14, FontWeights.SemiBold, Brushes.White);+ _artist = T(hub.Artist, 12.5, FontWeights.Medium, Ui("#C8FFFFFF"));+ switch (Size)+ {+ case DeskSize.Mini:+ {+ _title.FontSize = 12.5;+ var grid = Grid(columns: "Auto,*,Auto");+ grid.Children.Add(Art(hub, 48, 10));+ grid.Children.Add(At(Margin(Column(_title, _artist), 10, 0, 6), 0, 1));+ _artist.FontSize = 11;+ _play = DeskButton.Round("GlyphPlay", () => MediaHub.Instance.Command(s => s.TryTogglePlayPauseAsync()), 32, Brushes.White, Brushes.Black, 12);+ grid.Children.Add(At(_play, 0, 2));+ _progress = null;+ return grid;+ }+ case DeskSize.Strip:+ {+ var grid = Grid(columns: "Auto,*,Auto");+ grid.Children.Add(Art(hub, 54, 11));+ var text = Column(_title, _artist, Margin(ProgressBar(false), 0, 7, 8, 0));+ grid.Children.Add(At(Margin(text, 12, 0, 8), 0, 1));+ grid.Children.Add(At(Controls(34), 0, 2));+ return grid;+ }+ case DeskSize.Small:+ {+ var grid = Grid("*,Auto,Auto,Auto");+ var art = Art(hub, 70, 12);+ art.HorizontalAlignment = HorizontalAlignment.Left;+ grid.Children.Add(art);+ grid.Children.Add(At(_title, 1));+ grid.Children.Add(At(_artist, 2));+ _play = DeskButton.Round("GlyphPlay", () => MediaHub.Instance.Command(s => s.TryTogglePlayPauseAsync()), 34, Brushes.White, Brushes.Black, 13);+ _play.HorizontalAlignment = HorizontalAlignment.Right;+ _play.VerticalAlignment = VerticalAlignment.Top;+ grid.Children.Add(_play);+ grid.Children.Add(At(Margin(ProgressBar(false), 0, 8), 3));+ return grid;+ }+ case DeskSize.Medium:+ {+ var grid = Grid(columns: "Auto,*");+ grid.Children.Add(Art(hub, 130, 14));+ var app = T(hub.App, 11.5, FontWeights.SemiBold, Ui("#A6FFFFFF"));+ _title.FontSize = 16;+ var controls = Controls(38);+ controls.HorizontalAlignment = HorizontalAlignment.Center;+ var right = Grid("Auto,Auto,Auto,*,Auto,Auto");+ right.Children.Add(app);+ right.Children.Add(At(_title, 1));+ right.Children.Add(At(_artist, 2));+ right.Children.Add(At(ProgressBar(true), 4));+ right.Children.Add(At(Margin(controls, 0, 4), 5));+ grid.Children.Add(At(Margin(right, 14), 0, 1));+ return grid;+ }+ default:+ {+ _title.FontSize = 18;+ _title.HorizontalAlignment = HorizontalAlignment.Center;+ _artist.HorizontalAlignment = HorizontalAlignment.Center;+ var art = Art(hub, 168, 18);+ art.HorizontalAlignment = HorizontalAlignment.Center;+ var controls = Controls(44);+ controls.HorizontalAlignment = HorizontalAlignment.Center;+ return Column(art, Margin(_title, 0, 14), _artist, Margin(ProgressBar(true), 0, 12), Margin(controls, 0, 6));+ }+ }+ }++ public override void Tick()+ {+ var hub = MediaHub.Instance;+ if (_play is not null) _play.Child = Glyph(hub.Playing ? "GlyphPause" : "GlyphPlay", _play.Width * 0.38, Brushes.Black);+ if (_progress is null || _progressFill is null) return;+ var duration = hub.Duration;+ var position = hub.LivePosition;+ var fraction = duration > TimeSpan.Zero ? Math.Clamp(position / duration, 0, 1) : 0;+ _progressFill.Width = (_progress.ActualWidth > 0 ? _progress.ActualWidth : 200) * fraction;+ if (_elapsed is not null) _elapsed.Text = Format(position);+ if (_total is not null) _total.Text = duration > TimeSpan.Zero ? "-" + Format(duration - position) : "";+ }++ private static string Format(TimeSpan t) => $"{(int)t.TotalMinutes}:{t.Seconds:00}";+}diff --git a/DesktopWidgets/Kinds/ProductivityWidgets.cs b/DesktopWidgets/Kinds/ProductivityWidgets.csnew file mode 100644index 0000000..c6f96a4--- /dev/null+++ b/DesktopWidgets/Kinds/ProductivityWidgets.cs@@ -0,0 +1,651 @@+using System.Globalization;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services.Widgets;+using FocusTimer = QiDock.Services.FocusTimer;+using static QiDock.DesktopWidgets.DeskUi;++namespace QiDock.DesktopWidgets.Kinds;++/// <summary>Transparent text box that fits the dark cards.</summary>+internal static class DeskInput+{+ public static TextBox Box(string hint, double size = 13, bool multiline = false)+ {+ var box = new TextBox+ {+ FontSize = size,+ Foreground = Text,+ CaretBrush = Text,+ SelectionBrush = Blue,+ Background = Brushes.Transparent,+ BorderThickness = new Thickness(0),+ Padding = new Thickness(0),+ VerticalContentAlignment = VerticalAlignment.Center,+ AcceptsReturn = multiline,+ TextWrapping = multiline ? TextWrapping.Wrap : TextWrapping.NoWrap,+ Tag = hint+ };+ if (multiline) box.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;+ return box;+ }++ /// <summary>A text box with a grey hint behind it while empty.</summary>+ public static Grid WithHint(TextBox box)+ {+ var hint = T(box.Tag as string ?? "", box.FontSize, brush: Tertiary);+ hint.IsHitTestVisible = false;+ hint.VerticalAlignment = box.AcceptsReturn ? VerticalAlignment.Top : VerticalAlignment.Center;+ hint.Margin = new Thickness(2, 0, 0, 0);+ box.TextChanged += (_, _) => hint.Visibility = box.Text.Length == 0 ? Visibility.Visible : Visibility.Collapsed;+ hint.Visibility = box.Text.Length == 0 ? Visibility.Visible : Visibility.Collapsed;+ var grid = new Grid();+ grid.Children.Add(hint);+ grid.Children.Add(box);+ return grid;+ }++ /// <summary>Clicking the box gives the widget window the keyboard (widgets never take focus otherwise).</summary>+ public static void Focusable(TextBox box, IDeskHost host) =>+ box.PreviewMouseLeftButtonDown += (_, _) => host.FocusInput(box);++ /// <summary>Rounded inset field (search boxes, the to-do input).</summary>+ public static Border Field(UIElement content, double height = 34) => new()+ {+ Height = height,+ CornerRadius = new CornerRadius(height / 2),+ Background = Inset,+ Padding = new Thickness(14, 0, 6, 0),+ Child = content+ };+}++/// <summary>To-do list shared with the bar's to-do widget.</summary>+internal sealed class TodoDeskWidget : DeskWidget+{+ private bool _adding;+ private bool _refocus;++ private static IReadOnlyList<TodoItem> Items => Desk.Settings().Todos ?? [];++ public override FrameworkElement Build()+ {+ var items = Items.Where(t => !t.Done).Concat(Items.Where(t => t.Done)).ToList();+ var capacity = Size switch { DeskSize.Strip => 3, DeskSize.Small => 4, DeskSize.Medium => 3, _ => 10 };+ var withHeader = Size is DeskSize.Small or DeskSize.Medium or DeskSize.Large;+ var withInput = Size is DeskSize.Medium or DeskSize.Large || _adding;+ if (_adding && Size is DeskSize.Strip or DeskSize.Small) capacity -= 1;++ var stack = new StackPanel();+ if (withHeader)+ {+ var open = Items.Count(t => !t.Done);+ var header = Grid(columns: "*,Auto");+ header.Children.Add(T(Desk.L("Yapılacaklar", "To-do"), 14, FontWeights.SemiBold, Blue));+ var count = Digits(open.ToString(CultureInfo.InvariantCulture), 14, FontWeights.SemiBold, Secondary);+ header.Children.Add(At(count, 0, 1));+ header.Margin = new Thickness(0, 0, 0, 6);+ stack.Children.Add(header);+ }+ if (withInput) stack.Children.Add(Input());+ foreach (var item in items.Take(capacity)) stack.Children.Add(Row(item));+ if (items.Count == 0 && !withInput)+ stack.Children.Add(T(Desk.L("Liste boş. Sağ tık → Görev ekle", "Empty. Right-click → Add task"), 12.5, brush: Secondary));+ else if (items.Count > capacity)+ stack.Children.Add(T(Desk.L($"+{items.Count - capacity} görev daha", $"+{items.Count - capacity} more"), 11.5, FontWeights.SemiBold, Secondary));+ stack.VerticalAlignment = Size == DeskSize.Strip ? VerticalAlignment.Center : VerticalAlignment.Top;+ return stack;+ }++ private FrameworkElement Row(TodoItem item)+ {+ var size = Size == DeskSize.Strip ? 12.5 : 13.5;+ UIElement mark = item.Done+ ? new Border { Width = 15, Height = 15, CornerRadius = new CornerRadius(7.5), Background = Blue, Child = DeskUi.Icon("IconCheck", 9, Brushes.White, 2.4) }+ : new Border { Width = 15, Height = 15, CornerRadius = new CornerRadius(7.5), BorderBrush = Secondary, BorderThickness = new Thickness(1.5) };+ var toggle = new DeskButton(mark, () => Toggle(item), 22);+ var text = T(item.Text, size, FontWeights.Medium, item.Done ? Tertiary : Text);+ if (item.Done) text.TextDecorations = TextDecorations.Strikethrough;+ var remove = new DeskButton(DeskUi.Icon("IconClose", 9, Tertiary), () => Remove(item), 20) { Opacity = 0 };+ var grid = Grid(columns: "Auto,*,Auto");+ grid.Children.Add(toggle);+ grid.Children.Add(At(Margin(text, 6), 0, 1));+ grid.Children.Add(At(remove, 0, 2));+ grid.Background = Brushes.Transparent;+ grid.MouseEnter += (_, _) => remove.Opacity = 1;+ grid.MouseLeave += (_, _) => remove.Opacity = 0;+ grid.Margin = new Thickness(-3, Size == DeskSize.Strip ? 0 : 1, 0, Size == DeskSize.Strip ? 0 : 1);+ return grid;+ }++ private FrameworkElement Input()+ {+ var box = DeskInput.Box(Desk.L("Yeni görev…", "New task…"), 13);+ DeskInput.Focusable(box, Host);+ box.KeyDown += (_, e) =>+ {+ if (e.Key == Key.Escape && _adding)+ {+ _adding = false;+ Host.Rebuild();+ }+ if (e.Key != Key.Enter || string.IsNullOrWhiteSpace(box.Text)) return;+ var text = box.Text.Trim();+ Desk.UpdateSettings(s => s with { Todos = [.. s.Todos ?? [], new TodoItem(text)] }); // same order as the bar list+ _adding = false;+ _refocus = Size is DeskSize.Medium or DeskSize.Large;+ Host.Rebuild();+ };+ var field = DeskInput.Field(DeskInput.WithHint(box), Size == DeskSize.Strip ? 26 : 30);+ field.Margin = new Thickness(0, 0, 0, 6);+ if (_adding || _refocus)+ {+ _refocus = false;+ Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => Host.FocusInput(box));+ }+ return field;+ }++ private void Toggle(TodoItem item)+ {+ Desk.UpdateSettings(s =>+ {+ var list = (s.Todos ?? []).ToList();+ var index = list.IndexOf(item);+ if (index >= 0) list[index] = item with { Done = !item.Done };+ return s with { Todos = list };+ });+ Host.Rebuild();+ }++ private void Remove(TodoItem item)+ {+ Desk.UpdateSettings(s => s with { Todos = (s.Todos ?? []).Where(t => !Equals(t, item)).ToList() });+ Host.Rebuild();+ }++ public override void SettingsChanged() => Host.Rebuild();++ public override void AddMenuItems(ItemsControl menu)+ {+ menu.Items.Add(MenuEntry(Desk.L("Görev ekle", "Add task"), () =>+ {+ _adding = true;+ Host.Rebuild();+ }));+ if (Items.Any(t => t.Done))+ menu.Items.Add(MenuEntry(Desk.L("Tamamlananları temizle", "Clear completed"), () =>+ {+ Desk.UpdateSettings(s => s with { Todos = (s.Todos ?? []).Where(t => !t.Done).ToList() });+ Host.Rebuild();+ }));+ }+}++/// <summary>Sticky note; the text is kept with the widget.</summary>+internal sealed class NotesWidget : DeskWidget+{+ private readonly DispatcherTimer _save = new(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(700) };+ private TextBox? _box;++ public NotesWidget()+ {+ _save.Tick += (_, _) =>+ {+ _save.Stop();+ if (_box is not null) SetOption("text", _box.Text);+ };+ }++ private Brush Accent => (Option("color") ?? "yellow") switch+ {+ "blue" => Blue,+ "green" => Green,+ "pink" => Pink,+ "purple" => Purple,+ _ => Yellow+ };++ public override FrameworkElement Build()+ {+ var header = Row(new Border { Width = 10, Height = 10, CornerRadius = new CornerRadius(5), Background = Accent }, Margin(T(Desk.L("Not", "Note"), 13, FontWeights.SemiBold, Accent), 8));+ header.Margin = new Thickness(0, 0, 0, 8);+ _box = DeskInput.Box(Desk.L("Bir şeyler yazın…", "Write something…"), Size == DeskSize.Small ? 13 : 14, multiline: true);+ _box.Text = Option("text") ?? "";+ _box.VerticalContentAlignment = VerticalAlignment.Top;+ DeskInput.Focusable(_box, Host);+ _box.TextChanged += (_, _) =>+ {+ _save.Stop();+ _save.Start();+ };+ var grid = Grid("Auto,*");+ grid.Children.Add(header);+ grid.Children.Add(At(DeskInput.WithHint(_box), 1));+ return grid;+ }++ public override void AddMenuItems(ItemsControl menu)+ {+ var colors = new MenuItem { Header = Desk.L("Renk", "Color") };+ foreach (var (key, tr, en) in new[] { ("yellow", "Sarı", "Yellow"), ("blue", "Mavi", "Blue"), ("green", "Yeşil", "Green"), ("pink", "Pembe", "Pink"), ("purple", "Mor", "Purple") })+ colors.Items.Add(MenuEntry(Desk.L(tr, en), () =>+ {+ SetOption("color", key == "yellow" ? null : key);+ Host.Rebuild();+ }, (Option("color") ?? "yellow") == key));+ menu.Items.Add(colors);+ menu.Items.Add(MenuEntry(Desk.L("Notu temizle", "Clear note"), () =>+ {+ SetOption("text", null);+ Host.Rebuild();+ }));+ }++ public override void Dispose()+ {+ if (_save.IsEnabled && _box is not null) Host.Item.Options["text"] = _box.Text;+ _save.Stop();+ base.Dispose();+ }+}++/// <summary>This week, today's date and events from the iCal feed in the widget settings.</summary>+internal sealed class CalendarDeskWidget : DeskWidget+{+ private Border? _root;+ private DateTime _builtFor;++ public override TimeSpan? Interval => TimeSpan.FromMinutes(1);++ public override FrameworkElement Build()+ {+ _root = new Border();+ Render();+ return _root;+ }++ protected override void OnAttach()+ {+ CalendarHub.Instance.Subscribe(Render);+ if (Size == DeskSize.Strip) WeatherHub.Instance.Subscribe(Render);+ Render();+ }++ protected override void OnDetach()+ {+ CalendarHub.Instance.Unsubscribe(Render);+ WeatherHub.Instance.Unsubscribe(Render);+ }++ public override void Tick()+ {+ if (_builtFor.Date != DateTime.Today || DateTime.Now.Minute % 5 == 0) Render();+ }++ private void Render()+ {+ if (_root is null) return;+ _builtFor = DateTime.Now;+ _root.Child = Size switch+ {+ DeskSize.Strip => Week(),+ DeskSize.Small => Today(3, compact: true),+ DeskSize.Medium => TodayWide(),+ _ => Month()+ };+ }++ private static IReadOnlyList<CalendarOccurrence> Upcoming(int count)+ {+ var now = DateTime.Now;+ return CalendarHub.Instance.Between(now.Date, now.Date.AddDays(7))+ .Where(o => o.End > now || o.AllDay && o.Start.Date >= now.Date)+ .OrderBy(o => o.Start)+ .Take(count)+ .ToList();+ }++ private static readonly Brush[] EventColors = [Blue, Purple, Orange, Green, Pink];++ private static FrameworkElement EventRow(CalendarOccurrence occurrence, int index, bool showDay)+ {+ var bar = new Border { Width = 3.5, CornerRadius = new CornerRadius(2), Background = EventColors[index % EventColors.Length], Margin = new Thickness(0, 1, 8, 1) };+ var title = T(occurrence.Title, 13, FontWeights.SemiBold);+ var culture = Desk.Culture;+ var day = occurrence.Start.Date == DateTime.Today ? "" : occurrence.Start.Date == DateTime.Today.AddDays(1) ? Desk.L("Yarın ", "Tomorrow ") : occurrence.Start.ToString("ddd ", culture);+ var when = occurrence.AllDay ? Desk.L("Tüm gün", "All day") : $"{occurrence.Start:HH:mm} – {occurrence.End:HH:mm}";+ var time = T((showDay ? day : "") + when, 11.5, FontWeights.SemiBold, Secondary);+ var grid = Grid(columns: "Auto,*");+ grid.Children.Add(bar);+ grid.Children.Add(At(Column(title, time), 0, 1));+ grid.Margin = new Thickness(0, 0, 0, 7);+ return grid;+ }++ private static FrameworkElement NoEvents()+ {+ var text = CalendarHub.Instance.HasFeed+ ? Desk.L("Yaklaşan etkinlik yok", "No upcoming events")+ : Desk.L("Etkinlikler için Ayarlar → Widget’lar bölümünden iCal adresi ekleyin", "Add an iCal address in Settings → Widgets for events");+ var block = T(text, 12, brush: Secondary);+ block.TextWrapping = TextWrapping.Wrap;+ return block;+ }++ private FrameworkElement Week()+ {+ var today = DateTime.Today;+ var culture = Desk.Culture;+ var header = Grid(columns: "*,Auto");+ header.Children.Add(T(today.ToString("MMMM", culture), 12.5, FontWeights.SemiBold, Secondary));+ if (WeatherHub.Instance.Report is { } r)+ {+ var weather = Row(QiDock.Widgets.WeatherArt.Create(r.Code, r.IsDay, 16), Margin(T(WeatherHub.Temp(r.Temperature), 12.5, FontWeights.SemiBold), 4));+ header.Children.Add(At(weather, 0, 1));+ }+ var days = Grid(columns: "*,*,*,*,*,*,*");+ for (var i = 0; i < 7; i++)+ {+ var day = today.AddDays(i);+ var isToday = i == 0;+ var name = T(day.ToString("ddd", culture), 10.5, FontWeights.SemiBold, isToday ? Brushes.White : Secondary);+ var number = Digits(day.Day.ToString(CultureInfo.InvariantCulture), 15, FontWeights.SemiBold, isToday ? Brushes.White : Text);+ name.HorizontalAlignment = number.HorizontalAlignment = HorizontalAlignment.Center;+ var cell = new Border+ {+ CornerRadius = new CornerRadius(9),+ Background = isToday ? Blue : Brushes.Transparent,+ Margin = new Thickness(2, 0, 2, 0),+ Padding = new Thickness(0, 1, 0, 2),+ Child = Column(name, number)+ };+ days.Children.Add(At(cell, 0, i));+ }+ var grid = Grid("Auto,*");+ grid.Children.Add(header);+ grid.Children.Add(At(Margin(days, -2, 3, -2, 0), 1));+ return grid;+ }++ private static FrameworkElement Today(int events, bool compact)+ {+ var today = DateTime.Today;+ var culture = Desk.Culture;+ var stack = new StackPanel();+ stack.Children.Add(T(today.ToString("dddd", culture).ToUpper(culture), 12, FontWeights.Bold, Red));+ stack.Children.Add(Margin(Digits(today.Day.ToString(CultureInfo.InvariantCulture), compact ? 38 : 52, FontWeights.Normal), 0, -4, 0, compact ? 2 : 0));+ if (!compact)+ {+ stack.Children.Add(T(today.ToString("MMMM yyyy", culture), 12.5, FontWeights.SemiBold, Secondary));+ return stack;+ }+ var upcoming = Upcoming(1);+ if (upcoming.Count == 0) stack.Children.Add(NoEvents());+ else stack.Children.Add(EventRow(upcoming[0], 0, true));+ return stack;+ }++ private static FrameworkElement TodayWide()+ {+ var grid = Grid(columns: "110,*");+ grid.Children.Add(Today(0, compact: false));+ var list = new StackPanel();+ var upcoming = Upcoming(3);+ if (upcoming.Count == 0) list.Children.Add(NoEvents());+ for (var i = 0; i < upcoming.Count; i++) list.Children.Add(EventRow(upcoming[i], i, true));+ grid.Children.Add(At(list, 0, 1));+ return grid;+ }++ private static FrameworkElement Month()+ {+ var today = DateTime.Today;+ var culture = Desk.Culture;+ var stack = new StackPanel();+ var title = Grid(columns: "*,Auto");+ title.Children.Add(T(today.ToString("MMMM", culture), 15, FontWeights.SemiBold, Red));+ title.Children.Add(At(T(today.Year.ToString(CultureInfo.InvariantCulture), 15, FontWeights.SemiBold, Secondary), 0, 1));+ stack.Children.Add(title);+ var grid = Grid(columns: "*,*,*,*,*,*,*");+ grid.Margin = new Thickness(0, 6, 0, 8);+ grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });+ var first = culture.DateTimeFormat.FirstDayOfWeek;+ for (var i = 0; i < 7; i++)+ {+ var name = T(culture.DateTimeFormat.GetShortestDayName((DayOfWeek)(((int)first + i) % 7)), 10.5, FontWeights.SemiBold, Secondary);+ name.HorizontalAlignment = HorizontalAlignment.Center;+ grid.Children.Add(At(name, 0, i));+ }+ var start = new DateTime(today.Year, today.Month, 1);+ var offset = ((int)start.DayOfWeek - (int)first + 7) % 7;+ var days = DateTime.DaysInMonth(today.Year, today.Month);+ var rows = (int)Math.Ceiling((offset + days) / 7.0);+ var busy = CalendarHub.Instance.Between(start, start.AddMonths(1)).Select(o => o.Start.Date).ToHashSet();+ for (var r = 0; r < rows; r++) grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(24) });+ for (var d = 1; d <= days; d++)+ {+ var index = offset + d - 1;+ var date = new DateTime(today.Year, today.Month, d);+ var isToday = date == today;+ var number = Digits(d.ToString(CultureInfo.InvariantCulture), 12.5, FontWeights.SemiBold, isToday ? Brushes.White : date.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday ? Secondary : Text);+ number.HorizontalAlignment = HorizontalAlignment.Center;+ var cell = new Grid();+ if (isToday) cell.Children.Add(new Border { Width = 24, Height = 24, CornerRadius = new CornerRadius(12), Background = Red });+ cell.Children.Add(number);+ if (busy.Contains(date) && !isToday)+ cell.Children.Add(new Border { Width = 4, Height = 4, CornerRadius = new CornerRadius(2), Background = Blue, VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(0, 0, 0, 0) });+ grid.Children.Add(At(cell, index / 7 + 1, index % 7));+ }+ stack.Children.Add(grid);+ var upcoming = Upcoming(rows > 5 ? 1 : 2);+ if (upcoming.Count == 0) stack.Children.Add(NoEvents());+ for (var i = 0; i < upcoming.Count; i++) stack.Children.Add(EventRow(upcoming[i], i, true));+ return stack;+ }++ public override void SettingsChanged() => Render();+}++/// <summary>Repeating reminder (drink water, take a break…): fills up like a glass and tells you when due.</summary>+internal sealed class ReminderWidget : DeskWidget+{+ private static readonly int[] Intervals = [15, 20, 30, 45, 60, 90, 120];+ private static readonly (string Key, string Tr, string En, string Icon)[] Kinds =+ [+ ("water", "Su iç", "Drink water", "IconDroplet"),+ ("break", "Mola ver", "Take a break", "IconCoffee"),+ ("eyes", "Gözlerini dinlendir", "Rest your eyes", "IconEye"),+ ("stretch", "Esne, hareket et", "Stretch and move", "IconSmile"),+ ("posture", "Dik otur", "Sit up straight", "IconCheck")+ ];++ private readonly DispatcherTimer _due = new(DispatcherPriority.Normal);+ private WaveFill? _wave;+ private TextBlock? _label, _left;+ private bool _alerted;++ public ReminderWidget()+ {+ _due.Tick += (_, _) => Due();+ }++ private int Minutes => OptionInt("minutes", 30);+ private (string Key, string Tr, string En, string Icon) Kind => Kinds.FirstOrDefault(k => k.Key == (Option("kind") ?? "water")) is { Key: not null } k ? k : Kinds[0];++ private DateTime Since+ {+ get => long.TryParse(Option("since"), out var ticks) ? new DateTime(ticks) : DateTime.Now;+ set => SetOption("since", value.Ticks.ToString(CultureInfo.InvariantCulture));+ }++ public override TimeSpan? Interval => TimeSpan.FromSeconds(15);++ public override FrameworkElement Build()+ {+ if (Option("since") is null) Since = DateTime.Now;+ Schedule();+ _wave = new WaveFill { Margin = new Thickness(-16) };+ _label = T(Desk.L(Kind.Tr, Kind.En), Size == DeskSize.Small ? 15 : 16, FontWeights.SemiBold, Brushes.White);+ _left = T("", 12, FontWeights.SemiBold, Ui("#D9FFFFFF"));+ var every = T(Desk.L($"Her {Minutes} dk", $"Every {Minutes} min"), 11.5, FontWeights.SemiBold, Ui("#A6FFFFFF"));+ var done = new DeskButton(Row(DeskUi.Icon("IconCheck", 12, Brushes.White, 2.4), Margin(T(Desk.L("Yaptım", "Done"), 12, FontWeights.SemiBold, Brushes.White), 5)), Reset, background: Ui("#33FFFFFF"), radius: 13)+ {+ Height = 26,+ Padding = new Thickness(10, 0, 12, 0),+ HorizontalAlignment = HorizontalAlignment.Left+ };+ var grid = new Grid { Background = Ui("#FF16324F"), Margin = new Thickness(-Desk.Padding(Size).Left, -Desk.Padding(Size).Top, -Desk.Padding(Size).Right, -Desk.Padding(Size).Bottom) };+ _wave.Margin = new Thickness(0);+ grid.Children.Add(_wave);+ var content = Size == DeskSize.Small+ ? (FrameworkElement)Column(DeskUi.Icon(Kind.Icon, 20, Brushes.White), Margin(_label, 0, 8), _left, every, Margin(done, 0, 10))+ : new Func<FrameworkElement>(() =>+ {+ var row = Grid(columns: "Auto,*,Auto");+ row.Children.Add(DeskUi.Icon(Kind.Icon, 22, Brushes.White));+ row.Children.Add(At(Margin(Column(_label, Row(_left, Margin(T("·", 12, brush: Ui("#A6FFFFFF")), 5, 0, 5), every)), 12), 0, 1));+ row.Children.Add(At(done, 0, 2));+ return row;+ })();+ content.Margin = Desk.Padding(Size);+ grid.Children.Add(content);+ return grid;+ }++ private static Brush Ui(string hex) => QiDock.Widgets.Ui.Solid(hex);++ private void Schedule()+ {+ _due.Stop();+ var remaining = Since.AddMinutes(Minutes) - DateTime.Now;+ if (remaining <= TimeSpan.Zero) return;+ _alerted = false;+ _due.Interval = remaining;+ _due.Start();+ }++ private void Due()+ {+ _due.Stop();+ if (_alerted) return;+ _alerted = true;+ Desk.Notify(Kind.Icon, Desk.L(Kind.Tr, Kind.En));+ if (Host.IsLive) Tick();+ }++ private void Reset()+ {+ Since = DateTime.Now;+ Schedule();+ Tick();+ }++ public override void Tick()+ {+ var elapsed = DateTime.Now - Since;+ var fraction = elapsed.TotalMinutes / Minutes;+ _wave?.SetFraction(Math.Max(0.06, fraction));+ if (_left is null) return;+ var left = TimeSpan.FromMinutes(Minutes) - elapsed;+ _left.Text = left <= TimeSpan.Zero ? Desk.L("Zamanı geldi!", "Time now!") : Desk.L($"{Math.Ceiling(left.TotalMinutes)} dk sonra", $"in {Math.Ceiling(left.TotalMinutes)} min");+ }++ public override void AddMenuItems(ItemsControl menu)+ {+ var kinds = new MenuItem { Header = Desk.L("Hatırlatma", "Reminder") };+ foreach (var kind in Kinds)+ kinds.Items.Add(MenuEntry(Desk.L(kind.Tr, kind.En), () =>+ {+ SetOption("kind", kind.Key == "water" ? null : kind.Key);+ Host.Rebuild();+ }, Kind.Key == kind.Key));+ menu.Items.Add(kinds);+ var every = new MenuItem { Header = Desk.L("Sıklık", "Every") };+ foreach (var minutes in Intervals)+ every.Items.Add(MenuEntry(Desk.L($"{minutes} dakikada bir", $"Every {minutes} minutes"), () =>+ {+ SetOption("minutes", minutes.ToString(CultureInfo.InvariantCulture));+ Host.Rebuild();+ }, Minutes == minutes));+ menu.Items.Add(every);+ }++ public override void Dispose()+ {+ _due.Stop();+ base.Dispose();+ }+}++/// <summary>Pomodoro: focus and break rounds; tells you when each ends.</summary>+internal sealed class FocusDeskWidget : DeskWidget+{+ // Shows the shared focus timer, so the bar's focus tile and this widget run one countdown.+ private Border? _frame;+ private TextBlock? _label, _time;+ private DeskButton? _play;+ private RingGauge? _ring;++ public override TimeSpan? Interval => TimeSpan.FromSeconds(1);++ public override FrameworkElement Build()+ {+ _label = T("", 12, FontWeights.SemiBold, Secondary);+ _time = Digits("", Size == DeskSize.Small ? 30 : 30);+ _play = DeskButton.Round("GlyphPlay", () => { FocusTimer.Toggle(); Tick(); }, Size == DeskSize.Small ? 32 : 38, Red, Brushes.White);+ var skip = DeskButton.Round("GlyphNext", () => { FocusTimer.Skip(); Tick(); }, Size == DeskSize.Small ? 28 : 32, Inset, Secondary, 12);+ _frame = new Border+ {+ Margin = new Thickness(-Desk.Padding(Size).Left + 3, -Desk.Padding(Size).Top + 3, -Desk.Padding(Size).Right + 3, -Desk.Padding(Size).Bottom + 3),+ CornerRadius = new CornerRadius(21),+ BorderThickness = new Thickness(2),+ Padding = new Thickness(Desk.Padding(Size).Left - 5, Desk.Padding(Size).Top - 5, Desk.Padding(Size).Right - 5, Desk.Padding(Size).Bottom - 5)+ };+ if (Size == DeskSize.Small)+ {+ _ring = new RingGauge { Width = 66, Height = 66, Thickness = 6, Stroke = Red, HorizontalAlignment = HorizontalAlignment.Center };+ var center = new Grid { HorizontalAlignment = HorizontalAlignment.Center };+ center.Children.Add(_ring);+ _time.FontSize = 17;+ _time.HorizontalAlignment = HorizontalAlignment.Center;+ center.Children.Add(_time);+ var buttons = Row(_play, Margin(skip, 10));+ buttons.HorizontalAlignment = HorizontalAlignment.Center;+ _label.HorizontalAlignment = HorizontalAlignment.Center;+ _frame.Child = Column(_label, Margin(center, 0, 4, 0, 6), buttons);+ }+ else+ {+ _ring = null;+ var grid = Grid(columns: "*,Auto,Auto");+ grid.Children.Add(Column(_label, _time));+ grid.Children.Add(At(Margin(skip, 0, 0, 10), 0, 1));+ grid.Children.Add(At(_play, 0, 2));+ _frame.Child = grid;+ }+ return _frame;+ }++ public override void Tick()+ {+ var remaining = FocusTimer.Remaining;+ var round = Math.Min(FocusTimer.Round, FocusTimer.Rounds);+ var color = FocusTimer.OnBreak ? Green : Red;+ _label!.Text = FocusTimer.OnBreak ? Desk.L("Mola", "Break") : Desk.L($"Odak {round}/{FocusTimer.Rounds}", $"Focus {round}/{FocusTimer.Rounds}");+ _label.Foreground = color;+ _time!.Text = $"{(int)remaining.TotalMinutes}:{remaining.Seconds:00}";+ _frame!.BorderBrush = FocusTimer.Running ? color : Brushes.Transparent;+ _play!.Background = color;+ _play.Child = Glyph(FocusTimer.Running ? "GlyphPause" : "GlyphPlay", 13, Brushes.White);+ if (_ring is not null)+ {+ _ring.Stroke = color;+ _ring.Value = remaining.TotalSeconds / FocusTimer.PhaseLength.TotalSeconds * 100;+ }+ }+}diff --git a/DesktopWidgets/Kinds/SystemWidgets.cs b/DesktopWidgets/Kinds/SystemWidgets.csnew file mode 100644index 0000000..d75c88a--- /dev/null+++ b/DesktopWidgets/Kinds/SystemWidgets.cs@@ -0,0 +1,196 @@+using System.Globalization;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media;+using static QiDock.DesktopWidgets.DeskUi;++namespace QiDock.DesktopWidgets.Kinds;++internal enum Metric { Cpu, Ram, Disk, Battery }++/// <summary>CPU, memory, disk or battery as a ring, a bar or (CPU) a live graph.</summary>+internal sealed class MetricWidget(Metric metric) : DeskWidget+{+ private RingGauge? _ring;+ private TextBlock? _value, _detail;+ private Sparkline? _graph;+ private Border? _barFill;+ private Grid? _bar;+ private ContentControl? _icon;++ private Brush Color => metric switch+ {+ Metric.Cpu => Blue,+ Metric.Ram => Purple,+ Metric.Disk => Cyan,+ _ => Green+ };++ private string IconKey => metric switch+ {+ Metric.Cpu => "IconCpu",+ Metric.Ram => "IconMemory",+ Metric.Disk => "IconHardDrive",+ _ => "IconBattery"+ };++ private string Label => metric switch+ {+ Metric.Cpu => Desk.L("İşlemci", "CPU"),+ Metric.Ram => Desk.L("Bellek", "Memory"),+ Metric.Disk => Desk.L("Disk", "Disk"),+ _ => Desk.L("Pil", "Battery")+ };++ public override FrameworkElement Build()+ {+ _ring = null;+ _graph = null;+ _bar = null;+ _icon = new ContentControl { Content = DeskUi.Icon(IconKey, 14, Color) };+ _value = Digits("", 15, FontWeights.Bold);+ _detail = T("", 11.5, FontWeights.SemiBold, Secondary);+ switch (Size)+ {+ case DeskSize.Mini:+ {+ _ring = new RingGauge { Width = 50, Height = 50, Thickness = 5, Stroke = Color };+ var ringHost = new Grid();+ ringHost.Children.Add(_ring);+ ringHost.Children.Add(_icon);+ _value.FontSize = 20;+ var grid = Grid(columns: "Auto,*");+ grid.Children.Add(ringHost);+ grid.Children.Add(At(Margin(Column(_value, T(Label, 12, FontWeights.SemiBold, Secondary)), 12), 0, 1));+ return grid;+ }+ case DeskSize.Small:+ {+ _ring = new RingGauge { Width = 96, Height = 96, Thickness = 9, Stroke = Color, HorizontalAlignment = HorizontalAlignment.Center };+ var ringHost = new Grid { HorizontalAlignment = HorizontalAlignment.Center };+ ringHost.Children.Add(_ring);+ _value.FontSize = 24;+ _value.HorizontalAlignment = HorizontalAlignment.Center;+ ringHost.Children.Add(_value);+ var title = Row(_icon, Margin(T(Label, 12.5, FontWeights.SemiBold), 6));+ _detail.HorizontalAlignment = HorizontalAlignment.Center;+ var grid = Grid("Auto,*,Auto");+ grid.Children.Add(title);+ grid.Children.Add(At(ringHost, 1));+ grid.Children.Add(At(_detail, 2));+ return grid;+ }+ default:+ {+ var header = Grid(columns: "Auto,*,Auto");+ header.Children.Add(_icon);+ header.Children.Add(At(Margin(T(Label, 13, FontWeights.SemiBold), 6), 0, 1));+ header.Children.Add(At(_value, 0, 2));+ var grid = Grid("Auto,*,Auto");+ grid.Children.Add(header);+ if (metric == Metric.Cpu)+ {+ _graph = new Sparkline { Stroke = Color, Maximum = 100, Margin = new Thickness(0, 6, 0, Size == DeskSize.Medium ? 6 : 0) };+ grid.Children.Add(At(_graph, 1));+ }+ else+ {+ _barFill = new Border { CornerRadius = new CornerRadius(4), Background = Color, HorizontalAlignment = HorizontalAlignment.Left };+ _bar = new Grid { Height = 8, VerticalAlignment = VerticalAlignment.Center };+ _bar.Children.Add(new Border { CornerRadius = new CornerRadius(4), Background = Track });+ _bar.Children.Add(_barFill);+ grid.Children.Add(At(_bar, 1));+ }+ if (Size != DeskSize.Strip || metric != Metric.Cpu) grid.Children.Add(At(_detail, 2));+ return grid;+ }+ }+ }++ protected override void OnAttach() => SystemHub.Instance.Subscribe(Tick);+ protected override void OnDetach() => SystemHub.Instance.Unsubscribe(Tick);++ public override void Tick()+ {+ var hub = SystemHub.Instance;+ double percent;+ string detail;+ switch (metric)+ {+ case Metric.Cpu:+ percent = hub.Cpu;+ var uptime = TimeSpan.FromMilliseconds(Environment.TickCount64);+ detail = Size == DeskSize.Small+ ? Desk.L($"{Environment.ProcessorCount} çekirdek", $"{Environment.ProcessorCount} cores")+ : Desk.L($"{Environment.ProcessorCount} çekirdek · açık {(int)uptime.TotalDays} g {uptime.Hours} sa", $"{Environment.ProcessorCount} cores · up {(int)uptime.TotalDays} d {uptime.Hours} h");+ break;+ case Metric.Ram:+ percent = hub.RamPercent;+ detail = $"{SystemHub.Gb(hub.RamUsed)} / {SystemHub.Gb(hub.RamTotal)}";+ break;+ case Metric.Disk:+ percent = hub.DiskPercent;+ detail = Desk.L($"{SystemHub.Gb(hub.DiskFree)} boş", $"{SystemHub.Gb(hub.DiskFree)} free");+ break;+ default:+ if (hub.Battery is not { } battery)+ {+ percent = 0;+ detail = Desk.L("Pil yok", "No battery");+ break;+ }+ percent = battery.Percent;+ detail = battery.Charging ? Desk.L("Şarj oluyor", "Charging") : battery.OnAc ? Desk.L("Prize takılı", "Plugged in")+ : battery.Remaining is { } left ? Desk.L($"{(int)left.TotalHours} sa {left.Minutes} dk kaldı", $"{(int)left.TotalHours} h {left.Minutes} m left") : Desk.L("Pilde", "On battery");+ if (_ring is not null) _ring.Stroke = percent <= 20 && !battery.Charging ? Red : Green;+ if (_icon is not null) _icon.Content = DeskUi.Icon(battery.Charging ? "IconBolt" : IconKey, 14, Color);+ break;+ }+ if (_ring is not null) _ring.Value = percent;+ _value!.Text = Percent(percent);+ if (Size != DeskSize.Mini) _value.Foreground = Size == DeskSize.Small ? Text : QiDock.Widgets.Ui.UsageBrush(metric == Metric.Battery ? 100 - percent : percent);+ _detail!.Text = detail;+ _graph?.SetValues([.. hub.CpuHistory]);+ if (_bar is not null && _barFill is not null)+ _barFill.Width = Math.Max(8, (_bar.ActualWidth > 0 ? _bar.ActualWidth : 312) * percent / 100);+ }+}++/// <summary>Download and upload speed with a live graph.</summary>+internal sealed class NetworkWidget : DeskWidget+{+ private TextBlock? _down, _up;+ private Sparkline? _graph;++ public override FrameworkElement Build()+ {+ _down = Digits("", Size == DeskSize.Mini ? 13 : 14, FontWeights.Bold);+ _up = Digits("", Size == DeskSize.Mini ? 13 : 14, FontWeights.Bold);+ var down = Row(DeskUi.Icon("IconArrowDown", 13, Cyan), Margin(_down, 4));+ if (Size == DeskSize.Mini)+ {+ _graph = null;+ return Column(down, Margin(Row(DeskUi.Icon("IconArrowUp", 13, Purple), Margin(_up, 4)), 0, 6));+ }+ var up = Row(Margin(_up, 0, 0, 4), DeskUi.Icon("IconArrowUp", 13, Purple));+ _graph = new Sparkline { Stroke = Cyan, SecondStroke = Purple, LineThickness = 1.8 };+ var header = Grid(columns: "*,Auto");+ header.Children.Add(down);+ header.Children.Add(At(up, 0, 1));+ var grid = Grid("Auto,*");+ grid.Children.Add(header);+ grid.Children.Add(At(Margin(_graph, 0, 6), 1));+ return grid;+ }++ protected override void OnAttach() => SystemHub.Instance.Subscribe(Tick);+ protected override void OnDetach() => SystemHub.Instance.Unsubscribe(Tick);++ public override void Tick()+ {+ var hub = SystemHub.Instance;+ _down!.Text = SystemHub.Speed(hub.Down);+ _up!.Text = SystemHub.Speed(hub.Up);+ _graph?.SetValues([.. hub.DownHistory], [.. hub.UpHistory]);+ }+}diff --git a/DesktopWidgets/Kinds/TimeWidgets.cs b/DesktopWidgets/Kinds/TimeWidgets.csnew file mode 100644index 0000000..2512c25--- /dev/null+++ b/DesktopWidgets/Kinds/TimeWidgets.cs@@ -0,0 +1,644 @@+using System.Globalization;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media;+using System.Windows.Threading;+using QiDock.Services.Widgets;+using QiDock.Widgets;+using static QiDock.DesktopWidgets.DeskUi;++namespace QiDock.DesktopWidgets.Kinds;++/// <summary>Digital clock: time, weekday and date; the medium size adds the weather.</summary>+internal sealed class DigitalClockWidget : DeskWidget+{+ private TextBlock? _time, _seconds, _day, _date, _temp;+ private ContentControl? _weatherIcon;++ public override TimeSpan? Interval => TimeSpan.FromSeconds(1);+ private bool ShowSeconds => Option("seconds") == "1" || Size == DeskSize.Strip;++ public override FrameworkElement Build()+ {+ _seconds = _temp = null;+ _weatherIcon = null;+ switch (Size)+ {+ case DeskSize.Mini:+ {+ _time = Digits("", 30);+ _day = T("", 12, FontWeights.SemiBold, Orange);+ _date = T("", 12, brush: Secondary);+ var grid = Grid(columns: "*,Auto");+ grid.Children.Add(_time);+ var right = Column(_day, _date);+ right.HorizontalAlignment = HorizontalAlignment.Right;+ grid.Children.Add(At(right, 0, 1));+ return grid;+ }+ case DeskSize.Strip:+ {+ _time = Digits("", 42);+ _time.HorizontalAlignment = HorizontalAlignment.Center;+ return _time;+ }+ case DeskSize.Medium:+ {+ _day = T("", 14, FontWeights.SemiBold, Orange);+ _time = Digits("", 60);+ _date = T("", 13, brush: Secondary);+ _weatherIcon = new ContentControl { Width = 44, Height = 44 };+ _temp = T("", 28, FontWeights.SemiBold);+ var right = Column(_weatherIcon, _temp);+ right.HorizontalAlignment = HorizontalAlignment.Right;+ _temp.HorizontalAlignment = HorizontalAlignment.Center;+ var grid = Grid(columns: "*,Auto");+ grid.Children.Add(Column(_day, _time, _date));+ grid.Children.Add(At(right, 0, 1));+ return grid;+ }+ default:+ {+ _day = T("", 14, FontWeights.SemiBold, Orange);+ _time = Digits("", 46);+ _date = T("", 12.5, brush: Secondary);+ var stack = Column(_day, Margin(_time, 0, 6, 0, 2), _date);+ if (ShowSeconds)+ {+ _seconds = Digits("", 14, FontWeights.Medium, Secondary);+ stack.Children.Add(Margin(_seconds, 0, 6));+ }+ stack.VerticalAlignment = VerticalAlignment.Center;+ return stack;+ }+ }+ }++ protected override void OnAttach()+ {+ if (Size == DeskSize.Medium) WeatherHub.Instance.Subscribe(UpdateWeather);+ }++ protected override void OnDetach() => WeatherHub.Instance.Unsubscribe(UpdateWeather);++ public override void Tick()+ {+ var now = DateTime.Now;+ var culture = Desk.Culture;+ if (_time is not null)+ _time.Text = now.ToString(ShowSeconds && Size is DeskSize.Strip or DeskSize.Mini ? "HH:mm:ss" : "HH:mm", culture);+ if (Size == DeskSize.Mini && ShowSeconds && _time is not null) _time.FontSize = 26;+ if (_seconds is not null) _seconds.Text = now.ToString(":ss", culture);+ if (_day is not null) _day.Text = Size == DeskSize.Mini ? now.ToString("ddd", culture) : now.ToString("dddd", culture);+ if (_date is not null) _date.Text = Size == DeskSize.Mini ? now.ToString("d MMM", culture) : now.ToString("d MMMM yyyy", culture);+ UpdateWeather();+ }++ private void UpdateWeather()+ {+ if (_temp is null || _weatherIcon is null) return;+ if (WeatherHub.Instance.Report is not { } report) return;+ _temp.Text = WeatherHub.Temp(report.Temperature);+ if (_weatherIcon.Tag as string != $"{report.Code}{report.IsDay}")+ {+ _weatherIcon.Tag = $"{report.Code}{report.IsDay}";+ _weatherIcon.Content = WeatherArt.Create(report.Code, report.IsDay, 44);+ }+ }++ public override void AddMenuItems(ItemsControl menu)+ {+ if (Size is DeskSize.Small or DeskSize.Mini)+ menu.Items.Add(MenuEntry(Desk.L("Saniyeleri göster", "Show seconds"), () =>+ {+ SetOption("seconds", Option("seconds") == "1" ? null : "1");+ Host.Rebuild();+ }, Option("seconds") == "1"));+ }+}++/// <summary>Analog clock with a light or dark face.</summary>+internal sealed class AnalogClockWidget : DeskWidget+{+ private AnalogFace? _face;+ private TextBlock? _date;++ public override TimeSpan? Interval => TimeSpan.FromSeconds(1);++ public override FrameworkElement Build()+ {+ _face = new AnalogFace { Light = Option("dark") != "1" };+ if (Size == DeskSize.Small) return Margin(_face, -4, -4, -4, -4);+ _date = T("", 14, FontWeights.SemiBold, Secondary);+ _date.HorizontalAlignment = HorizontalAlignment.Center;+ var grid = Grid("*,Auto");+ grid.Children.Add(Margin(_face, 10, 4, 10, 8));+ grid.Children.Add(At(_date, 1));+ return grid;+ }++ public override void Tick()+ {+ var now = DateTime.Now;+ _face?.SetTime(now);+ if (_date is not null) _date.Text = now.ToString("dddd, d MMMM", Desk.Culture);+ }++ public override void AddMenuItems(ItemsControl menu) =>+ menu.Items.Add(MenuEntry(Desk.L("Koyu kadran", "Dark face"), () =>+ {+ SetOption("dark", Option("dark") == "1" ? null : "1");+ Host.Rebuild();+ }, Option("dark") == "1"));+}++/// <summary>Hours and minutes on four split-flap style tiles.</summary>+internal sealed class FlipClockWidget : DeskWidget+{+ private readonly TextBlock[] _digits = new TextBlock[4];+ private TextBlock? _date;++ public override TimeSpan? Interval => TimeSpan.FromSeconds(1);++ public override FrameworkElement Build()+ {+ var big = Size == DeskSize.Medium;+ var row = Grid(columns: "*,*,10,*,*");+ for (var i = 0; i < 4; i++)+ {+ _digits[i] = Digits("0", big ? 70 : 44, FontWeights.Bold);+ _digits[i].HorizontalAlignment = HorizontalAlignment.Center;+ var tile = new Grid { Margin = new Thickness(3, 0, 3, 0) };+ tile.Children.Add(new Border { CornerRadius = new CornerRadius(10), Background = QiDock.Widgets.Ui.Vertical("#FF3A3A3E", "#FF2A2A2E") });+ tile.Children.Add(_digits[i]);+ tile.Children.Add(new Border { Height = 1.5, Background = Ui.Solid("#CC1C1C1F"), VerticalAlignment = VerticalAlignment.Center });+ row.Children.Add(At(tile, 0, i < 2 ? i : i + 1));+ }+ if (!big) return row;+ _date = T("", 13, FontWeights.SemiBold, Secondary);+ _date.HorizontalAlignment = HorizontalAlignment.Center;+ var grid = Grid("*,Auto");+ grid.Children.Add(row);+ grid.Children.Add(At(Margin(_date, 0, 8), 1));+ return grid;+ }++ public override void Tick()+ {+ var text = DateTime.Now.ToString("HHmm", CultureInfo.InvariantCulture);+ for (var i = 0; i < 4; i++) _digits[i].Text = text[i].ToString();+ if (_date is not null) _date.Text = DateTime.Now.ToString("dddd, d MMMM", Desk.Culture);+ }+}++/// <summary>Today's date in calendar-page style.</summary>+internal sealed class DateWidget : DeskWidget+{+ private TextBlock? _a, _b, _c, _temp;+ private ContentControl? _icon;++ public override TimeSpan? Interval => TimeSpan.FromSeconds(30);++ public override FrameworkElement Build()+ {+ _temp = null;+ _icon = null;+ switch (Size)+ {+ case DeskSize.Mini:+ _a = T("", 12.5, FontWeights.SemiBold, Red);+ _b = T("", 24, FontWeights.SemiBold);+ return Column(_a, _b);+ case DeskSize.Strip:+ {+ _a = T("", 20, FontWeights.SemiBold);+ _b = T("", 13, brush: Secondary);+ _icon = new ContentControl { Width = 30, Height = 30 };+ _temp = T("", 22, FontWeights.SemiBold);+ var grid = Grid(columns: "*,Auto,Auto");+ grid.Children.Add(Column(_a, _b));+ grid.Children.Add(At(_icon, 0, 1));+ grid.Children.Add(At(Margin(_temp, 6), 0, 2));+ return grid;+ }+ default:+ {+ _a = T("", 14, FontWeights.Bold, Red);+ _b = Digits("", 64, FontWeights.Light);+ _c = T("", 13, brush: Secondary);+ foreach (var t in new[] { _a, _b, _c }) t.HorizontalAlignment = HorizontalAlignment.Center;+ _b.Margin = new Thickness(0, -6, 0, -4);+ return Column(_a, _b, _c);+ }+ }+ }++ protected override void OnAttach()+ {+ if (Size == DeskSize.Strip) WeatherHub.Instance.Subscribe(Tick);+ }++ protected override void OnDetach() => WeatherHub.Instance.Unsubscribe(Tick);++ public override void Tick()+ {+ var now = DateTime.Now;+ var culture = Desk.Culture;+ switch (Size)+ {+ case DeskSize.Mini:+ _a!.Text = now.ToString("dddd", culture);+ _b!.Text = now.ToString("d MMMM", culture);+ break;+ case DeskSize.Strip:+ _a!.Text = now.ToString("d MMMM, dddd", culture);+ _b!.Text = now.ToString("HH:mm", culture) + (WeatherHub.Instance.Report is { } r ? " · " + r.City : "");+ if (WeatherHub.Instance.Report is { } report)+ {+ _temp!.Text = WeatherHub.Temp(report.Temperature);+ if (_icon!.Tag as string != $"{report.Code}{report.IsDay}")+ {+ _icon.Tag = $"{report.Code}{report.IsDay}";+ _icon.Content = WeatherArt.Create(report.Code, report.IsDay, 30);+ }+ }+ break;+ default:+ _a!.Text = now.ToString("dddd", culture).ToUpper(culture);+ _b!.Text = now.Day.ToString(CultureInfo.InvariantCulture);+ _c!.Text = now.ToString("MMMM yyyy", culture);+ break;+ }+ }+}++/// <summary>How much of the year, month, week or day has gone by, as dots.</summary>+internal sealed class ProgressWidget : DeskWidget+{+ private DotGrid? _dots;+ private TextBlock? _label, _percent;+ private readonly List<(TextBlock Percent, Border Fill, Func<double> Value)> _rows = [];++ public override TimeSpan? Interval => TimeSpan.FromMinutes(1);+ private string Scope => Option("scope") ?? "year";++ public override FrameworkElement Build()+ {+ _rows.Clear();+ if (Size == DeskSize.Medium)+ {+ var stack = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ AddRow(stack, Desk.L("Bugün", "Today"), () => DayFraction(DateTime.Now), Orange);+ AddRow(stack, Desk.L("Bu hafta", "This week"), () => WeekFraction(DateTime.Now), Purple);+ AddRow(stack, DateTime.Now.ToString("MMMM", Desk.Culture), () => MonthFraction(DateTime.Now), Blue);+ AddRow(stack, DateTime.Now.Year.ToString(CultureInfo.InvariantCulture), () => YearFraction(DateTime.Now), Green);+ return stack;+ }+ _dots = new DotGrid { FilledBrush = Text, CurrentBrush = Orange };+ _label = T("", 12.5, FontWeights.SemiBold, Secondary);+ _percent = Digits("", 12.5, FontWeights.Bold);+ var footer = Grid(columns: "*,Auto");+ footer.Children.Add(_label);+ footer.Children.Add(At(_percent, 0, 1));+ var grid = Grid("*,Auto");+ grid.Children.Add(Margin(_dots, 0, 0, 0, 6));+ grid.Children.Add(At(footer, 1));+ return grid;+ }++ private void AddRow(Panel stack, string label, Func<double> value, Brush color)+ {+ var name = T(label, 12, FontWeights.SemiBold, Secondary);+ var percent = Digits("", 12, FontWeights.Bold);+ var top = Grid(columns: "*,Auto");+ top.Children.Add(name);+ top.Children.Add(At(percent, 0, 1));+ var fill = new Border { CornerRadius = new CornerRadius(3), Background = color, HorizontalAlignment = HorizontalAlignment.Left };+ var bar = new Grid { Height = 6, Margin = new Thickness(0, 3, 0, 7) };+ bar.Children.Add(new Border { CornerRadius = new CornerRadius(3), Background = Track });+ bar.Children.Add(fill);+ stack.Children.Add(top);+ stack.Children.Add(bar);+ _rows.Add((percent, fill, value));+ }++ public override void Tick()+ {+ var now = DateTime.Now;+ foreach (var (percent, fill, value) in _rows)+ {+ var f = value();+ percent.Text = Percent(f * 100);+ if (fill.Parent is Grid bar) fill.Width = Math.Max(6, (bar.ActualWidth > 0 ? bar.ActualWidth : 312) * f);+ }+ if (_dots is null) return;+ var strip = Size == DeskSize.Strip;+ var culture = Desk.Culture;+ switch (Scope)+ {+ case "month":+ {+ var days = DateTime.DaysInMonth(now.Year, now.Month);+ _dots.Set(days, now.Day - 1, strip ? 16 : 7);+ _label!.Text = now.ToString("MMMM yyyy", culture);+ _percent!.Text = Percent(MonthFraction(now) * 100);+ break;+ }+ case "week":+ _dots.Set(7, ((int)now.DayOfWeek + 6) % 7, 7);+ _label!.Text = Desk.L("Bu hafta", "This week");+ _percent!.Text = Percent(WeekFraction(now) * 100);+ break;+ case "day":+ _dots.Set(24, now.Hour, strip ? 12 : 6);+ _label!.Text = Desk.L("Bugün", "Today");+ _percent!.Text = Percent(DayFraction(now) * 100);+ break;+ default:+ {+ var week = Math.Min(51, (now.DayOfYear - 1) / 7);+ _dots.Set(52, week, strip ? 26 : 8);+ _label!.Text = now.Year.ToString(CultureInfo.InvariantCulture);+ _percent!.Text = Percent(YearFraction(now) * 100);+ break;+ }+ }+ }++ private static double DayFraction(DateTime now) => now.TimeOfDay.TotalHours / 24;+ private static double WeekFraction(DateTime now) => (((int)now.DayOfWeek + 6) % 7 + DayFraction(now)) / 7;+ private static double MonthFraction(DateTime now) => (now.Day - 1 + DayFraction(now)) / DateTime.DaysInMonth(now.Year, now.Month);+ private static double YearFraction(DateTime now) => (now.DayOfYear - 1 + DayFraction(now)) / (DateTime.IsLeapYear(now.Year) ? 366 : 365);++ public override void AddMenuItems(ItemsControl menu)+ {+ if (Size == DeskSize.Medium) return;+ foreach (var (key, tr, en) in new[] { ("year", "Yıl", "Year"), ("month", "Ay", "Month"), ("week", "Hafta", "Week"), ("day", "Gün", "Day") })+ menu.Items.Add(MenuEntry(Desk.L(tr, en), () =>+ {+ SetOption("scope", key == "year" ? null : key);+ Tick();+ }, Scope == key));+ }+}++/// <summary>Countdown timer; tells you when time is up even while covered by windows.</summary>+internal sealed class TimerWidget : DeskWidget+{+ private static readonly int[] Presets = [1, 3, 5, 10, 15, 20, 30, 45, 60];+ private readonly DispatcherTimer _done = new(DispatcherPriority.Normal);+ private TimeSpan _remaining;+ private DateTime _endsAt;+ private bool _running;+ private RingGauge? _ring;+ private TextBlock? _text;+ private DeskButton? _play;++ public TimerWidget()+ {+ _done.Tick += (_, _) => Finish();+ }++ private TimeSpan Length => TimeSpan.FromMinutes(Math.Clamp(OptionInt("minutes", 5), 1, 180));+ public override TimeSpan? Interval => TimeSpan.FromMilliseconds(500);++ public override FrameworkElement Build()+ {+ if (_remaining == TimeSpan.Zero && !_running) _remaining = Length;+ _ring = new RingGauge { Stroke = Orange, Thickness = Size == DeskSize.Small ? 8 : 4 };+ _text = Digits("", Size switch { DeskSize.Small => 30, DeskSize.Mini => 28, _ => 36 });+ _play = DeskButton.Round("GlyphPlay", Toggle, Size == DeskSize.Small ? 40 : 36, Orange, Brushes.White);+ var reset = DeskButton.Round("IconClose", Reset, Size == DeskSize.Small ? 40 : 30, Inset, Secondary, outline: true, glyph: 11);+ switch (Size)+ {+ case DeskSize.Small:+ {+ var center = new Grid { Width = 92, Height = 92, HorizontalAlignment = HorizontalAlignment.Center };+ center.Children.Add(_ring);+ _text.HorizontalAlignment = HorizontalAlignment.Center;+ _text.FontSize = 24;+ center.Children.Add(_text);+ var buttons = Row(reset, Margin(_play, 12));+ buttons.HorizontalAlignment = HorizontalAlignment.Center;+ buttons.Margin = new Thickness(0, 8, 0, 0);+ return Column(center, buttons);+ }+ case DeskSize.Mini:+ {+ var grid = Grid(columns: "*,Auto");+ grid.Children.Add(_text);+ grid.Children.Add(At(_play, 0, 1));+ return grid;+ }+ default:+ {+ var grid = Grid(columns: "Auto,*,Auto,Auto");+ var ringHost = new Grid { Width = 40, Height = 40 };+ ringHost.Children.Add(_ring);+ ringHost.Children.Add(Icon("IconTimer", 15, Orange));+ grid.Children.Add(ringHost);+ grid.Children.Add(At(Margin(_text, 12), 0, 1));+ grid.Children.Add(At(Margin(reset, 0, 0, 10), 0, 2));+ grid.Children.Add(At(_play, 0, 3));+ return grid;+ }+ }+ }++ public override void Tick()+ {+ var remaining = _running ? _endsAt - DateTime.Now : _remaining;+ if (remaining < TimeSpan.Zero) remaining = TimeSpan.Zero;+ if (_text is not null)+ _text.Text = remaining.TotalHours >= 1 ? remaining.ToString(@"h\:mm\:ss", CultureInfo.InvariantCulture) : $"{(int)remaining.TotalMinutes}:{remaining.Seconds:00}";+ if (_ring is not null) _ring.Value = remaining.TotalSeconds / Length.TotalSeconds * 100;+ if (_play is not null) _play.Child = Glyph(_running ? "GlyphPause" : "GlyphPlay", 13, Brushes.White);+ }++ private void Toggle()+ {+ if (_running)+ {+ _remaining = _endsAt - DateTime.Now;+ _running = false;+ _done.Stop();+ }+ else+ {+ if (_remaining <= TimeSpan.Zero) _remaining = Length;+ _endsAt = DateTime.Now + _remaining;+ _running = true;+ _done.Interval = _remaining;+ _done.Start();+ }+ Tick();+ }++ private void Reset()+ {+ _running = false;+ _done.Stop();+ _remaining = Length;+ Tick();+ }++ private void Finish()+ {+ _done.Stop();+ _running = false;+ _remaining = Length;+ Desk.Notify("IconTimer", Desk.L("Süre doldu", "Time is up"));+ if (Host.IsLive) Tick();+ }++ public override void AddMenuItems(ItemsControl menu)+ {+ var length = new MenuItem { Header = Desk.L("Süre", "Length") };+ foreach (var minutes in Presets)+ length.Items.Add(MenuEntry(Desk.L($"{minutes} dakika", $"{minutes} minutes"), () =>+ {+ SetOption("minutes", minutes.ToString(CultureInfo.InvariantCulture));+ Reset();+ }, Length.TotalMinutes == minutes));+ menu.Items.Add(length);+ }++ public override void Dispose()+ {+ _done.Stop();+ base.Dispose();+ }+}++/// <summary>Stopwatch with tenths of a second.</summary>+internal sealed class StopwatchWidget : DeskWidget+{+ private readonly System.Diagnostics.Stopwatch _watch = new();+ private TextBlock? _text;+ private DeskButton? _play;++ public override TimeSpan? Interval => TimeSpan.FromMilliseconds(100);++ public override FrameworkElement Build()+ {+ _text = Digits("", Size == DeskSize.Mini ? 26 : 36);+ _play = DeskButton.Round("GlyphPlay", Toggle, 36, Blue, Brushes.White);+ var reset = DeskButton.Round("IconRotate", Reset, 30, Inset, Secondary, outline: true, glyph: 13);+ var grid = Grid(columns: Size == DeskSize.Mini ? "*,Auto" : "*,Auto,Auto");+ grid.Children.Add(_text);+ if (Size == DeskSize.Mini)+ {+ grid.Children.Add(At(_play, 0, 1));+ return grid;+ }+ grid.Children.Add(At(Margin(reset, 0, 0, 10), 0, 1));+ grid.Children.Add(At(_play, 0, 2));+ return grid;+ }++ public override void Tick()+ {+ var t = _watch.Elapsed;+ if (_text is not null)+ _text.Text = t.TotalHours >= 1+ ? t.ToString(@"h\:mm\:ss", CultureInfo.InvariantCulture)+ : $"{(int)t.TotalMinutes}:{t.Seconds:00}.{t.Milliseconds / 100}";+ if (_play is not null) _play.Child = Glyph(_watch.IsRunning ? "GlyphPause" : "GlyphPlay", 13, Brushes.White);+ }++ private void Toggle()+ {+ if (_watch.IsRunning) _watch.Stop();+ else _watch.Start();+ Tick();+ }++ private void Reset()+ {+ _watch.Reset();+ Tick();+ }+}++/// <summary>Up to three cities' times (the same cities as the bar's world clock).</summary>+internal sealed class WorldClockDeskWidget : DeskWidget+{+ private readonly List<(string Zone, TextBlock Time, TextBlock? Offset, AnalogFace? Face)> _cells = [];++ public override TimeSpan? Interval => TimeSpan.FromSeconds(Size == DeskSize.Medium ? 1 : 20);++ private static IEnumerable<(string Name, string Zone)> Cities()+ {+ var keys = Desk.Settings().WorldClocks is { Count: > 0 } chosen ? chosen : WorldClockWidget.Defaults;+ foreach (var key in keys.Take(3))+ {+ var city = WorldClockWidget.Cities.FirstOrDefault(c => c.Key == key);+ if (city.Key is null) continue;+ yield return (Desk.L(city.Tr, city.En), city.Zone);+ }+ }++ public override FrameworkElement Build()+ {+ _cells.Clear();+ var cities = Cities().ToList();+ if (Size == DeskSize.Small)+ {+ var stack = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ foreach (var (name, zone) in cities)+ {+ var time = Digits("", 20);+ var offset = T("", 11, brush: Secondary);+ var row = Grid(columns: "*,Auto");+ row.Children.Add(Column(T(name, 12.5, FontWeights.SemiBold), offset));+ row.Children.Add(At(time, 0, 1));+ row.Margin = new Thickness(0, 3, 0, 3);+ stack.Children.Add(row);+ _cells.Add((zone, time, offset, null));+ }+ return stack;+ }+ var grid = Grid(columns: string.Join(",", cities.Select(_ => "*")));+ var i = 0;+ foreach (var (name, zone) in cities)+ {+ AnalogFace? face = null;+ var cell = new StackPanel { HorizontalAlignment = HorizontalAlignment.Center };+ if (Size == DeskSize.Medium)+ {+ face = new AnalogFace { Width = 64, Height = 64, Light = true, Numbers = false, Margin = new Thickness(0, 0, 0, 6) };+ cell.Children.Add(face);+ }+ var label = T(name, 12, FontWeights.SemiBold, Secondary);+ label.HorizontalAlignment = HorizontalAlignment.Center;+ var time = Digits("", Size == DeskSize.Medium ? 17 : 20);+ time.HorizontalAlignment = HorizontalAlignment.Center;+ cell.Children.Add(label);+ cell.Children.Add(time);+ grid.Children.Add(At(cell, 0, i++));+ _cells.Add((zone, time, null, face));+ }+ return grid;+ }++ public override void Tick()+ {+ foreach (var (zone, time, offset, face) in _cells)+ {+ DateTime local;+ try { local = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById(zone)); }+ catch (Exception ex) when (ex is TimeZoneNotFoundException or InvalidTimeZoneException) { continue; }+ time.Text = local.ToString("HH:mm", CultureInfo.InvariantCulture);+ face?.SetTime(local);+ if (offset is not null)+ {+ var hours = (local - DateTime.Now).TotalHours;+ hours = Math.Round(hours * 2) / 2;+ var day = local.Date == DateTime.Today ? Desk.L("Bugün", "Today") : local.Date > DateTime.Today ? Desk.L("Yarın", "Tomorrow") : Desk.L("Dün", "Yesterday");+ offset.Text = day + ", " + (hours == 0 ? "±0" : (hours > 0 ? "+" : "−") + Math.Abs(hours).ToString("0.#", CultureInfo.InvariantCulture)) + Desk.L(" sa", " h");+ }+ }+ }++ public override void SettingsChanged() => Host.Rebuild();+}diff --git a/DesktopWidgets/Kinds/ToolWidgets.cs b/DesktopWidgets/Kinds/ToolWidgets.csnew file mode 100644index 0000000..a0d43ba--- /dev/null+++ b/DesktopWidgets/Kinds/ToolWidgets.cs@@ -0,0 +1,534 @@+using System.Globalization;+using System.IO;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Input;+using System.Windows.Media;+using QiDock.Services.Widgets;+using QiDock.Widgets;+using static QiDock.DesktopWidgets.DeskUi;++namespace QiDock.DesktopWidgets.Kinds;++/// <summary>App launcher: the dock's pinned apps by default, or apps you pick.</summary>+internal sealed class AppsWidget : DeskWidget+{+ private List<string> Apps+ {+ get+ {+ var own = Option("apps");+ var list = string.IsNullOrWhiteSpace(own) ? Desk.DockApps().ToList() : own.Split('\n', StringSplitOptions.RemoveEmptyEntries).ToList();+ return list.Where(p => File.Exists(p) || Directory.Exists(p) || p.Contains("://", StringComparison.Ordinal)).ToList();+ }+ }++ public override FrameworkElement Build()+ {+ var (columns, rows, icon) = Size switch+ {+ DeskSize.Mini => (3, 1, 40),+ DeskSize.Small => (2, 2, 52),+ DeskSize.Strip => (6, 1, 44),+ DeskSize.Medium => (5, 2, 50),+ _ => (4, 4, 54)+ };+ var apps = Apps.Take(columns * rows).ToList();+ if (apps.Count == 0) return Empty("IconApps", Desk.L("Sağ tık → Uygulama ekle", "Right-click → Add app"));+ var grid = new UniformGrid { Columns = columns, Rows = rows };+ foreach (var path in apps)+ {+ var image = Ui.FileIcon(path, icon);+ var button = new DeskButton(image, () => Ui.Open(path), radius: 14)+ {+ ToolTip = Path.GetFileNameWithoutExtension(path),+ HorizontalAlignment = HorizontalAlignment.Center,+ VerticalAlignment = VerticalAlignment.Center,+ Padding = new Thickness(2)+ };+ grid.Children.Add(button);+ }+ return grid;+ }++ public override void AddMenuItems(ItemsControl menu)+ {+ menu.Items.Add(MenuEntry(Desk.L("Uygulama ekle…", "Add app…"), () =>+ {+ var dialog = new Microsoft.Win32.OpenFileDialog+ {+ Title = Desk.L("Eklenecek uygulama", "App to add"),+ Filter = Desk.L("Uygulamalar ve kısayollar", "Apps and shortcuts") + "|*.exe;*.lnk;*.url;*.appref-ms|" + Desk.L("Tüm dosyalar", "All files") + "|*.*",+ InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu),+ Multiselect = true+ };+ if (dialog.ShowDialog() != true) return;+ var list = Apps;+ list.AddRange(dialog.FileNames.Where(f => !list.Contains(f, StringComparer.OrdinalIgnoreCase)));+ SetOption("apps", string.Join('\n', list));+ Host.Rebuild();+ }));+ if (Option("apps") is not null)+ {+ menu.Items.Add(MenuEntry(Desk.L("Son ekleneni kaldır", "Remove last added"), () =>+ {+ var list = Apps;+ if (list.Count > 0) list.RemoveAt(list.Count - 1);+ SetOption("apps", list.Count == 0 ? null : string.Join('\n', list));+ Host.Rebuild();+ }));+ menu.Items.Add(MenuEntry(Desk.L("Dock'taki uygulamaları göster", "Use the dock's apps"), () =>+ {+ SetOption("apps", null);+ Host.Rebuild();+ }));+ }+ }+}++/// <summary>One-click actions: screenshot, clipboard history, emoji, calculator, lock and more.</summary>+internal sealed class ActionsWidget : DeskWidget+{+ private static readonly (string Icon, string Tr, string En, string Color, Action Run)[] Actions =+ [+ ("IconCamera", "Ekran alıntısı", "Snip", "#FF0A84FF", () => Ui.Open("ms-screenclip:")),+ ("IconClipboard", "Pano geçmişi", "Clipboard history", "#FF30D158", () => Desk.SendWinKey(0x56)),+ ("IconSmile", "Emoji", "Emoji", "#FFFF9F0A", () => Desk.SendWinKey(0xBE)),+ ("IconCalculator", "Hesap makinesi", "Calculator", "#FFBF5AF2", () => Ui.Open("calc.exe")),+ ("IconLock", "Ekranı kilitle", "Lock screen", "#FFFF453A", () => Desk.LockWorkStation()),+ ("IconFolder", "Dosya Gezgini", "File Explorer", "#FF64D2FF", () => Ui.Open("explorer.exe")),+ ("IconActivity", "Görev Yöneticisi", "Task Manager", "#FFFF375F", () => Ui.Open("taskmgr.exe")),+ ("IconSettings", "Ayarlar", "Settings", "#FF8E8E93", () => Ui.Open("ms-settings:"))+ ];++ public override FrameworkElement Build()+ {+ var (count, columns, size) = Size switch+ {+ DeskSize.Mini => (3, 3, 40),+ DeskSize.Small => (4, 2, 48),+ DeskSize.Strip => (6, 6, 42),+ _ => (8, 4, 50)+ };+ var grid = new UniformGrid { Columns = columns };+ foreach (var action in Actions.Take(count))+ {+ var color = Ui.Solid(action.Color);+ var tint = (SolidColorBrush)Ui.Solid("#33" + action.Color[3..]);+ var button = new DeskButton(DeskUi.Icon(action.Icon, size * 0.4, color), action.Run, size, tint)+ {+ ToolTip = Desk.L(action.Tr, action.En),+ HorizontalAlignment = HorizontalAlignment.Center,+ VerticalAlignment = VerticalAlignment.Center+ };+ grid.Children.Add(button);+ }+ return grid;+ }+}++/// <summary>Search box: the web (default browser) or files (Windows search).</summary>+internal sealed class SearchBoxWidget(bool web) : DeskWidget+{+ private static readonly (string Key, string Name, string Url)[] Engines =+ [+ ("google", "Google", "https://www.google.com/search?q="),+ ("bing", "Bing", "https://www.bing.com/search?q="),+ ("duck", "DuckDuckGo", "https://duckduckgo.com/?q="),+ ("youtube", "YouTube", "https://www.youtube.com/results?search_query=")+ ];++ private (string Key, string Name, string Url) Engine => Engines.FirstOrDefault(e => e.Key == (Option("engine") ?? "google")) is { Key: not null } e ? e : Engines[0];++ public override FrameworkElement Build()+ {+ var hint = web ? Desk.L($"{Engine.Name} ile ara…", $"Search {Engine.Name}…") : Desk.L("Dosya ara…", "Find files…");+ var box = DeskInput.Box(hint, 14);+ DeskInput.Focusable(box, Host);+ void Go()+ {+ var query = box.Text.Trim();+ if (query.Length == 0) return;+ if (web) Ui.Open(Engine.Url + Uri.EscapeDataString(query));+ else Ui.Open("search-ms:query=" + Uri.EscapeDataString(query) + "&crumb=location:" + Uri.EscapeDataString(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)));+ box.Clear();+ }+ box.KeyDown += (_, e) =>+ {+ if (e.Key == Key.Enter) Go();+ if (e.Key == Key.Escape) box.Clear();+ };+ var go = DeskButton.Round("IconArrowRight", Go, 28, InsetHover, Text, outline: true, glyph: 13);+ var grid = Grid(columns: "Auto,*,Auto");+ grid.Children.Add(DeskUi.Icon(web ? "IconSearch" : "IconFolder", 16, Secondary));+ grid.Children.Add(At(Margin(DeskInput.WithHint(box), 10, 0, 8), 0, 1));+ grid.Children.Add(At(go, 0, 2));+ var field = DeskInput.Field(grid, 46);+ field.Padding = new Thickness(16, 0, 9, 0);+ field.CornerRadius = new CornerRadius(16);+ field.VerticalAlignment = VerticalAlignment.Center;+ return field;+ }++ public override void AddMenuItems(ItemsControl menu)+ {+ if (!web) return;+ var engines = new MenuItem { Header = Desk.L("Arama motoru", "Search engine") };+ foreach (var engine in Engines)+ engines.Items.Add(MenuEntry(engine.Name, () =>+ {+ SetOption("engine", engine.Key == "google" ? null : engine.Key);+ Host.Rebuild();+ }, Engine.Key == engine.Key));+ menu.Items.Add(engines);+ }+}++/// <summary>Favourite emoji: a click copies one; + opens the Windows emoji panel.</summary>+internal sealed class EmojiWidget : DeskWidget+{+ private const string Defaults = "😂 ✨ ✅ 🔥 🥹 🙏 💡 🚀 ❤️ 👍 🎉 😊 🤔 👀 💯 😍";++ public override FrameworkElement Build()+ {+ var emoji = (Option("set") ?? Defaults).Split(' ', StringSplitOptions.RemoveEmptyEntries);+ var (columns, rows) = Size == DeskSize.Small ? (4, 4) : (5, 2);+ var grid = new UniformGrid { Columns = columns, Rows = rows };+ foreach (var e in emoji.Take(columns * rows - 1))+ {+ var text = new TextBlock { Text = e, FontSize = Size == DeskSize.Small ? 20 : 19, FontFamily = new FontFamily("Segoe UI Emoji"), Foreground = DeskUi.Text, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ TextOptions.SetTextRenderingMode(text, TextRenderingMode.Grayscale);+ grid.Children.Add(new DeskButton(text, () => Copy(e), radius: 8));+ }+ grid.Children.Add(new DeskButton(DeskUi.Icon("IconPlus", 15, Secondary), () => Desk.SendWinKey(0xBE), radius: 8) { ToolTip = Desk.L("Emoji paneli", "Emoji panel") });+ return grid;+ }++ private static void Copy(string emoji)+ {+ try+ {+ Clipboard.SetText(emoji);+ Ui.ShowHud("IconCopy", Desk.L($"{emoji} kopyalandı", $"{emoji} copied"));+ }+ catch (System.Runtime.InteropServices.COMException) { }+ }+}++/// <summary>Saved colors (shared with the bar's color picker): click copies, the pipette picks a new one.</summary>+internal sealed class ColorsDeskWidget : DeskWidget+{+ public override FrameworkElement Build()+ {+ var colors = (Desk.Settings().Colors ?? []).ToList();+ var (columns, rows) = Size == DeskSize.Small ? (2, 2) : (6, 1);+ var grid = new UniformGrid { Columns = columns, Rows = rows };+ foreach (var hex in colors.Take(columns * rows - 1))+ {+ Brush fill;+ try { fill = Ui.Solid(hex); }+ catch (FormatException) { continue; }+ var swatch = new Border { CornerRadius = new CornerRadius(Size == DeskSize.Small ? 14 : 12), Background = fill, Margin = new Thickness(4), BorderBrush = CardStroke, BorderThickness = new Thickness(1) };+ var button = new DeskButton(swatch, () => Copy(hex), radius: 14) { ToolTip = hex };+ button.MouseRightButtonUp += (_, e) =>+ {+ e.Handled = true;+ Desk.UpdateSettings(s => s with { Colors = (s.Colors ?? []).Where(c => !string.Equals(c, hex, StringComparison.OrdinalIgnoreCase)).ToList() });+ Host.Rebuild();+ };+ grid.Children.Add(button);+ }+ var pipette = new Border { CornerRadius = new CornerRadius(14), Background = Inset, Margin = new Thickness(4), Child = DeskUi.Icon("IconPipette", 18, Text) };+ grid.Children.Add(new DeskButton(pipette, Pick, radius: 14) { ToolTip = Desk.L("Ekrandan renk seç", "Pick a color on screen") });+ return grid;+ }++ private void Pick()+ {+ var overlay = new ColorPickerOverlay();+ overlay.Picked += hex =>+ {+ Desk.UpdateSettings(s => s with { Colors = new[] { hex }.Concat((s.Colors ?? []).Where(c => !string.Equals(c, hex, StringComparison.OrdinalIgnoreCase))).Take(24).ToList() });+ Copy(hex);+ Host.Rebuild();+ };+ overlay.Show();+ }++ private static void Copy(string hex)+ {+ try+ {+ Clipboard.SetText(hex);+ Ui.ShowHud("IconCopy", Desk.L($"{hex} kopyalandı", $"{hex} copied"));+ }+ catch (System.Runtime.InteropServices.COMException) { }+ }++ public override void SettingsChanged() => Host.Rebuild();++ public override void AddMenuItems(ItemsControl menu)+ {+ menu.Items.Add(MenuEntry(Desk.L("Renk seç", "Pick a color"), Pick));+ menu.Items.Add(new MenuItem { Header = Desk.L("Tıkla: kopyala · Sağ tık: sil", "Click: copy · Right-click: remove"), IsEnabled = false });+ }+}++/// <summary>Currency converter with European Central Bank rates.</summary>+internal sealed class CurrencyWidget : DeskWidget+{+ private TextBox? _amount;+ private TextBlock? _result, _rate;+ private int _version;++ private string From => Option("from") ?? "USD";+ private string To => Option("to") ?? "TRY";++ public override FrameworkElement Build()+ {+ _amount = DeskInput.Box("0", 16);+ _amount.Text = Option("amount") ?? "100";+ _amount.FontWeight = FontWeights.SemiBold;+ DeskInput.Focusable(_amount, Host);+ _amount.TextChanged += (_, _) =>+ {+ Host.Item.Options["amount"] = _amount.Text;+ Host.Save();+ _ = UpdateAsync();+ };+ _result = Digits("", Size == DeskSize.Small ? 24 : 26, FontWeights.SemiBold);+ _rate = T("", 11, FontWeights.SemiBold, Secondary);+ var from = CurrencyButton(From, code => SetOption("from", code));+ var to = CurrencyButton(To, code => SetOption("to", code));+ var swap = new DeskButton(DeskUi.Icon("IconSwap", 13, Secondary), () =>+ {+ var (a, b) = (From, To);+ Host.Item.Options["from"] = b;+ Host.Item.Options["to"] = a;+ Host.Save();+ Host.Rebuild();+ }, 24);+ if (Size == DeskSize.Small)+ {+ var top = Grid(columns: "*,Auto");+ top.Children.Add(_amount);+ top.Children.Add(At(from, 0, 1));+ var bottom = Grid(columns: "*,Auto");+ bottom.Children.Add(_result);+ bottom.Children.Add(At(to, 0, 1));+ swap.HorizontalAlignment = HorizontalAlignment.Right;+ return Column(top, Margin(swap, 0, 4, 2, 4), bottom, Margin(_rate, 0, 6));+ }+ _result.FontSize = 18;+ _amount.VerticalAlignment = _result.VerticalAlignment = VerticalAlignment.Center;+ var left = Grid(columns: "*,Auto");+ left.Children.Add(_amount);+ left.Children.Add(At(from, 0, 1));+ var right = Grid(columns: "*,Auto");+ right.Children.Add(_result);+ right.Children.Add(At(to, 0, 1));+ var row = Grid(columns: "*,Auto,*");+ row.Children.Add(left);+ row.Children.Add(At(Margin(swap, 6, 0, 6, 0), 0, 1));+ row.Children.Add(At(Margin(right, 4, 0, 0, 0), 0, 2));+ var grid = Grid("*,Auto");+ grid.Children.Add(At(row, 0));+ grid.Children.Add(At(Margin(_rate, 0, 2), 1));+ return grid;+ }++ private DeskButton CurrencyButton(string code, Action<string> choose)+ {+ var label = T(code, 11.5, FontWeights.Bold);+ label.Margin = new Thickness(8, 0, 8, 0);+ var button = new DeskButton(label, background: InsetHover, radius: 9) { Height = 20 };+ button.Click += (_, _) =>+ {+ var menu = new ContextMenu { PlacementTarget = button, Placement = PlacementMode.Bottom };+ foreach (var currency in RatesHub.Currencies)+ menu.Items.Add(MenuEntry(currency, () =>+ {+ choose(currency);+ Host.Rebuild();+ }, currency == code));+ menu.IsOpen = true;+ };+ return button;+ }++ public override TimeSpan? Interval => TimeSpan.FromMinutes(30);+ protected override void OnAttach() => _ = UpdateAsync();+ public override void Tick() => _ = UpdateAsync();++ private async Task UpdateAsync()+ {+ var version = ++_version;+ if (_amount is null || _result is null || _rate is null) return;+ var text = _amount.Text.Replace(" ", "", StringComparison.Ordinal);+ if (!double.TryParse(text, NumberStyles.Number, Desk.Culture, out var amount) && !double.TryParse(text, NumberStyles.Number, CultureInfo.InvariantCulture, out amount))+ {+ _result.Text = "–";+ return;+ }+ var rate = await RatesHub.RateAsync(From, To);+ if (version != _version) return;+ if (rate is not { } value)+ {+ _result.Text = "–";+ _rate.Text = Desk.L("Kur alınamadı", "Rate unavailable");+ return;+ }+ _result.Text = (amount * value).ToString("N2", Desk.Culture);+ _rate.Text = $"1 {From} = {value.ToString("N4", Desk.Culture)} {To}";+ }+}++/// <summary>Output volume with mute, following changes made elsewhere.</summary>+internal sealed class SoundWidget : DeskWidget+{+ private readonly AudioEndpoint _endpoint = new();+ private Slider? _slider;+ private TextBlock? _percent, _device;+ private DeskButton? _mute;+ private bool _updating;++ public override TimeSpan? Interval => TimeSpan.FromSeconds(2);++ public override FrameworkElement Build()+ {+ _slider = new Slider { Minimum = 0, Maximum = 100, VerticalAlignment = VerticalAlignment.Center, IsMoveToPointEnabled = true };+ _slider.SetResourceReference(FrameworkElement.StyleProperty, "WidgetSlider");+ _slider.ValueChanged += (_, e) =>+ {+ if (_updating) return;+ _endpoint.SetVolume((float)(e.NewValue / 100));+ if (_percent is not null) _percent.Text = Percent(e.NewValue);+ };+ _slider.PreviewMouseWheel += (_, e) =>+ {+ _slider.Value = Math.Clamp(_slider.Value + Math.Sign(e.Delta) * 4, 0, 100);+ e.Handled = true;+ };+ _percent = Digits("", 12, FontWeights.SemiBold, Secondary);+ _percent.Width = 38;+ _percent.TextAlignment = TextAlignment.Right;+ _device = T("", 12, FontWeights.SemiBold, Secondary);+ _mute = new DeskButton(DeskUi.Icon("IconVolume", 16, Text), ToggleMute, 30, Inset);+ var row = Grid(columns: "Auto,*,Auto");+ row.Children.Add(_mute);+ row.Children.Add(At(Margin(_slider, 10, 0, 4), 0, 1));+ row.Children.Add(At(_percent, 0, 2));+ if (Size == DeskSize.Mini) return row;+ var settings = new DeskButton(DeskUi.Icon("IconSettings", 13, Secondary), () => Ui.Open("ms-settings:sound"), 24) { ToolTip = Desk.L("Ses ayarları", "Sound settings") };+ var header = Grid(columns: "*,Auto");+ header.Children.Add(_device);+ header.Children.Add(At(settings, 0, 1));+ var grid = Grid("Auto,*");+ grid.Children.Add(header);+ grid.Children.Add(At(Margin(row, 0, 4), 1));+ return grid;+ }++ public override void Tick()+ {+ if (_endpoint.Read() is not { } state || _slider is null) return;+ _updating = true;+ if (!_slider.IsMouseCaptureWithin) _slider.Value = state.Volume * 100;+ _updating = false;+ _percent!.Text = Percent(state.Volume * 100);+ if (_device is not null) _device.Text = state.DeviceName;+ _mute!.Child = DeskUi.Icon(state.Muted ? "IconVolumeMute" : "IconVolume", 16, state.Muted ? Red : Text);+ }++ private void ToggleMute()+ {+ if (_endpoint.Read() is { } state) _endpoint.SetMute(!state.Muted);+ Tick();+ }++ public override void Dispose()+ {+ _endpoint.Dispose();+ base.Dispose();+ }+}++/// <summary>Quick settings: Wi-Fi, Bluetooth, night light, focus, on-screen keyboard.</summary>+internal sealed class TogglesWidget : DeskWidget+{+ private static RadioControls? _radios;+ private DeskButton? _wifi, _bluetooth;++ public override FrameworkElement Build()+ {+ _wifi = Toggle("IconWifi", Blue, async () =>+ {+ if (_radios is not null) await _radios.ToggleWifiAsync();+ Tick();+ }, Desk.L("Wi-Fi", "Wi-Fi"));+ _bluetooth = Toggle("IconBluetooth", Blue, async () =>+ {+ if (_radios is not null) await _radios.ToggleBluetoothAsync();+ Tick();+ }, "Bluetooth");+ var night = Toggle("IconMoon", Orange, () => Ui.Open("ms-settings:nightlight"), Desk.L("Gece ışığı", "Night light"));+ var focus = Toggle("IconBell", Purple, () => Ui.Open("ms-settings:quiethours"), Desk.L("Bildirimler / odak", "Notifications / focus"));+ var keyboard = Toggle("IconKeyboard", Secondary, () => Ui.Open("osk.exe"), Desk.L("Ekran klavyesi", "On-screen keyboard"));+ var grid = new UniformGrid { Columns = Size == DeskSize.Small ? 2 : 5, Rows = Size == DeskSize.Small ? 2 : 1 };+ grid.Children.Add(_wifi);+ grid.Children.Add(_bluetooth);+ grid.Children.Add(night);+ grid.Children.Add(focus);+ if (Size != DeskSize.Small) grid.Children.Add(keyboard);+ return grid;+ }++ private static DeskButton Toggle(string icon, Brush color, Action click, string tooltip)+ {+ var button = new DeskButton(DeskUi.Icon(icon, 18, Text), click, 48, Inset)+ {+ ToolTip = tooltip,+ BorderThickness = new Thickness(1.5),+ BorderBrush = Brushes.Transparent,+ HorizontalAlignment = HorizontalAlignment.Center,+ VerticalAlignment = VerticalAlignment.Center,+ Tag = color+ };+ return button;+ }++ protected override async void OnAttach()+ {+ if (_radios is null)+ {+ _radios = new RadioControls();+ try { await _radios.InitializeAsync(); }+ catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or UnauthorizedAccessException or InvalidOperationException) { }+ }+ _radios.Changed += RadiosChanged;+ Tick();+ }++ protected override void OnDetach()+ {+ if (_radios is not null) _radios.Changed -= RadiosChanged;+ }++ private void RadiosChanged(object? sender, EventArgs e) => Application.Current.Dispatcher.InvokeAsync(Tick);++ public override void Tick()+ {+ Paint(_wifi, _radios?.HasWifi == true, _radios?.WifiOn == true, "IconWifi", "IconWifiOff");+ Paint(_bluetooth, _radios?.HasBluetooth == true, _radios?.BluetoothOn == true, "IconBluetooth", "IconBluetoothOff");+ }++ private static void Paint(DeskButton? button, bool available, bool on, string onIcon, string offIcon)+ {+ if (button is null) return;+ var color = (Brush)button.Tag;+ button.Opacity = available ? 1 : 0.4;+ button.BorderBrush = on ? color : Brushes.Transparent;+ button.Child = DeskUi.Icon(on ? onIcon : offIcon, 18, on ? color : Secondary);+ }+}diff --git a/DesktopWidgets/Kinds/WeatherWidgets.cs b/DesktopWidgets/Kinds/WeatherWidgets.csnew file mode 100644index 0000000..41ea328--- /dev/null+++ b/DesktopWidgets/Kinds/WeatherWidgets.cs@@ -0,0 +1,313 @@+using System.Globalization;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media;+using QiDock.Services.Widgets;+using QiDock.Widgets;+using static QiDock.DesktopWidgets.DeskUi;++namespace QiDock.DesktopWidgets.Kinds;++/// <summary>Weather from the widget-settings city: now, the next hours and the coming days.</summary>+internal sealed class WeatherDeskWidget : DeskWidget+{+ private Border? _root;++ private bool Colored => Option("plain") != "1";++ public override FrameworkElement Build()+ {+ _root = new Border { Margin = Negative(Desk.Padding(Size)), Padding = Desk.Padding(Size) };+ Render();+ return _root;+ }++ private static Thickness Negative(Thickness t) => new(-t.Left, -t.Top, -t.Right, -t.Bottom);++ protected override void OnAttach()+ {+ WeatherHub.Instance.Subscribe(Render);+ Render(); // data may have arrived while this widget was covered+ }+ protected override void OnDetach() => WeatherHub.Instance.Unsubscribe(Render);++ private void Render()+ {+ if (_root is null) return;+ if (WeatherHub.Instance.Report is not { } r)+ {+ _root.Background = null;+ _root.Child = Empty("IconMapPin", WeatherHub.Instance.Error ?? Desk.L("Hava durumu yükleniyor…", "Loading weather…"));+ return;+ }+ _root.Background = Colored ? WeatherArt.Sky(r.Code, r.IsDay) : null;+ _root.Child = Size switch+ {+ DeskSize.Mini => Mini(r),+ DeskSize.Small => Small(r),+ DeskSize.Strip => Hours(r, r.Hours.Count),+ DeskSize.Medium => Medium(r),+ _ => Large(r)+ };+ }++ private static FrameworkElement Icon(WeatherReport r, double size) => WeatherArt.Create(r.Code, r.IsDay, size);++ private static FrameworkElement Mini(WeatherReport r)+ {+ var grid = Grid(columns: "Auto,*");+ grid.Children.Add(Icon(r, 38));+ var temp = T(WeatherHub.Temp(r.Temperature), 30, FontWeights.SemiBold);+ var city = T(r.City, 11.5, FontWeights.SemiBold, Secondary);+ grid.Children.Add(At(Margin(Column(temp, city), 10), 0, 1));+ return grid;+ }++ private static FrameworkElement Small(WeatherReport r)+ {+ var city = Row(T(r.City, 14, FontWeights.SemiBold), Margin(DeskUi.Icon("IconMapPin", 11, Text), 4));+ var temp = T(WeatherHub.Temp(r.Temperature), 46, FontWeights.Light);+ var icon = Icon(r, 30);+ icon.HorizontalAlignment = HorizontalAlignment.Left;+ var condition = T(WeatherService.Describe(r.Code), 12.5, FontWeights.SemiBold);+ var range = T(Desk.L("Y:", "H:") + WeatherHub.Temp(r.TodayMax) + " " + Desk.L("D:", "L:") + WeatherHub.Temp(r.TodayMin), 12, FontWeights.SemiBold, Secondary);+ var grid = Grid("Auto,*,Auto,Auto,Auto");+ grid.Children.Add(city);+ grid.Children.Add(At(Margin(temp, -2, -6, 0, 0), 1));+ grid.Children.Add(At(icon, 2));+ grid.Children.Add(At(condition, 3));+ grid.Children.Add(At(range, 4));+ return grid;+ }++ private static FrameworkElement Hours(WeatherReport r, int count)+ {+ var grid = Grid(columns: string.Join(",", Enumerable.Repeat("*", Math.Max(1, Math.Min(count, r.Hours.Count)))));+ var i = 0;+ foreach (var hour in r.Hours.Take(count))+ {+ var label = T(i == 0 ? Desk.L("Şimdi", "Now") : hour.Time.ToString("HH", CultureInfo.InvariantCulture), 11.5, FontWeights.SemiBold, Secondary);+ var icon = WeatherArt.Create(hour.Code, hour.IsDay, 22);+ icon.Margin = new Thickness(0, 3, 0, 3);+ var temp = T(WeatherHub.Temp(hour.Temperature), 13, FontWeights.SemiBold);+ foreach (var e in new FrameworkElement[] { label, icon, temp }) e.HorizontalAlignment = HorizontalAlignment.Center;+ grid.Children.Add(At(Column(label, icon, temp), 0, i++));+ }+ return grid;+ }++ private static FrameworkElement Now(WeatherReport r, double tempSize)+ {+ var city = Row(T(r.City, 15, FontWeights.SemiBold), Margin(DeskUi.Icon("IconMapPin", 11, Text), 4));+ var temp = T(WeatherHub.Temp(r.Temperature), tempSize, FontWeights.Light);+ temp.Margin = new Thickness(-2, -4, 0, -4);+ var right = Column(Icon(r, 34), T(WeatherService.Describe(r.Code), 12.5, FontWeights.SemiBold),+ T(Desk.L("Y:", "H:") + WeatherHub.Temp(r.TodayMax) + " " + Desk.L("D:", "L:") + WeatherHub.Temp(r.TodayMin), 12, FontWeights.SemiBold, Secondary));+ right.HorizontalAlignment = HorizontalAlignment.Right;+ foreach (UIElement child in right.Children)+ if (child is FrameworkElement fe) fe.HorizontalAlignment = HorizontalAlignment.Right;+ var grid = Grid(columns: "*,Auto");+ grid.Children.Add(Column(city, temp));+ grid.Children.Add(At(right, 0, 1));+ return grid;+ }++ private static FrameworkElement Medium(WeatherReport r)+ {+ var grid = Grid("Auto,*,Auto");+ grid.Children.Add(Now(r, 40));+ grid.Children.Add(At(new Border { Height = 1, Background = Track, Margin = new Thickness(0, 8, 0, 6), VerticalAlignment = VerticalAlignment.Bottom }, 1));+ grid.Children.Add(At(Hours(r, 6), 2));+ return grid;+ }++ private static FrameworkElement Large(WeatherReport r)+ {+ var grid = Grid("Auto,Auto,Auto,*");+ grid.Children.Add(Now(r, 48));+ grid.Children.Add(At(Margin(Hours(r, 6), 0, 10, 0, 8), 1));+ grid.Children.Add(At(new Border { Height = 1, Background = Track, Margin = new Thickness(0, 0, 0, 6) }, 2));+ var days = new StackPanel();+ var low = r.Days.Take(5).Select(d => d.Min).DefaultIfEmpty(0).Min();+ var high = r.Days.Take(5).Select(d => d.Max).DefaultIfEmpty(1).Max();+ var i = 0;+ foreach (var day in r.Days.Take(5))+ {+ var row = Grid(columns: "70,32,36,*,36");+ row.Margin = new Thickness(0, 2, 0, 2);+ row.Children.Add(T(i++ == 0 ? Desk.L("Bugün", "Today") : day.Date.ToString("ddd", Desk.Culture), 13, FontWeights.SemiBold));+ row.Children.Add(At(WeatherArt.Create(day.Code, true, 20), 0, 1));+ var min = T(WeatherHub.Temp(day.Min), 13, FontWeights.SemiBold, Secondary);+ min.HorizontalAlignment = HorizontalAlignment.Right;+ row.Children.Add(At(min, 0, 2));+ var bar = new Grid { Height = 5, Margin = new Thickness(10, 0, 10, 0) };+ bar.Children.Add(new Border { CornerRadius = new CornerRadius(2.5), Background = Track });+ var span = Math.Max(1, high - low);+ var fill = new Border+ {+ CornerRadius = new CornerRadius(2.5),+ Background = new LinearGradientBrush(Color.FromRgb(0x64, 0xD2, 0xFF), Color.FromRgb(0xFF, 0x9F, 0x0A), 0),+ HorizontalAlignment = HorizontalAlignment.Left+ };+ bar.Children.Add(fill);+ bar.SizeChanged += (_, e) =>+ {+ fill.Margin = new Thickness(e.NewSize.Width * (day.Min - low) / span, 0, 0, 0);+ fill.Width = Math.Max(5, e.NewSize.Width * (day.Max - day.Min) / span);+ };+ row.Children.Add(At(bar, 0, 3));+ var max = T(WeatherHub.Temp(day.Max), 13, FontWeights.SemiBold);+ max.HorizontalAlignment = HorizontalAlignment.Right;+ row.Children.Add(At(max, 0, 4));+ days.Children.Add(row);+ }+ grid.Children.Add(At(days, 3));+ return grid;+ }++ public override void SettingsChanged() => Render();++ public override void AddMenuItems(ItemsControl menu)+ {+ menu.Items.Add(MenuEntry(Desk.L("Gökyüzü renginde arka plan", "Sky-colored background"), () =>+ {+ SetOption("plain", Colored ? "1" : null);+ Render();+ }, Colored));+ menu.Items.Add(MenuEntry(Desk.L("Yenile", "Refresh"), () => _ = WeatherHub.Instance.RefreshAsync()));+ }+}++/// <summary>Sunrise and sunset with the sun's place on its arc.</summary>+internal sealed class SunWidget : DeskWidget+{+ private SunArc? _arc;+ private TextBlock? _rise, _set, _middle, _title, _big;++ public override TimeSpan? Interval => TimeSpan.FromMinutes(1);++ public override FrameworkElement Build()+ {+ _arc = new SunArc();+ _rise = Digits("", 13, FontWeights.SemiBold);+ _set = Digits("", 13, FontWeights.SemiBold);+ _middle = T("", 11.5, FontWeights.SemiBold, Secondary);+ if (Size == DeskSize.Small)+ {+ _title = T("", 12.5, FontWeights.SemiBold, Orange);+ _big = Digits("", 34, FontWeights.SemiBold);+ var grid = Grid("Auto,Auto,*,Auto");+ grid.Children.Add(_title);+ grid.Children.Add(At(_big, 1));+ grid.Children.Add(At(Margin(_arc, 0, 8, 0, 4), 2));+ grid.Children.Add(At(_middle, 3));+ return grid;+ }+ var footer = Grid(columns: "Auto,*,Auto");+ footer.Children.Add(Row(DeskUi.Icon("IconSunrise", 13, Orange), Margin(_rise, 5)));+ _middle.HorizontalAlignment = HorizontalAlignment.Center;+ footer.Children.Add(At(_middle, 0, 1));+ footer.Children.Add(At(Row(_set, Margin(DeskUi.Icon("IconSunset", 13, Orange), 5)), 0, 2));+ var layout = Grid("*,Auto");+ layout.Children.Add(Margin(_arc, 0, 0, 0, 4));+ layout.Children.Add(At(footer, 1));+ return layout;+ }++ protected override void OnAttach() => WeatherHub.Instance.Subscribe(Tick);+ protected override void OnDetach() => WeatherHub.Instance.Unsubscribe(Tick);++ public override void Tick()+ {+ if (WeatherHub.Instance.Report?.Extra is not { Sunrise: { } rise, Sunset: { } set } extra)+ {+ _middle?.SetCurrentValue(TextBlock.TextProperty, WeatherHub.Instance.Error ?? Desk.L("Yükleniyor…", "Loading…"));+ return;+ }+ var now = DateTime.Now;+ var length = set - rise;+ _arc?.SetProgress((now - rise).TotalMinutes / Math.Max(1, length.TotalMinutes));+ _rise!.Text = rise.ToString("HH:mm", CultureInfo.InvariantCulture);+ _set!.Text = set.ToString("HH:mm", CultureInfo.InvariantCulture);+ _middle!.Text = Desk.L($"Gün {(int)length.TotalHours} sa {length.Minutes} dk", $"Day {(int)length.TotalHours} h {length.Minutes} m");+ if (_title is null || _big is null) return;+ if (now < rise)+ {+ _title.Text = Desk.L("Gün doğumu", "Sunrise");+ _big.Text = rise.ToString("HH:mm", CultureInfo.InvariantCulture);+ }+ else if (now < set)+ {+ _title.Text = Desk.L("Gün batımı", "Sunset");+ _big.Text = set.ToString("HH:mm", CultureInfo.InvariantCulture);+ }+ else+ {+ _title.Text = Desk.L("Gün doğumu (yarın)", "Sunrise (tomorrow)");+ _big.Text = (extra.NextSunrise ?? rise.AddDays(1)).ToString("HH:mm", CultureInfo.InvariantCulture);+ }+ }+}++/// <summary>Wind speed, gusts and direction.</summary>+internal sealed class WindWidget : DeskWidget+{+ private Compass? _compass;+ private TextBlock? _speed, _detail;++ public override FrameworkElement Build()+ {+ _compass = new Compass();+ _speed = T("", Size == DeskSize.Small ? 22 : 26, FontWeights.SemiBold);+ _detail = T("", 11.5, FontWeights.SemiBold, Secondary);+ _detail.TextWrapping = TextWrapping.Wrap;+ if (Size == DeskSize.Small)+ {+ _compass.Width = _compass.Height = 58;+ _compass.VerticalAlignment = VerticalAlignment.Top;+ var top = Grid(columns: "*,Auto");+ var title = T(Desk.L("Rüzgâr", "Wind"), 12.5, FontWeights.SemiBold, Cyan);+ title.VerticalAlignment = VerticalAlignment.Top;+ top.Children.Add(title);+ top.Children.Add(At(_compass, 0, 1));+ var small = Grid("Auto,Auto,*");+ small.Children.Add(top);+ small.Children.Add(At(Margin(_speed, 0, 2), 1));+ _detail.VerticalAlignment = VerticalAlignment.Bottom;+ small.Children.Add(At(_detail, 2));+ return small;+ }+ _compass.Width = _compass.Height = 52;+ var grid = Grid(columns: "Auto,*");+ grid.Children.Add(_compass);+ grid.Children.Add(At(Margin(Column(_speed, _detail), 12), 0, 1));+ return grid;+ }++ protected override void OnAttach() => WeatherHub.Instance.Subscribe(Tick);+ protected override void OnDetach() => WeatherHub.Instance.Unsubscribe(Tick);++ public override void Tick()+ {+ if (WeatherHub.Instance.Report?.Extra is not { } extra || double.IsNaN(extra.WindSpeed))+ {+ if (_detail is not null) _detail.Text = WeatherHub.Instance.Error ?? Desk.L("Yükleniyor…", "Loading…");+ return;+ }+ _compass?.SetDirection(extra.WindDirection);+ _speed!.Text = Math.Round(extra.WindSpeed).ToString(CultureInfo.InvariantCulture) + Desk.L(" km/sa", " km/h");+ var direction = Direction(extra.WindDirection);+ var gust = double.IsNaN(extra.WindGusts) ? "" : Desk.L($"Hamle {Math.Round(extra.WindGusts)} km/sa", $"Gusts {Math.Round(extra.WindGusts)} km/h");+ _detail!.Text = Size == DeskSize.Small+ ? direction + (gust.Length > 0 ? Environment.NewLine + gust : "")+ : Desk.L($"{direction} rüzgârı", $"{direction} wind") + (gust.Length > 0 ? " · " + gust : "");+ }++ private static string Direction(double degrees)+ {+ string[] tr = ["K", "KD", "D", "GD", "G", "GB", "B", "KB"];+ string[] en = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];+ var index = (int)Math.Round(((degrees % 360) + 360) % 360 / 45) % 8;+ return Desk.L(tr[index], en[index]);+ }+}diff --git a/DockHud.cs b/DockHud.csnew file mode 100644index 0000000..2ded32c--- /dev/null+++ b/DockHud.cs@@ -0,0 +1,110 @@+using System.Globalization;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Documents;+using System.Windows.Media;+using System.Windows.Threading;+using QiDock.Widgets;++namespace QiDock;++/// <summary>+/// A small status card that grows out of the middle of the dock the way the bell's list does: a level ("Ses ▬▬ 57",+/// "Parlaklık ▬▬ 75") or a short message, sinking back a moment later.+/// </summary>+public sealed class DockHud : EdgePanel+{+ private const double BarWidth = 64;+ private static readonly TimeSpan Linger = TimeSpan.FromMilliseconds(1400);++ private static DockHud? _shared;+ public static DockHud Shared => _shared ??= new DockHud();+ public static bool IsCreated => _shared is not null;++ private readonly ContentControl _icon = new() { Width = 20, Height = 20, Focusable = false, VerticalAlignment = VerticalAlignment.Center };+ private readonly TextBlock _label = Ui.Text("", 14, FontWeights.SemiBold);+ private readonly Border _track;+ private readonly Border _fill;+ private readonly TextBlock _value = Ui.Text("", 13.5, FontWeights.SemiBold, brushKey: "TextSecondary");+ private readonly Border _body;+ private readonly DispatcherTimer _hide;++ private DockHud() : base(270, "QiDock HUD")+ {+ _label.Margin = new Thickness(12, 0, 0, 0);+ _label.VerticalAlignment = VerticalAlignment.Center;+ _label.TextTrimming = TextTrimming.CharacterEllipsis;+ _fill = new Border { CornerRadius = new CornerRadius(3), HorizontalAlignment = HorizontalAlignment.Left };+ _track = new Border { Width = BarWidth, Height = 6, CornerRadius = new CornerRadius(3), Child = _fill, VerticalAlignment = VerticalAlignment.Center };+ _track.SetResourceReference(Border.BackgroundProperty, "WidgetTrack");+ _value.Width = 34;+ _value.TextAlignment = TextAlignment.Right;+ _value.VerticalAlignment = VerticalAlignment.Center;+ var row = new DockPanel { LastChildFill = true, Height = 34 };+ DockPanel.SetDock(_icon, Dock.Left);+ DockPanel.SetDock(_value, Dock.Right);+ DockPanel.SetDock(_track, Dock.Right);+ row.Children.Add(_icon);+ row.Children.Add(_value);+ row.Children.Add(_track);+ row.Children.Add(_label);++ _body = new Border { Padding = new Thickness(10, 2, 8, 2), Width = CardWidth, Child = row };+ _body.SetResourceReference(TextElement.ForegroundProperty, "TextPrimary");++ _hide = new DispatcherTimer(DispatcherPriority.Normal) { Interval = Linger };+ _hide.Tick += (_, _) =>+ {+ _hide.Stop();+ Close(animated: true);+ };+ }++ /// <summary>Volume, brightness…: a label, a short bar in <paramref name="accent"/> and the value.</summary>+ public void ShowLevel(DockAnchor anchor, string iconKey, string label, int percent, Brush accent, bool dimmed = false)+ {+ SetLevel(iconKey, label, percent, accent, dimmed);+ Present(anchor, Linger);+ }++#if DEBUG+ internal void RehearseLevel(string iconKey, string label, int percent, Brush accent) => SetLevel(iconKey, label, percent, accent, false);+#endif++ private void SetLevel(string iconKey, string label, int percent, Brush accent, bool dimmed)+ {+ _icon.Content = Ui.Icon(iconKey, 20);+ _label.Text = label;+ _fill.Width = BarWidth * Math.Clamp(percent, 0, 100) / 100.0;+ _fill.Background = accent;+ _fill.Opacity = dimmed ? 0.35 : 1;+ _value.Text = dimmed ? "" : percent.ToString(CultureInfo.CurrentCulture);+ _track.Visibility = _value.Visibility = Visibility.Visible;+ }++ /// <summary>An icon and a short sentence ("Kopyalandı", "Odak süresi bitti").</summary>+ public void ShowMessage(DockAnchor anchor, string iconKey, string text)+ {+ _icon.Content = Ui.Icon(iconKey, 20);+ _label.Text = text;+ _track.Visibility = _value.Visibility = Visibility.Collapsed;+ Present(anchor, TimeSpan.FromMilliseconds(2200));+ }++ private void Present(DockAnchor anchor, TimeSpan linger)+ {+ _hide.Stop();+ _hide.Interval = linger;+ if (!IsOpen) ToggleFromDock(anchor);+ _hide.Start();+ }++ protected override void Build()+ {+ if (_body.Parent is Panel old) old.Children.Remove(_body);+ Cards.Children.Clear();+ Cards.Children.Add(_body);+ }++ protected override void OnHidden() => _hide.Stop();+}diff --git a/DockPreview.cs b/DockPreview.csnew file mode 100644index 0000000..e0da771--- /dev/null+++ b/DockPreview.cs@@ -0,0 +1,441 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Shapes;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;++namespace QiDock;++/// <summary>+/// A small picture of the desktop in the settings window: the dock as the choices in the window would make it+/// (edge, position, look, opacity, where the widgets go, auto-hide), redrawn on every change before anything is+/// applied. Pointing at its icons shows the magnification at the chosen size, and resting on one shows the window+/// preview after the same half second the real dock waits.+/// </summary>+public sealed class DockPreview : Border+{+ private const double W = 640, H = 196, Tile = 24, Gap = 5, Bar = 36, Margin8 = 8;+ private static readonly string[] AppColors = ["#FF0A84FF", "#FFFF9F0A", "#FF30D158", "#FFD97757", "#FFBF5AF2", "#FFFF375F", "#FF64D2FF"];++ private readonly Canvas _canvas = new() { Width = W, Height = H, ClipToBounds = true };+ private readonly TextBlock _caption = new() { FontSize = 12, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(2, 8, 2, 0) };+ private readonly DispatcherTimer _previewDelay = new() { Interval = TimeSpan.FromMilliseconds(500) };+ private readonly DispatcherTimer _demo = new() { Interval = TimeSpan.FromMilliseconds(16) };+ private DockSettings? _settings;+ private int _visibleWidgets;+ private double? _pointer; // along the dock, in un-magnified dock coordinates+ private int _restingOn = -1;+ private bool _showWindowPreview;+ private DateTime _demoStarted;++ public DockPreview()+ {+ Padding = new Thickness(16, 12, 16, 10);+ var stack = new StackPanel();+ var frame = new Border { CornerRadius = new CornerRadius(12), ClipToBounds = true, Child = new Viewbox { Child = _canvas, Stretch = Stretch.Uniform, MaxHeight = 132 } };+ stack.Children.Add(frame);+ _caption.SetResourceReference(TextBlock.ForegroundProperty, "TextSecondary");+ stack.Children.Add(_caption);+ Child = stack;++ _canvas.MouseMove += (_, e) => Point(e.GetPosition(_canvas));+ _canvas.MouseLeave += (_, _) =>+ {+ _pointer = null;+ _restingOn = -1;+ _showWindowPreview = false;+ _previewDelay.Stop();+ Draw();+ };+ _previewDelay.Tick += (_, _) =>+ {+ _previewDelay.Stop();+ _showWindowPreview = _settings?.PreviewsEnabled == true && _restingOn >= 0;+ Draw();+ };+ // After the magnification size changes, a sweep across the icons shows what it will look like.+ _demo.Tick += (_, _) =>+ {+ var t = (DateTime.Now - _demoStarted).TotalSeconds / 1.4;+ if (t >= 1)+ {+ _demo.Stop();+ _pointer = null;+ }+ else _pointer = AppStart + (0.15 + 0.7 * t) * AppCount * Cell;+ Draw();+ };+ }++ /// <summary>Draws the dock for <paramref name="settings"/>; <paramref name="showMagnify"/> plays the magnification once.</summary>+ public void Show(DockSettings settings, int visibleWidgets, bool showMagnify = false)+ {+ _settings = settings;+ _visibleWidgets = Math.Clamp(visibleWidgets, 0, 7);+ if (showMagnify && settings.Magnify && settings.AnimationsEnabled)+ {+ _demoStarted = DateTime.Now;+ _demo.Start();+ }+ Draw();+ }++ // ---- Geometry along the dock ---------------------------------------------------------------++ private const int AppCount = 7;+ private const double Cell = Tile + Gap;+ private static bool Vertical(DockSettings s) => s.Edge is DockEdge.Left or DockEdge.Right;+ private bool WidgetsInDock => _settings?.WidgetPlacement is WidgetPlacement.DockLeft or WidgetPlacement.DockRight;++ /// <summary>Where the first app tile starts along the dock (after Start and, on the left, the widgets).</summary>+ private double AppStart => 8 + Cell + (_settings?.WidgetPlacement == WidgetPlacement.DockLeft ? WidgetLength + 8 : 0);++ private double WidgetLength => _visibleWidgets == 0 ? 0 : Enumerable.Range(0, _visibleWidgets).Sum(WidgetSize) + (_visibleWidgets - 1) * 4;++ private double WidgetSize(int index) => _settings is not null && Vertical(_settings) ? 26 : index switch { 0 => 52, 1 => 42, 2 => 46, 3 => 36, _ => 26 };++ private void Point(Point at)+ {+ if (_settings is null || _demo.IsEnabled) return;+ var (origin, along, across) = DockFrame(_settings, DrawnLength());+ var main = Vertical(_settings) ? at.Y - origin.Y : at.X - origin.X;+ var cross = Vertical(_settings) ? at.X - origin.X : at.Y - origin.Y;+ var inside = cross >= -Tile * 1.2 && cross <= across + Tile * 0.4 && main >= 0 && main <= along + 40;+ if (!inside)+ {+ if (_pointer is null) return;+ _pointer = null;+ _restingOn = -1;+ _showWindowPreview = false;+ _previewDelay.Stop();+ Draw();+ return;+ }+ // Back to un-magnified coordinates: the dock grows around the pointer, so map through the drawn tiles.+ _pointer = Unmagnify(main);+ var over = (int)Math.Floor((_pointer.Value - AppStart) / Cell);+ var app = over is >= 0 and < AppCount ? over : -1;+ if (app != _restingOn)+ {+ _restingOn = app;+ _showWindowPreview = false;+ _previewDelay.Stop();+ if (app >= 0 && app < 4) _previewDelay.Start(); // the first four apps "have windows"+ }+ Draw();+ }++ private double Unmagnify(double drawn)+ {+ // Walk the tiles as drawn and find the base position under the pointer.+ var items = Items();+ double drawnPos = 8, basePos = 8;+ foreach (var item in items)+ {+ var size = item.Size * item.Scale + (item.Gap);+ if (drawn < drawnPos + size) return basePos + (drawn - drawnPos) / size * (item.Size + item.Gap);+ drawnPos += size;+ basePos += item.Size + item.Gap;+ }+ return basePos;+ }++ private sealed record Item(string Kind, double Size, double Gap, int Index)+ {+ public double Scale { get; set; } = 1;+ }++ /// <summary>The dock's contents along its length, each with its magnification for the pointer.</summary>+ private List<Item> Items()+ {+ var s = _settings!;+ var list = new List<Item>();+ void Widgets()+ {+ for (var i = 0; i < _visibleWidgets; i++) list.Add(new Item("widget", WidgetSize(i), 4, i));+ if (_visibleWidgets > 0) list[^1] = list[^1] with { Gap = 8 };+ }+ if (s.WidgetPlacement == WidgetPlacement.DockLeft) Widgets();+ list.Add(new Item("start", Tile, Gap, 0));+ for (var i = 0; i < AppCount; i++) list.Add(new Item("app", Tile, Gap, i));+ list.Add(new Item("divider", 1, Gap + 2, 0));+ list.Add(new Item("downloads", Tile, Gap, 0));+ list.Add(new Item("trash", Tile, s.WidgetPlacement == WidgetPlacement.DockRight ? 8 : 0, 0));+ if (s.WidgetPlacement == WidgetPlacement.DockRight) Widgets();++ var magnify = s.Magnify && s.AnimationsEnabled && _pointer is not null;+ var max = Math.Clamp(s.MagnifyScale, 1.1, 2.2);+ double pos = 8;+ foreach (var item in list)+ {+ if (magnify && item.Kind is "start" or "app" or "downloads" or "trash")+ {+ var d = Math.Abs(_pointer!.Value - (pos + item.Size / 2));+ var radius = Cell * 3.2;+ if (d < radius)+ {+ var f = Math.Cos(d / radius * Math.PI / 2);+ item.Scale = 1 + (max - 1) * f * f;+ }+ }+ pos += item.Size + item.Gap;+ }+ return list;+ }++ private double DrawnLength() => Items().Sum(i => i.Size * i.Scale + i.Gap) + 8;++ /// <summary>The dock's top-left corner, its length and thickness, for the chosen edge and position.</summary>+ private static (Point Origin, double Along, double Across) DockFrame(DockSettings s, double length)+ {+ var vertical = Vertical(s);+ var span = vertical ? H - 2 * Margin8 : W - 2 * Margin8;+ length = Math.Min(length, span);+ var start = s.Position switch+ {+ DockPosition.Left => Margin8 + 6,+ DockPosition.Right => Margin8 + span - length - 6,+ _ => Margin8 + (span - length) / 2+ };+ return s.Edge switch+ {+ DockEdge.Top => (new Point(start, Margin8), length, Bar),+ DockEdge.Left => (new Point(Margin8, start), length, Bar),+ DockEdge.Right => (new Point(W - Margin8 - Bar, start), length, Bar),+ _ => (new Point(start, H - Margin8 - Bar), length, Bar)+ };+ }++ // ---- Drawing -------------------------------------------------------------------------------++ private void Draw()+ {+ if (_settings is not { } s) return;+ _canvas.Children.Clear();+ var look = ThemeStyles.Find(s.Style);+ var glass = look.Id == ThemeStyles.Glass;+ var light = (glass ? s.Theme : look.Base) == AppTheme.Light;++ // Desktop: a wallpaper and a window or two.+ _canvas.Background = new LinearGradientBrush(Hex(light ? "#FFB9D3EE" : "#FF27405E").Color, Hex(light ? "#FFE9D8F0" : "#FF4A2F5E").Color, 35);+ AddRect(150, 34, 300, 112, 8, light ? Hex("#E6FFFFFF") : Hex("#CC2A2A30"), Hex("#22FFFFFF"));+ AddRect(150, 34, 300, 18, 8, light ? Hex("#FFF2F2F4") : Hex("#FF36363C"), null);++ var tileFill = glass ? (light ? Hex("#14000000") : Hex("#24FFFFFF")) : Hex(look.Tile);+ var text = glass ? (light ? Hex("#FF1C1C1E") : Hex("#FFF5F5F7")) : Hex(look.Text);++ // Widgets in their own strip at the top.+ if (s.WidgetPlacement == WidgetPlacement.TopBar && _visibleWidgets > 0)+ {+ var y = s.Edge == DockEdge.Top ? Margin8 + Bar + 8 : Margin8;+ var widths = Enumerable.Range(0, _visibleWidgets).Select(i => i switch { 0 => 52.0, 1 => 42, 2 => 46, 3 => 36, _ => 26 }).ToList();+ var total = widths.Sum() + (widths.Count - 1) * 4;+ var x = (W - total) / 2;+ AddRect(x - 6, y, total + 12, 32, 10, DockBrush(s, look, light), Edge(look, light));+ for (var i = 0; i < widths.Count; i++)+ {+ AddWidget(x, y + 4, widths[i], 24, i, tileFill, text);+ x += widths[i] + 4;+ }+ }++ var items = Items();+ var drawnLength = items.Sum(i => i.Size * i.Scale + i.Gap) + 8;+ var (origin, along, across) = DockFrame(s, drawnLength);+ var vertical = Vertical(s);+ var hidden = s.AutoHide == AutoHideMode.Always && _pointer is null && !_demo.IsEnabled;++ // The dock bar.+ var dock = new Rectangle+ {+ Width = vertical ? across : along,+ Height = vertical ? along : across,+ RadiusX = 12, RadiusY = 12,+ Fill = DockBrush(s, look, light),+ Stroke = Edge(look, light),+ StrokeThickness = 1,+ Opacity = hidden ? 0.28 : 1+ };+ if (hidden) dock.StrokeDashArray = [4, 3];+ Canvas.SetLeft(dock, origin.X);+ Canvas.SetTop(dock, origin.Y);+ _canvas.Children.Add(dock);++ // Its contents, grown away from the screen edge when magnified.+ double pos = 8;+ Point? previewAt = null;+ foreach (var item in items)+ {+ var size = item.Size * item.Scale;+ var crossSize = item.Kind == "widget" ? 26 : item.Kind == "divider" ? 20 : size;+ double inset = (across - (item.Kind is "widget" or "divider" ? crossSize : Tile)) / 2;+ // Magnified tiles keep their foot on the dock's inner edge and grow outward.+ double x, y;+ if (!vertical)+ {+ x = origin.X + pos;+ y = s.Edge == DockEdge.Top ? origin.Y + inset : origin.Y + across - inset - crossSize;+ }+ else+ {+ y = origin.Y + pos;+ x = s.Edge == DockEdge.Left ? origin.X + inset : origin.X + across - inset - crossSize;+ }+ var w = vertical ? crossSize : size;+ var h = vertical ? size : crossSize;+ if (item.Kind is not ("widget" or "divider")) { w = h = size; }+ var element = item.Kind switch+ {+ "widget" => Widget(w, h, item.Index, tileFill, text),+ "divider" => new Rectangle { Width = vertical ? 20 : 1, Height = vertical ? 1 : 20, Fill = Hex(light ? "#33000000" : "#40FFFFFF") },+ "start" => Icon(size, "#FF2A5BD7", "#FF7B4BE0"),+ "downloads" => Icon(size, "#FF5AB4FF", "#FF1A6BDB"),+ "trash" => Icon(size, "#FFB8BCC4", "#FF7D828C"),+ _ => Icon(size, AppColors[item.Index % AppColors.Length], null)+ };+ if (item.Kind == "divider")+ {+ if (!vertical) { x = origin.X + pos; y = origin.Y + (across - 20) / 2; }+ else { y = origin.Y + pos; x = origin.X + (across - 20) / 2; }+ }+ element.Opacity = hidden ? 0.28 : 1;+ Canvas.SetLeft(element, x);+ Canvas.SetTop(element, y);+ _canvas.Children.Add(element);+ if (item.Kind == "app" && item.Index < 4 && !hidden)+ {+ // A dot under apps that have windows.+ var dot = new Ellipse { Width = 3, Height = 3, Fill = text, Opacity = 0.7 };+ if (!vertical) { Canvas.SetLeft(dot, x + size / 2 - 1.5); Canvas.SetTop(dot, s.Edge == DockEdge.Top ? origin.Y + 1.5 : origin.Y + across - 4.5); }+ else { Canvas.SetTop(dot, y + size / 2 - 1.5); Canvas.SetLeft(dot, s.Edge == DockEdge.Left ? origin.X + 1.5 : origin.X + across - 4.5); }+ _canvas.Children.Add(dot);+ }+ if (item.Kind == "app" && item.Index == _restingOn) previewAt = new Point(x + w / 2, y + h / 2);+ pos += size + item.Gap;+ }++ if (_showWindowPreview && previewAt is { } at && !hidden) DrawWindowPreview(s, at, look, light, text);+ if (hidden) DrawHiddenHint(s, text, light);+ _caption.Text = Caption(s);+ }++ private void DrawWindowPreview(DockSettings s, Point at, ThemeStyle look, bool light, Brush text)+ {+ const double pw = 112, ph = 74;+ var x = Math.Clamp(at.X - pw / 2, 4, W - pw - 4);+ var y = s.Edge == DockEdge.Top ? Margin8 + Bar + 14 : at.Y - ph - 34;+ if (s.Edge == DockEdge.Left) { x = Margin8 + Bar + 14; y = Math.Clamp(at.Y - ph / 2, 4, H - ph - 4); }+ if (s.Edge == DockEdge.Right) { x = W - Margin8 - Bar - 14 - pw; y = Math.Clamp(at.Y - ph / 2, 4, H - ph - 4); }+ AddRect(x, y, pw, ph, 10, look.Id == ThemeStyles.Glass ? Hex(light ? "#F2FFFFFF" : "#F22A2A30") : Hex(look.Popup), Edge(look, light));+ AddRect(x + 8, y + 18, pw - 16, ph - 26, 4, Hex(light ? "#FFE4E8F0" : "#FF3A3F4A"), null);+ var title = new TextBlock { Text = UiText.Get("PreviewWindowTitle"), FontSize = 8.5, Foreground = text };+ Canvas.SetLeft(title, x + 9);+ Canvas.SetTop(title, y + 4);+ _canvas.Children.Add(title);+ }++ private void DrawHiddenHint(DockSettings s, Brush text, bool light)+ {+ var hint = new Border+ {+ CornerRadius = new CornerRadius(8),+ Padding = new Thickness(8, 3, 8, 4),+ Background = Hex(light ? "#CCFFFFFF" : "#B3000000"),+ Child = new TextBlock { Text = UiText.Get("PreviewHiddenHint"), FontSize = 10, Foreground = text }+ };+ hint.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));+ var (x, y) = s.Edge switch+ {+ DockEdge.Top => ((W - hint.DesiredSize.Width) / 2, Margin8 + Bar + 6),+ DockEdge.Left => (Margin8 + Bar + 6, (H - hint.DesiredSize.Height) / 2),+ DockEdge.Right => (W - Margin8 - Bar - 6 - hint.DesiredSize.Width, (H - hint.DesiredSize.Height) / 2),+ _ => ((W - hint.DesiredSize.Width) / 2, H - Margin8 - Bar - 6 - hint.DesiredSize.Height)+ };+ Canvas.SetLeft(hint, x);+ Canvas.SetTop(hint, y);+ _canvas.Children.Add(hint);+ }++ /// <summary>What the picture shows, in words.</summary>+ private string Caption(DockSettings s)+ {+ var parts = new List<string>+ {+ UiText.Get(s.Edge switch { DockEdge.Top => "PreviewEdgeTop", DockEdge.Left => "PreviewEdgeLeft", DockEdge.Right => "PreviewEdgeRight", _ => "PreviewEdgeBottom" }),+ UiText.Get(s.WidgetPlacement switch { WidgetPlacement.DockLeft => "PreviewWidgetsLeft", WidgetPlacement.DockRight => "PreviewWidgetsRight", _ => "PreviewWidgetsTop" }),+ s.Magnify && s.AnimationsEnabled+ ? UiText.Format("PreviewMagnifyOn", (int)Math.Round(Math.Clamp(s.MagnifyScale, 1.1, 2.2) * 100))+ : UiText.Get("PreviewMagnifyOff"),+ UiText.Get(s.AutoHide switch { AutoHideMode.Always => "PreviewHideAlways", AutoHideMode.Smart => "PreviewHideSmart", _ => "PreviewHideNever" })+ };+ return string.Join(" · ", parts) + "\n" + UiText.Get("PreviewTryHint");+ }++ // ---- Pieces --------------------------------------------------------------------------------++ private static Brush DockBrush(DockSettings s, ThemeStyle look, bool light)+ {+ var alpha = (byte)Math.Round(Math.Clamp(s.SurfaceOpacity, 0.3, 1) * 255);+ Color top, bottom;+ if (look.Id == ThemeStyles.Glass)+ {+ top = light ? Color.FromRgb(0xF6, 0xF6, 0xF8) : Color.FromRgb(0x2A, 0x2A, 0x30);+ bottom = light ? Color.FromRgb(0xE8, 0xE8, 0xEC) : Color.FromRgb(0x1C, 0x1C, 0x20);+ }+ else+ {+ top = Hex(look.DockTop).Color;+ bottom = Hex(look.DockBottom).Color;+ }+ top.A = bottom.A = alpha;+ return new LinearGradientBrush(top, bottom, 90);+ }++ private static Brush Edge(ThemeStyle look, bool light) =>+ look.Id == ThemeStyles.Glass ? Hex(light ? "#26000000" : "#33FFFFFF") : Hex(look.Edge);++ private static FrameworkElement Icon(double size, string from, string? to)+ {+ var fill = to is null ? (Brush)Hex(from) : new LinearGradientBrush(Hex(from).Color, Hex(to).Color, 90);+ var tile = new Border { Width = size, Height = size, CornerRadius = new CornerRadius(size * 0.24), Background = fill };+ tile.Child = new Ellipse { Width = size * 0.42, Height = size * 0.42, Fill = Hex("#D9FFFFFF"), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ return tile;+ }++ private static FrameworkElement Widget(double w, double h, int index, Brush fill, Brush text)+ {+ var tile = new Border { Width = w, Height = h, CornerRadius = new CornerRadius(7), Background = fill };+ // A hint of what is in it: a ring, a line of text…+ if (index % 3 == 1 || w <= 26)+ tile.Child = new Ellipse { Width = Math.Min(w, h) * 0.55, Height = Math.Min(w, h) * 0.55, Stroke = text, StrokeThickness = 1.6, Opacity = 0.75, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ else+ tile.Child = new Rectangle { Width = w * 0.55, Height = 3, RadiusX = 1.5, RadiusY = 1.5, Fill = text, Opacity = 0.6, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ return tile;+ }++ private void AddWidget(double x, double y, double w, double h, int index, Brush fill, Brush text)+ {+ var widget = Widget(w, h, index, fill, text);+ Canvas.SetLeft(widget, x);+ Canvas.SetTop(widget, y);+ _canvas.Children.Add(widget);+ }++ private void AddRect(double x, double y, double w, double h, double radius, Brush fill, Brush? stroke)+ {+ var rect = new Rectangle { Width = w, Height = h, RadiusX = radius, RadiusY = radius, Fill = fill };+ if (stroke is not null)+ {+ rect.Stroke = stroke;+ rect.StrokeThickness = 1;+ }+ Canvas.SetLeft(rect, x);+ Canvas.SetTop(rect, y);+ _canvas.Children.Add(rect);+ }++ private static SolidColorBrush Hex(string hex) => new((Color)ColorConverter.ConvertFromString(hex));+}diff --git a/DockSheet.cs b/DockSheet.csnew file mode 100644index 0000000..66a4627--- /dev/null+++ b/DockSheet.cs@@ -0,0 +1,46 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Documents;++namespace QiDock;++/// <summary>+/// A widget's card shown the way the bell's list is: the dock swells up out of the widget's tile into the card.+/// Used while the widgets sit in the dock; the card's own content is moved in and out by its widget popup.+/// </summary>+public sealed class DockSheet : EdgePanel+{+ // The popup card's padding (16, 14) less the panel's own space around its tiles.+ private static readonly Thickness BodyPadding = new(6, 4, 6, 4);+ private readonly Border _body;++ public event EventHandler? SheetOpened;+ public event EventHandler? SheetHidden;++ /// <param name="cardWidth">The popup card's width (padding and border included), as the widget asked for it.</param>+ public DockSheet(double cardWidth) : base(Math.Max(120, cardWidth - 22), "QiDock Widget")+ {+ _body = new Border { Padding = BodyPadding, Width = CardWidth };+ _body.SetResourceReference(TextElement.ForegroundProperty, "TextPrimary");+ _body.SizeChanged += (_, e) =>+ {+ if (Math.Abs(e.NewSize.Height - e.PreviousSize.Height) > 0.5) Refit();+ };+ }++ public UIElement? Body+ {+ get => _body.Child;+ set => _body.Child = value;+ }++ protected override void Build()+ {+ Cards.Children.Clear();+ Cards.Children.Add(_body);+ }++ protected override void OnOpened() => SheetOpened?.Invoke(this, EventArgs.Empty);++ protected override void OnHidden() => SheetHidden?.Invoke(this, EventArgs.Empty);+}diff --git a/EdgePanel.cs b/EdgePanel.csnew file mode 100644index 0000000..ba9cbf3--- /dev/null+++ b/EdgePanel.cs@@ -0,0 +1,1066 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Interop;+using System.Windows.Media;+using System.Windows.Media.Animation;+using System.Windows.Media.Effects;+using System.Windows.Threading;++namespace QiDock;++/// <summary>Shared timing and easing so every panel moves the same calm way.</summary>+public static class Motion+{+ public static readonly IEasingFunction Out = new PowerEase { Power = 4, EasingMode = EasingMode.EaseOut };+ public static readonly IEasingFunction In = new PowerEase { Power = 3, EasingMode = EasingMode.EaseIn };+ public static readonly IEasingFunction Settle = new BackEase { Amplitude = 0.18, EasingMode = EasingMode.EaseOut };++ public static DoubleAnimation To(double to, double milliseconds, IEasingFunction? ease = null, double delay = 0) =>+ new(to, TimeSpan.FromMilliseconds(milliseconds)) { EasingFunction = ease ?? Out, BeginTime = TimeSpan.FromMilliseconds(delay) };++ /// <summary>+ /// Runs from <paramref name="from"/> to <paramref name="to"/> and then lets go (the property's own+ /// value must already be <paramref name="to"/>). A delayed one holds <paramref name="from"/> while waiting,+ /// so nothing flashes in its final place first.+ /// </summary>+ public static AnimationTimeline FromTo(double from, double to, double milliseconds, IEasingFunction? ease = null, double delay = 0)+ {+ if (delay <= 0)+ return new DoubleAnimation(from, to, TimeSpan.FromMilliseconds(milliseconds)) { EasingFunction = ease ?? Out, FillBehavior = FillBehavior.Stop };+ var frames = new DoubleAnimationUsingKeyFrames { FillBehavior = FillBehavior.Stop };+ frames.KeyFrames.Add(new DiscreteDoubleKeyFrame(from, KeyTime.FromTimeSpan(TimeSpan.Zero)));+ frames.KeyFrames.Add(new DiscreteDoubleKeyFrame(from, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(delay))));+ frames.KeyFrames.Add(new EasingDoubleKeyFrame(to, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(delay + milliseconds)), ease ?? Out));+ return frames;+ }++ /// <summary>The element's own translate transform (created on first use).</summary>+ /// <summary>+ /// With QIDOCK_FRAMES=1, writes how long each frame took for a second after a movement+ /// starts (to %LOCALAPPDATA%\QiDock\frames.log), to find stutter.+ /// </summary>+ public static void Measure(string what)+ {+ if (Environment.GetEnvironmentVariable("QIDOCK_FRAMES") != "1") return;+ var watch = System.Diagnostics.Stopwatch.StartNew();+ var last = TimeSpan.Zero;+ var gaps = new List<double>();+ var slow = new List<string>();+ EventHandler? tick = null;+ tick = (_, args) =>+ {+ var now = ((RenderingEventArgs)args).RenderingTime;+ if (last != TimeSpan.Zero && now != last)+ {+ var gap = (now - last).TotalMilliseconds;+ gaps.Add(gap);+ if (gap > 25) slow.Add($"{watch.ElapsedMilliseconds}ms:{gap:0}");+ }+ last = now;+ if (watch.ElapsedMilliseconds < 1000) return;+ CompositionTarget.Rendering -= tick;+ gaps.Sort();+ var line = $"{DateTime.Now:HH:mm:ss} {what}: frames={gaps.Count} median={(gaps.Count > 0 ? gaps[gaps.Count / 2] : 0):0.0}ms max={(gaps.Count > 0 ? gaps[^1] : 0):0.0}ms over25={gaps.Count(g => g > 25)} at [{string.Join(", ", slow)}]";+ try { System.IO.File.AppendAllText(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock", "frames.log"), line + Environment.NewLine); }+ catch (System.IO.IOException) { }+ };+ CompositionTarget.Rendering += tick;+ }++ /// <summary>Runs <paramref name="action"/> once the next frame has been put on screen.</summary>+ public static void AfterFirstFrame(Action action)+ {+ // Rendering can be raised more than once per frame; count frames by their time.+ TimeSpan? first = null;+ EventHandler? tick = null;+ tick = (_, args) =>+ {+ var time = ((RenderingEventArgs)args).RenderingTime;+ if (first is null)+ {+ first = time;+ return;+ }+ if (time == first) return;+ CompositionTarget.Rendering -= tick;+ action();+ };+ CompositionTarget.Rendering += tick;+ }++ public static TranslateTransform Shift(UIElement element)+ {+ if (element.RenderTransform is TranslateTransform shift && !shift.IsFrozen) return shift;+ if (element.RenderTransform is TransformGroup { IsFrozen: false } group && group.Children.OfType<TranslateTransform>().FirstOrDefault() is { } inner) return inner;+ shift = new TranslateTransform();+ element.RenderTransform = shift;+ return shift;+ }++ /// <summary>+ /// Draws the element once into a bitmap that the GPU then only moves and fades, so moving+ /// cards with shadows never re-renders them frame by frame.+ /// </summary>+ public static void Cache(UIElement element)+ {+ var scale = Application.Current?.MainWindow is { } main && PresentationSource.FromVisual(main)?.CompositionTarget is { } target ? target.TransformToDevice.M11 : 1.5;+ element.CacheMode = new BitmapCache(scale) { SnapsToDevicePixels = true };+ }+}++/// <summary>+/// A frosted panel that slides in from the right edge of the screen (notification center,+/// control center): one sheet of blurred, tinted glass with rounded corners,+/// holding light tiles. It is only as tall as its tiles and grows or shrinks smoothly with them,+/// never takes focus from the app you are in and closes when you click anywhere else; opening+/// one closes the other. Rebuilding the tiles moves every tile from where it was to where it goes.+/// It can also grow out of the dock instead (<see cref="ToggleFromDock"/>): a small bump rises from the+/// clicked tile, swells into the panel with a soft overshoot and stays joined to the dock by inward+/// curves, in the dock's own material; closing pulls it back into the tile.+/// </summary>+public abstract class EdgePanel : Window+{+ /// <summary>+ /// The dock tile a panel grows out of (screen DIPs): the edge the dock stands on, the tile's centre and length+ /// along the dock, and the dock's inner edge (its top on the bottom edge, its right side on the left edge…).+ /// </summary>+ /// <remarks><paramref name="DockStart"/>..<paramref name="DockEnd"/> is the straight part of the dock (its rounded ends left+ /// out): the panel's foot always stands inside it, never past the dock's end.</remarks>+ public readonly record struct DockAnchor(Models.DockEdge Edge, double TileCenter, double TileWidth, double Inner,+ double DockStart = double.NegativeInfinity, double DockEnd = double.PositiveInfinity);++ // Dock-grown shape: inward curve where it meets the dock, top corner radius, room for the overshoot,+ // and how far it reaches down over the dock's top edge so the two read as one piece.+ private const double Fillet = 14;+ private const double DockCorner = 20;+ private const double Slack = 10;+ private const double Overlap = 2;++ /// <summary>How much of the dock's top the dock leaves out under a panel (its edge line): exactly what the panel covers.</summary>+ public const double SeamDepth = Overlap;++ /// <summary>+ /// Supplied by the main window: leaves the dock's top edge out between two screen x positions (DIPs) while a+ /// panel stands on the dock there, or draws it whole again (null).+ /// </summary>+ /// <remarks>+ /// The two points (screen DIPs) lie on the line where the panel's foot ends, on a device-pixel boundary: the dock+ /// cuts its inner edge away between them down to exactly that line, so no row of pixels is left between the windows.+ /// </remarks>+ public static Action<(Point From, Point To)?> DockSeam { get; set; } = _ => { };++ /// <summary>Device pixels per DIP on the dock's screen.</summary>+ private static double DeviceScale =>+ Application.Current?.MainWindow is { } main && PresentationSource.FromVisual(main) is not null ? VisualTreeHelper.GetDpi(main).DpiScaleY : 1;++ /// <summary>+ /// Sizes and places a dock-grown panel around content <paramref name="along"/> long (along the dock) and+ /// <paramref name="depth"/> deep, centred on the tile and kept on screen, with its foot ending on a whole device+ /// pixel just past the dock's inner edge.+ /// </summary>+ private void PlaceOnDock(DockAnchor dock, double along, double depth)+ {+ var scale = DeviceScale;+ var area = SystemParameters.WorkArea;+ var side = Fillet + Slack;+ var frameAlong = along + 2 * side;+ var depthPixels = Math.Ceiling((depth + Slack + Overlap) * scale);+ var frameDepth = depthPixels / scale;+ var vertical = dock.Edge is Models.DockEdge.Left or Models.DockEdge.Right;+ var (start, end) = vertical ? (area.Top, area.Bottom) : (area.Left, area.Right);+ // The foot (frame minus Slack at each end) stands on the dock's straight part; then the screen's edges.+ var low = Math.Max(start + EdgeGap - side, dock.DockStart - Slack);+ var high = Math.Min(end - frameAlong - EdgeGap + side, dock.DockEnd + Slack - frameAlong);+ var centred = dock.TileCenter - frameAlong / 2;+ var alongStart = Math.Round((high >= low ? Math.Clamp(centred, low, high) : (low + high) / 2) * scale) / scale;+ // The foot's end, on a pixel boundary, Overlap past the dock's inner edge.+ var footEnd = dock.Edge is Models.DockEdge.Bottom or Models.DockEdge.Right+ ? Math.Round((dock.Inner + Overlap) * scale) / scale+ : Math.Round((dock.Inner - Overlap) * scale) / scale;+ _foot = Math.Max(0.5, Math.Abs(footEnd - dock.Inner));+ _frameSize = new Size(frameAlong, frameDepth);+ if (vertical)+ {+ Width = frameDepth;+ Height = frameAlong;+ Top = alongStart;+ Left = dock.Edge == Models.DockEdge.Left ? footEnd : footEnd - frameDepth;+ }+ else+ {+ Width = frameAlong;+ Height = frameDepth;+ Left = alongStart;+ Top = dock.Edge == Models.DockEdge.Top ? footEnd : footEnd - frameDepth;+ }+ // The frame's margins (side, Slack, side, foot) turned to the real edge.+ _sheet.Margin = dock.Edge switch+ {+ Models.DockEdge.Top => new Thickness(side, Overlap, side, Slack),+ Models.DockEdge.Left => new Thickness(Overlap, side, Slack, side),+ Models.DockEdge.Right => new Thickness(Slack, side, Overlap, side),+ _ => new Thickness(side, Slack, side, Overlap)+ };+ _skin.Width = frameAlong;+ _skin.Height = frameDepth;+ _skin.LayoutTransform = new MatrixTransform(Services.DockGeometry.FrameToScreen(dock.Edge));+ _contentExtent = vertical ? along : depth;+ }++ private double _foot = Overlap;+ private Size _frameSize;+ private double _contentExtent;++ /// <summary>A point of the bottom-edge frame in window coordinates.</summary>+ private Point ToWindow(Point p) => (_dock?.Edge ?? Models.DockEdge.Bottom) switch+ {+ Models.DockEdge.Top => new Point(p.X, _frameSize.Height - p.Y),+ Models.DockEdge.Left => new Point(_frameSize.Height - p.Y, p.X),+ Models.DockEdge.Right => new Point(p.Y, p.X),+ _ => p+ };++ /// <summary>An opacity mask that hides a strip <paramref name="depth"/> deep along the top (or the bottom) of an element between two x positions.</summary>+ public static Brush? NotchMask(Size size, double from, double to, double depth, bool bottom = false)+ {+ if (to <= from || size.Width <= 0 || size.Height <= 0) return null;+ var bounds = new Rect(size);+ var strip = bottom ? new Rect(from, size.Height - depth, to - from, depth + 1) : new Rect(from, -1, to - from, depth + 1);+ var shape = new CombinedGeometry(GeometryCombineMode.Exclude, new RectangleGeometry(bounds), new RectangleGeometry(strip));+ var mask = new DrawingBrush(new GeometryDrawing(Brushes.Black, null, shape))+ {+ Stretch = Stretch.None,+ ViewboxUnits = BrushMappingMode.Absolute,+ Viewbox = bounds,+ ViewportUnits = BrushMappingMode.Absolute,+ Viewport = bounds+ };+ mask.Freeze();+ return mask;+ }++ /// <summary>Space between the glass edge and the tiles.</summary>+ protected const double Pad = 10;+ private const double EdgeGap = 10;+ private static EdgePanel? _open;+ private static EdgePanel? _onDock;++ /// <summary>A panel stands on the dock (opening, open or sinking back): the dock keeps still under it.</summary>+ public static bool StandsOnDock => _onDock is not null;++ /// <summary>+ /// Supplied by the main window: where a panel grows out of this dock element (the tiles settle first),+ /// or null when the element is not in the dock.+ /// </summary>+ public static Func<FrameworkElement, DockAnchor?> DockAnchorFor { get; set; } = _ => null;++ /// <summary>Opens out of <paramref name="element"/> when it sits in the dock, otherwise at the screen edge.</summary>+ public void ToggleFrom(FrameworkElement element)+ {+ if (IsOpen)+ {+ Close(animated: true);+ return;+ }+ Toggle(DockAnchorFor(element));+ }++ /// <summary>Supplied by the main window: the space to leave at the top (under the widget bar).</summary>+ public static Func<double> TopInset { get; set; } = () => 12;++ /// <summary>Raised when any panel opens or closes (the dock stays up while one is open).</summary>+ public static event EventHandler? AnyVisibilityChanged;++ public static bool AnyOpen => _open is { IsOpen: true };++ private static readonly DependencyProperty ScrollOffsetProperty = DependencyProperty.Register(+ "ScrollOffset", typeof(double), typeof(EdgePanel), new PropertyMetadata(0.0, (d, e) => ((EdgePanel)d)._scroll.ScrollToVerticalOffset((double)e.NewValue)));++ protected readonly double CardWidth;+ protected readonly StackPanel Cards = new();++ /// <summary>A row that stays put above the scrolling tiles (the notification center's title); empty by default.</summary>+ protected readonly ContentControl Header = new() { Focusable = false, Visibility = Visibility.Collapsed };+ private readonly ScrollViewer _scroll;+ private readonly Border _sheet;+ private readonly Grid _frame = new();+ // The dock-grown shape, drawn as if the dock were at the bottom and turned to its real edge.+ private readonly Grid _skin = new() { HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, IsHitTestVisible = false };+ private readonly System.Windows.Shapes.Path _shape = new() { Visibility = Visibility.Collapsed };+ private readonly System.Windows.Shapes.Path _outline = new() { Visibility = Visibility.Collapsed, IsHitTestVisible = false, StrokeThickness = 1 };+ private DockAnchor? _dock;+ private double _morph, _sheetMax = double.PositiveInfinity;+ private Tween? _morphTween;+ private readonly DispatcherTimer _outsideClick = new(DispatcherPriority.Input) { Interval = TimeSpan.FromMilliseconds(40) };+ private readonly System.Diagnostics.Stopwatch _clock = System.Diagnostics.Stopwatch.StartNew();+ private Tween? _leftTween;+ private readonly DispatcherTimer _shrink = new(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(520) };+ private bool _ticking;+ private double _scrollTarget, _restLeft, _awayLeft;+ private bool _buttonWasDown, _closing, _frosted;+ private DateTime _closedAt;++ /// <summary>Where a new tile comes from; <paramref name="Continues"/> when it is the same card seen there before (no fade).</summary>+ protected readonly record struct Origin(string Key, bool Continues = false);++ private sealed record Tween(double From, double To, double Start, double Duration, IEasingFunction Ease, Action? Done);++ protected EdgePanel(double cardWidth, string title)+ {+ CardWidth = cardWidth;+ WindowStyle = WindowStyle.None;+ ResizeMode = ResizeMode.NoResize;+ Services.GpuTransparency.Prepare(this);+ ShowInTaskbar = false;+ ShowActivated = false;+ Topmost = true;+ WindowStartupLocation = WindowStartupLocation.Manual;+ SizeToContent = SizeToContent.Manual;+ Title = title;+ SetResourceReference(FontFamilyProperty, "InterfaceFont");+ UseLayoutRounding = true;+ Cards.Margin = new Thickness(Pad);+ _scroll = new ScrollViewer+ {+ Content = Cards,+ VerticalScrollBarVisibility = ScrollBarVisibility.Hidden,+ HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,+ Focusable = false+ };+ _scroll.PreviewMouseWheel += SmoothWheel;+ // Transparent over the frosted glass; an opaque rounded sheet where Windows can't frost.+ Header.Margin = new Thickness(Pad, Pad, Pad, 0);+ var layout = new DockPanel();+ DockPanel.SetDock(Header, Dock.Top);+ layout.Children.Add(Header);+ layout.Children.Add(_scroll);+ _sheet = new Border { Child = layout, Background = Brushes.Transparent, CornerRadius = new CornerRadius(14), ClipToBounds = true };+ _skin.Children.Add(_shape);+ _skin.Children.Add(_outline);+ _frame.Children.Add(_skin);+ _frame.Children.Add(_sheet);+ _frame.SizeChanged += (_, _) => DrawMorph(_morph);+ Content = _frame;+ _outsideClick.Tick += (_, _) => WatchOutsideClick();+ _shrink.Tick += (_, _) =>+ {+ _shrink.Stop();+ if (IsOpen) SetSheetHeight(ContentHeight());+ };+ }++ public bool IsOpen => IsVisible && !_closing;++ /// <summary>How much of the screen's height the panel may take before it scrolls.</summary>+ protected double HeightShare { get; init; } = 1;++ /// <summary>Opens the panel at the right edge, or closes it when open (ignores the click that just closed it).</summary>+ public void Toggle() => Toggle(null);++ /// <summary>Opens the panel growing out of a dock tile, or closes it back into the tile.</summary>+ public void ToggleFromDock(DockAnchor anchor) => Toggle(anchor);++ private void Toggle(DockAnchor? dock)+ {+ if (IsOpen)+ {+ Close(animated: true);+ return;+ }+ if (DateTime.UtcNow - _closedAt < TimeSpan.FromMilliseconds(350)) return; // the same click closed it+ Open(dock);+ }++ /// <summary>Fills <see cref="Cards"/>. Give each top-level tile a key in its Tag so it can be followed when rebuilt.</summary>+ protected abstract void Build();++ protected virtual void OnOpened() { }++ /// <summary>The panel has finished closing.</summary>+ protected virtual void OnHidden() { }++ /// <summary>Fits the glass again after the content changed size by itself.</summary>+ protected void Refit()+ {+ if (IsOpen) Fit(ContentHeight());+ }++#if DEBUG+ /// <summary>Debug snapshot run: builds the panel's content without showing it and hands it out.</summary>+ internal FrameworkElement Rehearse()+ {+ Build();+ TrimLastGap();+ if (_sheet.Parent is Panel holder) holder.Children.Remove(_sheet);+ _sheet.Margin = new Thickness(0);+ _sheet.Clip = null;+ _sheet.Width = CardWidth + 2 * Pad;+ _scroll.Opacity = 1;+ return _sheet;+ }++ private (double Width, double Height, double TileX)? _rehearsal;+ private Border? _rehearsalDock;++ /// <summary>Debug snapshot run: the dock-grown panel over a stand-in dock, drawn by <see cref="RehearseMorph"/>.</summary>+ internal FrameworkElement RehearseDock()+ {+ Build();+ TrimLastGap();+ if (_sheet.Parent is Panel holder && !ReferenceEquals(holder, _frame)) holder.Children.Remove(_sheet);+ else if (_sheet.Parent is Border border) border.Child = null;+ if (_sheet.Parent is null) _frame.Children.Add(_sheet);+ if (_frame.Parent is Panel old) old.Children.Remove(_frame);+ Content = null;+ _sheet.Width = double.NaN;+ var side = Fillet + Slack;+ var sheetWidth = CardWidth + 2 * Pad;+ _sheetMax = 520;+ var sheetHeight = ContentHeight();+ var width = sheetWidth + 2 * side + 120;+ var height = sheetHeight + Slack + Overlap;+ _sheet.Margin = new Thickness(side + 60, Slack, side + 60, Overlap);+ _frame.Width = width;+ _frame.Height = height;+ _frame.VerticalAlignment = VerticalAlignment.Top;+ _skin.Width = width;+ _skin.Height = height;+ _frameSize = new Size(width, height);+ PaintDockShape();+ _shape.Visibility = Visibility.Visible;+ _outline.Visibility = Visibility.Collapsed; // no edge line: panel and dock read as one solid piece+ _rehearsal = (width, height, width / 2 + 90);++ var dock = new Border { Height = 62, CornerRadius = new CornerRadius(18), BorderThickness = new Thickness(1), Margin = new Thickness(0, height - Overlap, 0, 0), VerticalAlignment = VerticalAlignment.Top };+ dock.SetResourceReference(Border.BackgroundProperty, "DockMaterial");+ dock.SetResourceReference(Border.BorderBrushProperty, "DockBorderMaterial");+ var tile = new Border { Width = 50, Height = 50, CornerRadius = new CornerRadius(12), Background = Brushes.DimGray, HorizontalAlignment = HorizontalAlignment.Left, Margin = new Thickness(width / 2 + 90 - 25 - 1, 5, 0, 0), VerticalAlignment = VerticalAlignment.Top };+ dock.Child = new Grid { Children = { tile } };+ _rehearsalDock = dock;+ var stage = new Grid { Width = width, Height = height - Overlap + 62 };+ stage.Children.Add(dock);+ stage.Children.Add(_frame);+ return stage;+ }++ /// <summary>Draws the rehearsed dock-grown panel at <paramref name="progress"/> (0 = inside the tile, 1 = open).</summary>+ internal void RehearseMorph(double progress)+ {+ if (_rehearsal is not { } stage) return;+ var side = Fillet + Slack + 60;+ ApplyMorph(progress, stage.Width, stage.Height, stage.TileX, 50, side,+ range => _rehearsalDock!.OpacityMask = range is { } r ? NotchMask(new Size(stage.Width, 62), r.Left, r.Right, SeamDepth) : null);+ _scroll.Opacity = Math.Clamp((progress - 0.55) / 0.4, 0, 1);+ }+#endif++ private void Open(DockAnchor? dock)+ {+ if (_open is { } other && !ReferenceEquals(other, this)) other.Close(animated: false);+ _open = this;+ _closing = false;+ _dock = dock;+ Build();+ TrimLastGap();+ if (dock is { } anchor)+ {+ OpenFromDock(anchor);+ return;+ }+ _shape.Visibility = _outline.Visibility = Visibility.Collapsed;+ _sheet.Margin = new Thickness(0);+ _sheet.Clip = null;+ var area = SystemParameters.WorkArea;+ var top = area.Top + Math.Max(0, TopInset());+ Width = CardWidth + 2 * Pad;+ _sheetMax = Math.Max(220, (area.Bottom - top - EdgeGap) * HeightShare);+ Height = ContentHeight();+ Top = top;+ _restLeft = area.Right - Width - EdgeGap;+ _awayLeft = area.Right + 2; // just past the screen edge+ Left = _awayLeft;+ _scrollTarget = 0;+ _scroll.ScrollToVerticalOffset(0);+ _scroll.Opacity = 0;+ Show();+ Frost();+ // The first frame is drawn off screen, so the slide never starts with a skip.+ Motion.AfterFirstFrame(() =>+ {+ if (!IsOpen) return;+ Slide(_restLeft, 420, Motion.Out);+ _scroll.BeginAnimation(OpacityProperty, Motion.FromTo(0, 1, 260, delay: 60));+ _scroll.Opacity = 1;+ // Tiles drift in one after another, a few pixels each.+ var delay = 40.0;+ foreach (UIElement card in Cards.Children)+ {+ if (delay > 200) break;+ Motion.Shift(card).BeginAnimation(TranslateTransform.XProperty, Motion.FromTo(14 + delay / 10, 0, 460, delay: delay));+ delay += 26;+ }+ Motion.Measure(GetType().Name + " open");+ });+ Opened();+ }++ private void Opened()+ {+ _buttonWasDown = AnyButtonDown();+ _outsideClick.Start();+ OnOpened();+ AnyVisibilityChanged?.Invoke(this, EventArgs.Empty);+ }++ /// <summary>The panel rises out of the tile: a small bump on the dock swells into the full panel.</summary>+ private void OpenFromDock(DockAnchor dock)+ {+ var area = SystemParameters.WorkArea;+ var top = area.Top + Math.Max(0, TopInset());+ var side = Fillet + Slack;+ _sheetMax = Math.Max(220, dock.Edge switch+ {+ Models.DockEdge.Top => area.Bottom - dock.Inner - EdgeGap - Slack,+ Models.DockEdge.Left or Models.DockEdge.Right => Math.Min(area.Height - 2 * (EdgeGap + side), dock.DockEnd - dock.DockStart - 2 * Fillet),+ _ => (dock.Inner - top - EdgeGap - Slack) * HeightShare+ });+ PlaceSheet(ContentHeight());+ _scrollTarget = 0;+ _scroll.ScrollToVerticalOffset(0);+ _scroll.BeginAnimation(OpacityProperty, null);+ _scroll.Opacity = 0;+ PaintDockShape();+ // No edge line: a light rim round the grown shape kept the card and its tile from reading as one piece.+ _shape.Visibility = Visibility.Visible;+ _outline.Visibility = Visibility.Collapsed;+ _onDock = this;+ _morphTween = null;+ _morph = 0;+ DrawMorph(0);+ Show();+ Services.GpuTransparency.Unfrost(this);+ _frosted = false;+ _sheet.Background = Brushes.Transparent;+ _sheet.BorderThickness = new Thickness(0);+ Motion.AfterFirstFrame(() =>+ {+ if (!IsOpen) return;+ Morph(1, 430, Motion.Settle);+ // The content shows once the shape is nearly full, rising a little with it.+ _scroll.BeginAnimation(OpacityProperty, Motion.FromTo(0, 1, 220, delay: 170));+ _scroll.Opacity = 1;+ var delay = 170.0;+ foreach (UIElement card in Cards.Children)+ {+ if (delay > 300) break;+ // Rising out of the dock: from the dock's side, a few pixels.+ var (property, from) = dock.Edge switch+ {+ Models.DockEdge.Top => (TranslateTransform.YProperty, -12.0),+ Models.DockEdge.Left => (TranslateTransform.XProperty, -12.0),+ Models.DockEdge.Right => (TranslateTransform.XProperty, 12.0),+ _ => (TranslateTransform.YProperty, 12.0)+ };+ Motion.Shift(card).BeginAnimation(property, Motion.FromTo(from, 0, 380, delay: delay));+ delay += 24;+ }+ Motion.Measure(GetType().Name + " open from dock");+ });+ Opened();+ }++ private static Color Opaque(Color color) => Color.FromArgb(255, color.R, color.G, color.B);++ /// <summary>The dock's material made solid: while a panel stands on the dock both are solid, so nothing behind+ /// them shows through as lines and the two read as one piece.</summary>+ public static Brush? SolidDockMaterial()+ {+ if (Application.Current?.TryFindResource("DockMaterial") is not GradientBrush { GradientStops.Count: > 0 } dock) return null;+ var solid = dock.Clone();+ foreach (var stop in solid.GradientStops) stop.Color = Opaque(stop.Color);+ solid.Freeze();+ return solid;+ }++ /// <summary>The dock's material for the shape (its gradient turned over so the colours meet at the seam) and its edge.</summary>+ private void PaintDockShape()+ {+ if (TryFindResource("DockMaterial") is GradientBrush { GradientStops.Count: > 0 } dock)+ {+ var stops = dock.GradientStops.OrderBy(stop => stop.Offset).ToList();+ var fill = new LinearGradientBrush { StartPoint = new Point(0, 0), EndPoint = new Point(0, 1) };+ fill.GradientStops.Add(new GradientStop(Opaque(stops[^1].Color), 0));+ fill.GradientStops.Add(new GradientStop(Opaque(stops[0].Color), 1));+ fill.Freeze();+ _shape.Fill = fill;+ }+ else _shape.SetResourceReference(System.Windows.Shapes.Shape.FillProperty, "DockMaterial");+ if (TryFindResource("DockBorderMaterial") is GradientBrush { GradientStops.Count: > 0 } edge)+ _outline.Stroke = new SolidColorBrush(edge.GradientStops.OrderBy(stop => stop.Offset).First().Color);+ else _outline.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, "DockBorderMaterial");+ }++ private void Morph(double to, double milliseconds, IEasingFunction ease, double delay = 0, Action? done = null)+ {+ _morphTween = new Tween(_morph, to, _clock.Elapsed.TotalMilliseconds + delay, milliseconds, ease, done);+ StartTicking();+ }++ private void DrawMorph(double progress)+ {+ if (_dock is not { } dock || !IsVisible && progress > 0 && _frame.ActualWidth <= 0) return;+ var vertical = dock.Edge is Models.DockEdge.Left or Models.DockEdge.Right;+ var origin = new Point(Left, Top);+ var tileX = dock.TileCenter - (vertical ? Top : Left);+ var depth = _frameSize.Height;+ ApplyMorph(progress, _frameSize.Width, depth, tileX, dock.TileWidth, Fillet + Slack, range =>+ {+ if (range is not { } r)+ {+ DockSeam(null);+ return;+ }+ var a = ToWindow(new Point(r.Left, depth));+ var b = ToWindow(new Point(r.Right, depth));+ DockSeam((new Point(origin.X + a.X, origin.Y + a.Y), new Point(origin.X + b.X, origin.Y + b.Y)));+ });+ }++ /// <summary>+ /// Shapes the panel for <paramref name="progress"/>: from a bump as wide as part of the tile, centred on it,+ /// to the full panel; <paramref name="side"/> is the room left and right of the content.+ /// </summary>+ private void ApplyMorph(double progress, double width, double height, double tileX, double tileWidth, double side, Action<(double Left, double Right)?>? seam)+ {+ var fullWidth = width - 2 * side;+ var fullHeight = height - Slack; // down to the window's bottom, over the dock's edge+ if (fullWidth <= 0 || fullHeight <= 0) return;+ var startWidth = Math.Min(tileWidth * 0.62, fullWidth);+ var w = Math.Clamp(startWidth + (fullWidth - startWidth) * progress, 0, fullWidth + 2 * Slack - 2);+ var h = Math.Clamp(fullHeight * progress, 0, fullHeight + Slack - 1);+ var along = Math.Clamp(progress, 0, 1);+ var centre = tileX + (width / 2 - tileX) * along;+ var bottom = height;+ var topY = bottom - h;+ var left = centre - w / 2;+ var right = centre + w / 2;+ var foot = _foot; // the part standing over the dock's edge strip+ var rise = h - foot; // height above the dock's top edge+ var fillet = Math.Max(0, Math.Min(Fillet, rise * 0.45));+ var corner = Math.Max(0, Math.Min(Math.Min(DockCorner, w / 2), rise - fillet));++ if (rise < 0.5)+ {+ _shape.Data = _outline.Data = Geometry.Empty;+ seam?.Invoke(null);+ _sheet.Clip = Geometry.Empty;+ return;+ }+ _shape.Data = Outline(left, right, topY, bottom - foot, corner, fillet, closed: true, foot: foot);+ _outline.Data = Outline(left + 0.5, right - 0.5, topY + 0.5, bottom - foot, Math.Max(0, corner - 0.5), fillet, closed: false);+ // The dock leaves out its top edge where the panel stands on it, so the two read as one piece.+ seam?.Invoke((left - fillet, right + fillet));+ var clipHeight = bottom - foot - topY;+ if (clipHeight <= 0)+ {+ _sheet.Clip = Geometry.Empty;+ return;+ }+ // The frame's rectangle turned to the real edge, in the sheet's own coordinates.+ var a = ToWindow(new Point(left, topY));+ var b = ToWindow(new Point(left + w, topY + clipHeight));+ var clip = new Rect(a, b);+ clip.Offset(-_sheet.Margin.Left, -_sheet.Margin.Top);+ _sheet.Clip = new RectangleGeometry(clip, corner, corner);+ }++ /// <summary>Rounded top, straight sides, and inward curves that flare out into the dock at the bottom.</summary>+ /// <param name="foot">How far the filled shape continues straight down over the dock's edge strip.</param>+ private static Geometry Outline(double left, double right, double top, double bottom, double corner, double fillet, bool closed, double foot = 0)+ {+ var geometry = new StreamGeometry();+ using (var g = geometry.Open())+ {+ g.BeginFigure(new Point(left - fillet, bottom + foot), closed, closed);+ if (foot > 0) g.LineTo(new Point(left - fillet, bottom), true, true);+ if (fillet > 0) g.ArcTo(new Point(left, bottom - fillet), new Size(fillet, fillet), 0, false, SweepDirection.Counterclockwise, true, true);+ g.LineTo(new Point(left, top + corner), true, true);+ if (corner > 0) g.ArcTo(new Point(left + corner, top), new Size(corner, corner), 0, false, SweepDirection.Clockwise, true, true);+ g.LineTo(new Point(right - corner, top), true, true);+ if (corner > 0) g.ArcTo(new Point(right, top + corner), new Size(corner, corner), 0, false, SweepDirection.Clockwise, true, true);+ g.LineTo(new Point(right, bottom - fillet), true, true);+ if (fillet > 0) g.ArcTo(new Point(right + fillet, bottom), new Size(fillet, fillet), 0, false, SweepDirection.Counterclockwise, true, true);+ if (foot > 0) g.LineTo(new Point(right + fillet, bottom + foot), true, true);+ }+ geometry.Freeze();+ return geometry;+ }++ public void Close(bool animated)+ {+ if (!IsVisible || _closing) return;+ _closing = true;+ StopTyping();+ _outsideClick.Stop();+ _closedAt = DateTime.UtcNow;+ if (ReferenceEquals(_open, this)) _open = null;+ if (!animated)+ {+ Finish();+ return;+ }+ if (_dock is not null)+ {+ // Content first, then the shape sinks back into the tile.+ _scroll.BeginAnimation(OpacityProperty, new DoubleAnimation(0, TimeSpan.FromMilliseconds(110)) { EasingFunction = Motion.In });+ Morph(0, 250, Motion.In, delay: 60, done: () =>+ {+ if (_closing) Finish();+ });+ return;+ }+ _scroll.BeginAnimation(OpacityProperty, new DoubleAnimation(0, TimeSpan.FromMilliseconds(200)) { EasingFunction = Motion.In });+ Slide(_awayLeft, 240, Motion.In, () =>+ {+ if (_closing) Finish();+ });+ }++ private void Finish()+ {+ _leftTween = null;+ _morphTween = null;+ if (_dock is not null) DockSeam(null);+ if (ReferenceEquals(_onDock, this)) _onDock = null;+ _shrink.Stop();+ Hide();+ _closing = false;+ _scroll.BeginAnimation(OpacityProperty, null);+ AnyVisibilityChanged?.Invoke(this, EventArgs.Empty);+ OnHidden();+ }++ /// <summary>The frosted glass, tinted to the current theme (applied on every opening so a theme change shows).</summary>+ private void Frost()+ {+ var tint = TryFindResource("PanelFrostTint") is Color color ? color : Color.FromArgb(0xB8, 0x1C, 0x1D, 0x22);+ _frosted = Services.GpuTransparency.Frost(this, tint);+ if (_frosted)+ {+ _sheet.Background = Brushes.Transparent;+ _sheet.BorderThickness = new Thickness(0);+ return;+ }+ _sheet.SetResourceReference(Border.BackgroundProperty, "WidgetPopupFill");+ _sheet.SetResourceReference(Border.BorderBrushProperty, "DockBorderMaterial");+ _sheet.BorderThickness = new Thickness(1);+ }++ private double ContentHeight()+ {+ var available = new Size(CardWidth + 2 * Pad, double.PositiveInfinity);+ Cards.Measure(available);+ var header = 0.0;+ if (Header.Visibility == Visibility.Visible)+ {+ Header.Measure(available);+ header = Header.DesiredSize.Height;+ }+ return Math.Min(_sheetMax, Math.Ceiling(header + Cards.DesiredSize.Height)); // DesiredSize includes the margins+ }++ // ---- Window movement (position and height follow the same easing as the tiles) ---------------++ private void Slide(double to, double milliseconds, IEasingFunction ease, Action? done = null)+ {+ _leftTween = new Tween(Left, to, _clock.Elapsed.TotalMilliseconds, milliseconds, ease, done);+ StartTicking();+ }++ /// <summary>+ /// Fits the glass to the tiles. Resizing a window is slow, so it never happens frame by frame:+ /// a taller glass is set at once before the tiles move, a shorter one after they have settled.+ /// </summary>+ private void Fit(double to)+ {+ _shrink.Stop();+ if (to > SheetHeight + 0.5) SetSheetHeight(to);+ else if (to < SheetHeight - 0.5) _shrink.Start();+ }++ private double SheetHeight => _dock is null ? ActualHeight : _contentExtent;++ /// <summary>Sets the glass's height; a dock-grown panel keeps its foot on the dock.</summary>+ private void SetSheetHeight(double height)+ {+ if (_dock is null)+ {+ Height = height;+ return;+ }+ PlaceSheet(height);+ DrawMorph(_morph);+ }++ /// <summary>Places a dock-grown panel around content of this height (and the card's width).</summary>+ private void PlaceSheet(double contentHeight)+ {+ if (_dock is not { } dock) return;+ var width = CardWidth + 2 * Pad;+ if (dock.Edge is Models.DockEdge.Left or Models.DockEdge.Right) PlaceOnDock(dock, contentHeight, width);+ else PlaceOnDock(dock, width, contentHeight);+ }++ private void StartTicking()+ {+ if (_ticking) return;+ _ticking = true;+ CompositionTarget.Rendering += OnFrame;+ }++ private void OnFrame(object? sender, EventArgs e)+ {+ var now = _clock.Elapsed.TotalMilliseconds;+ if (_leftTween is { } left && Step(left, now, out var x))+ {+ Left = x;+ if (now - left.Start >= left.Duration && ReferenceEquals(_leftTween, left))+ {+ _leftTween = null;+ left.Done?.Invoke();+ }+ }+ if (_morphTween is { } morph)+ {+ var t = Math.Clamp((now - morph.Start) / morph.Duration, 0, 1);+ _morph = morph.From + (morph.To - morph.From) * morph.Ease.Ease(t);+ DrawMorph(_morph);+ if (t >= 1 && ReferenceEquals(_morphTween, morph))+ {+ _morphTween = null;+ morph.Done?.Invoke();+ }+ }+ if (_leftTween is null && _morphTween is null)+ {+ _ticking = false;+ CompositionTarget.Rendering -= OnFrame;+ }+ }++ private static bool Step(Tween tween, double now, out double value)+ {+ var t = Math.Clamp((now - tween.Start) / tween.Duration, 0, 1);+ value = Math.Round(tween.From + (tween.To - tween.From) * tween.Ease.Ease(t), 2);+ return true;+ }++ /// <summary>+ /// Rebuilds the tiles and moves each one from its old place to its new one while the glass+ /// grows or shrinks to fit. New tiles come out of <paramref name="origin"/> (a key of an old+ /// tile) or fade in where they land.+ /// </summary>+ protected void Rebuild(Func<string, Origin?>? origin = null)+ {+ if (!IsOpen)+ {+ Build();+ TrimLastGap();+ return;+ }+ var before = Positions();+ Build();+ TrimLastGap();+ Cards.UpdateLayout();+ var after = Positions();+ Fit(ContentHeight());+ // Every tile is put where it was (or where it comes from) right away; the movement starts+ // once that frame is on screen, so a slow first frame (new tiles, a resized glass) never skips.+ var starts = new List<Action>();+ var fresh = 0;+ foreach (UIElement child in Cards.Children)+ {+ if (child is not FrameworkElement { Tag: string key } element || !after.TryGetValue(key, out var now)) continue;+ var shift = Motion.Shift(element);+ if (before.TryGetValue(key, out var was))+ {+ if (Math.Abs(was - now) > 0.5) starts.Add(Move(shift, was - now, 0));+ continue;+ }+ var source = origin?.Invoke(key);+ double? start = source is { } o && before.TryGetValue(o.Key, out var at) ? at : null;+ var from = start is { } y ? y - now : -8;+ var delay = Math.Min(fresh++ * 30, 180);+ // Tiles coming out of one place: the first one drawn on top, the others appear as they leave it.+ if (start is not null) Panel.SetZIndex(element, 100 - fresh);+ starts.Add(Move(shift, from, source is { Continues: true } && start is not null ? 0 : delay));+ if (source is { Continues: true } && start is not null) continue;+ // Barely visible rather than invisible: WPF skips drawing invisible tiles, so their cached+ // picture would otherwise be made mid-movement, in one slow frame.+ element.Opacity = 0.01;+ var fadeDelay = delay + (start is null ? 0 : 60);+ starts.Add(() =>+ {+ element.Opacity = 1;+ element.BeginAnimation(OpacityProperty, Motion.FromTo(0.01, 1, start is null ? 300 : 240, Motion.Out, fadeDelay));+ });+ }+ Motion.AfterFirstFrame(() =>+ {+ foreach (var begin in starts) begin();+ Motion.Measure(GetType().Name + " rebuild");+ });+ }++ /// <summary>Holds the tile at <paramref name="from"/> now and returns what slides it home.</summary>+ private static Action Move(TranslateTransform shift, double from, double delay)+ {+ shift.BeginAnimation(TranslateTransform.YProperty, null);+ shift.Y = from;+ return () =>+ {+ shift.Y = 0;+ shift.BeginAnimation(TranslateTransform.YProperty, Motion.FromTo(from, 0, delay > 0 ? 460 : 420, Motion.Out, delay));+ };+ }++ /// <summary>The glass's own padding is the space under the last tile; its gap below would double it.</summary>+ private void TrimLastGap()+ {+ if (Cards.Children.Count > 0 && Cards.Children[^1] is FrameworkElement last)+ last.Margin = new Thickness(last.Margin.Left, last.Margin.Top, last.Margin.Right, 0);+ }++ private Dictionary<string, double> Positions()+ {+ var map = new Dictionary<string, double>(StringComparer.Ordinal);+ foreach (UIElement child in Cards.Children)+ if (child is FrameworkElement { Tag: string key, IsVisible: true } element)+ map[key] = element.TranslatePoint(new Point(0, 0), Cards).Y; // where it shows now, mid-move included+ return map;+ }++ /// <summary>Moves one tile out to the right and fades it, then runs <paramref name="done"/>.</summary>+ protected static void SlideAway(UIElement card, Action done)+ {+ var fade = new DoubleAnimation(0, TimeSpan.FromMilliseconds(220)) { EasingFunction = Motion.In };+ fade.Completed += (_, _) => done();+ Motion.Shift(card).BeginAnimation(TranslateTransform.XProperty, new DoubleAnimation(90, TimeSpan.FromMilliseconds(240)) { EasingFunction = Motion.In });+ card.IsHitTestVisible = false;+ card.BeginAnimation(OpacityProperty, fade);+ }++ private void SmoothWheel(object sender, MouseWheelEventArgs e)+ {+ e.Handled = true;+ var limit = _scroll.ScrollableHeight;+ if (limit <= 0) return;+ _scrollTarget = Math.Clamp(Math.Min(_scrollTarget, limit) - e.Delta * 0.9, 0, limit);+ BeginAnimation(ScrollOffsetProperty, new DoubleAnimation(_scroll.VerticalOffset, _scrollTarget, TimeSpan.FromMilliseconds(260)) { EasingFunction = Motion.Out });+ }++ protected static FrameworkElement Spaced(FrameworkElement element, double gap = 8)+ {+ element.Margin = new Thickness(0, 0, 0, gap);+ return element;+ }++ /// <summary>A light rounded tile on the glass (no shadow: the glass carries the depth).</summary>+ protected Border Glass(UIElement child, Thickness padding, double radius = 14, double? width = null)+ {+ var border = new Border+ {+ Width = width ?? CardWidth,+ Padding = padding,+ CornerRadius = new CornerRadius(radius),+ BorderThickness = new Thickness(1),+ Child = child+ };+ border.SetResourceReference(Border.BackgroundProperty, "PanelTile");+ border.SetResourceReference(Border.BorderBrushProperty, "PanelTileStroke");+ return border;+ }++ /// <summary>A small rounded button with text or an icon ("Daha az göster", "Temizle").</summary>+ protected static Border Capsule(UIElement content, Action click, string? tooltip = null)+ {+ var capsule = new Border+ {+ Height = 26,+ MinWidth = 26,+ Padding = new Thickness(10, 0, 10, 0),+ CornerRadius = new CornerRadius(13),+ Child = content,+ Cursor = Cursors.Hand,+ ToolTip = tooltip,+ VerticalAlignment = VerticalAlignment.Center+ };+ if (content is FrameworkElement inner)+ {+ inner.VerticalAlignment = VerticalAlignment.Center;+ inner.HorizontalAlignment = HorizontalAlignment.Center;+ }+ capsule.SetResourceReference(Border.BackgroundProperty, "PanelTile");+ capsule.MouseEnter += (_, _) => capsule.SetResourceReference(Border.BackgroundProperty, "PanelTileHover");+ capsule.MouseLeave += (_, _) => capsule.SetResourceReference(Border.BackgroundProperty, "PanelTile");+ capsule.MouseLeftButtonUp += (_, e) =>+ {+ e.Handled = true;+ click();+ };+ return capsule;+ }++ private void WatchOutsideClick()+ {+ var down = AnyButtonDown();+ if (down && !_buttonWasDown && !IsMouseOver) Close(animated: true);+ _buttonWasDown = down;+ }++ private static bool AnyButtonDown() => (GetAsyncKeyState(0x01) & 0x8000) != 0 || (GetAsyncKeyState(0x02) & 0x8000) != 0;++ protected override void OnSourceInitialized(EventArgs e)+ {+ base.OnSourceInitialized(e);+ if (PresentationSource.FromVisual(this) is not HwndSource source) return;+ Services.GpuTransparency.Apply(this);+ var style = GetWindowLongPtr(source.Handle, -20).ToInt64();+ SetWindowLongPtr(source.Handle, -20, new nint((style | 0x00000080 | 0x08000000) & ~0x00040000));+ source.AddHook((nint _, int message, nint _, nint _, ref bool handled) =>+ {+ if (message != 0x0021 /* WM_MOUSEACTIVATE */ || _typing) return 0;+ handled = true;+ return 3; // MA_NOACTIVATE+ });+ }++ private bool _typing;++ /// <summary>+ /// Lets the panel take the keyboard (a password box) until it closes. Normally clicking it never takes the focus+ /// away from the window being worked in, so nothing could be typed into it.+ /// </summary>+ protected void AllowTyping()+ {+ if (_typing || PresentationSource.FromVisual(this) is not HwndSource source) return;+ _typing = true;+ var style = GetWindowLongPtr(source.Handle, -20).ToInt64();+ SetWindowLongPtr(source.Handle, -20, new nint(style & ~0x08000000L));+ Activate();+ }++ private void StopTyping()+ {+ if (!_typing || PresentationSource.FromVisual(this) is not HwndSource source) return;+ _typing = false;+ var style = GetWindowLongPtr(source.Handle, -20).ToInt64();+ SetWindowLongPtr(source.Handle, -20, new nint(style | 0x08000000L));+ }++ [DllImport("user32.dll")] private static extern short GetAsyncKeyState(int key);+ [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/LICENSE b/LICENSEnew file mode 100644index 0000000..05a418c--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 QiDock contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/MainWindow.Desktop.cs b/MainWindow.Desktop.csnew file mode 100644index 0000000..f65adb4--- /dev/null+++ b/MainWindow.Desktop.cs@@ -0,0 +1,72 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Threading;+using QiDock.DesktopWidgets;++namespace QiDock;++/// <summary>+/// Desktop widgets: cards placed freely on the desktop (clocks, weather, music, system, notes…),+/// each in Mini / Small / Strip / Medium / Large size. They pause while an app window covers them.+/// </summary>+public partial class MainWindow+{+ private DeskWidgetManager? _deskWidgets;++ private void InitializeDesktopWidgets()+ {+ Desk.Settings = () => _preferences.Current.WidgetOptions;+ Services.FocusTimer.Minutes = () => _preferences.Current.WidgetOptions.FocusMinutes;+ Desk.UpdateSettings = change => SaveWidgetOptions(change(_preferences.Current.WidgetOptions));+ Desk.DockApps = () => _pinnedApps+ .Select(app => app.ExecutablePath)+ .Where(path => !string.IsNullOrWhiteSpace(path))+ .Distinct(StringComparer.OrdinalIgnoreCase)+ .ToList();+ // After the dock is up, so the desktop widgets never delay it.+ Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, () =>+ {+ if (_deskWidgets is not null) return;+ _deskWidgets = new DeskWidgetManager();+ _deskWidgets.Start();+ UpdateDeskCovers();+ });+ }++ /// <summary>Tells the desktop widgets which screen areas app windows cover (they pause underneath).</summary>+ private void UpdateDeskCovers()+ {+ if (_deskWidgets is null || _windowTracker?.Snapshot is not { } windows) return;+ var covers = new List<Rect>();+ foreach (var window in windows)+ {+ var handle = window.Handle;+ if (!TopNative.IsWindow(handle) || !TopNative.IsWindowVisible(handle) || TopNative.IsIconic(handle) || IsCloakedWindow(handle)) continue;+ if (GetWindowRect(handle, out var r)) covers.Add(new Rect(r.Left, r.Top, Math.Max(0, r.Right - r.Left), Math.Max(0, r.Bottom - r.Top)));+ }+ _deskWidgets.UpdateCovers(covers);+ }++ private void ShowDesktopWidgetGallery()+ {+ if (_deskWidgets is null)+ {+ _deskWidgets = new DeskWidgetManager();+ _deskWidgets.Start();+ }+ _deskWidgets.ShowGallery();+ }++ private void DisposeDesktopWidgets()+ {+ _deskWidgets?.Dispose();+ _deskWidgets = null;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct NativeRect { public int Left, Top, Right, Bottom; }++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool GetWindowRect(nint window, out NativeRect rect);+}diff --git a/MainWindow.DockMenu.cs b/MainWindow.DockMenu.csnew file mode 100644index 0000000..830545b--- /dev/null+++ b/MainWindow.DockMenu.cs@@ -0,0 +1,505 @@+using System.Diagnostics;+using System.IO;+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Media.Media3D;+using QiDock.Models;+using QiDock.Services;+using QiDock.Widgets;++namespace QiDock;++/// <summary>+/// The dock's own right-click menu (customize widgets, weather city, position, auto-hide, theme),+/// widget edit mode, the Desktop button, and Start-menu toggling.+/// </summary>+public partial class MainWindow+{+ private static readonly string[] Provinces =+ [+ "Adana", "Adıyaman", "Afyonkarahisar", "Ağrı", "Aksaray", "Amasya", "Ankara", "Antalya", "Ardahan", "Artvin",+ "Aydın", "Balıkesir", "Bartın", "Batman", "Bayburt", "Bilecik", "Bingöl", "Bitlis", "Bolu", "Burdur", "Bursa",+ "Çanakkale", "Çankırı", "Çorum", "Denizli", "Diyarbakır", "Düzce", "Edirne", "Elazığ", "Erzincan", "Erzurum",+ "Eskişehir", "Gaziantep", "Giresun", "Gümüşhane", "Hakkari", "Hatay", "Iğdır", "Isparta", "İstanbul", "İzmir",+ "Kahramanmaraş", "Karabük", "Karaman", "Kars", "Kastamonu", "Kayseri", "Kilis", "Kırıkkale", "Kırklareli",+ "Kırşehir", "Kocaeli", "Konya", "Kütahya", "Malatya", "Manisa", "Mardin", "Mersin", "Muğla", "Muş", "Nevşehir",+ "Niğde", "Ordu", "Osmaniye", "Rize", "Sakarya", "Samsun", "Şanlıurfa", "Siirt", "Sinop", "Şırnak", "Sivas",+ "Tekirdağ", "Tokat", "Trabzon", "Tunceli", "Uşak", "Van", "Yalova", "Yozgat", "Zonguldak"+ ];++ private bool _startWasOpenAtPress;+ private readonly System.Windows.Threading.DispatcherTimer _menuWatch = new(System.Windows.Threading.DispatcherPriority.Input) { Interval = TimeSpan.FromMilliseconds(40) };+ private bool _menuButtonWasDown;+ private bool _menuWatchHooked;+ private bool _desktopIconsHidden;++ // ---- Right-click menu -------------------------------------------------------------------++ /// <summary>+ /// Right-click anywhere on the dock except an app tile opens the dock menu. Opening it here+ /// (instead of through ContextMenuService on the dock surface) makes it work over widgets too.+ /// </summary>+ private void DockHost_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e)+ {+ for (var node = e.OriginalSource as DependencyObject; node is not null; node = ParentOf(node))+ {+ if (node is Button { DataContext: DockApp }) return; // app tiles keep their own menu+ if (ReferenceEquals(node, TrashButton)) return; // so does the Recycle Bin+ }++ e.Handled = true;+ ShowDockMenu(PlacementMode.MousePoint, null);+ }++ private static DependencyObject? ParentOf(DependencyObject node) =>+ node is Visual or Visual3D ? VisualTreeHelper.GetParent(node) ?? LogicalTreeHelper.GetParent(node) : LogicalTreeHelper.GetParent(node);++ private void ShowDockMenu(PlacementMode placement, UIElement? anchor)+ {+ _widgetBar.ClosePopups();+ var current = _preferences.Current;+ var options = current.WidgetOptions;+ var menu = new ContextMenu { PlacementTarget = anchor ?? DockSurface, Placement = placement };+ menu.Opened += DockContextMenu_Opened;+ menu.Closed += DockContextMenu_Closed;++ // The layout first: where the widgets live and which edge the dock stands on.+ var widgetPlace = Item(UiText.Get("WidgetPlacement"), "IconAlignCenter");+ foreach (var (value, key) in new[] { (WidgetPlacement.TopBar, "WidgetPlacementTop"), (WidgetPlacement.DockLeft, "WidgetPlacementDockLeft"), (WidgetPlacement.DockRight, "WidgetPlacementDockRight") })+ {+ var item = Item(UiText.Get(key), null, current.WidgetPlacement == value);+ item.Click += (_, _) => SavePreferences(_preferences.Current with { WidgetPlacement = value });+ widgetPlace.Items.Add(item);+ }+ widgetPlace.IsEnabled = !Services.DockGeometry.Vertical; // a side dock keeps the widgets in the top bar+ menu.Items.Add(widgetPlace);+ var edgeMenu = Item(UiText.Get("DockEdge"), "IconDock");+ foreach (var (value, key) in new[] { (DockEdge.Bottom, "DockEdgeBottom"), (DockEdge.Top, "DockEdgeTop"), (DockEdge.Left, "DockEdgeLeft"), (DockEdge.Right, "DockEdgeRight") })+ {+ var item = Item(UiText.Get(key), null, current.Edge == value);+ item.Click += (_, _) => SavePreferences(_preferences.Current with { Edge = value });+ edgeMenu.Items.Add(item);+ }+ menu.Items.Add(edgeMenu);+ menu.Items.Add(new Separator());++ // Widgets: tick to show / untick to hide.+ var widgets = Item(UiText.Get("MenuWidgets"), "IconLayout");+ foreach (var id in options.EffectiveOrder)+ {+ var visible = options.IsVisible(id);+ var item = Item(UiText.Get("Widget_" + id), null, visible);+ item.Click += (_, _) => SaveWidgetOptions(visible+ ? options with { Hidden = (options.Hidden ?? []).Append(id).Distinct().ToList() }+ : options with { Hidden = (options.Hidden ?? []).Where(h => h != id).ToList() });+ widgets.Items.Add(item);+ }+ menu.Items.Add(widgets);+++ var edit = Item(UiText.Get(_widgetBar.IsEditing ? "MenuEditDone" : "MenuEditDock"), "IconEdit");+ edit.Click += (_, _) => _widgetBar.SetEditing(!_widgetBar.IsEditing);+ menu.Items.Add(edit);++ // Dock shortcuts: apps, files, folders (web links: drag them from the browser onto the dock).+ var shortcuts = Item(UiText.Get("ShortcutAdd"), "IconPlus");+ var file = Item(UiText.Get("ShortcutAddFile"), "IconFile");+ file.Click += (_, _) => AddShortcutFromFile_Click();+ shortcuts.Items.Add(file);+ var folder = Item(UiText.Get("ShortcutAddFolder"), "IconFolder");+ folder.Click += (_, _) => AddShortcutFromFolder_Click();+ shortcuts.Items.Add(folder);+ var hint = Item(UiText.Get("ShortcutDropHint"), "IconLink");+ hint.IsEnabled = false;+ shortcuts.Items.Add(hint);+ menu.Items.Add(shortcuts);++ var desktopWidgets = Item(DesktopWidgets.Desk.L("Masaüstüne widget ekle…", "Add desktop widgets…"), "IconApps");+ desktopWidgets.Click += (_, _) => ShowDesktopWidgetGallery();+ menu.Items.Add(desktopWidgets);++ // Weather city: all 81 provinces, plus "other" for districts or foreign cities.+ var city = Item(string.Format(UiText.Get("MenuCity"), options.WeatherCity), "IconMapPin");+ foreach (var province in Provinces)+ {+ var item = Item(province, null, string.Equals(province, options.WeatherCity, StringComparison.CurrentCultureIgnoreCase));+ item.Click += (_, _) => SaveWidgetOptions(options with { WeatherCity = province });+ city.Items.Add(item);+ }+ city.Items.Add(new Separator());+ var other = Item(UiText.Get("MenuCityOther"), "IconSettings");+ other.Click += (_, _) => WidgetBar_SettingsRequested(this, EventArgs.Empty);+ city.Items.Add(other);+ menu.Items.Add(city);+ menu.Items.Add(new Separator());+++ var position = Item(UiText.Get("MenuPosition"), "IconAlignCenter");+ foreach (var (value, key) in new[] { (DockPosition.Left, "Left"), (DockPosition.Center, "Center"), (DockPosition.Right, "Right") })+ {+ var item = Item(UiText.Get(key), null, current.Position == value);+ item.Click += (_, _) => SavePreferences(_preferences.Current with { Position = value });+ position.Items.Add(item);+ }+ menu.Items.Add(position);++ var autoHide = Item(UiText.Get("MenuAutoHide"), "IconDock");+ foreach (var (value, key) in new[] { (AutoHideMode.Disabled, "MenuAutoHideOff"), (AutoHideMode.Smart, "MenuAutoHideSmart"), (AutoHideMode.Always, "MenuAutoHideAlways") })+ {+ var item = Item(UiText.Get(key), null, current.AutoHide == value);+ item.Click += (_, _) => SavePreferences(_preferences.Current with { AutoHide = value });+ autoHide.Items.Add(item);+ }+ menu.Items.Add(autoHide);++ var theme = Item(UiText.Get("MenuTheme"), "IconMoon");+ foreach (var (value, key) in new[] { (AppTheme.Dark, "Dark"), (AppTheme.Light, "Light") })+ {+ var item = Item(UiText.Get(key), null, current.Theme == value);+ item.Click += (_, _) => SavePreferences(_preferences.Current with { Theme = value });+ theme.Items.Add(item);+ }+ // Looks: Glass follows the dark/light choice above, the others bring their own colours.+ theme.Items.Add(new Separator());+ foreach (var look in ThemeStyles.All)+ {+ var item = Item(look.Name, null, ThemeStyles.Find(current.Style).Id == look.Id);+ item.Click += (_, _) => SavePreferences(_preferences.Current with { Style = look.Id });+ theme.Items.Add(item);+ }+ menu.Items.Add(theme);++ var cleanDesktop = Item(UiText.Get("MenuHideDesktopIcons"), "IconMonitor", current.HideDesktopIcons);+ cleanDesktop.Click += (_, _) => SavePreferences(_preferences.Current with { HideDesktopIcons = !_preferences.Current.HideDesktopIcons });+ menu.Items.Add(cleanDesktop);++ var peek = Item(UiText.Get("MenuTopBarPeek"), "IconLayout", current.TopBarPeek);+ peek.Click += (_, _) => SavePreferences(_preferences.Current with { TopBarPeek = !_preferences.Current.TopBarPeek });+ peek.IsEnabled = current.WidgetPlacement == WidgetPlacement.TopBar;+ menu.Items.Add(peek);++ var genie = Item(UiText.Get("GenieEffect"), "IconSparkle", current.GenieEffectEnabled);+ genie.Click += (_, _) => SavePreferences(_preferences.Current with { GenieEffectEnabled = !_preferences.Current.GenieEffectEnabled });+ genie.IsEnabled = current.AnimationsEnabled; // the effect needs animations; on without them it would do nothing+ menu.Items.Add(genie);+ menu.Items.Add(new Separator());++ var settings = Item(UiText.Get("Settings"), "IconSettings");+ settings.Click += OpenSettings_Click;+ menu.Items.Add(settings);+ menu.Items.Add(new Separator());+ var exit = Item(UiText.Get("Exit"), "IconExit");+ exit.Click += ExitQiDock_Click;+ menu.Items.Add(exit);++ menu.IsOpen = true;+ }++ /// <summary>+ /// The dock never takes activation, so as soon as a menu activates itself Windows moves mouse capture+ /// and a StaysOpen=false menu closes again within a frame. Menus therefore stay open on their own and+ /// close here: on a click outside them (another app, the desktop or the dock) or after an item runs.+ /// </summary>+ private void BeginMenuWatch(ContextMenu menu)+ {+ menu.StaysOpen = true;+ if (!_menuWatchHooked)+ {+ _menuWatchHooked = true;+ _menuWatch.Tick += (_, _) => WatchMenu();+ }+ if (menu.Tag as string != "watched")+ {+ menu.Tag = "watched";+ menu.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler((_, e) =>+ {+ if (e.OriginalSource is MenuItem { HasItems: false, StaysOpenOnClick: false }) menu.IsOpen = false;+ }));+ menu.PreviewKeyDown += (_, e) =>+ {+ if (e.Key == Key.Escape) menu.IsOpen = false;+ };+ }+ _menuButtonWasDown = AnyMouseButtonDown();+ _menuWatch.Start();+ }++ private void WatchMenu()+ {+ if (_openContextMenu is not { IsOpen: true } menu)+ {+ _menuWatch.Stop();+ return;+ }+ var down = AnyMouseButtonDown();+ var pressed = down && !_menuButtonWasDown;+ _menuButtonWasDown = down;+ if (!pressed || !DeskNative.GetCursorPos(out var cursor)) return;+ var root = DeskNative.GetAncestor(DeskNative.WindowFromPoint(cursor), 2);+ DeskNative.GetWindowThreadProcessId(root, out var processId);+ // Inside the menu or one of its submenus (our own popup windows): leave it to the menu.+ if (processId == Environment.ProcessId && root != (_source?.Handle ?? 0) && root != (_topBar?.Handle ?? 0)) return;+ menu.IsOpen = false;+ }++ private static bool AnyMouseButtonDown() =>+ (DeskNative.GetAsyncKeyState(0x01) & 0x8000) != 0 || (DeskNative.GetAsyncKeyState(0x02) & 0x8000) != 0 || (DeskNative.GetAsyncKeyState(0x04) & 0x8000) != 0;++ private static MenuItem Item(string header, string? icon, bool? isChecked = null)+ {+ var item = new MenuItem { Header = header.Replace("_", "__") };+ if (icon is not null && Application.Current.TryFindResource(icon) is Geometry geometry) item.Icon = geometry;+ if (isChecked is { } value) item.IsChecked = value;+ return item;+ }++ private void SavePreferences(DockSettings settings)+ {+ if (_preferences.Save(settings) is { } error) ShowStatus(error);+ }++ private void SaveWidgetOptions(WidgetSettings options) => SavePreferences(_preferences.Current with { Widgets = options });++ private void WidgetBar_SettingsEdited(object? sender, WidgetSettings options) => SaveWidgetOptions(options);++ /// <summary>"Add widget" pill in edit mode: lists the hidden widgets.</summary>+ private void WidgetBar_AddRequested(object? sender, FrameworkElement anchor)+ {+ var options = _preferences.Current.WidgetOptions;+ var menu = new ContextMenu { PlacementTarget = anchor, Placement = Services.DockGeometry.Inward };+ menu.Opened += DockContextMenu_Opened;+ menu.Closed += DockContextMenu_Closed;+ foreach (var id in options.EffectiveOrder.Where(id => !options.IsVisible(id)))+ {+ var item = Item(UiText.Get("Widget_" + id), "IconPlus");+ item.Click += (_, _) => _widgetBar.ShowWidget(id);+ menu.Items.Add(item);+ }+ if (menu.Items.Count == 0) menu.Items.Add(new MenuItem { Header = UiText.Get("EditAllShown"), IsEnabled = false });+ menu.IsOpen = true;+ }++ private void WidgetBar_EditingChanged(object? sender, EventArgs e)+ {+ // Editing happens in the top bar, which stays on screen until "Done" even over open windows.+ UpdateTopBarContent();+ }++ // ---- Start button -----------------------------------------------------------------------++ // Windows dismisses Start itself on the mouse-down outside it, before our click arrives, so a+ // second click would reopen it. Track when Start was last open and treat a click right after+ // it closed as "close", like the Windows taskbar.+ private bool _startOpen;+ private DateTime _startClosedAt;++ private void TrackStartMenu(nint foreground)+ {+ var open = IsStartMenuWindow(foreground);+ if (_startOpen && !open) _startClosedAt = DateTime.UtcNow;+ _startOpen = open;+ }++ private void StartButton_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) =>+ _startWasOpenAtPress = IsStartMenuOpen() || _startOpen || DateTime.UtcNow - _startClosedAt < TimeSpan.FromMilliseconds(600);++ /// <summary>The Start menu (or search) is the foreground window.</summary>+ private static bool IsStartMenuOpen() => IsStartMenuWindow(DeskNative.GetForegroundWindow());++ private static bool IsStartMenuWindow(nint foreground)+ {+ if (foreground == 0) return false;+ DeskNative.GetWindowThreadProcessId(foreground, out var processId);+ try+ {+ using var process = Process.GetProcessById((int)processId);+ return process.ProcessName is "StartMenuExperienceHost" or "SearchHost" or "SearchApp" or "ShellExperienceHost";+ }+ catch (ArgumentException)+ {+ return false;+ }+ }++ /// <summary>Second click on Start closes the menu, like the Windows taskbar.</summary>+ private bool CloseStartMenuIfOpen()+ {+ if (!_startWasOpenAtPress) return false;+ _startWasOpenAtPress = false;+ _startClosedAt = default;+ if (IsStartMenuOpen())+ {+ const byte vkEscape = 0x1B;+ DeskNative.keybd_event(vkEscape, 0, 0, 0);+ DeskNative.keybd_event(vkEscape, 0, 2, 0);+ }+ return true;+ }++ // ---- Desktop ----------------------------------------------------------------------------++ // True while the Desktop button has the desktop showing (windows minimized, icons visible).+ private bool _desktopShown;+ private DateTime _desktopShownAt;++ private void ToggleDesktop()+ {+ // Straight to Explorer's taskbar (what Win+D does): asking the shell to do it would find the dock's own+ // hidden tray window, which holds the background app icons, first.+ if (TrayHost.FindExplorerTaskbar() is var taskbar and not 0 && PostMessage(taskbar, 0x0111 /* WM_COMMAND */, 407 /* toggle desktop */, 0))+ return;+ object? shell = null;+ try+ {+ if (Type.GetTypeFromProgID("Shell.Application") is not { } type) return;+ shell = Activator.CreateInstance(type);+ type.InvokeMember("ToggleDesktop", System.Reflection.BindingFlags.InvokeMethod, null, shell, null);+ }+ catch (Exception ex) when (ex is COMException or System.Reflection.TargetInvocationException or InvalidCastException)+ {+ Trace.TraceWarning("Show desktop failed: {0}", ex.Message);+ }+ finally+ {+ if (shell is not null && Marshal.IsComObject(shell)) Marshal.ReleaseComObject(shell);+ }+ }++ /// <summary>Keeps the desktop clean whenever another window comes forward.</summary>+ private void KeepDesktopClean(nint foreground)+ {+ if (_desktopShown || _cleanShown)+ {+ // Either desktop ends only when a real app window comes forward. While Windows moves the+ // windows aside, focus passes through the taskbar and passing shell windows: those must not+ // hide the icons again (that made both desktop buttons look the same).+ if (DateTime.UtcNow - _desktopShownAt < TimeSpan.FromMilliseconds(900) || !IsAppWindow(foreground)) return;+ LeaveDesktop();+ }+ if (!_preferences.Current.HideDesktopIcons) return;+ ApplyDesktopIcons(true);+ }++ private static bool IsDesktopWindow(nint window)+ {+ if (window == 0) return false;+ var name = new System.Text.StringBuilder(32);+ DeskNative.GetClassName(window, name, name.Capacity);+ return name.ToString() is "Progman" or "WorkerW";+ }++ /// <summary>A window the user works in: shown, not minimized, not a tool window, not part of the shell.</summary>+ private static bool IsAppWindow(nint window)+ {+ if (window == 0 || !DeskNative.IsWindowVisible(window) || DeskNative.IsIconic(window)) return false;+ if ((DeskNative.GetWindowLongPtr(window, -20).ToInt64() & 0x00000080) != 0) return false; // WS_EX_TOOLWINDOW+ var name = new System.Text.StringBuilder(64);+ DeskNative.GetClassName(window, name, name.Capacity);+ return name.ToString() is not ("Progman" or "WorkerW" or "Shell_TrayWnd" or "Shell_SecondaryTrayWnd"+ or "ForegroundStaging" or "XamlExplorerHostIslandWindow" or "ApplicationManager_DesktopShellWindow"+ or "MultitaskingViewFrame" or "TaskListThumbnailWnd" or "NotifyIconOverflowWindow"+ or "TopLevelWindowForOverflowXamlIsland" or "Windows.UI.Core.CoreWindow");+ }++ /// <summary>+ /// Right after Windows starts, the dock can be up before Explorer has made the desktop (or Explorer makes it+ /// again a moment later). For the first two minutes the clean desktop is checked every few seconds: the icons+ /// are hidden once there, and the desktop widgets are tied to the desktop once it exists.+ /// </summary>+ private void WatchDesktopWhileStarting()+ {+ var started = DateTime.UtcNow;+ var hadDesktop = DeskNative.FindWindow("Progman", null) != 0;+ var timer = new System.Windows.Threading.DispatcherTimer(System.Windows.Threading.DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(3) };+ timer.Tick += (_, _) =>+ {+ if (DateTime.UtcNow - started > TimeSpan.FromMinutes(2)) timer.Stop();+ if (!hadDesktop && DeskNative.FindWindow("Progman", null) != 0)+ {+ hadDesktop = true;+ _deskWidgets?.Reattach();+ }+ if (_preferences.Current.HideDesktopIcons && !_desktopShown && FindDesktopListView() is var view and not 0 && DeskNative.IsWindowVisible(view))+ ApplyDesktopIcons(true);+ };+ timer.Start();+ }++ /// <summary>Hides (or shows again) the icons on the Windows desktop so only the wallpaper remains.</summary>+ private void ApplyDesktopIcons(bool hide)+ {+ var view = FindDesktopListView();+ if (view == 0) return;+ var visible = DeskNative.IsWindowVisible(view);+ if (hide)+ {+ if (visible) DeskNative.ShowWindow(view, 0);+ _desktopIconsHidden = true;+ MarkDesktopIconsHidden(true);+ return;+ }+ // Also when an earlier run hid them and never came back (crash, killed): the mark on disk says so.+ if (!visible && (_desktopIconsHidden || File.Exists(DesktopIconsMark))) DeskNative.ShowWindow(view, 5);+ _desktopIconsHidden = false;+ MarkDesktopIconsHidden(false);+ }++ private static readonly string DesktopIconsMark = Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock", "desktop-icons-hidden");++ private static void MarkDesktopIconsHidden(bool hidden)+ {+ try+ {+ if (hidden)+ {+ if (File.Exists(DesktopIconsMark)) return;+ Directory.CreateDirectory(Path.GetDirectoryName(DesktopIconsMark)!);+ File.WriteAllText(DesktopIconsMark, "");+ }+ else if (File.Exists(DesktopIconsMark)) File.Delete(DesktopIconsMark);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }+ }++ private static nint FindDesktopListView()+ {+ var defView = DeskNative.FindWindowEx(DeskNative.FindWindow("Progman", null), 0, "SHELLDLL_DefView", null);+ if (defView == 0)+ {+ // After a wallpaper slideshow or Win+Tab, Explorer re-parents the view under a WorkerW.+ nint worker = 0;+ while ((worker = DeskNative.FindWindowEx(0, worker, "WorkerW", null)) != 0)+ {+ defView = DeskNative.FindWindowEx(worker, 0, "SHELLDLL_DefView", null);+ if (defView != 0) break;+ }+ }+ return defView == 0 ? 0 : DeskNative.FindWindowEx(defView, 0, "SysListView32", null);+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct NativePoint { public int X, Y; }++ private static class DeskNative+ {+ [DllImport("user32.dll")] public static extern nint GetForegroundWindow();+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsIconic(nint window);+ [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW")] public static extern nint GetWindowLongPtr(nint window, int index);+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassName(nint window, System.Text.StringBuilder name, int count);+ [DllImport("user32.dll")] public static extern short GetAsyncKeyState(int key);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetCursorPos(out NativePoint point);+ [DllImport("user32.dll")] public static extern nint WindowFromPoint(NativePoint point);+ [DllImport("user32.dll")] public static extern nint GetAncestor(nint window, uint flags);+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(nint window, out uint processId);+ [DllImport("user32.dll")] public static extern void keybd_event(byte key, byte scan, uint flags, nint extra);+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern nint FindWindow(string? className, string? title);+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern nint FindWindowEx(nint parent, nint after, string? className, string? title);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWindowVisible(nint window);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool ShowWindow(nint window, int command);+ }+}diff --git a/MainWindow.Edge.cs b/MainWindow.Edge.csnew file mode 100644index 0000000..480ed24--- /dev/null+++ b/MainWindow.Edge.cs@@ -0,0 +1,139 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media;+using QiDock.Models;+using QiDock.Services;++namespace QiDock;++/// <summary>+/// The dock can stand on any screen edge. It is laid out as if it stood on the bottom edge and the whole layout+/// is turned to the real edge (<see cref="DockGeometry.FrameToScreen"/>), so magnification, hiding, reordering and+/// the running dots all keep working unchanged. Pictures and text are turned back so they always stand upright.+/// </summary>+public partial class MainWindow+{+ private DockEdge? _appliedEdge;++ private DockEdge? _edgeOverride;++ private DockEdge Edge => _edgeOverride ?? _preferences.Current.Edge;++ private void ApplyDockEdge()+ {+ var edge = Edge;+ DockGeometry.Edge = edge;+ if (_appliedEdge == edge) return;+ var first = _appliedEdge is null;+ _appliedEdge = edge;+ ResetMagnification();+ _thumbnailPreview.Hide();+ DockHost.LayoutTransform = edge == DockEdge.Bottom ? Transform.Identity : new MatrixTransform(DockGeometry.FrameToScreen(edge));+ StatusText.LayoutTransform = UprightTransform();+ OrientAllIcons();+ _placedWidgets = null;+ ApplyWidgetPlacement();+ if (first) return; // the taskbar session starts with the edge already set+ if (_replacementSession?.IsActive == true) _replacementSession.SetEdge(edge);+ else PositionDock();+ }++ /// <summary>Undoes the dock's turn for something that must read upright (text, pictures).</summary>+ private static Transform UprightTransform()+ {+ if (DockGeometry.Edge == DockEdge.Bottom) return Transform.Identity;+ var counter = DockGeometry.FrameToScreen(DockGeometry.Edge);+ counter.Invert();+ return new MatrixTransform(counter);+ }++ /// <summary>+ /// Turns a tile's picture upright about its own centre, before its magnification and bounce. Those keep working+ /// in the dock's frame: a tile still grows out of the screen edge and bounces away from it.+ /// </summary>+ private static void OrientIcon(FrameworkElement icon)+ {+ var (_, _) = GetIconTransforms(icon);+ if (icon.RenderTransform is not TransformGroup group) return;+ var orient = group.Children.OfType<MatrixTransform>().FirstOrDefault();+ if (orient is null)+ {+ if (DockGeometry.Edge == DockEdge.Bottom) return;+ orient = new MatrixTransform();+ group.Children.Insert(0, orient);+ }+ var counter = DockGeometry.FrameToScreen(DockGeometry.Edge);+ counter.Invert();+ var tile = Application.Current.Resources["DockTileSize"] is double size ? size : 48;+ var width = double.IsNaN(icon.Width) ? tile : icon.Width;+ var height = double.IsNaN(icon.Height) ? tile : icon.Height;+ var origin = icon.RenderTransformOrigin;+ // The centre, seen from the transform origin (the tile's foot).+ var cx = width * (0.5 - origin.X);+ var cy = height * (0.5 - origin.Y);+ var matrix = Matrix.Identity;+ matrix.Translate(-cx, -cy);+ matrix.Append(counter);+ matrix.Translate(cx, cy);+ orient.Matrix = matrix;+ }++ private void OrientAllIcons()+ {+ foreach (var button in GetAllDockButtons())+ {+ if (GetButtonIcon(button) is { } icon) OrientIcon(icon);+ PointTooltip(button);+ }+ }++ /// <summary>Tooltips open inward, clear of the magnified tile.</summary>+ private static void PointTooltip(Button button)+ {+ var placement = DockGeometry.Inward;+ ToolTipService.SetPlacement(button, placement);+ ToolTipService.SetVerticalOffset(button, placement switch { System.Windows.Controls.Primitives.PlacementMode.Top => -44, System.Windows.Controls.Primitives.PlacementMode.Bottom => 44, _ => 0 });+ ToolTipService.SetHorizontalOffset(button, placement switch { System.Windows.Controls.Primitives.PlacementMode.Right => 44, System.Windows.Controls.Primitives.PlacementMode.Left => -44, _ => 0 });+ }++ /// <summary>Where a panel grows out of this dock element (screen DIPs), or null while the dock is not laid out.</summary>+ private EdgePanel.DockAnchor? DockAnchorOf(FrameworkElement element)+ {+ _panelOnTopBar = false;+ var tile = element is Button { Content: FrameworkElement face } ? face : element;+ if (!IsVisible || tile.ActualWidth <= 0 || DockSurface.ActualHeight <= 0 || !tile.IsDescendantOf(this)) return null;+ // Bounds before magnification and bounce: the tile's own box, through the dock's turn.+ var bounds = tile.TransformToAncestor(this).TransformBounds(new Rect(tile.RenderSize));+ // Where the dock rests, not where its hiding slide has it now (a panel brings the dock back up as it opens).+ if (VisualTreeHelper.GetParent(DockSurface) is not Visual dockParent) return null;+ var surface = dockParent.TransformToAncestor(this).TransformBounds(new Rect((Point)VisualTreeHelper.GetOffset(DockSurface), DockSurface.RenderSize));+ var round = DockSurface.CornerRadius.TopLeft + 6; // clear of the dock's rounded ends+ var (dockStart, dockEnd) = DockGeometry.Vertical+ ? (Top + surface.Top + round, Top + surface.Bottom - round)+ : (Left + surface.Left + round, Left + surface.Right - round);+ return Edge switch+ {+ DockEdge.Top => new EdgePanel.DockAnchor(DockEdge.Top, Left + (bounds.Left + bounds.Right) / 2, bounds.Width, Top + surface.Bottom, dockStart, dockEnd),+ DockEdge.Left => new EdgePanel.DockAnchor(DockEdge.Left, Top + (bounds.Top + bounds.Bottom) / 2, bounds.Height, Left + surface.Right, dockStart, dockEnd),+ DockEdge.Right => new EdgePanel.DockAnchor(DockEdge.Right, Top + (bounds.Top + bounds.Bottom) / 2, bounds.Height, Left + surface.Left, dockStart, dockEnd),+ _ => new EdgePanel.DockAnchor(DockEdge.Bottom, Left + (bounds.Left + bounds.Right) / 2, bounds.Width, Top + surface.Top, dockStart, dockEnd)+ };+ }++ /// <summary>+ /// Leaves the dock's inner edge out under a panel standing on it, between two screen points on the line where+ /// the panel's foot ends (the cut goes down to exactly that line).+ /// </summary>+ private void CutDockSeam((Point From, Point To)? seam)+ {+ if (seam is not { } line || DockSurface.ActualWidth <= 0)+ {+ DockSurface.OpacityMask = null;+ return;+ }+ var a = TranslatePoint(new Point(line.From.X - Left, line.From.Y - Top), DockSurface);+ var b = TranslatePoint(new Point(line.To.X - Left, line.To.Y - Top), DockSurface);+ var depth = Math.Max(0, Math.Max(a.Y, b.Y));+ DockSurface.OpacityMask = EdgePanel.NotchMask(new Size(DockSurface.ActualWidth, DockSurface.ActualHeight), Math.Min(a.X, b.X), Math.Max(a.X, b.X), depth);+ }+}diff --git a/MainWindow.Extras.cs b/MainWindow.Extras.csnew file mode 100644index 0000000..4f950bb--- /dev/null+++ b/MainWindow.Extras.cs@@ -0,0 +1,256 @@+using System.IO;+using System.Runtime.InteropServices;+using System.Text;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Interop;+using System.Windows.Threading;+using QiDock.Services;+using QiDock.Widgets;++namespace QiDock;++/// <summary>+/// AppGrid, QuickSearch and Window Overview on global shortcuts, the Downloads stack on the dock,+/// hiding the dock and bar while a full-screen app is in front, and giving memory back while idle.+/// </summary>+public partial class MainWindow+{+ // Alt+Shift+Space: QuickSearch · Ctrl+Alt+↑: Window Overview · Ctrl+Alt+↓: AppGrid ·+ // Ctrl+Alt+←: notification center · Ctrl+Alt+→: control center.+ // (Alt+Space and Ctrl+Alt+Space are usually taken by other apps' quick launchers.)+ private const int HotkeyQuickSearch = 0xB001, HotkeyWindowOverview = 0xB002, HotkeyAppGrid = 0xB003, HotkeyNotifications = 0xB004, HotkeyControlCenter = 0xB005, HotkeyProfileFirst = 0xB011;+ private static readonly TimeSpan IdleBeforeTrim = TimeSpan.FromMinutes(2);++ private readonly DispatcherTimer _fullScreenWatch = new(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(1) };+ private readonly DispatcherTimer _memoryTrim = new(DispatcherPriority.ApplicationIdle) { Interval = TimeSpan.FromMinutes(1) };+ private WidgetPopup? _downloadsPopup;+ private nint _extrasHandle;+ private bool _ownFullScreenHide;+ private uint _trimmedAtInput;++ private void InitializeExtras(HwndSource source)+ {+ _extrasHandle = source.Handle;+ source.AddHook(ExtrasHook);+ RegisterHotKey(_extrasHandle, HotkeyQuickSearch, ModAlt | ModShift | ModNoRepeat, 0x20 /* Space */);+ RegisterHotKey(_extrasHandle, HotkeyWindowOverview, ModControl | ModAlt | ModNoRepeat, 0x26 /* Up */);+ RegisterHotKey(_extrasHandle, HotkeyAppGrid, ModControl | ModAlt | ModNoRepeat, 0x28 /* Down */);+ RegisterHotKey(_extrasHandle, HotkeyNotifications, ModControl | ModAlt | ModNoRepeat, 0x25 /* Left */);+ RegisterHotKey(_extrasHandle, HotkeyControlCenter, ModControl | ModAlt | ModNoRepeat, 0x27 /* Right */);+ // Ctrl+Alt+Shift+1…9: widget profiles (Ctrl+Alt alone is AltGr, which types # $ { [ on Turkish keyboards).+ for (var i = 0; i < 9; i++)+ RegisterHotKey(_extrasHandle, HotkeyProfileFirst + i, ModControl | ModAlt | ModShift | ModNoRepeat, (uint)(0x31 + i));+ ControlCenter.OpenAppSettings = () => OpenSettings_Click(this, new RoutedEventArgs());+ _downloadsPopup = new WidgetPopup(DownloadsButton);+ _downloadsPopup.Closed += (_, _) => _autoHideController?.EvaluateState();+ _fullScreenWatch.Tick += (_, _) => UpdateFullScreenAwareness(GetForegroundWindow());+ _fullScreenWatch.Start();+ _memoryTrim.Tick += (_, _) => TrimMemoryWhenIdle();+ _memoryTrim.Start();+ // Start-up work (icons, widgets, the first layout) leaves a lot of memory that is never touched again.+ var startupTrim = new DispatcherTimer(DispatcherPriority.ApplicationIdle) { Interval = TimeSpan.FromSeconds(45) };+ startupTrim.Tick += (_, _) =>+ {+ startupTrim.Stop();+ TrimMemory();+ };+ startupTrim.Start();+ OverlayWindow.AnyClosed += TrimMemory;+ }++ private nint ExtrasHook(nint window, int message, nint wParam, nint lParam, ref bool handled)+ {+ if (message != 0x0312 /* WM_HOTKEY */) return 0;+ switch ((int)wParam)+ {+ case HotkeyQuickSearch: QuickSearchWindow.Toggle(); break;+ case HotkeyWindowOverview: WindowOverviewWindow.Toggle(_windowTracker?.Snapshot ?? []); break;+ case HotkeyAppGrid: AppGridWindow.Toggle(); break;+ case HotkeyNotifications: NotificationCenter.Shared.Toggle(); break;+ case HotkeyControlCenter: ControlCenter.Shared.Toggle(); break;+ case >= HotkeyProfileFirst and < HotkeyProfileFirst + 9:+ var options = _preferences.Current.WidgetOptions;+ var index = (int)wParam - HotkeyProfileFirst;+ if (index >= options.EffectiveProfiles.Count) return 0;+ if (index != options.EffectiveActiveProfile) SaveWidgetOptions(options.SwitchProfile(index));+ Widgets.Ui.ShowHud("IconLayout", options.EffectiveProfiles[index].Name);+ break;+ default: return 0;+ }+ handled = true;+ return 0;+ }++ private void AppGridButton_Click(object sender, RoutedEventArgs e) => AppGridWindow.Toggle();++ private void DisposeExtras()+ {+ _fullScreenWatch.Stop();+ _memoryTrim.Stop();+ if (_extrasHandle != 0)+ {+ UnregisterHotKey(_extrasHandle, HotkeyQuickSearch);+ UnregisterHotKey(_extrasHandle, HotkeyWindowOverview);+ UnregisterHotKey(_extrasHandle, HotkeyAppGrid);+ UnregisterHotKey(_extrasHandle, HotkeyNotifications);+ UnregisterHotKey(_extrasHandle, HotkeyControlCenter);+ for (var i = 0; i < 9; i++) UnregisterHotKey(_extrasHandle, HotkeyProfileFirst + i);+ }+ _downloadsPopup?.Close();+ if (ControlCenter.IsCreated) ControlCenter.Shared.Close();+ }++ // ---- Full-screen apps ------------------------------------------------------------------++ /// <summary>+ /// Games, videos and presentations in full screen get the whole screen: the dock and the bar+ /// step aside until another window comes to the front. (The taskbar-replacement mode does+ /// this on its own.)+ /// </summary>+ private void UpdateFullScreenAwareness(nint foreground)+ {+ if (_replacementSession is not null || foreground == 0) return;+ GetWindowThreadProcessId(foreground, out var process);+ if (process == Environment.ProcessId) return;+ var fullScreen = IsFullScreenWindow(foreground);+ if (fullScreen == _ownFullScreenHide) return;+ _ownFullScreenHide = fullScreen;+ if (_extrasHandle != 0) ShowWindow(_extrasHandle, fullScreen ? 0 /* SW_HIDE */ : 4 /* SW_SHOWNOACTIVATE */);+ OnFullScreenChanged(fullScreen);+ }++ private static bool IsFullScreenWindow(nint window)+ {+ if (!IsWindowVisible(window) || IsIconic(window) || IsZoomed(window)) return false;+ var name = new StringBuilder(64);+ GetClassName(window, name, name.Capacity);+ if (name.ToString() is "Progman" or "WorkerW" or "Shell_TrayWnd" or "Windows.UI.Core.CoreWindow") return false;+ var monitor = new MonitorInfo { Size = (uint)Marshal.SizeOf<MonitorInfo>() };+ return GetMonitorInfo(MonitorFromWindow(window, 2), ref monitor) && GetWindowRect(window, out var rect)+ && rect.Left <= monitor.Bounds.Left && rect.Top <= monitor.Bounds.Top+ && rect.Right >= monitor.Bounds.Right && rect.Bottom >= monitor.Bounds.Bottom;+ }++ // ---- Memory ----------------------------------------------------------------------------++ /// <summary>After a couple of idle minutes, hands unused memory back to Windows (once per idle spell).</summary>+ private void TrimMemoryWhenIdle()+ {+ var input = new LastInputInfo { Size = (uint)Marshal.SizeOf<LastInputInfo>() };+ if (!GetLastInputInfo(ref input) || input.Time == _trimmedAtInput) return;+ if (TimeSpan.FromMilliseconds(unchecked((uint)Environment.TickCount - input.Time)) < IdleBeforeTrim) return;+ if (EdgePanel.AnyOpen || _thumbnailPreview.IsVisible) return;+ _trimmedAtInput = input.Time;+ TrimMemory();+ }++ private static void TrimMemory()+ {+ GC.Collect(2, GCCollectionMode.Optimized, blocking: false);+ using var self = System.Diagnostics.Process.GetCurrentProcess();+ SetProcessWorkingSetSize(self.Handle, -1, -1);+ }++ // ---- Downloads stack -------------------------------------------------------------------++ private void DownloadsButton_Click(object sender, RoutedEventArgs e)+ {+ if (_downloadsPopup is null) return;+ if (!_downloadsPopup.IsOpen) _downloadsPopup.SetContent(BuildDownloads(), 392);+ _downloadsPopup.Toggle();+ }++ private UIElement BuildDownloads()+ {+ var folder = DownloadsFolder();+ var root = new StackPanel();+ var open = Ui.Pill(UiText.Get("DownloadsOpenFolder"), (_, _) =>+ {+ _downloadsPopup?.Close();+ Ui.Open(folder);+ }, "IconFolderOpen");+ root.Children.Add(Ui.Header(UiText.Get("DownloadsTitle"), () => _downloadsPopup?.Close(), open));+ var files = Directory.Exists(folder)+ ? new DirectoryInfo(folder).EnumerateFileSystemInfos()+ .Where(f => (f.Attributes & (FileAttributes.Hidden | FileAttributes.System)) == 0 && !IsPartial(f.Name))+ .OrderByDescending(f => f.CreationTimeUtc > f.LastWriteTimeUtc ? f.CreationTimeUtc : f.LastWriteTimeUtc)+ .Take(12).ToList()+ : [];+ if (files.Count == 0)+ {+ var empty = Ui.Text(UiText.Get("DownloadsEmpty"), 12, brushKey: "TextSecondary");+ empty.Margin = new Thickness(4, 10, 4, 10);+ root.Children.Add(empty);+ return root;+ }+ var grid = new UniformGrid { Columns = 4, Margin = new Thickness(0, 4, 0, 0) };+ foreach (var file in files) grid.Children.Add(DownloadTile(file));+ root.Children.Add(grid);+ return root;+ }++ private FrameworkElement DownloadTile(FileSystemInfo file)+ {+ var icon = Ui.FileIcon(file.FullName, 44);+ icon.HorizontalAlignment = HorizontalAlignment.Center;+ var name = Ui.Text(file.Name, 11);+ name.TextAlignment = TextAlignment.Center;+ name.TextWrapping = TextWrapping.Wrap;+ name.TextTrimming = TextTrimming.CharacterEllipsis;+ name.MaxHeight = 11 * 1.4 * 2;+ name.Margin = new Thickness(0, 5, 0, 0);+ var when = Ui.Text(Ui.Ago(file.CreationTime > file.LastWriteTime ? file.CreationTime : file.LastWriteTime), 10, brushKey: "TextSecondary");+ when.HorizontalAlignment = HorizontalAlignment.Center;+ var column = new StackPanel();+ column.Children.Add(icon);+ column.Children.Add(name);+ column.Children.Add(when);+ var button = new Button { Content = column, Padding = new Thickness(4, 8, 4, 6), Margin = new Thickness(2), ToolTip = file.FullName, HorizontalContentAlignment = HorizontalAlignment.Stretch };+ button.SetResourceReference(StyleProperty, "WidgetTileButton");+ button.Height = double.NaN;+ button.Click += (_, _) =>+ {+ _downloadsPopup?.Close();+ Ui.Open(file.FullName);+ };+ FolderWidget.AttachDragOut(button, file.FullName);+ return button;+ }++ private static bool IsPartial(string name) =>+ name.EndsWith(".crdownload", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".part", StringComparison.OrdinalIgnoreCase)+ || name.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase) || name.Equals("desktop.ini", StringComparison.OrdinalIgnoreCase);++ private static string DownloadsFolder()+ {+ if (SHGetKnownFolderPath(new Guid("374DE290-123F-4565-9164-39C4925E467B"), 0, 0, out var pointer) == 0 && pointer != 0)+ {+ try { return Marshal.PtrToStringUni(pointer) ?? ""; }+ finally { Marshal.FreeCoTaskMem(pointer); }+ }+ return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");+ }++ // ---- Native ----------------------------------------------------------------------------++ private const uint ModAlt = 0x1, ModControl = 0x2, ModShift = 0x4, ModNoRepeat = 0x4000;++ [StructLayout(LayoutKind.Sequential)] private struct LastInputInfo { public uint Size; public uint Time; }+ [StructLayout(LayoutKind.Sequential)] private struct MonitorInfo { public uint Size; public NativeRect Bounds; public NativeRect Work; public uint Flags; }++ [DllImport("user32.dll")] private static extern bool RegisterHotKey(nint window, int id, uint modifiers, uint key);+ [DllImport("user32.dll")] private static extern bool UnregisterHotKey(nint window, int id);+ [DllImport("user32.dll")] private static extern nint GetForegroundWindow();+ [DllImport("user32.dll")] private static extern bool ShowWindow(nint window, int command);+ [DllImport("user32.dll")] private static extern bool IsWindowVisible(nint window);+ [DllImport("user32.dll")] private static extern bool IsIconic(nint window);+ [DllImport("user32.dll")] private static extern bool IsZoomed(nint window);+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetClassName(nint window, StringBuilder name, int capacity);+ [DllImport("user32.dll")] private static extern nint MonitorFromWindow(nint window, uint flags);+ [DllImport("user32.dll")] private static extern bool GetMonitorInfo(nint monitor, ref MonitorInfo info);+ [DllImport("user32.dll")] private static extern bool GetLastInputInfo(ref LastInputInfo info);+ [DllImport("kernel32.dll")] private static extern bool SetProcessWorkingSetSize(nint process, nint minimum, nint maximum);+ [DllImport("shell32.dll")] private static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid id, uint flags, nint token, out nint path);+}diff --git a/MainWindow.Hud.cs b/MainWindow.Hud.csnew file mode 100644index 0000000..ab4365f--- /dev/null+++ b/MainWindow.Hud.cs@@ -0,0 +1,126 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Interop;+using System.Windows.Threading;+using QiDock.Services;+using QiDock.Widgets;++namespace QiDock;++/// <summary>+/// Volume, brightness and short messages: a card growing out of the middle of the dock while the dock is on screen+/// (and no other panel stands on it), otherwise the small pill at the top of the screen.+/// </summary>+public partial class MainWindow+{+ private static readonly System.Windows.Media.Brush VolumeAccent = Ui.Solid("#FF30D158");+ private static readonly System.Windows.Media.Brush BrightnessAccent = Ui.Solid("#FFFFD60A");++ // GUID_VIDEO_CURRENT_MONITOR_BRIGHTNESS: Windows reports the built-in display's brightness whenever it changes.+ private static Guid _brightnessSetting = new("8ffee2c6-2d01-46be-adb9-398addc5b4ff");+ private nint _brightnessNotification;+ private int _lastBrightness = -1;++ private void InitializeHud(HwndSource source)+ {+ Ui.HudHandler = ShowMessageHud;+ if (_volumeWatcher is not null) _volumeWatcher.Changed += ShowVolumeHud;+ if (_volumeWatcher is not null) _volumeWatcher.Changed += ControlCenter.VolumeChanged;+ source.AddHook(HudHook);+ _brightnessNotification = RegisterPowerSettingNotification(source.Handle, ref _brightnessSetting, 0 /* DEVICE_NOTIFY_WINDOW_HANDLE */);+ QuietBrightness(TimeSpan.FromSeconds(30));+ }++ private DateTime _brightnessQuietUntil;++ /// <summary>+ /// Right after Windows starts (or wakes), Windows and the display driver set the saved or automatic brightness+ /// on their own; that is not the user turning it, so the card stays away for a while and only learns the level.+ /// </summary>+ private void QuietBrightness(TimeSpan span) => _brightnessQuietUntil = DateTime.UtcNow + span;++ /// <summary>Widgets in a hidden dock stop their clocks and meters; they catch up the moment it comes back.</summary>+ private void AttachHudToAutoHide()+ {+ if (_autoHideController is null) return;+ _autoHideController.VisibilityChanged += visible =>+ {+ if (WidgetsInDock) _widgetBar.SetLive(visible);+ };+ }++ /// <summary>+ /// Where the dock card would stand, or null when the dock is off screen (full-screen app), busy with another panel+ /// or the card is turned off. A hidden dock is brought up for it when <paramref name="reveal"/> (it goes down again+ /// once the card has sunk back).+ /// </summary>+ private EdgePanel.DockAnchor? HudAnchor(bool reveal = true)+ {+ if (!_preferences.Current.DockHud || !IsVisible || EdgePanel.AnyOpen && !DockHud.Shared.IsOpen) return null;+ if (_autoHideController is { IsHidden: true } hide)+ {+ if (!reveal) return null;+ hide.AnimateReveal();+ }+ return DockAnchorOf(DockSurface) is { } anchor ? anchor with { TileWidth = 56 } : null;+ }++ private void ShowVolumeHud(float level, bool muted)+ {+ var percent = (int)Math.Round(Math.Clamp(level, 0f, 1f) * 100);+ if (HudAnchor() is { } anchor)+ DockHud.Shared.ShowLevel(anchor, muted || percent == 0 ? "IconVolumeMute" : "IconVolume", UiText.Get("HudVolume"), percent, VolumeAccent, dimmed: muted);+ else _volumeHud?.ShowLevel(level, muted);+ }++ private void ShowMessageHud(string iconKey, string text)+ {+ if (HudAnchor() is { } anchor) DockHud.Shared.ShowMessage(anchor, iconKey, text);+ else _volumeHud?.ShowMessage(iconKey, text);+ }++ private void ShowBrightnessHud(int percent)+ {+ // The first report is the current level (sent on registering); a change made in an open panel shows there.+ var first = _lastBrightness < 0;+ if (percent == _lastBrightness) return;+ _lastBrightness = percent;+ if (first || DateTime.UtcNow < _brightnessQuietUntil || EdgePanel.AnyOpen && !DockHud.Shared.IsOpen) return;+ if (HudAnchor() is { } anchor) DockHud.Shared.ShowLevel(anchor, "IconSun", UiText.Get("HudBrightness"), percent, BrightnessAccent);+ else _volumeHud?.ShowMessage("IconSun", UiText.Format("HudBrightnessPill", percent));+ }++ private nint HudHook(nint window, int message, nint wParam, nint lParam, ref bool handled)+ {+ if (message != 0x0218 /* WM_POWERBROADCAST */) return 0;+ if (wParam is 0x7 /* PBT_APMRESUMESUSPEND */ or 0x12 /* PBT_APMRESUMEAUTOMATIC */)+ {+ QuietBrightness(TimeSpan.FromSeconds(20));+ return 0;+ }+ if (wParam != 0x8013 /* PBT_POWERSETTINGCHANGE */ || lParam == 0) return 0;+ var setting = Marshal.PtrToStructure<Guid>(lParam);+ if (setting != _brightnessSetting) return 0;+ var length = Marshal.ReadInt32(lParam, 16);+ if (length >= 4)+ {+ var percent = Marshal.ReadInt32(lParam, 20);+ Dispatcher.BeginInvoke(() => ShowBrightnessHud(Math.Clamp(percent, 0, 100)));+ }+ return 0;+ }++ private void DisposeHud()+ {+ if (_brightnessNotification != 0) UnregisterPowerSettingNotification(_brightnessNotification);+ _brightnessNotification = 0;+ if (_volumeWatcher is not null) _volumeWatcher.Changed -= ShowVolumeHud;+ }++ [DllImport("user32.dll", SetLastError = true)]+ private static extern nint RegisterPowerSettingNotification(nint recipient, ref Guid powerSettingGuid, int flags);++ [DllImport("user32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool UnregisterPowerSettingNotification(nint handle);+}diff --git a/MainWindow.Notifications.cs b/MainWindow.Notifications.csnew file mode 100644index 0000000..37449e5--- /dev/null+++ b/MainWindow.Notifications.cs@@ -0,0 +1,120 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using QiDock.Services.Notifications;+using QiDock.Widgets;++namespace QiDock;++/// <summary>+/// Notifications: new Windows notifications slide in at the top of the screen, the dock's bell+/// shows how many are unread, and the notification center (also opened from the widget bar) lists them.+/// </summary>+public partial class MainWindow+{+ private NotificationBanner? _notificationBanner;+ private readonly WindowsToastHider _toastHider = new();++ private void InitializeNotifications()+ {+ var feed = NotificationFeed.Shared;+ _notificationBanner = new NotificationBanner();+ _notificationBanner.Opened += feed.Remove;+ feed.Arrived += ShowNotifications;+ feed.Changed += UpdateNotificationsBadge;+ NotificationCenter.Settings = () => _preferences.Current.WidgetOptions;+ NotificationCenter.Update = change => SaveWidgetOptions(change(_preferences.Current.WidgetOptions));+ EdgePanel.TopInset = VolumeHudTop;+ EdgePanel.DockSeam = seam =>+ {+ if (seam is null)+ {+ CutDockSeam(null);+ _topBar?.CutSeam(null);+ }+ // The top bar turns solid with no edge line while a card stands on it, so nothing needs cutting+ // there; cutting would leave a row of pixels between the two windows.+ else if (!_panelOnTopBar) CutDockSeam(seam);+ };+ EdgePanel.AnyVisibilityChanged += (_, _) =>+ {+ _autoHideController?.EvaluateState();+ // While a panel stands on the dock the two are one solid piece: no edge line on the dock and no shadow+ // (the dock's shadow would darken the panel's foot, its edge line would stick out beside the curve).+ var standing = EdgePanel.StandsOnDock ? EdgePanel.SolidDockMaterial() : null;+ _topBar?.SetJoined(standing is not null && _panelOnTopBar ? standing : null);+ _topBar?.Update(); // the bar stays down while a card stands on it+ if (standing is { } solid && !_panelOnTopBar)+ {+ DockSurface.Background = solid;+ DockSurface.BorderBrush = solid;+ _dockShadow ??= DockSurface.Effect;+ DockSurface.Effect = null;+ }+ else+ {+ DockSurface.SetResourceReference(System.Windows.Controls.Border.BackgroundProperty, "DockMaterial");+ DockSurface.SetResourceReference(System.Windows.Controls.Border.BorderBrushProperty, "DockBorderMaterial");+ if (_dockShadow is not null && App.Shadows) DockSurface.Effect = _dockShadow;+ }+ };+ EdgePanel.DockAnchorFor = element =>+ {+ // A tile of the top bar (the classic layout): the card grows down out of the bar.+ if (_topBar is not null && ReferenceEquals(Window.GetWindow(element), _topBar))+ {+ var fromBar = _topBar.AnchorOf(element);+ if (fromBar is not null) _panelOnTopBar = true;+ return fromBar;+ }+ if (!ReferenceEquals(Window.GetWindow(element), this)) return null;+ EdgePanel.DockAnchor? anchor = null;+ ResetMagnification(() => anchor = DockAnchorOf(element));+ return anchor;+ };+ feed.Start();+ ApplyToastHiding();+ }++ /// <summary>Windows' own pop-up stays away while the top banners show each notification.</summary>+ private void ApplyToastHiding()+ {+ var options = _preferences.Current.WidgetOptions;+ _toastHider.SetEnabled(options.NotificationBanners && options.HideWindowsToasts);+ }++ private void ShowNotifications(IReadOnlyList<AppNotification> added)+ {+ var options = _preferences.Current.WidgetOptions;+ if (options.NotificationBanners) _notificationBanner?.Present(added);+ if (options.NotificationSound) PlaySound("Notification.Default", 0, 0x00010000 /* SND_ALIAS */ | 0x0001 /* SND_ASYNC */ | 0x0002 /* SND_NODEFAULT */);+ }++ private void UpdateNotificationsBadge()+ {+ NotificationList.SetBadge(NotificationsBadge, NotificationsBadgeText, NotificationFeed.Shared.UnreadCount);+ }++ /// <summary>The bell's list grows out of the bell itself (Ctrl+Alt+← and the bar tile keep the edge sheet).</summary>+ private void NotificationsButton_Click(object sender, RoutedEventArgs e)+ {+ // The tiles settle to their resting size and the panel grows out of where the bell comes to rest.+ EdgePanel.DockAnchor? anchor = null;+ ResetMagnification(() => anchor = DockAnchorOf(NotificationsButton));+ if (anchor is { } resting) NotificationCenter.Shared.ToggleFromDock(resting);+ else NotificationCenter.Shared.Toggle();+ }++ private static bool NotificationCenterOpen => EdgePanel.AnyOpen;++ private void DisposeNotifications()+ {+ NotificationFeed.Shared.Dispose();+ _toastHider.Dispose();+ if (NotificationCenter.IsCreated) NotificationCenter.Shared.Close();+ _notificationBanner?.Close();+ }++ [DllImport("winmm.dll", CharSet = CharSet.Unicode)]+ private static extern bool PlaySound(string sound, nint module, uint flags);+}diff --git a/MainWindow.Shortcuts.cs b/MainWindow.Shortcuts.csnew file mode 100644index 0000000..b5266c8--- /dev/null+++ b/MainWindow.Shortcuts.cs@@ -0,0 +1,376 @@+using System.Diagnostics;+using System.IO;+using System.Runtime.InteropServices;+using System.Text;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Input;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;++namespace QiDock;++/// <summary>+/// Dock shortcuts the user adds (apps, files, folders, web links: from the menu or by dropping+/// them on the dock), the two desktop buttons, and the Recycle Bin tile.+/// </summary>+public partial class MainWindow+{+ private DispatcherTimer? _trashTimer;+ private bool? _trashFull;++ // ---- Desktop buttons ---------------------------------------------------------------------++ /// <summary>"Clean desktop": straight to the wallpaper and the widgets, the desktop icons hidden.</summary>+ private void DesktopButton_Click(object sender, RoutedEventArgs e)+ {+ _thumbnailPreview.Hide();+ AnimateActivationFeedback((Button)sender);+ GoToDesktop(files: false);+ }++ /// <summary>"Desktop with files": straight to the desktop with its folders and files showing.</summary>+ private void FilesDesktopButton_Click(object sender, RoutedEventArgs e)+ {+ _thumbnailPreview.Hide();+ AnimateActivationFeedback((Button)sender);+ GoToDesktop(files: true);+ }++ // True while the clean desktop button has the desktop showing (the files one is _desktopShown).+ private bool _cleanShown;+ // True while the open windows were stepped aside by one of the desktop buttons.+ private bool _windowsAside;++ /// <summary>+ /// Goes straight to the clean desktop or to the one with files, whichever was pressed and from wherever the+ /// screen is: open windows step aside (only when some are open, since on an empty desktop Win+D would bring+ /// them back instead) and the icons are hidden or shown. The same button pressed again while still there+ /// brings the windows back.+ /// </summary>+ private void GoToDesktop(bool files)+ {+ var here = files ? _desktopShown : _cleanShown;+ if (here && _windowsAside && ComputeDesktopClean())+ {+ ToggleDesktop();+ LeaveDesktop();+ return;+ }+ if (!ComputeDesktopClean())+ {+ ToggleDesktop();+ _windowsAside = true;+ }+ _desktopShownAt = DateTime.UtcNow;+ _cleanShown = !files;+ SetDesktopFilesMode(files);+ if (!files) ApplyDesktopIcons(true);+ }++ /// <summary>Back from either desktop: the icons return to what the settings ask for.</summary>+ private void LeaveDesktop()+ {+ _windowsAside = false;+ _cleanShown = false;+ SetDesktopFilesMode(false);+ if (!_preferences.Current.HideDesktopIcons) ApplyDesktopIcons(false);+ }++ private void SetDesktopFilesMode(bool on)+ {+ _desktopShown = on;+ if (on) _desktopShownAt = DateTime.UtcNow;+ _topBar?.SetFilesMode(on);+ _deskWidgets?.SetHidden(on);+ if (on) ApplyDesktopIcons(false);+ else if (_preferences.Current.HideDesktopIcons) ApplyDesktopIcons(true);+ }++ // ---- Recycle Bin -------------------------------------------------------------------------++ private void InitializeTrash()+ {+ UpdateTrashIcon();+ _trashTimer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(30) };+ _trashTimer.Tick += (_, _) => UpdateTrashIcon();+ _trashTimer.Start();+ }++ private void UpdateTrashIcon()+ {+ var info = new RecycleBinInfo { Size = Marshal.SizeOf<RecycleBinInfo>() };+ var full = ShortcutNative.SHQueryRecycleBin(null, ref info) == 0 && info.Items > 0;+ if (_trashFull == full) return;+ _trashFull = full;+ TrashIcon.Source = ApplicationIconProvider.GetForResource(@"%SystemRoot%\System32\imageres.dll", full ? -54 : -55);+ }++ private void TrashButton_Click(object sender, RoutedEventArgs e)+ {+ _thumbnailPreview.Hide();+ AnimateActivationFeedback((Button)sender);+ Widgets.Ui.Open("shell:RecycleBinFolder");+ }++ private void TrashButton_DragOver(object sender, DragEventArgs e)+ {+ e.Effects = e.Data.GetDataPresent(DataFormats.FileDrop) ? DragDropEffects.Move : DragDropEffects.None;+ e.Handled = true;+ }++ /// <summary>Files dropped on the bin go to the Recycle Bin (undoable), like dragging them there in Explorer.</summary>+ private void TrashButton_Drop(object sender, DragEventArgs e)+ {+ e.Handled = true;+ if (e.Data.GetData(DataFormats.FileDrop) is not string[] { Length: > 0 } paths) return;+ var operation = new ShortcutNative.FileOperation+ {+ Function = 3, // FO_DELETE+ From = string.Join('\0', paths) + "\0\0",+ Flags = 0x0040 // FOF_ALLOWUNDO: to the Recycle Bin, Windows asks if needed+ };+ ShortcutNative.SHFileOperation(ref operation);+ _trashFull = null;+ UpdateTrashIcon();+ }++ private void TrashButton_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e)+ {+ e.Handled = true;+ var menu = new ContextMenu { PlacementTarget = TrashButton, Placement = Services.DockGeometry.Inward };+ menu.Opened += DockContextMenu_Opened;+ menu.Closed += DockContextMenu_Closed;+ var open = Item(UiText.Get("RecycleBinOpen"), "IconOpen");+ open.Click += (_, _) => Widgets.Ui.Open("shell:RecycleBinFolder");+ menu.Items.Add(open);+ var empty = Item(UiText.Get("RecycleBinEmpty"), "IconTrash");+ empty.IsEnabled = _trashFull == true;+ // Windows shows its own "permanently delete?" confirmation.+ empty.Click += (_, _) =>+ {+ ShortcutNative.SHEmptyRecycleBin(_source?.Handle ?? 0, null, 0);+ _trashFull = null;+ UpdateTrashIcon();+ };+ menu.Items.Add(empty);+ menu.IsOpen = true;+ }++ // ---- Shortcuts ---------------------------------------------------------------------------++ /// <summary>Dock apps for the shortcuts saved in settings (added to the pinned list on load).</summary>+ private List<DockApp> LoadCustomShortcuts(IReadOnlyCollection<DockApp> imported)+ {+ var apps = new List<DockApp>();+ foreach (var shortcut in _preferences.Current.Shortcuts ?? [])+ {+ if (imported.Any(a => string.Equals(a.ExecutablePath, shortcut.Target, StringComparison.OrdinalIgnoreCase))) continue;+ apps.Add(new DockApp(shortcut.Name, shortcut.Target) { LaunchArguments = shortcut.Arguments, IsCustomShortcut = true });+ }+ return apps;+ }++ private static System.Windows.Media.Imaging.BitmapSource? ShortcutIcon(string target) =>+ IsWebAddress(target) ? (DefaultBrowser() is { } browser ? ApplicationIconProvider.GetForFile(browser) : null) : ApplicationIconProvider.GetForFile(target);++ private static bool IsWebAddress(string target) =>+ target.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || target.StartsWith("https://", StringComparison.OrdinalIgnoreCase);++ private static string? DefaultBrowser()+ {+ uint length = 1024;+ var path = new StringBuilder((int)length);+ return ShortcutNative.AssocQueryString(0, 2 /* ASSOCSTR_EXECUTABLE */, "https", "open", path, ref length) == 0 ? path.ToString() : null;+ }++ /// <summary>Opens a shortcut that is not an app (file, folder, web page) with its default handler.</summary>+ private bool TryOpenShortcut(DockApp app, FrameworkElement? anchor)+ {+ if (!app.IsCustomShortcut || app.ExecutablePath.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return false;+ Widgets.Ui.Open(app.ExecutablePath);+ return true;+ }++ private void AddShortcutFromFile_Click()+ {+ var dialog = new Microsoft.Win32.OpenFileDialog { Title = UiText.Get("ShortcutPickFile"), Multiselect = true, DereferenceLinks = false };+ if (dialog.ShowDialog() == true) AddShortcuts(dialog.FileNames);+ }++ private void AddShortcutFromFolder_Click()+ {+ var dialog = new Microsoft.Win32.OpenFolderDialog { Title = UiText.Get("ShortcutPickFolder"), Multiselect = true };+ if (dialog.ShowDialog() == true) AddShortcuts(dialog.FolderNames);+ }++ private void AddShortcuts(IEnumerable<string> paths)+ {+ var added = 0;+ foreach (var path in paths)+ {+ var (target, arguments, name) = Describe(path);+ if (target is null) continue;+ if (_pinnedApps.Any(a => string.Equals(a.ExecutablePath, target, StringComparison.OrdinalIgnoreCase))) continue;+ var app = new DockApp(name, target) { LaunchArguments = arguments, IsCustomShortcut = true, Icon = ShortcutIcon(target) };+ var running = _runningApps.FirstOrDefault(r => string.Equals(r.ExecutablePath, target, StringComparison.OrdinalIgnoreCase));+ if (running is not null)+ {+ app.WindowCount = running.WindowCount;+ _runningApps.Remove(running);+ }+ _pinnedApps.Add(app);+ added++;+ }+ if (added == 0) return;+ SaveShortcuts();+ UpdateRunningAppsDivider();+ ResizeDockToContent();+ _replacementSession?.RefreshPosition();+ Widgets.Ui.ShowHud("IconPin", UiText.Format("ShortcutAdded", added));+ }++ private void SaveShortcuts()+ {+ var shortcuts = _pinnedApps.Where(a => a.IsCustomShortcut).Select(a => new DockShortcut(a.Name, a.ExecutablePath, a.LaunchArguments)).ToList();+ var order = _pinnedApps.Select(a => a.ExecutablePath).Distinct(StringComparer.OrdinalIgnoreCase).ToList();+ var error = _preferences.Save(_preferences.Current with { Shortcuts = shortcuts, PinOrder = order });+ if (error is not null) ShowStatus(error);+ }++ private void RemoveShortcut(DockApp app)+ {+ AnimateDockAppRemoval(PinnedApps, _pinnedApps, app, () =>+ {+ SaveShortcuts();+ if (_windowTracker is not null) UpdateRunningApps(_windowTracker.Snapshot);+ ResizeDockToContent();+ _replacementSession?.RefreshPosition();+ });+ }++ /// <summary>What a dropped or picked item opens: .lnk files are followed to their app.</summary>+ private static (string? Target, string? Arguments, string Name) Describe(string path)+ {+ if (IsWebAddress(path))+ {+ var host = Uri.TryCreate(path, UriKind.Absolute, out var uri) ? uri.Host.Replace("www.", "", StringComparison.OrdinalIgnoreCase) : path;+ return (path, null, host);+ }+ if (Directory.Exists(path))+ {+ var name = Path.GetFileName(path.TrimEnd('\\'));+ return (path, null, string.IsNullOrEmpty(name) ? path : name);+ }+ if (!File.Exists(path)) return (null, null, "");+ var title = Path.GetFileNameWithoutExtension(path);+ if (string.Equals(Path.GetExtension(path), ".url", StringComparison.OrdinalIgnoreCase))+ {+ var url = File.ReadLines(path).FirstOrDefault(l => l.StartsWith("URL=", StringComparison.OrdinalIgnoreCase))?[4..];+ return (url is not null && IsWebAddress(url) ? url : path, null, title);+ }+ if (string.Equals(Path.GetExtension(path), ".lnk", StringComparison.OrdinalIgnoreCase) && ReadLink(path) is { } link+ && link.Target.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && File.Exists(link.Target))+ {+ return (link.Target, string.IsNullOrWhiteSpace(link.Arguments) ? null : link.Arguments, title);+ }+ return (path, null, title);+ }++ private static (string Target, string Arguments)? ReadLink(string path)+ {+ object? shell = null;+ object? link = null;+ try+ {+ if (Type.GetTypeFromProgID("WScript.Shell") is not { } type) return null;+ shell = Activator.CreateInstance(type);+ link = type.InvokeMember("CreateShortcut", System.Reflection.BindingFlags.InvokeMethod, null, shell, [path]);+ if (link is null) return null;+ var linkType = link.GetType();+ var target = linkType.InvokeMember("TargetPath", System.Reflection.BindingFlags.GetProperty, null, link, null) as string ?? "";+ var arguments = linkType.InvokeMember("Arguments", System.Reflection.BindingFlags.GetProperty, null, link, null) as string ?? "";+ return (Environment.ExpandEnvironmentVariables(target), arguments);+ }+ catch (Exception ex) when (ex is COMException or System.Reflection.TargetInvocationException)+ {+ return null;+ }+ finally+ {+ if (link is not null && Marshal.IsComObject(link)) Marshal.FinalReleaseComObject(link);+ if (shell is not null && Marshal.IsComObject(shell)) Marshal.FinalReleaseComObject(shell);+ }+ }++ private static bool HasDroppable(IDataObject data) =>+ data.GetDataPresent(DataFormats.FileDrop) || data.GetDataPresent("UniformResourceLocatorW") || data.GetDataPresent("UniformResourceLocator");++ private void DockSurface_DragOver(object sender, DragEventArgs e)+ {+ if (e.Data.GetDataPresent(typeof(DockApp))) return;+ e.Effects = HasDroppable(e.Data) ? DragDropEffects.Link : DragDropEffects.None;+ e.Handled = true;+ }++ /// <summary>Drop files, folders, app shortcuts or a link from the browser to add them to the dock.</summary>+ private void DockSurface_Drop(object sender, DragEventArgs e)+ {+ if (e.Data.GetDataPresent(typeof(DockApp))) return;+ e.Handled = true;+ if (e.Data.GetData(DataFormats.FileDrop) is string[] { Length: > 0 } files)+ {+ AddShortcuts(files);+ return;+ }+ var url = ReadUrl(e.Data);+ if (url is not null && IsWebAddress(url)) AddShortcuts([url]);+ }++ private static string? ReadUrl(IDataObject data)+ {+ try+ {+ if (data.GetData("UniformResourceLocatorW") is MemoryStream wide)+ return Encoding.Unicode.GetString(wide.ToArray()).TrimEnd('\0').Trim();+ if (data.GetData("UniformResourceLocator") is MemoryStream narrow)+ return Encoding.Default.GetString(narrow.ToArray()).TrimEnd('\0').Trim();+ return data.GetData(DataFormats.UnicodeText) as string;+ }+ catch (COMException)+ {+ return null;+ }+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct RecycleBinInfo+ {+ public int Size;+ public long Bytes;+ public long Items;+ }++ private static class ShortcutNative+ {+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]+ public struct FileOperation+ {+ public nint Window;+ public uint Function;+ [MarshalAs(UnmanagedType.LPWStr)] public string From;+ [MarshalAs(UnmanagedType.LPWStr)] public string? To;+ public ushort Flags;+ [MarshalAs(UnmanagedType.Bool)] public bool AnyOperationsAborted;+ public nint NameMappings;+ [MarshalAs(UnmanagedType.LPWStr)] public string? ProgressTitle;+ }++ [DllImport("shell32.dll", CharSet = CharSet.Unicode)] public static extern int SHFileOperation(ref FileOperation operation);+ [DllImport("shell32.dll", CharSet = CharSet.Unicode)] public static extern int SHQueryRecycleBin(string? root, ref RecycleBinInfo info);+ [DllImport("shell32.dll", CharSet = CharSet.Unicode)] public static extern int SHEmptyRecycleBin(nint window, string? root, uint flags);+ [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] public static extern int AssocQueryString(uint flags, int what, string association, string? extra, StringBuilder output, ref uint length);+ }+}diff --git a/MainWindow.TopBar.cs b/MainWindow.TopBar.csnew file mode 100644index 0000000..559a47b--- /dev/null+++ b/MainWindow.TopBar.cs@@ -0,0 +1,799 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Media;+using System.Windows.Threading;+using QiDock.Services.Widgets;++namespace QiDock;++/// <summary>+/// The widget bar lives in its own strip at the top of the screen (the dock keeps only apps). It is+/// on screen while the desktop is clean and steps aside when app windows are open. Also hosts the+/// short volume HUD shown when the volume keys are pressed.+/// </summary>+public partial class MainWindow+{+ private TopBarWindow? _topBar;+ private VolumeHud? _volumeHud;+ private VolumeWatcher? _volumeWatcher;+ private DispatcherTimer? _desktopCheck;+ private nint _minimizeHook;+ private TopNative.WinEventProc? _minimizeProc;++ private void InitializeTopBar()+ {+ MigrateWidgetProfiles();+ HideDuplicateTiles();+ PreferControlCenterTile();+ BellToCorner();+ SecondBatchHidden();+ ApplyDockBell();+ _topBar = new TopBarWindow { Tabs = _widgetBar.ProfileStrip };+ _widgetBar.ProfileMenuRequested += (_, target) => ShowProfileMenu(target.Index, target.Anchor);+ _widgetBar.ProfilesRequested += (_, anchor) => ShowProfilesMenu(anchor);+ _topBar.SetLock(() => _widgetBar.IsAnyPopupOpen || _widgetBar.IsEditing || _openContextMenu?.IsOpen == true || EdgePanel.StandsOnDock || _holdDockUp);+ _topBar.LiveChanged += (_, live) => _widgetBar.SetLive(live || WidgetsInDock && DockOnScreen);+ _topBar.MenuRequested += (_, _) => ShowDockMenu(PlacementMode.MousePoint, null);+ _topBar.SetPeekEnabled(_preferences.Current.TopBarPeek);+ _widgetBar.SetLive(false);+ ApplyWidgetPlacement();+ UpdateTopBarContent();++ // Minimize/restore do not always change the foreground window; listen for them directly.+ _desktopCheck = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(120) };+ _desktopCheck.Tick += (_, _) =>+ {+ _desktopCheck.Stop();+ RefreshDesktopClean();+ };+ _minimizeProc = (_, _, _, objectId, _, _, _) =>+ {+ if (objectId == 0) ScheduleDesktopCheck();+ };+ _minimizeHook = TopNative.SetWinEventHook(0x0016, 0x0017, 0, _minimizeProc, 0, 0, 0);+ RefreshDesktopClean();+ InitializeTrash();++ _volumeHud = new VolumeHud { TopOffset = VolumeHudTop };+ _volumeWatcher = new VolumeWatcher(Dispatcher);+ if (PresentationSource.FromVisual(this) is System.Windows.Interop.HwndSource hudSource) InitializeHud(hudSource);+ _volumeWatcher.Start();+ }++ private Models.WidgetPlacement? _placedWidgets;+ private Border? _widgetDivider;++ private Models.WidgetPlacement? _placementOverride;+ private double _dockWidgetScale = 1;++ /// <summary>Widgets in the dock shrink with the icons when the row is too wide for the screen.</summary>+ private void SetDockWidgetScale(double scale)+ {+ scale = Math.Round(scale, 3);+ if (Math.Abs(scale - _dockWidgetScale) < 0.001) return;+ _dockWidgetScale = scale;+ ApplyWidgetHostTransform();+ AlignDockWidgets();+ }++ /// <summary>+ /// The widgets' place for the dock's edge: a side dock is too narrow for widget tiles (they keep the top strip),+ /// and a dock on the top edge takes the strip's place (the widgets then join it).+ /// </summary>+ private Models.WidgetPlacement CurrentPlacement+ {+ get+ {+ var placement = _placementOverride ?? _preferences.Current.WidgetPlacement;+ if (Services.DockGeometry.Vertical) return Models.WidgetPlacement.TopBar;+ if (Edge == Models.DockEdge.Top && placement == Models.WidgetPlacement.TopBar) return Models.WidgetPlacement.DockRight;+ return placement;+ }+ }++ private bool WidgetsInDock => CurrentPlacement != Models.WidgetPlacement.TopBar;++ /// <summary>The dock is on screen (not slid away by auto-hide): widgets in it only tick while it is.</summary>+ private bool DockOnScreen => _autoHideController is not { IsHidden: true };++ /// <summary>+ /// Puts the widget tiles where the user wants them: in the top strip (the dock keeps only apps), or inside the+ /// dock, left of the apps or right of them (before the bin), with a thin divider like the other dock groups.+ /// </summary>+ private void ApplyWidgetPlacement()+ {+ var placement = CurrentPlacement;+ if (_topBar is null || _placedWidgets == placement) return;+ _placedWidgets = placement;+ _widgetBar.ClosePopups();+ _topBar.Bar = null;+ WidgetHost.Content = null;+ _widgetDivider ??= CreateWidgetDivider();+ if (VisualTreeHelper.GetParent(WidgetHost) is Panel hostParent) hostParent.Children.Remove(WidgetHost);+ if (VisualTreeHelper.GetParent(_widgetDivider) is Panel dividerParent) dividerParent.Children.Remove(_widgetDivider);++ if (placement == Models.WidgetPlacement.TopBar)+ {+ // Parked in the dock row, empty: the dock measures it as zero width.+ DockRow.Children.Add(WidgetHost);+ WidgetHost.Visibility = Visibility.Collapsed;+ SetDockWidgetScale(1);+ _topBar.Bar = _widgetBar;+ _widgetBar.SetLive(_topBar.IsShown);+ }+ else+ {+ WidgetHost.Margin = placement == Models.WidgetPlacement.DockLeft ? new Thickness(2, 0, 0, 0) : new Thickness(0, 0, 2, 0);+ WidgetHost.VerticalAlignment = VerticalAlignment.Center;+ if (placement == Models.WidgetPlacement.DockLeft)+ {+ DockContents.Children.Insert(0, WidgetHost);+ DockContents.Children.Insert(1, _widgetDivider);+ }+ else+ {+ DockContents.Children.Add(_widgetDivider);+ DockContents.Children.Add(WidgetHost);+ }+ WidgetHost.Content = _widgetBar;+ WidgetHost.Visibility = Visibility.Visible;+ ApplyWidgetHostTransform();+ _widgetBar.SetLive(DockOnScreen);+ }+ AlignDockWidgets();+ UpdateTopBarContent();+ ResizeDockToContent();+ _replacementSession?.RefreshPosition();+ }++#if DEBUG+ /// <summary>Draws the dock with the widgets left and right of the apps (no clicks, nothing saved), then quits.</summary>+ private void SnapshotDockPlacements(string folder)+ {+ var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };+ timer.Tick += (_, _) =>+ {+ timer.Stop();+ System.IO.Directory.CreateDirectory(folder);+ foreach (var placement in new[] { Models.WidgetPlacement.TopBar, Models.WidgetPlacement.DockRight, Models.WidgetPlacement.DockLeft })+ {+ _placementOverride = placement;+ ApplyWidgetPlacement();+ UpdateLayout();+ var width = DockSurface.ActualWidth + 40;+ var height = DockSurface.ActualHeight + 40;+ var visual = new DrawingVisual();+ using (var context = visual.RenderOpen())+ {+ context.DrawRectangle(new SolidColorBrush(Color.FromRgb(0x5A, 0x7A, 0x9A)), null, new Rect(0, 0, width, height));+ context.DrawRectangle(new VisualBrush(DockSurface) { Stretch = Stretch.None }, null, new Rect(20, 20, DockSurface.ActualWidth, DockSurface.ActualHeight));+ }+ var bitmap = new System.Windows.Media.Imaging.RenderTargetBitmap((int)(width * 2), (int)(height * 2), 192, 192, PixelFormats.Pbgra32);+ bitmap.Render(visual);+ var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();+ encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmap));+ using var file = System.IO.File.Create(System.IO.Path.Combine(folder, $"dock-{placement}.png"));+ encoder.Save(file);+ }+ SnapshotSheets(folder);+ };+ timer.Start();+ }++ /// <summary>Opens two cards out of the dock (the AI limits tile, the Control Center tile) and draws each once settled.</summary>+ private void SnapshotSheets(string folder)+ {+ _placementOverride = Models.WidgetPlacement.DockRight;+ ApplyWidgetPlacement();+ UpdateLayout();+ var tiles = new Queue<(string Name, string Hint)>([("ai", "Claude"), ("sys", "CPU"), ("cc", "Denetim"), ("bell", "#bell")]);+ void Next()+ {+ if (tiles.Count == 0)+ {+ SnapshotEdges(folder);+ return;+ }+ var (name, hint) = tiles.Dequeue();+ var button = hint == "#bell" ? NotificationsButton : FindVisualChildren<System.Windows.Controls.Primitives.ButtonBase>(WidgetHost)+ .FirstOrDefault(b => FindVisualChildren<TextBlock>(b).Any(t => t.Text.StartsWith(hint, StringComparison.Ordinal)));+ button?.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));+ var wait = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1200) };+ wait.Tick += (_, _) =>+ {+ wait.Stop();+ var sheet = Application.Current.Windows.OfType<EdgePanel>().FirstOrDefault(w => w.IsVisible);+ if (sheet?.Content is FrameworkElement content)+ {+ var width = sheet.ActualWidth;+ var height = sheet.ActualHeight;+ var visual = new DrawingVisual();+ using (var context = visual.RenderOpen())+ {+ context.DrawRectangle(new SolidColorBrush(Color.FromRgb(0x5A, 0x7A, 0x9A)), null, new Rect(0, 0, width, height + 70));+ context.DrawRectangle(new VisualBrush(content) { Stretch = Stretch.None, AlignmentX = AlignmentX.Left, AlignmentY = AlignmentY.Top }, null, new Rect(0, 0, width, height));+ var dockLeft = Left + DockSurface.TranslatePoint(new Point(0, 0), this).X - sheet.Left;+ context.DrawRectangle(new VisualBrush(DockSurface) { Stretch = Stretch.None, AlignmentX = AlignmentX.Left, AlignmentY = AlignmentY.Top, ViewboxUnits = BrushMappingMode.Absolute, Viewbox = new Rect(-dockLeft, 0, width, 70) },+ null, new Rect(0, height - EdgePanel.SeamDepth, width, 70));+ }+ var bitmap = new System.Windows.Media.Imaging.RenderTargetBitmap((int)(width * 2), (int)((height + 70) * 2), 192, 192, PixelFormats.Pbgra32);+ bitmap.Render(visual);+ var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();+ encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmap));+ using var file = System.IO.File.Create(System.IO.Path.Combine(folder, $"sheet-{name}.png"));+ encoder.Save(file);+ // What the screen really shows at the seam (device pixels), sheet foot and dock together.+ if (PresentationSource.FromVisual(sheet) is System.Windows.Interop.HwndSource sheetSource+ && SnapNative.GetWindowRect(sheetSource.Handle, out var bounds))+ {+ var grab = SnapNative.Grab(bounds.Left - 40, bounds.Bottom - 140, bounds.Right - bounds.Left + 80, 220);+ var screenEncoder = new System.Windows.Media.Imaging.PngBitmapEncoder();+ screenEncoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(grab));+ using var screenFile = System.IO.File.Create(System.IO.Path.Combine(folder, $"screen-{name}.png"));+ screenEncoder.Save(screenFile);+ }+ sheet.Close(animated: false);+ }+ else System.IO.File.WriteAllText(System.IO.Path.Combine(folder, $"sheet-{name}.txt"), button is null ? "tile not found" : "no sheet open");+ Next();+ };+ wait.Start();+ }+ Next();+ }++ /// <summary>Moves the dock to the top, left and right edges in turn (nothing saved), opens the bell's list on+ /// each and records the real screen, then puts the dock back and quits.</summary>+ private void SnapshotEdges(string folder)+ {+ var edges = new Queue<Models.DockEdge>([Models.DockEdge.Top, Models.DockEdge.Left, Models.DockEdge.Right]);+ void After(int milliseconds, Action action)+ {+ var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(milliseconds) };+ timer.Tick += (_, _) =>+ {+ timer.Stop();+ action();+ };+ timer.Start();+ }+ void Next()+ {+ if (edges.Count == 0)+ {+ _edgeOverride = null;+ ApplyDockEdge();+ After(800, Close);+ return;+ }+ var edge = edges.Dequeue();+ _edgeOverride = edge;+ ApplyDockEdge();+ After(1500, () =>+ {+ NotificationsButton.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));+ After(1300, () =>+ {+ try+ {+ if (PresentationSource.FromVisual(this) is System.Windows.Interop.HwndSource dockSource && SnapNative.GetWindowRect(dockSource.Handle, out var dock))+ {+ var box = dock;+ var sheet = Application.Current.Windows.OfType<EdgePanel>().FirstOrDefault(w => w.IsVisible);+ if (sheet is not null && PresentationSource.FromVisual(sheet) is System.Windows.Interop.HwndSource sheetSource && SnapNative.GetWindowRect(sheetSource.Handle, out var panel))+ {+ box.Left = Math.Min(box.Left, panel.Left);+ box.Top = Math.Min(box.Top, panel.Top);+ box.Right = Math.Max(box.Right, panel.Right);+ box.Bottom = Math.Max(box.Bottom, panel.Bottom);+ }+ var grab = SnapNative.Grab(box.Left, box.Top, box.Right - box.Left, box.Bottom - box.Top);+ var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();+ encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(grab));+ using var file = System.IO.File.Create(System.IO.Path.Combine(folder, $"edge-{edge}.png"));+ encoder.Save(file);+ sheet?.Close(animated: false);+ }+ }+ catch (Exception ex)+ {+ System.IO.File.WriteAllText(System.IO.Path.Combine(folder, $"edge-{edge}.txt"), ex.ToString());+ }+ Next();+ });+ });+ }+ Next();+ }++ /// <summary>+ /// Plays the user's sequence without touching the mouse or saving anything: bottom, the bell on the bottom, the+ /// left edge with the Downloads tile magnified, the bell on the right edge, then back to the bottom. Each step is+ /// a real screen grab of the dock (and the panel), plus the dock's measurements.+ /// </summary>+ private void SnapshotEdgeCycle(string folder)+ {+ System.IO.Directory.CreateDirectory(folder);+ var log = new System.Text.StringBuilder();+ var steps = new Queue<(int Wait, Action Act)>();+ void Grab(string name)+ {+ UpdateLayout();+ log.AppendLine($"{name}: edge={Edge} placement={CurrentPlacement} window={ActualWidth:0}x{ActualHeight:0} area={_dockArea} surface={DockSurface.ActualWidth:0.0}x{DockSurface.ActualHeight:0.0} base={_baseSurfaceWidth:0.0} rowDesired={DockRow.DesiredSize.Width:0.0} rowActual={DockRow.ActualWidth:0.0} widgets={WidgetHost.ActualWidth:0.0} scale={_dockWidgetScale:0.00}");+ if (PresentationSource.FromVisual(this) is not System.Windows.Interop.HwndSource dockSource || !SnapNative.GetWindowRect(dockSource.Handle, out var box)) return;+ var sheet = Application.Current.Windows.OfType<EdgePanel>().FirstOrDefault(w => w.IsVisible);+ if (sheet is not null && PresentationSource.FromVisual(sheet) is System.Windows.Interop.HwndSource sheetSource && SnapNative.GetWindowRect(sheetSource.Handle, out var panel))+ {+ log.AppendLine($" panel {panel.Left},{panel.Top} {panel.Right - panel.Left}x{panel.Bottom - panel.Top}");+ box.Left = Math.Min(box.Left, panel.Left);+ box.Top = Math.Min(box.Top, panel.Top);+ box.Right = Math.Max(box.Right, panel.Right);+ box.Bottom = Math.Max(box.Bottom, panel.Bottom);+ }+ var grab = SnapNative.Grab(box.Left, box.Top, box.Right - box.Left, box.Bottom - box.Top);+ var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();+ encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(grab));+ using var file = System.IO.File.Create(System.IO.Path.Combine(folder, $"cycle-{name}.png"));+ encoder.Save(file);+ }+ void MoveTo(Models.DockEdge? edge)+ {+ _edgeOverride = edge;+ Preferences_Changed(null, EventArgs.Empty); // the same path as choosing it in the menu or the settings+ _autoHideController?.EvaluateState();+ }+ void Bell() => NotificationsButton.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));+ void CloseSheets()+ {+ foreach (var sheet in Application.Current.Windows.OfType<EdgePanel>().Where(w => w.IsVisible).ToList()) sheet.Close(animated: false);+ }+ void Magnify(Button tile)+ {+ var at = tile.TranslatePoint(new Point(tile.ActualWidth / 2, tile.ActualHeight / 2), DockContents);+ MagnifyAt(at.X);+ }+ void Add(int wait, Action act) => steps.Enqueue((wait, act));+ _holdDockUp = true;+ Add(100, () => _autoHideController?.EvaluateState());+ Add(5000, () => Grab("1-bottom"));+ Add(300, Bell);+ Add(1400, () => { Grab("2-bottom-bell"); CloseSheets(); });+ Add(300, () => MoveTo(Models.DockEdge.Left));+ Add(1800, () => { Grab("3-left"); Magnify(DownloadsButton); });+ Add(300, () => { Grab("4-left-magnified"); ResetMagnification(); });+ Add(400, () => MoveTo(Models.DockEdge.Right));+ Add(1800, () => { Grab("5-right"); Bell(); });+ Add(1400, () => { Grab("6-right-bell"); CloseSheets(); });+ Add(300, () => MoveTo(Models.DockEdge.Top));+ Add(1800, () => { Grab("7-top"); Bell(); });+ Add(1400, () => { Grab("8-top-bell"); CloseSheets(); });+ Add(300, () => MoveTo(null));+ Add(2500, () => Grab("9-bottom-again"));+ Add(300, () => Magnify(TrashButton));+ Add(300, () => { Grab("10-bottom-magnified"); ResetMagnification(); });+ // The classic layout: widgets in the top bar, cards grow down out of it.+ void TopTile(string hint)+ {+ if (_topBar is null) return;+ var tile = FindVisualChildren<System.Windows.Controls.Primitives.ButtonBase>(_topBar)+ .FirstOrDefault(b => FindVisualChildren<TextBlock>(b).Any(t => t.Text.StartsWith(hint, StringComparison.Ordinal)));+ log.AppendLine($"top tile {hint}: {(tile is null ? "not found" : "found")}");+ tile?.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));+ }+ void GrabTop(string name)+ {+ if (_topBar is null || !SnapNative.GetWindowRect(_topBar.Handle, out var box)) return;+ var sheet = Application.Current.Windows.OfType<EdgePanel>().FirstOrDefault(w => w.IsVisible);+ if (sheet is not null && PresentationSource.FromVisual(sheet) is System.Windows.Interop.HwndSource sheetSource && SnapNative.GetWindowRect(sheetSource.Handle, out var panel))+ {+ log.AppendLine($" {name} panel {panel.Left},{panel.Top} {panel.Right - panel.Left}x{panel.Bottom - panel.Top}");+ box.Left = Math.Min(box.Left, panel.Left);+ box.Right = Math.Max(box.Right, panel.Right);+ box.Bottom = Math.Max(box.Bottom, panel.Bottom);+ }+ else log.AppendLine($" {name}: no panel");+ var grab = SnapNative.Grab(box.Left, box.Top, box.Right - box.Left, box.Bottom - box.Top);+ var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();+ encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(grab));+ using var file = System.IO.File.Create(System.IO.Path.Combine(folder, $"cycle-{name}.png"));+ encoder.Save(file);+ }+ Add(300, () =>+ {+ _placementOverride = Models.WidgetPlacement.TopBar;+ ApplyWidgetPlacement();+ if (_topBar is not null) { _topBar.ForceVisible = true; _topBar.Update(); }+ });+ Add(1500, () => TopTile("Denetim"));+ Add(1400, () => { GrabTop("12-topbar-cc"); CloseSheets(); });+ Add(600, () => TopTile("Claude"));+ Add(1400, () => { GrabTop("13-topbar-ai"); CloseSheets(); foreach (var p in FindVisualChildren<System.Windows.Controls.Primitives.Popup>(_topBar!)) p.IsOpen = false; });+ Add(300, () =>+ {+ if (_topBar is not null) { _topBar.ForceVisible = false; _topBar.Update(); }+ _placementOverride = null;+ ApplyWidgetPlacement();+ });+ Add(300, () => OpenSettings_Click(this, new RoutedEventArgs()));+ Add(800, () =>+ {+ if (_settingsWindow is not null)+ foreach (var scroller in FindVisualChildren<ScrollViewer>(_settingsWindow).Where(v => v.IsVisible)) scroller.ScrollToVerticalOffset(0);+ });+ Add(700, () =>+ {+ if (_settingsWindow?.Content is FrameworkElement page && PresentationSource.FromVisual(_settingsWindow) is System.Windows.Interop.HwndSource settingsSource+ && SnapNative.GetWindowRect(settingsSource.Handle, out var r))+ {+ var grab = SnapNative.Grab(r.Left, r.Top, r.Right - r.Left, r.Bottom - r.Top);+ var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();+ encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(grab));+ using var file = System.IO.File.Create(System.IO.Path.Combine(folder, "cycle-11-settings.png"));+ encoder.Save(file);+ }+ _settingsWindow?.Close();+ });+ Add(500, () => { System.IO.File.WriteAllText(System.IO.Path.Combine(folder, "cycle.txt"), log.ToString()); Close(); });+ void Next()+ {+ if (steps.Count == 0) return;+ var (wait, act) = steps.Dequeue();+ var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(wait) };+ timer.Tick += (_, _) =>+ {+ timer.Stop();+ try { act(); }+ catch (Exception ex) { log.AppendLine("ERROR " + ex); }+ Next();+ };+ timer.Start();+ }+ Next();+ }++ private static class SnapNative+ {+ [StructLayout(LayoutKind.Sequential)] public struct Rect { public int Left, Top, Right, Bottom; }+ [DllImport("user32.dll")] public static extern bool GetWindowRect(nint window, out Rect rect);+ [DllImport("user32.dll")] private static extern nint GetDC(nint window);+ [DllImport("user32.dll")] private static extern int ReleaseDC(nint window, nint dc);+ [DllImport("gdi32.dll")] private static extern nint CreateCompatibleDC(nint dc);+ [DllImport("gdi32.dll")] private static extern nint CreateCompatibleBitmap(nint dc, int width, int height);+ [DllImport("gdi32.dll")] private static extern nint SelectObject(nint dc, nint item);+ [DllImport("gdi32.dll")] private static extern bool BitBlt(nint target, int x, int y, int width, int height, nint source, int sx, int sy, uint op);+ [DllImport("gdi32.dll")] private static extern bool DeleteObject(nint item);+ [DllImport("gdi32.dll")] private static extern bool DeleteDC(nint dc);++ /// <summary>Copies a part of the screen (device pixels).</summary>+ public static System.Windows.Media.Imaging.BitmapSource Grab(int x, int y, int width, int height)+ {+ var screen = GetDC(0);+ var memory = CreateCompatibleDC(screen);+ var bitmap = CreateCompatibleBitmap(screen, width, height);+ var old = SelectObject(memory, bitmap);+ BitBlt(memory, 0, 0, width, height, screen, x, y, 0x00CC0020 /* SRCCOPY */);+ SelectObject(memory, old);+ var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap, 0, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());+ DeleteObject(bitmap);+ DeleteDC(memory);+ ReleaseDC(0, screen);+ return source;+ }+ }++ private static IEnumerable<T> FindVisualChildren<T>(DependencyObject parent) where T : DependencyObject+ {+ for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)+ {+ var child = VisualTreeHelper.GetChild(parent, i);+ if (child is T match) yield return match;+ foreach (var nested in FindVisualChildren<T>(child)) yield return nested;+ }+ }+#endif++ /// <summary>The widgets' shrink, and on a top dock the turn undone so they read upright.</summary>+ private void ApplyWidgetHostTransform()+ {+ var matrix = Matrix.Identity;+ matrix.Scale(_dockWidgetScale, _dockWidgetScale);+ if (Edge == Models.DockEdge.Top) matrix.Append(Services.DockGeometry.FrameToScreen(Models.DockEdge.Top));+ WidgetHost.LayoutTransform = matrix.IsIdentity ? Transform.Identity : new MatrixTransform(matrix);+ }++ private Border CreateWidgetDivider()+ {+ var divider = new Border { Width = 1, Height = 22, Margin = new Thickness(4, 0, 4, 0), VerticalAlignment = VerticalAlignment.Center, Opacity = 0.7 };+ divider.SetResourceReference(Border.BackgroundProperty, "StrokeSubtle");+ return divider;+ }++ /// <summary>Widget tiles sit centred on the app icons (the row below the icons holds the running dots).</summary>+ private void AlignDockWidgets()+ {+ if (!WidgetsInDock) return;+ // Icons stand centred in the dock: so do the widget tiles and the divider.+ WidgetHost.VerticalAlignment = VerticalAlignment.Center;+ WidgetHost.Margin = new Thickness(WidgetHost.Margin.Left, 0, WidgetHost.Margin.Right, 0);+ if (_widgetDivider is not null) _widgetDivider.Margin = new Thickness(4, 0, 4, 0);+ }++ /// <summary>Under the widget bar when it is on screen, otherwise near the top edge.</summary>+ private double VolumeHudTop()+ {+ if (_topBar is not { IsVisible: true } bar || bar.ActualHeight <= 0) return 10;+ return bar.Top + bar.ActualHeight - 18 - SystemParameters.WorkArea.Top + 6;+ }++ /// <summary>+ /// First run with profiles: the existing layout becomes "Varsayılan" (new widgets start hidden+ /// there) and an "İş" profile shows the work-oriented widgets.+ /// </summary>+ private void MigrateWidgetProfiles()+ {+ var options = _preferences.Current.WidgetOptions;+ if (options.Profiles is { Count: > 0 }) return;+ var hidden = (options.Hidden ?? []).Concat(Models.WidgetIds.Added).Distinct().ToList();+ string[] work = [Models.WidgetIds.Clock, Models.WidgetIds.Focus, Models.WidgetIds.Todo, Models.WidgetIds.Folder, Models.WidgetIds.Search, Models.WidgetIds.System, Models.WidgetIds.AppVolume, Models.WidgetIds.Profile];+ string[] tools = [Models.WidgetIds.WorldClock, Models.WidgetIds.Colors, Models.WidgetIds.Tools, Models.WidgetIds.Weather, Models.WidgetIds.Profile];+ var migrated = options with+ {+ Hidden = hidden,+ Profiles =+ [+ new Models.WidgetProfile(Services.UiText.Get("ProfileDefault"), options.Order, hidden),+ new Models.WidgetProfile(Services.UiText.Get("ProfileWork"), work, Models.WidgetIds.All.Except(work).ToList()),+ new Models.WidgetProfile(Services.UiText.Get("ProfileTools"), tools, Models.WidgetIds.All.Except(tools).ToList())+ ],+ ActiveProfile = 0+ };+ SavePreferences(_preferences.Current with { Widgets = migrated });+ }++ /// <summary>+ /// Once per install: the notifications and Control Center tiles start hidden in every profile, since the dock+ /// bell and the Quick controls tile already open those panels. Showing them again later is kept.+ /// </summary>+ private void HideDuplicateTiles()+ {+ var options = _preferences.Current.WidgetOptions;+ if (options.LayoutRevision >= 1) return;+ List<string> Hide(IReadOnlyList<string>? hidden) => (hidden ?? []).Concat(Models.WidgetIds.Duplicates).Distinct().ToList();+ var profiles = options.EffectiveProfiles.Select(profile => profile with { Hidden = Hide(profile.Hidden) }).ToList();+ SavePreferences(_preferences.Current with+ {+ Widgets = options with { Hidden = Hide(options.Hidden), Profiles = profiles, LayoutRevision = 1 }+ });+ }++ /// <summary>+ /// Once per install: the Quick controls tile (Wi-Fi, Bluetooth, volume) makes way for the Control Center tile at+ /// the end of the row, which holds all of them plus brightness and opens like the bell's list.+ /// </summary>+ private void PreferControlCenterTile()+ {+ var options = _preferences.Current.WidgetOptions;+ if (options.LayoutRevision >= 2) return;+ const string quick = Models.WidgetIds.QuickControls, center = Models.WidgetIds.ControlCenter;+ List<string> Hidden(IReadOnlyList<string>? hidden) => (hidden ?? []).Where(id => id != center).Append(quick).Distinct().ToList();+ List<string> Order(IReadOnlyList<string>? order) => (order is { Count: > 0 } ? order : Models.WidgetIds.All).Where(id => id != center).Append(center).ToList();+ var profiles = options.EffectiveProfiles.Select(profile => profile with { Order = Order(profile.Order), Hidden = Hidden(profile.Hidden) }).ToList();+ SavePreferences(_preferences.Current with+ {+ Widgets = options with { Order = Order(options.EffectiveOrder), Hidden = Hidden(options.Hidden), Profiles = profiles, LayoutRevision = 2 }+ });+ }++ /// <summary>+ /// Once per install: the bell leaves the dock's left end and stands as a tile in the corner next to the battery+ /// (shown in every profile). Hiding it again later is kept.+ /// </summary>+ /// <summary>The dock's own bell shows only while the bell tile is hidden (so there is always one, never two).</summary>+ private void ApplyDockBell() =>+ NotificationsButton.Visibility = _preferences.Current.WidgetOptions.IsVisible(Models.WidgetIds.Notifications) ? Visibility.Collapsed : Visibility.Visible;++ private void BellToCorner()+ {+ var options = _preferences.Current.WidgetOptions;+ if (options.LayoutRevision >= 3) return;+ List<string> Shown(IReadOnlyList<string>? hidden) => (hidden ?? []).Except(Models.WidgetIds.Corner).ToList();+ var profiles = options.EffectiveProfiles.Select(profile => profile with { Hidden = Shown(profile.Hidden) }).ToList();+ SavePreferences(_preferences.Current with+ {+ Widgets = options with { Hidden = Shown(options.Hidden), Profiles = profiles, LayoutRevision = 3 }+ });+ }++ /// <summary>Once: the second batch of widgets starts hidden in every profile (they wait in the add list).</summary>+ private void SecondBatchHidden()+ {+ var options = _preferences.Current.WidgetOptions;+ if (options.LayoutRevision >= 4) return;+ List<string> Hide(IReadOnlyList<string>? hidden) => (hidden ?? []).Concat(Models.WidgetIds.SecondBatch).Distinct().ToList();+ var profiles = options.EffectiveProfiles.Select(profile => profile with { Hidden = Hide(profile.Hidden) }).ToList();+ SavePreferences(_preferences.Current with+ {+ Widgets = options with { Hidden = Hide(options.Hidden), Profiles = profiles, LayoutRevision = 4 }+ });+ }++ /// <summary>Preset profile names offered for a new profile or a rename.</summary>+ private static readonly string[] ProfileNames = ["ProfileWork", "ProfileCode", "ProfileHome", "ProfileFocus", "ProfileGame", "ProfileSchool", "ProfileCreative", "ProfileTools", "ProfileDefault"];++ /// <summary>The profile tile's menu: switch profile, make a new one, rename or remove the active one.</summary>+ private void ShowProfilesMenu(FrameworkElement anchor)+ {+ var options = _preferences.Current.WidgetOptions;+ var profiles = options.EffectiveProfiles;+ var active = options.EffectiveActiveProfile;+ var menu = new ContextMenu { PlacementTarget = anchor, Placement = Services.DockGeometry.Inward };+ menu.Opened += DockContextMenu_Opened;+ menu.Closed += DockContextMenu_Closed;+ for (var i = 0; i < profiles.Count; i++)+ {+ var index = i;+ var item = Item(profiles[i].Name, null, i == active);+ if (i < 9) item.InputGestureText = "Ctrl+Alt+Shift+" + (i + 1);+ item.Click += (_, _) =>+ {+ var current = _preferences.Current.WidgetOptions;+ if (index != current.EffectiveActiveProfile) SaveWidgetOptions(current.SwitchProfile(index));+ Widgets.Ui.ShowHud("IconLayout", current.EffectiveProfiles[index].Name);+ };+ menu.Items.Add(item);+ }+ menu.Items.Add(new Separator());+ var create = Item(Services.UiText.Get("ProfileNewMenu"), "IconPlus");+ var taken = profiles.Select(p => p.Name).ToHashSet(StringComparer.CurrentCultureIgnoreCase);+ foreach (var key in ProfileNames)+ {+ var name = Services.UiText.Get(key);+ if (taken.Contains(name)) continue;+ var item = Item(name, null);+ item.Click += (_, _) =>+ {+ SaveWidgetOptions(_preferences.Current.WidgetOptions.AddProfile(name));+ Widgets.Ui.ShowHud("IconLayout", Services.UiText.Format("ProfileCreated", name));+ };+ create.Items.Add(item);+ }+ var numbered = Item(Services.UiText.Format("ProfileNew", profiles.Count + 1), null);+ numbered.Click += (_, _) => SaveWidgetOptions(_preferences.Current.WidgetOptions.AddProfile(Services.UiText.Format("ProfileNew", profiles.Count + 1)));+ create.Items.Add(numbered);+ menu.Items.Add(create);+ var rename = Item(Services.UiText.Get("ProfileRename"), "IconEdit");+ foreach (var key in ProfileNames)+ {+ var name = Services.UiText.Get(key);+ var item = Item(name, null, profiles[active].Name == name);+ item.IsEnabled = !taken.Contains(name) || profiles[active].Name == name;+ item.Click += (_, _) => SaveWidgetOptions(_preferences.Current.WidgetOptions.RenameProfile(active, name));+ rename.Items.Add(item);+ }+ menu.Items.Add(rename);+ var remove = Item(Services.UiText.Format("ProfileRemoveNamed", profiles[active].Name), "IconClose");+ remove.IsEnabled = profiles.Count > 1;+ remove.Click += (_, _) => SaveWidgetOptions(_preferences.Current.WidgetOptions.RemoveProfile(active));+ menu.Items.Add(remove);+ menu.Items.Add(new Separator());+ var edit = Item(Services.UiText.Get(_widgetBar.IsEditing ? "MenuEditDone" : "ProfileEditWidgets"), "IconLayout");+ edit.Click += (_, _) => _widgetBar.SetEditing(!_widgetBar.IsEditing);+ menu.Items.Add(edit);+ menu.IsOpen = true;+ }++ private void ShowProfileMenu(int index, FrameworkElement anchor)+ {+ var options = _preferences.Current.WidgetOptions;+ var menu = new ContextMenu { PlacementTarget = anchor, Placement = PlacementMode.Bottom };+ menu.Opened += DockContextMenu_Opened;+ menu.Closed += DockContextMenu_Closed;+ var rename = Item(Services.UiText.Get("ProfileRename"), "IconEdit");+ foreach (var key in new[] { "ProfileDefault", "ProfileWork", "ProfileHome", "ProfileFocus", "ProfileGame", "ProfileSchool", "ProfileCreative", "ProfileTools" })+ {+ var name = Services.UiText.Get(key);+ var item = Item(name, null, options.EffectiveProfiles[index].Name == name);+ item.Click += (_, _) => SaveWidgetOptions(_preferences.Current.WidgetOptions.RenameProfile(index, name));+ rename.Items.Add(item);+ }+ menu.Items.Add(rename);+ var remove = Item(Services.UiText.Get("ProfileRemove"), "IconClose");+ remove.IsEnabled = options.EffectiveProfiles.Count > 1;+ remove.Click += (_, _) => SaveWidgetOptions(_preferences.Current.WidgetOptions.RemoveProfile(index));+ menu.Items.Add(remove);+ menu.Items.Add(new Separator());+ var edit = Item(Services.UiText.Get(_widgetBar.IsEditing ? "MenuEditDone" : "MenuEditDock"), "IconLayout");+ edit.Click += (_, _) => _widgetBar.SetEditing(!_widgetBar.IsEditing);+ menu.Items.Add(edit);+ menu.IsOpen = true;+ }++ private void UpdateTopBarContent()+ {+ if (_topBar is null) return;+ var onTop = !WidgetsInDock;+ _topBar.ForceVisible = onTop && _widgetBar.IsEditing;+ if (onTop && _widgetBar.IsEditing) _topBar.ShowTabs(true);+ else if (!_topBar.IsMouseOver) _topBar.ShowTabs(false);+ _topBar.SetHasContent(onTop && (_widgetBar.HasVisibleWidgets || _widgetBar.IsEditing));+ _topBar.Update();+ }++ private void ScheduleDesktopCheck()+ {+ if (_desktopCheck is null) return;+ _desktopCheck.Stop();+ _desktopCheck.Start();+ }++ /// <summary>Clean desktop = no visible, non-minimized app window on the primary monitor.</summary>+ private void RefreshDesktopClean()+ {+ UpdateDeskCovers();+ if (_topBar is null) return;+ var windows = _windowTracker?.Snapshot;+ if (windows is null)+ {+ _topBar.SetDesktopClean(false);+ return;+ }+ _topBar.SetDesktopClean(ComputeDesktopClean());+ }++ private bool ComputeDesktopClean()+ {+ if (_windowTracker?.Snapshot is not { } windows) return false;+ var primary = TopNative.MonitorFromPoint(new TopNative.Point(), 1 /* MONITOR_DEFAULTTOPRIMARY */);+ return !windows.Any(window => IsOpenOn(window.Handle, primary));+ }++ private static bool IsOpenOn(nint window, nint monitor) =>+ TopNative.IsWindow(window) && TopNative.IsWindowVisible(window) && !TopNative.IsIconic(window)+ && !IsCloakedWindow(window)+ && TopNative.MonitorFromWindow(window, 2 /* MONITOR_DEFAULTTONEAREST */) == monitor;++ private static bool IsCloakedWindow(nint window) =>+ TopNative.DwmGetWindowAttribute(window, 14 /* DWMWA_CLOAKED */, out var cloaked, sizeof(int)) == 0 && cloaked != 0;++ private void DisposeTopBar()+ {+ if (_minimizeHook != 0)+ {+ TopNative.UnhookWinEvent(_minimizeHook);+ _minimizeHook = 0;+ }+ _desktopCheck?.Stop();+ _trashTimer?.Stop();+ _volumeWatcher?.Dispose();+ _volumeWatcher = null;+ DisposeHud();+ _volumeHud?.Close();+ _volumeHud = null;+ if (_topBar is not null)+ {+ _topBar.Bar = null;+ _topBar.Close();+ _topBar = null;+ }+ }++ private static class TopNative+ {+ public delegate void WinEventProc(nint hook, uint eventType, nint window, int objectId, int childId, uint thread, uint time);++ [StructLayout(LayoutKind.Sequential)]+ public struct Point { public int X, Y; }++ [DllImport("user32.dll")] public static extern nint SetWinEventHook(uint eventMin, uint eventMax, nint module, WinEventProc callback, uint processId, uint threadId, uint flags);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnhookWinEvent(nint hook);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWindow(nint window);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWindowVisible(nint window);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsIconic(nint window);+ [DllImport("user32.dll")] public static extern nint MonitorFromWindow(nint window, uint flags);+ [DllImport("user32.dll")] public static extern nint MonitorFromPoint(Point point, uint flags);+ [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(nint window, int attribute, out int value, int size);+ }+}+diff --git a/MainWindow.xaml b/MainWindow.xamlnew file mode 100644index 0000000..be9fb99--- /dev/null+++ b/MainWindow.xaml@@ -0,0 +1,402 @@+<Window x:Class="QiDock.MainWindow"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="clr-namespace:QiDock.Services"+ xmlns:ctl="clr-namespace:QiDock"+ Title="QiDock"+ Width="360"+ Height="{StaticResource DockWindowHeight}"+ MinHeight="0"+ FontFamily="{StaticResource InterfaceFont}"+ UseLayoutRounding="True" SnapsToDevicePixels="True"+ WindowStyle="None"+ ResizeMode="NoResize"+ AllowsTransparency="True"+ Background="Transparent"+ ShowInTaskbar="False"+ Topmost="True"+ WindowStartupLocation="Manual"+ Closing="Window_Closing"+ SourceInitialized="Window_SourceInitialized"+ Closed="Window_Closed">+ <Window.Resources>+ <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />+ <ContextMenu x:Key="AppContextMenu" x:Shared="False" StaysOpen="True" Opened="DockContextMenu_Opened" Closed="DockContextMenu_Closed">+ <Separator Tag="JumpListCommands" Visibility="Collapsed" />+ <MenuItem Header="{local:Loc OpenApplication}" Icon="{StaticResource IconOpen}" Tag="ActivateDockApp" Click="DockAppContextMenu_Click" />+ <MenuItem Header="{local:Loc Pin}" Icon="{StaticResource IconPin}" Tag="PinDockApp" Visibility="Collapsed" Click="PinDockApp_Click" />+ <MenuItem Header="{local:Loc Unpin}" Icon="{StaticResource IconUnpin}" Tag="UnpinDockApp" Visibility="Collapsed" Click="UnpinDockApp_Click" />+ <Separator Tag="RunningCommandsDivider" />+ <MenuItem Header="{local:Loc CloseApplication}" Icon="{StaticResource IconClose}" Tag="CloseDockApp" Click="CloseDockApp_Click" />+ <MenuItem Header="{local:Loc Terminate}" Icon="{StaticResource IconTerminate}" Style="{StaticResource DestructiveMenuItem}" Tag="TerminateDockApp" Click="TerminateDockApp_Click" />+ </ContextMenu>+ <ContextMenu x:Key="DockContextMenu" x:Shared="False" Opened="DockContextMenu_Opened" Closed="DockContextMenu_Closed">+ <MenuItem Header="{local:Loc Settings}" Icon="{StaticResource IconSettings}" Click="OpenSettings_Click" />+ <Separator />+ <MenuItem Header="{local:Loc Exit}" Icon="{StaticResource IconExit}" Click="ExitQiDock_Click" />+ </ContextMenu>++ <!-- Keyboard focus only (Tab, arrows): a ring around the icon. A mouse click leaves no box behind. -->+ <Style x:Key="DockFocusRing">+ <Setter Property="Control.Template">+ <Setter.Value>+ <ControlTemplate>+ <Border Width="{DynamicResource DockTileSize}" Height="{DynamicResource DockTileSize}" Margin="0,-2,0,0"+ HorizontalAlignment="Center" VerticalAlignment="Top" CornerRadius="{DynamicResource DockGlassRadius}"+ BorderThickness="2" BorderBrush="#CC0A84FF" />+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <Style x:Key="DockButton" TargetType="Button">+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="FocusVisualStyle" Value="{StaticResource DockFocusRing}" />+ <Setter Property="BorderThickness" Value="0" />+ <Setter Property="Width" Value="{DynamicResource DockCellSize}" />+ <Setter Property="Height" Value="{DynamicResource DockCellHeight}" />+ <Setter Property="Margin" Value="0" />+ <Setter Property="Padding" Value="0" />+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="RenderTransformOrigin" Value="0.5,0.95" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="Button">+ <Border x:Name="Surface" Background="{TemplateBinding Background}"+ BorderBrush="Transparent" BorderThickness="0"+ CornerRadius="{StaticResource ControlRadius}" Padding="{TemplateBinding Padding}">+ <Grid>+ <!-- Icon centred in the cell (equal room above and below), running dot in the room under it. -->+ <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />+ <Ellipse x:Name="ActiveIndicator" Height="4" Width="4" Margin="0,0,0,1"+ Fill="{DynamicResource IndicatorBrush}" VerticalAlignment="Bottom"+ HorizontalAlignment="Center" Visibility="Collapsed" />+ </Grid>+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Surface" Property="Background" Value="Transparent" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter TargetName="Surface" Property="Opacity" Value="0.48" />+ </Trigger>+ <DataTrigger Binding="{Binding IsRunning}" Value="True">+ <Setter TargetName="ActiveIndicator" Property="Visibility" Value="Visible" />+ <Setter TargetName="ActiveIndicator" Property="Opacity" Value="0.55" />+ </DataTrigger>+ <DataTrigger Binding="{Binding IsForeground}" Value="True">+ <Setter TargetName="ActiveIndicator" Property="Visibility" Value="Visible" />+ <Setter TargetName="ActiveIndicator" Property="Opacity" Value="1.0" />+ <Setter TargetName="ActiveIndicator" Property="Width" Value="5" />+ <Setter TargetName="ActiveIndicator" Property="Height" Value="5" />+ <Setter TargetName="ActiveIndicator" Property="Fill" Value="{DynamicResource IndicatorForegroundBrush}" />+ </DataTrigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <Style x:Key="PreviewCloseButton" TargetType="Button">+ <Setter Property="Width" Value="28" />+ <Setter Property="Height" Value="28" />+ <Setter Property="Padding" Value="0" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimary}" />+ <Setter Property="Background" Value="{DynamicResource SurfaceSelected}" />+ <Setter Property="BorderThickness" Value="0" />+ <Setter Property="Cursor" Value="Hand" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="Button">+ <Border x:Name="Surface" Background="{TemplateBinding Background}" CornerRadius="7">+ <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Surface" Property="Background" Value="{DynamicResource SurfaceDanger}" />+ </Trigger>+ <Trigger Property="IsPressed" Value="True">+ <Setter TargetName="Surface" Property="Background" Value="{DynamicResource SurfaceDanger}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <DataTemplate x:Key="DockAppIconTemplate">+ <Button Style="{StaticResource DockButton}" Tag="{Binding ExecutablePath}"+ Click="DockApp_Click" AutomationProperties.Name="{Binding Name}"+ ToolTip="{Binding Name}" ToolTipService.InitialShowDelay="650" ToolTipService.Placement="Top" ToolTipService.VerticalOffset="-44" ContextMenu="{StaticResource AppContextMenu}"+ Loaded="DockAppButton_Loaded"+ PreviewMouseLeftButtonDown="DockApp_PreviewMouseLeftButtonDown"+ PreviewMouseLeftButtonUp="DockApp_PreviewMouseLeftButtonUp"+ PreviewMouseMove="DockApp_PreviewMouseMove"+ PreviewKeyDown="DockApp_PreviewKeyDown"+ AllowDrop="True"+ Drop="DockApp_Drop"+ DragOver="DockApp_DragOver"+ MouseEnter="DockApp_MouseEnter" MouseLeave="DockApp_MouseLeave">+ <!-- Each app sits on its own rounded glass tile; the whole tile magnifies. -->+ <Grid x:Name="IconTile" Width="{DynamicResource DockTileSize}" Height="{DynamicResource DockTileSize}"+ RenderTransformOrigin="0.5,1">+ <Grid.RenderTransform>+ <TransformGroup>+ <ScaleTransform ScaleX="1" ScaleY="1" />+ <TranslateTransform Y="0" />+ </TransformGroup>+ </Grid.RenderTransform>+ <Border Background="{DynamicResource DockTileFill}" BorderBrush="{DynamicResource DockTileStroke}"+ BorderThickness="1" CornerRadius="{DynamicResource DockTileRadius}" />+ <Image Source="{Binding Icon}" Stretch="Uniform" RenderOptions.BitmapScalingMode="HighQuality"+ Width="{DynamicResource DockIconSize}" Height="{DynamicResource DockIconSize}" />+ <Ellipse Width="10" Height="10" Fill="{DynamicResource NotificationBrush}" Margin="0,-2,-2,0"+ Stroke="{DynamicResource SurfacePopup}" StrokeThickness="1"+ HorizontalAlignment="Right" VerticalAlignment="Top"+ Visibility="{Binding HasNotification, Converter={StaticResource BooleanToVisibilityConverter}}" />+ </Grid>+ </Button>+ </DataTemplate>+ </Window.Resources>++ <Grid x:Name="DockHost" PreviewMouseRightButtonUp="DockHost_PreviewMouseRightButtonUp">+ <Grid.RowDefinitions>+ <RowDefinition Height="{Binding Source={StaticResource DockHeadroom}}" />+ <RowDefinition Height="*" />+ </Grid.RowDefinitions>+ <Border x:Name="DockHitBackground" Grid.Row="1" Background="#01000000" />+ <Border x:Name="DockSurface" Grid.Row="1" HorizontalAlignment="Stretch" Padding="{StaticResource DockPadding}"+ AllowDrop="True" DragOver="DockSurface_DragOver" Drop="DockSurface_Drop"+ Margin="{StaticResource DockInset}" VerticalAlignment="Bottom"+ Background="{DynamicResource DockMaterial}" BorderBrush="{DynamicResource DockBorderMaterial}" BorderThickness="1"+ CornerRadius="{StaticResource DockRadius}"+ MouseEnter="DockSurface_MouseEnter" MouseMove="DockSurface_MouseMove" MouseLeave="DockSurface_MouseLeave">+ <Border.RenderTransform>+ <TranslateTransform x:Name="DockSurfaceTranslate" Y="0" />+ </Border.RenderTransform>+ <Border.Effect>+ <DropShadowEffect Color="#000000" BlurRadius="20" ShadowDepth="3" Direction="270" Opacity="0.38" RenderingBias="Performance" />+ </Border.Effect>+ <ctl:UnclippedStackPanel x:Name="DockRow" Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center">+ <ctl:UnclippedStackPanel x:Name="DockContents" Orientation="Horizontal" HorizontalAlignment="Left"+ VerticalAlignment="Center">+ <Button x:Name="StartButton" Style="{StaticResource DockButton}" Click="StartButton_Click" PreviewMouseLeftButtonDown="StartButton_PreviewMouseLeftButtonDown"+ AutomationProperties.Name="{local:Loc Start}" ToolTip="{local:Loc Start}" ToolTipService.InitialShowDelay="650" ToolTipService.Placement="Top" ToolTipService.VerticalOffset="-44">+ <Grid Width="{DynamicResource DockTileSize}" Height="{DynamicResource DockTileSize}"+ RenderTransformOrigin="0.5,1">+ <Grid.RenderTransform>+ <TransformGroup>+ <ScaleTransform ScaleX="1" ScaleY="1" />+ <TranslateTransform Y="0" />+ </TransformGroup>+ </Grid.RenderTransform>+ <!-- Start: a dark tile with a silver four-pane logo. -->+ <Border Background="{DynamicResource StartTileFill}" BorderBrush="{DynamicResource DockTileStroke}"+ BorderThickness="1" CornerRadius="{DynamicResource DockTileRadius}" />+ <Path Width="{DynamicResource DockIconSize}" Height="{DynamicResource DockIconSize}" Stretch="Uniform" Margin="5"+ Fill="{DynamicResource StartLogoBrush}"+ Data="M0,0 H10 V10 H0 Z M12,0 H22 V10 H12 Z M0,12 H10 V22 H0 Z M12,12 H22 V22 H12 Z" />+ </Grid>+ </Button>+ <!-- AppGrid: every installed app as a full-screen grid (also Ctrl+Alt+Down). -->+ <Button x:Name="AppGridButton" Style="{StaticResource DockButton}" Click="AppGridButton_Click"+ AutomationProperties.Name="{local:Loc AppGridTitle}" ToolTip="{local:Loc AppGridTitle}" ToolTipService.InitialShowDelay="650" ToolTipService.Placement="Top" ToolTipService.VerticalOffset="-44">+ <Grid Width="{DynamicResource DockTileSize}" Height="{DynamicResource DockTileSize}" RenderTransformOrigin="0.5,1">+ <Grid.RenderTransform>+ <TransformGroup>+ <ScaleTransform ScaleX="1" ScaleY="1" />+ <TranslateTransform Y="0" />+ </TransformGroup>+ </Grid.RenderTransform>+ <Border BorderBrush="#40FFFFFF" BorderThickness="1" CornerRadius="{DynamicResource DockTileRadius}">+ <Border.Background>+ <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">+ <GradientStop Color="#FF8E8E99" Offset="0" />+ <GradientStop Color="#FF4B4B55" Offset="1" />+ </LinearGradientBrush>+ </Border.Background>+ </Border>+ <!-- A 3×3 grid of colored dots. -->+ <Viewbox Margin="5" Stretch="Uniform">+ <Canvas Width="24" Height="24">+ <Rectangle Canvas.Left="2" Canvas.Top="2" Width="5.5" Height="5.5" RadiusX="1.6" RadiusY="1.6" Fill="#FFFF5F57" />+ <Rectangle Canvas.Left="9.25" Canvas.Top="2" Width="5.5" Height="5.5" RadiusX="1.6" RadiusY="1.6" Fill="#FFFFBD2E" />+ <Rectangle Canvas.Left="16.5" Canvas.Top="2" Width="5.5" Height="5.5" RadiusX="1.6" RadiusY="1.6" Fill="#FF28C840" />+ <Rectangle Canvas.Left="2" Canvas.Top="9.25" Width="5.5" Height="5.5" RadiusX="1.6" RadiusY="1.6" Fill="#FF0A84FF" />+ <Rectangle Canvas.Left="9.25" Canvas.Top="9.25" Width="5.5" Height="5.5" RadiusX="1.6" RadiusY="1.6" Fill="#FFBF5AF2" />+ <Rectangle Canvas.Left="16.5" Canvas.Top="9.25" Width="5.5" Height="5.5" RadiusX="1.6" RadiusY="1.6" Fill="#FFFF375F" />+ <Rectangle Canvas.Left="2" Canvas.Top="16.5" Width="5.5" Height="5.5" RadiusX="1.6" RadiusY="1.6" Fill="#FF64D2FF" />+ <Rectangle Canvas.Left="9.25" Canvas.Top="16.5" Width="5.5" Height="5.5" RadiusX="1.6" RadiusY="1.6" Fill="#FFFFD60A" />+ <Rectangle Canvas.Left="16.5" Canvas.Top="16.5" Width="5.5" Height="5.5" RadiusX="1.6" RadiusY="1.6" Fill="#FF30D158" />+ </Canvas>+ </Viewbox>+ </Grid>+ </Button>+ <!-- Show desktop: windows step aside, the desktop stays clean (wallpaper and the widget bar). -->+ <Button x:Name="DesktopButton" Style="{StaticResource DockButton}" Click="DesktopButton_Click"+ AutomationProperties.Name="{local:Loc Desktop}" ToolTip="{local:Loc Desktop}" ToolTipService.InitialShowDelay="650" ToolTipService.Placement="Top" ToolTipService.VerticalOffset="-44">+ <Grid Width="{DynamicResource DockTileSize}" Height="{DynamicResource DockTileSize}" RenderTransformOrigin="0.5,1">+ <Grid.RenderTransform>+ <TransformGroup>+ <ScaleTransform ScaleX="1" ScaleY="1" />+ <TranslateTransform Y="0" />+ </TransformGroup>+ </Grid.RenderTransform>+ <Border BorderBrush="#33FFFFFF" BorderThickness="1" CornerRadius="{DynamicResource DockTileRadius}">+ <Border.Background>+ <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#FF6FD0FF" Offset="0" />+ <GradientStop Color="#FF1E6FE8" Offset="1" />+ </LinearGradientBrush>+ </Border.Background>+ </Border>+ <Viewbox Margin="8" Stretch="Uniform">+ <Canvas Width="24" Height="24">+ <Rectangle Canvas.Left="2" Canvas.Top="3.5" Width="20" Height="13.5" RadiusX="2.2" RadiusY="2.2" Fill="#F2FFFFFF" />+ <Rectangle Canvas.Left="3.6" Canvas.Top="5.1" Width="16.8" Height="10.3" RadiusX="1.2" RadiusY="1.2">+ <Rectangle.Fill>+ <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">+ <GradientStop Color="#FF7FC8FF" Offset="0" />+ <GradientStop Color="#FF2A5BD7" Offset="0.6" />+ <GradientStop Color="#FF7B4BE0" Offset="1" />+ </LinearGradientBrush>+ </Rectangle.Fill>+ </Rectangle>+ <Path Data="M9 17 L8.2 20.2 H15.8 L15 17 Z" Fill="#F2FFFFFF" />+ <Rectangle Canvas.Left="6.5" Canvas.Top="19.8" Width="11" Height="1.6" RadiusX="0.8" RadiusY="0.8" Fill="#F2FFFFFF" />+ </Canvas>+ </Viewbox>+ </Grid>+ </Button>+ <!-- Desktop files: the real desktop with its icons (windows step aside). -->+ <Button x:Name="FilesDesktopButton" Style="{StaticResource DockButton}" Click="FilesDesktopButton_Click"+ AutomationProperties.Name="{local:Loc DesktopFiles}" ToolTip="{local:Loc DesktopFiles}" ToolTipService.InitialShowDelay="650" ToolTipService.Placement="Top" ToolTipService.VerticalOffset="-44">+ <Grid Width="{DynamicResource DockTileSize}" Height="{DynamicResource DockTileSize}" RenderTransformOrigin="0.5,1">+ <Grid.RenderTransform>+ <TransformGroup>+ <ScaleTransform ScaleX="1" ScaleY="1" />+ <TranslateTransform Y="0" />+ </TransformGroup>+ </Grid.RenderTransform>+ <Border BorderBrush="#33FFFFFF" BorderThickness="1" CornerRadius="{DynamicResource DockTileRadius}">+ <Border.Background>+ <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#FFFFD772" Offset="0" />+ <GradientStop Color="#FFF39A1E" Offset="1" />+ </LinearGradientBrush>+ </Border.Background>+ </Border>+ <Viewbox Margin="9" Stretch="Uniform">+ <Canvas Width="24" Height="24">+ <Path Data="M3 6.5 A1.5 1.5 0 0 1 4.5 5 H9.2 L11 7 H19.5 A1.5 1.5 0 0 1 21 8.5 V18 A1.5 1.5 0 0 1 19.5 19.5 H4.5 A1.5 1.5 0 0 1 3 18 Z" Fill="#F2FFFFFF" />+ <Rectangle Canvas.Left="6.2" Canvas.Top="10.6" Width="3.2" Height="3.2" RadiusX="0.7" RadiusY="0.7" Fill="#FFF5A524" />+ <Rectangle Canvas.Left="10.4" Canvas.Top="10.6" Width="3.2" Height="3.2" RadiusX="0.7" RadiusY="0.7" Fill="#FF3F9BF5" />+ <Rectangle Canvas.Left="14.6" Canvas.Top="10.6" Width="3.2" Height="3.2" RadiusX="0.7" RadiusY="0.7" Fill="#FF34C759" />+ <Rectangle Canvas.Left="6.2" Canvas.Top="14.6" Width="3.2" Height="3.2" RadiusX="0.7" RadiusY="0.7" Fill="#FFFF6B5E" />+ <Rectangle Canvas.Left="10.4" Canvas.Top="14.6" Width="3.2" Height="3.2" RadiusX="0.7" RadiusY="0.7" Fill="#FFAF7BF0" />+ </Canvas>+ </Viewbox>+ </Grid>+ </Button>+ <!-- Notifications: a bell with a red badge for unread ones; click for the list. -->+ <Button x:Name="NotificationsButton" Style="{StaticResource DockButton}" Click="NotificationsButton_Click"+ AutomationProperties.Name="{local:Loc NotificationsTitle}" ToolTip="{local:Loc NotificationsTitle}" ToolTipService.InitialShowDelay="650" ToolTipService.Placement="Top" ToolTipService.VerticalOffset="-44">+ <Grid Width="{DynamicResource DockTileSize}" Height="{DynamicResource DockTileSize}" RenderTransformOrigin="0.5,1">+ <Grid.RenderTransform>+ <TransformGroup>+ <ScaleTransform ScaleX="1" ScaleY="1" />+ <TranslateTransform Y="0" />+ </TransformGroup>+ </Grid.RenderTransform>+ <Border BorderBrush="#33FFFFFF" BorderThickness="1" CornerRadius="{DynamicResource DockTileRadius}">+ <Border.Background>+ <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#FF4A4A50" Offset="0" />+ <GradientStop Color="#FF1F1F23" Offset="1" />+ </LinearGradientBrush>+ </Border.Background>+ </Border>+ <!-- The glyph scales with the tile (a fixed size plus margins would not fit and get clipped off-center). -->+ <Viewbox Margin="10" Stretch="Uniform" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">+ <Canvas Width="24" Height="24">+ <Path Data="{StaticResource IconBell}" Stroke="#F2FFFFFF" StrokeThickness="2" StrokeStartLineCap="Round" StrokeEndLineCap="Round" StrokeLineJoin="Round" />+ </Canvas>+ </Viewbox>+ <Border x:Name="NotificationsBadge" Visibility="Collapsed" MinWidth="19" Height="19" CornerRadius="9.5" Padding="5,0" Background="#FFFF3B30"+ BorderBrush="#F2FFFFFF" BorderThickness="1.5" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,-5,-5,0" IsHitTestVisible="False">+ <TextBlock x:Name="NotificationsBadgeText" FontSize="10.5" FontWeight="Bold" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,-1,0,0" />+ </Border>+ </Grid>+ </Button>+ <Border Width="1" Height="22" Background="{DynamicResource StrokeSubtle}" Margin="3,0,4,5" Visibility="Collapsed" />+ <ItemsControl x:Name="PinnedApps" ItemTemplate="{StaticResource DockAppIconTemplate}">+ <ItemsControl.ItemsPanel>+ <ItemsPanelTemplate><StackPanel Orientation="Horizontal" /></ItemsPanelTemplate>+ </ItemsControl.ItemsPanel>+ </ItemsControl>+ <Border x:Name="RunningAppsDivider" Width="1" Height="22" Background="{DynamicResource StrokeSubtle}" Margin="4,0,4,0" VerticalAlignment="Center" Visibility="Collapsed" Opacity="0.7" />+ <ItemsControl x:Name="RunningApps" ItemTemplate="{StaticResource DockAppIconTemplate}">+ <ItemsControl.ItemsPanel>+ <ItemsPanelTemplate><StackPanel Orientation="Horizontal" /></ItemsPanelTemplate>+ </ItemsControl.ItemsPanel>+ </ItemsControl>+ <Border x:Name="TrashDivider" Width="1" Height="22" Background="{DynamicResource StrokeSubtle}" Margin="4,0,4,0" VerticalAlignment="Center" Opacity="0.7" />+ <!-- Downloads: the newest downloads as a grid; drag them out or open the folder. -->+ <Button x:Name="DownloadsButton" Style="{StaticResource DockButton}" Click="DownloadsButton_Click"+ AutomationProperties.Name="{local:Loc DownloadsTitle}" ToolTip="{local:Loc DownloadsTitle}" ToolTipService.InitialShowDelay="650" ToolTipService.Placement="Top" ToolTipService.VerticalOffset="-44">+ <Grid Width="{DynamicResource DockTileSize}" Height="{DynamicResource DockTileSize}" RenderTransformOrigin="0.5,1">+ <Grid.RenderTransform>+ <TransformGroup>+ <ScaleTransform ScaleX="1" ScaleY="1" />+ <TranslateTransform Y="0" />+ </TransformGroup>+ </Grid.RenderTransform>+ <Border BorderBrush="#40FFFFFF" BorderThickness="1" CornerRadius="{DynamicResource DockTileRadius}">+ <Border.Background>+ <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">+ <GradientStop Color="#FF5AB4FF" Offset="0" />+ <GradientStop Color="#FF1A6BDB" Offset="1" />+ </LinearGradientBrush>+ </Border.Background>+ </Border>+ <Viewbox Margin="10" Stretch="Uniform" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">+ <Canvas Width="24" Height="24">+ <Path Data="{StaticResource IconArrowDown}" Stroke="#FFFFFFFF" StrokeThickness="2.4" StrokeStartLineCap="Round" StrokeEndLineCap="Round" StrokeLineJoin="Round" />+ </Canvas>+ </Viewbox>+ </Grid>+ </Button>+ <!-- Recycle Bin: open it, drop files on it to move them there, right-click to empty. -->+ <Button x:Name="TrashButton" Style="{StaticResource DockButton}" Click="TrashButton_Click" AllowDrop="True"+ DragOver="TrashButton_DragOver" Drop="TrashButton_Drop" PreviewMouseRightButtonUp="TrashButton_PreviewMouseRightButtonUp"+ AutomationProperties.Name="{local:Loc RecycleBin}" ToolTip="{local:Loc RecycleBin}" ToolTipService.InitialShowDelay="650" ToolTipService.Placement="Top" ToolTipService.VerticalOffset="-44">+ <Grid Width="{DynamicResource DockTileSize}" Height="{DynamicResource DockTileSize}" RenderTransformOrigin="0.5,1">+ <Grid.RenderTransform>+ <TransformGroup>+ <ScaleTransform ScaleX="1" ScaleY="1" />+ <TranslateTransform Y="0" />+ </TransformGroup>+ </Grid.RenderTransform>+ <Image x:Name="TrashIcon" Width="{DynamicResource DockTileSize}" Height="{DynamicResource DockTileSize}" RenderOptions.BitmapScalingMode="HighQuality" />+ </Grid>+ </Button>+ <TextBlock x:Name="StatusText" Foreground="{DynamicResource DangerText}" FontSize="{StaticResource TextSizeCaption}"+ MaxWidth="280" VerticalAlignment="Center" Margin="8,0" TextWrapping="Wrap">+ <TextBlock.Style>+ <Style TargetType="TextBlock">+ <Style.Triggers>+ <Trigger Property="Text" Value="">+ <Setter Property="Visibility" Value="Collapsed" />+ </Trigger>+ </Style.Triggers>+ </Style>+ </TextBlock.Style>+ </TextBlock>+ </ctl:UnclippedStackPanel>+ <ContentControl x:Name="WidgetHost" VerticalAlignment="Top" Margin="2,1,0,0" Focusable="False" Visibility="Collapsed" />+ </ctl:UnclippedStackPanel>+ </Border>+ <Border x:Name="DockEdgeTrigger" Grid.Row="1" VerticalAlignment="Bottom" Height="2" Background="#01000000"+ MouseEnter="DockEdgeTrigger_MouseEnter" MouseLeave="DockEdgeTrigger_MouseLeave" />+ </Grid>+</Window>diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.csnew file mode 100644index 0000000..b1f0495--- /dev/null+++ b/MainWindow.xaml.cs@@ -0,0 +1,2121 @@+using System.Collections.ObjectModel;+using System.ComponentModel;+using System.Diagnostics;+using System.IO;+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Interop;+using System.Windows.Media;+using System.Windows.Media.Animation;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;+using QiDock.Widgets;++namespace QiDock;++public partial class MainWindow : Window+{+ private const int GwlExStyle = -20;+ private const long WsExAppWindow = 0x00040000;+ private const long WsExToolWindow = 0x00000080;+ private const uint SwpNoSize = 0x0001;+ private const uint SwpNoMove = 0x0002;+ private const uint SwpNoZOrder = 0x0004;+ private const uint SwpNoActivate = 0x0010;+ private const uint SwpFrameChanged = 0x0020;+ private const int WmMouseActivate = 0x0021;+ private const int MaNoActivate = 3;++ private readonly ObservableCollection<DockApp> _pinnedApps = [];+ private readonly ObservableCollection<DockApp> _runningApps = [];+ private readonly HashSet<string> _exitingRunningPaths = new(StringComparer.OrdinalIgnoreCase);+ private readonly ApplicationPreferences _preferences = ((App)Application.Current).Preferences;+ private SettingsWindow? _settingsWindow;+ private readonly ApplicationJumpListService _jumpLists = new();+ private CancellationTokenSource? _jumpListLoad;+ private long? _jumpListSession;+ private readonly DispatcherTimer _previewCloseTimer;+ // The window preview opens only after the pointer rests on a tile this long (moving on to the next tile while a+ // preview is up switches at once).+ private readonly DispatcherTimer _previewOpenTimer;+ private Button? _previewPending;+ private readonly WindowThumbnailPreview _thumbnailPreview;+ private readonly GenieAnimator _genie = new();+ private DateTime _suppressPreviewsUntil;+ private readonly Dictionary<string, nint> _lastSelectedWindows = new(StringComparer.OrdinalIgnoreCase);+ private DockPosition _dockPosition = DockPosition.Left;+ private NativeWindowTracker? _windowTracker;+ private TaskbarReplacementSession? _replacementSession;+ private HwndSource? _source;+ private nint _foregroundWindow;+ private readonly List<FrameworkElement> _magnifiedIcons = [];+ private readonly List<Button> _magnifiedButtons = [];+ private double _baseSurfaceWidth = double.NaN;+ private double _tileSizeForHeight = 42;+ private ContextMenu? _openContextMenu;+ private bool _contextTargetWasForeground;+ private Size _dockArea;+ private bool _dockRefitQueued;+ private bool _panelOnTopBar; // the panel standing (or about to stand) on something grows out of the top bar, not the dock+ private System.Windows.Media.Effects.Effect? _dockShadow;+ private bool _holdDockUp; // debug sweeps: the dock stays up to be photographed+ private nint? _foregroundAtAppPress;+ private uint _taskbarCreatedMessage;+ private Point _dragStartPoint;+ private DockApp? _draggedApp;+ private DockAutoHideController? _autoHideController;+ private readonly WidgetBar _widgetBar = new();+ private double _iconSizeForHeight = 42;++ public MainWindow()+ {+ InitializeComponent();+ PinnedApps.ItemsSource = _pinnedApps;+ RunningApps.ItemsSource = _runningApps;+ _thumbnailPreview = new WindowThumbnailPreview((Style)FindResource("PreviewCloseButton"));+ _previewCloseTimer = new DispatcherTimer(DispatcherPriority.Background, Dispatcher)+ {+ Interval = TimeSpan.FromMilliseconds(500)+ };+ _previewCloseTimer.Tick += PreviewCloseTimer_Tick;+ _previewOpenTimer = new DispatcherTimer(DispatcherPriority.Normal, Dispatcher) { Interval = TimeSpan.FromMilliseconds(500) };+ _previewOpenTimer.Tick += (_, _) =>+ {+ _previewOpenTimer.Stop();+ if (_previewPending is { IsMouseOver: true } pending) ShowPreviewFor(pending);+ _previewPending = null;+ };+ _thumbnailPreview.PointerEntered += ThumbnailPreview_PointerEntered;+ _thumbnailPreview.PointerLeft += ThumbnailPreview_PointerLeft;+ _thumbnailPreview.PreviewClicked += ThumbnailPreview_PreviewClicked;+ _thumbnailPreview.CloseRequested += ThumbnailPreview_CloseRequested;+ _dockPosition = _preferences.Current.Position;+ _thumbnailPreview.AnimationsEnabled = _preferences.Current.AnimationsEnabled;+ ApplyMagnifyPreference();+ _preferences.Changed += Preferences_Changed;+ LoadPinnedApps(_preferences.Current.PinOrder);+ _widgetBar.LayoutInvalidated += WidgetBar_LayoutInvalidated;+ WidgetHost.SizeChanged += (_, e) =>+ {+ if (!WidgetsInDock || Math.Abs(e.NewSize.Width - e.PreviousSize.Width) < 0.5 || _dockRefitQueued) return;+ _dockRefitQueued = true;+ Dispatcher.BeginInvoke(() =>+ {+ _dockRefitQueued = false;+ if (!WidgetsInDock) return;+ ResizeDockToContent();+ _replacementSession?.RefreshPosition();+ }, System.Windows.Threading.DispatcherPriority.Background);+ };+ _widgetBar.SettingsRequested += WidgetBar_SettingsRequested;+ _widgetBar.SettingsEdited += WidgetBar_SettingsEdited;+ _widgetBar.AddRequested += WidgetBar_AddRequested;+ _widgetBar.EditingChanged += WidgetBar_EditingChanged;+ _widgetBar.Apply(_preferences.Current.WidgetOptions);+ if (_preferences.LoadError is not null)+ {+ ShowStatus(_preferences.LoadError);+ }++ PositionDock();+ }++ private void Window_SourceInitialized(object? sender, EventArgs e)+ {+ var source = (HwndSource?)PresentationSource.FromVisual(this);+ if (source is null)+ {+ ShowStatus("Dock penceresi Windows'a bağlanamadı.");+ return;+ }++ _source = source;+ _source.AddHook(WindowProc);+ _taskbarCreatedMessage = RegisterWindowMessage("TaskbarCreated");+ // The apps running in the background (their notification-area icons) are gathered for the dock.+ Dispatcher.BeginInvoke(() => TrayHost.Shared.Start(), System.Windows.Threading.DispatcherPriority.ApplicationIdle);+ WatchDesktopWhileStarting();+ // A dock that still starts from the slow Run list moves to the quick logon task (once, in the background).+ _ = Task.Run(async () =>+ {+ await Task.Delay(TimeSpan.FromSeconds(10));+ new StartupRegistration().UpgradeToTask();+ });+ if (!ExcludeFromTaskSwitcher(source.Handle))+ {+ ShowStatus("QiDock Alt+Tab listesinden çıkarılamadı.");+ }++ _windowTracker = new NativeWindowTracker(Dispatcher);+ _windowTracker.WindowsChanged += WindowTracker_WindowsChanged;+ _windowTracker.ForegroundWindowChanged += WindowTracker_ForegroundWindowChanged;+ try+ {+ _windowTracker.Start(source.Handle);+ if (!_windowTracker.NotificationsAvailable)+ {+ ShowStatus("Windows uygulama bildirimlerini dinleyemedi; bildirim rozeti kullanılamıyor.");+ }+ }+ catch (InvalidOperationException ex)+ {+ ShowStatus(ex.Message);+ _windowTracker.Dispose();+ _windowTracker = null;+ }++ InitializeTopBar();+#if DEBUG+ if (App.DockSnapshotFolder is { } snapshots)+ {+ if (App.DockCycle) SnapshotEdgeCycle(snapshots);+ else SnapshotDockPlacements(snapshots);+ }+#endif+ InitializeDesktopWidgets();+ InitializeNotifications();+ InitializeExtras(source);++ _autoHideController = new DockAutoHideController(+ this,+ source.Handle,+ DockSurfaceTranslate,+ DockSurface,+ () => _holdDockUp || (_openContextMenu?.IsOpen == true) || _thumbnailPreview.IsVisible || _draggedApp is not null || (_settingsWindow?.IsVisible == true) || _genie.IsBusy+ || NotificationCenterOpen || _downloadsPopup?.IsOpen == true);+ _autoHideController.SetMode(_preferences.Current.AutoHide);+ AttachHudToAutoHide();+ ApplyAutoHideHitArea();++ ApplyDockEdge();+ StartReplacementMode();+ }++ private void PositionDock()+ {+ if (_replacementSession?.IsActive == true)+ {+ return;+ }++ var workArea = SystemParameters.WorkArea;+ ResizeDockToContent();+ ApplyDockAlignment();+ if (Services.DockGeometry.Vertical)+ {+ Top = workArea.Top;+ Height = workArea.Height;+ Left = Edge == Models.DockEdge.Left ? workArea.Left : workArea.Right - Width;+ return;+ }+ Left = _dockPosition switch+ {+ DockPosition.Left => workArea.Left,+ DockPosition.Center => workArea.Left + (workArea.Width - Width) / 2,+ DockPosition.Right => workArea.Right - Width,+ _ => workArea.Left+ };+ Top = Edge == Models.DockEdge.Top ? workArea.Top : Math.Max(workArea.Top, workArea.Bottom - Height);+ }++ // True while the dock should stand in for the Windows taskbar (false after the taskbar was given back).+ private bool _replacementWanted;+ private System.Windows.Threading.DispatcherTimer? _taskbarWait;++ private void StartReplacementMode()+ {+ var source = _source;+ if (source is null)+ {+ ShowStatus("Dock penceresi hazır olmadan görev çubuğu modu açılamaz.");+ return;+ }+ _replacementWanted = true;+ // Started by the sign-in task, the dock can be up before Explorer has made its taskbar. It waits for it+ // (Explorer's TaskbarCreated also starts it) instead of failing once and leaving both bars on screen.+ if (TrayHost.FindExplorerTaskbar() == 0)+ {+ PositionDock();+ if (_taskbarWait is null)+ {+ var started = DateTime.UtcNow;+ _taskbarWait = new System.Windows.Threading.DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };+ _taskbarWait.Tick += (_, _) =>+ {+ var found = TrayHost.FindExplorerTaskbar() != 0;+ if (!found && DateTime.UtcNow - started < TimeSpan.FromMinutes(2)) return;+ _taskbarWait?.Stop();+ _taskbarWait = null;+ if (_replacementSession is null && _replacementWanted)+ {+ if (found) StartReplacementMode();+ else ShowStatus("Windows görev çubuğu bulunamadı; dock onun yerine geçemedi.");+ }+ };+ _taskbarWait.Start();+ }+ return;+ }++ ResizeDockToContent();+ ApplyDockAlignment();+ var session = new TaskbarReplacementSession(this, source.Handle) { Edge = Edge };+ session.OperationFailed += ShowStatus;+ session.LayoutChanged += ApplyTaskbarLayout;+ session.FullScreenChanged += OnFullScreenChanged;+ _replacementSession = session;+ try+ {+ // Set the mode first so Start() applies the matching Explorer taskbar state right away.+ session.UpdateAutoHide(_preferences.Current.AutoHide != AutoHideMode.Disabled);+ session.Start();+ session.UpdateAutoHide(_preferences.Current.AutoHide != AutoHideMode.Disabled);+ }+ catch (InvalidOperationException ex)+ {+ session.Dispose();+ if (!session.IsActive) _replacementSession = null;+ PositionDock();+ ShowStatus(ex.Message);+ }+ }++ private IntPtr WindowProc(IntPtr hwnd, int message, IntPtr wParam, IntPtr lParam, ref bool handled)+ {+ if (_taskbarCreatedMessage != 0 && unchecked((uint)message) == _taskbarCreatedMessage)+ {+ handled = true;+ // Explorer made its taskbar (again). A dock that could not take over yet does so now.+ if (_replacementSession is null && _replacementWanted && _taskbarWait is null) StartReplacementMode();+ else _replacementSession?.HandleTaskbarCreated();+ _deskWidgets?.Reattach();+ TrayHost.Shared.ExplorerRestarted();+ // A restarted Explorer shows its desktop icons again; the clean desktop is checked once more.+ WatchDesktopWhileStarting();+ return IntPtr.Zero;+ }++ // Keep the application's foreground state intact until the dock command runs.+ if (message == WmMouseActivate)+ {+ handled = true;+ return new IntPtr(MaNoActivate);+ }++ if (_replacementSession?.HandleMessage(unchecked((uint)message), wParam, lParam) == true)+ {+ handled = true;+ }++ return IntPtr.Zero;+ }++ private void LoadPinnedApps(IReadOnlyList<string>? preferredOrder = null)+ {+ var result = WindowsTaskbarPinImporter.Import();+ var apps = result.Apps.ToList();+ apps.AddRange(LoadCustomShortcuts(apps));+ foreach (var app in apps)+ {+ app.Icon = app.IsCustomShortcut ? ShortcutIcon(app.ExecutablePath) : ApplicationIconProvider.GetForFile(app.ExecutablePath);+ }++ if (preferredOrder is { Count: > 0 })+ {+ var orderMap = preferredOrder+ .Select((path, index) => (path, index))+ .ToDictionary(pair => pair.path, pair => pair.index, StringComparer.OrdinalIgnoreCase);++ apps.Sort((a, b) =>+ {+ var hasA = orderMap.TryGetValue(a.ExecutablePath, out var indexA);+ var hasB = orderMap.TryGetValue(b.ExecutablePath, out var indexB);+ if (hasA && hasB) return indexA.CompareTo(indexB);+ if (hasA) return -1;+ if (hasB) return 1;+ return 0;+ });+ }++ foreach (var app in apps)+ {+ _pinnedApps.Add(app);+ }++ if (result.Error is not null)+ {+ ShowStatus(result.Error);+ }+ }++ private void WindowTracker_WindowsChanged(object? sender, IReadOnlyList<TrackedWindow> windows)+ {+ ScheduleDesktopCheck();+ foreach (var path in _lastSelectedWindows.Keys.Where(path => !windows.Any(window =>+ string.Equals(window.ExecutablePath, path, StringComparison.OrdinalIgnoreCase))).ToList())+ {+ _lastSelectedWindows.Remove(path);+ }+ UpdateNotificationBadges(_pinnedApps, windows);+ UpdateWindowIndicators(windows);+ if (UpdateRunningApps(windows))+ {+ ResizeDockToContent();+ _replacementSession?.RefreshPosition();+ }++ if (_thumbnailPreview.IsVisible)+ {+ var activeHandles = _thumbnailPreview.ActiveHandles;+ if (activeHandles.Count > 0 && !activeHandles.Any(h => windows.Any(w => w.Handle == h)))+ {+ _thumbnailPreview.Hide();+ }+ }+ }++ private void UpdateNotificationBadges(+ ObservableCollection<DockApp> apps,+ IReadOnlyList<TrackedWindow> windows)+ {+ for (var index = 0; index < apps.Count; index++)+ {+ var app = apps[index];+ var hasNotification = _preferences.Current.NotificationBadgesEnabled && windows.Any(window => window.HasNotification+ && string.Equals(window.ExecutablePath, app.ExecutablePath, StringComparison.OrdinalIgnoreCase));+ if (app.HasNotification != hasNotification)+ {+ app.HasNotification = hasNotification;+ }+ }+ }++ private bool UpdateRunningApps(IReadOnlyList<TrackedWindow> windows)+ {+ var pinnedPaths = _pinnedApps.Select(app => app.ExecutablePath)+ .ToHashSet(StringComparer.OrdinalIgnoreCase);+ var desiredPaths = windows+ .Where(window => window.ExecutablePath is not null+ && File.Exists(window.ExecutablePath)+ && !pinnedPaths.Contains(window.ExecutablePath))+ .Select(window => window.ExecutablePath!)+ .ToHashSet(StringComparer.OrdinalIgnoreCase);+ foreach (var executablePath in desiredPaths)+ {+ CancelRunningAppExit(executablePath);+ }++ var currentApps = _runningApps.ToDictionary(app => app.ExecutablePath, StringComparer.OrdinalIgnoreCase);+ var desiredApps = windows+ .Where(window => window.ExecutablePath is not null+ && File.Exists(window.ExecutablePath)+ && !pinnedPaths.Contains(window.ExecutablePath))+ .GroupBy(window => window.ExecutablePath!, StringComparer.OrdinalIgnoreCase)+ .Select(group =>+ {+ var executablePath = group.Key;+ var hasNotification = _preferences.Current.NotificationBadgesEnabled && group.Any(window => window.HasNotification);+ if (currentApps.TryGetValue(executablePath, out var existingApp))+ {+ existingApp.HasNotification = hasNotification;+ existingApp.IsForeground = group.Any(window => window.Handle == _foregroundWindow);+ existingApp.WindowCount = group.Count();+ return existingApp;+ }++ return new DockApp(GetApplicationName(executablePath), executablePath)+ {+ Icon = ApplicationIconProvider.GetForFile(executablePath),+ HasNotification = hasNotification,+ IsForeground = group.Any(window => window.Handle == _foregroundWindow),+ WindowCount = group.Count()+ };+ })+ .OrderBy(app => app.Name, StringComparer.CurrentCultureIgnoreCase)+ .ThenBy(app => app.ExecutablePath, StringComparer.OrdinalIgnoreCase)+ .ToList();+ var layoutChanged = !_runningApps.Select(app => app.ExecutablePath)+ .SequenceEqual(desiredApps.Select(app => app.ExecutablePath), StringComparer.OrdinalIgnoreCase);++ for (var desiredIndex = 0; desiredIndex < desiredApps.Count; desiredIndex++)+ {+ var desiredApp = desiredApps[desiredIndex];+ if (desiredIndex < _runningApps.Count+ && string.Equals(_runningApps[desiredIndex].ExecutablePath, desiredApp.ExecutablePath, StringComparison.OrdinalIgnoreCase))+ {+ if (_runningApps[desiredIndex] != desiredApp)+ {+ _runningApps[desiredIndex] = desiredApp;+ }++ continue;+ }++ var existingIndex = -1;+ for (var index = desiredIndex + 1; index < _runningApps.Count; index++)+ {+ if (string.Equals(_runningApps[index].ExecutablePath, desiredApp.ExecutablePath, StringComparison.OrdinalIgnoreCase))+ {+ existingIndex = index;+ break;+ }+ }++ if (existingIndex >= 0)+ {+ _runningApps.Move(existingIndex, desiredIndex);+ if (_runningApps[desiredIndex] != desiredApp)+ {+ _runningApps[desiredIndex] = desiredApp;+ }+ }+ else+ {+ _runningApps.Insert(desiredIndex, desiredApp);+ }+ }++ for (var index = _runningApps.Count - 1; index >= desiredApps.Count; index--)+ {+ AnimateRunningAppRemoval(_runningApps[index]);+ }++ UpdateRunningAppsDivider();+ return layoutChanged;+ }++ private void UpdateRunningAppsDivider() =>+ RunningAppsDivider.Visibility = _runningApps.Count > 0 && !_widgetBar.IsEditing ? Visibility.Visible : Visibility.Collapsed;++ private void CancelRunningAppExit(string executablePath)+ {+ if (!_exitingRunningPaths.Remove(executablePath))+ {+ return;+ }++ var app = _runningApps.FirstOrDefault(candidate =>+ string.Equals(candidate.ExecutablePath, executablePath, StringComparison.OrdinalIgnoreCase));+ var button = app is null ? null : FindVisualChild<Button>(RunningApps.ItemContainerGenerator.ContainerFromItem(app));+ if (button is null) return;++ button.BeginAnimation(UIElement.OpacityProperty, null);+ button.Opacity = 1;+ button.IsHitTestVisible = true;+ if (button.RenderTransform is ScaleTransform scale)+ {+ scale.BeginAnimation(ScaleTransform.ScaleXProperty, null);+ scale.BeginAnimation(ScaleTransform.ScaleYProperty, null);+ scale.ScaleX = 1;+ scale.ScaleY = 1;+ }+ }++ private void AnimateRunningAppRemoval(DockApp app)+ {+ if (!_exitingRunningPaths.Add(app.ExecutablePath))+ {+ return;+ }++ AnimateDockAppRemoval(RunningApps, _runningApps, app, () =>+ {+ _exitingRunningPaths.Remove(app.ExecutablePath);+ ResizeDockToContent();+ _replacementSession?.RefreshPosition();+ });+ }++ private void AnimateDockAppRemoval(+ ItemsControl owner,+ ObservableCollection<DockApp> apps,+ DockApp app,+ Action afterRemoval)+ {+ var button = FindVisualChild<Button>(owner.ItemContainerGenerator.ContainerFromItem(app));+ if (!_preferences.Current.AnimationsEnabled || !SystemParameters.ClientAreaAnimation || button?.RenderTransform is not ScaleTransform scale)+ {+ RemoveDockApp(apps, app);+ afterRemoval();+ return;+ }++ button.IsHitTestVisible = false;+ var fade = new DoubleAnimation(0, TimeSpan.FromMilliseconds(135))+ {+ EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }+ };+ fade.Completed += (_, _) =>+ {+ if (ReferenceEquals(owner, RunningApps) && !_exitingRunningPaths.Contains(app.ExecutablePath))+ {+ return;+ }+ RemoveDockApp(apps, app);+ afterRemoval();+ };+ button.BeginAnimation(UIElement.OpacityProperty, fade);+ scale.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(0.95, TimeSpan.FromMilliseconds(135))+ {+ EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }+ });+ scale.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(0.95, TimeSpan.FromMilliseconds(135))+ {+ EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }+ });+ }++ private static void RemoveDockApp(ObservableCollection<DockApp> apps, DockApp app)+ {+ var index = apps.IndexOf(app);+ if (index >= 0)+ {+ apps.RemoveAt(index);+ }+ }++ private static T? FindVisualChild<T>(DependencyObject? parent) where T : DependencyObject+ {+ if (parent is null)+ {+ return null;+ }++ for (var index = 0; index < VisualTreeHelper.GetChildrenCount(parent); index++)+ {+ var child = VisualTreeHelper.GetChild(parent, index);+ if (child is T match)+ {+ return match;+ }++ var descendant = FindVisualChild<T>(child);+ if (descendant is not null)+ {+ return descendant;+ }+ }++ return null;+ }++ private void DockAppButton_Loaded(object sender, RoutedEventArgs e)+ {+ if (sender is Button tile)+ {+ if (GetButtonIcon(tile) is { } face) OrientIcon(face);+ PointTooltip(tile);+ }+ if (!_preferences.Current.AnimationsEnabled || !SystemParameters.ClientAreaAnimation || sender is not Button button)+ {+ return;+ }++ var scale = new ScaleTransform();+ button.RenderTransform = scale;+ // Keep the new application visible on its first rendered frame.+ button.Opacity = 1;+ scale.ScaleX = 0.95;+ scale.ScaleY = 0.95;+ var duration = TimeSpan.FromMilliseconds(165);+ var easing = new CubicEase { EasingMode = EasingMode.EaseOut };+ scale.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(0.95, 1, duration) { EasingFunction = easing });+ scale.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(0.95, 1, duration) { EasingFunction = easing });+ }++ private void DockApp_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)+ {+ // Snapshot before Button focus handling and preview dismissal can change foreground activation.+ var foreground = NativeWindowTracker.GetForegroundApplicationWindow();+ _foregroundAtAppPress = foreground != 0 ? foreground : _foregroundWindow;++ if (sender is Button { DataContext: DockApp app } && _pinnedApps.Contains(app))+ {+ _dragStartPoint = e.GetPosition(this);+ _draggedApp = app;+ }+ else+ {+ _draggedApp = null;+ }+ }++ private void DockApp_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)+ {+ _draggedApp = null;+ }++ private void DockApp_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)+ {+ if (e.LeftButton != System.Windows.Input.MouseButtonState.Pressed || _draggedApp is null || sender is not Button button)+ {+ return;+ }++ var currentPoint = e.GetPosition(this);+ var diff = _dragStartPoint - currentPoint;+ if (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance+ || Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance)+ {+ var app = _draggedApp;+ _draggedApp = null;+ _foregroundAtAppPress = null;+ _previewCloseTimer.Stop();+ _thumbnailPreview.Hide();+ ResetMagnification();+ DragDrop.DoDragDrop(button, app, DragDropEffects.Move);+ }+ }++ private void DockApp_DragOver(object sender, DragEventArgs e)+ {+ if (e.Data.GetDataPresent(typeof(DockApp))+ && sender is Button targetButton+ && targetButton.DataContext is DockApp targetApp+ && _pinnedApps.Contains(targetApp))+ {+ e.Effects = DragDropEffects.Move;+ e.Handled = true;+ }+ else+ {+ if (HasDroppable(e.Data)) return; // files and links: the dock adds them as shortcuts+ e.Effects = DragDropEffects.None;+ e.Handled = true;+ }+ }++ private void DockApp_Drop(object sender, DragEventArgs e)+ {+ if (!e.Data.GetDataPresent(typeof(DockApp))) return;+ if (e.Data.GetData(typeof(DockApp)) is DockApp sourceApp+ && sender is Button targetButton+ && targetButton.DataContext is DockApp targetApp+ && _pinnedApps.Contains(sourceApp)+ && _pinnedApps.Contains(targetApp)+ && !ReferenceEquals(sourceApp, targetApp))+ {+ var oldIndex = _pinnedApps.IndexOf(sourceApp);+ var newIndex = _pinnedApps.IndexOf(targetApp);+ if (oldIndex >= 0 && newIndex >= 0 && oldIndex != newIndex)+ {+ _pinnedApps.Move(oldIndex, newIndex);+ SavePinOrder();+ _replacementSession?.RefreshPosition();+ }+ }++ e.Handled = true;+ }++ private void DockApp_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)+ {+ _foregroundAtAppPress = null;+ }++ private void DockApp_Click(object sender, RoutedEventArgs e)+ {+ if (sender is not Button { DataContext: DockApp app })+ {+ return;+ }++ var foregroundAtPress = _foregroundAtAppPress;+ _foregroundAtAppPress = null;+ _previewCloseTimer.Stop();+ _thumbnailPreview.Hide();+ // The window is opening or minimizing (possibly with the genie effect); no hover preview on top.+ _suppressPreviewsUntil = DateTime.UtcNow.AddMilliseconds(1200);+ AnimateActivationFeedback((Button)sender);+ OpenDockApp(app, toggleIfForeground: true, foregroundAtPress, (Button)sender);+ }++ private void StartButton_Click(object sender, RoutedEventArgs e)+ {+ _previewCloseTimer.Stop();+ _thumbnailPreview.Hide();+ if (CloseStartMenuIfOpen()) return;+ const uint wmSysCommand = 0x0112;+ const int scTaskList = 0xF130;+ if (_source is null || !PostMessage(_source.Handle, wmSysCommand, scTaskList, 0))+ {+ ShowStatus("Windows Başlat menüsüne açılma isteği gönderilemedi.");+ }+ }++ private static (ScaleTransform Scale, TranslateTransform Translate) GetIconTransforms(FrameworkElement icon)+ {+ if (icon.RenderTransform is TransformGroup group)+ {+ // Transforms declared in templates are sealed; swap in an editable copy once.+ if (group.IsFrozen || group.Children.Any(child => child.IsFrozen))+ {+ group = group.Clone();+ icon.RenderTransform = group;+ }++ var s = group.Children.OfType<ScaleTransform>().FirstOrDefault();+ var t = group.Children.OfType<TranslateTransform>().FirstOrDefault();+ if (s is not null && t is not null)+ {+ return (s, t);+ }+ }++ var newScale = new ScaleTransform();+ var newTranslate = new TranslateTransform();+ var newGroup = new TransformGroup();+ newGroup.Children.Add(newScale);+ newGroup.Children.Add(newTranslate);+ icon.RenderTransform = newGroup;+ icon.RenderTransformOrigin = new Point(0.5, 0.95);+ return (newScale, newTranslate);+ }++ private static FrameworkElement? GetButtonIcon(Button button) => button.Content as FrameworkElement;++ private IEnumerable<Button> GetAllDockButtons()+ {+ yield return StartButton;+ yield return AppGridButton;+ yield return DesktopButton;+ yield return FilesDesktopButton;+ yield return NotificationsButton;++ for (var i = 0; i < _pinnedApps.Count; i++)+ {+ if (PinnedApps.ItemContainerGenerator.ContainerFromIndex(i) is DependencyObject container+ && FindVisualChild<Button>(container) is { } button)+ {+ yield return button;+ }+ }++ for (var i = 0; i < _runningApps.Count; i++)+ {+ if (RunningApps.ItemContainerGenerator.ContainerFromIndex(i) is DependencyObject container+ && FindVisualChild<Button>(container) is { } button)+ {+ yield return button;+ }+ }++ yield return DownloadsButton;+ yield return TrashButton;+ }++ private void AnimateActivationFeedback(Button button)+ {+ if (!_preferences.Current.AnimationsEnabled || !SystemParameters.ClientAreaAnimation) return;+ var icon = GetButtonIcon(button);+ if (icon is null) return;++ var (_, translate) = GetIconTransforms(icon);++ var bounce = new DoubleAnimationUsingKeyFrames+ {+ Duration = TimeSpan.FromMilliseconds(420),+ KeyFrames =+ {+ new EasingDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.Zero)),+ new EasingDoubleKeyFrame(-12, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(120)),+ new CubicEase { EasingMode = EasingMode.EaseOut }),+ new EasingDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(240)),+ new CubicEase { EasingMode = EasingMode.EaseIn }),+ new EasingDoubleKeyFrame(-5, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(330)),+ new CubicEase { EasingMode = EasingMode.EaseOut }),+ new EasingDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(420)),+ new CubicEase { EasingMode = EasingMode.EaseIn })+ }+ };+ translate.BeginAnimation(TranslateTransform.YProperty, bounce);+ }++ /// <summary>+ /// Magnification: tiles near the pointer grow from their bottom edge and push their+ /// neighbours apart (the dock widens), instead of just scaling on top of each other.+ /// Distances are measured in the un-magnified layout so the effect doesn't feed back on itself.+ /// </summary>+ private void DockSurface_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)+ {+ // While a panel stands on the dock the tiles keep still, so the panel stays joined to its tile.+ if (EdgePanel.StandsOnDock)+ {+ LiftHovered(null);+ return;+ }+ if (!_preferences.Current.Magnify || !_preferences.Current.AnimationsEnabled || !SystemParameters.ClientAreaAnimation)+ {+ // Without magnification the tile under the pointer rises a little, so it is clear which one it is.+ LiftHovered(GetAllDockButtons().FirstOrDefault(b => b.IsVisible && b.IsMouseOver));+ return;+ }++ LiftHovered(null);+ MagnifyAt(e.GetPosition(DockContents).X);+ }++ private Button? _liftedButton;++ /// <summary>Raises <paramref name="button"/>'s tile a few pixels (and lowers the one raised before).</summary>+ private void LiftHovered(Button? button)+ {+ if (ReferenceEquals(button, _liftedButton)) return;+ var animate = _preferences.Current.AnimationsEnabled && SystemParameters.ClientAreaAnimation;+ void Move(Button target, double to)+ {+ if (GetButtonIcon(target) is not { } icon) return;+ var (_, translate) = GetIconTransforms(icon);+ if (!animate)+ {+ translate.BeginAnimation(TranslateTransform.YProperty, null);+ translate.Y = to;+ return;+ }+ translate.BeginAnimation(TranslateTransform.YProperty, new DoubleAnimation(to, TimeSpan.FromMilliseconds(110))+ {+ EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }+ });+ }+ if (_liftedButton is { } previous) Move(previous, 0);+ _liftedButton = button;+ if (button is not null) Move(button, -7);+ }++ private void MagnifyAt(double mouseX)+ {+ var cell = Application.Current.Resources["DockCellSize"] is double size ? size : 50;+ var maxScale = (double)FindResource("DockHoverScale");+ var influenceRadius = cell * 3.2;++ var buttons = GetAllDockButtons().Where(b => b.IsVisible).ToList();+ if (buttons.Count == 0) return;+ var lefts = new double[buttons.Count];+ var baseLefts = new double[buttons.Count];+ double extra = 0;+ double? baseMouse = null;+ for (var i = 0; i < buttons.Count; i++)+ {+ var width = buttons[i].ActualWidth > 0 ? buttons[i].ActualWidth : cell;+ lefts[i] = buttons[i].TranslatePoint(new Point(0, 0), DockContents).X;+ baseLefts[i] = lefts[i] - extra;+ if (baseMouse is null && mouseX >= lefts[i] && mouseX < lefts[i] + width)+ baseMouse = baseLefts[i] + (mouseX - lefts[i]) / width * cell;+ extra += width - cell;+ }+ baseMouse ??= mouseX < lefts[0] ? mouseX : mouseX - extra;++ double totalExtra = 0;+ var magnified = new List<Button>();+ for (var i = 0; i < buttons.Count; i++)+ {+ var button = buttons[i];+ var icon = GetButtonIcon(button);+ if (icon is null) continue;+ var distance = Math.Abs(baseMouse.Value - (baseLefts[i] + cell / 2));+ var targetScale = 1.0;+ if (distance < influenceRadius)+ {+ var factor = Math.Cos(distance / influenceRadius * (Math.PI / 2));+ targetScale = 1.0 + (maxScale - 1.0) * factor * factor;+ }++ var (scale, _) = GetIconTransforms(icon);+ scale.BeginAnimation(ScaleTransform.ScaleXProperty, null);+ scale.BeginAnimation(ScaleTransform.ScaleYProperty, null);+ scale.ScaleX = targetScale;+ scale.ScaleY = targetScale;+ button.BeginAnimation(WidthProperty, null);+ if (targetScale > 1.005)+ {+ button.Width = cell * targetScale;+ totalExtra += cell * (targetScale - 1);+ magnified.Add(button);+ }+ else+ {+ button.ClearValue(WidthProperty);+ }+ }++ foreach (var button in _magnifiedButtons.Except(magnified))+ {+ button.BeginAnimation(WidthProperty, null);+ button.ClearValue(WidthProperty);+ if (GetButtonIcon(button) is { } icon)+ {+ var (scale, _) = GetIconTransforms(icon);+ scale.ScaleX = 1.0;+ scale.ScaleY = 1.0;+ }+ }+ _magnifiedButtons.Clear();+ _magnifiedButtons.AddRange(magnified);+ _magnifiedIcons.Clear();+ _magnifiedIcons.AddRange(magnified.Select(GetButtonIcon).OfType<FrameworkElement>());++ if (!double.IsNaN(_baseSurfaceWidth))+ {+ var length = _dockArea.Width > 0 ? _dockArea.Width : Services.DockGeometry.Vertical ? ActualHeight : ActualWidth;+ var maximum = Math.Max(_baseSurfaceWidth, length - DockSurface.Margin.Left - DockSurface.Margin.Right);+ DockSurface.BeginAnimation(WidthProperty, null);+ DockSurface.Width = Math.Min(maximum, _baseSurfaceWidth + totalExtra);+ }+ }++ private void DockSurface_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e) => _autoHideController?.OnMouseEnterDock();++ private void DockSurface_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)+ {+ LiftHovered(null);+ ResetMagnification();+ _autoHideController?.OnMouseLeaveDock();+ }++ private void DockEdgeTrigger_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e) => _autoHideController?.OnMouseEnterEdge();+ private void DockEdgeTrigger_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e) => _autoHideController?.OnMouseLeaveEdge();++ /// <summary>+ /// Lets the magnified tiles settle back to their size. <paramref name="atRest"/> runs with the layout already+ /// at rest (before the settling starts), to read where a tile will end up.+ /// </summary>+ private void ResetMagnification(Action? atRest = null)+ {+ if (_magnifiedButtons.Count == 0 && _magnifiedIcons.Count == 0)+ {+ atRest?.Invoke();+ return;+ }+ var animate = _preferences.Current.AnimationsEnabled && SystemParameters.ClientAreaAnimation;+ var duration = animate ? TimeSpan.FromMilliseconds(160) : TimeSpan.Zero;+ var easing = new CubicEase { EasingMode = EasingMode.EaseOut };++ foreach (var icon in _magnifiedIcons)+ {+ var (scale, _) = GetIconTransforms(icon);+ scale.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(1.0, duration) { EasingFunction = easing });+ scale.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(1.0, duration) { EasingFunction = easing });+ }++ // Widths fall back to the cell size: clear the local value, then animate from where they were.+ var widths = _magnifiedButtons.Select(button => (Button: button, From: button.ActualWidth)).ToList();+ foreach (var (button, _) in widths)+ {+ button.BeginAnimation(WidthProperty, null);+ button.ClearValue(WidthProperty);+ }+ var surfaceFrom = DockSurface.ActualWidth;+ if (!double.IsNaN(_baseSurfaceWidth))+ {+ DockSurface.BeginAnimation(WidthProperty, null);+ DockSurface.Width = _baseSurfaceWidth;+ }+ if (atRest is not null)+ {+ UpdateLayout();+ atRest();+ }+ if (animate)+ {+ foreach (var (button, from) in widths)+ button.BeginAnimation(WidthProperty, new DoubleAnimation(from, button.Width, duration) { EasingFunction = easing, FillBehavior = FillBehavior.Stop });+ if (!double.IsNaN(_baseSurfaceWidth))+ DockSurface.BeginAnimation(WidthProperty, new DoubleAnimation(surfaceFrom, _baseSurfaceWidth, duration) { EasingFunction = easing, FillBehavior = FillBehavior.Stop });+ }++ _magnifiedButtons.Clear();+ _magnifiedIcons.Clear();+ }++ private void OpenDockApp(DockApp app, bool toggleIfForeground = false, nint? foregroundAtPress = null, FrameworkElement? anchor = null)+ {+ if (TryOpenShortcut(app, anchor)) return;+ var executablePath = app.ExecutablePath;+ var existingWindow = foregroundAtPress is { } pressedWindow+ ? _windowTracker?.Snapshot.FirstOrDefault(window => window.Handle == pressedWindow+ && string.Equals(window.ExecutablePath, executablePath, StringComparison.OrdinalIgnoreCase))+ : null;+ existingWindow ??= FindNextWindowForExecutable(executablePath);+ if (existingWindow is not null)+ {+ if (anchor is not null && TryGenie(existingWindow.Handle, executablePath, toggleIfForeground, foregroundAtPress, anchor))+ {+ _lastSelectedWindows[executablePath] = existingWindow.Handle;+ ClearStatus();+ return;+ }++ var activated = toggleIfForeground+ ? NativeWindowTracker.ToggleActivation(existingWindow.Handle, executablePath, foregroundAtPress)+ : NativeWindowTracker.Activate(existingWindow.Handle);+ if (!activated)+ {+ ShowStatus("Pencereyi öne getirme veya küçültme isteği tamamlanamadı. Windows odağı engellemiş olabilir.");+ return;+ }++ _lastSelectedWindows[executablePath] = existingWindow.Handle;+ ClearStatus();+ return;+ }++ if (!File.Exists(executablePath))+ {+ ShowStatus("Uygulama dosyası bulunamadı. Windows görev çubuğundaki kısayolu güncelleyin.");+ return;+ }++ try+ {+ Process.Start(new ProcessStartInfo(executablePath)+ {+ Arguments = app.LaunchArguments ?? string.Empty,+ UseShellExecute = true+ });+ if (anchor is not null && GenieEnabled)+ {+ _genie.ExpectLaunch(executablePath, GetGenieTarget(anchor));+ }+ ClearStatus();+ }+ catch (Win32Exception)+ {+ ShowStatus("Uygulama Windows tarafından başlatılamadı.");+ }+ catch (InvalidOperationException)+ {+ ShowStatus("Uygulama başlatma isteği tamamlanamadı.");+ }+ catch (UnauthorizedAccessException)+ {+ ShowStatus("Uygulamayı başlatmak için erişim izni yok.");+ }+ catch (IOException)+ {+ ShowStatus("Uygulama dosyasına erişilemedi.");+ }+ }++ // Drawn on the processor (low-memory mode) the genie's window picture stutters, so windows then minimize plainly.+ private bool GenieEnabled => _preferences.Current.AnimationsEnabled && _preferences.Current.GenieEffectEnabled && SystemParameters.MinimizeAnimation+ && Application.Current is not App { SoftwareRendering: true };++ /// <summary>Screen rectangle (physical pixels) of the clicked dock tile, magnification included.</summary>+ private static Rect GetGenieTarget(FrameworkElement anchor)+ {+ var tile = anchor is Button { Content: FrameworkElement content } ? content : anchor;+ var topLeft = tile.PointToScreen(new Point(0, 0));+ var bottomRight = tile.PointToScreen(new Point(tile.ActualWidth, tile.ActualHeight));+ return new Rect(topLeft, bottomRight);+ }++ /// <summary>Minimize into / restore out of the dock tile with the genie effect when possible.</summary>+ private bool TryGenie(nint window, string executablePath, bool toggleIfForeground, nint? foregroundAtPress, FrameworkElement anchor)+ {+ if (!GenieEnabled) return false;+ var target = GetGenieTarget(anchor);+ if (toggleIfForeground)+ {+ var minimizeTarget = NativeWindowTracker.GetMinimizeTarget(window, executablePath, foregroundAtPress);+ if (minimizeTarget != 0) return _genie.TryMinimize(minimizeTarget, target);+ }++ return NativeWindowTracker.IsMinimized(window) && _genie.TryRestore(window, target, NativeWindowTracker.Activate);+ }++ /// <summary>The icons grow under the pointer only when magnification is on, by the chosen amount.</summary>+ private void ApplyMagnifyPreference()+ {+ var current = _preferences.Current;+ Application.Current.Resources["DockHoverScale"] = current.Magnify ? Math.Clamp(current.MagnifyScale, 1.1, 2.2) : 1.0;+ }++ private void DockApp_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)+ {+ _previewCloseTimer.Stop();+ _previewOpenTimer.Stop();+ _previewPending = null;+ if (sender is not Button button) return;+ var hasWindows = button.Tag is string path && _windowTracker?.Snapshot.Any(window =>+ string.Equals(window.ExecutablePath, path, StringComparison.OrdinalIgnoreCase)) == true;+ if (!_preferences.Current.PreviewsEnabled || _thumbnailPreview.IsVisible || !hasWindows)+ {+ ShowPreviewFor(button);+ return;+ }+ // No preview yet: wait until the pointer rests here (the tooltip waits meanwhile too).+ ToolTipService.SetIsEnabled(button, false);+ _previewPending = button;+ _previewOpenTimer.Start();+ }++ private void ShowPreviewFor(Button sender)+ {+ if (!_preferences.Current.PreviewsEnabled)+ {+ if (sender is Button button) ToolTipService.SetIsEnabled(button, true);+ _thumbnailPreview.Hide();+ return;+ }+ if (sender is not Button { Tag: string executablePath })+ {+ return;+ }++ if (_genie.IsBusy || DateTime.UtcNow < _suppressPreviewsUntil)+ {+ _thumbnailPreview.Hide();+ return;+ }++ var matchingWindows = _windowTracker?.Snapshot+ .Where(window => string.Equals(window.ExecutablePath, executablePath, StringComparison.OrdinalIgnoreCase))+ .ToList() ?? [];++ ToolTipService.SetIsEnabled((Button)sender, matchingWindows.Count == 0);+ if (matchingWindows.Count == 0)+ {+ _thumbnailPreview.Hide();+ return;+ }++ var appIcon = ((Button)sender).DataContext is DockApp app ? app.Icon : null;+ _thumbnailPreview.ShowForWindows(matchingWindows, (FrameworkElement)sender, appIcon);+ }++ private void DockApp_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)+ {+ if (ReferenceEquals(sender, _previewPending))+ {+ _previewOpenTimer.Stop();+ _previewPending = null;+ if (sender is Button left) ToolTipService.SetIsEnabled(left, true);+ }+ _previewCloseTimer.Stop();+ _previewCloseTimer.Start();+ }++ private void PreviewCloseTimer_Tick(object? sender, EventArgs e)+ {+ _previewCloseTimer.Stop();+ _thumbnailPreview.Hide();+ _autoHideController?.EvaluateState();+ }++ private void ThumbnailPreview_PointerEntered(object? sender, EventArgs e)+ {+ _previewCloseTimer.Stop();+ }++ private void ThumbnailPreview_PointerLeft(object? sender, EventArgs e)+ {+ _previewCloseTimer.Stop();+ _previewCloseTimer.Start();+ }++ private void ThumbnailPreview_PreviewClicked(object? sender, EventArgs e)+ {+ var sourceHandle = _thumbnailPreview.SourceHandle;+ _previewCloseTimer.Stop();+ _thumbnailPreview.Hide();+ if (sourceHandle == 0 || !NativeWindowTracker.Activate(sourceHandle))+ {+ ShowStatus("Önizleme penceresi etkinleştirilemedi. Windows odağı engellemiş olabilir.");+ return;+ }++ ClearStatus();+ }++ private void ThumbnailPreview_CloseRequested(object? sender, EventArgs e)+ {+ var sourceHandle = _thumbnailPreview.SourceHandle;+ _previewCloseTimer.Stop();+ _thumbnailPreview.Hide();+ if (sourceHandle == 0 || !NativeWindowTracker.RequestClose(sourceHandle))+ {+ ShowStatus("Önizlenen pencereye kapatma isteği gönderilemedi.");+ return;+ }++ ClearStatus();+ }++ private TrackedWindow? FindWindowForExecutable(string executablePath)+ {+ return _windowTracker?.Snapshot.FirstOrDefault(window => window.Handle == _foregroundWindow+ && string.Equals(window.ExecutablePath, executablePath, StringComparison.OrdinalIgnoreCase))+ ?? _windowTracker?.Snapshot.FirstOrDefault(window =>+ string.Equals(window.ExecutablePath, executablePath, StringComparison.OrdinalIgnoreCase));+ }++ private TrackedWindow? FindNextWindowForExecutable(string executablePath)+ {+ var matchingWindows = _windowTracker?.Snapshot.Where(window =>+ string.Equals(window.ExecutablePath, executablePath, StringComparison.OrdinalIgnoreCase)).ToList();+ if (matchingWindows is not { Count: > 0 })+ {+ return null;+ }++ var foreground = matchingWindows.FirstOrDefault(window => window.Handle == _foregroundWindow);+ if (foreground is not null)+ {+ return foreground;+ }++ matchingWindows.Sort((left, right) => left.Handle.ToInt64().CompareTo(right.Handle.ToInt64()));+ var previousIndex = _lastSelectedWindows.TryGetValue(executablePath, out var previousHandle)+ ? matchingWindows.FindIndex(window => window.Handle == previousHandle)+ : -1;+ return matchingWindows[(previousIndex + 1) % matchingWindows.Count];+ }++ private void UpdateWindowIndicators(IReadOnlyList<TrackedWindow> windows)+ {+ for (var index = 0; index < _pinnedApps.Count; index++)+ {+ var app = _pinnedApps[index];+ var matching = windows.Where(window => string.Equals(window.ExecutablePath, app.ExecutablePath,+ StringComparison.OrdinalIgnoreCase)).ToList();+ var isForeground = matching.Any(window => window.Handle == _foregroundWindow);+ var count = matching.Count;+ if (app.IsRunning != (count > 0) || app.IsForeground != isForeground || app.WindowCount != count)+ {+ app.IsForeground = isForeground;+ app.WindowCount = count;+ }+ }+ }++ private static string GetApplicationName(string executablePath)+ {+ var description = FileVersionInfo.GetVersionInfo(executablePath).FileDescription;+ return string.IsNullOrWhiteSpace(description)+ ? Path.GetFileNameWithoutExtension(executablePath)+ : description.Trim();+ }++ private void WindowTracker_ForegroundWindowChanged(nint windowHandle)+ {+ TrackStartMenu(windowHandle);+ ScheduleDesktopCheck();+ // Windows briefly reports "no foreground window" while focus moves; that is not a switch to+ // another app and must not close the dock's menus or popups.+ if (windowHandle == 0) return;+ _replacementSession?.UpdateForeground(windowHandle);+ UpdateFullScreenAwareness(windowHandle);+ _autoHideController?.CheckForegroundWindow(windowHandle);+ GetWindowThreadProcessId(windowHandle, out var processId);+ // Dock buttons, thumbnail hosts, and menus must not replace the last external foreground window.+ if (processId == Environment.ProcessId) return;+ // Explorer may rebuild the desktop view (wallpaper change, Win+D): keep it clean.+ KeepDesktopClean(windowHandle);+ // Window lists are re-reported whenever any app renames or opens a window; only a real switch closes the menu.+ if (_openContextMenu is not null && windowHandle != _foregroundWindow)+ {+ _openContextMenu.IsOpen = false;+ }+ _foregroundWindow = windowHandle;+ UpdateWindowIndicators(_windowTracker?.Snapshot ?? []);+ foreach (var app in _runningApps)+ {+ app.IsForeground = _windowTracker?.Snapshot.Any(window => window.Handle == windowHandle+ && string.Equals(window.ExecutablePath, app.ExecutablePath, StringComparison.OrdinalIgnoreCase)) == true;+ }+ if (_replacementSession?.IsActive == true)+ {+ _replacementSession.RefreshPosition();+ }+ }++ private void ShowStatus(string message)+ {+ StatusText.Text = UiText.LocalizeError(message);+ ResizeDockToContent();+ _replacementSession?.RefreshPosition();+ }++ private void ClearStatus()+ {+ StatusText.Text = string.Empty;+ ResizeDockToContent();+ _replacementSession?.RefreshPosition();+ }++ private async void DockContextMenu_Opened(object sender, RoutedEventArgs e)+ {+ if (sender is not ContextMenu contextMenu)+ {+ return;+ }++ _previewCloseTimer.Stop();+ _thumbnailPreview.Hide();+ ResetMagnification();+ if (_openContextMenu is not null && !ReferenceEquals(_openContextMenu, contextMenu))+ _openContextMenu.IsOpen = false;+ _openContextMenu = contextMenu;+ BeginMenuWatch(contextMenu);++ var pinnedApp = (contextMenu.PlacementTarget as FrameworkElement)?.DataContext as DockApp;+ _contextTargetWasForeground = pinnedApp?.IsForeground == true;+ var hasAppTarget = pinnedApp is not null;+ // Shortcuts added from the menu ("Kısayol ekle") live in the settings, not the pin folder: they are kept too.+ var isPinnedTarget = pinnedApp is { ShortcutPath: not null } or { IsCustomShortcut: true };+ var isRunning = pinnedApp?.IsRunning == true;+ SetMenuItemVisibility(contextMenu, "ActivateDockApp", hasAppTarget);+ SetMenuItemVisibility(contextMenu, "CloseDockApp", isRunning);+ SetMenuItemVisibility(contextMenu, "TerminateDockApp", isRunning);+ SetMenuItemVisibility(contextMenu, "PinDockApp", hasAppTarget && !isPinnedTarget);+ SetMenuItemVisibility(contextMenu, "UnpinDockApp", isPinnedTarget);+ SetSeparatorVisibility(contextMenu, "RunningCommandsDivider", isRunning);++ if (pinnedApp is null)+ {+ FocusContextMenu(contextMenu);+ return;+ }++ SetMenuCommandParameter(contextMenu, pinnedApp.ExecutablePath);+ var targetWindow = FindWindowForExecutable(pinnedApp.ExecutablePath);+ if (FindMenuItem(contextMenu, "ActivateDockApp") is { } activateMenuItem)+ {+ activateMenuItem.CommandParameter = pinnedApp;+ activateMenuItem.Header = isRunning+ ? (pinnedApp.IsForeground ? UiText.Get("MinimizeWindow") : UiText.Get("ActivateWindow"))+ : pinnedApp.IsCustomShortcut && !pinnedApp.ExecutablePath.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)+ ? UiText.Get("OpenItem") // a file, folder or web link+ : UiText.Get("OpenApplication");+ }+ if (FindMenuItem(contextMenu, "PinDockApp") is { } pinMenuItem)+ {+ pinMenuItem.CommandParameter = pinnedApp;+ }+ if (FindMenuItem(contextMenu, "UnpinDockApp") is { } unpinMenuItem)+ {+ unpinMenuItem.CommandParameter = pinnedApp;+ }+ FocusContextMenu(contextMenu);+ await LoadJumpListAsync(contextMenu, targetWindow?.Handle ?? 0, pinnedApp.ShortcutPath);+ }++ private async Task LoadJumpListAsync(ContextMenu menu, nint window, string? shortcut)+ {+ var boundary = menu.Items.OfType<Separator>().FirstOrDefault(item => item.Tag as string == "JumpListCommands");+ if (boundary is null) return;+ _jumpListLoad?.Cancel();+ _jumpListLoad?.Dispose();+ var load = new CancellationTokenSource(TimeSpan.FromSeconds(3));+ _jumpListLoad = load;+ ReplaceJumpListItems(menu, boundary, [new MenuItem { Header = UiText.Get("TasksLoading"), IsEnabled = false }]);+ try+ {+ var result = await _jumpLists.ReadAsync(window, shortcut, load.Token);+ if (!menu.IsOpen || !ReferenceEquals(_jumpListLoad, load))+ {+ await _jumpLists.ReleaseAsync(result.SessionId);+ return;+ }+ _jumpListSession = result.SessionId;+ var items = new List<Control>();+ foreach (var group in result.Groups)+ {+ if (items.Count > 0) items.Add(new Separator());+ var heading = new MenuItem { Header = group.Title.Replace("_", "__") };+ heading.SetResourceReference(StyleProperty, "MenuSectionHeading");+ items.Add(heading);+ foreach (var entry in group.Entries)+ {+ if (entry.IsSeparator) { items.Add(new Separator()); continue; }+ // Keep the session alive until Click queues invocation; WPF normally closes first.+ var item = new MenuItem { Header = entry.Title.Replace("_", "__"), StaysOpenOnClick = true };+ if (entry.Icon is not null) item.Icon = new Image { Source = entry.Icon, Width = 16, Height = 16 };+ item.Click += async (_, args) =>+ {+ args.Handled = true;+ var invocation = _jumpLists.InvokeAsync(result.SessionId, entry.CommandId, _source?.Handle ?? 0);+ menu.IsOpen = false;+ if (!await invocation && IsLoaded)+ ShowStatus("Uygulama görevi çalıştırılamadı. Menüyü yeniden açıp deneyin.");+ };+ items.Add(item);+ }+ }+ if (result.Status != JumpListStatus.Ready)+ {+ var message = result.Status switch+ {+ JumpListStatus.Empty => UiText.Get("TasksEmpty"),+ JumpListStatus.IdentityUnavailable => UiText.Get("TasksIdentityUnavailable"),+ JumpListStatus.Unsupported => UiText.Get("TasksUnsupported"),+ _ => UiText.Get("TasksReadError")+ };+ items.Add(new MenuItem { Header = message, IsEnabled = false });+ }+ ReplaceJumpListItems(menu, boundary, items);+ }+ catch (OperationCanceledException)+ {+ if (menu.IsOpen && ReferenceEquals(_jumpListLoad, load))+ {+ ReplaceJumpListItems(menu, boundary, [new MenuItem { Header = UiText.Get("TasksTimeout"), IsEnabled = false }]);+ }+ }+ catch (COMException ex)+ {+ Trace.TraceWarning("Shell worker failed: 0x{0:X8}", ex.HResult);+ if (menu.IsOpen && ReferenceEquals(_jumpListLoad, load))+ {+ ReplaceJumpListItems(menu, boundary, [new MenuItem { Header = UiText.Get("TasksServiceError"), IsEnabled = false }]);+ }+ }+ }++ private static void ReplaceJumpListItems(ContextMenu menu, Separator boundary, IReadOnlyList<Control> items)+ {+ foreach (var previous in menu.Items.OfType<Control>().Where(item => item.Tag as string == "JumpListEntry").ToArray())+ menu.Items.Remove(previous);+ var index = menu.Items.IndexOf(boundary);+ foreach (var item in items)+ {+ item.Tag = "JumpListEntry";+ menu.Items.Insert(index++, item);+ }+ boundary.Visibility = items.Count > 0 ? Visibility.Visible : Visibility.Collapsed;+ }++ private static void FocusContextMenu(ContextMenu menu)+ {+ // No SetForegroundWindow here: activating the popup makes Windows move mouse capture, and a+ // WPF menu that loses capture closes itself at once. Outside clicks are handled by WatchMenu.+ menu.Focus();+ }++ private async void DockContextMenu_Closed(object sender, RoutedEventArgs e)+ {+ if (!ReferenceEquals(sender, _openContextMenu)) return;+ _openContextMenu = null;+ _menuWatch.Stop();+ _autoHideController?.EvaluateState();+ _jumpListLoad?.Cancel();+ if (_jumpListSession is { } session)+ {+ _jumpListSession = null;+ await _jumpLists.ReleaseAsync(session);+ }+ }++ private void DockAppContextMenu_Click(object sender, RoutedEventArgs e)+ {+ if (sender is MenuItem { CommandParameter: DockApp app })+ {+ if (_contextTargetWasForeground && FindWindowForExecutable(app.ExecutablePath) is { } window)+ NativeWindowTracker.Activate(window.Handle);+ OpenDockApp(app, toggleIfForeground: _contextTargetWasForeground);+ }+ }++ private void PinDockApp_Click(object sender, RoutedEventArgs e)+ {+ if (sender is not MenuItem { CommandParameter: DockApp app })+ {+ return;+ }++ var (shortcutPath, error) = WindowsTaskbarPinImporter.AddPin(app.Name, app.ExecutablePath, app.LaunchArguments);+ if (error is not null || shortcutPath is null)+ {+ ShowStatus(error ?? "Uygulama sabitlenemedi.");+ return;+ }++ ClearStatus();++ var pinnedApp = new DockApp(app.Name, app.ExecutablePath)+ {+ Icon = app.Icon,+ LaunchArguments = app.LaunchArguments,+ ShortcutPath = shortcutPath,+ HasNotification = app.HasNotification,+ IsForeground = app.IsForeground,+ WindowCount = app.WindowCount+ };++ _runningApps.Remove(app);+ _pinnedApps.Add(pinnedApp);++ SavePinOrder();+ ResizeDockToContent();+ _replacementSession?.RefreshPosition();+ }++ private void SavePinOrder()+ {+ var order = _pinnedApps.Select(app => app.ExecutablePath).ToList();+ var error = _preferences.Save(_preferences.Current with { PinOrder = order });+ if (error is not null) ShowStatus(error);+ }++ private void UnpinDockApp_Click(object sender, RoutedEventArgs e)+ {+ if (sender is MenuItem { CommandParameter: DockApp { IsCustomShortcut: true } shortcut })+ {+ RemoveShortcut(shortcut);+ return;+ }+ if (sender is not MenuItem { CommandParameter: DockApp { ShortcutPath: not null } app })+ {+ return;+ }++ var error = WindowsTaskbarPinImporter.RemovePin(app.ShortcutPath);+ if (error is not null)+ {+ ShowStatus(error);+ return;+ }++ ClearStatus();+ AnimateDockAppRemoval(PinnedApps, _pinnedApps, app, () =>+ {+ SavePinOrder();+ if (_windowTracker is not null)+ {+ UpdateRunningApps(_windowTracker.Snapshot);+ }++ ResizeDockToContent();+ _replacementSession?.RefreshPosition();+ });+ }++ private void CloseDockApp_Click(object sender, RoutedEventArgs e)+ {+ if (sender is not MenuItem { CommandParameter: string executablePath })+ {+ return;+ }++ var (processes, inaccessibleCount) = FindProcessesForExecutable(executablePath);+ var closedCount = 0;+ var failedCount = inaccessibleCount;+ foreach (var process in processes)+ {+ try+ {+ if (process.CloseMainWindow())+ {+ closedCount++;+ }+ else+ {+ failedCount++;+ }+ }+ catch (InvalidOperationException)+ {+ // The process exited while the menu command was running.+ }+ catch (Win32Exception)+ {+ failedCount++;+ }+ finally+ {+ process.Dispose();+ }+ }++ if (closedCount > 0 && failedCount == 0)+ {+ ClearStatus();+ }+ else if (closedCount == 0)+ {+ ShowStatus("Uygulamaya normal kapanma isteği gönderilemedi. Zorla kapatmak için süreç sonlandırma seçeneğini kullanın.");+ }+ else+ {+ ShowStatus("Bazı uygulama süreçlerine normal kapanma isteği gönderilemedi.");+ }+ }++ private void TerminateDockApp_Click(object sender, RoutedEventArgs e)+ {+ if (sender is not MenuItem { CommandParameter: string executablePath })+ {+ return;+ }++ var (processes, inaccessibleCount) = FindProcessesForExecutable(executablePath);+ if (processes.Count == 0)+ {+ ShowStatus(inaccessibleCount == 0+ ? "Uygulamanın çalışan süreci bulunamadı."+ : "Uygulama süreçlerine erişilemiyor; uygulama yöneticisi iznini denetleyin.");+ return;+ }++ var appName = _pinnedApps.FirstOrDefault(app =>+ string.Equals(app.ExecutablePath, executablePath, StringComparison.OrdinalIgnoreCase))?.Name+ ?? Path.GetFileNameWithoutExtension(executablePath);+ var confirmation = MessageBox.Show(+ UiText.Format("TerminatePrompt", appName, processes.Count),+ UiText.Get("TerminateTitle"),+ MessageBoxButton.YesNo,+ MessageBoxImage.Warning,+ MessageBoxResult.No);+ if (confirmation != MessageBoxResult.Yes)+ {+ DisposeProcesses(processes);+ return;+ }++ var terminatedCount = 0;+ var failedCount = inaccessibleCount;+ foreach (var process in processes)+ {+ try+ {+ if (process.Id == Environment.ProcessId)+ {+ failedCount++;+ continue;+ }++ process.Kill(entireProcessTree: true);+ terminatedCount++;+ }+ catch (InvalidOperationException)+ {+ // The process exited while the menu command was running.+ }+ catch (Win32Exception)+ {+ failedCount++;+ }+ finally+ {+ process.Dispose();+ }+ }++ if (failedCount == 0 && terminatedCount > 0)+ {+ ClearStatus();+ }+ else if (terminatedCount == 0)+ {+ ShowStatus("Uygulama süreçleri sonlandırılamadı. Yetkiyi ve uygulamanın tekrar başlamadığını denetleyin.");+ }+ else+ {+ ShowStatus("Bazı uygulama süreçleri sonlandırılamadı.");+ }+ }++ // Widgets live in the top bar now; it sizes itself, the dock only learns whether it has any.+ private void WidgetBar_LayoutInvalidated(object? sender, EventArgs e)+ {+ UpdateTopBarContent();+ if (!WidgetsInDock) return;+ ResizeDockToContent();+ _replacementSession?.RefreshPosition();+ }++ private void WidgetBar_SettingsRequested(object? sender, EventArgs e)+ {+ OpenSettings_Click(this, new RoutedEventArgs());+ _settingsWindow?.SelectWidgetsTab();+ }++ private void OpenSettings_Click(object sender, RoutedEventArgs e)+ {+ if (_settingsWindow is null)+ {+ _settingsWindow = new SettingsWindow(_preferences);+ _settingsWindow.Closed += (_, _) => _settingsWindow = null;+ _settingsWindow.Show();+ }+ if (_settingsWindow.WindowState == WindowState.Minimized) _settingsWindow.WindowState = WindowState.Normal;+ _settingsWindow.Activate();+ }++ private void Preferences_Changed(object? sender, EventArgs e)+ {+ _dockPosition = _preferences.Current.Position;+ _thumbnailPreview.AnimationsEnabled = _preferences.Current.AnimationsEnabled;+ ApplyMagnifyPreference();+ _autoHideController?.SetMode(_preferences.Current.AutoHide);+ ApplyAutoHideHitArea();+ _replacementSession?.UpdateAutoHide(_preferences.Current.AutoHide != AutoHideMode.Disabled);+ _thumbnailPreview.Hide();+ if (_openContextMenu is not null) _openContextMenu.IsOpen = false;+ ResetMagnification();+ _widgetBar.Apply(_preferences.Current.WidgetOptions);+ ApplyDockBell();+ ApplyWidgetPlacement();+ ApplyDockEdge();+ _topBar?.SetPeekEnabled(_preferences.Current.TopBarPeek);+ _deskWidgets?.SettingsChanged();+ ApplyToastHiding();+ ApplyDesktopIcons(_preferences.Current.HideDesktopIcons);+ if (_windowTracker is not null)+ {+ UpdateNotificationBadges(_pinnedApps, _windowTracker.Snapshot);+ UpdateNotificationBadges(_runningApps, _windowTracker.Snapshot);+ }+ if (_replacementSession?.IsActive == true)+ {+ ApplyDockAlignment();+ }+ else+ {+ PositionDock();+ }++ }++ private static MenuItem? FindMenuItem(ItemsControl owner, string tag)+ {+ foreach (var item in owner.Items.OfType<MenuItem>())+ {+ if (string.Equals(item.Tag as string, tag, StringComparison.Ordinal))+ {+ return item;+ }++ var nested = FindMenuItem(item, tag);+ if (nested is not null)+ {+ return nested;+ }+ }++ return null;+ }++ private static void SetMenuItemVisibility(ItemsControl owner, string tag, bool visible)+ {+ var item = FindMenuItem(owner, tag);+ if (item is not null)+ {+ item.Visibility = visible ? Visibility.Visible : Visibility.Collapsed;+ }+ }++ private static void SetSeparatorVisibility(ItemsControl owner, string tag, bool visible)+ {+ var separator = owner.Items.OfType<Separator>()+ .FirstOrDefault(item => string.Equals(item.Tag as string, tag, StringComparison.Ordinal));+ if (separator is not null)+ {+ separator.Visibility = visible ? Visibility.Visible : Visibility.Collapsed;+ }+ }++ private static void SetMenuCommandParameter(ItemsControl owner, string executablePath)+ {+ foreach (var item in owner.Items.OfType<MenuItem>())+ {+ item.CommandParameter = executablePath;+ SetMenuCommandParameter(item, executablePath);+ }+ }++ private static (List<Process> Processes, int InaccessibleCount) FindProcessesForExecutable(string executablePath)+ {+ var matchingProcesses = new List<Process>();+ var inaccessibleCount = 0;+ var processName = Path.GetFileNameWithoutExtension(executablePath);+ foreach (var process in Process.GetProcessesByName(processName))+ {+ try+ {+ if (string.Equals(process.MainModule?.FileName, executablePath, StringComparison.OrdinalIgnoreCase))+ {+ matchingProcesses.Add(process);+ }+ else+ {+ process.Dispose();+ }+ }+ catch (Win32Exception)+ {+ inaccessibleCount++;+ process.Dispose();+ }+ catch (InvalidOperationException)+ {+ process.Dispose();+ }+ }++ return (matchingProcesses, inaccessibleCount);+ }++ private static void DisposeProcesses(IEnumerable<Process> processes)+ {+ foreach (var process in processes)+ {+ process.Dispose();+ }+ }++ /// <summary>+ /// With auto-hide the work area is not reserved, so maximized windows reach the screen bottom.+ /// The full-width strip behind the dock must then let clicks through; only the dock itself and+ /// the thin bottom-edge trigger (which reveals the dock) stay hit-testable.+ /// </summary>+ private void ApplyAutoHideHitArea()+ {+ var autoHide = _preferences.Current.AutoHide != AutoHideMode.Disabled;+ DockHitBackground.Background = autoHide ? null : new SolidColorBrush(Color.FromArgb(1, 0, 0, 0));+ DockHitBackground.IsHitTestVisible = !autoHide;+ DockEdgeTrigger.Visibility = autoHide ? Visibility.Visible : Visibility.Collapsed;+ }++ private void ApplyDockAlignment()+ {+ var alignment = _dockPosition switch+ {+ DockPosition.Left => HorizontalAlignment.Left,+ DockPosition.Center => HorizontalAlignment.Center,+ DockPosition.Right => HorizontalAlignment.Right,+ _ => throw new InvalidOperationException("Dock konumu desteklenmiyor.")+ };++ DockSurface.HorizontalAlignment = alignment;+ _replacementSession?.RefreshPosition();+ }++ private void ApplyTaskbarLayout(Size area)+ {+ _dockArea = area;+ // The dock fills the strip reserved for it (64 DIP when replacing the taskbar) and never more,+ // otherwise the bottom of the window clips it.+ var stripHeight = Math.Max(36, area.Height);+ var bottomGap = stripHeight >= 56 ? 6.0 : stripHeight >= 44 ? 4.0 : 2.0;+ var barHeight = Math.Min(66, stripHeight - bottomGap);+ DockSurface.Margin = new Thickness(12, 0, 12, bottomGap);+ var verticalChrome = DockSurface.Padding.Top + DockSurface.Padding.Bottom+ + DockSurface.BorderThickness.Top + DockSurface.BorderThickness.Bottom;+ var cellHeight = Math.Max(26, barHeight - verticalChrome);+ DockSurface.Height = cellHeight + verticalChrome;+ Application.Current.Resources["DockCellHeight"] = cellHeight;+ // Tile on top, a small strip under it for the running dot.+ // The same tile size as before; the 13 DIP left over is split above and below it (the dot sits below).+ _tileSizeForHeight = Math.Clamp(cellHeight - 13, 22, 50);+ ApplyTileSize(_tileSizeForHeight);+ ResizeDockToContent();+ }++ private void ApplyTileSize(double tile)+ {+ Application.Current.Resources["DockTileSize"] = tile;+ Application.Current.Resources["DockIconSize"] = Math.Round(tile * 0.76);+ Application.Current.Resources["DockTileRadius"] = new CornerRadius(Math.Round(tile * 0.26));+ Application.Current.Resources["DockGlassRadius"] = new CornerRadius(Math.Round(tile * 0.26) + 6);+ _iconSizeForHeight = Math.Round(tile * 0.76);+ AlignDockWidgets();+ if (_appliedEdge is { } edge && edge != Models.DockEdge.Bottom) OrientAllIcons();+ }++ private void OnFullScreenChanged(bool suppressed)+ {+ _topBar?.SetSuppressed(suppressed);+ if (!suppressed) return;+ _widgetBar.ClosePopups();+ _previewCloseTimer.Stop();+ _thumbnailPreview.Hide();+ if (_openContextMenu is not null) _openContextMenu.IsOpen = false;+ ResetMagnification();+ }++ private void ResizeDockToContent()+ {+ // Fit cells explicitly; a Viewbox would scale every control after transient layout changes.+ var availableWidth = _dockArea.Width > 0 ? _dockArea.Width : SystemParameters.PrimaryScreenWidth;+ var count = Math.Max(1, 7 + _pinnedApps.Count + _runningApps.Count); // Start, AppGrid, two desktop tiles, bell, downloads, bin+ var frameWidth = DockSurface.Padding.Left + DockSurface.Padding.Right+ + DockSurface.Margin.Left + DockSurface.Margin.Right + 12;+ var statusWidth = string.IsNullOrEmpty(StatusText.Text) ? 0 : 296;+ WidgetHost.Measure(new System.Windows.Size(double.PositiveInfinity, double.PositiveInfinity));+ var widgetWidth = WidgetHost.DesiredSize.Width / _dockWidgetScale;+ var fullCell = _tileSizeForHeight + 8;+ double cellSize;+ var widgetScale = 1.0;+ if (WidgetsInDock && widgetWidth > 0)+ {+ // Widgets in the dock: when the row does not fit, icons and widgets shrink together, so they stay in+ // proportion (instead of the icons alone getting small next to full-size widgets).+ // Room is kept for the magnified icons pushing their neighbours apart, so the ends never leave the screen.+ var room = availableWidth - frameWidth - statusWidth;+ var spread = ((double)FindResource("DockHoverScale") - 1) * 3.2;+ widgetScale = Math.Clamp(room / (widgetWidth + (count + spread) * fullCell), 0.5, 1);+ room -= spread * fullCell * widgetScale;+ cellSize = Math.Max(24, Math.Min(fullCell * widgetScale, (room - widgetWidth * widgetScale) / count));+ }+ else+ {+ // Tiles sit 8 DIP apart; with many apps and widgets the tiles shrink to fit.+ cellSize = Math.Min(fullCell, Math.Max(24, (availableWidth - frameWidth - statusWidth - widgetWidth) / count));+ }+ SetDockWidgetScale(widgetScale);+ var previousCell = Application.Current.Resources["DockCellSize"] is double cell ? cell : double.NaN;+ if (Math.Abs(previousCell - cellSize) > 0.01)+ {+ // Geometry changed: drop any magnification so it is recomputed against the new cells.+ ResetMagnification();+ Application.Current.Resources["DockCellSize"] = cellSize;+ ApplyTileSize(Math.Max(20, Math.Min(_tileSizeForHeight, cellSize - 6)));+ }+ // A new tile size reaches the tiles through resources: lay them out first, or the row is measured at the old size.+ DockRow.InvalidateMeasure();+ UpdateLayout();+ DockRow.Measure(new System.Windows.Size(double.PositiveInfinity, double.PositiveInfinity));+ // Widgets refresh every second (clock); keep an active magnification and measure around it.+ var magnifiedExtra = GetAllDockButtons()+ .Where(b => b.IsVisible && !double.IsNaN(b.Width))+ .Sum(b => Math.Max(0, b.Width - cellSize));+ var padding = DockSurface.Padding;+ var margin = DockSurface.Margin;+ var border = DockSurface.BorderThickness;+ var desiredWidth = Math.Ceiling(DockRow.DesiredSize.Width - magnifiedExtra + padding.Left + padding.Right+ + margin.Left + margin.Right + border.Left + border.Right);+ var maximumWidth = Math.Max(16, availableWidth);+ var dockWidth = Math.Clamp(desiredWidth, 16, maximumWidth);+ _baseSurfaceWidth = Math.Max(16, dockWidth - margin.Left - margin.Right);+ DockSurface.BeginAnimation(WidthProperty, null);+ DockSurface.Width = Math.Min(Math.Max(16, maximumWidth - margin.Left - margin.Right), _baseSurfaceWidth + magnifiedExtra);+ if (_dockArea.Width <= 0) Width = dockWidth;+ }++ private static bool ExcludeFromTaskSwitcher(nint windowHandle)+ {+ Marshal.SetLastPInvokeError(0);+ var currentStyle = GetWindowLongPtr(windowHandle, GwlExStyle);+ if (currentStyle == 0 && Marshal.GetLastPInvokeError() != 0)+ {+ return false;+ }++ var style = new nint((currentStyle.ToInt64() | WsExToolWindow) & ~WsExAppWindow);+ if (style != currentStyle)+ {+ Marshal.SetLastPInvokeError(0);+ var previousStyle = SetWindowLongPtr(windowHandle, GwlExStyle, style);+ if (previousStyle == 0 && Marshal.GetLastPInvokeError() != 0)+ {+ return false;+ }+ }++ return SetWindowPos(windowHandle, 0, 0, 0, 0, 0,+ SwpNoSize | SwpNoMove | SwpNoZOrder | SwpNoActivate | SwpFrameChanged);+ }++ private void ExitQiDock_Click(object sender, RoutedEventArgs e)+ {+ Close();+ }++ internal string? RestoreWindowsTaskbar()+ {+ var session = _replacementSession;+ if (session is null) return null;+ var error = session.Stop();+ if (session.IsActive) return error;+ session.OperationFailed -= ShowStatus;+ session.LayoutChanged -= ApplyTaskbarLayout;+ session.FullScreenChanged -= OnFullScreenChanged;+ session.Dispose();+ _replacementSession = null;+ _replacementWanted = false;+ return error;+ }++ private void Window_Closing(object? sender, CancelEventArgs e)+ {+ Services.AppLog.Write("Dock penceresi kapanıyor:" + Environment.NewLine + Environment.StackTrace);+ var error = RestoreWindowsTaskbar();+ if (_replacementSession?.IsActive == true)+ {+ e.Cancel = true;+ ShowStatus(error ?? "Windows görev çubuğu geri yüklenemedi. Uygulama açık bırakıldı.");+ return;+ }++ if (error is not null) Trace.TraceWarning(error);+ }++ private void Window_Closed(object? sender, EventArgs e)+ {+ _preferences.Changed -= Preferences_Changed;+ _settingsWindow?.CloseForShutdown();+ _jumpListLoad?.Cancel();+ _jumpListLoad?.Dispose();+ if (_openContextMenu is not null) _openContextMenu.IsOpen = false;+ _openContextMenu = null;+ _magnifiedIcons.Clear();+ ApplyDesktopIcons(false);+ _widgetBar.LayoutInvalidated -= WidgetBar_LayoutInvalidated;+ _widgetBar.SettingsRequested -= WidgetBar_SettingsRequested;+ DisposeTopBar();+ DisposeDesktopWidgets();+ DisposeNotifications();+ DisposeExtras();+ _widgetBar.Dispose();+ _source?.RemoveHook(WindowProc);+ _source = null;++ if (_windowTracker is not null)+ {+ _windowTracker.WindowsChanged -= WindowTracker_WindowsChanged;+ _windowTracker.ForegroundWindowChanged -= WindowTracker_ForegroundWindowChanged;+ _windowTracker.Dispose();+ _windowTracker = null;+ }++ _previewCloseTimer.Stop();+ _previewCloseTimer.Tick -= PreviewCloseTimer_Tick;+ _previewOpenTimer.Stop();+ _thumbnailPreview.PointerEntered -= ThumbnailPreview_PointerEntered;+ _thumbnailPreview.PointerLeft -= ThumbnailPreview_PointerLeft;+ _thumbnailPreview.PreviewClicked -= ThumbnailPreview_PreviewClicked;+ _thumbnailPreview.CloseRequested -= ThumbnailPreview_CloseRequested;+ _thumbnailPreview.Dispose();+ _genie.Dispose();+ _autoHideController?.Dispose();+ _autoHideController = null;+ _jumpLists.Dispose();+ }++ [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW", SetLastError = true)]+ private static extern nint GetWindowLongPtr(nint windowHandle, int index);++ [DllImport("user32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool PostMessage(nint windowHandle, uint message, nint wParam, nint lParam);++ [DllImport("user32.dll")]+ private static extern uint GetWindowThreadProcessId(nint windowHandle, out uint processId);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool SetForegroundWindow(nint windowHandle);++ [DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW", SetLastError = true)]+ private static extern nint SetWindowLongPtr(nint windowHandle, int index, nint value);++ [DllImport("user32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool SetWindowPos(nint windowHandle, nint insertAfter, int x, int y, int width, int height, uint flags);++ [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "RegisterWindowMessageW")]+ private static extern uint RegisterWindowMessage(string message);+}diff --git a/Models/ApplicationJumpList.cs b/Models/ApplicationJumpList.csnew file mode 100644index 0000000..71c9eaf--- /dev/null+++ b/Models/ApplicationJumpList.cs@@ -0,0 +1,8 @@+using System.Windows.Media.Imaging;++namespace QiDock.Models;++public enum JumpListStatus { Ready, Empty, IdentityUnavailable, Unsupported, Unavailable }+public sealed record JumpListEntry(int CommandId, string Title, BitmapSource? Icon, bool IsSeparator = false);+public sealed record JumpListGroup(string Title, IReadOnlyList<JumpListEntry> Entries);+public sealed record ApplicationJumpList(long SessionId, JumpListStatus Status, IReadOnlyList<JumpListGroup> Groups);diff --git a/Models/DockApp.cs b/Models/DockApp.csnew file mode 100644index 0000000..7a2ffee--- /dev/null+++ b/Models/DockApp.cs@@ -0,0 +1,55 @@+using System.Text.Json.Serialization;+using System.ComponentModel;+using System.Runtime.CompilerServices;+using System.Windows.Media.Imaging;++namespace QiDock.Models;++public sealed class DockApp(string name, string executablePath) : INotifyPropertyChanged+{+ public string Name { get; } = name;+ public string ExecutablePath { get; } = executablePath;+ public event PropertyChangedEventHandler? PropertyChanged;+ private bool _hasNotification;+ private bool _isForeground;+ private int _windowCount;+ public string? LaunchArguments { get; init; }++ [JsonIgnore]+ public string? ShortcutPath { get; init; }++ /// <summary>Added by the user from the dock (app, file, folder or web link), kept in settings.</summary>+ [JsonIgnore]+ public bool IsCustomShortcut { get; init; }++ [JsonIgnore]+ public BitmapSource? Icon { get; set; }++ [JsonIgnore]+ public bool HasNotification { get => _hasNotification; set => SetField(ref _hasNotification, value); }++ [JsonIgnore]+ public bool IsRunning => WindowCount > 0;++ [JsonIgnore]+ public bool IsForeground { get => _isForeground; set => SetField(ref _isForeground, value); }++ [JsonIgnore]+ public int WindowCount+ {+ get => _windowCount;+ set+ {+ if (SetField(ref _windowCount, value))+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsRunning)));+ }+ }++ private bool SetField<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)+ {+ if (EqualityComparer<T>.Default.Equals(field, value)) return false;+ field = value;+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));+ return true;+ }+}diff --git a/Models/DockSettings.cs b/Models/DockSettings.csnew file mode 100644index 0000000..5d9059a--- /dev/null+++ b/Models/DockSettings.cs@@ -0,0 +1,49 @@+namespace QiDock.Models;++public enum DockPosition+{+ Left,+ Center,+ Right+}++public enum AppTheme { Dark, Light }+public enum AppLanguage { Turkish, English }+public enum AutoHideMode { Disabled, Smart, Always }++/// <summary>The screen edge the dock stands on.</summary>+public enum DockEdge { Bottom, Top, Left, Right }++/// <summary>Where the widget tiles live: their own strip at the top, or inside the dock left or right of the apps.</summary>+public enum WidgetPlacement { TopBar, DockLeft, DockRight }++/// <summary>A shortcut the user added to the dock: an app, a file, a folder or a web address.</summary>+public sealed record DockShortcut(string Name, string Target, string? Arguments = null);++public sealed record DockSettings(+ DockPosition Position = DockPosition.Center,+ IReadOnlyList<string>? PinOrder = null,+ AppTheme Theme = AppTheme.Dark,+ AppLanguage Language = AppLanguage.Turkish,+ bool AnimationsEnabled = true,+ bool GenieEffectEnabled = true,+ bool HideDesktopIcons = true,+ bool TopBarPeek = true,+ bool PreviewsEnabled = true,+ bool NotificationBadgesEnabled = true,+ AutoHideMode AutoHide = AutoHideMode.Disabled,+ double SurfaceOpacity = 0.9,+ WidgetSettings? Widgets = null,+ IReadOnlyList<DockShortcut>? Shortcuts = null,+ WidgetPlacement WidgetPlacement = WidgetPlacement.TopBar,+ DockEdge Edge = DockEdge.Bottom,+ string Style = "glass",+ bool DockHud = true,+ bool ClaudeActivity = true,+ bool Magnify = false,+ double MagnifyScale = 1.85,+ bool LowMemory = false)+{+ [System.Text.Json.Serialization.JsonIgnore]+ public WidgetSettings WidgetOptions => Widgets ?? new WidgetSettings();+}diff --git a/Models/TrackedWindow.cs b/Models/TrackedWindow.csnew file mode 100644index 0000000..1645836--- /dev/null+++ b/Models/TrackedWindow.cs@@ -0,0 +1,3 @@+namespace QiDock.Models;++public sealed record TrackedWindow(nint Handle, string Title, string? ExecutablePath, bool HasNotification = false);diff --git a/Models/WidgetSettings.cs b/Models/WidgetSettings.csnew file mode 100644index 0000000..6f3e404--- /dev/null+++ b/Models/WidgetSettings.cs@@ -0,0 +1,181 @@+namespace QiDock.Models;++public static class WidgetIds+{+ public const string Media = "media";+ public const string Weather = "weather";+ public const string Clock = "clock";+ public const string AiLimits = "ai";+ public const string QuickControls = "quick";+ public const string System = "system";+ public const string Folder = "folder";+ public const string Search = "search";+ public const string Colors = "colors";+ public const string AppVolume = "appvolume";+ public const string Focus = "focus";+ public const string WorldClock = "worldclock";+ public const string Todo = "todo";+ public const string Tools = "tools";+ public const string Notifications = "notifications";+ public const string ControlCenter = "controlcenter";+ public const string Battery = "battery";+ public const string Profile = "profile";+ public const string Currency = "currency";+ public const string Stopwatch = "stopwatch";+ public const string Note = "note";+ public const string AppGroup = "appgroup";+ public const string Progress = "progress";+ public const string Reminder = "reminder";+ public const string VoiceMemo = "voicememo";+ public const string Tray = "tray";++ public static readonly IReadOnlyList<string> All =+ [Media, Weather, Clock, Battery, AiLimits, System, QuickControls, Folder, Search, Colors, AppVolume, Focus, WorldClock, Todo, Tools,+ Profile, Currency, Stopwatch, Note, AppGroup, Progress, Reminder, VoiceMemo, Tray, Notifications, ControlCenter];++ /// <summary>Widgets of the second batch: they start hidden (in the add list), so the dock does not overflow.</summary>+ public static readonly IReadOnlyList<string> SecondBatch = [Currency, Stopwatch, Note, AppGroup, Progress, Reminder, VoiceMemo];++ /// <summary>Widgets added after the first release; they start hidden in the default profile.</summary>+ public static readonly IReadOnlyList<string> Added = [Folder, Search, Colors, AppVolume, Focus, WorldClock, Todo, Tools, Notifications, ControlCenter, .. SecondBatch];++ /// <summary>+ /// Tiles that repeat something always at hand (the dock bell; Quick controls opens the Control Center).+ /// They start hidden and can still be shown from the widget list.+ /// </summary>+ public static readonly IReadOnlyList<string> Duplicates = [Notifications, ControlCenter];++ /// <summary>Always the last tiles of the row, in this order: the background apps, the battery, then the bell in the corner.</summary>+ public static readonly IReadOnlyList<string> Corner = [Tray, Battery, Notifications];+}++/// <summary>A named widget layout ("Varsayılan", "İş"…): which widgets show, in what order.</summary>+public sealed record WidgetProfile(string Name, IReadOnlyList<string>? Order = null, IReadOnlyList<string>? Hidden = null);++public sealed record TodoItem(string Text, bool Done = false);++/// <summary>An app in the app group: its name and its shell id (as the Start menu's "All apps" lists it).</summary>+public sealed record AppLink(string Name, string Id);++/// <summary>+/// Widget preferences. <see cref="Order"/> and <see cref="Hidden"/> describe the active profile;+/// <see cref="Profiles"/> keeps every profile's layout (the active one is synced on switch).+/// </summary>+public sealed record WidgetSettings(+ IReadOnlyList<string>? Order = null,+ IReadOnlyList<string>? Hidden = null,+ string WeatherCity = "İstanbul",+ string? CalendarFeedUrl = null,+ bool ShowSeconds = true,+ IReadOnlyList<WidgetProfile>? Profiles = null,+ int ActiveProfile = 0,+ string? FolderPath = null,+ IReadOnlyList<string>? Colors = null,+ IReadOnlyList<TodoItem>? Todos = null,+ IReadOnlyList<string>? WorldClocks = null,+ int FocusMinutes = 25,+ bool NotificationBanners = true,+ bool NotificationSound = false,+ bool HideWindowsToasts = true,+ int LayoutRevision = 0,+ string? Note = null,+ IReadOnlyList<AppLink>? AppGroup = null,+ string CurrencyFrom = "USD",+ string CurrencyTo = "TRY",+ string ProgressKind = "month",+ string ReminderKind = "water",+ int ReminderMinutes = 0)+{+ [System.Text.Json.Serialization.JsonIgnore]+ public IReadOnlyList<string> EffectiveOrder+ {+ get+ {+ var known = (Order ?? []).Where(id => WidgetIds.All.Contains(id) && !WidgetIds.Corner.Contains(id)).Distinct().ToList();+ known.AddRange(WidgetIds.All.Where(id => !known.Contains(id) && !WidgetIds.Corner.Contains(id)));+ known.AddRange(WidgetIds.Corner);+ return known;+ }+ }++ public bool IsVisible(string id) => Hidden?.Contains(id) != true;++ [System.Text.Json.Serialization.JsonIgnore]+ public IEnumerable<string> VisibleWidgets => EffectiveOrder.Where(IsVisible);++ [System.Text.Json.Serialization.JsonIgnore]+ public IReadOnlyList<WidgetProfile> EffectiveProfiles =>+ Profiles is { Count: > 0 } ? Profiles : [new WidgetProfile("Varsayılan", Order, Hidden)];++ [System.Text.Json.Serialization.JsonIgnore]+ public int EffectiveActiveProfile => Math.Clamp(ActiveProfile, 0, EffectiveProfiles.Count - 1);++ /// <summary>The profile list with the active profile's current layout written back into it.</summary>+ private List<WidgetProfile> SyncedProfiles()+ {+ var profiles = EffectiveProfiles.ToList();+ var active = EffectiveActiveProfile;+ profiles[active] = profiles[active] with { Order = Order, Hidden = Hidden };+ return profiles;+ }++ public WidgetSettings SwitchProfile(int index)+ {+ var profiles = SyncedProfiles();+ if (index < 0 || index >= profiles.Count) return this;+ var target = profiles[index];+ return this with { Profiles = profiles, ActiveProfile = index, Order = target.Order, Hidden = target.Hidden };+ }++ public WidgetSettings AddProfile(string name)+ {+ var profiles = SyncedProfiles();+ profiles.Add(new WidgetProfile(name, Order, Hidden));+ return this with { Profiles = profiles, ActiveProfile = profiles.Count - 1 };+ }++ public WidgetSettings RenameProfile(int index, string name)+ {+ var profiles = SyncedProfiles();+ if (index < 0 || index >= profiles.Count) return this;+ profiles[index] = profiles[index] with { Name = name };+ return this with { Profiles = profiles };+ }++ public WidgetSettings RemoveProfile(int index)+ {+ var profiles = SyncedProfiles();+ if (profiles.Count <= 1 || index < 0 || index >= profiles.Count) return this;+ var active = EffectiveActiveProfile;+ profiles.RemoveAt(index);+ var next = active == index ? Math.Max(0, index - 1) : active > index ? active - 1 : active;+ var target = profiles[next];+ return this with { Profiles = profiles, ActiveProfile = next, Order = target.Order, Hidden = target.Hidden };+ }++ // Lists compare by content so the settings window can detect real edits.+ public bool Equals(WidgetSettings? other) => other is not null+ && EffectiveOrder.SequenceEqual(other.EffectiveOrder)+ && (Hidden ?? []).OrderBy(x => x).SequenceEqual((other.Hidden ?? []).OrderBy(x => x))+ && string.Equals(WeatherCity, other.WeatherCity, StringComparison.Ordinal)+ && string.Equals(CalendarFeedUrl ?? "", other.CalendarFeedUrl ?? "", StringComparison.Ordinal)+ && ShowSeconds == other.ShowSeconds+ && ActiveProfile == other.ActiveProfile+ && EffectiveProfiles.Select(p => p.Name).SequenceEqual(other.EffectiveProfiles.Select(p => p.Name))+ && string.Equals(FolderPath ?? "", other.FolderPath ?? "", StringComparison.Ordinal)+ && (Colors ?? []).SequenceEqual(other.Colors ?? [])+ && (Todos ?? []).SequenceEqual(other.Todos ?? [])+ && (WorldClocks ?? []).SequenceEqual(other.WorldClocks ?? [])+ && FocusMinutes == other.FocusMinutes+ && NotificationBanners == other.NotificationBanners+ && NotificationSound == other.NotificationSound+ && HideWindowsToasts == other.HideWindowsToasts+ && LayoutRevision == other.LayoutRevision+ && string.Equals(Note ?? "", other.Note ?? "", StringComparison.Ordinal)+ && (AppGroup ?? []).SequenceEqual(other.AppGroup ?? [])+ && CurrencyFrom == other.CurrencyFrom && CurrencyTo == other.CurrencyTo+ && ProgressKind == other.ProgressKind+ && ReminderKind == other.ReminderKind && ReminderMinutes == other.ReminderMinutes;++ public override int GetHashCode() => HashCode.Combine(string.Join(",", EffectiveOrder), WeatherCity, CalendarFeedUrl ?? "", ShowSeconds, ActiveProfile);+}diff --git a/NotificationBanner.cs b/NotificationBanner.csnew file mode 100644index 0000000..4b8bf62--- /dev/null+++ b/NotificationBanner.cs@@ -0,0 +1,428 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Interop;+using System.Windows.Media;+using System.Windows.Media.Animation;+using System.Windows.Media.Imaging;+using System.Windows.Threading;+using QiDock.Services;+using QiDock.Services.Notifications;+using QiDock.Widgets;++namespace QiDock;++/// <summary>+/// Phone-style notification banners: each new Windows notification slides down from above the+/// top center of the screen as a frosted-glass card (app icon, app name, time, title, text),+/// stays for a few seconds and slides back up. Up to three stack, newest on top; the others+/// glide down to make room and up to close a gap. Hovering keeps them; a click opens the+/// notification's app; dragging a card up or its × sends it away. Never takes focus.+/// Each card is its own small window, because the frosted glass covers a whole window.+/// </summary>+public sealed class NotificationBanner+{+ private const int MaxCards = 3;+ private const double Gap = 8;+ private const double TopMargin = 10;+ private static readonly TimeSpan Linger = TimeSpan.FromSeconds(6);++ // Newest first; cards on their way out are no longer in the list.+ private readonly List<BannerCard> _cards = [];+ private bool _hovered;++ /// <summary>A card was clicked: its app has been opened; the owner marks it read.</summary>+ public event Action<AppNotification>? Opened;++ public void Present(IReadOnlyList<AppNotification> notifications)+ {+ if (IsFullScreenAppInFront()) return; // games and videos are not interrupted; the badge still counts+ foreach (var notification in notifications.OrderBy(n => n.Arrived).TakeLast(MaxCards))+ Add(notification);+ }++ public void Close()+ {+ foreach (var card in _cards.ToList()) card.Close();+ _cards.Clear();+ }++ private void Add(AppNotification notification)+ {+ while (_cards.Count >= MaxCards) Dismiss(_cards[^1]);+ var card = new BannerCard(notification);+ card.Dismissed += () => Dismiss(card);+ card.Tapped += () =>+ {+ Dismiss(card);+ NotificationApps.Activate(notification);+ Opened?.Invoke(notification);+ };+ card.HoverChanged += OnHoverChanged;+ card.Timer.Interval = Linger;+ card.Timer.Tick += (_, _) => Dismiss(card);+ _cards.Insert(0, card);+ var area = SystemParameters.WorkArea;+ card.Appear(area.Left + (area.Width - card.Width) / 2, area.Top - 20);+ Arrange();+ if (!_hovered) card.Timer.Start();+ }++ /// <summary>Sends a card up and out of the screen; the rest close the gap.</summary>+ private void Dismiss(BannerCard card)+ {+ if (!_cards.Remove(card)) return;+ card.Timer.Stop();+ card.Leave();+ Arrange();+ OnHoverChanged(); // the card under the pointer may be the one that left+ }++ /// <summary>Glides every card to its place: newest at the top, each below the one before.</summary>+ private void Arrange()+ {+ var top = SystemParameters.WorkArea.Top + TopMargin;+ foreach (var card in _cards)+ {+ card.GlideTo(top);+ top += card.ActualHeight + Gap;+ }+ }++ private void OnHoverChanged()+ {+ var hovered = _cards.Any(c => c.IsMouseOver);+ if (hovered == _hovered) return;+ _hovered = hovered;+ foreach (var card in _cards)+ {+ if (hovered) card.Timer.Stop();+ else+ {+ card.Timer.Interval = TimeSpan.FromSeconds(2.5);+ card.Timer.Start();+ }+ }+ }++ /// <summary>The app icon, the toast's own logo when the app has none, or a bell.</summary>+ internal static FrameworkElement IconFor(AppNotification notification, double size)+ {+ ImageSource? source = NotificationApps.Icon(notification.AppId);+ if (source is null && notification.LogoPath is { } path)+ {+ try+ {+ var image = new BitmapImage();+ image.BeginInit();+ image.UriSource = new Uri(path);+ image.DecodePixelWidth = (int)(size * 2);+ image.CacheOption = BitmapCacheOption.OnLoad;+ image.EndInit();+ image.Freeze();+ source = image;+ }+ catch (Exception ex) when (ex is System.IO.IOException or NotSupportedException or UriFormatException or ArgumentException) { }+ }+ if (source is not null)+ return new Border+ {+ Width = size,+ Height = size,+ CornerRadius = new CornerRadius(size * 0.24),+ Background = new ImageBrush(source) { Stretch = Stretch.Uniform }+ };+ return new Border+ {+ Width = size,+ Height = size,+ CornerRadius = new CornerRadius(size * 0.24),+ Background = Ui.Diagonal(Color.FromRgb(0xFF, 0x5E, 0x57), Color.FromRgb(0xE5, 0x2D, 0x27)),+ Child = Ui.Icon("IconBell", size * 0.5, Brushes.White)+ };+ }++ /// <summary>A game, video or presentation covers the whole monitor.</summary>+ private static bool IsFullScreenAppInFront()+ {+ var window = GetForegroundWindow();+ if (window == 0 || !GetWindowRect(window, out var rect)) return false;+ var className = new System.Text.StringBuilder(64);+ GetClassName(window, className, className.Capacity);+ if (className.ToString() is "Progman" or "WorkerW" or "Shell_TrayWnd") return false;+ var monitor = MonitorFromWindow(window, 2);+ var info = new MonitorInfo { Size = Marshal.SizeOf<MonitorInfo>() };+ if (!GetMonitorInfo(monitor, ref info)) return false;+ return rect.Left <= info.Monitor.Left && rect.Top <= info.Monitor.Top && rect.Right >= info.Monitor.Right && rect.Bottom >= info.Monitor.Bottom;+ }++ [StructLayout(LayoutKind.Sequential)] private struct NativeRect { public int Left, Top, Right, Bottom; }+ [StructLayout(LayoutKind.Sequential)] private struct MonitorInfo { public int Size; public NativeRect Monitor, Work; public uint Flags; }+ [DllImport("user32.dll")] private static extern nint GetForegroundWindow();+ [DllImport("user32.dll")] private static extern bool GetWindowRect(nint window, out NativeRect rect);+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetClassName(nint window, System.Text.StringBuilder name, int capacity);+ [DllImport("user32.dll")] private static extern nint MonitorFromWindow(nint window, uint flags);+ [DllImport("user32.dll")] private static extern bool GetMonitorInfo(nint monitor, ref MonitorInfo info);+}++/// <summary>One banner: a small frosted window that glides into its place and away.</summary>+internal sealed class BannerCard : Window+{+ private const double CardWidth = 360;+ private readonly Border _sheet;+ private readonly FrameworkElement _content;+ private readonly System.Diagnostics.Stopwatch _clock = System.Diagnostics.Stopwatch.StartNew();+ private (double From, double To, double Start, double Duration, IEasingFunction Ease, Action? Done)? _glide;+ private bool _ticking, _placed, _leaving;+ private double _slot;+ private double? _pressedAt, _pressedTop;++ public BannerCard(AppNotification notification)+ {+ WindowStyle = WindowStyle.None;+ ResizeMode = ResizeMode.NoResize;+ GpuTransparency.Prepare(this);+ ShowInTaskbar = false;+ ShowActivated = false;+ Topmost = true;+ Width = CardWidth;+ SizeToContent = SizeToContent.Height;+ WindowStartupLocation = WindowStartupLocation.Manual;+ Title = "QiDock Notification";+ SetResourceReference(FontFamilyProperty, "InterfaceFont");+ UseLayoutRounding = true;+ _content = Layout(notification, out var close);+ _sheet = new Border { Child = _content, Padding = new Thickness(12, 10, 14, 11), CornerRadius = new CornerRadius(16), Background = Brushes.Transparent, Cursor = Cursors.Hand };+ Content = _sheet;+ close.Click += (_, _) => Dismissed?.Invoke();+ MouseEnter += (_, _) =>+ {+ close.BeginAnimation(OpacityProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(140)));+ HoverChanged?.Invoke();+ };+ MouseLeave += (_, _) =>+ {+ close.BeginAnimation(OpacityProperty, new DoubleAnimation(0, TimeSpan.FromMilliseconds(180)));+ HoverChanged?.Invoke();+ };+ // Click opens the app; dragging the card up sends it away.+ _sheet.MouseLeftButtonDown += (_, e) =>+ {+ if (IsInsideButton(e.OriginalSource as DependencyObject) || _leaving) return;+ _pressedAt = CursorY();+ _pressedTop = Top;+ _glide = null;+ _sheet.CaptureMouse();+ e.Handled = true;+ };+ _sheet.MouseMove += (_, _) =>+ {+ if (_pressedAt is not { } start || _pressedTop is not { } top || !_sheet.IsMouseCaptured) return;+ Top = top + Math.Min(0, CursorY() - start);+ };+ _sheet.MouseLeftButtonUp += (_, _) =>+ {+ if (_pressedAt is not { } start) return;+ var dy = CursorY() - start;+ _pressedAt = _pressedTop = null;+ _sheet.ReleaseMouseCapture();+ if (dy < -28) Dismissed?.Invoke();+ else if (Math.Abs(dy) < 6) Tapped?.Invoke();+ else GlideTo(_slot);+ };+ }++#if DEBUG+ /// <summary>Debug snapshot run: hands out the card's content without showing the window.</summary>+ internal FrameworkElement Rehearse()+ {+ Content = null;+ _sheet.Width = CardWidth;+ _content.Opacity = 1;+ return _sheet;+ }+#endif++ public DispatcherTimer Timer { get; } = new(DispatcherPriority.Normal);++ public event Action? Dismissed;+ public event Action? Tapped;+ public event Action? HoverChanged;++ /// <summary>Shows the card just above the top of the screen (its bottom at <paramref name="above"/>).</summary>+ public void Appear(double left, double above)+ {+ Left = left;+ Top = -4000;+ Show();+ UpdateLayout();+ var tint = TryFindResource("PanelFrostTint") is Color color ? color : Color.FromArgb(0xC8, 0x19, 0x1A, 0x1F);+ if (!GpuTransparency.Frost(this, tint))+ {+ _sheet.SetResourceReference(Border.BackgroundProperty, "WidgetPopupFill");+ _sheet.SetResourceReference(Border.BorderBrushProperty, "DockBorderMaterial");+ _sheet.BorderThickness = new Thickness(1);+ }+ Top = above - ActualHeight;+ _content.Opacity = 0;+ }++ /// <summary>Glides to <paramref name="top"/>: the first time with a soft settle, later straight.</summary>+ public void GlideTo(double top)+ {+ if (_leaving) return;+ _slot = top;+ if (_pressedAt is not null) return; // being dragged: it goes back there when let go+ var first = !_placed;+ _placed = true;+ if (first)+ {+ // Start after the first frame, so a slow first draw never eats the start of the slide.+ Motion.AfterFirstFrame(() =>+ {+ if (_leaving) return;+ Glide(_slot, 520, Motion.Settle);+ _content.Opacity = 1;+ _content.BeginAnimation(OpacityProperty, Motion.FromTo(0, 1, 260, Motion.Out, 60));+ });+ return;+ }+ Glide(top, 380, Motion.Out);+ }++ /// <summary>Slides up and out of the screen, fading its content, then closes.</summary>+ public void Leave()+ {+ if (_leaving) return;+ _leaving = true;+ IsHitTestVisible = false;+ Timer.Stop();+ _content.BeginAnimation(OpacityProperty, new DoubleAnimation(0, TimeSpan.FromMilliseconds(220)) { EasingFunction = Motion.In });+ Glide(SystemParameters.WorkArea.Top - ActualHeight - 30, 320, Motion.In, Close);+ }++ private void Glide(double to, double milliseconds, IEasingFunction ease, Action? done = null)+ {+ _glide = (Top, to, _clock.Elapsed.TotalMilliseconds, milliseconds, ease, done);+ if (_ticking) return;+ _ticking = true;+ CompositionTarget.Rendering += OnFrame;+ }++ private void OnFrame(object? sender, EventArgs e)+ {+ if (_glide is not { } glide)+ {+ _ticking = false;+ CompositionTarget.Rendering -= OnFrame;+ return;+ }+ var t = Math.Clamp((_clock.Elapsed.TotalMilliseconds - glide.Start) / glide.Duration, 0, 1);+ Top = Math.Round(glide.From + (glide.To - glide.From) * glide.Ease.Ease(t), 2);+ if (t < 1) return;+ _glide = null;+ glide.Done?.Invoke();+ }++ protected override void OnClosed(EventArgs e)+ {+ base.OnClosed(e);+ _glide = null;+ if (_ticking) CompositionTarget.Rendering -= OnFrame;+ _ticking = false;+ Timer.Stop();+ }++ /// <summary>The pointer's height on screen in this window's units.</summary>+ private double CursorY()+ {+ GetCursorPos(out var point);+ var scale = PresentationSource.FromVisual(this)?.CompositionTarget?.TransformFromDevice.M22 ?? 1;+ return point.Y * scale;+ }++ private static FrameworkElement Layout(AppNotification notification, out Button close)+ {+ var icon = new Border { Width = 34, Height = 34, CornerRadius = new CornerRadius(8), VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(0, 1, 11, 0) };+ icon.Child = NotificationBanner.IconFor(notification, 34);++ var app = Ui.Text(NotificationApps.Name(notification.AppId), 11, FontWeights.SemiBold, "TextSecondary");+ app.TextTrimming = TextTrimming.CharacterEllipsis;+ var time = Ui.Text(Ui.Ago(notification.Arrived.ToLocalTime()), 11, FontWeights.Medium, "TextSecondary");+ time.Margin = new Thickness(8, 0, 0, 0);+ var header = new DockPanel { LastChildFill = true };+ DockPanel.SetDock(time, Dock.Right);+ header.Children.Add(time);+ header.Children.Add(app);++ var title = Ui.Text(notification.Title, 13, FontWeights.SemiBold);+ title.TextTrimming = TextTrimming.CharacterEllipsis;+ title.Margin = new Thickness(0, 1, 0, 0);+ var text = new StackPanel();+ text.Children.Add(header);+ text.Children.Add(title);+ if (notification.Body.Length > 0)+ {+ var body = Ui.Text(notification.Body, 12.5);+ body.TextWrapping = TextWrapping.Wrap;+ body.TextTrimming = TextTrimming.CharacterEllipsis;+ body.MaxHeight = 12.5 * 1.4 * 3;+ text.Children.Add(body);+ }++ var row = new DockPanel();+ DockPanel.SetDock(icon, Dock.Left);+ row.Children.Add(icon);+ row.Children.Add(text);++ close = new Button { Width = 20, Height = 20, Content = Ui.Icon("IconClose", 8), ToolTip = UiText.Get("NotificationDismiss"), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(-6, -5, 0, 0), Opacity = 0, Cursor = Cursors.Hand };+ close.Template = CloseTemplate();+ var content = new Grid();+ content.Children.Add(row);+ content.Children.Add(close);+ return content;+ }++ private static ControlTemplate CloseTemplate()+ {+ var template = new ControlTemplate(typeof(Button));+ var border = new FrameworkElementFactory(typeof(Border));+ border.SetValue(Border.CornerRadiusProperty, new CornerRadius(10));+ border.SetResourceReference(Border.BackgroundProperty, "PanelTileHover");+ var presenter = new FrameworkElementFactory(typeof(ContentPresenter));+ presenter.SetValue(HorizontalAlignmentProperty, HorizontalAlignment.Center);+ presenter.SetValue(VerticalAlignmentProperty, VerticalAlignment.Center);+ border.AppendChild(presenter);+ template.VisualTree = border;+ return template;+ }++ private static bool IsInsideButton(DependencyObject? node)+ {+ for (; node is not null; node = node is Visual or System.Windows.Media.Media3D.Visual3D ? VisualTreeHelper.GetParent(node) : LogicalTreeHelper.GetParent(node))+ if (node is Button) return true;+ return false;+ }++ protected override void OnSourceInitialized(EventArgs e)+ {+ base.OnSourceInitialized(e);+ if (PresentationSource.FromVisual(this) is not HwndSource source) return;+ GpuTransparency.Apply(this);+ // Tool window that never activates: clicking a banner must not steal focus from the user's app.+ var style = GetWindowLongPtr(source.Handle, -20).ToInt64();+ SetWindowLongPtr(source.Handle, -20, new nint((style | 0x00000080 | 0x08000000) & ~0x00040000));+ source.AddHook((nint _, int message, nint _, nint _, ref bool handled) =>+ {+ if (message != 0x0021 /* WM_MOUSEACTIVATE */) return 0;+ handled = true;+ return 3; // MA_NOACTIVATE+ });+ }++ [StructLayout(LayoutKind.Sequential)] private struct NativePoint { public int X, Y; }+ [DllImport("user32.dll")] private static extern bool GetCursorPos(out NativePoint point);+ [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/NotificationCenter.cs b/NotificationCenter.csnew file mode 100644index 0000000..a7dbf2a--- /dev/null+++ b/NotificationCenter.cs@@ -0,0 +1,548 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Media.Animation;+using System.Windows.Media.Effects;+using QiDock.Models;+using QiDock.Services;+using QiDock.Services.Notifications;+using QiDock.Widgets;++namespace QiDock;++/// <summary>+/// The notification center: a narrow column of cards along the right edge, only as tall as what+/// is in it. Several notifications of one app sit in a single stack (the newest card with the+/// others peeking out below); clicking the stack fans it out, "Daha az göster" folds it back.+/// Clicking a single card opens its app; the × on hover slides it away. Every change moves the+/// cards smoothly from where they were to where they go.+/// </summary>+public sealed class NotificationCenter : EdgePanel+{+ private const int ExpandedLimit = 8;+ private static NotificationCenter? _shared;++ /// <summary>The panel (created on first use, on the UI thread).</summary>+ public static NotificationCenter Shared => _shared ??= new NotificationCenter();+ public static bool IsCreated => _shared is not null;++ /// <summary>Supplied by the main window: current settings and saving a change.</summary>+ public static Func<WidgetSettings> Settings { get; set; } = () => new WidgetSettings();+ public static Action<Func<WidgetSettings, WidgetSettings>> Update { get; set; } = _ => { };++ private readonly HashSet<string> _expanded = new(StringComparer.OrdinalIgnoreCase);+ private readonly Dictionary<string, Origin> _origins = new(StringComparer.Ordinal);+ private readonly HashSet<string> _showAll = new(StringComparer.OrdinalIgnoreCase);+ // Cards sliding out: rebuilt invisible (still taking their place) until they are really gone.+ private readonly HashSet<string> _leaving = new(StringComparer.Ordinal);+ private bool _quiet;+ private bool _showOptions;++ private NotificationCenter() : base(330, "QiDock Notification Center")+ {+ HeightShare = 0.62;+ NotificationFeed.Shared.Changed += () =>+ {+ if (IsOpen && !_quiet) Refresh();+ };+ IsVisibleChanged += (_, _) =>+ {+ if (IsVisible) return;+ _showOptions = false;+ _expanded.Clear();+ _showAll.Clear();+ _leaving.Clear();+ };+ }++ /// <summary>Marks everything read; nothing here shows unread state, so the cards are not rebuilt for it.</summary>+ protected override void OnOpened()+ {+ _quiet = true;+ try { NotificationFeed.Shared.MarkAllRead(); }+ finally { _quiet = false; }+ }++ /// <summary>Rebuilds with movement; cards that appear come out of the place recorded in <see cref="_origins"/>.</summary>+ private void Refresh()+ {+ Rebuild(key => _origins.TryGetValue(key, out var source) ? source : null);+ _origins.Clear();+ }++ // ---- Content ---------------------------------------------------------------------------++ protected override void Build()+ {+ var feed = NotificationFeed.Shared;+ Cards.Children.Clear();+ Header.Content = TitleRow(feed);+ Header.Visibility = Visibility.Visible;+ if (_showOptions) Cards.Children.Add(Keyed("options", Options()));++ if (!feed.Available || feed.Items.Count == 0)+ {+ Cards.Children.Add(Keyed("empty", EmptyCard(!feed.Available ? UiText.Get("NotificationsUnavailable")+ : UiText.Get(Settings().NotificationBanners ? "NotificationsEmpty" : "NotificationsEmptyQuiet"))));+ return;+ }+ var groups = feed.Items.GroupBy(n => n.AppId, StringComparer.OrdinalIgnoreCase)+ .OrderByDescending(g => g.Max(n => n.Arrived));+ foreach (var group in groups)+ {+ var items = group.OrderByDescending(n => n.Arrived).ToList();+ if (items.Count == 1)+ Cards.Children.Add(Keyed(NoteKey(items[0]), Spaced(Card(items[0]), 6)));+ else if (_expanded.Contains(group.Key))+ {+ Cards.Children.Add(Keyed("gh:" + group.Key, GroupHeader(group.Key, items)));+ var limit = _showAll.Contains(group.Key) ? 60 : ExpandedLimit;+ foreach (var n in items.Take(limit)) Cards.Children.Add(Keyed(NoteKey(n), Spaced(Card(n), 6)));+ if (items.Count > limit)+ Cards.Children.Add(Keyed("rest:" + group.Key, Spaced(MoreLine(group.Key, items.Count - limit))));+ }+ else+ Cards.Children.Add(Keyed("g:" + group.Key, Stack(group.Key, items)));+ }+ }++ private static string NoteKey(AppNotification n) => "n:" + n.Id;++ private FrameworkElement Keyed(string key, FrameworkElement element)+ {+ element.Tag = key;+ if (_leaving.Contains(key))+ {+ element.Opacity = 0;+ element.IsHitTestVisible = false;+ }+ return element;+ }++ /// <summary>A slim capsule: the title, "Temizle" and the gear.</summary>+ private FrameworkElement TitleRow(NotificationFeed feed)+ {+ var title = Ui.Text(UiText.Get("NotificationsTitle"), 14, FontWeights.SemiBold);+ title.VerticalAlignment = VerticalAlignment.Center;+ title.Margin = new Thickness(4, 0, 0, 0);+ var buttons = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };+ if (feed.Items.Count > 0)+ {+ var clear = Capsule(Ui.Text(UiText.Get("NotificationsClear"), 11.5, FontWeights.SemiBold, "TextSecondary"), ClearEverything);+ clear.Height = 24;+ clear.Margin = new Thickness(0, 0, 4, 0);+ buttons.Children.Add(clear);+ }+ var gear = Capsule(Ui.Icon("IconSettings", 12, brushKey: _showOptions ? "TextPrimary" : "TextSecondary"), () =>+ {+ _showOptions = !_showOptions;+ Refresh();+ }, UiText.Get("NotificationsOptions"));+ gear.Height = 24;+ gear.Padding = new Thickness(0);+ gear.Width = 24;+ buttons.Children.Add(gear);+ var row = new DockPanel { Width = CardWidth, Margin = new Thickness(0, 0, 0, 0) };+ DockPanel.SetDock(buttons, Dock.Right);+ row.Children.Add(buttons);+ row.Children.Add(title);+ return row;+ }++ private FrameworkElement Options()+ {+ var settings = Settings();+ var list = new StackPanel();+ list.Children.Add(SwitchRow(UiText.Get("NotificationsBanners"), UiText.Get("NotificationsBannersHint"), settings.NotificationBanners, s => s with { NotificationBanners = !s.NotificationBanners }));+ list.Children.Add(SwitchRow(UiText.Get("NotificationsHideWindows"), UiText.Get("NotificationsHideWindowsHint"), settings.HideWindowsToasts, s => s with { HideWindowsToasts = !s.HideWindowsToasts }, settings.NotificationBanners));+ list.Children.Add(SwitchRow(UiText.Get("NotificationsSound"), UiText.Get("NotificationsSoundHint"), settings.NotificationSound, s => s with { NotificationSound = !s.NotificationSound }));+ var link = new Button { Content = UiText.Get("NotificationsWindowsSettings"), HorizontalAlignment = HorizontalAlignment.Left, Margin = new Thickness(-4, 2, 0, 0) };+ link.SetResourceReference(FrameworkElement.StyleProperty, "WidgetLinkButton");+ link.Click += (_, _) =>+ {+ Close(animated: true);+ Ui.Open("ms-settings:notifications");+ };+ list.Children.Add(link);+ return Spaced(Glass(list, new Thickness(12, 8, 10, 6)), 6);+ }++ private FrameworkElement SwitchRow(string title, string hint, bool on, Func<WidgetSettings, WidgetSettings> change, bool enabled = true)+ {+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 12, 0) };+ text.Children.Add(Ui.Text(title, 12.5, FontWeights.SemiBold));+ var detail = Ui.Text(hint, 11, brushKey: "TextSecondary");+ detail.TextWrapping = TextWrapping.Wrap;+ text.Children.Add(detail);+ var toggle = Switch(on, () =>+ {+ Update(change);+ // Let the knob finish its slide before the card is redrawn.+ Dispatcher.BeginInvoke(() =>+ {+ if (IsOpen) Refresh();+ }, System.Windows.Threading.DispatcherPriority.Background);+ });+ var row = new DockPanel { Margin = new Thickness(0, 3, 0, 5), IsEnabled = enabled, Opacity = enabled ? 1 : 0.45 };+ DockPanel.SetDock(toggle, Dock.Right);+ row.Children.Add(toggle);+ row.Children.Add(text);+ return row;+ }++ /// <summary>A phone-style switch whose knob glides across and whose track tints green.</summary>+ private FrameworkElement Switch(bool on, Action toggle)+ {+ var shift = new TranslateTransform(on ? 16 : 0, 0);+ var knob = new Border { Width = 18, Height = 18, CornerRadius = new CornerRadius(9), Background = Brushes.White, HorizontalAlignment = HorizontalAlignment.Left, Margin = new Thickness(2), RenderTransform = shift, Effect = new DropShadowEffect { BlurRadius = 4, ShadowDepth = 1, Opacity = 0.3, Direction = 270 } };+ var green = (Color)ColorConverter.ConvertFromString("#FF34C759");+ var gray = (Color)ColorConverter.ConvertFromString("#FF5A5A5E");+ var fill = new SolidColorBrush(on ? green : gray);+ var track = new Border { Width = 38, Height = 22, CornerRadius = new CornerRadius(11), Background = fill, Child = knob, Cursor = Cursors.Hand, VerticalAlignment = VerticalAlignment.Center };+ var busy = false;+ track.MouseLeftButtonUp += (_, e) =>+ {+ e.Handled = true;+ if (busy) return;+ busy = true;+ var slide = new DoubleAnimation(on ? 0 : 16, TimeSpan.FromMilliseconds(220)) { EasingFunction = Motion.Out };+ slide.Completed += (_, _) => toggle();+ fill.BeginAnimation(SolidColorBrush.ColorProperty, new ColorAnimation(on ? gray : green, TimeSpan.FromMilliseconds(200)));+ shift.BeginAnimation(TranslateTransform.XProperty, slide);+ };+ return track;+ }++ private FrameworkElement EmptyCard(string text)+ {+ var icon = Ui.Icon("IconBell", 18, brushKey: "TextSecondary");+ icon.VerticalAlignment = VerticalAlignment.Center;+ icon.Margin = new Thickness(0, 0, 10, 0);+ var label = Ui.Text(text, 12.5, brushKey: "TextSecondary");+ label.TextWrapping = TextWrapping.Wrap;+ label.VerticalAlignment = VerticalAlignment.Center;+ var row = new DockPanel();+ DockPanel.SetDock(icon, Dock.Left);+ row.Children.Add(icon);+ row.Children.Add(label);+ return Spaced(Glass(row, new Thickness(14, 12, 14, 12)), 0);+ }++ /// <summary>One notification: icon, app and time, title, two lines of text. × on hover.</summary>+ private Border Card(AppNotification notification, int more = 0, IReadOnlyList<AppNotification>? stack = null)+ {+ var icon = NotificationBanner.IconFor(notification, 28);+ icon.VerticalAlignment = VerticalAlignment.Top;+ icon.Margin = new Thickness(0, 2, 10, 0);+ var app = Ui.Text(NotificationApps.Name(notification.AppId), 10.5, FontWeights.SemiBold, "TextSecondary");+ app.TextTrimming = TextTrimming.CharacterEllipsis;+ var time = Ui.Text(Ui.Ago(notification.Arrived.ToLocalTime()), 10.5, brushKey: "TextSecondary");+ time.Margin = new Thickness(8, 0, 0, 0);+ var header = new DockPanel();+ DockPanel.SetDock(time, Dock.Right);+ header.Children.Add(time);+ if (more > 0)+ {+ var chip = new Border+ {+ CornerRadius = new CornerRadius(7),+ Padding = new Thickness(6, 0, 6, 1),+ Margin = new Thickness(8, 0, 0, 0),+ VerticalAlignment = VerticalAlignment.Center,+ Child = Ui.Text(UiText.Format("NotificationsMore", more), 10, FontWeights.SemiBold, "TextSecondary")+ };+ chip.SetResourceReference(Border.BackgroundProperty, "SurfaceHover");+ DockPanel.SetDock(chip, Dock.Right);+ header.Children.Add(chip);+ }+ header.Children.Add(app);+ var text = new StackPanel();+ text.Children.Add(header);+ var title = Ui.Text(notification.Title, 12.5, FontWeights.SemiBold);+ title.TextTrimming = TextTrimming.CharacterEllipsis;+ text.Children.Add(title);+ if (notification.Body.Length > 0)+ {+ var body = Ui.Text(notification.Body, 12);+ body.TextWrapping = TextWrapping.Wrap;+ body.TextTrimming = TextTrimming.CharacterEllipsis;+ body.MaxHeight = 12 * 1.35 * 2;+ text.Children.Add(body);+ }+ var row = new DockPanel();+ DockPanel.SetDock(icon, Dock.Left);+ row.Children.Add(icon);+ row.Children.Add(text);++ var layout = new Grid();+ layout.Children.Add(row);+ Border? card = null;+ var dismiss = CloseBadge(() =>+ {+ if (card is null) return;+ // The × of a stack clears the whole stack.+ var outer = Outer(card);+ var key = (outer as FrameworkElement)?.Tag as string;+ if (key is null || !_leaving.Add(key)) return;+ SlideAway(outer, () =>+ {+ NotificationFeed.Shared.RemoveMany(stack ?? [notification]);+ _leaving.Remove(key);+ });+ });+ layout.Children.Add(dismiss);+ card = Glass(layout, new Thickness(10, 8, 12, 9));+ card.Cursor = Cursors.Hand;+ card.MouseEnter += (_, _) => dismiss.BeginAnimation(OpacityProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(140)));+ card.MouseLeave += (_, _) => dismiss.BeginAnimation(OpacityProperty, new DoubleAnimation(0, TimeSpan.FromMilliseconds(180)));+ card.MouseLeftButtonUp += (_, e) =>+ {+ if (e.Handled) return;+ Close(animated: true);+ NotificationApps.Activate(notification);+ NotificationFeed.Shared.Remove(notification);+ };+ Pressable(card);+ return card;+ }++ /// <summary>The top-level element that holds <paramref name="element"/> (what the panel moves).</summary>+ private UIElement Outer(FrameworkElement element)+ {+ DependencyObject current = element;+ while (VisualTreeHelper.GetParent(current) is { } parent && !ReferenceEquals(parent, Cards)) current = parent;+ return (UIElement)current;+ }++ /// <summary>Shrinks a touch while pressed, like a key going down.</summary>+ private static void Pressable(FrameworkElement element)+ {+ var scale = new ScaleTransform(1, 1);+ element.RenderTransformOrigin = new Point(0.5, 0.5);+ // The panel moves cards through their translate; the press only scales.+ element.RenderTransform = new TransformGroup { Children = { scale, new TranslateTransform() } };+ void To(double value, double ms)+ {+ var animation = new DoubleAnimation(value, TimeSpan.FromMilliseconds(ms)) { EasingFunction = Motion.Out };+ scale.BeginAnimation(ScaleTransform.ScaleXProperty, animation);+ scale.BeginAnimation(ScaleTransform.ScaleYProperty, animation);+ }+ element.PreviewMouseLeftButtonDown += (_, e) =>+ {+ if (e.OriginalSource is DependencyObject source && IsInBadge(source)) return; // the × doesn't press the card+ To(0.975, 90);+ };+ element.MouseLeave += (_, _) => To(1, 160);+ element.PreviewMouseLeftButtonUp += (_, _) => To(1, 160);+ }++ /// <summary>The round × that appears on a card's top-left corner on hover.</summary>+ private static Border CloseBadge(Action click)+ {+ var badge = new Border+ {+ Width = 20,+ Height = 20,+ CornerRadius = new CornerRadius(10),+ BorderThickness = new Thickness(1),+ HorizontalAlignment = HorizontalAlignment.Left,+ VerticalAlignment = VerticalAlignment.Top,+ Margin = new Thickness(-13, -11, 0, 0),+ Opacity = 0,+ Child = Ui.Icon("IconClose", 8),+ ToolTip = UiText.Get("NotificationDismiss"),+ Tag = "badge",+ Cursor = Cursors.Hand+ };+ badge.SetResourceReference(Border.BackgroundProperty, "WidgetPopupFill");+ badge.SetResourceReference(Border.BorderBrushProperty, "DockBorderMaterial");+ ((FrameworkElement)badge.Child).HorizontalAlignment = HorizontalAlignment.Center;+ ((FrameworkElement)badge.Child).VerticalAlignment = VerticalAlignment.Center;+ badge.PreviewMouseLeftButtonDown += (_, e) => e.Handled = true; // no press shrink+ badge.MouseLeftButtonUp += (_, e) =>+ {+ e.Handled = true;+ click();+ };+ return badge;+ }++ /// <summary>Several notifications of one app: the newest card with one or two narrower lips peeking out below.</summary>+ private FrameworkElement Stack(string appId, List<AppNotification> items)+ {+ var top = Card(items[0], items.Count - 1, items);+ var host = new StackPanel { Margin = new Thickness(0, 0, 0, 6), Cursor = Cursors.Hand };+ host.Children.Add(top);+ var lips = new List<TranslateTransform>();+ for (var layer = 1; layer <= Math.Min(2, items.Count - 1); layer++)+ {+ var shift = new TranslateTransform();+ var lip = new Border+ {+ Height = layer == 1 ? 7 : 6,+ Width = CardWidth - layer * 28,+ CornerRadius = new CornerRadius(0, 0, 9, 9),+ HorizontalAlignment = HorizontalAlignment.Center,+ Opacity = layer == 1 ? 0.75 : 0.45,+ RenderTransform = shift+ };+ lip.SetResourceReference(Border.BackgroundProperty, "PanelTile");+ host.Children.Add(lip);+ lips.Add(shift);+ }+ // Hovering spreads the lips a little, hinting that the stack opens.+ host.MouseEnter += (_, _) =>+ {+ for (var i = 0; i < lips.Count; i++) lips[i].BeginAnimation(TranslateTransform.YProperty, new DoubleAnimation(2 * (i + 1), TimeSpan.FromMilliseconds(200)) { EasingFunction = Motion.Out });+ };+ host.MouseLeave += (_, _) =>+ {+ foreach (var shift in lips) shift.BeginAnimation(TranslateTransform.YProperty, new DoubleAnimation(0, TimeSpan.FromMilliseconds(220)) { EasingFunction = Motion.Out });+ };+ // Clicking a stack fans it out instead of opening the newest notification.+ host.PreviewMouseLeftButtonUp += (_, e) =>+ {+ if (e.OriginalSource is DependencyObject source && IsInBadge(source)) return;+ e.Handled = true;+ Expand(appId, items);+ };+ return host;+ }++ private void Expand(string appId, List<AppNotification> items)+ {+ _expanded.Add(appId);+ var stack = "g:" + appId;+ _origins["gh:" + appId] = new Origin(stack);+ foreach (var n in items.Take(ExpandedLimit)) _origins[NoteKey(n)] = new Origin(stack);+ _origins[NoteKey(items[0])] = new Origin(stack, Continues: true); // the stack's top card itself+ _origins["rest:" + appId] = new Origin(stack);+ Refresh();+ }++ /// <summary>Folds an opened group: its cards glide up into the first one, then the stack takes their place.</summary>+ private void Collapse(string appId, List<AppNotification> items)+ {+ if (!_expanded.Remove(appId)) return;+ var keys = items.Select(NoteKey).Append("rest:" + appId).Append("gh:" + appId).ToHashSet(StringComparer.Ordinal);+ var target = NoteKey(items[0]);+ FrameworkElement? first = null;+ foreach (UIElement child in Cards.Children)+ if (child is FrameworkElement { Tag: string key } element && key == target) first = element;+ var anchor = first?.TranslatePoint(new Point(0, 0), Cards).Y ?? 0;+ var any = false;+ foreach (UIElement child in Cards.Children)+ {+ if (child is not FrameworkElement { Tag: string key } element || !keys.Contains(key) || key == target) continue;+ var y = element.TranslatePoint(new Point(0, 0), Cards).Y;+ Motion.Shift(element).BeginAnimation(TranslateTransform.YProperty, new DoubleAnimation(anchor - y, TimeSpan.FromMilliseconds(200)) { EasingFunction = Motion.In });+ element.BeginAnimation(OpacityProperty, new DoubleAnimation(0, TimeSpan.FromMilliseconds(170)));+ element.IsHitTestVisible = false;+ any = true;+ }+ _origins["g:" + appId] = new Origin(target, Continues: true);+ if (!any)+ {+ Refresh();+ return;+ }+ var wait = new System.Windows.Threading.DispatcherTimer { Interval = TimeSpan.FromMilliseconds(170) };+ wait.Tick += (_, _) =>+ {+ wait.Stop();+ if (IsOpen) Refresh();+ };+ wait.Start();+ }++ private static bool IsInBadge(DependencyObject node)+ {+ for (var current = node; current is not null; current = current is Visual ? VisualTreeHelper.GetParent(current) : LogicalTreeHelper.GetParent(current))+ if (current is FrameworkElement { Tag: "badge" }) return true;+ return false;+ }++ /// <summary>The opened group's title row: app name on the left, "Daha az göster" and × capsules on the right.</summary>+ private FrameworkElement GroupHeader(string appId, List<AppNotification> items)+ {+ var name = Capsule(Ui.Text(NotificationApps.Name(appId), 12, FontWeights.SemiBold), () => Collapse(appId, items));+ name.HorizontalAlignment = HorizontalAlignment.Left;+ var less = Capsule(Ui.Text(UiText.Get("NotificationsShowLess"), 11.5, FontWeights.SemiBold, "TextSecondary"), () => Collapse(appId, items));+ less.Margin = new Thickness(0, 0, 4, 0);+ var clear = Capsule(Ui.Icon("IconClose", 9), () => DismissMany(items.Select(NoteKey).Append("gh:" + appId).Append("rest:" + appId), () => NotificationFeed.Shared.RemoveMany(items)), UiText.Get("NotificationsClear"));+ clear.Padding = new Thickness(0);+ clear.Width = 26;+ var buttons = new StackPanel { Orientation = Orientation.Horizontal };+ buttons.Children.Add(less);+ buttons.Children.Add(clear);+ var row = new DockPanel { Width = CardWidth, Margin = new Thickness(0, 2, 0, 6) };+ DockPanel.SetDock(buttons, Dock.Right);+ row.Children.Add(buttons);+ row.Children.Add(name);+ return row;+ }++ /// <summary>"+N daha" under an opened group: shows the rest of it.</summary>+ private FrameworkElement MoreLine(string appId, int count)+ {+ var capsule = Capsule(Ui.Text(UiText.Format("NotificationsMore", count), 11, FontWeights.SemiBold, "TextSecondary"), () =>+ {+ _showAll.Add(appId);+ Refresh();+ });+ capsule.Height = 24;+ capsule.HorizontalAlignment = HorizontalAlignment.Center;+ return capsule;+ }++ /// <summary>"Temizle": every card slides out, one after another, then the list is emptied.</summary>+ private void ClearEverything()+ {+ var keys = new List<string>();+ foreach (UIElement child in Cards.Children)+ if (child is FrameworkElement { Tag: string key } && key is not "options") keys.Add(key);+ DismissMany(keys, NotificationFeed.Shared.ClearAll);+ }++ private void DismissMany(IEnumerable<string> keys, Action done)+ {+ // Cards already on their way out are left alone (a second click changes nothing).+ var wanted = keys.Where(key => !_leaving.Contains(key)).ToHashSet(StringComparer.Ordinal);+ if (wanted.Count == 0) return;+ _leaving.UnionWith(wanted);+ var delay = 0;+ var moving = 0;+ foreach (UIElement child in Cards.Children)+ {+ if (child is not FrameworkElement { Tag: string key } element || !wanted.Contains(key)) continue;+ var start = delay;+ var slide = Motion.FromTo(0, 110, 260, Motion.In, start);+ slide.FillBehavior = FillBehavior.HoldEnd;+ var fade = Motion.FromTo(1, 0, 220, Motion.In, start + 30);+ fade.FillBehavior = FillBehavior.HoldEnd;+ Motion.Shift(element).BeginAnimation(TranslateTransform.XProperty, slide);+ element.BeginAnimation(OpacityProperty, fade);+ element.IsHitTestVisible = false;+ delay = Math.Min(delay + 35, 210);+ moving++;+ }+ void Finish()+ {+ done();+ _leaving.ExceptWith(wanted);+ }+ if (moving == 0)+ {+ Finish();+ return;+ }+ var wait = new System.Windows.Threading.DispatcherTimer { Interval = TimeSpan.FromMilliseconds(delay + 230) };+ wait.Tick += (_, _) =>+ {+ wait.Stop();+ Finish();+ };+ wait.Start();+ }+}diff --git a/Overlays.cs b/Overlays.csnew file mode 100644index 0000000..3b50222--- /dev/null+++ b/Overlays.cs@@ -0,0 +1,731 @@+using System.Globalization;+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Interop;+using System.Windows.Media;+using System.Windows.Media.Animation;+using System.Windows.Media.Effects;+using System.Windows.Media.Imaging;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;+using QiDock.Services.Notifications;+using QiDock.Widgets;++namespace QiDock;++/// <summary>+/// A full-screen layer over everything (AppGrid, QuickSearch, Window Overview): fades in, takes+/// the keyboard, and goes away on Esc, a click on the empty background or switching to another app.+/// </summary>+public abstract class OverlayWindow : Window+{+ private static OverlayWindow? _open;+ private bool _dismissing;+ protected readonly Grid Root = new();++ protected OverlayWindow(Brush background)+ {+ WindowStyle = WindowStyle.None;+ ResizeMode = ResizeMode.NoResize;+ GpuTransparency.Prepare(this);+ ShowInTaskbar = false;+ Topmost = true;+ WindowStartupLocation = WindowStartupLocation.Manual;+ Left = 0;+ Top = 0;+ Width = SystemParameters.PrimaryScreenWidth;+ Height = SystemParameters.PrimaryScreenHeight;+ SetResourceReference(FontFamilyProperty, "InterfaceFont");+ Root.Background = background;+ Root.Opacity = 0;+ Content = Root;+ Root.MouseLeftButtonUp += (_, e) =>+ {+ if (ReferenceEquals(e.OriginalSource, Root) || IsBackground(e.OriginalSource)) Dismiss();+ };+ PreviewKeyDown += (_, e) =>+ {+ if (e.Key != Key.Escape) return;+ e.Handled = true;+ Dismiss();+ };+ Deactivated += (_, _) => Dismiss();+ }++ /// <summary>Raised after an overlay has closed (its full-screen surface can be given back).</summary>+ public static event Action? AnyClosed;++ /// <summary>True when an overlay of this kind is showing (opening it again closes it).</summary>+ protected static bool CloseIfOpen<T>() where T : OverlayWindow+ {+ if (_open is T open)+ {+ open.Dismiss();+ return true;+ }+ _open?.Dismiss();+ return false;+ }++ /// <summary>Whether the desktop behind is blurred (AppGrid), not just dimmed.</summary>+ protected virtual bool Frosted => false;++ /// <summary>Clicks on these elements count as clicks on the empty background.</summary>+ protected virtual bool IsBackground(object source) => false;++ protected void Present()+ {+ _open = this;+ Show();+ Activate();+ OnShown();+ if (PresentationSource.FromVisual(this) is HwndSource source) SetForegroundWindow(source.Handle);+ // The first frame (building the whole grid) is drawn while still invisible; the fade starts after it, so it never skips.+ Motion.AfterFirstFrame(() =>+ {+ if (_dismissing) return;+ Root.BeginAnimation(OpacityProperty, new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(200)) { EasingFunction = Motion.Out });+ OnPresented();+ Motion.Measure(GetType().Name + " open");+ });+ }++ /// <summary>Right after the window appears, before anything moves (take the keyboard here).</summary>+ protected virtual void OnShown() { }++ /// <summary>Once the first frame is on screen: start the opening movement here.</summary>+ protected virtual void OnPresented() { }++ protected virtual void OnDismissing() { }++ public void Dismiss()+ {+ if (_dismissing) return;+ _dismissing = true;+ if (ReferenceEquals(_open, this)) _open = null;+ OnDismissing();+ if (Frosted) GpuTransparency.Blur(this, false);+ var fade = new DoubleAnimation(0, TimeSpan.FromMilliseconds(150)) { EasingFunction = Motion.In };+ fade.Completed += (_, _) =>+ {+ Close();+ Dispatcher.BeginInvoke(() => AnyClosed?.Invoke(), DispatcherPriority.ApplicationIdle);+ };+ Root.BeginAnimation(OpacityProperty, fade);+ }++ protected override void OnSourceInitialized(EventArgs e)+ {+ base.OnSourceInitialized(e);+ if (PresentationSource.FromVisual(this) is not HwndSource source) return;+ GpuTransparency.Apply(this);+ if (Frosted) GpuTransparency.Blur(this, true);+ // Keep the overlay out of Alt+Tab.+ var style = GetWindowLongPtr(source.Handle, -20).ToInt64();+ SetWindowLongPtr(source.Handle, -20, new nint((style | 0x80) & ~0x40000));+ }++ /// <summary>A rounded search field with a placeholder.</summary>+ protected static (Border Field, TextBox Box) SearchField(string placeholder, double fontSize, Brush foreground, Brush hint, Brush fill)+ {+ var box = new TextBox+ {+ FontSize = fontSize,+ Background = Brushes.Transparent,+ BorderThickness = new Thickness(0),+ Foreground = foreground,+ CaretBrush = foreground,+ VerticalContentAlignment = VerticalAlignment.Center,+ Padding = new Thickness(0)+ };+ var hintText = new TextBlock { Text = placeholder, FontSize = fontSize, Foreground = hint, VerticalAlignment = VerticalAlignment.Center, IsHitTestVisible = false, Margin = new Thickness(2, 0, 0, 0) };+ box.TextChanged += (_, _) => hintText.Visibility = box.Text.Length == 0 ? Visibility.Visible : Visibility.Collapsed;+ var icon = Ui.Icon("IconSearch", fontSize * 0.8, hint, null);+ icon.VerticalAlignment = VerticalAlignment.Center;+ icon.Margin = new Thickness(0, 0, fontSize * 0.5, 0);+ var text = new Grid();+ text.Children.Add(hintText);+ text.Children.Add(box);+ var row = new DockPanel();+ DockPanel.SetDock(icon, Dock.Left);+ row.Children.Add(icon);+ row.Children.Add(text);+ var field = new Border { Child = row, Background = fill, CornerRadius = new CornerRadius(fontSize * 0.6), Padding = new Thickness(fontSize * 0.6, fontSize * 0.35, fontSize * 0.6, fontSize * 0.35) };+ return (field, box);+ }++ protected static bool Matches(string name, string query) =>+ CultureInfo.CurrentCulture.CompareInfo.IndexOf(name, query, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace) >= 0;++ [DllImport("user32.dll")] private static extern bool SetForegroundWindow(nint window);+ [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);+}++/// <summary>Remembers the app list between openings so the overlays open instantly; refreshed in the background.</summary>+internal static class AppList+{+ private static List<InstalledApp>? _apps;+ private static Task<List<InstalledApp>>? _loading;++ public static List<InstalledApp>? Cached => _apps;++ public static Task<List<InstalledApp>> RefreshAsync()+ {+ if (_loading is { IsCompleted: false }) return _loading;+ _loading = AppCatalog.LoadAsync();+ _loading.ContinueWith(t => _apps = t.Result, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());+ return _loading;+ }+}++/// <summary>Every installed app as a grid of large icons over the dimmed screen; type to filter.</summary>+public sealed class AppGridWindow : OverlayWindow+{+ private const double Cell = 132;+ // Over the blurred desktop a lighter tint is enough; without blur the screen is darkened more.+ private static readonly Brush Dim = Ui.Solid(GpuTransparency.CanBlur ? "#8C0E0F13" : "#F00E0F13");+ // Icons stay cached between openings (about 64 KB each) so the grid fills at once next time.+ private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, ImageSource?> Icons = new(StringComparer.OrdinalIgnoreCase);+ private readonly WrapPanel _grid = new() { HorizontalAlignment = HorizontalAlignment.Center };+ private readonly ScrollViewer _scroll;+ private readonly TextBox _box;+ private List<InstalledApp> _apps = [];+ private List<InstalledApp> _shown = [];+ private volatile int _iconBuild;++ public static void Toggle()+ {+ if (CloseIfOpen<AppGridWindow>()) return;+ new AppGridWindow().Present();+ }++ private AppGridWindow() : base(Dim)+ {+ var (field, box) = SearchField(UiText.Get("AppGridSearch"), 15, Ui.White, Ui.Solid("#A6FFFFFF"), Ui.Solid("#33FFFFFF"));+ _box = box;+ field.Width = 300;+ field.HorizontalAlignment = HorizontalAlignment.Center;+ field.Margin = new Thickness(0, 56, 0, 30);+ box.TextChanged += (_, _) => Fill();+ box.PreviewKeyDown += (_, e) =>+ {+ if (e.Key != Key.Enter || _shown.Count == 0) return;+ e.Handled = true;+ Launch(_shown[0]);+ };+ var columns = Math.Max(4, Math.Min(8, (int)((Width - 160) / Cell)));+ _grid.MaxWidth = columns * Cell;+ _scroll = new ScrollViewer { Content = _grid, VerticalScrollBarVisibility = ScrollBarVisibility.Hidden, Focusable = false, Padding = new Thickness(0, 0, 0, 60) };+ var layout = new DockPanel();+ DockPanel.SetDock(field, Dock.Top);+ layout.Children.Add(field);+ layout.Children.Add(_scroll);+ Root.Children.Add(layout);+ _apps = AppList.Cached ?? [];+ Fill();+ AppList.RefreshAsync().ContinueWith(t =>+ {+ // Rebuilding a hundred tiles takes a moment, so only when the list really changed.+ if (!IsVisible || t.Result.SequenceEqual(_apps)) return;+ _apps = t.Result;+ Fill();+ }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());+ }++ protected override bool IsBackground(object source) => ReferenceEquals(source, _grid) || source is ScrollViewer || source is DockPanel { Parent: Grid };++ protected override bool Frosted => true;++ /// <summary>The grid settles from slightly large to its size.</summary>+ protected override void OnShown() => _box.Focus();++ protected override void OnPresented()+ {+ var scale = new ScaleTransform(1.05, 1.05, Width / 2, Height / 2);+ _scroll.RenderTransform = scale;+ scale.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(320)) { EasingFunction = Motion.Out });+ scale.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(320)) { EasingFunction = Motion.Out });+ }++ private void Fill()+ {+ var query = _box.Text.Trim();+ _shown = query.Length == 0 ? _apps : _apps.Where(a => Matches(a.Name, query)).ToList();+ _grid.Children.Clear();+ if (_apps.Count == 0)+ {+ _grid.Children.Add(new TextBlock { Text = UiText.Get("AppGridLoading"), Foreground = Ui.WhiteSoft, FontSize = 14, Margin = new Thickness(0, 40, 0, 0) });+ return;+ }+ var images = new List<(Image Image, string Id)>();+ foreach (var app in _shown)+ {+ var image = new Image { Width = 72, Height = 72, Stretch = Stretch.Uniform };+ if (Icons.TryGetValue(app.Id, out var known)) image.Source = known;+ else images.Add((image, app.Id));+ _grid.Children.Add(Tile(app, image));+ }+ LoadIcons(images);+ }++ /// <summary>Loads missing icons on a background thread and drops each into the grid as it arrives.</summary>+ private void LoadIcons(List<(Image Image, string Id)> pending)+ {+ var build = ++_iconBuild;+ if (pending.Count == 0) return;+ var thread = new Thread(() =>+ {+ // Icons are handed over in small batches so the grid redraws a few times, not once per icon.+ var batch = new List<(Image Image, ImageSource? Source)>();+ void Flush()+ {+ if (batch.Count == 0) return;+ var ready = batch.ToArray();+ batch.Clear();+ Dispatcher.BeginInvoke(() =>+ {+ foreach (var (image, source) in ready) image.Source = source;+ }, DispatcherPriority.Background);+ }+ foreach (var (image, id) in pending)+ {+ if (build != _iconBuild) return;+ batch.Add((image, Icons.GetOrAdd(id, key => NotificationApps.LoadIcon(key, 128))));+ if (batch.Count >= 16) Flush();+ }+ Flush();+ }) { IsBackground = true, Name = "AppGrid icons" };+ thread.SetApartmentState(ApartmentState.STA);+ thread.Start();+ }++ private FrameworkElement Tile(InstalledApp app, Image image)+ {+ var name = new TextBlock+ {+ Text = app.Name,+ Foreground = Ui.White,+ FontSize = 12,+ TextAlignment = TextAlignment.Center,+ TextTrimming = TextTrimming.CharacterEllipsis,+ Margin = new Thickness(0, 8, 0, 0)+ };+ // No per-icon shadows: a hundred of them made opening and scrolling stutter.+ var column = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality);+ column.Children.Add(image);+ column.Children.Add(name);+ var hover = Ui.Solid("#1FFFFFFF");+ var tile = new Border { Width = Cell - 12, Height = Cell - 8, Margin = new Thickness(6, 4, 6, 4), Padding = new Thickness(8, 10, 8, 6), CornerRadius = new CornerRadius(16), Background = Brushes.Transparent, Child = column, ToolTip = app.Name, Cursor = Cursors.Hand };+ tile.MouseEnter += (_, _) => tile.Background = hover;+ tile.MouseLeave += (_, _) => tile.Background = Brushes.Transparent;+ tile.MouseLeftButtonUp += (_, e) =>+ {+ e.Handled = true;+ Launch(app);+ };+ return tile;+ }++ private void Launch(InstalledApp app)+ {+ Dismiss();+ app.Launch();+ }+}++/// <summary>A search box in the middle of the screen for apps, files and quick sums.</summary>+public sealed class QuickSearchWindow : OverlayWindow+{+ private const int MaxResults = 8;+ private readonly TextBox _box;+ private readonly StackPanel _results = new();+ private readonly Border _card;+ private readonly DispatcherTimer _debounce;+ private List<SearchWidget.Entry>? _files;+ private CancellationTokenSource? _indexing;+ private readonly List<(FrameworkElement Row, Action Open)> _rows = [];+ private int _selected;++ public static void Toggle()+ {+ if (CloseIfOpen<QuickSearchWindow>()) return;+ new QuickSearchWindow().Present();+ }++ private QuickSearchWindow() : base(Ui.Solid("#01000000"))+ {+ var text = (Brush)Application.Current.Resources["TextPrimary"];+ var hint = (Brush)Application.Current.Resources["TextSecondary"];+ var (field, box) = SearchField(UiText.Get("QuickSearchHint"), 22, text, hint, Brushes.Transparent);+ _box = box;+ field.Padding = new Thickness(18, 14, 18, 14);+ var column = new StackPanel();+ column.Children.Add(field);+ _results.Margin = new Thickness(8, 0, 8, 8);+ column.Children.Add(_results);+ _card = new Border+ {+ Width = 680,+ CornerRadius = new CornerRadius(18),+ BorderThickness = new Thickness(1),+ Child = column,+ HorizontalAlignment = HorizontalAlignment.Center,+ VerticalAlignment = VerticalAlignment.Top,+ Margin = new Thickness(0, Height * 0.22, 0, 0),+ Effect = new DropShadowEffect { BlurRadius = 40, ShadowDepth = 10, Direction = 270, Opacity = 0.4 }+ };+ _card.SetResourceReference(Border.BackgroundProperty, "WidgetPopupFill");+ _card.SetResourceReference(Border.BorderBrushProperty, "DockBorderMaterial");+ Root.Children.Add(_card);+ _debounce = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(90) };+ _debounce.Tick += (_, _) =>+ {+ _debounce.Stop();+ Query();+ };+ box.TextChanged += (_, _) =>+ {+ _debounce.Stop();+ _debounce.Start();+ };+ box.PreviewKeyDown += Box_KeyDown;+ AppList.RefreshAsync();+ var cancel = _indexing = new CancellationTokenSource();+ Task.Run(() => SearchWidget.Collect(cancel.Token), cancel.Token).ContinueWith(t =>+ {+ if (cancel.IsCancellationRequested) return;+ _files = t.Result;+ if (_box.Text.Length > 0) Query();+ }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());+ }++ protected override void OnShown() => _box.Focus();++ protected override void OnDismissing()+ {+ _indexing?.Cancel();+ _files = null;+ }++ private void Box_KeyDown(object sender, KeyEventArgs e)+ {+ switch (e.Key)+ {+ case Key.Down when _rows.Count > 0:+ Select((_selected + 1) % _rows.Count);+ e.Handled = true;+ break;+ case Key.Up when _rows.Count > 0:+ Select((_selected - 1 + _rows.Count) % _rows.Count);+ e.Handled = true;+ break;+ case Key.Enter:+ var pending = _debounce.IsEnabled;+ _debounce.Stop();+ if (pending || _rows.Count == 0) Query();+ if (_rows.Count > 0) _rows[_selected].Open();+ e.Handled = true;+ break;+ }+ }++ private void Query()+ {+ _results.Children.Clear();+ _rows.Clear();+ var query = _box.Text.Trim();+ if (query.Length == 0) return;+ if (Calculate(query) is { } sum)+ {+ AddRow(Ui.Icon("IconCalculator", 18), sum, UiText.Get("QuickSearchCopy"), () =>+ {+ try { Clipboard.SetText(sum); } catch (COMException) { }+ Dismiss();+ });+ }+ var apps = (AppList.Cached ?? [])+ .Select(a => (App: a, At: CultureInfo.CurrentCulture.CompareInfo.IndexOf(a.Name, query, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace)))+ .Where(m => m.At >= 0)+ .OrderBy(m => m.At == 0 ? 0 : 1).ThenBy(m => m.App.Name.Length)+ .Take(5).Select(m => m.App).ToList();+ foreach (var app in apps)+ {+ var icon = new Image { Source = NotificationApps.Icon(app.Id), Width = 28, Height = 28 };+ AddRow(icon, app.Name, UiText.Get("SearchApp"), () =>+ {+ Dismiss();+ app.Launch();+ });+ }+ if (_files is not null)+ {+ var names = new HashSet<string>(apps.Select(a => a.Name), StringComparer.OrdinalIgnoreCase);+ var files = _files+ .Select(f => (File: f, At: CultureInfo.CurrentCulture.CompareInfo.IndexOf(f.Name, query, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace)))+ .Where(m => m.At >= 0 && !(m.File.IsApp && names.Contains(m.File.Name)))+ .OrderBy(m => m.File.IsApp ? 0 : 1).ThenBy(m => m.At == 0 ? 0 : 1).ThenBy(m => m.File.Name.Length)+ .Take(Math.Max(0, MaxResults - _rows.Count - 1)).Select(m => m.File);+ foreach (var file in files)+ {+ AddRow(Ui.FileIcon(file.Path, 28), file.Name, file.IsApp ? UiText.Get("SearchApp") : System.IO.Path.GetDirectoryName(file.Path) ?? "", () =>+ {+ Dismiss();+ Ui.Open(file.Path);+ });+ }+ }+ else AddNote(UiText.Get("SearchIndexing"));+ AddRow(Ui.Icon("IconGlobe", 18), UiText.Format("QuickSearchWeb", query), "", () =>+ {+ Dismiss();+ Ui.Open("https://www.google.com/search?q=" + Uri.EscapeDataString(query));+ });+ Select(0);+ }++ private void AddNote(string text)+ {+ var note = Ui.Text(text, 11.5, brushKey: "TextSecondary");+ note.Margin = new Thickness(12, 4, 0, 4);+ _results.Children.Add(note);+ }++ private void AddRow(FrameworkElement icon, string title, string detail, Action open)+ {+ icon.HorizontalAlignment = HorizontalAlignment.Center;+ icon.VerticalAlignment = VerticalAlignment.Center;+ var iconBox = new Grid { Width = 28, Height = 28, Margin = new Thickness(0, 0, 12, 0), VerticalAlignment = VerticalAlignment.Center };+ iconBox.Children.Add(icon);+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ var name = Ui.Text(title, 14, FontWeights.SemiBold);+ name.TextTrimming = TextTrimming.CharacterEllipsis;+ text.Children.Add(name);+ if (detail.Length > 0)+ {+ var sub = Ui.Text(detail, 11.5, brushKey: "TextSecondary");+ sub.TextTrimming = TextTrimming.CharacterEllipsis;+ text.Children.Add(sub);+ }+ var content = new DockPanel();+ DockPanel.SetDock(iconBox, Dock.Left);+ content.Children.Add(iconBox);+ content.Children.Add(text);+ var row = new Border { Child = content, Padding = new Thickness(12, 7, 12, 7), CornerRadius = new CornerRadius(10), Background = Brushes.Transparent, Cursor = Cursors.Hand };+ var index = _rows.Count;+ row.MouseEnter += (_, _) => Select(index);+ row.MouseLeftButtonUp += (_, e) =>+ {+ e.Handled = true;+ open();+ };+ _rows.Add((row, open));+ _results.Children.Add(row);+ }++ private void Select(int index)+ {+ _selected = Math.Clamp(index, 0, Math.Max(0, _rows.Count - 1));+ for (var i = 0; i < _rows.Count; i++)+ {+ if (i == _selected) ((Border)_rows[i].Row).SetResourceReference(Border.BackgroundProperty, "SurfaceSelected");+ else ((Border)_rows[i].Row).Background = Brushes.Transparent;+ }+ }++ /// <summary>"12*4+3" → "51" for simple sums typed into the box (digits, + - * / and parentheses).</summary>+ private static string? Calculate(string query)+ {+ var expression = query.Replace(',', '.').Replace('x', '*').Replace('×', '*').Replace('÷', '/');+ if (!expression.Any(char.IsDigit) || !expression.Any(c => "+-*/".Contains(c))) return null;+ if (expression.Any(c => !(char.IsDigit(c) || "+-*/(). ".Contains(c)))) return null;+ try+ {+ var value = Convert.ToDouble(new System.Data.DataTable().Compute(expression, null), CultureInfo.InvariantCulture);+ if (double.IsNaN(value) || double.IsInfinity(value)) return null;+ return Math.Round(value, 8).ToString("#,0.########", CultureInfo.CurrentCulture);+ }+ catch (Exception ex) when (ex is System.Data.EvaluateException or System.Data.SyntaxErrorException or InvalidCastException or OverflowException or DivideByZeroException or FormatException)+ {+ return null;+ }+ }+}++/// <summary>All open windows side by side as live thumbnails; click one to switch to it.</summary>+public sealed class WindowOverviewWindow : OverlayWindow+{+ private const double Gap = 34;+ private const double TitleHeight = 30;+ private static readonly Brush Dim = Ui.Solid("#C80B0C10");+ private readonly IReadOnlyList<TrackedWindow> _windows;+ private readonly Canvas _canvas = new();+ private readonly List<nint> _thumbnails = [];++ public static void Toggle(IEnumerable<TrackedWindow> windows)+ {+ if (CloseIfOpen<WindowOverviewWindow>()) return;+ new WindowOverviewWindow(windows.Where(w => IsWindow(w.Handle)).ToList()).Present();+ }++ private WindowOverviewWindow(IReadOnlyList<TrackedWindow> windows) : base(Dim)+ {+ _windows = windows;+ Root.Children.Add(_canvas);+ if (windows.Count == 0)+ {+ var empty = new TextBlock { Text = UiText.Get("WindowOverviewEmpty"), Foreground = Ui.WhiteSoft, FontSize = 16, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ Root.Children.Add(empty);+ }+ }++ protected override bool IsBackground(object source) => ReferenceEquals(source, _canvas);++ protected override void OnPresented()+ {+ if (_windows.Count == 0 || PresentationSource.FromVisual(this) is not HwndSource source) return;+ var scale = source.CompositionTarget?.TransformToDevice.M11 ?? 1;+ var area = new Rect(70, 70, Width - 140, Height - 70 - 150); // room for the dock+ var count = _windows.Count;+ var (columns, rows) = (1, count);+ var best = 0.0;+ for (var c = 1; c <= count; c++)+ {+ var r = (int)Math.Ceiling(count / (double)c);+ var w = (area.Width - Gap * (c - 1)) / c;+ var h = (area.Height - Gap * (r - 1)) / r - TitleHeight;+ var size = Math.Min(w, h * 1.6);+ if (size > best)+ {+ best = size;+ (columns, rows) = (c, r);+ }+ }+ var cellWidth = (area.Width - Gap * (columns - 1)) / columns;+ var cellHeight = (area.Height - Gap * (rows - 1)) / rows;+ // Center a short last row and the whole block vertically.+ var usedHeight = rows * cellHeight + (rows - 1) * Gap;+ var top = area.Top + (area.Height - usedHeight) / 2;+ for (var i = 0; i < count; i++)+ {+ var row = i / columns;+ var inRow = row == rows - 1 ? count - row * columns : columns;+ var rowWidth = inRow * cellWidth + (inRow - 1) * Gap;+ var left = area.Left + (area.Width - rowWidth) / 2 + (i % columns) * (cellWidth + Gap);+ AddCell(_windows[i], new Rect(left, top + row * (cellHeight + Gap), cellWidth, cellHeight), source.Handle, scale);+ }+ }++ private void AddCell(TrackedWindow window, Rect cell, nint host, double scale)+ {+ var frame = new Rect(cell.X, cell.Y, cell.Width, cell.Height - TitleHeight);+ var picture = frame;+ var minimized = NativeWindowTracker.IsMinimized(window.Handle);+ nint thumbnail = 0;+ if (!minimized && DwmRegisterThumbnail(host, window.Handle, out thumbnail) == 0 && thumbnail != 0+ && DwmQueryThumbnailSourceSize(thumbnail, out var size) == 0 && size.Width > 0 && size.Height > 0)+ {+ var fit = Math.Min(frame.Width / size.Width, frame.Height / size.Height);+ var w = size.Width * fit;+ var h = size.Height * fit;+ picture = new Rect(frame.X + (frame.Width - w) / 2, frame.Bottom - h, w, h);+ var properties = new ThumbnailProperties+ {+ Flags = 0x1 | 0x4 | 0x8 | 0x10, // destination, opacity, visible, client area only+ Destination = new NativeRect((int)(picture.Left * scale), (int)(picture.Top * scale), (int)(picture.Right * scale), (int)(picture.Bottom * scale)),+ Opacity = 255,+ Visible = true,+ SourceClientAreaOnly = false+ };+ DwmUpdateThumbnailProperties(thumbnail, ref properties);+ _thumbnails.Add(thumbnail);+ }+ else+ {+ if (thumbnail != 0) DwmUnregisterThumbnail(thumbnail);+ // Minimized windows have no live picture: show the app icon on a card instead.+ var w = Math.Min(frame.Width, 260);+ var h = Math.Min(frame.Height, 170);+ picture = new Rect(frame.X + (frame.Width - w) / 2, frame.Bottom - h, w, h);+ var icon = window.ExecutablePath is { } exe ? Ui.FileIcon(exe, 64) : Ui.Icon("IconApps", 48, Ui.White, null);+ icon.HorizontalAlignment = HorizontalAlignment.Center;+ icon.VerticalAlignment = VerticalAlignment.Center;+ var card = new Border { Width = w, Height = h, CornerRadius = new CornerRadius(12), Background = Ui.Solid("#33FFFFFF"), Child = icon, IsHitTestVisible = false };+ Canvas.SetLeft(card, picture.X);+ Canvas.SetTop(card, picture.Y);+ _canvas.Children.Add(card);+ }++ // A frame drawn around the picture on hover; it also takes the click.+ var outline = new Border+ {+ Width = picture.Width + 12,+ Height = picture.Height + 12,+ CornerRadius = new CornerRadius(12),+ BorderThickness = new Thickness(3),+ BorderBrush = Brushes.Transparent,+ Background = Ui.Solid("#01FFFFFF"),+ Cursor = Cursors.Hand+ };+ Canvas.SetLeft(outline, picture.X - 6);+ Canvas.SetTop(outline, picture.Y - 6);+ var accent = Ui.Solid("#FF0A84FF");+ outline.MouseEnter += (_, _) => outline.BorderBrush = accent;+ outline.MouseLeave += (_, _) => outline.BorderBrush = Brushes.Transparent;+ outline.MouseLeftButtonUp += (_, e) =>+ {+ e.Handled = true;+ Dismiss();+ NativeWindowTracker.Activate(window.Handle);+ };+ _canvas.Children.Add(outline);++ var icon16 = window.ExecutablePath is { } path ? Ui.FileIcon(path, 18) : new Border();+ icon16.Margin = new Thickness(0, 0, 7, 0);+ icon16.VerticalAlignment = VerticalAlignment.Center;+ var title = new TextBlock { Text = window.Title, Foreground = Ui.White, FontSize = 12.5, FontWeight = FontWeights.SemiBold, TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center, MaxWidth = Math.Max(60, cell.Width - 40) };+ var label = new StackPanel { Orientation = Orientation.Horizontal, IsHitTestVisible = false };+ label.Children.Add(icon16);+ label.Children.Add(title);+ label.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));+ Canvas.SetLeft(label, cell.X + (cell.Width - label.DesiredSize.Width) / 2);+ Canvas.SetTop(label, frame.Bottom + 10);+ _canvas.Children.Add(label);+ }++ protected override void OnDismissing()+ {+ foreach (var thumbnail in _thumbnails) DwmUnregisterThumbnail(thumbnail);+ _thumbnails.Clear();+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct ThumbnailProperties+ {+ public uint Flags;+ public NativeRect Destination;+ public NativeRect Source;+ public byte Opacity;+ [MarshalAs(UnmanagedType.Bool)] public bool Visible;+ [MarshalAs(UnmanagedType.Bool)] public bool SourceClientAreaOnly;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct NativeRect(int left, int top, int right, int bottom)+ {+ public int Left = left, Top = top, Right = right, Bottom = bottom;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct NativeSize { public int Width, Height; }++ [DllImport("user32.dll")] private static extern bool IsWindow(nint window);+ [DllImport("dwmapi.dll")] private static extern int DwmRegisterThumbnail(nint destination, nint source, out nint thumbnail);+ [DllImport("dwmapi.dll")] private static extern int DwmQueryThumbnailSourceSize(nint thumbnail, out NativeSize size);+ [DllImport("dwmapi.dll")] private static extern int DwmUpdateThumbnailProperties(nint thumbnail, ref ThumbnailProperties properties);+ [DllImport("dwmapi.dll")] private static extern int DwmUnregisterThumbnail(nint thumbnail);+}diff --git a/QiDock.csproj b/QiDock.csprojnew file mode 100644index 0000000..7a98f6b--- /dev/null+++ b/QiDock.csproj@@ -0,0 +1,28 @@+<Project Sdk="Microsoft.NET.Sdk">++ <PropertyGroup>+ <OutputType>WinExe</OutputType>+ <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>+ <SupportedOSPlatformVersion>10.0.19041.0</SupportedOSPlatformVersion>+ <Nullable>enable</Nullable>+ <ImplicitUsings>enable</ImplicitUsings>+ <UseWPF>true</UseWPF>+ <AssemblyName>QiDock</AssemblyName>+ <RootNamespace>QiDock</RootNamespace>+ <Version>0.2.0</Version>+ <ApplicationManifest>app.manifest</ApplicationManifest>+ <Product>QiDock</Product>+ <AssemblyTitle>QiDock</AssemblyTitle>+ <Company>QiDock</Company>+ <Authors>QiDock</Authors>+ <Copyright>Copyright (c) 2026 QiDock contributors</Copyright>+ <Deterministic>true</Deterministic>+ <PathMap>$(MSBuildProjectDirectory)=QiDock</PathMap>+ </PropertyGroup>++ <PropertyGroup Condition="'$(Configuration)' == 'Release'">+ <DebugType>none</DebugType>+ <DebugSymbols>false</DebugSymbols>+ </PropertyGroup>++</Project>diff --git a/README.md b/README.mdnew file mode 100644index 0000000..03445dd--- /dev/null+++ b/README.md@@ -0,0 +1,149 @@+# QiDock++QiDock turns the Windows 10 and 11 taskbar into a floating glass dock with a widget bar of its own: music, weather, calendar, AI limits, currency, timers, notes, reminders and more, grouped into profiles you switch with one click. Cards and panels grow straight out of the dock, notifications arrive as banners at the top, and the whole thing is built to stay light: a low-memory mode keeps it near 140 MB, and widgets sleep while they are off screen.++---++## Features++- **Floating Dock:** Smooth rounded pill container (`CornerRadius="18"`) with prominent high-resolution application icons (32 DIP base, extracted at up to 128x128), translucent smoked glass material, specular top highlight, and ambient shadow.+- **Continuous Fisheye Magnification:** Smooth wave scaling across hovered and adjacent icons, pushing neighbours apart without layout jitter. It is off by default and can be turned on, with its size set from 110% to 220% (Settings → Appearance). When it is on, a small note under the switch says it uses a little more processor time, and, while low-memory mode is on, that it can stutter and that turning low-memory mode off makes it smooth at about 300 MB more memory. No bubble or box appears behind the hovered icon; with magnification off, the tile under the pointer rises a few pixels instead.+- **Multi-Window Live Thumbnail Previews:** Interactive live DWM window preview cards for open applications with one-click window activation and individual window close controls. A preview opens only after the pointer rests on an icon for half a second; while one is open, moving to the next icon switches at once.+- **Smart Auto-Hide (IntelliHide):** Automatically slides down off-screen when an active or maximized window overlaps the dock, and stays visible on the desktop. Smoothly reveals when the mouse touches the bottom screen edge.+- **Drag-and-Drop Reordering:** Reorder dock icons interactively with persistent order saved automatically.+- **Dock Pinning:** Pin running applications or unpin shortcuts directly from the context menu. Classic taskbar shortcuts are imported from the user's Windows pin folder.+- **Native Windows Jump Lists:** View recent/frequent destinations and published application tasks directly in the context menu via lightweight STA Shell reading.+- **Crash Recovery & State Journaling:** Automatically restores the native Windows taskbar on exit or unexpected shutdown using a local state journal (`taskbar-state.txt`). Reconnects on Explorer restarts (`TaskbarCreated`).+- **Dedicated Settings Window:** A window with custom title-bar controls. Customize alignment (Left, Center, Right), theme (Dark/Light), auto-hide, animations, magnification, previews, and Windows startup. Every switch says under its name what it does. A live picture of the dock sits above the tabs: it redraws on every change (edge, position, look, opacity, widget placement, auto-hide, magnification) before anything is applied, its icons magnify under the pointer at the chosen size, and resting on one shows the window preview after the same half second. Nothing on screen changes until Apply.+- **Glass & Surface Opacity:** Settings use native Desktop Acrylic on Windows 11 build 22621 or later. Adjust background opacity from 60–100% for settings, the dock, and context menus without fading text or icons. Changes preview live, save on Apply, and revert when discarded. Unsupported Windows versions and high-contrast mode use an opaque settings surface.+- **Top Widget Bar:** The widgets live in a glass bar at the top of the screen, apart from the app dock. It stays on screen while the desktop is clean (no app window open on the primary monitor), steps aside as soon as a window is open, and can be brought down by resting the pointer on the top edge. While hidden, the widgets pause their per-second timers. Right-click the bar for the edit mode (move, remove, add widgets) and other options.+- **Dock Edge:** The dock can stand on the bottom, top, left or right edge of the screen (dock menu "Dock'un kenarı" or Settings → General). Icons stay upright, the running dots sit on the screen-edge side, magnification and hiding work on every edge, and panels, widget cards and window previews open inward. On the left and right edges the widgets stay in the top bar; on the top edge they move into the dock.+- **Widget Placement:** The widgets can also sit inside the dock, left of the apps or right of them (before Downloads and the bin), with a thin divider between the groups. Choose it from the dock menu ("Araçların yeri") or in Settings → Widgets. When the row is wider than the screen, icons and widgets shrink together so they stay in proportion. In the dock the widgets stay live, and each widget's card grows out of the dock the way the bell's list does (the dock keeps still while it stands there). The Control Center tile sits at the end of the row and replaces the Quick controls tile (Wi-Fi, Bluetooth, volume and brightness are all in the Control Center).+- **Widget Profiles:** Tabs under the bar (shown on hover) switch between widget sets such as "Varsayılan", "İş" and "Araçlar"; Ctrl+Alt+Shift+1…9 switch from anywhere (each tab shows its key), and "Kendinizinkini oluşturun" adds one. Each profile keeps its own order and hidden widgets; right-click a tab to rename or delete it, "+" adds one. The **Profile** tile (in the dock or the bar) shows the active profile; a click lists the profiles to switch to, makes a new one from ready names (İş, Kod, Ev, Odak, Oyun, Okul, Tasarım, Araçlar), renames or deletes the active one, and edits its widgets. It is how profiles are reached while the widgets sit in the dock, where the tabs are not shown.+- **Two Desktop Buttons:** The blue tile next to Start goes straight to the clean desktop (open windows step aside, desktop icons hidden, the widgets stay). The orange folder tile goes straight to the desktop with its folders and files; the desktop widgets and the widget bar step out of the way there. Either button switches to the other desktop directly; pressing the same one again brings the windows back.+- **Dock Shortcuts:** Add apps, files, folders or web links to the dock from the dock menu (Kısayol ekle) or by dropping them on the dock. Remove them with "Unpin" like any pinned app.+- **Recycle Bin:** A Recycle Bin tile at the end of the dock shows whether it is empty; drop files on it to delete them (undoable), click to open, right-click to empty.+- **Notifications at the Top:** New Windows notifications slide down from the top center of the screen as small cards of frosted glass (app icon, app name, time, title and text; the desktop behind is blurred and tinted). Up to three stack, newest on top, the others gliding down to make room; they slide back up after a few seconds; hovering keeps them, a click opens the app (or the notification's link), dragging a card up or its × dismisses it. They stay out of the way of full-screen apps. Windows' own pop-up at the bottom right is moved off screen while it shows, so each notification appears once (nothing in Windows' settings changes; turn "Windows balonlarını gizle" off to get it back). Notifications are read from Windows' own notification database (`wpndatabase.db`, through the `winsqlite3.dll` that ships with Windows) on a private copy, so the original is never written.+- **Notification Center:** Clicking the bell on the dock (with a red unread badge) grows the list out of the dock itself: a small bump rises from the bell and swells, with a soft overshoot, into a panel in the dock's own material, joined to the dock by inward curves (the dock leaves out its edge line there and the grown shape draws no rim of its own, so the two read as one piece); clicking outside pulls it back into the bell. The bell tile next to the battery opens it the same way. Ctrl+Alt+← slides a sheet of frosted glass in from the right edge instead (the desktop behind is blurred and tinted, with rounded corners). The sheet is only as tall as its cards (at most about 60% of the screen, then it scrolls smoothly under the fixed title row). Notifications of one app sit in a single stack (the newest card with the others peeking out below, "+N daha"); click the stack and the cards fan out of it, "Daha az göster" folds them back, × clears the group. Click a single card to open its app; hover it for the × that slides it away. Every change moves the cards from where they were to where they go. The gear holds switches for the top banners, hiding Windows' pop-up and a sound.+- **Smooth Motion:** Panels and overlays are see-through without WPF's layered-window mode (which copies every frame back to memory); cards only move and fade, the glass is resized once per change rather than every frame, and each movement starts after its first frame is drawn, so animations stay fluid on large, high-DPI screens. Set the environment variable `QIDOCK_FRAMES=1` to log frame times to `%LOCALAPPDATA%\QiDock\frames.log`.+- **Control Center:** Ctrl+Alt+→, any part of the Quick Controls tile, the battery tile or the round "Denetim Merkezi" button opens the same frosted sheet with tiles: Wi-Fi (with the network name) and Bluetooth toggles, power mode, unread notifications, volume and built-in display brightness sliders, battery, and shortcuts for screen snip, lock, Windows settings and QiDock settings. The chevron on the Wi-Fi row opens the networks in range (signal, padlock, a tick on the joined one); click one to join it, and a network Windows has not joined before asks for its password right there. "Windows ağ listesi" opens Windows' own list (also the way in when Windows does not let apps list networks).+- **All Apps ("Tüm uygulamalar"):** The dock's colored-grid button or Ctrl+Alt+↓ shows every installed app (desktop and Store apps, as in "All apps") as a large-icon grid over the blurred screen (dimmed on Windows 10); type to filter, Enter opens the first match, Esc or a click on the background closes it.+- **QuickSearch:** Alt+Shift+Space or the "Ara" bar tile opens a search box in the middle of the screen for apps and files in your user folders, with arrow-key selection. Simple sums ("12*4+3") show their result (Enter copies it); the last row searches the web.+- **Window Overview:** Ctrl+Alt+↑ shows all open windows side by side as live thumbnails (minimized ones as their app icon); click one to switch to it.+- **Downloads Stack:** The blue arrow next to the Recycle Bin shows the 12 newest files in your Downloads folder; click to open, drag them into other apps, or open the folder.+- **Full-Screen Apps:** While a game, video or presentation fills the screen, the dock and the bar step aside; they come back when another window comes to the front.+- **Light on Memory:** Start-up work, closed overlays and idle periods (two minutes without input) give unused memory back to Windows, so QiDock's working set drops to a few tens of megabytes while you are not using it.+- **Touchpad Gestures:** Windows keeps three- and four-finger gestures for itself, but Settings → Bluetooth & devices → Touchpad → Advanced gestures can map a swipe to a keyboard shortcut — for example four fingers up to Ctrl+Alt+↑ (Window Overview) and down to Ctrl+Alt+↓ (AppGrid).+- **Volume & Brightness HUD:** When the volume or the built-in display's brightness changes, a small card (icon, name, bar, value) grows out of the middle of the dock and sinks back a moment later; short messages ("copied", "focus done") use it too. While the dock is hidden or another panel stands on it, or with "Ses ve parlaklık dock'tan çıksın" off, a pill at the top of the screen shows instead. Brightness comes from Windows' own power-setting notification (no polling).+- **Claude Code Sessions:** Nothing opens by itself. Clicking the Claude ring of the AI limits tile shows, under Claude's usage, the Claude Code sessions of the last 30 minutes on this PC: the project, its current step ("2 dosya düzenleniyor…", "Komut çalışıyor…", or the command's own description) or "Bitti", with an orange dot while working, a grey one when it has gone quiet and a green tick when finished. The list follows the sessions live while the card is open. Only the end of the local transcripts in `%USERPROFILE%\.claude\projects` is read, and only while that card is open (no network, no background watcher). Turn it off with "Claude kartında Claude Code oturumları".+- **Low-Memory Mode:** "Az bellek modu" (Settings → General) draws everything on the processor instead of the graphics card. On integrated graphics the driver's drawing device alone holds about 300 MB as soon as the first window opens; without it the app needs roughly 50 MB (measured with `--memory-probe`). Blurred shadows are left out in this mode: drawn by the processor, a sliding dock with its shadow managed about 34 frames a second, and about 119 without it, as smooth as on the graphics card (measured with `--frame-probe`). The frosted blur behind panels is replaced by a plain tint. It takes effect after a restart, which the settings window offers. Memory use is written to `app.log` a minute after start and every 30 minutes.+- **Looks:** Settings → Appearance → Tema (or the dock menu's theme submenu) switches between 14 looks: Glass (follows dark/light), Black, Lo-fi, Pixel Night, Christmas, Ocean, Sunset, Forest, Graphite, Neon, Retro, Mocha, Paper and Sakura. Each lays its own colors over the dock, the widget tiles, menus and panels.+- **Widgets:** Each one optional and reorderable in Settings → Widgets or the bar's edit mode:+ - **Music:** Current track from any Windows media session (Spotify, browsers, Media Player): cover, title, artist, a progress bar and previous / play-pause / next. Click the tile for a card tinted by the cover's colour: a large cover, seeking, ±10 seconds, previous / play / next and the playing app's volume. With nothing playing the tile stays and says so (it used to disappear); its play button then sends the keyboard's play key, which resumes the player that last had sound.+ - **Weather:** Temperature with today's icon and the next three days (name, icon, high); click for the next hours and a 7-day forecast with temperature ranges. Data from [Open-Meteo](https://open-meteo.com) (no API key).+ - **Battery:** Charge as a ring with the percent inside and a bolt while charging (hidden on PCs without a battery). Click for the battery's own card: a large ring, where the power comes from (charging, plugged in, on battery), the time left, energy saver, and a link to Windows' battery settings.+ - **Background Apps:** Apps that run in the background with an icon by the clock (Windows' notification area) appear in the dock's corner tile. In its card, click an app to open it, right-click for the app's own menu, and × to close it; an app that does not close within a few seconds offers "Zorla kapat" (force close). QiDock keeps a hidden notification-area window of its own for this and passes everything on to Windows'.+ - **Notifications:** A square bell with the red unread badge, always the last tile of the row, in the corner next to the battery; the list grows out of it. While this tile is shown the dock's own bell stays hidden (so there is always exactly one).+ - **CPU & RAM:** Two small rings with the load inside; click for details.+ - **Clock & Calendar:** Large time with the date under it; click for a month view and the selected day's events from any iCal (.ics) address — Google Calendar's "secret address in iCal format", Outlook or iCloud. Common recurrence rules are supported.+ - **AI Limits:** Claude and ChatGPT as two small rings (logo inside, the busier limit's use around it, percent beside). Nothing shows on hover; click a ring for that provider's own card (bars, reset times, this week's curve and pace), and click the other ring to switch to it. Claude uses the Claude Code sign-in on this PC (the same usage endpoint as `/usage`); ChatGPT reads the latest rate-limit snapshot from Codex's local session logs, without network access. Tokens are read from disk only to call their own provider and are never stored.+ - **Quick Controls:** Wi-Fi and Bluetooth status (the capsules, their chevrons and the battery open the Control Center), a volume slider for the default output device (drag, click or scroll; click the speaker to mute) and a battery tile on laptops.+ - **Folder:** The Desktop (or a folder you pick) as a tile; the card shows its files in a grid you can browse, open or drag out.+ - **Search:** A search field that opens QuickSearch (the same search as Alt+Shift+Space).+ - **Color Picker:** Pick any color on screen with a magnifier; saved colors copy their hex code on click.+ - **App Volume:** Volume slider and mute for each app playing sound.+ - **Focus Timer:** Pomodoro timer (15/25/45/60 minutes) with a 5-minute break and a notice when time is up. It is the same timer as the desktop focus widget: start it in one place and both count down together; after each session a break follows (a long one every fourth round).+ - **World Clock:** Up to three cities with their time difference.+ - **To-Do:** A short task list; the tile shows the next open task.+ - **Tools:** Screenshot, clipboard history, emoji panel, calculator and lock screen.+ - **Profile:** The active widget profile; click to switch, add, rename or delete profiles (see Widget Profiles).+ - **Currency Converter:** One unit of a currency in another (1 USD = … ₺) on the tile; the card converts any amount between TRY, USD, EUR, GBP, CHF and JPY (click a currency to step to the next, ⇅ swaps). European Central Bank rates via [Frankfurter](https://www.frankfurter.app), fetched at most every six hours and only while the tile is shown.+ - **Stopwatch & Timer:** A stopwatch to the tenth of a second, or a countdown of 1–60 minutes that chimes and shows a message at the top of the screen when it ends. The display ticks only while running and on screen.+ - **Quick Note:** A small note that is saved as you type (after a short pause); the tile shows its first line.+ - **App Group:** Up to four favourite apps in one small square, picked from the Start menu's app list; click an icon to open the app, right-click (or an empty slot) to edit.+ - **Month / Year Progress:** Dots for the days of the month (or the months of the year, or the hours of the day) and the percent gone; click to switch. It redraws once a minute while shown.+ - **Water / Break Reminder:** Every 20–90 minutes it chimes and reminds you to drink water, take a break or rest your eyes; for water, "İçtim" counts today's glasses and restarts the wait.+ - **Voice Memo:** The red button records from the default microphone, a second press saves a .wav file (16-bit mono) in Documents\Ses Kayıtları; the card lists the latest recordings and opens the folder. It uses Windows' own recorder (MCI).++ The second batch (currency, stopwatch, note, app group, progress, reminder, voice memo) starts hidden in every profile; add them from the edit mode's "Add" list or the dock menu's widget list.+- **Desktop Widgets:** Dark cards placed freely on the desktop, below all windows, and kept there through Win+D. Open the gallery from the dock or bar menu ("Masaüstüne widget ekle…") or from a widget's right-click menu ("Widget ekle…"); it shows live previews by category with the sizes each kind offers. Drag a card to move it (it snaps to the screen edges and to other cards); right-click it to change its size, use its own options or remove it. Sizes: Mini (164×74), Small (164×164), Strip (344×74), Medium (344×164) and Large (344×344). A card fully covered by a window pauses its updates. The 34 kinds:+ - **Time and date:** digital clock, analog clock, flip clock, date, calendar (iCal events), year/month/week/day progress, world clock, timer, stopwatch.+ - **Weather:** weather (now, hours, days), sunrise and sunset, wind with a compass.+ - **System:** CPU (ring or live graph), memory, disk, battery, network speed with a graph.+ - **Media:** music player (artwork, progress, previous/play/next; five sizes) and volume.+ - **Productivity:** to-do list (shared with the bar), sticky note, focus (Pomodoro, the same timer as the bar) and a repeating reminder (drink water, take a break, rest your eyes).+ - **AI:** Claude and Codex (session and weekly usage limits with their reset times, from the same sources as the AI Limits tile) and Gemini (opens the app); each card carries the app's own icon, which opens the app.+ - **Tools:** apps, quick actions, quick settings, web search, file search, emoji, colors and a currency converter (European Central Bank rates via [Frankfurter](https://www.frankfurter.app)).+- **Vector Icons:** Clean vector outline icons (Lucide icon set, 24x24 coordinate space; license in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)) for context menus and dock controls.++## Requirements++- Windows 10 (version 2004 / build 19041 or later) or Windows 11+- Windows x64 architecture+- .NET 10 Desktop Runtime (or .NET 10 SDK when building from source)++## Run the Release++1. Get the latest `QiDock.exe` from the project's Releases page (or build it yourself, see below).+2. Save it in a folder you control and run it. Installation is not required.+3. QiDock replaces the Windows taskbar with a floating dock.++## Run from Source++With the .NET 10 SDK installed:++```powershell+dotnet run --project QiDock.csproj+```++To create a self-contained portable executable:++```powershell+powershell -ExecutionPolicy Bypass -File ".\scripts\publish-portable.ps1"+```++The output is written to `dist\QiDock.exe`.++Debug builds also accept a few command-line switches used to check the interface without a live session (`--render-ui <folder>`, `--render-desktop-widgets <file.png>`, `--memory-probe`, `--frame-probe`, `--audio-probe`, `--wifi-probe`, `--gallery-probe` …; see `App.xaml.cs`). They are compiled out of Release builds.++## Configuration and Storage++- `%LOCALAPPDATA%\QiDock\settings.json`: Preferences, alignment, theme, auto-hide, pin order, and `SurfaceOpacity` (0.6–1.0, default 0.9). Existing settings files receive the default opacity.+- `Widgets` in `settings.json`: widget order, hidden widgets, profiles, weather city, calendar iCal address, the seconds option, and widget data (folder path, saved colors, to-do items, world clocks, focus length).+- `Shortcuts` in `settings.json`: shortcuts added to the dock (name, target, arguments).+- `%LOCALAPPDATA%\QiDock\desktop-widgets.json`: desktop widgets — kind, size, position and per-widget options (note text, reminder interval, currencies…).+- `%LOCALAPPDATA%\QiDock\notifications.json`: which notifications were read, removed or cleared here. `notifications-copy\` holds the private copy of Windows' notification database.+- `%LOCALAPPDATA%\QiDock\taskbar-state.txt`: Safety journal that preserves the original Windows taskbar state for crash recovery.+- Task Scheduler task `QiDock`: starts the dock at sign-in when "Start with Windows" is on (the registry's `Software\Microsoft\Windows\CurrentVersion\Run\QiDock` is used only if the task cannot be created).+- `%LOCALAPPDATA%\QiDock\app.log`: start, exit, memory and error lines; `toast-windows.log`: what the Windows pop-up hider moved (kept under 64 KB).++## Project Structure++- `Design/`: Shared XAML styles, materials, typography, and dark/light color palettes (`Palettes/`).+- `Models/`: Application data structures (`DockApp.cs`, `DockSettings.cs`, `TrackedWindow.cs`, `WidgetSettings.cs`).+- `Services/`:+ - `TaskbarReplacementSession.cs`: Native Windows taskbar suppression, AppBar registration, and monitor layout.+ - `DockAutoHideController.cs`: Smart auto-hide, window overlap evaluation, and bottom edge trigger.+ - `WindowThumbnailPreview.cs`: DWM live multi-window thumbnail strip and preview cards.+ - `NativeWindowTracker.cs`: Win32 window event hooks and alert state tracking.+ - `ApplicationJumpListService.cs`: Background Jump List reader and task invocation.+ - `WindowsTaskbarPinImporter.cs`: Windows shortcut file importer and resolver.+ - `DockSettingsStore.cs` & `ApplicationPreferences.cs`: Settings persistence and state management.+- `Widgets/`: Widgets (`MediaWidget`, `WeatherWidget`, `ClockWidget`, `AiLimitsWidget`, `SystemWidget`, `BatteryWidget`, `QuickControlsWidget`, `ControlCenterWidget`, `NotificationsWidget`, `TrayWidget`, `FolderWidget`, `SearchWidget`, `ColorsWidget`, `AppVolumeWidget`, `FocusWidget`, `WorldClockWidget`, `TodoWidget`, `ToolsWidget`, `ProfileWidget`, `CurrencyWidget`, `StopwatchWidget`, `NoteWidget`, `AppGroupWidget`, `ProgressWidget`, `ReminderWidget`, `VoiceMemoWidget`), the `WidgetBar` host (shown in `TopBarWindow`) and shared popup/icon helpers (`WidgetUi.cs`).+- `Services/Widgets/`: Widget data sources — Open-Meteo weather, iCal feed parser, AI usage readers, Core Audio volume and per-app sessions, radios and battery.+- `DesktopWidgets/`: Desktop widgets — the per-card window (`DeskWidgetWindow`), layout and snapping (`DeskWidgetManager`), the gallery (`DeskGallery`), the catalog of kinds (`DeskCatalog`), shared data hubs (`DeskHubs`), drawing helpers (`DeskVisuals`) and the kinds themselves (`Kinds/`).+- `MainWindow.Desktop.cs`: Starts the desktop widgets and tells them which cards are covered by windows.+- `Services/Notifications/NotificationFeed.cs`: Reads Windows notifications, tracks read/removed state, and resolves each app's name, icon and window.+- `NotificationBanner.cs` & `MainWindow.Notifications.cs`: The top banners and the dock bell with its badge (`Widgets/NotificationsWidget.cs` has the bar tile); `Services/Notifications/WindowsToastHider.cs` keeps Windows' own pop-up off screen.+- `EdgePanel.cs`, `NotificationCenter.cs` & `ControlCenter.cs`: The panels that slide in from the right edge (`ControlCenter.Wifi.cs` and `Services/Widgets/WifiNetworks.cs`: the Wi-Fi network list).+- `Services/TrayHost.cs`: The hidden notification-area window that collects background apps' icons and forwards everything to Windows' own taskbar.+- `Overlays.cs`: AppGrid, QuickSearch and Window Overview (full-screen overlays); `Services/AppCatalog.cs` lists the installed apps.+- `Services/GpuTransparency.cs`: See-through windows composed by Windows itself (no layered-window copy), frosted glass for the side panels and blur behind AppGrid.+- `MainWindow.Extras.cs`: Global shortcuts, the Downloads stack, full-screen awareness and idle memory trimming.+- `MainWindow.Shortcuts.cs`: Desktop buttons, Recycle Bin and user dock shortcuts.+- `MainWindow.xaml`: Dock UI surface, Start button, application icon items, and context menus.+- `SettingsWindow.xaml`: Tabbed preferences window.++## License++QiDock is distributed under the MIT License. See [LICENSE](LICENSE). The outline icons come from Lucide (ISC); see [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).diff --git a/Services/AppCatalog.cs b/Services/AppCatalog.csnew file mode 100644index 0000000..58bc70a--- /dev/null+++ b/Services/AppCatalog.cs@@ -0,0 +1,87 @@+using System.Diagnostics;+using System.IO;+using System.Runtime.InteropServices;++namespace QiDock.Services;++/// <summary>An installed app as Windows lists it in "All apps": its name and shell parsing name.</summary>+public sealed record InstalledApp(string Name, string Id)+{+ public void Launch()+ {+ try+ {+ Process.Start(new ProcessStartInfo("explorer.exe", @"shell:AppsFolder\" + Id) { UseShellExecute = true })?.Dispose();+ }+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)+ {+ Trace.TraceWarning("Could not start {0}: {1}", Id, ex.Message);+ }+ }+}++/// <summary>+/// The apps of the Start menu's "All apps" list (desktop and Store apps alike), read from the+/// shell's Applications folder. The list is read when asked and not kept.+/// </summary>+public static class AppCatalog+{+ // Start menu entries that are documents or links rather than apps.+ private static readonly HashSet<string> DocumentExtensions = new(StringComparer.OrdinalIgnoreCase)+ {+ ".txt", ".chm", ".pdf", ".htm", ".html", ".url", ".rtf", ".ini", ".log", ".md", ".xml", ".hlp", ".doc", ".docx"+ };++ public static Task<List<InstalledApp>> LoadAsync()+ {+ var done = new TaskCompletionSource<List<InstalledApp>>();+ // Shell.Application needs a single-threaded apartment.+ var thread = new Thread(() =>+ {+ try { done.SetResult(Read()); }+ catch (Exception ex) when (ex is COMException or InvalidCastException or Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)+ {+ Trace.TraceWarning("Could not list apps: {0}", ex.Message);+ done.SetResult([]);+ }+ }) { IsBackground = true, Name = "App catalog" };+ thread.SetApartmentState(ApartmentState.STA);+ thread.Start();+ return done.Task;+ }++ private static List<InstalledApp> Read()+ {+ var list = new List<InstalledApp>();+ var type = Type.GetTypeFromProgID("Shell.Application");+ if (type is null) return list;+ dynamic shell = Activator.CreateInstance(type)!;+ try+ {+ dynamic? folder = shell.NameSpace("shell:AppsFolder");+ if (folder is null) return list;+ var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ foreach (dynamic item in folder.Items())+ {+ string name = item.Name ?? "";+ string id = item.Path ?? "";+ if (name.Length == 0 || id.Length == 0 || IsNoise(name, id) || !seen.Add(name)) continue;+ list.Add(new InstalledApp(name, id));+ }+ }+ finally+ {+ Marshal.FinalReleaseComObject(shell);+ }+ list.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.CurrentCultureIgnoreCase));+ return list;+ }++ private static bool IsNoise(string name, string id)+ {+ if (name.Contains("uninstall", StringComparison.OrdinalIgnoreCase) || name.Contains("kaldır", StringComparison.OrdinalIgnoreCase)) return true;+ if (id.StartsWith("http", StringComparison.OrdinalIgnoreCase)) return true;+ var extension = Path.GetExtension(id.Contains('!') ? "" : id);+ return extension.Length > 0 && DocumentExtensions.Contains(extension);+ }+}diff --git a/Services/AppLog.cs b/Services/AppLog.csnew file mode 100644index 0000000..82217f3--- /dev/null+++ b/Services/AppLog.cs@@ -0,0 +1,49 @@+using System.IO;++namespace QiDock.Services;++/// <summary>A small log of starts, exits and errors (%LOCALAPPDATA%\QiDock\app.log), so an unexpected exit can be traced.</summary>+public static class AppLog+{+ private static readonly object Gate = new();++ private static string Path => System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock", "app.log");++ private static System.Windows.Threading.DispatcherTimer? _memoryTimer;++ /// <summary>+ /// Writes how much memory the app holds a minute after start and then every 30 minutes (the whole process and+ /// the managed heap apart), so a growing footprint shows up in the log.+ /// </summary>+ public static void StartMemoryReports()+ {+ _memoryTimer = new System.Windows.Threading.DispatcherTimer(System.Windows.Threading.DispatcherPriority.Background) { Interval = TimeSpan.FromMinutes(1) };+ _memoryTimer.Tick += (_, _) =>+ {+ _memoryTimer.Interval = TimeSpan.FromMinutes(30);+ using var process = System.Diagnostics.Process.GetCurrentProcess();+ var gc = GC.GetGCMemoryInfo();+ Write($"Bellek: çalışma kümesi {process.WorkingSet64 >> 20} MB, özel {process.PrivateMemorySize64 >> 20} MB, " ++ $"yönetilen yığın {gc.HeapSizeBytes >> 20} MB (ayrılan {gc.TotalCommittedBytes >> 20} MB), iş parçacığı {process.Threads.Count}");+ };+ _memoryTimer.Start();+ }++ public static void Write(string message)+ {+ try+ {+ lock (Gate)+ {+ Directory.CreateDirectory(System.IO.Path.GetDirectoryName(Path)!);+ var file = new FileInfo(Path);+ if (file.Exists && file.Length > 512 * 1024) File.Move(Path, Path + ".old", overwrite: true);+ File.AppendAllText(Path, $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} {message}{Environment.NewLine}");+ }+ }+ catch+ {+ // logging never takes the app down+ }+ }+}diff --git a/Services/ApplicationIconProvider.cs b/Services/ApplicationIconProvider.csnew file mode 100644index 0000000..cff00ff--- /dev/null+++ b/Services/ApplicationIconProvider.cs@@ -0,0 +1,223 @@+using System.IO;+using System.Runtime.InteropServices;+using System.Windows.Interop;+using System.Windows.Media.Imaging;++namespace QiDock.Services;++public static class ApplicationIconProvider+{+ private const uint ShellIcon = 0x00000100;+ private const int TargetIconResolution = 128;++ public static BitmapSource? GetForFile(string path)+ {+ if (string.Equals(Path.GetExtension(path), ".exe", StringComparison.OrdinalIgnoreCase))+ {+ // Store apps (Calculator, Photos…) keep their icon in the package, not in the program file.+ if (GetPackagedLogo(path) is { } packaged) return packaged;+ var executableIcon = GetExecutableIcon(path);+ if (executableIcon is not null)+ {+ return executableIcon;+ }++ return null;+ }++ if (File.Exists(path))+ {+ var directIcon = GetExecutableIcon(path);+ if (directIcon is not null)+ {+ return directIcon;+ }+ }++ var fileInfo = new ShellFileInfo();+ var result = SHGetFileInfo(path, 0, ref fileInfo, (uint)Marshal.SizeOf<ShellFileInfo>(), ShellIcon);+ if (result == 0 || fileInfo.Icon == 0)+ {+ return null;+ }++ try+ {+ return ToBitmapSource(fileInfo.Icon);+ }+ finally+ {+ DestroyIcon(fileInfo.Icon);+ }+ }++ public static BitmapSource? GetForResource(string path, int index)+ {+ var expanded = Environment.ExpandEnvironmentVariables(path);+ return File.Exists(expanded) ? GetExecutableIcon(expanded, index) : null;+ }++ /// <summary>+ /// The logo a Store app shows in Windows' own taskbar: its package manifest names an image (Square44x44Logo) that+ /// exists in several sizes and variants; the largest "unplated" one (no coloured backplate) is used.+ /// </summary>+ private static BitmapSource? GetPackagedLogo(string executablePath)+ {+ try+ {+ var root = Path.GetDirectoryName(executablePath);+ for (var depth = 0; root is not null && depth < 4 && !File.Exists(Path.Combine(root, "AppxManifest.xml")); depth++)+ root = Path.GetDirectoryName(root);+ if (root is null || !File.Exists(Path.Combine(root, "AppxManifest.xml"))) return null;+ var relative = Path.GetRelativePath(root, executablePath);+ var manifest = System.Xml.Linq.XDocument.Load(Path.Combine(root, "AppxManifest.xml"));+ var applications = manifest.Descendants().Where(e => e.Name.LocalName == "Application").ToList();+ var application = applications.FirstOrDefault(e => string.Equals((string?)e.Attribute("Executable"), relative, StringComparison.OrdinalIgnoreCase))+ ?? (applications.Count == 1 ? applications[0] : null);+ var visuals = application?.Elements().FirstOrDefault(e => e.Name.LocalName == "VisualElements");+ var logo = (string?)visuals?.Attribute("Square44x44Logo") ?? (string?)visuals?.Attribute("Square150x150Logo");+ if (string.IsNullOrEmpty(logo)) return null;+ var logoPath = Path.Combine(root, logo);+ var folder = Path.GetDirectoryName(logoPath);+ if (folder is null || !Directory.Exists(folder)) return null;+ var stem = Path.GetFileNameWithoutExtension(logoPath);+ var extension = Path.GetExtension(logoPath);+ static int Number(string qualifiers, string key)+ {+ var at = qualifiers.IndexOf(key, StringComparison.OrdinalIgnoreCase);+ if (at < 0) return 0;+ var digits = new string(qualifiers.Skip(at + key.Length).TakeWhile(char.IsDigit).ToArray());+ return int.TryParse(digits, out var value) ? value : 0;+ }+ var best = Directory.EnumerateFiles(folder, stem + ".*" + extension)+ .Select(file => (File: file, Qualifiers: Path.GetFileNameWithoutExtension(file)[stem.Length..]))+ .Where(c => !c.Qualifiers.Contains("contrast-", StringComparison.OrdinalIgnoreCase)+ && !c.Qualifiers.Contains("lightunplated", StringComparison.OrdinalIgnoreCase))+ .Select(c => (c.File, Score:+ (c.Qualifiers.Contains("altform-unplated", StringComparison.OrdinalIgnoreCase) ? 100000 : 0)+ + Math.Min(Number(c.Qualifiers, "targetsize-"), 256) * 10+ + Number(c.Qualifiers, "scale-")))+ .OrderByDescending(c => c.Score)+ .Select(c => c.File)+ .FirstOrDefault() ?? (File.Exists(logoPath) ? logoPath : null);+ if (best is null) return null;+ var image = new BitmapImage();+ image.BeginInit();+ image.CacheOption = BitmapCacheOption.OnLoad;+ image.UriSource = new Uri(best);+ image.EndInit();+ image.Freeze();+ return image;+ }+ catch+ {+ return null; // an unreadable package falls back to the program file's own icon+ }+ }++ private static BitmapSource? GetExecutableIcon(string path, int index = 0)+ {+ // Primary path: Extract high-resolution icon resource (up to 128x128) for the large dock icons.+ var icons = new nint[1];+ var ids = new uint[1];+ try+ {+ var extracted = PrivateExtractIcons(path, index, TargetIconResolution, TargetIconResolution, icons, ids, 1, 0);+ if (extracted > 0 && icons[0] != 0)+ {+ try+ {+ return ToBitmapSource(icons[0]);+ }+ finally+ {+ DestroyIcon(icons[0]);+ }+ }+ }+ catch+ {+ // Fall through to ExtractIconEx when PrivateExtractIcons is unavailable+ }++ var count = ExtractIconEx(path, index, out var largeIcon, out var smallIcon, 1);+ if (count == 0 || (largeIcon == 0 && smallIcon == 0))+ {+ return null;+ }++ try+ {+ return ToBitmapSource(largeIcon != 0 ? largeIcon : smallIcon);+ }+ finally+ {+ if (largeIcon != 0)+ {+ DestroyIcon(largeIcon);+ }++ if (smallIcon != 0)+ {+ DestroyIcon(smallIcon);+ }+ }+ }++ private static BitmapSource? ToBitmapSource(nint iconHandle)+ {+ var iconCopy = CopyIcon(iconHandle);+ if (iconCopy == 0)+ {+ return null;+ }++ try+ {+ var bitmap = Imaging.CreateBitmapSourceFromHIcon(iconCopy, System.Windows.Int32Rect.Empty,+ BitmapSizeOptions.FromEmptyOptions());+ bitmap.Freeze();+ return bitmap;+ }+ finally+ {+ DestroyIcon(iconCopy);+ }+ }++ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]+ private struct ShellFileInfo+ {+ public nint Icon;+ public int IconIndex;+ public uint Attributes;+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]+ public string? DisplayName;+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]+ public string? TypeName;+ }++ [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]+ private static extern uint PrivateExtractIcons(+ string szFileName,+ int nIconIndex,+ int cxIcon,+ int cyIcon,+ nint[] phicon,+ uint[] piconid,+ uint nIcons,+ uint flags);++ [DllImport("shell32.dll", CharSet = CharSet.Unicode, EntryPoint = "ExtractIconExW")]+ private static extern uint ExtractIconEx(string file, int iconIndex, out nint largeIcon, out nint smallIcon, uint iconCount);++ [DllImport("shell32.dll", CharSet = CharSet.Unicode)]+ private static extern nint SHGetFileInfo(string path, uint fileAttributes, ref ShellFileInfo fileInfo, uint fileInfoSize, uint flags);++ [DllImport("user32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool DestroyIcon(nint iconHandle);++ [DllImport("user32.dll", SetLastError = true)]+ private static extern nint CopyIcon(nint iconHandle);+}diff --git a/Services/ApplicationJumpListService.cs b/Services/ApplicationJumpListService.csnew file mode 100644index 0000000..8c692df--- /dev/null+++ b/Services/ApplicationJumpListService.cs@@ -0,0 +1,134 @@+using System.ComponentModel;+using System.Diagnostics;+using System.Runtime.InteropServices;+using System.Windows.Threading;+using QiDock.Models;++namespace QiDock.Services;++public sealed class ApplicationJumpListService : IDisposable+{+ private readonly object _gate = new();+ private Task<Dispatcher>? _worker;+ private NativeJumpListSession? _session;+ private long _sessionId;+ private volatile bool _disposed;++ public async Task<ApplicationJumpList> ReadAsync(nint window, string? shortcut, CancellationToken cancellation)+ {+ var dispatcher = await GetWorker().WaitAsync(cancellation);+ return await dispatcher.InvokeAsync(() =>+ {+ cancellation.ThrowIfCancellationRequested();+ _session?.Dispose();+ _session = new NativeJumpListSession();+ var id = ++_sessionId;+ try+ {+ var result = _session.Read(id, window, shortcut, cancellation);+ cancellation.ThrowIfCancellationRequested();+ return result;+ }+ catch (OperationCanceledException)+ {+ _session.Dispose();+ _session = null;+ throw;+ }+ catch (COMException ex)+ {+ _session.Dispose();+ _session = null;+ Trace.TraceWarning("Jump List read failed: 0x{0:X8}", ex.HResult);+ var unsupported = ex.HResult is unchecked((int)0x80004002) or unchecked((int)0x80040154);+ return new ApplicationJumpList(id, unsupported ? JumpListStatus.Unsupported : JumpListStatus.Unavailable, []);+ }+ catch (InvalidOperationException)+ {+ _session.Dispose();+ _session = null;+ return new ApplicationJumpList(id, JumpListStatus.Unavailable, []);+ }+ }, DispatcherPriority.Normal, cancellation).Task.WaitAsync(cancellation);+ }++ public async Task<bool> InvokeAsync(long sessionId, int commandId, nint owner)+ {+ try+ {+ var dispatcher = await GetWorker();+ return await dispatcher.InvokeAsync(() =>+ {+ if (_disposed || _session is null || _sessionId != sessionId) return false;+ try { _session.Invoke(commandId, owner); return true; }+ catch (COMException ex) { Trace.TraceWarning("Jump List invocation failed: 0x{0:X8}", ex.HResult); return false; }+ catch (InvalidOperationException) { return false; }+ catch (Win32Exception ex) { Trace.TraceWarning("Jump List invocation failed: {0}", ex.NativeErrorCode); return false; }+ }).Task;+ }+ catch (OperationCanceledException) when (_disposed) { return false; }+ catch (ObjectDisposedException) when (_disposed) { return false; }+ }++ public async Task ReleaseAsync(long sessionId)+ {+ if (_disposed) return;+ try+ {+ var dispatcher = await GetWorker();+ await dispatcher.InvokeAsync(() =>+ {+ if (_sessionId != sessionId) return;+ _session?.Dispose();+ _session = null;+ }).Task;+ }+ catch (OperationCanceledException) when (_disposed) { /* The worker's finally releases the session. */ }+ catch (ObjectDisposedException) when (_disposed) { /* Shutdown owns cleanup. */ }+ }++ private Task<Dispatcher> GetWorker()+ {+ lock (_gate)+ {+ ObjectDisposedException.ThrowIf(_disposed, this);+ if (_worker is not null) return _worker;+ var ready = new TaskCompletionSource<Dispatcher>(TaskCreationOptions.RunContinuationsAsynchronously);+ _worker = ready.Task;+ var thread = new Thread(() =>+ {+ var result = CoInitializeEx(0, 2);+ if (result < 0) { ready.SetException(new COMException("Shell STA initialization failed.", result)); return; }+ try+ {+ ready.SetResult(Dispatcher.CurrentDispatcher);+ if (_disposed) Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);+ Dispatcher.Run();+ }+ finally+ {+ _session?.Dispose();+ _session = null;+ CoUninitialize();+ }+ }) { IsBackground = true, Name = "QiDock Jump Lists" };+ thread.SetApartmentState(ApartmentState.STA);+ thread.Start();+ return _worker;+ }+ }++ public void Dispose()+ {+ lock (_gate)+ {+ if (_disposed) return;+ _disposed = true;+ if (_worker?.IsCompletedSuccessfully == true)+ _worker.Result.BeginInvokeShutdown(DispatcherPriority.Background);+ }+ }++ [DllImport("ole32.dll")] private static extern int CoInitializeEx(nint reserved, uint flags);+ [DllImport("ole32.dll")] private static extern void CoUninitialize();+}diff --git a/Services/ApplicationPreferences.cs b/Services/ApplicationPreferences.csnew file mode 100644index 0000000..ce00d80--- /dev/null+++ b/Services/ApplicationPreferences.cs@@ -0,0 +1,29 @@+using QiDock.Models;++namespace QiDock.Services;++public sealed class ApplicationPreferences+{+ private readonly DockSettingsStore _store;+ public DockSettings Current { get; private set; }+ public string? LoadError { get; private set; }+ public event EventHandler? Changed;++ public ApplicationPreferences(DockSettingsStore store)+ {+ _store = store;+ (Current, LoadError) = store.Load();+ }++ public string? Save(DockSettings settings)+ {+ var error = _store.Save(settings);+ if (error is not null) return error;+ Current = settings;+ LoadError = null;+ UiText.Current.SetLanguage(settings.Language);+ ThemeManager.Apply(settings.Theme, settings.SurfaceOpacity, settings.Style);+ Changed?.Invoke(this, EventArgs.Empty);+ return null;+ }+}diff --git a/Services/ApplicationWindowMenu.cs b/Services/ApplicationWindowMenu.csnew file mode 100644index 0000000..3ead89c--- /dev/null+++ b/Services/ApplicationWindowMenu.cs@@ -0,0 +1,80 @@+using System.Runtime.InteropServices;+using System.Text;++namespace QiDock.Services;++public sealed record WindowMenuCommand(nint Window, nint Menu, uint Id, bool IsSystem);+public sealed record WindowMenuEntry(string Label, bool Enabled, bool Checked,+ WindowMenuCommand? Command, IReadOnlyList<WindowMenuEntry> Children, bool IsSeparator = false);++public static class ApplicationWindowMenu+{+ private const uint ByPosition = 0x400;++ public static IReadOnlyList<WindowMenuEntry> Read(nint window, bool system)+ {+ if (!IsWindow(window)) return [];+ var menu = system ? GetSystemMenu(window, false) : GetMenu(window);+ if (menu == 0) return [];+ // Let the owner refresh its own command state, without waiting on a hung process.+ if (SendMessageTimeout(window, 0x0116, menu, 0, 2, 80, out _) == 0) return [];+ var budget = 100;+ return ReadMenu(window, menu, system, 0, ref budget);+ }++ private static IReadOnlyList<WindowMenuEntry> ReadMenu(nint window, nint menu, bool system, int depth, ref int budget)+ {+ if (depth >= 5) return [];+ var entries = new List<WindowMenuEntry>();+ var count = Math.Min(GetMenuItemCount(menu), 100);+ for (uint index = 0; index < count && budget > 0; index++)+ {+ budget--;+ var state = GetMenuState(menu, index, ByPosition);+ if (state == uint.MaxValue) continue;+ if ((state & 0x800) != 0)+ {+ if (entries.Count > 0 && !entries[^1].IsSeparator)+ entries.Add(new WindowMenuEntry("", false, false, null, [], true));+ continue;+ }+ var text = new StringBuilder(512);+ if (GetMenuString(menu, index, text, text.Capacity, ByPosition) <= 0) continue;+ var label = text.ToString().Split('\t')[0].Replace("&", "").Trim();+ if (label.Length == 0) continue;+ var submenu = GetSubMenu(menu, (int)index);+ var children = submenu == 0 ? [] : ReadMenu(window, submenu, system, depth + 1, ref budget);+ var id = GetMenuItemID(menu, (int)index);+ var command = submenu == 0 && id != uint.MaxValue ? new WindowMenuCommand(window, menu, id, system) : null;+ if (command is null && children.Count == 0) continue;+ entries.Add(new WindowMenuEntry(label, (state & 3) == 0, (state & 8) != 0, command, children));+ }+ if (entries.Count > 0 && entries[^1].IsSeparator) entries.RemoveAt(entries.Count - 1);+ return entries;+ }++ public static bool Invoke(WindowMenuCommand command)+ {+ if (!IsWindow(command.Window) || !IsMenu(command.Menu)) return false;+ var state = GetMenuState(command.Menu, command.Id, 0);+ if (state == uint.MaxValue || (state & 3) != 0) return false;+ if (!NativeWindowTracker.Activate(command.Window)) return false;+ return PostMessage(command.Window, command.IsSystem ? 0x0112u : 0x0111u, (nint)command.Id, 0);+ }++ [DllImport("user32.dll")] private static extern nint GetMenu(nint window);+ [DllImport("user32.dll")] private static extern nint GetSystemMenu(nint window, [MarshalAs(UnmanagedType.Bool)] bool revert);+ [DllImport("user32.dll")] private static extern int GetMenuItemCount(nint menu);+ [DllImport("user32.dll")] private static extern uint GetMenuItemID(nint menu, int position);+ [DllImport("user32.dll")] private static extern nint GetSubMenu(nint menu, int position);+ [DllImport("user32.dll")] private static extern uint GetMenuState(nint menu, uint item, uint flags);+ [DllImport("user32.dll", CharSet = CharSet.Unicode)]+ private static extern int GetMenuString(nint menu, uint item, StringBuilder text, int count, uint flags);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsWindow(nint window);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsMenu(nint menu);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool PostMessage(nint window, uint message, nint wParam, nint lParam);+ [DllImport("user32.dll", CharSet = CharSet.Unicode)]+ private static extern nint SendMessageTimeout(nint window, uint message, nint wParam, nint lParam,+ uint flags, uint timeout, out nuint result);+}diff --git a/Services/ClaudeActivityWatcher.cs b/Services/ClaudeActivityWatcher.csnew file mode 100644index 0000000..fb769c0--- /dev/null+++ b/Services/ClaudeActivityWatcher.cs@@ -0,0 +1,191 @@+using System.IO;+using System.Text;+using System.Text.Json;+using System.Windows.Threading;++namespace QiDock.Services;++/// <summary>What a Claude Code session did last, read from the end of its transcript.</summary>+public sealed record ClaudeActivity(string SessionFile, string Project, string Detail, bool Done, DateTime UpdatedAt)+{+ /// <summary>Still at work: not finished and written to within the last minute and a half.</summary>+ public bool Working => !Done && DateTime.UtcNow - UpdatedAt < TimeSpan.FromSeconds(90);+}++/// <summary>+/// The Claude Code sessions on this PC (<c>%USERPROFILE%\.claude\projects\**\*.jsonl</c>), read without any network+/// access: the last few kilobytes of each recent transcript are turned into a short line ("2 dosya düzenleniyor…",+/// "Komut çalışıyor…", "Bitti"). Nothing is written and nothing is kept. Only used while the Claude card is open:+/// <see cref="RecentAsync"/> lists the sessions, and the watcher reports changes while the card stays open.+/// </summary>+public sealed class ClaudeActivityWatcher : IDisposable+{+ private const int TailBytes = 64 * 1024;+ private static readonly string Root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".claude", "projects");++ private readonly Dispatcher _dispatcher;+ private FileSystemWatcher? _watcher;+ private readonly DispatcherTimer _debounce;++ /// <summary>A transcript changed (raised on the UI thread, at most a few times a second).</summary>+ public event Action? Changed;++ public ClaudeActivityWatcher(Dispatcher dispatcher)+ {+ _dispatcher = dispatcher;+ _debounce = new DispatcherTimer(DispatcherPriority.Background, dispatcher) { Interval = TimeSpan.FromMilliseconds(600) };+ _debounce.Tick += (_, _) =>+ {+ _debounce.Stop();+ Changed?.Invoke();+ };+ }++ /// <summary>The sessions written to within <paramref name="within"/>, newest first (at most <paramref name="limit"/>).</summary>+ public static Task<List<ClaudeActivity>> RecentAsync(TimeSpan within, int limit = 5) => Task.Run(() =>+ {+ if (!Directory.Exists(Root)) return new List<ClaudeActivity>();+ var since = DateTime.UtcNow - within;+ try+ {+ return new DirectoryInfo(Root).EnumerateFiles("*.jsonl", SearchOption.AllDirectories)+ .Where(file => file.LastWriteTimeUtc >= since && !IsSubagent(file.FullName))+ .OrderByDescending(file => file.LastWriteTimeUtc)+ .Take(limit)+ .Select(file => Read(file.FullName, file.LastWriteTimeUtc))+ .OfType<ClaudeActivity>()+ .ToList();+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ return new List<ClaudeActivity>();+ }+ });++ // Subagent transcripts (…\subagents\…) belong to their main session, which reports the Agent step itself.+ private static bool IsSubagent(string path) =>+ path.Contains($"{Path.DirectorySeparatorChar}subagents{Path.DirectorySeparatorChar}", StringComparison.OrdinalIgnoreCase);++ public void Start()+ {+ if (_watcher is not null || !Directory.Exists(Root)) return;+ try+ {+ _watcher = new FileSystemWatcher(Root, "*.jsonl")+ {+ IncludeSubdirectories = true,+ NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.FileName,+ InternalBufferSize = 16 * 1024+ };+ _watcher.Changed += OnFileEvent;+ _watcher.Created += OnFileEvent;+ _watcher.EnableRaisingEvents = true;+ }+ catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException or PlatformNotSupportedException)+ {+ AppLog.Write($"Claude oturumları izlenemiyor: {ex.Message}");+ _watcher?.Dispose();+ _watcher = null;+ }+ }++ public void Stop()+ {+ _debounce.Stop();+ _watcher?.Dispose();+ _watcher = null;+ }++ private void OnFileEvent(object sender, FileSystemEventArgs e)+ {+ if (IsSubagent(e.FullPath)) return;+ _dispatcher.BeginInvoke(() =>+ {+ if (!_debounce.IsEnabled) _debounce.Start();+ });+ }++ private static ClaudeActivity? Read(string path, DateTime writtenAt)+ {+ try+ {+ using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);+ var start = Math.Max(0, stream.Length - TailBytes);+ stream.Seek(start, SeekOrigin.Begin);+ var buffer = new byte[stream.Length - start];+ var read = stream.Read(buffer, 0, buffer.Length);+ var lines = Encoding.UTF8.GetString(buffer, 0, read).Split('\n');+ // Newest first; the first line may be cut in half and is skipped.+ for (var i = lines.Length - 1; i >= (start > 0 ? 1 : 0); i--)+ {+ var line = lines[i].Trim();+ if (line.Length == 0 || line[0] != '{') continue;+ (string Project, string Detail, bool Done)? step;+ try { step = Describe(line); }+ catch (JsonException) { continue; } // a line still being written+ if (step is { } found)+ return new ClaudeActivity(path, found.Project, found.Detail, found.Done, writtenAt);+ }+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)+ {+ }+ return null;+ }++ /// <summary>A transcript line turned into (project, what is happening, finished), or null for lines that say nothing.</summary>+ private static (string Project, string Detail, bool Done)? Describe(string line)+ {+ using var document = JsonDocument.Parse(line);+ var root = document.RootElement;+ if (root.ValueKind != JsonValueKind.Object) return null;+ var type = root.TryGetProperty("type", out var t) ? t.GetString() : null;+ if (type is not ("assistant" or "user")) return null;+ if (root.TryGetProperty("isSidechain", out var side) && side.ValueKind == JsonValueKind.True) return null;+ var project = root.TryGetProperty("cwd", out var cwd) && cwd.GetString() is { Length: > 0 } dir+ ? Path.GetFileName(dir.TrimEnd('\\', '/')) : "Claude";+ if (!root.TryGetProperty("message", out var message) || message.ValueKind != JsonValueKind.Object) return null;+ var content = message.TryGetProperty("content", out var c) ? c : default;++ if (type == "user")+ {+ // A tool's result came back, or the user wrote: Claude is thinking about the next step.+ return (project, UiText.Get("ClaudeThinking"), false);+ }++ var stop = message.TryGetProperty("stop_reason", out var s) ? s.GetString() : null;+ var tools = new List<(string Name, JsonElement Input)>();+ if (content.ValueKind == JsonValueKind.Array)+ foreach (var part in content.EnumerateArray())+ if (part.TryGetProperty("type", out var pt) && pt.GetString() == "tool_use" && part.TryGetProperty("name", out var name))+ tools.Add((name.GetString() ?? "", part.TryGetProperty("input", out var input) ? input : default));+ if (tools.Count == 0)+ return stop is "end_turn" or "stop_sequence" ? (project, UiText.Get("ClaudeDone"), true) : (project, UiText.Get("ClaudeWriting"), false);+ return (project, ToolLine(tools), false);+ }++ private static string ToolLine(List<(string Name, JsonElement Input)> tools)+ {+ static string? Field(JsonElement input, string key) =>+ input.ValueKind == JsonValueKind.Object && input.TryGetProperty(key, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;+ var edits = tools.Where(x => x.Name is "Edit" or "Write" or "MultiEdit" or "NotebookEdit")+ .Select(x => Field(x.Input, "file_path") ?? Field(x.Input, "notebook_path") ?? x.Name).Distinct(StringComparer.OrdinalIgnoreCase).Count();+ if (edits > 0) return edits == 1 && tools.FirstOrDefault(x => x.Name is "Edit" or "Write" or "MultiEdit").Input is var input && Field(input, "file_path") is { } file+ ? UiText.Format("ClaudeEditingFile", Path.GetFileName(file))+ : UiText.Format("ClaudeEditingFiles", edits);+ var last = tools[^1];+ return last.Name switch+ {+ "Bash" or "PowerShell" => Field(last.Input, "description") is { Length: > 0 } what ? Trim(what) : UiText.Get("ClaudeRunning"),+ "Read" or "Grep" or "Glob" => UiText.Get("ClaudeReading"),+ "WebSearch" or "WebFetch" => UiText.Get("ClaudeBrowsing"),+ "Agent" or "Task" or "Workflow" => UiText.Get("ClaudeAgents"),+ _ when last.Name.StartsWith("mcp__", StringComparison.Ordinal) => UiText.Get("ClaudeTools"),+ _ => UiText.Get("ClaudeWorking")+ };+ }++ private static string Trim(string text) => text.Length <= 42 ? text : text[..41].TrimEnd() + "…";++ public void Dispose() => Stop();+}diff --git a/Services/DockAutoHideController.cs b/Services/DockAutoHideController.csnew file mode 100644index 0000000..de9cfe2--- /dev/null+++ b/Services/DockAutoHideController.cs@@ -0,0 +1,273 @@+using System.Diagnostics;+using System.Runtime.InteropServices;+using System.Text;+using System.Windows;+using System.Windows.Media;+using System.Windows.Media.Animation;+using System.Windows.Threading;+using QiDock.Models;++namespace QiDock.Services;++public sealed class DockAutoHideController : IDisposable+{+ private const uint MonitorDefaultToNearest = 2;++ private readonly Window _window;+ private readonly nint _windowHandle;+ private readonly TranslateTransform _dockTranslate;+ private readonly FrameworkElement _dockSurface;+ private readonly Func<bool> _isInteractionLocked;+ private readonly DispatcherTimer _hideTimer;+ // The pointer has to rest on the bottom edge briefly; brushing past it does nothing.+ private readonly DispatcherTimer _revealTimer;+ private bool _disposed;++ public AutoHideMode Mode { get; private set; } = AutoHideMode.Disabled;+ public bool IsHidden { get; private set; }+ public bool IsMouseOverDock { get; private set; }+ public bool IsMouseAtEdge { get; private set; }+ public bool HasOverlap { get; private set; }++ public event Action<bool>? VisibilityChanged;++ public DockAutoHideController(+ Window window,+ nint windowHandle,+ TranslateTransform dockTranslate,+ FrameworkElement dockSurface,+ Func<bool> isInteractionLocked)+ {+ _window = window;+ _windowHandle = windowHandle;+ _dockTranslate = dockTranslate;+ _dockSurface = dockSurface;+ _isInteractionLocked = isInteractionLocked;++ _hideTimer = new DispatcherTimer(DispatcherPriority.Normal)+ {+ // Leaving the dock hides it almost at once; a short grace keeps a wobbly pointer from flickering it.+ Interval = TimeSpan.FromMilliseconds(90)+ };+ _hideTimer.Tick += HideTimer_Tick;+ _revealTimer = new DispatcherTimer(DispatcherPriority.Normal)+ {+ Interval = TimeSpan.FromMilliseconds(160)+ };+ _revealTimer.Tick += (_, _) =>+ {+ _revealTimer.Stop();+ if (IsMouseAtEdge && IsHidden) AnimateReveal();+ };+ }++ public void SetMode(AutoHideMode mode)+ {+ if (Mode == mode) return;+ Mode = mode;+ if (Mode == AutoHideMode.Disabled)+ {+ _hideTimer.Stop();+ AnimateReveal();+ }+ else+ {+ EvaluateState();+ }+ }++ public void OnMouseEnterDock()+ {+ IsMouseOverDock = true;+ _hideTimer.Stop();+ if (IsHidden)+ {+ AnimateReveal();+ }+ }++ public void OnMouseLeaveDock()+ {+ IsMouseOverDock = false;+ EvaluateState();+ }++ public void OnMouseEnterEdge()+ {+ IsMouseAtEdge = true;+ _hideTimer.Stop();+ if (IsHidden)+ {+ // Reveal immediately when the pointer reaches the bottom edge.+ _revealTimer.Stop();+ AnimateReveal();+ }+ }++ public void OnMouseLeaveEdge()+ {+ IsMouseAtEdge = false;+ _revealTimer.Stop();+ EvaluateState();+ }++ public void CheckForegroundWindow(nint foregroundHwnd)+ {+ if (Mode != AutoHideMode.Smart) return;+ HasOverlap = EvaluateWindowOverlap(foregroundHwnd);+ EvaluateState();+ }++ public void EvaluateState()+ {+ if (_disposed || Mode == AutoHideMode.Disabled) return;++ if (ShouldHide())+ {+ if (!IsHidden && !_hideTimer.IsEnabled)+ {+ _hideTimer.Start();+ }+ }+ else+ {+ _hideTimer.Stop();+ if (IsHidden)+ {+ AnimateReveal();+ }+ }+ }++ private bool ShouldHide()+ {+ if (Mode == AutoHideMode.Disabled) return false;+ if (IsMouseOverDock || IsMouseAtEdge) return false;+ if (_isInteractionLocked()) return false;+ if (Mode == AutoHideMode.Always) return true;+ if (Mode == AutoHideMode.Smart) return HasOverlap;+ return false;+ }++ private void HideTimer_Tick(object? sender, EventArgs e)+ {+ _hideTimer.Stop();+ if (ShouldHide() && !IsHidden)+ {+ AnimateHide();+ }+ }++ public void AnimateReveal()+ {+ IsHidden = false;+ _hideTimer.Stop();+ var anim = new DoubleAnimation+ {+ To = 0,+ Duration = TimeSpan.FromMilliseconds(150),+ EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }+ };+ _dockTranslate.BeginAnimation(TranslateTransform.YProperty, anim);+ VisibilityChanged?.Invoke(true);+ }++ public void AnimateHide()+ {+ IsHidden = true;+ double hideOffset = Math.Max(72, _dockSurface.ActualHeight + 16);+ var anim = new DoubleAnimation+ {+ To = hideOffset,+ Duration = TimeSpan.FromMilliseconds(150),+ EasingFunction = new CubicEase { EasingMode = EasingMode.EaseIn }+ };+ _dockTranslate.BeginAnimation(TranslateTransform.YProperty, anim);+ VisibilityChanged?.Invoke(false);+ }++ private bool EvaluateWindowOverlap(nint hwnd)+ {+ if (hwnd == 0 || !IsWindow(hwnd) || !IsWindowVisible(hwnd) || IsIconic(hwnd))+ return false;++ if (hwnd == _windowHandle)+ return false;++ var className = new StringBuilder(64);+ GetClassName(hwnd, className, 64);+ var cls = className.ToString();+ if (cls is "Progman" or "WorkerW" or "Shell_TrayWnd")+ return false;++ var dockMonitor = MonitorFromWindow(_windowHandle, MonitorDefaultToNearest);+ var windowMonitor = MonitorFromWindow(hwnd, MonitorDefaultToNearest);+ if (dockMonitor != windowMonitor)+ return false;++ if (IsZoomed(hwnd))+ return true;++ if (GetWindowRect(hwnd, out var winRect) && GetWindowRect(_windowHandle, out var dockRect))+ {+ // The dock window's inner 16 px are headroom, not dock: a window may reach into them.+ switch (DockGeometry.Edge)+ {+ case Models.DockEdge.Top: dockRect.Bottom -= 16; break;+ case Models.DockEdge.Left: dockRect.Right -= 16; break;+ case Models.DockEdge.Right: dockRect.Left += 16; break;+ default: dockRect.Top += 16; break;+ }+ return winRect.Left < dockRect.Right+ && winRect.Right > dockRect.Left+ && winRect.Bottom > dockRect.Top+ && winRect.Top < dockRect.Bottom;+ }++ return false;+ }++ public void Dispose()+ {+ if (_disposed) return;+ _disposed = true;+ _hideTimer.Stop();+ _hideTimer.Tick -= HideTimer_Tick;+ _revealTimer.Stop();+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct Rect+ {+ public int Left;+ public int Top;+ public int Right;+ public int Bottom;+ }++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool GetWindowRect(nint hWnd, out Rect lpRect);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool IsZoomed(nint hWnd);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool IsWindow(nint hWnd);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool IsWindowVisible(nint hWnd);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool IsIconic(nint hWnd);++ [DllImport("user32.dll")]+ private static extern nint MonitorFromWindow(nint hWnd, uint dwFlags);++ [DllImport("user32.dll", CharSet = CharSet.Unicode)]+ private static extern int GetClassName(nint hWnd, StringBuilder lpClassName, int nMaxCount);+}diff --git a/Services/DockGeometry.cs b/Services/DockGeometry.csnew file mode 100644index 0000000..d90693c--- /dev/null+++ b/Services/DockGeometry.cs@@ -0,0 +1,34 @@+using System.Windows.Controls.Primitives;+using System.Windows.Media;+using QiDock.Models;++namespace QiDock.Services;++/// <summary>+/// The dock is laid out once, as if it stood on the bottom edge (its "frame"), and turned to the edge it really+/// stands on. Everything that is placed next to the dock (panels, previews, menus) asks here which way is "inward".+/// </summary>+public static class DockGeometry+{+ public static DockEdge Edge { get; set; } = DockEdge.Bottom;++ public static bool Vertical => Edge is DockEdge.Left or DockEdge.Right;++ /// <summary>Turns the bottom-edge frame to the real edge (linear part only): frame "down" points at the screen edge.</summary>+ public static Matrix FrameToScreen(DockEdge edge) => edge switch+ {+ DockEdge.Top => new Matrix(1, 0, 0, -1, 0, 0), // mirrored top to bottom+ DockEdge.Left => new Matrix(0, 1, -1, 0, 0, 0), // turned a quarter: down -> left, right -> down+ DockEdge.Right => new Matrix(0, 1, 1, 0, 0, 0), // down -> right, right -> down+ _ => Matrix.Identity+ };++ /// <summary>Where things open next to a dock tile: away from the screen edge.</summary>+ public static PlacementMode Inward => Edge switch+ {+ DockEdge.Top => PlacementMode.Bottom,+ DockEdge.Left => PlacementMode.Right,+ DockEdge.Right => PlacementMode.Left,+ _ => PlacementMode.Top+ };+}diff --git a/Services/DockSettingsStore.cs b/Services/DockSettingsStore.csnew file mode 100644index 0000000..dd7d16e--- /dev/null+++ b/Services/DockSettingsStore.cs@@ -0,0 +1,94 @@+using System.IO;+using System.Text.Json;+using System.Text.Json.Serialization;+using QiDock.Models;++namespace QiDock.Services;++public sealed class DockSettingsStore+{+ private static readonly JsonSerializerOptions JsonOptions = CreateJsonOptions();++ private readonly string _path;++ public DockSettingsStore(string? path = null)+ {+ _path = path ?? Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),+ "QiDock",+ "settings.json");+ }++ public (DockSettings Settings, string? Error) Load()+ {+ if (!File.Exists(_path))+ {+ return (new DockSettings(), null);+ }++ try+ {+ var settings = JsonSerializer.Deserialize<DockSettings>(File.ReadAllText(_path), JsonOptions);+ if (settings is null || !IsValid(settings))+ {+ return (new DockSettings(), "Dock ayarları geçersiz. Dosyayı düzeltin veya silip uygulamayı yeniden başlatın.");+ }++ return (settings, null);+ }+ catch (JsonException)+ {+ return (new DockSettings(), "Dock ayarları okunamadı. JSON biçimini düzeltin veya dosyayı silip yeniden başlatın.");+ }+ catch (IOException)+ {+ return (new DockSettings(), "Dock ayarları diskten okunamadı.");+ }+ catch (UnauthorizedAccessException)+ {+ return (new DockSettings(), "Dock ayarlarına erişim izni yok.");+ }+ }++ public string? Save(DockSettings settings)+ {+ if (!IsValid(settings))+ return "Ayar değerleri geçersiz.";+ try+ {+ var directory = Path.GetDirectoryName(_path);+ if (directory is null)+ {+ return "Dock ayarları için kayıt yolu oluşturulamadı.";+ }++ Directory.CreateDirectory(directory);+ var temporaryPath = _path + ".tmp";+ File.WriteAllText(temporaryPath, JsonSerializer.Serialize(settings, JsonOptions));+ File.Move(temporaryPath, _path, overwrite: true);+ return null;+ }+ catch (IOException)+ {+ return "Dock ayarları diske kaydedilemedi.";+ }+ catch (UnauthorizedAccessException)+ {+ return "Dock ayarlarına yazma izni yok.";+ }+ }++ private static bool IsValid(DockSettings settings) => Enum.IsDefined(settings.Position)+ && Enum.IsDefined(settings.Theme) && Enum.IsDefined(settings.Language)+ && Enum.IsDefined(settings.AutoHide)+ && double.IsFinite(settings.SurfaceOpacity) && settings.SurfaceOpacity is >= 0.6 and <= 1+ && settings.PinOrder?.Any(string.IsNullOrWhiteSpace) != true+ && settings.PinOrder?.Distinct(StringComparer.OrdinalIgnoreCase).Count() == settings.PinOrder?.Count;++ private static JsonSerializerOptions CreateJsonOptions()+ {+ var options = new JsonSerializerOptions { WriteIndented = true };+ options.Converters.Add(new JsonStringEnumConverter());+ return options;+ }+}diff --git a/Services/FocusTimer.cs b/Services/FocusTimer.csnew file mode 100644index 0000000..dfc0582--- /dev/null+++ b/Services/FocusTimer.cs@@ -0,0 +1,178 @@+using System.Media;+using System.Windows.Threading;+using QiDock.Widgets;++namespace QiDock.Services;++/// <summary>+/// The one focus (pomodoro) timer behind the bar's focus tile and the desktop focus widget, so both always show the+/// same countdown. A focus session is followed by a short break (a long one after every fourth round); the+/// one-second timer runs only while a countdown is running.+/// </summary>+public static class FocusTimer+{+ public const int Rounds = 4;+ private static readonly TimeSpan ShortBreak = TimeSpan.FromMinutes(5);+ private static readonly TimeSpan LongBreak = TimeSpan.FromMinutes(15);+ private static DispatcherTimer? _timer;+ private static TimeSpan _remaining;+ private static TimeSpan _breakLength = ShortBreak;+ private static bool _fresh = true; // a full, untouched focus session: follows the length setting+ private static DateTime _endsAt;+ private static int _completed;+ private static DateTime _completedOn = DateTime.Today;++ /// <summary>The focus length from the settings, in minutes.</summary>+ public static Func<int> Minutes { get; set; } = () => 25;++ /// <summary>Raised on every change and every second while running.</summary>+ public static event EventHandler? Changed;++ public static bool Running { get; private set; }+ public static bool OnBreak { get; private set; }+ public static int Round { get; private set; } = 1;++ public static TimeSpan FocusLength => TimeSpan.FromMinutes(Math.Clamp(Minutes(), 1, 180));++ /// <summary>Length of the current phase (focus or break), for progress rings.</summary>+ public static TimeSpan PhaseLength => OnBreak ? _breakLength : FocusLength;++ public static TimeSpan Remaining+ {+ get+ {+ var left = Running ? _endsAt - DateTime.UtcNow : _fresh && !OnBreak ? FocusLength : _remaining;+ return left < TimeSpan.Zero ? TimeSpan.Zero : left;+ }+ }++ /// <summary>True when there is something to reset: running, paused part-way, or on a break.</summary>+ public static bool Started => Running || OnBreak || !_fresh;++ public static int CompletedToday+ {+ get+ {+ if (_completedOn != DateTime.Today)+ {+ _completedOn = DateTime.Today;+ _completed = 0;+ }+ return _completed;+ }+ }++ public static void Toggle()+ {+ if (Running) Pause();+ else Start();+ }++ public static void Start()+ {+ if (Running) return;+ var left = Remaining;+ if (left <= TimeSpan.Zero) left = PhaseLength;+ _fresh = false;+ _endsAt = DateTime.UtcNow + left;+ Running = true;+ Timer.Start();+ Raise();+ }++ public static void Pause()+ {+ if (!Running) return;+ _remaining = Remaining;+ Running = false;+ Timer.Stop();+ Raise();+ }++ /// <summary>Back to a full focus session, stopped.</summary>+ public static void Reset()+ {+ Stop();+ OnBreak = false;+ _fresh = true;+ Raise();+ }++ /// <summary>Starts a five-minute break now.</summary>+ public static void StartBreak()+ {+ Stop();+ OnBreak = true;+ _breakLength = ShortBreak;+ _remaining = ShortBreak;+ Start();+ }++ /// <summary>Moves on to the next phase without finishing this one (a skipped session is not counted).</summary>+ public static void Skip()+ {+ Stop();+ Advance();+ Raise();+ }++ private static void Stop()+ {+ Running = false;+ _timer?.Stop();+ }++ private static void Advance()+ {+ if (OnBreak)+ {+ OnBreak = false;+ if (Round > Rounds) Round = 1;+ _fresh = true;+ }+ else+ {+ Round++;+ OnBreak = true;+ _breakLength = Round > Rounds ? LongBreak : ShortBreak;+ _remaining = _breakLength;+ _fresh = false;+ }+ }++ private static DispatcherTimer Timer+ {+ get+ {+ if (_timer is not null) return _timer;+ _timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(1) };+ _timer.Tick += (_, _) =>+ {+ if (Remaining > TimeSpan.Zero)+ {+ Raise();+ return;+ }+ Finish();+ };+ return _timer;+ }+ }++ private static void Finish()+ {+ Stop();+ var wasBreak = OnBreak;+ if (!wasBreak)+ {+ _ = CompletedToday; // starts a new day's count after midnight+ _completed++;+ }+ Advance();+ SystemSounds.Asterisk.Play();+ Ui.ShowHud("IconTimer", UiText.Get(wasBreak ? "FocusBreakDone" : "FocusDone"));+ Raise();+ }++ private static void Raise() => Changed?.Invoke(null, EventArgs.Empty);+}diff --git a/Services/GenieAnimator.cs b/Services/GenieAnimator.csnew file mode 100644index 0000000..476c1a5--- /dev/null+++ b/Services/GenieAnimator.cs@@ -0,0 +1,672 @@+using System.Diagnostics;+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Interop;+using System.Windows.Media;+using System.Windows.Media.Imaging;+using System.Windows.Media.Media3D;+using System.Windows.Threading;++namespace QiDock.Services;++/// <summary>+/// The "genie" effect for windows opened from or minimized into the dock.+/// Windows cannot warp another process's window, so the effect is staged: the window's image is+/// captured with PrintWindow, the real window is made fully transparent (layered alpha 0) while it+/// restores or minimizes, and the image is drawn on a GPU-composited overlay as a textured mesh that+/// pours out of / into the dock tile. The real window is made opaque again as soon as the effect ends.+/// </summary>+public sealed class GenieAnimator : IDisposable+{+ // A fine grid keeps the per-triangle (affine) texture mapping from shearing the content.+ private const int Rows = 96;+ private const int Columns = 24;+ private static readonly TimeSpan EffectDuration = TimeSpan.FromMilliseconds(480);+ private static readonly TimeSpan LaunchWindow = TimeSpan.FromSeconds(8);++ private readonly Dictionary<nint, int> _hiddenWindows = [];+ // Image taken when a window was minimized, reused to start its restore instantly.+ private const int MaxTextureSide = 1600;+ private readonly Dictionary<nint, (BitmapSource Image, NativeRect Frame)> _snapshots = [];+ private readonly List<nint> _snapshotOrder = [];+ private Window? _overlay;+ private nint _overlayHandle;+ private Viewport3D? _viewport;+ private OrthographicCamera? _camera;+ private MeshGeometry3D? _mesh;+ private DiffuseMaterial? _material;+ private Rect _fromRect;+ private Rect _iconRect;+ private bool _disposed;++ private string? _pendingLaunchPath;+ private Rect _pendingLaunchIcon;+ private DateTime _pendingLaunchUntil;+ private nint _showHook;+ private WinEventDelegate? _hookProc;+ private DispatcherTimer? _launchTimer;++ public bool IsBusy { get; private set; }++ /// <summary>Restores a minimized window, pouring it out of the dock tile.</summary>+ public bool TryRestore(nint window, Rect iconPixels, Func<nint, bool> activate)+ {+ if (_disposed || IsBusy || !IsWindow(window) || !IsIconic(window)) return false;+ if (!TryHide(window, out var originalStyle)) return false;+ IsBusy = true;+ if (!activate(window))+ {+ Reveal(window, originalStyle);+ IsBusy = false;+ return false;+ }++ _ = RunOpenAsync(window, iconPixels, originalStyle);+ return true;+ }++ /// <summary>Minimizes a visible window, sucking it into the dock tile.</summary>+ public bool TryMinimize(nint window, Rect iconPixels)+ {+ if (_disposed || IsBusy || !IsWindow(window) || IsIconic(window) || !IsWindowVisible(window)) return false;+ var image = Capture(window, out var frame);+ if (image is null) return false;+ IsBusy = true;+ _snapshots[window] = (image, frame);+ _snapshotOrder.Remove(window);+ _snapshotOrder.Add(window);+ while (_snapshotOrder.Count > 3)+ {+ _snapshots.Remove(_snapshotOrder[0]);+ _snapshotOrder.RemoveAt(0);+ }++ _ = RunMinimizeAsync(window, image, frame, iconPixels);+ return true;+ }++ /// <summary>The next app window of <paramref name="executablePath"/> that appears opens with the effect.</summary>+ public void ExpectLaunch(string executablePath, Rect iconPixels)+ {+ if (_disposed) return;+ _pendingLaunchPath = executablePath;+ _pendingLaunchIcon = iconPixels;+ _pendingLaunchUntil = DateTime.UtcNow + LaunchWindow;+ if (_showHook == 0)+ {+ _hookProc ??= OnWindowShown;+ _showHook = SetWinEventHook(EventObjectShow, EventObjectShow, 0, _hookProc, 0, 0,+ WinEventOutOfContext | WinEventSkipOwnProcess);+ }++ _launchTimer ??= new DispatcherTimer { Interval = LaunchWindow };+ _launchTimer.Tick -= LaunchTimer_Tick;+ _launchTimer.Tick += LaunchTimer_Tick;+ _launchTimer.Stop();+ _launchTimer.Start();+ }++ private void LaunchTimer_Tick(object? sender, EventArgs e) => StopWaitingForLaunch();++ private void StopWaitingForLaunch()+ {+ _launchTimer?.Stop();+ _pendingLaunchPath = null;+ if (_showHook != 0)+ {+ UnhookWinEvent(_showHook);+ _showHook = 0;+ }+ }++ private void OnWindowShown(nint hook, uint eventType, nint window, int objectId, int childId, uint thread, uint time)+ {+ if (objectId != 0 || window == 0 || _pendingLaunchPath is null) return;+ if (DateTime.UtcNow > _pendingLaunchUntil)+ {+ StopWaitingForLaunch();+ return;+ }++ if (GetAncestor(window, GaRoot) != window || GetWindow(window, GwOwner) != 0 || !IsWindowVisible(window)) return;+ if ((GetWindowLong(window, GwlExStyle) & WsExToolWindow) != 0) return;+ if (!GetWindowRect(window, out var rect) || rect.Right - rect.Left < 240 || rect.Bottom - rect.Top < 160) return;+ if (!string.Equals(NativeWindowTracker.ExecutablePathOf(window), _pendingLaunchPath, StringComparison.OrdinalIgnoreCase)) return;++ var icon = _pendingLaunchIcon;+ StopWaitingForLaunch();+ if (IsBusy || IsIconic(window) || !TryHide(window, out var originalStyle)) return;+ IsBusy = true;+ _ = RunOpenAsync(window, icon, originalStyle);+ }++ private async Task RunOpenAsync(nint window, Rect iconPixels, int originalStyle)+ {+ try+ {+ // The window is invisible but restored; give it a moment to paint before capturing.+ BitmapSource? image = null;+ NativeRect frame = default;+ if (_snapshots.Remove(window, out var snapshot))+ {+ _snapshotOrder.Remove(window);+ // Only valid when the window comes back where it was.+ if (DwmGetWindowAttribute(window, DwmwaExtendedFrameBounds, out var current, Marshal.SizeOf<NativeRect>()) == 0+ && current.Left == snapshot.Frame.Left && current.Top == snapshot.Frame.Top+ && current.Right == snapshot.Frame.Right && current.Bottom == snapshot.Frame.Bottom)+ {+ image = snapshot.Image;+ frame = snapshot.Frame;+ }+ }++ for (var attempt = 0; attempt < 8 && image is null; attempt++)+ {+ await Task.Delay(attempt == 0 ? 35 : 45);+ if (!IsWindow(window) || IsIconic(window)) return;+ image = Capture(window, out frame);+ }++ if (image is null) return;+ Prepare(window, image, frame, iconPixels);+ UpdateMesh(1);+ ShowOverlay();+ await AnimateAsync(1, 0);+ // Real window back first, then drop the overlay that shows the identical image.+ Reveal(window, originalStyle);+ await NextFrameAsync();+ await Task.Delay(16);+ }+ finally+ {+ Reveal(window, originalStyle);+ HideOverlay();+ IsBusy = false;+ }+ }++ private async Task RunMinimizeAsync(nint window, BitmapSource image, NativeRect frame, Rect iconPixels)+ {+ var hidden = false;+ var originalStyle = 0;+ try+ {+ Prepare(window, image, frame, iconPixels);+ UpdateMesh(0);+ ShowOverlay();+ // The overlay is freshly created; let it put its first frame on screen before the real+ // window disappears, so nothing flickers.+ await NextFrameAsync();+ await NextFrameAsync();+ await NextFrameAsync();+ await Task.Delay(15);+ hidden = TryHide(window, out originalStyle);+ ShowWindowAsync(window, SwMinimize);+ await AnimateAsync(0, 1);+ }+ finally+ {+ HideOverlay();+ for (var i = 0; i < 20 && IsWindow(window) && !IsIconic(window); i++)+ {+ await Task.Delay(25);+ }++ if (hidden) Reveal(window, originalStyle);+ IsBusy = false;+ }+ }++ private Task AnimateAsync(double from, double to)+ {+ var completion = new TaskCompletionSource();+ var clock = Stopwatch.StartNew();+ EventHandler? handler = null;+ handler = (_, _) =>+ {+ var t = Math.Min(1, clock.Elapsed / EffectDuration);+ UpdateMesh(from + (to - from) * t);+ if (t >= 1)+ {+ CompositionTarget.Rendering -= handler;+ completion.TrySetResult();+ }+ };+ CompositionTarget.Rendering += handler;+ return completion.Task;+ }++ private static Task NextFrameAsync()+ {+ var completion = new TaskCompletionSource();+ EventHandler? handler = null;+ handler = (_, _) =>+ {+ CompositionTarget.Rendering -= handler;+ completion.TrySetResult();+ };+ CompositionTarget.Rendering += handler;+ return completion.Task;+ }++ /// <summary>+ /// Shape at progress <paramref name="p"/>: 0 = the window itself, 1 = inside the dock tile.+ /// First the lower edge bends toward the tile (an S-curve), then the image slides down the curve.+ /// </summary>+ private void UpdateMesh(double p)+ {+ if (_mesh is null || _viewport is null) return;+ var w = _fromRect;+ var icon = _iconRect;+ var bend = Smooth(Clamp01(p / 0.42));+ var bottomT = EaseOutCubic(Clamp01(p / 0.62));+ var topT = EaseInCubic(Clamp01((p - 0.16) / 0.84));+ var top = Lerp(w.Top, icon.Top, topT);+ var bottom = Lerp(w.Bottom, icon.Bottom, bottomT);+ var span = Math.Max(1, icon.Top - w.Top);++ var points = new Point3DCollection((Rows + 1) * (Columns + 1));+ for (var row = 0; row <= Rows; row++)+ {+ var y = Lerp(top, bottom, (double)row / Rows);+ var shape = bend * Smooth(Clamp01((y - w.Top) / span));+ var left = Lerp(w.Left, icon.Left, shape);+ var right = Lerp(w.Right, icon.Right, shape);+ for (var column = 0; column <= Columns; column++)+ {+ points.Add(new Point3D(Lerp(left, right, (double)column / Columns), -y, 0));+ }+ }++ points.Freeze();+ _mesh.Positions = points;+ _viewport.Opacity = p > 0.86 ? 1 - Clamp01((p - 0.86) / 0.14) * 0.85 : 1;+ }++ private void Prepare(nint window, BitmapSource image, NativeRect frame, Rect iconPixels)+ {+ EnsureOverlay();+ var monitorInfo = new MonitorInfo { cbSize = (uint)Marshal.SizeOf<MonitorInfo>() };+ GetMonitorInfo(MonitorFromWindow(window, MonitorDefaultToNearest), ref monitorInfo);+ var monitor = monitorInfo.rcMonitor;+ SetWindowPos(_overlayHandle, HwndTopmost, monitor.Left, monitor.Top,+ monitor.Right - monitor.Left, monitor.Bottom - monitor.Top, SwpNoActivate);+ var dpi = GetDpiForWindow(_overlayHandle);+ var scale = (dpi == 0 ? 96 : dpi) / 96d;+ var width = (monitor.Right - monitor.Left) / scale;+ var height = (monitor.Bottom - monitor.Top) / scale;+ _camera!.Width = width;+ _camera.Position = new Point3D(width / 2, -height / 2, 10);+ _fromRect = new Rect((frame.Left - monitor.Left) / scale, (frame.Top - monitor.Top) / scale,+ (frame.Right - frame.Left) / scale, (frame.Bottom - frame.Top) / scale);+ _iconRect = new Rect((iconPixels.Left - monitor.Left) / scale, (iconPixels.Top - monitor.Top) / scale,+ iconPixels.Width / scale, iconPixels.Height / scale);+ _material!.Brush = new ImageBrush(image);+ }++ private void ShowOverlay()+ {+ if (_overlayHandle == 0) return;+ SetWindowPos(_overlayHandle, HwndTopmost, 0, 0, 0, 0, SwpNoActivate | SwpNoMove | SwpNoSize | SwpShowWindow);+ }++ private void HideOverlay()+ {+ if (_overlayHandle == 0) return;+ SetWindowPos(_overlayHandle, 0, 0, 0, 0, 0, SwpNoActivate | SwpNoMove | SwpNoSize | SwpNoZOrder | SwpHideWindow);+ // Destroy the overlay between effects: WPF keeps a full-screen 3D surface's graphics memory+ // (hundreds of MB) for as long as the window exists. Recreating it costs a few milliseconds.+ var overlay = _overlay;+ _overlay = null;+ _overlayHandle = 0;+ _viewport = null;+ _camera = null;+ _mesh = null;+ _material = null;+ overlay?.Dispatcher.BeginInvoke(DispatcherPriority.Background, () => overlay.Close());+ // Hand the texture and render surfaces back right away instead of whenever the GC next runs.+ overlay?.Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, () =>+ {+ GC.Collect();+ GC.WaitForPendingFinalizers();+ });+ }++ private void EnsureOverlay()+ {+ if (_overlay is not null) return;+ var textureCoordinates = new PointCollection((Rows + 1) * (Columns + 1));+ var indices = new Int32Collection(Rows * Columns * 6);+ for (var row = 0; row <= Rows; row++)+ {+ var v = (double)row / Rows;+ for (var column = 0; column <= Columns; column++)+ {+ textureCoordinates.Add(new Point((double)column / Columns, v));+ if (row == Rows || column == Columns) continue;+ var a = row * (Columns + 1) + column;+ var below = a + Columns + 1;+ indices.Add(a); indices.Add(below); indices.Add(a + 1);+ indices.Add(a + 1); indices.Add(below); indices.Add(below + 1);+ }+ }++ _mesh = new MeshGeometry3D { TextureCoordinates = textureCoordinates, TriangleIndices = indices };+ _material = new DiffuseMaterial();+ var group = new Model3DGroup();+ group.Children.Add(new AmbientLight(Colors.White));+ group.Children.Add(new GeometryModel3D(_mesh, _material) { BackMaterial = _material });+ _camera = new OrthographicCamera+ {+ LookDirection = new Vector3D(0, 0, -1),+ UpDirection = new Vector3D(0, 1, 0),+ NearPlaneDistance = 0.1,+ FarPlaneDistance = 100+ };+ _viewport = new Viewport3D { Camera = _camera, IsHitTestVisible = false };+ _viewport.Children.Add(new ModelVisual3D { Content = group });+ RenderOptions.SetBitmapScalingMode(_viewport, BitmapScalingMode.Linear);+ // No multisampling: an MSAA full-screen 3D surface is costly on integrated GPUs; the dense mesh+ // and the short duration keep the edges looking clean.+ RenderOptions.SetEdgeMode(_viewport, EdgeMode.Aliased);++ // Not a layered window: the client area is composited by DWM with per-pixel alpha+ // (frame extended over the whole window), which stays on the GPU even at full-screen size.+ _overlay = new Window+ {+ Title = "QiDock Genie",+ WindowStyle = WindowStyle.None,+ ResizeMode = ResizeMode.NoResize,+ AllowsTransparency = false,+ Background = Brushes.Transparent,+ ShowInTaskbar = false,+ ShowActivated = false,+ Focusable = false,+ Topmost = true,+ Left = -32000,+ Top = -32000,+ Width = 1,+ Height = 1,+ Content = _viewport+ };+ _overlay.SourceInitialized += (_, _) =>+ {+ var source = (HwndSource)PresentationSource.FromVisual(_overlay);+ source.CompositionTarget.BackgroundColor = Colors.Transparent;+ var handle = source.Handle;+ SetWindowLong(handle, GwlExStyle, GetWindowLong(handle, GwlExStyle)+ | WsExToolWindow | WsExNoActivate | WsExTransparent);+ var margins = new Margins { Left = -1, Right = -1, Top = -1, Bottom = -1 };+ DwmExtendFrameIntoClientArea(handle, ref margins);+ var noRounding = 1;+ DwmSetWindowAttribute(handle, DwmwaWindowCornerPreference, ref noRounding, sizeof(int));+ var noBorder = unchecked((int)0xFFFFFFFE);+ DwmSetWindowAttribute(handle, DwmwaBorderColor, ref noBorder, sizeof(int));+ var noTransitions = 1;+ DwmSetWindowAttribute(handle, DwmwaTransitionsForceDisabled, ref noTransitions, sizeof(int));+ };+ _overlay.Show();+ _overlayHandle = new WindowInteropHelper(_overlay).Handle;+ SetWindowPos(_overlayHandle, 0, 0, 0, 0, 0, SwpNoActivate | SwpNoMove | SwpNoSize | SwpNoZOrder | SwpHideWindow);+ }++ private bool TryHide(nint window, out int originalStyle)+ {+ originalStyle = GetWindowLong(window, GwlExStyle);+ // Windows that are already layered manage their own alpha; leave them alone.+ if (originalStyle == 0 || (originalStyle & WsExLayered) != 0) return false;+ SetWindowLong(window, GwlExStyle, originalStyle | WsExLayered);+ if ((GetWindowLong(window, GwlExStyle) & WsExLayered) == 0) return false;+ if (!SetLayeredWindowAttributes(window, 0, 0, LwaAlpha))+ {+ SetWindowLong(window, GwlExStyle, originalStyle);+ return false;+ }++ _hiddenWindows[window] = originalStyle;+ return true;+ }++ private void Reveal(nint window, int originalStyle)+ {+ if (!_hiddenWindows.Remove(window) || !IsWindow(window)) return;+ SetLayeredWindowAttributes(window, 0, 255, LwaAlpha);+ SetWindowLong(window, GwlExStyle, originalStyle);+ RedrawWindow(window, 0, 0, RdwErase | RdwInvalidate | RdwFrame | RdwAllChildren);+ }++ /// <summary>Captures the visible frame of a window (no invisible resize borders) as an opaque bitmap.</summary>+ private static BitmapSource? Capture(nint window, out NativeRect frame)+ {+ frame = default;+ if (!GetWindowRect(window, out var bounds)) return null;+ if (DwmGetWindowAttribute(window, DwmwaExtendedFrameBounds, out frame, Marshal.SizeOf<NativeRect>()) != 0)+ {+ frame = bounds;+ }++ var width = bounds.Right - bounds.Left;+ var height = bounds.Bottom - bounds.Top;+ var offsetX = Math.Clamp(frame.Left - bounds.Left, 0, width);+ var offsetY = Math.Clamp(frame.Top - bounds.Top, 0, height);+ var frameWidth = Math.Min(frame.Right - frame.Left, width - offsetX);+ var frameHeight = Math.Min(frame.Bottom - frame.Top, height - offsetY);+ if (width <= 0 || height <= 0 || width > 16384 || height > 16384 || frameWidth <= 8 || frameHeight <= 8) return null;+ frame = new NativeRect(bounds.Left + offsetX, bounds.Top + offsetY,+ bounds.Left + offsetX + frameWidth, bounds.Top + offsetY + frameHeight);++ var screenDc = GetDC(0);+ var memoryDc = CreateCompatibleDC(screenDc);+ var info = new BitmapInfoHeader+ {+ biSize = 40,+ biWidth = width,+ biHeight = -height,+ biPlanes = 1,+ biBitCount = 32+ };+ var dib = CreateDIBSection(screenDc, ref info, 0, out var bits, 0, 0);+ var previous = dib != 0 ? SelectObject(memoryDc, dib) : 0;+ try+ {+ if (dib == 0 || bits == 0 || !PrintWindow(window, memoryDc, PwRenderFullContent)) return null;+ GdiFlush();+ var pixels = new int[frameWidth * frameHeight];+ for (var row = 0; row < frameHeight; row++)+ {+ Marshal.Copy(bits + ((offsetY + row) * width + offsetX) * 4, pixels, row * frameWidth, frameWidth);+ }++ var samples = 0;+ var painted = 0;+ for (var i = 0; i < pixels.Length; i++)+ {+ pixels[i] |= unchecked((int)0xFF000000);+ if (i % 97 == 0)+ {+ samples++;+ if ((pixels[i] & 0xFFFFFF) != 0) painted++;+ }+ }++ // Nothing painted yet (all black): let the caller retry.+ if (painted * 50 < samples) return null;+ if (!IsZoomed(window))+ {+ var dpi = GetDpiForWindow(window);+ RoundCorners(pixels, frameWidth, frameHeight, (int)Math.Round(8 * (dpi == 0 ? 96 : dpi) / 96d));+ }++ BitmapSource bitmap = BitmapSource.Create(frameWidth, frameHeight, 96, 96, PixelFormats.Pbgra32, null, pixels, frameWidth * 4);+ // The window is only ever seen bent and moving, so a texture up to MaxTextureSide is plenty;+ // a full 4K-ish window would otherwise hold ~20 MB per copy.+ var shrink = Math.Min(1, MaxTextureSide / (double)Math.Max(frameWidth, frameHeight));+ if (shrink < 0.99)+ {+ var scaled = new TransformedBitmap(bitmap, new ScaleTransform(shrink, shrink));+ var scaledWidth = scaled.PixelWidth;+ var scaledHeight = scaled.PixelHeight;+ var scaledPixels = new int[scaledWidth * scaledHeight];+ scaled.CopyPixels(scaledPixels, scaledWidth * 4, 0);+ bitmap = BitmapSource.Create(scaledWidth, scaledHeight, 96, 96, PixelFormats.Pbgra32, null, scaledPixels, scaledWidth * 4);+ }++ bitmap.Freeze();+ return bitmap;+ }+ finally+ {+ if (previous != 0) SelectObject(memoryDc, previous);+ if (dib != 0) DeleteObject(dib);+ DeleteDC(memoryDc);+ ReleaseDC(0, screenDc);+ }+ }++ private static void RoundCorners(int[] pixels, int width, int height, int radius)+ {+ radius = Math.Min(radius, Math.Min(width, height) / 2);+ for (var y = 0; y < radius; y++)+ {+ for (var x = 0; x < radius; x++)+ {+ var dx = radius - x - 0.5;+ var dy = radius - y - 0.5;+ if (dx * dx + dy * dy <= radius * radius) continue;+ pixels[y * width + x] = 0;+ pixels[y * width + (width - 1 - x)] = 0;+ pixels[(height - 1 - y) * width + x] = 0;+ pixels[(height - 1 - y) * width + (width - 1 - x)] = 0;+ }+ }+ }++ private static double Clamp01(double value) => Math.Clamp(value, 0, 1);+ private static double Lerp(double from, double to, double t) => from + (to - from) * t;+ private static double Smooth(double t) => t * t * (3 - 2 * t);+ private static double EaseOutCubic(double t) => 1 - Math.Pow(1 - t, 3);+ private static double EaseInCubic(double t) => t * t * t;++ public void Dispose()+ {+ if (_disposed) return;+ _disposed = true;+ StopWaitingForLaunch();+ foreach (var (window, style) in _hiddenWindows.ToList())+ {+ Reveal(window, style);+ }++ _overlay?.Close();+ _overlay = null;+ }++ private const int GwlExStyle = -20;+ private const int WsExLayered = 0x00080000;+ private const int WsExTransparent = 0x00000020;+ private const int WsExToolWindow = 0x00000080;+ private const int WsExNoActivate = 0x08000000;+ private const uint LwaAlpha = 0x2;+ private const uint PwRenderFullContent = 0x2;+ private const int SwMinimize = 6;+ private const uint SwpNoSize = 0x1;+ private const uint SwpNoMove = 0x2;+ private const uint SwpNoZOrder = 0x4;+ private const uint SwpNoActivate = 0x10;+ private const uint SwpShowWindow = 0x40;+ private const uint SwpHideWindow = 0x80;+ private static readonly nint HwndTopmost = new(-1);+ private const uint RdwInvalidate = 0x1;+ private const uint RdwErase = 0x4;+ private const uint RdwAllChildren = 0x80;+ private const uint RdwFrame = 0x400;+ private const int DwmwaExtendedFrameBounds = 9;+ private const int DwmwaTransitionsForceDisabled = 3;+ private const int DwmwaWindowCornerPreference = 33;+ private const int DwmwaBorderColor = 34;+ private const uint MonitorDefaultToNearest = 2;+ private const uint EventObjectShow = 0x8002;+ private const uint WinEventOutOfContext = 0x0;+ private const uint WinEventSkipOwnProcess = 0x2;+ private const uint GaRoot = 2;+ private const uint GwOwner = 4;++ private delegate void WinEventDelegate(nint hook, uint eventType, nint window, int objectId, int childId, uint thread, uint time);++ [StructLayout(LayoutKind.Sequential)]+ private struct NativeRect(int left, int top, int right, int bottom)+ {+ public int Left = left;+ public int Top = top;+ public int Right = right;+ public int Bottom = bottom;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct MonitorInfo+ {+ public uint cbSize;+ public NativeRect rcMonitor;+ public NativeRect rcWork;+ public uint dwFlags;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct Margins+ {+ public int Left;+ public int Right;+ public int Top;+ public int Bottom;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct BitmapInfoHeader+ {+ public uint biSize;+ public int biWidth;+ public int biHeight;+ public ushort biPlanes;+ public ushort biBitCount;+ public uint biCompression;+ public uint biSizeImage;+ public int biXPelsPerMeter;+ public int biYPelsPerMeter;+ public uint biClrUsed;+ public uint biClrImportant;+ // Room for the (unused) colour table of a BITMAPINFO.+ public uint bmiColors;+ }++ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsWindow(nint window);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsIconic(nint window);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsZoomed(nint window);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsWindowVisible(nint window);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool ShowWindowAsync(nint window, int command);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetWindowRect(nint window, out NativeRect rect);+ [DllImport("user32.dll", EntryPoint = "GetWindowLongW")] private static extern int GetWindowLong(nint window, int index);+ [DllImport("user32.dll", EntryPoint = "SetWindowLongW")] private static extern int SetWindowLong(nint window, int index, int value);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetLayeredWindowAttributes(nint window, uint key, byte alpha, uint flags);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool RedrawWindow(nint window, nint rect, nint region, uint flags);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetWindowPos(nint window, nint insertAfter, int x, int y, int width, int height, uint flags);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool PrintWindow(nint window, nint dc, uint flags);+ [DllImport("user32.dll")] private static extern uint GetDpiForWindow(nint window);+ [DllImport("user32.dll")] private static extern nint MonitorFromWindow(nint window, uint flags);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetMonitorInfo(nint monitor, ref MonitorInfo info);+ [DllImport("user32.dll")] private static extern nint GetAncestor(nint window, uint flags);+ [DllImport("user32.dll")] private static extern nint GetWindow(nint window, uint command);+ [DllImport("user32.dll")] private static extern nint GetDC(nint window);+ [DllImport("user32.dll")] private static extern int ReleaseDC(nint window, nint dc);+ [DllImport("user32.dll")] private static extern nint SetWinEventHook(uint eventMin, uint eventMax, nint module, WinEventDelegate callback, uint process, uint thread, uint flags);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool UnhookWinEvent(nint hook);+ [DllImport("gdi32.dll")] private static extern nint CreateCompatibleDC(nint dc);+ [DllImport("gdi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteDC(nint dc);+ [DllImport("gdi32.dll")] private static extern nint SelectObject(nint dc, nint gdiObject);+ [DllImport("gdi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteObject(nint gdiObject);+ [DllImport("gdi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GdiFlush();+ [DllImport("gdi32.dll")] private static extern nint CreateDIBSection(nint dc, ref BitmapInfoHeader info, uint usage, out nint bits, nint section, uint offset);+ [DllImport("dwmapi.dll")] private static extern int DwmGetWindowAttribute(nint window, int attribute, out NativeRect value, int size);+ [DllImport("dwmapi.dll")] private static extern int DwmSetWindowAttribute(nint window, int attribute, ref int value, int size);+ [DllImport("dwmapi.dll")] private static extern int DwmExtendFrameIntoClientArea(nint window, ref Margins margins);+}diff --git a/Services/GpuTransparency.cs b/Services/GpuTransparency.csnew file mode 100644index 0000000..5840f56--- /dev/null+++ b/Services/GpuTransparency.cs@@ -0,0 +1,152 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Interop;+using System.Windows.Media;++namespace QiDock.Services;++/// <summary>+/// See-through windows without WPF's layered-window mode. A layered WPF window copies every+/// frame from the graphics card back to memory, which makes large moving content stutter.+/// Instead the window stays an ordinary one whose glass frame covers all of it, so the desktop+/// compositor blends the transparent pixels itself and animation stays on the graphics card.+/// Call <see cref="Prepare"/> in the constructor and <see cref="Apply"/> in OnSourceInitialized.+/// </summary>+public static class GpuTransparency+{+ /// <summary>Whether this Windows can do it (Windows 10 and later, composition on).</summary>+ public static bool Supported => Composition+ && (RenderCapability.Tier >> 16) > 0 // drawn by the graphics card (not remote desktop's software path)+ && RenderOptions.ProcessRenderMode != System.Windows.Interop.RenderMode.SoftwareOnly+ && !SystemParameters.HighContrast;++ private static readonly bool Composition = Environment.OSVersion.Version.Major >= 10 && Composited();++ /// <summary>Makes the window see-through: layered mode only where the compositor can't help.</summary>+ public static void Prepare(Window window)+ {+ window.AllowsTransparency = !Supported;+ window.Background = Brushes.Transparent;+ }++ /// <summary>Whether Windows can blur what lies behind a window (Windows 11 22H2 and later).</summary>+ public static bool CanBlur => Supported && Environment.OSVersion.Version.Build >= 22621;++ /// <summary>Turns the frosted blur behind the whole window on or off.</summary>+ public static void Blur(Window window, bool on)+ {+ if (!CanBlur || PresentationSource.FromVisual(window) is not HwndSource source) return;+ var value = on ? 3 /* DWMSBT_TRANSIENTWINDOW */ : 1 /* DWMSBT_NONE */;+ DwmSetWindowAttribute(source.Handle, 38, ref value, sizeof(int));+ value = 1; // dark material+ DwmSetWindowAttribute(source.Handle, 20, ref value, sizeof(int));+ }++ public static void Apply(Window window)+ {+ if (window.AllowsTransparency || !Supported || PresentationSource.FromVisual(window) is not HwndSource source) return;+ source.CompositionTarget.BackgroundColor = Colors.Transparent;+ var margins = new Margins { Left = -1, Right = -1, Top = -1, Bottom = -1 };+ DwmExtendFrameIntoClientArea(source.Handle, ref margins);+ var value = 1; // DWMWCP_DONOTROUND: no rounded window corners, the cards draw their own+ DwmSetWindowAttribute(source.Handle, 33, ref value, sizeof(int));+ value = unchecked((int)0xFFFFFFFE); // DWMWA_COLOR_NONE: no window border line+ DwmSetWindowAttribute(source.Handle, 34, ref value, sizeof(int));+ value = 1; // DWMSBT_NONE: no system backdrop behind the cards+ DwmSetWindowAttribute(source.Handle, 38, ref value, sizeof(int));+ }++ /// <summary>+ /// Frosted glass over the whole window: what lies behind is blurred and tinted with+ /// <paramref name="tint"/> (alpha = how much tint), and the window gets the rounded corners,+ /// thin edge and soft shadow Windows gives its own flyouts. Unlike the system backdrop this+ /// stays frosted while the window is not the active one (the panels never take focus).+ /// Returns false where Windows can't (then the caller draws an opaque background).+ /// </summary>+ public static bool Frost(Window window, Color tint)+ {+ if (window.AllowsTransparency || !Supported || PresentationSource.FromVisual(window) is not HwndSource source) return false;+ var policy = new AccentPolicy+ {+ AccentState = 4, // ACCENT_ENABLE_ACRYLICBLURBEHIND+ GradientColor = (uint)(tint.A << 24 | tint.B << 16 | tint.G << 8 | tint.R)+ };+ var size = Marshal.SizeOf<AccentPolicy>();+ var memory = Marshal.AllocHGlobal(size);+ try+ {+ Marshal.StructureToPtr(policy, memory, false);+ var data = new CompositionAttributeData { Attribute = 19 /* WCA_ACCENT_POLICY */, Data = memory, Size = size };+ if (!SetWindowCompositionAttribute(source.Handle, ref data)) return false;+ }+ catch (EntryPointNotFoundException) { return false; }+ finally { Marshal.FreeHGlobal(memory); }+ if (Environment.OSVersion.Version.Build >= 22000)+ {+ var value = 2; // DWMWCP_ROUND+ DwmSetWindowAttribute(source.Handle, 33, ref value, sizeof(int));+ value = unchecked((int)0xFFFFFFFF); // DWMWA_COLOR_DEFAULT: the system's thin edge+ DwmSetWindowAttribute(source.Handle, 34, ref value, sizeof(int));+ }+ return true;+ }++ /// <summary>Takes the frosted glass off again (a window that draws its own shape), with square, edgeless corners.</summary>+ public static void Unfrost(Window window)+ {+ if (window.AllowsTransparency || !Supported || PresentationSource.FromVisual(window) is not HwndSource source) return;+ var policy = new AccentPolicy { AccentState = 0 };+ var size = Marshal.SizeOf<AccentPolicy>();+ var memory = Marshal.AllocHGlobal(size);+ try+ {+ Marshal.StructureToPtr(policy, memory, false);+ var data = new CompositionAttributeData { Attribute = 19 /* WCA_ACCENT_POLICY */, Data = memory, Size = size };+ SetWindowCompositionAttribute(source.Handle, ref data);+ }+ catch (EntryPointNotFoundException) { }+ finally { Marshal.FreeHGlobal(memory); }+ var value = 1; // DWMWCP_DONOTROUND+ DwmSetWindowAttribute(source.Handle, 33, ref value, sizeof(int));+ value = unchecked((int)0xFFFFFFFE); // DWMWA_COLOR_NONE+ DwmSetWindowAttribute(source.Handle, 34, ref value, sizeof(int));+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct AccentPolicy+ {+ public int AccentState;+ public int AccentFlags;+ public uint GradientColor;+ public int AnimationId;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct CompositionAttributeData+ {+ public int Attribute;+ public nint Data;+ public int Size;+ }++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool SetWindowCompositionAttribute(nint window, ref CompositionAttributeData data);++ private static bool Composited()+ {+ try { return DwmIsCompositionEnabled(out var on) == 0 && on; }+ catch (DllNotFoundException) { return false; }+ catch (EntryPointNotFoundException) { return false; }+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct Margins+ {+ public int Left, Right, Top, Bottom;+ }++ [DllImport("dwmapi.dll")] private static extern int DwmExtendFrameIntoClientArea(nint window, ref Margins margins);+ [DllImport("dwmapi.dll")] private static extern int DwmSetWindowAttribute(nint window, int attribute, ref int value, int size);+ [DllImport("dwmapi.dll")] private static extern int DwmIsCompositionEnabled([MarshalAs(UnmanagedType.Bool)] out bool enabled);+}diff --git a/Services/NativeJumpListSession.cs b/Services/NativeJumpListSession.csnew file mode 100644index 0000000..af15fbb--- /dev/null+++ b/Services/NativeJumpListSession.cs@@ -0,0 +1,334 @@+using System.Runtime.InteropServices;+using System.Text;+using System.Windows;+using System.Windows.Interop;+using System.Windows.Media.Imaging;+using QiDock.Models;++namespace QiDock.Services;++internal sealed class NativeJumpListSession : IDisposable+{+ // Read-only ABI references: Open-Shell JumpLists.cpp and System Informer appresolverp.h.+ private static readonly Guid ResolverClass = new("660B90C8-73A9-4B58-8CAE-355B7F55341B");+ private static readonly Guid ResolverInterface = new("DE25675A-72DE-44B4-9373-05170450C140");+ private static readonly Guid DestinationClass = new("77F10CF0-3DB5-4966-B520-B7C54FD35ED6");+ private static readonly Guid DestinationInterface = new("507101CD-F6AD-46C8-8E20-EEB9E6BAC47F");+ private static readonly Guid AutomaticClass = new("F0AE1542-F497-484B-A175-A20DB09144BA");+ private static readonly Guid AutomaticInterface = new("E9C5EF8D-FD41-4F72-BA87-EB03BAD5817C");+ private static readonly Guid ShellItemInterface = new("43826D1E-E718-42EE-BC55-A1E261C37BFE");+ private static readonly Guid ObjectArrayInterface = new("92CA9DCD-5622-4BBA-A805-5E9F541BD8C9");+ private static readonly Guid PropertyStoreInterface = new("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99");+ private static readonly Guid ContextMenuInterface = new("000214E4-0000-0000-C000-000000000046");+ private static readonly Guid ImageFactoryInterface = new("BCC18B79-BA16-442F-80C4-8A59C30C463B");+ private static readonly Guid ShellLinkInterface = new("000214F9-0000-0000-C000-000000000046");+ private static readonly PropertyKey AppIdKey = new(new("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), 5);+ private static readonly PropertyKey SeparatorKey = new(AppIdKey.Format, 6);+ private static readonly PropertyKey HostEnvironmentKey = new(AppIdKey.Format, 14);+ private static readonly PropertyKey ActivationContextKey = new(AppIdKey.Format, 20);+ private static readonly PropertyKey TitleKey = new(new("F29F85E0-4FF9-1068-AB91-08002B27B3D9"), 2);+ private readonly Dictionary<int, ShellComObject> _commands = [];+ private int _nextCommand;++ public ApplicationJumpList Read(long sessionId, nint window, string? shortcut, CancellationToken cancellation)+ {+ if (IntPtr.Size != 8) return new(sessionId, JumpListStatus.Unsupported, []);+ var appId = ResolveIdentity(window, shortcut);+ if (string.IsNullOrWhiteSpace(appId)) return new(sessionId, JumpListStatus.IdentityUnavailable, []);+ cancellation.ThrowIfCancellationRequested();+ using var custom = ShellComObject.Create(DestinationClass, DestinationInterface);+ Marshal.ThrowExceptionForHR(custom.Method<SetAppId>(4)(custom.Handle, appId));+ using var automatic = ShellComObject.Create(AutomaticClass, AutomaticInterface);+ Marshal.ThrowExceptionForHR(automatic.Method<InitializeAutomatic>(3)(automatic.Handle, appId, 0, 0));+ var groups = new List<JumpListGroup>();+ AddAutomatic(groups, automatic, 0, UiText.Get("PinnedDestinations"), cancellation);+ var categoryResult = custom.Method<GetCount>(6)(custom.Handle, out var count);+ if (MissingList(categoryResult)) count = 0;+ else Marshal.ThrowExceptionForHR(categoryResult);+ if (count > 32) throw new InvalidOperationException("Jump List category limit exceeded.");+ var hasKnownCategory = false;+ for (uint index = 0; index < count && _commands.Count < 100; index++)+ {+ cancellation.ThrowIfCancellationRequested();+ Marshal.ThrowExceptionForHR(custom.Method<GetCategory>(7)(custom.Handle, index, 1, out var category));+ try+ {+ if (category.Type == 1)+ {+ var kind = category.Kind;+ if (kind is 1 or 2)+ {+ hasKnownCategory = true;+ AddAutomatic(groups, automatic, 3 - kind, kind == 1 ? UiText.Get("Frequent") : UiText.Get("Recent"), cancellation);+ }+ }+ else if (category.Type is 0 or 2)+ {+ var iid = ObjectArrayInterface;+ Marshal.ThrowExceptionForHR(custom.Method<EnumerateCategory>(9)(custom.Handle, index, ref iid, out var pointer));+ using var array = new ShellComObject(pointer);+ var title = category.Type == 2 ? UiText.Get("Tasks") : ResolveText(Marshal.PtrToStringUni(category.NameOrKind));+ AddGroup(groups, title, array, cancellation);+ }+ }+ finally+ {+ if (category.Type == 0 && category.NameOrKind != 0) Marshal.FreeCoTaskMem(category.NameOrKind);+ }+ }+ if (!hasKnownCategory) AddAutomatic(groups, automatic, 1, UiText.Get("Recent"), cancellation);+ return new(sessionId, groups.Count > 0 ? JumpListStatus.Ready : JumpListStatus.Empty, groups);+ }++ /// <summary>The AppUserModelID of a top-level window (explicit or resolved), or null.</summary>+ public static string? AppIdForWindow(nint window)+ {+ try { return ResolveIdentity(window, null); }+ catch (Exception ex) when (ex is COMException or InvalidCastException or InvalidOperationException) { return null; }+ }++ private static string? ResolveIdentity(nint window, string? shortcut)+ {+ if (window != 0)+ {+ var iid = PropertyStoreInterface;+ Marshal.ThrowExceptionForHR(SHGetPropertyStoreForWindow(window, ref iid, out var pointer));+ using var store = new ShellComObject(pointer);+ var explicitId = ReadString(store, AppIdKey);+ if (!string.IsNullOrWhiteSpace(explicitId)) return explicitId;+ }+ using var resolver = ShellComObject.Create(ResolverClass, ResolverInterface);+ nint appId;+ if (window != 0)+ {+ Marshal.ThrowExceptionForHR(resolver.Method<ResolveWindow>(5)(resolver.Handle, window, out appId, 0, 0, 0));+ }+ else if (!string.IsNullOrWhiteSpace(shortcut))+ {+ var iid = ShellItemInterface;+ Marshal.ThrowExceptionForHR(SHCreateItemFromParsingName(shortcut, 0, ref iid, out var pointer));+ using var item = new ShellComObject(pointer);+ Marshal.ThrowExceptionForHR(resolver.Method<ResolveShortcut>(3)(resolver.Handle, item.Handle, out appId));+ }+ else return null;+ try { return Marshal.PtrToStringUni(appId); }+ finally { if (appId != 0) Marshal.FreeCoTaskMem(appId); }+ }++ private void AddAutomatic(List<JumpListGroup> groups, ShellComObject automatic, int kind, string title, CancellationToken cancellation)+ {+ var iid = ObjectArrayInterface;+ var result = automatic.Method<GetAutomaticList>(5)(automatic.Handle, kind, 20, 1, ref iid, out var pointer);+ if (MissingList(result)) return;+ Marshal.ThrowExceptionForHR(result);+ using var array = new ShellComObject(pointer);+ AddGroup(groups, title, array, cancellation);+ }++ private void AddGroup(List<JumpListGroup> groups, string? title, ShellComObject array, CancellationToken cancellation)+ {+ if (string.IsNullOrWhiteSpace(title)) return;+ Marshal.ThrowExceptionForHR(array.Method<GetCount>(3)(array.Handle, out var count));+ var entries = new List<JumpListEntry>();+ for (uint index = 0; index < Math.Min(count, 40u) && _commands.Count < 100; index++)+ {+ cancellation.ThrowIfCancellationRequested();+ var iid = new Guid("00000000-0000-0000-C000-000000000046");+ Marshal.ThrowExceptionForHR(array.Method<GetAt>(4)(array.Handle, index, ref iid, out var pointer));+ var item = new ShellComObject(pointer);+ var retained = false;+ try+ {+ using var store = item.Query(PropertyStoreInterface);+ if (store is not null && ReadSeparator(store))+ {+ if (entries.Count > 0 && !entries[^1].IsSeparator) entries.Add(new(0, "", null, true));+ continue;+ }+ var label = store is null ? null : ResolveText(ReadString(store, TitleKey));+ using var shellItem = item.Query(ShellItemInterface);+ if (string.IsNullOrWhiteSpace(label) && shellItem is not null)+ {+ Marshal.ThrowExceptionForHR(shellItem.Method<GetDisplayName>(5)(shellItem.Handle, 0, out var name));+ try { label = Marshal.PtrToStringUni(name); }+ finally { Marshal.FreeCoTaskMem(name); }+ }+ if (string.IsNullOrWhiteSpace(label)) continue;+ var id = ++_nextCommand;+ entries.Add(new(id, label, ReadIcon(item)));+ _commands.Add(id, item);+ retained = true;+ }+ finally { if (!retained) item.Dispose(); }+ }+ if (entries.Count > 0 && entries[^1].IsSeparator) entries.RemoveAt(entries.Count - 1);+ if (entries.Count > 0) groups.Add(new(title, entries));+ }++ private static string? ReadString(ShellComObject store, PropertyKey key)+ {+ Marshal.ThrowExceptionForHR(store.Method<GetValue>(5)(store.Handle, ref key, out var value));+ try { return value.Type is 31 or 8 ? Marshal.PtrToStringUni(value.Pointer) : null; }+ finally { PropVariantClear(ref value); }+ }++ private static bool ReadSeparator(ShellComObject store)+ {+ var key = SeparatorKey;+ Marshal.ThrowExceptionForHR(store.Method<GetValue>(5)(store.Handle, ref key, out var value));+ try { return value.Type == 11 && value.Bool != 0; }+ finally { PropVariantClear(ref value); }+ }++ private static string? ResolveText(string? text)+ {+ if (string.IsNullOrEmpty(text) || !text.StartsWith('@')) return text;+ var resolved = new StringBuilder(1024);+ Marshal.ThrowExceptionForHR(SHLoadIndirectString(text, resolved, (uint)resolved.Capacity, 0));+ return resolved.ToString();+ }++ private static BitmapSource? ReadIcon(ShellComObject item)+ {+ using var factory = item.Query(ImageFactoryInterface);+ if (factory is not null)+ {+ var result = factory.Method<GetImage>(3)(factory.Handle, new NativeSize(24, 24), 4, out var bitmap);+ if (result >= 0 && bitmap != 0)+ {+ try+ {+ var source = Imaging.CreateBitmapSourceFromHBitmap(bitmap, 0, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());+ source.Freeze();+ return source;+ }+ finally { DeleteObject(bitmap); }+ }+ }+ // Tasks are often IShellLink objects with an explicit resource, rather than Shell images.+ using var link = item.Query(ShellLinkInterface);+ if (link is null) return null;+ var path = new StringBuilder(2048);+ var iconResult = link.Method<GetIconLocation>(16)(link.Handle, path, path.Capacity, out var iconIndex);+ if (iconResult < 0) return null;+ if (path.Length == 0)+ {+ var pathResult = link.Method<GetLinkPath>(3)(link.Handle, path, path.Capacity, 0, 4);+ if (pathResult < 0 || path.Length == 0) return null;+ iconIndex = 0;+ }+ return ApplicationIconProvider.GetForResource(path.ToString(), iconIndex);+ }++ private static bool MissingList(int result) => result is unchecked((int)0x80030002) or unchecked((int)0x80070002);++ public void Invoke(int commandId, nint owner)+ {+ if (!_commands.TryGetValue(commandId, out var item)) throw new InvalidOperationException("Jump List session expired.");+ using var store = item.Query(PropertyStoreInterface);+ var appId = store is null ? null : ReadString(store, AppIdKey);+ // Packaged task links activate their AppsFolder target with the published activation context.+ if (appId?.Contains('!') == true)+ {+ var folder = new Guid("1E87508D-89C2-42F0-8A7E-645A0F50CA58");+ var iid = ShellItemInterface;+ Marshal.ThrowExceptionForHR(SHCreateItemInKnownFolder(ref folder, 0, appId, ref iid, out var pointer));+ using var target = new ShellComObject(pointer);+ using var properties = Bind(target, new("0384E1A4-1523-439C-A4C8-AB911052F586"), PropertyStoreInterface);+ var key = HostEnvironmentKey;+ Marshal.ThrowExceptionForHR(properties.Method<GetValue>(5)(properties.Handle, ref key, out var host));+ try+ {+ if (host.Type == 19 && host.UInt32 != 0)+ {+ using var targetMenu = Bind(target, new("3981E225-F559-11D3-8E3A-00C04F6837D5"), ContextMenuInterface);+ InvokeDefault(targetMenu, owner, store is null ? null : ReadString(store, ActivationContextKey));+ return;+ }+ }+ finally { PropVariantClear(ref host); }+ }+ using var direct = item.Query(ContextMenuInterface);+ if (direct is not null)+ {+ InvokeDefault(direct, owner, null);+ return;+ }+ using var shellItem = item.Query(ShellItemInterface);+ if (shellItem is null) throw new COMException("No Shell invocation interface.");+ using var bound = Bind(shellItem, new("3981E225-F559-11D3-8E3A-00C04F6837D5"), ContextMenuInterface);+ InvokeDefault(bound, owner, null);+ }++ private static ShellComObject Bind(ShellComObject item, Guid handler, Guid iid)+ {+ Marshal.ThrowExceptionForHR(item.Method<BindHandler>(3)(item.Handle, 0, ref handler, ref iid, out var pointer));+ return new ShellComObject(pointer);+ }++ private static void InvokeDefault(ShellComObject menu, nint owner, string? activationContext)+ {+ var nativeMenu = CreatePopupMenu();+ if (nativeMenu == 0) throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());+ try+ {+ Marshal.ThrowExceptionForHR(menu.Method<QueryMenu>(3)(menu.Handle, nativeMenu, 0, 1, 0x7fff, 1));+ var defaultId = GetMenuDefaultItem(nativeMenu, false, 0);+ if (defaultId == uint.MaxValue || defaultId == 0) throw new InvalidOperationException("Shell default command unavailable.");+ var command = new InvokeInfo+ {+ Size = Marshal.SizeOf<InvokeInfo>(), Mask = 0x4000, Window = owner,+ Verb = (nint)(defaultId - 1), VerbW = (nint)(defaultId - 1), Show = 1,+ Parameters = activationContext, ParametersW = activationContext+ };+ Marshal.ThrowExceptionForHR(menu.Method<InvokeMenu>(4)(menu.Handle, ref command));+ }+ finally { DestroyMenu(nativeMenu); }+ }++ public void Dispose()+ {+ foreach (var item in _commands.Values) item.Dispose();+ _commands.Clear();+ }++ [StructLayout(LayoutKind.Sequential)] private struct PropertyKey(Guid format, uint id) { public Guid Format = format; public uint Id = id; }+ [StructLayout(LayoutKind.Explicit, Size = 24)] private struct Variant { [FieldOffset(0)] public ushort Type; [FieldOffset(8)] public nint Pointer; [FieldOffset(8)] public short Bool; [FieldOffset(8)] public uint UInt32; }+ [StructLayout(LayoutKind.Explicit, Size = 64)] private struct Category { [FieldOffset(0)] public int Type; [FieldOffset(8)] public nint NameOrKind; [FieldOffset(8)] public int Kind; }+ [StructLayout(LayoutKind.Sequential)] private readonly struct NativeSize(int width, int height) { public readonly int Width = width; public readonly int Height = height; }+ [StructLayout(LayoutKind.Sequential)] private struct InvokeInfo+ {+ public int Size; public uint Mask; public nint Window; public nint Verb;+ [MarshalAs(UnmanagedType.LPStr)] public string? Parameters;+ public nint Directory; public int Show; public uint HotKey; public nint Icon; public nint Title; public nint VerbW;+ [MarshalAs(UnmanagedType.LPWStr)] public string? ParametersW;+ public nint DirectoryW; public nint TitleW; public int PointX; public int PointY;+ }++ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int SetAppId(nint self, [MarshalAs(UnmanagedType.LPWStr)] string id);+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetCount(nint self, out uint count);+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetCategory(nint self, uint index, int flags, out Category category);+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int EnumerateCategory(nint self, uint index, ref Guid iid, out nint result);+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int InitializeAutomatic(nint self, [MarshalAs(UnmanagedType.LPWStr)] string id, nint link, nint extra);+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetAutomaticList(nint self, int kind, uint max, uint flags, ref Guid iid, out nint result);+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int ResolveWindow(nint self, nint window, out nint id, nint prevented, nint explicitId, nint embedded);+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int ResolveShortcut(nint self, nint item, out nint id);+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetValue(nint self, ref PropertyKey key, out Variant value);+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetAt(nint self, uint index, ref Guid iid, out nint item);+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetDisplayName(nint self, uint kind, out nint name);+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetImage(nint self, NativeSize size, uint flags, out nint bitmap);+ [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode)] private delegate int GetIconLocation(nint self, StringBuilder path, int length, out int index);+ [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode)] private delegate int GetLinkPath(nint self, StringBuilder path, int length, nint findData, uint flags);+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int BindHandler(nint self, nint context, ref Guid handler, ref Guid iid, out nint result);+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int QueryMenu(nint self, nint menu, uint index, uint first, uint last, uint flags);+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int InvokeMenu(nint self, ref InvokeInfo info);+ [DllImport("shell32.dll")] private static extern int SHGetPropertyStoreForWindow(nint window, ref Guid iid, out nint store);+ [DllImport("shell32.dll", CharSet = CharSet.Unicode)] private static extern int SHCreateItemFromParsingName(string path, nint context, ref Guid iid, out nint item);+ [DllImport("shell32.dll", CharSet = CharSet.Unicode)] private static extern int SHCreateItemInKnownFolder(ref Guid folder, uint flags, string path, ref Guid iid, out nint item);+ [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] private static extern int SHLoadIndirectString(string source, StringBuilder output, uint count, nint reserved);+ [DllImport("ole32.dll")] private static extern int PropVariantClear(ref Variant value);+ [DllImport("gdi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteObject(nint bitmap);+ [DllImport("user32.dll", SetLastError = true)] private static extern nint CreatePopupMenu();+ [DllImport("user32.dll")] private static extern uint GetMenuDefaultItem(nint menu, [MarshalAs(UnmanagedType.Bool)] bool byPosition, uint flags);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DestroyMenu(nint menu);+}diff --git a/Services/NativeWindowTracker.cs b/Services/NativeWindowTracker.csnew file mode 100644index 0000000..c0bae0e--- /dev/null+++ b/Services/NativeWindowTracker.cs@@ -0,0 +1,565 @@+using System.IO;+using System.Runtime.InteropServices;+using System.Text;+using System.Windows.Threading;+using QiDock.Models;++namespace QiDock.Services;++public sealed class NativeWindowTracker : IDisposable+{+ private const uint EventObjectCreate = 0x8000;+ private const uint EventObjectDestroy = 0x8001;+ private const uint EventObjectShow = 0x8002;+ private const uint EventObjectHide = 0x8003;+ private const uint EventObjectNameChange = 0x800C;+ private const uint EventObjectLocationChange = 0x800B;+ private const uint EventSystemAlert = 0x0002;+ private const uint EventSystemForeground = 0x0003;+ private const uint WineventOutOfContext = 0x0000;+ private const int ObjectWindow = 0;+ private const int ChildIdSelf = 0;+ private const int WindowOwner = 4;+ private const int GwlExStyle = -20;+ private const long WsExAppWindow = 0x00040000;+ private const long WsExToolWindow = 0x00000080;+ private const uint GaRootOwner = 3;+ private const uint GaRoot = 2;+ private const uint WmClose = 0x0010;+ private const int ShowRestore = 9;+ private const int ShowMinimize = 6;+ private const uint ProcessQueryLimitedInformation = 0x1000;+ private static readonly string WindowsSystemAppsDirectory = Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.Windows), "SystemApps") + Path.DirectorySeparatorChar;++ private readonly Dispatcher _dispatcher;+ private readonly DispatcherTimer _refreshTimer;+ private readonly WinEventDelegate _eventCallback;+ private readonly EnumWindowsDelegate _enumCallback;+ private readonly HashSet<nint> _notificationWindows = [];+ private nint _windowHook;+ private nint _nameChangeHook;+ private nint _systemEventHook;+ private nint _excludedWindow;+ private int _refreshQueued;+ private int _urgentRefresh;+ private bool _disposed;++ public NativeWindowTracker(Dispatcher dispatcher)+ {+ _dispatcher = dispatcher;+ _refreshTimer = new DispatcherTimer(DispatcherPriority.Input, dispatcher)+ {+ Interval = TimeSpan.FromMilliseconds(60)+ };+ _refreshTimer.Tick += RefreshTimer_Tick;+ _eventCallback = OnWinEvent;+ _enumCallback = CollectWindow;+ }++ public event EventHandler<IReadOnlyList<TrackedWindow>>? WindowsChanged;++ public event Action<nint>? ForegroundWindowChanged;++ public IReadOnlyList<TrackedWindow> Snapshot { get; private set; } = [];++ public bool NotificationsAvailable => _systemEventHook != 0;++ public void Start(nint excludedWindow)+ {+ ObjectDisposedException.ThrowIf(_disposed, this);+ _excludedWindow = excludedWindow;+ _windowHook = SetWinEventHook(EventObjectCreate, EventObjectHide, 0, _eventCallback, 0, 0, WineventOutOfContext);+ if (_windowHook == 0)+ {+ throw new InvalidOperationException("Windows pencere bildirimleri dinlenemedi.");+ }++ _nameChangeHook = SetWinEventHook(EventObjectLocationChange, EventObjectNameChange, 0, _eventCallback, 0, 0, WineventOutOfContext);+ if (_nameChangeHook == 0)+ {+ UnhookWinEvent(_windowHook);+ _windowHook = 0;+ throw new InvalidOperationException("Pencere başlığı değişiklikleri dinlenemedi.");+ }++ _systemEventHook = SetWinEventHook(EventSystemAlert, EventSystemForeground, 0, _eventCallback, 0, 0, WineventOutOfContext);+ RefreshWindows();+ var foregroundWindow = GetForegroundWindow();+ if (foregroundWindow != 0)+ {+ ForegroundWindowChanged?.Invoke(foregroundWindow);+ }+ }++ private void OnWinEvent(nint hook, uint eventType, nint windowHandle, int objectId, int childId, uint eventThread, uint eventTime)+ {+ if (_disposed)+ {+ return;+ }++ if (eventType == EventObjectLocationChange)+ {+ if (objectId == ObjectWindow && childId == ChildIdSelf && windowHandle == GetForegroundWindow())+ QueueRefresh();+ return;+ }++ if (eventType == EventSystemAlert && windowHandle != 0)+ {+ _notificationWindows.Add(windowHandle);+ QueueRefresh();+ return;+ }++ if (eventType == EventSystemForeground && windowHandle != 0)+ {+ _notificationWindows.Remove(windowHandle);+ QueueRefresh(urgent: true);+ _lastReportedForeground = windowHandle;+ ForegroundWindowChanged?.Invoke(windowHandle);+ return;+ }++ if (objectId != ObjectWindow || childId != ChildIdSelf+ || eventType is not (EventObjectCreate or EventObjectDestroy or EventObjectShow or EventObjectHide or EventObjectNameChange))+ {+ return;+ }++ // Apps (Electron, browsers) create, show and rename child and helper windows constantly; only+ // top-level windows, or ones already in the dock, can change what the dock shows.+ var tracked = Snapshot.Any(window => window.Handle == windowHandle);+ if (!tracked && (eventType == EventObjectDestroy || GetAncestor(windowHandle, GaRoot) != windowHandle))+ {+ return;+ }++ if (!tracked && eventType is EventObjectNameChange or EventObjectHide or EventObjectCreate)+ {+ // An untracked top-level window that is renamed, hidden or created (not yet shown) is+ // picked up by its EVENT_OBJECT_SHOW; a low-priority refresh covers late titles.+ if (eventType != EventObjectNameChange || !IsWindowVisible(windowHandle)) return;+ }++ QueueRefresh(urgent: eventType is EventObjectShow or EventObjectDestroy);+ }++ private void QueueRefresh(bool urgent = false)+ {+ if (urgent) Interlocked.Exchange(ref _urgentRefresh, 1);+ if (Interlocked.Exchange(ref _refreshQueued, 1) != 0)+ {+ return;+ }++ _dispatcher.InvokeAsync(() =>+ {+ Interlocked.Exchange(ref _refreshQueued, 0);+ if (!_disposed)+ {+ if (Interlocked.Exchange(ref _urgentRefresh, 0) != 0)+ {+ FlushRefresh();+ }+ else if (!_refreshTimer.IsEnabled)+ {+ // Bound the wait from the first event; later events must not postpone discovery.+ _refreshTimer.Start();+ }+ }+ }, DispatcherPriority.Input);+ }++ private void RefreshTimer_Tick(object? sender, EventArgs e)+ {+ FlushRefresh();+ }++ private void FlushRefresh()+ {+ _refreshTimer.Stop();+ var changed = RefreshWindows();+ // Only report real changes; every report repositions the dock window.+ var foreground = GetForegroundWindow();+ if (!changed && foreground == _lastReportedForeground) return;+ _lastReportedForeground = foreground;+ ForegroundWindowChanged?.Invoke(foreground);+ }++ private nint _lastReportedForeground;++ private bool RefreshWindows()+ {+ var windows = new List<TrackedWindow>();+ var previousWindows = Snapshot.ToDictionary(window => window.Handle);+ var state = GCHandle.Alloc(new WindowCollectionState(windows, previousWindows));+ try+ {+ EnumWindows(_enumCallback, GCHandle.ToIntPtr(state));+ }+ finally+ {+ state.Free();+ }++ _notificationWindows.RemoveWhere(windowHandle => !IsWindow(windowHandle));++ if (Snapshot.SequenceEqual(windows))+ {+ return false;+ }++ Snapshot = windows;+ WindowsChanged?.Invoke(this, windows);+ return true;+ }++ private bool CollectWindow(nint windowHandle, nint state)+ {+ if (windowHandle == _excludedWindow || !IsWindowVisible(windowHandle)+ || GetWindow(windowHandle, WindowOwner) != 0)+ {+ return true;+ }++ var extendedStyle = GetWindowLongPtr(windowHandle, GwlExStyle).ToInt64();+ if ((extendedStyle & WsExToolWindow) != 0 && (extendedStyle & WsExAppWindow) == 0)+ {+ return true;+ }++ var titleLength = GetWindowTextLength(windowHandle);+ if (titleLength <= 0)+ {+ return true;+ }++ var title = new StringBuilder(Math.Min(titleLength + 1, 1024));+ GetWindowText(windowHandle, title, title.Capacity);+ var value = title.ToString().Trim();+ if (value.Length > 0)+ {+ if (GCHandle.FromIntPtr(state).Target is WindowCollectionState collection)+ {+ collection.Previous.TryGetValue(windowHandle, out var previous);+ if (IsCloaked(windowHandle))+ {+ return true;+ }++ var executablePath = previous?.ExecutablePath ?? ResolveFrameHost(windowHandle, GetExecutablePath(windowHandle));+ if (executablePath == string.Empty || IsWindowsSystemApp(executablePath))+ {+ return true;+ }++ if (IsExplorerShellWindow(executablePath, windowHandle))+ {+ return true;+ }++ if (previous is not null)+ {+ collection.Windows.Add(previous with+ {+ Title = value,+ HasNotification = _notificationWindows.Contains(windowHandle)+ });+ }+ else+ {+ collection.Windows.Add(new TrackedWindow(windowHandle, value,+ executablePath, _notificationWindows.Contains(windowHandle)));+ }+ }+ }++ return true;+ }++ public static bool Activate(nint windowHandle)+ {+ if (!IsWindow(windowHandle))+ {+ return false;+ }++ if (IsIconic(windowHandle))+ {+ ShowWindow(windowHandle, ShowRestore);+ }++ var targetThread = GetWindowThreadProcessId(windowHandle, out _);+ var currentThread = GetCurrentThreadId();+ var attached = targetThread != 0 && targetThread != currentThread+ && AttachThreadInput(currentThread, targetThread, true);+ try+ {+ BringWindowToTop(windowHandle);+ return SetForegroundWindow(windowHandle);+ }+ finally+ {+ if (attached)+ {+ AttachThreadInput(currentThread, targetThread, false);+ }+ }+ }++ public static nint GetForegroundApplicationWindow()+ {+ var foreground = GetForegroundWindow();+ GetWindowThreadProcessId(foreground, out var processId);+ if (foreground == 0 || processId == Environment.ProcessId) return 0;+ var root = GetAncestor(foreground, GaRootOwner);+ return root != 0 ? root : foreground;+ }++ /// <summary>+ /// The window a dock click should minimize: the foreground window when it belongs to the clicked+ /// app, otherwise 0 (the click should bring the app forward instead).+ /// </summary>+ public static nint GetMinimizeTarget(nint windowHandle, string executablePath, nint? foregroundAtPress = null)+ {+ var foregroundWindow = foregroundAtPress ?? GetForegroundApplicationWindow();+ if (foregroundWindow == 0)+ {+ return 0;+ }++ var foregroundRoot = GetAncestor(foregroundWindow, GaRootOwner);+ if (foregroundRoot == 0)+ {+ foregroundRoot = foregroundWindow;+ }++ return IsWindow(foregroundRoot) && !IsIconic(foregroundRoot)+ && (foregroundRoot == windowHandle+ || string.Equals(GetExecutablePath(foregroundRoot), executablePath, StringComparison.OrdinalIgnoreCase))+ ? foregroundRoot+ : 0;+ }++ public static bool IsMinimized(nint windowHandle) => IsWindow(windowHandle) && IsIconic(windowHandle);++ internal static string? ExecutablePathOf(nint windowHandle) => GetExecutablePath(windowHandle);++ public static bool ToggleActivation(nint windowHandle, string executablePath, nint? foregroundAtPress = null)+ {+ if (!IsWindow(windowHandle))+ {+ return false;+ }++ var minimizeTarget = GetMinimizeTarget(windowHandle, executablePath, foregroundAtPress);+ return minimizeTarget != 0 ? ShowWindowAsync(minimizeTarget, ShowMinimize) : Activate(windowHandle);+ }++ public static bool RequestClose(nint windowHandle)+ {+ return IsWindow(windowHandle) && PostMessage(windowHandle, WmClose, 0, 0);+ }++ public void Dispose()+ {+ if (_disposed)+ {+ return;+ }++ _disposed = true;+ _refreshTimer.Stop();+ _refreshTimer.Tick -= RefreshTimer_Tick;+ if (_windowHook != 0)+ {+ UnhookWinEvent(_windowHook);+ _windowHook = 0;+ }++ if (_nameChangeHook != 0)+ {+ UnhookWinEvent(_nameChangeHook);+ _nameChangeHook = 0;+ }++ if (_systemEventHook != 0)+ {+ UnhookWinEvent(_systemEventHook);+ _systemEventHook = 0;+ }+ }++ private delegate void WinEventDelegate(nint hook, uint eventType, nint windowHandle, int objectId, int childId, uint eventThread, uint eventTime);+ private delegate bool EnumWindowsDelegate(nint windowHandle, nint state);++ private sealed record WindowCollectionState(List<TrackedWindow> Windows, IReadOnlyDictionary<nint, TrackedWindow> Previous);++ [DllImport("user32.dll", SetLastError = true)]+ private static extern nint SetWinEventHook(uint eventMin, uint eventMax, nint eventHookModule, WinEventDelegate callback, uint processId, uint threadId, uint flags);++ [DllImport("user32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool UnhookWinEvent(nint hook);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool EnumWindows(EnumWindowsDelegate callback, nint state);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool IsWindowVisible(nint windowHandle);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool IsWindow(nint windowHandle);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool IsIconic(nint windowHandle);++ [DllImport("user32.dll")]+ private static extern nint GetWindow(nint windowHandle, int command);++ [DllImport("user32.dll", CharSet = CharSet.Unicode)]+ private static extern int GetWindowText(nint windowHandle, StringBuilder text, int maximumCount);++ [DllImport("user32.dll", CharSet = CharSet.Unicode)]+ private static extern int GetWindowTextLength(nint windowHandle);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool SetForegroundWindow(nint windowHandle);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool BringWindowToTop(nint windowHandle);++ [DllImport("user32.dll")]+ private static extern uint GetWindowThreadProcessId(nint windowHandle, out uint processId);++ [DllImport("kernel32.dll")]+ private static extern uint GetCurrentThreadId();++ private static string? GetExecutablePath(nint windowHandle)+ {+ var threadId = GetWindowThreadProcessId(windowHandle, out var processId);+ if (threadId == 0 || processId == 0)+ {+ return null;+ }++ var processHandle = OpenProcess(ProcessQueryLimitedInformation, false, processId);+ if (processHandle == 0)+ {+ return null;+ }++ try+ {+ var path = new StringBuilder(32768);+ var length = (uint)path.Capacity;+ return QueryFullProcessImageName(processHandle, 0, path, ref length) ? path.ToString() : null;+ }+ finally+ {+ CloseHandle(processHandle);+ }+ }++ /// <summary>Suspended or virtual-desktop windows are cloaked; Windows' own taskbar hides them too.</summary>+ private static bool IsCloaked(nint windowHandle) =>+ DwmGetWindowAttribute(windowHandle, DwmwaCloaked, out var cloaked, sizeof(int)) == 0 && cloaked != 0;++ /// <summary>+ /// Store apps (Settings, Calculator…) live inside ApplicationFrameHost.exe, which has no icon of its own.+ /// Use the hosted app's process instead, or an empty path (skipped) when the app is not attached yet.+ /// </summary>+ private static string? ResolveFrameHost(nint windowHandle, string? executablePath)+ {+ if (!string.Equals(Path.GetFileName(executablePath), "ApplicationFrameHost.exe", StringComparison.OrdinalIgnoreCase))+ {+ return executablePath;+ }++ GetWindowThreadProcessId(windowHandle, out var hostProcessId);+ nint child = 0;+ while ((child = FindWindowEx(windowHandle, child, "Windows.UI.Core.CoreWindow", null)) != 0)+ {+ GetWindowThreadProcessId(child, out var childProcessId);+ if (childProcessId != 0 && childProcessId != hostProcessId)+ {+ return GetExecutablePath(child) ?? string.Empty;+ }+ }++ return string.Empty;+ }++ private const int DwmwaCloaked = 14;++ [DllImport("dwmapi.dll")]+ private static extern int DwmGetWindowAttribute(nint windowHandle, int attribute, out int value, int size);++ [DllImport("user32.dll", CharSet = CharSet.Unicode)]+ private static extern nint FindWindowEx(nint parent, nint childAfter, string? className, string? windowName);++ private static bool IsWindowsSystemApp(string? executablePath)+ {+ return executablePath is not null+ && executablePath.StartsWith(WindowsSystemAppsDirectory, StringComparison.OrdinalIgnoreCase);+ }++ private static bool IsExplorerShellWindow(string? executablePath, nint windowHandle)+ {+ if (!string.Equals(Path.GetFileName(executablePath), "explorer.exe", StringComparison.OrdinalIgnoreCase))+ {+ return false;+ }++ var className = new StringBuilder(256);+ var length = GetClassName(windowHandle, className, className.Capacity);+ return length <= 0 || className.ToString() is not ("CabinetWClass" or "ExploreWClass");+ }++ [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW", SetLastError = true)]+ private static extern nint GetWindowLongPtr(nint windowHandle, int index);++ [DllImport("user32.dll")]+ private static extern nint GetForegroundWindow();++ [DllImport("user32.dll")]+ private static extern nint GetAncestor(nint windowHandle, uint flags);++ [DllImport("user32.dll", CharSet = CharSet.Unicode)]+ private static extern int GetClassName(nint windowHandle, StringBuilder className, int maximumCount);++ [DllImport("user32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool PostMessage(nint windowHandle, uint message, nint wParam, nint lParam);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool AttachThreadInput(uint threadIdAttach, uint threadIdAttachTo, [MarshalAs(UnmanagedType.Bool)] bool attach);++ [DllImport("kernel32.dll", SetLastError = true)]+ private static extern nint OpenProcess(uint desiredAccess, [MarshalAs(UnmanagedType.Bool)] bool inheritHandle, uint processId);++ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool QueryFullProcessImageName(nint processHandle, uint flags, StringBuilder executablePath, ref uint size);++ [DllImport("kernel32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool CloseHandle(nint handle);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool ShowWindow(nint windowHandle, int command);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool ShowWindowAsync(nint windowHandle, int command);+}diff --git a/Services/Notifications/NotificationFeed.cs b/Services/Notifications/NotificationFeed.csnew file mode 100644index 0000000..e006038--- /dev/null+++ b/Services/Notifications/NotificationFeed.cs@@ -0,0 +1,475 @@+using System.Diagnostics;+using System.IO;+using System.Runtime.InteropServices;+using System.Text;+using System.Text.Json;+using System.Windows.Media.Imaging;+using System.Windows.Threading;+using System.Xml.Linq;++namespace QiDock.Services.Notifications;++/// <summary>One Windows notification as shown on the banner and in the list.</summary>+public sealed record AppNotification(+ long Id,+ string AppId,+ string Title,+ string Body,+ DateTime Arrived,+ string? Launch,+ bool LaunchIsProtocol,+ string? LogoPath);++/// <summary>+/// Windows notifications, read from Windows' own notification database+/// (%LOCALAPPDATA%\Microsoft\Windows\Notifications\wpndatabase.db) with the SQLite that ships in+/// System32. The WinRT listener API needs app identity and is slow; this needs neither. The database+/// is copied first, so Windows' lock never matters and the original is never written.+/// <para>+/// The list follows Windows: a notification cleared in the Windows notification center leaves+/// here too. Items removed here are remembered locally (Windows keeps its own copy).+/// </para>+/// </summary>+public sealed class NotificationFeed : IDisposable+{+ private const int MaxRows = 60;+ private static readonly string SourceDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Microsoft\Windows\Notifications");+ private static readonly string DataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock");+ private static readonly string CopyDir = Path.Combine(DataDir, "notifications-copy");+ private static readonly string StateFile = Path.Combine(DataDir, "notifications.json");+ private static readonly string[] Files = ["wpndatabase.db", "wpndatabase.db-wal"];++ /// <summary>The one feed the banner, the bar tile and the dock button share (created on the UI thread).</summary>+ public static NotificationFeed Shared { get; } = new();++ private readonly DispatcherTimer _poll = new(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(1) };+ private readonly HashSet<long> _seen = [];+ private DateTime _stamp = DateTime.MinValue;+ private bool _primed, _reading;+ private State _state;++ /// <summary>Notifications Windows still holds, newest first, without the ones removed here.</summary>+ public IReadOnlyList<AppNotification> Items { get; private set; } = [];++ /// <summary>Notifications that arrived after the list was last opened.</summary>+ public int UnreadCount => Items.Count(n => n.Arrived > _state.ReadUpTo);++ /// <summary>Whether the feed could read the database at all (false on an unsupported system).</summary>+ public bool Available { get; private set; } = true;++ /// <summary>New notifications since the last poll (never the ones present at start-up).</summary>+ public event Action<IReadOnlyList<AppNotification>>? Arrived;++ /// <summary>The list or the unread count changed.</summary>+ public event Action? Changed;++ private NotificationFeed()+ {+ _state = LoadState();+ _poll.Tick += (_, _) => _ = PollAsync();+ }++ public void Start()+ {+ _poll.Start();+ _ = PollAsync();+ }++ public void Dispose() => _poll.Stop();++ public void MarkAllRead()+ {+ if (Items.Count == 0 || Items[0].Arrived <= _state.ReadUpTo) return;+ _state = _state with { ReadUpTo = Items[0].Arrived };+ SaveState();+ Changed?.Invoke();+ }++ public void Remove(AppNotification notification) => RemoveMany([notification]);++ /// <summary>Removes several notifications with one save and one <see cref="Changed"/>.</summary>+ public void RemoveMany(IReadOnlyCollection<AppNotification> notifications)+ {+ if (notifications.Count == 0) return;+ var ids = notifications.Select(n => n.Id).ToHashSet();+ _state = _state with { Removed = [.. _state.Removed.Concat(ids).TakeLast(400)] };+ SaveState();+ Items = Items.Where(n => !ids.Contains(n.Id)).ToList();+ Changed?.Invoke();+ }++ public void ClearAll()+ {+ if (Items.Count == 0) return;+ var newest = Items.Max(n => n.Arrived);+ _state = _state with { ClearedUpTo = newest, ReadUpTo = newest > _state.ReadUpTo ? newest : _state.ReadUpTo };+ SaveState();+ Items = [];+ Changed?.Invoke();+ }++ private async Task PollAsync()+ {+ if (_reading) return;+ var stamp = DateTime.MinValue;+ try+ {+ foreach (var file in Files)+ {+ var path = Path.Combine(SourceDir, file);+ if (File.Exists(path) && File.GetLastWriteTimeUtc(path) > stamp) stamp = File.GetLastWriteTimeUtc(path);+ }+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return; }+ if (stamp == _stamp && _primed) return;++ _reading = true;+ List<AppNotification>? rows;+ try { rows = await Task.Run(ReadDatabase); }+ finally { _reading = false; }+ if (rows is null)+ {+ if (!_primed) Available = File.Exists(Path.Combine(SourceDir, Files[0]));+ return; // Windows held a lock; the next tick tries again+ }+ _stamp = stamp;++ var visible = rows.Where(n => n.Arrived > _state.ClearedUpTo && !_state.Removed.Contains(n.Id)).ToList();+ var added = new List<AppNotification>();+ foreach (var n in visible)+ if (_seen.Add(n.Id) && _primed && n.Arrived > DateTime.UtcNow.AddMinutes(-2)) added.Add(n);+ foreach (var n in rows) _seen.Add(n.Id);+ var changed = !_primed || !visible.Select(n => n.Id).SequenceEqual(Items.Select(n => n.Id));+ Items = visible;+ _primed = true;+ if (changed) Changed?.Invoke();+ if (added.Count > 0) Arrived?.Invoke(added);+ }++ // ---- Database ----------------------------------------------------------------------------++ private static List<AppNotification>? ReadDatabase()+ {+ try+ {+ Directory.CreateDirectory(CopyDir);+ // SQLite rebuilds the index file from the log; a stale one from the last copy must not be reused.+ var index = Path.Combine(CopyDir, "wpndatabase.db-shm");+ if (File.Exists(index)) File.Delete(index);+ foreach (var file in Files)+ {+ var source = Path.Combine(SourceDir, file);+ var target = Path.Combine(CopyDir, file);+ if (!File.Exists(source))+ {+ if (File.Exists(target)) File.Delete(target);+ continue;+ }+ if (!CopyShared(source, target)) return null;+ }+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ return null;+ }++ try+ {+ // Read-write on the private copy so SQLite can replay the write-ahead log.+ if (Sqlite.sqlite3_open_v2(Path.Combine(CopyDir, "wpndatabase.db"), out var db, 2, 0) != 0) return null;+ try+ {+ const string sql = "SELECT n.Id, h.PrimaryId, n.ArrivalTime, n.Payload FROM Notification n " ++ "JOIN NotificationHandler h ON n.HandlerId = h.RecordId WHERE n.Type = 'toast' " ++ "ORDER BY n.ArrivalTime DESC LIMIT 60";+ if (Sqlite.sqlite3_prepare_v2(db, sql, -1, out var statement, 0) != 0) return null;+ try+ {+ var result = new List<AppNotification>();+ while (Sqlite.sqlite3_step(statement) == 100 /* SQLITE_ROW */ && result.Count < MaxRows)+ {+ var id = Sqlite.sqlite3_column_int64(statement, 0);+ var appId = Marshal.PtrToStringUni(Sqlite.sqlite3_column_text16(statement, 1)) ?? "";+ var arrival = Sqlite.sqlite3_column_int64(statement, 2);+ var length = Sqlite.sqlite3_column_bytes(statement, 3);+ var blob = Sqlite.sqlite3_column_blob(statement, 3);+ if (blob == 0 || length <= 0) continue;+ var payload = new byte[length];+ Marshal.Copy(blob, payload, 0, length);+ if (Parse(id, appId, arrival, payload) is { } notification) result.Add(notification);+ }+ return result;+ }+ finally { Sqlite.sqlite3_finalize(statement); }+ }+ finally { Sqlite.sqlite3_close(db); }+ }+ catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException)+ {+ return null;+ }+ }++ private static bool CopyShared(string source, string target)+ {+ for (var attempt = 0; ; attempt++)+ {+ try+ {+ using var input = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);+ using var output = new FileStream(target, FileMode.Create, FileAccess.Write);+ input.CopyTo(output);+ return true;+ }+ catch (IOException) when (attempt < 4)+ {+ Thread.Sleep(40); // Windows may hold a byte-range lock for a moment+ }+ catch (IOException)+ {+ return false;+ }+ }+ }++ /// <summary>Title, text, launch target and logo from the toast XML.</summary>+ internal static AppNotification? Parse(long id, string appId, long arrival, byte[] payload)+ {+ string xml;+ if (payload.Length >= 2 && payload[1] == 0) xml = Encoding.Unicode.GetString(payload);+ else xml = Encoding.UTF8.GetString(payload);+ xml = xml.TrimStart('').TrimEnd('\0');+ XElement toast;+ try { toast = XElement.Parse(xml); }+ catch (System.Xml.XmlException) { return null; }+ if (toast.Name.LocalName != "toast") return null;++ var binding = toast.Descendants().FirstOrDefault(e => e.Name.LocalName == "binding");+ if (binding is null) return null;+ bool IsAttribution(XElement e) => (string?)e.Attribute("placement") == "attribution";+ var texts = binding.Elements().Where(e => e.Name.LocalName == "text" && !IsAttribution(e)).Select(e => e.Value.Trim()).Where(t => t.Length > 0).ToList();+ if (texts.Count == 0)+ texts = binding.Descendants().Where(e => e.Name.LocalName == "text" && !IsAttribution(e)).Select(e => e.Value.Trim()).Where(t => t.Length > 0).ToList();+ if (texts.Count == 0) return null;++ var logo = binding.Elements().FirstOrDefault(e => e.Name.LocalName == "image" && (string?)e.Attribute("placement") == "appLogoOverride");+ var launch = (string?)toast.Attribute("launch");+ var activation = (string?)toast.Attribute("activationType");+ DateTime arrived;+ try { arrived = DateTime.FromFileTimeUtc(arrival); }+ catch (ArgumentOutOfRangeException) { arrived = DateTime.UtcNow; }+ return new AppNotification(id, appId, texts[0], string.Join(Environment.NewLine, texts.Skip(1)), arrived,+ string.IsNullOrWhiteSpace(launch) ? null : launch, string.Equals(activation, "protocol", StringComparison.OrdinalIgnoreCase), LocalImage((string?)logo?.Attribute("src")));+ }++ private static string? LocalImage(string? source)+ {+ if (string.IsNullOrWhiteSpace(source)) return null;+ if (Uri.TryCreate(source, UriKind.Absolute, out var uri) && uri.IsFile) source = uri.LocalPath;+ return Path.IsPathFullyQualified(source) && File.Exists(source) ? source : null;+ }++ // ---- Local state ------------------------------------------------------------------------++ private sealed record State(DateTime ReadUpTo, DateTime ClearedUpTo, IReadOnlyList<long> Removed);++ private static State LoadState()+ {+ try+ {+ if (File.Exists(StateFile) && JsonSerializer.Deserialize<State>(File.ReadAllText(StateFile)) is { } state)+ return state with { Removed = state.Removed ?? [] };+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) { }+ // First run: what is already there counts as read.+ return new State(DateTime.UtcNow, DateTime.MinValue, []);+ }++ private void SaveState()+ {+ try+ {+ Directory.CreateDirectory(DataDir);+ var temporary = StateFile + ".tmp";+ File.WriteAllText(temporary, JsonSerializer.Serialize(_state));+ File.Move(temporary, StateFile, overwrite: true);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }+ }++ private static class Sqlite+ {+ private const string Library = "winsqlite3.dll";+ [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] public static extern int sqlite3_open_v2([MarshalAs(UnmanagedType.LPUTF8Str)] string file, out nint db, int flags, nint vfs);+ [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] public static extern int sqlite3_close(nint db);+ [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] public static extern int sqlite3_prepare_v2(nint db, [MarshalAs(UnmanagedType.LPUTF8Str)] string sql, int length, out nint statement, nint tail);+ [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] public static extern int sqlite3_step(nint statement);+ [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] public static extern int sqlite3_finalize(nint statement);+ [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] public static extern long sqlite3_column_int64(nint statement, int column);+ [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] public static extern nint sqlite3_column_text16(nint statement, int column);+ [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] public static extern nint sqlite3_column_blob(nint statement, int column);+ [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] public static extern int sqlite3_column_bytes(nint statement, int column);+ }+}++/// <summary>Name, icon and activation of the app behind a notification (by its AppUserModelID).</summary>+public static class NotificationApps+{+ private static readonly Dictionary<string, (string Name, BitmapSource? Icon)> Cache = new(StringComparer.OrdinalIgnoreCase);++ public static string Name(string appId) => Resolve(appId).Name;+ public static BitmapSource? Icon(string appId) => Resolve(appId).Icon;++ private static (string Name, BitmapSource? Icon) Resolve(string appId)+ {+ if (Cache.TryGetValue(appId, out var known)) return known;+ string? name = null;+ BitmapSource? icon = null;+ if (SHCreateItemFromParsingName(@"shell:AppsFolder\" + appId, 0, typeof(IShellItem).GUID, out var item) == 0 && item is not null)+ {+ try+ {+ if (item.GetDisplayName(0 /* SIGDN_NORMALDISPLAY */, out var pointer) == 0 && pointer != 0)+ {+ name = Marshal.PtrToStringUni(pointer);+ Marshal.FreeCoTaskMem(pointer);+ }+ icon = ImageOf(item, 64);+ }+ finally { Marshal.ReleaseComObject(item); }+ }+ var result = (string.IsNullOrWhiteSpace(name) || name == appId ? Fallback(appId) : name, icon);+ Cache[appId] = result;+ return result;+ }++ /// <summary>An app's icon at the given pixel size, not cached (the launcher loads them while it is open).</summary>+ public static BitmapSource? LoadIcon(string appId, int size)+ {+ if (SHCreateItemFromParsingName(@"shell:AppsFolder\" + appId, 0, typeof(IShellItem).GUID, out var item) != 0 || item is null) return null;+ try { return ImageOf(item, size); }+ finally { Marshal.ReleaseComObject(item); }+ }++ private static BitmapSource? ImageOf(IShellItem item, int size)+ {+ if (item is not IShellItemImageFactory factory || factory.GetImage(new NativeSize(size, size), 0x1 | 0x4 /* bigger ok, icon only */, out var bitmap) != 0 || bitmap == 0) return null;+ try { return FromHBitmap(bitmap); }+ finally { DeleteObject(bitmap); }+ }++ private static string Fallback(string appId)+ {+ var name = appId.Contains('!') ? appId[(appId.IndexOf('!') + 1)..] : appId;+ name = Path.GetFileNameWithoutExtension(name.Split('\\', '/').Last());+ var dot = name.LastIndexOf('.');+ if (dot > 0 && dot < name.Length - 1) name = name[(dot + 1)..];+ return name.Length > 0 ? char.ToUpperInvariant(name[0]) + name[1..] : appId;+ }++ /// <summary>A 32-bit shell bitmap with its alpha channel (CreateBitmapSourceFromHBitmap drops it).</summary>+ private static BitmapSource? FromHBitmap(nint bitmap)+ {+ var section = new DibSection();+ if (GetObject(bitmap, Marshal.SizeOf<DibSection>(), ref section) == 0 || section.Bits == 0 || section.BitsPixel != 32) return null;+ int width = section.Width, height = Math.Abs(section.Height), stride = width * 4;+ var pixels = new byte[stride * height];+ Marshal.Copy(section.Bits, pixels, 0, pixels.Length);+ if (section.HeaderHeight > 0) // bottom-up rows+ {+ var flipped = new byte[pixels.Length];+ for (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);+ source.Freeze();+ return source;+ }++ /// <summary>+ /// Opens what the notification points to: its link for protocol toasts, otherwise the app's+ /// open window (windows carry the AppUserModelID their toasts use), otherwise the app itself.+ /// </summary>+ public static void Activate(AppNotification notification)+ {+ try+ {+ if (notification.LaunchIsProtocol && notification.Launch is { } link+ && Uri.TryCreate(link, UriKind.Absolute, out var uri) && !uri.IsFile && !uri.IsUnc)+ {+ Process.Start(new ProcessStartInfo(link) { UseShellExecute = true });+ return;+ }+ if (FindWindow(notification.AppId) is { } window && NativeWindowTracker.Activate(window)) return;+ if (notification.AppId.Length > 0)+ Process.Start(new ProcessStartInfo("explorer.exe", @"shell:AppsFolder\" + notification.AppId) { UseShellExecute = true });+ }+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException) { }+ }++ private static nint? FindWindow(string appId)+ {+ nint? found = null;+ EnumWindows((window, _) =>+ {+ if (!IsWindowVisible(window) || GetWindow(window, 4 /* GW_OWNER */) != 0) return true;+ if ((GetWindowLongPtr(window, -20).ToInt64() & 0x80 /* WS_EX_TOOLWINDOW */) != 0) return true;+ if (string.Equals(NativeJumpListSession.AppIdForWindow(window), appId, StringComparison.OrdinalIgnoreCase))+ {+ found = window;+ return false;+ }+ return true;+ }, 0);+ return found;+ }++ private delegate bool EnumWindowsProc(nint window, nint parameter);+ [DllImport("user32.dll")] private static extern bool EnumWindows(EnumWindowsProc callback, nint parameter);+ [DllImport("user32.dll")] private static extern bool IsWindowVisible(nint window);+ [DllImport("user32.dll")] private static extern nint GetWindow(nint window, uint command);+ [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW")] private static extern nint GetWindowLongPtr(nint window, int index);+ [DllImport("gdi32.dll")] private static extern bool DeleteObject(nint handle);+ [DllImport("gdi32.dll", EntryPoint = "GetObjectW")] private static extern int GetObject(nint handle, int size, ref DibSection section);++ [DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = true)]+ private static extern int SHCreateItemFromParsingName(string path, nint context, [MarshalAs(UnmanagedType.LPStruct)] Guid iid, [MarshalAs(UnmanagedType.Interface)] out IShellItem? item);++ [StructLayout(LayoutKind.Sequential)]+ private struct NativeSize(int width, int height)+ {+ public int Width = width;+ public int Height = height;+ }++ /// <summary>DIBSECTION: BITMAP followed by BITMAPINFOHEADER (only the fields read here are named).</summary>+ [StructLayout(LayoutKind.Sequential)]+ private struct DibSection+ {+ public int Type, Width, Height, WidthBytes;+ public ushort Planes, BitsPixel;+ public nint Bits;+ public int HeaderSize, HeaderWidth, HeaderHeight;+ public ushort HeaderPlanes, HeaderBitCount;+ public int Compression, SizeImage, XPelsPerMeter, YPelsPerMeter, ClrUsed, ClrImportant;+ public int BitFields0, BitFields1, BitFields2;+ public nint Section;+ public int Offset;+ }++ [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IShellItem+ {+ [PreserveSig] int BindToHandler(nint context, ref Guid handler, ref Guid iid, out nint result);+ [PreserveSig] int GetParent(out nint parent);+ [PreserveSig] int GetDisplayName(uint form, out nint name);+ [PreserveSig] int GetAttributes(uint mask, out uint attributes);+ [PreserveSig] int Compare(nint other, uint hint, out int order);+ }++ [ComImport, Guid("BCC18B79-BA16-442F-80C4-8A59C30C463B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IShellItemImageFactory+ {+ [PreserveSig] int GetImage(NativeSize size, uint flags, out nint bitmap);+ }+}diff --git a/Services/Notifications/WindowsToastHider.cs b/Services/Notifications/WindowsToastHider.csnew file mode 100644index 0000000..9da422e--- /dev/null+++ b/Services/Notifications/WindowsToastHider.cs@@ -0,0 +1,191 @@+using System.Diagnostics;+using System.IO;+using System.Runtime.InteropServices;+using System.Text;++namespace QiDock.Services.Notifications;++/// <summary>+/// Keeps Windows' own notification pop-up (bottom right) off screen while QiDock shows the+/// notification at the top, so each notification appears once. Nothing in Windows' settings+/// changes: the pop-up window is only moved away when it appears (sound, the notification center+/// and "Do not disturb" keep working), and it is put back when this stops.+/// The window hooks run on a thread of their own, so the pop-up is moved within milliseconds even+/// while the app's interface thread is busy (starting up, drawing, loading icons).+/// </summary>+public sealed class WindowsToastHider : IDisposable+{+ private const uint EventObjectShow = 0x8002;+ private const uint EventObjectLocationChange = 0x800B;+ private const uint EventObjectUncloaked = 0x8018;+ private const uint OutOfContextSkipOwnProcess = 0x0002; // WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS+ private const uint WmQuit = 0x0012;+ private const int OffScreen = -32000;++ // The pop-up's window title in the languages QiDock ships with (the notification center has another title).+ private static readonly HashSet<string> Titles = new(StringComparer.OrdinalIgnoreCase) { "New notification", "Yeni bildirim" };+ private static readonly HashSet<string> Hosts = new(StringComparer.OrdinalIgnoreCase) { "ShellExperienceHost", "ShellHost" };+ private static readonly string LogFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QiDock", "toast-windows.log");++ // Everything below is used on the hook thread only.+ private readonly WinEventProc _callback;+ private readonly Dictionary<nint, NativeRect?> _moved = [];+ private readonly Dictionary<uint, string> _processNames = [];++ private Thread? _thread;+ private uint _threadId;++ public WindowsToastHider() => _callback = OnEvent;++ public void SetEnabled(bool enabled)+ {+ if (enabled == (_thread is not null)) return;+ if (enabled)+ {+ using var ready = new ManualResetEventSlim();+ _thread = new Thread(() => Run(ready)) { IsBackground = true, Name = "Windows toast hider" };+ _thread.Start();+ ready.Wait(2000);+ }+ else+ {+ PostThreadMessage(_threadId, WmQuit, 0, 0);+ _thread!.Join(2000);+ _thread = null;+ }+ }++ public void Dispose() => SetEnabled(false);++ private void Run(ManualResetEventSlim ready)+ {+ _threadId = GetCurrentThreadId();+ // The callbacks arrive through this thread's message queue.+ var hooks = new[]+ {+ SetWinEventHook(EventObjectShow, EventObjectShow, 0, _callback, 0, 0, OutOfContextSkipOwnProcess),+ SetWinEventHook(EventObjectLocationChange, EventObjectLocationChange, 0, _callback, 0, 0, OutOfContextSkipOwnProcess),+ // The pop-up is a shell window that stays shown and is only uncloaked for each notification.+ SetWinEventHook(EventObjectUncloaked, EventObjectUncloaked, 0, _callback, 0, 0, OutOfContextSkipOwnProcess)+ };+ // A pop-up window may already exist (and may still sit off screen if an earlier run did not end cleanly).+ EnumWindows((window, _) =>+ {+ if (IsToast(window, "scan")) Hide(window, "scan");+ return true;+ }, 0);+ ready.Set();++ while (GetMessage(out var message, 0, 0, 0) > 0)+ {+ TranslateMessage(ref message);+ DispatchMessage(ref message);+ }++ foreach (var hook in hooks)+ if (hook != 0) UnhookWinEvent(hook);+ Restore();+ }++ private void OnEvent(nint hook, uint kind, nint window, int objectId, int childId, uint thread, uint time)+ {+ if (objectId != 0 /* OBJID_WINDOW */ || childId != 0 || window == 0) return;+ if (_moved.ContainsKey(window))+ {+ // Windows places the reused pop-up again for each notification.+ if (GetWindowRect(window, out var rect) && rect.Left > OffScreen + 100)+ {+ MoveAway(window);+ if (kind != EventObjectLocationChange) Log($"moved again on {Name(kind)} from {rect.Left},{rect.Top}, {Lag(time)} ms after the event");+ }+ return;+ }+ if (GetAncestor(window, 2 /* GA_ROOT */) != window || !IsToast(window, kind == EventObjectUncloaked ? "trace" : null)) return;+ Hide(window, $"{Name(kind)}, {Lag(time)} ms after the event");+ }++ private void Hide(nint window, string reason)+ {+ // Remember the window even when it is already off screen, so later placements are caught at once.+ var onScreen = GetWindowRect(window, out var bounds) && bounds.Left > OffScreen + 100;+ _moved.TryAdd(window, onScreen ? bounds : null);+ if (onScreen) MoveAway(window);+ Log($"pop-up {window} {(onScreen ? $"moved from {bounds.Left},{bounds.Top}" : "already off screen")} ({reason})");+ }++ private bool IsToast(nint window, string? trace)+ {+ GetWindowThreadProcessId(window, out var pid);+ if (!_processNames.TryGetValue(pid, out var name))+ {+ try { name = Process.GetProcessById((int)pid).ProcessName; }+ catch (ArgumentException) { name = ""; }+ _processNames[pid] = name;+ }+ if (!Hosts.Contains(name)) return false;+ var title = Text(window, GetWindowText);+ if (title.Length == 0) return false;+ var match = Titles.Contains(title);+ // A short trace of shell windows, to recognise the notification pop-up on new Windows builds.+ if (!match && trace == "trace") Log($"{name} class={Text(window, GetClassName)} title='{title}' (not the pop-up)");+ return match;+ }++ private static void MoveAway(nint window) =>+ SetWindowPos(window, 0, OffScreen, OffScreen, 0, 0, 0x0001 /* NOSIZE */ | 0x0004 /* NOZORDER */ | 0x0010 /* NOACTIVATE */ | 0x4000 /* ASYNCWINDOWPOS */);++ private void Restore()+ {+ foreach (var (window, bounds) in _moved)+ if (bounds is { } rect && IsWindow(window)) SetWindowPos(window, 0, rect.Left, rect.Top, 0, 0, 0x0001 | 0x0004 | 0x0010 | 0x4000);+ _moved.Clear();+ }++ private static string Name(uint kind) => kind switch+ {+ EventObjectShow => "show",+ EventObjectUncloaked => "uncloak",+ EventObjectLocationChange => "move",+ _ => kind.ToString("X", System.Globalization.CultureInfo.InvariantCulture)+ };++ /// <summary>How long the event waited before it reached this thread.</summary>+ private static long Lag(uint time) => (uint)Environment.TickCount - time;++ private static void Log(string line)+ {+ try+ {+ if (File.Exists(LogFile) && new FileInfo(LogFile).Length > 64 * 1024) File.Delete(LogFile);+ File.AppendAllText(LogFile, $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} {line}{Environment.NewLine}");+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }+ }++ private static string Text(nint window, Func<nint, StringBuilder, int, int> read)+ {+ var buffer = new StringBuilder(128);+ read(window, buffer, buffer.Capacity);+ return buffer.ToString();+ }++ [StructLayout(LayoutKind.Sequential)] private struct NativeRect { public int Left, Top, Right, Bottom; }+ [StructLayout(LayoutKind.Sequential)] private struct NativeMessage { public nint Window; public uint Message; public nint WParam, LParam; public uint Time; public int X, Y; }+ private delegate void WinEventProc(nint hook, uint kind, nint window, int objectId, int childId, uint thread, uint time);+ private delegate bool EnumWindowsProc(nint window, nint parameter);+ [DllImport("user32.dll")] private static extern nint SetWinEventHook(uint min, uint max, nint module, WinEventProc callback, uint process, uint thread, uint flags);+ [DllImport("user32.dll")] private static extern bool UnhookWinEvent(nint hook);+ [DllImport("user32.dll")] private static extern bool EnumWindows(EnumWindowsProc callback, nint parameter);+ [DllImport("user32.dll")] private static extern int GetMessage(out NativeMessage message, nint window, uint min, uint max);+ [DllImport("user32.dll")] private static extern bool TranslateMessage(ref NativeMessage message);+ [DllImport("user32.dll")] private static extern nint DispatchMessage(ref NativeMessage message);+ [DllImport("user32.dll")] private static extern bool PostThreadMessage(uint thread, uint message, nint wParam, nint lParam);+ [DllImport("kernel32.dll")] private static extern uint GetCurrentThreadId();+ [DllImport("user32.dll")] private static extern nint GetAncestor(nint window, uint flags);+ [DllImport("user32.dll")] private static extern bool GetWindowRect(nint window, out NativeRect rect);+ [DllImport("user32.dll")] private static extern bool IsWindow(nint window);+ [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(nint window, out uint process);+ [DllImport("user32.dll")] private static extern bool SetWindowPos(nint window, nint after, int x, int y, int width, int height, uint flags);+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetWindowText(nint window, StringBuilder text, int capacity);+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetClassName(nint window, StringBuilder text, int capacity);+}diff --git a/Services/SettingsBackdrop.cs b/Services/SettingsBackdrop.csnew file mode 100644index 0000000..ed0cab8--- /dev/null+++ b/Services/SettingsBackdrop.cs@@ -0,0 +1,48 @@+using System.Diagnostics;+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Interop;+using System.Windows.Media;+using QiDock.Models;++namespace QiDock.Services;++internal static class SettingsBackdrop+{+ public static bool TryEnable(Window window, AppTheme theme)+ {+ var handle = new WindowInteropHelper(window).Handle;+ if (handle == 0 || !OperatingSystem.IsWindowsVersionAtLeast(10, 0, 22621) || SystemParameters.HighContrast)+ return false;+ var dark = theme == AppTheme.Dark ? 1 : 0;+ var backdrop = 3; // DWMSBT_TRANSIENTWINDOW: Desktop Acrylic on supported Windows 11 builds.+ var corners = 2;+ var darkResult = DwmSetWindowAttribute(handle, 20, ref dark, sizeof(int));+ var backdropResult = DwmSetWindowAttribute(handle, 38, ref backdrop, sizeof(int));+ var margins = new Margins(-1);+ var frameResult = DwmExtendFrameIntoClientArea(handle, ref margins);+ if (darkResult < 0 || backdropResult < 0 || frameResult < 0)+ {+ Trace.TraceWarning("Settings backdrop unavailable: theme=0x{0:X8}, backdrop=0x{1:X8}, frame=0x{2:X8}", darkResult, backdropResult, frameResult);+ return false;+ }+ var cornerResult = DwmSetWindowAttribute(handle, 33, ref corners, sizeof(int));+ if (cornerResult < 0) Trace.TraceWarning("Settings window corners unavailable: 0x{0:X8}", cornerResult);+ if (HwndSource.FromHwnd(handle)?.CompositionTarget is { } target) target.BackgroundColor = Colors.Transparent;+ return true;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct Margins(int value)+ {+ public int Left = value;+ public int Right = value;+ public int Top = value;+ public int Bottom = value;+ }++ [DllImport("dwmapi.dll")]+ private static extern int DwmSetWindowAttribute(nint window, uint attribute, ref int value, uint size);+ [DllImport("dwmapi.dll")]+ private static extern int DwmExtendFrameIntoClientArea(nint window, ref Margins margins);+}diff --git a/Services/ShellComObject.cs b/Services/ShellComObject.csnew file mode 100644index 0000000..2dc97c3--- /dev/null+++ b/Services/ShellComObject.cs@@ -0,0 +1,39 @@+using System.Runtime.InteropServices;++namespace QiDock.Services;++// Native objects stay on the Shell worker's STA; only immutable menu data crosses threads.+internal sealed class ShellComObject(nint handle) : IDisposable+{+ public nint Handle { get; private set; } = handle;++ public static ShellComObject Create(Guid classId, Guid interfaceId)+ {+ Marshal.ThrowExceptionForHR(CoCreateInstance(ref classId, 0, 1, ref interfaceId, out var pointer));+ return new ShellComObject(pointer);+ }++ public ShellComObject? Query(Guid interfaceId)+ {+ var result = Marshal.QueryInterface(Handle, in interfaceId, out var pointer);+ if (result == unchecked((int)0x80004002)) return null;+ Marshal.ThrowExceptionForHR(result);+ return new ShellComObject(pointer);+ }++ public T Method<T>(int slot) where T : Delegate+ {+ ObjectDisposedException.ThrowIf(Handle == 0, this);+ return Marshal.GetDelegateForFunctionPointer<T>(Marshal.ReadIntPtr(Marshal.ReadIntPtr(Handle), slot * IntPtr.Size));+ }++ public void Dispose()+ {+ if (Handle == 0) return;+ Marshal.Release(Handle);+ Handle = 0;+ }++ [DllImport("ole32.dll")]+ private static extern int CoCreateInstance(ref Guid classId, nint outer, uint context, ref Guid interfaceId, out nint pointer);+}diff --git a/Services/StartupRegistration.cs b/Services/StartupRegistration.csnew file mode 100644index 0000000..02c152d--- /dev/null+++ b/Services/StartupRegistration.cs@@ -0,0 +1,161 @@+using System.Diagnostics;+using System.IO;+using System.Security;+using System.Security.Principal;+using Microsoft.Win32;++namespace QiDock.Services;++/// <summary>+/// Starting with Windows. A logon task in the Task Scheduler starts the dock the moment the user signs in; the+/// registry's Run list, used before, is started by Windows only after a delay (half a minute was measured), so the+/// screen stayed without a taskbar meanwhile. The Run entry is kept only as a fallback when no task can be made.+/// </summary>+public sealed class StartupRegistration+{+ private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";+ private const string ValueName = "QiDock";+ private const string TaskName = "QiDock";++ public (bool Enabled, string? Error) Read()+ {+ if (TaskExists()) return (true, null);+ try+ {+ using var key = Registry.CurrentUser.OpenSubKey(RunKey);+ return (key?.GetValue(ValueName) is string { Length: > 0 }, null);+ }+ catch (Exception ex) when (ex is UnauthorizedAccessException or SecurityException or IOException)+ {+ return (false, UiText.Get("StartupReadError"));+ }+ }++ public string? SetEnabled(bool enabled)+ {+ var executable = Environment.ProcessPath;+ if (enabled && (string.IsNullOrWhiteSpace(executable) || !File.Exists(executable)+ || !string.Equals(Path.GetFileName(executable), "QiDock.exe", StringComparison.OrdinalIgnoreCase)+ || executable.Length + 2 > 260)) return UiText.Get("StartupPathError");+ try+ {+ if (enabled)+ {+ if (CreateTask(executable!))+ {+ SetRunValue(null);+ return null;+ }+ SetRunValue(executable); // no task could be made: the slower Run list still starts the dock+ return null;+ }+ SetRunValue(null);+ return DeleteTask() ? null : UiText.Get("StartupWriteError");+ }+ catch (Exception ex) when (ex is UnauthorizedAccessException or SecurityException or IOException)+ {+ return UiText.Get("StartupWriteError");+ }+ }++ /// <summary>+ /// Once, at start: a dock that still starts from the Run list moves to the quick logon task (and follows the+ /// program file if it was moved).+ /// </summary>+ public void UpgradeToTask()+ {+ try+ {+ string? runValue;+ using (var key = Registry.CurrentUser.OpenSubKey(RunKey)) runValue = key?.GetValue(ValueName) as string;+ if (string.IsNullOrWhiteSpace(runValue) || TaskExists()) return;+ var executable = Environment.ProcessPath;+ if (string.IsNullOrWhiteSpace(executable) || !File.Exists(executable)+ || !string.Equals(Path.GetFileName(executable), "QiDock.exe", StringComparison.OrdinalIgnoreCase)) return;+ // Only the copy Windows was starting moves to the task; a test build run once must not take its place.+ if (!string.Equals(Path.GetFullPath(runValue.Trim().Trim('"')), Path.GetFullPath(executable), StringComparison.OrdinalIgnoreCase)) return;+ if (CreateTask(executable))+ {+ SetRunValue(null);+ AppLog.Write("Windows ile başlatma oturum açılış görevine taşındı (beklemeden başlar)");+ }+ }+ catch (Exception ex) when (ex is UnauthorizedAccessException or SecurityException or IOException or InvalidOperationException)+ {+ AppLog.Write($"Başlangıç görevi oluşturulamadı: {ex.Message}");+ }+ }++ private static void SetRunValue(string? executable)+ {+ using var key = Registry.CurrentUser.CreateSubKey(RunKey, writable: true);+ if (executable is null) key.DeleteValue(ValueName, throwOnMissingValue: false);+ else key.SetValue(ValueName, $"\"{executable}\"", RegistryValueKind.String);+ }++ private static bool TaskExists() => Schtasks($"/Query /TN \"{TaskName}\"") == 0;++ private static bool DeleteTask() => !TaskExists() || Schtasks($"/Delete /TN \"{TaskName}\" /F") == 0;++ /// <summary>+ /// The logon task: only this user's sign-in, no delay, normal priority (tasks run below normal unless told),+ /// also on battery, never stopped after a time limit, a single copy.+ /// </summary>+ private static bool CreateTask(string executable)+ {+ var user = WindowsIdentity.GetCurrent().Name;+ var folder = Path.GetDirectoryName(executable) ?? "";+ static string Xml(string text) => SecurityElement.Escape(text) ?? "";+ var definition = $"""+ <?xml version="1.0" encoding="UTF-16"?>+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">+ <RegistrationInfo><Description>QiDock: oturum açılınca dock'u hemen başlatır.</Description></RegistrationInfo>+ <Triggers><LogonTrigger><Enabled>true</Enabled><UserId>{Xml(user)}</UserId></LogonTrigger></Triggers>+ <Principals><Principal id="Author"><UserId>{Xml(user)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>+ <Settings>+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>+ <AllowHardTerminate>false</AllowHardTerminate>+ <StartWhenAvailable>false</StartWhenAvailable>+ <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>+ <IdleSettings><StopOnIdleEnd>false</StopOnIdleEnd><RestartOnIdle>false</RestartOnIdle></IdleSettings>+ <AllowStartOnDemand>true</AllowStartOnDemand>+ <Enabled>true</Enabled>+ <Hidden>false</Hidden>+ <RunOnlyIfIdle>false</RunOnlyIfIdle>+ <WakeToRun>false</WakeToRun>+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>+ <Priority>4</Priority>+ </Settings>+ <Actions Context="Author"><Exec><Command>{Xml(executable)}</Command><WorkingDirectory>{Xml(folder)}</WorkingDirectory></Exec></Actions>+ </Task>+ """;+ var file = Path.Combine(Path.GetTempPath(), "qidock-task.xml");+ File.WriteAllText(file, definition, System.Text.Encoding.Unicode);+ try { return Schtasks($"/Create /TN \"{TaskName}\" /XML \"{file}\" /F") == 0; }+ finally { File.Delete(file); }+ }++ private static int Schtasks(string arguments)+ {+ try+ {+ using var process = Process.Start(new ProcessStartInfo("schtasks.exe", arguments)+ {+ CreateNoWindow = true,+ UseShellExecute = false,+ RedirectStandardOutput = true,+ RedirectStandardError = true+ });+ if (process is null) return -1;+ process.StandardOutput.ReadToEnd();+ process.StandardError.ReadToEnd();+ return process.WaitForExit(10000) ? process.ExitCode : -1;+ }+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)+ {+ return -1;+ }+ }+}diff --git a/Services/TaskbarReplacementSession.cs b/Services/TaskbarReplacementSession.csnew file mode 100644index 0000000..1660806--- /dev/null+++ b/Services/TaskbarReplacementSession.cs@@ -0,0 +1,696 @@+using System.Globalization;+using System.Diagnostics;+using System.IO;+using System.Runtime.InteropServices;+using System.Text;+using System.Windows;++namespace QiDock.Services;++public sealed class TaskbarReplacementSession : IDisposable+{+ private const uint AbmNew = 0x00000000;+ private const uint AbmRemove = 0x00000001;+ private const uint AbmGetState = 0x00000004;+ private const uint AbmSetState = 0x0000000A;+ private const uint AbmQueryPos = 0x00000002;+ private const uint AbmSetPos = 0x00000003;+ private const uint AbeLeft = 0;+ private const uint AbeTop = 1;+ private const uint AbeRight = 2;+ private const uint AbeBottom = 3;+ private const uint AbsAutoHide = 0x00000001;+ private const uint AbsAlwaysOnTop = 0x00000002;+ private const uint SupportedTaskbarState = AbsAutoHide | AbsAlwaysOnTop;+ private const uint AbnStateChange = 0;+ private const uint AbnPosChanged = 1;+ private const uint AbnFullScreenApp = 2;+ private const uint WmDisplayChange = 0x007E;+ private const uint WmDpiChanged = 0x02E0;+ private const uint CallbackMessage = 0x8000 + 0x52;+ private const uint MonitorDefaultToNearest = 2;+ private const uint SwpNoActivate = 0x0010;+ private const uint SwpNoOwnerZOrder = 0x0200;+ private const int SwHide = 0;+ private const int SwShowNoActivate = 4;+ private static readonly nint HwndTopmost = new(-1);++ private readonly Window _window;+ private readonly nint _handle;+ private bool _registered;+ private bool _active;+ private bool _stateChangeStarted;+ private uint _previousTaskbarState;+ private bool _disposed;+ private bool _fullScreenSuppressed;+ private double _nativeTaskbarHeight = 66;+ private const double DockHeadroomDips = 44;+ /// <summary>Height of the dock strip (bar + gap), taller than Windows' own 48 DIP taskbar.</summary>+ public const double DockHeightDips = 64;+ private Rect _reservedRect;+ private bool _hasReservation;+ private bool _autoHideEnabled;+ private Size _lastLayout;+ private int _stopInProgress;++ public TaskbarReplacementSession(Window window, nint handle)+ {+ _window = window;+ _handle = handle;+ AppDomain.CurrentDomain.ProcessExit += Process_Exit;+ }++ public bool IsActive => _active || _stateChangeStarted;++ /// <summary>The screen edge the dock stands on. Away from the bottom, Windows' hidden taskbar is set to hide itself+ /// so it reserves nothing, and the dock reserves its own strip on its edge.</summary>+ public Models.DockEdge Edge { get; set; } = Models.DockEdge.Bottom;++ /// <summary>Moves the dock to another edge while running.</summary>+ public void SetEdge(Models.DockEdge edge)+ {+ if (Edge == edge) return;+ Edge = edge;+ _lastLayout = default;+ if (!_active || Volatile.Read(ref _stopInProgress) != 0) return;+ SetTaskbarState(ReplacementState, _handle);+ PositionDockWindow();+ }++ /// <summary>Windows' own (hidden) taskbar hides itself while the dock hides, or while the dock is on another edge.</summary>+ private uint ReplacementState => (_previousTaskbarState & AbsAlwaysOnTop) | (_autoHideEnabled || Edge != Models.DockEdge.Bottom ? AbsAutoHide : 0);++ public event Action<string>? OperationFailed;+ public event Action<Size>? LayoutChanged;+ public event Action<bool>? FullScreenChanged;++ public void UpdateForeground(nint windowHandle)+ {+ if (!_active || Volatile.Read(ref _stopInProgress) != 0) return;+ GetWindowThreadProcessId(windowHandle, out var processId);+ if (processId == Environment.ProcessId) return;+ SetFullScreenSuppression(IsFullScreen(windowHandle));+ }++ private static bool HasPendingRecovery(out string? error)+ {+ error = null;+ if (!File.Exists(JournalPath))+ {+ return false;+ }++ try+ {+ _ = ReadJournal();+ return true;+ }+ catch (InvalidDataException)+ {+ error = "Görev çubuğu kurtarma kaydı bozuk. Windows ayarlarını elle denetleyin.";+ }+ catch (IOException)+ {+ error = "Görev çubuğu kurtarma kaydı okunamadı.";+ }+ catch (UnauthorizedAccessException)+ {+ error = "Görev çubuğu kurtarma kaydına erişim izni yok.";+ }++ return false;+ }++ public void Start()+ {+ ObjectDisposedException.ThrowIf(_disposed, this);+ if (_active)+ {+ return;+ }++ var pending = HasPendingRecovery(out var recoveryError);+ if (recoveryError is not null)+ {+ throw new InvalidOperationException(recoveryError);+ }++ _previousTaskbarState = pending ? ReadJournal() : GetTaskbarState();+ var nativeTaskbar = TrayHost.FindExplorerTaskbar();+ if (nativeTaskbar != 0 && GetWindowRect(nativeTaskbar, out var taskbarRect))+ {+ var nativeDpi = GetDpiForWindow(nativeTaskbar);+ if (nativeDpi > 0 && taskbarRect.Bottom > taskbarRect.Top+ && taskbarRect.Right - taskbarRect.Left > taskbarRect.Bottom - taskbarRect.Top)+ _nativeTaskbarHeight = (taskbarRect.Bottom - taskbarRect.Top) * 96d / nativeDpi;+ }+ try+ {+ if (!pending)+ {+ WriteJournal(_previousTaskbarState);+ }+ }+ catch (IOException ex)+ {+ throw new InvalidOperationException("Görev çubuğu ayarı değiştirilmedi; kurtarma kaydı yazılamadı.", ex);+ }+ catch (UnauthorizedAccessException ex)+ {+ throw new InvalidOperationException("Görev çubuğu ayarı değiştirilmedi; kurtarma kaydına yazma izni yok.", ex);+ }++ try+ {+ _stateChangeStarted = true;+ var replacementState = ReplacementState;+ if (!SetTaskbarState(replacementState, _handle))+ {+ throw new InvalidOperationException("Windows görev çubuğunun kenar tetiklemesi kapatılamadı.");+ }++ if (!HideNativeTaskbar())+ {+ throw new InvalidOperationException("Windows görev çubuğu gizlenemedi.");+ }++ var data = CreateData();+ data.uCallbackMessage = CallbackMessage;+ if (SHAppBarMessage(AbmNew, ref data) == 0)+ {+ throw new InvalidOperationException("QiDock Windows'a AppBar olarak kaydedilemedi.");+ }++ _registered = true;+ _active = true;+ PositionDockWindow();+ }+ catch+ {+ Stop();+ throw;+ }+ }++ public void HandleTaskbarCreated()+ {+ if (!_active)+ {+ return;+ }++ _registered = false;+ _hasReservation = false;+ var nativeTaskbar = TrayHost.FindExplorerTaskbar();+ if (nativeTaskbar != 0 && GetWindowRect(nativeTaskbar, out var taskbarRect))+ {+ var nativeDpi = GetDpiForWindow(nativeTaskbar);+ if (nativeDpi > 0 && taskbarRect.Bottom > taskbarRect.Top+ && taskbarRect.Right - taskbarRect.Left > taskbarRect.Bottom - taskbarRect.Top)+ {+ _nativeTaskbarHeight = (taskbarRect.Bottom - taskbarRect.Top) * 96d / nativeDpi;+ }+ }++ var replacementState = ReplacementState;+ SetTaskbarState(replacementState, _handle);+ HideNativeTaskbar();++ var data = CreateData();+ data.uCallbackMessage = CallbackMessage;+ if (SHAppBarMessage(AbmNew, ref data) != 0)+ {+ _registered = true;+ }++ PositionDockWindow();+ }++ public bool HandleMessage(uint message, nint wParam, nint lParam)+ {+ if (!_active || Volatile.Read(ref _stopInProgress) != 0)+ {+ return false;+ }++ if (message == CallbackMessage)+ {+ switch (unchecked((uint)wParam.ToInt64()))+ {+ case AbnPosChanged:+ EnforceNativeTaskbarHidden();+ PositionDockWindow();+ return true;+ case AbnFullScreenApp:+ if (lParam != 0)+ {+ UpdateForeground(GetForegroundWindow());+ }+ else+ {+ SetFullScreenSuppression(false);+ PositionDockWindow();+ }+ return true;+ case AbnStateChange:+ EnforceNativeTaskbarHidden();+ return true;+ }+ }++ if (message is WmDisplayChange or WmDpiChanged)+ {+ PositionDockWindow();+ }++ return false;+ }++ public string? Stop()+ {+ if (Interlocked.CompareExchange(ref _stopInProgress, 1, 0) != 0)+ {+ return "Windows görev çubuğu geri yükleme işlemi devam ediyor.";+ }++ try+ {+ if (!_active && !_registered && !_stateChangeStarted) return null;++ // Stop enforcing hidden state before Shell calls can reenter our AppBar callback.+ _active = false;+ if (_registered)+ {+ var data = CreateData();+ SHAppBarMessage(AbmRemove, ref data);+ _registered = false;+ _hasReservation = false;+ }++ var stateRestored = SetTaskbarState(_previousTaskbarState, _handle);+ var taskbarShown = ShowNativeTaskbar();+ if (!stateRestored || !taskbarShown)+ return "Windows görev çubuğu geri yüklenemedi. Kapatmayı yeniden deneyin veya Windows görev çubuğu ayarlarını denetleyin.";++ _stateChangeStarted = false;+ return DeleteJournal();+ }+ finally+ {+ Volatile.Write(ref _stopInProgress, 0);+ }+ }++ public void RefreshPosition()+ {+ PositionDockWindow();+ }++ public void UpdateAutoHide(bool autoHide)+ {+ _autoHideEnabled = autoHide;+ if (!_active || Volatile.Read(ref _stopInProgress) != 0) return;+ SetTaskbarState(ReplacementState, _handle);+ PositionDockWindow();+ }++ private void PositionDockWindow()+ {+ if ((!_active && !_registered) || Volatile.Read(ref _stopInProgress) != 0)+ {+ return;+ }++ var monitor = MonitorFromWindow(_handle, MonitorDefaultToNearest);+ var monitorInfo = new MonitorInfo { cbSize = (uint)Marshal.SizeOf<MonitorInfo>() };+ if (!GetMonitorInfo(monitor, ref monitorInfo))+ {+ throw new InvalidOperationException("Ekran boyutları alınamadı.");+ }++ var dpi = GetDpiForWindow(_handle);+ if (dpi == 0) return;+ if (UpdateReservation(monitorInfo.rcMonitor, dpi))+ {+ GetMonitorInfo(monitor, ref monitorInfo);+ }+ var mon = monitorInfo.rcMonitor;+ var work = monitorInfo.rcWork;+ // Thickness of the strip the dock stands in, then the headroom where magnified tiles grow into.+ var reserved = Edge switch+ {+ Models.DockEdge.Top => work.Top - mon.Top,+ Models.DockEdge.Left => work.Left - mon.Left,+ Models.DockEdge.Right => mon.Right - work.Right,+ _ => mon.Bottom - work.Bottom+ };+ var preferredPixels = (int)Math.Round((Edge == Models.DockEdge.Bottom ? Math.Max(_nativeTaskbarHeight, DockHeightDips) : DockHeightDips) * dpi / 96d);+ var thickness = reserved > 0 ? Math.Max(reserved, preferredPixels) : Math.Max(1, preferredPixels);+ var headroom = (int)Math.Round(DockHeadroomDips * dpi / 96d);+ var total = thickness + headroom;+ var vertical = Edge is Models.DockEdge.Left or Models.DockEdge.Right;+ var alongPixels = vertical ? mon.Bottom - mon.Top : mon.Right - mon.Left;+ // Along the dock and across it (DIPs), as the dock lays itself out.+ var layout = new Size(alongPixels * 96d / dpi, thickness * 96d / dpi);+ var totalDips = total * 96d / dpi;+ if (_lastLayout != layout)+ {+ _lastLayout = layout;+ _window.Width = vertical ? totalDips : layout.Width;+ _window.Height = vertical ? layout.Width : totalDips;+ LayoutChanged?.Invoke(layout);+ }+ UpdateForeground(GetForegroundWindow());+ // Explorer already reserves the hidden native taskbar's area; another appbar position would reserve a second strip.+ var (left, top, width, height) = Edge switch+ {+ Models.DockEdge.Top => (mon.Left, mon.Top, mon.Right - mon.Left, total),+ Models.DockEdge.Left => (mon.Left, mon.Top, total, mon.Bottom - mon.Top),+ Models.DockEdge.Right => (mon.Right - total, mon.Top, total, mon.Bottom - mon.Top),+ _ => (mon.Left, mon.Bottom - total, mon.Right - mon.Left, total)+ };+ if (!SetWindowPos(_handle, _fullScreenSuppressed ? new nint(1) : HwndTopmost, left, top,+ width, height,+ SwpNoActivate | SwpNoOwnerZOrder))+ {+ throw new InvalidOperationException("QiDock ekranın kenarına yerleştirilemedi.");+ }+ }++ private bool IsFullScreen(nint windowHandle)+ {+ if (windowHandle == 0 || !IsWindowVisible(windowHandle) || IsIconic(windowHandle)+ || MonitorFromWindow(windowHandle, MonitorDefaultToNearest) != MonitorFromWindow(_handle, MonitorDefaultToNearest))+ return false;+ var className = new StringBuilder(128);+ GetClassName(windowHandle, className, className.Capacity);+ if (className.ToString() is "Progman" or "WorkerW" or "Shell_TrayWnd") return false;+ // A maximized window fills the whole monitor once auto-hide frees the work area; that is an+ // ordinary window, not a full-screen game or video, so the dock must stay available.+ if (IsZoomed(windowHandle)) return false;+ var monitor = new MonitorInfo { cbSize = (uint)Marshal.SizeOf<MonitorInfo>() };+ return GetMonitorInfo(MonitorFromWindow(windowHandle, MonitorDefaultToNearest), ref monitor)+ && GetWindowRect(windowHandle, out var rect)+ && rect.Left <= monitor.rcMonitor.Left && rect.Top <= monitor.rcMonitor.Top+ && rect.Right >= monitor.rcMonitor.Right && rect.Bottom >= monitor.rcMonitor.Bottom;+ }++ private void SetFullScreenSuppression(bool suppressed)+ {+ if (_fullScreenSuppressed == suppressed) return;+ _fullScreenSuppressed = suppressed;+ ShowWindow(_handle, suppressed ? SwHide : SwShowNoActivate);+ FullScreenChanged?.Invoke(suppressed);+ }++ private static uint GetTaskbarState()+ {+ var data = new AppBarData { cbSize = (uint)Marshal.SizeOf<AppBarData>() };+ return unchecked((uint)SHAppBarMessage(AbmGetState, ref data));+ }++ private static bool HideNativeTaskbar()+ {+ var taskbarHandle = TrayHost.FindExplorerTaskbar();+ if (taskbarHandle == 0)+ {+ return false;+ }++ if (IsWindowVisible(taskbarHandle))+ {+ ShowWindow(taskbarHandle, SwHide);+ }++ return !IsWindowVisible(taskbarHandle);+ }++ /// <summary>+ /// Called while the process dies of a fatal error: Windows' taskbar is shown again, in the state saved in the+ /// recovery journal when there is one, so the user is not left without a taskbar until the dock starts again.+ /// </summary>+ public static void RestoreAfterCrash()+ {+ try+ {+ if (File.Exists(JournalPath) && SetTaskbarState(ReadJournal(), 0)) DeleteJournal();+ ShowNativeTaskbar();+ }+ catch (Exception)+ {+ // Nothing more can be done in a dying process; the journal brings the taskbar back at the next start.+ }+ }++ private static bool ShowNativeTaskbar()+ {+ var taskbarHandle = TrayHost.FindExplorerTaskbar();+ if (taskbarHandle == 0)+ {+ return false;+ }++ ShowWindow(taskbarHandle, SwShowNoActivate);+ return IsWindowVisible(taskbarHandle);+ }++ private void EnforceNativeTaskbarHidden()+ {+ if (!_active || Volatile.Read(ref _stopInProgress) != 0) return;+ // In auto-hide mode Explorer's (hidden) taskbar must be auto-hide too, otherwise it keeps+ // reserving its strip and maximized windows stop short of the screen bottom.+ var replacementState = ReplacementState;+ if (!SetTaskbarState(replacementState, _handle))+ {+ OperationFailed?.Invoke("Windows görev çubuğunun otomatik açılması yeniden etkinleşti.");+ return;+ }++ if (!HideNativeTaskbar())+ {+ OperationFailed?.Invoke("Windows görev çubuğu yeniden gizlenemedi.");+ }+ }++ private static bool SetTaskbarState(uint state, nint windowHandle)+ {+ var data = new AppBarData+ {+ cbSize = (uint)Marshal.SizeOf<AppBarData>(),+ hWnd = windowHandle,+ lParam = unchecked((nint)state)+ };+ SHAppBarMessage(AbmSetState, ref data);+ return (GetTaskbarState() & SupportedTaskbarState) == (state & SupportedTaskbarState);+ }++ /// <summary>+ /// Explorer keeps reserving the hidden taskbar's strip; the dock is taller, so reserve the+ /// difference as our own appbar right above it. Maximized windows then end above the dock.+ /// Returns true when the reservation changed (the work area moved).+ /// </summary>+ private bool UpdateReservation(Rect monitor, uint dpi)+ {+ var dockPixels = (int)Math.Round(DockHeightDips * dpi / 96d);+ // On the bottom edge Explorer's hidden taskbar still reserves its own strip; elsewhere it reserves nothing.+ var extra = _autoHideEnabled ? 0+ : Edge == Models.DockEdge.Bottom ? dockPixels - (int)Math.Round(_nativeTaskbarHeight * dpi / 96d)+ : dockPixels;+ var data = CreateData();+ data.uEdge = Edge switch+ {+ Models.DockEdge.Top => AbeTop,+ Models.DockEdge.Left => AbeLeft,+ Models.DockEdge.Right => AbeRight,+ _ => AbeBottom+ };+ if (extra <= 0)+ {+ if (!_hasReservation) return false;+ data.rc = new Rect(monitor.Left, monitor.Bottom, monitor.Right, monitor.Bottom);+ SHAppBarMessage(AbmSetPos, ref data);+ _hasReservation = false;+ return true;+ }++ data.rc = Edge switch+ {+ Models.DockEdge.Top => new Rect(monitor.Left, monitor.Top, monitor.Right, monitor.Top + extra),+ Models.DockEdge.Left => new Rect(monitor.Left, monitor.Top, monitor.Left + extra, monitor.Bottom),+ Models.DockEdge.Right => new Rect(monitor.Right - extra, monitor.Top, monitor.Right, monitor.Bottom),+ _ => new Rect(monitor.Left, monitor.Bottom - extra, monitor.Right, monitor.Bottom)+ };+ SHAppBarMessage(AbmQueryPos, ref data);+ switch (Edge)+ {+ case Models.DockEdge.Top: data.rc.Bottom = data.rc.Top + extra; break;+ case Models.DockEdge.Left: data.rc.Right = data.rc.Left + extra; break;+ case Models.DockEdge.Right: data.rc.Left = data.rc.Right - extra; break;+ default: data.rc.Top = data.rc.Bottom - extra; break;+ }+ if (_hasReservation && _reservedRect.Left == data.rc.Left && _reservedRect.Top == data.rc.Top+ && _reservedRect.Right == data.rc.Right && _reservedRect.Bottom == data.rc.Bottom)+ return false;+ SHAppBarMessage(AbmSetPos, ref data);+ _reservedRect = data.rc;+ _hasReservation = true;+ return true;+ }++ private AppBarData CreateData() => new()+ {+ cbSize = (uint)Marshal.SizeOf<AppBarData>(),+ hWnd = _handle+ };++ private static string JournalPath => Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),+ "QiDock",+ "taskbar-state.txt");++ private static void WriteJournal(uint state)+ {+ var path = JournalPath;+ var directory = Path.GetDirectoryName(path);+ if (directory is null)+ {+ throw new IOException("Görev çubuğu kurtarma kaydı için yol oluşturulamadı.");+ }++ Directory.CreateDirectory(directory);+ var temporaryPath = path + ".tmp";+ File.WriteAllText(temporaryPath, state.ToString(CultureInfo.InvariantCulture));+ File.Move(temporaryPath, path, overwrite: true);+ }++ private static uint ReadJournal()+ {+ var text = File.ReadAllText(JournalPath).Trim();+ if (!uint.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var state)+ || (state & ~SupportedTaskbarState) != 0)+ {+ throw new InvalidDataException("Görev çubuğu kurtarma kaydı geçersiz.");+ }++ return state;+ }++ private static string? DeleteJournal()+ {+ try+ {+ if (File.Exists(JournalPath))+ {+ File.Delete(JournalPath);+ }++ return null;+ }+ catch (IOException)+ {+ return "Görev çubuğu ayarı geri yüklendi ancak kurtarma kaydı silinemedi.";+ }+ catch (UnauthorizedAccessException)+ {+ return "Görev çubuğu ayarı geri yüklendi ancak kurtarma kaydını silme izni yok.";+ }+ }++ public void Dispose()+ {+ if (_disposed)+ {+ return;+ }++ var error = Stop();+ if (error is not null) Trace.TraceError(error);+ if (IsActive) return;+ _disposed = true;+ AppDomain.CurrentDomain.ProcessExit -= Process_Exit;+ }++ private void Process_Exit(object? sender, EventArgs e)+ {+ var error = Stop();+ if (error is not null) Trace.TraceError(error);+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct AppBarData+ {+ public uint cbSize;+ public nint hWnd;+ public uint uCallbackMessage;+ public uint uEdge;+ public Rect rc;+ public nint lParam;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct Rect(int left, int top, int right, int bottom)+ {+ public int Left = left;+ public int Top = top;+ public int Right = right;+ public int Bottom = bottom;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct MonitorInfo+ {+ public uint cbSize;+ public Rect rcMonitor;+ public Rect rcWork;+ public uint dwFlags;+ }++ [DllImport("shell32.dll")]+ private static extern nuint SHAppBarMessage(uint message, ref AppBarData data);++ [DllImport("user32.dll")]+ private static extern nint MonitorFromWindow(nint windowHandle, uint flags);++ [DllImport("user32.dll", CharSet = CharSet.Unicode)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool GetMonitorInfo(nint monitor, ref MonitorInfo monitorInfo);++ [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "FindWindowW")]+ private static extern nint FindWindow(string? className, string? windowName);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool IsWindowVisible(nint windowHandle);++ [DllImport("user32.dll")]+ private static extern uint GetDpiForWindow(nint windowHandle);++ [DllImport("user32.dll")]+ private static extern nint GetForegroundWindow();++ [DllImport("user32.dll")]+ private static extern uint GetWindowThreadProcessId(nint windowHandle, out uint processId);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool IsIconic(nint windowHandle);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool GetWindowRect(nint windowHandle, out Rect rect);++ [DllImport("user32.dll", CharSet = CharSet.Unicode)]+ private static extern int GetClassName(nint windowHandle, StringBuilder name, int length);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool IsZoomed(nint windowHandle);++ [DllImport("user32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool SetWindowPos(nint windowHandle, nint insertAfter, int x, int y, int width, int height, uint flags);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool ShowWindow(nint windowHandle, int command);+}diff --git a/Services/ThemeManager.cs b/Services/ThemeManager.csnew file mode 100644index 0000000..2d3f423--- /dev/null+++ b/Services/ThemeManager.cs@@ -0,0 +1,75 @@+using System.Windows;+using System.Windows.Media;+using QiDock.Models;++namespace QiDock.Services;++public static class ThemeManager+{+ private static ResourceDictionary? _palette;+ private static ResourceDictionary? _style;+ private static string _styleId = ThemeStyles.Glass;+ private static readonly ResourceDictionary Materials = new();++ /// <summary>The style last applied ("glass", "black"…).</summary>+ public static string CurrentStyle => _styleId;++ /// <summary>+ /// Loads the dark or light palette, lays the chosen style over it (a style brings its own base: the light+ /// styles always sit on the light palette) and sets the materials' opacity.+ /// </summary>+ public static void Apply(AppTheme theme, double opacity = 0.9, string? style = null)+ {+ var look = ThemeStyles.Find(style ?? _styleId);+ if (look.Id != ThemeStyles.Glass) theme = look.Base;+ var source = $"/QiDock;component/Design/Palettes/{theme}.xaml";+ var dictionaries = Application.Current.Resources.MergedDictionaries;+ if (_palette?.Source?.OriginalString != source)+ {+ var next = new ResourceDictionary { Source = new Uri(source, UriKind.Relative) };+ if (_palette is not null) dictionaries.Remove(_palette);+ dictionaries.Add(next);+ _palette = next;+ }+ if (_style is not null && look.Id != _styleId) dictionaries.Remove(_style);+ if (look.Id != _styleId || (_style is null && look.Id != ThemeStyles.Glass))+ {+ _style = ThemeStyles.Overlay(look);+ _styleId = look.Id;+ }+ // Order: palette, then the style over it, then the opacity-adjusted materials on top.+ dictionaries.Remove(Materials);+ if (_style is not null)+ {+ dictionaries.Remove(_style);+ dictionaries.Add(_style);+ }+ dictionaries.Add(Materials);+ SetSurfaceOpacity(opacity);+ }++ public static void SetSurfaceOpacity(double opacity)+ {+ if (!double.IsFinite(opacity) || opacity is < 0.6 or > 1) throw new ArgumentOutOfRangeException(nameof(opacity));+ if (_palette is null) throw new InvalidOperationException("The theme must be initialized before its materials.");+ var alpha = (byte)Math.Round(opacity * 255);+ var settings = ((SolidColorBrush)_palette["SettingsBackground"]).Color;+ settings.A = alpha;+ var settingsBrush = new SolidColorBrush(settings);+ settingsBrush.Freeze();+ Materials["SettingsGlassMaterial"] = settingsBrush;+ foreach (var key in new[] { "DockMaterial", "MenuMaterial" })+ {+ var from = _style is not null && _style.Contains(key) ? _style[key] : _palette[key];+ var material = ((LinearGradientBrush)from).Clone();+ foreach (var stop in material.GradientStops)+ {+ var color = stop.Color;+ color.A = alpha;+ stop.Color = color;+ }+ material.Freeze();+ Materials[key] = material;+ }+ }+}diff --git a/Services/ThemeStyles.cs b/Services/ThemeStyles.csnew file mode 100644index 0000000..1eae30c--- /dev/null+++ b/Services/ThemeStyles.cs@@ -0,0 +1,106 @@+using System.Windows;+using System.Windows.Media;+using QiDock.Models;++namespace QiDock.Services;++/// <summary>+/// A look for the dock, the widgets and the panels ("Glass", "Black", "Lo-fi"…): a set of colours laid over the+/// dark or light palette. Glass is the palette itself; every other style replaces its materials and text colours.+/// </summary>+public sealed record ThemeStyle(+ string Id,+ string NameTr,+ string NameEn,+ AppTheme Base,+ string DockTop,+ string DockBottom,+ string Tile,+ string TileStroke,+ string Text,+ string TextSecondary,+ string Accent,+ string Popup,+ string Edge,+ string[] Swatch)+{+ public string Name => UiText.Current.Language == AppLanguage.English ? NameEn : NameTr;+}++public static class ThemeStyles+{+ public const string Glass = "glass";++ public static readonly IReadOnlyList<ThemeStyle> All =+ [+ new(Glass, "Cam", "Glass", AppTheme.Dark, "", "", "", "", "", "", "", "", "", ["#FF8EC5FF", "#FFFFB86B", "#FF7EE0A1"]),+ new("black", "Siyah", "Black", AppTheme.Dark, "#FF050505", "#FF000000", "#FF262628", "#14FFFFFF", "#FFF5F5F7", "#FF98989D", "#FF0A84FF", "#FF151517", "#26FFFFFF",+ ["#FF0A84FF", "#FFFF9F0A", "#FF30D158"]),+ new("lofi", "Lo-fi", "Lo-fi", AppTheme.Dark, "#FF33271F", "#FF261C16", "#FF46372D", "#26F6E1C6", "#FFF7E8D4", "#FFC6A98E", "#FFE8915B", "#FF2E231C", "#33F6E1C6",+ ["#FFC9A47E", "#FFE8915B", "#FF8C6A55"]),+ new("pixelnight", "Piksel Gece", "Pixel Night", AppTheme.Dark, "#FF1B1538", "#FF100C24", "#FF2A2154", "#407B6CFF", "#FFEFEAFF", "#FFA99DDA", "#FFFF5FA2", "#FF18122F", "#557B6CFF",+ ["#FF7B6CFF", "#FFFF5FA2", "#FF4DE1FF"]),+ new("christmas", "Yılbaşı", "Christmas", AppTheme.Dark, "#FF113321", "#FF0A2015", "#FF1D4630", "#40E8C26A", "#FFFFF8EC", "#FFBAD4C3", "#FFE0343F", "#FF0E2A1B", "#55E8C26A",+ ["#FFE0343F", "#FF2F9E5A", "#FFE8C26A"]),+ new("ocean", "Okyanus", "Ocean", AppTheme.Dark, "#FF0D2840", "#FF07192A", "#FF16395A", "#333FC1FF", "#FFE8F6FF", "#FF8FB9D6", "#FF3FC1FF", "#FF0B2135", "#443FC1FF",+ ["#FF3FC1FF", "#FF1B6CA8", "#FF7FE3D6"]),+ new("sunset", "Gün Batımı", "Sunset", AppTheme.Dark, "#FF331734", "#FF221024", "#FF4A2342", "#33FF8A5B", "#FFFFF1EA", "#FFDDAABB", "#FFFF8A5B", "#FF2A1329", "#44FF8A5B",+ ["#FFFF8A5B", "#FFFF5C8A", "#FFFFC857"]),+ new("forest", "Orman", "Forest", AppTheme.Dark, "#FF1A2A1E", "#FF111D14", "#FF27402E", "#338BD17C", "#FFEFF7EA", "#FFA9C2A2", "#FF8BD17C", "#FF16241A", "#448BD17C",+ ["#FF8BD17C", "#FF4E8C5A", "#FFD9C27A"]),+ new("graphite", "Grafit", "Graphite", AppTheme.Dark, "#FF2E3034", "#FF232528", "#FF3D4045", "#1FFFFFFF", "#FFF0F1F3", "#FFA4A8AF", "#FFB4BBC6", "#FF26282C", "#33FFFFFF",+ ["#FFB4BBC6", "#FF6E737B", "#FFE6E8EB"]),+ new("neon", "Neon", "Neon", AppTheme.Dark, "#FF0B0B12", "#FF050508", "#FF161620", "#6600F0FF", "#FFF4FEFF", "#FF8FB7C0", "#FF00F0FF", "#FF0C0C14", "#8800F0FF",+ ["#FF00F0FF", "#FFFF2BD6", "#FFB6FF3B"]),+ new("retro", "Retro", "Retro", AppTheme.Dark, "#FF2F2B22", "#FF221F18", "#FF433D30", "#33F2B33D", "#FFF6EBCB", "#FFC4B48E", "#FFF2B33D", "#FF29251D", "#44F2B33D",+ ["#FFF2B33D", "#FFD9603B", "#FF6BA292"]),+ new("mocha", "Moka", "Mocha", AppTheme.Dark, "#FF1E1A26", "#FF15121B", "#FF2D2738", "#26CBA6F7", "#FFE8E0F5", "#FFA89FBA", "#FFCBA6F7", "#FF1A1621", "#33CBA6F7",+ ["#FFCBA6F7", "#FFF5C2E7", "#FF89DCEB"]),+ new("paper", "Kâğıt", "Paper", AppTheme.Light, "#FFF6F3EC", "#FFEDE8DE", "#FFFFFFFF", "#22000000", "#FF23201B", "#FF777063", "#FF2F6FEB", "#FFFBF9F4", "#26000000",+ ["#FFEDE8DE", "#FF2F6FEB", "#FF23201B"]),+ new("sakura", "Sakura", "Sakura", AppTheme.Light, "#FFFBEAF0", "#FFF3D9E3", "#FFFFFFFF", "#26E85D8E", "#FF3A2430", "#FF8C6A78", "#FFE85D8E", "#FFFFF6F9", "#33E85D8E",+ ["#FFF3D9E3", "#FFE85D8E", "#FF9BC88B"])+ ];++ public static ThemeStyle Find(string? id) => All.FirstOrDefault(s => s.Id == id) ?? All[0];++ /// <summary>The overlay for <paramref name="style"/>, or null for Glass (the palette alone).</summary>+ public static ResourceDictionary? Overlay(ThemeStyle style)+ {+ if (style.Id == Glass) return null;+ var light = style.Base == AppTheme.Light;+ var d = new ResourceDictionary();+ static Color C(string hex) => (Color)ColorConverter.ConvertFromString(hex);+ static SolidColorBrush S(string hex) { var b = new SolidColorBrush(C(hex)); b.Freeze(); return b; }+ static LinearGradientBrush V(string top, string bottom) { var b = new LinearGradientBrush(C(top), C(bottom), 90); b.Freeze(); return b; }+ static string Alpha(string hex, byte a) => $"#{a:X2}{hex[3..]}";+ var overlay = light ? "#FF000000" : "#FFFFFFFF";++ d["DockMaterial"] = V(style.DockTop, style.DockBottom);+ d["DockBorderMaterial"] = V(style.Edge, Alpha(style.Edge, 0x10));+ d["MenuMaterial"] = V(style.Popup, style.Popup);+ d["WidgetPopupFill"] = V(style.Popup, style.Popup);+ d["SurfacePopup"] = S(style.Popup);+ d["MenuStroke"] = S(style.Edge);+ d["MenuDivider"] = S(Alpha(style.Text, 0x22));+ d["TextPrimary"] = S(style.Text);+ d["TextSecondary"] = S(style.TextSecondary);+ d["WidgetTileFill"] = S(style.Tile);+ d["WidgetTileStroke"] = S(style.TileStroke);+ d["WidgetHoverOverlay"] = S(Alpha(overlay, 0x16));+ d["WidgetPressedOverlay"] = S(Alpha(overlay, 0x26));+ d["WidgetTrack"] = S(Alpha(style.Text, 0x30));+ d["WidgetAccent"] = S(style.Accent);+ d["DockTileFill"] = S(Alpha(style.Tile, 0xCC));+ d["DockTileStroke"] = S(style.TileStroke);+ d["SurfaceHover"] = S(Alpha(overlay, 0x1E));+ d["SurfacePressed"] = S(Alpha(overlay, 0x30));+ d["IndicatorBrush"] = S(Alpha(style.Text, 0xB0));+ d["NotificationBrush"] = S(style.Accent);+ d["PanelFrostTint"] = C(Alpha(style.DockBottom, 0xD8));+ d["PanelTile"] = S(Alpha(style.Tile, 0xE6));+ d["PanelTileHover"] = S(style.Tile);+ d["PanelTileStroke"] = S(style.TileStroke);+ return d;+ }+}diff --git a/Services/TrayHost.cs b/Services/TrayHost.csnew file mode 100644index 0000000..c2d2573--- /dev/null+++ b/Services/TrayHost.cs@@ -0,0 +1,553 @@+using System.Diagnostics;+using System.IO;+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Interop;+using System.Windows.Media;+using System.Windows.Media.Imaging;+using System.Windows.Threading;++namespace QiDock.Services;++/// <summary>An icon an app keeps in the notification area (the apps running in the background).</summary>+public sealed class TrayIcon+{+ internal TrayIcon(nint window, uint id, Guid? guid)+ {+ Window = window;+ Id = id;+ Guid = guid;+ GetWindowThreadProcessId(window, out var pid);+ ProcessId = (int)pid;+ (Path, Name) = Describe(ProcessId);+ }++ public nint Window { get; }+ public uint Id { get; }+ public Guid? Guid { get; }+ public int ProcessId { get; }+ public string? Path { get; }++ /// <summary>The app's own name ("Claude"), from its program file; the tooltip when there is none.</summary>+ public string Name { get; }++ public string Tip { get; internal set; } = "";+ public ImageSource? Image { get; internal set; }+ internal nint Handle { get; set; }+ public uint CallbackMessage { get; internal set; }+ public uint Version { get; internal set; }+ public bool Hidden { get; internal set; }++ // Windows' own helpers have plain program names ("Windows Gezgini"); their tooltip says what they are.+ public string Title => Name.Length > 0 && (CanClose || Tip.Length == 0) ? Name : FirstLine(Tip);+ public string Detail => Tip.Length > 0 && !string.Equals(FirstLine(Tip), Title, StringComparison.CurrentCultureIgnoreCase) ? Tip.Replace("\r", "").Replace('\n', ' ') : "";++ /// <summary>Windows' own helpers (explorer and the like) are shown but not closed from the dock.</summary>+ public bool CanClose => ProcessId > 0 && ProcessId != Environment.ProcessId && Path is { } path+ && !path.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.Windows), StringComparison.OrdinalIgnoreCase);++ public bool IsAlive => IsWindow(Window);++ internal bool Matches(nint window, uint id, Guid? guid) => guid is { } g ? Guid == g : Guid is null && Window == window && Id == id;++ private static string FirstLine(string text) => text.Split('\n', 2)[0].Trim();++ private static (string? Path, string Name) Describe(int pid)+ {+ try+ {+ using var process = Process.GetProcessById(pid);+ var path = process.MainModule?.FileName;+ if (path is null) return (null, process.ProcessName);+ var info = FileVersionInfo.GetVersionInfo(path);+ var name = !string.IsNullOrWhiteSpace(info.FileDescription) ? info.FileDescription.Trim()+ : !string.IsNullOrWhiteSpace(info.ProductName) ? info.ProductName.Trim()+ : System.IO.Path.GetFileNameWithoutExtension(path);+ return (path, name);+ }+ catch+ {+ // A process running as administrator cannot be read from here.+ try+ {+ using var process = Process.GetProcessById(pid);+ return (null, process.ProcessName);+ }+ catch { return (null, ""); }+ }+ }++ [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(nint hWnd, out uint processId);+ [DllImport("user32.dll")] private static extern bool IsWindow(nint hWnd);+}++/// <summary>+/// Stands in for the notification area while the Windows taskbar is hidden. Apps put their icons in the area by+/// sending them to the first window named "Shell_TrayWnd"; this host opens a hidden window of that name in front of+/// Explorer's, keeps a copy of every icon and passes each message on to Explorer, so Explorer's own area stays exactly+/// as it was. When the host closes, apps simply talk to Explorer again.+/// </summary>+public sealed class TrayHost+{+ public static TrayHost Shared { get; } = new();++ private const int WmCopyData = 0x004A, WmUser = 0x0400;+ private const uint NimAdd = 0, NimModify = 1, NimDelete = 2, NimSetVersion = 4;+ private const uint NifMessage = 0x1, NifIcon = 0x2, NifTip = 0x4, NifState = 0x8, NifGuid = 0x20;+ private const uint NisHidden = 0x1;+ private const int Magic = 0x34753423;++ private readonly List<TrayIcon> _icons = [];+ private WndProc? _proc; // kept alive while the window lives+ private nint _tray, _notify;+ private uint _taskbarCreated;+ private DispatcherTimer? _keepInFront;++ /// <summary>The icon list changed (an app came, went or changed its picture).</summary>+ public event EventHandler? Changed;++ private DispatcherTimer? _notifyTimer;+ private bool _urgent;++ /// <summary>+ /// Tells the dock about a change, gathered: an app coming or going shows at once, a new picture or tooltip at+ /// most every two seconds (some apps swap their icon several times a second).+ /// </summary>+ private void Notify(bool urgent)+ {+ _urgent |= urgent;+ if (_notifyTimer is null)+ {+ _notifyTimer = new DispatcherTimer(DispatcherPriority.Background);+ _notifyTimer.Tick += (_, _) =>+ {+ _notifyTimer.Stop();+ _urgent = false;+ Changed?.Invoke(this, EventArgs.Empty);+ };+ }+ var wait = TimeSpan.FromMilliseconds(_urgent ? 150 : 2000);+ if (_notifyTimer.IsEnabled && _notifyTimer.Interval <= wait) return;+ _notifyTimer.Stop();+ _notifyTimer.Interval = wait;+ _notifyTimer.Start();+ }++ public bool IsRunning => _tray != 0;++ /// <summary>Visible icons of apps that are still running, in the order they came.</summary>+ public IReadOnlyList<TrayIcon> Icons+ {+ get+ {+ if (_icons.RemoveAll(icon => !icon.IsAlive) > 0) Changed?.Invoke(this, EventArgs.Empty);+ return _icons.Where(icon => !icon.Hidden && icon.ProcessId != Environment.ProcessId).ToList();+ }+ }++ /// <summary>Explorer's taskbar, never this host's stand-in window.</summary>+ public static nint FindExplorerTaskbar()+ {+ var own = Shared._tray;+ nint found = 0;+ while ((found = FindWindowEx(0, found, "Shell_TrayWnd", null)) != 0)+ {+ if (found != own) return found;+ }+ return 0;+ }++ public void Start()+ {+ if (_tray != 0) return;+ try+ {+ _taskbarCreated = RegisterWindowMessage("TaskbarCreated");+ _proc = Procedure;+ var instance = GetModuleHandle(null);+ var cls = new WndClassEx { cbSize = (uint)Marshal.SizeOf<WndClassEx>(), lpfnWndProc = _proc, hInstance = instance, lpszClassName = "Shell_TrayWnd" };+ RegisterClassEx(ref cls);+ var notify = new WndClassEx { cbSize = (uint)Marshal.SizeOf<WndClassEx>(), lpfnWndProc = _proc, hInstance = instance, lpszClassName = "TrayNotifyWnd" };+ RegisterClassEx(ref notify);+ const uint popup = 0x80000000, clipChildren = 0x02000000, clipSiblings = 0x04000000, child = 0x40000000;+ const uint topmost = 0x8, toolWindow = 0x80;+ _tray = CreateWindowEx(topmost | toolWindow, "Shell_TrayWnd", "", popup | clipChildren | clipSiblings, 0, 0, 0, 0, 0, 0, instance, 0);+ if (_tray == 0)+ {+ AppLog.Write($"Arka plan simgeleri alınamadı (pencere açılmadı, hata {Marshal.GetLastWin32Error()})");+ return;+ }+ _notify = CreateWindowEx(0, "TrayNotifyWnd", null, child | clipChildren | clipSiblings, 0, 0, 0, 0, _tray, 0, instance, 0);+ KeepInFront();+ _keepInFront = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(2) };+ _keepInFront.Tick += (_, _) => KeepInFront();+ _keepInFront.Start();+ AskAppsAgain();+ AppLog.Write("Arka plan simgeleri dock'a alındı");+ // Some apps (Electron ones such as Claude) lose their re-add while the dock is still busy starting, so+ // they are asked once more when things are calm; an app asked twice just puts its icon in again.+ var again = new DispatcherTimer(DispatcherPriority.ApplicationIdle) { Interval = TimeSpan.FromSeconds(6) };+ again.Tick += (_, _) =>+ {+ again.Stop();+ if (_tray == 0) return;+ AskAppsAgain();+ var report = new DispatcherTimer { Interval = TimeSpan.FromSeconds(3) };+ report.Tick += (_, _) =>+ {+ report.Stop();+ AppLog.Write($"Arka planda {Icons.Count} simge: {string.Join(", ", Icons.Select(i => i.Title))}");+ };+ report.Start();+ };+ again.Start();+ }+ catch (Exception ex)+ {+ AppLog.Write($"Arka plan simgeleri alınamadı: {ex.Message}");+ Stop();+ }+ }++ public void Stop()+ {+ _keepInFront?.Stop();+ _keepInFront = null;+ if (_tray != 0) DestroyWindow(_tray); // its child goes with it+ _tray = _notify = 0;+ _icons.Clear();+ Changed?.Invoke(this, EventArgs.Empty);+ }++ /// <summary>Explorer started again: stand in front of its new window and collect the icons once more.</summary>+ public void ExplorerRestarted()+ {+ if (_tray == 0) return;+ _icons.Clear();+ Changed?.Invoke(this, EventArgs.Empty);+ var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };+ timer.Tick += (_, _) =>+ {+ timer.Stop();+ KeepInFront();+ AskAppsAgain();+ };+ timer.Start();+ }++ /// <summary>+ /// Every app with an icon puts it in again when it hears that the taskbar was created. Explorer is left out:+ /// hearing it, Explorer brings its own taskbar window to the front again and the icons would go back to it.+ /// </summary>+ private void AskAppsAgain()+ {+ var explorer = FindExplorerTaskbar();+ if (explorer == 0) return; // Explorer is not up yet; its own TaskbarCreated will ask everyone+ GetWindowThreadProcessId(explorer, out var shell);+ var own = (uint)Environment.ProcessId;+ EnumWindows((window, _) =>+ {+ GetWindowThreadProcessId(window, out var owner);+ if (owner != shell && owner != own) SendNotifyMessage(window, _taskbarCreated, 0, 0);+ return true;+ }, 0);+ }++ /// <summary>Apps send their icons to the first "Shell_TrayWnd" in the window order, so this one stays first.</summary>+ private void KeepInFront()+ {+ if (_tray == 0) return;+ const uint noSize = 0x1, noMove = 0x2, noActivate = 0x10;+ var explorer = FindExplorerTaskbar();+ if (explorer != 0 && GetWindowRect(explorer, out var rect))+ SetWindowPos(_tray, -1, rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top, noActivate);+ else+ SetWindowPos(_tray, -1, 0, 0, 0, 0, noSize | noMove | noActivate);+ }++ private nint Procedure(nint hwnd, uint message, nint wParam, nint lParam)+ {+ if (hwnd == _tray && message == WmCopyData && lParam != 0)+ {+ var data = Marshal.PtrToStructure<CopyData>(lParam);+ if (data.dwData == 1 && data.lpData != 0 && data.cbData >= 8 + 32)+ {+ var handled = false;+ try { handled = Take(data.lpData, data.cbData); }+ catch (Exception ex) { AppLog.Write($"Arka plan simgesi okunamadı: {ex.Message}"); }+ Forward(message, wParam, lParam);+ return handled ? 1 : 0;+ }+ // Desk bars (dwData 0) and icon places (3) are answered by Explorer itself.+ return Forward(message, wParam, lParam);+ }+ if (hwnd == _tray && message >= WmUser && message < 0x8000) return Forward(message, wParam, lParam);+ // Taskbar commands ("show desktop" / Win+D, minimize all, undo minimize all, cascade...) are sent to the first+ // Shell_TrayWnd found, which is now this one; Explorer's own taskbar is the one that carries them out.+ if (hwnd == _tray && message == 0x0111 /* WM_COMMAND */)+ {+ var explorer = FindExplorerTaskbar();+ if (explorer != 0) PostMessage(explorer, message, wParam, lParam);+ return 0;+ }+ return DefWindowProc(hwnd, message, wParam, lParam);+ }++ private static nint Forward(uint message, nint wParam, nint lParam)+ {+ var explorer = FindExplorerTaskbar();+ if (explorer == 0) return 0;+ const uint abortIfHung = 0x2;+ return SendMessageTimeout(explorer, message, wParam, lParam, abortIfHung, 2000, out var result) != 0 ? result : 0;+ }++ /// <summary>+ /// Reads one icon message. The layout is the 32-bit one Windows uses between processes: a magic number, the+ /// command, then NOTIFYICONDATA with every handle cut to 32 bits.+ /// </summary>+ private bool Take(nint data, int size)+ {+ const int n = 8; // NOTIFYICONDATA starts here+ if (size < n + 24 || Marshal.ReadInt32(data, 0) != Magic) return false;+ var command = (uint)Marshal.ReadInt32(data, 4);+ var window = (nint)(uint)Marshal.ReadInt32(data, n + 4);+ var id = (uint)Marshal.ReadInt32(data, n + 8);+ var flags = (uint)Marshal.ReadInt32(data, n + 12);+ Guid? guid = null;+ if ((flags & NifGuid) != 0 && size >= n + 952)+ {+ var bytes = new byte[16];+ Marshal.Copy(data + n + 936, bytes, 0, 16);+ guid = new Guid(bytes);+ }+ var icon = _icons.FirstOrDefault(i => i.Matches(window, id, guid));++ switch (command)+ {+ case NimDelete:+ if (icon is null) return false;+ _icons.Remove(icon);+ Notify(urgent: true);+ return true;+ case NimSetVersion:+ if (icon is null || size < n + 804) return false;+ icon.Version = (uint)Marshal.ReadInt32(data, n + 800);+ return true;+ case NimAdd:+ case NimModify:+ var urgent = false;+ if (icon is null)+ {+ // A change to an icon added before this host opened counts as adding it, if it brings a picture.+ if (command == NimModify && (flags & NifIcon) == 0) return false;+ if (!IsWindow(window)) return false;+ icon = new TrayIcon(window, id, guid);+ _icons.Add(icon);+ urgent = true;+ }+ else if (command == NimAdd) return false;+ var changed = urgent;+ if ((flags & NifMessage) != 0) icon.CallbackMessage = (uint)Marshal.ReadInt32(data, n + 16);+ if ((flags & NifIcon) != 0 && size >= n + 24)+ {+ // Some apps send the same picture several times a second; only a new one is copied.+ var handle = (nint)(uint)Marshal.ReadInt32(data, n + 20);+ if (handle != icon.Handle || icon.Image is null)+ {+ icon.Handle = handle;+ icon.Image = Picture(handle) ?? icon.Image;+ changed = true;+ }+ }+ if ((flags & NifTip) != 0 && size >= n + 24 + 256)+ {+ var tip = (Marshal.PtrToStringUni(data + n + 24, 128) ?? "").Split('\0')[0];+ changed |= tip != icon.Tip;+ icon.Tip = tip;+ }+ if ((flags & NifState) != 0 && size >= n + 288)+ {+ var state = (uint)Marshal.ReadInt32(data, n + 280);+ var mask = (uint)Marshal.ReadInt32(data, n + 284);+ var hidden = (mask & NisHidden) != 0 ? (state & NisHidden) != 0 : icon.Hidden;+ if (hidden != icon.Hidden)+ {+ icon.Hidden = hidden;+ changed = urgent = true;+ }+ }+ if (changed) Notify(urgent);+ return true;+ default:+ return icon is not null;+ }+ }++ /// <summary>Copies the app's icon at once: the app may destroy its handle right after sending it.</summary>+ private static ImageSource? Picture(nint handle)+ {+ if (handle == 0) return null;+ var copy = CopyIcon(handle);+ if (copy == 0) return null;+ try+ {+ var image = Imaging.CreateBitmapSourceFromHIcon(copy, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());+ image.Freeze();+ return image;+ }+ catch { return null; }+ finally { DestroyIcon(copy); }+ }++ // ---- What a click on an icon tells its app ----++ private const uint WmContextMenu = 0x007B, WmLButtonDown = 0x0201, WmLButtonUp = 0x0202, WmLButtonDblClk = 0x0203;+ private const uint WmRButtonDown = 0x0204, WmRButtonUp = 0x0205, NinSelect = WmUser;++ /// <summary>A left click on the icon, as the taskbar would send it (most apps open their window).</summary>+ public static void Click(TrayIcon icon) => Send(icon, icon.Version >= 4 ? [WmLButtonDown, WmLButtonUp, NinSelect] : [WmLButtonDown, WmLButtonUp]);++ /// <summary>A double click (some older apps open only on this).</summary>+ public static void DoubleClick(TrayIcon icon) => Send(icon, [WmLButtonDblClk, WmLButtonUp]);++ /// <summary>A right click: the app opens its own menu (with its "Quit" item) at the pointer.</summary>+ public static void RightClick(TrayIcon icon) => Send(icon, icon.Version >= 4 ? [WmRButtonDown, WmRButtonUp, WmContextMenu] : [WmRButtonDown, WmRButtonUp]);++ private static void Send(TrayIcon icon, uint[] messages)+ {+ if (icon.CallbackMessage == 0 || !icon.IsAlive) return;+ // The app brings its window or menu to the front itself; it may, since the click came to us.+ AllowSetForegroundWindow(icon.ProcessId);+ GetCursorPos(out var point);+ foreach (var message in messages)+ {+ if (icon.Version >= 4)+ PostMessage(icon.Window, icon.CallbackMessage, (nint)((point.Y << 16) | (point.X & 0xFFFF)), (nint)(((int)icon.Id << 16) | (int)(message & 0xFFFF)));+ else+ PostMessage(icon.Window, icon.CallbackMessage, (nint)icon.Id, (nint)message);+ }+ }++ /// <summary>+ /// Asks the app to close: every window of the program is told to close. Returns false when it cannot be asked.+ /// Apps that only hide into the tray may keep running; <see cref="ForceClose"/> ends them.+ /// </summary>+ public static bool AskToClose(TrayIcon icon)+ {+ if (!icon.CanClose) return false;+ const uint wmClose = 0x0010;+ var pid = (uint)icon.ProcessId;+ EnumWindows((window, _) =>+ {+ GetWindowThreadProcessId(window, out var owner);+ if (owner == pid) PostMessage(window, wmClose, 0, 0);+ return true;+ }, 0);+ return true;+ }++ public static bool IsRunningProcess(int pid)+ {+ try+ {+ using var process = Process.GetProcessById(pid);+ return !process.HasExited;+ }+ catch { return false; }+ }++ /// <summary>+ /// Ends the program: its own process and the other processes of the same program file (helpers of apps such as+ /// Electron ones). Programs it started (a launcher's apps, say) are left alone. Returns an error message, or null.+ /// </summary>+ public static string? ForceClose(TrayIcon icon)+ {+ if (!icon.CanClose) return UiText.Get("TrayCannotClose");+ try+ {+ using var process = Process.GetProcessById(icon.ProcessId);+ var name = process.ProcessName;+ var path = icon.Path;+ process.Kill();+ if (!string.IsNullOrEmpty(path))+ {+ foreach (var other in Process.GetProcessesByName(name))+ {+ using (other)+ {+ try+ {+ if (other.Id != Environment.ProcessId && string.Equals(other.MainModule?.FileName, path, StringComparison.OrdinalIgnoreCase))+ other.Kill();+ }+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException or NotSupportedException) { }+ }+ }+ }+ return null;+ }+ catch (ArgumentException) { return null; } // already gone+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException or NotSupportedException)+ {+ AppLog.Write($"Arka plan uygulaması kapatılamadı ({icon.Name}): {ex.Message}");+ return UiText.Get("TrayCannotClose");+ }+ }++ // ---- Windows ----++ private delegate nint WndProc(nint hwnd, uint message, nint wParam, nint lParam);+ private delegate bool EnumWindowsProc(nint hwnd, nint lParam);++ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]+ private struct WndClassEx+ {+ public uint cbSize;+ public uint style;+ [MarshalAs(UnmanagedType.FunctionPtr)] public WndProc lpfnWndProc;+ public int cbClsExtra;+ public int cbWndExtra;+ public nint hInstance;+ public nint hIcon;+ public nint hCursor;+ public nint hbrBackground;+ public string? lpszMenuName;+ public string lpszClassName;+ public nint hIconSm;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct CopyData+ {+ public nint dwData;+ public int cbData;+ public nint lpData;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct NativeRect { public int Left, Top, Right, Bottom; }++ [StructLayout(LayoutKind.Sequential)]+ private struct NativePoint { public int X, Y; }++ [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern ushort RegisterClassEx(ref WndClassEx cls);+ [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]+ private static extern nint CreateWindowEx(uint exStyle, string className, string? windowName, uint style, int x, int y, int width, int height, nint parent, nint menu, nint instance, nint param);+ [DllImport("user32.dll")] private static extern bool DestroyWindow(nint hWnd);+ [DllImport("user32.dll")] private static extern nint DefWindowProc(nint hWnd, uint message, nint wParam, nint lParam);+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern nint FindWindowEx(nint parent, nint after, string className, string? windowName);+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern uint RegisterWindowMessage(string name);+ [DllImport("user32.dll")] private static extern bool SendNotifyMessage(nint hWnd, uint message, nint wParam, nint lParam);+ [DllImport("user32.dll")] private static extern nint SendMessageTimeout(nint hWnd, uint message, nint wParam, nint lParam, uint flags, uint timeout, out nint result);+ [DllImport("user32.dll")] private static extern bool PostMessage(nint hWnd, uint message, nint wParam, nint lParam);+ [DllImport("user32.dll")] private static extern bool SetWindowPos(nint hWnd, nint after, int x, int y, int width, int height, uint flags);+ [DllImport("user32.dll")] private static extern bool GetWindowRect(nint hWnd, out NativeRect rect);+ [DllImport("user32.dll")] private static extern bool IsWindow(nint hWnd);+ [DllImport("user32.dll")] private static extern nint CopyIcon(nint icon);+ [DllImport("user32.dll")] private static extern bool DestroyIcon(nint icon);+ [DllImport("user32.dll")] private static extern bool AllowSetForegroundWindow(int processId);+ [DllImport("user32.dll")] private static extern bool GetCursorPos(out NativePoint point);+ [DllImport("user32.dll")] private static extern bool EnumWindows(EnumWindowsProc callback, nint lParam);+ [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(nint hWnd, out uint processId);+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern nint GetModuleHandle(string? name);+}diff --git a/Services/UiText.cs b/Services/UiText.csnew file mode 100644index 0000000..5d4395e--- /dev/null+++ b/Services/UiText.cs@@ -0,0 +1,706 @@+using System.ComponentModel;+using System.Windows.Data;+using System.Windows.Markup;+using QiDock.Models;++namespace QiDock.Services;++public sealed class UiText : INotifyPropertyChanged+{+ private static readonly IReadOnlyDictionary<string, (string Turkish, string English)> Entries =+ new Dictionary<string, (string, string)>+ {+ ["Settings"] = ("Ayarlar", "Settings"),+ ["SettingsTitle"] = ("QiDock ayarları", "QiDock settings"),+ ["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."),+ ["Widget_profile"] = ("Profil", "Profile"),+ ["Widget_currency"] = ("Döviz çevirici", "Currency converter"),+ ["Widget_stopwatch"] = ("Kronometre ve sayaç", "Stopwatch and timer"),+ ["Widget_note"] = ("Hızlı not", "Quick note"),+ ["Widget_appgroup"] = ("Uygulama grubu", "App group"),+ ["Widget_progress"] = ("Ay / yıl ilerlemesi", "Month / year progress"),+ ["Widget_reminder"] = ("Su / mola hatırlatıcı", "Water / break reminder"),+ ["Widget_voicememo"] = ("Ses kaydı", "Voice memo"),+ ["Widget_tray"] = ("Arka planda çalışanlar", "Background apps"),+ ["WidgetDescription_tray"] = ("Saatin yanındaki gizli simgeler: arka planda açık kalan uygulamaları gösterir, açar ya da kapatır.", "The hidden icons by the clock: shows the apps left running in the background, opens or closes them."),+ ["TrayTitle"] = ("Arka planda çalışanlar", "Running in the background"),+ ["TrayEmpty"] = ("Arka planda simgesi olan uygulama yok.", "No apps with an icon are running in the background."),+ ["TrayCount"] = ("Arka planda {0} uygulama", "{0} apps in the background"),+ ["TrayHint"] = ("Tıkla: uygulamayı aç · Sağ tık: uygulamanın kendi menüsü · Çarpı: kapat", "Click: open the app · Right click: the app's own menu · Cross: close"),+ ["TrayClose"] = ("Kapat", "Close"),+ ["TrayForceClose"] = ("Zorla kapat", "Force close"),+ ["TrayClosing"] = ("Kapanması istendi…", "Asked to close…"),+ ["TrayStillRunning"] = ("Kapanmadı, hâlâ çalışıyor", "It did not close, still running"),+ ["TrayCannotClose"] = ("Bu uygulama buradan kapatılamıyor", "This app cannot be closed from here"),+ ["TrayClosed"] = ("{0} kapatıldı", "{0} closed"),+ ["ProfileCaption"] = ("Profil", "Profile"),+ ["ProfileTileHint"] = ("Profil değiştir, yeni profil ekle (İş, Kod…). Her profil hangi bileşenlerin görüneceğini ayrı saklar.", "Switch profile or add one (Work, Code…). Each profile keeps its own set of widgets."),+ ["ProfileCode"] = ("Kod", "Code"),+ ["ProfileNewMenu"] = ("Yeni profil", "New profile"),+ ["ProfileCreated"] = ("\"{0}\" profili oluşturuldu", "Profile \"{0}\" created"),+ ["ProfileRemoveNamed"] = ("\"{0}\" profilini sil", "Delete profile \"{0}\""),+ ["ProfileEditWidgets"] = ("Bu profilin bileşenlerini düzenle", "Edit this profile's widgets"),+ ["MediaIdleTitle"] = ("Müzik", "Music"),+ ["MediaSeek"] = ("Şarkıda ilerle", "Move through the song"),+ ["MediaBack10"] = ("10 saniye geri", "10 seconds back"),+ ["MediaForward10"] = ("10 saniye ileri", "10 seconds forward"),+ ["MediaMute"] = ("Sesi kapat / aç", "Mute / unmute"),+ ["MediaAppVolume"] = ("{0} sesi", "{0} volume"),+ ["MediaSystemVolume"] = ("Bilgisayarın sesi", "Computer volume"),+ ["MediaIdle"] = ("Çalan bir şey yok", "Nothing playing"),+ ["MediaIdleHint"] = ("Oynat düğmesi en son çalan uygulamayı (Spotify, tarayıcı…) sürdürür", "Play resumes the app that last played (Spotify, the browser…)"),+ ["CurrencyTitle"] = ("Döviz çevirici", "Currency converter"),+ ["CurrencyTileHint"] = ("Tıklayınca istediğin tutarı çevirirsin", "Click to convert any amount"),+ ["CurrencyLoading"] = ("Kurlar alınıyor…", "Getting rates…"),+ ["CurrencyOffline"] = ("Kurlar alınamadı; internet bağlantısını kontrol et", "Could not get rates; check the internet connection"),+ ["CurrencySource"] = ("Avrupa Merkez Bankası kuru · {0}", "European Central Bank rate · {0}"),+ ["CurrencySwap"] = ("Yer değiştir", "Swap"),+ ["CurrencyCycleHint"] = ("Para birimine tıklayınca sıradakine geçer (TRY, USD, EUR, GBP, CHF, JPY).", "Click a currency to step to the next (TRY, USD, EUR, GBP, CHF, JPY)."),+ ["StopwatchTitle"] = ("Kronometre ve sayaç", "Stopwatch and timer"),+ ["StopwatchLabel"] = ("Kronometre", "Stopwatch"),+ ["StopwatchCountdownLabel"] = ("Sayaç · {0} dk", "Timer · {0} min"),+ ["StopwatchStartPause"] = ("Başlat / duraklat", "Start / pause"),+ ["StopwatchReset"] = ("Sıfırla", "Reset"),+ ["StopwatchDone"] = ("Süre doldu", "Time is up"),+ ["StopwatchMode"] = ("Kronometre", "Stopwatch"),+ ["StopwatchCountdownHint"] = ("Geri sayım (seçince hemen başlar)", "Countdown (starts as soon as picked)"),+ ["NoteTitle"] = ("Hızlı not", "Quick note"),+ ["NoteSavedHint"] = ("Yazdıkların kendiliğinden kaydedilir.", "What you type is saved on its own."),+ ["NoteMoreLines"] = ("+{0} satır daha", "+{0} more lines"),+ ["NoteTapToEdit"] = ("Düzenlemek için tıkla", "Click to edit"),+ ["NoteEmpty"] = ("Not almak için tıkla", "Click to take a note"),+ ["NotePlaceholder"] = ("Aklındakini yaz…", "Write it down…"),+ ["AppGroupTitle"] = ("Uygulama grubu", "App group"),+ ["AppGroupAdd"] = ("Uygulama ekle", "Add an app"),+ ["AppGroupHint"] = ("Simgeye tıkla: aç · Sağ tık: düzenle", "Click an icon to open · Right-click to edit"),+ ["AppGroupEmpty"] = ("En fazla 4 uygulama seç; kutudaki simgelerine tıklayınca açılırlar.", "Pick up to 4 apps; click their icons in the tile to open them."),+ ["AppGroupRemove"] = ("Gruptan çıkar", "Remove from group"),+ ["AppGroupFull"] = ("Grup dolu (4 uygulama)", "Group is full (4 apps)"),+ ["AppGroupSearch"] = ("Uygulama ara…", "Search apps…"),+ ["AppGroupLoading"] = ("Uygulamalar yükleniyor…", "Loading apps…"),+ ["ProgressToday"] = ("Bugün", "Today"),+ ["ProgressHint"] = ("{0}: %{1} geçti · Tıkla: ay / yıl / gün", "{0}: {1}% gone · Click: month / year / day"),+ ["ReminderTitle"] = ("Hatırlatıcı", "Reminder"),+ ["ReminderShort_water"] = ("Su", "Water"),+ ["ReminderShort_break"] = ("Mola", "Break"),+ ["ReminderShort_eyes"] = ("Göz", "Eyes"),+ ["ReminderKind_water"] = ("Su iç", "Drink water"),+ ["ReminderKind_break"] = ("Mola ver", "Take a break"),+ ["ReminderKind_eyes"] = ("Gözünü dinlendir", "Rest your eyes"),+ ["ReminderNow_water"] = ("Bir bardak su içme zamanı", "Time for a glass of water"),+ ["ReminderNow_break"] = ("Kalk, biraz hareket et", "Stand up and move a little"),+ ["ReminderNow_eyes"] = ("20 saniye uzağa bak", "Look far away for 20 seconds"),+ ["ReminderOff"] = ("Kapalı", "Off"),+ ["ReminderOffShort"] = ("Kapalı", "Off"),+ ["ReminderOffHint"] = ("Hatırlatıcıyı açmak için tıkla", "Click to turn the reminder on"),+ ["ReminderNext"] = ("{0} dk sonra", "in {0} min"),+ ["ReminderNextGlasses"] = ("{0} dk sonra · {1} bardak", "in {0} min · {1} glasses"),+ ["ReminderEvery"] = ("Her {0} dakikada bir hatırlatır", "Reminds every {0} minutes"),+ ["ReminderInterval"] = ("Ne sıklıkla", "How often"),+ ["ReminderGlasses"] = ("Bugün {0} bardak", "{0} glasses today"),+ ["ReminderDrank"] = ("İçtim", "Drank one"),+ ["MemoTitle"] = ("Ses kaydı", "Voice memo"),+ ["MemoTapToRecord"] = ("Kırmızıya bas: kaydet", "Press red to record"),+ ["MemoRecording"] = ("Kaydediliyor · bitirmek için bas", "Recording · press to finish"),+ ["MemoRecordStop"] = ("Kaydı başlat / bitir", "Start / finish recording"),+ ["MemoHint"] = ("Kayıtlar Belgeler\\Ses Kayıtları klasörüne kaydedilir", "Recordings are saved in Documents\\Ses Kayıtları"),+ ["MemoNoMic"] = ("Mikrofon açılamadı", "Could not open the microphone"),+ ["MemoSaved"] = ("Kayıt kaydedildi ({0})", "Recording saved ({0})"),+ ["MemoOpenFolder"] = ("Klasörü aç", "Open folder"),+ ["MemoNone"] = ("Henüz kayıt yok. Kutudaki kırmızı düğmeye basınca kayıt başlar, tekrar basınca biter.", "No recordings yet. Press the red button in the tile to start, press it again to finish."),+ ["Widget_media"] = ("Müzik", "Music"),+ ["Widget_weather"] = ("Hava durumu", "Weather"),+ ["Widget_clock"] = ("Saat ve takvim", "Clock and calendar"),+ ["Widget_ai"] = ("Yapay zekâ limitleri", "AI limits"),+ ["Desktop"] = ("Temiz masaüstü", "Clean desktop"),+ ["DesktopFiles"] = ("Klasörlü masaüstü", "Desktop with files"),+ ["MenuWidgets"] = ("Widget’lar", "Widgets"),+ ["MenuEditDock"] = ("Widget’ları düzenle (taşı, kaldır, ekle)", "Edit widgets (move, remove, add)"),+ ["MenuEditDone"] = ("Düzenlemeyi bitir", "Finish editing"),+ ["MenuCity"] = ("Hava durumu şehri: {0}", "Weather city: {0}"),+ ["MenuCityOther"] = ("Başka şehir veya ilçe…", "Another city or district…"),+ ["MenuPosition"] = ("Dock konumu", "Dock position"),+ ["MenuAutoHide"] = ("Otomatik gizle", "Auto-hide"),+ ["MenuAutoHideOff"] = ("Kapalı", "Off"),+ ["MenuAutoHideSmart"] = ("Pencere üstüne gelince", "When a window overlaps"),+ ["MenuAutoHideAlways"] = ("Her zaman (alt kenara gelince çıkar)", "Always (shows at the bottom edge)"),+ ["MenuTheme"] = ("Tema", "Theme"),+ ["MenuHideDesktopIcons"] = ("Temiz masaüstü (simgeleri gizle)", "Clean desktop (hide icons)"),+ ["DockEdge"] = ("Dock'un kenarı", "Dock edge"),+ ["DockEdgeBottom"] = ("Alt", "Bottom"),+ ["DockEdgeTop"] = ("Üst", "Top"),+ ["DockEdgeLeft"] = ("Sol", "Left"),+ ["DockEdgeRight"] = ("Sağ", "Right"),+ ["DockEdgeHint"] = ("Sol ve sağ kenarda araçlar üst çubukta durur; üst kenarda dock'un içine geçer.", "On the left and right edges the widgets stay in the top bar; on the top edge they move into the dock."),+ ["WidgetPlacement"] = ("Dock düzeni", "Dock layout"),+ ["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"),+ ["MenuTopBarPeek"] = ("Üst kenara gelince widget çubuğunu göster", "Show the widget bar at the top edge"),+ ["EditAddWidget"] = ("Ekle", "Add"),+ ["EditDone"] = ("Bitti", "Done"),+ ["EditMoveLeft"] = ("Sola taşı", "Move left"),+ ["EditMoveRight"] = ("Sağa taşı", "Move right"),+ ["EditRemove"] = ("Kaldır", "Remove"),+ ["EditAllShown"] = ("Bütün widget’lar zaten görünüyor", "All widgets are already shown"),+ ["Widget_system"] = ("Sistem (CPU ve RAM)", "System (CPU and RAM)"),+ ["Widget_quick"] = ("Hızlı kontroller", "Quick controls"),+ ["WidgetDescription_profile"] = ("Etkin profil (İş, Kod…); tıklayınca profil değiştirir ya da yeni profil eklersin.", "The active profile (Work, Code…); click to switch or add one."),+ ["WidgetDescription_currency"] = ("1 dolar kaç lira; tıklayınca istediğin tutarı TRY, USD, EUR, GBP arasında çevirir.", "One unit in another currency; click to convert any amount."),+ ["WidgetDescription_stopwatch"] = ("Kronometre ya da geri sayan sayaç; süre dolunca ses ve ekranın üstünde uyarı.", "Stopwatch or countdown; a chime and a message when time is up."),+ ["WidgetDescription_note"] = ("Kısa not; yazdıkların kalır, kutuda ilk satırı görünür.", "A short note; it is kept and its first line shows in the tile."),+ ["WidgetDescription_appgroup"] = ("En fazla 4 favori uygulama küçük bir kutuda; simgeye tıklayınca açılır.", "Up to 4 favourite apps in a small square; click an icon to open it."),+ ["WidgetDescription_progress"] = ("Ayın, yılın ya da günün ne kadarı geçti; noktalar ve yüzde.", "How much of the month, year or day has gone, as dots and a percent."),+ ["WidgetDescription_reminder"] = ("Belirli aralıklarla su içmeyi, mola vermeyi ya da gözünü dinlendirmeyi hatırlatır.", "Reminds you to drink water, take a break or rest your eyes."),+ ["WidgetDescription_voicememo"] = ("Tek tıkla mikrofondan kayıt; Belgeler\\Ses Kayıtları klasörüne kaydeder.", "One-click microphone recording, saved in Documents\\Ses Kayıtları."),+ ["WidgetDescription_media"] = ("Çalan şarkı; önceki, durdur/oynat ve sonraki.", "What’s playing; previous, play/pause and next."),+ ["WidgetDescription_weather"] = ("Anlık durum; tıklayınca saatlik ve 7 günlük tahmin.", "Current conditions; click for hourly and 7-day forecast."),+ ["WidgetDescription_clock"] = ("Saat ve tarih; tıklayınca ay takvimi ve günün etkinlikleri.", "Time and date; click for the month and today’s events."),+ ["WidgetDescription_ai"] = ("Claude ve ChatGPT kullanım limitleri ve sıfırlanma zamanları.", "Claude and ChatGPT usage limits and reset times."),+ ["Widget_folder"] = ("Klasör", "Folder"),+ ["Widget_search"] = ("Ara", "Search"),+ ["Widget_colors"] = ("Renk seçici", "Color picker"),+ ["Widget_appvolume"] = ("Uygulama sesleri", "App volume"),+ ["Widget_focus"] = ("Odak sayacı", "Focus timer"),+ ["Widget_worldclock"] = ("Dünya saati", "World clock"),+ ["Widget_todo"] = ("Yapılacaklar", "To-do"),+ ["Widget_shelf"] = ("Raf", "Shelf"),+ ["Widget_tools"] = ("Araçlar", "Tools"),+ ["Widget_notifications"] = ("Bildirimler", "Notifications"),+ ["NotificationsTitle"] = ("Bildirimler", "Notifications"),+ ["NotificationsUnread"] = ("{0} yeni", "{0} new"),+ ["NotificationsCount"] = ("{0} bildirim", "{0} notifications"),+ ["NotificationsNone"] = ("Yeni bildirim yok", "No new notifications"),+ ["NotificationsEmptyQuiet"] = ("Bildirim yok.", "No notifications."),+ ["NotificationsEmpty"] = ("Bildirim yok. Yeni gelenler ekranın üstünde görünür.", "No notifications. New ones appear at the top of the screen."),+ ["NotificationsUnavailable"] = ("Windows bildirimleri okunamadı.", "Windows notifications could not be read."),+ ["NotificationsClear"] = ("Tümünü temizle", "Clear all"),+ ["NotificationDismiss"] = ("Kapat", "Dismiss"),+ ["NotificationsBanners"] = ("Üstte göster", "Show at top"),+ ["NotificationsSound"] = ("Ses çal", "Play sound"),+ ["NotificationsWindowsHint"] = ("Windows'un sağ alttaki balonlarını kapatmak için Windows ayarlarında \"Rahatsız etmeyin\"i açın; bildirimler yine burada ve üstte görünür.", "To stop Windows' own pop-ups at the bottom right, turn on \"Do not disturb\" in Windows settings; notifications still show here and at the top."),+ ["NotificationsWindowsSettings"] = ("Windows bildirim ayarlarını aç", "Open Windows notification settings"),+ ["NotificationsOptions"] = ("Bildirim seçenekleri", "Notification options"),+ ["NotificationsBannersHint"] = ("Yeni bildirimler ekranın üstünden kayar.", "New notifications slide in at the top."),+ ["NotificationsHideWindows"] = ("Windows balonlarını gizle", "Hide Windows pop-ups"),+ ["NotificationsHideWindowsHint"] = ("Sağ alttaki Windows balonu çıkmaz, bildirim yalnızca üstte görünür.", "Windows' bottom-right pop-up stays away; each notification shows once, at the top."),+ ["NotificationsSoundHint"] = ("Bildirim gelince kısa bir ses çalar.", "Plays a short sound when one arrives."),+ ["NotificationsMore"] = ("+{0} daha", "+{0} more"),+ ["NotificationsShowLess"] = ("Daha az göster", "Show less"),+ ["Widget_controlcenter"] = ("Denetim Merkezi", "Control Center"),+ ["Widget_battery"] = ("Pil", "Battery"),+ ["WidgetDescription_battery"] = ("Pil doluluğu bir halkada; şarj olurken şimşek.", "Battery charge in a ring, with a bolt while charging."),+ ["BatteryNone"] = ("Pil yok (fişe bağlı)", "No battery (plugged in)"),+ ["BatteryCharging"] = ("Şarj oluyor", "Charging"),+ ["BatteryLeft"] = ("{0} sa {1} dk kaldı", "{0} h {1} min left"),+ ["BatteryTitle"] = ("Pil", "Battery"),+ ["PreviewWindowTitle"] = ("Pencere önizlemesi", "Window preview"),+ ["PreviewHiddenHint"] = ("Gizli: fareyi kenara götürünce çıkar", "Hidden: comes up at the screen edge"),+ ["PreviewEdgeBottom"] = ("Dock altta", "Dock at the bottom"),+ ["PreviewEdgeTop"] = ("Dock üstte", "Dock at the top"),+ ["PreviewEdgeLeft"] = ("Dock solda", "Dock on the left"),+ ["PreviewEdgeRight"] = ("Dock sağda", "Dock on the right"),+ ["PreviewWidgetsTop"] = ("bileşenler üst şeritte", "widgets in the top strip"),+ ["PreviewWidgetsLeft"] = ("bileşenler dock'un solunda", "widgets left in the dock"),+ ["PreviewWidgetsRight"] = ("bileşenler dock'un sağında", "widgets right in the dock"),+ ["PreviewMagnifyOn"] = ("büyütme %{0}", "magnify {0}%"),+ ["PreviewMagnifyOff"] = ("büyütme kapalı", "no magnification"),+ ["PreviewHideNever"] = ("hep görünür", "always shown"),+ ["PreviewHideSmart"] = ("pencere üstüne gelince gizlenir", "hides when a window covers it"),+ ["PreviewHideAlways"] = ("her zaman gizli", "always hidden"),+ ["PreviewTryHint"] = ("Önizlemedeki simgelerin üzerinde gezinip deneyin. Değişiklikler yalnızca Uygula'ya basınca dock'a geçer.", "Point at the icons in the picture to try it. Changes reach the dock only when you press Apply."),+ ["Magnify"] = ("Simgeleri büyüt", "Magnify icons"),+ ["MagnifyDescription"] = ("Fare dock'ta gezerken altındaki simgeler büyür", "Icons under the pointer grow as it moves along the dock"),+ ["MagnifyScale"] = ("Büyütme oranı", "Magnification"),+ ["MagnifyNote"] = ("Bilgi: Büyütme, fare dock'ta her kıpırdadığında dock'u yeniden çizer; işlemciyi biraz daha çalıştırır. Bilgisayar yavaş gelirse kapatabilirsin.", "Note: magnification redraws the dock on every pointer move, so it uses a little more processor time. Turn it off if the computer feels slow."),+ ["MagnifyNoteLowMemory"] = ("Bilgi: Az bellek modu açıkken büyütme takılabilir, çünkü çizimi işlemci yapıyor. Akıcı olsun istersen Genel sekmesinden az bellek modunu kapatabilirsin; o zaman uygulama yaklaşık 300 MB daha fazla bellek kullanır.", "Note: with low-memory mode on, magnification can stutter because the processor does the drawing. For smooth motion, turn low-memory mode off on the General tab; the app then uses about 300 MB more memory."),+ ["BatteryFull"] = ("Tam dolu, prize takılı", "Fully charged, plugged in"),+ ["BatteryPlugged"] = ("Prize takılı", "Plugged in"),+ ["BatteryOnBattery"] = ("Pille çalışıyor", "On battery"),+ ["BatteryEstimating"] = ("Kalan süre hesaplanıyor…", "Estimating time left…"),+ ["BatterySaverOn"] = ("Enerji tasarrufu açık", "Energy saver is on"),+ ["BatterySettings"] = ("Pil ayarları", "Battery settings"),+ ["BatteryLevel"] = ("Doluluk", "Charge"),+ ["ControlCenterTitle"] = ("Denetim Merkezi", "Control Center"),+ ["ControlCenterStatus"] = ("Wi-Fi, ses, parlaklık", "Wi-Fi, sound, brightness"),+ ["CcNetwork"] = ("Ağ", "Network"),+ ["WifiShowNetworks"] = ("Ağları göster", "Show networks"),+ ["WifiNetworks"] = ("Wi-Fi ağları", "Wi-Fi networks"),+ ["WifiScanning"] = ("Aranıyor…", "Searching…"),+ ["WifiRescan"] = ("Yeniden ara", "Search again"),+ ["WifiNone"] = ("Yakında ağ bulunamadı", "No networks nearby"),+ ["WifiNoAdapter"] = ("Bu bilgisayarda Wi-Fi kartı bulunamadı", "No Wi-Fi adapter found"),+ ["WifiDenied"] = ("Windows ağları listelemeye izin vermiyor (Ayarlar › Gizlilik › Konum › masaüstü uygulamaları kapalı olabilir). Windows'un kendi listesinden bağlanabilirsiniz.", "Windows does not allow listing networks (location access for desktop apps may be off). You can join from Windows' own list."),+ ["WifiJoining"] = ("Bağlanıyor…", "Connecting…"),+ ["WifiConnectedHint"] = ("Bağlı", "Connected"),+ ["WifiPasswordFor"] = ("“{0}” için şifre", "Password for “{0}”"),+ ["WifiWrongPassword"] = ("Şifre yanlış, yeniden deneyin", "Wrong password, try again"),+ ["WifiNotInRange"] = ("Ağ artık görünmüyor", "The network is out of range"),+ ["WifiUnsupported"] = ("Bu ağa yalnızca Windows'un listesinden bağlanılabilir", "This network can only be joined from Windows' list"),+ ["WifiFailed"] = ("Bağlanılamadı", "Could not connect"),+ ["WifiJoin"] = ("Bağlan", "Join"),+ ["WifiCancel"] = ("Vazgeç", "Cancel"),+ ["WifiWindowsList"] = ("Windows ağ listesi", "Windows network list"),+ ["CcPowerMode"] = ("Güç modu", "Power mode"),+ ["CcModeEfficiency"] = ("Verimli", "Efficiency"),+ ["CcModeBalanced"] = ("Dengeli", "Balanced"),+ ["CcModePerformance"] = ("Performans", "Performance"),+ ["CcVolume"] = ("Ses", "Sound"),+ ["CcMute"] = ("Sesi kapat / aç", "Mute / unmute"),+ ["CcBrightness"] = ("Parlaklık", "Brightness"),+ ["CcBattery"] = ("Pil", "Battery"),+ ["CcCharging"] = ("Şarj oluyor", "Charging"),+ ["CcPlugged"] = ("Prize takılı", "Plugged in"),+ ["CcOnBattery"] = ("Pilde · {0} kaldı", "On battery · {0} left"),+ ["CcScreenshot"] = ("Ekran alıntısı", "Snip"),+ ["CcLock"] = ("Ekranı kilitle", "Lock screen"),+ ["CcDockSettings"] = ("Dock ayarları", "Dock settings"),+ ["CcWindowsSettingsTip"] = ("Windows Ayarları", "Windows Settings"),+ ["CcWindowsSettings"] = ("Windows", "Windows"),+ ["AppGridTitle"] = ("Tüm uygulamalar (Ctrl+Alt+↓)", "All apps (Ctrl+Alt+↓)"),+ ["AppGridSearch"] = ("Ara", "Search"),+ ["AppGridLoading"] = ("Uygulamalar yükleniyor…", "Loading apps…"),+ ["QuickSearchHint"] = ("Uygulama, dosya ara ya da hesapla", "Search apps and files, or calculate"),+ ["QuickSearchCopy"] = ("Enter ile kopyala", "Press Enter to copy"),+ ["QuickSearchWeb"] = ("Web'de ara: “{0}”", "Search the web for “{0}”"),+ ["WindowOverviewEmpty"] = ("Açık pencere yok", "No open windows"),+ ["DownloadsTitle"] = ("İndirilenler", "Downloads"),+ ["DownloadsOpenFolder"] = ("Klasörü aç", "Open folder"),+ ["DownloadsEmpty"] = ("İndirilenler klasörü boş.", "The Downloads folder is empty."),+ ["WidgetDescription_folder"] = ("Masaüstü ya da seçtiğiniz klasör; dosyalar ızgarada, sürükleyip bırakılabilir.", "The Desktop or a folder you pick; files in a grid you can open or drag out."),+ ["WidgetDescription_search"] = ("Uygulama ve dosyaları yazarak bulun.", "Type to find apps and files."),+ ["WidgetDescription_colors"] = ("Ekrandan renk seçin; renkler saklanır, tıklayınca kodu kopyalanır.", "Pick colors from the screen; they are kept and copied on click."),+ ["WidgetDescription_appvolume"] = ("Her uygulamanın sesi ayrı ayrı.", "Volume for each app separately."),+ ["WidgetDescription_focus"] = ("Pomodoro odak sayacı; süre bitince haber verir.", "Pomodoro focus timer; tells you when time is up."),+ ["WidgetDescription_worldclock"] = ("Üç şehrin saati ve farkı.", "Three cities’ time and difference."),+ ["WidgetDescription_todo"] = ("Kısa yapılacaklar listesi.", "A short to-do list."),+ ["WidgetDescription_shelf"] = ("Dosyaları geçici olarak bırakıp sonra sürükleyin.", "Drop files to keep them at hand, then drag them out."),+ ["WidgetDescription_tools"] = ("Ekran görüntüsü, pano geçmişi, emoji, hesap makinesi, kilit.", "Screenshot, clipboard history, emoji, calculator, lock."),+ ["FolderItems"] = ("{0} öğe", "{0} items"),+ ["FolderDesktop"] = ("Masaüstü", "Desktop"),+ ["FolderChoose"] = ("Klasör seç", "Choose folder"),+ ["FolderOpenExplorer"] = ("Dosya Gezgini’nde aç", "Open in File Explorer"),+ ["FolderBack"] = ("Geri", "Back"),+ ["FolderEmpty"] = ("Bu klasör boş.", "This folder is empty."),+ ["AgoNow"] = ("az önce", "just now"),+ ["AgoMinutes"] = ("{0} dk önce", "{0} min ago"),+ ["AgoHours"] = ("{0} sa önce", "{0} h ago"),+ ["AgoDays"] = ("{0} gün önce", "{0} days ago"),+ ["AgoMonths"] = ("{0} ay önce", "{0} mo ago"),+ ["AgoYears"] = ("{0} yıl önce", "{0} yr ago"),+ ["SearchHint"] = ("Ara", "Search"),+ ["SearchTileTip"] = ("Uygulama ve dosya ara (Alt+Shift+Boşluk)", "Search apps and files (Alt+Shift+Space)"),+ ["SearchIndexing"] = ("Dosyalar taranıyor…", "Scanning files…"),+ ["SearchApp"] = ("Uygulama", "App"),+ ["ColorsPick"] = ("Seç", "Pick"),+ ["ColorsTitle"] = ("Renkler", "Colors"),+ ["ColorsEmpty"] = ("“Seç” ile ekrandaki herhangi bir rengi alın; Esc ya da sağ tık vazgeçer.", "Use “Pick” to grab any color on screen; Esc or right-click cancels."),+ ["ColorsCopyHint"] = ("Tıkla: kodu kopyala · Sağ tık: sil", "Click: copy code · Right-click: remove"),+ ["ColorsClear"] = ("Tümünü temizle", "Clear all"),+ ["ColorsCopied"] = ("{0} kopyalandı", "{0} copied"),+ ["Refresh"] = ("Yenile", "Refresh"),+ ["AppVolumeTitle"] = ("Uygulama sesleri", "App volume"),+ ["AppVolumeEmpty"] = ("Şu an ses çıkaran ya da ses açmış bir uygulama yok.", "No app has sound open right now."),+ ["AppVolumePlaying"] = ("çalıyor", "playing"),+ ["AppVolumeMute"] = ("Sessize al", "Mute"),+ ["FocusLabel"] = ("Odak", "Focus"),+ ["FocusRunning"] = ("Odaklanıyor", "Focusing"),+ ["FocusFinished"] = ("Bitti", "Done"),+ ["FocusStartPause"] = ("Başlat / duraklat", "Start / pause"),+ ["FocusReset"] = ("Sıfırla", "Reset"),+ ["FocusDone"] = ("Odak süresi bitti, mola zamanı", "Focus time is up, take a break"),+ ["FocusTitle"] = ("Odak sayacı", "Focus timer"),+ ["FocusLength"] = ("Süre", "Length"),+ ["FocusMinutes"] = ("{0} dk", "{0} min"),+ ["FocusBreak"] = ("5 dakikalık mola başlat", "Start a 5-minute break"),+ ["FocusBreakDone"] = ("Mola bitti, yeni odak için hazır", "Break is over, ready to focus again"),+ ["FocusOnBreak"] = ("Mola", "Break"),+ ["FocusToday"] = ("Bugün tamamlanan: {0}", "Completed today: {0}"),+ ["WorldClockTitle"] = ("Dünya saati", "World clock"),+ ["WorldClockHint"] = ("En fazla {0} şehir seçin.", "Pick up to {0} cities."),+ ["TodoTitle"] = ("Yapılacaklar", "To-do"),+ ["TodoAllDone"] = ("Hepsi tamam", "All done"),+ ["TodoOpen"] = ("{0} görev", "{0} tasks"),+ ["TodoAddHint"] = ("Görev eklemek için tıklayın", "Click to add a task"),+ ["TodoClearDone"] = ("Tamamlananları temizle", "Clear completed"),+ ["TodoPlaceholder"] = ("Yeni görev yazıp Enter’a basın…", "Type a task and press Enter…"),+ ["TodoToggle"] = ("Tamamlandı", "Done"),+ ["TodoRemove"] = ("Sil", "Remove"),+ ["ShelfTitle"] = ("Raf", "Shelf"),+ ["ShelfDropHint"] = ("Dosya bırakın", "Drop files"),+ ["ShelfCount"] = ("{0} dosya", "{0} files"),+ ["ShelfEmpty"] = ("Dosyaları rafın üstüne sürükleyip bırakın; sonra buradan başka yere sürükleyin.", "Drag files onto the shelf, then drag them out from here."),+ ["ShelfDragHint"] = ("Tıkla: aç · Sürükle: başka yere bırak", "Click: open · Drag: drop elsewhere"),+ ["ShelfRemove"] = ("Raftan kaldır", "Remove from shelf"),+ ["ShelfClear"] = ("Rafı boşalt", "Clear shelf"),+ ["ToolScreenshot"] = ("Ekran alıntısı al", "Take a snip"),+ ["ToolClipboard"] = ("Pano geçmişi", "Clipboard history"),+ ["ToolEmoji"] = ("Emoji", "Emoji"),+ ["ToolCalculator"] = ("Hesap makinesi", "Calculator"),+ ["ToolLock"] = ("Ekranı kilitle", "Lock screen"),+ ["ProfileAdd"] = ("Profil ekle", "Add profile"),+ ["ProfileNew"] = ("Profil {0}", "Profile {0}"),+ ["ProfileDefault"] = ("Varsayılan", "Default"),+ ["ProfileWork"] = ("İş", "Work"),+ ["ProfileTools"] = ("Araçlar", "Tools"),+ ["ProfileHome"] = ("Ev", "Home"),+ ["ProfileFocus"] = ("Odak", "Focus"),+ ["ProfileGame"] = ("Oyun", "Gaming"),+ ["ProfileSchool"] = ("Okul", "School"),+ ["ProfileCreative"] = ("Tasarım", "Design"),+ ["ProfileRename"] = ("Adını değiştir", "Rename"),+ ["ProfileRemove"] = ("Profili sil", "Delete profile"),+ ["RecycleBin"] = ("Geri Dönüşüm Kutusu", "Recycle Bin"),+ ["RecycleBinOpen"] = ("Aç", "Open"),+ ["RecycleBinEmpty"] = ("Geri Dönüşüm Kutusunu boşalt", "Empty Recycle Bin"),+ ["ShortcutAdd"] = ("Kısayol ekle", "Add shortcut"),+ ["ShortcutAddFile"] = ("Uygulama ya da dosya…", "App or file…"),+ ["ShortcutAddFolder"] = ("Klasör…", "Folder…"),+ ["ShortcutDropHint"] = ("Dosya, klasör ya da bağlantıyı dock’a sürükleyip bırakabilirsiniz", "You can also drop files, folders or links on the dock"),+ ["ShortcutPickFile"] = ("Dock’a eklenecek uygulama ya da dosya", "App or file to add to the dock"),+ ["ShortcutPickFolder"] = ("Dock’a eklenecek klasör", "Folder to add to the dock"),+ ["ShortcutAdded"] = ("{0} kısayol dock’a eklendi", "{0} shortcut(s) added to the dock"),+ ["WidgetDescription_system"] = ("İşlemci ve bellek kullanımı; düşükse yeşil, arttıkça sarı, turuncu ve kırmızı.", "Processor and memory load, green when low turning yellow, orange and red as it rises."),+ ["SysTitle"] = ("Sistem", "System"),+ ["SysCpu"] = ("İşlemci (CPU)", "Processor (CPU)"),+ ["SysRam"] = ("Bellek (RAM)", "Memory (RAM)"),+ ["SysCores"] = ("{0} mantıksal çekirdek", "{0} logical cores"),+ ["SysRamDetail"] = ("{0} / {1} kullanımda", "{0} of {1} in use"),+ ["SysUptime"] = ("Açık kalma süresi: {0} gün {1} sa {2} dk", "Up for {0} d {1} h {2} min"),+ ["SysTaskManager"] = ("Görev Yöneticisi'ni aç", "Open Task Manager"),+ ["WidgetDescription_notifications"] = ("Okunmamış bildirim sayısı; tıklayınca Bildirim Merkezi açılır.", "Unread notifications; click to open the Notification Center."),+ ["WidgetDescription_controlcenter"] = ("Wi-Fi, Bluetooth, ses, parlaklık ve pil tek panelde.", "Wi-Fi, Bluetooth, volume, brightness and battery in one panel."),+ ["WidgetDescription_quick"] = ("Wi-Fi, Bluetooth, ses düzeyi ve pil.", "Wi-Fi, Bluetooth, volume and battery."),+ ["MoveUp"] = ("Yukarı taşı", "Move up"),+ ["MoveDown"] = ("Aşağı taşı", "Move down"),+ ["WeatherCity"] = ("Hava durumu şehri", "Weather city"),+ ["WeatherCityHelp"] = ("Örnek: İstanbul, Ankara, İzmir. Veriler Open-Meteo’dan alınır.", "For example: London, Berlin. Data comes from Open-Meteo."),+ ["CalendarFeed"] = ("Takvim adresi (iCal)", "Calendar address (iCal)"),+ ["CalendarFeedHelp"] = ("Google Takvim → Ayarlar → takviminiz → “Takvimi entegre et” → “iCal biçiminde gizli adres”. Outlook ve iCloud .ics bağlantıları da çalışır. Boş bırakılırsa yalnızca takvim gösterilir.", "Google Calendar → Settings → your calendar → “Integrate calendar” → “Secret address in iCal format”. Outlook and iCloud .ics links work too. Leave empty to show the calendar only."),+ ["ShowSeconds"] = ("Saatte saniyeyi göster", "Show seconds on the clock"),+ ["AiLimitsHelp"] = ("Yapay zekâ limitleri: Claude için bu bilgisayarda Claude Code ile oturum açılmış olmalıdır. ChatGPT limitleri Codex’in yerel kayıtlarından okunur ve Codex’i her kullandığınızda güncellenir.", "AI limits: Claude requires being signed in to Claude Code on this PC. ChatGPT limits are read from Codex’s local logs and update whenever you use Codex."),+ ["CultureName"] = ("tr-TR", "en-US"),+ ["ClockDateFormat"] = ("ddd d MMM", "ddd d MMM"),+ ["CalToday"] = ("Bugün", "Today"),+ ["CalPrevMonth"] = ("Önceki ay", "Previous month"),+ ["CalNextMonth"] = ("Sonraki ay", "Next month"),+ ["CalAllDay"] = ("Tüm gün", "All day"),+ ["CalEvents"] = ("Etkinlikler", "Events"),+ ["CalCalendars"] = ("Takvimler", "Calendars"),+ ["CalEventCount"] = ("{0} etkinlik", "{0} events"),+ ["CalNewEvent"] = ("Yeni etkinlik", "New event"),+ ["CalNewEventOn"] = ("Yeni etkinlik: {0}", "New event {0}"),+ ["CalEmpty"] = ("Etkinlik yok", "No events"),+ ["CalLoading"] = ("Takvim yükleniyor…", "Loading calendar…"),+ ["CalNoFeed"] = ("Etkinlikleri burada görmek için takvim adresinizi bağlayın.", "Connect your calendar address to see events here."),+ ["CalConnect"] = ("Takvim bağla…", "Connect calendar…"),+ ["CalendarFeedError"] = ("Takvim alınamadı; adresi denetleyin.", "Couldn’t load the calendar; check the address."),+ ["CalendarUntitled"] = ("(Başlıksız)", "(Untitled)"),+ ["Weather"] = ("Hava durumu", "Weather"),+ ["WxLoading"] = ("Hava durumu yükleniyor…", "Loading weather…"),+ ["WxUnavailable"] = ("Bağlantı yok", "Offline"),+ ["WxCityNotFound"] = ("Şehir bulunamadı", "City not found"),+ ["WxChangeCity"] = ("Değiştir", "Change"),+ ["WxNow"] = ("Şimdi", "Now"),+ ["WxToday"] = ("Bugün", "Today"),+ ["ClaudeThinking"] = ("Düşünüyor…", "Thinking…"),+ ["ClaudeWriting"] = ("Yazıyor…", "Writing…"),+ ["ClaudeDone"] = ("Bitti", "Done"),+ ["ClaudeEditingFile"] = ("{0} düzenleniyor…", "Editing {0}…"),+ ["ClaudeEditingFiles"] = ("{0} dosya düzenleniyor…", "Editing {0} files…"),+ ["ClaudeRunning"] = ("Komut çalışıyor…", "Running a command…"),+ ["ClaudeReading"] = ("Kod okunuyor…", "Reading code…"),+ ["ClaudeBrowsing"] = ("Web'de arıyor…", "Searching the web…"),+ ["ClaudeAgents"] = ("Alt ajanlar çalışıyor…", "Agents at work…"),+ ["ClaudeTools"] = ("Araç kullanıyor…", "Using a tool…"),+ ["ClaudeWorking"] = ("Çalışıyor…", "Working…"),+ ["ClaudeActivitySetting"] = ("Claude kartında Claude Code oturumları", "Claude Code sessions in the Claude card"),+ ["ClaudeActivitySettingHelp"] = ("Sağdaki Claude halkasına tıklayınca son oturumlar (proje, o anki iş, bitti mi) listelenir. Kendiliğinden hiçbir şey açılmaz; yalnızca bu bilgisayardaki kayıtlar, kart açıkken okunur.", "Clicking the Claude ring lists the recent sessions (project, current step, finished or not). Nothing opens by itself; only this PC's logs are read, while the card is open."),+ ["ClaudeSessionsTitle"] = ("Claude Code", "Claude Code"),+ ["LowMemory"] = ("Az bellek modu", "Low-memory mode"),+ ["LowMemoryHelp"] = ("Ekranı ekran kartı yerine işlemciyle çizer: yaklaşık 300 MB daha az bellek. Akıcı kalsın diye gölgeler kapanır, panellerin arkasındaki buzlu cam bulanıklığı da kapanır. Yeniden başlatınca geçerli olur.", "Draws on the processor instead of the graphics card: about 300 MB less memory. To keep motion smooth, shadows are left out and the frosted blur behind panels goes away. Takes effect after a restart."),+ ["LowMemoryRestart"] = ("Az bellek modu uygulama yeniden başlayınca geçerli olur. Şimdi yeniden başlatılsın mı?", "Low-memory mode takes effect when the app restarts. Restart now?"),+ ["ClaudeSessionsCaption"] = ("Son oturumlar", "Recent sessions"),+ ["ClaudeSessionsNone"] = ("Son 30 dakikada Claude Code oturumu yok.", "No Claude Code session in the last 30 minutes."),+ ["ClaudeIdle"] = ("Bekliyor", "Waiting"),+ ["ClaudeAgoNow"] = ("şimdi", "now"),+ ["ClaudeAgoMinutes"] = ("{0} dk önce", "{0} min ago"),+ ["ProfileCreate"] = ("Kendinizinkini oluşturun", "Create your own"),+ ["ProfileShortcut"] = ("Ctrl+Alt+Shift+{0}", "Ctrl+Alt+Shift+{0}"),+ ["HudVolume"] = ("Ses", "Volume"),+ ["HudBrightness"] = ("Parlaklık", "Brightness"),+ ["HudBrightnessPill"] = ("Parlaklık %{0}", "Brightness {0}%"),+ ["DockHudSetting"] = ("Ses ve parlaklık dock'tan çıksın", "Volume and brightness rise from the dock"),+ ["DockHudSettingHelp"] = ("Kapalıyken ekranın üstünde küçük bir hap görünür.", "When off, a small pill shows at the top of the screen."),+ ["LookStyle"] = ("Tema", "Look"),+ ["LookStyleHint"] = ("Cam, yukarıdaki koyu/açık seçimini izler; diğer temalar dock'a, araçlara ve panellere kendi renklerini getirir.", "Glass follows the dark/light choice; the other looks bring their own colours to the dock, widgets and panels."),+ ["WxHigh"] = ("En yüksek", "H"),+ ["WxLow"] = ("En düşük", "L"),+ ["WxUpdated"] = ("Güncelleme {0} · Open-Meteo", "Updated {0} · Open-Meteo"),+ ["WxClear"] = ("Açık", "Clear"),+ ["WxMostlyClear"] = ("Az bulutlu", "Mostly clear"),+ ["WxPartlyCloudy"] = ("Parçalı bulutlu", "Partly cloudy"),+ ["WxOvercast"] = ("Kapalı", "Overcast"),+ ["WxFog"] = ("Sisli", "Fog"),+ ["WxDrizzle"] = ("Çisenti", "Drizzle"),+ ["WxFreezingDrizzle"] = ("Donan çisenti", "Freezing drizzle"),+ ["WxLightRain"] = ("Hafif yağmur", "Light rain"),+ ["WxRain"] = ("Yağmurlu", "Rain"),+ ["WxHeavyRain"] = ("Şiddetli yağmur", "Heavy rain"),+ ["WxFreezingRain"] = ("Donan yağmur", "Freezing rain"),+ ["WxLightSnow"] = ("Hafif kar", "Light snow"),+ ["WxSnow"] = ("Karlı", "Snow"),+ ["WxHeavySnow"] = ("Yoğun kar", "Heavy snow"),+ ["WxSnowGrains"] = ("Kar taneleri", "Snow grains"),+ ["WxShowers"] = ("Sağanak", "Showers"),+ ["WxSnowShowers"] = ("Kar sağanağı", "Snow showers"),+ ["WxThunder"] = ("Gök gürültülü", "Thunderstorm"),+ ["WxHail"] = ("Dolu ve fırtına", "Thunderstorm with hail"),+ ["WxUnknown"] = ("Bilinmiyor", "Unknown"),+ ["MediaPrevious"] = ("Önceki", "Previous"),+ ["MediaPlayPause"] = ("Oynat / duraklat", "Play / pause"),+ ["MediaNext"] = ("Sonraki", "Next"),+ ["AiLimits"] = ("Yapay zekâ limitleri", "AI limits"),+ ["AiSession"] = ("Oturum", "Session"),+ ["AiWeekly"] = ("Haftalık", "Weekly"),+ ["AiMonthly"] = ("Aylık", "Monthly"),+ ["AiWeeklyOpus"] = ("Haftalık · Opus", "Weekly · Opus"),+ ["AiWeeklySonnet"] = ("Haftalık · Sonnet", "Weekly · Sonnet"),+ ["AiHoursWindow"] = ("{0} saat", "{0} hours"),+ ["AiDaysWindow"] = ("{0} gün", "{0} days"),+ ["AiNoData"] = ("Veri yok", "No data"),+ ["AiNoDataHelp"] = ("Claude için Claude Code’da oturum açın; ChatGPT için Codex’i bir kez kullanın. Limitler burada görünür.", "Sign in to Claude Code for Claude, or use Codex once for ChatGPT. Limits will appear here."),+ ["AiClaudeExpired"] = ("Oturum süresi doldu; Claude Code’u bir kez açın.", "Session expired; open Claude Code once."),+ ["AiRateLimited"] = ("Çok sık soruldu; birkaç dakika sonra yenilenecek.", "Asked too often; will refresh in a few minutes."),+ ["AiFetchError"] = ("Kullanım bilgisi alınamadı.", "Couldn’t read usage."),+ ["AiRefresh"] = ("Yenile", "Refresh"),+ ["AiResetsIn"] = ("{0} sonra sıfırlanır ({1})", "Resets in {0} ({1})"),+ ["AiIdle"] = ("Henüz kullanılmadı", "Not used yet"),+ ["AiNoReset"] = ("Sıfırlanma zamanı bilinmiyor", "Reset time unknown"),+ ["AiSoon"] = ("az", "a moment"),+ ["AiDaysHours"] = ("{0} g {1} sa", "{0}d {1}h"),+ ["AiHoursMinutes"] = ("{0} sa {1} dk", "{0}h {1}m"),+ ["AiMinutes"] = ("{0} dk", "{0}m"),+ ["AiUpdated"] = ("Güncelleme {0} · {1}", "Updated {0} · {1}"),+ ["AiSourceClaude"] = ("Claude Code oturumu", "Claude Code session"),+ ["AiSourceCodex"] = ("Codex kayıtları", "Codex logs"),+ ["AiShortHM"] = ("{0}sa {1}dk", "{0}h {1}m"),+ ["AiShortM"] = ("{0}dk", "{0}m"),+ ["AiResetsShort"] = ("{0} sonra sıfırlanır", "resets in {0}"),+ ["AiOutBy"] = ("bu hızla {0} biter", "out by {0} at this pace"),+ ["AiPaceOk"] = ("bu hızla sıfırlanmada ~%{0}", "~{0}% at reset at this pace"),+ ["AiUsageCaption"] = ("Kullanım", "Usage"),+ ["AiThisWeek"] = ("Bu hafta", "This week"),+ ["AiThisPeriod"] = ("Bu dönem", "This period"),+ ["AiFooterNote"] = ("Claude Code ve Codex oturumlarınızdan okunur. Grafik, bu bilgisayarda kaydedilen ölçümlerden çizilir.", "Read from your Claude Code and Codex sign-ins. The chart is drawn from readings saved on this PC."),+ ["QcSound"] = ("Ses", "Sound"),+ ["QcMute"] = ("Sesi kapat / aç", "Mute / unmute"),+ ["QcMuted"] = ("Kapalı", "Muted"),+ ["QcOpenSettings"] = ("Windows ayarlarını aç", "Open Windows settings"),+ ["QcWifiOn"] = ("Wi-Fi açık", "Wi-Fi on"),+ ["QcWifiOff"] = ("Wi-Fi kapalı · açmak için tıklayın", "Wi-Fi off · click to turn on"),+ ["QcBluetoothOn"] = ("Bluetooth açık · kapatmak için tıklayın", "Bluetooth on · click to turn off"),+ ["QcBluetoothOff"] = ("Bluetooth kapalı · açmak için tıklayın", "Bluetooth off · click to turn on"),+ ["QcWifiOffShort"] = ("Wi-Fi kapalı", "Wi-Fi off"),+ ["QcBluetoothOnShort"] = ("Bluetooth açık", "Bluetooth on"),+ ["QcBluetoothOffShort"] = ("Bluetooth kapalı", "Bluetooth off"),+ ["QcBatteryTitle"] = ("Pil ve güç", "Battery and power"),+ ["QcOnBattery"] = ("Pille çalışıyor", "On battery"),+ ["QcSaverIsOn"] = ("Enerji tasarrufu açık", "Energy saver is on"),+ ["QcSaverIsOff"] = ("Enerji tasarrufu kapalı", "Energy saver is off"),+ ["QcPowerMode"] = ("Güç modu", "Power mode"),+ ["QcModeSaver"] = ("Verimli", "Efficiency"),+ ["QcModeBalanced"] = ("Dengeli", "Balanced"),+ ["QcModePerformance"] = ("Performans", "Performance"),+ ["QcPowerModeUnavailable"] = ("Bu bilgisayar güç modu değiştirmeyi desteklemiyor.", "This PC doesn't support changing the power mode."),+ ["QcPowerModeDenied"] = ("Windows güç modunu değiştirmeye izin vermedi.", "Windows didn't allow changing the power mode."),+ ["QcEnergySaver"] = ("Enerji tasarrufu", "Energy saver"),+ ["QcEnergySaverHint"] = ("Windows enerji tasarrufunu yalnızca kendi Ayarlar sayfasından açtırıyor; tıklayınca o sayfa açılır.", "Windows only lets its own Settings page switch energy saver; click to open it."),+ ["QcPowerSettings"] = ("Güç ve pil ayarları", "Power and battery settings"),+ ["QcConnections"] = ("Bağlantılar", "Connections"),+ ["QcNotConnected"] = ("Bağlı değil", "Not connected"),+ ["QcOn"] = ("Açık", "On"),+ ["QcOff"] = ("Kapalı", "Off"),+ ["QcTurnOn"] = ("Aç", "Turn on"),+ ["QcTurnOff"] = ("Kapat", "Turn off"),+ ["QcNoRadios"] = ("Bu bilgisayarda Wi-Fi veya Bluetooth bulunamadı.", "No Wi-Fi or Bluetooth found on this PC."),+ ["QcRadioDenied"] = ("Windows bu değişikliğe izin vermedi. Ayarlar › Gizlilik ve güvenlik › Radyolar bölümünden uygulamaların radyoları denetlemesine izin verin.", "Windows didn't allow this change. Allow apps to control radios in Settings › Privacy & security › Radios."),+ ["QcBattery"] = ("Pil %{0}", "Battery {0}%"),+ ["QcCharging"] = ("şarj oluyor", "charging"),+ ["QcPluggedIn"] = ("prize takılı", "plugged in"),+ ["QcRemaining"] = ("{0} sa {1} dk kaldı", "{0}h {1}m left"),+ ["Startup"] = ("Windows ile başlat", "Start with Windows"),+ ["StartupDescription"] = ("Oturum açtığında QiDock otomatik başlasın.", "Launch QiDock when you sign in."),+ ["Animations"] = ("Animasyonlar", "Animations"),+ ["AnimationsDescription"] = ("Simge büyütme, açılış ve geçiş hareketleri.", "Icon magnification, launch, and transition motion."),+ ["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"),+ ["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."),+ ["Theme"] = ("Açık / koyu", "Light / dark"),+ ["SurfaceOpacity"] = ("Yüzey opaklığı", "Surface opacity"),+ ["SurfaceOpacityHelp"] = ("Ayarlar, dock ve menülerin arka plan opaklığı.", "Background opacity for settings, the dock, and menus."),+ ["OpacityPercent"] = ("%{0}", "{0}%"),+ ["Minimize"] = ("Küçült", "Minimize"),+ ["Maximize"] = ("Büyüt", "Maximize"),+ ["Restore"] = ("Önceki boyut", "Restore"),+ ["ThemeDescription"] = ("Dock, menüler ve ayarların renkleri.", "Colors for the dock, menus, and settings."),+ ["Dark"] = ("Koyu", "Dark"),+ ["Light"] = ("Açık", "Light"),+ ["Language"] = ("Dil", "Language"),+ ["LanguageDescription"] = ("QiDock arayüzünün dili.", "Language used by the QiDock interface."),+ ["Position"] = ("Dock konumu", "Dock position"),+ ["PositionDescription"] = ("Simgelerin ekranın alt kenarındaki hizası.", "Align icons along the bottom of your screen."),+ ["Left"] = ("Sol", "Left"), ["Center"] = ("Orta", "Center"), ["Right"] = ("Sağ", "Right"),+ ["AutoHide"] = ("Otomatik gizle", "Auto-hide"),+ ["AutoHideDescription"] = ("Pencereler dock’un üzerine geldiğinde veya fare ayrıldığında dock’u gizle.", "Hide the dock when windows overlap or when the mouse leaves."),+ ["AutoHideDisabled"] = ("Kapalı", "Off"),+ ["AutoHideSmart"] = ("Pencere üstüne gelince", "When a window overlaps"),+ ["AutoHideAlways"] = ("Her zaman (alt kenara gelince çıkar)", "Always (shows at the bottom edge)"),+ ["Apply"] = ("Uygula", "Apply"),+ ["SettingsSaved"] = ("Ayarlar kaydedildi.", "Settings saved."),+ ["Close"] = ("Kapat", "Close"),+ ["Exit"] = ("QiDock’dan çık", "Quit QiDock"),+ ["OpenItem"] = ("Aç", "Open"),+ ["OpenApplication"] = ("Uygulamayı aç", "Open application"),+ ["ApplicationCommands"] = ("Uygulama komutları", "Application commands"),+ ["WindowCommands"] = ("Pencere komutları", "Window commands"),+ ["Pin"] = ("Dock’ta tut", "Keep in dock"),+ ["Unpin"] = ("Dock’tan kaldır", "Remove from dock"),+ ["CloseApplication"] = ("Uygulamayı kapat", "Close application"),+ ["Terminate"] = ("Süreci sonlandır…", "End process…"),+ ["Start"] = ("Başlat", "Start"),+ ["ActivateWindow"] = ("Pencereyi öne getir", "Bring window to front"),+ ["MinimizeWindow"] = ("Pencereyi küçült", "Minimize window"),+ ["Tasks"] = ("Görevler", "Tasks"),+ ["PinnedDestinations"] = ("Sabitlenenler", "Pinned"),+ ["Recent"] = ("Son kullanılanlar", "Recent"),+ ["Frequent"] = ("Sık kullanılanlar", "Frequent"),+ ["StartupReadError"] = ("Windows başlangıç tercihi okunamadı. Erişim izinlerini denetleyin.", "Cannot read the Windows startup preference. Check access permissions."),+ ["StartupWriteError"] = ("Windows başlangıç tercihi kaydedilemedi. Erişim izinlerini denetleyin.", "Cannot save the Windows startup preference. Check access permissions."),+ ["StartupPathError"] = ("Başlangıç kaydı için geçerli bir QiDock.exe yolu gerekiyor.", "A valid QiDock.exe path is required for startup registration."),+ ["DiscardTitle"] = ("Kaydedilmemiş değişiklikler", "Unsaved changes"),+ ["DiscardChanges"] = ("Uygulanmamış değişiklikler var. Kaydetmeden kapatılsın mı?", "You have unapplied changes. Close without saving?"),+ ["StartupRestoreError"] = ("Başlangıç tercihi de geri alınamadı. Windows başlangıç ayarlarını denetleyin.", "The startup preference could not be restored either. Check Windows startup settings."),+ ["AlreadyRunning"] = ("QiDock zaten çalışıyor.", "QiDock is already running."),+ ["CloseWindow"] = ("Pencereyi kapat", "Close window"),+ ["PreviewUnavailable"] = ("Önizleme kullanılamıyor", "Preview unavailable"),+ ["TasksLoading"] = ("Görevler yükleniyor…", "Loading tasks…"),+ ["TasksEmpty"] = ("Bu uygulama görev listesi sunmuyor", "This application has no task list"),+ ["TasksIdentityUnavailable"] = ("Uygulamanın görev listesi eşleştirilemedi", "Cannot match this application's task list"),+ ["TasksUnsupported"] = ("Görev listesi bu Windows sürümünde desteklenmiyor", "Task lists are not supported on this Windows version"),+ ["TasksReadError"] = ("Görev listesi okunamadı; menüyü yeniden açın", "Cannot read the task list; reopen the menu"),+ ["TasksTimeout"] = ("Görev listesi zamanında yanıt vermedi", "The task list did not respond in time"),+ ["TasksServiceError"] = ("Windows görev hizmeti başlatılamadı", "Cannot start the Windows task service"),+ ["SkippedPins"] = ("Windows görev çubuğundaki {0} kısayol desteklenmedi veya okunamadı; diğerleri içe aktarıldı.", "{0} Windows taskbar shortcuts were unsupported or unreadable; the others were imported."),+ ["TerminateTitle"] = ("QiDock · Süreci sonlandır", "QiDock · End process"),+ ["TerminatePrompt"] = ("{0} uygulamasına ait {1} süreç zorla sonlandırılacak. Kaydedilmemiş çalışmalar kaybolabilir. Devam edilsin?", "Force quit {1} processes belonging to {0}? Unsaved work may be lost. Continue?")+ };++ private static readonly IReadOnlyDictionary<string, string> ErrorTranslations = new Dictionary<string, string>+ {+ ["Dock penceresi Windows'a bağlanamadı."] = "Cannot connect the dock window to Windows.",+ ["QiDock Alt+Tab listesinden çıkarılamadı."] = "Cannot exclude QiDock from Alt+Tab.",+ ["Windows uygulama bildirimlerini dinleyemedi; bildirim rozeti kullanılamıyor."] = "Cannot listen for Windows application alerts; notification indicators are unavailable.",+ ["Dock penceresi hazır olmadan görev çubuğu modu açılamaz."] = "The dock window must be ready before taskbar replacement can start.",+ ["Windows Başlat menüsüne açılma isteği gönderilemedi."] = "Cannot request the Windows Start menu.",+ ["Pencereyi öne getirme veya küçültme isteği tamamlanamadı. Windows odağı engellemiş olabilir."] = "Cannot activate or minimize the window. Windows may have blocked focus.",+ ["Uygulama dosyası bulunamadı. Windows görev çubuğundaki kısayolu güncelleyin."] = "Application file not found. Update its Windows taskbar shortcut.",+ ["Uygulama Windows tarafından başlatılamadı."] = "Windows could not start the application.",+ ["Uygulama başlatma isteği tamamlanamadı."] = "The application launch request could not be completed.",+ ["Uygulamayı başlatmak için erişim izni yok."] = "Permission to start the application was denied.",+ ["Uygulama dosyasına erişilemedi."] = "Cannot access the application file.",+ ["Önizleme penceresi etkinleştirilemedi. Windows odağı engellemiş olabilir."] = "Cannot activate the previewed window. Windows may have blocked focus.",+ ["Önizlenen pencereye kapatma isteği gönderilemedi."] = "Cannot send a close request to the previewed window.",+ ["Uygulama görevi çalıştırılamadı. Menüyü yeniden açıp deneyin."] = "Cannot run the application task. Reopen the menu and try again.",+ ["Uygulama komutu çalıştırılamadı; pencereyi veya menüyü yeniden açın."] = "Cannot run the application command; reopen the window or menu.",+ ["Uygulama sabitlenemedi."] = "Cannot pin the application.",+ ["Uygulamaya normal kapanma isteği gönderilemedi. Zorla kapatmak için süreç sonlandırma seçeneğini kullanın."] = "Cannot request a normal application close. Use End process to force quit.",+ ["Bazı uygulama süreçlerine normal kapanma isteği gönderilemedi."] = "Cannot send a normal close request to some application processes.",+ ["Uygulamanın çalışan süreci bulunamadı."] = "No running application process was found.",+ ["Uygulama süreçlerine erişilemiyor; uygulama yöneticisi iznini denetleyin."] = "Cannot access the application processes; check administrator permissions.",+ ["Uygulama süreçleri sonlandırılamadı. Yetkiyi ve uygulamanın tekrar başlamadığını denetleyin."] = "Cannot end the application processes. Check permissions and whether the application restarted.",+ ["Bazı uygulama süreçleri sonlandırılamadı."] = "Some application processes could not be ended.",+ ["Windows görev çubuğu geri yüklenemedi. Uygulama açık bırakıldı."] = "Cannot restore the Windows taskbar. QiDock remains open.",+ ["Dock ayarları geçersiz. Dosyayı düzeltin veya silip uygulamayı yeniden başlatın."] = "Dock settings are invalid. Correct or delete the settings file and restart.",+ ["Dock ayarları okunamadı. JSON biçimini düzeltin veya dosyayı silip yeniden başlatın."] = "Cannot read dock settings. Correct the JSON or delete the settings file and restart.",+ ["Dock ayarları diskten okunamadı."] = "Cannot read dock settings from disk.",+ ["Dock ayarlarına erişim izni yok."] = "Permission to read dock settings was denied.",+ ["Ayar değerleri geçersiz."] = "Settings contain invalid values.",+ ["Dock ayarları için kayıt yolu oluşturulamadı."] = "Cannot create a location for dock settings.",+ ["Dock ayarları diske kaydedilemedi."] = "Cannot save dock settings to disk.",+ ["Dock ayarlarına yazma izni yok."] = "Permission to write dock settings was denied.",+ ["Pencere başlığı değişiklikleri dinlenemedi."] = "Cannot listen for window title changes.",+ ["Görev çubuğu kurtarma kaydı bozuk. Windows ayarlarını elle denetleyin."] = "The taskbar recovery record is invalid. Check Windows taskbar settings manually.",+ ["Görev çubuğu kurtarma kaydı okunamadı."] = "Cannot read the taskbar recovery record.",+ ["Görev çubuğu kurtarma kaydına erişim izni yok."] = "Permission to access the taskbar recovery record was denied.",+ ["Görev çubuğu ayarı değiştirilmedi; kurtarma kaydı yazılamadı."] = "The Windows taskbar was left unchanged because its recovery record could not be saved.",+ ["Görev çubuğu ayarı değiştirilmedi; kurtarma kaydına yazma izni yok."] = "The Windows taskbar was left unchanged because permission to save its recovery record was denied.",+ ["Windows görev çubuğunun kenar tetiklemesi kapatılamadı."] = "Cannot disable the Windows taskbar edge trigger.",+ ["Windows görev çubuğu gizlenemedi."] = "Cannot hide the Windows taskbar.",+ ["Windows görev çubuğu geri yükleme işlemi devam ediyor."] = "The Windows taskbar is still being restored.",+ ["Windows görev çubuğu geri yüklenemedi. Kapatmayı yeniden deneyin veya Windows görev çubuğu ayarlarını denetleyin."] = "Cannot restore the Windows taskbar. Try closing again or check Windows taskbar settings.",+ ["Ekran boyutları alınamadı."] = "Cannot read display dimensions.",+ ["QiDock ekranın alt kenarına yerleştirilemedi."] = "Cannot position QiDock along the bottom of the screen.",+ ["Windows görev çubuğunun otomatik açılması yeniden etkinleşti."] = "Windows taskbar auto-hide activation was enabled again.",+ ["Windows görev çubuğu yeniden gizlenemedi."] = "Cannot hide the Windows taskbar again.",+ ["Görev çubuğu kurtarma kaydı için yol oluşturulamadı."] = "Cannot create a location for the taskbar recovery record.",+ ["Görev çubuğu kurtarma kaydı geçersiz."] = "The taskbar recovery record is invalid.",+ ["Görev çubuğu ayarı geri yüklendi ancak kurtarma kaydı silinemedi."] = "The Windows taskbar was restored, but its recovery record could not be removed.",+ ["Görev çubuğu ayarı geri yüklendi ancak kurtarma kaydını silme izni yok."] = "The Windows taskbar was restored, but permission to remove its recovery record was denied.",+ ["Windows görev çubuğu kısayol klasörü okunamadı."] = "Cannot read the Windows taskbar shortcut folder.",+ ["Windows görev çubuğu kısayol klasörüne erişim izni yok."] = "Permission to access the Windows taskbar shortcut folder was denied.",+ ["Windows kısayol hizmeti başlatılamadı; görev çubuğu uygulamaları içe aktarılamadı."] = "Cannot start the Windows shortcut service; taskbar applications could not be imported.",+ ["Windows kısayol hizmeti durdu; görev çubuğu uygulamalarının bir bölümü içe aktarılamadı."] = "The Windows shortcut service stopped; some taskbar applications could not be imported.",+ ["Windows görev çubuğu sabitleme klasörü oluşturulamadı."] = "Cannot create the Windows taskbar pin folder.",+ ["Windows kısayol hizmeti başlatılamadı; sabitleme oluşturulamadı."] = "Cannot start the Windows shortcut service; the pin could not be created.",+ ["Kısayol nesnesi oluşturulamadı."] = "Cannot create a shortcut object.",+ ["Uygulama Windows görev çubuğuna sabitlenemedi."] = "Cannot pin the application to the Windows taskbar.",+ ["Kısayol Windows görev çubuğu sabitleme klasöründe değil."] = "The shortcut is outside the Windows taskbar pin folder.",+ ["Uygulama Windows görev çubuğu sabitlerinden kaldırılamadı."] = "Cannot remove the application from Windows taskbar pins.",+ ["Görev çubuğu sabitini kaldırmak için erişim izni yok."] = "Permission to remove the taskbar pin was denied."+ };++ private volatile AppLanguage _language;+ public static UiText Current { get; } = new();+ public AppLanguage Language => _language;+ public event PropertyChangedEventHandler? PropertyChanged;+ public string this[string key]+ {+ get+ {+ // A missing text must never take a window down with it: show the key and flag it in debug builds.+ if (!Entries.TryGetValue(key, out var entry))+ {+ System.Diagnostics.Debug.Fail("Missing UI text: " + key);+ return key;+ }+ return _language == AppLanguage.English ? entry.English : entry.Turkish;+ }+ }+ public static string Get(string key) => Current[key];+ public static string Format(string key, params object[] values) => string.Format(+ System.Globalization.CultureInfo.GetCultureInfo(Current._language == AppLanguage.English ? "en-US" : "tr-TR"), Get(key), values);++ // Preserve externally supplied errors when they are not one of our own localized messages.+ public static string LocalizeError(string message) => Current._language == AppLanguage.English+ && ErrorTranslations.TryGetValue(message, out var translated) ? translated : message;+ public void SetLanguage(AppLanguage language)+ {+ if (_language == language) return;+ _language = language;+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));+ }+}++[MarkupExtensionReturnType(typeof(string))]+public sealed class LocExtension(string key) : MarkupExtension+{+ public override object ProvideValue(IServiceProvider serviceProvider) =>+ new Binding($"[{key}]") { Source = UiText.Current, Mode = BindingMode.OneWay }.ProvideValue(serviceProvider);+}diff --git a/Services/Widgets/AiUsageHistory.cs b/Services/Widgets/AiUsageHistory.csnew file mode 100644index 0000000..6f3b000--- /dev/null+++ b/Services/Widgets/AiUsageHistory.cs@@ -0,0 +1,85 @@+using System.IO;+using System.Text.Json;++namespace QiDock.Services.Widgets;++/// <summary>One recorded reading of a weekly limit.</summary>+public sealed record UsageSample(DateTime At, double Percent);++/// <summary>+/// Keeps a small local history of weekly usage so the popup can draw this week's curve and+/// project when the limit would run out. Only percentages and times are stored, never tokens.+/// </summary>+public sealed class AiUsageHistory+{+ private static readonly TimeSpan MinimumSpacing = TimeSpan.FromMinutes(10);+ private static readonly TimeSpan KeepFor = TimeSpan.FromDays(9);++ private readonly string _path;+ private Dictionary<string, List<UsageSample>> _samples = new(StringComparer.Ordinal);+ private bool _loaded;++ public AiUsageHistory(string? path = null)+ {+ _path = path ?? Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),+ "QiDock",+ "ai-usage-history.json");+ }++ public void Record(string key, double percent, DateTime at)+ {+ EnsureLoaded();+ if (!_samples.TryGetValue(key, out var list))+ {+ list = [];+ _samples[key] = list;+ }++ var changed = list.Count == 0 || at - list[^1].At >= MinimumSpacing || Math.Abs(list[^1].Percent - percent) >= 0.5;+ if (!changed) return;+ list.Add(new UsageSample(at, percent));+ list.RemoveAll(sample => at - sample.At > KeepFor);+ Save();+ }++ /// <summary>Samples between <paramref name="from"/> and now, oldest first.</summary>+ public IReadOnlyList<UsageSample> Since(string key, DateTime from)+ {+ EnsureLoaded();+ return _samples.TryGetValue(key, out var list)+ ? list.Where(sample => sample.At >= from).OrderBy(sample => sample.At).ToList()+ : [];+ }++ private void EnsureLoaded()+ {+ if (_loaded) return;+ _loaded = true;+ try+ {+ if (!File.Exists(_path)) return;+ var data = JsonSerializer.Deserialize<Dictionary<string, List<UsageSample>>>(File.ReadAllText(_path));+ if (data is not null) _samples = new Dictionary<string, List<UsageSample>>(data, StringComparer.Ordinal);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)+ {+ _samples = new Dictionary<string, List<UsageSample>>(StringComparer.Ordinal);+ }+ }++ private void Save()+ {+ try+ {+ Directory.CreateDirectory(Path.GetDirectoryName(_path)!);+ var temporary = _path + ".tmp";+ File.WriteAllText(temporary, JsonSerializer.Serialize(_samples));+ File.Move(temporary, _path, true);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ System.Diagnostics.Trace.TraceWarning("AI usage history not saved: {0}", ex.Message);+ }+ }+}diff --git a/Services/Widgets/AiUsageService.cs b/Services/Widgets/AiUsageService.csnew file mode 100644index 0000000..ae9368d--- /dev/null+++ b/Services/Widgets/AiUsageService.cs@@ -0,0 +1,308 @@+using System.Globalization;+using System.IO;+using System.Net;+using System.Net.Http;+using System.Net.Http.Headers;+using System.Text;+using System.Text.Json;++namespace QiDock.Services.Widgets;++/// <param name="Length">How long the window lasts (5 hours, 7 days…) when known; used for pace projections.</param>+/// <param name="Key">Stable id for the usage history (labels are localized).</param>+public sealed record UsageWindow(string Label, double UsedPercent, DateTime? ResetsAt, TimeSpan? Length = null, string? Key = null)+{+ public DateTime? StartsAt => ResetsAt is { } reset && Length is { } length ? reset - length : null;+}++public sealed record ProviderUsage(+ string Provider,+ string DisplayName,+ string? Plan,+ IReadOnlyList<UsageWindow> Windows,+ DateTime UpdatedAt,+ string? Error);++/// <summary>+/// Usage limits for AI subscriptions that are already signed in on this PC.+/// Claude: reads Claude Code's OAuth session and asks Anthropic's usage endpoint (the same one Claude Code's /usage uses).+/// ChatGPT: reads the latest rate-limit snapshot Codex CLI writes into its local session logs (no network).+/// Tokens are only read from disk and sent to their own provider; they are never stored or logged.+/// </summary>+public sealed class AiUsageService+{+ public const string ClaudeId = "claude";+ public const string CodexId = "chatgpt";++ private static readonly TimeSpan ClaudeMinimumInterval = TimeSpan.FromMinutes(2);+ private ProviderUsage? _claude;+ private DateTime _claudeFetchedAt = DateTime.MinValue;+ private DateTime _claudeBackoffUntil = DateTime.MinValue;++ public async Task<IReadOnlyList<ProviderUsage>> FetchAsync(bool force, CancellationToken token)+ {+ var results = new List<ProviderUsage>();+ var claude = await GetClaudeAsync(force, token).ConfigureAwait(false);+ if (claude is not null) results.Add(claude);+ var codex = await Task.Run(ReadCodex, token).ConfigureAwait(false);+ if (codex is not null) results.Add(codex);+ return results;+ }++ // ---- Claude ----------------------------------------------------------------------------++ private async Task<ProviderUsage?> GetClaudeAsync(bool force, CancellationToken token)+ {+ var now = DateTime.Now;+ if (_claude is not null && (now < _claudeBackoffUntil || (!force && now - _claudeFetchedAt < ClaudeMinimumInterval)+ || (force && now - _claudeFetchedAt < TimeSpan.FromSeconds(20))))+ return _claude;++ var credentials = ReadClaudeCredentials();+ if (credentials is null) return null;+ var (accessToken, expiresAt, plan) = credentials.Value;+ if (expiresAt is { } expiry && expiry <= DateTime.Now)+ {+ _claude = new ProviderUsage(ClaudeId, "Claude", plan, _claude?.Windows ?? [], now, UiText.Get("AiClaudeExpired"));+ _claudeFetchedAt = now;+ return _claude;+ }++ try+ {+ using var request = new HttpRequestMessage(HttpMethod.Get, "https://api.anthropic.com/api/oauth/usage");+ request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);+ request.Headers.Add("anthropic-beta", "oauth-2025-04-20");+ using var response = await WidgetHttp.Client.SendAsync(request, token).ConfigureAwait(false);+ if (response.StatusCode == HttpStatusCode.TooManyRequests)+ {+ _claudeBackoffUntil = now.AddMinutes(10);+ _claude ??= new ProviderUsage(ClaudeId, "Claude", plan, [], now, UiText.Get("AiRateLimited"));+ return _claude;+ }+ if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)+ {+ _claude = new ProviderUsage(ClaudeId, "Claude", plan, _claude?.Windows ?? [], now, UiText.Get("AiClaudeExpired"));+ _claudeFetchedAt = now;+ return _claude;+ }+ response.EnsureSuccessStatusCode();+ await using var stream = await response.Content.ReadAsStreamAsync(token).ConfigureAwait(false);+ using var json = await JsonDocument.ParseAsync(stream, cancellationToken: token).ConfigureAwait(false);+ var windows = ReadClaudeLimits(json.RootElement);+ if (windows.Count == 0)+ {+ AddClaudeWindow(json.RootElement, "five_hour", UiText.Get("AiSession"), windows);+ AddClaudeWindow(json.RootElement, "seven_day", UiText.Get("AiWeekly"), windows);+ AddClaudeWindow(json.RootElement, "seven_day_opus", UiText.Get("AiWeeklyOpus"), windows, optional: true);+ AddClaudeWindow(json.RootElement, "seven_day_sonnet", UiText.Get("AiWeeklySonnet"), windows, optional: true);+ }+ _claude = new ProviderUsage(ClaudeId, "Claude", plan, windows, now, null);+ _claudeFetchedAt = now;+ }+ catch (OperationCanceledException) when (token.IsCancellationRequested)+ {+ throw;+ }+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException or KeyNotFoundException or InvalidOperationException)+ {+ _claude = new ProviderUsage(ClaudeId, "Claude", plan, _claude?.Windows ?? [], now, UiText.Get("AiFetchError"));+ _claudeFetchedAt = now;+ }++ return _claude;+ }++ /// <summary>+ /// Newer responses carry a "limits" list (session, weekly_all, weekly_scoped per model).+ /// Session and the overall weekly limit come first so the dock tile shows those two.+ /// </summary>+ private static List<UsageWindow> ReadClaudeLimits(JsonElement root)+ {+ var windows = new List<UsageWindow>();+ if (!root.TryGetProperty("limits", out var limits) || limits.ValueKind != JsonValueKind.Array) return windows;+ var scoped = new List<UsageWindow>();+ foreach (var limit in limits.EnumerateArray())+ {+ if (limit.ValueKind != JsonValueKind.Object) continue;+ var kind = limit.TryGetProperty("kind", out var k) && k.ValueKind == JsonValueKind.String ? k.GetString() : null;+ if (!limit.TryGetProperty("percent", out var p) || p.ValueKind != JsonValueKind.Number) continue;+ DateTime? resets = null;+ if (limit.TryGetProperty("resets_at", out var r) && r.ValueKind == JsonValueKind.String+ && DateTimeOffset.TryParse(r.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed))+ resets = parsed.LocalDateTime;+ var percent = Math.Clamp(p.GetDouble(), 0, 100);+ switch (kind)+ {+ case "session":+ windows.Insert(0, new UsageWindow(UiText.Get("AiSession"), percent, resets, TimeSpan.FromHours(5), "session"));+ break;+ case "weekly_all":+ windows.Add(new UsageWindow(UiText.Get("AiWeekly"), percent, resets, TimeSpan.FromDays(7), "weekly"));+ break;+ case "weekly_scoped":+ var model = limit.TryGetProperty("scope", out var scope) && scope.ValueKind == JsonValueKind.Object+ && scope.TryGetProperty("model", out var m) && m.ValueKind == JsonValueKind.Object+ && m.TryGetProperty("display_name", out var name) && name.ValueKind == JsonValueKind.String+ ? name.GetString() : null;+ scoped.Add(new UsageWindow(model is null ? UiText.Get("AiWeekly") : $"{UiText.Get("AiWeekly")} · {model}", percent, resets, TimeSpan.FromDays(7), "weekly-" + (model ?? "scoped")));+ break;+ }+ }+ windows.AddRange(scoped);+ return windows;+ }++ private static void AddClaudeWindow(JsonElement root, string property, string label, List<UsageWindow> windows, bool optional = false)+ {+ if (!root.TryGetProperty(property, out var window) || window.ValueKind != JsonValueKind.Object) return;+ if (!window.TryGetProperty("utilization", out var utilization) || utilization.ValueKind != JsonValueKind.Number) return;+ var used = utilization.GetDouble();+ DateTime? resets = null;+ if (window.TryGetProperty("resets_at", out var reset) && reset.ValueKind == JsonValueKind.String+ && DateTimeOffset.TryParse(reset.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed))+ resets = parsed.LocalDateTime;+ if (optional && used <= 0) return;+ var length = property == "five_hour" ? TimeSpan.FromHours(5) : TimeSpan.FromDays(7);+ var key = property == "five_hour" ? "session" : property == "seven_day" ? "weekly" : property;+ windows.Add(new UsageWindow(label, Math.Clamp(used, 0, 100), resets, length, key));+ }++ private static (string AccessToken, DateTime? ExpiresAt, string? Plan)? ReadClaudeCredentials()+ {+ var directory = Environment.GetEnvironmentVariable("CLAUDE_CONFIG_DIR");+ if (string.IsNullOrWhiteSpace(directory))+ directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".claude");+ var path = Path.Combine(directory, ".credentials.json");+ if (!File.Exists(path)) return null;+ try+ {+ using var json = JsonDocument.Parse(File.ReadAllText(path));+ if (!json.RootElement.TryGetProperty("claudeAiOauth", out var oauth)) return null;+ var accessToken = oauth.TryGetProperty("accessToken", out var t) ? t.GetString() : null;+ if (string.IsNullOrEmpty(accessToken)) return null;+ DateTime? expiresAt = oauth.TryGetProperty("expiresAt", out var e) && e.ValueKind == JsonValueKind.Number+ ? DateTimeOffset.FromUnixTimeMilliseconds(e.GetInt64()).LocalDateTime : null;+ var plan = oauth.TryGetProperty("subscriptionType", out var s) && s.ValueKind == JsonValueKind.String ? s.GetString() : null;+ return (accessToken, expiresAt, Capitalize(plan));+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or InvalidOperationException)+ {+ return null;+ }+ }++ // ---- ChatGPT / Codex ---------------------------------------------------------------------++ private static ProviderUsage? ReadCodex()+ {+ var home = Environment.GetEnvironmentVariable("CODEX_HOME");+ if (string.IsNullOrWhiteSpace(home))+ home = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".codex");+ var sessions = Path.Combine(home, "sessions");+ if (!Directory.Exists(sessions)) return null;++ try+ {+ foreach (var file in NewestSessionFiles(sessions).Take(25))+ {+ var line = FindLastLine(file, "\"rate_limits\"");+ if (line is null) continue;+ using var json = JsonDocument.Parse(line);+ if (FindProperty(json.RootElement, "rate_limits") is not { ValueKind: JsonValueKind.Object } limits) continue;+ var updated = json.RootElement.TryGetProperty("timestamp", out var ts) && ts.ValueKind == JsonValueKind.String+ && DateTimeOffset.TryParse(ts.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.None, out var stamp)+ ? stamp.LocalDateTime : File.GetLastWriteTime(file);++ var windows = new List<UsageWindow>();+ AddCodexWindow(limits, "primary", windows);+ AddCodexWindow(limits, "secondary", windows);+ if (windows.Count == 0) continue;+ var plan = limits.TryGetProperty("plan_type", out var p) && p.ValueKind == JsonValueKind.String ? Capitalize(p.GetString()) : null;+ return new ProviderUsage(CodexId, "ChatGPT", plan, windows, updated, null);+ }+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)+ {+ return new ProviderUsage(CodexId, "ChatGPT", null, [], DateTime.Now, UiText.Get("AiFetchError"));+ }++ return null;+ }++ private static void AddCodexWindow(JsonElement limits, string property, List<UsageWindow> windows)+ {+ if (!limits.TryGetProperty(property, out var window) || window.ValueKind != JsonValueKind.Object) return;+ var used = window.TryGetProperty("used_percent", out var u) && u.ValueKind == JsonValueKind.Number ? u.GetDouble() : 0;+ var minutes = window.TryGetProperty("window_minutes", out var m) && m.ValueKind == JsonValueKind.Number ? m.GetInt32() : 0;+ DateTime? resets = null;+ if (window.TryGetProperty("resets_at", out var r) && r.ValueKind == JsonValueKind.Number)+ resets = DateTimeOffset.FromUnixTimeSeconds(r.GetInt64()).LocalDateTime;+ else if (window.TryGetProperty("resets_in_seconds", out var rs) && rs.ValueKind == JsonValueKind.Number)+ resets = DateTime.Now.AddSeconds(rs.GetDouble());+ // A snapshot taken before the window reset no longer applies.+ if (resets is { } reset && reset <= DateTime.Now) used = 0;+ windows.Add(new UsageWindow(WindowLabel(minutes), Math.Clamp(used, 0, 100), resets is { } r2 && r2 > DateTime.Now ? r2 : null,+ minutes > 0 ? TimeSpan.FromMinutes(minutes) : null, property));+ }++ private static string WindowLabel(int minutes) => minutes switch+ {+ <= 0 => UiText.Get("AiSession"),+ 300 => UiText.Get("AiSession"),+ 10080 => UiText.Get("AiWeekly"),+ >= 40000 and <= 46000 => UiText.Get("AiMonthly"),+ < 1440 => UiText.Format("AiHoursWindow", minutes / 60),+ _ => UiText.Format("AiDaysWindow", minutes / 1440)+ };++ private static IEnumerable<string> NewestSessionFiles(string root)+ {+ // sessions/YYYY/MM/DD/rollout-*.jsonl — walk newest folders first instead of scanning everything.+ foreach (var year in Directory.EnumerateDirectories(root).OrderByDescending(Path.GetFileName, StringComparer.Ordinal))+ foreach (var month in Directory.EnumerateDirectories(year).OrderByDescending(Path.GetFileName, StringComparer.Ordinal))+ foreach (var day in Directory.EnumerateDirectories(month).OrderByDescending(Path.GetFileName, StringComparer.Ordinal))+ foreach (var file in Directory.EnumerateFiles(day, "*.jsonl").OrderByDescending(File.GetLastWriteTimeUtc))+ yield return file;+ }++ private static string? FindLastLine(string path, string marker)+ {+ using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);+ const int chunk = 512 * 1024;+ var start = Math.Max(0, stream.Length - chunk);+ while (true)+ {+ stream.Seek(start, SeekOrigin.Begin);+ var buffer = new byte[stream.Length - start];+ stream.ReadExactly(buffer);+ var text = Encoding.UTF8.GetString(buffer);+ var lines = text.Split('\n');+ for (var i = lines.Length - 1; i >= (start == 0 ? 0 : 1); i--)+ if (lines[i].Contains(marker, StringComparison.Ordinal)) return lines[i];+ if (start == 0 || stream.Length - start > 16 * chunk) return null;+ start = Math.Max(0, start - chunk * 4);+ }+ }++ private static JsonElement? FindProperty(JsonElement element, string name)+ {+ if (element.ValueKind == JsonValueKind.Object)+ {+ foreach (var property in element.EnumerateObject())+ {+ if (property.NameEquals(name)) return property.Value;+ if (FindProperty(property.Value, name) is { } nested) return nested;+ }+ }+ else if (element.ValueKind == JsonValueKind.Array)+ {+ foreach (var item in element.EnumerateArray())+ if (FindProperty(item, name) is { } nested) return nested;+ }+ return null;+ }++ private static string? Capitalize(string? value) =>+ string.IsNullOrWhiteSpace(value) ? null : char.ToUpperInvariant(value[0]) + value[1..];+}diff --git a/Services/Widgets/AudioSessions.cs b/Services/Widgets/AudioSessions.csnew file mode 100644index 0000000..c43d20a--- /dev/null+++ b/Services/Widgets/AudioSessions.cs@@ -0,0 +1,176 @@+using System.Diagnostics;+using System.Runtime.InteropServices;++namespace QiDock.Services.Widgets;++/// <summary>+/// Per-app volume through Core Audio sessions on the default playback device. Sessions of the+/// same app (browsers open several) are grouped into one entry. Call <see cref="Dispose"/> when+/// the list is no longer shown; nothing here runs in the background.+/// </summary>+public sealed class AudioSessions : IDisposable+{+ private static readonly Guid SessionManagerId = new("77AA99A0-1BD6-484F-8BC7-2C654C9A9B6F");+ private readonly List<object> _comObjects = [];++ public sealed class App+ {+ internal readonly List<ISimpleAudioVolume> Volumes = [];+ public required string Name { get; init; }+ public string? ExecutablePath { get; init; }+ public bool Playing { get; internal set; }++ public float Volume+ {+ get+ {+ foreach (var volume in Volumes)+ if (volume.GetMasterVolume(out var level) == 0) return level;+ return 0;+ }+ set+ {+ var context = AudioEndpoint.OwnContext;+ foreach (var volume in Volumes) volume.SetMasterVolume(Math.Clamp(value, 0f, 1f), ref context);+ }+ }++ public bool Muted+ {+ get => Volumes.Count > 0 && Volumes[0].GetMute(out var muted) == 0 && muted;+ set+ {+ var context = AudioEndpoint.OwnContext;+ foreach (var volume in Volumes) volume.SetMute(value, ref context);+ }+ }+ }++ public IReadOnlyList<App> Read()+ {+ var apps = new Dictionary<string, App>(StringComparer.OrdinalIgnoreCase);+ try+ {+ var enumerator = (IMMDeviceEnumerator)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E"), true)!)!;+ _comObjects.Add(enumerator);+ if (enumerator.GetDefaultAudioEndpoint(0, 1, out var device) != 0 || device is null) return [];+ _comObjects.Add(device);+ var iid = SessionManagerId;+ if (device.Activate(ref iid, 0x17, 0, out var managerObject) != 0) return [];+ var manager = (IAudioSessionManager2)managerObject;+ _comObjects.Add(manager);+ if (manager.GetSessionEnumerator(out var sessions) != 0 || sessions is null) return [];+ _comObjects.Add(sessions);+ sessions.GetCount(out var count);+ for (var index = 0; index < count; index++)+ {+ if (sessions.GetSession(index, out var control) != 0 || control is null) continue;+ _comObjects.Add(control);+ if (control is not IAudioSessionControl2 control2 || control2.IsSystemSoundsSession() == 0) continue;+ control2.GetState(out var state);+ if (state == 2 /* expired */) continue;+ control2.GetProcessId(out var processId);+ if (processId == 0 || control is not ISimpleAudioVolume volume) continue;+ var (name, path) = Describe((int)processId);+ if (name is null) continue;+ if (!apps.TryGetValue(name, out var app))+ {+ app = new App { Name = name, ExecutablePath = path };+ apps[name] = app;+ }+ app.Volumes.Add(volume);+ if (state == 1 /* active */) app.Playing = true;+ }+ }+ catch (Exception ex) when (ex is COMException or InvalidCastException)+ {+ Trace.TraceWarning("Audio sessions unavailable: {0}", ex.Message);+ }+ return apps.Values.OrderByDescending(a => a.Playing).ThenBy(a => a.Name, StringComparer.CurrentCultureIgnoreCase).ToList();+ }++ private static (string? Name, string? Path) Describe(int processId)+ {+ try+ {+ using var process = Process.GetProcessById(processId);+ string? path = null;+ try { path = process.MainModule?.FileName; }+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException) { }+ var name = process.ProcessName;+ if (path is not null)+ {+ var description = FileVersionInfo.GetVersionInfo(path).FileDescription;+ if (!string.IsNullOrWhiteSpace(description) && description.Length <= 40) name = description.Trim();+ }+ return (name, path);+ }+ catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)+ {+ return (null, null);+ }+ }++ public void Dispose()+ {+ foreach (var item in _comObjects)+ if (Marshal.IsComObject(item)) Marshal.ReleaseComObject(item);+ _comObjects.Clear();+ }++ [ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IMMDeviceEnumerator+ {+ [PreserveSig] int EnumAudioEndpoints(int dataFlow, int stateMask, out nint devices);+ [PreserveSig] int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice device);+ }++ [ComImport, Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IMMDevice+ {+ [PreserveSig] int Activate(ref Guid iid, int clsCtx, nint activationParams, [MarshalAs(UnmanagedType.IUnknown)] out object instance);+ }++ [ComImport, Guid("77AA99A0-1BD6-484F-8BC7-2C654C9A9B6F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IAudioSessionManager2+ {+ [PreserveSig] int GetAudioSessionControl(nint sessionGuid, int flags, out nint control);+ [PreserveSig] int GetSimpleAudioVolume(nint sessionGuid, int flags, out nint volume);+ [PreserveSig] int GetSessionEnumerator(out IAudioSessionEnumerator enumerator);+ }++ [ComImport, Guid("E2F5BB11-0570-40CA-ACDD-3AA01277DEE8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IAudioSessionEnumerator+ {+ [PreserveSig] int GetCount(out int count);+ [PreserveSig] int GetSession(int index, [MarshalAs(UnmanagedType.IUnknown)] out object session);+ }++ [ComImport, Guid("BFB7FF88-7239-4FC9-8FA2-07C950BE9C6D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IAudioSessionControl2+ {+ [PreserveSig] int GetState(out int state);+ [PreserveSig] int GetDisplayName(out nint name);+ [PreserveSig] int SetDisplayName(nint name, nint context);+ [PreserveSig] int GetIconPath(out nint path);+ [PreserveSig] int SetIconPath(nint path, nint context);+ [PreserveSig] int GetGroupingParam(out Guid grouping);+ [PreserveSig] int SetGroupingParam(nint grouping, nint context);+ [PreserveSig] int RegisterAudioSessionNotification(nint client);+ [PreserveSig] int UnregisterAudioSessionNotification(nint client);+ [PreserveSig] int GetSessionIdentifier(out nint id);+ [PreserveSig] int GetSessionInstanceIdentifier(out nint id);+ [PreserveSig] int GetProcessId(out uint processId);+ [PreserveSig] int IsSystemSoundsSession();+ [PreserveSig] int SetDuckingPreference([MarshalAs(UnmanagedType.Bool)] bool optOut);+ }++ [ComImport, Guid("87CE5498-68D6-44E5-9215-6DA47EF883D8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ internal interface ISimpleAudioVolume+ {+ [PreserveSig] int SetMasterVolume(float level, ref Guid context);+ [PreserveSig] int GetMasterVolume(out float level);+ [PreserveSig] int SetMute([MarshalAs(UnmanagedType.Bool)] bool mute, ref Guid context);+ [PreserveSig] int GetMute([MarshalAs(UnmanagedType.Bool)] out bool mute);+ }+}diff --git a/Services/Widgets/CalendarFeedService.cs b/Services/Widgets/CalendarFeedService.csnew file mode 100644index 0000000..967f2ad--- /dev/null+++ b/Services/Widgets/CalendarFeedService.cs@@ -0,0 +1,402 @@+using System.Globalization;+using System.Net.Http;+using System.Net.Http.Headers;+using System.Text;++namespace QiDock.Services.Widgets;++public sealed record CalendarOccurrence(string Title, string? Location, DateTime Start, DateTime End, bool AllDay);++/// <summary>+/// Reads an iCalendar (.ics) feed, such as Google Calendar's "secret address in iCal format",+/// and expands the common recurrence rules into concrete occurrences.+/// </summary>+public sealed class CalendarFeedService+{+ private const int MaxOccurrencesPerEvent = 800;+ private List<IcsEvent> _events = [];++ public bool HasFeed { get; private set; }+ public DateTime? LastUpdated { get; private set; }+ public string? LastError { get; private set; }++ public async Task RefreshAsync(string? feedUrl, CancellationToken token)+ {+ if (string.IsNullOrWhiteSpace(feedUrl))+ {+ HasFeed = false;+ _events = [];+ LastError = null;+ return;+ }++ HasFeed = true;+ try+ {+ var url = feedUrl.Trim();+ if (url.StartsWith("webcal://", StringComparison.OrdinalIgnoreCase)) url = "https://" + url[9..];+ using var request = new HttpRequestMessage(HttpMethod.Get, url);+ request.Headers.Accept.Clear();+ request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/calendar"));+ using var response = await WidgetHttp.Client.SendAsync(request, token).ConfigureAwait(false);+ response.EnsureSuccessStatusCode();+ var text = await response.Content.ReadAsStringAsync(token).ConfigureAwait(false);+ _events = Parse(text);+ LastUpdated = DateTime.Now;+ LastError = null;+ }+ catch (OperationCanceledException) when (token.IsCancellationRequested)+ {+ throw;+ }+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or FormatException or UriFormatException or InvalidOperationException)+ {+ LastError = UiText.Get("CalendarFeedError");+ }+ }++ public IReadOnlyList<CalendarOccurrence> GetOccurrences(DateTime from, DateTime to)+ {+ var result = new List<CalendarOccurrence>();+ var overrides = _events.Where(e => e.RecurrenceId is not null)+ .Select(e => (e.Uid, e.RecurrenceId!.Value))+ .ToHashSet();++ foreach (var item in _events)+ {+ foreach (var start in Expand(item, from, to))+ {+ if (item.RecurrenceId is null && item.Rule is not null && overrides.Contains((item.Uid, start))) continue;+ var end = start + item.Duration;+ if (end <= from || start >= to) continue;+ result.Add(new CalendarOccurrence(item.Summary, item.Location, start, end, item.AllDay));+ }+ }++ result.Sort((a, b) => a.AllDay != b.AllDay ? (a.AllDay ? -1 : 1) : a.Start.CompareTo(b.Start));+ return result;+ }++ private static IEnumerable<DateTime> Expand(IcsEvent item, DateTime from, DateTime to)+ {+ if (item.Rule is not { } rule)+ {+ yield return item.Start;+ yield break;+ }++ var produced = 0;+ var yielded = 0;+ var interval = Math.Max(1, rule.Interval);+ var limit = rule.Until ?? DateTime.MaxValue;+ var windowEnd = to < limit ? to : limit;++ IEnumerable<DateTime> Candidates()+ {+ var anchor = item.Start;+ for (var period = 0; period < 20000; period++)+ {+ switch (rule.Frequency)+ {+ case "DAILY":+ yield return anchor.AddDays(period * interval);+ break;+ case "WEEKLY":+ {+ var weekStart = anchor.Date.AddDays(-(((int)anchor.DayOfWeek + 6) % 7)).AddDays(period * 7 * interval);+ var days = rule.ByDay.Count > 0 ? rule.ByDay.Select(d => d.Day) : [anchor.DayOfWeek];+ foreach (var day in days.Distinct().OrderBy(d => ((int)d + 6) % 7))+ yield return weekStart.AddDays(((int)day + 6) % 7) + anchor.TimeOfDay;+ break;+ }+ case "MONTHLY":+ {+ var month = new DateTime(anchor.Year, anchor.Month, 1).AddMonths(period * interval);+ if (rule.ByDay.Count > 0)+ {+ foreach (var (ordinal, day) in rule.ByDay)+ if (NthWeekday(month, day, ordinal == 0 ? 1 : ordinal) is { } date)+ yield return date + anchor.TimeOfDay;+ }+ else+ {+ var dayOfMonth = rule.ByMonthDay ?? anchor.Day;+ if (dayOfMonth <= DateTime.DaysInMonth(month.Year, month.Month))+ yield return month.AddDays(dayOfMonth - 1) + anchor.TimeOfDay;+ }+ break;+ }+ case "YEARLY":+ {+ var year = anchor.Year + period * interval;+ if (anchor.Month == 2 && anchor.Day == 29 && !DateTime.IsLeapYear(year)) break;+ yield return new DateTime(year, anchor.Month, anchor.Day) + anchor.TimeOfDay;+ break;+ }+ default:+ yield return anchor;+ yield break;+ }+ }+ }++ foreach (var candidate in Candidates())+ {+ if (candidate < item.Start) continue;+ if (candidate > windowEnd) yield break;+ if (rule.Count is { } count && produced >= count) yield break;+ produced++;+ if (item.Exclusions.Contains(candidate)) continue;+ if (candidate + item.Duration > from && ++yielded <= MaxOccurrencesPerEvent) yield return candidate;+ }+ }++ private static DateTime? NthWeekday(DateTime month, DayOfWeek day, int ordinal)+ {+ var days = DateTime.DaysInMonth(month.Year, month.Month);+ var matches = Enumerable.Range(0, days).Select(i => month.AddDays(i)).Where(d => d.DayOfWeek == day).ToList();+ var index = ordinal > 0 ? ordinal - 1 : matches.Count + ordinal;+ return index >= 0 && index < matches.Count ? matches[index] : null;+ }++ // ---- Parsing -------------------------------------------------------------------------++ private sealed record RecurrenceRule(string Frequency, int Interval, int? Count, DateTime? Until,+ IReadOnlyList<(int Ordinal, DayOfWeek Day)> ByDay, int? ByMonthDay);++ private sealed class IcsEvent+ {+ public string Uid = "";+ public string Summary = "";+ public string? Location;+ public DateTime Start;+ public TimeSpan Duration;+ public bool AllDay;+ public RecurrenceRule? Rule;+ public DateTime? RecurrenceId;+ public HashSet<DateTime> Exclusions = [];+ }++ private static List<IcsEvent> Parse(string text)+ {+ if (!text.Contains("BEGIN:VCALENDAR", StringComparison.OrdinalIgnoreCase))+ throw new FormatException("iCalendar verisi değil.");++ var lines = Unfold(text);+ var events = new List<IcsEvent>();+ IcsEvent? current = null;+ DateTime? end = null;+ TimeSpan? duration = null;+ var cancelled = false;+ var depth = 0;++ foreach (var line in lines)+ {+ if (line.Equals("BEGIN:VEVENT", StringComparison.OrdinalIgnoreCase))+ {+ current = new IcsEvent();+ end = null;+ duration = null;+ cancelled = false;+ depth = 0;+ continue;+ }++ if (current is null) continue;+ if (line.StartsWith("BEGIN:", StringComparison.OrdinalIgnoreCase)) { depth++; continue; }+ if (line.StartsWith("END:", StringComparison.OrdinalIgnoreCase) && depth > 0) { depth--; continue; }+ if (depth > 0) continue; // VALARM and other nested components++ if (line.Equals("END:VEVENT", StringComparison.OrdinalIgnoreCase))+ {+ if (!cancelled && current.Start != default)+ {+ current.Duration = duration ?? (end is { } e ? e - current.Start+ : current.AllDay ? TimeSpan.FromDays(1) : TimeSpan.Zero);+ if (current.Duration < TimeSpan.Zero) current.Duration = TimeSpan.Zero;+ events.Add(current);+ }+ current = null;+ continue;+ }++ var colon = FindValueSeparator(line);+ if (colon < 0) continue;+ var head = line[..colon];+ var value = line[(colon + 1)..];+ var parts = head.Split(';');+ var name = parts[0].ToUpperInvariant();+ var parameters = parts.Skip(1)+ .Select(p => p.Split('=', 2))+ .Where(p => p.Length == 2)+ .ToDictionary(p => p[0].ToUpperInvariant(), p => p[1].Trim('"'), StringComparer.OrdinalIgnoreCase);++ switch (name)+ {+ case "UID": current.Uid = value; break;+ case "SUMMARY": current.Summary = UnescapeText(value); break;+ case "LOCATION": current.Location = string.IsNullOrWhiteSpace(value) ? null : UnescapeText(value); break;+ case "STATUS": cancelled = value.Equals("CANCELLED", StringComparison.OrdinalIgnoreCase); break;+ case "DTSTART":+ (current.Start, current.AllDay) = ParseDate(value, parameters);+ break;+ case "DTEND": end = ParseDate(value, parameters).Value; break;+ case "DURATION": duration = ParseDuration(value); break;+ case "RRULE": current.Rule = ParseRule(value); break;+ case "RECURRENCE-ID": current.RecurrenceId = ParseDate(value, parameters).Value; break;+ case "EXDATE":+ foreach (var item in value.Split(',', StringSplitOptions.RemoveEmptyEntries))+ current.Exclusions.Add(ParseDate(item, parameters).Value);+ break;+ }+ }++ foreach (var item in events.Where(e => string.IsNullOrEmpty(e.Summary)))+ item.Summary = UiText.Get("CalendarUntitled");+ return events;+ }++ private static int FindValueSeparator(string line)+ {+ var quoted = false;+ for (var i = 0; i < line.Length; i++)+ {+ if (line[i] == '"') quoted = !quoted;+ else if (line[i] == ':' && !quoted) return i;+ }+ return -1;+ }++ private static List<string> Unfold(string text)+ {+ var result = new List<string>();+ var builder = new StringBuilder();+ foreach (var raw in text.Replace("\r\n", "\n").Split('\n'))+ {+ if (raw.Length > 0 && (raw[0] == ' ' || raw[0] == '\t'))+ {+ builder.Append(raw, 1, raw.Length - 1);+ continue;+ }+ if (builder.Length > 0) result.Add(builder.ToString());+ builder.Clear().Append(raw.TrimEnd('\r'));+ }+ if (builder.Length > 0) result.Add(builder.ToString());+ return result;+ }++ private static string UnescapeText(string value) => value+ .Replace("\\n", " ", StringComparison.OrdinalIgnoreCase)+ .Replace("\\,", ",").Replace("\\;", ";").Replace("\\\\", "\\").Trim();++ private static (DateTime Value, bool AllDay) ParseDate(string value, IReadOnlyDictionary<string, string> parameters)+ {+ value = value.Trim();+ if (value.Length == 8 || (parameters.TryGetValue("VALUE", out var kind) && kind.Equals("DATE", StringComparison.OrdinalIgnoreCase)))+ return (DateTime.ParseExact(value[..8], "yyyyMMdd", CultureInfo.InvariantCulture), true);++ var utc = value.EndsWith('Z');+ var parsed = DateTime.ParseExact(value.TrimEnd('Z'), "yyyyMMdd'T'HHmmss", CultureInfo.InvariantCulture);+ if (utc) return (DateTime.SpecifyKind(parsed, DateTimeKind.Utc).ToLocalTime(), false);++ if (parameters.TryGetValue("TZID", out var zoneId) && FindZone(zoneId) is { } zone)+ {+ try+ {+ var utcTime = TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(parsed, DateTimeKind.Unspecified), zone);+ return (utcTime.ToLocalTime(), false);+ }+ catch (ArgumentException)+ {+ // Invalid local time in that zone (DST gap); fall through and keep it as written.+ }+ }++ return (DateTime.SpecifyKind(parsed, DateTimeKind.Local), false);+ }++ private static readonly Dictionary<string, TimeZoneInfo?> ZoneCache = new(StringComparer.OrdinalIgnoreCase);++ private static TimeZoneInfo? FindZone(string id)+ {+ lock (ZoneCache)+ {+ if (ZoneCache.TryGetValue(id, out var cached)) return cached;+ TimeZoneInfo? zone = null;+ try { zone = TimeZoneInfo.FindSystemTimeZoneById(id); }+ catch (Exception ex) when (ex is TimeZoneNotFoundException or InvalidTimeZoneException) { }+ ZoneCache[id] = zone;+ return zone;+ }+ }++ private static TimeSpan ParseDuration(string value)+ {+ // RFC 5545 duration: [+-]P[nW][nD][T[nH][nM][nS]]+ var negative = value.StartsWith('-');+ var text = value.TrimStart('+', '-');+ if (!text.StartsWith('P')) return TimeSpan.Zero;+ var total = TimeSpan.Zero;+ var number = 0;+ foreach (var c in text[1..])+ {+ if (char.IsDigit(c)) { number = number * 10 + (c - '0'); continue; }+ total += c switch+ {+ 'W' => TimeSpan.FromDays(7 * number),+ 'D' => TimeSpan.FromDays(number),+ 'H' => TimeSpan.FromHours(number),+ 'M' => TimeSpan.FromMinutes(number),+ 'S' => TimeSpan.FromSeconds(number),+ _ => TimeSpan.Zero+ };+ number = 0;+ }+ return negative ? -total : total;+ }++ private static RecurrenceRule? ParseRule(string value)+ {+ var parts = value.Split(';', StringSplitOptions.RemoveEmptyEntries)+ .Select(p => p.Split('=', 2))+ .Where(p => p.Length == 2)+ .ToDictionary(p => p[0].ToUpperInvariant(), p => p[1], StringComparer.OrdinalIgnoreCase);+ if (!parts.TryGetValue("FREQ", out var frequency)) return null;+ frequency = frequency.ToUpperInvariant();+ if (frequency is not ("DAILY" or "WEEKLY" or "MONTHLY" or "YEARLY")) return null;++ var interval = parts.TryGetValue("INTERVAL", out var i) && int.TryParse(i, out var parsedInterval) ? parsedInterval : 1;+ int? count = parts.TryGetValue("COUNT", out var c) && int.TryParse(c, out var parsedCount) ? parsedCount : null;+ DateTime? until = null;+ if (parts.TryGetValue("UNTIL", out var u))+ {+ try { until = ParseDate(u, new Dictionary<string, string>()).Value; }+ catch (FormatException) { }+ if (until is { } untilValue && untilValue.TimeOfDay == TimeSpan.Zero && u.Trim().Length == 8)+ until = untilValue.AddDays(1).AddTicks(-1);+ }++ var byDay = new List<(int, DayOfWeek)>();+ if (parts.TryGetValue("BYDAY", out var days))+ {+ foreach (var token in days.Split(',', StringSplitOptions.RemoveEmptyEntries))+ {+ var code = token.Length >= 2 ? token[^2..].ToUpperInvariant() : "";+ DayOfWeek? day = code switch+ {+ "MO" => DayOfWeek.Monday, "TU" => DayOfWeek.Tuesday, "WE" => DayOfWeek.Wednesday,+ "TH" => DayOfWeek.Thursday, "FR" => DayOfWeek.Friday, "SA" => DayOfWeek.Saturday,+ "SU" => DayOfWeek.Sunday, _ => null+ };+ if (day is null) continue;+ var ordinalText = token[..^2];+ var ordinal = int.TryParse(ordinalText, out var n) ? n : 0;+ byDay.Add((ordinal, day.Value));+ }+ }++ int? byMonthDay = parts.TryGetValue("BYMONTHDAY", out var md) && int.TryParse(md.Split(',')[0], out var parsedDay) && parsedDay > 0+ ? parsedDay : null;+ return new RecurrenceRule(frequency, interval, count, until, byDay, byMonthDay);+ }+}diff --git a/Services/Widgets/SystemControls.cs b/Services/Widgets/SystemControls.csnew file mode 100644index 0000000..9d73f87--- /dev/null+++ b/Services/Widgets/SystemControls.cs@@ -0,0 +1,381 @@+using System.Runtime.InteropServices;+using Windows.Devices.Radios;+using Windows.Networking.Connectivity;++namespace QiDock.Services.Widgets;++/// <summary>Default playback device volume through Windows Core Audio.</summary>+public sealed class AudioEndpoint : IDisposable+{+ private static readonly Guid AudioEndpointVolumeId = new("5CDF2C82-841E-4546-9722-0CF74078229A");+ private IMMDeviceEnumerator? _enumerator;+ // Shared by every QiDock audio change so the volume HUD can tell them from the volume keys.+ private static Guid _eventContext = Guid.NewGuid();+ public static Guid OwnContext => _eventContext;++ public sealed record State(float Volume, bool Muted, string DeviceName);++ /// <summary>Why the last read failed (for the log), or null.</summary>+ public string? LastProblem { get; private set; }++ /// <summary>Reads the volume on a worker thread with its own connection (the window thread never waits).</summary>+ public static Task<State?> ReadInBackgroundAsync() => Task.Run(() =>+ {+ using var endpoint = new AudioEndpoint();+ return endpoint.Read();+ });++ public State? Read()+ {+ try+ {+ var (volume, name) = Open();+ if (volume is null) return null;+ LastProblem = null;+ try+ {+ Marshal.ThrowExceptionForHR(volume.GetMasterVolumeLevelScalar(out var level));+ Marshal.ThrowExceptionForHR(volume.GetMute(out var muted));+ return new State(level, muted, name);+ }+ finally+ {+ Marshal.ReleaseComObject(volume);+ }+ }+ catch (Exception ex) when (ex is COMException or InvalidCastException or InvalidComObjectException)+ {+ LastProblem = $"{ex.GetType().Name} 0x{ex.HResult:X8}";+ ResetEnumerator();+ return null;+ }+ }++ public void SetVolume(float level)+ {+ Change(v =>+ {+ Marshal.ThrowExceptionForHR(v.SetMasterVolumeLevelScalar(Math.Clamp(level, 0f, 1f), ref _eventContext));+ if (level > 0) v.SetMute(false, ref _eventContext);+ });+ }++ public void SetMute(bool muted) => Change(v => Marshal.ThrowExceptionForHR(v.SetMute(muted, ref _eventContext)));++ private void Change(Action<IAudioEndpointVolume> action)+ {+ try+ {+ var (volume, _) = Open(withName: false);+ if (volume is null) return;+ try { action(volume); }+ finally { Marshal.ReleaseComObject(volume); }+ }+ catch (Exception ex) when (ex is COMException or InvalidCastException or InvalidComObjectException)+ {+ ResetEnumerator();+ }+ }++ /// <summary>+ /// Drops the cached device enumerator. Its connection to the audio service can break (sleep and+ /// resume, a restarted audio service, devices coming and going); a dead one fails every call, so+ /// the slider could no longer change the volume and showed it as zero.+ /// </summary>+ private void ResetEnumerator()+ {+ if (_enumerator is null) return;+ try { Marshal.ReleaseComObject(_enumerator); }+ catch (InvalidComObjectException) { }+ _enumerator = null;+ }++ private (IAudioEndpointVolume? Volume, string Name) Open(bool withName = true)+ {+ IMMDevice? device = null;+ for (var attempt = 0; attempt < 2 && device is null; attempt++)+ {+ try+ {+ _enumerator ??= (IMMDeviceEnumerator)Activator.CreateInstance(Type.GetTypeFromCLSID(MMDeviceEnumeratorId, throwOnError: true)!)!;+ var hr = _enumerator.GetDefaultAudioEndpoint(0 /* eRender */, 1 /* eMultimedia */, out device);+ if (hr != 0)+ {+ LastProblem = $"varsayılan ses aygıtı yok 0x{hr:X8}";+ device = null;+ }+ }+ catch (Exception ex) when (ex is COMException or InvalidComObjectException or InvalidCastException)+ {+ LastProblem = $"aygıt listesi açılamadı {ex.GetType().Name} 0x{ex.HResult:X8}";+ device = null;+ }+ // A failure retries once with a fresh enumerator; with no playback device at all both attempts fail.+ if (device is null) ResetEnumerator();+ }+ if (device is null) return (null, "");+ try+ {+ var name = withName ? ReadFriendlyName(device) : "";+ var iid = AudioEndpointVolumeId;+ Marshal.ThrowExceptionForHR(device.Activate(ref iid, 0x17 /* CLSCTX_ALL */, 0, out var instance));+ return ((IAudioEndpointVolume)instance, name);+ }+ finally+ {+ Marshal.ReleaseComObject(device);+ }+ }++ private static string ReadFriendlyName(IMMDevice device)+ {+ if (device.OpenPropertyStore(0 /* STGM_READ */, out var store) != 0 || store is null) return "";+ try+ {+ // PKEY_Device_DeviceDesc gives the short name ("Hoparlör", "Kulaklık"); fall back to the friendly name.+ foreach (var pid in new[] { 2u, 14u })+ {+ var key = new PropertyKey { FormatId = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), PropertyId = pid };+ if (store.GetValue(ref key, out var variant) != 0) continue;+ try+ {+ if (variant.Type == 31 /* VT_LPWSTR */ && variant.Pointer != 0)+ {+ var text = Marshal.PtrToStringUni(variant.Pointer);+ if (!string.IsNullOrWhiteSpace(text)) return text;+ }+ }+ finally+ {+ PropVariantClear(ref variant);+ }+ }+ return "";+ }+ finally+ {+ Marshal.ReleaseComObject(store);+ }+ }++ public void Dispose()+ {+ if (_enumerator is not null) Marshal.ReleaseComObject(_enumerator);+ _enumerator = null;+ }++ [DllImport("ole32.dll")] private static extern int PropVariantClear(ref PropVariant variant);++ [StructLayout(LayoutKind.Sequential)]+ private struct PropertyKey { public Guid FormatId; public uint PropertyId; }++ [StructLayout(LayoutKind.Explicit, Size = 24)]+ private struct PropVariant+ {+ [FieldOffset(0)] public ushort Type;+ [FieldOffset(8)] public nint Pointer;+ }++ // Made the same way as the volume watcher's and the app volume list's: Windows hands every caller in the process+ // the same enumerator, and .NET then gives back the wrapper it already made. Made through a [ComImport] class+ // instead, that existing wrapper could not be cast and every read failed (the slider sat at zero).+ private static readonly Guid MMDeviceEnumeratorId = new("BCDE0395-E52F-467C-8E3D-C4579291692E");++ [ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IMMDeviceEnumerator+ {+ [PreserveSig] int EnumAudioEndpoints(int dataFlow, int stateMask, out nint devices);+ [PreserveSig] int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice device);+ [PreserveSig] int GetDevice([MarshalAs(UnmanagedType.LPWStr)] string id, out IMMDevice device);+ [PreserveSig] int RegisterEndpointNotificationCallback(nint client);+ [PreserveSig] int UnregisterEndpointNotificationCallback(nint client);+ }++ [ComImport, Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IMMDevice+ {+ [PreserveSig] int Activate(ref Guid iid, int clsCtx, nint activationParams, [MarshalAs(UnmanagedType.IUnknown)] out object instance);+ [PreserveSig] int OpenPropertyStore(int access, out IPropertyStore store);+ [PreserveSig] int GetId([MarshalAs(UnmanagedType.LPWStr)] out string id);+ [PreserveSig] int GetState(out int state);+ }++ [ComImport, Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IPropertyStore+ {+ [PreserveSig] int GetCount(out uint count);+ [PreserveSig] int GetAt(uint index, out PropertyKey key);+ [PreserveSig] int GetValue(ref PropertyKey key, out PropVariant value);+ [PreserveSig] int SetValue(ref PropertyKey key, ref PropVariant value);+ [PreserveSig] int Commit();+ }++ [ComImport, Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IAudioEndpointVolume+ {+ [PreserveSig] int RegisterControlChangeNotify(nint notify);+ [PreserveSig] int UnregisterControlChangeNotify(nint notify);+ [PreserveSig] int GetChannelCount(out uint count);+ [PreserveSig] int SetMasterVolumeLevel(float levelDb, ref Guid context);+ [PreserveSig] int SetMasterVolumeLevelScalar(float level, ref Guid context);+ [PreserveSig] int GetMasterVolumeLevel(out float levelDb);+ [PreserveSig] int GetMasterVolumeLevelScalar(out float level);+ [PreserveSig] int SetChannelVolumeLevel(uint channel, float levelDb, ref Guid context);+ [PreserveSig] int SetChannelVolumeLevelScalar(uint channel, float level, ref Guid context);+ [PreserveSig] int GetChannelVolumeLevel(uint channel, out float levelDb);+ [PreserveSig] int GetChannelVolumeLevelScalar(uint channel, out float level);+ [PreserveSig] int SetMute([MarshalAs(UnmanagedType.Bool)] bool mute, ref Guid context);+ [PreserveSig] int GetMute([MarshalAs(UnmanagedType.Bool)] out bool mute);+ }+}++/// <summary>Wi-Fi and Bluetooth radios plus the current Wi-Fi network name.</summary>+public sealed class RadioControls+{+ private Radio? _wifi;+ private Radio? _bluetooth;+ private bool _accessRequested;+ public event EventHandler? Changed;++ public bool HasWifi => _wifi is not null;+ public bool HasBluetooth => _bluetooth is not null;+ public bool WifiOn => _wifi?.State == RadioState.On;+ public bool BluetoothOn => _bluetooth?.State == RadioState.On;++ public async Task InitializeAsync()+ {+ try+ {+ var radios = await Radio.GetRadiosAsync();+ _wifi = radios.FirstOrDefault(r => r.Kind == RadioKind.WiFi);+ _bluetooth = radios.FirstOrDefault(r => r.Kind == RadioKind.Bluetooth);+ if (_wifi is not null) _wifi.StateChanged += (_, _) => Changed?.Invoke(this, EventArgs.Empty);+ if (_bluetooth is not null) _bluetooth.StateChanged += (_, _) => Changed?.Invoke(this, EventArgs.Empty);+ }+ catch (Exception ex) when (ex is COMException or UnauthorizedAccessException or InvalidOperationException)+ {+ _wifi = null;+ _bluetooth = null;+ }+ NetworkInformation.NetworkStatusChanged += _ => Changed?.Invoke(this, EventArgs.Empty);+ }++ public Task<bool> ToggleWifiAsync() => ToggleAsync(_wifi);+ public Task<bool> ToggleBluetoothAsync() => ToggleAsync(_bluetooth);++ private async Task<bool> ToggleAsync(Radio? radio)+ {+ if (radio is null) return false;+ try+ {+ if (!_accessRequested)+ {+ _accessRequested = true;+ await Radio.RequestAccessAsync();+ }+ var result = await radio.SetStateAsync(radio.State == RadioState.On ? RadioState.Off : RadioState.On);+ return result == RadioAccessStatus.Allowed;+ }+ catch (Exception ex) when (ex is COMException or UnauthorizedAccessException or InvalidOperationException)+ {+ return false;+ }+ }++ public static string? CurrentNetworkName()+ {+ try+ {+ var profile = NetworkInformation.GetInternetConnectionProfile();+ if (profile is null) return null;+ if (profile.IsWlanConnectionProfile)+ {+ var ssid = profile.WlanConnectionProfileDetails?.GetConnectedSsid();+ if (!string.IsNullOrWhiteSpace(ssid)) return ssid;+ }+ return profile.ProfileName;+ }+ catch (Exception ex) when (ex is COMException or UnauthorizedAccessException)+ {+ return null;+ }+ }++ public static bool IsOnWifi()+ {+ try { return NetworkInformation.GetInternetConnectionProfile()?.IsWlanConnectionProfile == true; }+ catch (COMException) { return false; }+ }+}++/// <summary>Windows "power mode" (Settings › System › Power): best efficiency, balanced, best performance.</summary>+public static class PowerMode+{+ public enum Mode { Efficiency, Balanced, Performance }++ private static readonly Guid EfficiencyId = new("961cc777-2547-4f9d-8174-7d86181b8a7a");+ private static readonly Guid BalancedId = Guid.Empty;+ private static readonly Guid PerformanceId = new("ded574b5-45a0-4f42-8737-46345c09c238");++ public static Mode? Read()+ {+ try+ {+ if (PowerGetEffectiveOverlayScheme(out var overlay) != 0) return null;+ return overlay == EfficiencyId ? Mode.Efficiency : overlay == PerformanceId ? Mode.Performance : Mode.Balanced;+ }+ catch (EntryPointNotFoundException)+ {+ return null;+ }+ }++ public static bool Set(Mode mode)+ {+ try+ {+ var id = mode switch { Mode.Efficiency => EfficiencyId, Mode.Performance => PerformanceId, _ => BalancedId };+ return PowerSetActiveOverlayScheme(id) == 0;+ }+ catch (EntryPointNotFoundException)+ {+ return false;+ }+ }++ [DllImport("powrprof.dll")]+ private static extern uint PowerGetEffectiveOverlayScheme(out Guid overlay);++ [DllImport("powrprof.dll")]+ private static extern uint PowerSetActiveOverlayScheme(Guid overlay);+}++public static class BatteryStatus+{+ public sealed record State(int Percent, bool Charging, bool OnAc, TimeSpan? Remaining, bool Saver = false);++ /// <summary>Returns null on PCs without a system battery.</summary>+ public static State? Read()+ {+ if (!GetSystemPowerStatus(out var status)) return null;+ if ((status.BatteryFlag & 128) != 0 || status.BatteryFlag == 255 || status.BatteryLifePercent > 100) return null;+ var charging = (status.BatteryFlag & 8) != 0;+ TimeSpan? remaining = status.BatteryLifeTime is > 0 and < int.MaxValue ? TimeSpan.FromSeconds(status.BatteryLifeTime) : null;+ return new State(status.BatteryLifePercent, charging, status.ACLineStatus == 1, remaining, status.SystemStatusFlag == 1);+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct SystemPowerStatus+ {+ public byte ACLineStatus;+ public byte BatteryFlag;+ public byte BatteryLifePercent;+ public byte SystemStatusFlag;+ public int BatteryLifeTime;+ public int BatteryFullLifeTime;+ }++ [DllImport("kernel32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool GetSystemPowerStatus(out SystemPowerStatus status);+}diff --git a/Services/Widgets/VolumeWatcher.cs b/Services/Widgets/VolumeWatcher.csnew file mode 100644index 0000000..b3558e9--- /dev/null+++ b/Services/Widgets/VolumeWatcher.cs@@ -0,0 +1,190 @@+using System.Runtime.InteropServices;+using System.Windows.Threading;++namespace QiDock.Services.Widgets;++/// <summary>+/// Reports master volume and mute changes of the default playback device as they happen (volume+/// keys, the Windows mixer, other apps), with no polling. Changes made by QiDock's own slider+/// carry <see cref="AudioEndpoint.OwnContext"/> and are not reported. Follows default device changes.+/// </summary>+public sealed class VolumeWatcher : IDisposable+{+ private static readonly Guid AudioEndpointVolumeId = new("5CDF2C82-841E-4546-9722-0CF74078229A");+ private readonly Dispatcher _dispatcher;+ private IMMDeviceEnumerator? _enumerator;+ private IAudioEndpointVolume? _volume;+ private VolumeCallback? _callback;+ private nint _callbackPointer;+ private DeviceCallback? _deviceCallback;+ private nint _deviceCallbackPointer;+ private bool _disposed;++ public VolumeWatcher(Dispatcher dispatcher) => _dispatcher = dispatcher;++ /// <summary>Level 0..1 and mute state, raised on the UI thread.</summary>+ public event Action<float, bool>? Changed;++ public void Start()+ {+ try+ {+ _enumerator = (IMMDeviceEnumerator)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E"), throwOnError: true)!)!;+ _deviceCallback = new DeviceCallback(this);+ _deviceCallbackPointer = Marshal.GetComInterfaceForObject<DeviceCallback, IMMNotificationClient>(_deviceCallback);+ _enumerator.RegisterEndpointNotificationCallback(_deviceCallbackPointer);+ Attach();+ }+ catch (Exception ex) when (ex is COMException or InvalidCastException)+ {+ System.Diagnostics.Trace.TraceWarning("Volume watcher unavailable: {0}", ex.Message);+ }+ }++ private void Attach()+ {+ Detach();+ if (_disposed || _enumerator is null) return;+ try+ {+ if (_enumerator.GetDefaultAudioEndpoint(0 /* eRender */, 1 /* eMultimedia */, out var device) != 0 || device is null) return;+ try+ {+ var iid = AudioEndpointVolumeId;+ if (device.Activate(ref iid, 0x17 /* CLSCTX_ALL */, 0, out var instance) != 0) return;+ _volume = (IAudioEndpointVolume)instance;+ }+ finally+ {+ Marshal.ReleaseComObject(device);+ }+ _callback ??= new VolumeCallback(this);+ _callbackPointer = Marshal.GetComInterfaceForObject<VolumeCallback, IAudioEndpointVolumeCallback>(_callback);+ if (_volume.RegisterControlChangeNotify(_callbackPointer) != 0) Detach();+ }+ catch (Exception ex) when (ex is COMException or InvalidCastException)+ {+ Detach();+ }+ }++ private void Detach()+ {+ if (_volume is not null)+ {+ if (_callbackPointer != 0) _volume.UnregisterControlChangeNotify(_callbackPointer);+ Marshal.ReleaseComObject(_volume);+ _volume = null;+ }+ if (_callbackPointer != 0)+ {+ Marshal.Release(_callbackPointer);+ _callbackPointer = 0;+ }+ }++ private void OnNotify(nint data)+ {+ if (data == 0 || _disposed) return;+ // AUDIO_VOLUME_NOTIFICATION_DATA: GUID guidEventContext; BOOL bMuted; float fMasterVolume; ...+ var context = Marshal.PtrToStructure<Guid>(data);+ if (context == AudioEndpoint.OwnContext) return;+ var muted = Marshal.ReadInt32(data, 16) != 0;+ var level = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(data, 20));+ _dispatcher.InvokeAsync(() => Changed?.Invoke(level, muted));+ }++ private void OnDefaultDeviceChanged(int flow, int role)+ {+ if (flow != 0 || role != 1 || _disposed) return;+ _dispatcher.InvokeAsync(Attach);+ }++ public void Dispose()+ {+ if (_disposed) return;+ _disposed = true;+ Detach();+ if (_enumerator is not null)+ {+ if (_deviceCallbackPointer != 0)+ {+ _enumerator.UnregisterEndpointNotificationCallback(_deviceCallbackPointer);+ Marshal.Release(_deviceCallbackPointer);+ _deviceCallbackPointer = 0;+ }+ Marshal.ReleaseComObject(_enumerator);+ _enumerator = null;+ }+ }++ [ComVisible(true)]+ public sealed class VolumeCallback(VolumeWatcher owner) : IAudioEndpointVolumeCallback+ {+ public int OnNotify(nint data)+ {+ owner.OnNotify(data);+ return 0;+ }+ }++ [ComVisible(true)]+ public sealed class DeviceCallback(VolumeWatcher owner) : IMMNotificationClient+ {+ public int OnDeviceStateChanged(nint deviceId, int newState) => 0;+ public int OnDeviceAdded(nint deviceId) => 0;+ public int OnDeviceRemoved(nint deviceId) => 0;+ public int OnDefaultDeviceChanged(int flow, int role, nint defaultDeviceId)+ {+ owner.OnDefaultDeviceChanged(flow, role);+ return 0;+ }+ public int OnPropertyValueChanged(nint deviceId, PropertyKey key) => 0;+ }++ [StructLayout(LayoutKind.Sequential)]+ public struct PropertyKey+ {+ public Guid FormatId;+ public int PropertyId;+ }++ [ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IMMDeviceEnumerator+ {+ [PreserveSig] int EnumAudioEndpoints(int dataFlow, int stateMask, out nint devices);+ [PreserveSig] int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice device);+ [PreserveSig] int GetDevice([MarshalAs(UnmanagedType.LPWStr)] string id, out IMMDevice device);+ [PreserveSig] int RegisterEndpointNotificationCallback(nint client);+ [PreserveSig] int UnregisterEndpointNotificationCallback(nint client);+ }++ [ComImport, Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IMMDevice+ {+ [PreserveSig] int Activate(ref Guid iid, int clsCtx, nint activationParams, [MarshalAs(UnmanagedType.IUnknown)] out object instance);+ }++ [ComImport, Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ private interface IAudioEndpointVolume+ {+ [PreserveSig] int RegisterControlChangeNotify(nint notify);+ [PreserveSig] int UnregisterControlChangeNotify(nint notify);+ }++ [ComImport, Guid("657804FA-D6AD-4496-8A60-352752AF4F89"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ public interface IAudioEndpointVolumeCallback+ {+ [PreserveSig] int OnNotify(nint data);+ }++ [ComImport, Guid("7991EEC9-7E89-4D85-8390-6C703CEC60C0"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ public interface IMMNotificationClient+ {+ [PreserveSig] int OnDeviceStateChanged(nint deviceId, int newState);+ [PreserveSig] int OnDeviceAdded(nint deviceId);+ [PreserveSig] int OnDeviceRemoved(nint deviceId);+ [PreserveSig] int OnDefaultDeviceChanged(int flow, int role, nint defaultDeviceId);+ [PreserveSig] int OnPropertyValueChanged(nint deviceId, PropertyKey key);+ }+}diff --git a/Services/Widgets/WeatherService.cs b/Services/Widgets/WeatherService.csnew file mode 100644index 0000000..98445c5--- /dev/null+++ b/Services/Widgets/WeatherService.cs@@ -0,0 +1,159 @@+using System.Globalization;+using System.Net.Http;+using System.Text.Json;++namespace QiDock.Services.Widgets;++public enum WeatherKind { Clear, PartlyCloudy, Cloudy, Fog, Drizzle, Rain, Snow, Thunder }++public sealed record WeatherHour(DateTime Time, double Temperature, int Code, bool IsDay);+public sealed record WeatherDay(DateTime Date, int Code, double Min, double Max);++public sealed record WeatherReport(+ string City,+ double Temperature,+ int Code,+ bool IsDay,+ double TodayMin,+ double TodayMax,+ IReadOnlyList<WeatherHour> Hours,+ IReadOnlyList<WeatherDay> Days,+ DateTime FetchedAt,+ WeatherExtra? Extra = null);++/// <summary>Wind, humidity, rain and the sun's times (used by the desktop widgets).</summary>+public sealed record WeatherExtra(double WindSpeed, double WindDirection, double WindGusts, double Humidity, double Precipitation,+ double FeelsLike, DateTime? Sunrise, DateTime? Sunset, DateTime? NextSunrise);++/// <summary>Current conditions and a 7-day forecast from Open-Meteo (free, no API key).</summary>+public sealed class WeatherService+{+ private (string Query, double Lat, double Lon, string Name)? _place;++ public async Task<WeatherReport> FetchAsync(string city, CancellationToken token)+ {+ if (string.IsNullOrWhiteSpace(city)) throw new InvalidOperationException("Şehir belirtilmedi.");+ var place = _place is { } cached && string.Equals(cached.Query, city, StringComparison.OrdinalIgnoreCase)+ ? cached+ : await GeocodeAsync(city.Trim(), token).ConfigureAwait(false);+ _place = place;++ var url = FormattableString.Invariant($"https://api.open-meteo.com/v1/forecast?latitude={place.Lat:0.####}&longitude={place.Lon:0.####}") ++ "¤t=temperature_2m,weather_code,is_day,wind_speed_10m,wind_direction_10m,wind_gusts_10m,relative_humidity_2m,precipitation,apparent_temperature" ++ "&hourly=temperature_2m,weather_code,is_day" ++ "&daily=weather_code,temperature_2m_max,temperature_2m_min,sunrise,sunset" ++ "&timezone=auto&forecast_days=7";+ using var response = await WidgetHttp.Client.GetAsync(url, token).ConfigureAwait(false);+ response.EnsureSuccessStatusCode();+ await using var stream = await response.Content.ReadAsStreamAsync(token).ConfigureAwait(false);+ using var json = await JsonDocument.ParseAsync(stream, cancellationToken: token).ConfigureAwait(false);+ var root = json.RootElement;++ var current = root.GetProperty("current");+ var nowLocal = ParseTime(current.GetProperty("time").GetString());++ var hourly = root.GetProperty("hourly");+ var hourTimes = hourly.GetProperty("time").EnumerateArray().Select(t => ParseTime(t.GetString())).ToList();+ var hourTemps = hourly.GetProperty("temperature_2m").EnumerateArray().Select(ReadDouble).ToList();+ var hourCodes = hourly.GetProperty("weather_code").EnumerateArray().Select(ReadInt).ToList();+ var hourDay = hourly.GetProperty("is_day").EnumerateArray().Select(v => ReadInt(v) == 1).ToList();+ var hours = new List<WeatherHour>();+ for (var i = 0; i < hourTimes.Count && hours.Count < 7; i++)+ {+ if (hourTimes[i] < nowLocal.AddMinutes(-59)) continue;+ hours.Add(new WeatherHour(hourTimes[i], hourTemps[i], hourCodes[i], hourDay[i]));+ }++ var daily = root.GetProperty("daily");+ var dayTimes = daily.GetProperty("time").EnumerateArray().Select(t => ParseTime(t.GetString())).ToList();+ var dayCodes = daily.GetProperty("weather_code").EnumerateArray().Select(ReadInt).ToList();+ var dayMax = daily.GetProperty("temperature_2m_max").EnumerateArray().Select(ReadDouble).ToList();+ var dayMin = daily.GetProperty("temperature_2m_min").EnumerateArray().Select(ReadDouble).ToList();+ var days = dayTimes.Select((t, i) => new WeatherDay(t.Date, dayCodes[i], dayMin[i], dayMax[i])).ToList();+ var sunrises = daily.TryGetProperty("sunrise", out var rise) ? rise.EnumerateArray().Select(t => (DateTime?)ParseTime(t.GetString())).ToList() : [];+ var sunsets = daily.TryGetProperty("sunset", out var set) ? set.EnumerateArray().Select(t => (DateTime?)ParseTime(t.GetString())).ToList() : [];+ var extra = new WeatherExtra(+ ReadOptional(current, "wind_speed_10m"),+ ReadOptional(current, "wind_direction_10m"),+ ReadOptional(current, "wind_gusts_10m"),+ ReadOptional(current, "relative_humidity_2m"),+ ReadOptional(current, "precipitation"),+ ReadOptional(current, "apparent_temperature"),+ sunrises.Count > 0 ? sunrises[0] : null,+ sunsets.Count > 0 ? sunsets[0] : null,+ sunrises.Count > 1 ? sunrises[1] : null);++ return new WeatherReport(+ place.Name,+ ReadDouble(current.GetProperty("temperature_2m")),+ ReadInt(current.GetProperty("weather_code")),+ ReadInt(current.GetProperty("is_day")) == 1,+ days.Count > 0 ? days[0].Min : double.NaN,+ days.Count > 0 ? days[0].Max : double.NaN,+ hours,+ days,+ DateTime.Now,+ extra);+ }++ private static async Task<(string Query, double Lat, double Lon, string Name)> GeocodeAsync(string city, CancellationToken token)+ {+ var url = "https://geocoding-api.open-meteo.com/v1/search?count=1&format=json&language=tr&name="+ + Uri.EscapeDataString(city);+ using var response = await WidgetHttp.Client.GetAsync(url, token).ConfigureAwait(false);+ response.EnsureSuccessStatusCode();+ await using var stream = await response.Content.ReadAsStreamAsync(token).ConfigureAwait(false);+ using var json = await JsonDocument.ParseAsync(stream, cancellationToken: token).ConfigureAwait(false);+ if (!json.RootElement.TryGetProperty("results", out var results) || results.GetArrayLength() == 0)+ throw new InvalidOperationException("Şehir bulunamadı.");+ var first = results[0];+ return (city, first.GetProperty("latitude").GetDouble(), first.GetProperty("longitude").GetDouble(),+ first.TryGetProperty("name", out var name) ? name.GetString() ?? city : city);+ }++ private static DateTime ParseTime(string? value) =>+ DateTime.Parse(value ?? throw new FormatException("Zaman alanı boş."), CultureInfo.InvariantCulture, DateTimeStyles.None);++ private static double ReadOptional(JsonElement parent, string name) =>+ parent.TryGetProperty(name, out var value) ? ReadDouble(value) : double.NaN;++ private static double ReadDouble(JsonElement value) => value.ValueKind == JsonValueKind.Number ? value.GetDouble() : double.NaN;+ private static int ReadInt(JsonElement value) => value.ValueKind == JsonValueKind.Number ? (int)value.GetDouble() : 0;++ public static WeatherKind Classify(int code) => code switch+ {+ 0 => WeatherKind.Clear,+ 1 or 2 => WeatherKind.PartlyCloudy,+ 3 => WeatherKind.Cloudy,+ 45 or 48 => WeatherKind.Fog,+ 51 or 53 or 55 or 56 or 57 => WeatherKind.Drizzle,+ 61 or 63 or 65 or 66 or 67 or 80 or 81 or 82 => WeatherKind.Rain,+ 71 or 73 or 75 or 77 or 85 or 86 => WeatherKind.Snow,+ 95 or 96 or 99 => WeatherKind.Thunder,+ _ => WeatherKind.Cloudy+ };++ public static string Describe(int code) => UiText.Get(code switch+ {+ 0 => "WxClear",+ 1 => "WxMostlyClear",+ 2 => "WxPartlyCloudy",+ 3 => "WxOvercast",+ 45 or 48 => "WxFog",+ 51 or 53 or 55 => "WxDrizzle",+ 56 or 57 => "WxFreezingDrizzle",+ 61 => "WxLightRain",+ 63 => "WxRain",+ 65 => "WxHeavyRain",+ 66 or 67 => "WxFreezingRain",+ 71 => "WxLightSnow",+ 73 => "WxSnow",+ 75 => "WxHeavySnow",+ 77 => "WxSnowGrains",+ 80 or 81 or 82 => "WxShowers",+ 85 or 86 => "WxSnowShowers",+ 95 => "WxThunder",+ 96 or 99 => "WxHail",+ _ => "WxUnknown"+ });+}diff --git a/Services/Widgets/WidgetHttp.cs b/Services/Widgets/WidgetHttp.csnew file mode 100644index 0000000..ea72cdf--- /dev/null+++ b/Services/Widgets/WidgetHttp.cs@@ -0,0 +1,17 @@+using System.Net.Http;+using System.Net.Http.Headers;++namespace QiDock.Services.Widgets;++internal static class WidgetHttp+{+ public static HttpClient Client { get; } = Create();++ private static HttpClient Create()+ {+ var client = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };+ client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("QiDock", "0.2"));+ client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));+ return client;+ }+}diff --git a/Services/Widgets/WifiNetworks.cs b/Services/Widgets/WifiNetworks.csnew file mode 100644index 0000000..105fcf3--- /dev/null+++ b/Services/Widgets/WifiNetworks.cs@@ -0,0 +1,99 @@+using System.Runtime.InteropServices;+using Windows.Devices.WiFi;+using Windows.Networking.Connectivity;+using Windows.Security.Credentials;++namespace QiDock.Services.Widgets;++/// <summary>+/// The Wi-Fi networks in range and joining one of them, through the Windows Wi-Fi adapter. Newer Windows versions+/// only let programs list networks while location access is allowed for desktop apps; when it is not, the caller+/// falls back to Windows' own network list.+/// </summary>+public sealed class WifiNetworks+{+ public enum Scan { Ok, Denied, NoAdapter, Failed }++ public enum Join { Connected, NeedsPassword, WrongPassword, NotInRange, Unsupported, Failed }++ public sealed record Network(string Ssid, int Bars, bool Secured, bool Connected, WiFiAvailableNetwork? Source);++ private WiFiAdapter? _adapter;++ public async Task<(Scan Result, IReadOnlyList<Network> Networks)> ScanAsync()+ {+ try+ {+ if (await WiFiAdapter.RequestAccessAsync() != WiFiAccessStatus.Allowed) return (Scan.Denied, []);+ _adapter ??= (await WiFiAdapter.FindAllAdaptersAsync()).FirstOrDefault();+ if (_adapter is null) return (Scan.NoAdapter, []);+ try { await _adapter.ScanAsync(); }+ catch (UnauthorizedAccessException) { return (Scan.Denied, []); }+ var connected = await ConnectedSsidAsync();+ var networks = _adapter.NetworkReport.AvailableNetworks+ .Where(n => !string.IsNullOrWhiteSpace(n.Ssid))+ .GroupBy(n => n.Ssid)+ .Select(same => same.OrderByDescending(n => n.NetworkRssiInDecibelMilliwatts).First())+ .Select(n => new Network(n.Ssid, Math.Clamp((int)n.SignalBars, 0, 4), IsSecured(n), n.Ssid == connected, n))+ .OrderByDescending(n => n.Connected)+ .ThenByDescending(n => n.Bars)+ .ThenBy(n => n.Ssid, StringComparer.CurrentCultureIgnoreCase)+ .ToList();+ return (Scan.Ok, networks);+ }+ catch (Exception ex)+ {+ // WinRT can fail in many ways here (cancelled, timed out, adapter gone); the list must not stay stuck.+ return (ex is UnauthorizedAccessException ? Scan.Denied : Scan.Failed, []);+ }+ }++ /// <summary>+ /// Joins <paramref name="network"/>. Without a password Windows uses the saved one (or none for an open network);+ /// a secured network it has never joined answers <see cref="Join.NeedsPassword"/>.+ /// </summary>+ public async Task<Join> ConnectAsync(Network network, string? password)+ {+ if (_adapter is null || network.Source is null) return Join.Failed;+ try+ {+ var result = password is null+ ? await _adapter.ConnectAsync(network.Source, WiFiReconnectionKind.Automatic)+ : await _adapter.ConnectAsync(network.Source, WiFiReconnectionKind.Automatic, new PasswordCredential { Password = password });+ return result.ConnectionStatus switch+ {+ WiFiConnectionStatus.Success => Join.Connected,+ WiFiConnectionStatus.InvalidCredential => password is null && network.Secured ? Join.NeedsPassword : Join.WrongPassword,+ WiFiConnectionStatus.NetworkNotAvailable => Join.NotInRange,+ WiFiConnectionStatus.UnsupportedAuthenticationProtocol => Join.Unsupported,+ _ => password is null && network.Secured ? Join.NeedsPassword : Join.Failed+ };+ }+ catch (Exception)+ {+ return Join.Failed; // whatever went wrong, the network list must stay usable+ }+ }++ public void Disconnect()+ {+ try { _adapter?.Disconnect(); }+ catch (Exception ex) when (ex is COMException or InvalidOperationException) { }+ }++ private async Task<string?> ConnectedSsidAsync()+ {+ try+ {+ var profile = _adapter is null ? null : await _adapter.NetworkAdapter.GetConnectedProfileAsync();+ return profile is { IsWlanConnectionProfile: true } ? profile.WlanConnectionProfileDetails?.GetConnectedSsid() : null;+ }+ catch (Exception ex) when (ex is COMException or InvalidOperationException)+ {+ return RadioControls.IsOnWifi() ? RadioControls.CurrentNetworkName() : null;+ }+ }++ private static bool IsSecured(WiFiAvailableNetwork network) =>+ network.SecuritySettings?.NetworkAuthenticationType is not (null or NetworkAuthenticationType.Open80211 or NetworkAuthenticationType.None);+}diff --git a/Services/WindowThumbnailPreview.cs b/Services/WindowThumbnailPreview.csnew file mode 100644index 0000000..76e5d9d--- /dev/null+++ b/Services/WindowThumbnailPreview.cs@@ -0,0 +1,708 @@+using System.Runtime.InteropServices;+using System.Diagnostics;+using System.Windows;+using System.Windows.Automation;+using System.Windows.Controls;+using System.Windows.Interop;+using System.Windows.Media;+using System.Windows.Media.Imaging;+using System.Windows.Media.Animation;+using System.Windows.Threading;+using QiDock.Models;++namespace QiDock.Services;++public sealed class WindowThumbnailPreview : IDisposable+{+ private const uint DwmThumbnailRectDestination = 0x00000001;+ private const uint DwmThumbnailOpacity = 0x00000004;+ private const uint DwmThumbnailVisible = 0x00000008;+ private const uint MonitorDefaultToNearest = 2;+ private const uint SwpNoActivate = 0x0010;+ private const uint SwpNoOwnerZOrder = 0x0200;+ private static readonly nint HwndTopmost = new(-1);++ private readonly Style _closeButtonStyle;+ private readonly Window _window;+ private readonly Window _closeButtonWindow;+ private readonly StackPanel _surfaceContainer;+ private readonly StackPanel _overlayContainer;+ private readonly TextBlock _placeholder;+ private readonly DispatcherTimer _entranceTimer;+ private readonly double _entranceDurationMs;+ private readonly List<(nint Source, nint Thumbnail, NativeRect TargetRect)> _activeThumbnails = [];+ private long _entranceStarted;+ private nint _destinationHandle;+ private nint _sourceHandle;+ private bool _disposed;+ private bool _windowClosed;+ private bool _closeWindowClosed;++ public WindowThumbnailPreview(Style closeButtonStyle)+ {+ _closeButtonStyle = closeButtonStyle;+ var resources = Application.Current.Resources;+ var popupBrush = (Brush)resources["SurfacePopup"];+ var strokeBrush = (Brush)resources["StrokeSubtle"];+ _entranceDurationMs = (double)resources["PreviewDurationMs"];+ _entranceTimer = new DispatcherTimer(DispatcherPriority.Render)+ {+ Interval = TimeSpan.FromMilliseconds(16)+ };+ _entranceTimer.Tick += EntranceTimer_Tick;++ _placeholder = new TextBlock+ {+ Text = UiText.Get("PreviewUnavailable"),+ Foreground = (Brush)resources["TextSecondary"],+ FontFamily = (FontFamily)resources["InterfaceFont"],+ HorizontalAlignment = HorizontalAlignment.Center,+ VerticalAlignment = VerticalAlignment.Center+ };++ _surfaceContainer = new StackPanel+ {+ Orientation = Orientation.Horizontal,+ Margin = new Thickness(6)+ };++ var surfaceGrid = new Grid();+ surfaceGrid.Children.Add(_surfaceContainer);+ surfaceGrid.Children.Add(_placeholder);++ var surface = new Border+ {+ Background = popupBrush,+ BorderThickness = new Thickness(1),+ BorderBrush = strokeBrush,+ CornerRadius = new CornerRadius(10),+ Child = surfaceGrid+ };+ surface.SetResourceReference(Border.BackgroundProperty, "SurfacePopup");+ surface.SetResourceReference(Border.BorderBrushProperty, "StrokeSubtle");+ _placeholder.SetResourceReference(TextBlock.ForegroundProperty, "TextSecondary");++ _window = new Window+ {+ Width = (double)resources["PreviewWidth"],+ Height = (double)resources["PreviewHeight"],+ WindowStyle = WindowStyle.None,+ ResizeMode = ResizeMode.NoResize,+ ShowInTaskbar = false,+ ShowActivated = false,+ Topmost = true,+ Background = popupBrush,+ UseLayoutRounding = true,+ Cursor = System.Windows.Input.Cursors.Hand,+ Content = surface+ };+ _window.Closed += Window_Closed;+ _window.SetResourceReference(Window.BackgroundProperty, "SurfacePopup");+ _window.SourceInitialized += PreviewWindow_SourceInitialized;+ _window.MouseEnter += Window_MouseEnter;+ _window.MouseLeave += Window_MouseLeave;++ _overlayContainer = new StackPanel+ {+ Orientation = Orientation.Horizontal,+ Margin = new Thickness(6)+ };++ _closeButtonWindow = new Window+ {+ Width = _window.Width,+ Height = _window.Height,+ WindowStyle = WindowStyle.None,+ ResizeMode = ResizeMode.NoResize,+ AllowsTransparency = true,+ ShowInTaskbar = false,+ ShowActivated = false,+ Topmost = true,+ Background = Brushes.Transparent,+ Cursor = System.Windows.Input.Cursors.Hand,+ WindowStartupLocation = WindowStartupLocation.Manual,+ Content = _overlayContainer+ };+ _closeButtonWindow.Closed += CloseButtonWindow_Closed;+ _closeButtonWindow.SourceInitialized += PreviewWindow_SourceInitialized;+ _closeButtonWindow.MouseEnter += Window_MouseEnter;+ _closeButtonWindow.MouseLeave += Window_MouseLeave;+ }++ public event EventHandler? PointerEntered;++ public event EventHandler? PointerLeft;++ public event EventHandler? PreviewClicked;++ public event EventHandler? CloseRequested;++ public bool IsVisible => _window.IsVisible;+ public bool AnimationsEnabled { get; set; } = true;++ public nint SourceHandle => _sourceHandle;++ public IReadOnlyList<nint> ActiveHandles => _activeThumbnails.Select(t => t.Source).ToList();++ public bool ShowFor(nint sourceHandle, FrameworkElement anchor, string windowTitle, BitmapSource? icon)+ {+ return ShowForWindows([new TrackedWindow(sourceHandle, windowTitle, null)], anchor, icon);+ }++ public bool ShowForWindows(IReadOnlyList<TrackedWindow> windows, FrameworkElement anchor, BitmapSource? defaultIcon)+ {+ ObjectDisposedException.ThrowIf(_disposed, this);+ _placeholder.Text = UiText.Get("PreviewUnavailable");+ var validWindows = windows.Where(w => w.Handle != 0 && IsWindow(w.Handle)).Take(6).ToList();+ if (validWindows.Count == 0)+ {+ Hide();+ return false;+ }++ var isSingle = validWindows.Count == 1;+ var resources = Application.Current.Resources;+ var popupBrush = (Brush)resources["SurfacePopup"];+ var textBrush = (Brush)resources["TextPrimary"];+ var strokeBrush = (Brush)resources["StrokeSubtle"];+ var focusStroke = (Brush)resources["StrokeFocus"];++ double cardWidth = isSingle ? (double)resources["PreviewWidth"] : 250;+ double cardHeight = isSingle ? (double)resources["PreviewHeight"] : 180;+ double headerHeight = isSingle ? (double)resources["PreviewHeaderHeight"] : 36;+ double cardGap = 8;+ double margin = 6;++ var totalWidth = validWindows.Count * cardWidth + (validWindows.Count - 1) * cardGap + margin * 2;+ var totalHeight = cardHeight + margin * 2;++ _window.Width = totalWidth;+ _window.Height = totalHeight;+ _closeButtonWindow.Width = totalWidth;+ _closeButtonWindow.Height = totalHeight;++ var animateEntrance = AnimationsEnabled && SystemParameters.ClientAreaAnimation+ && (!_window.IsVisible || !_activeThumbnails.Select(t => t.Source).SequenceEqual(validWindows.Select(w => w.Handle)));++ _entranceTimer.Stop();+ _closeButtonWindow.BeginAnimation(UIElement.OpacityProperty, null);+ _closeButtonWindow.Opacity = 1;++ ReleaseThumbnails();+ _sourceHandle = validWindows[0].Handle;++ _surfaceContainer.Children.Clear();+ _overlayContainer.Children.Clear();++ if (!_window.IsVisible)+ {+ _placeholder.Visibility = Visibility.Visible;+ _window.Show();+ }++ _destinationHandle = new WindowInteropHelper(_window).Handle;+ if (_destinationHandle == 0 || !PositionWindow(anchor, totalWidth, totalHeight))+ {+ _placeholder.Visibility = Visibility.Visible;+ return false;+ }++ if (!PositionOverlayWindow())+ {+ _placeholder.Visibility = Visibility.Visible;+ return false;+ }++ var dpi = GetDpiForWindow(_destinationHandle);+ if (dpi == 0) dpi = 96;+ var scale = dpi / 96d;++ for (var i = 0; i < validWindows.Count; i++)+ {+ var tracked = validWindows[i];+ var handle = tracked.Handle;++ // Surface card frame+ var surfaceCard = new Border+ {+ Width = cardWidth,+ Height = cardHeight,+ Background = new SolidColorBrush(Color.FromArgb(1, 18, 21, 25)),+ BorderBrush = strokeBrush,+ BorderThickness = new Thickness(1),+ CornerRadius = new CornerRadius(8),+ Margin = new Thickness(0, 0, i < validWindows.Count - 1 ? cardGap : 0, 0)+ };+ _surfaceContainer.Children.Add(surfaceCard);++ // Overlay card+ var closeBtn = new Button+ {+ Style = _closeButtonStyle,+ Content = new System.Windows.Shapes.Path+ {+ Data = Geometry.Parse("M2,2 L10,10 M10,2 L2,10"),+ Stroke = textBrush,+ StrokeThickness = 1.5,+ Width = 10,+ Height = 10+ },+ Width = 24,+ Height = 24,+ HorizontalAlignment = HorizontalAlignment.Right,+ VerticalAlignment = VerticalAlignment.Center,+ Margin = new Thickness(4, 0, 0, 0),+ ToolTip = UiText.Get("CloseWindow")+ };+ AutomationProperties.SetName(closeBtn, UiText.Get("CloseWindow"));+ closeBtn.Click += (_, e) =>+ {+ e.Handled = true;+ _sourceHandle = handle;+ CloseRequested?.Invoke(this, EventArgs.Empty);+ };++ var iconImg = new Image+ {+ Width = 18,+ Height = 18,+ Stretch = Stretch.Uniform,+ Margin = new Thickness(0, 0, 6, 0),+ Source = defaultIcon+ };++ var titleBlock = new TextBlock+ {+ Text = tracked.Title,+ Foreground = textBrush,+ FontFamily = (FontFamily)resources["InterfaceFont"],+ FontSize = (double)resources["TextSizeCaption"],+ TextTrimming = TextTrimming.CharacterEllipsis,+ VerticalAlignment = VerticalAlignment.Center+ };++ var headerPanel = new DockPanel+ {+ LastChildFill = true,+ Margin = new Thickness(8, 4, 6, 4),+ Children = { closeBtn, iconImg, titleBlock }+ };+ DockPanel.SetDock(closeBtn, Dock.Right);+ DockPanel.SetDock(iconImg, Dock.Left);++ var headerSurface = new Border+ {+ Height = headerHeight,+ Background = popupBrush,+ BorderBrush = strokeBrush,+ BorderThickness = new Thickness(1, 1, 1, 0),+ CornerRadius = new CornerRadius(8, 8, 0, 0),+ Child = headerPanel+ };++ var bodySurface = new Border+ {+ Height = cardHeight - headerHeight,+ Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0)),+ BorderBrush = strokeBrush,+ BorderThickness = new Thickness(1, 0, 1, 1),+ CornerRadius = new CornerRadius(0, 0, 8, 8)+ };++ var cardContent = new StackPanel();+ cardContent.Children.Add(headerSurface);+ cardContent.Children.Add(bodySurface);++ var overlayCard = new Border+ {+ Width = cardWidth,+ Height = cardHeight,+ Background = Brushes.Transparent,+ Margin = new Thickness(0, 0, i < validWindows.Count - 1 ? cardGap : 0, 0),+ Cursor = System.Windows.Input.Cursors.Hand,+ Child = cardContent+ };++ overlayCard.MouseEnter += (_, _) =>+ {+ headerSurface.BorderBrush = focusStroke;+ bodySurface.BorderBrush = focusStroke;+ };+ overlayCard.MouseLeave += (_, _) =>+ {+ headerSurface.BorderBrush = strokeBrush;+ bodySurface.BorderBrush = strokeBrush;+ };+ overlayCard.MouseLeftButtonDown += (_, e) =>+ {+ if (!closeBtn.IsMouseOver)+ {+ e.Handled = true;+ _sourceHandle = handle;+ PreviewClicked?.Invoke(this, EventArgs.Empty);+ }+ };++ _overlayContainer.Children.Add(overlayCard);++ if (DwmRegisterThumbnail(_destinationHandle, handle, out var thumbnail) == 0 && thumbnail != 0)+ {+ if (DwmQueryThumbnailSourceSize(thumbnail, out var sourceSize) == 0+ && sourceSize.Width > 0 && sourceSize.Height > 0)+ {+ var cardLeft = margin + i * (cardWidth + cardGap);+ var cardTop = margin + headerHeight;+ var cLeft = (int)Math.Round((cardLeft + 2) * scale);+ var cTop = (int)Math.Round((cardTop + 2) * scale);+ var cRight = (int)Math.Round((cardLeft + cardWidth - 2) * scale);+ var cBottom = (int)Math.Round((margin + cardHeight - 2) * scale);++ var clientRect = new NativeRect(cLeft, cTop, cRight, cBottom);+ var destination = FitThumbnail(sourceSize, clientRect);+ var properties = new DwmThumbnailProperties+ {+ Flags = DwmThumbnailRectDestination | DwmThumbnailOpacity | DwmThumbnailVisible,+ Destination = destination,+ Opacity = byte.MaxValue,+ Visible = true,+ SourceClientAreaOnly = false+ };++ if (animateEntrance)+ {+ var initialProps = properties;+ initialProps.Opacity = 0;+ DwmUpdateThumbnailProperties(thumbnail, ref initialProps);+ }+ else+ {+ DwmUpdateThumbnailProperties(thumbnail, ref properties);+ }++ _activeThumbnails.Add((handle, thumbnail, destination));+ }+ else+ {+ _ = DwmUnregisterThumbnail(thumbnail);+ }+ }+ }++ _placeholder.Visibility = _activeThumbnails.Count == 0 ? Visibility.Visible : Visibility.Collapsed;++ if (animateEntrance)+ {+ _entranceStarted = Stopwatch.GetTimestamp();+ _closeButtonWindow.BeginAnimation(UIElement.OpacityProperty,+ new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(_entranceDurationMs))+ {+ EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }+ });+ _entranceTimer.Start();+ }++ return true;+ }++ private void EntranceTimer_Tick(object? sender, EventArgs e)+ {+ if (_activeThumbnails.Count == 0 || !_window.IsVisible)+ {+ _entranceTimer.Stop();+ return;+ }++ var progress = Math.Clamp(Stopwatch.GetElapsedTime(_entranceStarted).TotalMilliseconds / _entranceDurationMs, 0, 1);+ var eased = 1 - Math.Pow(1 - progress, 3);+ var opacity = (byte)Math.Round(byte.MaxValue * eased);++ foreach (var (_, thumb, target) in _activeThumbnails)+ {+ var insetX = (int)Math.Round((target.Right - target.Left) * 0.025 * (1 - eased));+ var insetY = (int)Math.Round((target.Bottom - target.Top) * 0.025 * (1 - eased));+ var frame = new DwmThumbnailProperties+ {+ Flags = DwmThumbnailRectDestination | DwmThumbnailOpacity | DwmThumbnailVisible,+ Destination = new NativeRect(target.Left + insetX, target.Top + insetY,+ target.Right - insetX, target.Bottom - insetY),+ Opacity = opacity,+ Visible = true+ };+ DwmUpdateThumbnailProperties(thumb, ref frame);+ }++ if (progress >= 1) _entranceTimer.Stop();+ }++ public void Hide()+ {+ _entranceTimer.Stop();+ _closeButtonWindow.BeginAnimation(UIElement.OpacityProperty, null);+ ReleaseThumbnails();+ _sourceHandle = 0;+ _surfaceContainer.Children.Clear();+ _overlayContainer.Children.Clear();+ if (_closeButtonWindow.IsVisible)+ {+ _closeButtonWindow.Hide();+ }++ if (_window.IsVisible)+ {+ _window.Hide();+ }+ }++ public void Dispose()+ {+ if (_disposed)+ {+ return;+ }++ Hide();+ _disposed = true;+ _entranceTimer.Tick -= EntranceTimer_Tick;+ _window.Closed -= Window_Closed;+ _closeButtonWindow.Closed -= CloseButtonWindow_Closed;+ _closeButtonWindow.MouseEnter -= Window_MouseEnter;+ _closeButtonWindow.MouseLeave -= Window_MouseLeave;+ if (!_closeWindowClosed)+ {+ _closeButtonWindow.Close();+ }++ if (!_windowClosed)+ {+ _window.Close();+ }+ }++ private bool PositionWindow(FrameworkElement anchor, double totalWidth, double totalHeight)+ {+ // The anchor's inner side (its top on a bottom dock): the dock is turned, the anchor's frame is not.+ var anchorTop = anchor.PointToScreen(new Point(anchor.ActualWidth / 2, 0));+ var dpi = GetDpiForWindow(_destinationHandle);+ if (dpi == 0)+ {+ return false;+ }++ var width = (int)Math.Ceiling(totalWidth * dpi / 96d);+ var height = (int)Math.Ceiling(totalHeight * dpi / 96d);+ var anchorWindow = Window.GetWindow(anchor);+ var anchorHandle = anchorWindow is null ? _destinationHandle : new WindowInteropHelper(anchorWindow).Handle;+ var monitor = MonitorFromWindow(anchorHandle, MonitorDefaultToNearest);+ var monitorInfo = new MonitorInfo { Size = (uint)Marshal.SizeOf<MonitorInfo>() };+ if (!GetMonitorInfo(monitor, ref monitorInfo))+ {+ return false;+ }++ width = Math.Min(width, monitorInfo.Monitor.Right - monitorInfo.Monitor.Left);+ height = Math.Min(height, monitorInfo.Monitor.Bottom - monitorInfo.Monitor.Top);++ var left = (int)Math.Round(anchorTop.X) - width / 2;+ left = Math.Clamp(left, monitorInfo.Monitor.Left, monitorInfo.Monitor.Right - width);+ var gapDips = Application.Current?.Resources["PreviewGap"] is double g ? g : 18.0;+ // The hovered dock tile is magnified upward; keep the preview clear of its grown top edge.+ var resources = Application.Current?.Resources;+ if (resources?["DockTileSize"] is double tile && resources["DockHoverScale"] is double hoverScale && hoverScale > 1)+ {+ gapDips += tile * (hoverScale - 1);+ }+ var gap = (int)Math.Round(gapDips * dpi / 96d);+ var monitorBox = monitorInfo.Monitor;+ int top;+ switch (DockGeometry.Edge)+ {+ case Models.DockEdge.Top:+ top = Math.Min((int)Math.Round(anchorTop.Y) + gap, monitorBox.Bottom - height);+ break;+ case Models.DockEdge.Left:+ case Models.DockEdge.Right:+ // Beside the tile, centred on it, on the screen's inner side.+ top = Math.Clamp((int)Math.Round(anchorTop.Y) - height / 2, monitorBox.Top, monitorBox.Bottom - height);+ left = DockGeometry.Edge == Models.DockEdge.Left+ ? Math.Min((int)Math.Round(anchorTop.X) + gap, monitorBox.Right - width)+ : Math.Max((int)Math.Round(anchorTop.X) - width - gap, monitorBox.Left);+ break;+ default:+ top = (int)Math.Round(anchorTop.Y) - height - gap;+ if (top < monitorBox.Top)+ {+ var anchorHeight = (int)Math.Ceiling(anchor.ActualHeight * dpi / 96d);+ top = (int)Math.Round(anchorTop.Y) + anchorHeight + gap;+ }+ top = Math.Min(top, monitorBox.Bottom - height);+ break;+ }+ return SetWindowPos(_destinationHandle, HwndTopmost, left, top, width, height, SwpNoActivate);+ }++ private bool PositionOverlayWindow()+ {+ var overlayInterop = new WindowInteropHelper(_closeButtonWindow);+ if (!_closeButtonWindow.IsVisible)+ {+ overlayInterop.Owner = _destinationHandle;+ _closeButtonWindow.Show();+ }++ var overlayHandle = overlayInterop.Handle;+ if (overlayHandle == 0 || !GetWindowRect(_destinationHandle, out var previewRect))+ {+ return false;+ }++ var width = previewRect.Right - previewRect.Left;+ var height = previewRect.Bottom - previewRect.Top;+ return SetWindowPos(overlayHandle, HwndTopmost,+ previewRect.Left, previewRect.Top, width, height,+ SwpNoActivate | SwpNoOwnerZOrder);+ }++ private static NativeRect FitThumbnail(NativeSize source, NativeRect client)+ {+ const int inset = 2;+ var availableWidth = Math.Max(1, client.Right - client.Left - inset * 2);+ var availableHeight = Math.Max(1, client.Bottom - client.Top - inset * 2);+ var scale = Math.Min((double)availableWidth / source.Width, (double)availableHeight / source.Height);+ var width = Math.Max(1, (int)Math.Round(source.Width * scale));+ var height = Math.Max(1, (int)Math.Round(source.Height * scale));+ var left = client.Left + (client.Right - client.Left - width) / 2;+ var top = client.Top + (client.Bottom - client.Top - height) / 2;+ return new NativeRect(left, top, left + width, top + height);+ }++ private void ReleaseThumbnails()+ {+ _entranceTimer.Stop();+ foreach (var (_, thumbnail, _) in _activeThumbnails)+ {+ if (thumbnail != 0)+ {+ _ = DwmUnregisterThumbnail(thumbnail);+ }+ }+ _activeThumbnails.Clear();+ }++ private void Window_Closed(object? sender, EventArgs e)+ {+ _windowClosed = true;+ ReleaseThumbnails();+ _destinationHandle = 0;+ _sourceHandle = 0;+ if (!_closeWindowClosed)+ {+ _closeButtonWindow.Close();+ }+ }++ private void CloseButtonWindow_Closed(object? sender, EventArgs e)+ {+ _closeWindowClosed = true;+ }++ private void Window_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)+ {+ PointerEntered?.Invoke(this, EventArgs.Empty);+ }++ private static void PreviewWindow_SourceInitialized(object? sender, EventArgs e)+ {+ if (sender is Window window && PresentationSource.FromVisual(window) is HwndSource source)+ {+ source.AddHook(PreviewWindowProc);+ }+ }++ private static nint PreviewWindowProc(nint hwnd, int message, nint wParam, nint lParam, ref bool handled)+ {+ const int wmMouseActivate = 0x0021;+ const int maNoActivate = 3;+ if (message == wmMouseActivate)+ {+ handled = true;+ return maNoActivate;+ }++ return 0;+ }++ private void Window_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)+ {+ PointerLeft?.Invoke(this, EventArgs.Empty);+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct DwmThumbnailProperties+ {+ public uint Flags;+ public NativeRect Destination;+ public NativeRect Source;+ public byte Opacity;+ [MarshalAs(UnmanagedType.Bool)] public bool Visible;+ [MarshalAs(UnmanagedType.Bool)] public bool SourceClientAreaOnly;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct NativeRect(int left, int top, int right, int bottom)+ {+ public int Left = left;+ public int Top = top;+ public int Right = right;+ public int Bottom = bottom;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct NativeSize+ {+ public int Width;+ public int Height;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct MonitorInfo+ {+ public uint Size;+ public NativeRect Monitor;+ public NativeRect Work;+ public uint Flags;+ }++ [DllImport("dwmapi.dll")]+ private static extern int DwmRegisterThumbnail(nint destination, nint source, out nint thumbnail);++ [DllImport("dwmapi.dll")]+ private static extern int DwmQueryThumbnailSourceSize(nint thumbnail, out NativeSize size);++ [DllImport("dwmapi.dll")]+ private static extern int DwmUpdateThumbnailProperties(nint thumbnail, ref DwmThumbnailProperties properties);++ [DllImport("dwmapi.dll")]+ private static extern int DwmUnregisterThumbnail(nint thumbnail);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool IsWindow(nint windowHandle);++ [DllImport("user32.dll")]+ private static extern uint GetDpiForWindow(nint windowHandle);++ [DllImport("user32.dll")]+ private static extern nint MonitorFromWindow(nint windowHandle, uint flags);++ [DllImport("user32.dll", CharSet = CharSet.Unicode)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool GetMonitorInfo(nint monitor, ref MonitorInfo monitorInfo);++ [DllImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool GetWindowRect(nint windowHandle, out NativeRect rect);++ [DllImport("user32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool SetWindowPos(nint windowHandle, nint insertAfter, int x, int y, int width, int height, uint flags);+}diff --git a/Services/WindowsTaskbarPinImporter.cs b/Services/WindowsTaskbarPinImporter.csnew file mode 100644index 0000000..e5cf050--- /dev/null+++ b/Services/WindowsTaskbarPinImporter.cs@@ -0,0 +1,318 @@+using System.IO;+using System.Reflection;+using System.Runtime.InteropServices;+using QiDock.Models;++namespace QiDock.Services;++public static class WindowsTaskbarPinImporter+{+ public static (IReadOnlyList<DockApp> Apps, string? Error) Import()+ {+ var taskbarPinsPath = Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),+ "Microsoft",+ "Internet Explorer",+ "Quick Launch",+ "User Pinned",+ "TaskBar");++ if (!Directory.Exists(taskbarPinsPath))+ {+ return ([], null);+ }++ List<string> shortcutPaths;+ try+ {+ shortcutPaths = Directory.EnumerateFiles(taskbarPinsPath, "*.lnk", SearchOption.TopDirectoryOnly)+ .OrderBy(Path.GetFileName, StringComparer.CurrentCultureIgnoreCase)+ .ToList();+ }+ catch (IOException)+ {+ return ([], "Windows görev çubuğu kısayol klasörü okunamadı.");+ }+ catch (UnauthorizedAccessException)+ {+ return ([], "Windows görev çubuğu kısayol klasörüne erişim izni yok.");+ }++ if (shortcutPaths.Count == 0)+ {+ return ([], null);+ }++ Type? shellType;+ object? shell;+ try+ {+ shellType = Type.GetTypeFromProgID("WScript.Shell");+ shell = shellType is null ? null : Activator.CreateInstance(shellType);+ }+ catch (COMException)+ {+ return ([], "Windows kısayol hizmeti başlatılamadı; görev çubuğu uygulamaları içe aktarılamadı.");+ }+ catch (TargetInvocationException ex) when (ex.InnerException is COMException)+ {+ return ([], "Windows kısayol hizmeti başlatılamadı; görev çubuğu uygulamaları içe aktarılamadı.");+ }++ if (shellType is null || shell is null)+ {+ return ([], "Windows kısayol hizmeti başlatılamadı; görev çubuğu uygulamaları içe aktarılamadı.");+ }++ var apps = new List<DockApp>();+ var seenPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ var skippedCount = 0;+ try+ {+ foreach (var shortcutPath in shortcutPaths)+ {+ try+ {+ var shortcut = shellType.InvokeMember(+ "CreateShortcut",+ BindingFlags.InvokeMethod,+ binder: null,+ target: shell,+ args: [shortcutPath]);+ if (shortcut is null)+ {+ skippedCount++;+ continue;+ }++ try+ {+ var shortcutType = shortcut.GetType();+ var targetPath = ReadStringProperty(shortcutType, shortcut, "TargetPath");+ var arguments = ReadStringProperty(shortcutType, shortcut, "Arguments");+ var iconLocation = ReadStringProperty(shortcutType, shortcut, "IconLocation");+ var executablePath = ResolveExecutablePath(targetPath, iconLocation);+ if (executablePath is null || !seenPaths.Add(executablePath))+ {+ skippedCount++;+ continue;+ }++ apps.Add(new DockApp(Path.GetFileNameWithoutExtension(shortcutPath), executablePath)+ {+ LaunchArguments = string.IsNullOrWhiteSpace(arguments) ? null : arguments,+ ShortcutPath = Path.GetFullPath(shortcutPath)+ });+ }+ finally+ {+ if (Marshal.IsComObject(shortcut))+ {+ _ = Marshal.FinalReleaseComObject(shortcut);+ }+ }+ }+ catch (COMException)+ {+ skippedCount++;+ }+ catch (TargetInvocationException ex) when (ex.InnerException is COMException)+ {+ skippedCount++;+ }+ catch (IOException)+ {+ skippedCount++;+ }+ catch (UnauthorizedAccessException)+ {+ skippedCount++;+ }+ }+ }+ catch (COMException)+ {+ return (apps, "Windows kısayol hizmeti durdu; görev çubuğu uygulamalarının bir bölümü içe aktarılamadı.");+ }+ catch (TargetInvocationException ex) when (ex.InnerException is COMException)+ {+ return (apps, "Windows kısayol hizmeti durdu; görev çubuğu uygulamalarının bir bölümü içe aktarılamadı.");+ }+ finally+ {+ if (Marshal.IsComObject(shell))+ {+ _ = Marshal.FinalReleaseComObject(shell);+ }+ }++ var error = skippedCount == 0+ ? null+ : UiText.Format("SkippedPins", skippedCount);+ return (apps, error);+ }++ public static (string? ShortcutPath, string? Error) AddPin(string appName, string executablePath, string? launchArguments = null)+ {+ var pinDirectory = Path.GetFullPath(Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),+ "Microsoft",+ "Internet Explorer",+ "Quick Launch",+ "User Pinned",+ "TaskBar"));++ try+ {+ Directory.CreateDirectory(pinDirectory);+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ return (null, "Windows görev çubuğu sabitleme klasörü oluşturulamadı.");+ }++ var invalidChars = Path.GetInvalidFileNameChars();+ var safeName = new string(appName.Where(ch => !invalidChars.Contains(ch)).ToArray()).Trim();+ if (string.IsNullOrWhiteSpace(safeName))+ {+ safeName = Path.GetFileNameWithoutExtension(executablePath);+ }++ var shortcutPath = Path.Combine(pinDirectory, safeName + ".lnk");++ Type? shellType;+ object? shell;+ try+ {+ shellType = Type.GetTypeFromProgID("WScript.Shell");+ shell = shellType is null ? null : Activator.CreateInstance(shellType);+ }+ catch (COMException)+ {+ return (null, "Windows kısayol hizmeti başlatılamadı; sabitleme oluşturulamadı.");+ }+ catch (TargetInvocationException ex) when (ex.InnerException is COMException)+ {+ return (null, "Windows kısayol hizmeti başlatılamadı; sabitleme oluşturulamadı.");+ }++ if (shellType is null || shell is null)+ {+ return (null, "Windows kısayol hizmeti başlatılamadı; sabitleme oluşturulamadı.");+ }++ try+ {+ var shortcut = shellType.InvokeMember(+ "CreateShortcut",+ BindingFlags.InvokeMethod,+ binder: null,+ target: shell,+ args: [shortcutPath]);++ if (shortcut is null)+ {+ return (null, "Kısayol nesnesi oluşturulamadı.");+ }++ try+ {+ var shortcutType = shortcut.GetType();+ shortcutType.InvokeMember("TargetPath", BindingFlags.SetProperty, null, shortcut, [executablePath]);+ var workingDir = Path.GetDirectoryName(executablePath);+ if (!string.IsNullOrEmpty(workingDir))+ {+ shortcutType.InvokeMember("WorkingDirectory", BindingFlags.SetProperty, null, shortcut, [workingDir]);+ }+ if (!string.IsNullOrWhiteSpace(launchArguments))+ {+ shortcutType.InvokeMember("Arguments", BindingFlags.SetProperty, null, shortcut, [launchArguments]);+ }+ shortcutType.InvokeMember("Save", BindingFlags.InvokeMethod, null, shortcut, null);+ return (shortcutPath, null);+ }+ finally+ {+ if (Marshal.IsComObject(shortcut))+ {+ _ = Marshal.FinalReleaseComObject(shortcut);+ }+ }+ }+ catch (Exception ex) when (ex is COMException or TargetInvocationException or IOException or UnauthorizedAccessException)+ {+ return (null, "Uygulama Windows görev çubuğuna sabitlenemedi.");+ }+ finally+ {+ if (Marshal.IsComObject(shell))+ {+ _ = Marshal.FinalReleaseComObject(shell);+ }+ }+ }++ public static string? RemovePin(string shortcutPath)+ {+ var pinDirectory = Path.GetFullPath(Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),+ "Microsoft",+ "Internet Explorer",+ "Quick Launch",+ "User Pinned",+ "TaskBar"));+ var fullPath = Path.GetFullPath(shortcutPath);+ if (!string.Equals(Path.GetDirectoryName(fullPath), pinDirectory, StringComparison.OrdinalIgnoreCase)+ || !string.Equals(Path.GetExtension(fullPath), ".lnk", StringComparison.OrdinalIgnoreCase))+ {+ return "Kısayol Windows görev çubuğu sabitleme klasöründe değil.";+ }++ try+ {+ File.Delete(fullPath);+ return null;+ }+ catch (IOException)+ {+ return "Uygulama Windows görev çubuğu sabitlerinden kaldırılamadı.";+ }+ catch (UnauthorizedAccessException)+ {+ return "Görev çubuğu sabitini kaldırmak için erişim izni yok.";+ }+ }++ private static string? ResolveExecutablePath(string targetPath, string iconLocation)+ {+ var normalizedTarget = Environment.ExpandEnvironmentVariables(targetPath.Trim().Trim('"'));+ if (Path.GetExtension(normalizedTarget).Equals(".exe", StringComparison.OrdinalIgnoreCase)+ && File.Exists(normalizedTarget))+ {+ return Path.GetFullPath(normalizedTarget);+ }++ if (string.IsNullOrWhiteSpace(normalizedTarget))+ {+ var iconPath = iconLocation.Split(',', 2)[0].Trim().Trim('"');+ var normalizedIconPath = Environment.ExpandEnvironmentVariables(iconPath);+ if (string.Equals(Path.GetFileName(normalizedIconPath), "explorer.exe", StringComparison.OrdinalIgnoreCase)+ && File.Exists(normalizedIconPath))+ {+ return Path.GetFullPath(normalizedIconPath);+ }+ }++ return null;+ }++ private static string ReadStringProperty(Type shortcutType, object shortcut, string propertyName)+ {+ return shortcutType.InvokeMember(+ propertyName,+ BindingFlags.GetProperty,+ binder: null,+ target: shortcut,+ args: null) as string ?? string.Empty;+ }+}diff --git a/SettingsWindow.xaml b/SettingsWindow.xamlnew file mode 100644index 0000000..05f6bbb--- /dev/null+++ b/SettingsWindow.xaml@@ -0,0 +1,227 @@+<Window x:Class="QiDock.SettingsWindow"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="clr-namespace:QiDock.Services"+ xmlns:shell="clr-namespace:System.Windows.Shell;assembly=PresentationFramework"+ Title="{local:Loc SettingsTitle}" Width="820" Height="780" MinWidth="600" MinHeight="520"+ WindowStyle="None" ResizeMode="CanResize" Background="Transparent"+ WindowStartupLocation="CenterScreen" Foreground="{DynamicResource TextPrimary}"+ FontFamily="{StaticResource InterfaceFont}" FontSize="{StaticResource TextSizeBody}"+ UseLayoutRounding="True" SnapsToDevicePixels="True"+ Closing="Window_Closing" PreviewKeyDown="Window_PreviewKeyDown">+ <shell:WindowChrome.WindowChrome>+ <shell:WindowChrome CaptionHeight="48" ResizeBorderThickness="6" GlassFrameThickness="-1" UseAeroCaptionButtons="False" />+ </shell:WindowChrome.WindowChrome>+ <Window.Resources>+ <ResourceDictionary>+ <ResourceDictionary.MergedDictionaries>+ <ResourceDictionary Source="Design/SettingsControls.xaml" />+ </ResourceDictionary.MergedDictionaries>+ </ResourceDictionary>+ </Window.Resources>+ <Border x:Name="SettingsFrame" Background="{DynamicResource SettingsGlassMaterial}"+ BorderBrush="{DynamicResource MenuStroke}" BorderThickness="1">+ <Border.Style>+ <Style TargetType="Border">+ <Setter Property="CornerRadius" Value="12" />+ <Style.Triggers>+ <DataTrigger Binding="{Binding WindowState, RelativeSource={RelativeSource AncestorType=Window}}" Value="Maximized">+ <Setter Property="CornerRadius" Value="0" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ </Border.Style>+ <Grid>+ <Grid.RowDefinitions><RowDefinition Height="48" /><RowDefinition Height="Auto" /><RowDefinition Height="*" /><RowDefinition Height="Auto" /></Grid.RowDefinitions>+ <Grid>+ <TextBlock Text="{local:Loc SettingsTitle}" Margin="20,0,148,0" FontWeight="SemiBold"+ VerticalAlignment="Center" IsHitTestVisible="False" TextTrimming="CharacterEllipsis" />+ <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,5,6,5"+ shell:WindowChrome.IsHitTestVisibleInChrome="True">+ <Button Content="" Style="{StaticResource CaptionButton}" Click="Minimize_Click"+ ToolTip="{local:Loc Minimize}" AutomationProperties.Name="{local:Loc Minimize}" />+ <Button x:Name="MaximizeButton" Style="{StaticResource MaximizeCaptionButton}" Click="Maximize_Click" />+ <Button Content="" Style="{StaticResource CloseCaptionButton}" Click="Close_Click"+ ToolTip="{local:Loc Close}" AutomationProperties.Name="{local:Loc Close}" />+ </StackPanel>+ </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">+ <TabItem Header="{local:Loc General}">+ <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" CanContentScroll="False">+ <StackPanel Margin="{StaticResource SettingsPageInset}">+ <TextBlock Text="{local:Loc General}" Style="{StaticResource SettingsHeading}" />+ <Border Style="{StaticResource SettingsChoiceRow}" Margin="0,0,0,10"><StackPanel>+ <TextBlock Text="{local:Loc DockEdge}" Style="{StaticResource SettingsChoiceLabel}" />+ <UniformGrid Columns="4" Margin="-3,0">+ <RadioButton x:Name="EdgeBottom" GroupName="DockEdge" Content="{local:Loc DockEdgeBottom}" Style="{StaticResource SettingsChoice}" />+ <RadioButton x:Name="EdgeTop" GroupName="DockEdge" Content="{local:Loc DockEdgeTop}" Style="{StaticResource SettingsChoice}" />+ <RadioButton x:Name="EdgeLeft" GroupName="DockEdge" Content="{local:Loc DockEdgeLeft}" Style="{StaticResource SettingsChoice}" />+ <RadioButton x:Name="EdgeRight" GroupName="DockEdge" Content="{local:Loc DockEdgeRight}" Style="{StaticResource SettingsChoice}" />+ </UniformGrid>+ <TextBlock Text="{local:Loc DockEdgeHint}" Foreground="{DynamicResource TextSecondary}" TextWrapping="Wrap" FontSize="12" Margin="0,8,0,0" />+ </StackPanel></Border>+ <Border Style="{StaticResource SettingsChoiceRow}" Margin="0,0,0,10"><StackPanel>+ <TextBlock Text="{local:Loc WidgetPlacement}" Style="{StaticResource SettingsChoiceLabel}" />+ <UniformGrid Columns="1" Margin="-3,0">+ <RadioButton x:Name="WidgetsTop" GroupName="WidgetPlacement" Content="{local:Loc WidgetPlacementTop}" Style="{StaticResource SettingsChoice}" />+ <RadioButton x:Name="WidgetsDockLeft" GroupName="WidgetPlacement" Content="{local:Loc WidgetPlacementDockLeft}" Style="{StaticResource SettingsChoice}" />+ <RadioButton x:Name="WidgetsDockRight" GroupName="WidgetPlacement" Content="{local:Loc WidgetPlacementDockRight}" Style="{StaticResource SettingsChoice}" />+ </UniformGrid>+ </StackPanel></Border>+ <Border Style="{StaticResource SettingsRow}"><DockPanel>+ <CheckBox x:Name="StartupToggle" DockPanel.Dock="Right" Style="{StaticResource SettingsSwitch}"+ AutomationProperties.Name="{local:Loc Startup}" AutomationProperties.HelpText="{local:Loc StartupDescription}" />+ <TextBlock Text="{local:Loc Startup}" Style="{StaticResource SettingsRowLabel}" />+ </DockPanel></Border>+ <Border Style="{StaticResource SettingsRow}"><DockPanel>+ <CheckBox x:Name="AnimationsToggle" DockPanel.Dock="Right" Style="{StaticResource SettingsSwitch}"+ AutomationProperties.Name="{local:Loc Animations}" AutomationProperties.HelpText="{local:Loc AnimationsDescription}" />+ <TextBlock Text="{local:Loc Animations}" Style="{StaticResource SettingsRowLabel}" />+ </DockPanel></Border>+ <Border Style="{StaticResource SettingsRow}"><DockPanel>+ <CheckBox x:Name="GenieToggle" DockPanel.Dock="Right" Style="{StaticResource SettingsSwitch}"+ AutomationProperties.Name="{local:Loc GenieEffect}" AutomationProperties.HelpText="{local:Loc GenieEffectDescription}" />+ <TextBlock Text="{local:Loc GenieEffect}" Style="{StaticResource SettingsRowLabel}" />+ </DockPanel></Border>+ <Border Style="{StaticResource SettingsRow}"><DockPanel>+ <CheckBox x:Name="PreviewsToggle" DockPanel.Dock="Right" Style="{StaticResource SettingsSwitch}"+ AutomationProperties.Name="{local:Loc Previews}" AutomationProperties.HelpText="{local:Loc PreviewsDescription}" />+ <TextBlock Text="{local:Loc Previews}" Style="{StaticResource SettingsRowLabel}" />+ </DockPanel></Border>+ <Border Style="{StaticResource SettingsRow}"><DockPanel>+ <CheckBox x:Name="BadgesToggle" DockPanel.Dock="Right" Style="{StaticResource SettingsSwitch}"+ AutomationProperties.Name="{local:Loc Badges}" AutomationProperties.HelpText="{local:Loc BadgesDescription}" />+ <TextBlock Text="{local:Loc Badges}" Style="{StaticResource SettingsRowLabel}" />+ </DockPanel></Border>+ <Border Style="{StaticResource SettingsRow}"><DockPanel>+ <CheckBox x:Name="DockHudToggle" DockPanel.Dock="Right" Style="{StaticResource SettingsSwitch}"+ AutomationProperties.Name="{local:Loc DockHudSetting}" AutomationProperties.HelpText="{local:Loc DockHudSettingHelp}" />+ <TextBlock Text="{local:Loc DockHudSetting}" Style="{StaticResource SettingsRowLabel}" ToolTip="{local:Loc DockHudSettingHelp}" />+ </DockPanel></Border>+ <Border Style="{StaticResource SettingsRow}"><DockPanel>+ <CheckBox x:Name="ClaudeActivityToggle" DockPanel.Dock="Right" Style="{StaticResource SettingsSwitch}"+ AutomationProperties.Name="{local:Loc ClaudeActivitySetting}" AutomationProperties.HelpText="{local:Loc ClaudeActivitySettingHelp}" />+ <TextBlock Text="{local:Loc ClaudeActivitySetting}" Style="{StaticResource SettingsRowLabel}" ToolTip="{local:Loc ClaudeActivitySettingHelp}" />+ </DockPanel></Border>+ <Border Style="{StaticResource SettingsRow}"><DockPanel>+ <CheckBox x:Name="LowMemoryToggle" DockPanel.Dock="Right" Style="{StaticResource SettingsSwitch}"+ AutomationProperties.Name="{local:Loc LowMemory}" AutomationProperties.HelpText="{local:Loc LowMemoryHelp}" />+ <TextBlock Text="{local:Loc LowMemory}" Style="{StaticResource SettingsRowLabel}" />+ </DockPanel></Border>+ <StackPanel Margin="0,18,0,0">+ <TextBlock Text="{local:Loc AutoHide}" FontWeight="SemiBold" Margin="0,0,0,10" />+ <RadioButton x:Name="AutoHideDisabled" GroupName="AutoHide" Content="{local:Loc AutoHideDisabled}" Style="{StaticResource SettingsListChoice}" />+ <RadioButton x:Name="AutoHideSmart" GroupName="AutoHide" Content="{local:Loc AutoHideSmart}" Style="{StaticResource SettingsListChoice}" />+ <RadioButton x:Name="AutoHideAlways" GroupName="AutoHide" Content="{local:Loc AutoHideAlways}" Style="{StaticResource SettingsListChoice}" />+ </StackPanel>+ </StackPanel>+ </ScrollViewer>+ </TabItem>+ <TabItem Header="{local:Loc Appearance}">+ <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" CanContentScroll="False">+ <StackPanel Margin="{StaticResource SettingsPageInset}">+ <TextBlock Text="{local:Loc Appearance}" Style="{StaticResource SettingsHeading}" />+ <Border Style="{StaticResource SettingsChoiceRow}"><StackPanel>+ <TextBlock Text="{local:Loc Theme}" Style="{StaticResource SettingsChoiceLabel}" />+ <UniformGrid Columns="2" Margin="-3,0">+ <RadioButton x:Name="DarkTheme" GroupName="Theme" Content="{local:Loc Dark}" Style="{StaticResource SettingsChoice}" />+ <RadioButton x:Name="LightTheme" GroupName="Theme" Content="{local:Loc Light}" Style="{StaticResource SettingsChoice}" />+ </UniformGrid>+ </StackPanel></Border>+ <Border Style="{StaticResource SettingsChoiceRow}"><StackPanel>+ <TextBlock Text="{local:Loc LookStyle}" Style="{StaticResource SettingsChoiceLabel}" />+ <WrapPanel x:Name="StylePicker" Margin="-3,0" />+ <TextBlock Text="{local:Loc LookStyleHint}" Foreground="{DynamicResource TextSecondary}" TextWrapping="Wrap" FontSize="12" Margin="0,8,0,0" />+ </StackPanel></Border>+ <Border Style="{StaticResource SettingsChoiceRow}"><StackPanel>+ <TextBlock Text="{local:Loc Language}" Style="{StaticResource SettingsChoiceLabel}" />+ <UniformGrid Columns="2" Margin="-3,0">+ <RadioButton x:Name="TurkishLanguage" GroupName="Language" Content="Türkçe" Style="{StaticResource SettingsChoice}" />+ <RadioButton x:Name="EnglishLanguage" GroupName="Language" Content="English" Style="{StaticResource SettingsChoice}" />+ </UniformGrid>+ </StackPanel></Border>+ <Border Style="{StaticResource SettingsChoiceRow}"><StackPanel>+ <TextBlock Text="{local:Loc Position}" Style="{StaticResource SettingsChoiceLabel}" />+ <UniformGrid Columns="3" Margin="-3,0">+ <RadioButton x:Name="LeftPosition" GroupName="Position" Content="{local:Loc Left}" Style="{StaticResource SettingsChoice}" />+ <RadioButton x:Name="CenterPosition" GroupName="Position" Content="{local:Loc Center}" Style="{StaticResource SettingsChoice}" />+ <RadioButton x:Name="RightPosition" GroupName="Position" Content="{local:Loc Right}" Style="{StaticResource SettingsChoice}" />+ </UniformGrid>+ </StackPanel></Border>+ <StackPanel Margin="0,16,0,0">+ <DockPanel Margin="0,0,0,12">+ <TextBlock x:Name="OpacityValue" DockPanel.Dock="Right" Foreground="{DynamicResource TextSecondary}" />+ <TextBlock Text="{local:Loc SurfaceOpacity}" FontWeight="SemiBold" />+ </DockPanel>+ <Slider x:Name="OpacitySlider" Minimum="60" Maximum="100" Value="90" TickFrequency="5"+ IsSnapToTickEnabled="True" SmallChange="5" LargeChange="10" Style="{StaticResource SettingsOpacitySlider}"+ AutomationProperties.Name="{local:Loc SurfaceOpacity}" AutomationProperties.HelpText="{local:Loc SurfaceOpacityHelp}"+ ValueChanged="OpacitySlider_ValueChanged" />+ </StackPanel>+ <Border Style="{StaticResource SettingsRow}" Margin="0,18,0,0"><DockPanel>+ <CheckBox x:Name="MagnifyToggle" DockPanel.Dock="Right" Style="{StaticResource SettingsSwitch}"+ AutomationProperties.Name="{local:Loc Magnify}" AutomationProperties.HelpText="{local:Loc MagnifyDescription}" />+ <TextBlock Text="{local:Loc Magnify}" Style="{StaticResource SettingsRowLabel}" />+ </DockPanel></Border>+ <Border x:Name="MagnifyNote" Visibility="Collapsed" Margin="0,8,0,0" Padding="12,9" CornerRadius="10"+ Background="{DynamicResource WidgetTileFill}" BorderBrush="{DynamicResource WidgetTileStroke}" BorderThickness="1">+ <DockPanel>+ <TextBlock DockPanel.Dock="Left" Text="" FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets" FontSize="14"+ Foreground="{DynamicResource TextSecondary}" Margin="0,1,10,0" VerticalAlignment="Top" />+ <TextBlock x:Name="MagnifyNoteText" TextWrapping="Wrap" FontSize="12.5" Foreground="{DynamicResource TextSecondary}" />+ </DockPanel>+ </Border>+ <StackPanel x:Name="MagnifyScalePanel" Margin="0,12,0,0">+ <DockPanel Margin="0,0,0,12">+ <TextBlock x:Name="MagnifyValue" DockPanel.Dock="Right" Foreground="{DynamicResource TextSecondary}" />+ <TextBlock Text="{local:Loc MagnifyScale}" FontWeight="SemiBold" />+ </DockPanel>+ <Slider x:Name="MagnifySlider" Minimum="110" Maximum="220" Value="185" TickFrequency="5"+ IsSnapToTickEnabled="True" SmallChange="5" LargeChange="15" Style="{StaticResource SettingsOpacitySlider}"+ AutomationProperties.Name="{local:Loc MagnifyScale}"+ ValueChanged="MagnifySlider_ValueChanged" />+ </StackPanel>+ </StackPanel>+ </ScrollViewer>+ </TabItem>+ <TabItem x:Name="WidgetsTab" Header="{local:Loc Widgets}">+ <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" CanContentScroll="False">+ <StackPanel Margin="{StaticResource SettingsPageInset}">+ <TextBlock Text="{local:Loc Widgets}" Style="{StaticResource SettingsHeading}" />+ <TextBlock Text="{local:Loc WidgetsDescription}" Foreground="{DynamicResource TextSecondary}" TextWrapping="Wrap" Margin="0,-4,0,8" />+ <StackPanel x:Name="WidgetList" />+ <StackPanel Margin="0,22,0,0">+ <TextBlock Text="{local:Loc WeatherCity}" FontWeight="SemiBold" Margin="0,0,0,8" />+ <TextBox x:Name="WeatherCityBox" Style="{StaticResource SettingsTextBox}" MaxLength="80"+ AutomationProperties.Name="{local:Loc WeatherCity}" TextChanged="WidgetText_Changed" />+ <TextBlock Text="{local:Loc WeatherCityHelp}" Foreground="{DynamicResource TextSecondary}" TextWrapping="Wrap" Margin="0,6,0,0" FontSize="{StaticResource TextSizeCaption}" />+ </StackPanel>+ <StackPanel Margin="0,20,0,0">+ <TextBlock Text="{local:Loc CalendarFeed}" FontWeight="SemiBold" Margin="0,0,0,8" />+ <TextBox x:Name="CalendarFeedBox" Style="{StaticResource SettingsTextBox}" MaxLength="2000"+ AutomationProperties.Name="{local:Loc CalendarFeed}" TextChanged="WidgetText_Changed" />+ <TextBlock Text="{local:Loc CalendarFeedHelp}" Foreground="{DynamicResource TextSecondary}" TextWrapping="Wrap" Margin="0,6,0,0" FontSize="{StaticResource TextSizeCaption}" />+ </StackPanel>+ <Border Style="{StaticResource SettingsRow}" Margin="0,14,0,0"><DockPanel>+ <CheckBox x:Name="SecondsToggle" DockPanel.Dock="Right" Style="{StaticResource SettingsSwitch}"+ AutomationProperties.Name="{local:Loc ShowSeconds}" />+ <TextBlock Text="{local:Loc ShowSeconds}" Style="{StaticResource SettingsRowLabel}" />+ </DockPanel></Border>+ <TextBlock Text="{local:Loc AiLimitsHelp}" Foreground="{DynamicResource TextSecondary}" TextWrapping="Wrap" Margin="0,14,0,0" FontSize="{StaticResource TextSizeCaption}" />+ </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>+ <TextBlock x:Name="SaveStatus" Visibility="Collapsed" TextWrapping="Wrap" VerticalAlignment="Center"+ Foreground="{DynamicResource TextSecondary}" Margin="0,0,16,0" AutomationProperties.LiveSetting="Polite" />+ <Button x:Name="ApplyButton" Grid.Column="1" Content="{local:Loc Apply}" Style="{StaticResource SettingsButton}"+ IsEnabled="False" Click="Apply_Click" />+ </Grid>+ </Border>+ </Grid>+ </Border>+</Window>diff --git a/SettingsWindow.xaml.cs b/SettingsWindow.xaml.csnew file mode 100644index 0000000..b5e87e3--- /dev/null+++ b/SettingsWindow.xaml.cs@@ -0,0 +1,498 @@+using System.ComponentModel;+using System.Diagnostics;+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls.Primitives;+using System.Windows.Input;+using System.Windows.Interop;+using System.Windows.Shell;+using QiDock.Models;+using QiDock.Services;++namespace QiDock;++public partial class SettingsWindow : Window+{+ private readonly ApplicationPreferences _preferences;+ private readonly StartupRegistration _startup = new();+ private bool _startupEnabled;+ private bool _startupAvailable;+ private DockSettings _applied;+ private bool _closingApplication;+ private bool _initializing = true;+ private bool _sourceReady;+ private HwndSource? _source;+ private readonly List<string> _widgetOrder;+ private readonly HashSet<string> _hiddenWidgets;+ private readonly DockPreview _preview = new();++ public SettingsWindow(ApplicationPreferences preferences)+ {+ _preferences = preferences;+ _applied = preferences.Current;+ InitializeComponent();+ _preferences.Changed += Preferences_Changed;+ Closed += (_, _) =>+ {+ _preferences.Changed -= Preferences_Changed;+ if (_source is { IsDisposed: false }) _source.RemoveHook(WindowProc);+ ThemeManager.SetSurfaceOpacity(_preferences.Current.SurfaceOpacity);+ };+ _widgetOrder = [];+ _hiddenWidgets = [];+ BuildStylePicker();+ PreviewHost.Child = _preview;+ AddRowHelp();+ LoadControls(_applied);+ var startup = _startup.Read();+ _startupEnabled = startup.Enabled;+ _startupAvailable = startup.Error is null;+ StartupToggle.IsEnabled = _startupAvailable;+ if (startup.Error is not null)+ {+ StartupToggle.ToolTip = startup.Error;+ System.Windows.Controls.ToolTipService.SetShowOnDisabled(StartupToggle, true);+ }+ StartupToggle.IsChecked = _startupEnabled;+ var errors = new[] { preferences.LoadError, startup.Error }.OfType<string>();+ var message = string.Join(" ", errors.Select(UiText.LocalizeError));+ if (message.Length > 0) ShowResult(message, error: true);+ var workArea = SystemParameters.WorkArea;+ MinHeight = Math.Min(MinHeight, workArea.Height);+ MinWidth = Math.Min(MinWidth, workArea.Width);+ Height = Math.Min(Height, workArea.Height);+ Width = Math.Min(Width, workArea.Width);+ AddHandler(ToggleButton.CheckedEvent, new RoutedEventHandler(PreferenceEdited));+ AddHandler(ToggleButton.UncheckedEvent, new RoutedEventHandler(PreferenceEdited));+ _initializing = false;+ UpdateApplyState();+ }++ protected override void OnSourceInitialized(EventArgs e)+ {+ base.OnSourceInitialized(e);+ _source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);+ _source?.AddHook(WindowProc);+ _sourceReady = true;+ UpdateBackdrop();+ }++ private nint WindowProc(nint window, int message, nint wParam, nint lParam, ref bool handled)+ {+ if (message != 0x0024 || lParam == 0) return 0; // WM_GETMINMAXINFO+ var monitor = MonitorFromWindow(window, 2);+ var info = new MonitorInfo { Size = Marshal.SizeOf<MonitorInfo>() };+ if (monitor == 0 || !GetMonitorInfo(monitor, ref info))+ {+ Trace.TraceWarning("Settings monitor work area unavailable: {0}", Marshal.GetLastWin32Error());+ return 0;+ }+ var sizing = Marshal.PtrToStructure<MinMaxInfo>(lParam);+ sizing.MaxPosition = new NativePoint(info.Work.Left - info.Monitor.Left, info.Work.Top - info.Monitor.Top);+ sizing.MaxSize = new NativePoint(info.Work.Right - info.Work.Left, info.Work.Bottom - info.Work.Top);+ var dpi = GetDpiForWindow(window);+ var scale = dpi > 0 ? dpi / 96d : 1;+ sizing.MinTrackSize = new NativePoint((int)Math.Ceiling(MinWidth * scale), (int)Math.Ceiling(MinHeight * scale));+ Marshal.StructureToPtr(sizing, lParam, false);+ handled = true;+ return 0;+ }++ /// <summary>Puts the saved settings into the controls; what they show becomes the baseline for edits.</summary>+ private void LoadControls(DockSettings settings)+ {+ var wasInitializing = _initializing;+ _initializing = true;+ DarkTheme.IsChecked = settings.Theme == AppTheme.Dark;+ LightTheme.IsChecked = settings.Theme == AppTheme.Light;+ TurkishLanguage.IsChecked = settings.Language == AppLanguage.Turkish;+ EnglishLanguage.IsChecked = settings.Language == AppLanguage.English;+ LeftPosition.IsChecked = settings.Position == DockPosition.Left;+ CenterPosition.IsChecked = settings.Position == DockPosition.Center;+ RightPosition.IsChecked = settings.Position == DockPosition.Right;+ EdgeBottom.IsChecked = settings.Edge == DockEdge.Bottom;+ EdgeTop.IsChecked = settings.Edge == DockEdge.Top;+ EdgeLeft.IsChecked = settings.Edge == DockEdge.Left;+ EdgeRight.IsChecked = settings.Edge == DockEdge.Right;+ WidgetsTop.IsChecked = settings.WidgetPlacement == WidgetPlacement.TopBar;+ WidgetsDockLeft.IsChecked = settings.WidgetPlacement == WidgetPlacement.DockLeft;+ WidgetsDockRight.IsChecked = settings.WidgetPlacement == WidgetPlacement.DockRight;+ AnimationsToggle.IsChecked = settings.AnimationsEnabled;+ GenieToggle.IsChecked = settings.GenieEffectEnabled;+ PreviewsToggle.IsChecked = settings.PreviewsEnabled;+ BadgesToggle.IsChecked = settings.NotificationBadgesEnabled;+ DockHudToggle.IsChecked = settings.DockHud;+ ClaudeActivityToggle.IsChecked = settings.ClaudeActivity;+ LowMemoryToggle.IsChecked = settings.LowMemory;+ AutoHideDisabled.IsChecked = settings.AutoHide == AutoHideMode.Disabled;+ AutoHideSmart.IsChecked = settings.AutoHide == AutoHideMode.Smart;+ AutoHideAlways.IsChecked = settings.AutoHide == AutoHideMode.Always;+ OpacitySlider.Value = settings.SurfaceOpacity * 100;+ MagnifyToggle.IsChecked = settings.Magnify;+ MagnifySlider.Value = Math.Clamp(settings.MagnifyScale, 1.1, 2.2) * 100;+ var style = ThemeStyles.Find(settings.Style).Id;+ foreach (var choice in StylePicker.Children.OfType<System.Windows.Controls.RadioButton>())+ choice.IsChecked = (string)choice.Tag == style;+ var widgets = settings.WidgetOptions;+ _widgetOrder.Clear();+ _widgetOrder.AddRange(widgets.EffectiveOrder);+ _hiddenWidgets.Clear();+ _hiddenWidgets.UnionWith(widgets.Hidden ?? []);+ WeatherCityBox.Text = widgets.WeatherCity;+ CalendarFeedBox.Text = widgets.CalendarFeedUrl ?? "";+ SecondsToggle.IsChecked = widgets.ShowSeconds;+ BuildWidgetList();+ UpdateOpacityLabel();+ UpdateGenieAvailability();+ _initializing = wasInitializing;+ UpdatePreview();+ }++ /// <summary>The genie effect needs animations: without them its switch would be on but do nothing.</summary>+ private void UpdateGenieAvailability()+ {+ // In low-memory mode the genie stutters (it is drawn on the processor), so it stays off there.+ GenieToggle.IsEnabled = AnimationsToggle.IsChecked == true && LowMemoryToggle.IsChecked != true;+ // The magnification is an animation too; its size only matters while it is on.+ MagnifyToggle.IsEnabled = AnimationsToggle.IsChecked == true;+ MagnifyScalePanel.IsEnabled = MagnifyToggle.IsChecked == true && MagnifyToggle.IsEnabled;+ MagnifyScalePanel.Opacity = MagnifyScalePanel.IsEnabled ? 1 : 0.45;+ MagnifyValue.Text = UiText.Format("OpacityPercent", (int)Math.Round(MagnifySlider.Value));+ // A gentle note, not a dialog: what the magnification costs, and that it stutters while low-memory mode is on.+ var magnifyOn = MagnifyToggle.IsChecked == true && MagnifyToggle.IsEnabled;+ MagnifyNote.Visibility = magnifyOn ? Visibility.Visible : Visibility.Collapsed;+ MagnifyNoteText.Text = UiText.Get(LowMemoryToggle.IsChecked == true ? "MagnifyNoteLowMemory" : "MagnifyNote");+ }++ /// <summary>The dock picture follows the controls (not the saved settings) on every edit.</summary>+ private void UpdatePreview(bool showMagnify = false)+ {+ var settings = ReadSelection();+ _preview.Show(settings, settings.WidgetOptions.VisibleWidgets.Count(), showMagnify);+ }++ /// <summary>+ /// Each switch row shows what it does under its name (the same words screen readers get), so nothing has to be+ /// found out by trying.+ /// </summary>+ private void AddRowHelp()+ {+ foreach (var row in LogicalChildren<System.Windows.Controls.DockPanel>(this).ToList())+ {+ var toggle = row.Children.OfType<System.Windows.Controls.CheckBox>().FirstOrDefault();+ var label = row.Children.OfType<System.Windows.Controls.TextBlock>().FirstOrDefault();+ if (toggle is null || label is null) continue;+ var binding = System.Windows.Data.BindingOperations.GetBindingBase(toggle, System.Windows.Automation.AutomationProperties.HelpTextProperty);+ var text = System.Windows.Automation.AutomationProperties.GetHelpText(toggle);+ if (binding is null && string.IsNullOrWhiteSpace(text)) continue;+ var help = new System.Windows.Controls.TextBlock { TextWrapping = TextWrapping.Wrap, FontSize = 12, Margin = new Thickness(0, 2, 16, 0) };+ help.SetResourceReference(ForegroundProperty, "TextSecondary");+ if (binding is not null) help.SetBinding(System.Windows.Controls.TextBlock.TextProperty, binding);+ else help.Text = text;+ var index = row.Children.IndexOf(label);+ row.Children.Remove(label);+ var stack = new System.Windows.Controls.StackPanel { VerticalAlignment = VerticalAlignment.Center };+ stack.Children.Add(label);+ stack.Children.Add(help);+ row.Children.Insert(index, stack);+ }+ }++ private static IEnumerable<T> LogicalChildren<T>(DependencyObject parent) where T : DependencyObject+ {+ foreach (var child in LogicalTreeHelper.GetChildren(parent).OfType<DependencyObject>())+ {+ if (child is T match) yield return match;+ foreach (var nested in LogicalChildren<T>(child)) yield return nested;+ }+ }++ private void Preferences_Changed(object? sender, EventArgs e)+ {+ // Changed elsewhere (dock menu, edit mode, another profile): show it here too unless the user is+ // in the middle of editing; then only the fields they edit are written back on Apply.+ if (!HasEdits())+ {+ _applied = _preferences.Current;+ LoadControls(_applied);+ UpdateApplyState();+ }+ ThemeManager.SetSurfaceOpacity(Math.Round(OpacitySlider.Value) / 100);+ UpdateOpacityLabel();+ UpdateBackdrop();+ }++ private void UpdateBackdrop()+ {+ if (!_sourceReady) return;+ var glass = SettingsBackdrop.TryEnable(this, _preferences.Current.Theme);+ SettingsFrame.SetResourceReference(System.Windows.Controls.Border.BackgroundProperty, glass ? "SettingsGlassMaterial" : "SettingsBackground");+ if (glass)+ {+ WindowChrome.GetWindowChrome(this).GlassFrameThickness = new Thickness(-1);+ SettingsFrame.ClearValue(System.Windows.Controls.Border.CornerRadiusProperty);+ }+ else+ {+ WindowChrome.GetWindowChrome(this).GlassFrameThickness = new Thickness(0);+ SettingsFrame.CornerRadius = new CornerRadius(0);+ }+ }++ /// <summary>+ /// The saved settings with this window's edits on top: only fields the user changed here (compared with+ /// what the window showed) are taken from the controls, so changes made elsewhere meanwhile are kept.+ /// </summary>+ private DockSettings ReadSelection()+ {+ var now = _preferences.Current;+ var shown = _applied;+ static T Pick<T>(T control, T wasShown, T saved) => EqualityComparer<T>.Default.Equals(control, wasShown) ? saved : control;+ var widgets = now.WidgetOptions;+ var shownWidgets = shown.WidgetOptions;+ var city = string.IsNullOrWhiteSpace(WeatherCityBox.Text) ? "İstanbul" : WeatherCityBox.Text.Trim();+ var feed = string.IsNullOrWhiteSpace(CalendarFeedBox.Text) ? null : CalendarFeedBox.Text.Trim();+ return now with+ {+ Theme = Pick(LightTheme.IsChecked == true ? AppTheme.Light : AppTheme.Dark, shown.Theme, now.Theme),+ Language = Pick(EnglishLanguage.IsChecked == true ? AppLanguage.English : AppLanguage.Turkish, shown.Language, now.Language),+ Position = Pick(RightPosition.IsChecked == true ? DockPosition.Right : CenterPosition.IsChecked == true ? DockPosition.Center : DockPosition.Left, shown.Position, now.Position),+ Edge = Pick(EdgeTop.IsChecked == true ? DockEdge.Top : EdgeLeft.IsChecked == true ? DockEdge.Left : EdgeRight.IsChecked == true ? DockEdge.Right : DockEdge.Bottom, shown.Edge, now.Edge),+ WidgetPlacement = Pick(WidgetsDockLeft.IsChecked == true ? WidgetPlacement.DockLeft : WidgetsDockRight.IsChecked == true ? WidgetPlacement.DockRight : WidgetPlacement.TopBar, shown.WidgetPlacement, now.WidgetPlacement),+ AnimationsEnabled = Pick(AnimationsToggle.IsChecked == true, shown.AnimationsEnabled, now.AnimationsEnabled),+ GenieEffectEnabled = Pick(GenieToggle.IsChecked == true, shown.GenieEffectEnabled, now.GenieEffectEnabled),+ PreviewsEnabled = Pick(PreviewsToggle.IsChecked == true, shown.PreviewsEnabled, now.PreviewsEnabled),+ NotificationBadgesEnabled = Pick(BadgesToggle.IsChecked == true, shown.NotificationBadgesEnabled, now.NotificationBadgesEnabled),+ DockHud = Pick(DockHudToggle.IsChecked == true, shown.DockHud, now.DockHud),+ ClaudeActivity = Pick(ClaudeActivityToggle.IsChecked == true, shown.ClaudeActivity, now.ClaudeActivity),+ LowMemory = Pick(LowMemoryToggle.IsChecked == true, shown.LowMemory, now.LowMemory),+ AutoHide = Pick(AutoHideAlways.IsChecked == true ? AutoHideMode.Always : AutoHideSmart.IsChecked == true ? AutoHideMode.Smart : AutoHideMode.Disabled, shown.AutoHide, now.AutoHide),+ Style = Pick(SelectedStyle(), ThemeStyles.Find(shown.Style).Id, now.Style),+ SurfaceOpacity = Pick(Math.Round(OpacitySlider.Value) / 100, Math.Round(shown.SurfaceOpacity * 100) / 100, now.SurfaceOpacity),+ Magnify = Pick(MagnifyToggle.IsChecked == true, shown.Magnify, now.Magnify),+ MagnifyScale = Pick(Math.Round(MagnifySlider.Value) / 100, Math.Round(Math.Clamp(shown.MagnifyScale, 1.1, 2.2) * 100) / 100, now.MagnifyScale),+ // Keep the fields this window does not edit (profiles, to-dos, colors, shelf…).+ Widgets = KeepUnset(now.Widgets, widgets, widgets with+ {+ Order = _widgetOrder.SequenceEqual(shownWidgets.EffectiveOrder) ? widgets.Order : _widgetOrder.ToList(),+ Hidden = _hiddenWidgets.SetEquals(shownWidgets.Hidden ?? []) ? widgets.Hidden : _hiddenWidgets.OrderBy(id => id, StringComparer.Ordinal).ToList(),+ WeatherCity = Pick(city, shownWidgets.WeatherCity, widgets.WeatherCity),+ CalendarFeedUrl = Pick(feed, shownWidgets.CalendarFeedUrl, widgets.CalendarFeedUrl),+ ShowSeconds = Pick(SecondsToggle.IsChecked == true, shownWidgets.ShowSeconds, widgets.ShowSeconds)+ })+ };+ }++ /// <summary>Unset widget settings stay unset while nothing in them was edited.</summary>+ private static WidgetSettings? KeepUnset(WidgetSettings? saved, WidgetSettings defaults, WidgetSettings edited) =>+ saved is null && edited == defaults ? null : edited;++ private void BuildWidgetList()+ {+ WidgetList.Children.Clear();+ for (var index = 0; index < _widgetOrder.Count; index++)+ {+ var id = _widgetOrder[index];+ var position = index;+ var row = new System.Windows.Controls.Border();+ row.SetResourceReference(StyleProperty, "SettingsRow");+ var panel = new System.Windows.Controls.DockPanel();++ var actions = new System.Windows.Controls.StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };+ System.Windows.Controls.DockPanel.SetDock(actions, System.Windows.Controls.Dock.Right);+ actions.Children.Add(OrderButton("M18 15l-6-6-6 6", UiText.Get("MoveUp"), position > 0, () => MoveWidget(position, -1)));+ actions.Children.Add(OrderButton("M6 9l6 6 6-6", UiText.Get("MoveDown"), position < _widgetOrder.Count - 1, () => MoveWidget(position, 1)));+ var toggle = new System.Windows.Controls.CheckBox { IsChecked = !_hiddenWidgets.Contains(id) };+ toggle.SetResourceReference(StyleProperty, "SettingsSwitch");+ System.Windows.Automation.AutomationProperties.SetName(toggle, UiText.Get("Widget_" + id));+ toggle.Checked += (_, _) => _hiddenWidgets.Remove(id);+ toggle.Unchecked += (_, _) => _hiddenWidgets.Add(id);+ actions.Children.Add(toggle);+ panel.Children.Add(actions);++ var text = new System.Windows.Controls.StackPanel { VerticalAlignment = VerticalAlignment.Center };+ text.Children.Add(new System.Windows.Controls.TextBlock { Text = UiText.Get("Widget_" + id), FontWeight = FontWeights.SemiBold });+ var description = new System.Windows.Controls.TextBlock { Text = UiText.Get("WidgetDescription_" + id), TextWrapping = TextWrapping.Wrap, FontSize = 12, Margin = new Thickness(0, 2, 12, 0) };+ description.SetResourceReference(ForegroundProperty, "TextSecondary");+ text.Children.Add(description);+ panel.Children.Add(text);+ row.Child = panel;+ WidgetList.Children.Add(row);+ }+ }++ private System.Windows.Controls.Button OrderButton(string geometry, string label, bool enabled, Action move)+ {+ var path = new System.Windows.Shapes.Path+ {+ Data = System.Windows.Media.Geometry.Parse(geometry),+ Width = 12, Height = 12, Stretch = System.Windows.Media.Stretch.Uniform, StrokeThickness = 2,+ StrokeStartLineCap = System.Windows.Media.PenLineCap.Round, StrokeEndLineCap = System.Windows.Media.PenLineCap.Round,+ StrokeLineJoin = System.Windows.Media.PenLineJoin.Round+ };+ path.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, "TextPrimary");+ var button = new System.Windows.Controls.Button { Content = path, IsEnabled = enabled, ToolTip = label };+ System.Windows.Automation.AutomationProperties.SetName(button, label);+ button.SetResourceReference(StyleProperty, "SettingsOrderButton");+ button.Click += (_, _) => move();+ return button;+ }++ private void MoveWidget(int index, int delta)+ {+ var target = index + delta;+ if (target < 0 || target >= _widgetOrder.Count) return;+ (_widgetOrder[index], _widgetOrder[target]) = (_widgetOrder[target], _widgetOrder[index]);+ BuildWidgetList();+ PreferenceEdited(this, new RoutedEventArgs());+ }++ private void WidgetText_Changed(object sender, System.Windows.Controls.TextChangedEventArgs e) => PreferenceEdited(sender, e);++ private void Apply_Click(object sender, RoutedEventArgs e)+ {+ var startupChanged = _startupAvailable && StartupToggle.IsChecked != _startupEnabled;+ if (startupChanged && _startup.SetEnabled(StartupToggle.IsChecked == true) is { } startupError)+ {+ ShowResult(startupError, error: true);+ return;+ }+ var settings = ReadSelection();+ if (_preferences.Save(settings) is { } error)+ {+ error = UiText.LocalizeError(error);+ if (startupChanged && _startup.SetEnabled(_startupEnabled) is not null)+ error += " " + UiText.Get("StartupRestoreError");+ ShowResult(error, error: true);+ return;+ }+ _applied = settings;+ _startupEnabled = StartupToggle.IsChecked == true;+ ShowResult(UiText.Get("SettingsSaved"), error: false);+ UpdateApplyState();+ // The drawing mode is chosen at start: offer to restart when it no longer matches.+ if (Application.Current is App app && app.SoftwareRendering != settings.LowMemory+ && MessageBox.Show(this, UiText.Get("LowMemoryRestart"), "QiDock", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) == MessageBoxResult.Yes)+ app.Restart();+ }++ private void ShowResult(string message, bool error)+ {+ SaveStatus.Text = UiText.LocalizeError(message);+ SaveStatus.Visibility = Visibility.Visible;+ SaveStatus.SetResourceReference(ForegroundProperty, error ? "DangerText" : "TextSecondary");+ }++ private void Window_Closing(object? sender, CancelEventArgs e)+ {+ if (_closingApplication || Application.Current.Dispatcher.HasShutdownStarted) return;+ if (!HasEdits()) return;+ e.Cancel = MessageBox.Show(this, UiText.Get("DiscardChanges"), UiText.Get("DiscardTitle"),+ MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) != MessageBoxResult.Yes;+ }++ /// <summary>One chip per look: three dots of its colours 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 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 });+ var choice = new System.Windows.Controls.RadioButton { GroupName = "LookStyle", Content = content, Tag = look.Id, Margin = new Thickness(3, 0, 3, 6), Padding = new Thickness(9, 7, 12, 7) };+ choice.SetResourceReference(StyleProperty, "SettingsChoice");+ System.Windows.Automation.AutomationProperties.SetName(choice, look.Name);+ StylePicker.Children.Add(choice);+ }+ }++ private string SelectedStyle() =>+ StylePicker.Children.OfType<System.Windows.Controls.RadioButton>().FirstOrDefault(c => c.IsChecked == true)?.Tag as string ?? ThemeStyles.Glass;++ private bool HasEdits()+ {+ // Unedited fields come from the saved settings, so anything changed elsewhere never counts as an edit here.+ // (Lists are reused when unedited, so record equality is exact.)+ return ReadSelection() != _preferences.Current+ || (_startupAvailable && StartupToggle.IsChecked != _startupEnabled);+ }++ private void PreferenceEdited(object sender, RoutedEventArgs e)+ {+ if (_initializing) return;+ UpdateGenieAvailability();+ SaveStatus.Visibility = Visibility.Collapsed;+ UpdateApplyState();+ UpdatePreview(showMagnify: ReferenceEquals(e.OriginalSource, MagnifyToggle) && MagnifyToggle.IsChecked == true);+ }++ private void MagnifySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)+ {+ if (_initializing) return;+ UpdateGenieAvailability();+ SaveStatus.Visibility = Visibility.Collapsed;+ UpdateApplyState();+ UpdatePreview(showMagnify: true);+ }++ private void UpdateApplyState() => ApplyButton.IsEnabled = HasEdits() || _preferences.LoadError is not null;++ private void UpdateOpacityLabel() => OpacityValue.Text = UiText.Format("OpacityPercent", (int)Math.Round(OpacitySlider.Value));++ private void OpacitySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)+ {+ if (_initializing) return;+ UpdateOpacityLabel();+ ThemeManager.SetSurfaceOpacity(Math.Round(e.NewValue) / 100);+ PreferenceEdited(sender, e);+ }++ private void Minimize_Click(object sender, RoutedEventArgs e) => SystemCommands.MinimizeWindow(this);+ private void Maximize_Click(object sender, RoutedEventArgs e)+ {+ if (WindowState == WindowState.Maximized) SystemCommands.RestoreWindow(this);+ else SystemCommands.MaximizeWindow(this);+ }+ private void Close_Click(object sender, RoutedEventArgs e) => Close();++ internal void SelectWidgetsTab() => SettingsTabs.SelectedItem = WidgetsTab;++ internal void CloseForShutdown()+ {+ _closingApplication = true;+ Close();+ }++ private void Window_PreviewKeyDown(object sender, KeyEventArgs e)+ {+ if (e.Key != Key.Escape) return;+ e.Handled = true;+ Close();+ }++ [StructLayout(LayoutKind.Sequential)] private struct NativePoint(int x, int y) { public int X = x; public int Y = y; }+ [StructLayout(LayoutKind.Sequential)] private struct NativeRect { public int Left, Top, Right, Bottom; }+ [StructLayout(LayoutKind.Sequential)] private struct MonitorInfo { public int Size; public NativeRect Monitor, Work; public uint Flags; }+ [StructLayout(LayoutKind.Sequential)] private struct MinMaxInfo { public NativePoint Reserved, MaxSize, MaxPosition, MinTrackSize, MaxTrackSize; }+ [DllImport("user32.dll")] private static extern nint MonitorFromWindow(nint window, uint flags);+ [DllImport("user32.dll", EntryPoint = "GetMonitorInfoW", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetMonitorInfo(nint monitor, ref MonitorInfo info);+ [DllImport("user32.dll")] private static extern uint GetDpiForWindow(nint window);++}diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..ba25510--- /dev/null+++ b/THIRD_PARTY_NOTICES.md@@ -0,0 +1,53 @@+# Third-Party Notices++QiDock includes material from the projects below. Their licenses require these notices to travel with the software.++## Lucide icons++Most outline icons in `Design/Theme.xaml` and `Design/Widgets.xaml` are path data from [Lucide](https://lucide.dev) (some redrawn or adapted for the 24×24 box used here).++```+ISC License++Copyright (c) 2026 Lucide Icons and Contributors++Permission to use, copy, modify, and/or distribute this software for any+purpose with or without fee is hereby granted, provided that the above+copyright notice and this permission notice appear in all copies.++THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.++---++The following Lucide icons are derived from the Feather project:++airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out++The MIT License (MIT) (for the icons listed above)++Copyright (c) 2013-present Cole Bemis++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+```diff --git a/TopBarWindow.cs b/TopBarWindow.csnew file mode 100644index 0000000..d048e36--- /dev/null+++ b/TopBarWindow.cs@@ -0,0 +1,392 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Interop;+using System.Windows.Media;+using System.Windows.Media.Animation;+using System.Windows.Media.Effects;+using System.Windows.Threading;++namespace QiDock;++/// <summary>+/// Glass widget strip at the top of the primary screen. It stays on screen while the desktop is+/// clean (no app window open on the primary monitor) and steps aside as soon as a window is open.+/// With "peek" on, resting the pointer on the top edge brings it down until the pointer leaves.+/// While hidden nothing in it renders, and the widgets drop their fast timers (see <see cref="LiveChanged"/>).+/// </summary>+public sealed class TopBarWindow : Window+{+ private const double TopGap = 8;+ private const double ShadowRoom = 18;+ private static readonly TimeSpan EdgeDwell = TimeSpan.FromMilliseconds(600);+ private static readonly TimeSpan LeaveDelay = TimeSpan.FromMilliseconds(400);++ private readonly Border _surface;+ private readonly Border _tabs;+ private readonly TranslateTransform _slide = new();+ private readonly DispatcherTimer _edgeWatch = new(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(150) };+ private Func<bool> _isLocked = () => false;+ private bool _desktopClean;+ private bool _suppressed;+ private bool _hasContent;+ private bool _peekEnabled = true;+ private bool _peeking;+ private bool _shown;+ private DateTime _edgeSince;+ private DateTime _leftSince;+ private NativePoint _edgePoint;++ /// <summary>True while the bar is on screen; the widgets only need their live timers then.</summary>+ public event EventHandler<bool>? LiveChanged;++ /// <summary>Right-click on the bar (the dock's menu: widgets, edit mode, city and so on).</summary>+ public event EventHandler? MenuRequested;++ public TopBarWindow()+ {+ WindowStyle = WindowStyle.None;+ ResizeMode = ResizeMode.NoResize;+ AllowsTransparency = true;+ Background = Brushes.Transparent;+ ShowInTaskbar = false;+ ShowActivated = false;+ Topmost = true;+ SizeToContent = SizeToContent.WidthAndHeight;+ WindowStartupLocation = WindowStartupLocation.Manual;+ UseLayoutRounding = true;+ SnapsToDevicePixels = true;+ Title = "QiDock Widgets";+ SetResourceReference(FontFamilyProperty, "InterfaceFont");++ _surface = new Border+ {+ Margin = new Thickness(ShadowRoom),+ Padding = new Thickness(6, 5, 6, 5),+ CornerRadius = new CornerRadius(22),+ BorderThickness = new Thickness(1),+ RenderTransform = _slide,+ Opacity = 0,+ Effect = new DropShadowEffect { Color = Colors.Black, BlurRadius = 18, ShadowDepth = 3, Direction = 270, Opacity = 0.34, RenderingBias = RenderingBias.Performance }+ };+ _surface.SetResourceReference(Border.BackgroundProperty, "DockMaterial");+ _surface.SetResourceReference(Border.BorderBrushProperty, "DockBorderMaterial");++ // Profile tabs sit under the bar and fade in while the pointer is over it. Fully transparent+ // pixels let clicks through, so the hidden strip never blocks the desktop.+ _tabs = new Border+ {+ Margin = new Thickness(ShadowRoom, -10, ShadowRoom, 10),+ Padding = new Thickness(4, 3, 4, 3),+ CornerRadius = new CornerRadius(13),+ HorizontalAlignment = HorizontalAlignment.Center,+ Opacity = 0,+ IsHitTestVisible = false+ };+ _tabs.SetResourceReference(Border.BackgroundProperty, "DockMaterial");+ var layout = new StackPanel();+ layout.Children.Add(_surface);+ layout.Children.Add(_tabs);+ Content = layout;+ MouseEnter += (_, _) => ShowTabs(true);+ Widgets.WidgetPopup.AnyOpened += (_, _) => ShowTabs(false);+ MouseLeave += (_, _) => ShowTabs(_isLocked());++ SizeChanged += (_, _) => Reposition();+ SystemParameters.StaticPropertyChanged += (_, e) =>+ {+ if (e.PropertyName == nameof(SystemParameters.WorkArea)) Dispatcher.InvokeAsync(Reposition);+ };+ MouseRightButtonUp += (_, e) =>+ {+ e.Handled = true;+ MenuRequested?.Invoke(this, EventArgs.Empty);+ };+ _edgeWatch.Tick += (_, _) => WatchPointer();+ }++ public UIElement? Bar+ {+ get => _surface.Child;+ set => _surface.Child = value;+ }++ public nint Handle { get; private set; }++ public UIElement? Tabs+ {+ get => _tabs.Child;+ set => _tabs.Child = value;+ }++ public void ShowTabs(bool show)+ {+ _tabs.IsHitTestVisible = show;+ _tabs.BeginAnimation(OpacityProperty, new DoubleAnimation(show ? 1 : 0, TimeSpan.FromMilliseconds(show ? 140 : 220)) { BeginTime = show ? TimeSpan.Zero : TimeSpan.FromMilliseconds(250) });+ }++ /// <summary>+ /// Where a card grows out of a tile of this bar (screen DIPs): from the bar's bottom edge, downwards, like a card+ /// grows out of a dock on the top edge. Null while the bar is not on screen.+ /// </summary>+ public EdgePanel.DockAnchor? AnchorOf(FrameworkElement element)+ {+ if (!_shown || !IsVisible || element.ActualWidth <= 0 || !element.IsDescendantOf(this)) return null;+ if (VisualTreeHelper.GetParent(_surface) is not Visual parent) return null;+ // Where the bar rests, not where its slide has it now.+ var tile = element.TransformToAncestor(this).TransformBounds(new Rect(element.RenderSize));+ tile.Offset(0, -_slide.Y);+ var surface = parent.TransformToAncestor(this).TransformBounds(new Rect((Point)VisualTreeHelper.GetOffset(_surface), _surface.RenderSize));+ var round = _surface.CornerRadius.BottomLeft + 6;+ return new EdgePanel.DockAnchor(Models.DockEdge.Top, Left + (tile.Left + tile.Right) / 2, tile.Width, Top + surface.Bottom,+ Left + surface.Left + round, Left + surface.Right - round);+ }++ /// <summary>Leaves the bar's bottom edge out under a card standing on it (screen DIPs on the card's foot line), or draws it whole (null).</summary>+ public void CutSeam((Point From, Point To)? seam)+ {+ if (seam is not { } line || _surface.ActualWidth <= 0)+ {+ _surface.OpacityMask = null;+ return;+ }+ var a = TranslatePoint(new Point(line.From.X - Left, line.From.Y - Top), _surface);+ var b = TranslatePoint(new Point(line.To.X - Left, line.To.Y - Top), _surface);+ var size = new Size(_surface.ActualWidth, _surface.ActualHeight);+ var depth = Math.Max(0, size.Height - Math.Min(a.Y, b.Y));+ _surface.OpacityMask = EdgePanel.NotchMask(size, Math.Min(a.X, b.X), Math.Max(a.X, b.X), depth, bottom: true);+ }++ private Effect? _shadow;++ /// <summary>While a card stands on the bar the two are one solid piece: no edge line and no shadow.</summary>+ public void SetJoined(Brush? solid)+ {+ if (solid is not null)+ {+ // The bar's material is lightest at its top, the card's at its foot: turned over, the two meet in one colour.+ if (solid is LinearGradientBrush gradient)+ {+ var turned = gradient.Clone();+ (turned.StartPoint, turned.EndPoint) = (gradient.EndPoint, gradient.StartPoint);+ turned.Freeze();+ solid = turned;+ }+ _surface.Background = solid;+ _surface.BorderBrush = solid;+ _shadow ??= _surface.Effect;+ _surface.Effect = null;+ return;+ }+ _surface.SetResourceReference(Border.BackgroundProperty, "DockMaterial");+ _surface.SetResourceReference(Border.BorderBrushProperty, "DockBorderMaterial");+ if (_shadow is not null && App.Shadows) _surface.Effect = _shadow;+ }++ /// <summary>Things that must keep the bar on screen (open popup, menu, edit mode).</summary>+ public void SetLock(Func<bool> isLocked) => _isLocked = isLocked;++ public void SetDesktopClean(bool clean)+ {+ if (_desktopClean == clean) return;+ _desktopClean = clean;+ if (clean) _peeking = false;+ Update();+ }++ /// <summary>Full-screen apps (games, video) hide the bar entirely.</summary>+ public void SetSuppressed(bool suppressed)+ {+ if (_suppressed == suppressed) return;+ _suppressed = suppressed;+ if (suppressed) _peeking = false;+ Update();+ }++ private bool _filesMode;++ /// <summary>While the desktop shows its files (icons), the bar stays out of the way.</summary>+ public void SetFilesMode(bool on)+ {+ if (_filesMode == on) return;+ _filesMode = on;+ Update();+ }++ public void SetHasContent(bool hasContent)+ {+ if (_hasContent == hasContent) return;+ _hasContent = hasContent;+ Update();+ }++ public void SetPeekEnabled(bool enabled)+ {+ _peekEnabled = enabled;+ if (!enabled) _peeking = false;+ Update();+ }++ /// <summary>Re-evaluates visibility (call when a lock such as edit mode or a popup changes).</summary>+ public void Update()+ {+ var locked = _shown && _isLocked();+ var target = _hasContent && !_suppressed && (ForceVisible || locked || (!_filesMode && (_desktopClean || _peeking)));+ if (target && !_shown) Reveal();+ else if (!target && _shown) Conceal();++ // Only poll the pointer when the edge can bring the bar in, or to send a peeked bar away.+ var watch = !_suppressed && _hasContent && ((_peekEnabled && !_desktopClean && !_shown) || _peeking);+ if (watch) _edgeWatch.Start();+ else _edgeWatch.Stop();+ }++ /// <summary>Keeps the bar visible regardless of windows (edit mode started from the dock menu).</summary>+ public bool ForceVisible { get; set; }++ /// <summary>True while the bar is on screen (or sliding in).</summary>+ public bool IsShown => _shown;++ private void Reveal()+ {+ _shown = true;+ if (!IsVisible)+ {+ Show();+ Reposition();+ }+ LiveChanged?.Invoke(this, true);+ Animate(1, 0, 170, new CubicEase { EasingMode = EasingMode.EaseOut }, null);+ }++ private void Conceal()+ {+ _shown = false;+ LiveChanged?.Invoke(this, false);+ Animate(0, -14, 140, new CubicEase { EasingMode = EasingMode.EaseIn }, () =>+ {+ if (!_shown) Hide();+ });+ }++ private void Animate(double opacity, double y, int milliseconds, IEasingFunction ease, Action? done)+ {+ var duration = TimeSpan.FromMilliseconds(milliseconds);+ var fade = new DoubleAnimation(opacity, duration) { EasingFunction = ease };+ if (done is not null) fade.Completed += (_, _) => done();+ _surface.BeginAnimation(OpacityProperty, fade);+ if (opacity > 0 && _slide.Y >= 0 && _surface.Opacity <= 0.01) _slide.Y = -14;+ _slide.BeginAnimation(TranslateTransform.YProperty, new DoubleAnimation(y, duration) { EasingFunction = ease });+ }++ private void Reposition()+ {+ var area = SystemParameters.WorkArea;+ if (ActualWidth <= 0) return;+ Left = Math.Round(area.Left + (area.Width - ActualWidth) / 2);+ Top = Math.Round(area.Top + TopGap - ShadowRoom);+ }++ private void WatchPointer()+ {+ if (!GetCursorPos(out var cursor)) return;+ var now = DateTime.UtcNow;+ if (!_peeking)+ {+ // Rest on the top edge, over the bar's span, without clicking (browser tabs live up there too).+ var atEdge = cursor.Y <= 1 && WithinBarSpan(cursor.X);+ if (!atEdge || Math.Abs(cursor.X - _edgePoint.X) > 24)+ {+ _edgeSince = atEdge ? now : default;+ _edgePoint = cursor;+ return;+ }+ if (_edgeSince == default || now - _edgeSince < EdgeDwell) return;+ _edgeSince = default;+ _peeking = true;+ _leftSince = default;+ Update();+ return;+ }++ if (_isLocked() || OverSurface(cursor))+ {+ _leftSince = default;+ return;+ }+ if (_leftSince == default)+ {+ _leftSince = now;+ return;+ }+ if (now - _leftSince < LeaveDelay) return;+ _peeking = false;+ Update();+ }++ private bool WithinBarSpan(int x)+ {+ var screenWidth = GetSystemMetrics(0);+ var halfSpan = Math.Max(screenWidth * 0.18, ActualWidth * DpiScale() / 2);+ return Math.Abs(x - screenWidth / 2.0) <= halfSpan;+ }++ private bool OverSurface(NativePoint cursor)+ {+ if (!IsVisible || PresentationSource.FromVisual(_surface) is null) return false;+ var topLeft = _surface.PointToScreen(new Point(-24, -40));+ var bottomRight = _surface.PointToScreen(new Point(_surface.ActualWidth + 24, _surface.ActualHeight + 48));+ return cursor.X >= topLeft.X && cursor.X <= bottomRight.X && cursor.Y >= topLeft.Y && cursor.Y <= bottomRight.Y;+ }++ private double DpiScale() => PresentationSource.FromVisual(this)?.CompositionTarget?.TransformToDevice.M11 ?? 1;++ protected override void OnSourceInitialized(EventArgs e)+ {+ base.OnSourceInitialized(e);+ if (PresentationSource.FromVisual(this) is not HwndSource source) return;+ Handle = source.Handle;+ source.AddHook(WindowProc);+ // Tool window (no Alt+Tab, no taskbar button) that never takes focus from the user's app.+ var style = GetWindowLongPtr(Handle, -20).ToInt64();+ SetWindowLongPtr(Handle, -20, new nint((style | 0x00000080 | 0x08000000) & ~0x00040000));+ }++ private static IntPtr WindowProc(IntPtr hwnd, int message, IntPtr wParam, IntPtr lParam, ref bool handled)+ {+ const int WmMouseActivate = 0x0021;+ const int MaNoActivate = 3;+ if (message != WmMouseActivate) return IntPtr.Zero;+ handled = true;+ return new IntPtr(MaNoActivate);+ }++ protected override void OnClosed(EventArgs e)+ {+ _edgeWatch.Stop();+ base.OnClosed(e);+ }++ 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", 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/UiSheet.cs b/UiSheet.csnew file mode 100644index 0000000..392a555--- /dev/null+++ b/UiSheet.cs@@ -0,0 +1,273 @@+#if DEBUG+using System.IO;+using System.Windows;+using System.Windows.Automation.Peers;+using System.Windows.Automation.Provider;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Media;+using System.Windows.Media.Imaging;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;+using QiDock.Services.Notifications;+using QiDock.Widgets;++namespace QiDock;++/// <summary>+/// Debug builds only (<c>--render-ui <folder></c>): draws every bar widget's tile and card,+/// the Notification Center, the Control Center and a top banner to PNG files at twice the size,+/// in the dark and the light theme, without showing a window. For reviewing layout and alignment.+/// </summary>+internal static class UiSheet+{+ private const double Scale = 2;++ public static void Render(string folder, WidgetSettings settings, double opacity, Action done)+ {+ Directory.CreateDirectory(folder);+ var themes = new Queue<AppTheme>([AppTheme.Dark, AppTheme.Light]);+ void Next()+ {+ if (themes.Count == 0)+ {+ ThemeManager.Apply(AppTheme.Dark, opacity);+ done();+ return;+ }+ var theme = themes.Dequeue();+ ThemeManager.Apply(theme, opacity);+ RenderTheme(folder, theme.ToString().ToLowerInvariant(), settings, Next);+ }+ Next();+ }++ private static void RenderTheme(string folder, string theme, WidgetSettings settings, Action next)+ {+ DockWidget[] widgets =+ [+ new MediaWidget(), new WeatherWidget(), new ClockWidget(), new BatteryWidget(), new AiLimitsWidget(), new SystemWidget(), new QuickControlsWidget(),+ new FolderWidget(), new SearchWidget(), new ColorsWidget(), new AppVolumeWidget(), new FocusWidget(), new WorldClockWidget(),+ new TodoWidget(), new ToolsWidget(), new NotificationsWidget(), new ControlCenterWidget(),+ new ProfileWidget(), new CurrencyWidget(), new StopwatchWidget(), new NoteWidget(), new AppGroupWidget(), new ProgressWidget(),+ new ReminderWidget(), new VoiceMemoWidget(), new TrayWidget()+ ];+ var tiles = new WrapPanel { Width = 1400 };+ foreach (var widget in widgets)+ {+ widget.Current = settings;+ widget.ApplySettings(settings);+ widget.Start();+ widget.SetLive(true);+ var cell = new StackPanel { Margin = new Thickness(10) };+ cell.Children.Add(Ui.Text(widget.Id, 10, brushKey: "TextSecondary"));+ cell.Children.Add(new Border { Height = 44, Child = widget.View, HorizontalAlignment = HorizontalAlignment.Left });+ tiles.Children.Add(cell);+ }+ Layout(tiles);++ // Let the widgets fetch their data (weather, media, feeds) before drawing them.+ var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(8) };+ timer.Tick += (_, _) =>+ {+ timer.Stop();+ Layout(tiles);+ Save(Backdrop(tiles, null), Path.Combine(folder, $"{theme}-tiles.png"));++ foreach (var widget in widgets)+ {+ var popups = new List<WidgetPopup>();+ WidgetPopup.Rehearsal = popups;+ try+ {+ // Only widgets with a card get their tile clicked: on the others the first button is a real+ // action (screen snip, play, lock…) that must never run during a snapshot.+ if (widget is MediaWidget media) media.RehearseCard();+ else if (HasPopup(widget) && FirstButton(widget.View) is { } button) Click(button);+ }+ catch (Exception ex)+ {+ File.WriteAllText(Path.Combine(folder, $"{theme}-popup-{widget.Id}.error.txt"), ex.ToString());+ }+ finally+ {+ WidgetPopup.Rehearsal = null;+ }+ foreach (var (popup, index) in popups.Distinct().Select((p, i) => (p, i)))+ {+ var surface = popup.DetachSurface();+ Save(Backdrop(surface, null), Path.Combine(folder, $"{theme}-popup-{widget.Id}{(index > 0 ? "-" + index : "")}.png"));+ }+ }++ var center = NotificationCenter.Shared.Rehearse();+ Save(Backdrop(center, "PanelFrostTint"), Path.Combine(folder, $"{theme}-notification-center.png"));+ Release(center);+ // The bell's panel growing out of the dock, frame by frame (1.04 = the overshoot).+ var bell = NotificationCenter.Shared.RehearseDock();+ foreach (var (step, index) in new[] { 0.06, 0.2, 0.45, 0.75, 1.04, 1.0 }.Select((p, i) => (p, i)))+ {+ NotificationCenter.Shared.RehearseMorph(step);+ Save(Backdrop(bell, null), Path.Combine(folder, $"{theme}-bell-{index}.png"));+ Release(bell);+ }+ var control = ControlCenter.Shared.Rehearse();+ Save(Backdrop(control, "PanelFrostTint"), Path.Combine(folder, $"{theme}-control-center.png"));+ Release(control);+ var networks = ControlCenter.Shared.RehearseNetworks();+ Save(Backdrop(networks, "PanelFrostTint"), Path.Combine(folder, $"{theme}-control-center-wifi.png"));+ Release(networks);++ var sample = new AppNotification(1, "Microsoft.WindowsTerminal_8wekyb3d8bbwe!App", "Derleme tamamlandı",+ "QiDock sürümü hazır; taşınabilir dosya dist klasöründe. Uzun bir açıklama satırı da burada kırpılmalı ve üç satırı geçmemeli.",+ DateTime.UtcNow.AddMinutes(-2), null, false, null);+ var banner = new BannerCard(sample);+ Save(Backdrop(banner.Rehearse(), "PanelFrostTint"), Path.Combine(folder, $"{theme}-banner.png"));+ banner.Close();++ try+ {+ // The settings window, one picture per tab (built, never shown, never saved).+ var settingsWindow = new SettingsWindow(((App)Application.Current).Preferences);+ if (settingsWindow.Content is FrameworkElement page)+ {+ settingsWindow.Content = null;+ // The window's own styles (tabs, switches, lists) must come along, or the page draws unstyled.+ page.Resources.MergedDictionaries.Add(settingsWindow.Resources);+ page.Width = settingsWindow.Width;+ page.Height = settingsWindow.Height;+ var tabs = settingsWindow.SettingsTabs;+ for (var i = 0; i < tabs.Items.Count; i++)+ {+ tabs.SelectedIndex = i;+ Save(Backdrop(page, null), Path.Combine(folder, $"{theme}-settings-{i}.png"));+ Release(page);+ }+ }+ settingsWindow.Close();+ }+ catch (Exception ex)+ {+ File.WriteAllText(Path.Combine(folder, $"{theme}-settings.error.txt"), ex.ToString());+ }++ foreach (var widget in widgets) widget.Dispose();+ next();+ };+ timer.Start();+ }++ /// <summary>+ /// <c>--render-styles <folder></c>: a dock-like strip (the dock material with a row of widget tiles) in+ /// every look, one picture each, after the widgets had time to load.+ /// </summary>+ public static void RenderStyles(string folder, WidgetSettings settings, double opacity, Action done)+ {+ Directory.CreateDirectory(folder);+ DockWidget[] widgets = [new MediaWidget(), new ProfileWidget(), new CurrencyWidget(), new StopwatchWidget(), new NoteWidget(), new AppGroupWidget(), new ProgressWidget(), new ReminderWidget(), new VoiceMemoWidget(), new ControlCenterWidget()];+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ foreach (var widget in widgets)+ {+ widget.Current = settings;+ widget.ApplySettings(settings);+ widget.Start();+ row.Children.Add(new Border { Height = 44, Child = widget.View });+ }+ var dock = new Border { CornerRadius = new CornerRadius(18), BorderThickness = new Thickness(1), Padding = new Thickness(8, 7, 8, 7), Child = row };+ dock.SetResourceReference(Border.BackgroundProperty, "DockMaterial");+ dock.SetResourceReference(Border.BorderBrushProperty, "DockBorderMaterial");+ var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(6) };+ timer.Tick += (_, _) =>+ {+ timer.Stop();+ foreach (var look in ThemeStyles.All)+ {+ ThemeManager.Apply(AppTheme.Dark, opacity, look.Id);+ Save(Backdrop(dock, null), Path.Combine(folder, $"style-{look.Id}.png"));+ Release(dock);+ if (look.Id is ThemeStyles.Glass or "black" or "lofi")+ {+ DockHud.Shared.RehearseLevel("IconVolume", UiText.Get("HudVolume"), 57, Ui.Solid("#FF30D158"));+ var hud = DockHud.Shared.RehearseDock();+ DockHud.Shared.RehearseMorph(1.0);+ Save(Backdrop(hud, null), Path.Combine(folder, $"hud-{look.Id}.png"));+ Release(hud);+ }+ }+ ThemeManager.Apply(AppTheme.Dark, opacity, ThemeStyles.Glass);+ foreach (var widget in widgets) widget.Dispose();+ done();+ };+ timer.Start();+ }++ /// <summary>Frees a shared panel's content from this run's backdrop so the next theme can draw it again.</summary>+ private static void Release(FrameworkElement element)+ {+ if (element.Parent is Border border) border.Child = null;+ }++ private static void Layout(FrameworkElement element)+ {+ element.Measure(new Size(element.Width > 0 ? element.Width : double.PositiveInfinity, double.PositiveInfinity));+ element.Arrange(new Rect(element.DesiredSize));+ element.UpdateLayout();+ }++ /// <summary>Puts the element on a desktop-like backdrop; <paramref name="frostKey"/> stands in for the frosted glass.</summary>+ private static FrameworkElement Backdrop(FrameworkElement element, string? frostKey)+ {+ FrameworkElement body = element;+ if (frostKey is not null)+ {+ var color = Application.Current.TryFindResource(frostKey) is Color c ? c : Color.FromArgb(0xC8, 0x19, 0x1A, 0x1F);+ body = new Border { Background = new SolidColorBrush(color), CornerRadius = new CornerRadius(14), Child = element };+ }+ var root = new Border+ {+ Background = Ui.Diagonal(Color.FromRgb(0x3E, 0x5F, 0x8E), Color.FromRgb(0x1D, 0x2B, 0x45)),+ Padding = new Thickness(24),+ Child = body+ };+ root.SetResourceReference(System.Windows.Documents.TextElement.FontFamilyProperty, "InterfaceFont");+ root.SetResourceReference(System.Windows.Documents.TextElement.ForegroundProperty, "TextPrimary");+ TextOptions.SetTextFormattingMode(root, TextFormattingMode.Ideal);+ Layout(root);+ Layout(root); // twice: some cards size themselves after their first layout+ return root;+ }++ private static void Save(FrameworkElement element, string path)+ {+ var width = (int)Math.Ceiling(element.ActualWidth * Scale);+ var height = (int)Math.Ceiling(element.ActualHeight * Scale);+ if (width <= 0 || height <= 0) return;+ var bitmap = new RenderTargetBitmap(width, height, 96 * Scale, 96 * Scale, PixelFormats.Pbgra32);+ bitmap.Render(element);+ var encoder = new PngBitmapEncoder();+ encoder.Frames.Add(BitmapFrame.Create(bitmap));+ using var stream = File.Create(path);+ encoder.Save(stream);+ }++ private static bool HasPopup(DockWidget widget) => widget.GetType()+ .GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)+ .Any(field => field.FieldType == typeof(WidgetPopup));++ private static ButtonBase? FirstButton(DependencyObject node)+ {+ if (node is ButtonBase button) return button;+ for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++)+ if (FirstButton(VisualTreeHelper.GetChild(node, i)) is { } found) return found;+ return null;+ }++ private static void Click(ButtonBase button)+ {+ if (UIElementAutomationPeer.CreatePeerForElement(button)?.GetPattern(PatternInterface.Invoke) is IInvokeProvider invoke) invoke.Invoke();+ else button.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));+ button.Dispatcher.Invoke(DispatcherPriority.Background, () => { });+ }+}+#endifdiff --git a/VolumeHud.cs b/VolumeHud.csnew file mode 100644index 0000000..e680a25--- /dev/null+++ b/VolumeHud.cs@@ -0,0 +1,170 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Interop;+using System.Windows.Media;+using System.Windows.Media.Animation;+using System.Windows.Media.Effects;+using System.Windows.Shapes;+using System.Windows.Threading;+using QiDock.Widgets;++namespace QiDock;++/// <summary>+/// Small glass pill that pops in at the top of the screen when the volume changes (volume keys,+/// mute key) and is gone again a moment later. Click-through and never focused.+/// </summary>+public sealed class VolumeHud : Window+{+ private const double Shadow = 16;+ private const double BarWidth = 150;+ private static readonly TimeSpan Linger = TimeSpan.FromMilliseconds(1100);++ private readonly Border _surface;+ private readonly ScaleTransform _scale = new(0.86, 0.86);+ private readonly ContentControl _icon = new() { Width = 18, Height = 18, Focusable = false };+ private readonly Border _fill;+ private readonly TextBlock _percent;+ private readonly Border _track;+ private readonly TextBlock _message;+ private readonly DispatcherTimer _hideTimer;+ private bool _shown;++ /// <summary>Screen-top offset in DIP (below the widget bar when that is on screen).</summary>+ public Func<double> TopOffset { get; set; } = () => 10;++ public VolumeHud()+ {+ WindowStyle = WindowStyle.None;+ ResizeMode = ResizeMode.NoResize;+ AllowsTransparency = true;+ Background = Brushes.Transparent;+ ShowInTaskbar = false;+ ShowActivated = false;+ Topmost = true;+ IsHitTestVisible = false;+ SizeToContent = SizeToContent.WidthAndHeight;+ WindowStartupLocation = WindowStartupLocation.Manual;+ Title = "QiDock Volume";+ SetResourceReference(FontFamilyProperty, "InterfaceFont");++ var track = _track = new Border { Width = BarWidth, Height = 6, CornerRadius = new CornerRadius(3), Background = Ui.Solid("#33FFFFFF"), VerticalAlignment = VerticalAlignment.Center };+ _fill = new Border { Width = 0, CornerRadius = new CornerRadius(3), HorizontalAlignment = HorizontalAlignment.Left, Background = Ui.Solid("#FFFFFFFF") };+ track.Child = _fill;+ _percent = Ui.Text("", 12.5, FontWeights.SemiBold);+ _percent.Width = 34;+ _percent.TextAlignment = TextAlignment.Right;++ var row = new StackPanel { Orientation = Orientation.Horizontal };+ row.Children.Add(_icon);+ track.Margin = new Thickness(10, 0, 8, 0);+ row.Children.Add(track);+ row.Children.Add(_percent);+ _message = Ui.Text("", 12.5, FontWeights.SemiBold);+ _message.Margin = new Thickness(10, 0, 2, 0);+ _message.Visibility = Visibility.Collapsed;+ row.Children.Add(_message);++ _surface = new Border+ {+ Margin = new Thickness(Shadow),+ Padding = new Thickness(14, 9, 14, 9),+ CornerRadius = new CornerRadius(19),+ BorderThickness = new Thickness(1),+ Child = row,+ Opacity = 0,+ RenderTransformOrigin = new Point(0.5, 0.5),+ RenderTransform = _scale,+ Effect = new DropShadowEffect { Color = Colors.Black, BlurRadius = 16, ShadowDepth = 2, Direction = 270, Opacity = 0.32, RenderingBias = RenderingBias.Performance }+ };+ _surface.SetResourceReference(Border.BackgroundProperty, "MenuMaterial");+ _surface.SetResourceReference(Border.BorderBrushProperty, "DockBorderMaterial");+ Content = _surface;+ SizeChanged += (_, _) => Reposition();++ _hideTimer = new DispatcherTimer(DispatcherPriority.Normal) { Interval = Linger };+ _hideTimer.Tick += (_, _) =>+ {+ _hideTimer.Stop();+ Disappear();+ };+ }++ public void ShowLevel(float level, bool muted)+ {+ var percent = (int)Math.Round(Math.Clamp(level, 0f, 1f) * 100);+ _icon.Content = Ui.Icon(muted || percent == 0 ? "IconVolumeMute" : "IconVolume", 18);+ _fill.Width = muted ? 0 : BarWidth * percent / 100.0;+ _fill.Opacity = muted ? 0.4 : 1;+ _percent.Text = muted ? "" : percent.ToString(System.Globalization.CultureInfo.CurrentCulture);+ _track.Visibility = Visibility.Visible;+ _message.Visibility = Visibility.Collapsed;+ _percent.Visibility = Visibility.Visible;+ Pop(Linger);+ }++ /// <summary>Icon and a short sentence ("Kopyalandı", "Odak süresi bitti").</summary>+ public void ShowMessage(string iconKey, string text)+ {+ _icon.Content = Ui.Icon(iconKey, 18);+ _message.Text = text;+ _track.Visibility = Visibility.Collapsed;+ _percent.Visibility = Visibility.Collapsed;+ _message.Visibility = Visibility.Visible;+ Pop(TimeSpan.FromMilliseconds(2200));+ }++ private void Pop(TimeSpan linger)+ {+ _hideTimer.Stop();+ _hideTimer.Interval = linger;+ _hideTimer.Start();+ if (_shown) return;+ _shown = true;+ if (!IsVisible) Show();+ Reposition();+ var duration = TimeSpan.FromMilliseconds(150);+ var ease = new BackEase { EasingMode = EasingMode.EaseOut, Amplitude = 0.35 };+ _surface.BeginAnimation(OpacityProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(110)));+ _scale.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(0.86, 1, duration) { EasingFunction = ease });+ _scale.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(0.86, 1, duration) { EasingFunction = ease });+ }++ private void Disappear()+ {+ _shown = false;+ var duration = TimeSpan.FromMilliseconds(180);+ var fade = new DoubleAnimation(0, duration);+ fade.Completed += (_, _) =>+ {+ if (!_shown) Hide();+ };+ _surface.BeginAnimation(OpacityProperty, fade);+ _scale.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(0.92, duration));+ _scale.BeginAnimation(ScaleTransform.ScaleYProperty, new DoubleAnimation(0.92, duration));+ }++ private void Reposition()+ {+ var area = SystemParameters.WorkArea;+ if (ActualWidth <= 0) return;+ Left = Math.Round(area.Left + (area.Width - ActualWidth) / 2);+ Top = Math.Round(area.Top + TopOffset() - Shadow);+ }++ protected override void OnSourceInitialized(EventArgs e)+ {+ base.OnSourceInitialized(e);+ if (PresentationSource.FromVisual(this) is not HwndSource source) return;+ // Tool window, never activated, transparent to the mouse.+ var style = GetWindowLongPtr(source.Handle, -20).ToInt64();+ SetWindowLongPtr(source.Handle, -20, new nint((style | 0x00000080 | 0x08000000 | 0x00000020) & ~0x00040000));+ }++ [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/Widgets/AiLimitsWidget.cs b/Widgets/AiLimitsWidget.csnew file mode 100644index 0000000..3334a5f--- /dev/null+++ b/Widgets/AiLimitsWidget.cs@@ -0,0 +1,549 @@+using System.Globalization;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media;+using System.Windows.Shapes;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;+using QiDock.Services.Widgets;++namespace QiDock.Widgets;++/// <summary>+/// Claude and ChatGPT usage limits: a compact ring per provider in the dock. Clicking a ring opens that provider's+/// card (usage, this week's curve and pace); nothing shows on hover. Claude's card also lists this PC's recent+/// Claude Code sessions (what each is doing, or that it finished), read only while that card is open.+/// </summary>+public sealed class AiLimitsWidget : DockWidget+{+ private static readonly Brush WarningBrush = Ui.Solid("#FFFFB224");+ private static readonly Brush DangerBrush = Ui.Solid("#FFFF5F57");+ private static readonly Brush LineBrush = Ui.Solid("#FF32D74B");++ private readonly Border _tile;+ private string? _shown;+ private readonly ClaudeActivityWatcher _claudeWatch = new(Dispatcher.CurrentDispatcher);+ private readonly DispatcherTimer _sessionTick = new(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(30) };+ private List<ClaudeActivity> _claudeSessions = [];+ private static readonly TimeSpan SessionWindow = TimeSpan.FromMinutes(30);+ private readonly StackPanel _cards;+ private readonly WidgetPopup _popup;+ private readonly DispatcherTimer _timer;+ private readonly AiUsageService _service = new();+ private readonly AiUsageHistory _history = new();+ private IReadOnlyList<ProviderUsage> _usage = [];+ private CancellationTokenSource? _load;+ private string _layoutSignature = "";++ public AiLimitsWidget()+ {+ _cards = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };+ // A plain tile: each ring inside is its own button.+ _tile = new Border { Child = _cards, Padding = new Thickness(3, 0, 3, 0), Margin = new Thickness(3, 0, 3, 0), BorderThickness = new Thickness(1), VerticalAlignment = VerticalAlignment.Center };+ _tile.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ _tile.SetResourceReference(Border.BorderBrushProperty, "WidgetTileStroke");+ _tile.SetResourceReference(FrameworkElement.HeightProperty, "WidgetTileHeight");+ _tile.CornerRadius = new CornerRadius(11);+ _popup = new WidgetPopup(_tile);+ _popup.Closed += (_, _) => StopSessions();+ _claudeWatch.Changed += () => _ = LoadSessionsAsync();+ _sessionTick.Tick += (_, _) => _ = LoadSessionsAsync(); // "3 dk önce" and sessions going quiet+ _timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMinutes(1) };+ _timer.Tick += (_, _) => _ = RefreshAsync(false);+ UiText.Current.PropertyChanged += (_, _) => Render();+ Render();+ }++ public override string Id => WidgetIds.AiLimits;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;++ public override void Start()+ {+ _timer.Start();+ _ = RefreshAsync(false);+ }++ public override void Stop()+ {+ _timer.Stop();+ _load?.Cancel();+ _popup.Close();+ StopSessions();+ }++ public override void ClosePopup() => _popup.Close();++ private async Task RefreshAsync(bool force)+ {+ _load?.Cancel();+ var load = _load = new CancellationTokenSource();+ try+ {+ _usage = await _service.FetchAsync(force, load.Token);+ }+ catch (OperationCanceledException)+ {+ return;+ }++ foreach (var provider in _usage.Where(p => p.Error is null))+ foreach (var window in provider.Windows.Where(w => w.Key is not null))+ _history.Record($"{provider.Provider}:{window.Key}", window.UsedPercent, provider.UpdatedAt);++ Render();+ if (_popup.IsOpen) BuildPopup();+ }++ // ---- Dock tile ---------------------------------------------------------------------------++ private void Render()+ {+ _cards.Children.Clear();+ if (_usage.Count == 0)+ {+ _cards.Children.Add(Gauge(AiUsageService.ClaudeId, null));+ }++ // Compact: one ring per provider (the logo inside, the busier window's use around it) and its percent.+ foreach (var (provider, index) in _usage.Select((p, i) => (p, i)))+ {+ var used = provider.Error is null && provider.Windows.Count > 0 ? provider.Windows.Max(w => w.UsedPercent) : (double?)null;+ var gauge = Gauge(provider.Provider, used);+ gauge.Margin = new Thickness(index == 0 ? 0 : 2, 0, 0, 0);+ _cards.Children.Add(gauge);+ }+ var signature = string.Join("|", _usage.Select(p => $"{p.Provider}{p.Windows.Count}{p.Error is null}"));+ if (signature != _layoutSignature)+ {+ _layoutSignature = signature;+ RaiseLayoutChanged();+ }+ }++ private static CultureInfo Culture => CultureInfo.GetCultureInfo(UiText.Get("CultureName"));++ private static string Percent(double value) => UiText.Format("OpacityPercent", Math.Round(value).ToString("0", CultureInfo.InvariantCulture));++ /// <summary>"2sa 14dk" for today's resets, "19 Çar" for later ones.</summary>+ private static string ShortReset(DateTime at)+ {+ var span = at - DateTime.Now;+ if (span <= TimeSpan.Zero) return UiText.Get("AiSoon");+ if (span.TotalHours < 24)+ return span.TotalHours >= 1 ? UiText.Format("AiShortHM", (int)span.TotalHours, span.Minutes) : UiText.Format("AiShortM", Math.Max(1, span.Minutes));+ return at.ToString("d ddd", Culture);+ }++ internal static string Remaining(TimeSpan span)+ {+ if (span <= TimeSpan.Zero) return UiText.Get("AiSoon");+ if (span.TotalDays >= 1) return UiText.Format("AiDaysHours", (int)span.TotalDays, span.Hours);+ if (span.TotalHours >= 1) return UiText.Format("AiHoursMinutes", (int)span.TotalHours, span.Minutes);+ return UiText.Format("AiMinutes", Math.Max(1, span.Minutes));+ }++ private static string When(DateTime at) =>+ at.Date == DateTime.Today ? at.ToString("HH:mm", Culture) : at.ToString("ddd HH:mm", Culture);++ // ---- Pace --------------------------------------------------------------------------------++ /// <summary>At the current average rate since the window started: when 100% is reached, or the level at reset.</summary>+ private static (DateTime? ExhaustedAt, double AtReset)? Pace(UsageWindow window)+ {+ if (window.StartsAt is not { } start || window.ResetsAt is not { } reset) return null;+ var elapsed = DateTime.Now - start;+ if (elapsed < TimeSpan.FromMinutes(20) || window.UsedPercent <= 0) return null;+ var perHour = window.UsedPercent / elapsed.TotalHours;+ var atReset = window.UsedPercent + perHour * (reset - DateTime.Now).TotalHours;+ if (atReset < 100) return (null, atReset);+ var exhausted = DateTime.Now + TimeSpan.FromHours((100 - window.UsedPercent) / perHour);+ return (exhausted, 100);+ }++ // ---- Popup -------------------------------------------------------------------------------++ private void TogglePopup()+ {+ if (!_popup.IsOpen)+ {+ BuildPopup();+ _ = RefreshAsync(true);+ }+ _popup.Toggle();+ }++ /// <summary>A ring was clicked: its provider's card opens (another provider's card on show switches over).</summary>+ private void ToggleProvider(string provider)+ {+ if (_popup.IsOpen && _shown != provider)+ {+ _shown = provider;+ FollowSessions();+ BuildPopup();+ return;+ }+ _shown = provider;+ if (!_popup.IsOpen) FollowSessions();+ TogglePopup();+ }++ // ---- Claude Code sessions (only while Claude's card is open) ------------------------------++ private bool ShowSessions => _shown == AiUsageService.ClaudeId+ && (Application.Current as App)?.Preferences.Current.ClaudeActivity != false;++ private void FollowSessions()+ {+ if (!ShowSessions)+ {+ StopSessions();+ return;+ }+ _claudeWatch.Start();+ _sessionTick.Start();+ _ = LoadSessionsAsync();+ }++ private void StopSessions()+ {+ _claudeWatch.Stop();+ _sessionTick.Stop();+ }++ private async Task LoadSessionsAsync()+ {+ var sessions = await ClaudeActivityWatcher.RecentAsync(SessionWindow);+ _claudeSessions = sessions;+ if (_popup.IsOpen && ShowSessions) BuildPopup();+ }++ /// <summary>Claude Code on this PC: each recent session with what it is doing, or that it finished.</summary>+ private UIElement SessionsCard()+ {+ var card = new Border { CornerRadius = new CornerRadius(12), Padding = new Thickness(14, 12, 14, 8), Margin = new Thickness(0, 0, 0, 10) };+ card.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ var content = new StackPanel();+ var title = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 8) };+ title.Children.Add(Logo(AiUsageService.ClaudeId, 22));+ var name = Ui.Text(UiText.Get("ClaudeSessionsTitle"), 13.5, FontWeights.SemiBold);+ name.Margin = new Thickness(8, 0, 0, 0);+ title.Children.Add(name);+ content.Children.Add(title);+ content.Children.Add(Caption(UiText.Get("ClaudeSessionsCaption")));+ if (_claudeSessions.Count == 0)+ {+ var none = Ui.Text(UiText.Get("ClaudeSessionsNone"), 11.5, brushKey: "TextSecondary");+ none.TextWrapping = TextWrapping.Wrap;+ none.TextTrimming = TextTrimming.None;+ none.Margin = new Thickness(0, 0, 0, 6);+ content.Children.Add(none);+ }+ foreach (var session in _claudeSessions) content.Children.Add(SessionRow(session));+ card.Child = content;+ return card;+ }++ private static UIElement SessionRow(ClaudeActivity session)+ {+ var row = new DockPanel { Margin = new Thickness(0, 0, 0, 8) };+ // A green tick when finished, an orange dot while working, a grey one when it has gone quiet.+ FrameworkElement mark = session.Done+ ? Ui.Icon("IconCheck", 13, Ui.Solid("#FF30D158"), stroke: 2.6)+ : new Ellipse { Width = 8, Height = 8, Fill = session.Working ? Ui.Solid("#FFD97757") : Ui.Solid("#FF8E8E93") };+ var markHost = new Grid { Width = 16, Margin = new Thickness(0, 3, 8, 0), VerticalAlignment = VerticalAlignment.Top };+ mark.HorizontalAlignment = HorizontalAlignment.Center;+ mark.VerticalAlignment = VerticalAlignment.Center;+ markHost.Children.Add(mark);+ DockPanel.SetDock(markHost, Dock.Left);+ row.Children.Add(markHost);++ var minutes = (int)Math.Floor((DateTime.UtcNow - session.UpdatedAt).TotalMinutes);+ var ago = Ui.Text(minutes < 1 ? UiText.Get("ClaudeAgoNow") : UiText.Format("ClaudeAgoMinutes", minutes), 10.5, brushKey: "TextSecondary");+ ago.VerticalAlignment = VerticalAlignment.Top;+ ago.Margin = new Thickness(8, 1, 0, 0);+ DockPanel.SetDock(ago, Dock.Right);+ row.Children.Add(ago);++ var text = new StackPanel();+ var project = Ui.Text(session.Project, 12.5, FontWeights.SemiBold);+ project.TextTrimming = TextTrimming.CharacterEllipsis;+ text.Children.Add(project);+ var detail = Ui.Text(session.Done || session.Working ? session.Detail : UiText.Get("ClaudeIdle"), 11, brushKey: "TextSecondary");+ detail.TextTrimming = TextTrimming.CharacterEllipsis;+ text.Children.Add(detail);+ row.Children.Add(text);+ return row;+ }++ private const double PopupWidth = 360;+ private const double ContentWidth = PopupWidth - 32 - 28;++ private void BuildPopup()+ {+ var root = new StackPanel();+ var header = new DockPanel { Margin = new Thickness(0, 0, 0, 10) };+ var close = Ui.IconButton(Ui.Icon("IconClose", 12, brushKey: "TextSecondary"), (_, _) => _popup.Close(), UiText.Get("Close"));+ DockPanel.SetDock(close, Dock.Right);+ header.Children.Add(close);+ header.Children.Add(Ui.Text(_usage.FirstOrDefault(p => p.Provider == _shown)?.DisplayName ?? UiText.Get("AiLimits"), 14, FontWeights.SemiBold));+ root.Children.Add(header);++ if (_usage.Count == 0)+ {+ var help = Ui.Text(UiText.Get("AiNoDataHelp"), 11.5, brushKey: "TextSecondary");+ help.TextWrapping = TextWrapping.Wrap;+ help.TextTrimming = TextTrimming.None;+ root.Children.Add(help);+ }++ // Only the clicked provider (all of them if it is not among the data).+ foreach (var provider in _shown is null ? _usage : _usage.Where(p => p.Provider == _shown)) root.Children.Add(ProviderCard(provider));+ if (ShowSessions) root.Children.Add(SessionsCard());++ // Footer: where the numbers come from, and a refresh button.+ var footer = new DockPanel { Margin = new Thickness(2, 4, 0, 0) };+ var refresh = new Button { Content = UiText.Get("AiRefresh"), VerticalAlignment = VerticalAlignment.Center };+ refresh.SetResourceReference(FrameworkElement.StyleProperty, "WidgetPillButton");+ refresh.Click += (_, _) => _ = RefreshAsync(true);+ DockPanel.SetDock(refresh, Dock.Right);+ footer.Children.Add(refresh);+ var note = Ui.Text(UiText.Get("AiFooterNote"), 10, brushKey: "TextSecondary");+ note.TextWrapping = TextWrapping.Wrap;+ note.TextTrimming = TextTrimming.None;+ note.Margin = new Thickness(0, 0, 10, 0);+ footer.Children.Add(note);+ root.Children.Add(footer);++ _popup.SetContent(root, PopupWidth);+ }++ private UIElement ProviderCard(ProviderUsage provider)+ {+ var card = new Border { CornerRadius = new CornerRadius(12), Padding = new Thickness(14, 12, 14, 12), Margin = new Thickness(0, 0, 0, 10) };+ card.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ var content = new StackPanel();++ var title = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 10) };+ title.Children.Add(Logo(provider.Provider, 22));+ var name = Ui.Text(provider.DisplayName, 13.5, FontWeights.SemiBold);+ name.Margin = new Thickness(8, 0, 8, 0);+ title.Children.Add(name);+ if (provider.Plan is { } plan)+ {+ var badge = new Border { CornerRadius = new CornerRadius(6), Padding = new Thickness(7, 1, 7, 2), VerticalAlignment = VerticalAlignment.Center };+ badge.SetResourceReference(Border.BackgroundProperty, "SurfaceHover");+ badge.Child = Ui.Text(plan, 10.5, FontWeights.SemiBold, "TextSecondary");+ title.Children.Add(badge);+ }+ content.Children.Add(title);++ if (provider.Windows.Count > 0) content.Children.Add(Caption(UiText.Get("AiUsageCaption")));+ foreach (var window in provider.Windows) content.Children.Add(UsageRow(window));++ if (provider.Error is { } error)+ {+ var errorText = Ui.Text(error, 11, brushKey: "DangerText");+ errorText.TextWrapping = TextWrapping.Wrap;+ errorText.TextTrimming = TextTrimming.None;+ errorText.Margin = new Thickness(0, 2, 0, 6);+ content.Children.Add(errorText);+ }++ // The longest window that has a start and end gets the curve (weekly for Claude, monthly/weekly for ChatGPT).+ var charted = provider.Windows.Where(w => w.StartsAt is not null && w.Length >= TimeSpan.FromDays(1))+ .OrderByDescending(w => w.UsedPercent).FirstOrDefault();+ if (charted is not null)+ {+ content.Children.Add(Caption(charted.Length <= TimeSpan.FromDays(7) ? UiText.Get("AiThisWeek") : UiText.Get("AiThisPeriod")));+ content.Children.Add(Chart(provider, charted));+ }++ var updated = Ui.Text(UiText.Format("AiUpdated", When(provider.UpdatedAt),+ provider.Provider == AiUsageService.CodexId ? UiText.Get("AiSourceCodex") : UiText.Get("AiSourceClaude")), 10, brushKey: "TextSecondary");+ updated.Opacity = 0.8;+ updated.Margin = new Thickness(0, 8, 0, 0);+ content.Children.Add(updated);+ card.Child = content;+ return card;+ }++ private static TextBlock Caption(string text)+ {+ var caption = Ui.Text(text.ToUpper(Culture), 9.5, FontWeights.SemiBold, "TextSecondary");+ caption.Margin = new Thickness(0, 2, 0, 6);+ caption.Opacity = 0.85;+ return caption;+ }++ private static UIElement UsageRow(UsageWindow window)+ {+ var block = new StackPanel { Margin = new Thickness(0, 0, 0, 10) };+ var top = new DockPanel();+ var percent = Ui.Text(Percent(window.UsedPercent), 12, FontWeights.SemiBold);+ percent.Width = 38;+ percent.TextAlignment = TextAlignment.Right;+ DockPanel.SetDock(percent, Dock.Right);+ top.Children.Add(percent);++ TextBlock status;+ if (Pace(window) is { ExhaustedAt: { } exhausted } && window.ResetsAt is { } reset && exhausted < reset)+ status = Ui.Text(UiText.Format("AiOutBy", When(exhausted)), 11, FontWeights.SemiBold, brush: WarningBrush);+ else if (window.ResetsAt is { } resetsAt)+ status = Ui.Text(UiText.Format("AiResetsShort", Remaining(resetsAt - DateTime.Now)), 11, brushKey: "TextSecondary");+ else+ status = Ui.Text(window.UsedPercent <= 0 ? UiText.Get("AiIdle") : UiText.Get("AiNoReset"), 11, brushKey: "TextSecondary");+ if (window.ResetsAt is { } r) status.ToolTip = r.ToString("f", Culture);+ DockPanel.SetDock(status, Dock.Right);+ top.Children.Add(status);+ top.Children.Add(Ui.Text(window.Label, 12, FontWeights.SemiBold));+ block.Children.Add(top);++ var bar = Ui.Bar(window.UsedPercent, ContentWidth, 5, Ui.UsageBrush(window.UsedPercent));+ bar.Margin = new Thickness(0, 5, 0, 0);+ block.Children.Add(bar);+ return block;+ }++ /// <summary>Usage since the window started (green), and where the current pace leads (dashed).</summary>+ private UIElement Chart(ProviderUsage provider, UsageWindow window)+ {+ const double height = 50;+ var width = ContentWidth;+ var start = window.StartsAt!.Value;+ var reset = window.ResetsAt!.Value;+ var span = (reset - start).TotalSeconds;+ double X(DateTime t) => Math.Clamp((t - start).TotalSeconds / span, 0, 1) * width;+ double Y(double p) => height - Math.Clamp(p, 0, 100) / 100 * (height - 4) - 1;++ var now = DateTime.Now;+ var points = new List<Point> { new(X(start), Y(0)) };+ foreach (var sample in _history.Since($"{provider.Provider}:{window.Key}", start).Where(s => s.At <= now))+ points.Add(new Point(X(sample.At), Y(sample.Percent)));+ points.Add(new Point(X(now), Y(window.UsedPercent)));++ var canvas = new Canvas { Width = width, Height = height, ClipToBounds = false };+ var panel = new Border { CornerRadius = new CornerRadius(8), Padding = new Thickness(0, 6, 0, 0) };++ // Faint guides at 50% and 100%.+ foreach (var level in new[] { 50.0, 100.0 })+ {+ var guide = new Line { X1 = 0, X2 = width, Y1 = Y(level), Y2 = Y(level), StrokeThickness = 1, StrokeDashArray = [2, 3] };+ guide.SetResourceReference(Shape.StrokeProperty, "WidgetTrack");+ canvas.Children.Add(guide);+ }++ var area = new Polygon { Fill = new LinearGradientBrush(Color.FromArgb(0x66, 0x32, 0xD7, 0x4B), Color.FromArgb(0x08, 0x32, 0xD7, 0x4B), 90) };+ foreach (var point in points) area.Points.Add(point);+ area.Points.Add(new Point(points[^1].X, height));+ area.Points.Add(new Point(points[0].X, height));+ canvas.Children.Add(area);++ var line = new Polyline { Stroke = LineBrush, StrokeThickness = 2, StrokeLineJoin = PenLineJoin.Round };+ foreach (var point in points) line.Points.Add(point);+ canvas.Children.Add(line);++ string? paceText = null;+ Brush paceBrush = Brushes.Gray;+ if (Pace(window) is { } pace)+ {+ var exhausts = pace.ExhaustedAt is { } at && at < reset;+ var end = exhausts ? new Point(X(pace.ExhaustedAt!.Value), Y(100)) : new Point(X(reset), Y(pace.AtReset));+ paceBrush = exhausts ? DangerBrush : Ui.Solid("#998E8E93");+ canvas.Children.Add(new Line+ {+ X1 = points[^1].X, Y1 = points[^1].Y, X2 = end.X, Y2 = end.Y,+ Stroke = paceBrush, StrokeThickness = 1.6, StrokeDashArray = [3, 2.5]+ });+ paceText = exhausts ? UiText.Format("AiOutBy", When(pace.ExhaustedAt!.Value))+ : UiText.Format("AiPaceOk", Math.Round(pace.AtReset).ToString("0", CultureInfo.InvariantCulture));+ if (exhausts) paceBrush = WarningBrush;+ }++ var dot = new Ellipse { Width = 7, Height = 7, Fill = LineBrush, Stroke = Brushes.White, StrokeThickness = 1.2 };+ Canvas.SetLeft(dot, points[^1].X - 3.5);+ Canvas.SetTop(dot, points[^1].Y - 3.5);+ canvas.Children.Add(dot);+ panel.Child = canvas;++ var stack = new StackPanel();+ stack.Children.Add(panel);+ var labels = new DockPanel { Margin = new Thickness(0, 5, 0, 0) };+ if (paceText is not null)+ {+ var paceLabel = Ui.Text(paceText, 10, FontWeights.SemiBold, brush: paceBrush);+ DockPanel.SetDock(paceLabel, Dock.Right);+ labels.Children.Add(paceLabel);+ }+ labels.Children.Add(Ui.Text(start.ToString("ddd HH:mm", Culture), 10, brushKey: "TextSecondary"));+ stack.Children.Add(labels);+ return stack;+ }++ /// <summary>The provider's logo inside a thin usage ring, with the percent beside it ("—" without data); a button of its own.</summary>+ private FrameworkElement Gauge(string provider, double? used)+ {+ var ring = new QiDock.DesktopWidgets.RingGauge+ {+ Width = 32, Height = 32, Thickness = 3,+ TrackBrush = Ui.Solid("#47808080"),+ Stroke = used is { } u ? Ui.UsageBrush(u) : Ui.Solid("#55FFFFFF"),+ Value = used ?? 0+ };+ var logo = Logo(provider, 18);+ logo.HorizontalAlignment = HorizontalAlignment.Center;+ logo.VerticalAlignment = VerticalAlignment.Center;+ var face = new Grid { Width = 32, Height = 32 };+ face.Children.Add(ring);+ face.Children.Add(logo);+ var row = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };+ row.Children.Add(face);+ var text = Ui.Text(used is { } v ? Math.Round(v).ToString("0", CultureInfo.InvariantCulture) + "%" : "—", 11.5, FontWeights.SemiBold,+ brush: used is { } w ? Ui.UsageBrush(w) : null);+ text.Margin = new Thickness(5, 0, 0, 0);+ text.VerticalAlignment = VerticalAlignment.Center;+ row.Children.Add(text);+ var button = new Button { Content = row, Width = double.NaN, Height = 38, Padding = new Thickness(0), VerticalAlignment = VerticalAlignment.Center };+ button.SetResourceReference(FrameworkElement.StyleProperty, "WidgetIconButton");+ // The style fixes the width; the ring and its percent set it here, with room around them for the hover face.+ button.Width = double.NaN;+ row.Margin = new Thickness(4, 0, 6, 0);+ button.Click += (_, _) => ToggleProvider(provider);+ return button;+ }++ /// <summary>Simple brand-neutral marks: an orange burst for Claude, a ringed disc for ChatGPT.</summary>++ internal static FrameworkElement Logo(string provider, double size)+ {+ var canvas = new Canvas { Width = 24, Height = 24 };+ if (provider == AiUsageService.CodexId)+ {+ canvas.Children.Add(new Rectangle { Width = 24, Height = 24, RadiusX = 6, RadiusY = 6, Fill = Ui.Solid("#FFF4F4F4") });+ var ring = new Ellipse { Width = 14, Height = 14, Stroke = Ui.Solid("#FF111111"), StrokeThickness = 2.2 };+ Canvas.SetLeft(ring, 5);+ Canvas.SetTop(ring, 5);+ canvas.Children.Add(ring);+ var dot = new Ellipse { Width = 4, Height = 4, Fill = Ui.Solid("#FF111111") };+ Canvas.SetLeft(dot, 10);+ Canvas.SetTop(dot, 10);+ canvas.Children.Add(dot);+ }+ else+ {+ canvas.Children.Add(new Rectangle { Width = 24, Height = 24, RadiusX = 6, RadiusY = 6, Fill = Ui.Solid("#FFD97757") });+ for (var i = 0; i < 6; i++)+ {+ var angle = i * Math.PI / 6;+ canvas.Children.Add(new Line+ {+ X1 = 12 - Math.Cos(angle) * 7, Y1 = 12 - Math.Sin(angle) * 7,+ X2 = 12 + Math.Cos(angle) * 7, Y2 = 12 + Math.Sin(angle) * 7,+ Stroke = Brushes.White, StrokeThickness = 2, StrokeStartLineCap = PenLineCap.Round, StrokeEndLineCap = PenLineCap.Round+ });+ }+ }+ return new Viewbox { Width = size, Height = size, Child = canvas, VerticalAlignment = VerticalAlignment.Center };+ }+}diff --git a/Widgets/AppGroupWidget.cs b/Widgets/AppGroupWidget.csnew file mode 100644index 0000000..97bc289--- /dev/null+++ b/Widgets/AppGroupWidget.cs@@ -0,0 +1,192 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Input;+using System.Windows.Media;+using QiDock.Models;+using QiDock.Services;+using QiDock.Services.Notifications;++namespace QiDock.Widgets;++/// <summary>+/// Up to four favourite apps in one small square: a click on an icon opens that app; an empty slot (or a right+/// click) opens the card, where apps are picked from the Start menu's list.+/// </summary>+public sealed class AppGroupWidget : DockWidget+{+ private const int Slots = 4;+ private static readonly Dictionary<string, ImageSource?> Icons = new(StringComparer.OrdinalIgnoreCase);++ private readonly Border _tile;+ private readonly UniformGrid _grid = new() { Rows = 2, Columns = 2 };+ private readonly WidgetPopup _popup;+ private readonly TextBox _search = new();+ private readonly StackPanel _chosen = new();+ private readonly StackPanel _results = new();+ private readonly StackPanel _card = new();+ private List<InstalledApp>? _catalog;+ private bool _loadingCatalog;+ private IReadOnlyList<AppLink> _apps = [];++ public AppGroupWidget()+ {+ _tile = new Border { Child = _grid, CornerRadius = new CornerRadius(11), BorderThickness = new Thickness(1), Padding = new Thickness(3), Margin = new Thickness(3, 0, 3, 0), VerticalAlignment = VerticalAlignment.Center };+ _tile.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ _tile.SetResourceReference(Border.BorderBrushProperty, "WidgetTileStroke");+ _tile.SetResourceReference(FrameworkElement.HeightProperty, "WidgetTileHeight");+ _tile.SetResourceReference(FrameworkElement.WidthProperty, "WidgetTileHeight");+ _tile.MouseRightButtonUp += (_, e) =>+ {+ e.Handled = true;+ Toggle();+ };+ _popup = new WidgetPopup(_tile);++ _search.SetResourceReference(FrameworkElement.StyleProperty, "WidgetTextBox");+ _search.TextChanged += (_, _) => RenderResults();+ _search.KeyDown += (_, e) => { if (e.Key == Key.Escape) _popup.Close(); };+ _card.Children.Add(Ui.Header(UiText.Get("AppGroupTitle"), () => _popup.Close()));+ _card.Children.Add(_chosen);+ _search.Margin = new Thickness(0, 10, 0, 6);+ _card.Children.Add(_search);+ _card.Children.Add(Ui.FadingScroller(_results, 220));+ UiText.Current.PropertyChanged += (_, _) => Render();+ Render();+ }++ public override string Id => WidgetIds.AppGroup;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();++ public override void Stop()+ {+ _popup.Close();+ _catalog = null; // the list is read again when asked; it is not kept+ }++ public override void ApplySettings(WidgetSettings settings)+ {+ var apps = settings.AppGroup ?? [];+ if (apps.SequenceEqual(_apps)) return;+ _apps = apps;+ Render();+ }++ private static ImageSource? IconOf(string id, int size)+ {+ var key = id + "|" + size;+ if (!Icons.TryGetValue(key, out var icon)) Icons[key] = icon = NotificationApps.LoadIcon(id, size);+ return icon;+ }++ private void Render()+ {+ _grid.Children.Clear();+ var cell = Math.Max(14, ((Application.Current.TryFindResource("WidgetTileHeight") as double? ?? 40) - 10) / 2);+ for (var i = 0; i < Slots; i++)+ {+ if (i < _apps.Count)+ {+ var app = _apps[i];+ var image = new Image { Source = IconOf(app.Id, 32), Width = cell - 2, Height = cell - 2, Stretch = Stretch.Uniform };+ RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality);+ var open = Ui.IconButton(image, (_, _) => new InstalledApp(app.Name, app.Id).Launch(), app.Name, cell, cell);+ open.Padding = new Thickness(0);+ _grid.Children.Add(open);+ }+ else+ {+ var plus = Ui.IconButton(Ui.Icon("IconPlus", 9, brushKey: "TextSecondary"), (_, _) => Toggle(), UiText.Get("AppGroupAdd"), cell, cell);+ plus.Padding = new Thickness(0);+ _grid.Children.Add(plus);+ }+ }+ _tile.ToolTip = _apps.Count > 0 ? UiText.Get("AppGroupHint") : null;+ if (_popup.IsOpen) RenderCard();+ }++ private void RenderCard()+ {+ _chosen.Children.Clear();+ if (_apps.Count == 0)+ {+ var none = Ui.Text(UiText.Get("AppGroupEmpty"), 11.5, brushKey: "TextSecondary");+ none.TextWrapping = TextWrapping.Wrap;+ _chosen.Children.Add(none);+ }+ foreach (var app in _apps)+ {+ var row = new DockPanel { Margin = new Thickness(0, 2, 0, 2) };+ var image = new Image { Source = IconOf(app.Id, 32), Width = 22, Height = 22, Margin = new Thickness(0, 0, 8, 0) };+ DockPanel.SetDock(image, Dock.Left);+ var remove = Ui.IconButton(Ui.Icon("IconClose", 10, brushKey: "TextSecondary"), (_, _) =>+ UpdateSettings(s => s with { AppGroup = (s.AppGroup ?? []).Where(a => a.Id != app.Id).ToList() }), UiText.Get("AppGroupRemove"));+ DockPanel.SetDock(remove, Dock.Right);+ row.Children.Add(image);+ row.Children.Add(remove);+ row.Children.Add(Ui.Text(app.Name, 12.5, FontWeights.SemiBold));+ _chosen.Children.Add(row);+ }+ _search.Tag = UiText.Get(_apps.Count >= Slots ? "AppGroupFull" : "AppGroupSearch");+ _search.IsEnabled = _apps.Count < Slots;+ RenderResults();+ }++ private void RenderResults()+ {+ _results.Children.Clear();+ if (_apps.Count >= Slots) return;+ if (_catalog is null)+ {+ _results.Children.Add(Ui.Text(UiText.Get("AppGroupLoading"), 11, brushKey: "TextSecondary"));+ _ = LoadCatalogAsync();+ return;+ }+ var query = _search.Text.Trim();+ var matches = _catalog+ .Where(app => _apps.All(a => a.Id != app.Id))+ .Where(app => query.Length == 0 || app.Name.Contains(query, StringComparison.CurrentCultureIgnoreCase))+ .Take(query.Length == 0 ? 8 : 20);+ foreach (var app in matches)+ {+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ row.Children.Add(new Image { Source = IconOf(app.Id, 32), Width = 20, Height = 20, Margin = new Thickness(0, 0, 8, 0) });+ row.Children.Add(Ui.Text(app.Name, 12));+ var pick = new Button { Content = row, HorizontalContentAlignment = HorizontalAlignment.Left, Padding = new Thickness(6, 4, 6, 4) };+ pick.SetResourceReference(FrameworkElement.StyleProperty, "WidgetIconButton");+ pick.Width = double.NaN;+ pick.Height = double.NaN;+ pick.HorizontalAlignment = HorizontalAlignment.Stretch;+ pick.Click += (_, _) =>+ {+ _search.Text = "";+ UpdateSettings(s => s with { AppGroup = (s.AppGroup ?? []).Append(new AppLink(app.Name, app.Id)).Take(Slots).ToList() });+ };+ _results.Children.Add(pick);+ }+ }++ private async Task LoadCatalogAsync()+ {+ if (_loadingCatalog) return;+ _loadingCatalog = true;+ try { _catalog = (await AppCatalog.LoadAsync()).OrderBy(app => app.Name, StringComparer.CurrentCultureIgnoreCase).ToList(); }+ finally { _loadingCatalog = false; }+ if (_popup.IsOpen) RenderResults();+ }++ private void Toggle()+ {+ if (_popup.IsOpen)+ {+ _popup.Close();+ return;+ }+ _popup.SetContent(_card, 300);+ _popup.Toggle();+ RenderCard();+ if (_apps.Count < Slots) _popup.FocusInput(_search);+ }+}diff --git a/Widgets/AppVolumeWidget.cs b/Widgets/AppVolumeWidget.csnew file mode 100644index 0000000..6921701--- /dev/null+++ b/Widgets/AppVolumeWidget.cs@@ -0,0 +1,117 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using QiDock.Models;+using QiDock.Services;+using QiDock.Services.Widgets;++namespace QiDock.Widgets;++/// <summary>Per-app volume: one slider and mute button for every app that has sound open.</summary>+public sealed class AppVolumeWidget : DockWidget+{+ private readonly Button _tile;+ private readonly WidgetPopup _popup;+ private AudioSessions? _sessions;++ public AppVolumeWidget()+ {+ _tile = Ui.Tile(Ui.Icon("IconMixer", 18), (_, _) => Toggle(), 12);+ _tile.ToolTip = UiText.Get("AppVolumeTitle");+ _popup = new WidgetPopup(_tile);+ _popup.Closed += (_, _) =>+ {+ _sessions?.Dispose();+ _sessions = null;+ };+ }++ public override string Id => WidgetIds.AppVolume;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();+ public override void Stop() => _popup.Close();++ private void Toggle()+ {+ if (!_popup.IsOpen) Build();+ _popup.Toggle();+ }++ private void Build()+ {+ _sessions?.Dispose();+ _sessions = new AudioSessions();+ var apps = _sessions.Read();+ var root = new StackPanel();+ root.Children.Add(Ui.Header(UiText.Get("AppVolumeTitle"), () => _popup.Close(),+ Ui.IconButton(Ui.Icon("IconRefresh", 13), (_, _) => Build(), UiText.Get("Refresh"))));+ if (apps.Count == 0)+ {+ var empty = Ui.Text(UiText.Get("AppVolumeEmpty"), 12, brushKey: "TextSecondary");+ empty.TextWrapping = TextWrapping.Wrap;+ empty.Margin = new Thickness(0, 0, 0, 6);+ root.Children.Add(empty);+ }+ var list = new StackPanel();+ foreach (var app in apps) list.Children.Add(Row(app));+ root.Children.Add(new ScrollViewer { Content = list, MaxHeight = 360, VerticalScrollBarVisibility = ScrollBarVisibility.Auto });+ _popup.SetContent(root, 320);+ }++ private static FrameworkElement Row(AudioSessions.App app)+ {+ var icon = app.ExecutablePath is { } path ? Ui.FileIcon(path, 22) : Ui.Icon("IconVolume", 16);+ icon.Margin = new Thickness(0, 0, 10, 0);+ icon.VerticalAlignment = VerticalAlignment.Top;+ var title = new StackPanel { Orientation = Orientation.Horizontal };+ title.Children.Add(Ui.Text(app.Name, 12, FontWeights.SemiBold));+ if (app.Playing)+ {+ var playing = Ui.Text(UiText.Get("AppVolumePlaying"), 10, brushKey: "TextSecondary");+ playing.Margin = new Thickness(6, 1, 0, 0);+ title.Children.Add(playing);+ }+ var percent = Ui.Text("", 10.5, brushKey: "TextSecondary");+ percent.Width = 32;+ percent.TextAlignment = TextAlignment.Right;+ var slider = new Slider { Value = Math.Round(app.Volume * 100), Margin = new Thickness(0, 0, 4, 0), VerticalAlignment = VerticalAlignment.Center };+ slider.SetResourceReference(FrameworkElement.StyleProperty, "WidgetSlider");+ var mute = new Button();+ void Refresh()+ {+ var muted = app.Muted;+ mute.Content = Ui.Icon(muted ? "IconVolumeMute" : "IconVolume", 13, brushKey: muted ? "TextSecondary" : "TextPrimary");+ percent.Text = "%" + (int)slider.Value;+ slider.Opacity = muted ? 0.45 : 1;+ }+ mute = Ui.IconButton(new ContentControl(), (_, _) =>+ {+ app.Muted = !app.Muted;+ Refresh();+ }, UiText.Get("AppVolumeMute"));+ slider.ValueChanged += (_, e) =>+ {+ app.Volume = (float)(e.NewValue / 100);+ if (app.Muted && e.NewValue > 0) app.Muted = false;+ Refresh();+ };+ Refresh();+ // The slider takes the room left, so the percentages end at the card's right edge, under the ×.+ var controls = new DockPanel { Margin = new Thickness(-4, 2, 0, 0) };+ DockPanel.SetDock(mute, Dock.Left);+ DockPanel.SetDock(percent, Dock.Right);+ percent.VerticalAlignment = VerticalAlignment.Center;+ controls.Children.Add(mute);+ controls.Children.Add(percent);+ controls.Children.Add(slider);+ var text = new StackPanel();+ text.Children.Add(title);+ text.Children.Add(controls);+ var row = new DockPanel { Margin = new Thickness(0, 4, 0, 6) };+ DockPanel.SetDock(icon, Dock.Left);+ row.Children.Add(icon);+ row.Children.Add(text);+ return row;+ }+}diff --git a/Widgets/BatteryWidget.cs b/Widgets/BatteryWidget.csnew file mode 100644index 0000000..0599ca0--- /dev/null+++ b/Widgets/BatteryWidget.cs@@ -0,0 +1,185 @@+using System.Globalization;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Threading;+using QiDock.DesktopWidgets;+using QiDock.Models;+using QiDock.Services;+using QiDock.Services.Widgets;++namespace QiDock.Widgets;++/// <summary>Battery charge as a ring with the percent inside (a bolt under it while charging); a click opens the battery's own card.</summary>+public sealed class BatteryWidget : DockWidget+{+ private static readonly System.Windows.Media.Brush Green = Ui.Solid("#FF30D158");+ private static readonly System.Windows.Media.Brush Yellow = Ui.Solid("#FFFFD60A");+ private static readonly System.Windows.Media.Brush Red = Ui.Solid("#FFFF453A");++ private readonly Button _tile;+ private readonly RingGauge _ring;+ private readonly TextBlock _percent;+ private readonly FrameworkElement _bolt;+ private readonly DispatcherTimer _timer;+ private readonly WidgetPopup _popup;+ private BatteryStatus.State? _state;+ private string _last = "";++ public BatteryWidget()+ {+ _ring = new RingGauge { Width = 34, Height = 34, Thickness = 3.5, TrackBrush = Ui.Solid("#47808080"), Stroke = Green };+ _percent = Ui.Text("", 11.5, FontWeights.Bold);+ _percent.HorizontalAlignment = HorizontalAlignment.Center;+ _bolt = Ui.Glyph("GlyphBolt", 7, Green);+ _bolt.HorizontalAlignment = HorizontalAlignment.Center;+ _bolt.Margin = new Thickness(0, -1, 0, 0);+ _bolt.Visibility = Visibility.Collapsed;+ var inside = new StackPanel { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ inside.Children.Add(_percent);+ inside.Children.Add(_bolt);+ var face = new Grid { Width = 34, Height = 34, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ face.Children.Add(_ring);+ face.Children.Add(inside);+ _tile = Ui.Tile(face, (_, _) => TogglePopup(), horizontalPadding: 0);+ _popup = new WidgetPopup(_tile);+ _tile.SetResourceReference(FrameworkElement.WidthProperty, "WidgetTileHeight");+ _tile.Visibility = Visibility.Collapsed;+ _timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(30) };+ _timer.Tick += (_, _) => Update();+ UiText.Current.PropertyChanged += (_, _) => { _last = ""; Update(); };+ }++ public override string Id => WidgetIds.Battery;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();++ public override void Start()+ {+ Update();+ _timer.Start();+ }++ public override void Stop()+ {+ _timer.Stop();+ _popup.Close();+ }++ public override void SetLive(bool live)+ {+ if (!live)+ {+ _timer.Stop();+ return;+ }+ Update();+ _timer.Start();+ }++ private void Update()+ {+ var state = _state = BatteryStatus.Read();+ var signature = state is null ? "none" : $"{state.Percent}{state.Charging}{state.OnAc}{state.Remaining?.TotalMinutes:0}";+ if (signature == _last) return;+ _last = signature;+ var visible = state is not null;+ if ((_tile.Visibility == Visibility.Visible) != visible)+ {+ _tile.Visibility = visible ? Visibility.Visible : Visibility.Collapsed;+ RaiseLayoutChanged();+ }+ if (_popup.IsOpen) BuildPopup();+ if (state is null) return;+ var color = state.Percent <= 15 && !state.OnAc ? Red : state.Percent <= 30 && !state.OnAc ? Yellow : Green;+ _ring.Stroke = color;+ _ring.Value = state.Percent;+ _ring.InvalidateVisual();+ _percent.Text = state.Percent.ToString(CultureInfo.InvariantCulture);+ _bolt.Visibility = state.Charging || state.OnAc ? Visibility.Visible : Visibility.Collapsed;+ }++ private static System.Windows.Media.Brush ColorFor(BatteryStatus.State state) =>+ state.Percent <= 15 && !state.OnAc ? Red : state.Percent <= 30 && !state.OnAc ? Yellow : Green;++ private void TogglePopup()+ {+ if (!_popup.IsOpen)+ {+ _last = "";+ Update();+ BuildPopup();+ }+ _popup.Toggle();+ }++ /// <summary>The battery's card: a large ring, where the power comes from, the time left and a way to the settings.</summary>+ private void BuildPopup()+ {+ var root = new StackPanel();+ var header = new DockPanel { Margin = new Thickness(0, 0, 0, 12) };+ var close = Ui.IconButton(Ui.Icon("IconClose", 12, brushKey: "TextSecondary"), (_, _) => _popup.Close(), UiText.Get("Close"));+ DockPanel.SetDock(close, Dock.Right);+ header.Children.Add(close);+ header.Children.Add(Ui.Text(UiText.Get("BatteryTitle"), 14, FontWeights.SemiBold));+ root.Children.Add(header);++ if (_state is not { } state)+ {+ root.Children.Add(Ui.Text(UiText.Get("BatteryNone"), 12, brushKey: "TextSecondary"));+ _popup.SetContent(root, 280);+ return;+ }++ var color = ColorFor(state);+ var ring = new RingGauge { Width = 72, Height = 72, Thickness = 6, TrackBrush = Ui.Solid("#47808080"), Stroke = color, Value = state.Percent };+ var percent = Ui.Text(state.Percent.ToString(CultureInfo.InvariantCulture) + "%", 17, FontWeights.Bold);+ percent.HorizontalAlignment = HorizontalAlignment.Center;+ percent.VerticalAlignment = VerticalAlignment.Center;+ var face = new Grid { Width = 72, Height = 72 };+ face.Children.Add(ring);+ face.Children.Add(percent);++ var source = state.Charging ? UiText.Get("BatteryCharging")+ : state.OnAc ? (state.Percent >= 100 ? UiText.Get("BatteryFull") : UiText.Get("BatteryPlugged"))+ : UiText.Get("BatteryOnBattery");+ var info = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(16, 0, 0, 0) };+ var sourceRow = new StackPanel { Orientation = Orientation.Horizontal };+ if (state.Charging || state.OnAc)+ {+ var bolt = Ui.Glyph("GlyphBolt", 10, Green);+ bolt.Margin = new Thickness(0, 0, 6, 0);+ bolt.VerticalAlignment = VerticalAlignment.Center;+ sourceRow.Children.Add(bolt);+ }+ sourceRow.Children.Add(Ui.Text(source, 13.5, FontWeights.SemiBold));+ info.Children.Add(sourceRow);+ if (!state.OnAc)+ {+ var left = state.Remaining is { } r ? UiText.Format("BatteryLeft", (int)r.TotalHours, r.Minutes) : UiText.Get("BatteryEstimating");+ var leftText = Ui.Text(left, 12, brushKey: "TextSecondary");+ leftText.Margin = new Thickness(0, 3, 0, 0);+ info.Children.Add(leftText);+ }+ if (state.Saver)+ {+ var saver = Ui.Text(UiText.Get("BatterySaverOn"), 12, FontWeights.SemiBold, brush: Yellow);+ saver.Margin = new Thickness(0, 3, 0, 0);+ info.Children.Add(saver);+ }+ var top = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 14) };+ top.Children.Add(face);+ top.Children.Add(info);+ root.Children.Add(top);++ var settings = new Button { Content = UiText.Get("BatterySettings"), HorizontalAlignment = HorizontalAlignment.Left };+ settings.SetResourceReference(FrameworkElement.StyleProperty, "WidgetPillButton");+ settings.Click += (_, _) =>+ {+ _popup.Close();+ Ui.Open("ms-settings:batterysaver");+ };+ root.Children.Add(settings);+ _popup.SetContent(root, 300);+ }+}diff --git a/Widgets/ClockWidget.cs b/Widgets/ClockWidget.csnew file mode 100644index 0000000..ad4afe1--- /dev/null+++ b/Widgets/ClockWidget.cs@@ -0,0 +1,407 @@+using System.Globalization;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Media;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;+using QiDock.Services.Widgets;++namespace QiDock.Widgets;++/// <summary>Clock tile; opens a month calendar with the selected day's events.</summary>+public sealed class ClockWidget : DockWidget+{+ private readonly Button _tile;+ private readonly TextBlock _time;+ private readonly TextBlock _seconds;+ private readonly TextBlock _date;+ private readonly DispatcherTimer _timer;+ private readonly DispatcherTimer _feedTimer;+ private readonly WidgetPopup _popup;+ private readonly CalendarFeedService _feed = new();+ private CancellationTokenSource? _feedLoad;+ private bool _showSeconds;+ private string? _feedUrl;+ private DateTime _visibleMonth;+ private DateTime _selectedDay;+ private string _lastTime = "";++ public ClockWidget()+ {+ // Large hours:minutes, small seconds beside them and the date underneath, straight on the dock glass.+ _time = Ui.Text(size: 19, weight: FontWeights.SemiBold);+ _seconds = Ui.Text(size: 10.5, weight: FontWeights.SemiBold, brushKey: "TextSecondary");+ _seconds.VerticalAlignment = VerticalAlignment.Bottom;+ _seconds.Margin = new Thickness(1, 0, 0, 3);+ var timeRow = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Center };+ timeRow.Children.Add(_time);+ timeRow.Children.Add(_seconds);+ _date = Ui.Text(size: 10, brushKey: "TextSecondary");+ _date.Margin = new Thickness(0, -3, 0, 0);+ _date.HorizontalAlignment = HorizontalAlignment.Center;+ var stack = new StackPanel { VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };+ stack.Children.Add(timeRow);+ stack.Children.Add(_date);+ // A filled tile like the others: big time centred, the date under it.+ _tile = new Button { Content = stack, MinWidth = 88, Padding = new Thickness(12, 0, 12, 0) };+ _tile.SetResourceReference(FrameworkElement.StyleProperty, "WidgetTileButton");+ _tile.Click += (_, _) => TogglePopup();+ _popup = new WidgetPopup(_tile);++ _timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(1) };+ _timer.Tick += (_, _) => UpdateClock();+ _feedTimer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMinutes(15) };+ _feedTimer.Tick += (_, _) => _ = RefreshFeedAsync();+ UiText.Current.PropertyChanged += (_, _) => { _lastTime = ""; UpdateClock(); };+ }++ public override string Id => WidgetIds.Clock;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;++ public override void Start()+ {+ UpdateClock();+ _timer.Start();+ _feedTimer.Start();+ _ = RefreshFeedAsync();+ }++ public override void Stop()+ {+ _timer.Stop();+ _feedTimer.Stop();+ _feedLoad?.Cancel();+ _popup.Close();+ }++ public override void ClosePopup() => _popup.Close();++ public override void SetLive(bool live)+ {+ if (!live)+ {+ _timer.Stop();+ return;+ }+ UpdateClock();+ _timer.Start();+ }++ public override void ApplySettings(WidgetSettings settings)+ {+ _showSeconds = settings.ShowSeconds;+ _lastTime = "";+ UpdateClock();+ if (!string.Equals(_feedUrl, settings.CalendarFeedUrl, StringComparison.Ordinal))+ {+ _feedUrl = settings.CalendarFeedUrl;+ _ = RefreshFeedAsync();+ }+ }++ private static CultureInfo Culture => CultureInfo.GetCultureInfo(UiText.Get("CultureName"));++ private void UpdateClock()+ {+ var now = DateTime.Now;+ var time = now.ToString("HH:mm:ss", Culture);+ if (time == _lastTime) return;+ _lastTime = time;+ _time.Text = now.ToString("HH:mm", Culture);+ _seconds.Text = now.ToString(":ss", Culture);+ _seconds.Visibility = _showSeconds ? Visibility.Visible : Visibility.Collapsed;+ _date.Text = now.ToString(UiText.Get("ClockDateFormat"), Culture);+ _tile.ToolTip = now.ToString("D", Culture);+ }++ private async Task RefreshFeedAsync()+ {+ _feedLoad?.Cancel();+ var load = _feedLoad = new CancellationTokenSource();+ try+ {+ await _feed.RefreshAsync(_feedUrl, load.Token);+ if (_popup.IsOpen) BuildPopup();+ }+ catch (OperationCanceledException)+ {+ }+ }++ private void TogglePopup()+ {+ if (!_popup.IsOpen)+ {+ _visibleMonth = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);+ _selectedDay = DateTime.Today;+ BuildPopup();+ if (_feed.HasFeed && (_feed.LastUpdated is null || DateTime.Now - _feed.LastUpdated > TimeSpan.FromMinutes(5)))+ _ = RefreshFeedAsync();+ }+ _popup.Toggle();+ }++ private const double CellWidth = 44;+ private const double CellHeight = 46;++ private void BuildPopup()+ {+ var culture = Culture;+ var root = new Grid();+ root.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(CellWidth * 7 + 4) });+ root.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(16) });+ root.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(236) });+ root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });+ root.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });++ // --- Header: "Kasım 2026" on the left; Calendars · Today · ‹ › · × on the right ---+ var header = new DockPanel { Margin = new Thickness(2, 0, 0, 4) };+ Grid.SetColumnSpan(header, 3);+ var nav = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };+ DockPanel.SetDock(nav, Dock.Right);+ var calendars = new Button { Content = UiText.Get("CalCalendars"), Padding = new Thickness(11, 4, 11, 4), Margin = new Thickness(0, 0, 6, 0) };+ calendars.SetResourceReference(FrameworkElement.StyleProperty, "WidgetPillButton");+ calendars.Click += (_, _) => { _popup.Close(); RequestSettings(); };+ nav.Children.Add(calendars);+ var today = new Button { Content = UiText.Get("CalToday"), VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 4, 0) };+ today.SetResourceReference(FrameworkElement.StyleProperty, "WidgetLinkButton");+ today.Click += (_, _) => { _visibleMonth = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1); _selectedDay = DateTime.Today; BuildPopup(); };+ nav.Children.Add(today);+ nav.Children.Add(Ui.IconButton(Ui.Icon("IconChevronLeft", 14), (_, _) => ShiftMonth(-1), UiText.Get("CalPrevMonth")));+ nav.Children.Add(Ui.IconButton(Ui.Icon("IconChevronRight", 14), (_, _) => ShiftMonth(1), UiText.Get("CalNextMonth")));+ nav.Children.Add(Ui.IconButton(Ui.Icon("IconClose", 12, brushKey: "TextSecondary"), (_, _) => _popup.Close(), UiText.Get("Close")));+ header.Children.Add(nav);+ var title = Ui.Text(culture.TextInfo.ToTitleCase(_visibleMonth.ToString("MMMM, yyyy", culture)), 19, FontWeights.Bold);+ header.Children.Add(title);+ root.Children.Add(header);++ // --- Month view ---+ var month = new StackPanel();+ Grid.SetRow(month, 1);++ var legend = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(3, 0, 0, 10) };+ legend.Children.Add(LegendDot(EventBrush, UiText.Get("CalEvents")));+ legend.Children.Add(LegendDot(AllDayBrush, UiText.Get("CalAllDay")));+ if (_feed.HasFeed) month.Children.Add(legend); // a key for colors that can't show yet is noise++ var weekdays = new UniformGrid { Columns = 7, Margin = new Thickness(0, 0, 0, 4) };+ var firstDay = culture.DateTimeFormat.FirstDayOfWeek;+ for (var i = 0; i < 7; i++)+ {+ var day = (DayOfWeek)(((int)firstDay + i) % 7);+ var isTodayColumn = day == DateTime.Today.DayOfWeek;+ var chip = new Border { CornerRadius = new CornerRadius(8), Margin = new Thickness(2), Padding = new Thickness(0, 3, 0, 3) };+ chip.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ var label = Ui.Text(culture.DateTimeFormat.GetAbbreviatedDayName(day).ToUpper(culture), 9.5, FontWeights.SemiBold,+ isTodayColumn ? "TextPrimary" : "TextSecondary");+ label.HorizontalAlignment = HorizontalAlignment.Center;+ chip.Child = label;+ weekdays.Children.Add(chip);+ }+ month.Children.Add(weekdays);++ var gridStart = _visibleMonth.AddDays(-(((int)_visibleMonth.DayOfWeek - (int)firstDay + 7) % 7));+ var weeks = (int)Math.Ceiling(((_visibleMonth - gridStart).Days + DateTime.DaysInMonth(_visibleMonth.Year, _visibleMonth.Month)) / 7.0);+ var gridEnd = gridStart.AddDays(weeks * 7);+ var occurrences = _feed.GetOccurrences(gridStart, gridEnd);+ var perDay = new Dictionary<DateTime, (int Timed, int AllDay)>();+ foreach (var item in occurrences)+ {+ var lastDay = item.AllDay ? item.End.AddDays(-1).Date : (item.End > item.Start ? item.End.AddTicks(-1).Date : item.Start.Date);+ for (var d = item.Start.Date; d <= lastDay && d < gridEnd; d = d.AddDays(1))+ {+ perDay.TryGetValue(d, out var count);+ perDay[d] = item.AllDay ? (count.Timed, count.AllDay + 1) : (count.Timed + 1, count.AllDay);+ }+ }++ var days = new UniformGrid { Columns = 7, Rows = weeks };+ for (var i = 0; i < weeks * 7; i++)+ {+ var date = gridStart.AddDays(i);+ perDay.TryGetValue(date, out var count);+ days.Children.Add(date.Month == _visibleMonth.Month ? CreateDayCell(date, count.Timed, count.AllDay) : new Border());+ }+ month.Children.Add(days);+ root.Children.Add(month);++ // --- Agenda panel ---+ // Top and bottom edges line up with the weekday chips and the last row of day tiles.+ var panel = new Border { CornerRadius = new CornerRadius(12), Padding = new Thickness(14, 12, 14, 12), Margin = new Thickness(0, 2, 0, 2) };+ panel.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ Grid.SetColumn(panel, 2);+ Grid.SetRow(panel, 1);+ var agendaLayout = new DockPanel();+ panel.Child = agendaLayout;++ // Footer: current time and a quick way to add an event.+ var footer = new Border { CornerRadius = new CornerRadius(10), Padding = new Thickness(10, 6, 10, 6), Margin = new Thickness(0, 10, 0, 0) };+ footer.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ DockPanel.SetDock(footer, Dock.Bottom);+ var footerRow = new DockPanel();+ var now = Ui.Text(DateTime.Now.ToString("HH:mm", culture), 11.5, FontWeights.SemiBold);+ now.VerticalAlignment = VerticalAlignment.Center;+ DockPanel.SetDock(now, Dock.Left);+ footerRow.Children.Add(now);+ var newEvent = new Button { Content = UiText.Format("CalNewEventOn", _selectedDay == DateTime.Today ? UiText.Get("CalToday").ToLower(culture) : _selectedDay.ToString("d MMM", culture)), Margin = new Thickness(6, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left };+ newEvent.SetResourceReference(FrameworkElement.StyleProperty, "WidgetLinkButton");+ newEvent.SetResourceReference(Control.ForegroundProperty, "TextSecondary");+ newEvent.Click += (_, _) => { _popup.Close(); Ui.Open(NewEventLink(_selectedDay)); };+ footerRow.Children.Add(newEvent);+ footer.Child = footerRow;+ agendaLayout.Children.Add(footer);++ var agenda = new StackPanel();+ var titleRow = new DockPanel { Margin = new Thickness(0, 0, 0, 12) };+ var dayItems = _feed.HasFeed ? _feed.GetOccurrences(_selectedDay, _selectedDay.AddDays(1)) : [];+ if (_feed.HasFeed)+ {+ var count = Ui.Text(UiText.Format("CalEventCount", dayItems.Count), 10.5, brushKey: "TextSecondary");+ DockPanel.SetDock(count, Dock.Right);+ titleRow.Children.Add(count);+ }+ var agendaTitle = _selectedDay == DateTime.Today ? UiText.Get("CalToday")+ : culture.TextInfo.ToTitleCase(_selectedDay.ToString("d MMMM dddd", culture));+ titleRow.Children.Add(Ui.Text(agendaTitle, 14, FontWeights.Bold));+ agenda.Children.Add(titleRow);++ var list = new StackPanel();+ var scroller = new ScrollViewer { Content = list, MaxHeight = 250, VerticalScrollBarVisibility = ScrollBarVisibility.Auto };+ agenda.Children.Add(scroller);++ if (!_feed.HasFeed)+ {+ var hint = Ui.Text(UiText.Get("CalNoFeed"), 11.5, brushKey: "TextSecondary");+ hint.TextWrapping = TextWrapping.Wrap;+ hint.TextTrimming = TextTrimming.None;+ list.Children.Add(hint);+ var connect = new Button { Content = UiText.Get("CalConnect"), HorizontalAlignment = HorizontalAlignment.Left, Margin = new Thickness(-6, 8, 0, 0) };+ connect.SetResourceReference(FrameworkElement.StyleProperty, "WidgetLinkButton");+ connect.Click += (_, _) => { _popup.Close(); RequestSettings(); };+ list.Children.Add(connect);+ }+ else if (dayItems.Count == 0)+ {+ list.Children.Add(Ui.Text(_feed.LastError ?? (_feed.LastUpdated is null ? UiText.Get("CalLoading") : UiText.Get("CalEmpty")),+ 12, brushKey: _feed.LastError is null ? "TextSecondary" : "DangerText"));+ }+ foreach (var item in dayItems) list.Children.Add(CreateEventRow(item, culture));+ agendaLayout.Children.Add(agenda);+ root.Children.Add(panel);++ _popup.SetContent(root, CellWidth * 7 + 4 + 16 + 236 + 34);+ }++ private static readonly Brush EventBrush = Ui.Solid("#FF3B9BFF");+ private static readonly Brush AllDayBrush = Ui.Solid("#FF8E7CFF");++ private static UIElement LegendDot(Brush brush, string text)+ {+ var row = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 0, 12, 0) };+ row.Children.Add(new System.Windows.Shapes.Ellipse { Width = 6, Height = 6, Fill = brush, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 5, 0) });+ row.Children.Add(Ui.Text(text, 10.5, brushKey: "TextSecondary"));+ return row;+ }++ /// <summary>Opens a new-event page for the day: Google Calendar for Google feeds, Outlook on the web otherwise.</summary>+ private string NewEventLink(DateTime day)+ {+ var date = day.ToString("yyyyMMdd", CultureInfo.InvariantCulture);+ if (_feedUrl is { } url && url.Contains("outlook", StringComparison.OrdinalIgnoreCase))+ return "https://outlook.live.com/calendar/0/deeplink/compose?startdt=" + day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + "T09:00:00";+ return $"https://calendar.google.com/calendar/r/eventedit?dates={date}/{day.AddDays(1).ToString("yyyyMMdd", CultureInfo.InvariantCulture)}";+ }++ private UIElement CreateDayCell(DateTime date, int timed, int allDay)+ {+ var isToday = date == DateTime.Today;+ var isSelected = date == _selectedDay;+ var isWeekend = date.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday;++ // Same 2px inset as the weekday chips above, so the columns line up exactly.+ var tile = new Border { CornerRadius = new CornerRadius(10), Margin = new Thickness(2), Height = CellHeight - 4 };+ tile.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ if (isSelected)+ {+ tile.SetResourceReference(Border.BorderBrushProperty, "WidgetAccent");+ tile.BorderThickness = new Thickness(1.5);+ }++ // Day number in the middle of the tile (with its event chips under it); today sits in a blue circle.+ var grid = new StackPanel { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ var badge = new Border { Width = 24, Height = 24, CornerRadius = new CornerRadius(12), HorizontalAlignment = HorizontalAlignment.Center };+ if (isToday) badge.SetResourceReference(Border.BackgroundProperty, "WidgetAccent");+ var number = Ui.Text(date.Day.ToString(CultureInfo.InvariantCulture), 12, isToday ? FontWeights.Bold : FontWeights.SemiBold,+ brush: isToday ? Brushes.White : null, brushKey: isWeekend ? "TextSecondary" : "TextPrimary");+ number.HorizontalAlignment = HorizontalAlignment.Center;+ number.VerticalAlignment = VerticalAlignment.Center;+ badge.Child = number;+ grid.Children.Add(badge);++ // Event chips along the bottom: blue for timed events, violet for all-day ones.+ if (timed + allDay > 0)+ {+ var chips = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Center, Height = 7, Margin = new Thickness(0, 2, 0, 0) };+ for (var i = 0; i < Math.Min(timed, 3); i++) chips.Children.Add(Chip(EventBrush));+ for (var i = 0; i < Math.Min(allDay, 3 - Math.Min(timed, 3)); i++) chips.Children.Add(Chip(AllDayBrush));+ var total = timed + allDay;+ if (total > 3) chips.Children.Add(Ui.Text("+" + (total - 3).ToString(CultureInfo.InvariantCulture), 8.5, FontWeights.SemiBold, "TextSecondary"));+ grid.Children.Add(chips);+ }+ tile.Child = grid;++ var button = new Button { Content = tile, ToolTip = date.ToString("D", Culture) };+ button.SetResourceReference(FrameworkElement.StyleProperty, "WidgetDayButton");+ button.Click += (_, _) =>+ {+ _selectedDay = date;+ BuildPopup();+ };+ return button;+ }++ private static UIElement Chip(Brush brush) => new Border+ {+ Width = 8, Height = 5, CornerRadius = new CornerRadius(2.5), Background = brush, Margin = new Thickness(1, 0, 1, 0), VerticalAlignment = VerticalAlignment.Center+ };++ private static UIElement CreateEventRow(CalendarOccurrence item, CultureInfo culture)+ {+ var row = new DockPanel { Margin = new Thickness(0, 0, 0, 12) };+ var time = Ui.Text(item.AllDay ? UiText.Get("CalAllDay") : item.Start.ToString("HH:mm", culture), 10.5, brushKey: "TextSecondary");+ time.Width = 46;+ time.VerticalAlignment = VerticalAlignment.Top;+ time.Margin = new Thickness(0, 2, 0, 0);+ DockPanel.SetDock(time, Dock.Left);+ row.Children.Add(time);++ var icon = new Border { Width = 24, Height = 24, CornerRadius = new CornerRadius(7), Background = item.AllDay ? AllDayBrush : EventBrush, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(0, 0, 9, 0) };+ icon.Child = Ui.Icon("IconCalendar", 12, Brushes.White, stroke: 2.1);+ DockPanel.SetDock(icon, Dock.Left);+ row.Children.Add(icon);++ var text = new StackPanel();+ var title = Ui.Text(item.Title, 12, FontWeights.SemiBold);+ title.ToolTip = item.Title;+ text.Children.Add(title);+ var when = item.AllDay ? UiText.Get("CalAllDay")+ : $"{item.Start.ToString("HH:mm", culture)} – {item.End.ToString("HH:mm", culture)}";+ if (!string.IsNullOrWhiteSpace(item.Location)) when += " · " + item.Location;+ var detail = Ui.Text(when, 10.5, brushKey: "TextSecondary");+ detail.ToolTip = when;+ text.Children.Add(detail);+ row.Children.Add(text);+ return row;+ }++ private void ShiftMonth(int delta)+ {+ _visibleMonth = _visibleMonth.AddMonths(delta);+ _selectedDay = _visibleMonth.Month == DateTime.Today.Month && _visibleMonth.Year == DateTime.Today.Year+ ? DateTime.Today : _visibleMonth;+ BuildPopup();+ }+}diff --git a/Widgets/ColorsWidget.cs b/Widgets/ColorsWidget.csnew file mode 100644index 0000000..df523f4--- /dev/null+++ b/Widgets/ColorsWidget.cs@@ -0,0 +1,263 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Interop;+using System.Windows.Media;+using System.Windows.Media.Imaging;+using System.Windows.Shapes;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>+/// Color picker: pick any pixel on screen with a magnifying loupe; picked colors are kept as+/// swatches, and clicking one copies its hex code.+/// </summary>+public sealed class ColorsWidget : DockWidget+{+ private const int MaxColors = 24; // shared with the desktop color widget+ private readonly Button _tile;+ private readonly WidgetPopup _popup;+ private readonly StackPanel _recent = new() { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };+ private IReadOnlyList<string> _colors = [];++ public ColorsWidget()+ {+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ var pick = Ui.IconButton(Ui.Icon("IconPipette", 14), (_, e) =>+ {+ e.Handled = true; // the tile itself would open the card+ Pick();+ }, UiText.Get("ColorsPick"), 30, 30);+ row.Children.Add(pick);+ row.Children.Add(_recent);+ _tile = Ui.Tile(row, (_, _) => Toggle(), 6);+ _popup = new WidgetPopup(_tile);+ }++ public override string Id => WidgetIds.Colors;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();+ public override void Stop() => _popup.Close();++ public override void ApplySettings(WidgetSettings settings)+ {+ var colors = settings.Colors ?? [];+ if (colors.SequenceEqual(_colors)) return;+ _colors = colors;+ _recent.Children.Clear();+ foreach (var hex in _colors.Take(3))+ _recent.Children.Add(new Border { Width = 16, Height = 26, CornerRadius = new CornerRadius(5), Margin = new Thickness(2, 0, 0, 0), Background = Brush(hex), BorderBrush = Ui.Solid("#40FFFFFF"), BorderThickness = new Thickness(1) });+ if (_popup.IsOpen) Build();+ }++ private static Brush Brush(string hex)+ {+ try { return Ui.Solid(hex); }+ catch (FormatException) { return Brushes.Transparent; }+ }++ private void Toggle()+ {+ if (!_popup.IsOpen) Build();+ _popup.Toggle();+ }++ private void Build()+ {+ var root = new StackPanel();+ root.Children.Add(Ui.Header(UiText.Get("ColorsTitle"), () => _popup.Close(),+ Ui.Pill(UiText.Get("ColorsPick"), (_, _) => Pick(), "IconPipette")));+ if (_colors.Count == 0)+ {+ var empty = Ui.Text(UiText.Get("ColorsEmpty"), 12, brushKey: "TextSecondary");+ empty.TextWrapping = TextWrapping.Wrap;+ empty.Margin = new Thickness(2, 0, 0, 8);+ root.Children.Add(empty);+ }+ var grid = new WrapPanel();+ foreach (var hex in _colors)+ {+ var label = Ui.Text(hex, 10.5, FontWeights.SemiBold, brush: Contrast(hex));+ label.HorizontalAlignment = HorizontalAlignment.Left;+ label.VerticalAlignment = VerticalAlignment.Bottom;+ label.Margin = new Thickness(8, 0, 0, 6);+ var face = new Border { Width = 92, Height = 58, CornerRadius = new CornerRadius(10), Background = Brush(hex), Child = label, BorderBrush = Ui.Solid("#30FFFFFF"), BorderThickness = new Thickness(1) };+ var swatch = new Button { Content = face, Margin = new Thickness(3), Cursor = Cursors.Hand, ToolTip = UiText.Get("ColorsCopyHint") };+ swatch.SetResourceReference(FrameworkElement.StyleProperty, "WidgetIconButton");+ swatch.Width = 96;+ swatch.Height = 62;+ swatch.Click += (_, _) => Copy(hex);+ swatch.MouseRightButtonUp += (_, e) =>+ {+ e.Handled = true;+ UpdateSettings(s => s with { Colors = (s.Colors ?? []).Where(c => c != hex).ToList() });+ };+ grid.Children.Add(swatch);+ }+ root.Children.Add(grid);+ if (_colors.Count > 0)+ {+ var clear = Ui.Pill(UiText.Get("ColorsClear"), (_, _) => UpdateSettings(s => s with { Colors = [] }));+ clear.Margin = new Thickness(3, 8, 0, 0);+ clear.HorizontalAlignment = HorizontalAlignment.Left;+ root.Children.Add(clear);+ }+ _popup.SetContent(root, 440);+ }++ private static Brush Contrast(string hex)+ {+ try+ {+ var color = (Color)ColorConverter.ConvertFromString(hex);+ return 0.299 * color.R + 0.587 * color.G + 0.114 * color.B > 150 ? Ui.Solid("#CC000000") : Ui.Solid("#E6FFFFFF");+ }+ catch (FormatException) { return Ui.White; }+ }++ private static void Copy(string hex)+ {+ try+ {+ Clipboard.SetText(hex);+ Ui.ShowHud("IconCopy", UiText.Format("ColorsCopied", hex));+ }+ catch (COMException) { }+ }++ private void Pick()+ {+ _popup.Close();+ var overlay = new ColorPickerOverlay();+ overlay.Picked += hex =>+ {+ Copy(hex);+ UpdateSettings(s => s with { Colors = new[] { hex }.Concat((s.Colors ?? []).Where(c => c != hex)).Take(MaxColors).ToList() });+ };+ overlay.Show();+ overlay.Activate();+ }+}++/// <summary>Full-screen, nearly invisible window with a loupe that follows the pointer; click picks.</summary>+internal sealed class ColorPickerOverlay : Window+{+ private const int Grab = 11;+ private const double LoupeSize = 120;+ private readonly Image _zoom = new() { Width = LoupeSize, Height = LoupeSize, Stretch = Stretch.Fill };+ private readonly Canvas _canvas = new();+ private readonly Border _loupe;+ private readonly TextBlock _hex;+ private string _current = "#000000";++ public event Action<string>? Picked;++ public ColorPickerOverlay()+ {+ WindowStyle = WindowStyle.None;+ ResizeMode = ResizeMode.NoResize;+ AllowsTransparency = true;+ Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0));+ ShowInTaskbar = false;+ Topmost = true;+ Cursor = Cursors.Cross;+ Left = SystemParameters.VirtualScreenLeft;+ Top = SystemParameters.VirtualScreenTop;+ Width = SystemParameters.VirtualScreenWidth;+ Height = SystemParameters.VirtualScreenHeight;+ RenderOptions.SetBitmapScalingMode(_zoom, BitmapScalingMode.NearestNeighbor);++ var lens = new Grid { Width = LoupeSize, Height = LoupeSize, Clip = new EllipseGeometry(new Point(LoupeSize / 2, LoupeSize / 2), LoupeSize / 2, LoupeSize / 2) };+ lens.Children.Add(_zoom);+ var cell = LoupeSize / Grab;+ lens.Children.Add(new Rectangle { Width = cell, Height = cell, Stroke = Brushes.White, StrokeThickness = 1.5, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center });+ var ring = new Ellipse { Width = LoupeSize, Height = LoupeSize, Stroke = Brushes.White, StrokeThickness = 3 };+ lens.Children.Add(ring);+ _hex = new TextBlock { Foreground = Brushes.White, FontSize = 12, FontWeight = FontWeights.SemiBold, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 6, 0, 0) };+ var label = new Border { Background = new SolidColorBrush(Color.FromArgb(0xD0, 0x1C, 0x1E, 0x24)), CornerRadius = new CornerRadius(8), Padding = new Thickness(8, 3, 8, 4), Child = _hex, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 6, 0, 0) };+ var stack = new StackPanel();+ stack.Children.Add(lens);+ stack.Children.Add(label);+ _loupe = new Border { Child = stack, IsHitTestVisible = false, Effect = new System.Windows.Media.Effects.DropShadowEffect { BlurRadius = 14, ShadowDepth = 2, Opacity = 0.45 } };+ _canvas.Children.Add(_loupe);+ Content = _canvas;++ MouseMove += (_, _) => Track();+ MouseLeftButtonUp += (_, _) =>+ {+ Track();+ var hex = _current;+ Close();+ Picked?.Invoke(hex);+ };+ MouseRightButtonUp += (_, _) => Close();+ KeyDown += (_, e) =>+ {+ if (e.Key == Key.Escape) Close();+ };+ Loaded += (_, _) => Track();+ }++ private void Track()+ {+ if (!GetCursorPos(out var cursor)) return;+ var bitmap = Capture(cursor.X - Grab / 2, cursor.Y - Grab / 2, Grab, Grab);+ if (bitmap is not null)+ {+ _zoom.Source = bitmap;+ var pixel = new byte[4];+ bitmap.CopyPixels(new Int32Rect(Grab / 2, Grab / 2, 1, 1), pixel, 4, 0);+ _current = $"#{pixel[2]:X2}{pixel[1]:X2}{pixel[0]:X2}";+ _hex.Text = _current;+ }+ var point = PointFromScreen(new Point(cursor.X, cursor.Y));+ var x = point.X + 24;+ var y = point.Y + 24;+ if (x + LoupeSize > ActualWidth) x = point.X - 24 - LoupeSize;+ if (y + LoupeSize + 40 > ActualHeight) y = point.Y - 24 - LoupeSize - 40;+ Canvas.SetLeft(_loupe, x);+ Canvas.SetTop(_loupe, y);+ }++ /// <summary>Screen pixels without layered windows (so this overlay and its loupe never show up).</summary>+ private static BitmapSource? Capture(int x, int y, int width, int height)+ {+ var screen = GetDC(0);+ var memory = CreateCompatibleDC(screen);+ var bitmap = CreateCompatibleBitmap(screen, width, height);+ var old = SelectObject(memory, bitmap);+ try+ {+ if (!BitBlt(memory, 0, 0, width, height, screen, x, y, 0x00CC0020 /* SRCCOPY, no CAPTUREBLT */)) return null;+ SelectObject(memory, old);+ var source = Imaging.CreateBitmapSourceFromHBitmap(bitmap, 0, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());+ var converted = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0);+ converted.Freeze();+ return converted;+ }+ finally+ {+ SelectObject(memory, old);+ DeleteObject(bitmap);+ DeleteDC(memory);+ ReleaseDC(0, screen);+ }+ }++ [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 nint GetDC(nint window);+ [DllImport("user32.dll")] private static extern int ReleaseDC(nint window, nint dc);+ [DllImport("gdi32.dll")] private static extern nint CreateCompatibleDC(nint dc);+ [DllImport("gdi32.dll")] private static extern nint CreateCompatibleBitmap(nint dc, int width, int height);+ [DllImport("gdi32.dll")] private static extern nint SelectObject(nint dc, nint item);+ [DllImport("gdi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool BitBlt(nint destination, int x, int y, int width, int height, nint source, int sourceX, int sourceY, uint operation);+ [DllImport("gdi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteObject(nint item);+ [DllImport("gdi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteDC(nint dc);+}diff --git a/Widgets/ControlCenterWidget.cs b/Widgets/ControlCenterWidget.csnew file mode 100644index 0000000..94589af--- /dev/null+++ b/Widgets/ControlCenterWidget.cs@@ -0,0 +1,32 @@+using System.Windows;+using System.Windows.Controls;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>A single round button that opens the control center (Wi-Fi, Bluetooth, sound, brightness, battery).</summary>+public sealed class ControlCenterWidget : DockWidget+{+ private readonly Button _tile;++ public ControlCenterWidget()+ {+ var icon = Ui.Icon("IconMixer", 18);+ icon.HorizontalAlignment = HorizontalAlignment.Center;+ icon.VerticalAlignment = VerticalAlignment.Center;+ _tile = Ui.Tile(icon, (_, _) => ControlCenter.Shared.ToggleFrom(_tile!), horizontalPadding: 0);+ _tile.SetResourceReference(FrameworkElement.WidthProperty, "WidgetTileHeight");+ _tile.ToolTip = UiText.Get("ControlCenterTitle");+ System.Windows.Automation.AutomationProperties.SetName(_tile, UiText.Get("ControlCenterTitle"));+ }++ public override string Id => WidgetIds.ControlCenter;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => ControlCenter.IsCreated && ControlCenter.Shared.IsOpen;++ public override void ClosePopup()+ {+ if (ControlCenter.IsCreated) ControlCenter.Shared.Close(animated: true);+ }+}diff --git a/Widgets/CurrencyWidget.cs b/Widgets/CurrencyWidget.csnew file mode 100644index 0000000..c42887c--- /dev/null+++ b/Widgets/CurrencyWidget.cs@@ -0,0 +1,197 @@+using System.Globalization;+using System.Net.Http;+using System.Text.Json;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>+/// Currency converter: the tile shows one unit of the first currency in the second (1 USD = 34,21 ₺); the card+/// converts any amount. Rates are the European Central Bank's daily reference rates (frankfurter.app, no key, no+/// personal data sent), fetched at most every six hours and only while the widget is shown.+/// </summary>+public sealed class CurrencyWidget : DockWidget+{+ private static readonly string[] Codes = ["TRY", "USD", "EUR", "GBP", "CHF", "JPY"];+ private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(10) };+ private static readonly TimeSpan Fresh = TimeSpan.FromHours(6);++ private readonly Button _tile;+ private readonly WidgetPopup _popup;+ private readonly TextBlock _pair;+ private readonly TextBlock _rate;+ private readonly TextBox _amount = new() { Text = "100" };+ private readonly TextBlock _result = Ui.Text("", 26, FontWeights.Bold);+ private readonly TextBlock _status = Ui.Text("", 10.5, brushKey: "TextSecondary");+ private readonly Button _fromButton;+ private readonly Button _toButton;+ private readonly System.Windows.Threading.DispatcherTimer _refresh = new() { Interval = TimeSpan.FromHours(1) };+ // Rates against the euro (the bank's base): 1 EUR = rate[code].+ private Dictionary<string, double> _rates = new(StringComparer.OrdinalIgnoreCase);+ private DateTime _fetchedAt;+ private string? _rateDate;+ private bool _loading;+ private bool _started;+ private StackPanel? _card;++ public CurrencyWidget()+ {+ var icon = Ui.Icon("IconSwap", 14);+ icon.Margin = new Thickness(0, 0, 8, 0);+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ _pair = Ui.Text("", 10, brushKey: "TextSecondary");+ _rate = Ui.Text("…", 13.5, FontWeights.Bold);+ _rate.FontFeatures();+ text.Children.Add(_pair);+ text.Children.Add(_rate);+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ row.Children.Add(icon);+ row.Children.Add(text);+ _tile = Ui.Tile(row, (_, _) => Toggle());+ _popup = new WidgetPopup(_tile);++ _amount.SetResourceReference(FrameworkElement.StyleProperty, "WidgetTextBox");+ _amount.FontSize = 18;+ _amount.TextChanged += (_, _) => RenderCard();+ _amount.KeyDown += (_, e) => { if (e.Key == Key.Escape) _popup.Close(); };+ _result.FontFeatures();+ _result.Margin = new Thickness(2, 10, 0, 2);+ _fromButton = Ui.Pill("", (_, _) => Cycle(from: true));+ _toButton = Ui.Pill("", (_, _) => Cycle(from: false));+ _refresh.Tick += (_, _) => _ = LoadAsync();+ UiText.Current.PropertyChanged += (_, _) => Render();+ }++ public override string Id => WidgetIds.Currency;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();++ public override void Start()+ {+ _started = true;+ _refresh.Start();+ _ = LoadAsync();+ }++ public override void Stop()+ {+ _started = false;+ _refresh.Stop();+ _popup.Close();+ }++ public override void ApplySettings(WidgetSettings settings) => Render();++ private async Task LoadAsync()+ {+ if (_loading || !_started || DateTime.UtcNow - _fetchedAt < Fresh && _rates.Count > 0) return;+ _loading = true;+ try+ {+ using var stream = await Http.GetStreamAsync("https://api.frankfurter.app/latest?from=EUR&to=" + string.Join(",", Codes.Where(c => c != "EUR")));+ using var json = await JsonDocument.ParseAsync(stream);+ var rates = new Dictionary<string, double>(StringComparer.OrdinalIgnoreCase) { ["EUR"] = 1 };+ foreach (var rate in json.RootElement.GetProperty("rates").EnumerateObject()) rates[rate.Name] = rate.Value.GetDouble();+ _rates = rates;+ _rateDate = json.RootElement.TryGetProperty("date", out var date) ? date.GetString() : null;+ _fetchedAt = DateTime.UtcNow;+ }+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException or KeyNotFoundException or InvalidOperationException)+ {+ AppLog.Write("Döviz kurları alınamadı: " + ex.Message);+ }+ finally+ {+ _loading = false;+ }+ Render();+ }++ /// <summary>How many <paramref name="to"/> one <paramref name="from"/> is worth; null until the rates are in.</summary>+ private double? Rate(string from, string to) =>+ _rates.TryGetValue(from, out var a) && _rates.TryGetValue(to, out var b) && a > 0 ? b / a : null;++ private static string Symbol(string code) => code switch+ {+ "TRY" => "₺", "USD" => "$", "EUR" => "€", "GBP" => "£", "JPY" => "¥", _ => code+ };++ private static string Money(double value, string code) =>+ value.ToString(value >= 1000 ? "N0" : value >= 10 ? "N2" : "N4", CultureInfo.CurrentCulture) + " " + Symbol(code);++ private void Render()+ {+ var from = Current.CurrencyFrom;+ var to = Current.CurrencyTo;+ _pair.Text = $"1 {from}";+ _rate.Text = Rate(from, to) is { } rate ? Money(rate, to) : _loading || _fetchedAt == default ? "…" : "—";+ _tile.ToolTip = UiText.Get("CurrencyTileHint");+ if (_popup.IsOpen) RenderCard();+ }++ private void RenderCard()+ {+ var from = Current.CurrencyFrom;+ var to = Current.CurrencyTo;+ ((TextBlock)_fromButton.Content).Text = from;+ ((TextBlock)_toButton.Content).Text = to;+ var text = _amount.Text.Trim().Replace(" ", "");+ var parsed = double.TryParse(text, NumberStyles.Number, CultureInfo.CurrentCulture, out var amount)+ || double.TryParse(text, NumberStyles.Number, CultureInfo.InvariantCulture, out amount);+ _result.Text = !parsed ? "—" : Rate(from, to) is { } rate ? Money(amount * rate, to) : "…";+ _status.Text = _rates.Count == 0+ ? UiText.Get(_loading ? "CurrencyLoading" : "CurrencyOffline")+ : UiText.Format("CurrencySource", _rateDate ?? "");+ }++ private void Cycle(bool from)+ {+ var current = from ? Current.CurrencyFrom : Current.CurrencyTo;+ var other = from ? Current.CurrencyTo : Current.CurrencyFrom;+ var next = Codes[(Array.IndexOf(Codes, current) + 1) % Codes.Length];+ if (next == other) next = Codes[(Array.IndexOf(Codes, next) + 1) % Codes.Length];+ UpdateSettings(s => from ? s with { CurrencyFrom = next } : s with { CurrencyTo = next });+ }++ private StackPanel BuildCard()+ {+ var root = new StackPanel();+ root.Children.Add(Ui.Header(UiText.Get("CurrencyTitle"), () => _popup.Close()));+ root.Children.Add(_amount);+ var pairs = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 10, 0, 0) };+ pairs.Children.Add(_fromButton);+ var swap = Ui.IconButton(Ui.Icon("IconSwap", 13), (_, _) =>+ UpdateSettings(s => s with { CurrencyFrom = s.CurrencyTo, CurrencyTo = s.CurrencyFrom }), UiText.Get("CurrencySwap"), 34, 28);+ swap.Margin = new Thickness(4, 0, 4, 0);+ pairs.Children.Add(swap);+ pairs.Children.Add(_toButton);+ root.Children.Add(pairs);+ root.Children.Add(_result);+ var hint = Ui.Text(UiText.Get("CurrencyCycleHint"), 10.5, brushKey: "TextSecondary");+ hint.TextWrapping = TextWrapping.Wrap;+ root.Children.Add(hint);+ _status.Margin = new Thickness(0, 4, 0, 0);+ root.Children.Add(_status);+ return root;+ }++ private void Toggle()+ {+ if (_popup.IsOpen)+ {+ _popup.Close();+ return;+ }+ _card ??= BuildCard();+ _popup.SetContent(_card, 280);+ _popup.Toggle();+ RenderCard();+ _popup.FocusInput(_amount);+ _ = LoadAsync();+ }+}diff --git a/Widgets/FocusWidget.cs b/Widgets/FocusWidget.csnew file mode 100644index 0000000..0823575--- /dev/null+++ b/Widgets/FocusWidget.cs@@ -0,0 +1,133 @@+using System.Globalization;+using System.Windows;+using System.Windows.Controls;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>+/// Focus timer (pomodoro): start, pause, reset; the length is picked in the card. It shows the shared+/// <see cref="FocusTimer"/>, the same countdown as the desktop focus widget. When time is up it chimes and+/// shows a message at the top of the screen, even while the bar is hidden.+/// </summary>+public sealed class FocusWidget : DockWidget+{+ private static readonly int[] Lengths = [15, 25, 45, 60];+ private static readonly System.Windows.Media.Brush Running = Ui.Solid("#FFFF6B5E");+ private static readonly System.Windows.Media.Brush Resting = Ui.Solid("#FF34C759");+ private readonly Button _tile;+ private readonly WidgetPopup _popup;+ private readonly TextBlock _time;+ private readonly TextBlock _label;+ private readonly ContentControl _playIcon = new() { Focusable = false };+ private readonly Button _reset;+ private readonly EventHandler _changed;++ public FocusWidget()+ {+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 8, 0) };+ _label = Ui.Text(UiText.Get("FocusLabel"), 10, brushKey: "TextSecondary");+ _time = Ui.Text("25:00", 17, FontWeights.Bold);+ _time.FontFeatures();+ text.Children.Add(_label);+ text.Children.Add(_time);+ var play = Ui.IconButton(_playIcon, (_, e) =>+ {+ e.Handled = true;+ FocusTimer.Toggle();+ }, UiText.Get("FocusStartPause"), 28, 28);+ _reset = Ui.IconButton(Ui.Icon("IconRotate", 12), (_, e) =>+ {+ e.Handled = true;+ FocusTimer.Reset();+ }, UiText.Get("FocusReset"), 26, 28);+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ row.Children.Add(text);+ row.Children.Add(play);+ row.Children.Add(_reset);+ _tile = Ui.Tile(row, (_, _) => Toggle(), 10);+ _popup = new WidgetPopup(_tile);+ _changed = (_, _) => Render();+ FocusTimer.Changed += _changed;+ UiText.Current.PropertyChanged += (_, _) => Render();+ Render();+ }++ public override string Id => WidgetIds.Focus;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();++ // The length setting is read by the shared timer itself; only the display needs a refresh.+ public override void ApplySettings(WidgetSettings settings) => Render();++ public override void Dispose()+ {+ FocusTimer.Changed -= _changed;+ base.Dispose();+ }++ private void Render()+ {+ var shown = FocusTimer.Remaining;+ _time.Text = shown.TotalHours >= 1+ ? shown.ToString(@"h\:mm\:ss", CultureInfo.InvariantCulture)+ : $"{(int)shown.TotalMinutes:00}:{shown.Seconds:00}";+ var accent = FocusTimer.OnBreak ? Resting : Running;+ if (FocusTimer.Running) _time.Foreground = accent;+ else _time.SetResourceReference(TextBlock.ForegroundProperty, "TextPrimary");+ _label.Text = UiText.Get(FocusTimer.OnBreak ? "FocusOnBreak" : FocusTimer.Running ? "FocusRunning" : "FocusLabel");+ _playIcon.Content = Ui.Glyph(FocusTimer.Running ? "GlyphPause" : "GlyphPlay", 12, FocusTimer.Running ? accent : null);+ _reset.Visibility = FocusTimer.Started ? Visibility.Visible : Visibility.Collapsed;+ }++ private void Toggle()+ {+ if (!_popup.IsOpen) Build();+ _popup.Toggle();+ }++ private void Build()+ {+ var root = new StackPanel();+ root.Children.Add(Ui.Header(UiText.Get("FocusTitle"), () => _popup.Close()));+ var hint = Ui.Text(UiText.Get("FocusLength"), 11, brushKey: "TextSecondary");+ hint.Margin = new Thickness(0, 0, 0, 6);+ root.Children.Add(hint);+ // The pills' outer edges line up with the title and the button below.+ var grid = new System.Windows.Controls.Primitives.UniformGrid { Columns = Lengths.Length, Margin = new Thickness(-2, 0, -2, 0) };+ foreach (var minutes in Lengths)+ {+ var selected = (int)FocusTimer.FocusLength.TotalMinutes == minutes;+ var button = Ui.Pill(UiText.Format("FocusMinutes", minutes), (_, _) =>+ {+ UpdateSettings(s => s with { FocusMinutes = minutes });+ FocusTimer.Reset();+ _popup.Close();+ });+ button.Margin = new Thickness(2);+ if (selected) button.SetResourceReference(Control.BackgroundProperty, "WidgetAccent");+ grid.Children.Add(button);+ }+ root.Children.Add(grid);+ var breakButton = Ui.Pill(UiText.Get("FocusBreak"), (_, _) =>+ {+ FocusTimer.StartBreak();+ _popup.Close();+ }, "IconLeaf");+ breakButton.Margin = new Thickness(0, 8, 0, 0);+ breakButton.HorizontalAlignment = HorizontalAlignment.Stretch;+ root.Children.Add(breakButton);+ var stats = Ui.Text(UiText.Format("FocusToday", FocusTimer.CompletedToday), 11, brushKey: "TextSecondary");+ stats.Margin = new Thickness(0, 10, 0, 0);+ root.Children.Add(stats);+ _popup.SetContent(root, 300);+ }+}++internal static class TextFeatures+{+ /// <summary>Tabular digits so the countdown does not wobble.</summary>+ public static void FontFeatures(this TextBlock text) => System.Windows.Documents.Typography.SetNumeralAlignment(text, FontNumeralAlignment.Tabular);+}diff --git a/Widgets/FolderWidget.cs b/Widgets/FolderWidget.csnew file mode 100644index 0000000..9bef065--- /dev/null+++ b/Widgets/FolderWidget.cs@@ -0,0 +1,236 @@+using System.Globalization;+using System.IO;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>+/// A folder (the Desktop by default) as a tile with its item count; the card shows its files and+/// folders as a grid you can browse into, open, or drag out to other apps.+/// </summary>+public sealed class FolderWidget : DockWidget+{+ private const int MaxItems = 150;+ private readonly Button _tile;+ private readonly WidgetPopup _popup;+ private readonly TextBlock _name;+ private readonly TextBlock _count;+ private string _root = DefaultFolder;+ private string _current = DefaultFolder;+ private int _build;++ private static string DefaultFolder => Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);++ public FolderWidget()+ {+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ var icon = Ui.Glyph("IconFolder", 26, Ui.Vertical("#FF6CC4FF", "#FF2E8FE8"));+ icon.Margin = new Thickness(0, 0, 9, 0);+ row.Children.Add(icon);+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ _name = Ui.Text("", 12.5, FontWeights.SemiBold);+ _name.MaxWidth = 110;+ _count = Ui.Text("", 10.5, brushKey: "TextSecondary");+ text.Children.Add(_name);+ text.Children.Add(_count);+ row.Children.Add(text);+ _tile = Ui.Tile(row, (_, _) => Toggle());+ _popup = new WidgetPopup(_tile);+ UiText.Current.PropertyChanged += (_, _) => RefreshTile();+ }++ public override string Id => WidgetIds.Folder;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();+ public override void Start() => RefreshTile();+ public override void Stop() => _popup.Close();++ public override void SetLive(bool live)+ {+ if (live) RefreshTile();+ }++ public override void ApplySettings(WidgetSettings settings)+ {+ var root = string.IsNullOrWhiteSpace(settings.FolderPath) || !Directory.Exists(settings.FolderPath) ? DefaultFolder : settings.FolderPath;+ if (string.Equals(root, _root, StringComparison.OrdinalIgnoreCase)) return;+ _root = _current = root;+ RefreshTile();+ if (_popup.IsOpen) BuildPopup();+ }++ private void RefreshTile()+ {+ _name.Text = DisplayName(_root);+ var count = 0;+ try+ {+ count = Directory.EnumerateFileSystemEntries(_root, "*", new EnumerationOptions { AttributesToSkip = FileAttributes.Hidden | FileAttributes.System }).Take(9999).Count();+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }+ _count.Text = UiText.Format("FolderItems", count);+ _tile.ToolTip = _root;+ }++ private static string DisplayName(string path)+ {+ if (string.Equals(path.TrimEnd('\\'), DefaultFolder.TrimEnd('\\'), StringComparison.OrdinalIgnoreCase)) return UiText.Get("FolderDesktop");+ var name = Path.GetFileName(path.TrimEnd('\\'));+ return string.IsNullOrEmpty(name) ? path : name;+ }++ private void Toggle()+ {+ if (!_popup.IsOpen)+ {+ _current = _root;+ BuildPopup();+ }+ _popup.Toggle();+ }++ private void BuildPopup()+ {+ var build = ++_build;+ var root = new StackPanel();+ var buttons = new List<UIElement>+ {+ Ui.IconButton(Ui.Icon("IconFolderOpen", 13), (_, _) => ChooseFolder(), UiText.Get("FolderChoose")),+ Ui.IconButton(Ui.Icon("IconOpen", 13), (_, _) => { _popup.Close(); Ui.Open(_current); }, UiText.Get("FolderOpenExplorer"))+ };+ var header = Ui.Header("", () => _popup.Close(), buttons.ToArray());+ var title = new StackPanel { Orientation = Orientation.Horizontal };+ if (!string.Equals(_current, _root, StringComparison.OrdinalIgnoreCase))+ {+ var back = Ui.IconButton(Ui.Icon("IconChevronLeft", 13), (_, _) => Navigate(Path.GetDirectoryName(_current.TrimEnd('\\')) ?? _root), UiText.Get("FolderBack"));+ back.Margin = new Thickness(-4, 0, 4, 0);+ title.Children.Add(back);+ title.Children.Add(Ui.Text(DisplayName(_root) + " › ", 13, brushKey: "TextSecondary"));+ }+ title.Children.Add(Ui.Text(DisplayName(_current), 13, FontWeights.SemiBold));+ header.Children.RemoveAt(header.Children.Count - 1);+ header.Children.Add(title);+ root.Children.Add(header);++ var entries = ReadEntries(_current);+ // Five cells fill the card edge to edge, lined up with the title; no scroll bar, just a fade where more follows.+ var grid = new WrapPanel { Width = 480, Margin = new Thickness(-2, 0, -2, 0) };+ var pending = new List<(Border Host, string Path)>();+ foreach (var entry in entries)+ {+ var (cell, iconHost) = Cell(entry);+ grid.Children.Add(cell);+ pending.Add((iconHost, entry.FullName));+ }+ if (entries.Count == 0)+ {+ var empty = Ui.Text(UiText.Get("FolderEmpty"), 12, brushKey: "TextSecondary");+ empty.Margin = new Thickness(4, 10, 0, 16);+ root.Children.Add(empty);+ }+ else+ {+ root.Children.Add(Ui.FadingScroller(grid, 360));+ }+ _popup.SetContent(root, 510);++ // Shell icons are slow-ish; fill them in small batches after the card is up.+ var index = 0;+ void LoadBatch()+ {+ if (build != _build) return;+ for (var end = Math.Min(index + 10, pending.Count); index < end; index++)+ pending[index].Host.Child = Ui.FileIcon(pending[index].Path, 44);+ if (index < pending.Count) _tile.Dispatcher.BeginInvoke(DispatcherPriority.Background, LoadBatch);+ }+ _tile.Dispatcher.BeginInvoke(DispatcherPriority.Background, LoadBatch);+ }++ private static List<FileSystemInfo> ReadEntries(string folder)+ {+ try+ {+ var info = new DirectoryInfo(folder);+ var options = new EnumerationOptions { AttributesToSkip = FileAttributes.Hidden | FileAttributes.System };+ return info.EnumerateFileSystemInfos("*", options)+ .OrderByDescending(e => e is DirectoryInfo)+ .ThenByDescending(e => e.LastWriteTime)+ .Take(MaxItems)+ .ToList();+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException)+ {+ return [];+ }+ }++ private (FrameworkElement Cell, Border IconHost) Cell(FileSystemInfo entry)+ {+ var iconHost = new Border { Width = 46, Height = 46, HorizontalAlignment = HorizontalAlignment.Center };+ iconHost.Child = Ui.Icon(entry is DirectoryInfo ? "IconFolder" : "IconFile", 30, brushKey: "TextSecondary");+ var name = Ui.Text(entry is FileInfo ? Path.GetFileNameWithoutExtension(entry.Name) : entry.Name, 11, FontWeights.SemiBold);+ name.HorizontalAlignment = HorizontalAlignment.Center;+ name.MaxWidth = 82;+ name.Margin = new Thickness(0, 5, 0, 0);+ var age = Ui.Text(Ui.Ago(entry.LastWriteTime), 9.5, brushKey: "TextSecondary");+ age.HorizontalAlignment = HorizontalAlignment.Center;+ var stack = new StackPanel { Margin = new Thickness(0, 8, 0, 6) };+ stack.Children.Add(iconHost);+ stack.Children.Add(name);+ stack.Children.Add(age);+ var cell = new Button { Content = stack, Width = 92, Margin = new Thickness(2), ToolTip = entry.FullName, Padding = new Thickness(2, 0, 2, 0), Height = double.NaN };+ cell.SetResourceReference(FrameworkElement.StyleProperty, "WidgetTileButton");+ cell.Height = double.NaN;+ cell.Click += (_, _) =>+ {+ if (entry is DirectoryInfo) Navigate(entry.FullName);+ else+ {+ _popup.Close();+ Ui.Open(entry.FullName);+ }+ };+ AttachDragOut(cell, entry.FullName);+ return (cell, iconHost);+ }++ /// <summary>Drag a file or folder from the card into another app or folder.</summary>+ internal static void AttachDragOut(FrameworkElement element, string path)+ {+ Point? start = null;+ element.PreviewMouseLeftButtonDown += (_, e) => start = e.GetPosition(element);+ element.PreviewMouseMove += (_, e) =>+ {+ if (start is not { } origin || e.LeftButton != MouseButtonState.Pressed) return;+ var position = e.GetPosition(element);+ if (Math.Abs(position.X - origin.X) < 6 && Math.Abs(position.Y - origin.Y) < 6) return;+ start = null;+ var data = new DataObject(DataFormats.FileDrop, new[] { path });+ DragDrop.DoDragDrop(element, data, DragDropEffects.Copy | DragDropEffects.Move | DragDropEffects.Link);+ };+ element.PreviewMouseLeftButtonUp += (_, _) => start = null;+ }++ private void Navigate(string folder)+ {+ if (!Directory.Exists(folder)) return;+ _current = folder;+ BuildPopup();+ }++ private void ChooseFolder()+ {+ _popup.Close();+ var dialog = new Microsoft.Win32.OpenFolderDialog { Title = UiText.Get("FolderChoose"), InitialDirectory = _root };+ if (dialog.ShowDialog() != true) return;+ var path = dialog.FolderName;+ UpdateSettings(s => s with { FolderPath = string.Equals(path, DefaultFolder, StringComparison.OrdinalIgnoreCase) ? null : path });+ }+}diff --git a/Widgets/MediaWidget.Card.cs b/Widgets/MediaWidget.Card.csnew file mode 100644index 0000000..49fc4f3--- /dev/null+++ b/Widgets/MediaWidget.Card.cs@@ -0,0 +1,463 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Documents;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Media.Animation;+using System.Windows.Media.Imaging;+using QiDock.Services;+using QiDock.Services.Widgets;+using Windows.Media.Control;++namespace QiDock.Widgets;++/// <summary>+/// The card that opens from the music tile: a large cover, the song, a bar to move through it, ten seconds back+/// and forward, previous / play / next and the player's volume. The card takes its colour from the cover.+/// </summary>+public sealed partial class MediaWidget+{+ private static readonly Color IdleTop = Color.FromRgb(0x3A, 0x3B, 0x46), IdleBottom = Color.FromRgb(0x1C, 0x1C, 0x22);++ private WidgetPopup? _popup;+ private Border? _card;+ private GradientStop? _topStop, _bottomStop;+ private Image? _cardArt;+ private TextBlock? _cardTitle, _cardArtist, _cardAlbum, _cardSource, _elapsed, _remaining, _volumeText, _volumeLabel;+ private Slider? _seek, _volume;+ private System.Windows.Shapes.Path? _cardPlayPause, _volumeIcon;+ private Button? _cardPrevious, _cardNext, _back10, _forward10;+ private bool _seeking, _settingVolume, _canSeek;+ private DockPanel? _times;+ private AudioSessions? _sessions;+ private AudioSessions.App? _playerAudio;+ private AudioEndpoint? _endpoint;+ private Color _coverColor = IdleTop;++#if DEBUG+ /// <summary>Debug snapshot run: opens the card without touching the player.</summary>+ internal void RehearseCard()+ {+ ToggleCard();+ OpenAudio();+ FillCard();+ }+#endif++ private bool CardOpen => _popup?.IsOpen == true;+ public override bool IsPopupOpen => CardOpen;+ public override void ClosePopup() => _popup?.Close();++ /// <summary>The tile's free space (not its buttons) opens the card.</summary>+ private void WireCard()+ {+ _tile.Cursor = Cursors.Hand;+ _tile.MouseLeftButtonUp += (_, e) =>+ {+ e.Handled = true;+ ToggleCard();+ };+ }++ private void ToggleCard()+ {+ if (_popup is null)+ {+ _popup = new WidgetPopup(_tile);+ _popup.SetContent(BuildCard(), 340);+ _popup.Opened += (_, _) =>+ {+ OpenAudio();+ FillCard();+ UpdateProgressTimer();+ };+ _popup.Closed += (_, _) =>+ {+ CloseAudio();+ UpdateProgressTimer();+ };+ }+ FillCard();+ _popup.Toggle();+ }++ private Border BuildCard()+ {+ // The card's own colours: white writing on the cover's colour, whatever the theme.+ _topStop = new GradientStop(_coverColor, 0);+ _bottomStop = new GradientStop(Darker(_coverColor, 0.45), 1);+ var fill = new LinearGradientBrush(new GradientStopCollection { _topStop, _bottomStop }, new Point(0, 0), new Point(0.35, 1));++ _cardArt = new Image { Stretch = Stretch.UniformToFill };+ RenderOptions.SetBitmapScalingMode(_cardArt, BitmapScalingMode.HighQuality);+ var artLayers = new Grid();+ artLayers.Children.Add(new ContentControl { Content = Ui.Icon("IconMusic", 30, Ui.WhiteSoft), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center });+ artLayers.Children.Add(_cardArt);+ artLayers.Clip = new RectangleGeometry(new Rect(0, 0, 96, 96), 12, 12);+ var artFrame = new Border { Width = 96, Height = 96, CornerRadius = new CornerRadius(12), Background = Ui.Solid("#26FFFFFF"), Child = artLayers };++ _cardTitle = Ui.Text(size: 15.5, weight: FontWeights.SemiBold);+ _cardTitle.TextWrapping = TextWrapping.Wrap;+ _cardTitle.MaxHeight = 42;+ _cardTitle.TextTrimming = TextTrimming.CharacterEllipsis;+ _cardArtist = Ui.Text(size: 12.5);+ _cardArtist.TextTrimming = TextTrimming.CharacterEllipsis;+ _cardArtist.Margin = new Thickness(0, 2, 0, 0);+ _cardAlbum = Ui.Text(size: 11, brushKey: "TextSecondary");+ _cardAlbum.TextTrimming = TextTrimming.CharacterEllipsis;+ _cardSource = Ui.Text(size: 10.5, brushKey: "TextSecondary");+ _cardSource.Margin = new Thickness(0, 6, 0, 0);+ var words = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(14, 0, 0, 0) };+ words.Children.Add(_cardTitle);+ words.Children.Add(_cardArtist);+ words.Children.Add(_cardAlbum);+ words.Children.Add(_cardSource);+ var top = new DockPanel();+ DockPanel.SetDock(artFrame, Dock.Left);+ top.Children.Add(artFrame);+ top.Children.Add(words);++ // Where in the song: drag or click the bar to jump there.+ _seek = new Slider { Minimum = 0, Maximum = 1, Margin = new Thickness(0, 14, 0, 0) };+ _seek.SetResourceReference(FrameworkElement.StyleProperty, "WidgetSlider");+ _seek.ToolTip = UiText.Get("MediaSeek");+ _seek.PreviewMouseLeftButtonDown += (_, _) => _seeking = true;+ _seek.PreviewMouseLeftButtonUp += async (_, _) =>+ {+ await SeekTo(TimeSpan.FromSeconds(_seek.Value));+ _seeking = false;+ };+ _seek.LostMouseCapture += (_, _) => _seeking = false;+ _elapsed = Ui.Text("0:00", 10.5, brushKey: "TextSecondary");+ _remaining = Ui.Text("", 10.5, brushKey: "TextSecondary");+ var times = _times = new DockPanel { Margin = new Thickness(2, 0, 2, 0) };+ DockPanel.SetDock(_remaining, Dock.Right);+ times.Children.Add(_remaining);+ times.Children.Add(_elapsed);++ // Ten seconds back, previous, play / pause, next, ten seconds forward.+ _back10 = Ui.IconButton(Jump(forward: false), async (_, _) => await SeekBy(-10), UiText.Get("MediaBack10"), 40, 40);+ _cardPrevious = Ui.IconButton(Ui.Glyph("GlyphPrevious", 15), async (_, _) => await Run(s => s.TrySkipPreviousAsync()), UiText.Get("MediaPrevious"), 44, 40);+ _cardPlayPause = Ui.Glyph("GlyphPlay", 18, Ui.Solid("#FF141418"), brushKey: null);+ var playFace = new Border { Width = 52, Height = 52, CornerRadius = new CornerRadius(26), Background = Ui.Solid("#F2FFFFFF"), Child = _cardPlayPause };+ var play = Ui.IconButton(playFace, async (_, _) => await Run(s => s.TryTogglePlayPauseAsync()), UiText.Get("MediaPlayPause"), 58, 58);+ _cardNext = Ui.IconButton(Ui.Glyph("GlyphNext", 15), async (_, _) => await Run(s => s.TrySkipNextAsync()), UiText.Get("MediaNext"), 44, 40);+ _forward10 = Ui.IconButton(Jump(forward: true), async (_, _) => await SeekBy(10), UiText.Get("MediaForward10"), 40, 40);+ var controls = new UniformGrid { Columns = 5, Margin = new Thickness(0, 4, 0, 4) };+ foreach (var button in new[] { _back10, _cardPrevious, play, _cardNext, _forward10 })+ {+ button.HorizontalAlignment = HorizontalAlignment.Center;+ button.VerticalAlignment = VerticalAlignment.Center;+ controls.Children.Add(button);+ }++ // The player's own volume (Spotify, the browser…), or the computer's when the player cannot be found.+ _volumeIcon = Ui.Icon("IconVolume", 14);+ var mute = Ui.IconButton(_volumeIcon, (_, _) => ToggleMute(), UiText.Get("MediaMute"), 28, 26);+ DockPanel.SetDock(mute, Dock.Left);+ _volumeText = Ui.Text("", 11, FontWeights.SemiBold);+ _volumeText.Width = 34;+ _volumeText.TextAlignment = TextAlignment.Right;+ _volumeText.VerticalAlignment = VerticalAlignment.Center;+ DockPanel.SetDock(_volumeText, Dock.Right);+ _volume = new Slider { Minimum = 0, Maximum = 100, Margin = new Thickness(4, 0, 2, 0), VerticalAlignment = VerticalAlignment.Center };+ _volume.SetResourceReference(FrameworkElement.StyleProperty, "WidgetSlider");+ _volume.ValueChanged += (_, e) =>+ {+ if (_settingVolume) return;+ SetVolume((float)(e.NewValue / 100));+ };+ var volumeRow = new DockPanel();+ volumeRow.Children.Add(mute);+ volumeRow.Children.Add(_volumeText);+ volumeRow.Children.Add(_volume);+ _volumeLabel = Ui.Text("", 10.5, brushKey: "TextSecondary");+ _volumeLabel.Margin = new Thickness(4, 6, 0, 2);++ var body = new StackPanel();+ body.Children.Add(top);+ body.Children.Add(_seek);+ body.Children.Add(times);+ body.Children.Add(controls);+ body.Children.Add(_volumeLabel);+ body.Children.Add(volumeRow);++ _card = new Border { CornerRadius = new CornerRadius(14), Padding = new Thickness(16, 16, 16, 12), Background = fill, Child = body };+ _card.Resources["TextPrimary"] = Ui.White;+ _card.Resources["TextSecondary"] = Ui.Solid("#B8FFFFFF");+ _card.Resources["WidgetTrack"] = Ui.Solid("#38FFFFFF");+ _card.Resources["WidgetAccent"] = Ui.Solid("#F2FFFFFF");+ _card.Resources["SurfaceHover"] = Ui.Solid("#24FFFFFF");+ TextElement.SetForeground(_card, Ui.White);+ return _card;+ }++ /// <summary>The round arrow of a ten-second jump, with "10" in its middle.</summary>+ private static Grid Jump(bool forward)+ {+ var arrow = Ui.Icon("IconRotate", 22);+ if (forward)+ {+ arrow.RenderTransformOrigin = new Point(0.5, 0.5);+ arrow.RenderTransform = new ScaleTransform(-1, 1);+ }+ var ten = Ui.Text("10", 7.5, FontWeights.Bold);+ ten.HorizontalAlignment = HorizontalAlignment.Center;+ ten.VerticalAlignment = VerticalAlignment.Center;+ ten.Margin = new Thickness(0, 1, 0, 0);+ var face = new Grid();+ face.Children.Add(arrow);+ face.Children.Add(ten);+ return face;+ }++ /// <summary>Puts the current song in the card (title, cover, buttons); the bar follows on the timer.</summary>+ private void FillCard()+ {+ if (_card is null) return;+ var idle = _session is null || _art.Source is null && _title.Text == UiText.Get("MediaIdleTitle");+ _cardTitle!.Text = _title.Text;+ _cardArtist!.Text = _artist.Text;+ _cardAlbum!.Text = _album;+ _cardAlbum.Visibility = string.IsNullOrWhiteSpace(_album) ? Visibility.Collapsed : Visibility.Visible;+ _cardSource!.Text = SourceName();+ _cardSource.Visibility = _cardSource.Text.Length > 0 ? Visibility.Visible : Visibility.Collapsed;+ _cardArt!.Source = _art.Source;+ _cardPlayPause!.Data = (Geometry)Application.Current.FindResource(_playing ? "GlyphPause" : "GlyphPlay");+ _cardPrevious!.IsEnabled = _previous.IsEnabled;+ _cardNext!.IsEnabled = _next.IsEnabled;+ _canSeek = !idle && CanSeek();+ UpdateCardProgress();+ ShowVolume();+ }++ private string SourceName()+ {+ var id = _session?.SourceAppUserModelId;+ if (string.IsNullOrWhiteSpace(id)) return "";+ var name = id.Contains('!') ? id[(id.LastIndexOf('!') + 1)..] : id;+ if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) name = name[..^4];+ if (name.Equals("msedge", StringComparison.OrdinalIgnoreCase)) name = "Edge";+ return name.Length > 0 ? char.ToUpper(name[0]) + name[1..] : "";+ }++ private bool CanSeek()+ {+ try { return _session?.GetPlaybackInfo()?.Controls?.IsPlaybackPositionEnabled == true; }+ catch (Exception ex) when (ex is COMException or InvalidOperationException) { return false; }+ }++ /// <summary>Moves the bar and the two times; left alone while the bar is being dragged.</summary>+ private void UpdateCardProgress()+ {+ if (_seek is null || !CardOpen && _card?.IsLoaded != true) return;+ double position = 0, length = 0;+ try+ {+ if (_session?.GetTimelineProperties() is { } timeline)+ {+ length = Math.Max(0, (timeline.EndTime - timeline.StartTime).TotalSeconds);+ position = (timeline.Position - timeline.StartTime).TotalSeconds;+ if (_playing) position += (DateTimeOffset.Now - timeline.LastUpdatedTime).TotalSeconds;+ position = Math.Clamp(position, 0, Math.Max(length, 0));+ }+ }+ catch (Exception ex) when (ex is COMException or InvalidOperationException) { }+ // Players that do not tell the song's length (some sites in the browser) get no bar to drag.+ var known = length > 1;+ _seek.Visibility = _times!.Visibility = known ? Visibility.Visible : Visibility.Collapsed;+ _seek.IsEnabled = _back10!.IsEnabled = _forward10!.IsEnabled = known && _canSeek;+ if (_seeking) return;+ _seek.Maximum = Math.Max(1, length);+ _seek.Value = position;+ _elapsed!.Text = Clock(position);+ _remaining!.Text = length > 1 ? "-" + Clock(length - position) : "";+ }++ private static string Clock(double seconds)+ {+ var time = TimeSpan.FromSeconds(Math.Max(0, Math.Round(seconds)));+ return time.TotalHours >= 1 ? time.ToString(@"h\:mm\:ss") : time.ToString(@"m\:ss");+ }++ private async Task SeekBy(double seconds)+ {+ if (_seek is null) return;+ await SeekTo(TimeSpan.FromSeconds(Math.Clamp(_seek.Value + seconds, 0, _seek.Maximum)));+ }++ private async Task SeekTo(TimeSpan position)+ {+ if (_session is null) return;+ try+ {+ var start = _session.GetTimelineProperties()?.StartTime ?? TimeSpan.Zero;+ await _session.TryChangePlaybackPositionAsync((start + position).Ticks);+ }+ catch (Exception ex) when (ex is COMException or InvalidOperationException) { }+ if (_seek is not null && !_seeking) _seek.Value = position.TotalSeconds;+ _elapsed!.Text = Clock(position.TotalSeconds);+ }++ // ---- Volume ----++ private void OpenAudio()+ {+ CloseAudio();+ _endpoint = new AudioEndpoint();+ _sessions = new AudioSessions();+ var id = (_session?.SourceAppUserModelId ?? "").ToLowerInvariant();+ if (id.Length == 0) return;+ try+ {+ _playerAudio = _sessions.Read().FirstOrDefault(app =>+ {+ var exe = System.IO.Path.GetFileNameWithoutExtension(app.ExecutablePath ?? "").ToLowerInvariant();+ return exe.Length > 1 && id.Contains(exe) || id.Contains(app.Name.ToLowerInvariant().Replace(" ", ""));+ });+ }+ catch (Exception ex) when (ex is COMException or InvalidCastException) { _playerAudio = null; }+ }++ private void CloseAudio()+ {+ _playerAudio = null;+ _sessions?.Dispose();+ _sessions = null;+ _endpoint?.Dispose();+ _endpoint = null;+ }++ private void ShowVolume()+ {+ if (_volume is null) return;+ float level;+ bool muted;+ if (_playerAudio is { } app)+ {+ level = app.Volume;+ muted = app.Muted;+ _volumeLabel!.Text = UiText.Format("MediaAppVolume", SourceName() is { Length: > 0 } name ? name : app.Name);+ }+ else if (_endpoint?.Read() is { } state)+ {+ level = state.Volume;+ muted = state.Muted;+ _volumeLabel!.Text = UiText.Get("MediaSystemVolume");+ }+ else return;+ _settingVolume = true;+ _volume.Value = Math.Round(level * 100);+ _settingVolume = false;+ _volumeText!.Text = "%" + (int)_volume.Value;+ _volumeIcon!.Data = (Geometry)Application.Current.FindResource(muted || level <= 0 ? "IconVolumeMute" : "IconVolume");+ }++ private void SetVolume(float level)+ {+ try+ {+ if (_playerAudio is { } app)+ {+ app.Volume = level;+ if (level > 0 && app.Muted) app.Muted = false;+ }+ else _endpoint?.SetVolume(level);+ }+ catch (Exception ex) when (ex is COMException or InvalidComObjectException) { }+ ShowVolume();+ }++ private void ToggleMute()+ {+ try+ {+ if (_playerAudio is { } app) app.Muted = !app.Muted;+ else if (_endpoint?.Read() is { } state) _endpoint.SetMute(!state.Muted);+ }+ catch (Exception ex) when (ex is COMException or InvalidComObjectException) { }+ ShowVolume();+ }++ // ---- The cover's colour ----++ /// <summary>The card slides to the cover's colour (a soft grey without a cover).</summary>+ private void TintCard(BitmapSource? cover)+ {+ var color = cover is null ? IdleTop : CoverColor(cover);+ if (color == _coverColor) return;+ _coverColor = color;+ if (_topStop is null || _bottomStop is null) return;+ var bottom = cover is null ? IdleBottom : Darker(color, 0.45);+ var duration = TimeSpan.FromMilliseconds(CardOpen ? 450 : 0);+ _topStop.BeginAnimation(GradientStop.ColorProperty, new ColorAnimation(color, duration));+ _bottomStop.BeginAnimation(GradientStop.ColorProperty, new ColorAnimation(bottom, duration));+ }++ /// <summary>+ /// The cover's main colour: colourful, mid-bright pixels count most (not the black or white background), then+ /// the colour is brought to a depth where white writing reads well on it.+ /// </summary>+ private static Color CoverColor(BitmapSource cover)+ {+ try+ {+ var small = new TransformedBitmap(cover, new ScaleTransform(24.0 / cover.PixelWidth, 24.0 / cover.PixelHeight));+ var pixels = new FormatConvertedBitmap(small, PixelFormats.Bgra32, null, 0);+ var width = pixels.PixelWidth;+ var height = pixels.PixelHeight;+ var data = new byte[width * height * 4];+ pixels.CopyPixels(data, width * 4, 0);+ double r = 0, g = 0, b = 0, weight = 0, ar = 0, ag = 0, ab = 0;+ for (var i = 0; i < data.Length; i += 4)+ {+ double pb = data[i] / 255.0, pg = data[i + 1] / 255.0, pr = data[i + 2] / 255.0;+ var max = Math.Max(pr, Math.Max(pg, pb));+ var min = Math.Min(pr, Math.Min(pg, pb));+ var saturation = max <= 0 ? 0 : (max - min) / max;+ var w = saturation * saturation * (max < 0.12 ? 0.1 : 1) + 0.002;+ r += pr * w; g += pg * w; b += pb * w; weight += w;+ ar += pr; ag += pg; ab += pb;+ }+ var count = data.Length / 4.0;+ (r, g, b) = weight > 0.02 * count ? (r / weight, g / weight, b / weight) : (ar / count, ag / count, ab / count);+ return Settle(r, g, b);+ }+ catch (Exception ex) when (ex is NotSupportedException or InvalidOperationException or ArgumentException)+ {+ return IdleTop;+ }+ }++ /// <summary>Keeps the hue, holds the lightness near 32% and the saturation at most 70%.</summary>+ private static Color Settle(double r, double g, double b)+ {+ var max = Math.Max(r, Math.Max(g, b));+ var min = Math.Min(r, Math.Min(g, b));+ var light = (max + min) / 2;+ double hue = 0, saturation = 0;+ if (max - min > 1e-6)+ {+ var d = max - min;+ saturation = light > 0.5 ? d / (2 - max - min) : d / (max + min);+ hue = max == r ? (g - b) / d + (g < b ? 6 : 0) : max == g ? (b - r) / d + 2 : (r - g) / d + 4;+ hue /= 6;+ }+ saturation = Math.Min(saturation, 0.7);+ light = Math.Clamp(light, 0.26, 0.36);+ double Channel(double t)+ {+ var q = light < 0.5 ? light * (1 + saturation) : light + saturation - light * saturation;+ var p = 2 * light - q;+ if (t < 0) t += 1;+ if (t > 1) t -= 1;+ return t < 1 / 6.0 ? p + (q - p) * 6 * t : t < 0.5 ? q : t < 2 / 3.0 ? p + (q - p) * (2 / 3.0 - t) * 6 : p;+ }+ return Color.FromRgb((byte)(Channel(hue + 1 / 3.0) * 255), (byte)(Channel(hue) * 255), (byte)(Channel(hue - 1 / 3.0) * 255));+ }++ private static Color Darker(Color color, double amount) =>+ Color.FromRgb((byte)(color.R * (1 - amount)), (byte)(color.G * (1 - amount)), (byte)(color.B * (1 - amount)));+}diff --git a/Widgets/MediaWidget.cs b/Widgets/MediaWidget.csnew file mode 100644index 0000000..50a4b37--- /dev/null+++ b/Widgets/MediaWidget.cs@@ -0,0 +1,350 @@+using System.IO;+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media;+using System.Windows.Media.Imaging;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;+using Windows.Media.Control;++namespace QiDock.Widgets;++/// <summary>Now playing tile with previous / play-pause / next for the system media session.</summary>+public sealed partial class MediaWidget : DockWidget+{+ private const double ProgressWidth = 96;++ private readonly Border _tile;+ private readonly TextBlock _title;+ private readonly TextBlock _artist;+ private readonly ContentControl _playPause;+ private readonly Button _previous;+ private readonly Button _next;+ private readonly Image _art;+ private readonly Border _artFrame;+ private readonly Border _progressFill;+ private readonly DispatcherTimer _progressTimer;+ private readonly Dispatcher _dispatcher;+ private GlobalSystemMediaTransportControlsSessionManager? _manager;+ private GlobalSystemMediaTransportControlsSession? _session;+ private int _refreshVersion;+ private bool _started;+ private bool _live = true;+ private bool _playing;+ private string? _thumbnailKey;+ private string _album = "";++ public MediaWidget()+ {+ _dispatcher = Dispatcher.CurrentDispatcher;++ // Cover on the left, title / artist / progress in the middle, previous - play - next on the right.+ _art = new Image { Stretch = Stretch.UniformToFill };+ _artFrame = new Border { Width = 34, Height = 34, CornerRadius = new CornerRadius(7), ClipToBounds = true, Background = Ui.Solid("#33FFFFFF"), VerticalAlignment = VerticalAlignment.Center };+ var artLayers = new Grid();+ artLayers.Children.Add(new ContentControl { Content = Ui.Icon("IconMusic", 15, Ui.WhiteSoft), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center });+ artLayers.Children.Add(_art);+ _artFrame.Child = artLayers;+ _artFrame.SizeChanged += (_, e) => artLayers.Clip = new RectangleGeometry(new Rect(e.NewSize), 7, 7);++ _title = Ui.Text(size: 11.5, weight: FontWeights.SemiBold);+ _title.TextTrimming = TextTrimming.CharacterEllipsis;+ _artist = Ui.Text(size: 10, brushKey: "TextSecondary");+ _artist.TextTrimming = TextTrimming.CharacterEllipsis;+ _artist.Margin = new Thickness(0, -1, 0, 3);+ var track = new Border { Width = ProgressWidth, Height = 3, CornerRadius = new CornerRadius(1.5), HorizontalAlignment = HorizontalAlignment.Left };+ track.SetResourceReference(Border.BackgroundProperty, "WidgetTrack");+ _progressFill = new Border { Width = 0, CornerRadius = new CornerRadius(1.5), HorizontalAlignment = HorizontalAlignment.Left };+ _progressFill.SetResourceReference(Border.BackgroundProperty, "TextPrimary");+ track.Child = _progressFill;+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(9, 0, 8, 0), Width = ProgressWidth + 14 };+ text.Children.Add(_title);+ text.Children.Add(_artist);+ text.Children.Add(track);++ _playPause = new ContentControl { Content = Ui.Glyph("GlyphPlay", 11), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ _previous = Ui.IconButton(Ui.Glyph("GlyphPrevious", 10), async (_, _) => await Run(s => s.TrySkipPreviousAsync()), UiText.Get("MediaPrevious"), 24, 24);+ var playFace = new Border { Width = 28, Height = 28, CornerRadius = new CornerRadius(14), Child = _playPause };+ playFace.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ var play = Ui.IconButton(playFace, async (_, _) => await Run(s => s.TryTogglePlayPauseAsync()), UiText.Get("MediaPlayPause"), 30, 30);+ _next = Ui.IconButton(Ui.Glyph("GlyphNext", 10), async (_, _) => await Run(s => s.TrySkipNextAsync()), UiText.Get("MediaNext"), 24, 24);+ var controls = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };+ controls.Children.Add(_previous);+ controls.Children.Add(play);+ controls.Children.Add(_next);++ var row = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };+ row.Children.Add(_artFrame);+ row.Children.Add(text);+ row.Children.Add(controls);++ _tile = new Border+ {+ Child = row,+ CornerRadius = (CornerRadius)Application.Current.FindResource("WidgetRadius"),+ BorderThickness = new Thickness(1),+ Padding = new Thickness(5, 0, 5, 0),+ Margin = new Thickness(3, 0, 3, 0),+ VerticalAlignment = VerticalAlignment.Center,+ Visibility = Visibility.Collapsed+ };+ _tile.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ _tile.SetResourceReference(Border.BorderBrushProperty, "WidgetTileStroke");+ _tile.SetResourceReference(FrameworkElement.HeightProperty, "WidgetTileHeight");++ _progressTimer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(1) };+ _progressTimer.Tick += (_, _) =>+ {+ UpdateProgress();+ if (CardOpen) ShowVolume();+ };+ WireCard();+ }++ public override string Id => WidgetIds.Media;+ public override FrameworkElement View => _tile;++ public override async void Start()+ {+ if (_started) return;+ _started = true;+ try+ {+ _manager = await GlobalSystemMediaTransportControlsSessionManager.RequestAsync();+ _manager.CurrentSessionChanged += (_, _) => _dispatcher.InvokeAsync(AttachCurrentSession);+ _manager.SessionsChanged += (_, _) => _dispatcher.InvokeAsync(AttachCurrentSession);+ AttachCurrentSession();+ }+ catch (Exception ex) when (ex is COMException or UnauthorizedAccessException or InvalidOperationException)+ {+ _manager = null;+ ShowIdle();+ }+ }++ public override void Stop()+ {+ _started = false;+ _popup?.Close();+ _progressTimer.Stop();+ Detach();+ _manager = null;+ }++ public override void SetLive(bool live)+ {+ _live = live;+ UpdateProgressTimer();+ }++ private void UpdateProgressTimer()+ {+ if (_started && (_live || CardOpen) && (_playing || CardOpen) && _tile.Visibility == Visibility.Visible)+ {+ UpdateProgress();+ _progressTimer.Start();+ }+ else+ {+ _progressTimer.Stop();+ UpdateProgress();+ }+ }++ /// <summary>The bar follows the session's timeline, moved on by the time since its last report while playing.</summary>+ private void UpdateProgress()+ {+ double fraction = 0;+ try+ {+ if (_session?.GetTimelineProperties() is { } timeline)+ {+ var length = (timeline.EndTime - timeline.StartTime).TotalSeconds;+ var position = timeline.Position.TotalSeconds;+ if (_playing) position += (DateTimeOffset.Now - timeline.LastUpdatedTime).TotalSeconds;+ if (length > 1) fraction = Math.Clamp(position / length, 0, 1);+ }+ }+ catch (Exception ex) when (ex is COMException or InvalidOperationException)+ {+ }+ _progressFill.Width = ProgressWidth * fraction;+ if (CardOpen) UpdateCardProgress();+ }++ private void AttachCurrentSession()+ {+ if (_manager is null) return;+ GlobalSystemMediaTransportControlsSession? session;+ try+ {+ session = _manager.GetCurrentSession() ?? _manager.GetSessions().FirstOrDefault();+ }+ catch (COMException)+ {+ session = null;+ }++ if (!ReferenceEquals(session, _session))+ {+ Detach();+ _session = session;+ if (session is not null)+ {+ session.MediaPropertiesChanged += Session_Changed;+ session.PlaybackInfoChanged += Session_Changed;+ }+ }+ _ = RefreshAsync();+ }++ private void Detach()+ {+ if (_session is null) return;+ _session.MediaPropertiesChanged -= Session_Changed;+ _session.PlaybackInfoChanged -= Session_Changed;+ _session = null;+ }++ private void Session_Changed(GlobalSystemMediaTransportControlsSession sender, object args) =>+ _dispatcher.InvokeAsync(() => _ = RefreshAsync());++ private async Task RefreshAsync()+ {+ var version = ++_refreshVersion;+ var session = _session;+ if (session is null)+ {+ ShowIdle();+ return;+ }++ try+ {+ var playback = session.GetPlaybackInfo();+ var properties = await session.TryGetMediaPropertiesAsync();+ if (version != _refreshVersion) return;++ var title = properties?.Title ?? "";+ var artist = properties?.Artist ?? "";+ if (string.IsNullOrWhiteSpace(title) && string.IsNullOrWhiteSpace(artist))+ {+ ShowIdle();+ return;+ }++ var text = string.IsNullOrWhiteSpace(artist) ? title : $"{title} · {artist}";+ _title.Text = string.IsNullOrWhiteSpace(title) ? artist : title;+ _artist.Text = string.IsNullOrWhiteSpace(title) ? "" : artist;+ _tile.ToolTip = text;+ var playing = _playing = playback?.PlaybackStatus == GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing;+ _playPause.Content = Ui.Glyph(playing ? "GlyphPause" : "GlyphPlay", 11);+ _previous.IsEnabled = playback?.Controls?.IsPreviousEnabled != false;+ _next.IsEnabled = playback?.Controls?.IsNextEnabled != false;++ _album = properties?.AlbumTitle ?? "";+ var key = $"{title}|{artist}|{properties?.AlbumTitle}";+ if (key != _thumbnailKey)+ {+ _thumbnailKey = key;+ await LoadArtworkAsync(properties?.Thumbnail, version);+ }+ SetVisible(true);+ UpdateProgressTimer();+ if (CardOpen) FillCard();+ }+ catch (Exception ex) when (ex is COMException or InvalidOperationException or UnauthorizedAccessException)+ {+ if (version == _refreshVersion) ShowIdle();+ }+ }++ private async Task LoadArtworkAsync(Windows.Storage.Streams.IRandomAccessStreamReference? reference, int version)+ {+ if (reference is null)+ {+ _art.Source = null;+ TintCard(null);+ return;+ }++ try+ {+ using var winStream = await reference.OpenReadAsync();+ using var source = winStream.AsStreamForRead();+ var memory = new MemoryStream();+ await source.CopyToAsync(memory);+ memory.Position = 0;+ if (version != _refreshVersion) return;++ var image = new BitmapImage();+ image.BeginInit();+ image.CacheOption = BitmapCacheOption.OnLoad;+ image.DecodePixelWidth = 192; // sharp in the card's large cover too+ image.StreamSource = memory;+ image.EndInit();+ image.Freeze();+ _art.Source = image;+ TintCard(image);+ }+ catch (Exception ex) when (ex is COMException or IOException or NotSupportedException or InvalidOperationException or FileFormatException)+ {+ _art.Source = null;+ TintCard(null);+ }+ }++ /// <summary>+ /// Nothing playing: the tile stays (it used to vanish, and then it could be found neither in the dock nor in+ /// the add list) and says so; its play button sends the keyboard's play key, which resumes the last player.+ /// </summary>+ private void ShowIdle()+ {+ _playing = false;+ _thumbnailKey = null;+ _art.Source = null;+ _album = "";+ TintCard(null);+ _title.Text = UiText.Get("MediaIdleTitle");+ _artist.Text = UiText.Get("MediaIdle");+ _tile.ToolTip = UiText.Get("MediaIdleHint");+ _playPause.Content = Ui.Glyph("GlyphPlay", 11);+ _previous.IsEnabled = _next.IsEnabled = false;+ SetVisible(true);+ UpdateProgressTimer();+ if (CardOpen) FillCard();+ }++ [DllImport("user32.dll")]+ private static extern void keybd_event(byte key, byte scan, uint flags, nuint extra);++ private async Task Run(Func<GlobalSystemMediaTransportControlsSession, Windows.Foundation.IAsyncOperation<bool>> command)+ {+ if (_session is null)+ {+ // The media play/pause key: Windows hands it to the player that last had sound (Spotify, the browser…).+ keybd_event(0xB3, 0, 0, 0);+ keybd_event(0xB3, 0, 2 /* key up */, 0);+ return;+ }+ try+ {+ await command(_session);+ }+ catch (Exception ex) when (ex is COMException or InvalidOperationException)+ {+ System.Diagnostics.Trace.TraceWarning("Media command failed: {0}", ex.Message);+ }+ }++ private void SetVisible(bool visible)+ {+ var target = visible ? Visibility.Visible : Visibility.Collapsed;+ if (_tile.Visibility == target) return;+ _tile.Visibility = target;+ UpdateProgressTimer();+ RaiseLayoutChanged();+ }+}diff --git a/Widgets/NoteWidget.cs b/Widgets/NoteWidget.csnew file mode 100644index 0000000..3b55916--- /dev/null+++ b/Widgets/NoteWidget.cs@@ -0,0 +1,106 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>Quick note: the tile shows the note's first line; the card is a small text box that keeps what is typed.</summary>+public sealed class NoteWidget : DockWidget+{+ private readonly Button _tile;+ private readonly WidgetPopup _popup;+ private readonly TextBlock _first;+ private readonly TextBlock _caption;+ private readonly TextBox _box = new()+ {+ AcceptsReturn = true,+ TextWrapping = TextWrapping.Wrap,+ Height = 170,+ VerticalContentAlignment = VerticalAlignment.Top,+ VerticalScrollBarVisibility = ScrollBarVisibility.Auto+ };+ private readonly StackPanel _card = new();+ // Saving waits until typing pauses, so every key press does not rewrite the settings file.+ private readonly DispatcherTimer _save = new() { Interval = TimeSpan.FromMilliseconds(700) };++ public NoteWidget()+ {+ var icon = Ui.Icon("IconEdit", 14);+ icon.Margin = new Thickness(0, 0, 8, 0);+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ _first = Ui.Text("", 12, FontWeights.SemiBold);+ _first.MaxWidth = 140;+ _caption = Ui.Text("", 10, brushKey: "TextSecondary");+ text.Children.Add(_first);+ text.Children.Add(_caption);+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ row.Children.Add(icon);+ row.Children.Add(text);+ _tile = Ui.Tile(row, (_, _) => Toggle());+ _popup = new WidgetPopup(_tile);+ _popup.Closed += (_, _) => Flush();++ _box.SetResourceReference(FrameworkElement.StyleProperty, "WidgetTextBox");+ _box.TextChanged += (_, _) =>+ {+ _save.Stop();+ _save.Start();+ Render(_box.Text);+ };+ _box.KeyDown += (_, e) => { if (e.Key == Key.Escape) _popup.Close(); };+ _save.Tick += (_, _) => Flush();+ _card.Children.Add(Ui.Header(UiText.Get("NoteTitle"), () => _popup.Close()));+ _card.Children.Add(_box);+ var hint = Ui.Text(UiText.Get("NoteSavedHint"), 10.5, brushKey: "TextSecondary");+ hint.Margin = new Thickness(0, 6, 0, 0);+ _card.Children.Add(hint);+ UiText.Current.PropertyChanged += (_, _) => Render(Current.Note ?? "");+ Render("");+ }++ public override string Id => WidgetIds.Note;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();+ public override void Stop() => _popup.Close();++ public override void ApplySettings(WidgetSettings settings)+ {+ var note = settings.Note ?? "";+ // Never overwrite what is being typed with the saved copy that is a moment behind.+ if (!_box.IsKeyboardFocusWithin && !_save.IsEnabled && _box.Text != note) _box.Text = note;+ Render(_box.IsKeyboardFocusWithin ? _box.Text : note);+ }++ private void Flush()+ {+ _save.Stop();+ var text = _box.Text;+ if (text != (Current.Note ?? "")) UpdateSettings(s => s with { Note = text });+ }++ private void Render(string note)+ {+ var lines = note.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);+ _first.Text = lines.Length > 0 ? lines[0] : UiText.Get("NoteTitle");+ _caption.Text = lines.Length > 1 ? UiText.Format("NoteMoreLines", lines.Length - 1) : UiText.Get(lines.Length > 0 ? "NoteTapToEdit" : "NoteEmpty");+ _tile.ToolTip = lines.Length > 0 ? note.Trim() : null;+ _box.Tag = UiText.Get("NotePlaceholder");+ }++ private void Toggle()+ {+ if (_popup.IsOpen)+ {+ _popup.Close();+ return;+ }+ _popup.SetContent(_card, 320);+ _popup.Toggle();+ _popup.FocusInput(_box);+ _box.CaretIndex = _box.Text.Length;+ }+}diff --git a/Widgets/NotificationsWidget.cs b/Widgets/NotificationsWidget.csnew file mode 100644index 0000000..8e928a0--- /dev/null+++ b/Widgets/NotificationsWidget.cs@@ -0,0 +1,105 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media;+using QiDock.Models;+using QiDock.Services;+using QiDock.Services.Notifications;++namespace QiDock.Widgets;++/// <summary>+/// A square bell button with a red badge for unread notifications, at the far end of the row next to the battery;+/// the list grows out of it.+/// </summary>+public sealed class NotificationsWidget : DockWidget+{+ private readonly Button _tile;+ private readonly Border _badge;+ private readonly TextBlock _badgeText;++ public NotificationsWidget()+ {+ (var bell, _badge, _badgeText) = NotificationList.Bell(18, Ui.Icon("IconBell", 18));+ bell.HorizontalAlignment = HorizontalAlignment.Center;+ _tile = Ui.Tile(bell, (_, _) => Toggle(), horizontalPadding: 0);+ _tile.SetResourceReference(FrameworkElement.WidthProperty, "WidgetTileHeight");+ _tile.ToolTip = UiText.Get("NotificationsTitle");+ }++ public override string Id => WidgetIds.Notifications;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => NotificationCenter.IsCreated && NotificationCenter.Shared.IsOpen;+ public override void ClosePopup()+ {+ if (NotificationCenter.IsCreated) NotificationCenter.Shared.Close(animated: true);+ }++ public override void Start()+ {+ NotificationFeed.Shared.Changed += Render;+ Render();+ }++ public override void Stop()+ {+ NotificationFeed.Shared.Changed -= Render;+ }++ public override void ApplySettings(WidgetSettings settings) { }++ private void Render()+ {+ var feed = NotificationFeed.Shared;+ var unread = feed.UnreadCount;+ NotificationList.SetBadge(_badge, _badgeText, unread);+ }++ /// <summary>"3 yeni", "5 bildirim" or "Yeni bildirim yok": the same wording on every notifications tile.</summary>+ public static string StatusText()+ {+ var feed = NotificationFeed.Shared;+ var unread = feed.UnreadCount;+ return unread > 0 ? UiText.Format("NotificationsUnread", unread)+ : feed.Items.Count > 0 ? UiText.Format("NotificationsCount", feed.Items.Count)+ : UiText.Get("NotificationsNone");+ }++ /// <summary>The list grows out of the bell (out of the dock or the top bar, wherever the tile stands).</summary>+ private void Toggle() => NotificationCenter.Shared.ToggleFrom(_tile);+}++/// <summary>The bell with its red count badge, shared by the bar tile and the dock button.</summary>+public static class NotificationList+{+ /// <summary>An icon with a red count badge on its top-right corner.</summary>+ public static (Grid Host, Border Badge, TextBlock Count) Bell(double size, UIElement icon)+ {+ var count = new TextBlock { FontSize = 9.5, FontWeight = FontWeights.Bold, Foreground = Brushes.White, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, -1, 0, 0) };+ var badge = new Border+ {+ MinWidth = 15,+ Height = 15,+ CornerRadius = new CornerRadius(7.5),+ Padding = new Thickness(4, 0, 4, 0),+ Background = Ui.Solid("#FFFF3B30"),+ BorderThickness = new Thickness(1.2),+ BorderBrush = Ui.Solid("#E6FFFFFF"),+ HorizontalAlignment = HorizontalAlignment.Right,+ VerticalAlignment = VerticalAlignment.Top,+ Margin = new Thickness(0, -6, -8, 0),+ Child = count,+ Visibility = Visibility.Collapsed,+ IsHitTestVisible = false+ };+ var host = new Grid { Width = size, Height = size, VerticalAlignment = VerticalAlignment.Center };+ host.Children.Add(icon);+ host.Children.Add(badge);+ return (host, badge, count);+ }++ public static void SetBadge(Border badge, TextBlock text, int unread)+ {+ badge.Visibility = unread > 0 ? Visibility.Visible : Visibility.Collapsed;+ text.Text = unread > 9 ? "9+" : unread.ToString(System.Globalization.CultureInfo.InvariantCulture);+ }+}diff --git a/Widgets/ProfileWidget.cs b/Widgets/ProfileWidget.csnew file mode 100644index 0000000..f05cb62--- /dev/null+++ b/Widgets/ProfileWidget.cs@@ -0,0 +1,51 @@+using System.Windows;+using System.Windows.Controls;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>+/// The active widget profile ("İş", "Kod"…) as a tile; a click opens the profile menu (switch, new, rename, remove).+/// The menu itself is built by the dock window, so it keeps the dock up while it is open.+/// </summary>+public sealed class ProfileWidget : DockWidget+{+ private readonly Button _tile;+ private readonly TextBlock _name;+ private readonly TextBlock _caption;++ /// <summary>Raised on a click; the argument is the tile to anchor the menu to.</summary>+ public event EventHandler<FrameworkElement>? MenuRequested;++ public ProfileWidget()+ {+ var icon = Ui.Icon("IconLayout", 15);+ icon.Margin = new Thickness(0, 0, 8, 0);+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ _caption = Ui.Text("", 10, brushKey: "TextSecondary");+ _name = Ui.Text("", 12.5, FontWeights.SemiBold);+ _name.MaxWidth = 110;+ text.Children.Add(_caption);+ text.Children.Add(_name);+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ row.Children.Add(icon);+ row.Children.Add(text);+ _tile = Ui.Tile(row, (sender, _) => MenuRequested?.Invoke(this, (FrameworkElement)sender));+ UiText.Current.PropertyChanged += (_, _) => Render();+ Render();+ }++ public override string Id => WidgetIds.Profile;+ public override FrameworkElement View => _tile;++ public override void ApplySettings(WidgetSettings settings) => Render();++ private void Render()+ {+ var profiles = Current.EffectiveProfiles;+ _caption.Text = UiText.Get("ProfileCaption");+ _name.Text = profiles[Current.EffectiveActiveProfile].Name;+ _tile.ToolTip = UiText.Get("ProfileTileHint");+ }+}diff --git a/Widgets/ProgressWidget.cs b/Widgets/ProgressWidget.csnew file mode 100644index 0000000..2e88e48--- /dev/null+++ b/Widgets/ProgressWidget.cs@@ -0,0 +1,99 @@+using System.Globalization;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Media;+using System.Windows.Shapes;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>+/// How much of the month, year or day has gone, as dots (days, months or hours) and a percent. A click switches+/// between month, year and day. It redraws once a minute while on screen.+/// </summary>+public sealed class ProgressWidget : DockWidget+{+ private static readonly string[] Kinds = ["month", "year", "day"];+ private readonly Button _tile;+ private readonly UniformGrid _dots = new() { Rows = 3, VerticalAlignment = VerticalAlignment.Center };+ private readonly TextBlock _name;+ private readonly TextBlock _percent;+ private readonly DispatcherTimer _minute = new(DispatcherPriority.Background) { Interval = TimeSpan.FromMinutes(1) };+ private string _kind = "month";+ private string _drawn = "";++ public ProgressWidget()+ {+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 0, 0, 0) };+ _name = Ui.Text("", 10, brushKey: "TextSecondary");+ _percent = Ui.Text("", 13.5, FontWeights.Bold);+ _percent.FontFeatures();+ text.Children.Add(_name);+ text.Children.Add(_percent);+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ row.Children.Add(_dots);+ row.Children.Add(text);+ _tile = Ui.Tile(row, (_, _) => UpdateSettings(s => s with { ProgressKind = Kinds[(Array.IndexOf(Kinds, s.ProgressKind) + 1) % Kinds.Length] }), 9);+ _minute.Tick += (_, _) => Render();+ UiText.Current.PropertyChanged += (_, _) => { _drawn = ""; Render(); };+ Render();+ }++ public override string Id => WidgetIds.Progress;+ public override FrameworkElement View => _tile;++ public override void Start() => _minute.Start();+ public override void Stop() => _minute.Stop();++ public override void SetLive(bool live)+ {+ if (live)+ {+ Render();+ _minute.Start();+ }+ else _minute.Stop();+ }++ public override void ApplySettings(WidgetSettings settings)+ {+ _kind = Array.IndexOf(Kinds, settings.ProgressKind) >= 0 ? settings.ProgressKind : "month";+ Render();+ }++ private void Render()+ {+ var now = DateTime.Now;+ var culture = CultureInfo.CurrentUICulture;+ (int Total, int Done, double Fraction, string Name, int Rows) state = _kind switch+ {+ "year" => (12, now.Month - 1, (now.DayOfYear - 1 + now.TimeOfDay.TotalDays) / (DateTime.IsLeapYear(now.Year) ? 366 : 365), now.Year.ToString(culture), 2),+ "day" => (24, now.Hour, now.TimeOfDay.TotalDays, UiText.Get("ProgressToday"), 2),+ _ => (DateTime.DaysInMonth(now.Year, now.Month), now.Day - 1, (now.Day - 1 + now.TimeOfDay.TotalDays) / DateTime.DaysInMonth(now.Year, now.Month),+ culture.DateTimeFormat.GetMonthName(now.Month), 3)+ };+ _name.Text = state.Name;+ _percent.Text = UiText.Format("OpacityPercent", (int)Math.Floor(state.Fraction * 100));+ _tile.ToolTip = UiText.Format("ProgressHint", state.Name, Math.Floor(state.Fraction * 100));++ var signature = $"{_kind}|{state.Total}|{state.Done}";+ if (signature == _drawn) return;+ _drawn = signature;+ _dots.Children.Clear();+ _dots.Rows = state.Rows;+ _dots.Columns = (int)Math.Ceiling(state.Total / (double)state.Rows);+ var size = state.Rows == 3 ? 6.0 : 7.0;+ for (var i = 0; i < state.Total; i++)+ {+ var dot = new Ellipse { Width = size, Height = size, Margin = new Thickness(1.2) };+ // Gone: solid; the current one: the accent; still to come: faint.+ if (i < state.Done) dot.SetResourceReference(Shape.FillProperty, "TextPrimary");+ else if (i == state.Done) dot.Fill = Ui.Solid("#FF0A84FF");+ else dot.SetResourceReference(Shape.FillProperty, "WidgetTrack");+ _dots.Children.Add(dot);+ }+ }+}diff --git a/Widgets/QuickControlsWidget.cs b/Widgets/QuickControlsWidget.csnew file mode 100644index 0000000..4c99d62--- /dev/null+++ b/Widgets/QuickControlsWidget.cs@@ -0,0 +1,356 @@+using System.Globalization;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;+using QiDock.Services.Widgets;++namespace QiDock.Widgets;++/// <summary>Wi-Fi, Bluetooth, volume slider and battery.</summary>+public sealed class QuickControlsWidget : DockWidget+{+ private static readonly Brush OnFill = Ui.Solid("#FF0A84FF");+ private static readonly Brush OnIcon = Ui.Solid("#FF5EB1FF");+ private static readonly Brush PillFill = Ui.Solid("#33000000");+ private static readonly Brush PillOnStroke = Ui.Solid("#8C2F8BFF");+ private static readonly Brush PillOffStroke = Ui.Solid("#33FFFFFF");+ private static readonly Brush BatteryFill = Ui.Vertical("#FF7CD3FF", "#FF2D8CF0");+ private static readonly Brush BatteryLowFill = Ui.Vertical("#FFFF8A80", "#FFE5372C");++ private readonly Border _tile;+ private readonly Border _wifiPill;+ private readonly Border _bluetoothPill;+ private readonly Button _wifiButton;+ private readonly Button _bluetoothButton;+ private readonly Border _wifiIconBack;+ private readonly Border _bluetoothIconBack;+ private readonly Button _muteButton;+ private readonly TextBlock _deviceName;+ private readonly TextBlock _volumeText;+ private readonly Grid _slider;+ private readonly Border _sliderFill;+ private readonly Border _battery;+ private readonly TextBlock _batteryText;+ private readonly ContentControl _batteryBolt;+ private readonly System.Windows.Shapes.Path _batteryLevel;+ private double _batteryPercent = 100;+ private readonly DispatcherTimer _timer;+ private readonly AudioEndpoint _audio = new();+ private readonly RadioControls _radios = new();+ private AudioEndpoint.State? _audioState;+ private bool _dragging;+ private bool _initialized;+ private int _tick;++ public QuickControlsWidget()+ {+ // The Wi-Fi and Bluetooth capsules open the Control Center, where the radios are switched.+ (_wifiPill, _wifiButton, _wifiIconBack) = CreateRadioPill("IconWifi");+ (_bluetoothPill, _bluetoothButton, _bluetoothIconBack) = CreateRadioPill("IconBluetooth");++ // Volume: icon + device name + percent on top, slider below.+ _muteButton = Ui.IconButton(Ui.Icon("IconVolume", 13), (_, _) => ToggleMute(), UiText.Get("QcMute"), 22, 20);+ _deviceName = Ui.Text(UiText.Get("QcSound"), 10.5, FontWeights.SemiBold);+ _deviceName.Margin = new Thickness(4, 0, 0, 0);+ _volumeText = Ui.Text("", 10.5, FontWeights.SemiBold, "TextSecondary");+ _volumeText.Margin = new Thickness(6, 0, 2, 0);+ var top = new DockPanel();+ DockPanel.SetDock(_muteButton, Dock.Left);+ DockPanel.SetDock(_volumeText, Dock.Right);+ top.Children.Add(_muteButton);+ top.Children.Add(_volumeText);+ top.Children.Add(_deviceName);+ var deviceButton = (UIElement)top;++ _slider = new Grid { Height = 14, Margin = new Thickness(2, 1, 2, 0), Cursor = Cursors.Hand, Background = Brushes.Transparent };+ var track = new Border { Height = 8, CornerRadius = new CornerRadius(4), VerticalAlignment = VerticalAlignment.Center };+ track.SetResourceReference(Border.BackgroundProperty, "WidgetTrack");+ _sliderFill = new Border { Height = 8, CornerRadius = new CornerRadius(4), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Background = OnFill };+ _slider.Children.Add(track);+ _slider.Children.Add(_sliderFill);+ _slider.MouseLeftButtonDown += Slider_MouseDown;+ _slider.MouseMove += Slider_MouseMove;+ _slider.MouseLeftButtonUp += Slider_MouseUp;+ _slider.LostMouseCapture += (_, _) => _dragging = false;+ _slider.SizeChanged += (_, _) => UpdateSliderFill();++ var volume = new StackPanel { Width = 148, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 0, 6, 0) };+ volume.Children.Add(deviceButton);+ volume.Children.Add(_slider);+ volume.MouseWheel += Volume_MouseWheel;+ volume.Background = Brushes.Transparent;++ // Battery tile.+ _batteryText = Ui.Text("", 13, FontWeights.Bold, brush: Brushes.White);+ _batteryText.HorizontalAlignment = HorizontalAlignment.Center;+ _batteryBolt = new ContentControl { Content = Ui.Glyph("GlyphBolt", 9, Brushes.White), HorizontalAlignment = HorizontalAlignment.Center, Visibility = Visibility.Collapsed, Margin = new Thickness(0, -2, 0, 0) };+ var batteryStack = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ batteryStack.Children.Add(_batteryText);+ batteryStack.Children.Add(_batteryBolt);+ // Battery: a glass square that fills up like liquid to the charge level, wavy surface on top.+ _batteryLevel = new System.Windows.Shapes.Path { Fill = BatteryFill };+ var batteryLayers = new Grid { ClipToBounds = true };+ batteryLayers.Children.Add(new Border { Background = Ui.Solid("#3364B5FF") });+ batteryLayers.Children.Add(_batteryLevel);+ batteryLayers.Children.Add(batteryStack);+ batteryLayers.SizeChanged += (_, e) =>+ {+ batteryLayers.Clip = new RectangleGeometry(new Rect(e.NewSize), 9, 9);+ UpdateBatteryLevel();+ };+ _battery = new Border+ {+ Width = 42,+ CornerRadius = new CornerRadius(9),+ Margin = new Thickness(4, 3, 0, 3),+ Child = batteryLayers,+ Visibility = Visibility.Collapsed,+ Cursor = Cursors.Hand+ };+ _battery.MouseLeftButtonUp += (_, _) => ControlCenter.Shared.Toggle();++ var row = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Stretch };+ row.Children.Add(_wifiPill);+ row.Children.Add(_bluetoothPill);+ row.Children.Add(volume);+ row.Children.Add(_battery);++ _tile = new Border+ {+ Child = row,+ CornerRadius = (CornerRadius)Application.Current.FindResource("WidgetRadius"),+ BorderThickness = new Thickness(1),+ Padding = new Thickness(5, 0, 3, 0),+ Margin = new Thickness(3, 0, 3, 0),+ VerticalAlignment = VerticalAlignment.Center+ };+ _tile.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ _tile.SetResourceReference(Border.BorderBrushProperty, "WidgetTileStroke");+ _tile.SetResourceReference(FrameworkElement.HeightProperty, "WidgetTileHeight");++ _timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(1) };+ _timer.Tick += (_, _) => Poll();+ _radios.Changed += (_, _) => _tile.Dispatcher.InvokeAsync(UpdateRadios);+ UiText.Current.PropertyChanged += (_, _) => { UpdateRadios(); UpdateAudio(); UpdateBattery(); };+ }++ public override string Id => WidgetIds.QuickControls;+ public override FrameworkElement View => _tile;++ public override async void Start()+ {+ _timer.Start();+ Poll();+ if (_initialized) return;+ _initialized = true;+ await _radios.InitializeAsync();+ UpdateRadios();+ }++ public override void Stop()+ {+ _timer.Stop();+ }+++ public override void SetLive(bool live)+ {+ if (!live)+ {+ _timer.Stop();+ return;+ }+ Poll();+ _timer.Start();+ }++ /// <summary>The tile is the quick view; its pills, chevrons and battery open the Control Center for the rest.</summary>+ private void ToggleConnections() => ControlCenter.Shared.ToggleFrom(View);++ public override void Dispose()+ {+ base.Dispose();+ _audio.Dispose();+ }++ private (Border Pill, Button Toggle, Border IconBack) CreateRadioPill(string icon)+ {+ // Outlined capsule: radio icon | divider | chevron. Either part opens the Control Center.+ var iconBack = new Border { Width = 22, Height = 22 };+ iconBack.Child = Ui.Icon(icon, 13);+ var toggleButton = new Button { Content = iconBack, Width = 30, Height = 26 };+ toggleButton.SetResourceReference(FrameworkElement.StyleProperty, "WidgetIconButton");+ toggleButton.Click += (_, _) => ToggleConnections();+ var divider = new Border { Width = 1, Height = 14, VerticalAlignment = VerticalAlignment.Center };+ divider.SetResourceReference(Border.BackgroundProperty, "StrokeSubtle");+ var more = Ui.IconButton(Ui.Icon("IconChevronRight", 11, brushKey: "TextSecondary"), (_, _) => ToggleConnections(), UiText.Get("QcConnections"), 22, 26);+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ row.Children.Add(toggleButton);+ row.Children.Add(divider);+ row.Children.Add(more);+ var pill = new Border+ {+ Child = row,+ CornerRadius = new CornerRadius(14),+ Padding = new Thickness(2, 0, 2, 0),+ Margin = new Thickness(2, 0, 2, 0),+ Height = 30,+ VerticalAlignment = VerticalAlignment.Center,+ Background = PillFill,+ BorderBrush = PillOffStroke,+ BorderThickness = new Thickness(1)+ };+ return (pill, toggleButton, iconBack);+ }++ private void Poll()+ {+ _tick++;+ if (!_dragging) UpdateAudio();+ if (_tick % 5 == 1) UpdateRadios();+ if (_tick % 15 == 1) UpdateBattery();+ }++ private void UpdateRadios()+ {+ StyleRadio(_wifiPill, _wifiButton, _wifiIconBack, _radios.HasWifi, _radios.WifiOn, "IconWifi", "IconWifiOff",+ _radios.WifiOn ? (RadioControls.IsOnWifi() ? RadioControls.CurrentNetworkName() : null) ?? UiText.Get("QcWifiOn") : UiText.Get("QcWifiOffShort"));+ StyleRadio(_bluetoothPill, _bluetoothButton, _bluetoothIconBack, _radios.HasBluetooth, _radios.BluetoothOn, "IconBluetooth", "IconBluetoothOff",+ UiText.Get(_radios.BluetoothOn ? "QcBluetoothOnShort" : "QcBluetoothOffShort"));+ }++ private static void StyleRadio(Border pill, Button button, Border iconBack, bool available, bool on, string onIcon, string offIcon, string tooltip)+ {+ pill.Visibility = available ? Visibility.Visible : Visibility.Collapsed;+ if (!available) return;+ pill.BorderBrush = on ? PillOnStroke : PillOffStroke;+ iconBack.Child = on ? Ui.Icon(onIcon, 13, OnIcon) : Ui.Icon(offIcon, 13, brushKey: "TextSecondary");+ button.ToolTip = tooltip;+ }++ private void UpdateAudio()+ {+ _audioState = _audio.Read();+ if (_audioState is not { } state)+ {+ _volumeText.Text = "–";+ _sliderFill.Width = 0;+ return;+ }+ var name = string.IsNullOrWhiteSpace(state.DeviceName) ? UiText.Get("QcSound") : state.DeviceName;+ if (_deviceName.Text != name) _deviceName.Text = name;+ _deviceName.ToolTip = name;+ var percent = (int)Math.Round(state.Volume * 100);+ _volumeText.Text = state.Muted ? UiText.Get("QcMuted") : UiText.Format("OpacityPercent", percent.ToString(CultureInfo.InvariantCulture));+ _muteButton.Content = Ui.Icon(state.Muted || percent == 0 ? "IconVolumeMute" : "IconVolume", 13);+ UpdateSliderFill();+ }++ private void UpdateSliderFill()+ {+ if (_audioState is not { } state) return;+ _sliderFill.Background = state.Muted ? Ui.Solid("#FF8E8E93") : OnFill;+ _sliderFill.Width = Math.Max(state.Volume > 0 ? 6 : 0, _slider.ActualWidth * state.Volume);+ }++ private void SetVolumeFromPoint(Point point)+ {+ if (_slider.ActualWidth <= 0) return;+ var level = (float)Math.Clamp(point.X / _slider.ActualWidth, 0, 1);+ _audio.SetVolume(level);+ _audioState = (_audioState ?? new AudioEndpoint.State(level, false, "")) with { Volume = level, Muted = false };+ _volumeText.Text = UiText.Format("OpacityPercent", ((int)Math.Round(level * 100)).ToString(CultureInfo.InvariantCulture));+ UpdateSliderFill();+ }++ private void Slider_MouseDown(object sender, MouseButtonEventArgs e)+ {+ _dragging = true;+ _slider.CaptureMouse();+ SetVolumeFromPoint(e.GetPosition(_slider));+ e.Handled = true;+ }++ private void Slider_MouseMove(object sender, MouseEventArgs e)+ {+ if (_dragging && e.LeftButton == MouseButtonState.Pressed) SetVolumeFromPoint(e.GetPosition(_slider));+ }++ private void Slider_MouseUp(object sender, MouseButtonEventArgs e)+ {+ _dragging = false;+ _slider.ReleaseMouseCapture();+ UpdateAudio();+ }++ private void Volume_MouseWheel(object sender, MouseWheelEventArgs e)+ {+ var current = _audio.Read();+ if (current is null) return;+ var step = e.Delta > 0 ? 0.02f : -0.02f;+ _audio.SetVolume(current.Volume + step);+ UpdateAudio();+ e.Handled = true;+ }++ private void ToggleMute()+ {+ var current = _audio.Read();+ if (current is null) return;+ _audio.SetMute(!current.Muted);+ UpdateAudio();+ }++ private void UpdateBattery()+ {+ var state = BatteryStatus.Read();+ if (state is null)+ {+ if (_battery.Visibility != Visibility.Collapsed)+ {+ _battery.Visibility = Visibility.Collapsed;+ RaiseLayoutChanged();+ }+ return;+ }++ if (_battery.Visibility != Visibility.Visible)+ {+ _battery.Visibility = Visibility.Visible;+ RaiseLayoutChanged();+ }+ _batteryText.Text = state.Percent.ToString(CultureInfo.InvariantCulture);+ _batteryBolt.Visibility = state.Charging || state.OnAc ? Visibility.Visible : Visibility.Collapsed;+ _batteryLevel.Fill = state.Percent <= 20 && !state.OnAc ? BatteryLowFill : BatteryFill;+ _batteryPercent = state.Percent;+ UpdateBatteryLevel();+ var tooltip = UiText.Format("QcBattery", state.Percent);+ if (state.Charging) tooltip += " · " + UiText.Get("QcCharging");+ else if (state.OnAc) tooltip += " · " + UiText.Get("QcPluggedIn");+ else if (state.Remaining is { } remaining) tooltip += " · " + UiText.Format("QcRemaining", (int)remaining.TotalHours, remaining.Minutes);+ _battery.ToolTip = tooltip;+ }++ /// <summary>Liquid fill up to the charge level with a gentle wave on its surface.</summary>+ private void UpdateBatteryLevel()+ {+ if (_batteryLevel.Parent is not FrameworkElement host) return;+ var width = host.ActualWidth;+ var height = host.ActualHeight;+ if (width <= 0 || height <= 0) return;+ var surface = height * (1 - Math.Clamp(_batteryPercent, 0, 100) / 100);+ var wave = _batteryPercent >= 99 ? 0 : 3.2;+ var figure = new PathFigure { StartPoint = new Point(0, surface), IsClosed = true, IsFilled = true };+ figure.Segments.Add(new BezierSegment(new Point(width * 0.25, surface - wave), new Point(width * 0.25, surface + wave), new Point(width * 0.5, surface), true));+ figure.Segments.Add(new BezierSegment(new Point(width * 0.75, surface - wave), new Point(width * 0.75, surface + wave), new Point(width, surface), true));+ figure.Segments.Add(new LineSegment(new Point(width, height), true));+ figure.Segments.Add(new LineSegment(new Point(0, height), true));+ var geometry = new PathGeometry([figure]);+ geometry.Freeze();+ _batteryLevel.Data = geometry;+ }+}diff --git a/Widgets/ReminderWidget.cs b/Widgets/ReminderWidget.csnew file mode 100644index 0000000..e321992--- /dev/null+++ b/Widgets/ReminderWidget.cs@@ -0,0 +1,200 @@+using System.Media;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>+/// Water / break / eye-rest reminder: every chosen number of minutes it chimes and shows a message at the top of+/// the screen. The tile shows what it reminds of and when; the card picks the kind and the interval (or off), and+/// for water counts today's glasses. One timer waits for the next reminder; nothing polls in between.+/// </summary>+public sealed class ReminderWidget : DockWidget+{+ private static readonly int[] Intervals = [20, 30, 45, 60, 90];+ private static readonly string[] Kinds = ["water", "break", "eyes"];++ private readonly Button _tile;+ private readonly WidgetPopup _popup;+ private readonly ContentControl _icon = new() { Focusable = false, Margin = new Thickness(0, 0, 8, 0) };+ private readonly TextBlock _title;+ private readonly TextBlock _next;+ private readonly DispatcherTimer _due = new(DispatcherPriority.Normal);+ private readonly DispatcherTimer _label = new(DispatcherPriority.Background) { Interval = TimeSpan.FromMinutes(1) };+ private DateTime _nextAt;+ private int _glasses;+ private DateTime _glassesDay = DateTime.Today;+ private (string Kind, int Minutes) _applied;++ public ReminderWidget()+ {+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ _title = Ui.Text("", 12, FontWeights.SemiBold);+ _next = Ui.Text("", 10, brushKey: "TextSecondary");+ text.Children.Add(_title);+ text.Children.Add(_next);+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ row.Children.Add(_icon);+ row.Children.Add(text);+ _tile = Ui.Tile(row, (_, _) => Toggle());+ _popup = new WidgetPopup(_tile);+ _due.Tick += (_, _) => Remind();+ _label.Tick += (_, _) => Render();+ UiText.Current.PropertyChanged += (_, _) => Render();+ Render();+ }++ public override string Id => WidgetIds.Reminder;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();++ // Hidden widgets get their settings too; only a shown one reminds.+ private bool _started;++ public override void Start()+ {+ _started = true;+ _applied = default;+ ApplySettings(Current);+ }++ public override void Stop()+ {+ _started = false;+ _due.Stop();+ _label.Stop();+ _popup.Close();+ _applied = default;+ }++ public override void SetLive(bool live)+ {+ if (live && _due.IsEnabled) _label.Start();+ else _label.Stop();+ Render();+ }++ public override void ApplySettings(WidgetSettings settings)+ {+ var wanted = (settings.ReminderKind, settings.ReminderMinutes);+ if (_started && wanted != _applied)+ {+ _applied = wanted;+ Schedule();+ }+ Render();+ }++ private string Kind => Array.IndexOf(Kinds, Current.ReminderKind) >= 0 ? Current.ReminderKind : "water";++ private void Schedule()+ {+ _due.Stop();+ if (Current.ReminderMinutes <= 0)+ {+ _label.Stop();+ return;+ }+ _nextAt = DateTime.Now.AddMinutes(Current.ReminderMinutes);+ _due.Interval = TimeSpan.FromMinutes(Current.ReminderMinutes);+ _due.Start();+ _label.Start();+ }++ private void Remind()+ {+ _nextAt = DateTime.Now + _due.Interval;+ SystemSounds.Asterisk.Play();+ Ui.ShowHud(IconKey(Kind), UiText.Get("ReminderNow_" + Kind));+ Render();+ }++ private static string IconKey(string kind) => kind switch { "break" => "IconCoffee", "eyes" => "IconEye", _ => "IconDroplet" };++ private void Render()+ {+ if (_glassesDay != DateTime.Today)+ {+ _glassesDay = DateTime.Today;+ _glasses = 0;+ }+ var kind = Kind;+ var on = Current.ReminderMinutes > 0 && _due.IsEnabled;+ _icon.Content = Ui.Icon(IconKey(kind), 15, on ? Ui.Solid(kind == "water" ? "#FF64D2FF" : kind == "break" ? "#FFFF9F0A" : "#FF30D158") : null);+ _title.Text = UiText.Get("ReminderKind_" + kind);+ var minutes = Math.Max(0, (int)Math.Ceiling((_nextAt - DateTime.Now).TotalMinutes));+ _next.Text = !on ? UiText.Get("ReminderOff")+ : kind == "water" && _glasses > 0 ? UiText.Format("ReminderNextGlasses", minutes, _glasses)+ : UiText.Format("ReminderNext", minutes);+ _tile.ToolTip = on ? UiText.Format("ReminderEvery", Current.ReminderMinutes) : UiText.Get("ReminderOffHint");+ }++ private void Toggle()+ {+ if (_popup.IsOpen)+ {+ _popup.Close();+ return;+ }+ Build();+ _popup.Toggle();+ }++ private void Build()+ {+ var root = new StackPanel();+ root.Children.Add(Ui.Header(UiText.Get("ReminderTitle"), () => _popup.Close()));+ var kinds = new System.Windows.Controls.Primitives.UniformGrid { Columns = Kinds.Length, Margin = new Thickness(-2, 0, -2, 0) };+ foreach (var kind in Kinds)+ {+ var button = Ui.Pill(UiText.Get("ReminderShort_" + kind), (_, _) =>+ {+ UpdateSettings(s => s with { ReminderKind = kind, ReminderMinutes = s.ReminderMinutes > 0 ? s.ReminderMinutes : 30 });+ Build();+ }, IconKey(kind));+ button.ToolTip = UiText.Get("ReminderKind_" + kind);+ button.Margin = new Thickness(2);+ if (Kind == kind) button.SetResourceReference(Control.BackgroundProperty, "WidgetAccent");+ kinds.Children.Add(button);+ }+ root.Children.Add(kinds);+ var hint = Ui.Text(UiText.Get("ReminderInterval"), 11, brushKey: "TextSecondary");+ hint.Margin = new Thickness(0, 12, 0, 6);+ root.Children.Add(hint);+ var grid = new System.Windows.Controls.Primitives.UniformGrid { Columns = 3, Margin = new Thickness(-2, 0, -2, 0) };+ foreach (var minutes in Intervals.Prepend(0))+ {+ var button = Ui.Pill(minutes == 0 ? UiText.Get("ReminderOffShort") : UiText.Format("FocusMinutes", minutes), (_, _) =>+ {+ UpdateSettings(s => s with { ReminderMinutes = minutes });+ _popup.Close();+ });+ button.Margin = new Thickness(2);+ if (Current.ReminderMinutes == minutes) button.SetResourceReference(Control.BackgroundProperty, "WidgetAccent");+ grid.Children.Add(button);+ }+ root.Children.Add(grid);+ if (Kind == "water")+ {+ var count = Ui.Text(UiText.Format("ReminderGlasses", _glasses), 12, FontWeights.SemiBold);+ var drink = Ui.Pill(UiText.Get("ReminderDrank"), (_, _) =>+ {+ _glasses++;+ // Drinking now restarts the wait, so the next reminder comes a full interval later.+ if (Current.ReminderMinutes > 0) Schedule();+ Render();+ Build();+ }, "IconPlus");+ var row = new DockPanel { Margin = new Thickness(0, 12, 0, 0) };+ DockPanel.SetDock(drink, Dock.Right);+ row.Children.Add(drink);+ row.Children.Add(count);+ root.Children.Add(row);+ }+ _popup.SetContent(root, 330);+ }+}diff --git a/Widgets/SearchWidget.cs b/Widgets/SearchWidget.csnew file mode 100644index 0000000..4059452--- /dev/null+++ b/Widgets/SearchWidget.cs@@ -0,0 +1,113 @@+using System.IO;+using System.Windows;+using System.Windows.Controls;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>+/// The search tile: opens the same search as Alt+Shift+Space (apps, files, calculator), so there is one search+/// everywhere. <see cref="Collect"/> builds that search's list of apps and files.+/// </summary>+public sealed class SearchWidget : DockWidget+{+ private const int MaxIndex = 150_000;+ private readonly Button _tile;++ internal sealed record Entry(string Name, string Path, bool IsApp);++ public SearchWidget()+ {+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ var icon = Ui.Icon("IconSearch", 14, brushKey: "TextSecondary");+ icon.Margin = new Thickness(0, 0, 8, 0);+ row.Children.Add(icon);+ var hint = Ui.Text(UiText.Get("SearchHint"), 12, brushKey: "TextSecondary");+ hint.Width = 110;+ row.Children.Add(hint);+ _tile = Ui.Tile(row, (_, _) => QuickSearchWindow.Toggle(), 12);+ _tile.ToolTip = UiText.Get("SearchTileTip");+ UiText.Current.PropertyChanged += (_, _) =>+ {+ hint.Text = UiText.Get("SearchHint");+ _tile.ToolTip = UiText.Get("SearchTileTip");+ };+ }++ public override string Id => WidgetIds.Search;+ public override FrameworkElement View => _tile;++ internal static List<Entry> Collect(CancellationToken cancel)+ {+ var list = new List<Entry>();+ var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ // Apps first: Start menu shortcuts.+ foreach (var start in new[] { Environment.SpecialFolder.CommonStartMenu, Environment.SpecialFolder.StartMenu })+ {+ foreach (var path in Enumerate(Environment.GetFolderPath(start), "*.lnk", 6, cancel))+ {+ var name = System.IO.Path.GetFileNameWithoutExtension(path);+ if (name.Contains("uninstall", StringComparison.OrdinalIgnoreCase) || name.Contains("kaldır", StringComparison.OrdinalIgnoreCase)) continue;+ if (seen.Add(name)) list.Add(new Entry(name, path, true));+ }+ }+ var profile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);+ var roots = new[]+ {+ Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),+ Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),+ System.IO.Path.Combine(profile, "Downloads"),+ Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),+ Environment.GetFolderPath(Environment.SpecialFolder.MyVideos),+ Environment.GetFolderPath(Environment.SpecialFolder.MyMusic)+ };+ var done = new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ foreach (var root in roots)+ {+ if (string.IsNullOrEmpty(root) || !done.Add(root)) continue;+ foreach (var path in Enumerate(root, "*", 7, cancel))+ {+ list.Add(new Entry(System.IO.Path.GetFileName(path), path, false));+ if (list.Count >= MaxIndex) return list;+ }+ }+ return list;+ }++ private static IEnumerable<string> Enumerate(string root, string pattern, int depth, CancellationToken cancel)+ {+ if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) yield break;+ var options = new EnumerationOptions+ {+ RecurseSubdirectories = true,+ MaxRecursionDepth = depth,+ IgnoreInaccessible = true,+ AttributesToSkip = FileAttributes.Hidden | FileAttributes.System+ };+ IEnumerator<string> items;+ try+ {+ items = Directory.EnumerateFileSystemEntries(root, pattern, options).GetEnumerator();+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ yield break;+ }+ using (items)+ {+ while (true)+ {+ if (cancel.IsCancellationRequested) yield break;+ bool next;+ try { next = items.MoveNext(); }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { yield break; }+ if (!next) yield break;+ var path = items.Current;+ // Skip build and package caches that flood results.+ if (path.Contains("\\node_modules\\", StringComparison.OrdinalIgnoreCase) || path.Contains("\\.git\\", StringComparison.OrdinalIgnoreCase)) continue;+ yield return path;+ }+ }+ }+}diff --git a/Widgets/StopwatchWidget.cs b/Widgets/StopwatchWidget.csnew file mode 100644index 0000000..44af4fb--- /dev/null+++ b/Widgets/StopwatchWidget.cs@@ -0,0 +1,181 @@+using System.Diagnostics;+using System.Media;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>+/// Stopwatch and countdown in one tile: the tile shows whichever runs, with start/pause and reset; the card picks+/// stopwatch or a countdown length. A finished countdown chimes and shows a message at the top of the screen.+/// The display ticks only while something runs and the widget is on screen.+/// </summary>+public sealed class StopwatchWidget : DockWidget+{+ private static readonly int[] Countdowns = [1, 3, 5, 10, 15, 30, 45, 60];+ private static readonly System.Windows.Media.Brush Accent = Ui.Solid("#FF0A84FF");+ private static readonly System.Windows.Media.Brush CountAccent = Ui.Solid("#FFFF9F0A");++ private readonly Button _tile;+ private readonly WidgetPopup _popup;+ private readonly TextBlock _time;+ private readonly TextBlock _label;+ private readonly ContentControl _playIcon = new() { Focusable = false };+ private readonly Button _reset;+ private readonly DispatcherTimer _tick = new(DispatcherPriority.Render) { Interval = TimeSpan.FromMilliseconds(100) };+ private readonly DispatcherTimer _alarm = new(DispatcherPriority.Normal);+ private readonly Stopwatch _watch = new();+ private TimeSpan? _countdown; // null: stopwatch mode+ private bool _live = true;++ public StopwatchWidget()+ {+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 8, 0), MinWidth = 64 };+ _label = Ui.Text("", 10, brushKey: "TextSecondary");+ _time = Ui.Text("0:00.0", 16, FontWeights.Bold);+ _time.FontFeatures();+ text.Children.Add(_label);+ text.Children.Add(_time);+ var play = Ui.IconButton(_playIcon, (_, e) =>+ {+ e.Handled = true;+ StartPause();+ }, UiText.Get("StopwatchStartPause"), 28, 28);+ _reset = Ui.IconButton(Ui.Icon("IconRotate", 12), (_, e) =>+ {+ e.Handled = true;+ Reset();+ }, UiText.Get("StopwatchReset"), 26, 28);+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ row.Children.Add(text);+ row.Children.Add(play);+ row.Children.Add(_reset);+ _tile = Ui.Tile(row, (_, _) => Toggle(), 10);+ _popup = new WidgetPopup(_tile);+ _tick.Tick += (_, _) => Render();+ _alarm.Tick += (_, _) => Finished();+ UiText.Current.PropertyChanged += (_, _) => Render();+ Render();+ }++ public override string Id => WidgetIds.Stopwatch;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();+ public override void Stop() => _popup.Close();++ public override void SetLive(bool live)+ {+ _live = live;+ UpdateTicking();+ Render();+ }++ private TimeSpan Shown => _countdown is { } length ? (length - _watch.Elapsed) is var left && left > TimeSpan.Zero ? left : TimeSpan.Zero : _watch.Elapsed;++ private void StartPause()+ {+ if (_watch.IsRunning) _watch.Stop();+ else+ {+ if (_countdown is not null && Shown <= TimeSpan.Zero) _watch.Reset();+ _watch.Start();+ }+ UpdateTicking();+ Render();+ }++ private void Reset()+ {+ _watch.Reset();+ UpdateTicking();+ Render();+ }++ private void UpdateTicking()+ {+ // The countdown's end is a single timer, so it fires while the dock is hidden; the display ticks only when seen.+ _alarm.Stop();+ if (_watch.IsRunning && _countdown is not null && Shown > TimeSpan.Zero)+ {+ _alarm.Interval = Shown;+ _alarm.Start();+ }+ _tick.Interval = TimeSpan.FromMilliseconds(_countdown is null ? 100 : 250);+ if (_watch.IsRunning && _live) _tick.Start();+ else _tick.Stop();+ }++ private void Finished()+ {+ _alarm.Stop();+ _watch.Stop();+ _watch.Reset();+ UpdateTicking();+ Render();+ SystemSounds.Exclamation.Play();+ Ui.ShowHud("IconTimer", UiText.Get("StopwatchDone"));+ }++ private void Render()+ {+ var shown = Shown;+ if (_countdown is null)+ _time.Text = shown.TotalHours >= 1 ? shown.ToString(@"h\:mm\:ss") : $"{(int)shown.TotalMinutes}:{shown.Seconds:00}.{shown.Milliseconds / 100}";+ else+ {+ // A countdown shows whole seconds, rounded up: it reads 0:01 until the very end.+ var seconds = (int)Math.Ceiling(shown.TotalSeconds - 0.0001);+ _time.Text = seconds >= 3600 ? $"{seconds / 3600}:{seconds / 60 % 60:00}:{seconds % 60:00}" : $"{seconds / 60}:{seconds % 60:00}";+ }+ _label.Text = _countdown is { } length ? UiText.Format("StopwatchCountdownLabel", (int)length.TotalMinutes) : UiText.Get("StopwatchLabel");+ var accent = _countdown is null ? Accent : CountAccent;+ if (_watch.IsRunning) _time.Foreground = accent;+ else _time.SetResourceReference(TextBlock.ForegroundProperty, "TextPrimary");+ _playIcon.Content = Ui.Glyph(_watch.IsRunning ? "GlyphPause" : "GlyphPlay", 12, _watch.IsRunning ? accent : null);+ _reset.Visibility = _watch.Elapsed > TimeSpan.Zero ? Visibility.Visible : Visibility.Collapsed;+ }++ private void Toggle()+ {+ if (_popup.IsOpen)+ {+ _popup.Close();+ return;+ }+ var root = new StackPanel();+ root.Children.Add(Ui.Header(UiText.Get("StopwatchTitle"), () => _popup.Close()));+ var stopwatch = Ui.Pill(UiText.Get("StopwatchMode"), (_, _) => Choose(null), "IconTimer");+ stopwatch.HorizontalAlignment = HorizontalAlignment.Stretch;+ if (_countdown is null) stopwatch.SetResourceReference(Control.BackgroundProperty, "WidgetAccent");+ root.Children.Add(stopwatch);+ var hint = Ui.Text(UiText.Get("StopwatchCountdownHint"), 11, brushKey: "TextSecondary");+ hint.Margin = new Thickness(0, 12, 0, 6);+ root.Children.Add(hint);+ var grid = new System.Windows.Controls.Primitives.UniformGrid { Columns = 4, Margin = new Thickness(-2, 0, -2, 0) };+ foreach (var minutes in Countdowns)+ {+ var button = Ui.Pill(UiText.Format("FocusMinutes", minutes), (_, _) => Choose(TimeSpan.FromMinutes(minutes)));+ button.Margin = new Thickness(2);+ if (_countdown is { } length && (int)length.TotalMinutes == minutes) button.SetResourceReference(Control.BackgroundProperty, "WidgetAccent");+ grid.Children.Add(button);+ }+ root.Children.Add(grid);+ _popup.SetContent(root, 300);+ _popup.Toggle();+ }++ /// <summary>Switches to the stopwatch (null) or a countdown of the given length; a countdown starts at once.</summary>+ private void Choose(TimeSpan? countdown)+ {+ _countdown = countdown;+ _watch.Reset();+ if (countdown is not null) _watch.Start();+ UpdateTicking();+ Render();+ _popup.Close();+ }+}diff --git a/Widgets/SystemWidget.cs b/Widgets/SystemWidget.csnew file mode 100644index 0000000..9ac0930--- /dev/null+++ b/Widgets/SystemWidget.cs@@ -0,0 +1,208 @@+using System.Globalization;+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>CPU and memory load as two small bars that turn green → yellow → orange → red as load rises.</summary>+public sealed class SystemWidget : DockWidget+{+ private readonly Button _tile;+ private readonly WidgetPopup _popup;+ private readonly DispatcherTimer _timer;+ private readonly QiDock.DesktopWidgets.RingGauge _cpuBar;+ private readonly QiDock.DesktopWidgets.RingGauge _ramBar;+ private readonly TextBlock _cpuText;+ private readonly TextBlock _ramText;+ private ulong _lastIdle;+ private ulong _lastTotal;+ private double _cpu;+ private MemoryStatus _memory;++ public SystemWidget()+ {+ var rows = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center };+ (_cpuBar, _cpuText) = AddRow(rows, "CPU");+ (_ramBar, _ramText) = AddRow(rows, "RAM");+ ((FrameworkElement)rows.Children[1]).Margin = new Thickness(6, 0, 0, 0);+ _tile = new Button { Content = rows, Padding = new Thickness(6, 0, 6, 0) };+ _tile.SetResourceReference(FrameworkElement.StyleProperty, "WidgetTileButton");+ _tile.Click += (_, _) => TogglePopup();+ _popup = new WidgetPopup(_tile);+ _timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(2) };+ _timer.Tick += (_, _) => Sample();+ UiText.Current.PropertyChanged += (_, _) => Render();+ }++ public override string Id => WidgetIds.System;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;++ public override void Start()+ {+ Sample();+ _timer.Start();+ }++ public override void Stop()+ {+ _timer.Stop();+ _popup.Close();+ }++ public override void ClosePopup() => _popup.Close();++ public override void SetLive(bool live)+ {+ if (!live)+ {+ _timer.Stop();+ return;+ }+ Sample();+ _timer.Start();+ }++ /// <summary>A small ring with the percent and the label ("CPU", "RAM") inside.</summary>+ private static (QiDock.DesktopWidgets.RingGauge Ring, TextBlock Percent) AddRow(Panel rows, string label)+ {+ var ring = new QiDock.DesktopWidgets.RingGauge { Width = 34, Height = 34, Thickness = 3, TrackBrush = Ui.Solid("#47808080") };+ var percent = Ui.Text("", 10.5, FontWeights.Bold);+ percent.HorizontalAlignment = HorizontalAlignment.Center;+ var name = Ui.Text(label, 6.5, FontWeights.SemiBold, brushKey: "TextSecondary");+ name.HorizontalAlignment = HorizontalAlignment.Center;+ name.Margin = new Thickness(0, -2, 0, 0);+ var inside = new StackPanel { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ inside.Children.Add(percent);+ inside.Children.Add(name);+ var face = new Grid { Width = 34, Height = 34, VerticalAlignment = VerticalAlignment.Center };+ face.Children.Add(ring);+ face.Children.Add(inside);+ rows.Children.Add(face);+ return (ring, percent);+ }++ private void Sample()+ {+ if (GetSystemTimes(out var idle, out var kernel, out var user))+ {+ var total = kernel + user; // kernel time includes idle time+ if (_lastTotal != 0 && total > _lastTotal)+ {+ var busy = 1 - (double)(idle - _lastIdle) / (total - _lastTotal);+ _cpu = Math.Clamp(busy * 100, 0, 100);+ }+ _lastIdle = idle;+ _lastTotal = total;+ }++ var memory = new MemoryStatus { Length = (uint)Marshal.SizeOf<MemoryStatus>() };+ if (GlobalMemoryStatusEx(ref memory)) _memory = memory;+ Render();+ if (_popup.IsOpen) BuildPopup();+ }++ private void Render()+ {+ SetBar(_cpuBar, _cpu);+ SetBar(_ramBar, _memory.MemoryLoad);+ _cpuText.Text = Math.Round(_cpu).ToString(CultureInfo.InvariantCulture);+ _ramText.Text = Math.Round((double)_memory.MemoryLoad).ToString(CultureInfo.InvariantCulture);+ _tile.ToolTip = $"CPU {Percent(_cpu)} · RAM {Gb(_memory.TotalPhys - _memory.AvailPhys)} / {Gb(_memory.TotalPhys)}";+ }++ private static void SetBar(QiDock.DesktopWidgets.RingGauge ring, double percent)+ {+ ring.Stroke = Ui.UsageBrush(percent);+ ring.Value = percent;+ ring.InvalidateVisual();+ }++ private void TogglePopup()+ {+ if (!_popup.IsOpen) BuildPopup();+ _popup.Toggle();+ }++ private void BuildPopup()+ {+ var root = new StackPanel();+ var header = new DockPanel { Margin = new Thickness(0, 0, 0, 12) };+ var close = Ui.IconButton(Ui.Icon("IconClose", 12), (_, _) => _popup.Close(), UiText.Get("Close"));+ DockPanel.SetDock(close, Dock.Right);+ header.Children.Add(close);+ header.Children.Add(Ui.Text(UiText.Get("SysTitle"), 13, FontWeights.SemiBold));+ root.Children.Add(header);++ root.Children.Add(Card(UiText.Get("SysCpu"), Percent(_cpu), _cpu,+ string.Format(CultureInfo.CurrentCulture, UiText.Get("SysCores"), Environment.ProcessorCount)));+ var used = _memory.TotalPhys - _memory.AvailPhys;+ root.Children.Add(Card(UiText.Get("SysRam"), Percent(_memory.MemoryLoad), _memory.MemoryLoad,+ string.Format(CultureInfo.CurrentCulture, UiText.Get("SysRamDetail"), Gb(used), Gb(_memory.TotalPhys))));++ var uptime = TimeSpan.FromMilliseconds(Environment.TickCount64);+ var footer = Ui.Text(string.Format(CultureInfo.CurrentCulture, UiText.Get("SysUptime"), (int)uptime.TotalDays, uptime.Hours, uptime.Minutes),+ 11, brushKey: "TextSecondary");+ footer.Margin = new Thickness(2, 2, 0, 10);+ root.Children.Add(footer);++ var taskManager = new Button { Content = Ui.Text(UiText.Get("SysTaskManager"), 12, FontWeights.SemiBold), Height = 30, HorizontalAlignment = HorizontalAlignment.Stretch };+ taskManager.SetResourceReference(FrameworkElement.StyleProperty, "WidgetPillButton");+ taskManager.Click += (_, _) =>+ {+ _popup.Close();+ Ui.Open("taskmgr.exe");+ };+ root.Children.Add(taskManager);+ _popup.SetContent(root, 280);+ }++ private static FrameworkElement Card(string title, string value, double percent, string detail)+ {+ var top = new DockPanel();+ var valueText = Ui.Text(value, 15, FontWeights.Bold, brush: Ui.UsageBrush(percent));+ DockPanel.SetDock(valueText, Dock.Right);+ top.Children.Add(valueText);+ top.Children.Add(Ui.Text(title, 12.5, FontWeights.SemiBold));+ var stack = new StackPanel();+ stack.Children.Add(top);+ var bar = Ui.Bar(percent, 236, 6, Ui.UsageBrush(percent));+ bar.Margin = new Thickness(0, 6, 0, 5);+ bar.HorizontalAlignment = HorizontalAlignment.Left;+ stack.Children.Add(bar);+ stack.Children.Add(Ui.Text(detail, 11, brushKey: "TextSecondary"));+ var card = new Border { CornerRadius = new CornerRadius(12), Padding = new Thickness(12, 10, 12, 10), Margin = new Thickness(0, 0, 0, 6), Child = stack };+ card.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ return card;+ }++ private static string Percent(double value) => "%" + Math.Round(value).ToString(CultureInfo.InvariantCulture);++ private static string Gb(ulong bytes) => (bytes / 1073741824d).ToString("0.0", CultureInfo.CurrentCulture) + " GB";++ [StructLayout(LayoutKind.Sequential)]+ private struct MemoryStatus+ {+ public uint Length;+ public uint MemoryLoad;+ public ulong TotalPhys;+ public ulong AvailPhys;+ public ulong TotalPageFile;+ public ulong AvailPageFile;+ public ulong TotalVirtual;+ public ulong AvailVirtual;+ public ulong AvailExtendedVirtual;+ }++ [DllImport("kernel32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool GetSystemTimes(out ulong idleTime, out ulong kernelTime, out ulong userTime);++ [DllImport("kernel32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool GlobalMemoryStatusEx(ref MemoryStatus buffer);+}diff --git a/Widgets/TodoWidget.cs b/Widgets/TodoWidget.csnew file mode 100644index 0000000..f1b3789--- /dev/null+++ b/Widgets/TodoWidget.cs@@ -0,0 +1,132 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>Small to-do list: the tile shows the next open task; the card adds, ticks off and removes tasks.</summary>+public sealed class TodoWidget : DockWidget+{+ private readonly Button _tile;+ private readonly WidgetPopup _popup;+ private readonly TextBlock _next;+ private readonly TextBlock _count;+ private readonly TextBox _input = new();+ private readonly StackPanel _list = new();+ private readonly StackPanel _card = new();+ private IReadOnlyList<TodoItem> _items = [];++ public TodoWidget()+ {+ var icon = Ui.Icon("IconListCheck", 16);+ icon.Margin = new Thickness(0, 0, 9, 0);+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ _next = Ui.Text("", 12, FontWeights.SemiBold);+ _next.MaxWidth = 150;+ _count = Ui.Text("", 10.5, brushKey: "TextSecondary");+ text.Children.Add(_next);+ text.Children.Add(_count);+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ row.Children.Add(icon);+ row.Children.Add(text);+ _tile = Ui.Tile(row, (_, _) => Toggle());+ _popup = new WidgetPopup(_tile);++ _input.SetResourceReference(FrameworkElement.StyleProperty, "WidgetTextBox");+ _input.KeyDown += (_, e) =>+ {+ if (e.Key == Key.Enter && _input.Text.Trim() is { Length: > 0 } text)+ {+ _input.Text = "";+ UpdateSettings(s => s with { Todos = (s.Todos ?? []).Append(new TodoItem(text)).ToList() });+ }+ else if (e.Key == Key.Escape) _popup.Close();+ };+ _card.Children.Add(Ui.Header(UiText.Get("TodoTitle"), () => _popup.Close()));+ _card.Children.Add(_input);+ _list.Margin = new Thickness(0, 8, 0, 0);+ _card.Children.Add(new ScrollViewer { Content = _list, MaxHeight = 320, VerticalScrollBarVisibility = ScrollBarVisibility.Auto });+ UiText.Current.PropertyChanged += (_, _) => Render();+ Render();+ }++ public override string Id => WidgetIds.Todo;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();+ public override void Stop() => _popup.Close();++ public override void ApplySettings(WidgetSettings settings)+ {+ var items = settings.Todos ?? [];+ if (items.SequenceEqual(_items)) return;+ _items = items;+ Render();+ }++ private void Render()+ {+ var open = _items.Where(i => !i.Done).ToList();+ _next.Text = open.Count > 0 ? open[0].Text : UiText.Get(_items.Count > 0 ? "TodoAllDone" : "TodoTitle");+ _count.Text = open.Count > 0 ? UiText.Format("TodoOpen", open.Count) : UiText.Get("TodoAddHint");+ _tile.ToolTip = string.Join(Environment.NewLine, open.Select(i => "• " + i.Text));+ if (_tile.ToolTip is "") _tile.ToolTip = null;++ _list.Children.Clear();+ for (var index = 0; index < _items.Count; index++) _list.Children.Add(Row(_items[index], index));+ if (_items.Any(i => i.Done))+ {+ var clear = Ui.Pill(UiText.Get("TodoClearDone"), (_, _) => UpdateSettings(s => s with { Todos = (s.Todos ?? []).Where(i => !i.Done).ToList() }));+ clear.HorizontalAlignment = HorizontalAlignment.Left;+ clear.Margin = new Thickness(0, 8, 0, 0);+ _list.Children.Add(clear);+ }+ _input.Tag = UiText.Get("TodoPlaceholder");+ }++ private FrameworkElement Row(TodoItem item, int index)+ {+ var check = new Border+ {+ Width = 18,+ Height = 18,+ CornerRadius = new CornerRadius(9),+ BorderThickness = new Thickness(1.5),+ BorderBrush = item.Done ? Ui.Solid("#FF32D74B") : Ui.Solid("#80FFFFFF"),+ Background = item.Done ? Ui.Solid("#FF32D74B") : System.Windows.Media.Brushes.Transparent,+ Child = item.Done ? Ui.Icon("IconCheck", 10, System.Windows.Media.Brushes.White, stroke: 3) : null+ };+ var toggle = Ui.IconButton(check, (_, _) => Replace(index, item with { Done = !item.Done }), UiText.Get("TodoToggle"), 28, 28);+ var text = Ui.Text(item.Text, 12.5, item.Done ? FontWeights.Normal : FontWeights.SemiBold, item.Done ? "TextSecondary" : "TextPrimary");+ text.TextWrapping = TextWrapping.Wrap;+ text.TextTrimming = TextTrimming.None;+ if (item.Done) text.TextDecorations = TextDecorations.Strikethrough;+ text.Margin = new Thickness(6, 0, 6, 0);+ var remove = Ui.IconButton(Ui.Icon("IconClose", 10, brushKey: "TextSecondary"), (_, _) =>+ UpdateSettings(s => s with { Todos = (s.Todos ?? []).Where((_, i) => i != index).ToList() }), UiText.Get("TodoRemove"));+ var row = new DockPanel { Margin = new Thickness(0, 1, 0, 1) };+ DockPanel.SetDock(toggle, Dock.Left);+ DockPanel.SetDock(remove, Dock.Right);+ row.Children.Add(toggle);+ row.Children.Add(remove);+ row.Children.Add(text);+ return row;+ }++ private void Replace(int index, TodoItem item) =>+ UpdateSettings(s => s with { Todos = (s.Todos ?? []).Select((old, i) => i == index ? item : old).ToList() });++ private void Toggle()+ {+ if (_popup.IsOpen)+ {+ _popup.Close();+ return;+ }+ _popup.SetContent(_card, 330);+ _popup.Toggle();+ _popup.FocusInput(_input);+ }+}diff --git a/Widgets/ToolsWidget.cs b/Widgets/ToolsWidget.csnew file mode 100644index 0000000..c895682--- /dev/null+++ b/Widgets/ToolsWidget.cs@@ -0,0 +1,49 @@+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Controls;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>One-click tools: screenshot, clipboard history, emoji, calculator, lock screen.</summary>+public sealed class ToolsWidget : DockWidget+{+ private readonly Border _tile;++ public ToolsWidget()+ {+ var row = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(4, 0, 4, 0) };+ row.Children.Add(Tool("IconCamera", "ToolScreenshot", () => Ui.Open("ms-screenclip:")));+ row.Children.Add(Tool("IconClipboard", "ToolClipboard", () => SendWinKey(0x56 /* V */)));+ row.Children.Add(Tool("IconSmile", "ToolEmoji", () => SendWinKey(0xBE /* . */)));+ row.Children.Add(Tool("IconCalculator", "ToolCalculator", () => Ui.Open("calc.exe")));+ row.Children.Add(Tool("IconLock", "ToolLock", () => LockWorkStation()));+ _tile = new Border { Child = row, CornerRadius = new CornerRadius(11), BorderThickness = new Thickness(1), Margin = new Thickness(3, 0, 3, 0), VerticalAlignment = VerticalAlignment.Center };+ _tile.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ _tile.SetResourceReference(Border.BorderBrushProperty, "WidgetTileStroke");+ _tile.SetResourceReference(FrameworkElement.HeightProperty, "WidgetTileHeight");+ }++ public override string Id => WidgetIds.Tools;+ public override FrameworkElement View => _tile;++ private static Button Tool(string icon, string textKey, Action run)+ {+ var button = Ui.IconButton(Ui.Icon(icon, 16), (_, _) => run(), UiText.Get(textKey), 34, 34);+ button.Margin = new Thickness(1, 0, 1, 0);+ return button;+ }++ /// <summary>Windows key shortcuts (Win+V clipboard history, Win+. emoji panel).</summary>+ private static void SendWinKey(byte key)+ {+ keybd_event(0x5B, 0, 0, 0);+ keybd_event(key, 0, 0, 0);+ keybd_event(key, 0, 2, 0);+ keybd_event(0x5B, 0, 2, 0);+ }++ [DllImport("user32.dll")] private static extern void keybd_event(byte key, byte scan, int flags, int extra);+ [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool LockWorkStation();+}diff --git a/Widgets/TrayWidget.cs b/Widgets/TrayWidget.csnew file mode 100644index 0000000..d270a8a--- /dev/null+++ b/Widgets/TrayWidget.cs@@ -0,0 +1,238 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Shapes;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>+/// The apps running in the background (the icons the hidden taskbar would show by its clock): up to four of their+/// icons in one square. The card lists them all; a click opens the app, a right click opens the app's own menu and+/// the cross closes it (asking first, then ending it if it will not go).+/// </summary>+public sealed class TrayWidget : DockWidget+{+ private enum Closing { Asked, Stubborn }++ private readonly Button _tile;+ private readonly UniformGrid _grid = new() { Rows = 2, Columns = 2 };+ private readonly Path _empty = Ui.Icon("IconApps", 17, brushKey: "TextSecondary");+ private readonly Grid _face = new();+ private readonly WidgetPopup _popup;+ private readonly StackPanel _rows = new();+ private readonly StackPanel _card = new();+ private readonly Dictionary<int, Closing> _closing = [];+ private readonly Dictionary<int, string> _errors = [];+ private readonly DispatcherTimer _refresh = new(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(3) };+ private bool _started;++ public TrayWidget()+ {+ _face.Children.Add(_grid);+ _face.Children.Add(_empty);+ _empty.HorizontalAlignment = HorizontalAlignment.Center;+ _empty.VerticalAlignment = VerticalAlignment.Center;+ _tile = Ui.Tile(_face, (_, _) => Toggle(), horizontalPadding: 0);+ _tile.SetResourceReference(FrameworkElement.WidthProperty, "WidgetTileHeight");+ _popup = new WidgetPopup(_tile);+ _popup.Opened += (_, _) => _refresh.Start();+ _popup.Closed += (_, _) => _refresh.Stop();+ _refresh.Tick += (_, _) => Render();++ _card.Children.Add(Ui.Header(UiText.Get("TrayTitle"), () => _popup.Close()));+ _card.Children.Add(Ui.FadingScroller(_rows, 330));+ var hint = Ui.Text(UiText.Get("TrayHint"), 10.5, brushKey: "TextSecondary");+ hint.TextWrapping = TextWrapping.Wrap;+ hint.Margin = new Thickness(2, 10, 2, 0);+ _card.Children.Add(hint);+ _popup.SetContent(_card, 310);+ UiText.Current.PropertyChanged += (_, _) => Render();+ }++ public override string Id => WidgetIds.Tray;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();++ public override void Start()+ {+ if (_started) return;+ _started = true;+ TrayHost.Shared.Changed += HostChanged;+ Render();+ }++ public override void Stop()+ {+ _started = false;+ TrayHost.Shared.Changed -= HostChanged;+ _popup.Close();+ }++ private void HostChanged(object? sender, EventArgs e) => Render();++ private void Toggle()+ {+ Render();+ _popup.Toggle();+ }++ private void Render()+ {+ var icons = TrayHost.Shared.Icons;+ RenderTile(icons);+ RenderCard(icons);+ }++ private void RenderTile(IReadOnlyList<TrayIcon> icons)+ {+ _grid.Children.Clear();+ _empty.Visibility = icons.Count == 0 ? Visibility.Visible : Visibility.Collapsed;+ var cell = Math.Max(14, ((Application.Current.TryFindResource("WidgetTileHeight") as double? ?? 40) - 12) / 2);+ var shown = icons.Count > 4 ? 3 : icons.Count;+ for (var i = 0; i < shown; i++)+ {+ var image = new Image { Source = icons[i].Image, Width = cell - 3, Height = cell - 3, Stretch = Stretch.Uniform, Margin = new Thickness(1.5) };+ RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality);+ _grid.Children.Add(image);+ }+ if (icons.Count > 4)+ {+ var more = Ui.Text("+" + (icons.Count - 3), 9.5, FontWeights.Bold, brushKey: "TextSecondary");+ more.HorizontalAlignment = HorizontalAlignment.Center;+ more.VerticalAlignment = VerticalAlignment.Center;+ _grid.Children.Add(more);+ }+ _tile.ToolTip = icons.Count == 0 ? UiText.Get("TrayEmpty") : UiText.Format("TrayCount", icons.Count);+ }++ private void RenderCard(IReadOnlyList<TrayIcon> icons)+ {+ _rows.Children.Clear();+ foreach (var pid in _closing.Keys.Where(pid => icons.All(i => i.ProcessId != pid)).ToList()) _closing.Remove(pid);+ if (icons.Count == 0)+ {+ var none = Ui.Text(UiText.Get("TrayEmpty"), 11.5, brushKey: "TextSecondary");+ none.TextWrapping = TextWrapping.Wrap;+ none.Margin = new Thickness(2, 4, 2, 4);+ _rows.Children.Add(none);+ return;+ }+ foreach (var icon in icons) _rows.Children.Add(Row(icon));+ }++ private FrameworkElement Row(TrayIcon icon)+ {+ var row = new DockPanel { LastChildFill = true };+ var image = new Image { Source = icon.Image, Width = 20, Height = 20, Margin = new Thickness(0, 0, 10, 0), VerticalAlignment = VerticalAlignment.Center };+ RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality);+ DockPanel.SetDock(image, Dock.Left);+ row.Children.Add(image);++ if (icon.CanClose)+ {+ FrameworkElement action;+ if (_closing.TryGetValue(icon.ProcessId, out var state) && state == Closing.Stubborn)+ {+ var force = Ui.Pill(UiText.Get("TrayForceClose"), (_, _) => Force(icon));+ force.Height = 24;+ force.Padding = new Thickness(9, 2, 9, 2);+ force.Foreground = Ui.Solid("#FFFF6B5E");+ action = force;+ }+ else+ {+ action = Ui.IconButton(Ui.Icon("IconClose", 10, brushKey: "TextSecondary"), (_, _) => Close(icon), UiText.Get("TrayClose"));+ action.IsEnabled = !_closing.ContainsKey(icon.ProcessId);+ }+ action.VerticalAlignment = VerticalAlignment.Center;+ action.Margin = new Thickness(6, 0, 0, 0);+ DockPanel.SetDock(action, Dock.Right);+ row.Children.Add(action);+ }++ var words = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ var title = Ui.Text(icon.Title, 12.5, FontWeights.SemiBold);+ title.TextTrimming = TextTrimming.CharacterEllipsis;+ words.Children.Add(title);+ var detail = _errors.TryGetValue(icon.ProcessId, out var error) ? error+ : _closing.TryGetValue(icon.ProcessId, out var closing) ? UiText.Get(closing == Closing.Asked ? "TrayClosing" : "TrayStillRunning")+ : icon.Detail;+ if (detail.Length > 0)+ {+ var line = Ui.Text(detail, 10.5, brushKey: "TextSecondary");+ line.TextTrimming = TextTrimming.CharacterEllipsis;+ words.Children.Add(line);+ }+ row.Children.Add(words);++ var surface = new Border { Child = row, CornerRadius = new CornerRadius(9), Padding = new Thickness(8, 6, 6, 6), Background = Brushes.Transparent, Cursor = Cursors.Hand };+ surface.ToolTip = icon.Tip.Length > 0 ? icon.Tip : null;+ surface.MouseEnter += (_, _) => surface.SetResourceReference(Border.BackgroundProperty, "SurfaceHover");+ surface.MouseLeave += (_, _) => surface.Background = Brushes.Transparent;+ surface.MouseLeftButtonUp += (_, e) =>+ {+ if (e.OriginalSource is DependencyObject source && IsInButton(source, surface)) return;+ e.Handled = true;+ _popup.Close();+ if (e.ClickCount >= 2) TrayHost.DoubleClick(icon);+ else TrayHost.Click(icon);+ };+ surface.MouseRightButtonUp += (_, e) =>+ {+ e.Handled = true;+ _popup.Close();+ // The app's own menu opens at the pointer once the card is out of the way.+ Dispatcher.CurrentDispatcher.BeginInvoke(() => TrayHost.RightClick(icon), DispatcherPriority.Background);+ };+ return surface;+ }++ private static bool IsInButton(DependencyObject source, DependencyObject stop)+ {+ for (var node = source; node is not null && !ReferenceEquals(node, stop); node = VisualTreeHelper.GetParent(node) ?? LogicalTreeHelper.GetParent(node))+ if (node is ButtonBase) return true;+ return false;+ }++ /// <summary>Asks the app to close; if it is still running a moment later, offers to end it.</summary>+ private void Close(TrayIcon icon)+ {+ _errors.Remove(icon.ProcessId);+ if (!TrayHost.AskToClose(icon)) return;+ var pid = icon.ProcessId;+ _closing[pid] = Closing.Asked;+ Render();+ var wait = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2.5) };+ wait.Tick += (_, _) =>+ {+ wait.Stop();+ if (TrayHost.IsRunningProcess(pid) && icon.IsAlive) _closing[pid] = Closing.Stubborn;+ else _closing.Remove(pid);+ Render();+ };+ wait.Start();+ }++ private void Force(TrayIcon icon)+ {+ var error = TrayHost.ForceClose(icon);+ _closing.Remove(icon.ProcessId);+ if (error is not null) _errors[icon.ProcessId] = error;+ else+ {+ _errors.Remove(icon.ProcessId);+ Ui.ShowHud("IconCheck", UiText.Format("TrayClosed", icon.Title));+ }+ // Its icon leaves the list once its window is gone.+ var later = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(600) };+ later.Tick += (_, _) => { later.Stop(); Render(); };+ later.Start();+ Render();+ }+}diff --git a/Widgets/VoiceMemoWidget.cs b/Widgets/VoiceMemoWidget.csnew file mode 100644index 0000000..6ef7b65--- /dev/null+++ b/Widgets/VoiceMemoWidget.cs@@ -0,0 +1,211 @@+using System.IO;+using System.Runtime.InteropServices;+using System.Text;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media.Animation;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>+/// Voice memo: one click starts recording from the default microphone, the next saves it as a .wav file in+/// Documents\Ses Kayıtları. The card lists the latest recordings (click to play) and opens the folder.+/// Recording uses Windows' own sound recorder (MCI), so nothing extra is installed.+/// </summary>+public sealed class VoiceMemoWidget : DockWidget+{+ private const string Alias = "qidockmemo";+ private static readonly System.Windows.Media.Brush Red = Ui.Solid("#FFFF453A");++ private readonly Button _tile;+ private readonly WidgetPopup _popup;+ private readonly ContentControl _icon = new() { Focusable = false, Margin = new Thickness(0, 0, 8, 0) };+ private readonly TextBlock _title;+ private readonly TextBlock _caption;+ private readonly DispatcherTimer _clock = new(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(1) };+ private DateTime _startedAt;+ private bool _recording;+ private string? _last;++ public VoiceMemoWidget()+ {+ var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ _title = Ui.Text("", 12, FontWeights.SemiBold);+ _title.FontFeatures();+ _caption = Ui.Text("", 10, brushKey: "TextSecondary");+ text.Children.Add(_title);+ text.Children.Add(_caption);+ var record = Ui.IconButton(_icon, (_, e) =>+ {+ e.Handled = true;+ if (_recording) Finish();+ else Begin();+ }, UiText.Get("MemoRecordStop"), 30, 30);+ _icon.Margin = new Thickness(0);+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ record.Margin = new Thickness(0, 0, 6, 0);+ row.Children.Add(record);+ row.Children.Add(text);+ _tile = Ui.Tile(row, (_, _) => Toggle(), 7);+ _popup = new WidgetPopup(_tile);+ _clock.Tick += (_, _) => Render();+ UiText.Current.PropertyChanged += (_, _) => Render();+ Render();+ }++ public override string Id => WidgetIds.VoiceMemo;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();++ public override void Stop()+ {+ // Hidden while recording: keep what was said.+ if (_recording) Finish();+ _popup.Close();+ }++ private static string Folder => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Ses Kayıtları");++ [DllImport("winmm.dll", CharSet = CharSet.Unicode)]+ private static extern int mciSendString(string command, StringBuilder? result, int length, nint callback);++ [DllImport("winmm.dll", CharSet = CharSet.Unicode)]+ private static extern bool mciGetErrorString(int error, StringBuilder text, int length);++ private static bool Mci(string command)+ {+ var error = mciSendString(command, null, 0, 0);+ if (error == 0) return true;+ var text = new StringBuilder(256);+ mciGetErrorString(error, text, text.Capacity);+ AppLog.Write($"Ses kaydı ({command.Split(' ')[0]}): {text}");+ return false;+ }++ private void Begin()+ {+ Mci("close " + Alias); // a recording left open by a crash+ // 16-bit mono 44.1 kHz: clear speech in about 5 MB a minute.+ if (!Mci($"open new type waveaudio alias {Alias}")+ || !Mci($"set {Alias} bitspersample 16 channels 1 samplespersec 44100 bytespersec 88200 alignment 2")+ || !Mci($"record {Alias}"))+ {+ Mci("close " + Alias);+ Ui.ShowHud("IconMic", UiText.Get("MemoNoMic"));+ return;+ }+ _recording = true;+ _startedAt = DateTime.Now;+ _clock.Start();+ Render();+ }++ private void Finish()+ {+ _clock.Stop();+ _recording = false;+ Mci("stop " + Alias);+ try+ {+ Directory.CreateDirectory(Folder);+ var path = Path.Combine(Folder, $"Kayıt {_startedAt:yyyy-MM-dd HH-mm-ss}.wav");+ if (Mci($"save {Alias} \"{path}\""))+ {+ _last = path;+ Ui.ShowHud("IconMic", UiText.Format("MemoSaved", (DateTime.Now - _startedAt).ToString(@"m\:ss")));+ }+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ AppLog.Write("Ses kaydı kaydedilemedi: " + ex.Message);+ }+ finally+ {+ Mci("close " + Alias);+ }+ Render();+ if (_popup.IsOpen) Build();+ }++ private void Render()+ {+ if (_recording)+ {+ var dot = new System.Windows.Shapes.Rectangle { Width = 12, Height = 12, RadiusX = 3, RadiusY = 3, Fill = Red };+ if (_icon.Content is not System.Windows.Shapes.Rectangle)+ {+ // A slow pulse says the microphone is on.+ dot.BeginAnimation(UIElement.OpacityProperty, new DoubleAnimation(1, 0.45, TimeSpan.FromMilliseconds(700)) { AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever });+ _icon.Content = dot;+ }+ var elapsed = DateTime.Now - _startedAt;+ _title.Text = elapsed.ToString(elapsed.TotalHours >= 1 ? @"h\:mm\:ss" : @"m\:ss");+ _title.Foreground = Red;+ _caption.Text = UiText.Get("MemoRecording");+ }+ else+ {+ _icon.Content = new System.Windows.Shapes.Ellipse { Width = 13, Height = 13, Fill = Red };+ _title.Text = UiText.Get("MemoTitle");+ _title.SetResourceReference(TextBlock.ForegroundProperty, "TextPrimary");+ _caption.Text = UiText.Get("MemoTapToRecord");+ }+ _tile.ToolTip = UiText.Get("MemoHint");+ }++ private void Toggle()+ {+ if (_popup.IsOpen)+ {+ _popup.Close();+ return;+ }+ Build();+ _popup.Toggle();+ }++ private void Build()+ {+ var root = new StackPanel();+ var folder = Ui.IconButton(Ui.Icon("IconFolderOpen", 13), (_, _) =>+ {+ Directory.CreateDirectory(Folder);+ Ui.Open(Folder);+ }, UiText.Get("MemoOpenFolder"));+ root.Children.Add(Ui.Header(UiText.Get("MemoTitle"), () => _popup.Close(), folder));+ var files = Directory.Exists(Folder)+ ? new DirectoryInfo(Folder).EnumerateFiles("*.wav").OrderByDescending(f => f.CreationTime).Take(6).ToList()+ : [];+ if (files.Count == 0)+ {+ var none = Ui.Text(UiText.Get("MemoNone"), 11.5, brushKey: "TextSecondary");+ none.TextWrapping = TextWrapping.Wrap;+ root.Children.Add(none);+ }+ foreach (var file in files)+ {+ var row = new DockPanel();+ var play = Ui.Glyph("GlyphPlay", 10);+ play.Margin = new Thickness(0, 0, 10, 0);+ DockPanel.SetDock(play, Dock.Left);+ var size = Ui.Text($"{file.Length / 1024.0 / 1024.0:0.0} MB", 10.5, brushKey: "TextSecondary");+ DockPanel.SetDock(size, Dock.Right);+ row.Children.Add(play);+ row.Children.Add(size);+ row.Children.Add(Ui.Text(Path.GetFileNameWithoutExtension(file.Name), 12, file.FullName == _last ? FontWeights.SemiBold : FontWeights.Normal));+ var open = new Button { Content = row, HorizontalContentAlignment = HorizontalAlignment.Stretch, Padding = new Thickness(6, 5, 6, 5) };+ open.SetResourceReference(FrameworkElement.StyleProperty, "WidgetIconButton");+ open.Width = double.NaN;+ open.Height = double.NaN;+ open.HorizontalAlignment = HorizontalAlignment.Stretch;+ var path = file.FullName;+ open.Click += (_, _) => Ui.Open(path);+ root.Children.Add(open);+ }+ _popup.SetContent(root, 320);+ }+}diff --git a/Widgets/WeatherWidget.cs b/Widgets/WeatherWidget.csnew file mode 100644index 0000000..0c0a945--- /dev/null+++ b/Widgets/WeatherWidget.cs@@ -0,0 +1,292 @@+using System.Globalization;+using System.Net.Http;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;+using QiDock.Services.Widgets;++namespace QiDock.Widgets;++/// <summary>Current weather tile; opens hourly and 7-day forecasts.</summary>+public sealed class WeatherWidget : DockWidget+{+ private readonly Button _tile;+ private readonly TextBlock _condition;+ private readonly TextBlock _city;+ private readonly TextBlock _temperature;+ private readonly ContentControl _icon;+ private readonly StackPanel _days;+ private readonly WidgetPopup _popup;+ private readonly DispatcherTimer _timer;+ private readonly WeatherService _service = new();+ private CancellationTokenSource? _load;+ private WeatherReport? _report;+ private string? _error;+ private string _city_ = "";++ public WeatherWidget()+ {+ // Left: the temperature, "Today" (or the city) under it. Right: the next three days (name, icon, high).+ _temperature = Ui.Text(size: 20, weight: FontWeights.SemiBold);+ _condition = Ui.Text(size: 10, brushKey: "TextSecondary");+ _condition.Margin = new Thickness(1, -3, 0, 0);+ _city = Ui.Text(size: 10, brushKey: "TextSecondary");+ _icon = new ContentControl { Width = 16, Height = 16, VerticalAlignment = VerticalAlignment.Center, IsHitTestVisible = false, Margin = new Thickness(5, 0, 0, 0) };+ var top = new StackPanel { Orientation = Orientation.Horizontal };+ top.Children.Add(_temperature);+ top.Children.Add(_icon);+ var left = new StackPanel { VerticalAlignment = VerticalAlignment.Center };+ left.Children.Add(top);+ left.Children.Add(_condition);++ _days = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(10, 0, 0, 0) };+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ row.Children.Add(left);+ row.Children.Add(_days);++ _tile = new Button { Content = row, Padding = new Thickness(12, 0, 10, 0) };+ _tile.SetResourceReference(FrameworkElement.StyleProperty, "WidgetTileButton");+ _tile.Click += (_, _) => TogglePopup();+ _popup = new WidgetPopup(_tile);++ _timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMinutes(15) };+ _timer.Tick += (_, _) => _ = RefreshAsync();+ UiText.Current.PropertyChanged += (_, _) => { Render(); _ = RefreshAsync(); };+ Render();+ }++ public override string Id => WidgetIds.Weather;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;++ public override void Start()+ {+ _timer.Start();+ _ = RefreshAsync();+ }++ public override void Stop()+ {+ _timer.Stop();+ _load?.Cancel();+ _popup.Close();+ }++ public override void ClosePopup() => _popup.Close();++ public override void ApplySettings(WidgetSettings settings)+ {+ var city = string.IsNullOrWhiteSpace(settings.WeatherCity) ? "İstanbul" : settings.WeatherCity.Trim();+ if (city == _city_) return;+ _city_ = city;+ _report = null;+ Render();+ _ = RefreshAsync();+ }++ private async Task RefreshAsync()+ {+ if (string.IsNullOrEmpty(_city_)) return;+ _load?.Cancel();+ var load = _load = new CancellationTokenSource();+ try+ {+ _report = await _service.FetchAsync(_city_, load.Token);+ _error = null;+ }+ catch (OperationCanceledException) when (load.IsCancellationRequested)+ {+ return;+ }+ catch (InvalidOperationException ex)+ {+ _error = ex.Message == "Şehir bulunamadı." ? UiText.Get("WxCityNotFound") : UiText.Get("WxUnavailable");+ }+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or System.Text.Json.JsonException or KeyNotFoundException or FormatException)+ {+ _error = UiText.Get("WxUnavailable");+ }++ Render();+ if (_popup.IsOpen) BuildPopup();+ }++ private static CultureInfo Culture => CultureInfo.GetCultureInfo(UiText.Get("CultureName"));++ private static string Degrees(double value) => double.IsFinite(value)+ ? Math.Round(value).ToString("0", CultureInfo.InvariantCulture) + "°" : "–";++ private void Render()+ {+ _days.Children.Clear();+ if (_report is { } report)+ {+ _temperature.Text = Degrees(report.Temperature);+ _icon.Content = WeatherArt.Create(report.Code, report.IsDay, 16);+ _condition.Text = UiText.Get("WxToday");+ _city.Text = report.City;+ foreach (var day in report.Days.Where(d => d.Date.Date > DateTime.Today).Take(3))+ _days.Children.Add(DayColumn(day));+ _tile.ToolTip = $"{report.City} · {WeatherService.Describe(report.Code)} · {Degrees(report.Temperature)}";+ }+ else+ {+ _temperature.Text = "–";+ _icon.Content = WeatherArt.Create(2, true, 16);+ _condition.Text = _error ?? (string.IsNullOrEmpty(_city_) ? UiText.Get("Weather") : _city_);+ _tile.ToolTip = _error;+ }+ }++ /// <summary>"Per", the day's icon and its high, stacked.</summary>+ private static FrameworkElement DayColumn(WeatherDay day)+ {+ var name = Ui.Text(day.Date.ToString("ddd", Culture), 9.5, FontWeights.SemiBold, brushKey: "TextSecondary");+ name.HorizontalAlignment = HorizontalAlignment.Center;+ var icon = WeatherArt.Create(day.Code, true, 14);+ icon.HorizontalAlignment = HorizontalAlignment.Center;+ icon.Margin = new Thickness(0, 1, 0, 1);+ var high = Ui.Text(Degrees(day.Max), 10, FontWeights.SemiBold);+ high.HorizontalAlignment = HorizontalAlignment.Center;+ var column = new StackPanel { Width = 32, VerticalAlignment = VerticalAlignment.Center };+ column.Children.Add(name);+ column.Children.Add(icon);+ column.Children.Add(high);+ return column;+ }++ private void TogglePopup()+ {+ if (!_popup.IsOpen)+ {+ BuildPopup();+ if (_report is null || DateTime.Now - _report.FetchedAt > TimeSpan.FromMinutes(10)) _ = RefreshAsync();+ }+ _popup.Toggle();+ }++ private void BuildPopup()+ {+ var culture = Culture;+ var root = new StackPanel();++ // Header: city + change link + close+ var header = new DockPanel { Margin = new Thickness(0, 0, 0, 8) };+ var close = Ui.IconButton(Ui.Icon("IconClose", 12), (_, _) => _popup.Close(), UiText.Get("Close"));+ DockPanel.SetDock(close, Dock.Right);+ header.Children.Add(close);+ var titleRow = new StackPanel { Orientation = Orientation.Horizontal };+ titleRow.Children.Add(Ui.Text(_report?.City ?? _city_, 13, FontWeights.SemiBold));+ var change = new Button { Content = UiText.Get("WxChangeCity"), Margin = new Thickness(4, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center };+ change.SetResourceReference(FrameworkElement.StyleProperty, "WidgetLinkButton");+ change.Click += (_, _) => { _popup.Close(); RequestSettings(); };+ titleRow.Children.Add(change);+ header.Children.Add(titleRow);+ root.Children.Add(header);++ if (_report is not { } report)+ {+ root.Children.Add(Ui.Text(_error ?? UiText.Get("WxLoading"), 12, brushKey: _error is null ? "TextSecondary" : "DangerText"));+ _popup.SetContent(root, 360);+ return;+ }++ // Current conditions+ var now = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 2) };+ now.Children.Add(WeatherArt.Create(report.Code, report.IsDay, 40));+ var nowTemp = Ui.Text(Degrees(report.Temperature), 34, FontWeights.Light);+ nowTemp.Margin = new Thickness(10, 0, 0, 0);+ now.Children.Add(nowTemp);+ root.Children.Add(now);+ root.Children.Add(Ui.Text($"{WeatherService.Describe(report.Code)} · {UiText.Get("WxHigh")} {Degrees(report.TodayMax)} {UiText.Get("WxLow")} {Degrees(report.TodayMin)}",+ 11.5, brushKey: "TextSecondary"));++ // Hourly strip+ var hours = new Grid();+ for (var i = 0; i < report.Hours.Count; i++)+ {+ hours.ColumnDefinitions.Add(new ColumnDefinition());+ var hour = report.Hours[i];+ var cell = new StackPanel { HorizontalAlignment = HorizontalAlignment.Center };+ var label = Ui.Text(i == 0 ? UiText.Get("WxNow") : hour.Time.ToString("HH:mm", culture), 10.5, i == 0 ? FontWeights.SemiBold : FontWeights.Normal, "TextSecondary");+ label.HorizontalAlignment = HorizontalAlignment.Center;+ cell.Children.Add(label);+ var icon = WeatherArt.Create(hour.Code, hour.IsDay, 22);+ icon.Margin = new Thickness(0, 4, 0, 4);+ cell.Children.Add(icon);+ var temp = Ui.Text(Degrees(hour.Temperature), 12, FontWeights.SemiBold);+ temp.HorizontalAlignment = HorizontalAlignment.Center;+ cell.Children.Add(temp);+ Grid.SetColumn(cell, i);+ hours.Children.Add(cell);+ }+ // Hourly strip sits on its own lighter panel, like the daily list's header.+ var hourPanel = new Border { CornerRadius = new CornerRadius(12), Padding = new Thickness(4, 8, 4, 8), Margin = new Thickness(0, 12, 0, 10), Child = hours };+ hourPanel.SetResourceReference(Border.BackgroundProperty, "WidgetTileFill");+ root.Children.Add(hourPanel);++ // 7-day list with temperature range bars+ var weekMin = report.Days.Where(d => double.IsFinite(d.Min)).Select(d => d.Min).DefaultIfEmpty(0).Min();+ var weekMax = report.Days.Where(d => double.IsFinite(d.Max)).Select(d => d.Max).DefaultIfEmpty(1).Max();+ var span = Math.Max(1, weekMax - weekMin);+ foreach (var (day, index) in report.Days.Select((d, i) => (d, i)))+ {+ var row = new Grid { Height = 30 };+ row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(62) });+ row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(34) });+ row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(40) });+ row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });+ row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(40) });++ var name = index == 0 ? UiText.Get("CalToday") : culture.TextInfo.ToTitleCase(day.Date.ToString("ddd", culture));+ row.Children.Add(Ui.Text(name, 12.5, index == 0 ? FontWeights.SemiBold : FontWeights.Normal));+ var icon = WeatherArt.Create(day.Code, true, 20);+ icon.HorizontalAlignment = HorizontalAlignment.Left;+ icon.ToolTip = WeatherService.Describe(day.Code);+ Grid.SetColumn(icon, 1);+ row.Children.Add(icon);+ var min = Ui.Text(Degrees(day.Min), 12, brushKey: "TextSecondary");+ min.HorizontalAlignment = HorizontalAlignment.Right;+ min.Margin = new Thickness(0, 0, 8, 0);+ Grid.SetColumn(min, 2);+ row.Children.Add(min);++ var track = new Grid { Height = 5, VerticalAlignment = VerticalAlignment.Center };+ var trackBg = new Border { CornerRadius = new CornerRadius(2.5) };+ trackBg.SetResourceReference(Border.BackgroundProperty, "WidgetTrack");+ track.Children.Add(trackBg);+ var range = new Border+ {+ CornerRadius = new CornerRadius(2.5),+ Background = new LinearGradientBrush(Color.FromRgb(0x5A, 0xC8, 0xFA), Color.FromRgb(0xFF, 0xB3, 0x40), 0),+ HorizontalAlignment = HorizontalAlignment.Left+ };+ track.Children.Add(range);+ var startRatio = double.IsFinite(day.Min) ? (day.Min - weekMin) / span : 0;+ var endRatio = double.IsFinite(day.Max) ? (day.Max - weekMin) / span : 1;+ track.SizeChanged += (_, e) =>+ {+ range.Margin = new Thickness(e.NewSize.Width * startRatio, 0, 0, 0);+ range.Width = Math.Max(5, e.NewSize.Width * Math.Max(0, endRatio - startRatio));+ };+ Grid.SetColumn(track, 3);+ row.Children.Add(track);++ var max = Ui.Text(Degrees(day.Max), 12, FontWeights.SemiBold);+ max.HorizontalAlignment = HorizontalAlignment.Right;+ Grid.SetColumn(max, 4);+ row.Children.Add(max);+ root.Children.Add(row);+ }++ var footer = Ui.Text(UiText.Format("WxUpdated", report.FetchedAt.ToString("HH:mm", culture)), 10.5, brushKey: "TextSecondary");+ footer.Margin = new Thickness(0, 6, 0, 0);+ footer.Opacity = 0.8;+ root.Children.Add(footer);++ _popup.SetContent(root, 360);+ }+}diff --git a/Widgets/WidgetBar.cs b/Widgets/WidgetBar.csnew file mode 100644index 0000000..196c9b4--- /dev/null+++ b/Widgets/WidgetBar.cs@@ -0,0 +1,308 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Media.Animation;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>+/// Hosts the enabled widgets next to the dock icons, in the user's order. In edit mode the widgets+/// wiggle and each gets ‹ × › controls (move left, remove, move right), plus "Add" and "Done" pills.+/// </summary>+public sealed class WidgetBar : StackPanel, IDisposable+{+ private readonly Dictionary<string, DockWidget> _widgets;+ private readonly HashSet<string> _started = [];+ private readonly List<Grid> _wrappers = [];+ private WidgetSettings _settings = new();+ private string _signature = "";++ public event EventHandler? LayoutInvalidated;+ public event EventHandler? SettingsRequested;++ /// <summary>Raised in edit mode with the new widget settings (order or hidden list changed).</summary>+ public event EventHandler<WidgetSettings>? SettingsEdited;++ /// <summary>Raised when the user asks for the "add widget" menu; the argument is the anchor element.</summary>+ public event EventHandler<FrameworkElement>? AddRequested;++ public event EventHandler? EditingChanged;++ /// <summary>Right-click on a profile tab: the argument is the profile index and the tab.</summary>+ public event EventHandler<(int Index, FrameworkElement Anchor)>? ProfileMenuRequested;++ /// <summary>The profile tile was clicked; the argument is the tile.</summary>+ public event EventHandler<FrameworkElement>? ProfilesRequested;++ /// <summary>Profile tabs ("Varsayılan", "İş", "+"), shown under the bar by its window.</summary>+ public StackPanel ProfileStrip { get; } = new() { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Center };++ private void BuildProfileStrip()+ {+ ProfileStrip.Children.Clear();+ var profiles = _settings.EffectiveProfiles;+ var active = _settings.EffectiveActiveProfile;+ for (var index = 0; index < profiles.Count; index++)+ {+ var position = index;+ // The name and, for the first nine, its shortcut (Ctrl+Alt+Shift+1…9) in a small key cap.+ var content = new StackPanel { Orientation = Orientation.Horizontal };+ content.Children.Add(new TextBlock { Text = profiles[index].Name, VerticalAlignment = VerticalAlignment.Center });+ if (index < 9)+ {+ var cap = new Border+ {+ CornerRadius = new CornerRadius(5),+ Padding = new Thickness(4, 0, 4, 1),+ Margin = new Thickness(7, 0, -4, 0),+ Background = Ui.Solid("#26808080"),+ VerticalAlignment = VerticalAlignment.Center,+ Child = new TextBlock { Text = "⌃⌥⇧" + (index + 1), FontSize = 9.5, FontWeight = FontWeights.Normal, Opacity = 0.8 }+ };+ content.Children.Add(cap);+ }+ var tab = new System.Windows.Controls.Primitives.ToggleButton { Content = content, IsChecked = index == active, ToolTip = index < 9 ? UiText.Format("ProfileShortcut", index + 1) : null };+ tab.SetResourceReference(FrameworkElement.StyleProperty, "WidgetProfileTab");+ tab.Click += (_, _) =>+ {+ tab.IsChecked = position == _settings.EffectiveActiveProfile;+ if (position != _settings.EffectiveActiveProfile) SettingsEdited?.Invoke(this, _settings.SwitchProfile(position));+ };+ tab.MouseRightButtonUp += (_, e) =>+ {+ e.Handled = true;+ ProfileMenuRequested?.Invoke(this, (position, tab));+ };+ ProfileStrip.Children.Add(tab);+ }+ var addContent = new StackPanel { Orientation = Orientation.Horizontal };+ var plus = Ui.Icon("IconPlus", 11, brushKey: null);+ plus.SetResourceReference(System.Windows.Shapes.Shape.StrokeProperty, "TextSecondary");+ plus.Margin = new Thickness(0, 0, 6, 0);+ plus.VerticalAlignment = VerticalAlignment.Center;+ addContent.Children.Add(plus);+ addContent.Children.Add(new TextBlock { Text = UiText.Get("ProfileCreate"), VerticalAlignment = VerticalAlignment.Center });+ var add = new System.Windows.Controls.Primitives.ToggleButton { Content = addContent, ToolTip = UiText.Get("ProfileAdd") };+ add.SetResourceReference(FrameworkElement.StyleProperty, "WidgetProfileTab");+ add.Click += (_, _) =>+ {+ add.IsChecked = false;+ SettingsEdited?.Invoke(this, _settings.AddProfile(UiText.Format("ProfileNew", _settings.EffectiveProfiles.Count + 1)));+ };+ ProfileStrip.Children.Add(add);+ }++ public WidgetBar()+ {+ Orientation = Orientation.Horizontal;+ VerticalAlignment = VerticalAlignment.Center;++ DockWidget[] all =+ [+ new MediaWidget(), new WeatherWidget(), new ClockWidget(), new BatteryWidget(), new AiLimitsWidget(), new SystemWidget(), new QuickControlsWidget(),+ new FolderWidget(), new SearchWidget(), new ColorsWidget(), new AppVolumeWidget(), new FocusWidget(), new WorldClockWidget(),+ new TodoWidget(), new ToolsWidget(), new ProfileWidget(), new CurrencyWidget(), new StopwatchWidget(), new NoteWidget(),+ new AppGroupWidget(), new ProgressWidget(), new ReminderWidget(), new VoiceMemoWidget(), new TrayWidget(),+ new NotificationsWidget(), new ControlCenterWidget()+ ];+ _widgets = all.ToDictionary(w => w.Id);+ foreach (var widget in all)+ {+ widget.LayoutChanged += (_, _) => LayoutInvalidated?.Invoke(this, EventArgs.Empty);+ widget.SettingsRequested += (_, _) => SettingsRequested?.Invoke(this, EventArgs.Empty);+ widget.SettingsUpdateRequested += (_, change) => SettingsEdited?.Invoke(this, change(_settings));+ if (widget is ProfileWidget profile) profile.MenuRequested += (_, anchor) => ProfilesRequested?.Invoke(this, anchor);+ }+ SizeChanged += (_, e) =>+ {+ if (Math.Abs(e.NewSize.Width - e.PreviousSize.Width) > 0.5) LayoutInvalidated?.Invoke(this, EventArgs.Empty);+ };+ }++ public bool IsAnyPopupOpen => _widgets.Values.Any(w => w.IsPopupOpen);++ public bool HasVisibleWidgets => Children.Count > 0;++ private bool _live = true;++ /// <summary>+ /// Off while the bar is hidden: widgets drop their fast timers (clock, CPU/RAM, volume) and catch+ /// up the moment the bar is back on screen. Slow refreshes (weather, limits) keep running.+ /// </summary>+ public void SetLive(bool live)+ {+ if (_live == live) return;+ _live = live;+ foreach (var id in _started) _widgets[id].SetLive(live);+ }++ public bool IsEditing { get; private set; }++ public void SetEditing(bool editing)+ {+ if (IsEditing == editing) return;+ IsEditing = editing;+ ClosePopups();+ _signature = "";+ Apply(_settings);+ EditingChanged?.Invoke(this, EventArgs.Empty);+ }++ public void Apply(WidgetSettings settings)+ {+ _settings = settings;+ var visible = settings.VisibleWidgets.ToList();+ var signature = string.Join(",", visible) + (IsEditing ? "|edit" : "");+ if (signature != _signature)+ {+ _signature = signature;+ Children.Clear();+ foreach (var wrapper in _wrappers) wrapper.Children.Clear();+ _wrappers.Clear();+ foreach (var widget in _widgets.Values.Where(w => !visible.Contains(w.Id)))+ {+ widget.Stop();+ _started.Remove(widget.Id);+ }+ for (var index = 0; index < visible.Count; index++)+ {+ var widget = _widgets[visible[index]];+ widget.View.IsHitTestVisible = !IsEditing;+ Children.Add(IsEditing ? Wrap(widget, index, visible.Count) : widget.View);+ if (_started.Add(widget.Id))+ {+ widget.Start();+ if (!_live) widget.SetLive(false);+ }+ }+ if (IsEditing)+ {+ var add = Pill(UiText.Get("EditAddWidget"), "IconPlus", accent: false);+ add.Click += (_, _) => AddRequested?.Invoke(this, add);+ add.IsEnabled = visible.Count < WidgetIds.All.Count;+ Children.Add(add);+ var done = Pill(UiText.Get("EditDone"), "IconCheck", accent: true);+ done.Click += (_, _) => SetEditing(false);+ Children.Add(done);+ }+ LayoutInvalidated?.Invoke(this, EventArgs.Empty);+ }++ BuildProfileStrip();+ foreach (var widget in _widgets.Values)+ {+ widget.Current = settings;+ widget.ApplySettings(settings);+ }+ }++ /// <summary>Shows a hidden widget again (from the add menu), keeping its place in the order.</summary>+ public void ShowWidget(string id) =>+ SettingsEdited?.Invoke(this, _settings with { Hidden = (_settings.Hidden ?? []).Where(h => h != id).ToList() });++ private Grid Wrap(DockWidget widget, int index, int count)+ {+ var host = new Grid { RenderTransformOrigin = new Point(0.5, 0.5), Margin = new Thickness(0, 0, 0, 0) };+ host.Children.Add(widget.View);++ var controls = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ controls.Children.Add(RoundButton("IconChevronLeft", UiText.Get("EditMoveLeft"), index > 0, () => Move(widget.Id, -1)));+ controls.Children.Add(RoundButton("IconClose", UiText.Get("EditRemove"), true, () => Hide(widget.Id), danger: true));+ controls.Children.Add(RoundButton("IconChevronRight", UiText.Get("EditMoveRight"), index < count - 1, () => Move(widget.Id, 1)));+ var shade = new Border+ {+ CornerRadius = new CornerRadius(12),+ Background = Ui.Solid("#8C0B0D12"),+ BorderBrush = Ui.Solid("#59FFFFFF"),+ BorderThickness = new Thickness(1),+ Margin = new Thickness(2, 0, 2, 0),+ Child = controls+ };+ host.Children.Add(shade);++ // The tiles wiggle while editing.+ var rotate = new RotateTransform();+ host.RenderTransform = rotate;+ var wiggle = new DoubleAnimation(-0.9, 0.9, TimeSpan.FromMilliseconds(130 + index * 9))+ {+ AutoReverse = true,+ RepeatBehavior = RepeatBehavior.Forever,+ BeginTime = TimeSpan.FromMilliseconds(index * 37)+ };+ rotate.BeginAnimation(RotateTransform.AngleProperty, wiggle);+ _wrappers.Add(host);+ return host;+ }++ private void Move(string id, int delta)+ {+ var order = _settings.EffectiveOrder.ToList();+ var visible = _settings.VisibleWidgets.ToList();+ var position = visible.IndexOf(id);+ var target = position + delta;+ if (position < 0 || target < 0 || target >= visible.Count) return;+ // Swap with the neighbouring visible widget inside the full order (hidden ones keep their slots).+ var a = order.IndexOf(id);+ var b = order.IndexOf(visible[target]);+ (order[a], order[b]) = (order[b], order[a]);+ SettingsEdited?.Invoke(this, _settings with { Order = order });+ }++ private void Hide(string id) =>+ SettingsEdited?.Invoke(this, _settings with { Hidden = (_settings.Hidden ?? []).Append(id).Distinct().ToList() });++ private static Button RoundButton(string icon, string tooltip, bool enabled, Action click, bool danger = false)+ {+ var face = new Border+ {+ Width = 24,+ Height = 24,+ CornerRadius = new CornerRadius(12),+ Background = danger ? Ui.Solid("#E6FF453A") : Ui.Solid("#E62C2F36"),+ BorderBrush = Ui.Solid("#66FFFFFF"),+ BorderThickness = new Thickness(1),+ Child = Ui.Icon(icon, 11, Brushes.White, stroke: 2.4)+ };+ var button = new Button { Content = face, Width = 28, Height = 28, Margin = new Thickness(1, 0, 1, 0), IsEnabled = enabled, ToolTip = tooltip, Cursor = Cursors.Hand };+ button.SetResourceReference(FrameworkElement.StyleProperty, "WidgetIconButton");+ System.Windows.Automation.AutomationProperties.SetName(button, tooltip);+ button.Click += (_, e) =>+ {+ e.Handled = true;+ click();+ };+ return button;+ }++ /// <summary>Compact round edit-mode button (icon only, label in the tooltip) so the dock still fits.</summary>+ private static Button Pill(string text, string icon, bool accent)+ {+ var face = new Border+ {+ Width = 30,+ Height = 30,+ CornerRadius = new CornerRadius(15),+ Background = accent ? Ui.Vertical("#FF4DA3FF", "#FF1F78F0") : Ui.Solid("#40FFFFFF"),+ BorderBrush = Ui.Solid("#66FFFFFF"),+ BorderThickness = new Thickness(1),+ Child = Ui.Icon(icon, 13, Brushes.White, stroke: 2.4)+ };+ var button = new Button { Content = face, Width = 34, Height = 34, Margin = new Thickness(2, 0, 0, 0), Cursor = Cursors.Hand, VerticalAlignment = VerticalAlignment.Center, ToolTip = text };+ button.SetResourceReference(FrameworkElement.StyleProperty, "WidgetIconButton");+ System.Windows.Automation.AutomationProperties.SetName(button, text);+ return button;+ }++ public void ClosePopups()+ {+ foreach (var widget in _widgets.Values) widget.ClosePopup();+ }++ public void Dispose()+ {+ foreach (var widget in _widgets.Values) widget.Dispose();+ }+}diff --git a/Widgets/WidgetUi.cs b/Widgets/WidgetUi.csnew file mode 100644index 0000000..6e72426--- /dev/null+++ b/Widgets/WidgetUi.cs@@ -0,0 +1,591 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Shapes;+using QiDock.Models;+using QiDock.Services.Widgets;++namespace QiDock.Widgets;++/// <summary>A widget shown in the dock: a tile plus optional popup.</summary>+public abstract class DockWidget : IDisposable+{+ public abstract string Id { get; }+ public abstract FrameworkElement View { get; }+ public virtual bool IsPopupOpen => false;++ /// <summary>Raised when the tile's width or visibility changes so the dock can resize.</summary>+ public event EventHandler? LayoutChanged;++ /// <summary>Raised when the widget wants the settings window (for example "change city").</summary>+ public event EventHandler? SettingsRequested;++ public virtual void Start() { }+ public virtual void Stop() { }+ public virtual void ApplySettings(WidgetSettings settings) { }+ public virtual void ClosePopup() { }++ /// <summary>Pauses (false) or resumes (true) per-second work while the widget is off screen.</summary>+ public virtual void SetLive(bool live) { }++ /// <summary>The widget settings last applied (kept by the bar before <see cref="ApplySettings"/>).</summary>+ public WidgetSettings Current { get; internal set; } = new();++ /// <summary>Raised with a change to the widget settings (to-dos, colors, shelf…); the bar saves it.</summary>+ public event EventHandler<Func<WidgetSettings, WidgetSettings>>? SettingsUpdateRequested;++ protected void UpdateSettings(Func<WidgetSettings, WidgetSettings> change) => SettingsUpdateRequested?.Invoke(this, change);+ public virtual void Dispose() => Stop();++ protected void RaiseLayoutChanged() => LayoutChanged?.Invoke(this, EventArgs.Empty);+ protected void RequestSettings() => SettingsRequested?.Invoke(this, EventArgs.Empty);+}++/// <summary>+/// Popup anchored centered above a dock tile. The dock window never takes activation, so WPF's+/// StaysOpen=false capture is unreliable here (it drops when content changes). Instead the popup+/// stays open and closes itself when a mouse button goes down outside the card and its tile.+/// </summary>+public sealed class WidgetPopup+{+ private readonly Popup _popup;+ private readonly FrameworkElement _target;+ private readonly Border _surface;+ private readonly System.Windows.Threading.DispatcherTimer _outsideClickWatch = new(System.Windows.Threading.DispatcherPriority.Input)+ {+ Interval = TimeSpan.FromMilliseconds(40)+ };+ private bool _buttonWasDown;+ private UIElement? _content;+ private double _width, _sheetWidth;+ private DockSheet? _sheet;+ public event EventHandler? Opened;++ /// <summary>The card closed (from its popup or from the dock sheet).</summary>+ public event EventHandler? Closed;++ /// <summary>Any widget card opened (the bar hides its profile tabs so they do not cover it).</summary>+ public static event EventHandler? AnyOpened;++ public WidgetPopup(FrameworkElement target)+ {+ _target = target;+ // Placement=Top aligns the popup window's bottom with the tile's top. The window must not overlap+ // the tile (it would swallow clicks meant for it), so the card's bottom margin is the gap.+ _popup = new Popup+ {+ AllowsTransparency = true,+ StaysOpen = true,+ Placement = PlacementMode.Top,+ PlacementTarget = target,+ PopupAnimation = PopupAnimation.Fade,+ VerticalOffset = 0+ };+ _surface = new Border { Style = (Style)Application.Current.FindResource("WidgetPopupSurface") };+ _surface.Margin = new Thickness(18, 18, 18, 10);+ _popup.Child = _surface;+ _popup.Opened += (_, _) =>+ {+ _buttonWasDown = AnyButtonDown();+ _outsideClickWatch.Start();+ Opened?.Invoke(this, EventArgs.Empty);+ AnyOpened?.Invoke(this, EventArgs.Empty);+ };+ _popup.Closed += (_, _) =>+ {+ _outsideClickWatch.Stop();+ Closed?.Invoke(this, EventArgs.Empty);+ };+ // Keep the card centered above the tile when its size changes while open.+ _surface.SizeChanged += (_, _) =>+ {+ Center();+ if (!_popup.IsOpen) return;+ _popup.VerticalOffset = 0.01;+ _popup.VerticalOffset = 0;+ };+ _outsideClickWatch.Tick += (_, _) => WatchOutsideClick();+ }++ public bool IsOpen => _popup.IsOpen || _sheet?.IsOpen == true;++ /// <summary>Replaces the popup body; the styled surface stays in place.</summary>+ public void SetContent(UIElement content, double width)+ {+ _content = content;+ _width = width;+ _surface.Width = width;+ if (_sheet?.IsVisible == true) _sheet.Body = content;+ else+ {+ if (_sheet is not null) _sheet.Body = null;+ _surface.Child = content;+ }+ Center();+ }++ /// <summary>+ /// While the widget sits in the dock its card grows out of the dock like the bell's list. Returns false when+ /// the tile is not in the dock (the card then opens as a popup).+ /// </summary>+ private bool ToggleSheet()+ {+ if (_sheet?.IsOpen == true)+ {+ _sheet.Close(animated: true);+ return true;+ }+ if (_popup.IsOpen || _content is null || EdgePanel.DockAnchorFor(_target) is not { } anchor) return false;+ if (_sheet is null || Math.Abs(_sheetWidth - _width) > 0.5)+ {+ _sheet?.Close();+ var sheet = new DockSheet(_width);+ _sheet = sheet;+ _sheetWidth = _width;+ sheet.SheetOpened += (_, _) =>+ {+ Opened?.Invoke(this, EventArgs.Empty);+ AnyOpened?.Invoke(this, EventArgs.Empty);+ };+ sheet.SheetHidden += (_, _) => Closed?.Invoke(this, EventArgs.Empty);+ }+ _surface.Child = null;+ _sheet.Body = _content;+ _sheet.ToggleFromDock(anchor);+ return true;+ }++#if DEBUG+ /// <summary>Debug snapshot run: Toggle records the popup here instead of opening it.</summary>+ internal static List<WidgetPopup>? Rehearsal;++ /// <summary>Debug snapshot run: takes the card out of its popup so it can be drawn to a picture.</summary>+ internal Border DetachSurface()+ {+ _popup.Child = null;+ _surface.Margin = new Thickness(0);+ return _surface;+ }+#endif++ public void Toggle()+ {+#if DEBUG+ if (Rehearsal is not null)+ {+ Rehearsal.Add(this);+ return;+ }+#endif+ if (ToggleSheet()) return;+ if (!_popup.IsOpen)+ {+ if (_surface.Child is null && _content is not null)+ {+ if (_sheet is not null) _sheet.Body = null;+ _surface.Child = _content;+ }+ var below = Window.GetWindow(_target) is { } window && window.Top < SystemParameters.WorkArea.Height / 2;+ _popup.Placement = below ? PlacementMode.Bottom : PlacementMode.Top;+ _surface.Margin = below ? new Thickness(18, 10, 18, 18) : new Thickness(18, 18, 18, 10);+ Center();+ }+ _popup.IsOpen = !_popup.IsOpen;+ }++ public void Close()+ {+ _popup.IsOpen = false;+ if (_sheet?.IsOpen == true) _sheet.Close(animated: true);+ }++ /// <summary>+ /// The bar never takes focus by itself; a popup with a text box asks for it so typing works.+ /// Allowed because the user just clicked our window.+ /// </summary>+ public void FocusInput(IInputElement element)+ {+ Window? owner = _sheet?.IsOpen == true ? _sheet : Window.GetWindow(_target);+ if (owner is not null && PresentationSource.FromVisual(owner) is System.Windows.Interop.HwndSource source)+ SetForegroundWindow(source.Handle);+ _popup.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input, () => Keyboard.Focus(element));+ }++ [System.Runtime.InteropServices.DllImport("user32.dll")]+ [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]+ private static extern bool SetForegroundWindow(nint window);++ private void Center()+ {+ _surface.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));+ _popup.HorizontalOffset = (_target.ActualWidth - _surface.DesiredSize.Width) / 2;+ }++ private void WatchOutsideClick()+ {+ var down = AnyButtonDown();+ var pressed = down && !_buttonWasDown;+ _buttonWasDown = down;+ if (!pressed || !GetCursorPos(out var cursor)) return;+ // The tile handles its own click (toggle); clicks inside the card are the card's.+ if (Contains(_surface, cursor) || Contains(_target, cursor)) return;+ _popup.IsOpen = false;+ }++ private static bool Contains(FrameworkElement element, NativePoint cursor)+ {+ if (PresentationSource.FromVisual(element) is null || element.ActualWidth <= 0) return false;+ var topLeft = element.PointToScreen(new Point(0, 0));+ var bottomRight = element.PointToScreen(new Point(element.ActualWidth, element.ActualHeight));+ return cursor.X >= topLeft.X && cursor.X <= bottomRight.X && cursor.Y >= topLeft.Y && cursor.Y <= bottomRight.Y;+ }++ private static bool AnyButtonDown() =>+ (GetAsyncKeyState(0x01) & 0x8000) != 0 || (GetAsyncKeyState(0x02) & 0x8000) != 0 || (GetAsyncKeyState(0x04) & 0x8000) != 0;++ [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]+ private struct NativePoint { public int X, Y; }++ [System.Runtime.InteropServices.DllImport("user32.dll")]+ private static extern short GetAsyncKeyState(int key);++ [System.Runtime.InteropServices.DllImport("user32.dll")]+ [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]+ private static extern bool GetCursorPos(out NativePoint point);+}++internal static class Ui+{+ public static Brush Freeze(Brush brush)+ {+ brush.Freeze();+ return brush;+ }++ public static SolidColorBrush Solid(byte a, byte r, byte g, byte b) => (SolidColorBrush)Freeze(new SolidColorBrush(Color.FromArgb(a, r, g, b)));+ public static SolidColorBrush Solid(string hex) => (SolidColorBrush)Freeze(new SolidColorBrush((Color)ColorConverter.ConvertFromString(hex)));++ public static LinearGradientBrush Vertical(string top, string bottom) => (LinearGradientBrush)Freeze(new LinearGradientBrush(+ (Color)ColorConverter.ConvertFromString(top), (Color)ColorConverter.ConvertFromString(bottom), 90));++ public static LinearGradientBrush Diagonal(Color from, Color to) => (LinearGradientBrush)Freeze(new LinearGradientBrush(from, to, new Point(0, 0), new Point(1, 1)));++ public static readonly Brush White = Brushes.White;+ public static readonly Brush WhiteSoft = Solid(0xD9, 0xFF, 0xFF, 0xFF);++ public static TextBlock Text(string text = "", double size = 12, FontWeight? weight = null, string? brushKey = "TextPrimary", Brush? brush = null)+ {+ var block = new TextBlock+ {+ Text = text,+ FontSize = size,+ FontWeight = weight ?? FontWeights.Normal,+ TextTrimming = TextTrimming.CharacterEllipsis,+ VerticalAlignment = VerticalAlignment.Center+ };+ if (brush is not null) block.Foreground = brush;+ else if (brushKey is not null) block.SetResourceReference(TextBlock.ForegroundProperty, brushKey);+ return block;+ }++ /// <summary>Lucide-style outline icon.</summary>+ public static Path Icon(string geometryKey, double size, Brush? brush = null, string? brushKey = "TextPrimary", double stroke = 1.9)+ {+ var path = new Path+ {+ Data = (Geometry)Application.Current.FindResource(geometryKey),+ Width = size,+ Height = size,+ Stretch = Stretch.Uniform,+ StrokeThickness = stroke,+ StrokeStartLineCap = PenLineCap.Round,+ StrokeEndLineCap = PenLineCap.Round,+ StrokeLineJoin = PenLineJoin.Round,+ VerticalAlignment = VerticalAlignment.Center,+ HorizontalAlignment = HorizontalAlignment.Center,+ SnapsToDevicePixels = true+ };+ if (brush is not null) path.Stroke = brush;+ else if (brushKey is not null) path.SetResourceReference(Shape.StrokeProperty, brushKey);+ return path;+ }++ /// <summary>Solid glyph (play, pause, bolt…).</summary>+ public static Path Glyph(string geometryKey, double size, Brush? brush = null, string? brushKey = "TextPrimary")+ {+ var path = new Path+ {+ Data = (Geometry)Application.Current.FindResource(geometryKey),+ Width = size,+ Height = size,+ Stretch = Stretch.Uniform,+ VerticalAlignment = VerticalAlignment.Center,+ HorizontalAlignment = HorizontalAlignment.Center+ };+ if (brush is not null) path.Fill = brush;+ else if (brushKey is not null) path.SetResourceReference(Shape.FillProperty, brushKey);+ return path;+ }++ public static Button IconButton(UIElement content, RoutedEventHandler click, string? tooltip = null, double width = 26, double height = 24)+ {+ var button = new Button { Content = content, Width = width, Height = height, ToolTip = tooltip };+ button.SetResourceReference(FrameworkElement.StyleProperty, "WidgetIconButton");+ button.Click += click;+ if (tooltip is not null) System.Windows.Automation.AutomationProperties.SetName(button, tooltip);+ return button;+ }++ /// <summary>Thin rounded progress bar.</summary>+ public static Grid Bar(double percent, double width, double height, Brush fill)+ {+ var grid = new Grid { Width = width, Height = height, VerticalAlignment = VerticalAlignment.Center };+ var track = new Border { CornerRadius = new CornerRadius(height / 2) };+ track.SetResourceReference(Border.BackgroundProperty, "WidgetTrack");+ grid.Children.Add(track);+ grid.Children.Add(new Border+ {+ CornerRadius = new CornerRadius(height / 2),+ Background = fill,+ HorizontalAlignment = HorizontalAlignment.Left,+ Width = Math.Max(percent > 0 ? height : 0, width * Math.Clamp(percent, 0, 100) / 100)+ });+ return grid;+ }++ private static readonly Brush UsageLow = Solid("#FF32D74B");+ private static readonly Brush UsageMedium = Solid("#FFFFD60A");+ private static readonly Brush UsageHigh = Solid("#FFFF9F0A");+ private static readonly Brush UsageCritical = Solid("#FFFF453A");++ /// <summary>Load colour: green when low, yellow in the middle, orange when high, red when nearly full.</summary>+ public static Brush UsageBrush(double percent) => percent switch+ {+ >= 85 => UsageCritical,+ >= 70 => UsageHigh,+ >= 50 => UsageMedium,+ _ => UsageLow+ };++ /// <summary>Short message pill at the top of the screen (set by the main window).</summary>+ public static Action<string, string>? HudHandler { get; set; }++ public static void ShowHud(string iconKey, string text) => HudHandler?.Invoke(iconKey, text);++ /// <summary>Shell icon of a file, folder or app as an image.</summary>+ public static FrameworkElement FileIcon(string path, double size)+ {+ var source = QiDock.Services.ApplicationIconProvider.GetForFile(path);+ if (source is null) return Icon(System.IO.Directory.Exists(path) ? "IconFolder" : "IconFile", size * 0.8);+ return new Image { Source = source, Width = size, Height = size, Stretch = Stretch.Uniform };+ }++ /// <summary>Popup title row: title on the left, extra buttons and a close button on the right.</summary>+ public static DockPanel Header(string title, Action close, params UIElement[] buttons)+ {+ var header = new DockPanel { Margin = new Thickness(0, 0, 0, 10), LastChildFill = true };+ var right = new StackPanel { Orientation = Orientation.Horizontal };+ foreach (var button in buttons) right.Children.Add(button);+ right.Children.Add(IconButton(Icon("IconClose", 12), (_, _) => close(), QiDock.Services.UiText.Get("Close")));+ DockPanel.SetDock(right, Dock.Right);+ header.Children.Add(right);+ header.Children.Add(Text(title, 13, FontWeights.SemiBold));+ return header;+ }++ /// <summary>+ /// A scroll area without a scroll bar (the wheel still scrolls): while more content follows below,+ /// the bottom edge fades out instead of cutting the last row off.+ /// </summary>+ public static ScrollViewer FadingScroller(FrameworkElement content, double maxHeight)+ {+ var scroller = new ScrollViewer+ {+ Content = content,+ MaxHeight = maxHeight,+ VerticalScrollBarVisibility = ScrollBarVisibility.Hidden,+ HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled+ };+ var fade = (Brush)Freeze(new LinearGradientBrush(+ [new GradientStop(Colors.Black, 0), new GradientStop(Colors.Black, 1 - 28 / maxHeight), new GradientStop(Colors.Transparent, 1)],+ new Point(0, 0), new Point(0, 1)));+ void Update() => scroller.OpacityMask = scroller.VerticalOffset < scroller.ScrollableHeight - 1 ? fade : null;+ scroller.ScrollChanged += (_, _) => Update();+ scroller.Loaded += (_, _) => Update();+ return scroller;+ }++ public static Button Pill(string text, RoutedEventHandler click, string? iconKey = null)+ {+ UIElement content = Text(text, 11.5, FontWeights.SemiBold);+ if (iconKey is not null)+ {+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ var icon = Icon(iconKey, 12);+ icon.Margin = new Thickness(0, 0, 6, 0);+ row.Children.Add(icon);+ row.Children.Add(content);+ content = row;+ }+ var button = new Button { Content = content, Height = 28 };+ button.SetResourceReference(FrameworkElement.StyleProperty, "WidgetPillButton");+ button.Click += click;+ return button;+ }++ public static Button Tile(UIElement content, RoutedEventHandler click, double horizontalPadding = 10)+ {+ var tile = new Button { Content = content, Padding = new Thickness(horizontalPadding, 0, horizontalPadding, 0) };+ tile.SetResourceReference(FrameworkElement.StyleProperty, "WidgetTileButton");+ tile.Click += click;+ return tile;+ }++ /// <summary>"3 dk önce", "2 gün önce"…</summary>+ public static string Ago(DateTime time)+ {+ var span = DateTime.Now - time;+ if (span.TotalMinutes < 1) return QiDock.Services.UiText.Get("AgoNow");+ if (span.TotalHours < 1) return QiDock.Services.UiText.Format("AgoMinutes", (int)span.TotalMinutes);+ if (span.TotalDays < 1) return QiDock.Services.UiText.Format("AgoHours", (int)span.TotalHours);+ if (span.TotalDays < 31) return QiDock.Services.UiText.Format("AgoDays", (int)span.TotalDays);+ if (span.TotalDays < 365) return QiDock.Services.UiText.Format("AgoMonths", (int)(span.TotalDays / 30));+ return QiDock.Services.UiText.Format("AgoYears", (int)(span.TotalDays / 365));+ }++ public static void Open(string target)+ {+#if DEBUG+ if (WidgetPopup.Rehearsal is not null) return; // a snapshot run never opens anything on the user's screen+#endif+ try+ {+ System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(target) { UseShellExecute = true })?.Dispose();+ }+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)+ {+ System.Diagnostics.Trace.TraceWarning("Could not open {0}: {1}", target, ex.Message);+ }+ }+}++/// <summary>Colored vector weather icons drawn in a 24x24 space.</summary>+internal static class WeatherArt+{+ private static readonly Brush SunFill = Ui.Solid("#FFFFC83D");+ private static readonly Brush SunStroke = Ui.Solid("#FFFFB000");+ private static readonly Brush CloudFill = Ui.Vertical("#FFFFFFFF", "#FFDCE3EC");+ private static readonly Brush CloudDarkFill = Ui.Vertical("#FFC5CEDA", "#FF9AA6B5");+ private static readonly Brush RainStroke = Ui.Solid("#FF5AB8FF");+ private static readonly Brush SnowFill = Ui.Solid("#FFFFFFFF");+ private static readonly Brush MoonFill = Ui.Solid("#FFF4E9B8");+ private static readonly Brush FogStroke = Ui.Solid("#FFD4DAE2");+ private static readonly Brush BoltFill = Ui.Solid("#FFFFD60A");++ private static readonly Geometry CloudShape = Geometry.Parse(+ "M7 20 H17.5 A4.5 4.5 0 0 0 18.2 11.06 A6 6 0 0 0 6.6 11.6 A4.2 4.2 0 0 0 7 20 Z");+ private static readonly Geometry SmallCloudShape = Geometry.Parse(+ "M8 21 H17.5 A3.8 3.8 0 0 0 18 13.43 A5 5 0 0 0 8.4 14 A3.5 3.5 0 0 0 8 21 Z");+ private static readonly Geometry MoonShape = Geometry.Parse(+ "M14.5 2.5 A8 8 0 1 0 21.5 13.5 A6.3 6.3 0 0 1 14.5 2.5 Z");++ public static FrameworkElement Create(int code, bool isDay, double size)+ {+ var kind = WeatherService.Classify(code);+ var canvas = new Canvas { Width = 24, Height = 24 };+ switch (kind)+ {+ case WeatherKind.Clear:+ if (isDay) AddSun(canvas, 12, 12, 5.2);+ else AddMoon(canvas, 0, 0, 1);+ break;+ case WeatherKind.PartlyCloudy:+ if (isDay) AddSun(canvas, 15.5, 8.5, 4.2);+ else AddMoon(canvas, 5, -1, 0.7);+ canvas.Children.Add(new Path { Data = SmallCloudShape, Fill = CloudFill, RenderTransform = new TranslateTransform(-3, 0) });+ break;+ case WeatherKind.Cloudy:+ canvas.Children.Add(new Path { Data = SmallCloudShape, Fill = CloudDarkFill, RenderTransform = new TranslateTransform(1, -6) });+ canvas.Children.Add(new Path { Data = CloudShape, Fill = CloudFill, RenderTransform = new TranslateTransform(-1, 0) });+ break;+ case WeatherKind.Fog:+ canvas.Children.Add(new Path { Data = CloudShape, Fill = CloudDarkFill, RenderTransform = new TranslateTransform(0, -4) });+ for (var i = 0; i < 2; i++)+ canvas.Children.Add(new Line { X1 = 4 + i * 2, X2 = 20 - i * 2, Y1 = 19 + i * 3, Y2 = 19 + i * 3, Stroke = FogStroke, StrokeThickness = 1.8, StrokeStartLineCap = PenLineCap.Round, StrokeEndLineCap = PenLineCap.Round });+ break;+ case WeatherKind.Drizzle:+ case WeatherKind.Rain:+ canvas.Children.Add(new Path { Data = CloudShape, Fill = CloudFill, RenderTransform = new TranslateTransform(0, -5) });+ var drops = kind == WeatherKind.Rain ? 3 : 2;+ for (var i = 0; i < drops; i++)+ {+ var x = drops == 3 ? 8 + i * 4 : 10 + i * 4;+ canvas.Children.Add(new Line { X1 = x, X2 = x - 1.5, Y1 = 17, Y2 = 22, Stroke = RainStroke, StrokeThickness = 1.9, StrokeStartLineCap = PenLineCap.Round, StrokeEndLineCap = PenLineCap.Round });+ }+ break;+ case WeatherKind.Snow:+ canvas.Children.Add(new Path { Data = CloudShape, Fill = CloudFill, RenderTransform = new TranslateTransform(0, -5) });+ foreach (var (x, y) in new[] { (8.0, 18.5), (12.0, 21.0), (16.0, 18.5) })+ {+ var flake = new Ellipse { Width = 2.8, Height = 2.8, Fill = SnowFill, Stroke = RainStroke, StrokeThickness = 0.6 };+ Canvas.SetLeft(flake, x - 1.4);+ Canvas.SetTop(flake, y - 1.4);+ canvas.Children.Add(flake);+ }+ break;+ case WeatherKind.Thunder:+ canvas.Children.Add(new Path { Data = CloudShape, Fill = CloudDarkFill, RenderTransform = new TranslateTransform(0, -5) });+ canvas.Children.Add(new Path { Data = Geometry.Parse("M13 13 L9 19 H12 L11 24 L16 17 H13 Z"), Fill = BoltFill });+ break;+ }++ return new Viewbox { Width = size, Height = size, Child = canvas, Stretch = Stretch.Uniform };+ }++ private static void AddSun(Canvas canvas, double cx, double cy, double radius)+ {+ for (var i = 0; i < 8; i++)+ {+ var angle = i * Math.PI / 4;+ canvas.Children.Add(new Line+ {+ X1 = cx + Math.Cos(angle) * (radius + 1.6),+ Y1 = cy + Math.Sin(angle) * (radius + 1.6),+ X2 = cx + Math.Cos(angle) * (radius + 3.4),+ Y2 = cy + Math.Sin(angle) * (radius + 3.4),+ Stroke = SunStroke,+ StrokeThickness = 1.6,+ StrokeStartLineCap = PenLineCap.Round,+ StrokeEndLineCap = PenLineCap.Round+ });+ }+ var sun = new Ellipse { Width = radius * 2, Height = radius * 2, Fill = SunFill };+ Canvas.SetLeft(sun, cx - radius);+ Canvas.SetTop(sun, cy - radius);+ canvas.Children.Add(sun);+ }++ private static void AddMoon(Canvas canvas, double x, double y, double scale)+ {+ var group = new TransformGroup();+ group.Children.Add(new ScaleTransform(scale, scale));+ group.Children.Add(new TranslateTransform(x, y));+ canvas.Children.Add(new Path { Data = MoonShape, Fill = MoonFill, RenderTransform = group });+ }++ /// <summary>Tile background that follows the sky.</summary>+ public static Brush Sky(int code, bool isDay)+ {+ var kind = WeatherService.Classify(code);+ if (!isDay) return Ui.Vertical("#FF27346B", "#FF141B3D");+ return kind switch+ {+ WeatherKind.Clear or WeatherKind.PartlyCloudy => Ui.Vertical("#FF5AA9F5", "#FF2F72DA"),+ WeatherKind.Cloudy or WeatherKind.Fog => Ui.Vertical("#FF8697AD", "#FF5E6E85"),+ WeatherKind.Thunder => Ui.Vertical("#FF55607A", "#FF2F3648"),+ _ => Ui.Vertical("#FF6683A6", "#FF3E5778")+ };+ }+}diff --git a/Widgets/WorldClockWidget.cs b/Widgets/WorldClockWidget.csnew file mode 100644index 0000000..b810a8a--- /dev/null+++ b/Widgets/WorldClockWidget.cs@@ -0,0 +1,167 @@+using System.Globalization;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Threading;+using QiDock.Models;+using QiDock.Services;++namespace QiDock.Widgets;++/// <summary>Up to three cities' local time with the difference to here; cities are picked in the card.</summary>+public sealed class WorldClockWidget : DockWidget+{+ private const int MaxCities = 3;++ // Key → (Turkish name, English name, Windows time zone id)+ internal static readonly (string Key, string Tr, string En, string Zone)[] Cities =+ [+ ("newyork", "New York", "New York", "Eastern Standard Time"),+ ("losangeles", "Los Angeles", "Los Angeles", "Pacific Standard Time"),+ ("chicago", "Chicago", "Chicago", "Central Standard Time"),+ ("saopaulo", "São Paulo", "São Paulo", "E. South America Standard Time"),+ ("london", "Londra", "London", "GMT Standard Time"),+ ("paris", "Paris", "Paris", "Romance Standard Time"),+ ("berlin", "Berlin", "Berlin", "W. Europe Standard Time"),+ ("istanbul", "İstanbul", "Istanbul", "Turkey Standard Time"),+ ("moscow", "Moskova", "Moscow", "Russian Standard Time"),+ ("dubai", "Dubai", "Dubai", "Arabian Standard Time"),+ ("baku", "Bakü", "Baku", "Azerbaijan Standard Time"),+ ("tashkent", "Taşkent", "Tashkent", "West Asia Standard Time"),+ ("delhi", "Delhi", "Delhi", "India Standard Time"),+ ("beijing", "Pekin", "Beijing", "China Standard Time"),+ ("tokyo", "Tokyo", "Tokyo", "Tokyo Standard Time"),+ ("sydney", "Sidney", "Sydney", "AUS Eastern Standard Time")+ ];++ internal static readonly string[] Defaults = ["newyork", "london", "tokyo"];+ private readonly Button _tile;+ private readonly WidgetPopup _popup;+ private readonly StackPanel _rows = new() { VerticalAlignment = VerticalAlignment.Center };+ private readonly DispatcherTimer _timer;+ private IReadOnlyList<string> _keys = Defaults;++ public WorldClockWidget()+ {+ _tile = Ui.Tile(_rows, (_, _) => Toggle(), 10);+ _popup = new WidgetPopup(_tile);+ _timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(20) };+ _timer.Tick += (_, _) => Render();+ UiText.Current.PropertyChanged += (_, _) => Render();+ }++ public override string Id => WidgetIds.WorldClock;+ public override FrameworkElement View => _tile;+ public override bool IsPopupOpen => _popup.IsOpen;+ public override void ClosePopup() => _popup.Close();++ public override void Start()+ {+ Render();+ _timer.Start();+ }++ public override void Stop()+ {+ _timer.Stop();+ _popup.Close();+ }++ public override void SetLive(bool live)+ {+ if (!live)+ {+ _timer.Stop();+ return;+ }+ Render();+ _timer.Start();+ }++ public override void ApplySettings(WidgetSettings settings)+ {+ var keys = settings.WorldClocks is { Count: > 0 } chosen ? chosen.Where(k => Cities.Any(c => c.Key == k)).ToList() : Defaults.ToList();+ if (keys.SequenceEqual(_keys)) return;+ _keys = keys;+ Render();+ if (_popup.IsOpen) Build();+ }++ private static string CityName((string Key, string Tr, string En, string Zone) city) =>+ UiText.Current.Language == AppLanguage.English ? city.En : city.Tr;++ private static DateTime? TimeIn(string zone)+ {+ try { return TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById(zone)); }+ catch (Exception ex) when (ex is TimeZoneNotFoundException or InvalidTimeZoneException) { return null; }+ }++ private static string Offset(DateTime there)+ {+ var hours = Math.Round((there - DateTime.Now).TotalHours * 2) / 2;+ return hours == 0 ? "±0" : (hours > 0 ? "+" : "−") + Math.Abs(hours).ToString("0.#", CultureInfo.InvariantCulture);+ }++ private void Render()+ {+ _rows.Children.Clear();+ foreach (var key in _keys.Take(MaxCities))+ {+ var city = Cities.First(c => c.Key == key);+ if (TimeIn(city.Zone) is not { } time) continue;+ var row = new StackPanel { Orientation = Orientation.Horizontal };+ var name = Ui.Text(CityName(city), 10, brushKey: "TextSecondary");+ name.Width = 64;+ var clock = Ui.Text(time.ToString("HH:mm", CultureInfo.InvariantCulture), 10.5, FontWeights.SemiBold);+ clock.Width = 34;+ var diff = Ui.Text(Offset(time), 9.5, brushKey: "TextSecondary");+ row.Children.Add(name);+ row.Children.Add(clock);+ row.Children.Add(diff);+ _rows.Children.Add(row);+ }+ }++ private void Toggle()+ {+ if (!_popup.IsOpen) Build();+ _popup.Toggle();+ }++ private void Build()+ {+ var root = new StackPanel();+ root.Children.Add(Ui.Header(UiText.Get("WorldClockTitle"), () => _popup.Close()));+ var hint = Ui.Text(UiText.Format("WorldClockHint", MaxCities), 11, brushKey: "TextSecondary");+ hint.Margin = new Thickness(0, 0, 0, 8);+ root.Children.Add(hint);+ // Three tiles fill the card exactly: their outer edges line up with the title and the ×.+ var grid = new WrapPanel { Width = 340, Margin = new Thickness(-2, 0, -2, 0) };+ foreach (var city in Cities)+ {+ var chosen = _keys.Contains(city.Key);+ var time = TimeIn(city.Zone);+ var content = new StackPanel();+ content.Children.Add(Ui.Text(CityName(city), 11.5, FontWeights.SemiBold));+ content.Children.Add(Ui.Text(time is { } t ? $"{t:HH:mm} · {Offset(t)}" : "–", 10.5, brushKey: "TextSecondary"));+ var button = new Button { Content = content, Width = 340 / 3.0 - 4, Height = 46, Margin = new Thickness(2), HorizontalContentAlignment = HorizontalAlignment.Left };+ button.SetResourceReference(FrameworkElement.StyleProperty, "WidgetTileButton");+ button.Height = 46;+ if (chosen) button.SetResourceReference(Control.BorderBrushProperty, "WidgetAccent");+ button.Click += (_, _) =>+ {+ var keys = _keys.ToList();+ if (keys.Contains(city.Key)) keys.Remove(city.Key);+ else+ {+ if (keys.Count >= MaxCities) keys.RemoveAt(0);+ keys.Add(city.Key);+ }+ if (keys.Count == 0) return;+ UpdateSettings(s => s with { WorldClocks = keys });+ };+ grid.Children.Add(button);+ }+ root.Children.Add(grid);+ _popup.SetContent(root, 370);+ }+}diff --git a/app.manifest b/app.manifestnew file mode 100644index 0000000..495b708--- /dev/null+++ b/app.manifest@@ -0,0 +1,22 @@+<?xml version="1.0" encoding="utf-8"?>+<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">+ <assemblyIdentity version="1.0.0.0" name="QiDock.app" />+ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">+ <security>+ <requestedPrivileges>+ <requestedExecutionLevel level="asInvoker" uiAccess="false" />+ </requestedPrivileges>+ </security>+ </trustInfo>+ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">+ <application>+ <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />+ </application>+ </compatibility>+ <application xmlns="urn:schemas-microsoft-com:asm.v3">+ <windowsSettings>+ <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>+ <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>+ </windowsSettings>+ </application>+</assembly>diff --git a/scripts/publish-portable.ps1 b/scripts/publish-portable.ps1new file mode 100644index 0000000..6cc0d9e--- /dev/null+++ b/scripts/publish-portable.ps1@@ -0,0 +1,26 @@+# QiDock Portable Single-File Publisher+# Builds a self-contained, compressed single-file executable for Windows x64.+param (+ [string]$OutputDir = "$PSScriptRoot\..\dist"+)++$ErrorActionPreference = "Stop"++Write-Host "Publishing QiDock as self-contained portable executable..." -ForegroundColor Cyan++$projectPath = "$PSScriptRoot\..\QiDock.csproj"++dotnet publish $projectPath `+ -c Release `+ -r win-x64 `+ --self-contained true `+ -p:PublishSingleFile=true `+ -p:IncludeNativeLibrariesForSelfExtract=true `+ -p:EnableCompressionInSingleFile=true `+ -o $OutputDir++if ($LASTEXITCODE -eq 0) {+ Write-Host "Publish succeeded! Portable executable is ready at: $OutputDir\QiDock.exe" -ForegroundColor Green+} else {+ Write-Error "Publish failed with exit code $LASTEXITCODE"+}