ViewModelMain.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Windows;
  7. using System.Windows.Input;
  8. using System.Windows.Threading;
  9. using Microsoft.Extensions.DependencyInjection;
  10. using PixiEditor.Helpers;
  11. using PixiEditor.Models.Controllers;
  12. using PixiEditor.Models.Controllers.Shortcuts;
  13. using PixiEditor.Models.DataHolders;
  14. using PixiEditor.Models.Dialogs;
  15. using PixiEditor.Models.Enums;
  16. using PixiEditor.Models.Events;
  17. using PixiEditor.Models.Position;
  18. using PixiEditor.Models.Tools;
  19. using PixiEditor.Models.Tools.Tools;
  20. using PixiEditor.Models.UserPreferences;
  21. using PixiEditor.ViewModels.SubViewModels.Main;
  22. using PixiEditor.Views.Dialogs;
  23. using SkiaSharp;
  24. namespace PixiEditor.ViewModels
  25. {
  26. public class ViewModelMain : ViewModelBase
  27. {
  28. private string actionDisplay;
  29. private bool overrideActionDisplay;
  30. public static ViewModelMain Current { get; set; }
  31. public IServiceProvider Services { get; private set; }
  32. public Action CloseAction { get; set; }
  33. public event EventHandler OnStartupEvent;
  34. public RelayCommand OnStartupCommand { get; set; }
  35. public RelayCommand CloseWindowCommand { get; set; }
  36. public FileViewModel FileSubViewModel { get; set; }
  37. public UpdateViewModel UpdateSubViewModel { get; set; }
  38. public ToolsViewModel ToolsSubViewModel { get; set; }
  39. public IoViewModel IoSubViewModel { get; set; }
  40. public LayersViewModel LayersSubViewModel { get; set; }
  41. public ClipboardViewModel ClipboardSubViewModel { get; set; }
  42. public UndoViewModel UndoSubViewModel { get; set; }
  43. public SelectionViewModel SelectionSubViewModel { get; set; }
  44. public ViewportViewModel ViewportSubViewModel { get; set; }
  45. public ColorsViewModel ColorsSubViewModel { get; set; }
  46. public DocumentViewModel DocumentSubViewModel { get; set; }
  47. public MiscViewModel MiscSubViewModel { get; set; }
  48. public DiscordViewModel DiscordViewModel { get; set; }
  49. public DebugViewModel DebugSubViewModel { get; set; }
  50. public BitmapManager BitmapManager { get; set; }
  51. public ShortcutController ShortcutController { get; set; }
  52. public StylusViewModel StylusSubViewModel { get; set; }
  53. public WindowViewModel WindowSubViewModel { get; set; }
  54. public RegistryViewModel RegistrySubViewModel { get; set; }
  55. public IPreferences Preferences { get; set; }
  56. public string ActionDisplay
  57. {
  58. get
  59. {
  60. if (OverrideActionDisplay)
  61. {
  62. return actionDisplay;
  63. }
  64. return ToolsSubViewModel.ActiveTool.ActionDisplay;
  65. }
  66. set
  67. {
  68. actionDisplay = value;
  69. }
  70. }
  71. /// <summary>
  72. /// Gets or sets a value indicating whether a custom action display should be used. If false the action display of the selected tool will be used.
  73. /// </summary>
  74. public bool OverrideActionDisplay
  75. {
  76. get => overrideActionDisplay;
  77. set
  78. {
  79. SetProperty(ref overrideActionDisplay, value);
  80. RaisePropertyChanged(nameof(ActionDisplay));
  81. }
  82. }
  83. public bool IsDebug
  84. {
  85. get =>
  86. #if DEBUG
  87. true;
  88. #else
  89. false;
  90. #endif
  91. }
  92. public ViewModelMain(IServiceProvider serviceProvider)
  93. {
  94. Current = this;
  95. }
  96. public void Setup(IServiceProvider services)
  97. {
  98. Services = services;
  99. Preferences = services.GetRequiredService<IPreferences>();
  100. Preferences.Init();
  101. BitmapManager = services.GetRequiredService<BitmapManager>();
  102. BitmapManager.BitmapOperations.BitmapChanged += BitmapUtility_BitmapChanged;
  103. BitmapManager.DocumentChanged += BitmapManager_DocumentChanged;
  104. SelectionSubViewModel = services.GetService<SelectionViewModel>();
  105. OnStartupCommand = new RelayCommand(OnStartup);
  106. CloseWindowCommand = new RelayCommand(CloseWindow);
  107. FileSubViewModel = services.GetService<FileViewModel>();
  108. ToolsSubViewModel = services.GetService<ToolsViewModel>();
  109. ToolsSubViewModel.SelectedToolChanged += BitmapManager_SelectedToolChanged;
  110. IoSubViewModel = services.GetService<IoViewModel>();
  111. LayersSubViewModel = services.GetService<LayersViewModel>();
  112. ClipboardSubViewModel = services.GetService<ClipboardViewModel>();
  113. UndoSubViewModel = services.GetService<UndoViewModel>();
  114. ViewportSubViewModel = services.GetService<ViewportViewModel>();
  115. ColorsSubViewModel = services.GetService<ColorsViewModel>();
  116. ColorsSubViewModel?.SetupPaletteParsers(services);
  117. ToolsSubViewModel?.SetupTools(services);
  118. DocumentSubViewModel = services.GetService<DocumentViewModel>();
  119. DiscordViewModel = services.GetService<DiscordViewModel>();
  120. UpdateSubViewModel = services.GetService<UpdateViewModel>();
  121. WindowSubViewModel = services.GetService<WindowViewModel>();
  122. StylusSubViewModel = services.GetService<StylusViewModel>();
  123. RegistrySubViewModel = services.GetService<RegistryViewModel>();
  124. AddDebugOnlyViewModels();
  125. AddReleaseOnlyViewModels();
  126. ShortcutController = new ShortcutController(
  127. new ShortcutGroup(
  128. "Tools",
  129. CreateToolShortcut<PenTool>(Key.B, "Pen"),
  130. CreateToolShortcut<EraserTool>(Key.E, "Eraser"),
  131. CreateToolShortcut<ColorPickerTool>(Key.O, "Color picker"),
  132. CreateToolShortcut<RectangleTool>(Key.R, "Rectangle"),
  133. CreateToolShortcut<CircleTool>(Key.C, "Ellipse"),
  134. CreateToolShortcut<LineTool>(Key.L, "Line"),
  135. CreateToolShortcut<FloodFillTool>(Key.G, "Flood fill"),
  136. CreateToolShortcut<BrightnessTool>(Key.U, "Brightness"),
  137. CreateToolShortcut<MoveTool>(Key.V, "Move selection"),
  138. CreateToolShortcut<SelectTool>(Key.M, "Select"),
  139. CreateToolShortcut<ZoomTool>(Key.Z, "Zoom"),
  140. CreateToolShortcut<MoveViewportTool>(Key.H, "Move viewport"),
  141. CreateToolShortcut<MagicWandTool>(Key.W, "Magic wand"),
  142. new Shortcut(Key.OemPlus, ViewportSubViewModel.ZoomCommand, "Zoom in", 1),
  143. new Shortcut(Key.OemMinus, ViewportSubViewModel.ZoomCommand, "Zoom out", -1),
  144. new Shortcut(Key.OemOpenBrackets, ToolsSubViewModel.ChangeToolSizeCommand, "Decrease tool size", -1),
  145. new Shortcut(Key.OemCloseBrackets, ToolsSubViewModel.ChangeToolSizeCommand, "Increase tool size", 1)),
  146. new ShortcutGroup(
  147. "Editor",
  148. new Shortcut(Key.X, ColorsSubViewModel.SwapColorsCommand, "Swap primary and secondary colors"),
  149. new Shortcut(Key.Y, UndoSubViewModel.RedoCommand, "Redo", modifier: ModifierKeys.Control),
  150. new Shortcut(Key.Z, UndoSubViewModel.UndoCommand, "Undo", modifier: ModifierKeys.Control),
  151. new Shortcut(Key.D, SelectionSubViewModel.DeselectCommand, "Clear selection", modifier: ModifierKeys.Control),
  152. new Shortcut(Key.A, SelectionSubViewModel.SelectAllCommand, "Select all", modifier: ModifierKeys.Control),
  153. new Shortcut(Key.C, ClipboardSubViewModel.CopyCommand, "Copy", modifier: ModifierKeys.Control),
  154. new Shortcut(Key.V, ClipboardSubViewModel.PasteCommand, "Paste", modifier: ModifierKeys.Control),
  155. new Shortcut(Key.J, ClipboardSubViewModel.DuplicateCommand, "Duplicate", modifier: ModifierKeys.Control),
  156. new Shortcut(Key.X, ClipboardSubViewModel.CutCommand, "Cut", modifier: ModifierKeys.Control),
  157. new Shortcut(Key.Delete, DocumentSubViewModel.DeletePixelsCommand, "Clear selected area"),
  158. new Shortcut(Key.I, DocumentSubViewModel.OpenResizePopupCommand, "Resize image", modifier: ModifierKeys.Control | ModifierKeys.Shift),
  159. new Shortcut(Key.C, DocumentSubViewModel.OpenResizePopupCommand, "Resize canvas", "canvas", ModifierKeys.Control | ModifierKeys.Shift),
  160. new Shortcut(Key.F11, SystemCommands.MaximizeWindowCommand, "Maximize window")),
  161. new ShortcutGroup(
  162. "File",
  163. new Shortcut(Key.O, FileSubViewModel.OpenFileCommand, "Open image", modifier: ModifierKeys.Control),
  164. new Shortcut(Key.S, FileSubViewModel.ExportFileCommand, "Export image", modifier: ModifierKeys.Control | ModifierKeys.Shift | ModifierKeys.Alt),
  165. new Shortcut(Key.S, FileSubViewModel.SaveDocumentCommand, "Save", modifier: ModifierKeys.Control),
  166. new Shortcut(Key.S, FileSubViewModel.SaveDocumentCommand, "Save as new", "AsNew", ModifierKeys.Control | ModifierKeys.Shift),
  167. new Shortcut(Key.N, FileSubViewModel.OpenNewFilePopupCommand, "Create new image", modifier: ModifierKeys.Control)),
  168. new ShortcutGroup(
  169. "Layers",
  170. new Shortcut(Key.F2, LayersSubViewModel.RenameLayerCommand, "Rename active layer", BitmapManager.ActiveDocument?.ActiveLayerGuid)),
  171. new ShortcutGroup(
  172. "View",
  173. new Shortcut(Key.OemTilde, ViewportSubViewModel.ToggleGridLinesCommand, "Toggle gridlines", modifier: ModifierKeys.Control)));
  174. Shortcut[] colorShortcuts = new Shortcut[10];
  175. colorShortcuts[9] = new Shortcut(
  176. Key.D0, ColorsSubViewModel.SelectPaletteColorCommand, 9);
  177. for (int i = 0; i < colorShortcuts.Length - 1; i++)
  178. {
  179. //35 is a D1 key integer value
  180. colorShortcuts[i] = new Shortcut((Key)35 + i, ColorsSubViewModel.SelectPaletteColorCommand, i);
  181. }
  182. ShortcutController.ShortcutGroups.Add(new ShortcutGroup("Palette Colors", colorShortcuts));
  183. MiscSubViewModel = services.GetService<MiscViewModel>();
  184. // Add F1 shortcut after MiscSubViewModel is constructed
  185. ShortcutController.ShortcutGroups.Add(
  186. new ShortcutGroup(
  187. "Misc",
  188. new Shortcut(Key.F1, MiscSubViewModel.OpenShortcutWindowCommand, "Open shortcuts window", true)));
  189. ShortcutController.TransientShortcuts[Key.Space] = ToolsSubViewModel.ToolSet.First(x => x is MoveViewportTool);
  190. ShortcutController.TransientShortcuts[Key.LeftAlt] = ToolsSubViewModel.ToolSet.First(x => x is ColorPickerTool);
  191. BitmapManager.PrimaryColor = ColorsSubViewModel.PrimaryColor;
  192. ToolsSubViewModel?.SetupToolsTooltipShortcuts(services);
  193. }
  194. /// <summary>
  195. /// Resets most variables and controller, so new documents can be handled.
  196. /// </summary>
  197. public void ResetProgramStateValues()
  198. {
  199. foreach (var document in BitmapManager.Documents)
  200. {
  201. document.PreviewLayer.Reset();
  202. }
  203. }
  204. public bool DocumentIsNotNull(object property)
  205. {
  206. return BitmapManager.ActiveDocument != null;
  207. }
  208. public bool DocumentIsNotNull((SKColor oldColor, SKColor newColor) obj)
  209. {
  210. return DocumentIsNotNull(null);
  211. }
  212. public void CloseWindow(object property)
  213. {
  214. if (!(property is CancelEventArgs))
  215. {
  216. throw new ArgumentException();
  217. }
  218. ((CancelEventArgs)property).Cancel = !RemoveDocumentsWithSaveConfirmation();
  219. }
  220. private void BitmapManager_SelectedToolChanged(object sender, SelectedToolEventArgs e)
  221. {
  222. if (e.OldTool != null)
  223. e.OldTool.PropertyChanged -= SelectedTool_PropertyChanged;
  224. e.NewTool.PropertyChanged += SelectedTool_PropertyChanged;
  225. NotifyToolActionDisplayChanged();
  226. BitmapManager.InputTarget.OnToolChange(e.NewTool);
  227. }
  228. private void SelectedTool_PropertyChanged(object sender, PropertyChangedEventArgs e)
  229. {
  230. if (e.PropertyName == nameof(Tool.ActionDisplay))
  231. {
  232. NotifyToolActionDisplayChanged();
  233. }
  234. }
  235. private void NotifyToolActionDisplayChanged()
  236. {
  237. if (!OverrideActionDisplay) RaisePropertyChanged(nameof(ActionDisplay));
  238. }
  239. [Conditional("DEBUG")]
  240. private void AddDebugOnlyViewModels()
  241. {
  242. DebugSubViewModel = new DebugViewModel(this);
  243. }
  244. [Conditional("RELEASE")]
  245. private void AddReleaseOnlyViewModels()
  246. {
  247. }
  248. private Shortcut CreateToolShortcut<T>(Key key, ModifierKeys modifier = ModifierKeys.None)
  249. where T : Tool
  250. {
  251. return new Shortcut(key, ToolsSubViewModel.SelectToolCommand, typeof(T), modifier);
  252. }
  253. private Shortcut CreateToolShortcut<T>(Key key, string description, ModifierKeys modifier = ModifierKeys.None)
  254. where T : Tool
  255. {
  256. return new Shortcut(key, ToolsSubViewModel.SelectToolCommand, description, typeof(T), modifier);
  257. }
  258. /// <summary>
  259. /// Removes documents with unsaved changes confirmation dialog.
  260. /// </summary>
  261. /// <returns>If documents was removed successfully.</returns>
  262. private bool RemoveDocumentsWithSaveConfirmation()
  263. {
  264. int docCount = BitmapManager.Documents.Count;
  265. for (int i = 0; i < docCount; i++)
  266. {
  267. BitmapManager.ActiveDocument = BitmapManager.Documents.First();
  268. bool canceled = !RemoveDocumentWithSaveConfirmation();
  269. if (canceled)
  270. {
  271. return false;
  272. }
  273. }
  274. return true;
  275. }
  276. /// <summary>
  277. /// Removes document with unsaved changes confirmation dialog.
  278. /// </summary>
  279. /// <returns>If document was removed successfully.</returns>
  280. private bool RemoveDocumentWithSaveConfirmation()
  281. {
  282. ConfirmationType result = ConfirmationType.No;
  283. if (!BitmapManager.ActiveDocument.ChangesSaved)
  284. {
  285. result = ConfirmationDialog.Show(DocumentViewModel.ConfirmationDialogMessage, DocumentViewModel.ConfirmationDialogTitle);
  286. if (result == ConfirmationType.Yes)
  287. {
  288. FileSubViewModel.SaveDocument(false);
  289. //cancel was pressed in the save file dialog
  290. if (!BitmapManager.ActiveDocument.ChangesSaved)
  291. return false;
  292. }
  293. }
  294. if (result != ConfirmationType.Canceled)
  295. {
  296. var doc = BitmapManager.ActiveDocument;
  297. BitmapManager.Documents.Remove(doc);
  298. doc.Dispose();
  299. return true;
  300. }
  301. else
  302. {
  303. return false;
  304. }
  305. }
  306. private void OnStartup(object parameter)
  307. {
  308. OnStartupEvent?.Invoke(this, EventArgs.Empty);
  309. }
  310. private void BitmapManager_DocumentChanged(object sender, DocumentChangedEventArgs e)
  311. {
  312. if (e.NewDocument != null)
  313. {
  314. e.NewDocument.DocumentSizeChanged += ActiveDocument_DocumentSizeChanged;
  315. }
  316. }
  317. private void ActiveDocument_DocumentSizeChanged(object sender, DocumentSizeChangedEventArgs e)
  318. {
  319. BitmapManager.ActiveDocument.ActiveSelection = new Selection(Array.Empty<Coordinates>(), new PixelSize(e.NewWidth, e.NewHeight));
  320. BitmapManager.ActiveDocument.ChangesSaved = false;
  321. BitmapManager.ActiveDocument.CenterViewportTrigger.Execute(this, new Size(BitmapManager.ActiveDocument.Width, BitmapManager.ActiveDocument.Height));
  322. }
  323. private void BitmapUtility_BitmapChanged(object sender, EventArgs e)
  324. {
  325. BitmapManager.ActiveDocument.ChangesSaved = false;
  326. if (ToolsSubViewModel.ActiveTool is BitmapOperationTool)
  327. {
  328. ColorsSubViewModel.AddSwatch(ColorsSubViewModel.PrimaryColor);
  329. }
  330. }
  331. }
  332. }