Form1.cs 19 KB

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