MVP_Model.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Media;
  9. using System.Windows.Media.Imaging;
  10. namespace SketchAssistantWPF
  11. {
  12. public class MVP_Model
  13. {
  14. /// <summary>
  15. /// The Presenter of the MVP-Model.
  16. /// </summary>
  17. MVP_Presenter programPresenter;
  18. /// <summary>
  19. /// History of Actions
  20. /// </summary>
  21. ActionHistory historyOfActions;
  22. /// <summary>
  23. /// The assistant responsible for the redraw mode
  24. /// </summary>
  25. //RedrawAssistant redrawAss;
  26. /*******************/
  27. /*** ENUMERATORS ***/
  28. /*******************/
  29. /***********************/
  30. /*** CLASS VARIABLES ***/
  31. /***********************/
  32. /// <summary>
  33. /// If the program is in drawing mode.
  34. /// </summary>
  35. bool inDrawingMode;
  36. /// <summary>
  37. /// If the mouse is currently pressed or not.
  38. /// </summary>
  39. bool mousePressed;
  40. /// <summary>
  41. /// Size of deletion area
  42. /// </summary>
  43. int deletionRadius = 5;
  44. /// <summary>
  45. /// Size of areas marking endpoints of lines in the redraw mode.
  46. /// </summary>
  47. int markerRadius = 10;
  48. /// <summary>
  49. /// The Position of the Cursor in the right picture box
  50. /// </summary>
  51. Point currentCursorPosition;
  52. /// <summary>
  53. /// The Previous Cursor Position in the right picture box
  54. /// </summary>
  55. Point previousCursorPosition;
  56. /// <summary>
  57. /// Queue for the cursorPositions
  58. /// </summary>
  59. Queue<Point> cursorPositions = new Queue<Point>();
  60. /// <summary>
  61. /// Lookup Matrix for checking postions of lines in the image
  62. /// </summary>
  63. bool[,] isFilledMatrix;
  64. /// <summary>
  65. /// Lookup Matrix for getting line ids at a certain postions of the image
  66. /// </summary>
  67. HashSet<int>[,] linesMatrix;
  68. /// <summary>
  69. /// List of items which will be overlayed over the right canvas.
  70. /// </summary>
  71. List<Tuple<bool, HashSet<Point>>> overlayItems;
  72. /// <summary>
  73. /// Width of the LeftImageBox.
  74. /// </summary>
  75. public int leftImageBoxWidth;
  76. /// <summary>
  77. /// Height of the LeftImageBox.
  78. /// </summary>
  79. public int leftImageBoxHeight;
  80. /// <summary>
  81. /// Width of the RightImageBox.
  82. /// </summary>
  83. public int rightImageBoxWidth;
  84. /// <summary>
  85. /// Height of the RightImageBox.
  86. /// </summary>
  87. public int rightImageBoxHeight;
  88. //Images
  89. Image leftImage;
  90. List<Line> leftLineList;
  91. Image rightImageWithoutOverlay;
  92. Image rightImageWithOverlay;
  93. List<Tuple<bool, Line>> rightLineList;
  94. List<Point> currentLine;
  95. public MVP_Model(MVP_Presenter presenter)
  96. {
  97. programPresenter = presenter;
  98. historyOfActions = new ActionHistory();
  99. //redrawAss = new RedrawAssistant();
  100. rightLineList = new List<Tuple<bool, Line>>();
  101. overlayItems = new List<Tuple<bool, HashSet<Point>>>();
  102. }
  103. /**************************/
  104. /*** INTERNAL FUNCTIONS ***/
  105. /**************************/
  106. /// <summary>
  107. /// A function that returns a white canvas for a given width and height.
  108. /// </summary>
  109. /// <param name="width">The width of the canvas in pixels</param>
  110. /// <param name="height">The height of the canvas in pixels</param>
  111. /// <returns>The new canvas</returns>
  112. private Image GetEmptyCanvas(int width, int height)
  113. {
  114. Image image;
  115. WriteableBitmap newCanvas;
  116. try
  117. {
  118. newCanvas = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null);
  119. image = new Bitmap(width, height);
  120. }
  121. catch (ArgumentException e)
  122. {
  123. programPresenter.PassMessageToView("The requested canvas size caused an error: \n"
  124. + e.ToString() + "\n The Canvas will be set to match your window.");
  125. newCanvas = new WriteableBitmap(leftImageBoxWidth, leftImageBoxHeight, 96, 96, PixelFormats.Bgra32, null);
  126. }
  127. Graphics graph = Graphics.FromImage(image);
  128. graph.FillRectangle(Brushes.White, 0, 0, width + 10, height + 10);
  129. return image;
  130. }
  131. /// <summary>
  132. /// Creates an empty Canvas on the left
  133. /// </summary>
  134. /// <param name="width"> width of the new canvas in pixels </param>
  135. /// <param name="height"> height of the new canvas in pixels </param>
  136. private void DrawEmptyCanvasLeft(int width, int height)
  137. {
  138. if (width == 0)
  139. {
  140. leftImage = GetEmptyCanvas(leftImageBoxWidth, leftImageBoxHeight);
  141. }
  142. else
  143. {
  144. leftImage = GetEmptyCanvas(width, height);
  145. }
  146. programPresenter.UpdateLeftImage(leftImage);
  147. }
  148. /// <summary>
  149. /// Redraws all lines in rightLineList, for which their associated boolean value equals true and calls RedrawRightOverlay.
  150. /// </summary>
  151. private void RedrawRightImage()
  152. {
  153. var workingCanvas = GetEmptyCanvas(rightImageWithoutOverlay.Width, rightImageWithoutOverlay.Height);
  154. var workingGraph = Graphics.FromImage(workingCanvas);
  155. //Lines
  156. foreach (Tuple<bool, Line> lineBoolTuple in rightLineList)
  157. {
  158. if (lineBoolTuple.Item1)
  159. {
  160. lineBoolTuple.Item2.DrawLine(workingGraph);
  161. }
  162. }
  163. //The Line being currently drawn
  164. if (currentLine != null && currentLine.Count > 0 && inDrawingMode && mousePressed)
  165. {
  166. var currLine = new Line(currentLine);
  167. currLine.DrawLine(workingGraph);
  168. }
  169. rightImageWithoutOverlay = workingCanvas;
  170. //Redraw the Overlay if needed
  171. if (leftImage != null)
  172. {
  173. RedrawRightOverlay();
  174. }
  175. else
  176. {
  177. programPresenter.UpdateRightImage(rightImageWithoutOverlay);
  178. }
  179. }
  180. /// <summary>
  181. /// Redraws all elements in the overlay items for which the respective boolean value is true.
  182. /// </summary>
  183. private void RedrawRightOverlay()
  184. {
  185. var workingCanvas = rightImageWithoutOverlay;
  186. var workingGraph = Graphics.FromImage(workingCanvas);
  187. foreach (Tuple<bool, HashSet<Point>> tup in overlayItems)
  188. {
  189. if (tup.Item1)
  190. {
  191. foreach (Point p in tup.Item2)
  192. {
  193. workingGraph.FillRectangle(Brushes.Green, p.X, p.Y, 1, 1);
  194. }
  195. }
  196. }
  197. rightImageWithOverlay = workingCanvas;
  198. programPresenter.UpdateRightImage(rightImageWithOverlay);
  199. }
  200. /// <summary>
  201. /// Change the status of whether or not the lines are shown.
  202. /// </summary>
  203. /// <param name="lines">The HashSet containing the affected Line IDs.</param>
  204. /// <param name="shown">True if the lines should be shown, false if they should be hidden.</param>
  205. private void ChangeLines(HashSet<int> lines, bool shown)
  206. {
  207. var changed = false;
  208. foreach (int lineId in lines)
  209. {
  210. if (lineId <= rightLineList.Count - 1 && lineId >= 0)
  211. {
  212. rightLineList[lineId] = new Tuple<bool, Line>(shown, rightLineList[lineId].Item2);
  213. changed = true;
  214. }
  215. }
  216. if (changed) { RedrawRightImage(); }
  217. }
  218. /// <summary>
  219. /// A function that populates the matrixes needed for deletion detection with line data.
  220. /// </summary>
  221. private void RepopulateDeletionMatrixes()
  222. {
  223. if (rightImageWithoutOverlay != null)
  224. {
  225. isFilledMatrix = new bool[rightImageWithoutOverlay.Width, rightImageWithoutOverlay.Height];
  226. linesMatrix = new HashSet<int>[rightImageWithoutOverlay.Width, rightImageWithoutOverlay.Height];
  227. foreach (Tuple<bool, Line> lineTuple in rightLineList)
  228. {
  229. if (lineTuple.Item1)
  230. {
  231. lineTuple.Item2.PopulateMatrixes(isFilledMatrix, linesMatrix);
  232. }
  233. }
  234. }
  235. }
  236. /// <summary>
  237. /// A function that checks the deletion matrixes at a certain point
  238. /// and returns all Line ids at that point and in a square around it in a certain range.
  239. /// </summary>
  240. /// <param name="p">The point around which to check.</param>
  241. /// <param name="range">The range around the point. If range is 0, only the point is checked.</param>
  242. /// <returns>A List of all lines.</returns>
  243. private HashSet<int> CheckDeletionMatrixesAroundPoint(Point p, int range)
  244. {
  245. HashSet<int> returnSet = new HashSet<int>();
  246. foreach (Point pnt in GeometryCalculator.FilledCircleAlgorithm(p, (int)range))
  247. {
  248. if (pnt.X >= 0 && pnt.Y >= 0 && pnt.X < rightImageWithoutOverlay.Width && pnt.Y < rightImageWithoutOverlay.Height)
  249. {
  250. if (isFilledMatrix[pnt.X, pnt.Y])
  251. {
  252. returnSet.UnionWith(linesMatrix[pnt.X, pnt.Y]);
  253. }
  254. }
  255. }
  256. return returnSet;
  257. }
  258. /*
  259. /// <summary>
  260. /// Will calculate the start and endpoints of the given line on the right canvas.
  261. /// </summary>
  262. /// <param name="line">The line.</param>
  263. /// <param name="size">The size of the circle with which the endpoints of the line are marked.</param>
  264. private Tuple<HashSet<Point>, HashSet<Point>> CalculateStartAndEnd(Line line, int size)
  265. {
  266. var circle0 = GeometryCalculator.FilledCircleAlgorithm(line.GetStartPoint(), size);
  267. var circle1 = GeometryCalculator.FilledCircleAlgorithm(line.GetEndPoint(), size);
  268. var currentLineEndings = new Tuple<HashSet<Point>, HashSet<Point>>(circle0, circle1);
  269. return currentLineEndings;
  270. }
  271. */
  272. /// <summary>
  273. /// Tells the Presenter to Update the UI
  274. /// </summary>
  275. private void UpdateUI()
  276. {
  277. programPresenter.UpdateUIState(inDrawingMode, historyOfActions.CanUndo(), historyOfActions.CanRedo(), (rightImageWithoutOverlay != null));
  278. }
  279. /********************************************/
  280. /*** FUNCTIONS TO INTERACT WITH PRESENTER ***/
  281. /********************************************/
  282. /// <summary>
  283. /// Creates an empty Canvas
  284. /// </summary>
  285. public void DrawEmptyCanvasRight()
  286. {
  287. if (leftImage == null)
  288. {
  289. rightImageWithoutOverlay = GetEmptyCanvas(leftImageBoxWidth, leftImageBoxHeight);
  290. }
  291. else
  292. {
  293. rightImageWithoutOverlay = GetEmptyCanvas(leftImage.Width, leftImage.Height);
  294. }
  295. RepopulateDeletionMatrixes();
  296. rightImageWithOverlay = rightImageWithoutOverlay;
  297. programPresenter.UpdateRightImage(rightImageWithOverlay);
  298. }
  299. /// <summary>
  300. /// The function to set the left image.
  301. /// </summary>
  302. /// <param name="width">The width of the left image.</param>
  303. /// <param name="height">The height of the left image.</param>
  304. /// <param name="listOfLines">The List of Lines to be displayed in the left image.</param>
  305. public void SetLeftLineList(int width, int height, List<Line> listOfLines)
  306. {
  307. var workingCanvas = GetEmptyCanvas(width, height);
  308. var workingGraph = Graphics.FromImage(workingCanvas);
  309. leftLineList = listOfLines;
  310. //redrawAss = new RedrawAssistant(leftLineList);
  311. //overlayItems = redrawAss.Initialize(markerRadius);
  312. //Lines
  313. foreach (Line line in leftLineList)
  314. {
  315. line.DrawLine(workingGraph);
  316. }
  317. leftImage = workingCanvas;
  318. programPresenter.UpdateLeftImage(leftImage);
  319. //Set right image to same size as left image and delete linelist
  320. DrawEmptyCanvasRight();
  321. rightLineList = new List<Tuple<bool, Line>>();
  322. }
  323. /// <summary>
  324. /// Will undo the last action taken, if the action history allows it.
  325. /// </summary>
  326. public void Undo()
  327. {
  328. if (historyOfActions.CanUndo())
  329. {
  330. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  331. SketchAction.ActionType undoAction = historyOfActions.GetCurrentAction().GetActionType();
  332. switch (undoAction)
  333. {
  334. case SketchAction.ActionType.Delete:
  335. //Deleted Lines need to be shown
  336. ChangeLines(affectedLines, true);
  337. break;
  338. case SketchAction.ActionType.Draw:
  339. //Drawn lines need to be hidden
  340. ChangeLines(affectedLines, false);
  341. break;
  342. default:
  343. break;
  344. }
  345. if (leftImage != null)
  346. {
  347. //overlayItems = redrawAss.Tick(currentCursorPosition, rightLineList, -1, false);
  348. }
  349. RedrawRightImage();
  350. }
  351. RepopulateDeletionMatrixes();
  352. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(true));
  353. UpdateUI();
  354. }
  355. /// <summary>
  356. /// Will redo the last action undone, if the action history allows it.
  357. /// </summary>
  358. public void Redo()
  359. {
  360. if (historyOfActions.CanRedo())
  361. {
  362. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(false));
  363. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  364. SketchAction.ActionType redoAction = historyOfActions.GetCurrentAction().GetActionType();
  365. switch (redoAction)
  366. {
  367. case SketchAction.ActionType.Delete:
  368. //Deleted Lines need to be redeleted
  369. ChangeLines(affectedLines, false);
  370. break;
  371. case SketchAction.ActionType.Draw:
  372. //Drawn lines need to be redrawn
  373. ChangeLines(affectedLines, true);
  374. break;
  375. default:
  376. break;
  377. }
  378. if (leftImage != null)
  379. {
  380. //overlayItems = redrawAss.Tick(currentCursorPosition, rightLineList, -1, false);
  381. }
  382. RedrawRightImage();
  383. RepopulateDeletionMatrixes();
  384. }
  385. UpdateUI();
  386. }
  387. /// <summary>
  388. /// The function called by the Presenter to change the drawing state of the program.
  389. /// </summary>
  390. /// <param name="nowDrawing">The new drawingstate of the program</param>
  391. public void ChangeState(bool nowDrawing)
  392. {
  393. inDrawingMode = nowDrawing;
  394. UpdateUI();
  395. }
  396. /// <summary>
  397. /// A method to get the dimensions of the right image.
  398. /// </summary>
  399. /// <returns>A tuple containing the width and height of the right image.</returns>
  400. public Tuple<int, int> GetRightImageDimensions()
  401. {
  402. if (rightImageWithoutOverlay != null)
  403. {
  404. return new Tuple<int, int>(rightImageWithoutOverlay.Width, rightImageWithoutOverlay.Height);
  405. }
  406. else
  407. {
  408. return new Tuple<int, int>(0, 0);
  409. }
  410. }
  411. /// <summary>
  412. /// Updates the current cursor position of the model.
  413. /// </summary>
  414. /// <param name="p">The new cursor position</param>
  415. public void SetCurrentCursorPosition(Point p)
  416. {
  417. currentCursorPosition = p;
  418. }
  419. /// <summary>
  420. /// Start a new Line, when the Mouse is pressed down.
  421. /// </summary>
  422. public void MouseDown()
  423. {
  424. mousePressed = true;
  425. if (inDrawingMode)
  426. {
  427. currentLine = new List<Point>();
  428. }
  429. }
  430. /// <summary>
  431. /// Finish the current Line, when the pressed Mouse is released.
  432. /// </summary>
  433. public void MouseUp()
  434. {
  435. mousePressed = false;
  436. if (inDrawingMode && currentLine.Count > 0)
  437. {
  438. Line newLine = new Line(currentLine, rightLineList.Count);
  439. rightLineList.Add(new Tuple<bool, Line>(true, newLine));
  440. newLine.PopulateMatrixes(isFilledMatrix, linesMatrix);
  441. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Draw, newLine.GetID())));
  442. if (leftImage != null)
  443. {
  444. //Execute a RedrawAssistant tick with the currently finished Line
  445. //overlayItems = redrawAss.Tick(currentCursorPosition, rightLineList, newLine.GetID(), true);
  446. }
  447. RedrawRightImage();
  448. }
  449. UpdateUI();
  450. }
  451. /// <summary>
  452. /// Method to be called every tick. Updates the current Line, or checks for Lines to delete, depending on the drawing mode.
  453. /// </summary>
  454. public void Tick()
  455. {
  456. if (cursorPositions.Count > 0) { previousCursorPosition = cursorPositions.Dequeue(); }
  457. else { previousCursorPosition = currentCursorPosition; }
  458. cursorPositions.Enqueue(currentCursorPosition);
  459. //Drawing
  460. if (inDrawingMode && mousePressed)
  461. {
  462. var rightGraph = Graphics.FromImage(rightImageWithoutOverlay);
  463. currentLine.Add(currentCursorPosition);
  464. Line drawline = new Line(currentLine);
  465. drawline.DrawLine(rightGraph);
  466. RedrawRightOverlay();
  467. }
  468. //Deleting
  469. if (!inDrawingMode && mousePressed)
  470. {
  471. List<Point> uncheckedPoints = GeometryCalculator.BresenhamLineAlgorithm(previousCursorPosition, currentCursorPosition);
  472. foreach (Point currPoint in uncheckedPoints)
  473. {
  474. HashSet<int> linesToDelete = CheckDeletionMatrixesAroundPoint(currPoint, deletionRadius);
  475. if (linesToDelete.Count > 0)
  476. {
  477. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Delete, linesToDelete)));
  478. foreach (int lineID in linesToDelete)
  479. {
  480. rightLineList[lineID] = new Tuple<bool, Line>(false, rightLineList[lineID].Item2);
  481. }
  482. RepopulateDeletionMatrixes();
  483. if (leftImage != null)
  484. {
  485. //Redraw overlay gets ticked
  486. //overlayItems = redrawAss.Tick(currentCursorPosition, rightLineList, -1, false);
  487. }
  488. RedrawRightImage();
  489. }
  490. }
  491. }
  492. }
  493. /// <summary>
  494. /// A helper Function that updates the markerRadius & deletionRadius, considering the size of the canvas.
  495. /// </summary>
  496. public void UpdateSizes()
  497. {
  498. if (rightImageWithoutOverlay != null)
  499. {
  500. int widthImage = rightImageWithoutOverlay.Width;
  501. int heightImage = rightImageWithoutOverlay.Height;
  502. int widthBox = rightImageBoxWidth;
  503. int heightBox = rightImageBoxHeight;
  504. float imageRatio = (float)widthImage / (float)heightImage;
  505. float containerRatio = (float)widthBox / (float)heightBox;
  506. float zoomFactor = 0;
  507. if (imageRatio >= containerRatio)
  508. {
  509. //Image is wider than it is high
  510. zoomFactor = (float)widthImage / (float)widthBox;
  511. }
  512. else
  513. {
  514. //Image is higher than it is wide
  515. zoomFactor = (float)heightImage / (float)heightBox;
  516. }
  517. markerRadius = (int)(10 * zoomFactor);
  518. redrawAss.SetMarkerRadius(markerRadius);
  519. deletionRadius = (int)(5 * zoomFactor);
  520. }
  521. }
  522. /// <summary>
  523. /// If there is unsaved progress.
  524. /// </summary>
  525. /// <returns>True if there is progress that has not been saved.</returns>
  526. public bool HasUnsavedProgress()
  527. {
  528. return !historyOfActions.IsEmpty();
  529. }
  530. }
  531. }