DebugViewModel.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. using System.Collections.Generic;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Threading.Tasks;
  7. using Avalonia;
  8. using Avalonia.Controls.ApplicationLifetimes;
  9. using Avalonia.Platform.Storage;
  10. using Newtonsoft.Json;
  11. using PixiEditor.AvaloniaUI.Helpers.Extensions;
  12. using PixiEditor.AvaloniaUI.Models.Commands.Attributes.Commands;
  13. using PixiEditor.AvaloniaUI.Models.Commands.Attributes.Evaluators;
  14. using PixiEditor.AvaloniaUI.Models.Commands.Templates.Providers.Parsers;
  15. using PixiEditor.AvaloniaUI.Models.Dialogs;
  16. using PixiEditor.AvaloniaUI.Views;
  17. using PixiEditor.AvaloniaUI.Views.Dialogs.Debugging;
  18. using PixiEditor.AvaloniaUI.Views.Dialogs.Debugging.Localization;
  19. using PixiEditor.Extensions.Common.Localization;
  20. using PixiEditor.Extensions.CommonApi.UserPreferences.Settings;
  21. using PixiEditor.Extensions.CommonApi.UserPreferences.Settings.PixiEditor;
  22. using PixiEditor.OperatingSystem;
  23. namespace PixiEditor.AvaloniaUI.ViewModels.SubViewModels;
  24. [Command.Group("PixiEditor.Debug", "DEBUG", IsVisibleMenuProperty = $"{nameof(ViewModelMain.DebugSubViewModel)}.{nameof(UseDebug)}")]
  25. internal class DebugViewModel : SubViewModel<ViewModelMain>
  26. {
  27. public static bool IsDebugBuild { get; set; }
  28. public bool IsDebugModeEnabled { get; set; }
  29. private bool useDebug;
  30. public bool UseDebug
  31. {
  32. get => useDebug;
  33. set => SetProperty(ref useDebug, value);
  34. }
  35. private LocalizationKeyShowMode localizationKeyShowMode;
  36. public LocalizationKeyShowMode LocalizationKeyShowMode
  37. {
  38. get => localizationKeyShowMode;
  39. set
  40. {
  41. if (SetProperty(ref localizationKeyShowMode, value))
  42. {
  43. LocalizedString.OverridenKeyFlowMode = value;
  44. Owner.LocalizationProvider.ReloadLanguage();
  45. }
  46. }
  47. }
  48. private bool forceOtherFlowDirection;
  49. public bool ForceOtherFlowDirection
  50. {
  51. get => forceOtherFlowDirection;
  52. set
  53. {
  54. if (SetProperty(ref forceOtherFlowDirection, value))
  55. {
  56. Language.FlipFlowDirection = value;
  57. Owner.LocalizationProvider.ReloadLanguage();
  58. }
  59. }
  60. }
  61. public DebugViewModel(ViewModelMain owner)
  62. : base(owner)
  63. {
  64. SetDebug();
  65. PixiEditorSettings.Debug.IsDebugModeEnabled.ValueChanged += UpdateDebugMode;
  66. UpdateDebugMode(null, PixiEditorSettings.Debug.IsDebugModeEnabled.Value);
  67. }
  68. public static void OpenFolder(string path)
  69. {
  70. if (!Directory.Exists(path))
  71. {
  72. NoticeDialog.Show(new LocalizedString("PATH_DOES_NOT_EXIST", path), "LOCATION_DOES_NOT_EXIST");
  73. return;
  74. }
  75. IOperatingSystem.Current.OpenFolder(path);
  76. }
  77. [Command.Debug("PixiEditor.Debug.IO.OpenLocalAppDataDirectory", @"PixiEditor", "OPEN_LOCAL_APPDATA_DIR", "OPEN_LOCAL_APPDATA_DIR", IconPath = "Folder.png",
  78. MenuItemPath = "DEBUG/OPEN_LOCAL_APPDATA_DIR", MenuItemOrder = 3)]
  79. [Command.Debug("PixiEditor.Debug.IO.OpenCrashReportsDirectory", @"PixiEditor\crash_logs", "OPEN_CRASH_REPORTS_DIR", "OPEN_CRASH_REPORTS_DIR", IconPath = "Folder.png",
  80. MenuItemPath = "DEBUG/OPEN_CRASH_REPORTS_DIR", MenuItemOrder = 4)]
  81. public static void OpenLocalAppDataFolder(string subDirectory)
  82. {
  83. var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), subDirectory);
  84. OpenFolder(path);
  85. }
  86. [Command.Debug("PixiEditor.Debug.IO.OpenRoamingAppDataDirectory", @"PixiEditor", "OPEN_ROAMING_APPDATA_DIR", "OPEN_ROAMING_APPDATA_DIR", IconPath = "Folder.png",
  87. MenuItemPath = "DEBUG/OPEN_ROAMING_APPDATA_DIR", MenuItemOrder = 5)]
  88. public static void OpenAppDataFolder(string subDirectory)
  89. {
  90. var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), subDirectory);
  91. OpenFolder(path);
  92. }
  93. [Command.Debug("PixiEditor.Debug.IO.OpenTempDirectory", @"PixiEditor", "OPEN_TEMP_DIR", "OPEN_TEMP_DIR", IconPath = "Folder.png",
  94. MenuItemPath = "DEBUG/OPEN_TEMP_DIR", MenuItemOrder = 6)]
  95. public static void OpenTempFolder(string subDirectory)
  96. {
  97. var path = Path.Combine(Path.GetTempPath(), subDirectory);
  98. OpenFolder(path);
  99. }
  100. [Command.Debug("PixiEditor.Debug.DumpAllCommands", "DUMP_ALL_COMMANDS", "DUMP_ALL_COMMANDS_DESCRIPTIVE")]
  101. public async Task DumpAllCommands()
  102. {
  103. await Application.Current.ForDesktopMainWindowAsync(async desktop =>
  104. {
  105. FilePickerSaveOptions options = new FilePickerSaveOptions();
  106. options.DefaultExtension = "txt";
  107. options.FileTypeChoices = new FilePickerFileType[] { new FilePickerFileType("Text") {Patterns = new [] {"*.txt"}} };
  108. var pickedFile = desktop.StorageProvider.SaveFilePickerAsync(options).Result;
  109. if (pickedFile != null)
  110. {
  111. var commands = Owner.CommandController.Commands;
  112. using StreamWriter writer = new StreamWriter(pickedFile.Path.LocalPath);
  113. foreach (var command in commands)
  114. {
  115. writer.WriteLine($"InternalName: {command.InternalName}");
  116. writer.WriteLine($"Default Shortcut: {command.DefaultShortcut}");
  117. writer.WriteLine($"IsDebug: {command.IsDebug}");
  118. writer.WriteLine();
  119. }
  120. }
  121. });
  122. }
  123. [Command.Debug("PixiEditor.Debug.GenerateKeysTemplate", "GENERATE_KEY_BINDINGS_TEMPLATE", "GENERATE_KEY_BINDINGS_TEMPLATE_DESCRIPTIVE")]
  124. public async Task GenerateKeysTemplate()
  125. {
  126. await Application.Current.ForDesktopMainWindowAsync(async desktop =>
  127. {
  128. FilePickerSaveOptions options = new FilePickerSaveOptions();
  129. options.DefaultExtension = "json";
  130. options.FileTypeChoices = new FilePickerFileType[] { new FilePickerFileType("Json") {Patterns = new [] {"*.json"}} };
  131. var pickedFile = await desktop.StorageProvider.SaveFilePickerAsync(options);
  132. if (pickedFile != null)
  133. {
  134. var commands = Owner.CommandController.Commands;
  135. using StreamWriter writer = new StreamWriter(pickedFile.Path.LocalPath);
  136. Dictionary<string, KeyDefinition> keyDefinitions = new Dictionary<string, KeyDefinition>();
  137. foreach (var command in commands)
  138. {
  139. if(command.IsDebug)
  140. continue;
  141. keyDefinitions.Add($"(provider).{command.InternalName}", new KeyDefinition(command.InternalName, new HumanReadableKeyCombination("None"), Array.Empty<string>()));
  142. }
  143. writer.Write(JsonConvert.SerializeObject(keyDefinitions, Formatting.Indented));
  144. writer.Close();
  145. string file = await File.ReadAllTextAsync(pickedFile.Path.LocalPath);
  146. foreach (var command in commands)
  147. {
  148. if(command.IsDebug)
  149. continue;
  150. file = file.Replace($"(provider).{command.InternalName}", "");
  151. }
  152. await File.WriteAllTextAsync(pickedFile.Path.LocalPath, file);
  153. IOperatingSystem.Current.OpenFolder(Path.GetDirectoryName(pickedFile.Path.LocalPath));
  154. }
  155. });
  156. }
  157. [Command.Debug("PixiEditor.Debug.ValidateShortcutMap", "VALIDATE_SHORTCUT_MAP", "VALIDATE_SHORTCUT_MAP_DESCRIPTIVE")]
  158. public async Task ValidateShortcutMap()
  159. {
  160. await Application.Current.ForDesktopMainWindowAsync(async desktop =>
  161. {
  162. FilePickerOpenOptions options = new FilePickerOpenOptions
  163. {
  164. SuggestedStartLocation =
  165. await desktop.StorageProvider.TryGetFolderFromPathAsync(
  166. Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Data",
  167. "ShortcutActionMaps")),
  168. FileTypeFilter = new FilePickerFileType[] { new FilePickerFileType("Json") {Patterns = new [] {"*.json"}} }
  169. };
  170. var pickedFile = desktop.StorageProvider.OpenFilePickerAsync(options).Result.FirstOrDefault();
  171. if (pickedFile != null)
  172. {
  173. string file = await File.ReadAllTextAsync(pickedFile.Path.LocalPath);
  174. var keyDefinitions = JsonConvert.DeserializeObject<Dictionary<string, KeyDefinition>>(file);
  175. int emptyKeys = file.Split("\"\":").Length - 1;
  176. int unknownCommands = 0;
  177. foreach (var keyDefinition in keyDefinitions)
  178. {
  179. if (!Owner.CommandController.Commands.ContainsKey(keyDefinition.Value.Command))
  180. {
  181. unknownCommands++;
  182. }
  183. }
  184. NoticeDialog.Show(new LocalizedString("VALIDATION_KEYS_NOTICE_DIALOG", emptyKeys, unknownCommands), "RESULT");
  185. }
  186. });
  187. }
  188. [Command.Debug("PixiEditor.Debug.ClearRecentDocument", "CLEAR_RECENT_DOCUMENTS", "CLEAR_RECENTLY_OPENED_DOCUMENTS",
  189. MenuItemPath = "DEBUG/DELETE/CLEAR_RECENT_DOCUMENTS")]
  190. public void ClearRecentDocuments()
  191. {
  192. Owner.FileSubViewModel.RecentlyOpened.Clear();
  193. PixiEditorSettings.File.RecentlyOpened.Value = [];
  194. }
  195. [Command.Debug("PixiEditor.Debug.OpenCommandDebugWindow", "OPEN_CMD_DEBUG_WINDOW", "OPEN_CMD_DEBUG_WINDOW",
  196. MenuItemPath = "DEBUG/OPEN_COMMAND_DEBUG_WINDOW", MenuItemOrder = 0)]
  197. public void OpenCommandDebugWindow()
  198. {
  199. new CommandDebugPopup().Show();
  200. }
  201. [Command.Debug("PixiEditor.Debug.OpenPointerDebugWindow", "Open pointer debug window", "Open pointer debug window",
  202. MenuItemPath = "DEBUG/Open pointer debug window", MenuItemOrder = 1)]
  203. public void OpenPointerDebugWindow()
  204. {
  205. new PointerDebugPopup().Show();
  206. }
  207. [Command.Debug("PixiEditor.Debug.OpenLocalizationDebugWindow", "OPEN_LOCALIZATION_DEBUG_WINDOW", "OPEN_LOCALIZATION_DEBUG_WINDOW",
  208. MenuItemPath = "DEBUG/OPEN_LOCALIZATION_DEBUG_WINDOW", MenuItemOrder = 2)]
  209. public void OpenLocalizationDebugWindow()
  210. {
  211. if (Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  212. {
  213. var window = desktop.Windows.OfType<LocalizationDebugWindow>().FirstOrDefault(new LocalizationDebugWindow());
  214. window.Show();
  215. window.Activate();
  216. }
  217. }
  218. [Command.Internal("PixiEditor.Debug.SetLanguageFromFilePicker")]
  219. public async Task SetLanguageFromFilePicker()
  220. {
  221. await Application.Current.ForDesktopMainWindowAsync(async desktop =>
  222. {
  223. FilePickerOpenOptions options = new FilePickerOpenOptions
  224. {
  225. SuggestedStartLocation =
  226. await desktop.StorageProvider.TryGetFolderFromPathAsync(
  227. Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Data",
  228. "Languages")),
  229. FileTypeFilter = new FilePickerFileType[] { new FilePickerFileType("key-value json") {Patterns = new [] {"*.json"}} }
  230. };
  231. var pickedFile = desktop.StorageProvider.OpenFilePickerAsync(options).Result.FirstOrDefault();
  232. if (pickedFile != null)
  233. {
  234. Owner.LocalizationProvider.LoadDebugKeys(
  235. JsonConvert.DeserializeObject<Dictionary<string, string>>(
  236. await File.ReadAllTextAsync(pickedFile.Path.LocalPath)),
  237. false);
  238. }
  239. });
  240. }
  241. [Command.Debug("PixiEditor.Debug.IO.OpenInstallDirectory", "OPEN_INSTALLATION_DIR", "OPEN_INSTALLATION_DIR", IconPath = "Folder.png",
  242. MenuItemPath = "DEBUG/OPEN_INSTALLATION_DIR", MenuItemOrder = 8)]
  243. public static void OpenInstallLocation()
  244. {
  245. IOperatingSystem.Current.OpenFolder(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
  246. }
  247. [Command.Debug("PixiEditor.Debug.Crash", "CRASH", "CRASH_APP",
  248. MenuItemPath = "DEBUG/CRASH", MenuItemOrder = 9)]
  249. public static void Crash() => throw new InvalidOperationException("User requested to crash :c");
  250. [Command.Debug("PixiEditor.Debug.DeleteUserPreferences", @"%appdata%\PixiEditor\user_preferences.json", "DELETE_USR_PREFS", "DELETE_USR_PREFS",
  251. MenuItemPath = "DEBUG/DELETE/USER_PREFS", MenuItemOrder = 10)]
  252. [Command.Debug("PixiEditor.Debug.DeleteShortcutFile", @"%appdata%\PixiEditor\shortcuts.json", "DELETE_SHORTCUT_FILE", "DELETE_SHORTCUT_FILE",
  253. MenuItemPath = "DEBUG/DELETE/SHORTCUT_FILE", MenuItemOrder = 11)]
  254. [Command.Debug("PixiEditor.Debug.DeleteEditorData", @"%localappdata%\PixiEditor\editor_data.json", "DELETE_EDITOR_DATA", "DELETE_EDITOR_DATA",
  255. MenuItemPath = "DEBUG/DELETE/EDITOR_DATA", MenuItemOrder = 12)]
  256. public static async Task DeleteFile(string path)
  257. {
  258. if (MainWindow.Current is null)
  259. return;
  260. string file = Environment.ExpandEnvironmentVariables(path);
  261. if (!File.Exists(file))
  262. {
  263. NoticeDialog.Show(new LocalizedString("File {0} does not exist\n(Full Path: {1})", path, file), "FILE_NOT_FOUND");
  264. return;
  265. }
  266. OptionsDialog<string> dialog = new("ARE_YOU_SURE", new LocalizedString("ARE_YOU_SURE_PATH_FULL_PATH", path, file), MainWindow.Current)
  267. {
  268. // TODO: seems like this should be localized strings
  269. { new LocalizedString("YES"), x => File.Delete(file) },
  270. new LocalizedString("CANCEL")
  271. };
  272. await dialog.ShowDialog();
  273. }
  274. [Conditional("DEBUG")]
  275. private static void SetDebug() => IsDebugBuild = true;
  276. private void UpdateDebugMode(Setting<bool> setting, bool value)
  277. {
  278. IsDebugModeEnabled = value;
  279. UseDebug = IsDebugBuild || IsDebugModeEnabled;
  280. }
  281. }