Advertisement
Guest User

Form1.cs

a guest
Dec 10th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 16.72 KB | None | 0 0
  1. using Figures;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Drawing;
  5. using System.Dynamic;
  6. using System.Linq;
  7. using System.Windows.Forms;
  8.  
  9. namespace Polygons
  10. {
  11.     public partial class Form1 : Form, IOriginator
  12.     {
  13.         private Type _newFigureShape = typeof(Circle);
  14.         private readonly ConvexPolygon _polygon = new ConvexPolygon();
  15.         private readonly Random _rand = new Random();
  16.         private readonly Timer _dynamicsTimer = new Timer { Interval = 40 };
  17.        
  18.         #region Init
  19.         public Form1()
  20.         {
  21.             InitializeComponent();
  22.             AllowDrop = true;
  23.             KeyPreview = true;
  24.  
  25.             //shapeToolStripMenuItem.Ke += Form1_KeyDown;
  26.             //foreach (ToolStripItem i in shapeMenuStrip.Items)
  27.                 //i. += (_, __) => tmp();//Convert<KeyDownEventHandler, PreviewKeyDownEventHandler>(Form1_KeyDown);
  28.  
  29.             _dynamicsTimer.Tick += (_, __) => Refresh();
  30.  
  31.             PluginManager.MemorisePlugin(typeof(Circle));
  32.  
  33.             try
  34.             {
  35.                 PluginManager.LoadFromDirectory(Environment.CurrentDirectory + @"\Plugins", "*.dll");
  36.             }
  37.             catch (Exception exc)
  38.             {
  39.                 MessageBox.Show(exc.Message);
  40.             }
  41.  
  42.             PlugInit(PluginManager.GetTypes().ToArray());
  43.             (shapeToolStripMenuItem.DropDownItems[0] as ToolStripMenuItem).Checked = true;
  44.         }
  45.  
  46.         public ToolStripMenuItem CreateMenuItem(Type type)
  47.         {
  48.             if (type == null) throw new ArgumentNullException(nameof(type));
  49.             var newMenuItem = new ToolStripMenuItem(type.Name);
  50.             newMenuItem.Name = type.Name;
  51.  
  52.             newMenuItem.Click += (_, __) =>
  53.             {
  54.                 #region check mark
  55.                 var history = new List<ICommand>();
  56.                 foreach (ToolStripMenuItem item in shapeToolStripMenuItem.DropDownItems)
  57.                 {
  58.                     if (item.Checked)
  59.                     {
  60.                         item.Checked = false;
  61.                         history.Add(new MenuItemUnchecked(item.Name));
  62.                     }
  63.                 }
  64.  
  65.                 var tmp = shapeToolStripMenuItem.DropDownItems[shapeToolStripMenuItem.DropDownItems.IndexOf(newMenuItem)] as ToolStripMenuItem;
  66.                 tmp.Checked = true;
  67.                 history.Add(new MenuItemChecked(newMenuItem.Name));
  68.  
  69.                 HistoryManager.Add(history.ToArray());
  70.                 #endregion
  71.  
  72.                 _newFigureShape = type;
  73.             };
  74.             return newMenuItem;
  75.         }
  76.  
  77.         private void PlugInit(params Type[] classes)
  78.         {
  79.             foreach (Type NewClass in classes)
  80.                 shapeToolStripMenuItem.DropDownItems.Add(CreateMenuItem(NewClass));
  81.         }
  82.         #endregion
  83.  
  84.         #region Events
  85.         private void Form1_FormClosed(object sender, FormClosedEventArgs e)
  86.         {
  87.             _dynamicsTimer.Dispose();
  88.             Application.Exit();
  89.         }
  90.  
  91.         private void Form1_KeyDown(object sender, KeyEventArgs e)
  92.         {
  93.             if (e.Control)
  94.             {
  95.                 if (e.KeyCode == Keys.Z)
  96.                 {
  97.                     if (e.Shift && HistoryManager.RedoCount > 0)
  98.                         HistoryManager.Redo(this, _polygon);
  99.                     else if (!e.Shift && HistoryManager.UndoCount > 0)
  100.                         HistoryManager.Undo(this, _polygon);
  101.                     _polygon.ConvexHull();
  102.                     Refresh();
  103.                 }
  104.             }
  105.         }
  106.  
  107.         private void Form1_DragDrop(object sender, DragEventArgs e)
  108.         {
  109.             string[] files = e.Data.GetData(DataFormats.FileDrop, false) as string[];
  110.             List<Type> exportedTypes = new List<Type>();
  111.  
  112.             foreach (string file in files)
  113.             {
  114.                 var extension = System.IO.Path.GetExtension(file);
  115.                 if (!extension.Equals(".dll", StringComparison.CurrentCultureIgnoreCase))
  116.                 {
  117.                     MessageBox.Show("Wrong Plugin: please drop .dll file!");
  118.                     return;
  119.                 }
  120.                 try
  121.                 {
  122.                     exportedTypes.AddRange(PluginManager.LoadFile(file));
  123.                 }
  124.                 catch (Exception exc)
  125.                 {
  126.                     MessageBox.Show(exc.Message);
  127.                 }
  128.             }
  129.             foreach (var plugin in exportedTypes)
  130.             {
  131.                 if (plugin.FullName.Contains("Figures"))
  132.                 {
  133.                     PlugInit(plugin);
  134.                     HistoryManager.Add(new PluginAdd(plugin, plugin.Name)); // !!! already exist error
  135.                 }
  136.                 else
  137.                 {
  138.                     MessageBox.Show("Error: plugin named \"{0}\" is not compartible!", plugin.Name);
  139.                     //PluginManager. // delete plugin
  140.                 }
  141.             }
  142.         }
  143.        
  144.         private void Form1_DragEnter(object sender, DragEventArgs e)
  145.         {
  146.             if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
  147.                 e.Effect = DragDropEffects.Link;
  148.         }
  149.  
  150.         private void Form1_Paint(object sender, PaintEventArgs e)
  151.         {
  152.             e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  153.             if (_dynamicsTimer.Enabled)
  154.                 _polygon.Draw(e.Graphics, _rand);
  155.             else
  156.                 _polygon.Draw(e.Graphics);
  157.         }
  158.  
  159.         private void DynamicsButton_Click(object sender, EventArgs e) // динамика
  160.         {
  161.             _dynamicsTimer.Enabled = !_dynamicsTimer.Enabled;
  162.             //_rand = (_rand ?? new Random());
  163.             dynamicsButton.Refresh();
  164.         }
  165.  
  166.         private void DynamicsButton_Paint(object sender, PaintEventArgs e)
  167.         {
  168.             e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  169.             Point center = new Point(dynamicsButton.Width / 2, dynamicsButton.Height / 2);
  170.             int r = dynamicsButton.Width / 2 * 6 / 10;
  171.             if (_dynamicsTimer.Enabled)
  172.                 e.Graphics.FillRectangle(new SolidBrush(Color.Red), center.X - r, center.Y - r, r * 2, r * 2);
  173.             else
  174.                 e.Graphics.FillPolygon(new SolidBrush(Color.Green), new PointF[]
  175.                 {
  176.                     new PointF((float)(center.X - Math.Sqrt(3) * r / 2), center.Y - r),
  177.                     new PointF(center.X + r, center.Y),
  178.                     new PointF((float)(center.X - Math.Sqrt(3) * r / 2), center.Y + r)
  179.                 });
  180.         }
  181.        
  182.         private static Color ChooseColor(Color StartColor)
  183.         {
  184.             ColorDialog ChooseColorDialog = new ColorDialog
  185.             {
  186.                 Color = StartColor,
  187.                 FullOpen = true // расширенное окно для выбора цвета
  188.             };
  189.  
  190.  
  191.             if (ChooseColorDialog.ShowDialog() == DialogResult.OK)
  192.                 StartColor = ChooseColorDialog.Color;
  193.             ChooseColorDialog.Dispose();
  194.             return StartColor;
  195.         }
  196.  
  197.         #region Mouse events
  198.         private void Form1_MouseMove(object sender, MouseEventArgs e)
  199.         {
  200.             //if (_polygon.DragAndDrop)
  201.             if (DragAndDropManager.Dropping)
  202.             {
  203.                 //_polygon.DragAndDropCheck(e.Location);
  204.                 DragAndDropManager.Tick(e.Location);
  205.                 Refresh();
  206.             }
  207.         }
  208.  
  209.         private void Form1_MouseUp(object sender, MouseEventArgs e)
  210.         {
  211.             if (DragAndDropManager.Dropping)
  212.             {
  213.                 var history = (from i in DragAndDropManager.StartPositions.Zip(DragAndDropManager.DragObjects, (pos, obj) => (pos, obj))
  214.                               select (IPolygonCommand)new VertexPositionChanged(i.pos, i.obj)).ToList();
  215.  
  216.                 DragAndDropManager.Stop();
  217.                 var result = _polygon.ConvexHull(history).ToArray();
  218.                 if (result.Length > 0)
  219.                     HistoryManager.Add(result);
  220.             }
  221.  
  222.             Refresh();
  223.         }
  224.  
  225.         private void Form1_MouseDown(object sender, MouseEventArgs e)
  226.         {
  227.             if (e.Button == MouseButtons.Left)
  228.             {
  229.                 var clickedVertices = _polygon.CheckVertices(e.Location);
  230.                 if (clickedVertices.Count > 0)
  231.                     DragAndDropManager.Start(e.Location, clickedVertices);
  232.                 else if (_polygon.Check(e.Location))
  233.                     DragAndDropManager.Start(e.Location, _polygon.Vertices);
  234.                 else
  235.                 {
  236.                     var command = new VertexAdd((Vertex)Activator.CreateInstance(_newFigureShape, e.X, e.Y));
  237.                     command.Do(_polygon);
  238.                     HistoryManager.Add(_polygon.ConvexHull(new List<IPolygonCommand>() { command }).ToArray());
  239.                 }
  240.             }
  241.             else
  242.             {
  243.                 var history = _polygon.RemoveRange(_polygon.CheckVertices(e.Location)).ToArray();
  244.                 if (history.Length > 0)
  245.                     HistoryManager.Add(history);
  246.             }
  247.  
  248.             Refresh();
  249.         }
  250.         #endregion
  251.         #endregion
  252.         // Todo: Undo/Redo for menu items
  253.         // Todo: Undo/Redo for hotplug
  254.         #region Memento
  255.         public void SetMemento(in IMemento memento)
  256.         {
  257.             if (memento == null) throw new ArgumentNullException("memento");
  258.  
  259.             dynamic state = (memento as Form1Memento).GetState();
  260.             _polygon.SetMemento(state.PolygonMemento as IMemento);
  261.             _newFigureShape = state.Type;
  262.             BackColor = state.BackColor;
  263.  
  264.             shapeToolStripMenuItem.DropDownItems.Clear();
  265.             shapeToolStripMenuItem.Checked = false;
  266.  
  267.             PlugInit((state.FigureTypes as IEnumerable<Type>).ToArray());
  268.             (shapeToolStripMenuItem.DropDownItems[state.CheckedMenuItemIndex] as ToolStripMenuItem).Checked = true;
  269.         }
  270.  
  271.         public IMemento CreateMemento()
  272.         {
  273.             int checkedMenuItemIndex = -1;
  274.             for (int i = 0; i < shapeToolStripMenuItem.DropDownItems.Count && checkedMenuItemIndex == -1; ++i)
  275.             {
  276.                 if ((shapeToolStripMenuItem.DropDownItems[i] as ToolStripMenuItem).Checked)
  277.                     checkedMenuItemIndex = i;
  278.             }
  279.             return new Form1Memento(_polygon.CreateMemento() as PolygonMemento, _newFigureShape, BackColor, PluginManager.GetTypes(), checkedMenuItemIndex, null); //, HistoryManager.);
  280.         }
  281.         #endregion
  282.  
  283.         #region StripMenus
  284.         #region Color
  285.         private void ColorStripMenuVertices_Click(object sender, EventArgs e)
  286.         {
  287.             var NewColor = ChooseColor(_polygon.VertexColor);
  288.             HistoryManager.Add(new VertexColorChanged(_polygon.VertexColor, NewColor));
  289.             _polygon.VertexColor = NewColor;
  290.  
  291.             Refresh();
  292.         }
  293.  
  294.         private void ColorStripMenuLines_Click(object sender, EventArgs e)
  295.         {
  296.             var NewColor = ChooseColor(_polygon.LineColor);
  297.             HistoryManager.Add(new LineColorChanged(_polygon.LineColor, NewColor));
  298.             _polygon.LineColor = NewColor;
  299.  
  300.             Refresh();
  301.         }
  302.  
  303.         private void ColorStripMenuBackground_Click(object sender, EventArgs e)
  304.         {
  305.             var NewColor = ChooseColor(BackColor);
  306.             HistoryManager.Add(new BackgroundColorChanged(BackColor, NewColor));
  307.             BackColor = NewColor;
  308.  
  309.             Refresh();
  310.         }
  311.         #endregion
  312.         #region Resize
  313.         private void ResizeStripMenuVertices_Click(object sender, EventArgs e)
  314.         {
  315.             int _originalVertexRadius = _polygon.VertexRadius;
  316.             var ResizeBar = new TrackBar
  317.             {
  318.                 Name = "ResizeBar", // Todo: remove?
  319.                 Minimum = 5,
  320.                 Maximum = 150,
  321.                 Value = _polygon.VertexRadius,
  322.                 Orientation = Orientation.Horizontal,
  323.                 TickStyle = TickStyle.None,
  324.                 Location = new Point(0, 0),
  325.                 Width = 400
  326.             };
  327.             ResizeBar.Scroll += (_, __) => { _polygon.VertexRadius = ResizeBar.Value; Refresh(); };
  328.             ResizeBar.MouseDown += (_, __) => _originalVertexRadius = _polygon.VertexRadius;
  329.             ResizeBar.MouseUp += (_, __) =>
  330.             {
  331.                 if (ResizeBar.Value != _originalVertexRadius)
  332.                     HistoryManager.Add(new VertexRadiusChanged(_originalVertexRadius, ResizeBar.Value));
  333.             };
  334.  
  335.             var SizeForm = new Form
  336.             {
  337.                 ClientSize = new Size(ResizeBar.Width, ResizeBar.Height),
  338.                 FormBorderStyle = FormBorderStyle.FixedSingle,
  339.                 Text = "Vertices Radius Changer",
  340.                 MinimizeBox = false,
  341.                 MaximizeBox = false,
  342.                 Visible = true,
  343.                 KeyPreview = true
  344.             };
  345.             SizeForm.Controls.Add(ResizeBar);
  346.             SizeForm.KeyDown += Form1_KeyDown;
  347.             SizeForm.Deactivate += (_, __) => { SizeForm.Close(); SizeForm.Dispose(); };
  348.         }
  349.  
  350.         private void ResizeStripMenuLines_Click(object sender, EventArgs e)
  351.         {
  352.             int _originalLineWidth = _polygon.LineWidth;
  353.             var ResizeBar = new TrackBar
  354.             {
  355.  
  356.                 Name = "ResizeBar", // Todo: remove?
  357.                 Minimum = 1,
  358.                 Maximum = 60,
  359.                 Value = _polygon.LineWidth,
  360.                 Orientation = Orientation.Horizontal,
  361.                 TickStyle = TickStyle.None,
  362.                 Location = new Point(0, 0),
  363.                 Width = 400,
  364.  
  365.             };
  366.             ResizeBar.Scroll += (_, __) => { _polygon.LineWidth = ResizeBar.Value; Refresh(); };
  367.             ResizeBar.MouseDown += (_, __) => _originalLineWidth = _polygon.LineWidth;
  368.             ResizeBar.MouseUp += (_, __) =>
  369.             {
  370.                 if (ResizeBar.Value != _originalLineWidth)
  371.                     HistoryManager.Add(new LineWidthChanged(_originalLineWidth, ResizeBar.Value));
  372.             };
  373.  
  374.             var SizeForm = new Form
  375.             {
  376.                 ClientSize = new Size(ResizeBar.Width, ResizeBar.Height),
  377.                 FormBorderStyle = FormBorderStyle.FixedSingle,
  378.                 Text = "Hull Thickness Changer", // Todo: replace with "Lines ..."
  379.                 MinimizeBox = false,
  380.                 MaximizeBox = false,
  381.                 Visible = true,
  382.                 KeyPreview = true
  383.             };
  384.             SizeForm.Controls.Add(ResizeBar);
  385.             SizeForm.KeyDown += Form1_KeyDown;
  386.             SizeForm.Deactivate += (_, __) => { SizeForm.Close(); SizeForm.Dispose(); };
  387.         }
  388.         #endregion
  389.         #region Save/Load
  390.         private void FileStripMenuSave_Click(object sender, EventArgs e)
  391.         {
  392.             SaveLoadManager.Save(CreateMemento());
  393.         }
  394.  
  395.         private void FileStripMenuLoad_Click(object sender, EventArgs e)
  396.         {
  397.             var memento = SaveLoadManager.Load();
  398.             if (memento != null)
  399.                 SetMemento(memento as Form1Memento);
  400.         }
  401.         #endregion
  402.         #endregion
  403.  
  404.         public ToolStripItemCollection GetMenuItems()
  405.         {
  406.             return shapeToolStripMenuItem.DropDownItems;
  407.         }
  408.     }
  409.  
  410.     [Serializable]
  411.     public class Form1Memento : IMemento
  412.     {
  413.  
  414.         private readonly PolygonMemento _polygonMemento;
  415.         private readonly Type _type;
  416.         private readonly Color _backColor;
  417.         private readonly IEnumerable<Type> _figureTypes;
  418.         private readonly int _checkedMenuItemIndex;
  419.         private readonly IEnumerable<ICommand> _history;
  420.  
  421.         public Form1Memento(in PolygonMemento polygonMemento, in Type type, in Color backColor, in IEnumerable<Type> figureTypes, in int checkedMenuItemIndex, in IEnumerable<ICommand> history)
  422.         {
  423.             _polygonMemento = polygonMemento ?? throw new ArgumentNullException("polygonMemento");
  424.             _type = type ?? throw new ArgumentNullException("type");
  425.             _figureTypes = figureTypes ?? throw new ArgumentNullException("figureTypes");
  426.             _backColor = backColor;
  427.             _checkedMenuItemIndex = checkedMenuItemIndex;
  428.             _history = history;
  429.         }
  430.  
  431.         public ExpandoObject GetState()
  432.         {
  433.             dynamic state = new ExpandoObject();
  434.  
  435.             state.PolygonMemento = _polygonMemento;
  436.             state.Type = _type;
  437.             state.BackColor = _backColor;
  438.             state.FigureTypes = _figureTypes;
  439.             state.CheckedMenuItemIndex = _checkedMenuItemIndex;
  440.             state.History = _history;
  441.  
  442.             return state;
  443.         }
  444.     }
  445. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement