Flow.Launcher/Flow.Launcher.Core/Plugin/JsonRPCPlugin.cs

678 lines
28 KiB
C#
Raw Normal View History

2022-08-22 00:59:31 +00:00
using Flow.Launcher.Core.Resource;
using Flow.Launcher.Infrastructure;
using System;
2016-01-06 21:34:42 +00:00
using System.Collections.Generic;
2014-07-06 14:57:11 +00:00
using System.Diagnostics;
2021-02-14 05:56:27 +00:00
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
2014-07-10 15:57:08 +00:00
using System.Threading;
using System.Threading.Tasks;
2020-04-21 09:12:17 +00:00
using Flow.Launcher.Infrastructure.Logger;
using Flow.Launcher.Infrastructure.UserSettings;
2020-04-21 09:12:17 +00:00
using Flow.Launcher.Plugin;
using Microsoft.IO;
using System.Windows;
using System.Windows.Controls;
2021-10-30 18:46:57 +00:00
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using CheckBox = System.Windows.Controls.CheckBox;
using Control = System.Windows.Controls.Control;
using Orientation = System.Windows.Controls.Orientation;
using TextBox = System.Windows.Controls.TextBox;
using UserControl = System.Windows.Controls.UserControl;
2022-12-10 00:53:41 +00:00
using System.Windows.Documents;
using static System.Windows.Forms.LinkLabel;
using Droplex;
2022-12-11 03:39:28 +00:00
using System.Windows.Forms;
2014-07-06 14:57:11 +00:00
2020-04-21 09:12:17 +00:00
namespace Flow.Launcher.Core.Plugin
2014-07-06 14:57:11 +00:00
{
2014-12-26 11:36:43 +00:00
/// <summary>
/// Represent the plugin that using JsonPRC
/// every JsonRPC plugin should has its own plugin instance
2014-12-26 11:36:43 +00:00
/// </summary>
internal abstract class JsonRPCPlugin : IAsyncPlugin, IContextMenu, ISettingProvider, ISavable
2014-07-06 14:57:11 +00:00
{
protected PluginInitContext context;
public const string JsonRPC = "JsonRPC";
2014-07-06 14:57:11 +00:00
2021-08-13 05:55:07 +00:00
protected abstract Task<Stream> RequestAsync(JsonRPCRequestModel rpcRequest, CancellationToken token = default);
protected abstract string Request(JsonRPCRequestModel rpcRequest, CancellationToken token = default);
2014-07-06 14:57:11 +00:00
private static readonly RecyclableMemoryStreamManager BufferManager = new();
private string SettingConfigurationPath => Path.Combine(context.CurrentPluginMetadata.PluginDirectory, "SettingsTemplate.yaml");
private string SettingPath => Path.Combine(DataLocation.PluginSettingsDirectory, context.CurrentPluginMetadata.Name, "Settings.json");
2017-04-11 13:34:04 +00:00
public List<Result> LoadContextMenus(Result selectedResult)
{
2021-08-13 05:55:07 +00:00
var request = new JsonRPCRequestModel
{
Method = "context_menu",
Parameters = new[]
{
selectedResult.ContextData
}
};
var output = Request(request);
return DeserializedResult(output);
2017-04-11 13:34:04 +00:00
}
2021-07-05 03:03:07 +00:00
private static readonly JsonSerializerOptions options = new()
{
2021-07-05 03:03:07 +00:00
PropertyNameCaseInsensitive = true,
#pragma warning disable SYSLIB0020
// IgnoreNullValues is obsolete, but the replacement JsonIgnoreCondition.WhenWritingNull still
// deserializes null, instead of ignoring it and leaving the default (empty list). We can change the behaviour
// to accept null and fallback to a default etc, or just keep IgnoreNullValues for now
// see: https://github.com/dotnet/runtime/issues/39152
IgnoreNullValues = true,
#pragma warning restore SYSLIB0020 // Type or member is obsolete
Converters =
{
new JsonObjectConverter()
}
};
2021-11-14 17:46:09 +00:00
private static readonly JsonSerializerOptions settingSerializeOption = new()
{
WriteIndented = true
};
private Dictionary<string, object> Settings { get; set; }
2014-07-07 15:05:06 +00:00
private readonly Dictionary<string, FrameworkElement> _settingControls = new();
2021-11-14 17:46:09 +00:00
2021-02-14 05:59:59 +00:00
private async Task<List<Result>> DeserializedResultAsync(Stream output)
{
await using (output)
{
if (output == Stream.Null) return null;
2021-02-14 05:59:59 +00:00
var queryResponseModel =
await JsonSerializer.DeserializeAsync<JsonRPCQueryResponseModel>(output, options);
return ParseResults(queryResponseModel);
}
2021-02-14 05:59:59 +00:00
}
private List<Result> DeserializedResult(string output)
{
if (string.IsNullOrEmpty(output)) return null;
var queryResponseModel =
2021-07-05 03:03:07 +00:00
JsonSerializer.Deserialize<JsonRPCQueryResponseModel>(output, options);
2021-02-14 05:59:59 +00:00
return ParseResults(queryResponseModel);
}
2021-02-14 05:56:27 +00:00
private List<Result> ParseResults(JsonRPCQueryResponseModel queryResponseModel)
{
if (queryResponseModel.Result == null) return null;
if (!string.IsNullOrEmpty(queryResponseModel.DebugMessage))
2021-02-14 05:59:59 +00:00
{
context.API.ShowMsg(queryResponseModel.DebugMessage);
}
foreach (var result in queryResponseModel.Result)
2021-02-14 05:56:27 +00:00
{
2022-04-15 23:32:05 +00:00
result.AsyncAction = async c =>
2017-04-11 13:32:51 +00:00
{
2021-11-14 17:46:09 +00:00
UpdateSettings(result.SettingsChange);
2021-11-14 05:48:53 +00:00
2021-02-14 05:56:27 +00:00
if (result.JsonRPCAction == null) return false;
if (string.IsNullOrEmpty(result.JsonRPCAction.Method))
2021-02-14 05:56:27 +00:00
{
return !result.JsonRPCAction.DontHideAfterAction;
}
if (result.JsonRPCAction.Method.StartsWith("Flow.Launcher."))
{
ExecuteFlowLauncherAPI(result.JsonRPCAction.Method["Flow.Launcher.".Length..],
result.JsonRPCAction.Parameters);
}
else
{
await using var actionResponse = await RequestAsync(result.JsonRPCAction);
if (actionResponse.Length == 0)
2017-04-11 13:32:51 +00:00
{
return !result.JsonRPCAction.DontHideAfterAction;
2021-02-14 05:56:27 +00:00
}
var jsonRpcRequestModel = await
JsonSerializer.DeserializeAsync<JsonRPCRequestModel>(actionResponse, options);
if (jsonRpcRequestModel?.Method?.StartsWith("Flow.Launcher.") ?? false)
2021-02-14 05:56:27 +00:00
{
ExecuteFlowLauncherAPI(jsonRpcRequestModel.Method["Flow.Launcher.".Length..],
jsonRpcRequestModel.Parameters);
2017-04-11 13:32:51 +00:00
}
2021-02-14 05:56:27 +00:00
}
2021-02-08 06:37:37 +00:00
2021-02-14 05:56:27 +00:00
return !result.JsonRPCAction.DontHideAfterAction;
};
2014-07-06 14:57:11 +00:00
}
2021-02-08 06:37:37 +00:00
var results = new List<Result>();
results.AddRange(queryResponseModel.Result);
2021-11-14 17:46:09 +00:00
UpdateSettings(queryResponseModel.SettingsChange);
2021-02-14 05:56:27 +00:00
return results;
}
2020-04-21 12:16:10 +00:00
private void ExecuteFlowLauncherAPI(string method, object[] parameters)
2014-07-10 15:57:08 +00:00
{
var parametersTypeArray = parameters.Select(param => param.GetType()).ToArray();
var methodInfo = typeof(IPublicAPI).GetMethod(method, parametersTypeArray);
if (methodInfo == null)
{
return;
}
try
{
methodInfo.Invoke(PluginManager.API, parameters);
}
catch (Exception)
2014-07-10 15:57:08 +00:00
{
#if (DEBUG)
throw;
2014-07-10 15:57:08 +00:00
#endif
}
}
2014-07-07 15:05:06 +00:00
/// <summary>
/// Execute external program and return the output
/// </summary>
/// <param name="fileName"></param>
/// <param name="arguments"></param>
2021-02-08 06:37:37 +00:00
/// <param name="token">Cancellation Token</param>
2014-07-07 15:05:06 +00:00
/// <returns></returns>
2021-02-14 05:56:27 +00:00
protected Task<Stream> ExecuteAsync(string fileName, string arguments, CancellationToken token = default)
2014-07-18 12:00:55 +00:00
{
2021-02-14 05:56:27 +00:00
ProcessStartInfo start = new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
2021-02-14 04:02:59 +00:00
return ExecuteAsync(start, token);
2014-07-18 12:00:55 +00:00
}
protected string Execute(ProcessStartInfo startInfo)
{
try
{
using var process = Process.Start(startInfo);
if (process == null) return string.Empty;
2021-02-14 05:56:27 +00:00
using var standardOutput = process.StandardOutput;
var result = standardOutput.ReadToEnd();
if (string.IsNullOrEmpty(result))
{
using var standardError = process.StandardError;
var error = standardError.ReadToEnd();
if (!string.IsNullOrEmpty(error))
{
Log.Error($"|JsonRPCPlugin.Execute|{error}");
return string.Empty;
}
Log.Error("|JsonRPCPlugin.Execute|Empty standard output and standard error.");
return string.Empty;
}
return result;
}
catch (Exception e)
{
Log.Exception(
$"|JsonRPCPlugin.Execute|Exception for filename <{startInfo.FileName}> with argument <{startInfo.Arguments}>",
e);
return string.Empty;
}
}
2021-02-14 05:56:27 +00:00
protected async Task<Stream> ExecuteAsync(ProcessStartInfo startInfo, CancellationToken token = default)
2014-07-06 14:57:11 +00:00
{
using var process = Process.Start(startInfo);
if (process == null)
2014-07-06 14:57:11 +00:00
{
Log.Error("|JsonRPCPlugin.ExecuteAsync|Can't start new process");
return Stream.Null;
}
var sourceBuffer = BufferManager.GetStream();
using var errorBuffer = BufferManager.GetStream();
var sourceCopyTask = process.StandardOutput.BaseStream.CopyToAsync(sourceBuffer, token);
var errorCopyTask = process.StandardError.BaseStream.CopyToAsync(errorBuffer, token);
await using var registeredEvent = token.Register(() =>
{
try
{
if (!process.HasExited)
process.Kill();
sourceBuffer.Dispose();
}
catch (Exception e)
{
Log.Exception("|JsonRPCPlugin.ExecuteAsync|Exception when kill process", e);
}
});
try
{
// token expire won't instantly trigger the exception,
// manually kill process at before
await process.WaitForExitAsync(token);
await Task.WhenAll(sourceCopyTask, errorCopyTask);
}
catch (OperationCanceledException)
{
await sourceBuffer.DisposeAsync();
return Stream.Null;
}
switch (sourceBuffer.Length, errorBuffer.Length)
2021-07-27 06:11:48 +00:00
{
case (0, 0):
2022-08-22 02:09:56 +00:00
const string errorMessage = "Empty JSON-RPC Response.";
Log.Warn($"|{nameof(JsonRPCPlugin)}.{nameof(ExecuteAsync)}|{errorMessage}");
break;
case (_, not 0):
throw new InvalidDataException(Encoding.UTF8.GetString(errorBuffer.ToArray())); // The process has exited with an error message
2021-07-27 06:11:48 +00:00
}
sourceBuffer.Seek(0, SeekOrigin.Begin);
return sourceBuffer;
2014-07-06 14:57:11 +00:00
}
2021-02-08 06:37:37 +00:00
public async Task<List<Result>> QueryAsync(Query query, CancellationToken token)
{
2021-08-13 05:55:07 +00:00
var request = new JsonRPCRequestModel
{
Method = "query",
Parameters = new object[]
2021-08-13 05:55:07 +00:00
{
query.Search
},
Settings = Settings
2021-08-13 05:55:07 +00:00
};
var output = await RequestAsync(request, token);
return await DeserializedResultAsync(output);
2021-02-08 06:37:37 +00:00
}
public async Task InitSettingAsync()
{
2021-10-30 18:46:57 +00:00
if (!File.Exists(SettingConfigurationPath))
return;
if (File.Exists(SettingPath))
2021-12-09 03:17:51 +00:00
{
await using var fileStream = File.OpenRead(SettingPath);
Settings = await JsonSerializer.DeserializeAsync<Dictionary<string, object>>(fileStream, options);
}
2021-10-30 18:46:57 +00:00
var deserializer = new DeserializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).Build();
_settingsTemplate = deserializer.Deserialize<JsonRpcConfigurationModel>(await File.ReadAllTextAsync(SettingConfigurationPath));
2021-10-30 18:46:57 +00:00
Settings ??= new Dictionary<string, object>();
2021-10-30 18:46:57 +00:00
foreach (var (type, attribute) in _settingsTemplate.Body)
{
2021-11-16 02:35:05 +00:00
if (type == "textBlock")
continue;
2021-10-30 18:46:57 +00:00
if (!Settings.ContainsKey(attribute.Name))
{
2021-10-30 18:46:57 +00:00
Settings[attribute.Name] = attribute.DefaultValue;
}
}
}
public virtual async Task InitAsync(PluginInitContext context)
2014-07-06 14:57:11 +00:00
{
2021-02-08 06:37:37 +00:00
this.context = context;
await InitSettingAsync();
}
2022-12-09 23:04:56 +00:00
private static readonly Thickness settingControlMargin = new(0, 9, 18, 9);
private static readonly Thickness settingCheckboxMargin = new(0, 9, 9, 9);
private static readonly Thickness settingPanelMargin = new(0, 0, 0, 0);
2022-12-11 03:29:17 +00:00
private static readonly Thickness settingTextBlockMargin = new(70, 9, 18, 9);
private static readonly Thickness settingLabelPanelMargin = new(70, 9, 18, 9);
private static readonly Thickness settingLabelMargin = new(0, 0, 0, 0);
private static readonly Thickness settingDescMargin = new(0, 2, 0, 0);
2022-12-09 23:04:56 +00:00
private static readonly Thickness settingSepMargin = new(0, 0, 0, 2);
2021-10-30 18:46:57 +00:00
private JsonRpcConfigurationModel _settingsTemplate;
public Control CreateSettingPanel()
{
if (Settings == null)
return new();
var settingWindow = new UserControl();
var mainPanel = new Grid
{
2022-12-11 03:29:17 +00:00
Margin = settingPanelMargin, VerticalAlignment = VerticalAlignment.Center
};
2022-12-09 23:04:56 +00:00
ColumnDefinition gridCol1 = new ColumnDefinition();
ColumnDefinition gridCol2 = new ColumnDefinition();
2021-10-30 18:46:57 +00:00
2022-12-09 23:04:56 +00:00
gridCol1.Width = new GridLength(70, GridUnitType.Star);
gridCol2.Width = new GridLength(30, GridUnitType.Star);
mainPanel.ColumnDefinitions.Add(gridCol1);
mainPanel.ColumnDefinitions.Add(gridCol2);
settingWindow.Content = mainPanel;
int rowCount = 0;
2021-10-30 18:46:57 +00:00
foreach (var (type, attribute) in _settingsTemplate.Body)
{
2022-12-09 23:04:56 +00:00
Separator sep = new Separator();
sep.VerticalAlignment = VerticalAlignment.Top;
sep.Margin = settingSepMargin;
sep.SetResourceReference(Separator.BackgroundProperty, "Color03B"); /* for theme change */
var panel = new StackPanel
{
Orientation = Orientation.Vertical,
VerticalAlignment = VerticalAlignment.Center,
2022-12-11 03:29:17 +00:00
Margin = settingLabelPanelMargin
};
RowDefinition gridRow = new RowDefinition();
mainPanel.RowDefinitions.Add(gridRow);
2021-12-17 02:25:41 +00:00
var name = new TextBlock()
{
2021-12-17 02:25:41 +00:00
Text = attribute.Label,
2021-12-16 19:05:17 +00:00
VerticalAlignment = VerticalAlignment.Center,
Margin = settingLabelMargin,
2021-12-17 02:25:41 +00:00
TextWrapping = TextWrapping.WrapWithOverflow
};
2022-12-09 23:04:56 +00:00
var desc = new TextBlock()
{
Text = attribute.Description,
FontSize = 12,
VerticalAlignment = VerticalAlignment.Center,
Margin = settingDescMargin,
2021-12-17 02:25:41 +00:00
TextWrapping = TextWrapping.WrapWithOverflow
};
2022-12-09 23:04:56 +00:00
desc.SetResourceReference(TextBlock.ForegroundProperty, "Color04B");
if (attribute.Description == null) /* if no description, hide */
desc.Visibility = Visibility.Collapsed;
if (type != "textBlock") /* if textBlock, hide desc */
{
panel.Children.Add(name);
panel.Children.Add(desc);
}
2022-12-09 23:04:56 +00:00
Grid.SetColumn(panel, 0);
Grid.SetRow(panel, rowCount);
2021-10-30 18:46:57 +00:00
2021-11-16 02:35:05 +00:00
FrameworkElement contentControl;
2021-10-30 18:46:57 +00:00
switch (type)
{
2021-11-16 02:35:05 +00:00
case "textBlock":
{
contentControl = new TextBlock
2021-11-16 02:35:05 +00:00
{
Text = attribute.Description.Replace("\\r\\n", "\r\n"),
Margin = settingTextBlockMargin,
Padding = new Thickness(0, 0, 0, 0),
2022-12-11 03:39:28 +00:00
HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
TextAlignment = TextAlignment.Left,
2022-12-11 03:29:17 +00:00
TextWrapping = TextWrapping.Wrap
};
Grid.SetColumn(contentControl, 0);
Grid.SetColumnSpan(contentControl, 2);
Grid.SetRow(contentControl, rowCount);
if (rowCount != 0)
mainPanel.Children.Add(sep);
Grid.SetRow(sep, rowCount);
Grid.SetColumn(sep, 0);
Grid.SetColumnSpan(sep, 2);
break;
}
2021-11-14 17:46:09 +00:00
case "input":
{
var textBox = new TextBox()
{
Text = Settings[attribute.Name] as string ?? string.Empty,
Margin = settingControlMargin,
2022-12-11 03:39:28 +00:00
HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
ToolTip = attribute.Description
};
textBox.TextChanged += (_, _) =>
{
Settings[attribute.Name] = textBox.Text;
};
contentControl = textBox;
Grid.SetColumn(contentControl, 1);
Grid.SetRow(contentControl, rowCount);
if (rowCount != 0)
mainPanel.Children.Add(sep);
Grid.SetRow(sep, rowCount);
Grid.SetColumn(sep, 0);
Grid.SetColumnSpan(sep, 2);
break;
}
2022-12-11 03:39:28 +00:00
case "inputWithFileBtn":
{
var textBox = new TextBox()
2022-12-11 03:39:28 +00:00
{
Margin = new Thickness(10, 0, 0, 0),
Text = Settings[attribute.Name] as string ?? string.Empty,
HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
ToolTip = attribute.Description
};
textBox.TextChanged += (_, _) =>
{
Settings[attribute.Name] = textBox.Text;
};
var Btn = new System.Windows.Controls.Button()
{
Margin = new Thickness(10, 0, 0, 0), Content = "Browse"
};
var dockPanel = new DockPanel()
{
Margin = settingControlMargin
};
DockPanel.SetDock(Btn, Dock.Right);
dockPanel.Children.Add(Btn);
dockPanel.Children.Add(textBox);
contentControl = dockPanel;
Grid.SetColumn(contentControl, 1);
Grid.SetRow(contentControl, rowCount);
if (rowCount != 0)
mainPanel.Children.Add(sep);
Grid.SetRow(sep, rowCount);
Grid.SetColumn(sep, 0);
Grid.SetColumnSpan(sep, 2);
break;
}
2021-10-30 18:46:57 +00:00
case "textarea":
{
var textBox = new TextBox()
{
Height = 120,
Margin = settingControlMargin,
2022-12-09 23:04:56 +00:00
VerticalAlignment = VerticalAlignment.Center,
TextWrapping = TextWrapping.WrapWithOverflow,
AcceptsReturn = true,
2022-12-11 03:39:28 +00:00
HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
Text = Settings[attribute.Name] as string ?? string.Empty,
ToolTip = attribute.Description
};
textBox.TextChanged += (sender, _) =>
{
Settings[attribute.Name] = ((TextBox)sender).Text;
};
contentControl = textBox;
Grid.SetColumn(contentControl, 1);
Grid.SetRow(contentControl, rowCount);
if (rowCount != 0)
mainPanel.Children.Add(sep);
Grid.SetRow(sep, rowCount);
Grid.SetColumn(sep, 0);
Grid.SetColumnSpan(sep, 2);
break;
}
2021-11-14 05:59:14 +00:00
case "passwordBox":
{
var passwordBox = new PasswordBox()
2021-11-14 05:59:14 +00:00
{
Margin = settingControlMargin,
Password = Settings[attribute.Name] as string ?? string.Empty,
PasswordChar = attribute.passwordChar == default ? '*' : attribute.passwordChar,
2022-12-11 03:39:28 +00:00
HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
ToolTip = attribute.Description
};
passwordBox.PasswordChanged += (sender, _) =>
{
Settings[attribute.Name] = ((PasswordBox)sender).Password;
};
contentControl = passwordBox;
Grid.SetColumn(contentControl, 1);
Grid.SetRow(contentControl, rowCount);
if (rowCount != 0)
mainPanel.Children.Add(sep);
Grid.SetRow(sep, rowCount);
Grid.SetColumn(sep, 0);
Grid.SetColumnSpan(sep, 2);
break;
}
2021-10-30 18:46:57 +00:00
case "dropdown":
{
2022-12-11 03:39:28 +00:00
var comboBox = new System.Windows.Controls.ComboBox()
2021-10-30 18:46:57 +00:00
{
ItemsSource = attribute.Options,
SelectedItem = Settings[attribute.Name],
Margin = settingControlMargin,
2022-12-11 03:39:28 +00:00
HorizontalAlignment = System.Windows.HorizontalAlignment.Right,
ToolTip = attribute.Description
};
comboBox.SelectionChanged += (sender, _) =>
{
2022-12-11 03:39:28 +00:00
Settings[attribute.Name] = (string)((System.Windows.Controls.ComboBox)sender).SelectedItem;
};
contentControl = comboBox;
Grid.SetColumn(contentControl, 1);
Grid.SetRow(contentControl, rowCount);
if (rowCount != 0)
mainPanel.Children.Add(sep);
Grid.SetRow(sep, rowCount);
Grid.SetColumn(sep, 0);
Grid.SetColumnSpan(sep, 2);
break;
}
2021-10-30 18:46:57 +00:00
case "checkbox":
var checkBox = new CheckBox
{
2021-10-30 18:46:57 +00:00
IsChecked = Settings[attribute.Name] is bool isChecked ? isChecked : bool.Parse(attribute.DefaultValue),
2022-12-09 23:04:56 +00:00
Margin = settingCheckboxMargin,
2022-12-11 03:39:28 +00:00
HorizontalAlignment = System.Windows.HorizontalAlignment.Right,
2021-11-16 02:35:05 +00:00
ToolTip = attribute.Description
};
checkBox.Click += (sender, _) =>
{
Settings[attribute.Name] = ((CheckBox)sender).IsChecked;
};
2021-10-30 18:46:57 +00:00
contentControl = checkBox;
Grid.SetColumn(contentControl, 1);
Grid.SetRow(contentControl, rowCount);
2022-12-09 23:04:56 +00:00
if (rowCount != 0)
mainPanel.Children.Add(sep);
Grid.SetRow(sep, rowCount);
Grid.SetColumn(sep, 0);
Grid.SetColumnSpan(sep, 2);
break;
2022-12-10 00:53:41 +00:00
case "hyperlink":
var hyperlink = new Hyperlink
{
ToolTip = attribute.Description, NavigateUri = attribute.url
2022-12-10 00:53:41 +00:00
};
2022-12-11 03:39:28 +00:00
var linkbtn = new System.Windows.Controls.Button
2022-12-10 00:53:41 +00:00
{
HorizontalAlignment = System.Windows.HorizontalAlignment.Right, Margin = settingControlMargin
2022-12-10 00:53:41 +00:00
};
linkbtn.Content = attribute.urlLabel;
contentControl = linkbtn;
Grid.SetColumn(contentControl, 1);
Grid.SetRow(contentControl, rowCount);
if (rowCount != 0)
mainPanel.Children.Add(sep);
Grid.SetRow(sep, rowCount);
Grid.SetColumn(sep, 0);
Grid.SetColumnSpan(sep, 2);
break;
default:
2021-10-30 18:46:57 +00:00
continue;
}
2021-11-16 02:35:05 +00:00
if (type != "textBlock")
_settingControls[attribute.Name] = contentControl;
mainPanel.Children.Add(panel);
mainPanel.Children.Add(contentControl);
rowCount++;
}
return settingWindow;
}
public void Save()
{
if (Settings != null)
{
Helper.ValidateDirectory(Path.Combine(DataLocation.PluginSettingsDirectory, context.CurrentPluginMetadata.Name));
2021-11-14 17:46:09 +00:00
File.WriteAllText(SettingPath, JsonSerializer.Serialize(Settings, settingSerializeOption));
}
}
public void UpdateSettings(Dictionary<string, object> settings)
{
if (settings == null || settings.Count == 0)
return;
foreach (var (key, value) in settings)
{
if (Settings.ContainsKey(key))
{
Settings[key] = value;
}
if (_settingControls.ContainsKey(key))
{
switch (_settingControls[key])
{
case TextBox textBox:
textBox.Dispatcher.Invoke(() => textBox.Text = value as string);
break;
case PasswordBox passwordBox:
passwordBox.Dispatcher.Invoke(() => passwordBox.Password = value as string);
break;
2022-12-11 03:39:28 +00:00
case System.Windows.Controls.ComboBox comboBox:
2021-11-14 17:46:09 +00:00
comboBox.Dispatcher.Invoke(() => comboBox.SelectedItem = value);
break;
case CheckBox checkBox:
checkBox.Dispatcher.Invoke(() => checkBox.IsChecked = value is bool isChecked ? isChecked : bool.Parse(value as string));
break;
}
}
}
2014-07-06 14:57:11 +00:00
}
}
2022-08-08 21:55:04 +00:00
}