MVP_Model.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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. /// binds the given picture to templatePicture and draws it
  256. /// </summary>
  257. /// <param name="newTemplatePicture"> the new template picture, represented as a list of polylines </param>
  258. /// <returns></returns>
  259. private void BindAndDrawLeftImage(List<Line> newTemplatePicture)
  260. {
  261. leftLineList = newTemplatePicture;
  262. foreach (Line l in leftLineList)
  263. {
  264. l.DrawLine(Graphics.FromImage(leftImage));
  265. }
  266. }
  267. /// <summary>
  268. /// Will calculate the start and endpoints of the given line on the right canvas.
  269. /// </summary>
  270. /// <param name="line">The line.</param>
  271. /// <param name="size">The size of the circle with which the endpoints of the line are marked.</param>
  272. private Tuple<HashSet<Point>, HashSet<Point>> CalculateStartAndEnd(Line line, int size)
  273. {
  274. var circle0 = GeometryCalculator.FilledCircleAlgorithm(line.GetStartPoint(), size);
  275. var circle1 = GeometryCalculator.FilledCircleAlgorithm(line.GetEndPoint(), size);
  276. var currentLineEndings = new Tuple<HashSet<Point>, HashSet<Point>>(circle0, circle1);
  277. return currentLineEndings;
  278. }
  279. */
  280. /// <summary>
  281. /// Tells the Presenter to Update the UI
  282. /// </summary>
  283. private void UpdateUI()
  284. {
  285. programPresenter.UpdateUIState(inDrawingMode, historyOfActions.CanUndo(), historyOfActions.CanRedo(), (rightImageWithoutOverlay != null));
  286. }
  287. /*
  288. /// <summary>
  289. /// Checks if there is unsaved progess, and warns the user. Returns True if it safe to continue.
  290. /// </summary>
  291. /// <returns>true if there is none, or the user wishes to continue without saving.
  292. /// false if there is progress, and the user doesn't wish to continue.</returns>
  293. private bool CheckSavedStatus()
  294. {
  295. if (!historyOfActions.IsEmpty())
  296. {
  297. return (MessageBox.Show("You have unsaved changes, do you wish to continue?",
  298. "Attention", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes);
  299. }
  300. return true;
  301. }
  302. */
  303. /********************************************/
  304. /*** FUNCTIONS TO INTERACT WITH PRESENTER ***/
  305. /********************************************/
  306. /// <summary>
  307. /// Creates an empty Canvas
  308. /// </summary>
  309. public void DrawEmptyCanvasRight()
  310. {
  311. if (leftImage == null)
  312. {
  313. rightImageWithoutOverlay = GetEmptyCanvas(leftImageBoxWidth, leftImageBoxHeight);
  314. }
  315. else
  316. {
  317. rightImageWithoutOverlay = GetEmptyCanvas(leftImage.Width, leftImage.Height);
  318. }
  319. RepopulateDeletionMatrixes();
  320. rightImageWithOverlay = rightImageWithoutOverlay;
  321. programPresenter.UpdateRightImage(rightImageWithOverlay);
  322. }
  323. /// <summary>
  324. /// The function to set the left image.
  325. /// </summary>
  326. /// <param name="width">The width of the left image.</param>
  327. /// <param name="height">The height of the left image.</param>
  328. /// <param name="listOfLines">The List of Lines to be displayed in the left image.</param>
  329. public void SetLeftLineList(int width, int height, List<Line> listOfLines)
  330. {
  331. var workingCanvas = GetEmptyCanvas(width,height);
  332. var workingGraph = Graphics.FromImage(workingCanvas);
  333. leftLineList = listOfLines;
  334. //Lines
  335. foreach (Line line in leftLineList)
  336. {
  337. line.DrawLine(workingGraph);
  338. }
  339. leftImage = workingCanvas;
  340. programPresenter.UpdateLeftImage(leftImage);
  341. //Set right image to same size as left image and delete linelist
  342. DrawEmptyCanvasRight();
  343. rightLineList = new List<Tuple<bool, Line>>();
  344. }
  345. public void Undo()
  346. {
  347. if (historyOfActions.CanUndo())
  348. {
  349. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  350. SketchAction.ActionType undoAction = historyOfActions.GetCurrentAction().GetActionType();
  351. switch (undoAction)
  352. {
  353. case SketchAction.ActionType.Delete:
  354. //Deleted Lines need to be shown
  355. ChangeLines(affectedLines, true);
  356. break;
  357. case SketchAction.ActionType.Draw:
  358. //Drawn lines need to be hidden
  359. ChangeLines(affectedLines, false);
  360. break;
  361. default:
  362. break;
  363. }
  364. if(leftImage != null)
  365. {
  366. //overlayItems = redrawAss.Tick(currentCursorPosition, rightLineList, -1, false);
  367. }
  368. RedrawRightImage();
  369. }
  370. RepopulateDeletionMatrixes();
  371. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(true));
  372. UpdateUI();
  373. }
  374. public void Redo()
  375. {
  376. if (historyOfActions.CanRedo())
  377. {
  378. programPresenter.PassLastActionTaken(historyOfActions.MoveAction(false));
  379. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  380. SketchAction.ActionType redoAction = historyOfActions.GetCurrentAction().GetActionType();
  381. switch (redoAction)
  382. {
  383. case SketchAction.ActionType.Delete:
  384. //Deleted Lines need to be redeleted
  385. ChangeLines(affectedLines, false);
  386. break;
  387. case SketchAction.ActionType.Draw:
  388. //Drawn lines need to be redrawn
  389. ChangeLines(affectedLines, true);
  390. break;
  391. default:
  392. break;
  393. }
  394. if (leftImage != null)
  395. {
  396. //overlayItems = redrawAss.Tick(currentCursorPosition, rightLineList, -1, false);
  397. }
  398. RedrawRightImage();
  399. RepopulateDeletionMatrixes();
  400. }
  401. UpdateUI();
  402. }
  403. /// <summary>
  404. /// The function called by the Presenter to change the drawing state of the program.
  405. /// </summary>
  406. /// <param name="nowDrawing">The new drawingstate of the program</param>
  407. public void ChangeState(bool nowDrawing)
  408. {
  409. inDrawingMode = nowDrawing;
  410. UpdateUI();
  411. }
  412. /// <summary>
  413. /// A method to get the dimensions of the right image.
  414. /// </summary>
  415. /// <returns>A tuple containing the width and height of the right image.</returns>
  416. public Tuple<int, int> GetRightImageDimensions()
  417. {
  418. if (rightImageWithoutOverlay != null)
  419. {
  420. return new Tuple<int, int>(rightImageWithoutOverlay.Width, rightImageWithoutOverlay.Height);
  421. }
  422. else
  423. {
  424. return new Tuple<int, int>(0, 0);
  425. }
  426. }
  427. public void SetCurrentCursorPosition(Point p)
  428. {
  429. currentCursorPosition = p;
  430. }
  431. public void MouseDown()
  432. {
  433. mousePressed = true;
  434. if (inDrawingMode)
  435. {
  436. currentLine = new List<Point>();
  437. }
  438. }
  439. public void MouseUp()
  440. {
  441. mousePressed = false;
  442. if (inDrawingMode && currentLine.Count > 0)
  443. {
  444. Line newLine = new Line(currentLine, rightLineList.Count);
  445. rightLineList.Add(new Tuple<bool, Line>(true, newLine));
  446. newLine.PopulateMatrixes(isFilledMatrix, linesMatrix);
  447. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Draw, newLine.GetID())));
  448. if(leftImage != null)
  449. {
  450. //Execute a RedrawAssistant tick with the currently finished Line
  451. //overlayItems = redrawAss.Tick(currentCursorPosition, rightLineList, newLine.GetID(), true);
  452. }
  453. RedrawRightImage();
  454. }
  455. UpdateUI();
  456. }
  457. public void Tick()
  458. {
  459. if (cursorPositions.Count > 0) { previousCursorPosition = cursorPositions.Dequeue(); }
  460. else { previousCursorPosition = currentCursorPosition; }
  461. cursorPositions.Enqueue(currentCursorPosition);
  462. //Drawing
  463. if (inDrawingMode && mousePressed)
  464. {
  465. var rightGraph = Graphics.FromImage(rightImageWithoutOverlay);
  466. currentLine.Add(currentCursorPosition);
  467. Line drawline = new Line(currentLine);
  468. drawline.DrawLine(rightGraph);
  469. RedrawRightOverlay();
  470. }
  471. //Deleting
  472. if (!inDrawingMode && mousePressed)
  473. {
  474. List<Point> uncheckedPoints = GeometryCalculator.BresenhamLineAlgorithm(previousCursorPosition, currentCursorPosition);
  475. foreach (Point currPoint in uncheckedPoints)
  476. {
  477. HashSet<int> linesToDelete = CheckDeletionMatrixesAroundPoint(currPoint, deletionRadius);
  478. if (linesToDelete.Count > 0)
  479. {
  480. programPresenter.PassLastActionTaken(historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Delete, linesToDelete)));
  481. foreach (int lineID in linesToDelete)
  482. {
  483. rightLineList[lineID] = new Tuple<bool, Line>(false, rightLineList[lineID].Item2);
  484. }
  485. RepopulateDeletionMatrixes();
  486. if(leftImage != null)
  487. {
  488. //Redraw overlay gets ticked
  489. //overlayItems = redrawAss.Tick(currentCursorPosition, rightLineList, -1, false);
  490. }
  491. RedrawRightImage();
  492. }
  493. }
  494. }
  495. }
  496. /// <summary>
  497. /// A helper Function that updates the markerRadius & deletionRadius, considering the size of the canvas.
  498. /// </summary>
  499. public void UpdateSizes()
  500. {
  501. if (rightImageWithoutOverlay != null)
  502. {
  503. int widthImage = rightImageWithoutOverlay.Width;
  504. int heightImage = rightImageWithoutOverlay.Height;
  505. int widthBox = rightImageBoxWidth;
  506. int heightBox = rightImageBoxHeight;
  507. float imageRatio = (float)widthImage / (float)heightImage;
  508. float containerRatio = (float)widthBox / (float)heightBox;
  509. float zoomFactor = 0;
  510. if (imageRatio >= containerRatio)
  511. {
  512. //Image is wider than it is high
  513. zoomFactor = (float)widthImage / (float)widthBox;
  514. }
  515. else
  516. {
  517. //Image is higher than it is wide
  518. zoomFactor = (float)heightImage / (float)heightBox;
  519. }
  520. markerRadius = (int)(10 * zoomFactor);
  521. redrawAss.SetMarkerRadius(markerRadius);
  522. deletionRadius = (int)(5 * zoomFactor);
  523. }
  524. }
  525. /// <summary>
  526. /// If there is unsaved progress.
  527. /// </summary>
  528. /// <returns>True if there is progress that has not been saved.</returns>
  529. public bool HasUnsavedProgress()
  530. {
  531. return !historyOfActions.IsEmpty();
  532. }
  533. }
  534. }