Example #1
0
        int ProcessDotFile(string inputFile)
        {
            Graph graph;
            int   i = CreateGraphFromDotFile(inputFile, out graph);

            if (i != 0)
            {
                return(i);
            }
            graph.LayoutAlgorithmSettings = PickLayoutAlgorithmSettings(graph.EdgeCount, graph.NodeCount);
            if (argsParser.OptionIsUsed(NoArrowheads))
            {
                RemoveArrowheadsFromGraph(graph);
            }
            EnlargeLabelMargins(graph);
            SetConsolasFontAndSize(graph, 13);

            // rendering
            var renderer = new GraphRenderer(graph);

            renderer.CalculateLayout();
            SetBoxRadiuses(graph);

            var    outputFile = Path.ChangeExtension(inputFile, ".svg");
            string outputDir  = argsParser.GetValueOfOptionWithAfterString(OutputDirOption);

            if (outputDir != null)
            {
                var name = Path.GetFileName(outputFile);
                if (name != null)
                {
                    outputFile = Path.Combine(outputDir, name);
                }
            }


            SetConsolasFontAndSize(graph, 11);
            if (argsParser.OptionIsUsed(NoLabelsOption))
            {
                RemoveLabelsFromGraph(graph);
            }

            var svgWriter = new SvgGraphWriter(File.Create(outputFile), graph)
            {
                NodeSanitizer = AntiXss.HtmlAttributeEncode, AttrSanitizer = AntiXss.HtmlAttributeEncode,
                Precision     = precision, AllowedToWriteUri = !argsParser.OptionIsUsed(NoUrls)
            };

            svgWriter.Write();
            DumpFileToConsole(outputFile);


            if (msaglOutput)
            {
                outputFile = SetMsaglOutputFileName(inputFile);
                var geomGraph = graph.GeometryGraph;
                WriteGeomGraph(outputFile, geomGraph);
            }
            return(0);
        }
        public void SaveGraphToFile(string fileName)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                MessageBox.Show("Unable to save. The given filename is invalid.", "Export error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string ext = Path.GetExtension(fileName).ToLower();

            if (!(ext == ".emf" || ext == ".wmf" || ext == ".svg"))
            {
                ext = ".svg";
            }
            fileName = Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName) + ext;
            try
            {
                if (ext != ".svg")
                {
                    var w = (int)Math.Ceiling(gViewer.SrcRect.Width);
                    var h = (int)Math.Ceiling(gViewer.SrcRect.Height);
                    DrawVectorGraphics(w, h);
                }
                else
                {
                    SvgGraphWriter.Write(gViewer.Graph, fileName, null, null, 4);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unfortunately an error occurred while saving image : " + ex.Message, "Export error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #3
0
        private void TestOverlapRemovalOnGraph(string graphName, Graph parentGraph,
                                               HashSet <Tuple <int, int> > proximityEdges, HashSet <Tuple <int, int, int> > proximityTriangles, Tuple <String, Action <GeometryGraph> > layoutMethod, int layoutPos, Tuple <string, OverlapRemovalSettings> overlapMethod, int overlapMethodPos)
        {
//            Graph parentGraph = Helper.CopyGraph(parentGraphOriginal);
            var geomGraphOld = Helper.CopyGraph(parentGraph.GeometryGraph);
            var geomGraph    = parentGraph.GeometryGraph;
//            GeometryGraph graph = Helper.CopyGraph(geomGraph);
            List <Tuple <String, double> > statistics = new List <Tuple <string, double> >();

            String layoutMethodName  = layoutMethod.Item1;
            String overlapMethodName = overlapMethod.Item1;
            var    overlapSettings   = overlapMethod.Item2;

            IOverlapRemoval overlapRemover = GetOverlapRemover(overlapSettings, geomGraph);


            overlapRemover.RemoveOverlaps();

            RefreshAndCleanGraph(parentGraph);


            var statIterations = Tuple.Create("Iterations", (double)overlapRemover.GetLastRunIterations());

            var statEdgeLength = Statistics.Statistics.EdgeLengthDeviation(geomGraphOld, geomGraph, proximityEdges);
            var statProcrustes =
                Statistics.Statistics.ProcrustesStatistics(geomGraphOld.Nodes.Select(v => v.Center).ToList(),
                                                           geomGraph.Nodes.Select(v => v.Center).ToList());
            var statTriangleOrient = Statistics.Statistics.TriangleOrientation(geomGraphOld, geomGraph, proximityTriangles);
            var statArea           = Statistics.Statistics.Area(geomGraph);

//            statistics.Add(Tuple.Create());
            statistics.Add(statIterations);
            statistics.Add(statEdgeLength);
            statistics.Add(statProcrustes);
            statistics.Add(statArea);
            statistics.Add(statTriangleOrient);

            String nameAddon = "-" + layoutPos.ToString() + "_" + overlapMethodPos + "-" + layoutMethodName + "_" +
                               overlapMethodName;

//            RefreshAndCleanGraph(parentGraph);
//           Parallel.Invoke(
//            ()=>parentGraph.Write(graphName + nameAddon+".msagl"),
//            () =>
            SvgGraphWriter.Write(parentGraph, graphName + nameAddon + ".svg");
//
//            );

            WriteHeader(statistics);
            String line = graphName + "," + geomGraph.Nodes.Count + "," + geomGraph.Edges.Count + "," + layoutMethodName + "," + overlapMethodName;

            for (int i = 0; i < statistics.Count; i++)
            {
                Tuple <string, double> stat = statistics[i];
                line += "," + stat.Item2;
            }
            WriteLine(line);
        }
        void OkButtonClick(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(saveInTextBox.Text))
            {
                MessageBox.Show("File name is not set");
                return;
            }

            Cursor c = Cursor;

            Cursor = Cursors.WaitCursor;
            try {
                int w, h;
                if (saveCurrentView.Checked)
                {
                    w = (int)Math.Ceiling(gViewer.SrcRect.Width * ImageScale);
                    h = (int)Math.Ceiling(gViewer.SrcRect.Height * ImageScale);
                }
                else
                {
                    w = (int)Math.Ceiling(gViewer.Graph.Width * ImageScale);
                    h = (int)Math.Ceiling(gViewer.Graph.Height * ImageScale);
                }

                Bitmap bitmap = null;
                string ext    = GetFileNameExtension();
                if (ext == ".EMF" || ext == ".WMF")
                {
                    DrawVectorGraphics(w, h);
                }
                else if (ext == ".SVG")
                {
                    SvgGraphWriter.Write(gViewer.Graph, FileName, null, null, 4);
                }
                else
                {
                    bitmap = new Bitmap(w, h, PixelFormat.Format32bppPArgb);
                    using (Graphics graphics = Graphics.FromImage(bitmap))
                        DrawGeneral(w, h, graphics);
                }

                AdjustFileName();
                if (bitmap != null)
                {
                    bitmap.Save(saveInTextBox.Text);
                }
            }
            catch (Exception ex) {
                MessageBox.Show("Cannot save the image: " + ex.Message);
                Cursor = c;
                return;
            }
            Cursor = c;
            Close();
        }
        private void DumpProximityCdtToSvg(string svgFileName, Graph graph, HashSet <Tuple <int, int> > proximityEdges)
        {
            SvgGraphWriter writer = new SvgGraphWriter(File.Create(svgFileName), graph);

            writer.TransformGraphByFlippingY();
            writer.WriteOpening();
            foreach (var t in proximityEdges)
            {
                writer.WriteLine(GetIthPoint(t.Item1, graph), GetIthPoint(t.Item2, graph));
            }
            writer.TransformGraphByFlippingY();
            writer.Close();
        }
Example #6
0
        public void SaveGraphToFile(bool currentViewOnly, string fileName, double imageScale)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                MessageBox.Show("Unable to save. The given filename is invalid.", "Export error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            this.FileName = fileName;
            try
            {
                int w, h;
                if (currentViewOnly)
                {
                    w = (int)Math.Ceiling(gViewer.SrcRect.Width * imageScale);
                    h = (int)Math.Ceiling(gViewer.SrcRect.Height * imageScale);
                }
                else
                {
                    w = (int)Math.Ceiling(gViewer.Graph.Width * imageScale);
                    h = (int)Math.Ceiling(gViewer.Graph.Height * imageScale);
                }

                Bitmap bitmap = null;
                string ext    = GetFileNameExtension();
                if (ext == ".EMF" || ext == ".WMF")
                {
                    DrawVectorGraphics(w, h);
                }
                else if (ext == ".SVG")
                {
                    SvgGraphWriter.Write(gViewer.Graph, fileName, null, null, 4);
                }
                else
                {
                    bitmap = new Bitmap(w, h, PixelFormat.Format32bppPArgb);
                    using (Graphics graphics = Graphics.FromImage(bitmap))
                        DrawGeneral(w, h, graphics);
                }

                AdjustFileName();
                if (bitmap != null)
                {
                    bitmap.Save(saveInTextBox.Text);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unfortunately an error occurred while saving image : " + ex.Message, "Export error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
        static void PrintSvgAsString(Graph drawingGraph)
        {
            var ms        = new MemoryStream();
            var writer    = new StreamWriter(ms);
            var svgWriter = new SvgGraphWriter(writer.BaseStream, drawingGraph);

            svgWriter.Write();
            // get the string from MemoryStream
            ms.Position = 0;
            var sr    = new StreamReader(ms);
            var myStr = sr.ReadToEnd();

            System.Console.WriteLine(myStr);
        }
Example #8
0
        private static void DumpScatterPlotOfDelaunayFacesAreaChange(string graphName, HashSet <Tuple <int, int, int> > proximityTriangles,
                                                                     GeometryGraph geomGraphOld, GeometryGraph geomGraph, string nameAddon)
        {
            Graph scatterPlot = new Graph();

            for (int i = 0; i < proximityTriangles.Count; i++)
            {
                scatterPlot.AddNode(i.ToString());
            }

            scatterPlot.CreateGeometryGraph();
            int k = 0;

            foreach (var triangle in proximityTriangles)
            {
                Point a = geomGraphOld.Nodes[triangle.Item1].Center;
                Point b = geomGraphOld.Nodes[triangle.Item2].Center;
                Point c = geomGraphOld.Nodes[triangle.Item3].Center;

                Point d = geomGraph.Nodes[triangle.Item1].Center;
                Point e = geomGraph.Nodes[triangle.Item2].Center;
                Point f = geomGraph.Nodes[triangle.Item3].Center;

                double signOld = Point.SignedDoubledTriangleArea(a, b, c);
                double signNew = Point.SignedDoubledTriangleArea(d, e, f);
                var    node    = scatterPlot.FindNode(k.ToString());
                k++;
                node.GeometryNode.BoundaryCurve = CurveFactory.CreateCircle(1, new Point(signOld, signNew));
                if (signNew < 0)
                {
                    node.Attr.FillColor = node.Attr.Color = Color.Red;
                }
            }

            scatterPlot.GeometryGraph.UpdateBoundingBox();
            double w = scatterPlot.GeometryGraph.BoundingBox.Width;
            double h = scatterPlot.GeometryGraph.BoundingBox.Height;
            PlaneTransformation p = new PlaneTransformation(
                200 / w, 0, 0,
                0, 200 / h, 0);

            scatterPlot.GeometryGraph.Transform(p);
            scatterPlot.GeometryGraph.UpdateBoundingBox();
            SvgGraphWriter.Write(scatterPlot, "cdt_area_change_" + graphName + nameAddon + ".svg");
        }
        void okButton_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(saveInTextBox.Text))
            {
                MessageBox.Show("File name is not set");
                return;
            }


            string ext = Path.GetExtension(FileName).ToLower();

            if (!(ext == ".emf" || ext == ".wmf" || ext == ".svg"))
            {
                saveInTextBox.Text += ".svg";
            }

            Cursor c = Cursor;

            Cursor = Cursors.WaitCursor;
            try {
                if (ext != ".svg")
                {
                    var w = (int)Math.Ceiling(gViewer.SrcRect.Width);
                    var h = (int)Math.Ceiling(gViewer.SrcRect.Height);

                    DrawVectorGraphics(w, h);
                }
                else
                {
                    SvgGraphWriter.Write(gViewer.Graph, FileName, null, null, 4);
                }
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
                Cursor = c;
                return;
            }
            Cursor = c;
            Close();
        }
Example #10
0
        static void ProcessDotFile(GViewer gviewer, ArgsParser.ArgsParser argsParser, string dotFileName)
        {
            int    line;
            int    col;
            string msg;
            Graph  graph = Parser.Parse(dotFileName, out line, out col, out msg);

            if (graph == null)
            {
                System.Diagnostics.Debug.WriteLine("{0}({1},{2}): error: {3}", dotFileName, line, col, msg);
                Environment.Exit(1);
            }
            if (argsParser.OptionIsUsed(RecoverSugiyamaTestOption))
            {
                gviewer.CalculateLayout(graph);
                graph.GeometryGraph.AlgorithmData = null;
                LayeredLayout.RecoverAlgorithmData(graph.GeometryGraph);

                Node node = graph.GeometryGraph.Nodes[1];
                node.BoundaryCurve = node.BoundaryCurve.Transform(new PlaneTransformation(3, 0, 0, 0, 3, 0));

                LayeredLayout.IncrementalLayout(graph.GeometryGraph, node);
                gviewer.NeedToCalculateLayout = false;
                gviewer.Graph = graph;
                gviewer.NeedToCalculateLayout = true;

                return;
            }

            if (argsParser.OptionIsUsed(MdsOption))
            {
                graph.LayoutAlgorithmSettings = gviewer.mdsLayoutSettings;
            }
            else if (argsParser.OptionIsUsed(FdOption))
            {
                graph.LayoutAlgorithmSettings = new FastIncrementalLayoutSettings();
            }

            if (argsParser.OptionIsUsed(BundlingOption))
            {
                graph.LayoutAlgorithmSettings.EdgeRoutingSettings.EdgeRoutingMode = EdgeRoutingMode.SplineBundling;
                BundlingSettings bs = GetBundlingSettings(argsParser);
                graph.LayoutAlgorithmSettings.EdgeRoutingSettings.BundlingSettings = bs;
                string ink = argsParser.GetStringOptionValue(InkImportanceOption);
                if (ink != null)
                {
                    double inkCoeff;
                    if (double.TryParse(ink, out inkCoeff))
                    {
                        bs.InkImportance = inkCoeff;
                        BundlingSettings.DefaultInkImportance = inkCoeff;
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("cannot parse {0}", ink);
                        Environment.Exit(1);
                    }
                }

                string esString = argsParser.GetStringOptionValue(EdgeSeparationOption);
                if (esString != null)
                {
                    double es;
                    if (double.TryParse(esString, out es))
                    {
                        BundlingSettings.DefaultEdgeSeparation = es;
                        bs.EdgeSeparation = es;
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("cannot parse {0}", esString);
                        Environment.Exit(1);
                    }
                }
            }

            gviewer.Graph = graph;
            string svgout = argsParser.GetStringOptionValue(SvgFileNameOption);

            try {
                if (svgout != null)
                {
                    SvgGraphWriter.Write(gviewer.Graph, svgout, null, null, 4);
                }
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
Example #11
0
        int ProcessDotFile(string inputFile)
        {
            Graph graph;
            int   i = CreateGraphFromDotFile(inputFile, out graph);

            graph.Attr.LayerDirection = GetLayerDirection();

            if (i != 0)
            {
                return(i);
            }
            if (argsParser.OptionIsUsed("-nolayout") && GeometryIsPresent(graph))
            {
                double nodeScale;
                bool   scaling = argsParser.GetDoubleOptionValue("-scaleNodesBy", out nodeScale);
                if (scaling)
                {
                    foreach (var node in graph.GeometryGraph.Nodes)
                    {
                        node.BoundaryCurve = node.BoundaryCurve.Transform(PlaneTransformation.ScaleAroundCenterTransformation(nodeScale,
                                                                                                                              node.Center));
                    }
                    graph.GeometryGraph.UpdateBoundingBox();
                }
                double nodeLineWidth;
                if (argsParser.GetDoubleOptionValue("-nblw", out nodeLineWidth))
                {
                    foreach (var node in graph.Nodes)
                    {
                        node.Attr.LineWidth = nodeLineWidth;
                    }
                    graph.GeometryGraph.UpdateBoundingBox();
                }
            }
            else
            {
                PrepareForOutput(graph);
            }

            var    outputFile = Path.ChangeExtension(inputFile, ".svg");
            string outputDir  = argsParser.GetStringOptionValue(OutputDirOption);

            if (outputDir != null)
            {
                var name = Path.GetFileName(outputFile);
                if (name != null)
                {
                    outputFile = Path.Combine(outputDir, name);
                }
            }


            SetConsolasFontAndSize(graph, 11);
            if (argsParser.OptionIsUsed(NoLabelsOption))
            {
                RemoveLabelsFromGraph(graph);
            }
            using (var stream = File.Create(outputFile)) {
                var svgWriter = new SvgGraphWriter(stream, graph)
                {
                    BlackAndWhite     = argsParser.OptionIsUsed("-bw"),
                    NodeSanitizer     = AntiXss.HtmlAttributeEncode,
                    AttrSanitizer     = AntiXss.HtmlAttributeEncode,
                    Precision         = precision,
                    AllowedToWriteUri = !argsParser.OptionIsUsed(NoUrls),
                    IgnoreEdges       = argsParser.OptionIsUsed("-noedges")
                };
                svgWriter.Write();
                DumpFileToConsole(outputFile);
            }

            if (msaglOutput)
            {
                outputFile = SetMsaglOutputFileName(inputFile);
                var geomGraph = graph.GeometryGraph;
                WriteGeomGraph(outputFile, geomGraph);
            }
            return(0);
        }
Example #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="graphFilename"></param>
        public void RunOverlapRemoval(String graphFilename)
        {
            String graphName = Path.GetFileNameWithoutExtension(graphFilename);
            Graph  graph     = LoadGraphFile(graphFilename);

            if (graph == null)
            {
                Console.WriteLine("Failed to load drawing graph: {0}", graphName);
                return;
            }
            if (graph.GeometryGraph == null)
            {
                Console.WriteLine("Failed to load geometry graph: {0}", graphName);
                return;
            }
            Point[] initPositions = graph.GeometryGraph.Nodes.Select(v => v.Center).ToArray();

            for (int i = 0; i < layoutMethods.Count(); i++)
            {
                var layoutMethod = layoutMethods[i];
                layoutMethod.Item2.Invoke(graph.GeometryGraph); //do initial layout
                //randomize cooincident points
                Point[] nodePositions = graph.GeometryGraph.Nodes.Select(v => v.Center).ToArray();

                //                LayoutAlgorithmSettings.ShowDebugCurves(
                //                    nodePositions.Select(p => new DebugCurve(220, 0.01, "green", CurveFactory.CreateOctagon(2, 2, p)))
                //                                 .ToArray());

                RandomizeNodes(graph, nodePositions);
                RouteGraphEdges(graph);
                SvgGraphWriter.Write(graph, graphName + "-" + i.ToString() + "-" + layoutMethod.Item1 + ".svg");

                HashSet <Tuple <int, int, int> > proximityTriangles;
                HashSet <Tuple <int, int> >      proximityEdges;
                GetProximityRelations(graph.GeometryGraph, out proximityEdges, out proximityTriangles);

                for (int j = 0; j < overlapMethods.Count; j++)
                {
                    if (graph.NodeCount == 0)
                    {
                        continue;
                    }
                    var overlapMethod = overlapMethods[j];
                    TestOverlapRemovalOnGraph(graphName, graph, proximityEdges, proximityTriangles, layoutMethod, i, overlapMethod, j);
                    SetOldPositions(nodePositions, graph);
                }
                SetOldPositions(initPositions, graph);
            }



            //#if DEBUG
            //            //write the number of crossings per iteration
            //            String convergenceFilename = graphName + "-crossPerIterat.csv";
            //            List<int> crossings1 = prism1.crossingsOverTime;
            //            List<int> crossings2 = prism2.crossingsOverTime;
            //
            //            int maxIter = Math.Max(crossings1.Count, crossings2.Count);
            //            List<String> lines=new List<string>();
            //            lines.Add("iteration,crossingsPRISM,crossingsGridBoost");
            //            for (int i = 0; i < maxIter; i++) {
            //                String l = i.ToString();
            //                if (i < crossings1.Count)
            //                    l += "," + crossings1[i];
            //                else l += ",0";
            //                if (i < crossings2.Count)
            //                    l += "," + crossings2[i];
            //                else l += ",0";
            //                lines.Add(l);
            //            }
            //            File.WriteAllLines(convergenceFilename,
            //                lines.ToArray(),Encoding.UTF8);
            //#endif
        }
Example #13
0
        // ReSharper disable once MethodTooLong
        private static void Main(string[] args)
        {
            try
            {
                LoadApplicationSettings();
                //Console.BackgroundColor = _Settings.EditorBackgroundColor;
                //Console.ForegroundColor = _Settings.EditorTextColor;
                //FillCurrentLineBackground();

                var parser       = new Parser(with => with.HelpWriter = null);
                var parserResult = parser.ParseArguments <Options>(args);
                parserResult
                .WithParsed(o =>
                {
                    var options       = Grammar.ParseOption.None;
                    var loadGui       = false;
                    var showParseTree = false;
                    var writeSvg      = false;
                    ISyntaxHighlightingGuide guide = null;

                    if (o.Tokens)
                    {
                        options |= Grammar.ParseOption.Tokens;
                    }
                    if (o.Diagnostics)
                    {
                        options |= Grammar.ParseOption.Diagnostics;
                    }
                    if (o.Trace)
                    {
                        options |= Grammar.ParseOption.Trace;
                    }
                    if (o.Tree)
                    {
                        options      |= Grammar.ParseOption.Tree;
                        showParseTree = true;
                    }

                    if (!string.IsNullOrEmpty(o.SvgFileName))
                    {
                        writeSvg = true;
                        options |= Grammar.ParseOption.Tree;
                    }

                    if (o.Sll)
                    {
                        options |= Grammar.ParseOption.Sll;
                    }
                    if (o.Gui)
                    {
                        loadGui  = true;
                        options |= Grammar.ParseOption.Tree;
                    }

                    var workingDirectory = Environment.CurrentDirectory;
                    var scanner          = new Grammar.Scanner();

                    var grammar = scanner.LocateGrammar(workingDirectory, o.GrammarName);
                    if (grammar == null)
                    {
                        Console.WriteLine(Resources.GrammarNotFoundErrorMessage, o.GrammarName);
                        return;
                    }

                    // To be used later once syntax highlighting for the console is enabled.
                    //var guideResult = grammar.LoadSyntaxHighlightingGuide();
                    //guide = guideResult != null ? guideResult.Item2 : new HeuristicSyntaxHighlightingGuide(_Settings);

                    string data;

                    if (!string.IsNullOrEmpty(o.FileName))
                    {
                        if (!File.Exists(o.FileName))
                        {
                            Console.WriteLine(Resources.FileNotFoundErrorMessage, o.FileName);
                            return;
                        }

                        var encodingToUse = !string.IsNullOrEmpty(o.EncodingName) ? Encoding.GetEncoding(o.EncodingName) : Encoding.Default;
                        using (var reader = new StreamReader(o.FileName, encodingToUse))
                            data = reader.ReadToEnd();
                    }
                    else
                    {
                        //var analyzer = new Analyzer();
                        var builder = new StringBuilder();
                        Console.WriteLine(Resources.ReadingFromStandardInputPromptMessage);
                        var currentLine = Console.CursorTop;
                        var keepReading = true;
                        while (keepReading)
                        {
                            if (Console.KeyAvailable)
                            {
                                while (Console.KeyAvailable)
                                {
                                    var typed = Console.ReadKey(true);

                                    if ((typed.Modifiers & ConsoleModifiers.Control) == ConsoleModifiers.Control &&
                                        typed.Key == ConsoleKey.Z)
                                    {
                                        Console.Write("^Z");
                                        keepReading = false;
                                        break;
                                    }

                                    if (typed.Key == ConsoleKey.Enter)
                                    {
                                        if (Console.CursorTop == Console.BufferHeight - 1)
                                        {
                                            _ScrollFadeCount++;
                                        }
                                        Console.WriteLine();
                                        FillCurrentLineBackground();
                                        builder.Append("\r\n");
                                    }
                                    else if (typed.Key == ConsoleKey.Tab)
                                    {
                                        var spaces = new string(' ', _Settings.EditorTabLength);
                                        Console.Write(spaces);
                                        builder.Append(spaces);
                                    }
                                    else if (typed.Key == ConsoleKey.Backspace)
                                    {
                                        if (Console.CursorLeft > 0)
                                        {
                                            Console.Write(typed.KeyChar);
                                            Console.Write(' ');
                                            Console.Write(typed.KeyChar);
                                            builder.Remove(builder.Length - 1, 1);
                                            _Cache.FlushTokensForLine(currentLine - (_ScrollFadeCount + 1));
                                        }
                                    }
                                    else
                                    {
                                        Console.Write(typed.KeyChar);
                                        builder.Append(typed.KeyChar);
                                    }
                                }

                                //analyzer.Tokenize(grammar, builder.ToString());
                                //HighlightSyntaxInConsole(currentLine - (_ScrollFadeCount + 1), analyzer, guide);
                            }
                        }

                        Console.WriteLine();
                        data = builder.ToString();
                    }

                    // If tokens are the only option we've received, we don't need to parse
                    if (options == Grammar.ParseOption.Tokens)
                    {
                        DisplayTokens(grammar, data);
                        return;
                    }

                    // Now we attempt to parse, but still handle a lexer-only grammar.
                    if (grammar.Parser != null)
                    {
                        var analyzer      = new Analyzer();
                        var grammarParser = analyzer.BuildParserWithOptions(grammar, data, options);
                        analyzer.ExecuteParsing(grammarParser, o.RuleName);

                        if (showParseTree)
                        {
                            Console.WriteLine(analyzer.ParserContext.ToStringTree(grammarParser));
                        }

                        if (writeSvg)
                        {
                            var rules   = scanner.GetParserRulesForGrammarParser(grammar.Parser);
                            var grapher = new ParseTreeGrapher()
                            {
                                BackgroundColor = _Settings.GraphNodeBackgroundColor.GetMsAglColor(),
                                BorderColor     = _Settings.GraphNodeBorderColor.GetMsAglColor(),
                                TextColor       = _Settings.GraphNodeTextColor.GetMsAglColor()
                            };
                            var graph = grapher.CreateGraph(analyzer.ParserContext, rules.ToList());
                            graph.LayoutAlgorithmSettings = new SugiyamaLayoutSettings();
                            GraphRenderer renderer        = new GraphRenderer(graph);
                            renderer.CalculateLayout();
                            graph.EscapeNodesForSvg();
                            SvgGraphWriter.Write(graph, o.SvgFileName, null, null, 4);
                        }
                    }
                    else
                    {
                        if (options.HasFlag(ParseOption.Tokens))
                        {
                            DisplayTokens(grammar, data);
                        }

                        if (showParseTree || writeSvg)
                        {
                            Console.WriteLine(Resources.GrammarHasNoParserErrorMessage, grammar.GrammarName);
                        }
                        if (showParseTree)
                        {
                            Console.WriteLine(Resources.UnableToDisplayParseTree);
                        }
                        if (writeSvg)
                        {
                            Console.WriteLine(Resources.SvgWritingAbortedErrorMessage);
                        }
                    }

                    if (loadGui)
                    {
                        LoadGui(data, grammar, o.RuleName);
                    }
                })
                .WithNotParsed(errs => DisplayHelp(parserResult, errs));

#if DEBUG
                Console.WriteLine(Resources.PressAnyKeyMessage);
                Console.ReadKey();
#endif
            }
            // ReSharper disable once CatchAllClause
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
#if DEBUG
                Console.WriteLine(Resources.PressAnyKeyMessage);
                Console.ReadKey();
#endif
            }
        }
Example #14
0
        private void TestOverlapRemovalOnGraph(string graphName, Graph parentGraph,
                                               HashSet <Tuple <int, int> > proximityEdges, HashSet <Tuple <int, int, int> > proximityTriangles,
                                               Tuple <String, Action <GeometryGraph> > layoutMethod, int layoutPos,
                                               Tuple <string, OverlapRemovalSettings> overlapMethod, int overlapMethodPos)
        {
//            Graph parentGraph = Helper.CopyGraph(parentGraphOriginal);
            var geomGraphOld = Helper.CopyGraph(parentGraph.GeometryGraph);
            var geomGraph    = parentGraph.GeometryGraph;

            graphName = Path.GetFileNameWithoutExtension(graphName);
//            GeometryGraph graph = Helper.CopyGraph(geomGraph);
            List <Tuple <String, double> > statistics = new List <Tuple <string, double> >();

            String layoutMethodName  = layoutMethod.Item1;
            String overlapMethodName = overlapMethod.Item1;
            var    overlapSettings   = overlapMethod.Item2;

            IOverlapRemoval overlapRemover = GetOverlapRemover(overlapSettings, geomGraph);

            overlapRemover.RemoveOverlaps();

            RouteGraphEdges(parentGraph);

            MakeEdgesTransparent(parentGraph);

            List <Tuple <string, double> > kClosestNeighborsError = new List <Tuple <string, double> >();
            var statIterations = RunStats(proximityEdges, proximityTriangles, overlapRemover, geomGraphOld, geomGraph,
                                          kClosestNeighborsError);

            foreach (var t in kClosestNeighborsError)
            {
                statistics.Add(t);
            }
            statistics.Add(statIterations);

            String nameAddon = "-" + layoutPos + "_" + overlapMethodPos + "-" + layoutMethodName + "_" +
                               overlapMethodName;

            parentGraph.GeometryGraph.UpdateBoundingBox();
            DumpProximityCdtToSvg("cdt_" + graphName + nameAddon + ".svg", parentGraph, proximityEdges);


            SvgGraphWriter.WriteAllExceptEdgesInBlack(parentGraph, graphName + nameAddon + ".svg");

            WriteHeader(statistics);
            String line = graphName + "," + geomGraph.Nodes.Count + "," + geomGraph.Edges.Count + "," + layoutMethodName +
                          "," + overlapMethodName;

            double closestNeighErr = 0;

            for (int i = 0; i < statistics.Count; i++)
            {
                Tuple <string, double> stat = statistics[i];
                line += "," + stat.Item2;
                if (stat.Item1.StartsWith("f"))
                {
                    closestNeighErr += stat.Item2;
                }
            }
            ErrorCouple ec;

            if (!_errorDict.TryGetValue(graphName, out ec))
            {
                ec = new ErrorCouple();
                _errorDict[graphName] = ec;
            }
            if (overlapMethodName.Contains("PRISM"))
            {
                ec.prismError = closestNeighErr;
            }
            else
            {
                ec.gtreeError = closestNeighErr;
            }

            WriteLine(line);
        }
        static void ProcessDotFile(GViewer gviewer, ArgsParser.ArgsParser argsParser, string dotFileName)
        {
            Graph graph = Parser.Parse(dotFileName, out int line, out int col, out string msg);

            if (graph == null)
            {
                Console.WriteLine("{0}({1},{2}): error: {3}", dotFileName, line, col, msg);
                Environment.Exit(1);
            }


            if (argsParser.OptionIsUsed(MdsOption))
            {
                graph.LayoutAlgorithmSettings = new MdsLayoutSettings();
            }
            else if (argsParser.OptionIsUsed(FdOption))
            {
                graph.LayoutAlgorithmSettings = new FastIncrementalLayoutSettings();
            }

            if (argsParser.OptionIsUsed(BundlingOption))
            {
                graph.LayoutAlgorithmSettings.EdgeRoutingSettings.EdgeRoutingMode = EdgeRoutingMode.SplineBundling;
                BundlingSettings bs = GetBundlingSettings(argsParser);
                graph.LayoutAlgorithmSettings.EdgeRoutingSettings.BundlingSettings = bs;
                string ink = argsParser.GetStringOptionValue(InkImportanceOption);
                if (ink != null)
                {
                    if (double.TryParse(ink, out double inkCoeff))
                    {
                        bs.InkImportance = inkCoeff;
                        BundlingSettings.DefaultInkImportance = inkCoeff;
                    }
                    else
                    {
                        Console.WriteLine("cannot parse {0}", ink);
                        Environment.Exit(1);
                    }
                }

                string esString = argsParser.GetStringOptionValue(EdgeSeparationOption);
                if (esString != null)
                {
                    if (double.TryParse(esString, out double es))
                    {
                        BundlingSettings.DefaultEdgeSeparation = es;
                        bs.EdgeSeparation = es;
                    }
                    else
                    {
                        Console.WriteLine("cannot parse {0}", esString);
                        Environment.Exit(1);
                    }
                }
            }

            gviewer.Graph = graph;
            string svgout = argsParser.GetStringOptionValue(SvgFileNameOption);

            try {
                if (svgout != null)
                {
                    SvgGraphWriter.Write(gviewer.Graph, svgout, null, null, 4);
                }
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
Example #16
0
        public static void Main(string[] args)
        {
            var options = new Options();

            CommandLine.Parser.Default.ParseArgumentsStrict(args, options);

            if ((options.SourceFiles?.Count ?? 0) == 0)
            {
                Console.WriteLine("No source files");
                return;
            }

            var compilation = CreateCompilation(options.SourceFiles);

            PrintDiagnostics(compilation);

            void saveGraph(Graph graph, string name)
            {
                // 強制的にレイアウトをかける(アホなやり方)
                var viewer = new GViewer();

                viewer.Graph = graph;

                switch (options.OutputFormat)
                {
                case OutputFormat.Msagl:
                    graph.Write(FileNameGenerator.CreateFilePath(
                                    options.OutputDirectory,
                                    name, "msagl"
                                    ));
                    break;

                case OutputFormat.Svg:
                    SvgGraphWriter.Write(
                        graph,
                        FileNameGenerator.CreateFilePath(
                            options.OutputDirectory,
                            name, "svg"
                            )
                        );
                    break;

                default:
                    throw new InvalidOperationException();
                }
            }

            foreach (var syntaxTree in compilation.SyntaxTrees)
            {
                var graph = CreateSyntaxGraph(syntaxTree.GetRoot());
                saveGraph(graph, Path.GetFileName(syntaxTree.FilePath));
            }

            {
                var graph = new Graph();
                new SymbolGraphGenerator(graph).Visit(compilation.Assembly);
                saveGraph(graph, "symbols");
            }

            foreach (var(symbol, graph) in new OperationGraphGenerator(compilation).Visit(compilation.Assembly))
            {
                saveGraph(graph, symbol.ToDisplayString());
            }
        }