Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion Network Monitor/App.xaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
<Application x:Class="Network_Monitor.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources />
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes/FluentTheme.xaml" />
<!-- ThemeService puts the palette for the theme in its place when the app starts, and whenever the theme changes. -->
<ResourceDictionary Source="Themes/LightPalette.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
4 changes: 4 additions & 0 deletions Network Monitor/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ protected override void OnStartup(StartupEventArgs e)
}

SettingsSaver.Start();

// The palette for the theme goes in before the window is created, so the widget never shows the light one first.
_ = ThemeService.Instance;

RepairStartup();

var window = new MainWindow();
Expand Down
47 changes: 3 additions & 44 deletions Network Monitor/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
Background="Transparent"
UseLayoutRounding="True"
FontFamily="Consolas"
Foreground="{DynamicResource WidgetTextBrush}"
MouseDown="MainWindow_OnMouseDown"
SizeChanged="Window_SizeChanged"
ContentRendered="Window_ContentRendered"
Expand All @@ -28,27 +29,6 @@
<Window.Resources>
<root:EnumToBooleanConverter x:Key="EnumToBoolean" />
</Window.Resources>
<Window.Style>
<Style TargetType="Window">
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="#242424" />
</Setter.Value>
</Setter>

<Style.Triggers>
<DataTrigger Binding="{Binding IsDark, Source={x:Static root:ThemeService.Instance}}" Value="True">
<DataTrigger.Setters>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="#FFFFFF" />
</Setter.Value>
</Setter>
</DataTrigger.Setters>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Style>
<Window.ContextMenu>
<ContextMenu Opened="ContextMenu_OnOpened">
<!-- Shows which version is running, as in DesktopClock. -->
Expand Down Expand Up @@ -139,29 +119,8 @@
</ContextMenu>
</Window.ContextMenu>

<Grid Grid.IsSharedSizeScope="True">
<Grid.Style>
<Style TargetType="Grid">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="#F3F3F3" Opacity="0.90" />
</Setter.Value>
</Setter>

<Style.Triggers>
<DataTrigger Binding="{Binding IsDark, Source={x:Static root:ThemeService.Instance}}" Value="True">
<DataTrigger.Setters>
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="#202020" Opacity="0.90" />
</Setter.Value>
</Setter>
</DataTrigger.Setters>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>

<!-- The colors come from the theme's palette in Themes, which ThemeService puts in place. -->
<Grid Background="{DynamicResource WidgetBackgroundBrush}" Grid.IsSharedSizeScope="True">
<Grid.Resources>
<Style TargetType="root:MonitorView">
<Setter Property="Template">
Expand Down
2 changes: 1 addition & 1 deletion Network Monitor/MonitorView.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
Margin="0,2,0,6"
Values="{Binding History}"
MinimumTop="{Binding HistoryMinimumTop}"
Stroke="{Binding TooltipBrush}"
Stroke="{Binding IconBrush}"
StrokeThickness="1.5" />

<TextBlock Text="{Binding Details}" />
Expand Down
29 changes: 10 additions & 19 deletions Network Monitor/Monitors/Monitor.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
using Network_Monitor.Properties;

namespace Network_Monitor.Monitors;

Expand Down Expand Up @@ -41,11 +41,7 @@ protected Monitor(bool updatesEverySecond)
if (updatesEverySecond)
ClockTimer.SecondChanged += (_, _) => Update();

ThemeService.Instance.PropertyChanged += (_, _) =>
{
RaisePropertyChanged(nameof(IconBrush));
RaisePropertyChanged(nameof(TooltipBrush));
};
ThemeService.Instance.PropertyChanged += (_, _) => RaisePropertyChanged(nameof(IconBrush));
}

/// <summary>
Expand All @@ -69,21 +65,17 @@ public static event EventHandler ClockTicked
public char Icon { get; protected set; }

/// <summary>
/// Icon color for the active theme.
/// Color for the icon and the graph in the tooltip, in the active theme.
/// Light and Dark use the fixed Fluent palette (darker shades in light mode, lighter tints in dark mode); Auto follows the system accent color instead.
/// A high contrast theme's own text color takes the place of both, since only its own colors are sure to be readable.
/// </summary>
/// <remarks>
/// The graph draws with a frozen pen, which needs a brush that can be frozen, so high contrast uses the system's own brush rather than the palette's.
/// </remarks>
public Brush IconBrush =>
Settings.Default.Theme == AppTheme.Auto && ThemeService.Instance.AccentBrush is Brush accent
? accent
: ThemeService.Instance.IsDark ? _darkIconBrush : _lightIconBrush;

