Form1.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Text.RegularExpressions;
  11. // This is the code for your desktop app.
  12. // Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
  13. namespace SketchAssistant
  14. {
  15. public partial class Form1 : Form
  16. {
  17. public Form1()
  18. {
  19. InitializeComponent();
  20. fileImporter = new FileImporter(this);
  21. }
  22. /**********************************/
  23. /*** CLASS VARIABLES START HERE ***/
  24. /**********************************/
  25. /// <summary>
  26. /// Different Program States
  27. /// </summary>
  28. public enum ProgramState
  29. {
  30. Idle,
  31. Draw,
  32. Delete
  33. }
  34. /// <summary>
  35. /// Current Program State
  36. /// </summary>
  37. private ProgramState currentState;
  38. /// <summary>
  39. /// instance of FileImporter to handle drawing imports
  40. /// </summary>
  41. private FileImporter fileImporter;
  42. /// <summary>
  43. /// Dialog to select a file.
  44. /// </summary>
  45. OpenFileDialog openFileDialogLeft = new OpenFileDialog();
  46. /// <summary>
  47. /// Image loaded on the left
  48. /// </summary>
  49. private Image leftImage = null;
  50. /// <summary>
  51. /// the graphic shown in the left window, represented as a list of polylines
  52. /// </summary>
  53. private List<Line> templatePicture;
  54. /// <summary>
  55. /// Image on the right
  56. /// </summary>
  57. Image rightImage = null;
  58. /// <summary>
  59. /// Current Line being Drawn
  60. /// </summary>
  61. List<Point> currentLine;
  62. /// <summary>
  63. /// All Lines in the current session
  64. /// </summary>
  65. List<Tuple<bool,Line>> lineList = new List<Tuple<bool, Line>>();
  66. /// <summary>
  67. /// Whether the Mouse is currently pressed in the rightPictureBox
  68. /// </summary>
  69. bool mousePressed = false;
  70. /// <summary>
  71. /// The Position of the Cursor in the right picture box
  72. /// </summary>
  73. Point currentCursorPosition;
  74. /// <summary>
  75. /// The Previous Cursor Position in the right picture box
  76. /// </summary>
  77. Point previousCursorPosition;
  78. /// <summary>
  79. /// Queue for the cursorPositions
  80. /// </summary>
  81. Queue<Point> cursorPositions = new Queue<Point>();
  82. /// <summary>
  83. /// The graphic representation of the right image
  84. /// </summary>
  85. Graphics graph = null;
  86. /// <summary>
  87. /// Deletion Matrixes for checking postions of lines in the image
  88. /// </summary>
  89. bool[,] isFilledMatrix;
  90. HashSet<int>[,] linesMatrix;
  91. /// <summary>
  92. /// Size of deletion area
  93. /// </summary>
  94. uint deletionSize = 2;
  95. /// <summary>
  96. /// History of Actions
  97. /// </summary>
  98. ActionHistory historyOfActions;
  99. /******************************************/
  100. /*** FORM SPECIFIC FUNCTIONS START HERE ***/
  101. /******************************************/
  102. private void Form1_Load(object sender, EventArgs e)
  103. {
  104. currentState = ProgramState.Idle;
  105. this.DoubleBuffered = true;
  106. historyOfActions = new ActionHistory(null);
  107. UpdateButtonStatus();
  108. }
  109. //Resize Function connected to the form resize event, will refresh the form when it is resized
  110. private void Form1_Resize(object sender, System.EventArgs e)
  111. {
  112. this.Refresh();
  113. }
  114. //Load button, will open an OpenFileDialog
  115. private void loadToolStripMenuItem_Click(object sender, EventArgs e)
  116. {
  117. openFileDialogLeft.Filter = "Image|*.jpg;*.png;*.jpeg";
  118. if(openFileDialogLeft.ShowDialog() == DialogResult.OK)
  119. {
  120. toolStripLoadStatus.Text = openFileDialogLeft.SafeFileName;
  121. leftImage = Image.FromFile(openFileDialogLeft.FileName);
  122. pictureBoxLeft.Image = leftImage;
  123. //Refresh the left image box when the content is changed
  124. this.Refresh();
  125. }
  126. UpdateButtonStatus();
  127. }
  128. /// <summary>
  129. /// Import button, will open an OpenFileDialog
  130. /// </summary>
  131. private void examplePictureToolStripMenuItem_Click(object sender, EventArgs e)
  132. {
  133. openFileDialogLeft.Filter = "Interactive Sketch-Assistant Drawing|*.isad";
  134. if (openFileDialogLeft.ShowDialog() == DialogResult.OK)
  135. {
  136. toolStripLoadStatus.Text = openFileDialogLeft.SafeFileName;
  137. try
  138. {
  139. (int, int, List<Line>) values = fileImporter.ParseISADInput(openFileDialogLeft.FileName);
  140. DrawEmptyCanvasLeft(values.Item1, values.Item2);
  141. BindAndDrawLeftImage(values.Item3);
  142. this.Refresh();
  143. }
  144. catch(FileImporterException ex)
  145. {
  146. ShowInfoMessage(ex.ToString());
  147. }
  148. }
  149. }
  150. //Changes the state of the program to drawing
  151. private void drawButton_Click(object sender, EventArgs e)
  152. {
  153. if(rightImage != null)
  154. {
  155. if (currentState.Equals(ProgramState.Draw))
  156. {
  157. ChangeState(ProgramState.Idle);
  158. }
  159. else
  160. {
  161. ChangeState(ProgramState.Draw);
  162. }
  163. }
  164. UpdateButtonStatus();
  165. }
  166. //Changes the state of the program to deletion
  167. private void deleteButton_Click(object sender, EventArgs e)
  168. {
  169. if (rightImage != null)
  170. {
  171. if (currentState.Equals(ProgramState.Delete))
  172. {
  173. ChangeState(ProgramState.Idle);
  174. }
  175. else
  176. {
  177. ChangeState(ProgramState.Delete);
  178. }
  179. }
  180. UpdateButtonStatus();
  181. }
  182. //Undo an action
  183. private void undoButton_Click(object sender, EventArgs e)
  184. {
  185. if (historyOfActions.CanUndo())
  186. {
  187. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  188. SketchAction.ActionType undoAction = historyOfActions.GetCurrentAction().GetActionType();
  189. switch (undoAction)
  190. {
  191. case SketchAction.ActionType.Delete:
  192. //Deleted Lines need to be shown
  193. ChangeLines(affectedLines, true);
  194. break;
  195. case SketchAction.ActionType.Draw:
  196. //Drawn lines need to be hidden
  197. ChangeLines(affectedLines, false);
  198. break;
  199. default:
  200. break;
  201. }
  202. }
  203. historyOfActions.MoveAction(true);
  204. UpdateButtonStatus();
  205. }
  206. //Redo an action
  207. private void redoButton_Click(object sender, EventArgs e)
  208. {
  209. if (historyOfActions.CanRedo())
  210. {
  211. historyOfActions.MoveAction(false);
  212. HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
  213. SketchAction.ActionType redoAction = historyOfActions.GetCurrentAction().GetActionType();
  214. switch (redoAction)
  215. {
  216. case SketchAction.ActionType.Delete:
  217. //Deleted Lines need to be redeleted
  218. ChangeLines(affectedLines, false);
  219. break;
  220. case SketchAction.ActionType.Draw:
  221. //Drawn lines need to be redrawn
  222. ChangeLines(affectedLines, true);
  223. break;
  224. default:
  225. break;
  226. }
  227. }
  228. UpdateButtonStatus();
  229. }
  230. //Detect Keyboard Shortcuts
  231. private void Form1_KeyDown(object sender, KeyEventArgs e)
  232. {
  233. if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Z)
  234. {
  235. undoButton_Click(sender, e);
  236. }
  237. if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Y)
  238. {
  239. redoButton_Click(sender, e);
  240. }
  241. }
  242. //get current Mouse positon within the right picture box
  243. private void pictureBoxRight_MouseMove(object sender, MouseEventArgs e)
  244. {
  245. currentCursorPosition = ConvertCoordinates(new Point(e.X, e.Y));
  246. }
  247. //hold left mouse button to draw.
  248. private void pictureBoxRight_MouseDown(object sender, MouseEventArgs e)
  249. {
  250. mousePressed = true;
  251. if (currentState.Equals(ProgramState.Draw))
  252. {
  253. currentLine = new List<Point>();
  254. }
  255. }
  256. //Lift left mouse button to stop drawing and add a new Line.
  257. private void pictureBoxRight_MouseUp(object sender, MouseEventArgs e)
  258. {
  259. mousePressed = false;
  260. if (currentState.Equals(ProgramState.Draw) && currentLine.Count > 0)
  261. {
  262. Line newLine = new Line(currentLine, lineList.Count);
  263. lineList.Add(new Tuple<bool, Line>(true, newLine));
  264. newLine.PopulateMatrixes(isFilledMatrix, linesMatrix);
  265. historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Draw, newLine.GetID()));
  266. }
  267. UpdateButtonStatus();
  268. }
  269. //Button to create a new Canvas. Will create an empty image
  270. //which is the size of the left image, if there is one.
  271. //If there is no image loaded the canvas will be the size of the right picture box
  272. private void canvasButton_Click(object sender, EventArgs e)
  273. {
  274. if (!historyOfActions.IsEmpty())
  275. {
  276. if (MessageBox.Show("You have unsaved changes, creating a new canvas will discard these.",
  277. "Attention", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
  278. {
  279. historyOfActions = new ActionHistory(lastActionTakenLabel);
  280. DrawEmptyCanvas();
  281. //The following lines cannot be in DrawEmptyCanvas()
  282. isFilledMatrix = new bool[rightImage.Width, rightImage.Height];
  283. linesMatrix = new HashSet<int>[rightImage.Width, rightImage.Height];
  284. lineList = new List<Tuple<bool, Line>>();
  285. }
  286. }
  287. else
  288. {
  289. historyOfActions = new ActionHistory(lastActionTakenLabel);
  290. DrawEmptyCanvas();
  291. //The following lines cannot be in DrawEmptyCanvas()
  292. isFilledMatrix = new bool[rightImage.Width, rightImage.Height];
  293. linesMatrix = new HashSet<int>[rightImage.Width, rightImage.Height];
  294. lineList = new List<Tuple<bool, Line>>();
  295. }
  296. UpdateButtonStatus();
  297. }
  298. //add a Point on every tick to the Drawpath
  299. private void mouseTimer_Tick(object sender, EventArgs e)
  300. {
  301. cursorPositions.Enqueue(currentCursorPosition);
  302. previousCursorPosition = cursorPositions.Dequeue();
  303. if (currentState.Equals(ProgramState.Draw) && mousePressed)
  304. {
  305. currentLine.Add(currentCursorPosition);
  306. Line drawline = new Line(currentLine);
  307. drawline.DrawLine(graph);
  308. pictureBoxRight.Image = rightImage;
  309. }
  310. if (currentState.Equals(ProgramState.Delete) && mousePressed)
  311. {
  312. List<Point> uncheckedPoints = Line.BresenhamLineAlgorithm(previousCursorPosition, currentCursorPosition);
  313. foreach (Point currPoint in uncheckedPoints)
  314. {
  315. HashSet<int> linesToDelete = CheckDeletionMatrixesAroundPoint(currPoint, deletionSize);
  316. if (linesToDelete.Count > 0)
  317. {
  318. historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Delete, linesToDelete));
  319. foreach (int lineID in linesToDelete)
  320. {
  321. lineList[lineID] = new Tuple<bool, Line>(false, lineList[lineID].Item2);
  322. }
  323. RepopulateDeletionMatrixes();
  324. RedrawRightImage();
  325. }
  326. }
  327. }
  328. }
  329. /***********************************/
  330. /*** HELPER FUNCTIONS START HERE ***/
  331. /***********************************/
  332. /// <summary>
  333. /// Creates an empty Canvas
  334. /// </summary>
  335. private void DrawEmptyCanvas()
  336. {
  337. if (leftImage == null)
  338. {
  339. rightImage = new Bitmap(pictureBoxRight.Width, pictureBoxRight.Height);
  340. graph = Graphics.FromImage(rightImage);
  341. graph.FillRectangle(Brushes.White, 0, 0, pictureBoxRight.Width + 10, pictureBoxRight.Height + 10);
  342. pictureBoxRight.Image = rightImage;
  343. }
  344. else
  345. {
  346. rightImage = new Bitmap(leftImage.Width, leftImage.Height);
  347. graph = Graphics.FromImage(rightImage);
  348. graph.FillRectangle(Brushes.White, 0, 0, leftImage.Width + 10, leftImage.Height + 10);
  349. pictureBoxRight.Image = rightImage;
  350. }
  351. this.Refresh();
  352. pictureBoxRight.Refresh();
  353. }
  354. /// <summary>
  355. /// Creates an empty Canvas on the left
  356. /// </summary>
  357. /// <param name="width"> width of the new canvas in pixels </param>
  358. /// <param name="height"> height of the new canvas in pixels </param>
  359. private void DrawEmptyCanvasLeft(int width, int height)
  360. {
  361. if (width == 0)
  362. {
  363. leftImage = new Bitmap(pictureBoxLeft.Width, pictureBoxLeft.Height);
  364. }
  365. else
  366. {
  367. leftImage = new Bitmap(width, height);
  368. }
  369. Graphics.FromImage(leftImage).FillRectangle(Brushes.White, 0, 0, pictureBoxLeft.Width + 10, pictureBoxLeft.Height + 10);
  370. pictureBoxLeft.Image = leftImage;
  371. this.Refresh();
  372. pictureBoxLeft.Refresh();
  373. }
  374. /// <summary>
  375. /// Redraws all lines in lineList, for which their associated boolean value equals true.
  376. /// </summary>
  377. private void RedrawRightImage()
  378. {
  379. DrawEmptyCanvas();
  380. foreach (Tuple<bool, Line> lineBoolTuple in lineList)
  381. {
  382. if (lineBoolTuple.Item1)
  383. {
  384. lineBoolTuple.Item2.DrawLine(graph);
  385. }
  386. }
  387. pictureBoxRight.Refresh();
  388. }
  389. /// <summary>
  390. /// Change the status of whether or not the lines are shown.
  391. /// </summary>
  392. /// <param name="lines">The HashSet containing the affected Line IDs.</param>
  393. /// <param name="shown">True if the lines should be shown, false if they should be hidden.</param>
  394. private void ChangeLines(HashSet<int> lines, bool shown)
  395. {
  396. foreach (int lineId in lines)
  397. {
  398. if (lineId <= lineList.Count - 1 && lineId >= 0)
  399. {
  400. lineList[lineId] = new Tuple<bool, Line>(shown, lineList[lineId].Item2);
  401. }
  402. }
  403. RedrawRightImage();
  404. }
  405. /// <summary>
  406. /// Updates the active status of buttons. Currently draw, delete, undo and redo button.
  407. /// </summary>
  408. private void UpdateButtonStatus()
  409. {
  410. undoButton.Enabled = historyOfActions.CanUndo();
  411. redoButton.Enabled = historyOfActions.CanRedo();
  412. drawButton.Enabled = (rightImage != null);
  413. deleteButton.Enabled = (rightImage != null);
  414. }
  415. /// <summary>
  416. /// A helper function which handles tasks associated witch changing states,
  417. /// such as checking and unchecking buttons and changing the state.
  418. /// </summary>
  419. /// <param name="newState">The new state of the program</param>
  420. private void ChangeState(ProgramState newState)
  421. {
  422. switch (currentState)
  423. {
  424. case ProgramState.Draw:
  425. drawButton.CheckState = CheckState.Unchecked;
  426. mouseTimer.Enabled = false;
  427. break;
  428. case ProgramState.Delete:
  429. deleteButton.CheckState = CheckState.Unchecked;
  430. mouseTimer.Enabled = false;
  431. break;
  432. default:
  433. break;
  434. }
  435. switch (newState)
  436. {
  437. case ProgramState.Draw:
  438. drawButton.CheckState = CheckState.Checked;
  439. mouseTimer.Enabled = true;
  440. break;
  441. case ProgramState.Delete:
  442. deleteButton.CheckState = CheckState.Checked;
  443. mouseTimer.Enabled = true;
  444. break;
  445. default:
  446. break;
  447. }
  448. currentState = newState;
  449. pictureBoxRight.Refresh();
  450. }
  451. /// <summary>
  452. /// A function that calculates the coordinates of a point on a zoomed in image.
  453. /// </summary>
  454. /// <param name="">The position of the mouse cursor</param>
  455. /// <returns>The real coordinates of the mouse cursor on the image</returns>
  456. private Point ConvertCoordinates(Point cursorPosition)
  457. {
  458. Point realCoordinates = new Point(5,3);
  459. if(pictureBoxRight.Image == null)
  460. {
  461. return cursorPosition;
  462. }
  463. int widthImage = pictureBoxRight.Image.Width;
  464. int heightImage = pictureBoxRight.Image.Height;
  465. int widthBox = pictureBoxRight.Width;
  466. int heightBox = pictureBoxRight.Height;
  467. float imageRatio = (float)widthImage / (float)heightImage;
  468. float containerRatio = (float)widthBox / (float)heightBox;
  469. if (imageRatio >= containerRatio)
  470. {
  471. //Image is wider than it is high
  472. float zoomFactor = (float)widthImage / (float)widthBox;
  473. float scaledHeight = heightImage / zoomFactor;
  474. float filler = (heightBox - scaledHeight) / 2;
  475. realCoordinates.X = (int)(cursorPosition.X * zoomFactor);
  476. realCoordinates.Y = (int)((cursorPosition.Y - filler) * zoomFactor);
  477. }
  478. else
  479. {
  480. //Image is higher than it is wide
  481. float zoomFactor = (float)heightImage / (float)heightBox;
  482. float scaledWidth = widthImage / zoomFactor;
  483. float filler = (widthBox - scaledWidth) / 2;
  484. realCoordinates.X = (int)((cursorPosition.X - filler) * zoomFactor);
  485. realCoordinates.Y = (int)(cursorPosition.Y * zoomFactor);
  486. }
  487. return realCoordinates;
  488. }
  489. /// <summary>
  490. /// A function that populates the matrixes needed for deletion detection with line data.
  491. /// </summary>
  492. private void RepopulateDeletionMatrixes()
  493. {
  494. if(rightImage != null)
  495. {
  496. isFilledMatrix = new bool[rightImage.Width,rightImage.Height];
  497. linesMatrix = new HashSet<int>[rightImage.Width, rightImage.Height];
  498. foreach(Tuple<bool,Line> lineTuple in lineList)
  499. {
  500. if (lineTuple.Item1)
  501. {
  502. lineTuple.Item2.PopulateMatrixes(isFilledMatrix, linesMatrix);
  503. }
  504. }
  505. }
  506. }
  507. /// <summary>
  508. /// A function that checks the deletion matrixes at a certain point
  509. /// and returns all Line ids at that point and in a square around it in a certain range.
  510. /// </summary>
  511. /// <param name="p">The point around which to check.</param>
  512. /// <param name="range">The range around the point. If range is 0, only the point is checked.</param>
  513. /// <returns>A List of all lines.</returns>
  514. private HashSet<int> CheckDeletionMatrixesAroundPoint(Point p, uint range)
  515. {
  516. HashSet<int> returnSet = new HashSet<int>();
  517. if (p.X >= 0 && p.Y >= 0 && p.X < rightImage.Width && p.Y < rightImage.Height)
  518. {
  519. if (isFilledMatrix[p.X, p.Y])
  520. {
  521. returnSet.UnionWith(linesMatrix[p.X, p.Y]);
  522. }
  523. }
  524. for (int x_mod = (int)range*(-1); x_mod < range; x_mod++)
  525. {
  526. for (int y_mod = (int)range * (-1); y_mod < range; y_mod++)
  527. {
  528. if (p.X + x_mod >= 0 && p.Y + y_mod >= 0 && p.X + x_mod < rightImage.Width && p.Y + y_mod < rightImage.Height)
  529. {
  530. if (isFilledMatrix[p.X + x_mod, p.Y + y_mod])
  531. {
  532. returnSet.UnionWith(linesMatrix[p.X + x_mod, p.Y + y_mod]);
  533. }
  534. }
  535. }
  536. }
  537. return returnSet;
  538. }
  539. /// <summary>
  540. /// binds the given picture to templatePicture and draws it
  541. /// </summary>
  542. /// <param name="newTemplatePicture"> the new template picture, represented as a list of polylines </param>
  543. /// <returns></returns>
  544. private void BindAndDrawLeftImage(List<Line> newTemplatePicture)
  545. {
  546. templatePicture = newTemplatePicture;
  547. foreach(Line l in templatePicture)
  548. {
  549. l.DrawLine(Graphics.FromImage(leftImage));
  550. }
  551. }
  552. /// <summary>
  553. /// shows the given info message in a popup and asks the user to aknowledge it
  554. /// </summary>
  555. /// <param name="message">the message to show</param>
  556. private void ShowInfoMessage(String message)
  557. {
  558. MessageBox.Show(message);
  559. }
  560. }
  561. }