Form1.cs 20 KB

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