/// <summary>
/// Color for the graph in the tooltip, which stays light whatever the widget's theme: the accent in Auto, otherwise the light theme's darker shade, which can be seen against it.
/// </summary>
public Brush TooltipBrush =>
Settings.Default.Theme == AppTheme.Auto && ThemeService.Instance.AccentBrush is Brush accent
? accent
: _lightIconBrush;
ThemeService.Instance.IsHighContrast
? SystemColors.WindowTextBrush
: ThemeService.Instance.AccentBrush ?? (ThemeService.Instance.IsDark ? _darkIconBrush : _lightIconBrush);

/// <summary>
/// User-friendly text to show in the UI.
Expand Down Expand Up @@ -295,7 +287,6 @@ protected void SetIconColors(string lightHexColor, string darkHexColor)
_lightIconBrush = CreateFrozenBrush(lightHexColor);
_darkIconBrush = CreateFrozenBrush(darkHexColor);
RaisePropertyChanged(nameof(IconBrush));
RaisePropertyChanged(nameof(TooltipBrush));
}

private static Brush CreateFrozenBrush(string hexColor)
Expand Down
76 changes: 72 additions & 4 deletions Network Monitor/ThemeService.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Windows;
using System.Windows.Media;
using Microsoft.Win32;
Expand All @@ -8,9 +9,24 @@ namespace Network_Monitor;
/// <summary>
/// Single source of truth for the effective theme.
/// Light and Dark force the appearance; Auto follows the operating system's light/dark setting and accent color, updating live when either changes.
/// A high contrast theme overrides all three with its own colors, whenever it's on.
/// </summary>
/// <remarks>
/// The colors of the widget, the menu, and the tooltips come from a palette in Themes, which this puts in the app's resources in place of the one App.xaml starts with.
/// </remarks>
public sealed class ThemeService : ObservableObject
{
/// <summary>
/// The app resource for the accent of the menu, like its check marks, which this sets to the system accent in Auto.
/// The palettes have one of their own for the other themes.
/// </summary>
private const string AccentBrushKey = "AccentBrush";

private static readonly Uri LightPaletteUri = new("Themes/LightPalette.xaml", UriKind.Relative);
private static readonly Uri DarkPaletteUri = new("Themes/DarkPalette.xaml", UriKind.Relative);
private static readonly Uri HighContrastPaletteUri = new("Themes/HighContrastPalette.xaml", UriKind.Relative);

// After the palettes' addresses, since static fields are set in the order they're written, and creating this reads them.
public static ThemeService Instance { get; } = new();

private ThemeService()
Expand All @@ -21,10 +37,17 @@ private ThemeService()
Refresh();
};

// The OS theme and accent only matter in Auto mode, but refreshing unconditionally is cheap and keeps the logic simple.
// The OS theme and accent only matter in Auto mode, and the system's colors only in high contrast, but refreshing unconditionally is cheap and keeps the logic simple.
// The event can arrive on a non-UI thread, so marshal back to the dispatcher before touching bound state.
SystemEvents.UserPreferenceChanged += (_, _) => Application.Current?.Dispatcher.BeginInvoke(Refresh);

// High contrast is also announced by WPF once it has read the new setting, which the event above can arrive before.
SystemParameters.StaticPropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(SystemParameters.HighContrast))
Application.Current?.Dispatcher.BeginInvoke(Refresh);
};

Refresh();
}

Expand All @@ -34,26 +57,58 @@ private ThemeService()
public bool IsDark { get; private set; }

/// <summary>
/// The system accent color used for the icons in Auto mode, or null when it can't be read (the monitors then keep their normal per-theme colors).
/// Whether a high contrast theme is on, in which only its own colors are sure to be readable, so they're used for everything and nothing is see-through.
/// </summary>
public bool IsHighContrast { get; private set; }

/// <summary>
/// The system accent color for the icons, the graphs, and the menu in Auto mode, in the shade Windows uses for accent-colored text in the theme, or null in the other modes, in high contrast, or when it can't be read (the monitors then keep their normal per-theme colors).
/// </summary>
public Brush AccentBrush { get; private set; }

