CommandController.cs 22 KB

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