Refactor step 1

This commit is contained in:
Stone_Red
2023-11-19 16:19:07 +01:00
parent 3eae8bcdfc
commit 74bf7c2fb8
30 changed files with 595 additions and 412 deletions
@@ -1,5 +1,6 @@
using DesktopMagicPluginAPI;
using DesktopMagicPluginAPI.Inputs;
using DesktopMagicPluginAPI.Settings;
using System;
using System.Drawing;
@@ -9,7 +10,7 @@ namespace DesktopMagic.BuiltInWindowElements;
internal class DatePlugin : Plugin
{
[Element("Short date")]
[Setting("Short date")]
private readonly CheckBox shortDatecheckBox = new CheckBox(true);
private DateTime oldDateTime = DateTime.MinValue;
@@ -2,6 +2,7 @@
using DesktopMagicPluginAPI;
using DesktopMagicPluginAPI.Inputs;
using DesktopMagicPluginAPI.Settings;
using NAudio.Wave;
@@ -21,19 +22,19 @@ internal class MusicVisualizerPlugin : Plugin
private readonly Bitmap output = new Bitmap(880, 300);
[Element("Mirror")]
[Setting("Mirror")]
private readonly CheckBox mirrorMode = new CheckBox(false);
[Element("Line")]
[Setting("Line")]
private readonly CheckBox lineMode = new CheckBox(false);
[Element("Spectrum Mode")]
[Setting("Spectrum Mode")]
private readonly ComboBox spectrumMode = new ComboBox("Bottom", "Middle", "Top");
[Element("Amplification")]
[Setting("Amplification")]
private readonly IntegerUpDown amplifierLevel = new IntegerUpDown(-50, 50, 0);
[Element("Line thickness")]
[Setting("Line thickness")]
private readonly IntegerUpDown lineThickness = new IntegerUpDown(1, 10, 1);
private WasapiLoopbackCapture waveIn;
@@ -1,5 +1,6 @@
using DesktopMagicPluginAPI;
using DesktopMagicPluginAPI.Inputs;
using DesktopMagicPluginAPI.Settings;
using System;
using System.Drawing;
@@ -9,7 +10,7 @@ namespace DesktopMagic.BuiltInWindowElements;
internal class TimePlugin : Plugin
{
[Element("Display Seconds")]
[Setting("Display Seconds")]
private readonly CheckBox displaySecondscheckBox = new CheckBox(true);
public override int UpdateInterval => 1000;
+1
View File
@@ -13,6 +13,7 @@
<AssemblyVersion>0.0.3.2</AssemblyVersion>
<FileVersion>0.0.3.2</FileVersion>
<TargetFramework>net8.0-windows7.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
+2 -1
View File
@@ -8,4 +8,5 @@ using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "Windows only application")]
[assembly: SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "No need to")]
[assembly: SuppressMessage("Minor Code Smell", "S1075:URIs should not be hardcoded", Justification = "<Pending>")]
[assembly: SuppressMessage("Minor Code Smell", "S3604:Member initializer values should not be redundant", Justification = "False postives")]
[assembly: SuppressMessage("Minor Code Smell", "S3604:Member initializer values should not be redundant", Justification = "False postives")]
[assembly: SuppressMessage("Critical Code Smell", "S2696:Instance members should not write to \"static\" fields", Justification = "<Pending>", Scope = "member", Target = "~P:DesktopMagic.MainWindowDataContext.Settings")]
@@ -74,6 +74,16 @@ internal static partial class MultiColorConverter
}
}
public static System.Windows.Media.Color ConvertToMediaColor(System.Drawing.Color color)
{
return System.Windows.Media.Color.FromArgb(color.A, color.R, color.G, color.B);
}
public static System.Drawing.Color ConvertToSystemColor(System.Windows.Media.Color color)
{
return System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B);
}
[GeneratedRegex("(?:[0-9a-fA-F]{8})")]
private static partial Regex Hex8();
@@ -10,11 +10,11 @@ internal class SettingElementGenerator(ComboBox optionsComboBox)
{
private readonly ComboBox optionsComboBox = optionsComboBox;
public void Generate(SettingElement settingElement, DockPanel dockPanel, TextBlock textBlock)
public void Generate(InputElement settingElement, DockPanel dockPanel, TextBlock textBlock)
{
dockPanel.UpdateLayout();
textBlock.UpdateLayout();
if (settingElement.Element is DesktopMagicPluginAPI.Inputs.Label eLabel)
if (settingElement.Input is DesktopMagicPluginAPI.Inputs.Label eLabel)
{
textBlock.Text = eLabel.Value;
textBlock.Margin = new Thickness(0, 5, 3, 0);
@@ -33,7 +33,7 @@ internal class SettingElementGenerator(ComboBox optionsComboBox)
});
};
}
else if (settingElement.Element is DesktopMagicPluginAPI.Inputs.Button eButton)
else if (settingElement.Input is DesktopMagicPluginAPI.Settings.Button eButton)
{
Button button = new()
{
@@ -66,7 +66,7 @@ internal class SettingElementGenerator(ComboBox optionsComboBox)
_ = dockPanel.Children.Add(button);
}
else if (settingElement.Element is DesktopMagicPluginAPI.Inputs.CheckBox eCheckBox)
else if (settingElement.Input is DesktopMagicPluginAPI.Settings.CheckBox eCheckBox)
{
CheckBox checkBox = new()
{
@@ -96,7 +96,7 @@ internal class SettingElementGenerator(ComboBox optionsComboBox)
_ = dockPanel.Children.Add(checkBox);
}
else if (settingElement.Element is DesktopMagicPluginAPI.Inputs.TextBox eTextBox)
else if (settingElement.Input is DesktopMagicPluginAPI.Settings.TextBox eTextBox)
{
TextBox textBox = new()
{
@@ -125,7 +125,7 @@ internal class SettingElementGenerator(ComboBox optionsComboBox)
};
_ = dockPanel.Children.Add(textBox);
}
else if (settingElement.Element is DesktopMagicPluginAPI.Inputs.IntegerUpDown eIntegerUpDown)
else if (settingElement.Input is DesktopMagicPluginAPI.Settings.IntegerUpDown eIntegerUpDown)
{
Xceed.Wpf.Toolkit.IntegerUpDown integerUpDown = new()
{
@@ -155,7 +155,7 @@ internal class SettingElementGenerator(ComboBox optionsComboBox)
};
_ = dockPanel.Children.Add(integerUpDown);
}
else if (settingElement.Element is DesktopMagicPluginAPI.Inputs.Slider eSlider)
else if (settingElement.Input is DesktopMagicPluginAPI.Settings.Slider eSlider)
{
Slider slider = new()
{
@@ -188,7 +188,7 @@ internal class SettingElementGenerator(ComboBox optionsComboBox)
_ = dockPanel.Children.Add(slider);
}
else if (settingElement.Element is DesktopMagicPluginAPI.Inputs.ComboBox eComboBox)
else if (settingElement.Input is DesktopMagicPluginAPI.Settings.ComboBox eComboBox)
{
ComboBox comboBox = new()
{
+18 -9
View File
@@ -2,6 +2,11 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:DesktopMagic"
d:DataContext="{d:DesignInstance Type=local:MainWindowDataContext}"
Closing="Window_Closing"
Closed="Window_Closed"
ShowInTaskbar="True"
@@ -34,14 +39,18 @@
<CheckBox x:Name="EditCheckBox" VerticalAlignment="Center" Grid.Row="1" Content="{DynamicResource edit}" Click="EditCheckBox_Click" Foreground="Black" BorderBrush="#FF323232" Style="{StaticResource MaterialDesignDarkCheckBox}" IsChecked="True" />
</Grid>
<ScrollViewer Background="#FFBBBBBB" PreviewMouseWheel="ScrollViewer_PreviewMouseWheel">
<StackPanel x:Name="stackPanel">
<CheckBox x:Name="TimeCb" Content="{DynamicResource time}" Click="CheckBox_Click" Style="{StaticResource MaterialDesignDarkCheckBox}" />
<CheckBox x:Name="DateCb" Content="{DynamicResource date}" Click="CheckBox_Click" Style="{StaticResource MaterialDesignDarkCheckBox}" />
<CheckBox x:Name="CpuUsageCb" Content="{DynamicResource cpuUsage}" Click="CheckBox_Click" Style="{StaticResource MaterialDesignDarkCheckBox}" />
<CheckBox x:Name="CalendarCb" Content="{DynamicResource googleCalendar}" Click="CheckBox_Click" Style="{StaticResource MaterialDesignDarkCheckBox}" Visibility="Collapsed" />
<!--Currently disabled because it's not working-->
<CheckBox x:Name="MusicVisualizerCb" Content="{DynamicResource musicVisualizer}" HorizontalAlignment="Left" VerticalAlignment="Top" Click="CheckBox_Click" Style="{StaticResource MaterialDesignDarkCheckBox}" />
</StackPanel>
<ItemsControl ItemsSource="{Binding Settings.CurrentLayout.Plugins}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Click="PluginCheckBox_Click" Content="{Binding Key}" IsChecked="{Binding Value.Enabled}" Style="{StaticResource MaterialDesignDarkCheckBox}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</DockPanel>
@@ -121,7 +130,7 @@
<Rectangle Fill="#FFC5C5C5" Stroke="#FFC5C5C5" Grid.ColumnSpan="3" />
<StackPanel Margin="{StaticResource DefaultMargin}" VerticalAlignment="Bottom">
<ComboBox x:Name="layoutsComboBox" HorizontalAlignment="Left" Margin="0,0,0,5" Width="170" Height="20" SelectionChanged="LayoutsComboBox_SelectionChanged" />
<ComboBox ItemsSource="{Binding Settings.Layouts}" DisplayMemberPath="Name" SelectedValue="{Binding Settings.CurrentLayoutName}" SelectedValuePath="Name" HorizontalAlignment="Left" Margin="0,0,0,5" Width="170" Height="20" SelectionChanged="LayoutsComboBox_SelectionChanged" />
<Button x:Name="newLayoutButton" Content="{DynamicResource newLayout}" Margin="0,0,0,5" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="170" Click="NewLayoutButton_Click" FontWeight="Regular" />
<Button x:Name="removeLayoutButton" Content="{DynamicResource deleteLayout}" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="170" Click="RemoveLayoutButton_Click" FontWeight="Regular" />
</StackPanel>
+119 -254
View File
@@ -2,17 +2,20 @@
using DesktopMagic.Dialogs;
using DesktopMagic.Helpers;
using DesktopMagic.Plugins;
using DesktopMagic.Settings;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
@@ -23,32 +26,28 @@ namespace DesktopMagic
{
public partial class MainWindow : Window
{
#region Global settings
internal static Theme Theme { get; } = new Theme();
internal static bool EditMode { get; private set; } = false;
#endregion Global settings
#region Plugins settings
internal static Dictionary<string, List<SettingElement>> PluginsSettings { get; } = [];
#endregion Plugins settings
private readonly RegistryKey key;
private readonly System.Windows.Forms.NotifyIcon notifyIcon = new();
private readonly MainWindowDataContext mainWindowDataContext = new();
private bool loaded = false;
private bool blockWindowsClosing = true;
public static List<PluginWindow> Windows { get; } = [];
public static List<string> WindowNames { get; } = [];
internal static bool EditMode { get; set; } = false;
private DesktopMagicSettings Settings
{
get => mainWindowDataContext.Settings;
set => mainWindowDataContext.Settings = value;
}
public MainWindow()
{
DataContext = mainWindowDataContext;
try
{
key = Registry.CurrentUser.CreateSubKey(@"Software\" + App.AppName);
Stream iconStream = Application.GetResourceStream(new Uri("pack://application:,,,/DesktopMagic;component/icon.ico")).Stream;
notifyIcon.Click += TaskbarIcon_TrayLeftClick;
notifyIcon.Visible = true;
@@ -73,6 +72,8 @@ namespace DesktopMagic
#region Load
private readonly List<string> pluginNames = [];
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
@@ -94,7 +95,7 @@ namespace DesktopMagic
App.Logger.Log("Loading Plugin names", "Main");
LoadPlugins();
App.Logger.Log("Loading Layout names", "Main");
LoadLayoutNames();
LoadSettings();
App.Logger.Log("Loading Layout", "Main");
LoadLayout();
@@ -110,15 +111,18 @@ namespace DesktopMagic
private void LoadPlugins()
{
string PluginsPath = App.ApplicationDataPath + "\\Plugins";
pluginNames.Add("MusicVisualizer");
pluginNames.Add("Test");
foreach (string fileName in Directory.GetFiles(PluginsPath, "*.dll"))
string pluginsPath = App.ApplicationDataPath + "\\Plugins";
foreach (string fileName in Directory.GetFiles(pluginsPath, "*.dll"))
{
string PluginName = fileName[(fileName.LastIndexOf('\\') + 1)..].Replace(fileName[fileName.LastIndexOf('.')..], "");
string pluginName = fileName[(fileName.LastIndexOf('\\') + 1)..].Replace(fileName[fileName.LastIndexOf('.')..], "");
try
{
_ = Directory.CreateDirectory(Path.Combine(PluginsPath, PluginName));
File.Move(fileName, $"{PluginsPath}\\{PluginName}\\{PluginName}.dll");
_ = Directory.CreateDirectory(Path.Combine(pluginsPath, pluginName));
File.Move(fileName, $"{pluginsPath}\\{pluginName}\\{pluginName}.dll");
}
catch (Exception ex)
{
@@ -126,43 +130,22 @@ namespace DesktopMagic
}
}
foreach (string directory in Directory.GetDirectories(PluginsPath))
foreach (string directory in Directory.GetDirectories(pluginsPath))
{
foreach (string fileName in Directory.GetFiles(directory).Where(s => s.EndsWith(".dll", StringComparison.InvariantCulture) || s.EndsWith(".cs", StringComparison.InvariantCulture)))
{
string badChars = ",#-<>?!=()*,. ";
string PluginName = fileName[(fileName.LastIndexOf('\\') + 1)..].Replace(fileName[fileName.LastIndexOf('.')..], "");
string clearPluginName = PluginName;
string pluginName = fileName[(fileName.LastIndexOf('\\') + 1)..].Replace(fileName[fileName.LastIndexOf('.')..], "");
string clearPluginName = pluginName;
if (PluginName == directory[(directory.LastIndexOf('\\') + 1)..])
if (pluginName == directory[(directory.LastIndexOf('\\') + 1)..])
{
foreach (char c in badChars)
{
clearPluginName = clearPluginName.Replace(c, '_');
}
CheckBox checkBox = new()
{
Name = "_PluginCb_" + clearPluginName,
Content = PluginName,
Style = (Style)FindResource("MaterialDesignDarkCheckBox")
};
checkBox.Click += CheckBox_Click;
bool exists = false;
foreach (UIElement item in stackPanel.Children)
{
if (((CheckBox)item).Name == "_PluginCb_" + clearPluginName)
{
exists = true;
break;
}
}
if (!exists)
{
_ = stackPanel.Children.Add(checkBox);
}
pluginNames.Add(pluginName);
}
}
}
@@ -174,56 +157,35 @@ namespace DesktopMagic
private void EditCheckBox_Click(object sender, RoutedEventArgs e)
{
EditMode = (bool)EditCheckBox.IsChecked;
SaveLayout();
EditMode = EditCheckBox.IsChecked == true;
SaveSettings();
}
private void CheckBox_Click(object sender, RoutedEventArgs e)
private void PluginCheckBox_Click(object sender, RoutedEventArgs e)
{
string pluginName = ((CheckBox)sender).Content.ToString() ?? string.Empty;
if (!Settings.CurrentLayout.Plugins.TryGetValue(pluginName, out PluginSettings? pluginSettings))
{
pluginSettings = new PluginSettings();
Settings.CurrentLayout.Plugins.Add(pluginName, pluginSettings);
}
CheckBox checkBox = (CheckBox)sender;
PluginWindow window = null;
PluginWindow window = new PluginWindow(pluginName, pluginSettings)
{
Title = pluginName
};
blockWindowsClosing = false;
switch (checkBox.Name)
{
case "TimeCb":
window = new PluginWindow(new TimePlugin(), checkBox.Content.ToString());
break;
case "DateCb":
window = new PluginWindow(new DatePlugin(), checkBox.Content.ToString());
break;
case "CpuUsageCb":
//window = new PluginWindow();
break;
case "MusicVisualizerCb":
window = new PluginWindow(new MusicVisualizerPlugin(), checkBox.Content.ToString());
break;
default:
if (!checkBox.Name.Contains("_PluginCb_"))
{
return;
}
window = new PluginWindow(checkBox.Content.ToString());
break;
}
if (window is null)
{
return;
}
window.Title = checkBox.Content.ToString();
if (!WindowNames.Contains(window.Title) && checkBox.IsChecked == true)
{
_ = Task.Run(() =>
{
Dispatcher.Invoke(() =>
{
Action onPluginLoaded = null;
Action? onPluginLoaded = null;
onPluginLoaded = () =>
{
Dispatcher.Invoke(() =>
@@ -238,10 +200,10 @@ namespace DesktopMagic
});
};
window.OnExit += () =>
{
checkBox.IsChecked = false;
CheckBox_Click(checkBox, null);
};
{
checkBox.IsChecked = false;
PluginCheckBox_Click(checkBox, null);
};
window.PluginLoaded += onPluginLoaded;
window.ShowInTaskbar = false;
@@ -273,15 +235,15 @@ namespace DesktopMagic
}
}
}
key.SetValue(checkBox.Name, checkBox.IsChecked.ToString());
pluginSettings.Enabled = checkBox.IsChecked == true;
blockWindowsClosing = true;
SaveLayout();
SaveSettings();
}
private void DisplayWindow_ContentRendered(object sender, EventArgs e)
{
WindowPos.SendWpfWindowBack(sender as Window);
WindowPos.SendWpfWindowBack(sender as Window);
WindowPos.SendWpfWindowBack((Window)sender);
WindowPos.SendWpfWindowBack((Window)sender);
}
private void DisplayWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
@@ -328,9 +290,8 @@ namespace DesktopMagic
private void FontComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Theme.Font = fontComboBox.SelectedValue.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "");
key.SetValue("Font", Theme.Font);
SaveLayout();
Settings.CurrentLayout.Theme.Font = fontComboBox.SelectedValue.ToString()!.Replace("System.Windows.Controls.ComboBoxItem: ", "");
SaveSettings();
}
private void OptionsComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
@@ -344,8 +305,8 @@ namespace DesktopMagic
return;
}
bool success = PluginsSettings.TryGetValue(optionsComboBox.SelectedItem.ToString(), out List<SettingElement> settingElements);
if (!success || settingElements is null || settingElements.Count == 0)
bool success = Settings.CurrentLayout.Plugins.TryGetValue(optionsComboBox.SelectedItem.ToString()!, out Settings.PluginSettings? pluginSettings);
if (!success || pluginSettings is null || pluginSettings.Settings.Count == 0)
{
_ = optionsPanel.Children.Add(new TextBlock() { Text = (string)FindResource("noOptions") });
return;
@@ -353,7 +314,7 @@ namespace DesktopMagic
SettingElementGenerator settingElementGenerator = new SettingElementGenerator(optionsComboBox);
foreach (SettingElement settingElement in settingElements)
foreach (InputElement settingElement in pluginSettings.Settings)
{
DockPanel dockPanel = new()
{
@@ -388,7 +349,7 @@ namespace DesktopMagic
};
_ = fontComboBox.Items.Add(comboBoxItem);
if (ff.ToString() == Theme.Font)
if (ff.ToString() == Settings.CurrentLayout.Theme.Font)
{
fontComboBox.SelectedIndex = index;
}
@@ -402,43 +363,37 @@ namespace DesktopMagic
private void ChangePrimaryColorButton_Click(object sender, RoutedEventArgs e)
{
ColorDialog colorDialog = new ColorDialog("Set Primary Color", Theme.PrimaryColor);
ColorDialog colorDialog = new ColorDialog("Set Primary Color", Settings.CurrentLayout.Theme.PrimaryColor);
if (colorDialog.ShowDialog() == true)
{
Theme.PrimaryBrush = colorDialog.ResultBrush;
Theme.PrimaryColor = colorDialog.ResultColor;
Settings.CurrentLayout.Theme.PrimaryColor = colorDialog.ResultColor;
primaryColorRechtangle.Fill = colorDialog.ResultBrush;
key.SetValue("PrimaryColor", MultiColorConverter.ConvertToHex(Theme.PrimaryColor));
SaveLayout();
SaveSettings();
}
}
private void ChangeSecondaryColorButton_Click(object sender, RoutedEventArgs e)
{
ColorDialog colorDialog = new ColorDialog("Set Secondary Color", Theme.SecondaryColor);
ColorDialog colorDialog = new ColorDialog("Set Secondary Color", Settings.CurrentLayout.Theme.SecondaryColor);
if (colorDialog.ShowDialog() == true)
{
Theme.SecondaryBrush = colorDialog.ResultBrush;
Theme.SecondaryColor = colorDialog.ResultColor;
Settings.CurrentLayout.Theme.SecondaryColor = colorDialog.ResultColor;
secondaryColorRechtangle.Fill = colorDialog.ResultBrush;
key.SetValue("SecondaryColor", MultiColorConverter.ConvertToHex(Theme.SecondaryColor));
SaveLayout();
SaveSettings();
}
}
private void ChangeBackgroundColorButton_Click(object sender, RoutedEventArgs e)
{
ColorDialog colorDialog = new ColorDialog("Set Background Color", Theme.BackgroundColor);
ColorDialog colorDialog = new ColorDialog("Set Background Color", Settings.CurrentLayout.Theme.BackgroundColor);
if (colorDialog.ShowDialog() == true)
{
Theme.BackgroundBrush = colorDialog.ResultBrush;
Theme.BackgroundColor = colorDialog.ResultColor;
Settings.CurrentLayout.Theme.BackgroundColor = colorDialog.ResultColor;
backgroundColorRechtangle.Fill = colorDialog.ResultBrush;
key.SetValue("BackgroundColor", MultiColorConverter.ConvertToHex(Theme.BackgroundColor));
SaveLayout();
SaveSettings();
}
}
@@ -448,9 +403,8 @@ namespace DesktopMagic
if (sucess)
{
cornerRadiusTextBox.Foreground = Brushes.Black;
Theme.CornerRadius = cornerRadius;
key.SetValue("CornerRadius", cornerRadius);
SaveLayout();
Settings.CurrentLayout.Theme.CornerRadius = cornerRadius;
SaveSettings();
}
else
{
@@ -464,9 +418,8 @@ namespace DesktopMagic
if (sucess)
{
marginTextBox.Foreground = Brushes.Black;
Theme.Margin = margin;
key.SetValue("Margin", margin);
SaveLayout();
Settings.CurrentLayout.Theme.Margin = margin;
SaveSettings();
}
else
{
@@ -478,33 +431,7 @@ namespace DesktopMagic
private void LayoutsComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
removeLayoutButton.IsEnabled = layoutsComboBox.SelectedIndex != 0;
if (layoutsComboBox.SelectedIndex == -1 || !loaded)
{
return;
}
key.SetValue("SelectedLayout", layoutsComboBox.SelectedIndex);
string[] lines = File.ReadAllLines(App.ApplicationDataPath + "\\layouts.save");
string[] data = lines[layoutsComboBox.SelectedIndex].Split(';');
foreach (string dat in data.Where(dat => dat.Contains(':')))
{
string value = dat[(dat.LastIndexOf(':') + 1)..];
string name = dat.Replace(":" + value, "");
key.SetValue(name, value);
}
LoadLayout(false);
for (int i = 0; i < fontComboBox.Items.Count; i++)
{
ComboBoxItem comboBoxItem = (ComboBoxItem)fontComboBox.Items[i];
if (comboBoxItem.FontFamily.ToString() == Theme.Font)
{
fontComboBox.SelectedIndex = i;
}
}
}
private void NewLayoutButton_Click(object sender, RoutedEventArgs e)
@@ -512,110 +439,64 @@ namespace DesktopMagic
InputDialog inputDialog = new((string)FindResource("enterLayoutName"));
if (inputDialog.ShowDialog() == true)
{
StringBuilder content = new StringBuilder();
foreach (string valueName in key.GetValueNames())
{
if (valueName != "SelectedLayout")
{
content.Append($"{valueName}:{key.GetValue(valueName).ToString()};");
}
}
content.AppendLine(inputDialog.ResponseText);
File.AppendAllText(App.ApplicationDataPath + "\\layouts.save", content.ToString());
key.SetValue("SelectedLayout", -1);
LoadLayoutNames();
layoutsComboBox.SelectedIndex = layoutsComboBox.Items.Count - 1;
Settings.Layouts.Add(new Layout(inputDialog.ResponseText));
Settings.CurrentLayoutName = inputDialog.ResponseText;
SaveSettings();
}
}
private void RemoveLayoutButton_Click(object sender, RoutedEventArgs e)
{
if (layoutsComboBox.SelectedIndex == -1)
{
return;
}
List<string> lines = [.. File.ReadAllLines(App.ApplicationDataPath + "\\layouts.save")];
lines.RemoveAt(layoutsComboBox.SelectedIndex);
File.WriteAllLines(App.ApplicationDataPath + "\\layouts.save", lines);
LoadLayoutNames();
layoutsComboBox.SelectedIndex = 0;
Settings.Layouts.Remove(Settings.CurrentLayout);
SaveSettings();
}
private void SaveLayout()
private void SaveSettings()
{
if (!loaded)
{
return;
}
_ = Task.Run(() =>
{
lock (App.ApplicationDataPath)
{
List<string> lines = [.. File.ReadAllLines(App.ApplicationDataPath + "\\layouts.save")];
StringBuilder content = new StringBuilder();
foreach (string valueName in key.GetValueNames())
{
if (valueName != "SelectedLayout")
{
content.Append($"{valueName}:{key.GetValue(valueName).ToString()};");
}
}
Dispatcher.Invoke(() =>
{
content.Append(layoutsComboBox.SelectedItem.ToString());
lines[layoutsComboBox.SelectedIndex] = content.ToString();
});
File.WriteAllLines(App.ApplicationDataPath + "\\layouts.save", lines);
}
});
string json = JsonSerializer.Serialize(Settings);
File.WriteAllText(Path.Combine(App.ApplicationDataPath, "settings.json"), json);
}
private void LoadLayoutNames()
private void LoadSettings()
{
layoutsComboBox.Items.Clear();
string[] lines = File.ReadAllLines(App.ApplicationDataPath + "\\layouts.save");
foreach (string line in lines)
if (!File.Exists(Path.Combine(App.ApplicationDataPath, "settings.json")))
{
string name = line[(line.LastIndexOf(';') + 1)..];
_ = layoutsComboBox.Items.Add(name);
Settings = new DesktopMagicSettings()
{
Layouts =
[
new Layout((string)FindResource("default"))
]
};
return;
}
layoutsComboBox.SelectedIndex = int.Parse(key.GetValue("SelectedLayout", "0").ToString(), CultureInfo.InvariantCulture);
string json = File.ReadAllText(Path.Combine(App.ApplicationDataPath, "settings.json"));
Settings = JsonSerializer.Deserialize<DesktopMagicSettings>(json) ?? new DesktopMagicSettings()
{
Layouts =
[
new Layout((string)FindResource("default"))
]
};
}
private void LoadLayout(bool minimize = true)
{
Theme.Font = key.GetValue("Font", "Segoe UI").ToString();
cornerRadiusTextBox.Text = key.GetValue("CornerRadius", "0").ToString();
marginTextBox.Text = key.GetValue("Margin", "0").ToString();
cornerRadiusTextBox.Text = Settings.CurrentLayout.Theme.CornerRadius.ToString();
marginTextBox.Text = Settings.CurrentLayout.Theme.Margin.ToString();
blockWindowsClosing = false;
string primaryColorHex = key.GetValue("PrimaryColor", "#FFFFFFFF").ToString();
string secondaryColorHex = key.GetValue("SecondaryColor", "#FFFFFFFF").ToString();
string backgroundColorHex = key.GetValue("BackgroundColor", "#00FFFFFF").ToString();
_ = MultiColorConverter.TryConvertToSystemColor(primaryColorHex, out System.Drawing.Color primarySystemColor);
_ = MultiColorConverter.TryConvertToMediaColor(primaryColorHex, out Color primaryMediaColor);
_ = MultiColorConverter.TryConvertToSystemColor(secondaryColorHex, out System.Drawing.Color secondarySystemColor);
_ = MultiColorConverter.TryConvertToMediaColor(secondaryColorHex, out Color secondaryMediaColor);
_ = MultiColorConverter.TryConvertToSystemColor(backgroundColorHex, out System.Drawing.Color backgroundSystemColor);
_ = MultiColorConverter.TryConvertToMediaColor(backgroundColorHex, out Color backgroundMediaColor);
Theme.PrimaryColor = primarySystemColor;
Theme.PrimaryBrush = new SolidColorBrush(primaryMediaColor);
Theme.SecondaryColor = secondarySystemColor;
Theme.SecondaryBrush = new SolidColorBrush(secondaryMediaColor);
Theme.BackgroundColor = backgroundSystemColor;
Theme.BackgroundBrush = new SolidColorBrush(backgroundMediaColor);
primaryColorRechtangle.Fill = Theme.PrimaryBrush;
secondaryColorRechtangle.Fill = Theme.SecondaryBrush;
backgroundColorRechtangle.Fill = Theme.BackgroundBrush;
primaryColorRechtangle.Fill = new SolidColorBrush(MultiColorConverter.ConvertToMediaColor(Settings.CurrentLayout.Theme.PrimaryColor));
secondaryColorRechtangle.Fill = new SolidColorBrush(MultiColorConverter.ConvertToMediaColor(Settings.CurrentLayout.Theme.SecondaryColor));
backgroundColorRechtangle.Fill = new SolidColorBrush(MultiColorConverter.ConvertToMediaColor(Settings.CurrentLayout.Theme.BackgroundColor));
CornerRadiusTextBox_TextChanged(null, null);
MarginTextBox_TextChanged(null, null);
@@ -634,37 +515,21 @@ namespace DesktopMagic
_ = optionsComboBox.Items.Add((string)FindResource("musicVisualizer"));
IEnumerable<CheckBox> list = stackPanel.Children.OfType<CheckBox>();
bool showWindow = true;
try
foreach (string pluginName in pluginNames)
{
foreach (CheckBox checkBox in list)
if (!Settings.CurrentLayout.Plugins.TryGetValue(pluginName, out PluginSettings? pluginSettings))
{
try
{
if (key.GetValue(checkBox.Name, "False").ToString() == "True")
{
checkBox.IsChecked = true;
CheckBox_Click(checkBox, null);
showWindow = false;
}
else
{
checkBox.IsChecked = false;
}
}
catch (Exception ex)
{
App.Logger.Log(ex.ToString(), "Main");
_ = MessageBox.Show(ex.ToString());
}
Settings.CurrentLayout.Plugins.Add(pluginName, new PluginSettings());
Settings.CurrentLayout.UpdatePlugins();
continue;
}
if (showWindow && pluginSettings.Enabled)
{
showWindow = false;
}
}
catch (Exception ex)
{
App.Logger.Log(ex.ToString(), "Main");
_ = MessageBox.Show(ex.ToString());
}
if (!showWindow && minimize)
+33
View File
@@ -0,0 +1,33 @@
using DesktopMagic.Settings;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace DesktopMagic;
internal class MainWindowDataContext : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private static DesktopMagicSettings settings = new();
public DesktopMagicSettings Settings
{
get => settings;
set
{
settings = value;
OnPropertyChanged();
}
}
public static DesktopMagicSettings GetSettings()
{
return settings;
}
protected void OnPropertyChanged([CallerMemberName] string? name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
+10
View File
@@ -0,0 +1,10 @@
using DesktopMagicPluginAPI.Settings;
namespace DesktopMagic.Plugins;
public class InputElement(Setting element, string name, int orderIndex)
{
public Setting Input { get; } = element;
public string Name { get; } = name;
public int OrderIndex { get; } = orderIndex;
}
+5 -7
View File
@@ -1,18 +1,16 @@
using DesktopMagicPluginAPI;
using DesktopMagic.Settings;
using DesktopMagicPluginAPI;
using System.Drawing;
namespace DesktopMagic.Plugins;
internal class PluginData(PluginWindow window) : IPluginData
internal class PluginData(PluginWindow window, PluginSettings pluginSettings) : IPluginData
{
private readonly PluginWindow window = window;
public string Font => Theme.Font;
public Color Color => Theme.PrimaryColor;
public ITheme Theme { get; } = MainWindow.Theme;
public ITheme Theme { get; } = pluginSettings.Theme;
public Size WindowSize => new Size((int)window.ActualWidth, (int)window.ActualHeight);
+57 -66
View File
@@ -1,10 +1,11 @@
using DesktopMagic.Plugins;
using DesktopMagic.Helpers;
using DesktopMagic.Plugins;
using DesktopMagic.Settings;
using DesktopMagicPluginAPI;
using DesktopMagicPluginAPI.Drawing;
using DesktopMagicPluginAPI.Inputs;
using Microsoft.Win32;
using DesktopMagicPluginAPI.Settings;
using System;
using System.Collections.Generic;
@@ -24,30 +25,30 @@ namespace DesktopMagic;
public partial class PluginWindow : Window
{
public event Action PluginLoaded;
public event Action? PluginLoaded;
public event Action OnExit;
public event Action? OnExit;
private readonly RegistryKey key;
private Thread pluginThread;
private System.Timers.Timer valueTimer;
private readonly PluginSettings settings;
private Thread? pluginThread;
private System.Timers.Timer? valueTimer;
private Plugin pluginClassInstance;
private Plugin? pluginClassInstance;
public bool IsRunning { get; private set; } = true;
public string PluginName { get; private set; }
public string PluginFolderPath { get; private set; }
public string? PluginFolderPath { get; private set; }
public PluginWindow(string pluginName)
public PluginWindow(string pluginName, PluginSettings settings)
{
InitializeComponent();
Window w = new()
{
Top = -100,
Left = -100,
Width = 0,
Height = 0,
Left = settings.Position.X,
Top = settings.Position.Y,
Width = settings.Size.X,
Height = settings.Size.Y,
WindowStyle = WindowStyle.ToolWindow,
ShowInTaskbar = false
@@ -64,15 +65,10 @@ public partial class PluginWindow : Window
t.Start();
PluginName = pluginName;
key = Registry.CurrentUser.CreateSubKey(@"Software\" + App.AppName);
Top = double.Parse(key.GetValue(pluginName + "WindowTop", 100).ToString());
Left = double.Parse(key.GetValue(pluginName + "WindowLeft", 100).ToString());
Height = double.Parse(key.GetValue(pluginName + "WindowHeight", 200).ToString());
Width = double.Parse(key.GetValue(pluginName + "WindowWidth", 500).ToString());
this.settings = settings;
}
public PluginWindow(Plugin pluginClassInstance, string pluginName) : this(pluginName)
public PluginWindow(Plugin pluginClassInstance, string pluginName, Settings.PluginSettings settings) : this(pluginName, settings)
{
this.pluginClassInstance = pluginClassInstance;
}
@@ -118,13 +114,13 @@ public partial class PluginWindow : Window
return bitmapSource;
}
private void Window_ContentRendered(object sender, EventArgs e)
private void Window_ContentRendered(object? sender, EventArgs e)
{
pluginThread = new Thread(LoadPlugin);
pluginThread.Start();
}
private void UpdateTimer_Elapsed(object sender, ElapsedEventArgs e)
private void UpdateTimer_Elapsed(object? sender, ElapsedEventArgs e)
{
Dispatcher.Invoke(() =>
{
@@ -145,16 +141,16 @@ public partial class PluginWindow : Window
if (!IsRunning)
{
((System.Timers.Timer)sender).Stop();
(sender as System.Timers.Timer)?.Stop();
}
else
{
viewBox.Margin = new Thickness(MainWindow.Theme.Margin);
border.Width = viewBox.ActualWidth + (MainWindow.Theme.Margin * 2);
border.Height = viewBox.ActualHeight + (MainWindow.Theme.Margin * 2);
rectangleGeometry.Rect = new Rect(-MainWindow.Theme.Margin, -MainWindow.Theme.Margin, border.ActualWidth, border.ActualHeight);
border.Background = MainWindow.Theme.BackgroundBrush;
border.CornerRadius = new CornerRadius(MainWindow.Theme.CornerRadius);
viewBox.Margin = new Thickness(settings.Theme.Margin);
border.Width = viewBox.ActualWidth + (settings.Theme.Margin * 2);
border.Height = viewBox.ActualHeight + (settings.Theme.Margin * 2);
rectangleGeometry.Rect = new Rect(-settings.Theme.Margin, -settings.Theme.Margin, border.ActualWidth, border.ActualHeight);
border.Background = new SolidColorBrush(MultiColorConverter.ConvertToMediaColor(settings.Theme.BackgroundColor));
border.CornerRadius = new CornerRadius(settings.Theme.CornerRadius);
}
});
}
@@ -167,7 +163,7 @@ public partial class PluginWindow : Window
if (!File.Exists($"{PluginFolderPath}\\{PluginName}.dll"))
{
_ = MessageBox.Show("File does not exist!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
_ = MessageBox.Show("File does not exist!", $"Error \"{PluginName}\"", MessageBoxButton.OK, MessageBoxImage.Error);
Exit();
return;
}
@@ -179,8 +175,8 @@ public partial class PluginWindow : Window
}
catch (Exception ex)
{
App.Logger.Log(ex.ToString(), "Plugin", LogSeverity.Error);
_ = MessageBox.Show("File execution error:\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
App.Logger.Log($"\"{PluginName}\" - {ex}", "Plugin", LogSeverity.Error);
_ = MessageBox.Show("File execution error:\n" + ex, $"Error \"{PluginName}\"", MessageBoxButton.OK, MessageBoxImage.Error);
Exit();
return;
}
@@ -189,30 +185,30 @@ public partial class PluginWindow : Window
private void ExecuteSource()
{
object instance = pluginClassInstance;
object? instance = pluginClassInstance;
if (instance is null)
{
byte[] assemblyBytes = File.ReadAllBytes($"{PluginFolderPath}\\{PluginName}.dll");
Assembly dll = Assembly.Load(assemblyBytes);
Type instanceType = Array.Find(dll.GetTypes(), type => type.GetTypeInfo().BaseType == typeof(Plugin));
Type? instanceType = Array.Find(dll.GetTypes(), type => type.GetTypeInfo().BaseType == typeof(Plugin));
if (instanceType is null)
{
_ = MessageBox.Show($"The \"Plugin\" class could not be found! It has to inherit from \"{typeof(Plugin).FullName}\"", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
_ = MessageBox.Show($"The \"Plugin\" class could not be found! It has to inherit from \"{typeof(Plugin).FullName}\"", $"Error \"{PluginName}\"", MessageBoxButton.OK, MessageBoxImage.Error);
Exit();
return;
}
instance = Activator.CreateInstance(instanceType);
}
if (instance is Plugin)
if (instance is Plugin plugin)
{
pluginClassInstance = instance as Plugin;
pluginClassInstance.Application = new PluginData(this);
pluginClassInstance = plugin;
pluginClassInstance.Application = new Plugins.PluginData(this, settings);
}
else
{
_ = MessageBox.Show($"The \"Plugin\" class has to inherit from \"{typeof(Plugin).FullName}\"", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
_ = MessageBox.Show($"The \"Plugin\" class has to inherit from \"{typeof(Plugin).FullName}\"", $"Error \"{PluginName}\"", MessageBoxButton.OK, MessageBoxImage.Error);
Exit();
return;
}
@@ -243,53 +239,49 @@ public partial class PluginWindow : Window
FieldInfo[] props = instance.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.GetField);
#pragma warning restore S3011 // Reflection should not be used to increase accessibility of classes, methods, or fields
List<SettingElement> settingElements = [];
List<InputElement> settingElements = [];
foreach (FieldInfo prop in props)
{
if (prop.GetValue(instance) is Element element)
if (prop.GetValue(instance) is Setting element)
{
object[] attributes = prop.GetCustomAttributes(true);
foreach (object attribute in attributes)
{
if (attribute is ElementAttribute elementAttribute)
if (attribute is SettingAttribute elementAttribute)
{
settingElements.Add(new SettingElement(element, elementAttribute.Name, elementAttribute.OrderIndex));
settingElements.Add(new InputElement(element, elementAttribute.Name, elementAttribute.OrderIndex));
break;
}
}
}
}
settingElements = [.. settingElements.OrderBy(x => x.OrderIndex)];
if (!MainWindow.PluginsSettings.TryAdd(PluginName, settingElements))
{
MainWindow.PluginsSettings[PluginName] = settingElements;
}
settings.Settings = [.. settingElements.OrderBy(x => x.OrderIndex)];
}
catch (Exception ex)
{
IsRunning = false;
App.Logger.Log(ex.ToString(), "Plugin", LogSeverity.Error);
_ = MessageBox.Show("File execution error:\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
App.Logger.Log($"\"{PluginName}\" - {ex}", "Plugin", LogSeverity.Error);
_ = MessageBox.Show("File execution error:\n" + ex, $"Error \"{PluginName}\"", MessageBoxButton.OK, MessageBoxImage.Error);
Exit();
}
}
private void ValueTimer_Elapsed(object sender, ElapsedEventArgs e)
private void ValueTimer_Elapsed(object? sender, ElapsedEventArgs? e)
{
try
{
if (IsRunning)
if (IsRunning && pluginClassInstance is not null)
{
Bitmap result = pluginClassInstance.Main();
if (pluginClassInstance.UpdateInterval > 0)
{
valueTimer.Interval = pluginClassInstance.UpdateInterval;
valueTimer!.Interval = pluginClassInstance.UpdateInterval;
}
else
{
valueTimer.Stop();
valueTimer!.Stop();
}
if (result is not null)
@@ -314,15 +306,15 @@ public partial class PluginWindow : Window
catch (Exception ex)
{
IsRunning = false;
App.Logger.Log(ex.ToString(), "Plugin", LogSeverity.Error);
_ = MessageBox.Show("File execution error:\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
App.Logger.Log($"\"{PluginName}\" - {ex}", "Plugin", LogSeverity.Error);
_ = MessageBox.Show("File execution error:\n" + ex, $"Error \"{PluginName}\"", MessageBoxButton.OK, MessageBoxImage.Error);
Exit();
return;
}
if (!IsRunning)
{
valueTimer.Stop();
valueTimer!.Stop();
}
}
@@ -336,14 +328,13 @@ public partial class PluginWindow : Window
private void Window_LocationChanged(object sender, EventArgs e)
{
key.SetValue(PluginName + "WindowTop", Top);
key.SetValue(PluginName + "WindowLeft", Left);
settings.Position = new System.Windows.Point(Left, Top);
}
private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
key.SetValue(PluginName + "WindowHeight", Height);
key.SetValue(PluginName + "WindowWidth", Width);
settings.Size = new System.Windows.Point(Width, Height);
tileBar.CaptionHeight = ActualHeight - 10;
}
@@ -375,7 +366,7 @@ public partial class PluginWindow : Window
}
System.Drawing.Point point = new System.Drawing.Point((int)pixelMousePositionX, (int)pixelMousePositionY);
pluginClassInstance.OnMouseClick(point, mouseButton);
pluginClassInstance?.OnMouseClick(point, mouseButton);
}
private void Window_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
@@ -386,7 +377,7 @@ public partial class PluginWindow : Window
double pixelMousePositionY = e.GetPosition(image).Y * bitmapImage.PixelHeight / image.ActualHeight;
System.Drawing.Point point = new System.Drawing.Point((int)pixelMousePositionX, (int)pixelMousePositionY);
pluginClassInstance.OnMouseMove(point);
pluginClassInstance?.OnMouseMove(point);
}
private void Window_MouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
@@ -397,7 +388,7 @@ public partial class PluginWindow : Window
double pixelMousePositionY = e.GetPosition(image).Y * bitmapImage.PixelHeight / image.ActualHeight;
System.Drawing.Point point = new System.Drawing.Point((int)pixelMousePositionX, (int)pixelMousePositionY);
pluginClassInstance.OnMouseWheel(point, e.Delta);
pluginClassInstance?.OnMouseWheel(point, e.Delta);
}
#endregion Window Events
@@ -1,10 +0,0 @@
using DesktopMagicPluginAPI.Inputs;
namespace DesktopMagic.Plugins;
internal class SettingElement(Element element, string name, int orderIndex)
{
public Element Element { get; } = element;
public string Name { get; } = name;
public int OrderIndex { get; } = orderIndex;
}
+112 -12
View File
@@ -1,20 +1,120 @@
using DesktopMagicPluginAPI;
using DesktopMagic.Helpers;
using System.Drawing;
using DesktopMagicPluginAPI;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
using System.Windows.Media;
using Brush = System.Windows.Media.Brush;
using Color = System.Drawing.Color;
namespace DesktopMagic.Plugins;
internal class Theme : ITheme
public class Theme : ITheme, INotifyPropertyChanged
{
public Color PrimaryColor { get; set; } = Color.White;
public Color SecondaryColor { get; set; } = Color.White;
public Color BackgroundColor { get; set; } = Color.Transparent;
public event PropertyChangedEventHandler? PropertyChanged;
public string Font { get; set; } = "Segoe UI";
public int CornerRadius { get; set; }
public int Margin { get; set; }
private Color primaryColor = Color.White;
private Color secondaryColor = Color.White;
private Color backgroundColor = Color.Transparent;
private string font = "Segoe UI";
private int cornerRadius;
private int margin;
public System.Windows.Media.Brush PrimaryBrush { get; set; } = System.Windows.Media.Brushes.White;
public System.Windows.Media.Brush SecondaryBrush { get; set; } = System.Windows.Media.Brushes.White;
public System.Windows.Media.Brush BackgroundBrush { get; set; } = System.Windows.Media.Brushes.Transparent;
public Color PrimaryColor
{
get => primaryColor;
set
{
if (primaryColor != value)
{
primaryColor = value;
OnPropertyChanged();
OnPropertyChanged(nameof(PrimaryColorBrush));
}
}
}
public Color SecondaryColor
{
get => secondaryColor;
set
{
if (secondaryColor != value)
{
secondaryColor = value;
OnPropertyChanged();
OnPropertyChanged(nameof(SecondaryColorBrush));
}
}
}
public Color BackgroundColor
{
get => backgroundColor;
set
{
if (backgroundColor != value)
{
backgroundColor = value;
OnPropertyChanged();
OnPropertyChanged(nameof(BackgroundColorBrush));
}
}
}
public string Font
{
get => font;
set
{
if (font != value)
{
font = value;
OnPropertyChanged();
}
}
}
public int CornerRadius
{
get => cornerRadius;
set
{
if (cornerRadius != value)
{
cornerRadius = value;
OnPropertyChanged();
}
}
}
public int Margin
{
get => margin;
set
{
if (margin != value)
{
margin = value;
OnPropertyChanged();
}
}
}
[JsonIgnore]
public Brush PrimaryColorBrush => new SolidColorBrush(MultiColorConverter.ConvertToMediaColor(PrimaryColor));
[JsonIgnore]
public Brush SecondaryColorBrush => new SolidColorBrush(MultiColorConverter.ConvertToMediaColor(SecondaryColor));
[JsonIgnore]
public Brush BackgroundColorBrush => new SolidColorBrush(MultiColorConverter.ConvertToMediaColor(BackgroundColor));
protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
@@ -0,0 +1,44 @@
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
namespace DesktopMagic.Settings;
internal class DesktopMagicSettings : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private ObservableCollection<Layout> layouts = [];
private string? currentLayoutName;
public ObservableCollection<Layout> Layouts
{
get => layouts;
set
{
layouts = value;
OnPropertyChanged();
}
}
[JsonIgnore]
public Layout CurrentLayout => Layouts.FirstOrDefault(layout => layout.Name == CurrentLayoutName, Layouts.FirstOrDefault() ?? new Layout("ERROR"));
public string? CurrentLayoutName
{
get => currentLayoutName;
set
{
currentLayoutName = value;
OnPropertyChanged();
OnPropertyChanged(nameof(CurrentLayout));
}
}
protected void OnPropertyChanged([CallerMemberName] string? name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
+56
View File
@@ -0,0 +1,56 @@
using DesktopMagic.Plugins;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace DesktopMagic.Settings;
internal class Layout(string name) : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private string name = name;
private Theme theme = new Theme();
private Dictionary<string, PluginSettings> plugins = [];
public Theme Theme
{
get => theme;
set
{
theme = value;
OnPropertyChanged();
}
}
public Dictionary<string, PluginSettings> Plugins
{
get => plugins;
set
{
plugins = value;
OnPropertyChanged();
}
}
public string Name
{
get => name;
set
{
name = value;
OnPropertyChanged();
}
}
public void UpdatePlugins()
{
OnPropertyChanged(nameof(Plugins));
}
protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
@@ -0,0 +1,80 @@
using DesktopMagic.Plugins;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
using System.Windows;
namespace DesktopMagic.Settings;
public class PluginSettings : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private readonly Theme? theme;
private List<InputElement> settings = [];
private bool enabled = true;
private Point position = new Point(0, 0);
private Point size = new Point(0, 0);
[JsonIgnore]
public Theme Theme => theme is null ? MainWindowDataContext.GetSettings().CurrentLayout.Theme : theme;
public List<InputElement> Settings
{
get => settings;
set
{
if (settings != value)
{
settings = value;
OnPropertyChanged();
}
}
}
public bool Enabled
{
get => enabled;
set
{
if (enabled != value)
{
enabled = value;
OnPropertyChanged();
}
}
}
public Point Position
{
get => position;
set
{
if (position != value)
{
position = value;
OnPropertyChanged();
}
}
}
public Point Size
{
get => size;
set
{
if (size != value)
{
size = value;
OnPropertyChanged();
}
}
}
protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
+3 -2
View File
@@ -1,5 +1,6 @@
using DesktopMagicPluginAPI;
using DesktopMagicPluginAPI.Inputs;
using DesktopMagicPluginAPI.Settings;
using System;
using System.Collections.Generic;
@@ -14,10 +15,10 @@ public class GifPlugin : Plugin
{
private const string SaveFilePath = "gifPath.txt";
[Element("Gif path:")]
[Setting("Gif path:")]
private readonly TextBox input = new TextBox("");
[Element]
[Setting]
private readonly Label info = new Label("");
private readonly List<Bitmap> bitmaps = [];
+1 -14
View File
@@ -1,5 +1,4 @@
using System;
using System.Drawing;
using System.Drawing;
namespace DesktopMagicPluginAPI;
@@ -8,18 +7,6 @@ namespace DesktopMagicPluginAPI;
/// </summary>
public interface IPluginData
{
/// <summary>
/// Gets the current font of the current theme.
/// </summary>
[Obsolete("Use the \"Theme\" property instead")]
string Font { get; }
/// <summary>
/// Gets the current color of the current theme.
/// </summary>
[Obsolete("Use the \"Theme\" property instead")]
Color Color { get; }
/// <summary>
/// Gets the current theme setting of the main application.
/// </summary>
@@ -1,11 +1,11 @@
using System;
namespace DesktopMagicPluginAPI.Inputs;
namespace DesktopMagicPluginAPI.Settings;
/// <summary>
/// Represents a button control.
/// </summary>
public class Button : Element
public class Button : Setting
{
/// <summary>
/// Occurs when the button gets clicked.
@@ -1,9 +1,9 @@
namespace DesktopMagicPluginAPI.Inputs;
namespace DesktopMagicPluginAPI.Settings;
/// <summary>
/// Represents a check box control.
/// </summary>
public class CheckBox : Element
public class CheckBox : Setting
{
private bool _value;
@@ -1,11 +1,13 @@
using System.Collections.ObjectModel;
using DesktopMagicPluginAPI.Inputs;
namespace DesktopMagicPluginAPI.Inputs;
using System.Collections.ObjectModel;
namespace DesktopMagicPluginAPI.Settings;
/// <summary>
/// Represents a selection control with a drop-down list.
/// </summary>
public class ComboBox : Element
public class ComboBox : Setting
{
private string _value;
@@ -1,11 +1,11 @@
using System;
namespace DesktopMagicPluginAPI.Inputs;
namespace DesktopMagicPluginAPI.Settings;
/// <summary>
/// Represents a up-down control.
/// </summary>
public class IntegerUpDown : Element
public class IntegerUpDown : Setting
{
private int _value;
@@ -1,9 +1,11 @@
namespace DesktopMagicPluginAPI.Inputs;
using DesktopMagicPluginAPI.Settings;
namespace DesktopMagicPluginAPI.Inputs;
/// <summary>
/// Represents a label control.
/// </summary>
public class Label : Element
public class Label : Setting
{
private string _value;
@@ -1,11 +1,11 @@
using System;
namespace DesktopMagicPluginAPI.Inputs;
namespace DesktopMagicPluginAPI.Settings;
/// <summary>
/// The element base class.
/// </summary>
public abstract class Element
public abstract class Setting
{
/// <summary>
/// Occurs when the value has been changed.
@@ -6,7 +6,7 @@ namespace DesktopMagicPluginAPI.Inputs;
/// Marks a Property as element.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class ElementAttribute : Attribute
public class SettingAttribute : Attribute
{
/// <summary>
/// The name of the element.
@@ -23,7 +23,7 @@ public class ElementAttribute : Attribute
/// </summary>
/// <param name="name">The name of the element.</param>
/// <param name="orderIndex">The order index of the element.</param>
public ElementAttribute(string name, int orderIndex = 0)
public SettingAttribute(string name, int orderIndex = 0)
{
Name = name;
OrderIndex = orderIndex;
@@ -33,13 +33,13 @@ public class ElementAttribute : Attribute
/// Marks a Property as element with the provided <paramref name="orderIndex"/>.
/// </summary>
/// <param name="orderIndex">The order index of the element.</param>
public ElementAttribute(int orderIndex)
public SettingAttribute(int orderIndex)
{
OrderIndex = orderIndex;
}
/// <inheritdoc cref="ElementAttribute"/>
public ElementAttribute()
/// <inheritdoc cref="SettingAttribute"/>
public SettingAttribute()
{
}
}
@@ -1,11 +1,11 @@
using System;
namespace DesktopMagicPluginAPI.Inputs;
namespace DesktopMagicPluginAPI.Settings;
/// <summary>
/// Represents a slider control.
/// </summary>
public sealed class Slider : Element
public sealed class Slider : Setting
{
private double _value;
@@ -1,9 +1,9 @@
namespace DesktopMagicPluginAPI.Inputs;
namespace DesktopMagicPluginAPI.Settings;
/// <summary>
/// Represents a text box control.
/// </summary>
public class TextBox : Element
public class TextBox : Setting
{
private string _value;