private void Refresh()
{
IsHighContrast = SystemParameters.HighContrast;

IsDark = Settings.Default.Theme switch
{
AppTheme.Light => false,
AppTheme.Dark => true,
_ => !ReadAppsUseLightTheme()
};

AccentBrush = ReadAccentColor() is Color accent ? CreateFrozenBrush(accent) : null;
// The accent stands in for the readings' own colors only in Auto, and a high contrast theme keeps to its own colors.
var accent = Settings.Default.Theme == AppTheme.Auto && !IsHighContrast ? ReadAccentColor(IsDark) : null;
AccentBrush = accent is Color color ? CreateFrozenBrush(color) : null;

if (Application.Current is not null)
{
ApplyPalette();

// The menu's check marks and the Size slider take the accent in place of the palette's own.
if (AccentBrush is not null)
Application.Current.Resources[AccentBrushKey] = AccentBrush;
else
Application.Current.Resources.Remove(AccentBrushKey);
}

// Raise unconditionally: even when IsDark is unchanged the icons still need to switch between their palette and the accent when only the mode changed.
RaisePropertyChanged(nameof(IsDark));
RaisePropertyChanged(nameof(IsHighContrast));
RaisePropertyChanged(nameof(AccentBrush));
}

/// <summary>
/// Puts the palette for the theme in the app's resources, in place of the one that's there.
/// </summary>
private void ApplyPalette()
{
var uri = IsHighContrast ? HighContrastPaletteUri : IsDark ? DarkPaletteUri : LightPaletteUri;

// The palette is the second of App.xaml's dictionaries, after FluentTheme.xaml.
Application.Current.Resources.MergedDictionaries[1] = new ResourceDictionary { Source = uri };
}

private static bool ReadAppsUseLightTheme()
{
try
Expand All @@ -68,10 +123,23 @@ private static bool ReadAppsUseLightTheme()
}
}

private static Color? ReadAccentColor()
/// <summary>
/// The system accent color in the shade Windows uses for accent-colored text and icons in the theme, or the accent itself when Windows hasn't saved its shades.
/// </summary>
private static Color? ReadAccentColor(bool isDark)
{
try
{
using var accent = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\Accent");

// Eight colors of four bytes each, red first: Light3, Light2, Light1, the accent, Dark1, Dark2, Dark3, and one that's unused.
// WinUI uses Light3 for accent-colored text and icons in the dark theme, and Dark2 in the light one.
if (accent?.GetValue("AccentPalette") is byte[] { Length: >= 32 } palette)
{
var offset = isDark ? 0 : 20;
return Color.FromRgb(palette[offset], palette[offset + 1], palette[offset + 2]);
}

using var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\DWM");

// Stored as a COLORREF-style DWORD in ABGR order (0xAABBGGRR), so red is the low byte.
Expand Down
26 changes: 26 additions & 0 deletions Network Monitor/Themes/DarkPalette.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- Windows 11's dark colors, from DesktopClock's DarkPalette.xaml. -->

<!-- The widget, a little see-through so the desktop shows through it. -->
<SolidColorBrush x:Key="WidgetBackgroundBrush"
Opacity="0.90"
Color="#202020" />
<SolidColorBrush x:Key="WidgetTextBrush" Color="#FFFFFF" />

<!-- The menu and the tooltips. -->
<SolidColorBrush x:Key="TextPrimaryBrush" Color="#FFFFFF" />
<SolidColorBrush x:Key="TextSecondaryBrush" Color="#A6A6A6" />
<SolidColorBrush x:Key="MenuBackgroundBrush" Color="#2C2C2C" />
<SolidColorBrush x:Key="MenuBorderBrush" Color="#383838" />
<SolidColorBrush x:Key="SeparatorBrush" Color="#3F3F3F" />
<SolidColorBrush x:Key="SliderTrackBrush" Color="#757575" />
<SolidColorBrush x:Key="SliderThumbBackgroundBrush" Color="#454545" />

<!-- An item under the pointer or the keyboard. -->
<SolidColorBrush x:Key="HoverBrush" Color="#383838" />
<SolidColorBrush x:Key="OnHoverTextBrush" Color="#FFFFFF" />

<!-- Windows' own blue, lightened for the dark theme, for Light and Dark. In Auto, ThemeService puts the system accent over it. -->
<SolidColorBrush x:Key="AccentBrush" Color="#4CC2FF" />
</ResourceDictionary>
Loading