Skip to content

Commit

Permalink
Fixed (most) broken event listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
KimihikoAkayasaki committed Mar 12, 2023
1 parent bb29ff0 commit f89fc12
Show file tree
Hide file tree
Showing 10 changed files with 100 additions and 66 deletions.
5 changes: 4 additions & 1 deletion Amethyst/Classes/AppSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,10 @@ public void ReadSettings()
AppData.Settings ??= new AppSettings(); // Reset if null
}

CheckSettings(true);
Logger.Info("Requesting re-subscription from listeners...");
Interfacing.AppSettingsRead(this, EventArgs.Empty);

CheckSettings(true); // Check partially
}

public void CheckSettings(bool partial = false, TrackingDevice device = null)
Expand Down
4 changes: 4 additions & 0 deletions Amethyst/Classes/Interfacing.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ namespace Amethyst.Classes;

public static class Interfacing
{
public delegate void AppSettingsReadEventHandler(object sender, EventArgs e);

public const uint MaxPingCheckingThreads = 3;

public static bool
Expand Down Expand Up @@ -98,6 +100,8 @@ public static bool

public static DirectoryInfo AppDataTempDir => Directory.CreateDirectory(Path.GetTempPath() + "Amethyst");

public static AppSettingsReadEventHandler AppSettingsRead { get; set; } = (_, _) => { };

public static string GetAppDataFileDir(string relativeFilePath)
{
Directory.CreateDirectory(Path.Join(
Expand Down
14 changes: 10 additions & 4 deletions Amethyst/Controls/JointSelectorExpander.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,8 @@ public JointSelectorExpander()
{
InitializeComponent();

// Register for any pending changes
AppData.Settings.PropertyChanged += (_, _) => OnPropertyChanged();
AppData.Settings.TrackersVector.CollectionChanged += (_, _) => OnPropertyChanged();
Trackers.ForEach(x => x.PropertyChanged += (_, _) => OnPropertyChanged());
ResubscribeListeners(); // Register for any pending changes
Interfacing.AppSettingsRead += (_, _) => ResubscribeListeners();
}

public string Header { get; set; } = "";
Expand All @@ -51,6 +49,14 @@ public List<AppTracker> Trackers

public event PropertyChangedEventHandler PropertyChanged;

private void ResubscribeListeners()
{
// Register for any pending changes
AppData.Settings.PropertyChanged += (_, _) => OnPropertyChanged();
AppData.Settings.TrackersVector.CollectionChanged += (_, _) => OnPropertyChanged();
Trackers.ForEach(x => x.PropertyChanged += (_, _) => OnPropertyChanged());
}

public void OnPropertyChanged(string propName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
Expand Down
10 changes: 8 additions & 2 deletions Amethyst/Controls/JointSettingsExpander.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ public JointSettingsExpander()
{
InitializeComponent();

// Register for any pending changes
AppData.Settings.PropertyChanged += (_, _) => OnPropertyChanged();
ResubscribeListeners(); // Register for any pending changes
Interfacing.AppSettingsRead += (_, _) => ResubscribeListeners();
}

public TrackerType Role { get; set; }
Expand Down Expand Up @@ -133,6 +133,12 @@ private bool Show

public event PropertyChangedEventHandler PropertyChanged;

private void ResubscribeListeners()
{
// Register for any pending changes
AppData.Settings.PropertyChanged += (_, _) => OnPropertyChanged();
}

public void OnPropertyChanged(string propName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
Expand Down
14 changes: 10 additions & 4 deletions Amethyst/Controls/OverrideExpander.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,8 @@ public OverrideExpander()
{
InitializeComponent();

// Register for any pending changes
AppData.Settings.PropertyChanged += (_, _) => OnPropertyChanged();
AppData.Settings.TrackersVector.CollectionChanged += (_, _) => OnPropertyChanged();
Trackers.ForEach(x => x.PropertyChanged += (_, _) => OnPropertyChanged());
ResubscribeListeners(); // Register for any pending changes
Interfacing.AppSettingsRead += (_, _) => ResubscribeListeners();
}

public string Header { get; set; } = "";
Expand All @@ -49,6 +47,14 @@ public List<AppTracker> Trackers

public event PropertyChangedEventHandler PropertyChanged;

private void ResubscribeListeners()
{
// Register for any pending changes
AppData.Settings.PropertyChanged += (_, _) => OnPropertyChanged();
AppData.Settings.TrackersVector.CollectionChanged += (_, _) => OnPropertyChanged();
Trackers.ForEach(x => x.PropertyChanged += (_, _) => OnPropertyChanged());
}

public void OnPropertyChanged(string propName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
Expand Down
15 changes: 8 additions & 7 deletions Amethyst/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,26 @@
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.Loader;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Windows.Data.Json;
using Windows.Graphics;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.System;
using Windows.Web.Http;
using Amethyst.Classes;
using Amethyst.MVVM;
using Amethyst.Pages;
using Amethyst.Plugins.Contract;
using Amethyst.Schedulers;
using Amethyst.Utils;
using Microsoft.AppCenter.Analytics;
using Microsoft.AppCenter.Crashes;
Expand All @@ -47,7 +44,6 @@
using RestSharp;
using WinRT;
using WinRT.Interop;
using Amethyst.Schedulers;

// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
Expand Down Expand Up @@ -350,9 +346,10 @@ public MainWindow()
Logger.Error($"Checking for external plugins has failed, an exception occurred. Message: {e.Message}");
}

// Try reading the startup task config
try
{
// Try reading the startup task config
Logger.Info("Searching for scheduled startup tasks...");
StartupController.Controller.ReadTasks();
}
catch (Exception e)
Expand All @@ -361,7 +358,7 @@ public MainWindow()
}

// Execute plugin updates: replace plugin files
foreach (var action in StartupController.Controller.UpdateTasks)
foreach (var action in StartupController.Controller.UpdateTasks.ToList())
try
{
Logger.Info($"Parsing a startup {action.GetType()} task with name \"{action.Name}\"...");
Expand All @@ -379,6 +376,10 @@ public MainWindow()
Logger.Info("Deleting the plugin update package...");
File.Delete(action.UpdatePackage); // Cleanup after the update

Logger.Info("Deleting attempted scheduled startup " +
$"{action.GetType()} task with name \"{action.Name}\"...");

StartupController.Controller.StartupTasks.Remove(action);
Logger.Info($"Looks like a startup {action.GetType()} task with " +
$"name \"{action.Name}\" has been executed successfully!");
}
Expand Down
10 changes: 8 additions & 2 deletions Amethyst/Pages/Devices.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ public Devices()
Logger.Info($"Registering devices MVVM for page: '{GetType().FullName}'...");
TrackingDeviceTreeView.ItemsSource = AppPlugins.TrackingDevicesList.Values;

//AppData.Settings.PropertyChanged += (_, _) => OnPropertyChanged();
AppData.Settings.TrackersVector.CollectionChanged += (_, _) => OnPropertyChanged();
ResubscribeListeners(); // Register for any pending changes
Interfacing.AppSettingsRead += (_, _) => ResubscribeListeners();

// Set currently tracking device & selected device
Logger.Info("Overwriting the devices TreeView selected item...");
Expand Down Expand Up @@ -104,6 +104,12 @@ public Devices()
// MVVM stuff
public event PropertyChangedEventHandler PropertyChanged;

private void ResubscribeListeners()
{
//AppData.Settings.PropertyChanged += (_, _) => OnPropertyChanged();
AppData.Settings.TrackersVector.CollectionChanged += (_, _) => OnPropertyChanged();
}

private async void Page_Loaded(object sender, RoutedEventArgs e)
{
Logger.Info($"Re/Loading page: '{GetType().FullName}'...");
Expand Down
56 changes: 31 additions & 25 deletions Amethyst/Pages/Settings.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,31 +66,8 @@ public Settings()
tracker.OnPropertyChanged(); // Refresh the transition
});

AppData.Settings.TrackersVector.CollectionChanged += (_, _) =>
{
// Trackers' collection has changed,
Shared.Main.DispatcherQueue.TryEnqueue(async () =>
{
// This 'ease in' transition will affect the added expander
AppData.Settings.TrackersVector.ToList().ForEach(tracker =>
{
tracker.SettingsExpanderTransitions =
new TransitionCollection { new ContentThemeTransition() };
tracker.OnPropertyChanged(); // Refresh the transition
});
// Wait for the transition to end
await Task.Delay(200);
// This 'move' transition will affect all tracker expanders
AppData.Settings.TrackersVector.ToList().ForEach(tracker =>
{
tracker.SettingsExpanderTransitions =
new TransitionCollection { new RepositionThemeTransition() };
tracker.OnPropertyChanged(); // Refresh the transition
});
});
};
ResubscribeListeners(); // Register for any pending changes
Interfacing.AppSettingsRead += (_, _) => ResubscribeListeners();

Logger.Info($"Registering settings MVVM for page: '{GetType().FullName}'...");
DataContext = AppData.Settings; // Set this settings instance as the context
Expand Down Expand Up @@ -203,6 +180,35 @@ private string ManageTrackersText
// MVVM stuff
public event PropertyChangedEventHandler PropertyChanged;

private void ResubscribeListeners()
{
AppData.Settings.TrackersVector.CollectionChanged += (_, _) =>
{
// Trackers' collection has changed,
Shared.Main.DispatcherQueue.TryEnqueue(async () =>
{
// This 'ease in' transition will affect the added expander
AppData.Settings.TrackersVector.ToList().ForEach(tracker =>
{
tracker.SettingsExpanderTransitions =
new TransitionCollection { new ContentThemeTransition() };
tracker.OnPropertyChanged(); // Refresh the transition
});
// Wait for the transition to end
await Task.Delay(200);
// This 'move' transition will affect all tracker expanders
AppData.Settings.TrackersVector.ToList().ForEach(tracker =>
{
tracker.SettingsExpanderTransitions =
new TransitionCollection { new RepositionThemeTransition() };
tracker.OnPropertyChanged(); // Refresh the transition
});
});
};
}


private void Page_Loaded(object sender, RoutedEventArgs e)
{
Expand Down
35 changes: 16 additions & 19 deletions Amethyst/Schedulers/StartupController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class StartupTask
{
public string Name { get; set; }
public string Data { get; set; }
public bool Priority { get; set; } = false;
public bool Priority { get; set; }
}

public class StartupUpdateTask : StartupTask
Expand All @@ -34,57 +34,54 @@ public static class StartupController

public class TaskController
{
public TaskController()
{
StartupTasks.CollectionChanged += (_, _) =>
{
// Save our changes
SaveTasks();
};
}

// Vector of actions Amethyst should do upon a graceful shutdown
// This will not be run when quitting due to runtime failures
public ObservableCollection<StartupTask> StartupTasks { get; private set; } = new();

// For updating the plugins, i.e. clean and unpack a downloaded plugin zip
public List<StartupUpdateTask> UpdateTasks => StartupTasks.OfType<StartupUpdateTask>().ToList();
public IEnumerable<StartupUpdateTask> UpdateTasks => StartupTasks.OfType<StartupUpdateTask>();

// For deleting plugins, i.e. delete a plugin folder while it's not loaded yet
public List<StartupDeleteTask> DeleteTasks => StartupTasks.OfType<StartupDeleteTask>().ToList();
public IEnumerable<StartupDeleteTask> DeleteTasks => StartupTasks.OfType<StartupDeleteTask>();

// Save settings
// Save scheduled tasks
private void SaveTasks()
{
try
{
// Save plugin settings to $env:AppData/Amethyst/
// Save scheduled startup tasks
File.WriteAllText(Path.Join(Interfacing.ProgramLocation.DirectoryName, "Startup.json"),
JsonConvert.SerializeObject(StartupTasks, Formatting.Indented,
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }));
}
catch (Exception e)
{
Logger.Error($"Error saving plugin settings! Message: {e.Message}");
Logger.Error($"Error saving startup scheduled tasks! Message: {e.Message}");
}
}

// Re/Load settings
// Re/Load scheduled tasks
public void ReadTasks()
{
try
{
// Read plugin settings from $env:AppData/Amethyst/
// Read scheduled startup tasks
StartupTasks = JsonConvert.DeserializeObject<ObservableCollection<StartupTask>>
(File.ReadAllText(Path.Join(Interfacing.ProgramLocation.DirectoryName, "Startup.json")),
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }) ??
new ObservableCollection<StartupTask>();
}
catch (Exception e)
{
Logger.Error($"Error reading plugin settings! Message: {e.Message}");
AppPlugins.PluginSettings ??= new AppPluginSettings(); // Reset if null
Logger.Error($"Error reading scheduled startup tasks! Message: {e.Message}");
StartupTasks = new ObservableCollection<StartupTask>(); // Reset if null
}

StartupTasks.CollectionChanged += (_, _) =>
{
// Save our changes
SaveTasks();
};
}
}
}
3 changes: 1 addition & 2 deletions Amethyst/Utils/TypeUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@
using System.Threading.Tasks;
using Amethyst.Plugins.Contract;
using AmethystSupport;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System.Threading;

namespace Amethyst.Utils;

Expand Down

0 comments on commit f89fc12

Please sign in to comment.