Skip to content

Commit

Permalink
Clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
Tyrrrz committed Mar 28, 2024
1 parent cf8e53e commit 8977ab9
Show file tree
Hide file tree
Showing 13 changed files with 68 additions and 43 deletions.
7 changes: 7 additions & 0 deletions LightBulb.WindowsApi/MessageBox.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace LightBulb.WindowsApi;

public static class MessageBox
{
public static bool ShowError(string title, string message) =>
NativeMethods.MessageBox(0, message, title, 0x10) == 0;
}
3 changes: 3 additions & 0 deletions LightBulb.WindowsApi/NativeMethods.User32.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,7 @@ uint dwFlags

[DllImport(User32, SetLastError = true)]
public static extern bool UnhookWinEvent(nint hWinEventHook);

[DllImport(User32, CharSet = CharSet.Auto)]
public static extern int MessageBox(nint hWnd, string text, string caption, uint type);
}
2 changes: 1 addition & 1 deletion LightBulb/App.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ private void DisableTemporarily1MinuteMenuItem_OnClick(object? sender, EventArgs
_mainViewModel.Dashboard.DisableTemporarilyCommand.Execute(TimeSpan.FromMinutes(1));

private void ExitMenuItem_OnClick(object? sender, EventArgs args) =>
ApplicationLifetime?.TryShutdown();
ApplicationLifetime?.Shutdown();

public void Dispose() => _services.Dispose();
}
6 changes: 2 additions & 4 deletions LightBulb/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using System.Reflection;
using System.Threading;
using Avalonia;
using LightBulb.Utils;
using LightBulb.WindowsApi;

namespace LightBulb;

Expand Down Expand Up @@ -49,9 +49,7 @@ out var isOnlyRunningInstance
}
catch (Exception ex)
{
if (OperatingSystem.IsWindows())
_ = NativeMethods.Windows.MessageBox(0, ex.ToString(), "Fatal Error", 0x10);

MessageBox.ShowError("Fatal Error", ex.ToString());
throw;
}
finally
Expand Down
4 changes: 2 additions & 2 deletions LightBulb/Services/SettingsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public partial class SettingsService() : SettingsBase(GetFilePath())
new(
RegistryHive.CurrentUser,
@"Software\Microsoft\Windows\CurrentVersion\Run",
"LightBulb",
Program.Name,
$"\"{Program.ExecutableFilePath}\" {StartupOptions.IsInitiallyHiddenArgument}"
);

Expand Down Expand Up @@ -183,7 +183,7 @@ private static string GetFilePath()
{
return Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"LightBulb",
Program.Name,
"Settings.json"
);
}
Expand Down
4 changes: 1 addition & 3 deletions LightBulb/Services/UpdateService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,7 @@ public void FinalizePendingUpdates()
return;

_updateManager.LaunchUpdater(lastPreparedUpdate);

if (Application.Current?.ApplicationLifetime?.TryShutdown(2) != true)
Environment.Exit(2);
Application.Current?.ApplicationLifetime?.Shutdown(2);
}
catch (UpdaterAlreadyLaunchedException)
{
Expand Down
9 changes: 3 additions & 6 deletions LightBulb/StartupOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ public partial class StartupOptions
{
public static string IsInitiallyHiddenArgument { get; } = "--start-hidden";

public static StartupOptions Current { get; } =
Parse(Environment.GetCommandLineArgs().Skip(1).ToArray());

public static StartupOptions Parse(IReadOnlyList<string> commandLineArgs) =>
new()
{
Expand All @@ -22,9 +25,3 @@ public static StartupOptions Parse(IReadOnlyList<string> commandLineArgs) =>
)
};
}

public partial class StartupOptions
{
public static StartupOptions Current { get; } =
Parse(Environment.GetCommandLineArgs().Skip(1).ToArray());
}
12 changes: 7 additions & 5 deletions LightBulb/Utils/Extensions/AvaloniaExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Avalonia.Controls;
using System;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;

namespace LightBulb.Utils.Extensions;
Expand All @@ -13,19 +14,20 @@ internal static class AvaloniaExtensions
return null;
}

