123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572 |
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using System.Text.RegularExpressions;
- // This is the code for your desktop app.
- // Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
- namespace SketchAssistant
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- fileImporter = new FileImporter(this);
- }
- /**********************************/
- /*** CLASS VARIABLES START HERE ***/
- /**********************************/
-
- //Different Program States
- public enum ProgramState
- {
- Idle,
- Draw,
- Delete
- }
- //Current Program State
- private ProgramState currentState;
- /// <summary>
- /// instance of FileImporter to handle drawing imports
- /// </summary>
- private FileImporter fileImporter;
- //Dialog to select a file.
- OpenFileDialog openFileDialogLeft = new OpenFileDialog();
- /// <summary>
- /// Image loaded on the left
- /// </summary>
- public Image leftImage { get; private set; } = null;
- /// <summary>
- /// the graphic shown in the left window, represented as a list of polylines
- /// </summary>
- public List<Line> templatePicture { get; private set; }
- //Image on the right
- Image rightImage = null;
- //Current Line being Drawn
- List<Point> currentLine;
- //All Lines in the current session
- List<Tuple<bool,Line>> lineList = new List<Tuple<bool, Line>>();
- //Whether the Mouse is currently pressed in the rightPictureBox
- bool mousePressed = false;
- //The Position of the Cursor in the right picture box
- Point currentCursorPosition;
- //The Previous Cursor Position in the right picture box
- Point previousCursorPosition;
- //Queue for the cursorPositions
- Queue<Point> cursorPositions = new Queue<Point>();
- //The graphic representation of the right image
- Graphics graph = null;
- //Deletion Matrixes for checking postions of lines in the image
- bool[,] isFilledMatrix;
- HashSet<int>[,] linesMatrix;
- //Size of deletion area
- uint deletionSize = 2;
- //History of Actions
- ActionHistory historyOfActions;
- /******************************************/
- /*** FORM SPECIFIC FUNCTIONS START HERE ***/
- /******************************************/
- private void Form1_Load(object sender, EventArgs e)
- {
- currentState = ProgramState.Idle;
- this.DoubleBuffered = true;
- historyOfActions = new ActionHistory(null);
- UpdateButtonStatus();
- }
- //Resize Function connected to the form resize event, will refresh the form when it is resized
- private void Form1_Resize(object sender, System.EventArgs e)
- {
- this.Refresh();
- }
-
- //Load button, will open an OpenFileDialog
- private void loadToolStripMenuItem_Click(object sender, EventArgs e)
- {
- openFileDialogLeft.Filter = "Image|*.jpg;*.png;*.jpeg";
- if(openFileDialogLeft.ShowDialog() == DialogResult.OK)
- {
- toolStripLoadStatus.Text = openFileDialogLeft.SafeFileName;
- leftImage = Image.FromFile(openFileDialogLeft.FileName);
- pictureBoxLeft.Image = leftImage;
- //Refresh the left image box when the content is changed
- this.Refresh();
- }
- UpdateButtonStatus();
- }
- /// <summary>
- /// Import button, will open an OpenFileDialog
- /// </summary>
- private void examplePictureToolStripMenuItem_Click(object sender, EventArgs e)
- {
- openFileDialogLeft.Filter = "Interactive Sketch-Assistant Drawing|*.isad";
- if (openFileDialogLeft.ShowDialog() == DialogResult.OK)
- {
- toolStripLoadStatus.Text = openFileDialogLeft.SafeFileName;
- try
- {
- (int, int, List<Line>) values = fileImporter.ParseISADInput(openFileDialogLeft.FileName);
- DrawEmptyCanvasLeft(values.Item1, values.Item2);
- BindAndDrawLeftImage(values.Item3);
- this.Refresh();
- }
- catch(FileImporterException ex)
- {
- ShowInfoMessage(ex.ToString());
- }
- }
- }
- //Changes the state of the program to drawing
- private void drawButton_Click(object sender, EventArgs e)
- {
- if(rightImage != null)
- {
- if (currentState.Equals(ProgramState.Draw))
- {
- ChangeState(ProgramState.Idle);
- }
- else
- {
- ChangeState(ProgramState.Draw);
- }
- }
- UpdateButtonStatus();
- }
- //Changes the state of the program to deletion
- private void deleteButton_Click(object sender, EventArgs e)
- {
- if (rightImage != null)
- {
- if (currentState.Equals(ProgramState.Delete))
- {
- ChangeState(ProgramState.Idle);
- }
- else
- {
- ChangeState(ProgramState.Delete);
- }
- }
- UpdateButtonStatus();
- }
- //Undo an action
- private void undoButton_Click(object sender, EventArgs e)
- {
- if (historyOfActions.CanUndo())
- {
- HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
- SketchAction.ActionType undoAction = historyOfActions.GetCurrentAction().GetActionType();
- switch (undoAction)
- {
- case SketchAction.ActionType.Delete:
- //Deleted Lines need to be shown
- ChangeLines(affectedLines, true);
- break;
- case SketchAction.ActionType.Draw:
- //Drawn lines need to be hidden
- ChangeLines(affectedLines, false);
- break;
- default:
- break;
- }
- }
- historyOfActions.MoveAction(true);
- UpdateButtonStatus();
- }
- //Redo an action
- private void redoButton_Click(object sender, EventArgs e)
- {
- if (historyOfActions.CanRedo())
- {
- historyOfActions.MoveAction(false);
- HashSet<int> affectedLines = historyOfActions.GetCurrentAction().GetLineIDs();
- SketchAction.ActionType redoAction = historyOfActions.GetCurrentAction().GetActionType();
- switch (redoAction)
- {
- case SketchAction.ActionType.Delete:
- //Deleted Lines need to be redeleted
- ChangeLines(affectedLines, false);
- break;
- case SketchAction.ActionType.Draw:
- //Drawn lines need to be redrawn
- ChangeLines(affectedLines, true);
- break;
- default:
- break;
- }
- }
- UpdateButtonStatus();
- }
- //Detect Keyboard Shortcuts
- private void Form1_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Z)
- {
- undoButton_Click(sender, e);
- }
- if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Y)
- {
- redoButton_Click(sender, e);
- }
- }
- //get current Mouse positon within the right picture box
- private void pictureBoxRight_MouseMove(object sender, MouseEventArgs e)
- {
- currentCursorPosition = ConvertCoordinates(new Point(e.X, e.Y));
- }
- //hold left mouse button to draw.
- private void pictureBoxRight_MouseDown(object sender, MouseEventArgs e)
- {
- mousePressed = true;
- if (currentState.Equals(ProgramState.Draw))
- {
- currentLine = new List<Point>();
- }
- }
- //Lift left mouse button to stop drawing and add a new Line.
- private void pictureBoxRight_MouseUp(object sender, MouseEventArgs e)
- {
- mousePressed = false;
- if (currentState.Equals(ProgramState.Draw) && currentLine.Count > 0)
- {
- Line newLine = new Line(currentLine, lineList.Count);
- lineList.Add(new Tuple<bool, Line>(true, newLine));
- newLine.PopulateMatrixes(isFilledMatrix, linesMatrix);
- historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Draw, newLine.GetID()));
- }
- UpdateButtonStatus();
- }
- //Button to create a new Canvas. Will create an empty image
- //which is the size of the left image, if there is one.
- //If there is no image loaded the canvas will be the size of the right picture box
- private void canvasButton_Click(object sender, EventArgs e)
- {
- if (!historyOfActions.IsEmpty())
- {
- if (MessageBox.Show("You have unsaved changes, creating a new canvas will discard these.",
- "Attention", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
- {
- historyOfActions = new ActionHistory(lastActionTakenLabel);
- DrawEmptyCanvas();
- //The following lines cannot be in DrawEmptyCanvas()
- isFilledMatrix = new bool[rightImage.Width, rightImage.Height];
- linesMatrix = new HashSet<int>[rightImage.Width, rightImage.Height];
- lineList = new List<Tuple<bool, Line>>();
- }
- }
- else
- {
- historyOfActions = new ActionHistory(lastActionTakenLabel);
- DrawEmptyCanvas();
- //The following lines cannot be in DrawEmptyCanvas()
- isFilledMatrix = new bool[rightImage.Width, rightImage.Height];
- linesMatrix = new HashSet<int>[rightImage.Width, rightImage.Height];
- lineList = new List<Tuple<bool, Line>>();
- }
- UpdateButtonStatus();
- }
- //add a Point on every tick to the Drawpath
- private void mouseTimer_Tick(object sender, EventArgs e)
- {
- cursorPositions.Enqueue(currentCursorPosition);
- previousCursorPosition = cursorPositions.Dequeue();
- if (currentState.Equals(ProgramState.Draw) && mousePressed)
- {
- currentLine.Add(currentCursorPosition);
- Line drawline = new Line(currentLine);
- drawline.DrawLine(graph);
- pictureBoxRight.Image = rightImage;
- }
- if (currentState.Equals(ProgramState.Delete) && mousePressed)
- {
- List<Point> uncheckedPoints = Line.BresenhamLineAlgorithm(previousCursorPosition, currentCursorPosition);
- foreach (Point currPoint in uncheckedPoints)
- {
- HashSet<int> linesToDelete = CheckDeletionMatrixesAroundPoint(currPoint, deletionSize);
- if (linesToDelete.Count > 0)
- {
- historyOfActions.AddNewAction(new SketchAction(SketchAction.ActionType.Delete, linesToDelete));
- foreach (int lineID in linesToDelete)
- {
- lineList[lineID] = new Tuple<bool, Line>(false, lineList[lineID].Item2);
- }
- RepopulateDeletionMatrixes();
- RedrawRightImage();
- }
- }
- }
- }
- /***********************************/
- /*** HELPER FUNCTIONS START HERE ***/
- /***********************************/
- /// <summary>
- /// Creates an empty Canvas
- /// </summary>
- private void DrawEmptyCanvas()
- {
- if (leftImage == null)
- {
- rightImage = new Bitmap(pictureBoxRight.Width, pictureBoxRight.Height);
- graph = Graphics.FromImage(rightImage);
- graph.FillRectangle(Brushes.White, 0, 0, pictureBoxRight.Width + 10, pictureBoxRight.Height + 10);
- pictureBoxRight.Image = rightImage;
- }
- else
- {
- rightImage = new Bitmap(leftImage.Width, leftImage.Height);
- graph = Graphics.FromImage(rightImage);
- graph.FillRectangle(Brushes.White, 0, 0, leftImage.Width + 10, leftImage.Height + 10);
- pictureBoxRight.Image = rightImage;
- }
- this.Refresh();
- pictureBoxRight.Refresh();
- }
- /// <summary>
- /// Creates an empty Canvas on the left
- /// </summary>
- /// <param name="width"> width of the new canvas in pixels </param>
- /// <param name="height"> height of the new canvas in pixels </param>
- private void DrawEmptyCanvasLeft(int width, int height)
- {
- if (width == 0)
- {
- leftImage = new Bitmap(pictureBoxLeft.Width, pictureBoxLeft.Height);
- }
- else
- {
- leftImage = new Bitmap(width, height);
- }
- Graphics.FromImage(leftImage).FillRectangle(Brushes.White, 0, 0, pictureBoxLeft.Width + 10, pictureBoxLeft.Height + 10);
- pictureBoxLeft.Image = leftImage;
-
- this.Refresh();
- pictureBoxLeft.Refresh();
- }
- /// <summary>
- /// Redraws all lines in lineList, for which their associated boolean value equals true.
- /// </summary>
- private void RedrawRightImage()
- {
- DrawEmptyCanvas();
- foreach (Tuple<bool, Line> lineBoolTuple in lineList)
- {
- if (lineBoolTuple.Item1)
- {
- lineBoolTuple.Item2.DrawLine(graph);
- }
- }
- pictureBoxRight.Refresh();
- }
- /// <summary>
- /// Change the status of whether or not the lines are shown.
- /// </summary>
- /// <param name="lines">The HashSet containing the affected Line IDs.</param>
- /// <param name="shown">True if the lines should be shown, false if they should be hidden.</param>
- private void ChangeLines(HashSet<int> lines, bool shown)
- {
- foreach (int lineId in lines)
- {
- if (lineId <= lineList.Count - 1 && lineId >= 0)
- {
- lineList[lineId] = new Tuple<bool, Line>(shown, lineList[lineId].Item2);
- }
- }
- RedrawRightImage();
- }
- /// <summary>
- /// Updates the active status of buttons. Currently draw, delete, undo and redo button.
- /// </summary>
- private void UpdateButtonStatus()
- {
- undoButton.Enabled = historyOfActions.CanUndo();
- redoButton.Enabled = historyOfActions.CanRedo();
- drawButton.Enabled = (rightImage != null);
- deleteButton.Enabled = (rightImage != null);
- }
- /// <summary>
- /// A helper function which handles tasks associated witch changing states,
- /// such as checking and unchecking buttons and changing the state.
- /// </summary>
- /// <param name="newState">The new state of the program</param>
- private void ChangeState(ProgramState newState)
- {
- switch (currentState)
- {
- case ProgramState.Draw:
- drawButton.CheckState = CheckState.Unchecked;
- mouseTimer.Enabled = false;
- break;
- case ProgramState.Delete:
- deleteButton.CheckState = CheckState.Unchecked;
- mouseTimer.Enabled = false;
- break;
- default:
- break;
- }
- switch (newState)
- {
- case ProgramState.Draw:
- drawButton.CheckState = CheckState.Checked;
- mouseTimer.Enabled = true;
- break;
- case ProgramState.Delete:
- deleteButton.CheckState = CheckState.Checked;
- mouseTimer.Enabled = true;
- break;
- default:
- break;
- }
- currentState = newState;
- pictureBoxRight.Refresh();
- }
- /// <summary>
- /// A function that calculates the coordinates of a point on a zoomed in image.
- /// </summary>
- /// <param name="">The position of the mouse cursor</param>
- /// <returns>The real coordinates of the mouse cursor on the image</returns>
- private Point ConvertCoordinates(Point cursorPosition)
- {
- Point realCoordinates = new Point(5,3);
- if(pictureBoxRight.Image == null)
- {
- return cursorPosition;
- }
- int widthImage = pictureBoxRight.Image.Width;
- int heightImage = pictureBoxRight.Image.Height;
- int widthBox = pictureBoxRight.Width;
- int heightBox = pictureBoxRight.Height;
- float imageRatio = (float)widthImage / (float)heightImage;
- float containerRatio = (float)widthBox / (float)heightBox;
- if (imageRatio >= containerRatio)
- {
- //Image is wider than it is high
- float zoomFactor = (float)widthImage / (float)widthBox;
- float scaledHeight = heightImage / zoomFactor;
- float filler = (heightBox - scaledHeight) / 2;
- realCoordinates.X = (int)(cursorPosition.X * zoomFactor);
- realCoordinates.Y = (int)((cursorPosition.Y - filler) * zoomFactor);
- }
- else
- {
- //Image is higher than it is wide
- float zoomFactor = (float)heightImage / (float)heightBox;
- float scaledWidth = widthImage / zoomFactor;
- float filler = (widthBox - scaledWidth) / 2;
- realCoordinates.X = (int)((cursorPosition.X - filler) * zoomFactor);
- realCoordinates.Y = (int)(cursorPosition.Y * zoomFactor);
- }
- return realCoordinates;
- }
- /// <summary>
- /// A function that populates the matrixes needed for deletion detection with line data.
- /// </summary>
- private void RepopulateDeletionMatrixes()
- {
- if(rightImage != null)
- {
- isFilledMatrix = new bool[rightImage.Width,rightImage.Height];
- linesMatrix = new HashSet<int>[rightImage.Width, rightImage.Height];
- foreach(Tuple<bool,Line> lineTuple in lineList)
- {
- if (lineTuple.Item1)
- {
- lineTuple.Item2.PopulateMatrixes(isFilledMatrix, linesMatrix);
- }
- }
- }
- }
- /// <summary>
- /// A function that checks the deletion matrixes at a certain point
- /// and returns all Line ids at that point and in a square around it in a certain range.
- /// </summary>
- /// <param name="p">The point around which to check.</param>
- /// <param name="range">The range around the point. If range is 0, only the point is checked.</param>
- /// <returns>A List of all lines.</returns>
- private HashSet<int> CheckDeletionMatrixesAroundPoint(Point p, uint range)
- {
- HashSet<int> returnSet = new HashSet<int>();
- if (p.X >= 0 && p.Y >= 0 && p.X < rightImage.Width && p.Y < rightImage.Height)
- {
- if (isFilledMatrix[p.X, p.Y])
- {
- returnSet.UnionWith(linesMatrix[p.X, p.Y]);
- }
- }
- for (int x_mod = (int)range*(-1); x_mod < range; x_mod++)
- {
- for (int y_mod = (int)range * (-1); y_mod < range; y_mod++)
- {
- if (p.X + x_mod >= 0 && p.Y + y_mod >= 0 && p.X + x_mod < rightImage.Width && p.Y + y_mod < rightImage.Height)
- {
- if (isFilledMatrix[p.X + x_mod, p.Y + y_mod])
- {
- returnSet.UnionWith(linesMatrix[p.X + x_mod, p.Y + y_mod]);
- }
- }
- }
- }
- return returnSet;
- }
- /// <summary>
- /// checks that all lines of the given picture are inside the constraints of the left canvas and binds it to templatePicture
- /// </summary>
- /// <param name="newTemplatePicture"> the new template picture, represented as a list of polylines </param>
- /// <returns></returns>
- private void BindAndDrawLeftImage(List<Line> newTemplatePicture)
- {
- templatePicture = newTemplatePicture;
- foreach(Line l in templatePicture)
- {
- l.DrawLine(Graphics.FromImage(leftImage));
- }
- }
- /// <summary>
- /// shows the given info message in a popup and asks the user to aknowledge it
- /// </summary>
- /// <param name="message">the message to show</param>
- private void ShowInfoMessage(String message)
- {
- MessageBox.Show(message);
- }
- }
- }
|