GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: parse bar component labels (#289)
lars-bergeref2d290f0b97
diff --git a/GlazeWM.Bar/Components/BatteryComponent.xaml b/GlazeWM.Bar/Components/BatteryComponent.xamlindex 3b5f0d81..fd314bca 100644--- a/GlazeWM.Bar/Components/BatteryComponent.xaml+++ b/GlazeWM.Bar/Components/BatteryComponent.xaml@@ -4,13 +4,7 @@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"+ xmlns:components="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 FormattedPowerStatus}" />+ <components:LabelComponent DataContext="{Binding Label}" /></UserControl>diff --git a/GlazeWM.Bar/Components/BatteryComponentViewModel.cs b/GlazeWM.Bar/Components/BatteryComponentViewModel.csindex bf9aad92..e91ccfde 100644--- a/GlazeWM.Bar/Components/BatteryComponentViewModel.cs+++ b/GlazeWM.Bar/Components/BatteryComponentViewModel.cs@@ -1,4 +1,5 @@using System;+using System.Collections.Generic;using System.Globalization;using System.Reactive.Linq;using GlazeWM.Domain.UserConfigs;@@ -8,48 +9,70 @@ namespace GlazeWM.Bar.Components{public class BatteryComponentViewModel : ComponentViewModel{- private readonly BatteryComponentConfig _batteryComponentConfig;+ private readonly BatteryComponentConfig _config;/// <summary>/// Format the current power status with the user's formatting config./// </summary>- public string FormattedPowerStatus => FormatLabel();+ private LabelViewModel _label;+ public LabelViewModel Label+ {+ get => _label;+ protected set => SetField(ref _label, value);+ }++ public BatteryComponentViewModel(+ BarViewModel parentViewModel,+ BatteryComponentConfig config) : base(parentViewModel, config)+ {+ _config = config;++ Observable+ .Timer(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(5))+ .TakeUntil(_parentViewModel.WindowClosing)+ .Subscribe(_ => Label = CreateLabel());+ }- private string FormatLabel()+ public LabelViewModel CreateLabel(){WindowsApiService.GetSystemPowerStatus(out var ps);var batteryLevel = ps.BatteryLifePercent.ToString(CultureInfo.InvariantCulture);- // display the battery level as a 100% if no dedicated battery is available on the device+ // Display the battery level as a 100% if device has no dedicated battery.if (ps.BatteryFlag == 128)- {- return _batteryComponentConfig.LabelDraining.Replace("{battery_level}", "100");- }+ return XamlHelper.ParseLabel(+ _config.LabelDraining,+ CreateVariableDict(batteryLevel),+ this+ );if (ps.ACLineStatus == 1)- {- return _batteryComponentConfig.LabelCharging.Replace("{battery_level}", batteryLevel);- }- else if (ps.SystemStatusFlag == 1)- {- return _batteryComponentConfig.LabelPowerSaver.Replace("{battery_level}", batteryLevel);- }- else- {- return _batteryComponentConfig.LabelDraining.Replace("{battery_level}", batteryLevel);- }+ return XamlHelper.ParseLabel(+ _config.LabelCharging,+ CreateVariableDict(batteryLevel),+ this+ );++ if (ps.SystemStatusFlag == 1)+ return XamlHelper.ParseLabel(+ _config.LabelPowerSaver,+ CreateVariableDict(batteryLevel),+ this+ );++ return XamlHelper.ParseLabel(+ _config.LabelDraining,+ CreateVariableDict(batteryLevel),+ this+ );}- public BatteryComponentViewModel(- BarViewModel parentViewModel,- BatteryComponentConfig config) : base(parentViewModel, config)+ public static Dictionary<string, string> CreateVariableDict(string batteryLevel){- _batteryComponentConfig = config;-- Observable- .Interval(TimeSpan.FromSeconds(3))- .TakeUntil(_parentViewModel.WindowClosing)- .Subscribe(_ => OnPropertyChanged(nameof(FormattedPowerStatus)));+ return new()+ {+ { "battery_level", batteryLevel }+ };}}}diff --git a/GlazeWM.Bar/Components/LabelComponent.xaml b/GlazeWM.Bar/Components/LabelComponent.xamlnew file mode 100644index 00000000..38633eeb--- /dev/null+++ b/GlazeWM.Bar/Components/LabelComponent.xaml@@ -0,0 +1,27 @@+<UserControl+ x:Class="GlazeWM.Bar.Components.LabelComponent"+ 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"+ mc:Ignorable="d">+ <ItemsControl ItemsSource="{Binding Spans}">+ <ItemsControl.ItemsPanel>+ <ItemsPanelTemplate>+ <StackPanel Orientation="Horizontal" />+ </ItemsPanelTemplate>+ </ItemsControl.ItemsPanel>+ <ItemsControl.ItemTemplate>+ <DataTemplate>+ <TextBlock+ Text="{Binding Text}"+ VerticalAlignment="Center"+ Background="{Binding Background}"+ Foreground="{Binding Foreground}"+ FontFamily="{Binding FontFamily}"+ FontWeight="{Binding FontWeight}"+ FontSize="{Binding FontSize}" />+ </DataTemplate>+ </ItemsControl.ItemTemplate>+ </ItemsControl>+</UserControl>diff --git a/GlazeWM.Bar/Components/LabelComponent.xaml.cs b/GlazeWM.Bar/Components/LabelComponent.xaml.csnew file mode 100644index 00000000..2a385590--- /dev/null+++ b/GlazeWM.Bar/Components/LabelComponent.xaml.cs@@ -0,0 +1,15 @@+using System.Windows.Controls;++namespace GlazeWM.Bar.Components+{+ /// <summary>+ /// Interaction logic for LabelComponent.xaml+ /// </summary>+ public partial class LabelComponent : UserControl+ {+ public LabelComponent()+ {+ InitializeComponent();+ }+ }+}diff --git a/GlazeWM.Bar/Components/LabelSpan.cs b/GlazeWM.Bar/Components/LabelSpan.csnew file mode 100644index 00000000..cb76e02a--- /dev/null+++ b/GlazeWM.Bar/Components/LabelSpan.cs@@ -0,0 +1,96 @@+namespace GlazeWM.Bar.Components+{+ public class LabelSpan+ {+ public string Text { get; }+ public string Background { get; }+ public string Foreground { get; }+ public string FontFamily { get; }+ public string FontWeight { get; }+ public string FontSize { get; }++ public LabelSpan(+ string text,+ string background,+ string foreground,+ string fontFamily,+ string fontWeight,+ string fontSize)+ {+ Text = text;+ Background = background;+ Foreground = foreground;+ FontFamily = fontFamily;+ FontWeight = fontWeight;+ FontSize = fontSize;+ }+ }+}++/// Usage:+/**+public class BatteryComponentViewModel : ComponentViewModel+{+ private readonly BatteryComponentConfig _config;++ private LabelViewModel _label;+ public string Label+ {+ get => _label;+ protected set => SetField(ref _label, value);+ }++ public BatteryComponentViewModel(...) : base(parentViewModel, config)+ {+ _batteryComponentConfig = config;++ Label = XamlHelper.ParseLabel(config.Label, CreateVariableDict());++ Observable+ .Interval(TimeSpan.FromSeconds(3))+ .TakeUntil(_parentViewModel.WindowClosing)+ .Subscribe(_ => {+ Label.UpdateVariables(CreateVariableDict());+ OnPropertyChanged(nameof(Label));+ });+ }+}+*/++/// Alternatively:+/**+public class BatteryComponentViewModel : ComponentViewModel+{+ private readonly BatteryComponentConfig _config;++ private LabelViewModel _label;+ public string Label+ {+ get => _label;+ protected set => SetField(ref _label, value);+ }++ public BatteryComponentViewModel(...) : base(parentViewModel, config)+ {+ _batteryComponentConfig = config;++ Label = XamlHelper.ParseLabel(config.Label, GetVariableDict());++ Observable+ .Interval(TimeSpan.FromSeconds(3))+ .TakeUntil(_parentViewModel.WindowClosing)+ .Subscribe(_ => {+ Label.UpdateVariables();+ OnPropertyChanged(nameof(Label));+ });+ }++ public Dictionary<string, Action<string>> GetVariableDict()+ {+ return new()+ {+ { "battery_level", () => GetBatteryLevel() }+ }+ }+}+*/diff --git a/GlazeWM.Bar/Components/LabelViewModel.cs b/GlazeWM.Bar/Components/LabelViewModel.csnew file mode 100644index 00000000..11bca6ba--- /dev/null+++ b/GlazeWM.Bar/Components/LabelViewModel.cs@@ -0,0 +1,15 @@+using System.Collections.Generic;+using GlazeWM.Bar.Common;++namespace GlazeWM.Bar.Components+{+ public class LabelViewModel : ViewModelBase+ {+ public List<LabelSpan> Spans { get; }++ public LabelViewModel(List<LabelSpan> spans)+ {+ Spans = spans;+ }+ }+}diff --git a/GlazeWM.Bar/XamlHelper.cs b/GlazeWM.Bar/XamlHelper.csindex fe90be4c..9a8fdabc 100644--- a/GlazeWM.Bar/XamlHelper.cs+++ b/GlazeWM.Bar/XamlHelper.cs@@ -1,5 +1,8 @@using System;+using System.Collections.Generic;using System.Linq;+using System.Xml.Linq;+using GlazeWM.Bar.Components;using GlazeWM.Infrastructure.Utils;namespace GlazeWM.Bar@@ -55,5 +58,62 @@ namespace GlazeWM.Bar_ => throw new ArgumentException(null, nameof(shorthand)),};}++ public static LabelViewModel ParseLabel(+ string labelString,+ Dictionary<string, 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);++ // Wrap `labelString` in arbitrary tag to make it valid XML.+ var wrappedLabel = $"<Label>{labelWithVariables}</Label>";+ var labelXml = XElement.Parse(wrappedLabel);++ var labelSpans = labelXml.Nodes().Select(node =>+ {+ var value = node switch+ {+ XText text => text.Value,+ XElement element => element.Value,+ _ => throw new ArgumentException("Invalid XML.", nameof(labelString))+ };++ string background = null;+ string foreground = null;+ string fontFamily = null;+ string fontWeight = null;+ string fontSize = null;++ var ancestor = node;++ while (ancestor is not null)+ {+ background ??= (ancestor as XElement)?.Attribute("bg")?.Value;+ foreground ??= (ancestor as XElement)?.Attribute("fg")?.Value;+ fontFamily ??= (ancestor as XElement)?.Attribute("ff")?.Value;+ fontWeight ??= (ancestor as XElement)?.Attribute("fw")?.Value;+ fontSize ??= (ancestor as XElement)?.Attribute("fs")?.Value;++ // Traverse upwards to get attributes to apply.+ ancestor = ancestor.Parent;+ }++ return new LabelSpan(+ value,+ background ?? viewModel.Background,+ foreground ?? viewModel.Foreground,+ fontFamily ?? viewModel.FontFamily,+ fontWeight ?? viewModel.FontWeight,+ fontSize ?? viewModel.FontSize+ );+ }).ToList();++ return new LabelViewModel(labelSpans);+ }}}