GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: add cpu, gpu, memory, text file, and weather bar components (#297)
Sewere24f55669172
diff --git a/.editorconfig b/.editorconfigindex a7c8feb1..4283ada2 100644--- a/.editorconfig+++ b/.editorconfig@@ -151,6 +151,9 @@ csharp_preserve_single_line_blocks = true# Analyzer Rules ################################+# Suppress 'async void lambda' warning in JetBrains editors.+resharper_async_void_lambda_highlighting = hint+roslynator_refactorings.enabled = trueroslynator_compiler_diagnostic_fixes.enabled = truediff --git a/GlazeWM.Bar/BarViewModel.cs b/GlazeWM.Bar/BarViewModel.csindex 46827ef9..9b5bfa07 100644--- a/GlazeWM.Bar/BarViewModel.cs+++ b/GlazeWM.Bar/BarViewModel.cs@@ -74,7 +74,9 @@ namespace GlazeWM.BarList<ComponentViewModel> componentViewModels, TextComponentViewModel componentSeparator){- componentViewModels.Intersperse(componentSeparator);+ if (!string.IsNullOrEmpty(componentSeparator.Text))+ componentViewModels.Intersperse(componentSeparator);+return componentViewModels;}@@ -97,12 +99,17 @@ namespace GlazeWM.BarBindingModeComponentConfig bmc => new BindingModeComponentViewModel(this, bmc),ClockComponentConfig ccc => new ClockComponentViewModel(this, ccc),TextComponentConfig tcc => new TextComponentViewModel(this, tcc),+ WeatherComponentConfig wcc => new WeatherComponentViewModel(this, wcc),NetworkComponentConfig ncc => new NetworkComponentViewModel(this, ncc),TilingDirectionComponentConfig tdc => new TilingDirectionComponentViewModel(this, tdc),WorkspacesComponentConfig wcc => new WorkspacesComponentViewModel(this, wcc),WindowTitleComponentConfig wtcc => new WindowTitleComponentViewModel(this, wtcc),VolumeComponentConfig vcc => new VolumeComponentViewModel(this, vcc),SystemTrayComponentConfig stcc => new SystemTrayComponentViewModel(this, stcc),+ CpuComponentConfig cpupc => new CpuComponentViewModel(this, cpupc),+ GpuComponentConfig gpupc => new GpuComponentViewModel(this, gpupc),+ MemoryComponentConfig rampc => new MemoryComponentViewModel(this, rampc),+ TextFileComponentConfig stc => new TextFileComponentViewModel(this, stc),_ => throw new ArgumentOutOfRangeException(nameof(config)),});}diff --git a/GlazeWM.Bar/Components/BatteryComponentViewModel.cs b/GlazeWM.Bar/Components/BatteryComponentViewModel.csindex e91ccfde..2ba5dc98 100644--- a/GlazeWM.Bar/Components/BatteryComponentViewModel.cs+++ b/GlazeWM.Bar/Components/BatteryComponentViewModel.cs@@ -67,11 +67,11 @@ namespace GlazeWM.Bar.Components);}- public static Dictionary<string, string> CreateVariableDict(string batteryLevel)+ public static Dictionary<string, Func<string>> CreateVariableDict(string batteryLevel){return new(){- { "battery_level", batteryLevel }+ { "battery_level", () => batteryLevel }};}}diff --git a/GlazeWM.Bar/Components/ComponentPortal.xaml b/GlazeWM.Bar/Components/ComponentPortal.xamlindex 7cca2484..6b36b65d 100644--- a/GlazeWM.Bar/Components/ComponentPortal.xaml+++ b/GlazeWM.Bar/Components/ComponentPortal.xaml@@ -17,31 +17,74 @@<ContentPresenter Content="{Binding .}"><ContentPresenter.Resources><DataTemplate DataType="{x:Type components:BatteryComponentViewModel}">- <components:BatteryComponent Padding="{Binding Padding}" Background="{Binding Background}" />+ <components:BatteryComponent+ Padding="{Binding Padding}"+ Background="{Binding Background}" /></DataTemplate><DataTemplate DataType="{x:Type components:BindingModeComponentViewModel}">- <components:BindingModeComponent Padding="{Binding Padding}" Background="{Binding Background}" />+ <components:BindingModeComponent+ Padding="{Binding Padding}"+ Background="{Binding Background}" /></DataTemplate><DataTemplate DataType="{x:Type components:ClockComponentViewModel}">- <components:ClockComponent Padding="{Binding Padding}" Background="{Binding Background}" />+ <components:ClockComponent+ Padding="{Binding Padding}"+ Background="{Binding Background}" /></DataTemplate><DataTemplate DataType="{x:Type components:TextComponentViewModel}">- <components:TextComponent Padding="{Binding Padding}" Background="{Binding Background}" />+ <components:TextComponent+ Padding="{Binding Padding}"+ Background="{Binding Background}" /></DataTemplate><DataTemplate DataType="{x:Type components:NetworkComponentViewModel}">- <components:NetworkComponent Padding="{Binding Padding}" Background="{Binding Background}" />+ <components:NetworkComponent+ Padding="{Binding Padding}"+ Background="{Binding Background}" /></DataTemplate><DataTemplate DataType="{x:Type components:WindowTitleComponentViewModel}">- <components:WindowTitleComponent Padding="{Binding Padding}" Background="{Binding Background}" />+ <components:WindowTitleComponent+ Padding="{Binding Padding}"+ Background="{Binding Background}" /></DataTemplate><DataTemplate DataType="{x:Type components:SystemTrayComponentViewModel}">- <components:SystemTrayComponent Padding="{Binding Padding}" Background="{Binding Background}" />+ <components:SystemTrayComponent+ Padding="{Binding Padding}"+ Background="{Binding Background}" /></DataTemplate><DataTemplate DataType="{x:Type components:TilingDirectionComponentViewModel}">- <components:TilingDirectionComponent Padding="{Binding Padding}" Background="{Binding Background}" />+ <components:TilingDirectionComponent+ Padding="{Binding Padding}"+ Background="{Binding Background}" /></DataTemplate><DataTemplate DataType="{x:Type components:WorkspacesComponentViewModel}">- <components:WorkspacesComponent Padding="{Binding Padding}" Background="{Binding Background}" />+ <components:WorkspacesComponent+ Padding="{Binding Padding}"+ Background="{Binding Background}" />+ </DataTemplate>+ <DataTemplate DataType="{x:Type components:CpuComponentViewModel}">+ <components:CpuComponent+ Padding="{Binding Padding}"+ Background="{Binding Background}" />+ </DataTemplate>+ <DataTemplate DataType="{x:Type components:GpuComponentViewModel}">+ <components:GpuComponent+ Padding="{Binding Padding}"+ Background="{Binding Background}" />+ </DataTemplate>+ <DataTemplate DataType="{x:Type components:MemoryComponentViewModel}">+ <components:MemoryComponent+ Padding="{Binding Padding}"+ Background="{Binding Background}" />+ </DataTemplate>+ <DataTemplate DataType="{x:Type components:TextFileComponentViewModel}">+ <components:TextFileComponent+ Padding="{Binding Padding}"+ Background="{Binding Background}" />+ </DataTemplate>+ <DataTemplate DataType="{x:Type components:WeatherComponentViewModel}">+ <components:WeatherComponent+ Padding="{Binding Padding}"+ Background="{Binding Background}" /></DataTemplate><DataTemplate DataType="{x:Type components:VolumeComponentViewModel}"><components:VolumeComponent />diff --git a/GlazeWM.Bar/Components/CpuComponent.xaml b/GlazeWM.Bar/Components/CpuComponent.xamlnew file mode 100644index 00000000..cec71c2a--- /dev/null+++ b/GlazeWM.Bar/Components/CpuComponent.xaml@@ -0,0 +1,10 @@+<UserControl+ x:Class="GlazeWM.Bar.Components.CpuComponent"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"+ xmlns:components="clr-namespace:GlazeWM.Bar.Components"+ mc:Ignorable="d">+ <components:LabelComponent DataContext="{Binding Label}" />+</UserControl>diff --git a/GlazeWM.Bar/Components/CpuComponent.xaml.cs b/GlazeWM.Bar/Components/CpuComponent.xaml.csnew file mode 100644index 00000000..020ce530--- /dev/null+++ b/GlazeWM.Bar/Components/CpuComponent.xaml.cs@@ -0,0 +1,15 @@+using System.Windows.Controls;++namespace GlazeWM.Bar.Components+{+ /// <summary>+ /// Interaction logic for CpuComponent.xaml+ /// </summary>+ public partial class CpuComponent : UserControl+ {+ public CpuComponent()+ {+ InitializeComponent();+ }+ }+}diff --git a/GlazeWM.Bar/Components/CpuComponentViewModel.cs b/GlazeWM.Bar/Components/CpuComponentViewModel.csnew file mode 100644index 00000000..5abb143c--- /dev/null+++ b/GlazeWM.Bar/Components/CpuComponentViewModel.cs@@ -0,0 +1,51 @@+using System;+using System.Collections.Generic;+using System.Globalization;+using System.Reactive.Linq;+using GlazeWM.Domain.UserConfigs;+using GlazeWM.Infrastructure;+using GlazeWM.Infrastructure.WindowsApi;++namespace GlazeWM.Bar.Components+{+ public class CpuComponentViewModel : ComponentViewModel+ {+ private readonly CpuComponentConfig _config;+ private readonly CpuStatsService _cpuStatsService;++ private LabelViewModel _label;+ public LabelViewModel Label+ {+ get => _label;+ protected set => SetField(ref _label, value);+ }++ public CpuComponentViewModel(+ BarViewModel parentViewModel,+ CpuComponentConfig config) : base(parentViewModel, config)+ {+ _config = config;+ _cpuStatsService = ServiceLocator.GetRequiredService<CpuStatsService>();++ Observable.Timer(+ TimeSpan.Zero,+ TimeSpan.FromMilliseconds(_config.RefreshIntervalMs)+ )+ .TakeUntil(_parentViewModel.WindowClosing)+ .Subscribe((_) => Label = CreateLabel());+ }++ private LabelViewModel CreateLabel()+ {+ var variableDictionary = new Dictionary<string, Func<string>>()+ {+ {+ "percent_usage",+ () => _cpuStatsService.GetCpuUsage().ToString("0", CultureInfo.InvariantCulture)+ }+ };++ return XamlHelper.ParseLabel(_config.Label, variableDictionary, this);+ }+ }+}diff --git a/GlazeWM.Bar/Components/GpuComponent.xaml b/GlazeWM.Bar/Components/GpuComponent.xamlnew file mode 100644index 00000000..72234924--- /dev/null+++ b/GlazeWM.Bar/Components/GpuComponent.xaml@@ -0,0 +1,10 @@+<UserControl+ x:Class="GlazeWM.Bar.Components.GpuComponent"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"+ xmlns:components="clr-namespace:GlazeWM.Bar.Components"+ mc:Ignorable="d">+ <components:LabelComponent DataContext="{Binding Label}" />+</UserControl>diff --git a/GlazeWM.Bar/Components/GpuComponent.xaml.cs b/GlazeWM.Bar/Components/GpuComponent.xaml.csnew file mode 100644index 00000000..3d47bd15--- /dev/null+++ b/GlazeWM.Bar/Components/GpuComponent.xaml.cs@@ -0,0 +1,15 @@+using System.Windows.Controls;++namespace GlazeWM.Bar.Components+{+ /// <summary>+ /// Interaction logic for GpuComponent.xaml+ /// </summary>+ public partial class GpuComponent : UserControl+ {+ public GpuComponent()+ {+ InitializeComponent();+ }+ }+}diff --git a/GlazeWM.Bar/Components/GpuComponentViewModel.cs b/GlazeWM.Bar/Components/GpuComponentViewModel.csnew file mode 100644index 00000000..1fca9386--- /dev/null+++ b/GlazeWM.Bar/Components/GpuComponentViewModel.cs@@ -0,0 +1,54 @@+using System;+using System.Collections.Generic;+using System.Globalization;+using System.Reactive.Linq;+using GlazeWM.Domain.UserConfigs;+using GlazeWM.Infrastructure;+using GlazeWM.Infrastructure.WindowsApi;++namespace GlazeWM.Bar.Components+{+ public class GpuComponentViewModel : ComponentViewModel+ {+ private readonly GpuComponentConfig _config;+ private readonly GpuStatsService _gpuStatsService;++ private LabelViewModel _label;+ public LabelViewModel Label+ {+ get => _label;+ protected set => SetField(ref _label, value);+ }++ public GpuComponentViewModel(+ BarViewModel parentViewModel,+ GpuComponentConfig config) : base(parentViewModel, config)+ {+ _config = config;+ _gpuStatsService = ServiceLocator.GetRequiredService<GpuStatsService>();++ Observable.Timer(+ TimeSpan.Zero,+ TimeSpan.FromMilliseconds(_config.RefreshIntervalMs)+ )+ .TakeUntil(_parentViewModel.WindowClosing)+ .Subscribe((_) => Label = CreateLabel());+ }++ private LabelViewModel CreateLabel()+ {+ var variableDictionary = new Dictionary<string, Func<string>>()+ {+ {+ "percent_usage",+ () =>+ _gpuStatsService+ .GetAverageLoadPercent(GpuPerformanceCategoryFlags.Graphics)+ .ToString("0", CultureInfo.InvariantCulture)+ }+ };++ return XamlHelper.ParseLabel(_config.Label, variableDictionary, this);+ }+ }+}diff --git a/GlazeWM.Bar/Components/MemoryComponent.xaml b/GlazeWM.Bar/Components/MemoryComponent.xamlnew file mode 100644index 00000000..5a007621--- /dev/null+++ b/GlazeWM.Bar/Components/MemoryComponent.xaml@@ -0,0 +1,10 @@+<UserControl+ x:Class="GlazeWM.Bar.Components.MemoryComponent"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"+ xmlns:components="clr-namespace:GlazeWM.Bar.Components"+ mc:Ignorable="d">+ <components:LabelComponent DataContext="{Binding Label}" />+</UserControl>diff --git a/GlazeWM.Bar/Components/MemoryComponent.xaml.cs b/GlazeWM.Bar/Components/MemoryComponent.xaml.csnew file mode 100644index 00000000..106fcd11--- /dev/null+++ b/GlazeWM.Bar/Components/MemoryComponent.xaml.cs@@ -0,0 +1,15 @@+using System.Windows.Controls;++namespace GlazeWM.Bar.Components+{+ /// <summary>+ /// Interaction logic for MemoryComponent.xaml+ /// </summary>+ public partial class MemoryComponent : UserControl+ {+ public MemoryComponent()+ {+ InitializeComponent();+ }+ }+}diff --git a/GlazeWM.Bar/Components/MemoryComponentViewModel.cs b/GlazeWM.Bar/Components/MemoryComponentViewModel.csnew file mode 100644index 00000000..49383639--- /dev/null+++ b/GlazeWM.Bar/Components/MemoryComponentViewModel.cs@@ -0,0 +1,51 @@+using System;+using System.Collections.Generic;+using System.Globalization;+using System.Reactive.Linq;+using GlazeWM.Domain.UserConfigs;+using GlazeWM.Infrastructure;+using GlazeWM.Infrastructure.WindowsApi;++namespace GlazeWM.Bar.Components+{+ public class MemoryComponentViewModel : ComponentViewModel+ {+ private readonly MemoryComponentConfig _config;+ private readonly MemoryStatsService _memoryStatsService;++ private LabelViewModel _label;+ public LabelViewModel Label+ {+ get => _label;+ protected set => SetField(ref _label, value);+ }++ public MemoryComponentViewModel(+ BarViewModel parentViewModel,+ MemoryComponentConfig config) : base(parentViewModel, config)+ {+ _config = config;+ _memoryStatsService = ServiceLocator.GetRequiredService<MemoryStatsService>();++ Observable.Timer(+ TimeSpan.Zero,+ TimeSpan.FromMilliseconds(_config.RefreshIntervalMs)+ )+ .TakeUntil(_parentViewModel.WindowClosing)+ .Subscribe((_) => Label = CreateLabel());+ }++ private LabelViewModel CreateLabel()+ {+ var variableDictionary = new Dictionary<string, Func<string>>()+ {+ {+ "percent_usage",+ () => _memoryStatsService.GetMemoryUsage().ToString("0", CultureInfo.InvariantCulture)+ }+ };++ return XamlHelper.ParseLabel(_config.Label, variableDictionary, this);+ }+ }+}diff --git a/GlazeWM.Bar/Components/TextFileComponent.xaml b/GlazeWM.Bar/Components/TextFileComponent.xamlnew file mode 100644index 00000000..9575773f--- /dev/null+++ b/GlazeWM.Bar/Components/TextFileComponent.xaml@@ -0,0 +1,17 @@+<UserControl+ x:Class="GlazeWM.Bar.Components.TextFileComponent"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"+ xmlns:local="clr-namespace:GlazeWM.Bar.Components"+ mc:Ignorable="d">+ <TextBlock+ VerticalAlignment="Center"+ Foreground="{Binding Foreground}"+ FontFamily="{Binding FontFamily}"+ FontWeight="{Binding FontWeight}"+ FontSize="{Binding FontSize}"+ Text="{Binding Text}">+ </TextBlock>+</UserControl>diff --git a/GlazeWM.Bar/Components/TextFileComponent.xaml.cs b/GlazeWM.Bar/Components/TextFileComponent.xaml.csnew file mode 100644index 00000000..0baa7f37--- /dev/null+++ b/GlazeWM.Bar/Components/TextFileComponent.xaml.cs@@ -0,0 +1,15 @@+using System.Windows.Controls;++namespace GlazeWM.Bar.Components+{+ /// <summary>+ /// Interaction logic for TextFileComponent.xaml+ /// </summary>+ public partial class TextFileComponent : UserControl+ {+ public TextFileComponent()+ {+ InitializeComponent();+ }+ }+}diff --git a/GlazeWM.Bar/Components/TextFileComponentViewModel.cs b/GlazeWM.Bar/Components/TextFileComponentViewModel.csnew file mode 100644index 00000000..f4c0c22f--- /dev/null+++ b/GlazeWM.Bar/Components/TextFileComponentViewModel.cs@@ -0,0 +1,85 @@+using System;+using System.IO;+using System.Reactive.Linq;+using System.Threading;+using GlazeWM.Domain.UserConfigs;+using GlazeWM.Domain.UserConfigs.Events;+using GlazeWM.Infrastructure;+using GlazeWM.Infrastructure.Bussing;++namespace GlazeWM.Bar.Components+{+ public class TextFileComponentViewModel : ComponentViewModel+ {+ private readonly TextFileComponentConfig _baseConfig;+ private readonly IDisposable _disposable;++ public string Text { get; set; } = "Loading...";++ public FileSystemWatcher Watcher { get; }++ public TextFileComponentViewModel(BarViewModel parentViewModel, TextFileComponentConfig baseConfig) : base(parentViewModel, baseConfig)+ {+ _baseConfig = baseConfig;++ var bus = ServiceLocator.GetRequiredService<Bus>();+ _disposable = bus.Events.OfType<UserConfigReloadedEvent>().Subscribe(_ => Dispose(true));++ Watcher = new FileSystemWatcher(Path.GetDirectoryName(_baseConfig.FilePath)!)+ {+ Filter = Path.GetFileName(_baseConfig.FilePath)!,+ EnableRaisingEvents = true,+ NotifyFilter = NotifyFilters.LastWrite+ };+ Watcher.Changed += OnFileChanged;+ Update();+ }++ protected override void Dispose(bool disposing)+ {+ if (disposing)+ {+ Watcher.Dispose();+ _disposable.Dispose();+ }++ base.Dispose(disposing);+ }++ private void OnFileChanged(object sender, FileSystemEventArgs e)+ {+ Update();+ }++ private void Update()+ {+ var numAttempts = 0;+ var sleepTime = 32;+ const int maxRetries = 6;++ try+ {+ Watcher.EnableRaisingEvents = false;+ while (true)+ {+ try+ {+ Text = File.ReadAllText(_baseConfig.FilePath);+ OnPropertyChanged(nameof(Text));+ break;+ }+ catch (Exception) when (numAttempts < maxRetries)+ {+ numAttempts++;+ Thread.Sleep(sleepTime);+ sleepTime *= 2;+ }+ }+ }+ finally+ {+ Watcher.EnableRaisingEvents = true;+ }+ }+ }+}diff --git a/GlazeWM.Bar/Components/WeatherComponent.xaml b/GlazeWM.Bar/Components/WeatherComponent.xamlnew file mode 100644index 00000000..7e19f6dc--- /dev/null+++ b/GlazeWM.Bar/Components/WeatherComponent.xaml@@ -0,0 +1,10 @@+<UserControl+ x:Class="GlazeWM.Bar.Components.WeatherComponent"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"+ xmlns:components="clr-namespace:GlazeWM.Bar.Components"+ mc:Ignorable="d">+ <components:LabelComponent DataContext="{Binding Label}" />+</UserControl>diff --git a/GlazeWM.Bar/Components/WeatherComponent.xaml.cs b/GlazeWM.Bar/Components/WeatherComponent.xaml.csnew file mode 100644index 00000000..463ffa49--- /dev/null+++ b/GlazeWM.Bar/Components/WeatherComponent.xaml.cs@@ -0,0 +1,15 @@+using System.Windows.Controls;++namespace GlazeWM.Bar.Components+{+ /// <summary>+ /// Interaction logic for WeatherComponent.xaml+ /// </summary>+ public partial class WeatherComponent : UserControl+ {+ public WeatherComponent()+ {+ InitializeComponent();+ }+ }+}diff --git a/GlazeWM.Bar/Components/WeatherComponentViewModel.cs b/GlazeWM.Bar/Components/WeatherComponentViewModel.csnew file mode 100644index 00000000..26c9fc29--- /dev/null+++ b/GlazeWM.Bar/Components/WeatherComponentViewModel.cs@@ -0,0 +1,77 @@+using System;+using System.Collections.Generic;+using System.Globalization;+using System.Reactive.Linq;+using System.Threading.Tasks;+using GlazeWM.Domain.UserConfigs;+using GlazeWM.Infrastructure.Services;++namespace GlazeWM.Bar.Components+{+ public class WeatherComponentViewModel : ComponentViewModel+ {+ private readonly WeatherComponentConfig _config;++ private LabelViewModel _label;+ public LabelViewModel Label+ {+ get => _label;+ protected set => SetField(ref _label, value);+ }++ public WeatherComponentViewModel(+ BarViewModel parentViewModel,+ WeatherComponentConfig config) : base(parentViewModel, config)+ {+ _config = config;++ Observable.Timer(+ TimeSpan.Zero,+ TimeSpan.FromMilliseconds(_config.RefreshIntervalMs)+ )+ .TakeUntil(_parentViewModel.WindowClosing)+ .Subscribe(async (_) => await UpdateLabel());+ }++ private async Task UpdateLabel()+ {+ var weather = await WeatherService.GetWeatherAsync(_config.Latitude, _config.Longitude);++ var variableDictionary = new Dictionary<string, Func<string>>()+ {+ {+ "temperature_celsius",+ () => weather.Result.CurrentWeather.Temperature.ToString("0", CultureInfo.InvariantCulture)+ },+ {+ "temperature_fahrenheit",+ () =>+ WeatherService+ .ToFahrenheit(weather.Result.CurrentWeather.Temperature)+ .ToString("0", CultureInfo.InvariantCulture)+ }+ };++ var labelString = GetLabelStringFromStatus(weather.Status);+ Label = XamlHelper.ParseLabel(labelString, variableDictionary, this);+ }++ private string GetLabelStringFromStatus(WeatherStatus status)+ {+ return status switch+ {+ WeatherStatus.Sun => _config.LabelSun,+ WeatherStatus.Moon => _config.LabelMoon,+ WeatherStatus.CloudSun => _config.LabelCloudSun,+ WeatherStatus.CloudMoon => _config.LabelCloudMoon,+ WeatherStatus.Cloud => _config.LabelCloud,+ WeatherStatus.CloudSunRain => _config.LabelCloudSunRain,+ WeatherStatus.CloudMoonRain => _config.LabelCloudMoonRain,+ WeatherStatus.CloudRain => _config.LabelCloudRain,+ WeatherStatus.Snowflake => _config.LabelSnowflake,+ WeatherStatus.Thunder => _config.LabelThunderstorm,+ _ => _config.Label+ };+ }+ }+}diff --git a/GlazeWM.Bar/GlazeWM.Bar.csproj b/GlazeWM.Bar/GlazeWM.Bar.csprojindex fa47e674..92db9f27 100644--- a/GlazeWM.Bar/GlazeWM.Bar.csproj+++ b/GlazeWM.Bar/GlazeWM.Bar.csproj@@ -13,6 +13,21 @@</ItemGroup><ItemGroup>- <PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.39" />+ <PackageReference+ Include="Microsoft.Xaml.Behaviors.Wpf"+ Version="1.1.39" />+ </ItemGroup>++ <ItemGroup>+ <Page Update="Components\TextFileComponent.xaml">+ <Generator>MSBuild:Compile</Generator>+ <XamlRuntime>Wpf</XamlRuntime>+ <SubType>Designer</SubType>+ </Page>+ <Page Update="Components\WeatherComponent.xaml">+ <Generator>MSBuild:Compile</Generator>+ <XamlRuntime>Wpf</XamlRuntime>+ <SubType>Designer</SubType>+ </Page></ItemGroup></Project>diff --git a/GlazeWM.Bar/MainWindow.xaml b/GlazeWM.Bar/MainWindow.xamlindex c41f347d..70a6d1a9 100644--- a/GlazeWM.Bar/MainWindow.xaml+++ b/GlazeWM.Bar/MainWindow.xaml@@ -26,14 +26,9 @@BorderBrush="{Binding BorderColor}"Background="{Binding Background}"><Grid Margin="{Binding Padding}">- <Grid.ColumnDefinitions>- <ColumnDefinition Width="*" />- <ColumnDefinition Width="auto" />- <ColumnDefinition Width="*" />- </Grid.ColumnDefinitions><ItemsControl- Grid.Column="0"+ HorizontalAlignment="Left"ItemsSource="{Binding ComponentsLeft}"><ItemsControl.ItemsPanel><ItemsPanelTemplate>@@ -49,7 +44,7 @@</ItemsControl><ItemsControl- Grid.Column="1"+ HorizontalAlignment="Center"ItemsSource="{Binding ComponentsCenter}"><ItemsControl.ItemsPanel><ItemsPanelTemplate>@@ -65,7 +60,6 @@</ItemsControl><ItemsControl- Grid.Column="2"HorizontalAlignment="Right"ItemsSource="{Binding ComponentsRight}"><ItemsControl.ItemsPanel>diff --git a/GlazeWM.Bar/XamlHelper.cs b/GlazeWM.Bar/XamlHelper.csindex 9a8fdabc..4427eef4 100644--- a/GlazeWM.Bar/XamlHelper.cs+++ b/GlazeWM.Bar/XamlHelper.cs@@ -61,14 +61,14 @@ namespace GlazeWM.Barpublic static LabelViewModel ParseLabel(string labelString,- Dictionary<string, string> labelVariables,+ Dictionary<string, Func<string>> labelVariables,ComponentViewModel viewModel){var labelWithVariables = labelString;// Replace variables in label with their corresponding variable.foreach (var (key, value) in labelVariables)- labelWithVariables = labelWithVariables.Replace($"{{{key}}}", value);+ labelWithVariables = labelWithVariables.Replace($"{{{key}}}", value());// Wrap `labelString` in arbitrary tag to make it valid XML.var wrappedLabel = $"<Label>{labelWithVariables}</Label>";diff --git a/GlazeWM.Bootstrapper/GlazeWM.Bootstrapper.csproj b/GlazeWM.Bootstrapper/GlazeWM.Bootstrapper.csprojindex 4f576f58..7bcaeede 100644--- a/GlazeWM.Bootstrapper/GlazeWM.Bootstrapper.csproj+++ b/GlazeWM.Bootstrapper/GlazeWM.Bootstrapper.csproj@@ -3,7 +3,6 @@<PropertyGroup><OutputType>WinExe</OutputType><TargetFramework>net6.0-windows10.0.17763.0</TargetFramework>- <UseWindowsForms>true</UseWindowsForms><DebugType>embedded</DebugType><ApplicationIcon>Resources\icon.ico</ApplicationIcon><AssemblyName>GlazeWM</AssemblyName>diff --git a/GlazeWM.Domain/UserConfigs/BarComponentConfigConverter.cs b/GlazeWM.Domain/UserConfigs/BarComponentConfigConverter.csindex fccbf726..538b6dc6 100644--- a/GlazeWM.Domain/UserConfigs/BarComponentConfigConverter.cs+++ b/GlazeWM.Domain/UserConfigs/BarComponentConfigConverter.cs@@ -63,11 +63,35 @@ namespace GlazeWM.Domain.UserConfigsjsonObject.RootElement.ToString(),options),+ "weather" =>+ JsonSerializer.Deserialize<WeatherComponentConfig>(+ jsonObject.RootElement.ToString(),+ options+ ),"workspaces" =>JsonSerializer.Deserialize<WorkspacesComponentConfig>(jsonObject.RootElement.ToString(),options),+ "cpu" =>+ JsonSerializer.Deserialize<CpuComponentConfig>(+ jsonObject.RootElement.ToString(),+ options+ ),+ "gpu" =>+ JsonSerializer.Deserialize<GpuComponentConfig>(+ jsonObject.RootElement.ToString(),+ options+ ),+ "memory" =>+ JsonSerializer.Deserialize<MemoryComponentConfig>(+ jsonObject.RootElement.ToString(),+ options+ ),+ "text file" => JsonSerializer.Deserialize<TextFileComponentConfig>(+ jsonObject.RootElement.ToString(),+ options+ ),_ => throw new ArgumentException($"Invalid component type '{typeDiscriminator}'."),};}diff --git a/GlazeWM.Domain/UserConfigs/CpuComponentConfig.cs b/GlazeWM.Domain/UserConfigs/CpuComponentConfig.csnew file mode 100644index 00000000..c9c4569f--- /dev/null+++ b/GlazeWM.Domain/UserConfigs/CpuComponentConfig.cs@@ -0,0 +1,15 @@+namespace GlazeWM.Domain.UserConfigs+{+ public class CpuComponentConfig : BarComponentConfig+ {+ /// <summary>+ /// Label assigned to the CPU component.+ /// </summary>+ public string Label { get; set; } = "CPU: {percent_usage}%";++ /// <summary>+ /// How often this component refreshes in milliseconds.+ /// </summary>+ public int RefreshIntervalMs { get; set; } = 1000;+ }+}diff --git a/GlazeWM.Domain/UserConfigs/GeneralConfig.cs b/GlazeWM.Domain/UserConfigs/GeneralConfig.csindex 3643c3c3..81c2dfe8 100644--- a/GlazeWM.Domain/UserConfigs/GeneralConfig.cs+++ b/GlazeWM.Domain/UserConfigs/GeneralConfig.cs@@ -15,6 +15,7 @@ namespace GlazeWM.Domain.UserConfigs/// Focus the window directly under the cursor at all times/// </summary>public bool FocusFollowsCursor { get; set; }+ /// <summary>/// Amount by which to move floating windows/// </summary>public string FloatingWindowMoveAmount { get; set; } = "5%";@@ -22,6 +23,7 @@ namespace GlazeWM.Domain.UserConfigs/// Color for border drawn around a focused window./// </summary>public string FocusBorderColor { get; set; } = "#FFFFFFFF";+ /// <summary>/// If activated, by switching to the current workspace the previous focused workspace is activated./// </summary>public bool ToggleWorkspaceOnRefocus { get; set; }diff --git a/GlazeWM.Domain/UserConfigs/GpuComponentConfig.cs b/GlazeWM.Domain/UserConfigs/GpuComponentConfig.csnew file mode 100644index 00000000..df9906a7--- /dev/null+++ b/GlazeWM.Domain/UserConfigs/GpuComponentConfig.cs@@ -0,0 +1,15 @@+namespace GlazeWM.Domain.UserConfigs+{+ public class GpuComponentConfig : BarComponentConfig+ {+ /// <summary>+ /// Label assigned to the GPU component.+ /// </summary>+ public string Label { get; set; } = "GPU: {percent_usage}%";++ /// <summary>+ /// How often this component refreshes in milliseconds.+ /// </summary>+ public int RefreshIntervalMs { get; set; } = 1000;+ }+}diff --git a/GlazeWM.Domain/UserConfigs/MemoryComponentConfig.cs b/GlazeWM.Domain/UserConfigs/MemoryComponentConfig.csnew file mode 100644index 00000000..0ceda207--- /dev/null+++ b/GlazeWM.Domain/UserConfigs/MemoryComponentConfig.cs@@ -0,0 +1,15 @@+namespace GlazeWM.Domain.UserConfigs+{+ public class MemoryComponentConfig : BarComponentConfig+ {+ /// <summary>+ /// Label assigned to the memory component.+ /// </summary>+ public string Label { get; set; } = "RAM: {percent_usage}%";++ /// <summary>+ /// How often this component refreshes in milliseconds.+ /// </summary>+ public int RefreshIntervalMs { get; set; } = 1000;+ }+}diff --git a/GlazeWM.Domain/UserConfigs/NetworkComponentConfig.cs b/GlazeWM.Domain/UserConfigs/NetworkComponentConfig.csindex 6b8afe7b..946cd608 100644--- a/GlazeWM.Domain/UserConfigs/NetworkComponentConfig.cs+++ b/GlazeWM.Domain/UserConfigs/NetworkComponentConfig.cs@@ -27,7 +27,7 @@ namespace GlazeWM.Domain.UserConfigs/// </summary>public string LabelEthernet { get; set; } = " ";/// <summary>- /// Label for connection to the internet.+ /// Label for connection to the internet./// </summary>public string LabelNoInternet { get; set; } = " ";diff --git a/GlazeWM.Domain/UserConfigs/TextFileComponentConfig.cs b/GlazeWM.Domain/UserConfigs/TextFileComponentConfig.csnew file mode 100644index 00000000..13ee20bc--- /dev/null+++ b/GlazeWM.Domain/UserConfigs/TextFileComponentConfig.cs@@ -0,0 +1,7 @@+namespace GlazeWM.Domain.UserConfigs+{+ public class TextFileComponentConfig : BarComponentConfig+ {+ public string FilePath { get; set; }+ }+}diff --git a/GlazeWM.Domain/UserConfigs/WeatherComponentConfig.cs b/GlazeWM.Domain/UserConfigs/WeatherComponentConfig.csnew file mode 100644index 00000000..8c41c77d--- /dev/null+++ b/GlazeWM.Domain/UserConfigs/WeatherComponentConfig.cs@@ -0,0 +1,75 @@+namespace GlazeWM.Domain.UserConfigs+{+ public class WeatherComponentConfig : BarComponentConfig+ {+ /// <summary>+ /// Latitude to retreive weather.+ /// </summary>+ public float Latitude { get; set; }++ /// <summary>+ /// Longitude to retrieve weather.+ /// </summary>+ public float Longitude { get; set; }++ /// <summary>+ /// How often this component refreshes in milliseconds.+ /// </summary>+ public int RefreshIntervalMs { get; set; } = 60 * 60 * 1000;++ /// <summary>+ /// Default label.+ /// </summary>+ public string Label { get; set; } = "{temperature_celsius}°C";++ /// <summary>+ /// Label to represent sunny weather.+ /// </summary>+ public string LabelSun { get; set; } = "☀️ {temperature_celsius}°C";++ /// <summary>+ /// Label to represent clear weather at night.+ /// </summary>+ public string LabelMoon { get; set; } = "🌙 {temperature_celsius}°C";++ /// <summary>+ /// Label to represent partly cloudy at night.+ /// </summary>+ public string LabelCloudMoon { get; set; } = "🌙☁️ {temperature_celsius}°C";++ /// <summary>+ /// Label to represent partly cloudy.+ /// </summary>+ public string LabelCloudSun { get; set; } = "⛅ {temperature_celsius}°C";++ /// <summary>+ /// Label to represent light rain at night.+ /// </summary>+ public string LabelCloudMoonRain { get; set; } = "🌙🌧️ {temperature_celsius}°C";++ /// <summary>+ /// Label to represent light rain.+ /// </summary>+ public string LabelCloudSunRain { get; set; } = "🌦️ {temperature_celsius}°C";++ /// <summary>+ /// Label to represent heavy rain.+ /// </summary>+ public string LabelCloudRain { get; set; } = "🌧️ {temperature_celsius}°C";++ /// <summary>+ /// Label to represent snow.+ /// </summary>+ public string LabelSnowflake { get; set; } = "❄️ {temperature_celsius}°C";++ /// <summary>+ /// Label to represent a thunderstorm.+ /// </summary>+ public string LabelThunderstorm { get; set; } = "⚡ {temperature_celsius}°C";++ /// <summary>+ /// Label to represent heavy clouds.+ /// </summary>+ public string LabelCloud { get; set; } = "☁️ {temperature_celsius}°C";+ }+}diff --git a/GlazeWM.Domain/Windows/WindowService.cs b/GlazeWM.Domain/Windows/WindowService.csindex b04ffb4b..86444553 100644--- a/GlazeWM.Domain/Windows/WindowService.cs+++ b/GlazeWM.Domain/Windows/WindowService.cs@@ -57,8 +57,15 @@ namespace GlazeWM.Domain.Windows/// </summary>public static Process GetProcessOfHandle(IntPtr handle){- _ = GetWindowThreadProcessId(handle, out var processId);- return Array.Find(Process.GetProcesses(), process => process.Id == (int)processId);+ try+ {+ _ = GetWindowThreadProcessId(handle, out var processId);+ return Process.GetProcessById((int)processId);+ }+ catch (Exception)+ {+ return null;+ }}/// <summary>diff --git a/GlazeWM.Infrastructure/DependencyInjection.cs b/GlazeWM.Infrastructure/DependencyInjection.csindex b4930a55..d46cd3bc 100644--- a/GlazeWM.Infrastructure/DependencyInjection.cs+++ b/GlazeWM.Infrastructure/DependencyInjection.cs@@ -16,7 +16,9 @@ namespace GlazeWM.Infrastructureservices.AddSingleton<WindowEventService>();services.AddSingleton<JsonService>();services.AddSingleton<YamlService>();-+ services.AddSingleton<CpuStatsService>();+ services.AddSingleton<GpuStatsService>();+ services.AddSingleton<MemoryStatsService>();services.AddSingleton<SystemVolumeInformation>();services.AddSingleton<ICommandHandler<ExitApplicationCommand>, ExitApplicationHandler>();diff --git a/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csproj b/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csprojindex 275fa60a..1cd68d6f 100644--- a/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csproj+++ b/GlazeWM.Infrastructure/GlazeWM.Infrastructure.csproj@@ -7,19 +7,50 @@</PropertyGroup><ItemGroup>- <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />- <PackageReference Include="System.Reactive" Version="5.0.0" />- <PackageReference Include="Vanara.Core" Version="3.4.13" />- <PackageReference Include="Vanara.PInvoke.CoreAudio" Version="3.4.13" />- <PackageReference Include="Vanara.PInvoke.DwmApi" Version="3.4.13" />- <PackageReference Include="Vanara.PInvoke.Kernel32" Version="3.4.13" />- <PackageReference Include="Vanara.PInvoke.SHCore" Version="3.4.13" />- <PackageReference Include="Vanara.PInvoke.User32" Version="3.4.13" />- <PackageReference Include="Vanara.PInvoke.WlanApi" Version="3.4.12" />- <PackageReference Include="Vanara.PInvoke.IpHlpApi" Version="3.4.12" />- <PackageReference Include="YamlDotNet" Version="8.1.0" />- <PackageReference Include="Roslynator.Analyzers" Version="4.2.0" />- <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="7.0.0" />- <PackageReference Include="ManagedShell" Version="0.0.198" />+ <PackageReference+ Include="Microsoft.Extensions.Hosting"+ Version="6.0.1" />+ <PackageReference+ Include="System.Reactive"+ Version="5.0.0" />+ <PackageReference+ Include="Vanara.Core"+ Version="3.4.13" />+ <PackageReference+ Include="Vanara.PInvoke.CoreAudio"+ Version="3.4.13" />+ <PackageReference+ Include="Vanara.PInvoke.DwmApi"+ Version="3.4.13" />+ <PackageReference+ Include="Vanara.PInvoke.Kernel32"+ Version="3.4.13" />+ <PackageReference+ Include="Vanara.PInvoke.SHCore"+ Version="3.4.13" />+ <PackageReference+ Include="Vanara.PInvoke.User32"+ Version="3.4.13" />+ <PackageReference+ Include="Vanara.PInvoke.WlanApi"+ Version="3.4.12" />+ <PackageReference+ Include="Vanara.PInvoke.IpHlpApi"+ Version="3.4.12" />+ <PackageReference+ Include="Vostok.Sys.Metrics.PerfCounters"+ Version="0.0.6" />+ <PackageReference+ Include="YamlDotNet"+ Version="8.1.0" />+ <PackageReference+ Include="Roslynator.Analyzers"+ Version="4.2.0" />+ <PackageReference+ Include="Microsoft.CodeAnalysis.NetAnalyzers"+ Version="7.0.0" />+ <PackageReference+ Include="ManagedShell"+ Version="0.0.198" /></ItemGroup></Project>diff --git a/GlazeWM.Infrastructure/Services/WeatherService.cs b/GlazeWM.Infrastructure/Services/WeatherService.csnew file mode 100644index 00000000..328d9a81--- /dev/null+++ b/GlazeWM.Infrastructure/Services/WeatherService.cs@@ -0,0 +1,151 @@+using System;+using System.Collections.Generic;+using System.Globalization;+using System.Net.Http;+using System.Text.Json;+using System.Text.Json.Serialization;+using System.Threading.Tasks;+using static GlazeWM.Infrastructure.Services.WeatherStatus;++namespace GlazeWM.Infrastructure.Services+{+ /// <summary>+ /// Service that queries current weather status using the OpenMeteo API.+ /// </summary>+ public static class WeatherService+ {+ /// <summary>+ /// Retrieves the current weather status asynchronously.+ /// </summary>+ /// <param name="latitude">Current latitude.</param>+ /// <param name="longitude">Current longitude.</param>+ public static async Task<WeatherServiceResult> GetWeatherAsync(float latitude, float longitude)+ {+ var lat = latitude.ToString(CultureInfo.InvariantCulture);+ var lng = longitude.ToString(CultureInfo.InvariantCulture);++ using var client = new HttpClient();++ var res = await client.GetStringAsync(+ "https://api.open-meteo.com/v1/forecast?latitude=" ++ lat ++ "&longitude=" ++ lng ++ "&temperature_unit=celsius¤t_weather=true&daily=sunset,sunrise&timezone=auto"+ );++ var weather = JsonSerializer.Deserialize<MeteoWeatherResult>(res);+ var isDaylight = IsDaytime(weather.Daily);+ var status = GetWeatherStatus(weather.CurrentWeather.WeatherCode, isDaylight);++ return new WeatherServiceResult(status, weather);+ }++ private static bool IsDaytime(MeteoDailyResult times)+ {+ var now = DateTime.Now;+ var sunsetToday = times.Sunset.Find(t => t.Day == now.Day);+ var sunriseToday = times.Sunrise.Find(t => t.Day == now.Day);+ return now > sunriseToday && now < sunsetToday;+ }++ public static double ToFahrenheit(double celsius)+ {+ return (celsius * 1.8) + 32;+ }++ private static WeatherStatus GetWeatherStatus(int code, bool isDaytime)+ {+ return code switch+ {+ // https://open-meteo.com/en/docs+ 0 => isDaytime ? Sun : Moon,+ < 3 => isDaytime ? CloudSun : CloudMoon,+ < 50 => Cloud,+ < 60 => isDaytime ? CloudSunRain : CloudMoonRain,+ < 70 => CloudRain,+ < 80 => Snowflake,+ < 83 => CloudRain,+ < 87 => Snowflake,+ < 99 => Thunder,+ _ => Sun+ };+ }+ }++ /// <summary>+ /// Result of individual weather service query.+ /// </summary>+ /// <param name="Status">Weather status.</param>+ /// <param name="Result">Result of the weather lookup.</param>+ public record WeatherServiceResult(WeatherStatus Status, MeteoWeatherResult Result);++ /// <summary>+ /// Describes the icon to use for a given returned weather code.+ /// </summary>+ public enum WeatherStatus+ {+ Sun,+ Moon,+ CloudSun,+ CloudMoon,+ Cloud,+ CloudSunRain,+ CloudMoonRain,+ CloudRain,+ Snowflake,+ Thunder+ }++ /// <summary>+ /// Temperature Unit returned from the API.+ /// </summary>+ public enum TemperatureUnit+ {+ /// <summary>+ /// Temperature is returned in Celsius (C).+ /// </summary>+ Celsius,++ /// <summary>+ /// Temperature is returned in Fahrenheit (F).+ /// </summary>+ Fahrenheit+ }++ public record MeteoWeatherResult+ {+ [JsonPropertyName("latitude")]+ public float Latitude { get; set; }++ [JsonPropertyName("longitude")]+ public float Longitude { get; set; }++ [JsonPropertyName("current_weather")]+ public MeteoCurrentWeatherResult CurrentWeather { get; set; }++ [JsonPropertyName("daily")]+ public MeteoDailyResult Daily { get; set; }+ }++ public record MeteoDailyResult+ {+ [JsonPropertyName("sunset")]+ public List<DateTime> Sunset { get; set; }++ [JsonPropertyName("sunrise")]+ public List<DateTime> Sunrise { get; set; }+ }++ public record MeteoCurrentWeatherResult+ {+ [JsonPropertyName("temperature")]+ public float Temperature { get; set; }++ [JsonPropertyName("weathercode")]+ public int WeatherCode { get; set; }++ [JsonPropertyName("time")]+ public DateTime Time { get; set; }+ }+}diff --git a/GlazeWM.Infrastructure/WindowsApi/CpuStatsService.cs b/GlazeWM.Infrastructure/WindowsApi/CpuStatsService.csnew file mode 100644index 00000000..fddb53e6--- /dev/null+++ b/GlazeWM.Infrastructure/WindowsApi/CpuStatsService.cs@@ -0,0 +1,36 @@+using System;+using Vostok.Sys.Metrics.PerfCounters;++namespace GlazeWM.Infrastructure.WindowsApi+{+ /// <summary>+ /// Provides access to current CPU statistics.+ /// </summary>+ public class CpuStatsService : IDisposable+ {+ private readonly IPerformanceCounter<double> _cpuCounter =+ PerformanceCounterFactory.Default.CreateCounter(+ "Processor Information",+ "% Processor Utility",+ "_Total"+ );++ /// <inheritdoc />+ ~CpuStatsService() => Dispose();++ /// <inheritdoc />+ public void Dispose()+ {+ _cpuCounter.Dispose();+ GC.SuppressFinalize(this);+ }++ /// <summary>+ /// Returns the current CPU utilization as a percentage.+ /// </summary>+ public double GetCpuUsage()+ {+ return _cpuCounter.Observe();+ }+ }+}diff --git a/GlazeWM.Infrastructure/WindowsApi/GpuStatsService.cs b/GlazeWM.Infrastructure/WindowsApi/GpuStatsService.csnew file mode 100644index 00000000..964728e5--- /dev/null+++ b/GlazeWM.Infrastructure/WindowsApi/GpuStatsService.cs@@ -0,0 +1,286 @@+using System;+using System.Collections.Generic;+using System.Diagnostics;+using System.Linq;+using System.Runtime.CompilerServices;+using Vostok.Sys.Metrics.PerfCounters;++namespace GlazeWM.Infrastructure.WindowsApi+{+ /// <summary>+ /// Provides access to current GPU statistics.+ /// </summary>+ public class GpuStatsService : IDisposable+ {+ private readonly PerformanceCounterCategory GpuEngineCategory = new("GPU Engine");++ /// <summary>+ /// Stats for individual GPU performance counters indexed by GpuPerformanceCategory.+ /// </summary>+ private readonly GpuStatsForType[] StatsForTypes =+ {+ new("engtype_3D"),+ new("engtype_LegacyOverlay"),+ new("engtype_VideoDecode"),+ new("engtype_Security"),+ new("engtype_Copy"),+ new("engtype_VideoEncode"),+ new("engtype_VR")+ };++ public void Dispose()+ {+ GC.SuppressFinalize(this);+ foreach (var stat in StatsForTypes)+ stat.Dispose();+ }++ ~GpuStatsService()+ {+ Dispose();+ }++ /// <summary>+ /// Returns the current GPU utilization (average of all GPUs) for a given set of categories.+ /// </summary>+ /// <param name="categories">Categories to fetch info for.</param>+ /// <returns>Average load.</returns>+ public float GetAverageLoadPercent(GpuPerformanceCategoryFlags categories)+ {+ var instanceNames = GpuEngineCategory.GetInstanceNames();+ var numCategories = 0;+ var totalValue = 0f;++ QueryCategory(categories, GpuPerformanceCategoryFlags.Copy, GpuPerformanceCategory.Copy, instanceNames, ref numCategories, ref totalValue);+ QueryCategory(categories, GpuPerformanceCategoryFlags.VideoDecode, GpuPerformanceCategory.VideoDecode, instanceNames, ref numCategories, ref totalValue);+ QueryCategory(categories, GpuPerformanceCategoryFlags.VideoEncode, GpuPerformanceCategory.VideoEncode, instanceNames, ref numCategories, ref totalValue);+ QueryCategory(categories, GpuPerformanceCategoryFlags.LegacyOverlay, GpuPerformanceCategory.LegacyOverlay, instanceNames, ref numCategories, ref totalValue);+ QueryCategory(categories, GpuPerformanceCategoryFlags.Graphics, GpuPerformanceCategory.Graphics, instanceNames, ref numCategories, ref totalValue);+ QueryCategory(categories, GpuPerformanceCategoryFlags.Security, GpuPerformanceCategory.Security, instanceNames, ref numCategories, ref totalValue);+ QueryCategory(categories, GpuPerformanceCategoryFlags.Vr, GpuPerformanceCategory.Vr, instanceNames, ref numCategories, ref totalValue);++ if (numCategories == 0)+ numCategories = 1;++ return totalValue / numCategories;+ }++ /// <summary>+ /// Returns the current GPU utilization (average of all GPUs) for a given category.+ /// </summary>+ /// <param name="category">Category to fetch info for.</param>+ /// <param name="instanceNames">Names of all available counter instances.</param>+ /// <returns>Average load.</returns>+ public float GetAverageLoadPercent(GpuPerformanceCategory category, string[] instanceNames = null)+ {+ try+ {+ instanceNames ??= GpuEngineCategory.GetInstanceNames();+ var totalUtilization = 0f;++ var statsForType = StatsForTypes[(int)category];+ foreach (var counterForProcess in statsForType.Update(instanceNames))+ {+ var processUtilization = 0f;++ // Try/catch here isn't ideal, but this appears to throw on+ // own PID after a reload; I don't exactly know why.+ foreach (var counter in counterForProcess.Value)+ {+ try { processUtilization += (float)counter.Observe(); }+ catch { /* ignored */ }+ }++ totalUtilization += processUtilization / counterForProcess.Value.Count;+ }++ return totalUtilization;+ }+ catch (Exception)+ {+ // TODO: Some decent way of logging error here; this has no instance state.+ return -1;+ }+ }++ [MethodImpl(MethodImplOptions.AggressiveInlining)]+ private void QueryCategory(GpuPerformanceCategoryFlags requestedCategories, GpuPerformanceCategoryFlags flags, GpuPerformanceCategory category, string[] instanceNames, ref int numCategories, ref float totalValue)+ {+ if ((requestedCategories & flags) != flags)+ return;++ totalValue += GetAverageLoadPercent(category, instanceNames);+ numCategories++;+ }++ private class GpuStatsForType : IDisposable+ {+ /// <summary>+ /// Name of the counter, e.g. engtype_VR.+ /// </summary>+ private readonly string _counter;++ /// <summary>+ /// Counters for each given instance of this counter.+ /// </summary>+ private readonly Dictionary<string, IPerformanceCounter<double>> _counters = new();++ public GpuStatsForType(string counter)+ {+ _counter = counter;+ }++ /// <summary>+ /// Updates the state of this counter.+ /// </summary>+ /// <param name="instanceNames">Name of all counter instances.</param>+ public Dictionary<int, List<IPerformanceCounter<double>>> Update(string[] instanceNames)+ {+ // Problem, process can have multiple eng of 1 type; in that case, value should be averaged.+ var filteredInstances = new HashSet<string>(instanceNames.Length);+ foreach (var name in instanceNames)+ {+ if (name.Contains(_counter, StringComparison.Ordinal))+ filteredInstances.Add(name);+ }++ // Remove dead items from counters.+ foreach (var key in _counters.Keys.ToArray())+ {+ if (filteredInstances.Contains(key))+ continue;++ if (_counters.Remove(key, out var value))+ value.Dispose();+ }++ // Add items not present in dictionary.+ foreach (var name in filteredInstances)+ {+ if (!_counters.ContainsKey(name))+ _counters[name] = PerformanceCounterFactory.Default.CreateCounter(+ "GPU Engine",+ "Utilization Percentage",+ name+ );+ }++ // Copy remaining results.+ var byProcessId = new Dictionary<int, List<IPerformanceCounter<double>>>();+ const string searchString = "pid_";+ var stringLength = searchString.Length;+ foreach (var counter in _counters)+ {+ var pidIndex = counter.Key.IndexOf(searchString, StringComparison.Ordinal);+ if (pidIndex == -1)+ continue;++ var processId = ExtractNumber(counter.Key.AsSpan(pidIndex + stringLength));+ if (!byProcessId.TryGetValue(processId, out var value))+ {+ value = new List<IPerformanceCounter<double>>();+ byProcessId[processId] = value;+ }++ value.Add(counter.Value);+ }++ return byProcessId;+ }++ /// <summary>+ /// Extracts a number from a string which begins with a number.+ /// </summary>+ /// <param name="input">Input string.</param>+ /// <returns>Number starting at input.</returns>+ private static int ExtractNumber(ReadOnlySpan<char> input)+ {+ var result = 0;+ foreach (var c in input)+ {+ if (char.IsDigit(c))+ result = (result * 10) + (c - '0');+ else+ break;+ }++ return result;+ }++ public void Dispose()+ {+ foreach (var counter in _counters)+ counter.Value.Dispose();+ }+ }+ }++ // DO NOT REARRANGE ITEMS BELOW, ENUM USED AS INDEXER.++ /// <summary>+ /// Category used for fetching GPU performance data.+ /// </summary>+ [Flags]+ public enum GpuPerformanceCategoryFlags+ {+ /// <summary>+ /// 3D GPU Engine usage. i.e. engtype_3D+ /// </summary>+ Graphics = 1 << 0,++ /// <summary>+ /// Legacy API for displaying items over other items. i.e. engtype_LegacyOverlay+ /// </summary>+ LegacyOverlay = 1 << 1,++ /// <summary>+ /// Dedicated video decoding silicon. i.e. engtype_VideoDecode+ /// </summary>+ VideoDecode = 1 << 2,++ /// <summary>+ /// Workloads related to cryptography, such as encryption, decryption, and secure video processing. i.e. engtype_Security+ /// </summary>+ Security = 1 << 3,++ /// <summary>+ /// Copying data without intervention of CPU e.g. copying framebuffer across screens in multi GPU setup or uploading textures. engtype_Copy+ /// </summary>+ Copy = 1 << 4,++ /// <summary>+ /// Dedicated video encoding silicon load, i.e. NVENC/AMD AMF/QuickSync. engtype_VideoEncode+ /// </summary>+ VideoEncode = 1 << 5,++ /// <summary>+ /// Virtual Reality Related Stuff (don't know exact work, probably space reproduction stuff). engtype_VR+ /// </summary>+ Vr = 1 << 6,++ /// <summary>+ /// All supported categories.+ /// </summary>+ All = Graphics | LegacyOverlay | VideoDecode | Security | Copy | VideoEncode | Vr+ }++ /// <inheritdoc cref="GpuPerformanceCategoryFlags"/>+ [Flags]+ public enum GpuPerformanceCategory+ {+ /// <inheritdoc cref="GpuPerformanceCategoryFlags.Graphics"/>+ Graphics,+ /// <inheritdoc cref="GpuPerformanceCategoryFlags.LegacyOverlay"/>+ LegacyOverlay,+ /// <inheritdoc cref="GpuPerformanceCategoryFlags.VideoDecode"/>+ VideoDecode,+ /// <inheritdoc cref="GpuPerformanceCategoryFlags.Security"/>+ Security,+ /// <inheritdoc cref="GpuPerformanceCategoryFlags.Copy"/>+ Copy,+ /// <inheritdoc cref="GpuPerformanceCategoryFlags.VideoEncode"/>+ VideoEncode,+ /// <inheritdoc cref="GpuPerformanceCategoryFlags.Vr"/>+ Vr+ }+}diff --git a/GlazeWM.Infrastructure/WindowsApi/MemoryStatsService.cs b/GlazeWM.Infrastructure/WindowsApi/MemoryStatsService.csnew file mode 100644index 00000000..9ef0e3c0--- /dev/null+++ b/GlazeWM.Infrastructure/WindowsApi/MemoryStatsService.cs@@ -0,0 +1,36 @@+using System;+using Microsoft.VisualBasic.Devices;+using Vostok.Sys.Metrics.PerfCounters;++namespace GlazeWM.Infrastructure.WindowsApi+{+ /// <summary>+ /// Provides access to current memory statistics.+ /// </summary>+ public class MemoryStatsService : IDisposable+ {+ private readonly IPerformanceCounter<double> _availableBytes =+ PerformanceCounterFactory.Default.CreateCounter("Memory", "Available Bytes");++ private readonly long _physicalBytes = (long)new ComputerInfo().TotalPhysicalMemory;++ /// <inheritdoc />+ ~MemoryStatsService() => Dispose();++ /// <inheritdoc />+ public void Dispose()+ {+ GC.SuppressFinalize(this);+ _availableBytes.Dispose();+ }++ /// <summary>+ /// Returns the current memory utilization as a percentage.+ /// </summary>+ public double GetMemoryUsage()+ {+ var percent = (_physicalBytes - _availableBytes.Observe()) / _physicalBytes;+ return percent * 100;+ }+ }+}diff --git a/README.md b/README.mdindex 7576ac2d..032e8f68 100644--- a/README.md+++ b/README.md@@ -37,7 +37,7 @@ GlazeWM can be download via Scoop in the [Extras](https://github.com/ScoopInstal```powershellscoop bucket add extras # Ensure bucket is added firstscoop install glazewm-````+```## Build from source@@ -154,7 +154,7 @@ The appearance of the bar can be changed via the `bar` property in the config fibar:# The option to enable/disable the bar.enabled: true-+# Height of the bar in pixels.height: "30px"@@ -299,6 +299,74 @@ There are three labels available that can be customized:label_charging: "{battery_level}% (charging)"```+### Bar Component: CPU Usage++Displays the current CPU usage.++```yaml+- type: "cpu"+ label: "CPU: {percent_usage}%"+ # How often this counter is refreshed.+ refresh_interval_ms: 1000+```++### Bar Component: GPU Usage++This component has high CPU requirement (compared to others); due to no efficient way to pull data from Windows API. Avoid using low refresh intervals.++```yaml+- type: "gpu"+ label: "GPU: {percent_usage}%"+ # How often this counter is refreshed.+ refresh_interval_ms: 1000+```++### Bar Component: Memory Usage++Displays the current Memory usage.++```yaml+- type: "memory"+ label: "RAM: {percent_usage}%"+ # How often this counter is refreshed.+ refresh_interval_ms: 1000+```++### Bar Component: Text File++For displaying any content without a native integrated widget; updates in real time.++```yaml+- type: "text file"+ # Path to file.+ file_path: "PATH_HERE"+```++### Bar Component: Weather++Uses Open-Meteo API, refreshes every hour.++```yaml+- type: "weather"+ latitude: 40.6892+ longitude: 74.0445+ label: "{temperature_celsius}°C"+ label_sun: "☀️ {temperature_celsius}°C"+ label_moon: "🌙 {temperature_celsius}°C"+ label_cloud_moon: "🌙☁️ {temperature_celsius}°C"+ label_cloud_sun: "⛅ {temperature_celsius}°C"+ label_cloud_moon_rain: "🌙🌧️ {temperature_celsius}°C"+ label_cloud_sun_rain: "🌦️ {temperature_celsius}°C"+ label_cloud_rain: "🌧️ {temperature_celsius}°C"+ label_snow_flake: "❄️ {temperature_celsius}°C"+ label_thunderstorm: "⚡ {temperature_celsius}°C"+ label_cloud: "☁️ {temperature_celsius}°C"+```++### Adding Custom Bar Components++[Guide Available Here](./docs/contributing-new-components.md)+## Window rulesCommands can be run when a window is initially launched. This can be used to assign an app to a specific workspace or to always start an app in floating mode.diff --git a/docs/contributing-new-components.md b/docs/contributing-new-components.mdnew file mode 100644index 00000000..b4fbaa7e--- /dev/null+++ b/docs/contributing-new-components.md@@ -0,0 +1,152 @@+# Adding Components++Adding a new component is relatively trivial and involves a few simple steps; though requires some upfront plumbing. This document should hopefully help make this process easier.++## Adding a Config++First add a config to the `GlazeWM.Domain.UserConfigs` namespace; here is an example:++```csharp+public class CpuComponentConfig : BarComponentConfig+{+ /// <summary>+ /// Label assigned to the CPU component.+ /// </summary>+ public string Label { get; set; } = "CPU: {percent_usage}%";+}+```++Once this is done, you should register this config in `BarComponentConfigConverter.Read`:++```csharp+"cpu" =>+ JsonSerializer.Deserialize<CpuComponentConfig>(+ jsonObject.RootElement.ToString(),+ options+ )+```++This will map directly to the config using the YAML naming rules, i.e.++```yaml+components_right:+ - type: "cpu"+ label: "CPU: {percent_usage}%"+```++Each capital letter is prefixed by a space delimited by `_`.++## Adding a Service [Optional]++In some cases to add a component, you might want to register a `'Service'`; this will allow your logic to be reused across multiple locations in the program.++To do so, first create the raw service in `GlazeWM.Infrastructure`.++```csharp+/// <summary>+/// Provides access to current CPU statistics.+/// </summary>+public class CpuStatsService+{ ... }+```++And register it in the DI container in `GlazeWM.Infrastructure.DependencyInjection`:++```csharp+services.AddSingleton<CpuStatsService>();+```++## Adding a ViewModel++This contains the main logic used to fetch the data to be displayed in the UI.+You add this file to `GlazeWM.Bar.Components`.++Example:++```csharp+public class CpuComponentViewModel : ComponentViewModel+{+ public CpuComponentViewModel(+ BarViewModel parentViewModel,+ CpuComponentConfig config) : base(parentViewModel, config)+ {+ _config = config;+ _cpuStatsService = ServiceLocator.GetRequiredService<CpuStatsService>();++ Observable.Timer(+ TimeSpan.Zero,+ TimeSpan.FromMilliseconds(_config.RefreshIntervalMs)+ )+ .TakeUntil(_parentViewModel.WindowClosing)+ .Subscribe((_) => Label = CreateLabel());+ }+}+```++Note the line `.TakeUntil(_parentViewModel.WindowClosing)`. This is necessary to correctly clean up after config reloads; otherwise your component will remain alive; wasting CPU and RAM.++Then register your ViewModel to `BarViewModel.CreateComponentViewModels`++```csharp+CpuComponentConfig cpupc => new CpuComponentViewModel(this, cpupc),+```++## Adding a Component XAML++Each individual component has its own custom XAML WPF UserControl.+Most of these don't require much customization; so it's usually easier to just copy an existing component; for example.++### Copy Existing Component++CTRL+C & CTRL+V existing Xaml file++++### Fix Class Name++Fix the class name to correspond to your new class in the XAML, i.e.++```xaml+<UserControl+ x:Class="GlazeWM.Bar.Components.CpuComponent"+```++(first line)++And corresponding `xaml.cs` file.++```csharp+public partial class CpuComponent : UserControl+{+ public CpuComponent() => InitializeComponent();+}+```++### Fix Item Name++Change following line in the XAML++```xaml+<!-- Or whichever property is here -->+Text="{Binding TilingDirectionString}" />+```++To match your property from the `ViewModel`, i.e. `FormattedText`, so the XAML reads.++```xaml+Text="{Binding FormattedText}" />+```++## Register Component XAML++Add your component to `ComponentPortal.xaml` beside all the other components.++```xaml+<DataTemplate DataType="{x:Type components:CpuComponentViewModel}">+ <components:CpuComponent Padding="{Binding Padding}" Background="{Binding Background}" />+</DataTemplate>+```++After doing this, add the component to your config, see if it works.++diff --git a/docs/images/duplicate_xaml.png b/docs/images/duplicate_xaml.pngnew file mode 100644index 00000000..e933bed8Binary files /dev/null and b/docs/images/duplicate_xaml.png differdiff --git a/docs/images/working_cpu_indicator.png b/docs/images/working_cpu_indicator.pngnew file mode 100644index 00000000..72ff4168Binary files /dev/null and b/docs/images/working_cpu_indicator.png differ