MVP_Presenter.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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.Input;
  9. using System.Windows.Media;
  10. using System.Windows.Shapes;
  11. using OptiTrack;
  12. using System.Windows.Ink;
  13. namespace SketchAssistantWPF
  14. {
  15. public class MVP_Presenter
  16. {
  17. /// <summary>
  18. /// The View of the MVP-Model, in this case Form1.
  19. /// </summary>
  20. MVP_View programView;
  21. /// <summary>
  22. /// The Model of the MVP-Model.
  23. /// </summary>
  24. MVP_Model programModel;
  25. /// <summary>
  26. /// A dictionary connecting the id of an InternalLine with the respective Polyline in the right canvas.
  27. /// </summary>
  28. Dictionary<int, Shape> rightPolyLines;
  29. /// <summary>
  30. /// The actual size of the left canvas.
  31. /// </summary>
  32. ImageDimension canvasSizeLeft = new ImageDimension(0, 0);
  33. /// <summary>
  34. /// The actual size of the right canvas.
  35. /// </summary>
  36. ImageDimension canvasSizeRight = new ImageDimension(0, 0);
  37. /// <summary>
  38. /// A list of line similarities, resulting in the similarity of the whole image.
  39. /// </summary>
  40. List<double> imageSimilarity = new List<double>();
  41. /// <summary>
  42. /// The lines in the left canvas.
  43. /// </summary>
  44. List<InternalLine> leftLines = new List<InternalLine>();
  45. /*******************/
  46. /*** ENUMERATORS ***/
  47. /*******************/
  48. public enum MouseAction
  49. {
  50. Down,
  51. Up,
  52. Up_Invalid,
  53. Move
  54. }
  55. /***********************/
  56. /*** CLASS VARIABLES ***/
  57. /***********************/
  58. /// <summary>
  59. /// Instance of FileImporter to handle drawing imports.
  60. /// </summary>
  61. private FileImporter fileImporter;
  62. public MVP_Presenter(MVP_View form)
  63. {
  64. programView = form;
  65. programModel = new MVP_Model(this);
  66. fileImporter = new FileImporter();
  67. }
  68. /***********************************/
  69. /*** FUNCTIONS VIEW -> PRESENTER ***/
  70. /***********************************/
  71. /// <summary>
  72. /// Pass-trough function to update the appropriate information of the model, when the window is resized.
  73. /// </summary>
  74. /// <param name="leftPBS">The new size of the left picture box.</param>
  75. /// <param name="rightPBS">The new size of the left picture box.</param>
  76. public void Resize(Tuple<int, int> leftPBS, Tuple<int, int> rightPBS)
  77. {
  78. canvasSizeLeft.ChangeDimension(leftPBS.Item1, leftPBS.Item2);
  79. canvasSizeRight.ChangeDimension(rightPBS.Item1, rightPBS.Item2);
  80. programModel.ResizeEvent(canvasSizeRight);
  81. }
  82. /// <summary>
  83. /// Display a new FileDialog to a svg drawing.
  84. /// </summary>
  85. /// <returns>True if loading was a success</returns>
  86. public bool SVGToolStripMenuItemClick()
  87. {
  88. var okToContinue = true; bool returnval = false;
  89. if (programModel.HasUnsavedProgress())
  90. {
  91. okToContinue = programView.ShowWarning("You have unsaved progress. Continue?");
  92. }
  93. if (okToContinue)
  94. {
  95. var fileNameTup = programView.openNewDialog("Scalable Vector Graphics|*.svg");
  96. if (!fileNameTup.Item1.Equals("") && !fileNameTup.Item2.Equals(""))
  97. {
  98. programView.SetToolStripLoadStatus(fileNameTup.Item2);
  99. try
  100. {
  101. Tuple<int, int, List<InternalLine>> values = fileImporter.ParseSVGInputFile(fileNameTup.Item1, programModel.leftImageBoxWidth, programModel.leftImageBoxHeight);
  102. values.Item3.ForEach(line => line.MakePermanent(0)); //Make all lines permanent
  103. programModel.SetLeftLineList(values.Item1, values.Item2, values.Item3);
  104. programModel.ResizeEvent(canvasSizeRight);
  105. programModel.ResetRightImage();
  106. programModel.CanvasActivated();
  107. programModel.ChangeState(true);
  108. programView.EnableTimer();
  109. ClearRightLines();
  110. returnval = true;
  111. }
  112. catch (FileImporterException ex)
  113. {
  114. programView.ShowInfoMessage(ex.ToString());
  115. }
  116. catch (Exception ex)
  117. {
  118. programView.ShowInfoMessage("exception occured while trying to parse svg file:\n\n" + ex.ToString() + "\n\n" + ex.StackTrace);
  119. }
  120. }
  121. }
  122. return returnval;
  123. }
  124. /// <summary>
  125. /// Pass-trough function to change the drawing state of the model.
  126. /// </summary>
  127. /// <param name="NowDrawing">Indicates if the program is in drawing (true) or deletion (false) mode.</param>
  128. public void ChangeState(bool NowDrawing)
  129. {
  130. programModel.ChangeState(NowDrawing);
  131. }
  132. /// <summary>
  133. /// Gets whether the program is in drawing state or not.
  134. /// </summary>
  135. /// <returns></returns>
  136. public bool GetDrawingState()
  137. {
  138. return programModel.inDrawingMode;
  139. }
  140. /// <summary>
  141. /// Gets whether Optitrack is in use or not.
  142. /// </summary>
  143. /// <returns>Return optiTrackInUse</returns>
  144. public bool GetOptitrackActive()
  145. {
  146. return programModel.optiTrackInUse;
  147. }
  148. /// <summary>
  149. /// Pass-through function to change the OptiTrack-in-use state of the model
  150. /// </summary>
  151. public void ChangeOptiTrack(bool usingOptiTrack)
  152. {
  153. if (programModel.optitrackAvailable)
  154. {
  155. programModel.SetOptiTrack(usingOptiTrack);
  156. }
  157. }
  158. /// <summary>
  159. /// Pass-trough function to undo an action.
  160. /// </summary>
  161. public void Undo()
  162. {
  163. programModel.Undo();
  164. }
  165. /// <summary>
  166. /// Pass-trough function to redo an action.
  167. /// </summary>
  168. public void Redo()
  169. {
  170. programModel.Redo();
  171. }
  172. /// <summary>
  173. /// Pass-trough function for ticking the model.
  174. /// </summary>
  175. public void Tick()
  176. {
  177. programModel.Tick();
  178. }
  179. /// <summary>
  180. /// Checks if there is unsaved progress, and promts the model to generate a new canvas if not.
  181. /// </summary>
  182. public void NewCanvas()
  183. {
  184. var okToContinue = true;
  185. if (programModel.HasUnsavedProgress())
  186. {
  187. okToContinue = programView.ShowWarning("You have unsaved progress. Continue?");
  188. }
  189. if (okToContinue)
  190. {
  191. programModel.ResizeEvent(canvasSizeRight);
  192. programModel.ResetRightImage();
  193. programModel.CanvasActivated();
  194. programModel.ChangeState(true);
  195. programView.EnableTimer();
  196. ClearRightLines();
  197. }
  198. }
  199. /// <summary>
  200. /// Pass-trough when the mouse is moved.
  201. /// </summary>
  202. /// <param name="mouseAction">The action which is sent by the View.</param>
  203. /// <param name="position">The position of the mouse.</param>
  204. public void MouseEvent(MouseAction mouseAction, Point position)
  205. {
  206. switch (mouseAction)
  207. {
  208. case MouseAction.Move:
  209. programModel.SetCurrentCursorPosition(position);
  210. break;
  211. default:
  212. break;
  213. }
  214. }
  215. /// <summary>
  216. /// Pass-trough function that calls the correct Mouse event of the model, when the mouse is clicked.
  217. /// </summary>
  218. /// <param name="mouseAction">The action which is sent by the View.</param>
  219. /// <param name="strokes">The Strokes.</param>
  220. public void MouseEvent(MouseAction mouseAction, StrokeCollection strokes)
  221. {
  222. if (!programModel.optiTrackInUse)
  223. {
  224. switch (mouseAction)
  225. {
  226. case MouseAction.Down:
  227. programModel.StartNewLine();
  228. break;
  229. case MouseAction.Up:
  230. if (strokes.Count > 0)
  231. {
  232. StylusPointCollection sPoints = strokes.First().StylusPoints;
  233. List<Point> points = new List<Point>();
  234. foreach (StylusPoint p in sPoints)
  235. points.Add(new Point(p.X, p.Y));
  236. programModel.FinishCurrentLine(points);
  237. }
  238. else
  239. {
  240. programModel.FinishCurrentLine(true);
  241. }
  242. break;
  243. case MouseAction.Up_Invalid:
  244. programModel.FinishCurrentLine(false);
  245. break;
  246. default:
  247. break;
  248. }
  249. }
  250. }
  251. /************************************/
  252. /*** FUNCTIONS MODEL -> PRESENTER ***/
  253. /************************************/
  254. /// <summary>
  255. /// Return the position of the cursor
  256. /// </summary>
  257. /// <returns>The position of the cursor</returns>
  258. public Point GetCursorPosition()
  259. {
  260. return programView.GetCursorPosition();
  261. }
  262. /// <summary>
  263. /// Updates the currentline
  264. /// </summary>
  265. /// <param name="linepoints">The points of the current line.</param>
  266. public void UpdateCurrentLine(List<Point> linepoints)
  267. {
  268. Polyline currentLine = new Polyline();
  269. currentLine.Stroke = Brushes.Black;
  270. currentLine.Points = new PointCollection(linepoints);
  271. programView.DisplayCurrLine(currentLine);
  272. }
  273. /// <summary>
  274. /// Clears all Lines in the right canvas.
  275. /// </summary>
  276. public void ClearRightLines()
  277. {
  278. programView.RemoveAllRightLines();
  279. rightPolyLines = new Dictionary<int, Shape>();
  280. //Reset the similarity display
  281. UpdateSimilarityScore(Double.NaN);
  282. }
  283. /// <summary>
  284. /// A function to update the displayed lines in the right canvas.
  285. /// </summary>
  286. public void UpdateRightLines(List<Tuple<bool, InternalLine>> lines)
  287. {
  288. foreach (Tuple<bool, InternalLine> tup in lines)
  289. {
  290. var status = tup.Item1;
  291. var line = tup.Item2;
  292. if (!rightPolyLines.ContainsKey(line.GetID()))
  293. {
  294. if (!line.isPoint)
  295. {
  296. Polyline newLine = new Polyline();
  297. newLine.Points = line.GetPointCollection();
  298. rightPolyLines.Add(line.GetID(), newLine);
  299. programView.AddNewLineRight(newLine);
  300. }
  301. else
  302. {
  303. Ellipse newPoint = new Ellipse();
  304. rightPolyLines.Add(line.GetID(), newPoint);
  305. programView.AddNewPointRight(newPoint, line);
  306. }
  307. }
  308. SetVisibility(rightPolyLines[line.GetID()], status);
  309. }
  310. //Calculate similarity scores
  311. UpdateSimilarityScore(Double.NaN); var templist = lines.Where(tup => tup.Item1).ToList();
  312. if (leftLines.Count > 0)
  313. {
  314. for (int i = 0; i < leftLines.Count; i++)
  315. {
  316. if (templist.Count == i) break;
  317. UpdateSimilarityScore(GeometryCalculator.CalculateSimilarity(templist[i].Item2, leftLines[i]));
  318. }
  319. }
  320. else if (templist.Count > 1)
  321. {
  322. UpdateSimilarityScore(GeometryCalculator.CalculateSimilarity(templist[templist.Count - 2].Item2, templist[templist.Count - 1].Item2));
  323. }
  324. }
  325. /// <summary>
  326. /// A function to update the displayed lines in the left canvas.
  327. /// </summary>
  328. public void UpdateLeftLines(List<InternalLine> lines)
  329. {
  330. programView.RemoveAllLeftLines();
  331. foreach (InternalLine line in lines)
  332. {
  333. Polyline newLine = new Polyline();
  334. newLine.Stroke = Brushes.Black;
  335. newLine.Points = line.GetPointCollection();
  336. programView.AddNewLineLeft(newLine);
  337. }
  338. programView.SetCanvasState("LeftCanvas", true);
  339. programView.SetCanvasState("RightCanvas", true);
  340. leftLines = lines;
  341. }
  342. /// <summary>
  343. /// Called by the model when the state of the Program changes.
  344. /// Changes the look of the UI according to the current state of the model.
  345. /// </summary>
  346. /// <param name="inDrawingMode">If the model is in Drawing Mode</param>
  347. /// <param name="canUndo">If actions in the model can be undone</param>
  348. /// <param name="canRedo">If actions in the model can be redone</param>
  349. /// <param name="canvasActive">If the right canvas is active</param>
  350. /// <param name="graphicLoaded">If an image is loaded in the model</param>
  351. /// <param name="optiTrackAvailable">If there is an optitrack system available</param>
  352. /// <param name="optiTrackInUse">If the optitrack system is active</param>
  353. public void UpdateUIState(bool inDrawingMode, bool canUndo, bool canRedo, bool canvasActive,
  354. bool graphicLoaded, bool optiTrackAvailable, bool optiTrackInUse)
  355. {
  356. Dictionary<String, MainWindow.ButtonState> dict = new Dictionary<String, MainWindow.ButtonState> {
  357. {"canvasButton", MainWindow.ButtonState.Enabled }, {"drawButton", MainWindow.ButtonState.Disabled}, {"deleteButton",MainWindow.ButtonState.Disabled },
  358. {"undoButton", MainWindow.ButtonState.Disabled },{"redoButton", MainWindow.ButtonState.Disabled}, {"drawWithOptiButton", MainWindow.ButtonState.Disabled}};
  359. if (canvasActive)
  360. {
  361. if (inDrawingMode)
  362. {
  363. if (optiTrackAvailable)
  364. {
  365. if (optiTrackInUse)
  366. {
  367. dict["drawButton"] = MainWindow.ButtonState.Enabled;
  368. dict["drawWithOptiButton"] = MainWindow.ButtonState.Active;
  369. dict["deleteButton"] = MainWindow.ButtonState.Enabled;
  370. }
  371. else
  372. {
  373. dict["drawButton"] = MainWindow.ButtonState.Active;
  374. dict["drawWithOptiButton"] = MainWindow.ButtonState.Enabled;
  375. dict["deleteButton"] = MainWindow.ButtonState.Enabled;
  376. }
  377. }
  378. else
  379. {
  380. dict["drawButton"] = MainWindow.ButtonState.Active;
  381. dict["deleteButton"] = MainWindow.ButtonState.Enabled;
  382. }
  383. }
  384. else
  385. {
  386. dict["drawButton"] = MainWindow.ButtonState.Enabled;
  387. dict["deleteButton"] = MainWindow.ButtonState.Active;
  388. if (optiTrackAvailable)
  389. {
  390. dict["drawWithOptiButton"] = MainWindow.ButtonState.Enabled;
  391. }
  392. }
  393. if (canUndo) { dict["undoButton"] = MainWindow.ButtonState.Enabled; }
  394. if (canRedo) { dict["redoButton"] = MainWindow.ButtonState.Enabled; }
  395. }
  396. foreach (KeyValuePair<String, MainWindow.ButtonState> entry in dict)
  397. {
  398. programView.SetToolStripButtonStatus(entry.Key, entry.Value);
  399. }
  400. programView.SetCanvasState("RightCanvas", canvasActive);
  401. programView.SetCanvasState("LeftCanvas", graphicLoaded);
  402. }
  403. /// <summary>
  404. /// Pass-trough function to display an info message in the view.
  405. /// </summary>
  406. /// <param name="msg">The message.</param>
  407. public void PassMessageToView(String msg)
  408. {
  409. programView.ShowInfoMessage(msg);
  410. }
  411. /// <summary>
  412. /// Pass-through function to desplay an Warning message in the view
  413. /// </summary>
  414. /// <param name="msg">The message.</param>
  415. /// <returns>True if the user confirms (Yes), negative if he doesn't (No)</returns>
  416. public bool PassWarning(String msg)
  417. {
  418. return programView.ShowWarning(msg);
  419. }
  420. /// <summary>
  421. /// Pass-trough function to update the display of the last action taken.
  422. /// </summary>
  423. /// <param name="msg">The new last action taken.</param>
  424. public void PassLastActionTaken(String msg)
  425. {
  426. programView.SetLastActionTakenText(msg);
  427. }
  428. /// <summary>
  429. /// Passes whether or not the mouse is pressed.
  430. /// </summary>
  431. /// <returns>Whether or not the mouse is pressed</returns>
  432. public bool IsMousePressed()
  433. {
  434. return programView.IsMousePressed();
  435. }
  436. public void PassOptiTrackMessage(String stringToPass)
  437. {
  438. programView.SetOptiTrackText(stringToPass);
  439. }
  440. /// <summary>
  441. /// Update the similarity score displayed in the UI.
  442. /// </summary>
  443. /// <param name="score">Score will be reset if NaN is passed,
  444. /// will be ignored if the score is not between 0 and 1</param>
  445. public void UpdateSimilarityScore(double score)
  446. {
  447. if (Double.IsNaN(score))
  448. {
  449. imageSimilarity.Clear();
  450. programView.SetImageSimilarityText("");
  451. }
  452. else
  453. {
  454. if (score >= 0 && score <= 1) imageSimilarity.Add(score);
  455. programView.SetImageSimilarityText((imageSimilarity.Sum() / imageSimilarity.Count).ToString());
  456. }
  457. }
  458. /// <summary>
  459. /// Change the color of an overlay item.
  460. /// </summary>
  461. /// <param name="name">The name of the item in the overlay dictionary</param>
  462. /// <param name="color">The color of the item</param>
  463. public void SetOverlayColor(String name, Brush color)
  464. {
  465. Shape shape = new Ellipse();
  466. if(((MainWindow)programView).overlayDictionary.ContainsKey(name))
  467. {
  468. shape = ((MainWindow)programView).overlayDictionary[name];
  469. if(name.Substring(0, 7).Equals("dotLine"))
  470. shape.Stroke = color;
  471. else
  472. shape.Fill = color;
  473. }
  474. }
  475. /// <summary>
  476. /// Change the properties of an overlay item.
  477. /// </summary>
  478. /// <param name="name">The name of the item in the overlay dictionary</param>
  479. /// <param name="visible">If the element should be visible</param>
  480. /// <param name="position">The new position of the element</param>
  481. public void SetOverlayStatus(String name, bool visible, Point position)
  482. {
  483. Shape shape = new Ellipse(); double visibility = 1; double xDif = 0; double yDif = 0;
  484. Point point = ConvertRightCanvasCoordinateToOverlay(position);
  485. switch (name)
  486. {
  487. case "optipoint":
  488. shape = ((MainWindow)programView).overlayDictionary["optipoint"];
  489. visibility = 0.75; xDif = 2.5; yDif = 2.5;
  490. break;
  491. case "startpoint":
  492. shape = ((MainWindow)programView).overlayDictionary["startpoint"];
  493. xDif = ((MainWindow)programView).markerRadius; yDif = xDif;
  494. break;
  495. case "endpoint":
  496. shape = ((MainWindow)programView).overlayDictionary["endpoint"];
  497. xDif = ((MainWindow)programView).markerRadius; yDif = xDif;
  498. break;
  499. default:
  500. Console.WriteLine("Unknown Overlay Item. Please check in MVP_Presenter if this item exists.");
  501. return;
  502. }
  503. if (visible) shape.Opacity = visibility;
  504. else shape.Opacity = 0.00001;
  505. shape.Margin = new Thickness(point.X - xDif, point.Y - yDif, 0, 0);
  506. }
  507. /// <summary>
  508. /// Change the properties of an overlay item.
  509. /// </summary>
  510. /// <param name="name">The name of the item in the overlay dictionary</param>
  511. /// <param name="visible">If the element should be visible</param>
  512. /// <param name="pos1">The new position of the element</param>
  513. /// <param name="pos2">The new position of the element</param>
  514. public void SetOverlayStatus(String name, bool visible, Point pos1, Point pos2)
  515. {
  516. Shape shape = new Ellipse();
  517. switch (name.Substring(0, 7))
  518. {
  519. case "dotLine":
  520. if (((MainWindow)programView).overlayDictionary.ContainsKey(name))
  521. {
  522. shape = ((MainWindow)programView).overlayDictionary[name];
  523. break;
  524. }
  525. goto default;
  526. default:
  527. SetOverlayStatus(name, visible, pos1);
  528. return;
  529. }
  530. if (visible) shape.Opacity = 1;
  531. else shape.Opacity = 0.00001;
  532. Point p1 = ConvertRightCanvasCoordinateToOverlay(pos1); Point p2 = ConvertRightCanvasCoordinateToOverlay(pos2);
  533. ((Line)shape).X1 = p1.X; ((Line)shape).X2 = p2.X; ((Line)shape).Y1 = p1.Y; ((Line)shape).Y2 = p2.Y;
  534. }
  535. /// <summary>
  536. /// Move the optitrack pointer to a new position.
  537. /// </summary>
  538. /// <param name="position">Position relative to the Rightcanvas</param>
  539. public void MoveOptiPoint(Point position)
  540. {
  541. Point point = ConvertRightCanvasCoordinateToOverlay(position);
  542. Shape shape = ((MainWindow)programView).overlayDictionary["optipoint"];
  543. shape.Margin = new Thickness(point.X - 2.5, point.Y - 2.5, 0, 0);
  544. }
  545. /*************************/
  546. /*** HELPING FUNCTIONS ***/
  547. /*************************/
  548. /// <summary>
  549. /// Convert point relative to the right canvas to a point relative to the overlay canvas.
  550. /// </summary>
  551. /// <param name="p">The point to convert.</param>
  552. /// <returns>The respective overlay canvas.</returns>
  553. private Point ConvertRightCanvasCoordinateToOverlay(Point p)
  554. {
  555. MainWindow main = (MainWindow)programView;
  556. double xDif = (main.CanvasLeftEdge.ActualWidth + main.LeftCanvas.ActualWidth + main.CanvasSeperator.ActualWidth);
  557. double yDif = (main.ButtonToolbar.ActualHeight);
  558. return new Point(p.X + xDif, p.Y + yDif);
  559. }
  560. /// <summary>
  561. /// Sets the visibility of a polyline.
  562. /// </summary>
  563. /// <param name="line">The polyline</param>
  564. /// <param name="visible">Whether or not it should be visible.</param>
  565. private void SetVisibility(Shape line, bool visible)
  566. {
  567. if (!visible)
  568. {
  569. line.Opacity = 0.00001;
  570. }
  571. else
  572. {
  573. line.Opacity = 1;
  574. }
  575. }
  576. }
  577. }