MVP_Presenter.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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.Ink;
  9. using System.Windows.Input;
  10. using System.Windows.Media;
  11. using System.Windows.Shapes;
  12. namespace SketchAssistantWPF
  13. {
  14. public class MVP_Presenter
  15. {
  16. /// <summary>
  17. /// The View of the MVP-Model, in this case Form1.
  18. /// </summary>
  19. MVP_View programView;
  20. /// <summary>
  21. /// The Model of the MVP-Model.
  22. /// </summary>
  23. MVP_Model programModel;
  24. /// <summary>
  25. /// A dictionary connecting the id of an InternalLine with the respective Polyline in the right canvas.
  26. /// </summary>
  27. Dictionary<int, Shape> rightPolyLines;
  28. ImageDimension CanvasSizeLeft = new ImageDimension(0,0);
  29. ImageDimension CanvasSizeRight = new ImageDimension(0, 0);
  30. ImageDimension ImageSizeLeft = new ImageDimension(0, 0);
  31. ImageDimension ImageSizeRight = new ImageDimension(0, 0);
  32. List<double> ImageSimilarity = new List<double>();
  33. List<InternalLine> LeftLines = new List<InternalLine>();
  34. /*******************/
  35. /*** ENUMERATORS ***/
  36. /*******************/
  37. public enum MouseAction
  38. {
  39. Click,
  40. Down,
  41. Up,
  42. Up_Invalid,
  43. Move
  44. }
  45. /***********************/
  46. /*** CLASS VARIABLES ***/
  47. /***********************/
  48. /// <summary>
  49. /// Instance of FileImporter to handle drawing imports.
  50. /// </summary>
  51. private FileImporter fileImporter;
  52. public MVP_Presenter(MVP_View form)
  53. {
  54. programView = form;
  55. programModel = new MVP_Model(this);
  56. //Initialize Class Variables
  57. fileImporter = new FileImporter();
  58. }
  59. /***********************************/
  60. /*** FUNCTIONS VIEW -> PRESENTER ***/
  61. /***********************************/
  62. /// <summary>
  63. /// Pass-trough function to update the appropriate information of the model, when the window is resized.
  64. /// </summary>
  65. /// <param name="leftPBS">The new size of the left picture box.</param>
  66. /// <param name="rightPBS">The new size of the left picture box.</param>
  67. public void Resize(Tuple<int, int> leftPBS, Tuple<int, int> rightPBS)
  68. {
  69. CanvasSizeLeft.ChangeDimension(leftPBS.Item1, leftPBS.Item2);
  70. CanvasSizeRight.ChangeDimension(rightPBS.Item1, rightPBS.Item2);
  71. //programModel.UpdateSizes(CanvasSizeRight);
  72. programModel.ResizeEvent(CanvasSizeLeft, CanvasSizeRight);
  73. }
  74. /// <summary>
  75. /// Display a new FileDialog to load a collection of lines.
  76. /// </summary>
  77. /// <returns>True if loading was a success</returns>
  78. public bool ExamplePictureToolStripMenuItemClick()
  79. {
  80. var okToContinue = true; bool returnval = false;
  81. if (programModel.HasUnsavedProgress())
  82. {
  83. okToContinue = programView.ShowWarning("You have unsaved progress. Continue?");
  84. }
  85. if (okToContinue)
  86. {
  87. var fileNameTup = programView.openNewDialog("Interactive Sketch-Assistant Drawing|*.isad");
  88. if (!fileNameTup.Item1.Equals("") && !fileNameTup.Item2.Equals(""))
  89. {
  90. programView.SetToolStripLoadStatus(fileNameTup.Item2);
  91. try
  92. {
  93. Tuple<int, int, List<InternalLine>> values = fileImporter.ParseISADInputFile(fileNameTup.Item1);
  94. values.Item3.ForEach(line => line.MakePermanent(0)); //Make all lines permanent
  95. programModel.SetLeftLineList(values.Item1, values.Item2, values.Item3);
  96. programModel.ResetRightImage();
  97. programModel.CanvasActivated();
  98. programModel.ChangeState(true);
  99. programView.EnableTimer();
  100. ClearRightLines();
  101. returnval = true;
  102. }
  103. catch (FileImporterException ex)
  104. {
  105. programView.ShowInfoMessage(ex.ToString());
  106. }
  107. catch (Exception ex)
  108. {
  109. programView.ShowInfoMessage("exception occured while trying to load interactive sketch-assistant drawing file:\n\n" + ex.ToString() + "\n\n" + ex.StackTrace);
  110. }
  111. }
  112. }
  113. return returnval;
  114. }
  115. /// <summary>
  116. /// Display a new FileDialog to a svg drawing.
  117. /// </summary>
  118. /// <returns>True if loading was a success</returns>
  119. public bool SVGToolStripMenuItemClick()
  120. {
  121. var okToContinue = true; bool returnval = false;
  122. if (programModel.HasUnsavedProgress())
  123. {
  124. okToContinue = programView.ShowWarning("You have unsaved progress. Continue?");
  125. }
  126. if (okToContinue)
  127. {
  128. var fileNameTup = programView.openNewDialog("Scalable Vector Graphics|*.svg");
  129. if (!fileNameTup.Item1.Equals("") && !fileNameTup.Item2.Equals(""))
  130. {
  131. programView.SetToolStripLoadStatus(fileNameTup.Item2);
  132. try
  133. {
  134. Tuple<int, int, List<InternalLine>> values = fileImporter.ParseSVGInputFile(fileNameTup.Item1, programModel.leftImageBoxWidth, programModel.leftImageBoxHeight);
  135. values.Item3.ForEach(line => line.MakePermanent(0)); //Make all lines permanent
  136. programModel.SetLeftLineList(values.Item1, values.Item2, values.Item3);
  137. programModel.ResetRightImage();
  138. programModel.CanvasActivated();
  139. programModel.ChangeState(true);
  140. programView.EnableTimer();
  141. ClearRightLines();
  142. returnval = true;
  143. }
  144. catch (FileImporterException ex)
  145. {
  146. programView.ShowInfoMessage(ex.ToString());
  147. }
  148. catch (Exception ex)
  149. {
  150. programView.ShowInfoMessage("exception occured while trying to parse svg file:\n\n" + ex.ToString() + "\n\n" + ex.StackTrace);
  151. }
  152. }
  153. }
  154. return returnval;
  155. }
  156. /// <summary>
  157. /// Pass-trough function to change the drawing state of the model.
  158. /// </summary>
  159. /// <param name="NowDrawing">Indicates if the program is in drawing (true) or deletion (false) mode.</param>
  160. public void ChangeState(bool NowDrawing)
  161. {
  162. programModel.ChangeState(NowDrawing);
  163. }
  164. /// <summary>
  165. /// Pass-trough function to undo an action.
  166. /// </summary>
  167. public void Undo()
  168. {
  169. programModel.Undo();
  170. }
  171. /// <summary>
  172. /// Pass-trough function to redo an action.
  173. /// </summary>
  174. public void Redo()
  175. {
  176. programModel.Redo();
  177. }
  178. /// <summary>
  179. /// Pass-trough function for ticking the model.
  180. /// </summary>
  181. public void Tick()
  182. {
  183. programModel.Tick();
  184. }
  185. /// <summary>
  186. /// Checks if there is unsaved progress, and promts the model to generate a new canvas if not.
  187. /// </summary>
  188. public void NewCanvas()
  189. {
  190. var okToContinue = true;
  191. if (programModel.HasUnsavedProgress())
  192. {
  193. okToContinue = programView.ShowWarning("You have unsaved progress. Continue?");
  194. }
  195. if (okToContinue)
  196. {
  197. programModel.ResizeEvent(CanvasSizeLeft, CanvasSizeRight);
  198. programModel.ResetRightImage();
  199. programModel.CanvasActivated();
  200. programModel.ChangeState(true);
  201. programView.EnableTimer();
  202. ClearRightLines();
  203. }
  204. }
  205. /// <summary>
  206. /// Pass-trough when the mouse is moved.
  207. /// </summary>
  208. /// <param name="mouseAction">The action which is sent by the View.</param>
  209. /// <param name="e">The Mouse event arguments.</param>
  210. public void MouseEvent(MouseAction mouseAction, Point position)
  211. {
  212. switch (mouseAction)
  213. {
  214. case MouseAction.Move:
  215. programModel.SetCurrentCursorPosition(position);
  216. break;
  217. default:
  218. break;
  219. }
  220. }
  221. /// <summary>
  222. /// Pass-trough function that calls the correct Mouse event of the model, when the mouse is clicked.
  223. /// </summary>
  224. /// <param name="mouseAction">The action which is sent by the View.</param>
  225. /// <param name="strokes">The Strokes.</param>
  226. public void MouseEvent(MouseAction mouseAction, StrokeCollection strokes)
  227. {
  228. switch (mouseAction)
  229. {
  230. case MouseAction.Click:
  231. programModel.MouseDown();
  232. programModel.Tick();
  233. programModel.MouseUp(true);
  234. break;
  235. case MouseAction.Down:
  236. programModel.MouseDown();
  237. break;
  238. case MouseAction.Up:
  239. if(strokes.Count > 0)
  240. {
  241. StylusPointCollection sPoints = strokes.First().StylusPoints;
  242. List<Point> points = new List<Point>();
  243. foreach(StylusPoint p in sPoints)
  244. points.Add(new Point(p.X, p.Y));
  245. programModel.MouseUp(points);
  246. }
  247. else
  248. {
  249. programModel.MouseUp(true);
  250. }
  251. break;
  252. case MouseAction.Up_Invalid:
  253. programModel.MouseUp(false);
  254. break;
  255. default:
  256. break;
  257. }
  258. }
  259. /************************************/
  260. /*** FUNCTIONS MODEL -> PRESENTER ***/
  261. /************************************/
  262. /// <summary>
  263. /// Return the position of the cursor
  264. /// </summary>
  265. /// <returns>The position of the cursor</returns>
  266. public Point GetCursorPosition()
  267. {
  268. return programView.GetCursorPosition();
  269. }
  270. /// <summary>
  271. /// Clears all Lines in the right canvas.
  272. /// </summary>
  273. public void ClearRightLines()
  274. {
  275. programView.RemoveAllRightLines();
  276. rightPolyLines = new Dictionary<int, Shape>();
  277. //Reset the similarity display
  278. UpdateSimilarityScore(Double.NaN);
  279. }
  280. /// <summary>
  281. /// A function to update the displayed lines in the right canvas.
  282. /// </summary>
  283. public void UpdateRightLines(List<Tuple<bool, InternalLine>> lines)
  284. {
  285. foreach(Tuple<bool, InternalLine> tup in lines)
  286. {
  287. var status = tup.Item1;
  288. var line = tup.Item2;
  289. if (!rightPolyLines.ContainsKey(line.GetID()))
  290. {
  291. if (!line.isPoint)
  292. {
  293. Polyline newLine = new Polyline();
  294. newLine.Points = line.GetPointCollection();
  295. rightPolyLines.Add(line.GetID(), newLine);
  296. programView.AddNewLineRight(newLine);
  297. }
  298. else
  299. {
  300. Ellipse newPoint = new Ellipse();
  301. rightPolyLines.Add(line.GetID(), newPoint);
  302. programView.AddNewPointRight(newPoint, line);
  303. }
  304. }
  305. SetVisibility(rightPolyLines[line.GetID()], status);
  306. }
  307. //Calculate similarity scores
  308. UpdateSimilarityScore(Double.NaN); var templist = lines.Where(tup => tup.Item1).ToList();
  309. if(LeftLines.Count > 0)
  310. {
  311. for(int i = 0; i < LeftLines.Count; i++)
  312. {
  313. if (templist.Count == i) break;
  314. UpdateSimilarityScore(GeometryCalculator.CalculateSimilarity(templist[i].Item2, LeftLines[i]));
  315. }
  316. }
  317. else if(templist.Count > 1)
  318. {
  319. UpdateSimilarityScore(GeometryCalculator.CalculateSimilarity(templist[templist.Count-2].Item2, templist[templist.Count-1].Item2));
  320. }
  321. }
  322. /*
  323. /// <summary>
  324. /// Updates the currentline
  325. /// </summary>
  326. /// <param name="linepoints">The points of the current line.</param>
  327. public void UpdateCurrentLine(List<Point> linepoints)
  328. {
  329. Polyline currentLine = new Polyline();
  330. currentLine.Stroke = Brushes.Black;
  331. currentLine.Points = new PointCollection(linepoints);
  332. programView.DisplayCurrLine(currentLine);
  333. }
  334. */
  335. /// <summary>
  336. /// A function to update the displayed lines in the left canvas.
  337. /// </summary>
  338. public void UpdateLeftLines(List<InternalLine> lines)
  339. {
  340. programView.RemoveAllLeftLines();
  341. foreach (InternalLine line in lines)
  342. {
  343. Polyline newLine = new Polyline();
  344. newLine.Stroke = Brushes.Black;
  345. newLine.Points = line.GetPointCollection();
  346. programView.AddNewLineLeft(newLine);
  347. }
  348. programView.SetCanvasState("LeftCanvas", true);
  349. programView.SetCanvasState("RightCanvas", true);
  350. LeftLines = lines;
  351. }
  352. /// <summary>
  353. /// Called by the model when the state of the Program changes.
  354. /// Changes the look of the UI according to the current state of the model.
  355. /// </summary>
  356. /// <param name="inDrawingMode">If the model is in Drawing Mode</param>
  357. /// <param name="canUndo">If actions in the model can be undone</param>
  358. /// <param name="canRedo">If actions in the model can be redone</param>
  359. /// <param name="canvasActive">If the right canvas is active</param>
  360. /// <param name="graphicLoaded">If an image is loaded in the model</param>
  361. public void UpdateUIState(bool inDrawingMode, bool canUndo, bool canRedo, bool canvasActive, bool graphicLoaded)
  362. {
  363. Dictionary<String, MainWindow.ButtonState> dict = new Dictionary<String, MainWindow.ButtonState> {
  364. {"canvasButton", MainWindow.ButtonState.Enabled }, {"drawButton", MainWindow.ButtonState.Disabled}, {"deleteButton",MainWindow.ButtonState.Disabled },
  365. {"undoButton", MainWindow.ButtonState.Disabled },{"redoButton", MainWindow.ButtonState.Disabled}};
  366. if (canvasActive)
  367. {
  368. if (inDrawingMode)
  369. {
  370. dict["drawButton"] = MainWindow.ButtonState.Active;
  371. dict["deleteButton"] = MainWindow.ButtonState.Enabled;
  372. }
  373. else
  374. {
  375. dict["drawButton"] = MainWindow.ButtonState.Enabled;
  376. dict["deleteButton"] = MainWindow.ButtonState.Active;
  377. }
  378. if (canUndo) { dict["undoButton"] = MainWindow.ButtonState.Enabled; }
  379. if (canRedo) { dict["redoButton"] = MainWindow.ButtonState.Enabled; }
  380. }
  381. foreach (KeyValuePair<String, MainWindow.ButtonState> entry in dict)
  382. {
  383. programView.SetToolStripButtonStatus(entry.Key, entry.Value);
  384. }
  385. programView.SetCanvasState("RightCanvas", canvasActive);
  386. programView.SetCanvasState("LeftCanvas", graphicLoaded);
  387. }
  388. /// <summary>
  389. /// Pass-trough function to display an info message in the view.
  390. /// </summary>
  391. /// <param name="msg">The message.</param>
  392. public void PassMessageToView(String msg)
  393. {
  394. programView.ShowInfoMessage(msg);
  395. }
  396. /// <summary>
  397. /// Pass-trough function to update the display of the last action taken.
  398. /// </summary>
  399. /// <param name="msg">The new last action taken.</param>
  400. public void PassLastActionTaken(String msg)
  401. {
  402. programView.SetLastActionTakenText(msg);
  403. }
  404. /// <summary>
  405. /// Passes whether or not the mouse is pressed.
  406. /// </summary>
  407. /// <returns>Whether or not the mouse is pressed</returns>
  408. public bool IsMousePressed()
  409. {
  410. return programView.IsMousePressed();
  411. }
  412. /// <summary>
  413. ///
  414. /// </summary>
  415. /// <param name="score">Score will be reset if NaN is passed,
  416. /// will be ignored if the score is not between 0 and 1</param>
  417. public void UpdateSimilarityScore(double score)
  418. {
  419. if (Double.IsNaN(score))
  420. {
  421. ImageSimilarity.Clear();
  422. programView.SetImageSimilarityText("");
  423. }
  424. else
  425. {
  426. if (score >= 0 && score <= 1) ImageSimilarity.Add(score);
  427. programView.SetImageSimilarityText((ImageSimilarity.Sum() / ImageSimilarity.Count).ToString());
  428. }
  429. }
  430. /*************************/
  431. /*** HELPING FUNCTIONS ***/
  432. /*************************/
  433. /// <summary>
  434. /// Sets the visibility of a polyline.
  435. /// </summary>
  436. /// <param name="line">The polyline</param>
  437. /// <param name="visible">Whether or not it should be visible.</param>
  438. private void SetVisibility(Shape line, bool visible)
  439. {
  440. if (!visible)
  441. {
  442. line.Opacity = 0.00001;
  443. }
  444. else
  445. {
  446. line.Opacity = 1;
  447. }
  448. }
  449. }
  450. }