MVP_Presenter.cs 24 KB

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