DebugViewModel.cs 14 KB

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