MVP_Model.cs 21 KB

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