aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.EmbroideryUI/EmbroideryFileEditor.xaml.cs
blob: 6b86c68cbbe28a6606287fbff3b6aed697f7d378 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Tango.MachineStudio.Publisher.UI.UI.Properties {
    using System;
    
    
    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or 
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Tango.Editors;
using Tango.PMR;
using Tango.PMR.Embroidery;

namespace Tango.EmbroideryUI
{
    /// <summary>
    /// Interaction logic for EmbroideryFileEditor.xaml
    /// </summary>
    public partial class EmbroideryFileEditor : UserControl
    {
        [DllImport("Tango.Embroidery.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "AnalyzeEmbroideryFile")]
        public static extern int AnalyzeEmbroideryFile(IntPtr data, int size, ref IntPtr output);

        private Thickness _currentMargins;

        #region Properties

        public ObservableCollection<EmbroideryPath> Paths
        {
            get { return (ObservableCollection<EmbroideryPath>)GetValue(PathsProperty); }
            set { SetValue(PathsProperty, value); }
        }
        public static readonly DependencyProperty PathsProperty =
            DependencyProperty.Register("Paths", typeof(ObservableCollection<EmbroideryPath>), typeof(EmbroideryFileEditor), new PropertyMetadata(null, (d, e) => (d as EmbroideryFileEditor).OnPathsChanged()));

        public EmbroideryFile EmbroideryFile
        {
            get { return (EmbroideryFile)GetValue(EmbroideryFileProperty); }
            set { SetValue(EmbroideryFileProperty, value); }
        }
        public static readonly DependencyProperty EmbroideryFileProperty =
            DependencyProperty.Register("EmbroideryFile", typeof(EmbroideryFile), typeof(EmbroideryFileEditor), new PropertyMetadata(null));

        public String FileName
        {
            get { return (String)GetValue(FileNameProperty); }
            set { SetValue(FileNameProperty, value); }
        }
        public static readonly DependencyProperty FileNameProperty =
            DependencyProperty.Register("FileName", typeof(String), typeof(EmbroideryFileEditor), new PropertyMetadata(null, (d, e) => (d as EmbroideryFileEditor).OnFileNameChanged()));

        public double ScaleFactor
        {
            get { return (double)GetValue(ScaleFactorProperty); }
            set { SetValue(ScaleFactorProperty, value); }
        }
        public static readonly DependencyProperty ScaleFactorProperty =
            DependencyProperty.Register("ScaleFactor", typeof(double), typeof(EmbroideryFileEditor), new PropertyMetadata(1.0, (d, e) => (d as EmbroideryFileEditor).OnScaleFactorChanged()));

        public EmbroideryPath SelectedPath
        {
            get { return (EmbroideryPath)GetValue(SelectedPathProperty); }
            set { SetValue(SelectedPathProperty, value); }
        }
        public static readonly DependencyProperty SelectedPathProperty =
            DependencyProperty.Register("SelectedPath", typeof(EmbroideryPath), typeof(EmbroideryFileEditor), new PropertyMetadata(null));

        #endregion

        #region Constructors

        public EmbroideryFileEditor()
        {
            Paths = new ObservableCollection<EmbroideryPath>();
            InitializeComponent();
            MouseWheel += EmbroideryFileEditor_MouseWheel;
        }

        #endregion

        #region Virtual Methods

        protected virtual void OnFileNameChanged()
        {
            if (!File.Exists(FileName)) return;

            AnalyzeInput input = new AnalyzeInput();
            input.FilePath = FileName;


            NativePMR<AnalyzeInput, AnalyzeOutput> nativePMR = new NativePMR<AnalyzeInput, AnalyzeOutput>(AnalyzeEmbroideryFile);
            AnalyzeOutput output = nativePMR.Invoke(input);

            EmbroideryFile = output.EmbroideryFile;
            DrawFile();
            ScaleToFit();
        }

        protected virtual void OnPathsChanged()
        {
            if (Paths != null)
            {
                Paths.CollectionChanged -= Paths_CollectionChanged;
                Paths.CollectionChanged += Paths_CollectionChanged;

                RegisterPathsEvents();
            }
        }

        protected virtual void OnScaleFactorChanged()
        {
            if (EmbroideryFile != null)
            {
                DrawFile();
            }
        }

        #endregion

        #region Event Handlers

        private void EmbroideryFileEditor_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            double factor = e.Delta > 0 ? 0.5 : -0.5;
            Paths.Clear();
            ScaleFactor += factor;
            DrawFile();
        }

        private void Paths_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            RegisterPathsEvents();
        }

        private void Path_MouseDown(object sender, MouseButtonEventArgs e)
        {
            EmbroideryPath path = sender as EmbroideryPath;

            path.IsSelected = !path.IsSelected;
            SelectedPath = path;
            Paths.Where(x => x != path).ToList().ForEach(x => x.IsSelected = false);
        }

        private void OnThumbDragging(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            list.Margin = new Thickness(_currentMargins.Left + e.HorizontalChange, _currentMargins.Top + e.VerticalChange, 0, 0);
            this.Cursor = Cursors.SizeAll;
        }

        private void OnThumbDragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e)
        {
            _currentMargins = list.Margin;
        }

        private void OnDragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
        {
            this.Cursor = Cursors.Arrow;
        }

        #endregion

        #region Private Methods

        private void RegisterPathsEvents()
        {
            foreach (var path in Paths)
            {
                path.MouseDown -= Path_MouseDown;
                path.MouseDown += Path_MouseDown;
            }
        }

        public void DrawFile()
        {
            if (EmbroideryFile == null) return;

            Point _currentPoint = new Point();
            Point _lastPoint = new Point();
            Stitch _lastStitch = new Stitch();
            StitchFlag _mode = StitchFlag.Jump;

            if (Paths == null)
            {
                Paths = new ObservableCollection<EmbroideryPath>();
            }

            Paths.Clear();

            Color color = ConvertStitchColorToColor(EmbroideryFile.Colors[0]);
            var path = CreatePathFigure(color, _currentPoint);

            foreach (var stitch in EmbroideryFile.Stitches)
            {
                _currentPoint = new Point(stitch.XX * ScaleFactor, stitch.YY * -1 * ScaleFactor);

                switch (stitch.Flag)
                {
                    case StitchFlag.Jump:
                        path = CreatePathFigure(color, _currentPoint);
                        _mode = StitchFlag.Jump;
                        break;
                    case StitchFlag.Stop:
                        color = ConvertStitchColorToColor(EmbroideryFile.Colors[stitch.ColorIndex]);
                        break;
                    case StitchFlag.Normal:

                        if (_mode == StitchFlag.Normal)
                        {
                            path.PathFigure.Segments.Add(new LineSegment(new Point(_currentPoint.X, _currentPoint.Y), true));
                            path.Length += Math.Abs(GetDistance(_lastStitch.XX, _lastStitch.YY, stitch.XX, stitch.YY));
                            path.StitchCount++;
                        }
                        _mode = StitchFlag.Normal;
                        break;
                }


                _lastStitch = stitch;
                _lastPoint = _currentPoint;
            }
        }

        private Color ConvertStitchColorToColor(StitchColor stitchColor)
        {
            return Color.FromRgb((byte)stitchColor.Red, (byte)stitchColor.Green, (byte)stitchColor.Blue);
        }

        private EmbroideryPath CreatePathFigure(Color color, Point startPoint)
        {
            PathFigure figure = new PathFigure();
            figure.StartPoint = startPoint;
            figure.IsClosed = false;


            EmbroideryPath path = new EmbroideryPath(new PathGeometry(new PathFigureCollection() { figure }));
            path.PathFigure = figure;
            path.StrokeThickness = 1;
            path.Brush = new SolidColorBrush(color);
            Paths.Add(path);
            return path;
        }

        private static double GetDistance(double x1, double y1, double x2, double y2)
        {
            return Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2));
        }

        #endregion

        #region Public Methods

        public void ScaleToFit()
        {
            double minX = Paths.Select(x => x.Path.GetFlattenedPathGeometry().Bounds.Left).Min();
            double minY = Paths.Select(x => x.Path.GetFlattenedPathGeometry().Bounds.Top).Min();
            double maxX = Paths.Select(x => x.Path.GetFlattenedPathGeometry().Bounds.Right).Max();
            double maxY = Paths.Select(x => x.Path.GetFlattenedPathGeometry().Bounds.Bottom).Max();

            Rect embRect = new Rect(minX, minY, maxX - minX, maxY - minY);
            Rect editorRect = new Rect(0, 0, ActualWidth, ActualHeight);

            double embRectArea = embRect.Width * embRect.Height;
            double editorRectArea = editorRect.Width * editorRect.Height;

            double factor = (editorRect.Width / embRect.Width) / 2d;

            if (embRect.Height > embRect.Width)
            {
                factor = (editorRect.Height / embRect.Height) / 2d;
            }

            ScaleFactor = factor;

            minY = Paths.Select(x => x.Path.GetFlattenedPathGeometry().Bounds.Top).Min();
            minX = Paths.Select(x => x.Path.GetFlattenedPathGeometry().Bounds.Left).Min();

            list.Margin = new Thickness(minX / 2, -minY / 2, 0, 0);
        }

        #endregion
    }
}