CommandController.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. using System.Collections.Generic;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Threading.Tasks;
  6. using Avalonia.Media;
  7. using Avalonia.Media.Imaging;
  8. using Avalonia.Threading;
  9. using CommunityToolkit.Mvvm.ComponentModel;
  10. using Microsoft.Extensions.DependencyInjection;
  11. using Newtonsoft.Json;
  12. using PixiEditor.AvaloniaUI.Helpers.Extensions;
  13. using PixiEditor.AvaloniaUI.Models.Commands.Attributes.Evaluators;
  14. using PixiEditor.AvaloniaUI.Models.Commands.Commands;
  15. using PixiEditor.AvaloniaUI.Models.Commands.Evaluators;
  16. using PixiEditor.AvaloniaUI.Models.Dialogs;
  17. using PixiEditor.AvaloniaUI.Models.Handlers;
  18. using PixiEditor.AvaloniaUI.Models.Input;
  19. using PixiEditor.AvaloniaUI.Models.Structures;
  20. using PixiEditor.Extensions.Common.Localization;
  21. using CommandAttribute = PixiEditor.AvaloniaUI.Models.Commands.Attributes.Commands.Command;
  22. namespace PixiEditor.AvaloniaUI.Models.Commands;
  23. internal class CommandController
  24. {
  25. private ShortcutFile shortcutFile;
  26. public static CommandController Current { get; private set; }
  27. public static string ShortcutsPath { get; private set; }
  28. public CommandCollection Commands { get; }
  29. public List<CommandGroup> CommandGroups { get; }
  30. public CommandLog.CommandLog Log { get; }
  31. public OneToManyDictionary<string, Command> FilterCommands { get; }
  32. public Dictionary<string, string> FilterSearchTerm { get; }
  33. public Dictionary<string, CanExecuteEvaluator> CanExecuteEvaluators { get; }
  34. public Dictionary<string, IconEvaluator> IconEvaluators { get; }
  35. private static readonly List<Command> objectsToInvokeOn = new();
  36. public CommandController()
  37. {
  38. Current ??= this;
  39. Log = new CommandLog.CommandLog();
  40. ShortcutsPath = Path.Join(
  41. Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
  42. "PixiEditor",
  43. "shortcuts.json");
  44. shortcutFile = new(ShortcutsPath, this);
  45. FilterCommands = new();
  46. FilterSearchTerm = new();
  47. Commands = new();
  48. CommandGroups = new();
  49. CanExecuteEvaluators = new();
  50. IconEvaluators = new();
  51. }
  52. public void Import(List<Shortcut> shortcuts, bool save = true)
  53. {
  54. foreach (var shortcut in shortcuts)
  55. {
  56. foreach (var command in shortcut.Commands)
  57. {
  58. if (Commands.ContainsKey(command))
  59. {
  60. ReplaceShortcut(Commands[command], shortcut.KeyCombination);
  61. }
  62. }
  63. }
  64. if (save)
  65. {
  66. shortcutFile.SaveShortcuts();
  67. }
  68. }
  69. private static List<(string internalName, LocalizedString displayName)> FindCommandGroups(IEnumerable<Type> typesToSearchForAttributes)
  70. {
  71. List<(string internalName, LocalizedString displayName)> result = new();
  72. foreach (var type in typesToSearchForAttributes)
  73. {
  74. foreach (var group in type.GetCustomAttributes<CommandAttribute.GroupAttribute>())
  75. {
  76. result.Add((group.InternalName, group.DisplayName));
  77. }
  78. }
  79. return result;
  80. }
  81. private static void ForEachMethod
  82. (Type[] typesToSearchForMethods, IServiceProvider serviceProvider, Action<MethodInfo, object> action)
  83. {
  84. foreach (var type in typesToSearchForMethods)
  85. {
  86. object serviceInstance = serviceProvider.GetService(type);
  87. var methods = type.GetMethods();
  88. foreach (var method in methods)
  89. {
  90. action(method, serviceInstance);
  91. }
  92. }
  93. }
  94. public void Init(IServiceProvider serviceProvider)
  95. {
  96. ShortcutsTemplate template = new();
  97. try
  98. {
  99. template = shortcutFile.LoadTemplate();
  100. }
  101. catch (JsonException)
  102. {
  103. File.Move(shortcutFile.Path, $"{shortcutFile.Path}.corrupted", true);
  104. shortcutFile = new ShortcutFile(ShortcutsPath, this);
  105. template = shortcutFile.LoadTemplate();
  106. NoticeDialog.Show("SHORTCUTS_CORRUPTED", "SHORTCUTS_CORRUPTED_TITLE");
  107. }
  108. var compiledCommandList = new CommandNameList();
  109. List<(string internalName, LocalizedString displayName)> commandGroupsData = FindCommandGroups(compiledCommandList.Groups);
  110. OneToManyDictionary<string, Command> commands = new(); // internal name of the corr. group -> command in that group
  111. LoadEvaluators(serviceProvider, compiledCommandList);
  112. LoadCommands(serviceProvider, compiledCommandList, commandGroupsData, commands, template);
  113. LoadTools(serviceProvider, commandGroupsData, commands, template);
  114. var miscList = new List<Command>();
  115. foreach (var (groupInternalName, storedCommands) in commands)
  116. {
  117. var groupData = commandGroupsData.FirstOrDefault(group => group.internalName == groupInternalName);
  118. if (groupData == default || groupData.internalName == "PixiEditor.Links")
  119. {
  120. miscList.AddRange(storedCommands);
  121. continue;
  122. }
  123. LocalizedString groupDisplayName = groupData.displayName;
  124. CommandGroups.Add(new CommandGroup(groupDisplayName, storedCommands));
  125. }
  126. CommandGroups.Add(new CommandGroup("MISC", miscList));
  127. }
  128. public static void ListenForCanExecuteChanged(Command command)
  129. {
  130. objectsToInvokeOn.Add(command);
  131. }
  132. public static void StopListeningForCanExecuteChanged(Command handler)
  133. {
  134. objectsToInvokeOn.Remove(handler);
  135. }
  136. public void NotifyPropertyChanged(string? propertyName)
  137. {
  138. foreach (var evaluator in objectsToInvokeOn)
  139. {
  140. //TODO: Check if performance is better with or without this
  141. /*if (evaluator.Methods.CanExecuteEvaluator.DependentOn != null && evaluator.Methods.CanExecuteEvaluator.DependentOn.Contains(propertyName))*/
  142. {
  143. evaluator.OnCanExecuteChanged();
  144. }
  145. }
  146. }
  147. private void LoadTools(IServiceProvider serviceProvider, List<(string internalName, LocalizedString displayName)> commandGroupsData, OneToManyDictionary<string, Command> commands,
  148. ShortcutsTemplate template)
  149. {
  150. IToolsHandler toolsHandler = serviceProvider.GetService<IToolsHandler>();
  151. foreach (var toolInstance in serviceProvider.GetServices<IToolHandler>())
  152. {
  153. var type = toolInstance.GetType();
  154. if (!type.IsAssignableTo(typeof(IToolHandler)))
  155. continue;
  156. var toolAttr = type.GetCustomAttribute<CommandAttribute.ToolAttribute>();
  157. if (toolAttr is null)
  158. continue;
  159. string internalName = $"PixiEditor.Tools.Select.{type.Name}";
  160. LocalizedString displayName = new("SELECT_TOOL", toolInstance.DisplayName);
  161. var command = new Command.ToolCommand(toolsHandler)
  162. {
  163. InternalName = internalName,
  164. DisplayName = displayName,
  165. Description = displayName,
  166. IconPath = $"@{toolInstance.ImagePath}",
  167. IconEvaluator = IconEvaluator.Default,
  168. TransientKey = toolAttr.Transient,
  169. DefaultShortcut = toolAttr.GetShortcut(),
  170. Shortcut = GetShortcut(internalName, toolAttr.GetShortcut(), template),
  171. ToolType = type,
  172. };
  173. Commands.Add(command);
  174. AddCommandToCommandsCollection(command, commandGroupsData, commands);
  175. }
  176. }
  177. private KeyCombination GetShortcut(string internalName, KeyCombination defaultShortcut, ShortcutsTemplate template) =>
  178. template.Shortcuts
  179. .FirstOrDefault(x => x.Commands.Contains(internalName), new Shortcut(defaultShortcut, (List<string>)null))
  180. .KeyCombination;
  181. private void AddCommandToCommandsCollection(Command command, List<(string internalName, LocalizedString displayName)> commandGroupsData, OneToManyDictionary<string, Command> commands)
  182. {
  183. (string internalName, string displayName) group = commandGroupsData.FirstOrDefault(x => command.InternalName.StartsWith(x.internalName));
  184. if (group == default)
  185. commands.Add("", command);
  186. else
  187. commands.Add(group.internalName, command);
  188. }
  189. private void LoadCommands(IServiceProvider serviceProvider, CommandNameList compiledCommandList, List<(string internalName, LocalizedString displayName)> commandGroupsData, OneToManyDictionary<string, Command> commands, ShortcutsTemplate template)
  190. {
  191. foreach (var type in compiledCommandList.Commands)
  192. {
  193. foreach (var methodNames in type.Value)
  194. {
  195. var name = methodNames.Item1;
  196. var methodInfo = type.Key.GetMethod(name, methodNames.Item2.ToArray());
  197. var commandAttrs = methodInfo.GetCustomAttributes<CommandAttribute.CommandAttribute>();
  198. foreach (var attribute in commandAttrs)
  199. {
  200. if (attribute is CommandAttribute.BasicAttribute basic)
  201. {
  202. AddCommand(methodInfo, serviceProvider.GetService(type.Key), attribute,
  203. (isDebug, name, x, xCan, xIcon) => new Command.BasicCommand(x, xCan)
  204. {
  205. InternalName = name,
  206. IsDebug = isDebug,
  207. DisplayName = attribute.DisplayName,
  208. Description = attribute.Description,
  209. IconPath = attribute.IconPath,
  210. IconEvaluator = xIcon,
  211. DefaultShortcut = attribute.GetShortcut(),
  212. Shortcut = GetShortcut(name, attribute.GetShortcut(), template),
  213. Parameter = basic.Parameter,
  214. });
  215. }
  216. else if (attribute is CommandAttribute.FilterAttribute menu)
  217. {
  218. string searchTerm = menu.SearchTerm;
  219. if (searchTerm == null)
  220. {
  221. searchTerm = FilterSearchTerm[menu.InternalName];
  222. }
  223. else
  224. {
  225. FilterSearchTerm.Add(menu.InternalName, menu.SearchTerm);
  226. }
  227. bool hasFilter = FilterCommands.ContainsKey(searchTerm);
  228. foreach (var menuCommand in commandAttrs.Where(x => x is not CommandAttribute.FilterAttribute))
  229. {
  230. FilterCommands.Add(searchTerm, Commands[menuCommand.InternalName]);
  231. }
  232. if (hasFilter)
  233. continue;
  234. ISearchHandler searchHandler = serviceProvider.GetRequiredService<ISearchHandler>();
  235. if (searchHandler is null)
  236. continue;
  237. var command =
  238. new Command.BasicCommand(
  239. _ => searchHandler.OpenSearchWindow($":{searchTerm}:"),
  240. CanExecuteEvaluator.AlwaysTrue)
  241. {
  242. InternalName = menu.InternalName,
  243. DisplayName = menu.DisplayName,
  244. Description = menu.DisplayName,
  245. IconEvaluator = IconEvaluator.Default,
  246. DefaultShortcut = menu.GetShortcut(),
  247. Shortcut = GetShortcut(name, attribute.GetShortcut(), template)
  248. };
  249. Commands.Add(command);
  250. AddCommandToCommandsCollection(command, commandGroupsData, commands);
  251. }
  252. }
  253. }
  254. }
  255. TCommand AddCommand<TAttr, TCommand>(MethodInfo method, object instance, TAttr attribute,
  256. Func<bool, string, Action<object>, CanExecuteEvaluator, IconEvaluator, TCommand> commandFactory)
  257. where TAttr : CommandAttribute.CommandAttribute
  258. where TCommand : Command
  259. {
  260. if (method != null)
  261. {
  262. if (method.GetParameters().Length > 1)
  263. {
  264. throw new Exception(
  265. $"Too many parameters for the CanExecute evaluator '{attribute.InternalName}' at {method.ReflectedType.FullName}.{method.Name}");
  266. }
  267. else if (!method.IsStatic && instance is null)
  268. {
  269. throw new Exception(
  270. $"No type instance for the CanExecute evaluator '{attribute.InternalName}' at {method.ReflectedType.FullName}.{method.Name} found");
  271. }
  272. }
  273. var parameters = method?.GetParameters();
  274. async void ActionOnException(Task faultedTask)
  275. {
  276. // since this method is "async void" and not "async Task", the runtime will propagate exceptions out if it
  277. // (instead of putting them into the returned task and forgetting about them)
  278. await faultedTask; // this instantly throws the exception from the already faulted task
  279. }
  280. Action<object> action;
  281. if (parameters is not { Length: 1 })
  282. {
  283. action = x =>
  284. {
  285. object result = method.Invoke(instance, null);
  286. if (result is Task task)
  287. task.ContinueWith(ActionOnException, TaskContinuationOptions.OnlyOnFaulted);
  288. };
  289. }
  290. else
  291. {
  292. action = x =>
  293. {
  294. object result = method.Invoke(instance, new[] { x });
  295. if (result is Task task)
  296. task.ContinueWith(ActionOnException, TaskContinuationOptions.OnlyOnFaulted);
  297. };
  298. }
  299. string name = attribute.InternalName;
  300. bool isDebug = attribute.InternalName.StartsWith("#DEBUG#");
  301. if (attribute.InternalName.StartsWith("#DEBUG#"))
  302. {
  303. name = name["#DEBUG#".Length..];
  304. }
  305. var command = commandFactory(
  306. isDebug,
  307. name,
  308. action,
  309. attribute.CanExecute != null ? CanExecuteEvaluators[attribute.CanExecute] : CanExecuteEvaluator.AlwaysTrue,
  310. attribute.IconEvaluator != null ? IconEvaluators[attribute.IconEvaluator] : IconEvaluator.Default);
  311. Commands.Add(command);
  312. AddCommandToCommandsCollection(command, commandGroupsData, commands);
  313. return command;
  314. }
  315. }
  316. private void LoadEvaluators(IServiceProvider serviceProvider, CommandNameList compiledCommandList)
  317. {
  318. object CastParameter(object input, Type target)
  319. {
  320. if (target == typeof(object) || target == input?.GetType())
  321. return input;
  322. return Convert.ChangeType(input, target);
  323. }
  324. void AddEvaluatorFactory<TAttr, T, TParameter>(MethodInfo method, object serviceInstance, TAttr attribute,
  325. IDictionary<string, T> evaluators, Func<Func<object, TParameter>, T> factory)
  326. where T : Evaluator<TParameter>, new()
  327. where TAttr : Evaluator.EvaluatorAttribute
  328. {
  329. bool isAssignableAsync = IsAssignaleAsync<TAttr, T, TParameter>(method);
  330. if (!method.ReturnType.IsAssignableFrom(typeof(TParameter)) && !isAssignableAsync)
  331. {
  332. throw new Exception(
  333. $"Invalid return type for the CanExecute evaluator '{attribute.Name}' at {method.ReflectedType.FullName}.{method.Name}\nExpected '{typeof(TParameter).FullName}'");
  334. }
  335. else if (method.GetParameters().Length > 1)
  336. {
  337. throw new Exception(
  338. $"Too many parameters for the CanExecute evaluator '{attribute.Name}' at {method.ReflectedType.FullName}.{method.Name}");
  339. }
  340. else if (!method.IsStatic && serviceInstance is null)
  341. {
  342. throw new Exception(
  343. $"No type instance for the CanExecute evaluator '{attribute.Name}' at {method.ReflectedType.FullName}.{method.Name} found");
  344. }
  345. var parameters = method.GetParameters();
  346. if (!isAssignableAsync)
  347. {
  348. Func<object, TParameter> func;
  349. if (parameters.Length == 1)
  350. {
  351. func = x => (TParameter)method.Invoke(serviceInstance,
  352. new[] { CastParameter(x, parameters[0].ParameterType) });
  353. }
  354. else
  355. {
  356. func = x => (TParameter)method.Invoke(serviceInstance, null);
  357. }
  358. T evaluator = factory(func);
  359. evaluators.Add(evaluator.Name, evaluator);
  360. }
  361. else
  362. {
  363. Func<object, Task<TParameter>> func;
  364. if (parameters.Length == 1)
  365. {
  366. func = async x => await method.InvokeAsync<TParameter>(serviceInstance,
  367. new[] { CastParameter(x, parameters[0].ParameterType) });
  368. }
  369. else
  370. {
  371. func = async x => await method.InvokeAsync<TParameter>(serviceInstance, null);
  372. }
  373. T evaluator = factory(x => Task.Run(async () => await func(x)).Result);//TODO: This is not truly async
  374. evaluators.Add(evaluator.Name, evaluator);
  375. }
  376. }
  377. void AddEvaluator<TAttr, T, TParameter>(MethodInfo method, object instance, TAttr attribute,
  378. IDictionary<string, T> evaluators)
  379. where T : Evaluator<TParameter>, new()
  380. where TAttr : Evaluator.EvaluatorAttribute
  381. => AddEvaluatorFactory<TAttr, T, TParameter>(method, instance, attribute, evaluators,
  382. x => new T() { Name = attribute.Name, Evaluate = x });
  383. {
  384. foreach (var type in compiledCommandList.Evaluators)
  385. {
  386. foreach (var methodNames in type.Value)
  387. {
  388. var name = methodNames.Item1;
  389. var methodInfo = type.Key.GetMethod(name, methodNames.Item2.ToArray());
  390. var commandAttrs = methodInfo.GetCustomAttributes<Evaluator.EvaluatorAttribute>();
  391. foreach (var attribute in commandAttrs)
  392. {
  393. switch (attribute)
  394. {
  395. case Evaluator.CanExecuteAttribute canExecuteAttribute:
  396. {
  397. AddEvaluatorFactory<Evaluator.CanExecuteAttribute, CanExecuteEvaluator, bool>(
  398. methodInfo,
  399. serviceProvider.GetService(type.Key),
  400. canExecuteAttribute,
  401. CanExecuteEvaluators,
  402. evaluateFunction => new CanExecuteEvaluator()
  403. {
  404. Name = attribute.Name,
  405. Evaluate = evaluateFunction.Invoke,
  406. /*DependentOn = canExecuteAttribute.DependentOn*/
  407. });
  408. break;
  409. }
  410. case Evaluator.IconAttribute icon:
  411. AddEvaluator<Evaluator.IconAttribute, IconEvaluator, IImage>(methodInfo,
  412. serviceProvider.GetService(type.Key), icon, IconEvaluators);
  413. break;
  414. }
  415. }
  416. }
  417. }
  418. }
  419. }
  420. private static bool IsAssignaleAsync<TAttr, T, TParameter>(MethodInfo method) where T : Evaluator<TParameter>, new() where TAttr : Evaluator.EvaluatorAttribute
  421. {
  422. if (method.ReturnType.IsAssignableTo(typeof(Task)))
  423. {
  424. return method.ReturnType.GenericTypeArguments.Length == 0 ||
  425. method.ReturnType.GenericTypeArguments[0].IsAssignableFrom(typeof(TParameter));
  426. }
  427. return false;
  428. }
  429. /// <summary>
  430. /// Removes the old shortcut to this command and adds the new one
  431. /// </summary>
  432. public void UpdateShortcut(Command command, KeyCombination newShortcut)
  433. {
  434. Commands.RemoveShortcut(command, command.Shortcut);
  435. Commands.AddShortcut(command, newShortcut);
  436. command.Shortcut = newShortcut;
  437. shortcutFile.SaveShortcuts();
  438. }
  439. /// <summary>
  440. /// Deletes all shortcuts of <paramref name="newShortcut"/> and adds <paramref name="command"/>
  441. /// </summary>
  442. public void ReplaceShortcut(Command command, KeyCombination newShortcut)
  443. {
  444. foreach (Command other in Commands[newShortcut])
  445. {
  446. other.Shortcut = KeyCombination.None;
  447. }
  448. Commands.ClearShortcut(newShortcut);
  449. Commands.RemoveShortcut(command, command.Shortcut);
  450. Commands.AddShortcut(command, newShortcut);
  451. command.Shortcut = newShortcut;
  452. shortcutFile.SaveShortcuts();
  453. }
  454. public void ResetShortcuts()
  455. {
  456. File.Copy(ShortcutsPath, Path.ChangeExtension(ShortcutsPath, ".json.bak"), true);
  457. Commands.ClearShortcuts();
  458. foreach (var command in Commands)
  459. {
  460. Commands.RemoveShortcut(command, command.Shortcut);
  461. Commands.AddShortcut(command, command.DefaultShortcut);
  462. command.Shortcut = command.DefaultShortcut;
  463. }
  464. shortcutFile.SaveShortcuts();
  465. }
  466. }