diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 11cab2d..f963543 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -23,7 +23,15 @@ jobs: uses: actions/setup-dotnet@v4 with: dotnet-version: '10.0.x' - + + - name: Cache NuGet packages + uses: actions/cache@v4 + with: + path: ~\.nuget\packages + key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj') }} + restore-keys: | + ${{ runner.os }}-nuget- + - name: Restore dependencies run: dotnet restore WindowsEdgeLight/WindowsEdgeLight.csproj @@ -130,7 +138,7 @@ jobs: - name: Create Release if: startsWith(github.ref, 'refs/tags/') - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v2 with: files: artifacts/*.zip generate_release_notes: true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ee00e6a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,44 @@ +name: CI + +on: + pull_request: + push: + branches: + - master + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + build-and-test: + runs-on: windows-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Cache NuGet packages + uses: actions/cache@v4 + with: + path: ~\.nuget\packages + key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj') }} + restore-keys: | + ${{ runner.os }}-nuget- + + - name: Restore + run: dotnet restore WindowsEdgeLight.sln + + - name: Build + run: dotnet build WindowsEdgeLight.sln --configuration Release --no-restore + + - name: Test + run: dotnet test WindowsEdgeLight.sln --configuration Release --no-build diff --git a/README.md b/README.md index b34cf18..db54400 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,21 @@ # Windows Edge Light -A lightweight WPF application that adds a customizable glowing edge light effect around your primary monitor on Windows. Perfect for ambient lighting during video calls, streaming, or just adding a professional touch to your workspace. +A lightweight WPF application that adds a customizable glowing edge light effect around your monitors on Windows. Perfect for ambient lighting during video calls, streaming, or just adding a professional touch to your workspace. ## Features - **Automatic Updates**: Built-in update system checks GitHub Releases for new versions -- **Primary Monitor Display**: Automatically detects and displays on your primary monitor, even in multi-monitor setups +- **Multi-Monitor Support**: Display on your primary monitor, switch to another monitor, or show on all monitors simultaneously - **DPI Aware**: Properly handles high-DPI displays (4K monitors with scaling) - **Fluent Design**: Modern UX that fits in with the Windows look and feel - **Click-Through Transparency**: Overlay doesn't interfere with your work - all clicks pass through to applications beneath - **Customizable Brightness**: Adjust opacity with easy-to-use controls - - **Adjustable Color Temperature**: Shift the edge light from cooler (blue-ish) to warmer (amber) tones +- **Adjustable Color Temperature**: Shift the edge light from cooler (blue-ish) to warmer (amber) tones - **Toggle On/Off**: Quickly enable or disable the edge light effect - **Hideable Controls**: Hide the control toolbar for a cleaner look, restore via tray menu - **Always On Top**: Stays visible above all other windows +- **Persistent Settings**: Brightness, color temperature, on/off state, and preferences are saved across restarts +- **Settings Window**: Dedicated settings panel with sliders and control-bar customization - **Exclude from Screen Capture**: Optional setting to hide the edge light from screen sharing (Teams, Zoom) and screenshots - **Keyboard Shortcuts**: - `Ctrl+Shift+L` - Toggle light on/off @@ -82,19 +84,19 @@ The executable will be in `bin\Release\net10.0-windows\win-x64\publish\WindowsEd 3. Control toolbar appears at the bottom center with these buttons: - 🔅 **Decrease Brightness** - Reduces opacity - 🔆 **Increase Brightness** - Increases opacity - - 🌡️ **Cooler Color** - Shifts the glow towards a cooler, blue-ish white - 🔥 **Warmer Color** - Shifts the glow towards a warmer, amber tone + - ❄️ **Cooler Color** - Shifts the glow towards a cooler, blue-ish white - 💡 **Toggle Light** - Turn the effect on/off - 🖥️ **Switch Monitor** - Move to next monitor (if multiple monitors) - 🖥️🖥️ **All Monitors** - Show on all monitors (if multiple monitors) - - 🎥 **Exclude from Capture** - Hide from screen sharing and screenshots + - ⚙️ **Settings** - Adjust appearance, capture exclusion, and control visibility - ✖ **Exit** - Close the application 4. Hide the control toolbar for a cleaner look using the tray menu (right-click tray icon → "Hide Controls") ### Screen Sharing Mode When sharing your screen on video conferencing apps (Teams, Zoom, etc.), you may want the edge light to be visible to you but invisible to viewers. Enable **"Exclude from Screen Capture"** via: -- Click the 🎥 button in the control toolbar, or +- Open ⚙️ **Settings** from the control toolbar and enable **Exclude from Screen Capture**, or - Right-click the tray icon → "Exclude from Screen Capture" **Note**: When this setting is enabled, the edge light will also be excluded from screenshots taken with Windows Snipping Tool, PrintScreen, or other capture tools. @@ -124,11 +126,11 @@ When sharing your screen on video conferencing apps (Teams, Zoom, etc.), you may ## Multi-Monitor Support -The application specifically targets the **primary monitor** in your display setup: -- Automatically detects primary monitor position and dimensions -- Correctly handles DPI scaling (e.g., 150%, 200% on 4K displays) -- Works with any monitor arrangement (horizontal, vertical, mixed) -- Does not span across multiple monitors +The application supports flexible multi-monitor configurations: +- Starts on the primary monitor +- Switches between connected monitors from the toolbar or tray menu +- Can display the edge light on every connected monitor simultaneously +- Handles per-monitor DPI scaling and mixed monitor arrangements ## Development diff --git a/WindowsEdgeLight.Tests/AppSettingsTests.cs b/WindowsEdgeLight.Tests/AppSettingsTests.cs new file mode 100644 index 0000000..364696f --- /dev/null +++ b/WindowsEdgeLight.Tests/AppSettingsTests.cs @@ -0,0 +1,137 @@ +using System.Text.Json; +using Xunit; + +namespace WindowsEdgeLight.Tests; + +public sealed class AppSettingsTests : IDisposable +{ + private readonly string tempDirectory = Path.Combine( + Path.GetTempPath(), + $"WindowsEdgeLight.Tests-{Guid.NewGuid():N}"); + + private string SettingsPath => Path.Combine(tempDirectory, "settings.json"); + + [Fact] + public void DefaultsMatchApplicationDefaults() + { + var settings = new AppSettings(); + + Assert.True(settings.ExcludeFromCapture); + Assert.True(settings.IsLightOn); + Assert.Equal(1.0, settings.Brightness); + Assert.Equal(0.5, settings.ColorTemperature); + Assert.True(settings.ShowToggleButton); + Assert.True(settings.ShowBrightnessButtons); + Assert.True(settings.ShowColorTempButtons); + Assert.True(settings.ShowMonitorControlButtons); + } + + [Fact] + public void MissingFileReturnsDefaults() + { + var settings = AppSettings.LoadFrom(SettingsPath); + + Assert.Equal(1.0, settings.Brightness); + Assert.True(settings.IsLightOn); + } + + [Fact] + public void SaveAndLoadRoundTripsAllProperties() + { + var expected = new AppSettings + { + ExcludeFromCapture = false, + IsLightOn = false, + Brightness = 0.7, + ColorTemperature = 0.3, + ShowToggleButton = false, + ShowBrightnessButtons = false, + ShowColorTempButtons = false, + ShowMonitorControlButtons = false + }; + + expected.SaveTo(SettingsPath); + var actual = AppSettings.LoadFrom(SettingsPath); + + Assert.Equal(expected.ExcludeFromCapture, actual.ExcludeFromCapture); + Assert.Equal(expected.IsLightOn, actual.IsLightOn); + Assert.Equal(expected.Brightness, actual.Brightness); + Assert.Equal(expected.ColorTemperature, actual.ColorTemperature); + Assert.Equal(expected.ShowToggleButton, actual.ShowToggleButton); + Assert.Equal(expected.ShowBrightnessButtons, actual.ShowBrightnessButtons); + Assert.Equal(expected.ShowColorTempButtons, actual.ShowColorTempButtons); + Assert.Equal(expected.ShowMonitorControlButtons, actual.ShowMonitorControlButtons); + Assert.False(File.Exists(SettingsPath + ".tmp")); + } + + [Fact] + public void SaveReplacesExistingFile() + { + Directory.CreateDirectory(tempDirectory); + File.WriteAllText(SettingsPath, """{"Brightness":0.2}"""); + var settings = new AppSettings { Brightness = 0.8 }; + + settings.SaveTo(SettingsPath); + + Assert.Equal(0.8, AppSettings.LoadFrom(SettingsPath).Brightness); + Assert.False(File.Exists(SettingsPath + ".tmp")); + } + + [Fact] + public void SaveCreatesParentDirectory() + { + var nestedPath = Path.Combine(tempDirectory, "nested", "settings.json"); + + new AppSettings().SaveTo(nestedPath); + + Assert.True(File.Exists(nestedPath)); + } + + [Fact] + public void CorruptJsonReturnsDefaultsAndDeletesFile() + { + Directory.CreateDirectory(tempDirectory); + File.WriteAllText(SettingsPath, "{ invalid"); + + var settings = AppSettings.LoadFrom(SettingsPath); + + Assert.Equal(1.0, settings.Brightness); + Assert.False(File.Exists(SettingsPath)); + } + + [Fact] + public void CommentsAndTrailingCommasAreAccepted() + { + Directory.CreateDirectory(tempDirectory); + File.WriteAllText(SettingsPath, """ + { + // User-edited settings remain supported. + "Brightness": 0.6, + "ColorTemperature": 0.2, + } + """); + + var settings = AppSettings.LoadFrom(SettingsPath); + + Assert.Equal(0.6, settings.Brightness); + Assert.Equal(0.2, settings.ColorTemperature); + } + + [Fact] + public void SavedJsonIsIndented() + { + new AppSettings().SaveTo(SettingsPath); + + var json = File.ReadAllText(SettingsPath); + Assert.Contains(Environment.NewLine, json); + Assert.NotNull(JsonSerializer.Deserialize(json)); + } + + public void Dispose() + { + if (Directory.Exists(tempDirectory)) + { + Directory.Delete(tempDirectory, recursive: true); + } + } +} diff --git a/WindowsEdgeLight.Tests/WindowsEdgeLight.Tests.csproj b/WindowsEdgeLight.Tests/WindowsEdgeLight.Tests.csproj new file mode 100644 index 0000000..83d8c41 --- /dev/null +++ b/WindowsEdgeLight.Tests/WindowsEdgeLight.Tests.csproj @@ -0,0 +1,24 @@ + + + + net10.0-windows + enable + enable + false + true + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/WindowsEdgeLight.sln b/WindowsEdgeLight.sln index 6ea1e8e..e3bb4df 100644 --- a/WindowsEdgeLight.sln +++ b/WindowsEdgeLight.sln @@ -4,6 +4,8 @@ VisualStudioVersion = 17.5.2.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsEdgeLight", "WindowsEdgeLight\WindowsEdgeLight.csproj", "{C2187EC4-5511-1F4A-A7C5-D7D114D039DC}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsEdgeLight.Tests", "WindowsEdgeLight.Tests\WindowsEdgeLight.Tests.csproj", "{B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -14,6 +16,10 @@ Global {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Debug|Any CPU.Build.0 = Debug|Any CPU {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Release|Any CPU.ActiveCfg = Release|Any CPU {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Release|Any CPU.Build.0 = Release|Any CPU + {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/WindowsEdgeLight/AppSettings.cs b/WindowsEdgeLight/AppSettings.cs index 1f46de9..547091e 100644 --- a/WindowsEdgeLight/AppSettings.cs +++ b/WindowsEdgeLight/AppSettings.cs @@ -14,6 +14,17 @@ public class AppSettings "WindowsEdgeLight", "settings.json"); + private static readonly JsonSerializerOptions ReadOptions = new() + { + AllowTrailingCommas = true, + ReadCommentHandling = JsonCommentHandling.Skip + }; + + private static readonly JsonSerializerOptions WriteOptions = new() + { + WriteIndented = true + }; + /// /// When enabled, excludes the edge light from screen capture (Teams, screenshots, etc.) /// Note: When enabled, screenshots won't capture the edge light effect @@ -59,20 +70,17 @@ public class AppSettings /// /// Load settings from disk /// - public static AppSettings Load() + public static AppSettings Load() => LoadFrom(SettingsFilePath); + + internal static AppSettings LoadFrom(string filePath) { try { - if (File.Exists(SettingsFilePath)) + if (File.Exists(filePath)) { - var json = File.ReadAllText(SettingsFilePath); - var options = new JsonSerializerOptions - { - AllowTrailingCommas = true, - ReadCommentHandling = JsonCommentHandling.Skip - }; - var settings = JsonSerializer.Deserialize(json, options); - + var json = File.ReadAllText(filePath); + var settings = JsonSerializer.Deserialize(json, ReadOptions); + // Validate deserialized settings if (settings != null) { @@ -86,9 +94,9 @@ public static AppSettings Load() // Delete corrupted settings file try { - if (File.Exists(SettingsFilePath)) + if (File.Exists(filePath)) { - File.Delete(SettingsFilePath); + File.Delete(filePath); } } catch { /* Ignore deletion errors */ } @@ -104,21 +112,22 @@ public static AppSettings Load() /// /// Save settings to disk /// - public void Save() + public void Save() => SaveTo(SettingsFilePath); + + internal void SaveTo(string filePath) { try { - var directory = Path.GetDirectoryName(SettingsFilePath); + var directory = Path.GetDirectoryName(filePath); if (directory != null && !Directory.Exists(directory)) { Directory.CreateDirectory(directory); } - var json = JsonSerializer.Serialize(this, new JsonSerializerOptions - { - WriteIndented = true - }); - File.WriteAllText(SettingsFilePath, json); + var json = JsonSerializer.Serialize(this, WriteOptions); + var tempPath = filePath + ".tmp"; + File.WriteAllText(tempPath, json); + File.Move(tempPath, filePath, overwrite: true); } catch (Exception ex) { diff --git a/WindowsEdgeLight/AssemblyInfo.cs b/WindowsEdgeLight/AssemblyInfo.cs index cc29e7f..664c931 100644 --- a/WindowsEdgeLight/AssemblyInfo.cs +++ b/WindowsEdgeLight/AssemblyInfo.cs @@ -1,4 +1,7 @@ using System.Windows; +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("WindowsEdgeLight.Tests")] [assembly:ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located diff --git a/WindowsEdgeLight/ControlWindow.xaml.cs b/WindowsEdgeLight/ControlWindow.xaml.cs index 871d03d..3509199 100644 --- a/WindowsEdgeLight/ControlWindow.xaml.cs +++ b/WindowsEdgeLight/ControlWindow.xaml.cs @@ -94,7 +94,8 @@ private void DragHandle_MouseLeftButtonDown(object sender, MouseButtonEventArgs return; } - mainWindow.NotifyControlWindowManuallyMoved(); + var initialLeft = Left; + var initialTop = Top; try { @@ -104,6 +105,11 @@ private void DragHandle_MouseLeftButtonDown(object sender, MouseButtonEventArgs { // DragMove can throw if the mouse button is no longer pressed; ignore. } + + if (Math.Abs(Left - initialLeft) > 0.5 || Math.Abs(Top - initialTop) > 0.5) + { + mainWindow.NotifyControlWindowManuallyMoved(); + } } private void Close_Click(object sender, RoutedEventArgs e) diff --git a/WindowsEdgeLight/MainWindow.xaml.cs b/WindowsEdgeLight/MainWindow.xaml.cs index 2cf0f38..5d517d2 100644 --- a/WindowsEdgeLight/MainWindow.xaml.cs +++ b/WindowsEdgeLight/MainWindow.xaml.cs @@ -5,8 +5,10 @@ using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; +using System.Windows.Media.Effects; using System.Windows.Shapes; using System.Windows.Threading; +using MediaColor = System.Windows.Media.Color; namespace WindowsEdgeLight; @@ -44,6 +46,13 @@ public partial class MainWindow : Window // Application settings private AppSettings settings = new AppSettings(); + private sealed class HoleCache + { + public Geometry? BaseGeometry { get; set; } + public EllipseGeometry? Hole { get; set; } + public CombinedGeometry? Combined { get; set; } + } + private class MonitorWindowContext { public Window Window { get; set; } = null!; @@ -57,6 +66,7 @@ private class MonitorWindowContext public double PathOffsetY { get; set; } public double DpiScaleX { get; set; } = 1.0; public double DpiScaleY { get; set; } = 1.0; + public HoleCache HoleCache { get; } = new(); } // Monitor management @@ -143,6 +153,10 @@ private struct MSLLHOOKSTRUCT private Geometry? baseFrameGeometry; // original frame geometry (outer minus inner) private double pathOffsetX; // offset of geometry within window private double pathOffsetY; + private readonly HoleCache primaryHoleCache = new(); + + private static readonly MediaColor CoolColor = MediaColor.FromRgb(220, 235, 255); + private static readonly MediaColor WarmColor = MediaColor.FromRgb(255, 220, 180); private const uint MOD_CONTROL = 0x0002; private const uint MOD_SHIFT = 0x0004; @@ -219,6 +233,7 @@ private void SetupNotifyIcon() // Add toggle controls menu item - text will be set by UpdateTrayMenuToggleControlsText toggleControlsMenuItem = new ToolStripMenuItem("🎛️ Hide Controls", null, (s, e) => ToggleControlsVisibility()); contextMenu.Items.Add(toggleControlsMenuItem); + contextMenu.Items.Add("📍 Reset Control Bar Position", null, (s, e) => ResetControlWindowPosition()); // Add exclude from capture menu item with checkmark excludeFromCaptureMenuItem = new ToolStripMenuItem("🎥 Exclude from Screen Capture", null, (s, e) => ToggleExcludeFromCapture()); @@ -268,7 +283,7 @@ private void SetupWindow() // Initialize available monitors on first setup if (availableMonitors.Length == 0) { - availableMonitors = Screen.AllScreens; + RefreshAvailableMonitors(); // Find the primary monitor index for (int i = 0; i < availableMonitors.Length; i++) @@ -281,7 +296,7 @@ private void SetupWindow() } } - var targetScreen = availableMonitors.Length > 0 ? availableMonitors[currentMonitorIndex] : Screen.PrimaryScreen; + var targetScreen = GetCurrentScreen(); if (targetScreen == null) return; SetupWindowForScreen(targetScreen); @@ -445,7 +460,7 @@ private void HandleMouseMove(int screenX, int screenY) // --- Main Window Logic --- if (frameOuterRect != null && frameInnerRect != null && hoverCursorRing != null && baseFrameGeometry != null) { - var screen = availableMonitors.Length > 0 ? availableMonitors[currentMonitorIndex] : Screen.PrimaryScreen; + var screen = GetCurrentScreen(); if (screen != null) { ApplyHolePunchEffect( @@ -457,7 +472,8 @@ private void HandleMouseMove(int screenX, int screenY) EdgeLightBorder, baseFrameGeometry, pathOffsetX, pathOffsetY, - (ring, x, y) => { Canvas.SetLeft(ring, x); Canvas.SetTop(ring, y); } + (ring, x, y) => { Canvas.SetLeft(ring, x); Canvas.SetTop(ring, y); }, + primaryHoleCache ); } } @@ -476,7 +492,8 @@ private void HandleMouseMove(int screenX, int screenY) ctx.BorderPath, ctx.BaseGeometry, ctx.PathOffsetX, ctx.PathOffsetY, - (ring, x, y) => { ring.Margin = new Thickness(x, y, 0, 0); } + (ring, x, y) => { ring.Margin = new Thickness(x, y, 0, 0); }, + ctx.HoleCache ); } catch (InvalidOperationException) @@ -495,7 +512,8 @@ private void ApplyHolePunchEffect( System.Windows.Shapes.Path borderPath, Geometry baseGeometry, double pathOffsetX, double pathOffsetY, - Action positionRing) + Action positionRing, + HoleCache holeCache) { // Manual coordinate calculation to avoid PointFromScreen issues across monitors/DPIs // We positioned the window using dpiScaleX/Y relative to the screen WorkingArea. @@ -532,8 +550,21 @@ private void ApplyHolePunchEffect( // Punch a transparent hole under the ring by excluding a circle geometry from the frame // Convert window coordinates to geometry local coordinates by subtracting stored offsets var localCenter = new System.Windows.Point(windowPt.X - pathOffsetX, windowPt.Y - pathOffsetY); - var hole = new EllipseGeometry(localCenter, holeRadius, holeRadius); - borderPath.Data = new CombinedGeometry(GeometryCombineMode.Exclude, baseGeometry, hole); + if (holeCache.BaseGeometry != baseGeometry || + holeCache.Hole == null || + holeCache.Hole.RadiusX != holeRadius || + holeCache.Combined == null) + { + holeCache.BaseGeometry = baseGeometry; + holeCache.Hole = new EllipseGeometry(localCenter, holeRadius, holeRadius); + holeCache.Combined = new CombinedGeometry(GeometryCombineMode.Exclude, baseGeometry, holeCache.Hole); + } + else + { + holeCache.Hole.Center = localCenter; + } + + borderPath.Data = holeCache.Combined; } else { @@ -855,29 +886,7 @@ private void UpdateAdditionalMonitorWindows() var path = ctx.BorderPath; path.Opacity = currentOpacity; path.Visibility = isLightOn ? Visibility.Visible : Visibility.Collapsed; - - // Update color temperature - if (path.Fill is LinearGradientBrush brush && brush.GradientStops.Count >= 3) - { - var cool = System.Windows.Media.Color.FromRgb(220, 235, 255); - var warm = System.Windows.Media.Color.FromRgb(255, 220, 180); - - System.Windows.Media.Color Lerp(System.Windows.Media.Color a, System.Windows.Media.Color b, double t) - { - byte LerpByte(byte x, byte y, double tt) => (byte)(x + (y - x) * tt); - return System.Windows.Media.Color.FromArgb(255, LerpByte(a.R, b.R, t), LerpByte(a.G, b.G, t), LerpByte(a.B, b.B, t)); - } - - var midColor = Lerp(cool, warm, _colorTemperature); - - foreach (var stop in brush.GradientStops) - { - if (stop.Offset is > 0.2 and < 0.8) - { - stop.Color = midColor; - } - } - } + ApplyColorTemperature(path); } } @@ -894,39 +903,7 @@ public void DecreaseColorTemperature() public void SetColorTemperature(double value, bool save = true) { _colorTemperature = Math.Max(MinColorTemp, Math.Min(MaxColorTemp, value)); - - // Map 0-1 slider to a simple cool-to-warm gradient. - // We'll bias the inner gradient stops from blueish-white (cool) to amber (warm). - // NOTE: This assumes the brush defined in XAML is still a LinearGradientBrush. - if (EdgeLightBorder.Fill is LinearGradientBrush brush && brush.GradientStops.Count >= 3) - { - // Cool: RGB ~ (220, 235, 255), Warm: RGB ~ (255, 220, 180) - System.Windows.Media.Color Lerp(System.Windows.Media.Color a, System.Windows.Media.Color b, double t) - { - byte LerpByte(byte x, byte y, double tt) => (byte)(x + (y - x) * tt); - - return System.Windows.Media.Color.FromArgb( - 255, - LerpByte(a.R, b.R, t), - LerpByte(a.G, b.G, t), - LerpByte(a.B, b.B, t)); - } - - var cool = System.Windows.Media.Color.FromRgb(220, 235, 255); - var warm = System.Windows.Media.Color.FromRgb(255, 220, 180); - - var midColor = Lerp(cool, warm, _colorTemperature); - - // Update a couple of inner stops to shift perceived temperature - // Keep outer rim relatively neutral for consistent edge. - foreach (var stop in brush.GradientStops) - { - if (stop.Offset is > 0.2 and < 0.8) - { - stop.Color = midColor; - } - } - } + ApplyColorTemperature(EdgeLightBorder); // Update all additional monitor windows UpdateAdditionalMonitorWindows(); @@ -944,7 +921,7 @@ public void MoveToNextMonitor() if (showOnAllMonitors) return; // Refresh monitor list in case of hot-plug/unplug - availableMonitors = Screen.AllScreens; + RefreshAvailableMonitors(); if (availableMonitors.Length <= 1) { @@ -993,8 +970,8 @@ public void MoveToNextMonitor() _isManualMonitorSwitch = false; } - // Reposition control window to follow - RepositionControlWindow(); + // An explicit monitor switch should bring the controls to the selected monitor. + ResetControlWindowPosition(); } [DllImport("user32.dll", SetLastError = true)] @@ -1021,8 +998,7 @@ public void ToggleAllMonitors() private void ShowOnAllMonitors() { - // Refresh monitor list - availableMonitors = Screen.AllScreens; + RefreshAvailableMonitors(); // Close any existing additional windows HideAdditionalMonitorWindows(); @@ -1084,26 +1060,26 @@ private MonitorWindowContext CreateMonitorWindow(Screen screen) Visibility = isLightOn ? Visibility.Visible : Visibility.Collapsed }; - // Create gradient brush + var temperatureColor = GetColorForTemperature(_colorTemperature); var gradient = new LinearGradientBrush { StartPoint = new System.Windows.Point(0, 0), EndPoint = new System.Windows.Point(1, 1) }; gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(255, 255, 255), 0.0)); - gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(240, 240, 240), 0.3)); - gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(255, 255, 255), 0.5)); - gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(240, 240, 240), 0.7)); + gradient.GradientStops.Add(new GradientStop(temperatureColor, 0.3)); + gradient.GradientStops.Add(new GradientStop(temperatureColor, 0.5)); + gradient.GradientStops.Add(new GradientStop(temperatureColor, 0.7)); gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(255, 255, 255), 1.0)); path.Fill = gradient; // Add drop shadow effect - path.Effect = new System.Windows.Media.Effects.DropShadowEffect + path.Effect = new DropShadowEffect { BlurRadius = 76, Opacity = 1, ShadowDepth = 0, - Color = System.Windows.Media.Color.FromRgb(255, 255, 255) + Color = temperatureColor }; // Create hover ring (Ellipse) @@ -1282,7 +1258,7 @@ public void ResetControlWindowPosition() public bool HasMultipleMonitors() { // Refresh monitor count to handle hot-plug scenarios - availableMonitors = Screen.AllScreens; + RefreshAvailableMonitors(); return availableMonitors.Length > 1; } @@ -1295,6 +1271,13 @@ public bool IsExcludeFromCaptureEnabled() public double GetColorTemperature() => _colorTemperature; + public void SaveAppearanceSettings() + { + settings.Brightness = currentOpacity; + settings.ColorTemperature = _colorTemperature; + settings.Save(); + } + public bool GetIsToggleButtonVisible() => settings.ShowToggleButton; public bool GetIsBrightnessButtonsVisible() => settings.ShowBrightnessButtons; @@ -1356,8 +1339,7 @@ private void UpdateCurrentMonitorIndex() // If we are manually switching, trust the index we set explicitly if (_isManualMonitorSwitch) return; - // Refresh monitor list - availableMonitors = Screen.AllScreens; + RefreshAvailableMonitors(); if (availableMonitors.Length == 0) return; @@ -1382,6 +1364,55 @@ private void UpdateCurrentMonitorIndex() // Window might not be loaded or visible yet } } + + private void RefreshAvailableMonitors() + { + availableMonitors = Screen.AllScreens; + currentMonitorIndex = availableMonitors.Length == 0 + ? 0 + : Math.Clamp(currentMonitorIndex, 0, availableMonitors.Length - 1); + } + + private Screen? GetCurrentScreen() + { + if (availableMonitors.Length == 0) + { + return Screen.PrimaryScreen; + } + + currentMonitorIndex = Math.Clamp(currentMonitorIndex, 0, availableMonitors.Length - 1); + return availableMonitors[currentMonitorIndex]; + } + + private static MediaColor GetColorForTemperature(double temperature) + { + byte Lerp(byte cool, byte warm) => (byte)(cool + ((warm - cool) * temperature)); + return MediaColor.FromRgb( + Lerp(CoolColor.R, WarmColor.R), + Lerp(CoolColor.G, WarmColor.G), + Lerp(CoolColor.B, WarmColor.B)); + } + + private void ApplyColorTemperature(System.Windows.Shapes.Path path) + { + var temperatureColor = GetColorForTemperature(_colorTemperature); + + if (path.Fill is LinearGradientBrush brush) + { + foreach (var stop in brush.GradientStops) + { + if (stop.Offset is > 0.2 and < 0.8) + { + stop.Color = temperatureColor; + } + } + } + + if (path.Effect is DropShadowEffect shadow) + { + shadow.Color = temperatureColor; + } + } private (double dpiScaleX, double dpiScaleY) GetDpiForScreen(Screen screen) { diff --git a/WindowsEdgeLight/SettingsWindow.xaml.cs b/WindowsEdgeLight/SettingsWindow.xaml.cs index 0128cf6..edcab9c 100644 --- a/WindowsEdgeLight/SettingsWindow.xaml.cs +++ b/WindowsEdgeLight/SettingsWindow.xaml.cs @@ -1,5 +1,7 @@ using System.Windows; using System.Windows.Controls; +using System.Windows.Interop; +using System.Windows.Media; namespace WindowsEdgeLight; @@ -59,7 +61,16 @@ private void SettingsWindow_Loaded(object sender, RoutedEventArgs e) } const double gap = 12; - var workArea = SystemParameters.WorkArea; + var ownerHandle = new WindowInteropHelper(Owner).Handle; + var screen = System.Windows.Forms.Screen.FromHandle(ownerHandle); + var transformFromDevice = PresentationSource.FromVisual(Owner)? + .CompositionTarget?.TransformFromDevice ?? Matrix.Identity; + var workArea = new Rect( + screen.WorkingArea.X * transformFromDevice.M11, + screen.WorkingArea.Y * transformFromDevice.M22, + screen.WorkingArea.Width * transformFromDevice.M11, + screen.WorkingArea.Height * transformFromDevice.M22); + MaxHeight = Math.Max(200, workArea.Height - (gap * 2)); var desiredLeft = Owner.Left + ((Owner.ActualWidth - ActualWidth) / 2); Left = Math.Min(Math.Max(desiredLeft, workArea.Left + gap), workArea.Right - ActualWidth - gap); @@ -83,8 +94,7 @@ private void SettingsWindow_Loaded(object sender, RoutedEventArgs e) private void SettingsWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e) { - mainWindow.SetBrightness(BrightnessSlider.Value, save: true); - mainWindow.SetColorTemperature(ColorTempSlider.Value, save: true); + mainWindow.SaveAppearanceSettings(); } private void ExcludeFromCapture_Click(object sender, RoutedEventArgs e)