ViewModelMain.cs 17 KB

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