Skip to content

Commit

Permalink
Improved livelyproperty restore logic
Browse files Browse the repository at this point in the history
  • Loading branch information
rocksdanister committed Jan 24, 2025
1 parent 6549b3d commit c16c2c0
Show file tree
Hide file tree
Showing 8 changed files with 148 additions and 166 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

namespace Lively.Common.Helpers
{
public static class SingleInstanceUtil
public static class AppLifeCycleUtil
{
public static bool IsAppMutexRunning(string mutexName)
{
Expand Down
72 changes: 72 additions & 0 deletions src/Lively/Lively.Common/Helpers/LivelyPropertyUtil.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using Lively.Common.JsonConverters;
using Lively.Models.LivelyControls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace Lively.Common.Helpers
{
public static class LivelyPropertyUtil
{
public delegate Task ExecuteScriptDelegate(string key, object value);

public static async Task LoadProperty(string propertyPath, string rootDir, ExecuteScriptDelegate execute)
{
if (!File.Exists(propertyPath))
return;

var controls = GetControls(propertyPath);
foreach (var control in controls.Values)
{
// Skip, user interaction only.
if (control is ButtonModel || control is LabelModel)
continue;

object value = control switch
{
SliderModel slider => slider.Value,
DropdownModel dropdown => dropdown.Value,
FolderDropdownModel folderDropdown => GetFolderDropdownValue(folderDropdown, rootDir),
CheckboxModel checkbox => checkbox.Value,
TextboxModel textbox => textbox.Value,
ColorPickerModel colorPicker => colorPicker.Value,
_ => throw new NotSupportedException($"Unsupported control type: {control.Type}")
};

await execute(control.Name, value);
}
}

public static void LoadProperty(string propertyPath, Action<ControlModel> execute)
{
if (!File.Exists(propertyPath))
return;

var controls = GetControls(propertyPath);
foreach (var control in controls.Values)
{
// Skip, user interaction only.
if (control is ButtonModel || control is LabelModel)
continue;

execute(control);
}
}

public static Dictionary<string, ControlModel> GetControls(string propertyPath)
{
var jsonSerializerSettings = new JsonSerializerSettings { Converters = new List<JsonConverter> { new LivelyControlModelConverter() } };
return JsonConvert.DeserializeObject<Dictionary<string, ControlModel>>(File.ReadAllText(propertyPath), jsonSerializerSettings);
}

private static string GetFolderDropdownValue(FolderDropdownModel fd, string rootPath)
{
// It is null when no item is selected or file missing.
var relativeFilePath = fd.Value is null || fd.Folder is null ? null : Path.Combine(fd.Folder, fd.Value);
var filePath = relativeFilePath is null ? null : Path.Combine(rootPath, relativeFilePath);
return File.Exists(filePath) ? relativeFilePath : null;
}
}
}
54 changes: 14 additions & 40 deletions src/Lively/Lively.Player.CefSharp/Form1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -448,9 +448,7 @@ private void ChromeBrowser_TitleChanged(object sender, TitleChangedEventArgs e)
private void ChromeBrowser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
if (e.IsLoading)
{
return;
}

RestoreLivelyProperties(startArgs.Properties);
WriteToParent(new LivelyMessageWallpaperLoaded() { Success = true });
Expand Down Expand Up @@ -529,50 +527,26 @@ private void ChromeBrowser_LoadingStateChanged(object sender, LoadingStateChange
}
}

private void RestoreLivelyProperties(string path)
private void RestoreLivelyProperties(string propertyPath)
{
try
{
if (path == null)
return;
_ = LivelyPropertyUtil.LoadProperty(propertyPath, Path.GetDirectoryName(startArgs.Url), (key, value) =>
{
if (chromeBrowser.CanExecuteJavascriptInMainFrame)
chromeBrowser.ExecuteScriptAsync("livelyPropertyListener", key, value);

if (chromeBrowser.CanExecuteJavascriptInMainFrame) //if js context ready
return Task.FromResult(0);
});
}
catch (Exception ex)
{
WriteToParent(new LivelyMessageConsole()
{
foreach (var item in JsonUtil.ReadJObject(path))
{
string uiElementType = item.Value["type"].ToString();
if (!uiElementType.Equals("button", StringComparison.OrdinalIgnoreCase) && !uiElementType.Equals("label", StringComparison.OrdinalIgnoreCase))
{
if (uiElementType.Equals("dropdown", StringComparison.OrdinalIgnoreCase))
{
chromeBrowser.ExecuteScriptAsync("livelyPropertyListener", item.Key, (int)item.Value["value"]);
}
else if (uiElementType.Equals("slider", StringComparison.OrdinalIgnoreCase))
{
chromeBrowser.ExecuteScriptAsync("livelyPropertyListener", item.Key, (double)item.Value["value"]);
}
else if (uiElementType.Equals("folderDropdown", StringComparison.OrdinalIgnoreCase))
{
var fileName = item.Value["value"].ToString();
var folderName = item.Value["folder"].ToString();
var filePath = fileName is null || folderName is null ? null : Path.Combine(Path.GetDirectoryName(startArgs.Url), folderName, fileName);
chromeBrowser.ExecuteScriptAsync("livelyPropertyListener",
item.Key,
File.Exists(filePath) ? Path.Combine(folderName, fileName) : null);
}
else if (uiElementType.Equals("checkbox", StringComparison.OrdinalIgnoreCase))
{
chromeBrowser.ExecuteScriptAsync("livelyPropertyListener", item.Key, (bool)item.Value["value"]);
}
else if (uiElementType.Equals("color", StringComparison.OrdinalIgnoreCase) || uiElementType.Equals("textbox", StringComparison.OrdinalIgnoreCase))
{
chromeBrowser.ExecuteScriptAsync("livelyPropertyListener", item.Key, (string)item.Value["value"]);
}
}
}
}
Category = ConsoleMessageType.error,
Message = ex.Message
});
}
catch { }
}

private void ChromeBrowser_IsBrowserInitializedChanged1(object sender, EventArgs e)
Expand Down
73 changes: 25 additions & 48 deletions src/Lively/Lively.Player.WebView2/Form1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -313,18 +313,19 @@ await Task.Run(async () =>
switch (obj.Type)
{
case MessageType.cmd_reload:
try
{
webView?.Reload();
}
catch (Exception ie)
{
WriteToParent(new LivelyMessageConsole()
{
Category = ConsoleMessageType.error,
Message = $"Reload failed: {ie.Message}"
});
}
// ConnectionAborted issue.
//try
//{
// webView?.Reload();
//}
//catch (Exception ie)
//{
// WriteToParent(new LivelyMessageConsole()
// {
// Category = ConsoleMessageType.error,
// Message = $"Reload failed: {ie.Message}"
// });
//}
break;
case MessageType.cmd_suspend:
if (startArgs.PauseEvent && !isPaused)
Expand Down Expand Up @@ -459,47 +460,23 @@ await webView.ExecuteScriptFunctionAsync("livelyWallpaperPlaybackChanged",
}
}

private async Task RestoreLivelyProperties(string path)
private async Task RestoreLivelyProperties(string propertyPath)
{
try
{
if (path == null)
return;

foreach (var item in JsonUtil.ReadJObject(path))
await LivelyPropertyUtil.LoadProperty(propertyPath, Path.GetDirectoryName(startArgs.Url), async (key, value) =>
{
string uiElementType = item.Value["type"].ToString();
if (!uiElementType.Equals("button", StringComparison.OrdinalIgnoreCase) && !uiElementType.Equals("label", StringComparison.OrdinalIgnoreCase))
{
if (uiElementType.Equals("dropdown", StringComparison.OrdinalIgnoreCase))
{
await webView.ExecuteScriptFunctionAsync("livelyPropertyListener", item.Key, (int)item.Value["value"]);
}
else if (uiElementType.Equals("slider", StringComparison.OrdinalIgnoreCase))
{
await webView.ExecuteScriptFunctionAsync("livelyPropertyListener", item.Key, (double)item.Value["value"]);
}
else if (uiElementType.Equals("folderDropdown", StringComparison.OrdinalIgnoreCase))
{
var fileName = item.Value["value"].ToString();
var folderName = item.Value["folder"].ToString();
var filePath = fileName is null || folderName is null ? null : Path.Combine(Path.GetDirectoryName(startArgs.Url), folderName, fileName);
await webView.ExecuteScriptFunctionAsync("livelyPropertyListener",
item.Key,
File.Exists(filePath) ? Path.Combine(folderName, fileName) : null);
}
else if (uiElementType.Equals("checkbox", StringComparison.OrdinalIgnoreCase))
{
await webView.ExecuteScriptFunctionAsync("livelyPropertyListener", item.Key, (bool)item.Value["value"]);
}
else if (uiElementType.Equals("color", StringComparison.OrdinalIgnoreCase) || uiElementType.Equals("textbox", StringComparison.OrdinalIgnoreCase))
{
await webView.ExecuteScriptFunctionAsync("livelyPropertyListener", item.Key, (string)item.Value["value"]);
}
}
}
await webView.ExecuteScriptFunctionAsync("livelyPropertyListener", key, value);
});
}
catch (Exception ex)
{
WriteToParent(new LivelyMessageConsole()
{
Category = ConsoleMessageType.error,
Message = ex.Message
});
}
catch { /* TODO */ }
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Lively.Common;
using Lively.Common.JsonConverters;
using Lively.Common.Helpers;
using Lively.Common.Services;
using Lively.Grpc.Client;
using Lively.Models;
Expand All @@ -25,9 +25,6 @@ public partial class CustomiseWallpaperViewModel : ObservableObject
private readonly IUserSettingsClient userSettings;
private readonly IDispatcherService dispatcher;

private readonly JsonSerializerSettings jsonSerializerSettings;


private Dictionary<string, ControlModel> livelyControlsCopy;
private DisplayMonitor currentScreen;
private string currentFilePath;
Expand All @@ -41,8 +38,6 @@ public CustomiseWallpaperViewModel(IDesktopCoreClient desktopCore,
this.displayManager = displayManager;
this.userSettings = userSettings;
this.dispatcher = dispatcher;

this.jsonSerializerSettings = new JsonSerializerSettings { Converters = new List<JsonConverter> { new LivelyControlModelConverter() } };
}

public void Load(LibraryModel model)
Expand All @@ -55,12 +50,11 @@ public void Load(LibraryModel model)
// We create a copy of the LivelyProperties.json file and modify it instead.
(this.currentFilePath, this.currentScreen) = CreatePropertyCopy(model, userSettings.Settings.WallpaperArrangement, userSettings.Settings.SelectedDisplay);

var file = File.ReadAllText(this.currentFilePath);
var livelyControls = JsonConvert.DeserializeObject<Dictionary<string, ControlModel>>(file, this.jsonSerializerSettings);
var livelyControls = LivelyPropertyUtil.GetControls(this.currentFilePath);
this.Controls = new ObservableCollection<ControlModel>(livelyControls.Values);

// For checking value change and updating storage file.
this.livelyControlsCopy = JsonConvert.DeserializeObject<Dictionary<string, ControlModel>>(file, this.jsonSerializerSettings);
this.livelyControlsCopy = LivelyPropertyUtil.GetControls(this.currentFilePath);

if (livelyControls.Count == 0)
InfoText = "No control(s) defined.";
Expand Down Expand Up @@ -189,7 +183,7 @@ private void DropdownValueChanged(ControlModel control)
return;

// It is null when no item is selected or file missing.
var relativeFilePath = folderDropdown.Value is null ? null : Path.Combine(folderDropdown.Folder, folderDropdown.Value);
var relativeFilePath = folderDropdown.Value is null || folderDropdown.Folder is null ? null : Path.Combine(folderDropdown.Folder, folderDropdown.Value);
WallpaperSendMsg(new LivelyFolderDropdown() { Name = folderDropdown.Name, Value = relativeFilePath });
copy.Value = folderDropdown.Value;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Lively/Lively.UI.WinUI/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public static IServiceProvider Services
/// </summary>
public App()
{
if (!SingleInstanceUtil.IsAppMutexRunning(SingleInstance.UniqueAppName))
if (!AppLifeCycleUtil.IsAppMutexRunning(SingleInstance.UniqueAppName))
{
_ = NativeMethods.MessageBox(IntPtr.Zero, "Wallpaper core is not running, run Lively.exe first before opening UI.", "Lively Wallpaper", 16);
//Sad dev noises.. this.Exit() does not work without Window: https://github.com/microsoft/microsoft-ui-xaml/issues/5931
Expand Down
2 changes: 1 addition & 1 deletion src/Lively/Lively.Utility.Commandline/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ static void Main(string[] args)
errs => HandleParseError(errs));


if (!SingleInstanceUtil.IsAppMutexRunning(SingleInstance.UniqueAppName))
if (!AppLifeCycleUtil.IsAppMutexRunning(SingleInstance.UniqueAppName))
{
Console.WriteLine("\nWARNING: Lively core is currently not running!");
}
Expand Down
Loading

0 comments on commit c16c2c0

Please sign in to comment.