public static bool TryShutdown(this IApplicationLifetime lifetime, int exitCode = 0)
public static void Shutdown(this IApplicationLifetime lifetime, int exitCode = 0)
{
if (lifetime is IClassicDesktopStyleApplicationLifetime desktopLifetime)
{
return desktopLifetime.TryShutdown(exitCode);
desktopLifetime.TryShutdown(exitCode);
return;
}

if (lifetime is IControlledApplicationLifetime controlledLifetime)
{
controlledLifetime.Shutdown(exitCode);
return true;
return;
}

return false;
Environment.Exit(exitCode);
}
}
28 changes: 25 additions & 3 deletions LightBulb/Utils/Extensions/NotifyPropertyChangedExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reactive.Disposables;
using System.Reflection;
Expand All @@ -10,15 +12,20 @@ namespace LightBulb.Utils.Extensions;

internal static class NotifyPropertyChangedExtensions
{
public static IDisposable WatchProperty<TOwner, TProperty>(
public static IDisposable WatchProperty<TOwner>(
this TOwner owner,
Expression<Func<TOwner, TProperty>> propertyExpression,
Expression<Func<TOwner, object?>> propertyExpression,
Action handle,
bool watchInitialValue = true
)
where TOwner : INotifyPropertyChanged
{
if (propertyExpression.Body is not MemberExpression { Member: PropertyInfo property })
var memberExpression =
propertyExpression.Body as MemberExpression
// If the property is not of type object, it will be wrapped in an unary conversion expression
?? (propertyExpression.Body as UnaryExpression)?.Operand as MemberExpression;

if (memberExpression?.Member is not PropertyInfo property)
throw new ArgumentException("Provided expression must reference a property.");

void OnPropertyChanged(object? sender, PropertyChangedEventArgs args)
Expand All @@ -40,6 +47,21 @@ void OnPropertyChanged(object? sender, PropertyChangedEventArgs args)
return Disposable.Create(() => owner.PropertyChanged -= OnPropertyChanged);
}

public static IDisposable WatchProperties<TOwner>(
this TOwner owner,
IReadOnlyList<Expression<Func<TOwner, object?>>> propertyExpressions,
Action handle,
bool watchInitialValue = true
)
where TOwner : INotifyPropertyChanged
{
var watchers = propertyExpressions
.Select(x => WatchProperty(owner, x, handle, watchInitialValue))
.ToArray();

return Disposable.Create(() => watchers.DisposeAll());
}

public static IDisposable WatchAllProperties<TOwner>(
this TOwner owner,
Action handle,
Expand Down
12 changes: 0 additions & 12 deletions LightBulb/Utils/NativeMethods.cs

This file was deleted.

15 changes: 15 additions & 0 deletions LightBulb/ViewModels/Components/DashboardViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,21 @@ ExternalApplicationService externalApplicationService
)
);

_eventRoot.Add(
// Re-register hotkeys when they get updated
settingsService.WatchProperties(
[
o => o.ToggleHotKey,
o => o.IncreaseTemperatureOffsetHotKey,
o => o.DecreaseTemperatureOffsetHotKey,
o => o.IncreaseBrightnessOffsetHotKey,
o => o.DecreaseBrightnessOffsetHotKey,
o => o.ResetConfigurationOffsetHotKey
],
RegisterHotKeys
)
);

_updateConfigurationTimer = new Timer(TimeSpan.FromMilliseconds(50), UpdateConfiguration);
_updateInstantTimer = new Timer(TimeSpan.FromMilliseconds(50), UpdateInstant);
_updateIsPausedTimer = new Timer(TimeSpan.FromSeconds(1), UpdateIsPaused);
Expand Down
7 changes: 1 addition & 6 deletions LightBulb/ViewModels/MainViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,14 +112,9 @@ private async Task InitializeAsync()
}

[RelayCommand]
private async Task ShowSettingsAsync()
{
private async Task ShowSettingsAsync() =>
await dialogManager.ShowDialogAsync(viewModelManager.CreateSettingsViewModel());

// Re-initialize timers, hotkeys, and other stateful components
Dashboard.InitializeCommand.Execute(null);
}

[RelayCommand]
private void ShowAbout() => ProcessEx.StartShellExecute(Program.ProjectUrl);

Expand Down
2 changes: 1 addition & 1 deletion LightBulb/Views/MainView.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
xmlns:materialIcons="clr-namespace:Material.Icons.Avalonia;assembly=Material.Icons.Avalonia"
xmlns:viewModels="clr-namespace:LightBulb.ViewModels"
x:Name="Window"
Title="LightBulb"
Title="{x:Static lightBulb:Program.Name}"
Width="450"
Height="350"
CanResize="False"
Expand Down

0 comments on commit 8977ab9

Please sign in to comment.