private void DisconnectVirtualPoint(VirtualPoint virtualPoint, bool recordUndo, bool saveAssets = false)
        {
            if (!virtualPoint.Socket.IsConnected)
            {
                return;
            }
            if (!virtualPoint.IsConnected)
            {
                return;
            }

            if (recordUndo)
            {
                RecordUndo(GraphAction.Disconnect.ToString());
            }

            var connections = new List <VirtualConnection>();

            foreach (VirtualConnection connection in ConnectionsDatabase.Values)
            {
                if (connection.InputVirtualPoint == virtualPoint || connection.OutputVirtualPoint == virtualPoint)
                {
                    connections.Add(connection);
                }
            }

            foreach (VirtualConnection vc in connections)
            {
                vc.OutputSocket.RemoveConnection(vc.ConnectionId);
                vc.InputSocket.RemoveConnection(vc.ConnectionId);
                EditorUtility.SetDirty(vc.OutputNode);
                EditorUtility.SetDirty(vc.InputNode);
                ConnectionsDatabase.Remove(vc.ConnectionId);
            }

            CurrentGraph.SetDirty(saveAssets);
            GraphEvent.Send(GraphEvent.EventType.EVENT_CONNECTION_DELETED);
        }
Ejemplo n.º 2
0
        private static void DeleteUnreferencedAssetNodes()
        {
            if (CurrentGraph == null)
            {
                return;                                                                                     //check that the graph is not null
            }
            Object[] objects = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(CurrentGraph)); //load all of the graph sub assets
            if (objects == null)
            {
                return;                                                                                     //make sure they are not null
            }
            List <Node> foundNodes = objects.OfType <Node>().ToList();                                      //create a temp list of all the found sub assets node

            if (CurrentGraph.Nodes == null)
            {
                CurrentGraph.Nodes = new List <Node>();                                                     //sanity check
            }
            bool saveGraph = false;                                                                         //mark true if any sub asset was destroyed

            foreach (Node node in foundNodes)
            {
                if (CurrentGraph.Nodes.Contains(node))
                {
                    continue;                                    //node reference was FOUND in the Nodes list -> continue
                }
                DestroyImmediate(node, true);                    //node reference was NOT FOUND in the Nodes list -> destroy the asset (it was probably soft deleted)
                saveGraph = true;                                //mark true in order to set the graph dirty and save it
            }

            WindowSettings.DeletedNodes.Clear();
            if (!saveGraph)
            {
                return;             //if no sub asset was destroyed -> stop here
            }
            WindowSettings.SetDirty(false);
            CurrentGraph.SetDirty(true); //save the graph
        }
Ejemplo n.º 3
0
        private void SoftDeleteNodes(List <Node> nodes, bool recordUndo, bool saveAssets)
        {
            if (nodes == null || nodes.Count == 0)
            {
                return;
            }
            nodes = nodes.Where(n => n != null).ToList();

            if (recordUndo)
            {
                RecordUndo("Delete Nodes");
            }

            //disconnect all the nodes that need to be deleted
            foreach (Node node in nodes)
            {
                if (!CanDeleteNode(node))
                {
                    continue;
                }

                foreach (VirtualConnection connection in ConnectionsDatabase.Values)
                {
                    if (node == null || connection == null)
                    {
                        continue;
                    }

                    if (connection.InputNode == node && connection.OutputSocket != null)
                    {
                        connection.OutputSocket.DisconnectFromNode(node.Id);
                        EditorUtility.SetDirty(connection.OutputNode);
                    }

                    if (connection.OutputNode == node && connection.InputSocket != null)
                    {
                        connection.InputSocket.DisconnectFromNode(node.Id);
                        EditorUtility.SetDirty(connection.InputNode);
                    }
                }
            }

            //at this point the nodes have been disconnected
            //'delete' the nodes by adding them the the DeletedNodes list
            foreach (Node node in nodes)
            {
                if (node == null)
                {
                    continue;
                }
                if (!CanDeleteNode(node))
                {
                    continue;
                }
                WindowSettings.DeletedNodes.Add(node);
                CurrentGraph.Nodes.Remove(node);
            }

            DeselectAll(false);                //deselect any selected nodes
            CurrentGraph.SetDirty(saveAssets); //mark the graph as dirty
            WindowSettings.SetDirty(false);    //mark the editor settings as dirty
            ConstructGraphGUI();               //invalidate all the databases and reconstruct the GUI
        }
Ejemplo n.º 4
0
        private void PasteNodes()
        {
            if (!WindowSettings.CanPasteNodes)
            {
                return;                                                     //paste operation cannot work if no nodes have been added to the 'virtual clipboard'
            }
            for (int i = WindowSettings.CopiedNodes.Count - 1; i >= 0; i--) //remove any null nodes
            {
                if (WindowSettings.CopiedNodes[i] == null)
                {
                    WindowSettings.CopiedNodes.RemoveAt(i);
                }
            }

            if (!WindowSettings.CanPasteNodes)
            {
                return;                                //paste operation cannot work if no not null nodes are left to be copied
            }
            //create current nodes list
            var copyNodes = new List <Node>();

            //get the first node to the left
            Node    firstNodeToTheLeft = null;
            Vector2 firstNodePosition  = Vector2.zero;

            foreach (Node node in WindowSettings.CopiedNodes)
            {
                if (node == null)
                {
                    continue;
                }
                if (firstNodeToTheLeft == null)
                {
                    firstNodeToTheLeft = node;
                    firstNodePosition  = node.GetPosition();
                }

                if (!(node.GetX() < firstNodePosition.x))
                {
                    continue;
                }
                firstNodeToTheLeft = node;
                firstNodePosition  = node.GetPosition();
            }

            foreach (Node node in WindowSettings.CopiedNodes)
            {
                Node original = node;

                if (original == null)
                {
                    continue;
                }
                Node copy = CreateNodeCopy(original);

                copy.hideFlags = original.hideFlags;

                Vector2 offsetFromFirstNodePosition = Vector2.zero;

                if (original != firstNodeToTheLeft)
                {
                    offsetFromFirstNodePosition = firstNodePosition - copy.GetPosition();
                }

                copy.SetPosition(WorldToGridPosition(CurrentMousePosition));
                copy.SetPosition(copy.GetPosition() - new Vector2(copy.GetWidth() / 2, NodySettings.Instance.NodeHeaderHeight / 2));
                copy.SetPosition(copy.GetPosition() - offsetFromFirstNodePosition);

                copyNodes.Add(copy);
                if (!EditorUtility.IsPersistent(copy))
                {
                    AssetDatabase.AddObjectToAsset(copy, CurrentGraph);
                }
                CurrentGraph.SetDirty(false);
            }

            //create current sockets list
            var copySockets = new List <Socket>();

            foreach (Node copyNode in copyNodes)
            {
                copySockets.AddRange(copyNode.InputSockets);
                copySockets.AddRange(copyNode.OutputSockets);
            }

            //create current connections list
            var copyConnections = new List <Connection>();

            foreach (Socket copySocket in copySockets)
            {
                foreach (Connection copyConnection in copySocket.Connections)
                {
                    copyConnections.Add(copyConnection);
                }
            }

            //generate new connection ids
            foreach (Connection copyConnection in copyConnections)
            {
                string oldConnectionId = copyConnection.Id;                     //save previous connection id
                string newConnectionId = copyConnection.GenerateNewId();        //save new conenction id

                foreach (Socket socket in copySockets)                          //go through each socket
                {
                    foreach (Connection socketConnection in socket.Connections) //go through each socket's connections
                    {
                        if (socketConnection.Id == oldConnectionId)
                        {
                            socketConnection.Id = newConnectionId; //update the connection id
                        }
                    }
                }
            }

            //generate new socket ids
            foreach (Socket copySocket in copySockets)
            {
                string oldSocketId = copySocket.Id;                //save previous socket id
                string newSocketId = copySocket.GenerateNewId();   //save new socket id

                foreach (Connection connection in copyConnections) //update all the connection socket ids
                {
                    if (connection.InputSocketId == oldSocketId)
                    {
                        connection.InputSocketId = newSocketId;
                    }
                    if (connection.OutputSocketId == oldSocketId)
                    {
                        connection.OutputSocketId = newSocketId;
                    }
                }
            }

            //generate new node ids
            foreach (Node copyNode in copyNodes)
            {
                string oldNodeId = copyNode.Id;                                   //save previous node id
                string newNodeId = copyNode.GenerateNewId();                      //save new node id

                foreach (Socket copySocket in copySockets)                        //go through all the sockets
                {
                    if (copySocket.NodeId == oldNodeId)                           //check that the current node id is equal the the old node id
                    {
                        copySocket.NodeId = newNodeId;                            //update the node id
                    }
                    foreach (Connection copyConnection in copySocket.Connections) //update all the connection node ids
                    {
                        if (copyConnection.OutputNodeId == oldNodeId)
                        {
                            copyConnection.OutputNodeId = newNodeId;
                        }
                        if (copyConnection.InputNodeId == oldNodeId)
                        {
                            copyConnection.InputNodeId = newNodeId;
                        }
                    }
                }
            }

            //a list of all the copied nodes ids is needed in order to be able to keep the connections between the copied nodes and remove any 'outside' connections
            var copiedNodesIds = new List <string>(); //create a list of all the copied nodes ids (list contains the newly generated ids)
            foreach (Node copyNode in copyNodes)
            {
                copiedNodesIds.Add(copyNode.Id);
            }

            foreach (Socket copySocket in copySockets)
            {
                for (int i = copySocket.Connections.Count - 1; i >= 0; i--)
                {
                    Connection c = copySocket.Connections[i];
                    //remove any connection that is made with a node outside the copied nodes list
                    //keep the connections between the copied nodes and remove any 'outside' connections
                    if (copiedNodesIds.Contains(c.InputNodeId) && copiedNodesIds.Contains(c.OutputNodeId))
                    {
                        continue;
                    }
                    copySocket.Connections.RemoveAt(i);
                }
            }

            //record undo for paste
            RecordUndo("Paste Nodes");

            //add the references of the pasted nodes to the graph's nodes list
            //do it in reverse order in order to be sorted on top of all the other nodes
            var nodesList = new List <Node>(copyNodes);
            nodesList.AddRange(CurrentGraph.Nodes);
            CurrentGraph.Nodes = nodesList;

            //add the node asset files under the graph asset
            foreach (Node copiedNode in copyNodes)
            {
                if (!EditorUtility.IsPersistent(copiedNode))
                {
                    AssetDatabase.AddObjectToAsset(copiedNode, CurrentGraph);
                }
                EditorUtility.SetDirty(copiedNode);
            }

            //mark the graph as dirty in order to be able to save the changes
            CurrentGraph.SetDirty(false);

            //reconstruct the databases in order to draw
            ConstructGraphGUI();
            RecalculateAllPointRects();

            //Select the pasted nodes
            SelectNodes(copyNodes, false, false);

            //Paste completed -> clear clipboard
            WindowSettings.CopiedNodes.Clear();
            WindowSettings.SetDirty(false);
        }
Ejemplo n.º 5
0
 public void ListItemAndDependencyFactories()
 {
     Log.WriteInfo(CurrentGraph.ListItemAndDependencyFactories() ??
                   _itemAndDependencyFactories.ListItemAndDependencyFactories());
 }
Ejemplo n.º 6
0
 public void RemoveLocalItemAndDependencyFactories(string namePart)
 {
     CurrentGraph.RemoveItemAndDependencyFactories(namePart);
 }
Ejemplo n.º 7
0
 public void AddLocalItemAndDependencyFactory(string factoryAssembly, string factoryClass)
 {
     CurrentGraph.AddItemAndDependencyFactory(GetOrCreatePlugin <IItemAndDependencyFactory>(
                                                  factoryAssembly, factoryClass));
 }
Ejemplo n.º 8
0
 public void RenameCurrentGraph(string newName)
 {
     CurrentGraph.SetName(newName);
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Extract file patterns from args and read files
        /// </summary>
        /// <param name="includes"></param>
        /// <param name="excludes"></param>
        /// <param name="assemblyName"></param>
        /// <param name="readerFactoryClassNameOrNull">if null, detect from reader class from first extension in patterns</param>
        public void ReadFiles(IEnumerable <string> includes, IEnumerable <string> excludes, string assemblyName,
                              [CanBeNull] string readerFactoryClassNameOrNull)
        {
            IReaderFactory readerFactory;

            if (readerFactoryClassNameOrNull == null)
            {
                IEnumerable <string> allFileNames = includes.Concat(excludes);
                readerFactory = GetSuitableInternalReader(assemblyName, allFileNames);
                if (readerFactory == null)
                {
                    throw new ApplicationException($"Found no reader for files {string.Join(",", allFileNames)}");
                }
            }
            else
            {
                readerFactory = GetOrCreatePlugin <IReaderFactory>(assemblyName, readerFactoryClassNameOrNull);
            }

            InputFilesOrTestDataSpecified = true;

            IEnumerable <string> extensionsForDirectoryReading = readerFactory.SupportedFileExtensions;

            IEnumerable <string> includedFilenames = includes.SelectMany(p => Option.ExpandFilePatternFileNames(p, extensionsForDirectoryReading));
            IEnumerable <string> excludedFilenames = excludes.SelectMany(p => Option.ExpandFilePatternFileNames(p, extensionsForDirectoryReading));

            string[] fileNames = includedFilenames
                                 .Except(excludedFilenames)
                                 .Distinct()
                                 .OrderBy(s => s)
                                 .ToArray();

            if (Log.IsVerboseEnabled)
            {
                Log.WriteInfo("Files to be read");
                foreach (var f in fileNames)
                {
                    Log.WriteInfo("  " + f);
                }
            }

            IDependencyReader[] readers = fileNames.Select(fileName => readerFactory.CreateReader(fileName, needsOnlyItemTails: false /*???*/)).ToArray();

            foreach (var r in readers)
            {
                r.SetReadersInSameReadFilesBeforeReadDependencies(readers);
            }

            // Currently, we add the previous set of dependencies to the newly read ones; with the introduction of a useful "working set" concept, this should vanish ...
            var readSet = new List <Dependency>();

            foreach (var r in readers)
            {
                Dependency[] dependencies = r.ReadDependencies(CurrentGraph, 0, IgnoreCase).ToArray();
                if (!dependencies.Any())
                {
                    Log.WriteWarning("No dependencies found in " + r.FullFileName);
                }

                readSet.AddRange(dependencies);
            }
            if (_autoGraphsForRead > 0)
            {
                CreateWorkingGraph(readerFactory.GetType().Name, GraphCreationType.AutoRead, readSet);
                RemoveSuperfluousGraphs(_autoGraphsForRead, GraphCreationType.AutoRead);
            }
            else
            {
                CurrentGraph.AddDependencies(readSet);
            }

            Log.WriteInfo($"... now {CurrentGraph.DependencyCount} dependencies");
        }
Ejemplo n.º 10
0
        private void CreateToolbar()
        {
            _graphButton = new TextElement {
                tooltip = "Select a graph to edit"
            };
            _graphButton.AddToClassList(ToolbarButtonUssClassName);
            _graphButton.AddToClassList(ToolbarButtonLargeUssClassName);
            _graphButton.AddToClassList(ToolbarButtonFirstUssClassName);
            _graphButton.AddToClassList(ToolbarButtonGraphUssClassName);
            _graphButton.AddManipulator(new Clickable(() => ShowGraphPicker(GUIUtility.GUIToScreenPoint(_graphButton.worldBound.position))));

            _editButton = CreateEditMenu();
            _editButton.AddToClassList(ToolbarMenuUssClassName);

            _viewButton = CreateViewMenu();
            _viewButton.AddToClassList(ToolbarMenuUssClassName);

            _playButton = new Image {
                image = _playIcon.Texture, tooltip = "Resume execution of the graph"
            };
            _playButton.AddToClassList(ToolbarButtonUssClassName);
            _playButton.AddToClassList(ToolbarButtonSmallUssClassName);
            _playButton.AddManipulator(new Clickable(() => CurrentGraph.DebugPlay()));

            _pauseButton = new Image {
                image = _pauseIcon.Texture, tooltip = "Pause the execution of the graph"
            };
            _pauseButton.AddToClassList(ToolbarButtonUssClassName);
            _pauseButton.AddToClassList(ToolbarButtonSmallUssClassName);
            _pauseButton.AddManipulator(new Clickable(() => CurrentGraph.DebugPause()));

            _stepButton = new Image {
                image = _stepIcon.Texture, tooltip = "Step forward one node in the graph"
            };
            _stepButton.AddToClassList(ToolbarButtonUssClassName);
            _stepButton.AddToClassList(ToolbarButtonSmallUssClassName);
            _stepButton.AddManipulator(new Clickable(() => CurrentGraph.DebugStep()));

            _stopButton = new Image {
                image = _stopIcon.Texture, tooltip = "Stop executing the graph", tintColor = Color.gray
            };
            _stopButton.AddToClassList(ToolbarButtonUssClassName);
            _stopButton.AddToClassList(ToolbarButtonSmallUssClassName);
            _stopButton.AddManipulator(new Clickable(() => CurrentGraph.DebugStop()));

            _breakButton = new VisualElement {
                tooltip = "Enable/Disable node breakpoints for all graphs"
            };
            _breakButton.AddToClassList(ToolbarButtonUssClassName);
            _breakButton.AddToClassList(ToolbarButtonSmallUssClassName);
            _breakButton.AddToClassList(ToolbarButtonFirstUssClassName);
            _breakButton.AddManipulator(new Clickable(ToggleBreakpointsEnabled));

            var breakButton = new VisualElement();

            breakButton.AddToClassList(ToolbarButtonBreakpointUssClassName);

            _breakButton.Add(breakButton);

            _loggingButton = new Image {
                image = _logIcon.Texture, tooltip = "Enable/Disable logging of graph execution for all graphs"
            };
            _loggingButton.AddToClassList(ToolbarButtonUssClassName);
            _loggingButton.AddToClassList(ToolbarButtonSmallUssClassName);
            _loggingButton.AddManipulator(new Clickable(ToggleLoggingEnabled));

            _lockButton = new Image {
                tintColor = Color.black, tooltip = "Lock/Unlock this window so it won't be used when other graphs are opened"
            };
            _lockButton.AddToClassList(ToolbarButtonUssClassName);
            _lockButton.AddToClassList(ToolbarButtonSmallUssClassName);
            _lockButton.AddToClassList(ToolbarButtonLockUssClassName);
            _lockButton.AddManipulator(new Clickable(ToggleLockingEnabled));

            var watchButton = new Image {
                image = Icon.View.Texture, tooltip = "Open the Watch Window"
            };

            watchButton.AddToClassList(ToolbarButtonUssClassName);
            watchButton.AddToClassList(ToolbarButtonSmallUssClassName);
            watchButton.AddManipulator(new Clickable(WatchWindow.ShowWindow));

            RefreshToolbar();

            var toolbar = new Toolbar();

            toolbar.AddToClassList(ToolbarUssClassName);
            toolbar.Add(_graphButton);
            toolbar.Add(_editButton);
            toolbar.Add(_viewButton);
            toolbar.Add(_playButton);
            toolbar.Add(_pauseButton);
            toolbar.Add(_stepButton);
            toolbar.Add(_stopButton);
            toolbar.Add(new ToolbarSpacer {
                flex = true
            });
            toolbar.Add(_breakButton);
            toolbar.Add(_loggingButton);
            toolbar.Add(watchButton);
            toolbar.Add(_lockButton);

            Add(toolbar);
        }
Ejemplo n.º 11
0
        private void button2_Click(object sender, EventArgs e)
        {
            List <Node> nodeselected = new List <Node>();

            nodeselected.Add(CurrentGraph.GetNodeById(0));

            //foreach (ListViewItem item in listView1.SelectedItems) {
            //    var node = (Node)item.Tag;
            //    nodeselected.Add(CurrentGraph.GetNodeById(node.GetId()));
            //}

            foreach (ListViewItem item in listView1.SelectedItems)
            {
                var node = (Node)item.Tag;
                foreach (var item2 in CurrentGraph.Nodes)
                {
                    if (item2.Value.Name == node.Name)
                    {
                        nodeselected.Add(CurrentGraph.GetNodeById(item2.Value.GetId()));
                    }
                }
            }

            Queue <Node> nodeFila = new Queue <Node>();

            nodeFila.Enqueue(CurrentGraph.GetNodeById(0));
            Node          nodePai        = null;
            Node          inicio         = null;
            Node          fim            = null;
            List <int>    visited        = new List <int>();
            List <string> visitedProf    = new List <string>();
            double        distancia      = double.MaxValue;
            double        distanciaAux   = 0;
            double        distanciaTotal = 0;
            var           flag           = 0;

            while (nodeFila.Count > 0 && visited.Count <= nodeselected.Count)
            {
                nodePai = nodeFila.Dequeue();
                foreach (var item in nodeselected)
                {
                    if (!visitedProf.Contains(item.profissao) && nodePai.profissao != item.profissao && nodePai != null && nodePai.Name != item.Name && !visited.Contains(nodePai.GetId()) && !visited.Contains(item.GetId()) && CurrentGraph.GetNodeById(nodePai.GetId()).AdjacencyList[CurrentGraph.GetNodeById(item.GetId())].Cost <= distancia)
                    {
                        distancia = CurrentGraph.GetNodeById(nodePai.GetId()).AdjacencyList[CurrentGraph.GetNodeById(item.GetId())].Cost;
                        if (double.Parse(textBox1.Text) >= distancia)
                        {
                            distanciaAux += distancia;
                            if (distanciaAux <= double.Parse(textBox1.Text) && !visitedProf.Contains(item.profissao))
                            {
                                inicio = CurrentGraph.Nodes[CurrentGraph.Nodes.Keys.ToArray()[nodePai.GetId()]];
                                fim    = CurrentGraph.Nodes[CurrentGraph.Nodes.Keys.ToArray()[item.GetId()]];
                                Steps  = CurrentGraph.Dijkstra(inicio, fim);
                            }
                        }
                    }
                }
                nodeFila.Enqueue(fim);
                if (inicio != null)
                {
                    if (!visitedProf.Contains(fim.profissao))
                    {
                        distanciaTotal += inicio.AdjacencyList[fim].Cost;
                    }
                    flag = 0;
                    visited.Add(inicio.GetId());
                    visitedProf.Add(fim.profissao);
                    distancia    = double.MaxValue;
                    CurrentStep  = Steps.Count - 1;
                    CurrentGraph = Steps[CurrentStep];
                    RefreshGraphDraw();
                }
                else
                {
                    MessageBox.Show("Não existe nenhum serviço nas proximidades");
                    return;
                }
            }
            if (inicio != null)
            {
                inicio       = CurrentGraph.Nodes[CurrentGraph.Nodes.Keys.ToArray()[nodePai.GetId()]];
                fim          = CurrentGraph.Nodes[CurrentGraph.Nodes.Keys.ToArray()[0]];
                Steps        = CurrentGraph.Dijkstra(inicio, fim);
                CurrentStep  = Steps.Count - 1;
                CurrentGraph = Steps[CurrentStep];
                RefreshGraphDraw();
            }
            CurrentGraph    = BaseGraph.Copy();
            distanciaTotal += inicio.AdjacencyList[fim].Cost;
            MessageBox.Show("Total Percorrido " + distanciaTotal.ToString("F") + " KM");
        }
Ejemplo n.º 12
0
        private void button1_Click(object sender, EventArgs e)
        {
            var filecontend = string.Empty;
            var file        = string.Empty;

            string[] trabalhadores;
            using (OpenFileDialog open = new OpenFileDialog())
            {
                open.InitialDirectory = Path.Combine(Application.StartupPath);
                open.Filter           = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                if (open.ShowDialog() == DialogResult.OK)
                {
                    file = open.FileName;
                    var filestream = open.OpenFile();
                    using (StreamReader reader = new StreamReader(filestream, Encoding.GetEncoding("iso-8859-1")))
                    {
                        filecontend = reader.ReadToEnd();
                    }
                }
            }
            filecontend   = filecontend.Replace("\r", "");
            trabalhadores = filecontend.Split(',', ';', '\n');
            for (int i = 0; i < trabalhadores.Length; i = i + 5)
            {
                trabalhadores[i + 1] = trabalhadores[i + 1].Replace('.', ',');
                trabalhadores[i + 2] = trabalhadores[i + 2].Replace(".", ",");
            }
            CurrentGraph.AddNode("julio", "-15,836073", "-47,912019", "estudante", true);
            for (int i = 0; i < trabalhadores.Length; i = i + 5)
            {
                if (bool.Parse(trabalhadores[i + 4]) == true)
                {
                    CurrentGraph.AddNode(trabalhadores[i], trabalhadores[i + 1], trabalhadores[i + 2], trabalhadores[i + 3], bool.Parse(trabalhadores[i + 4]));
                }
            }
            for (int i = 0; i < CurrentGraph.Nodes.Count; i++)
            {
                for (int j = 0; j < CurrentGraph.Nodes.Count; j++)
                {
                    if (i != j)
                    {
                        CurrentGraph.AddAdjacency(CurrentGraph.GetNodeById(i), CurrentGraph.GetNodeById(j), converterCord(CurrentGraph.GetNodeById(i).latitude, CurrentGraph.GetNodeById(j).latitude, CurrentGraph.GetNodeById(i).longitude, CurrentGraph.GetNodeById(j).longitude));
                    }
                }
            }
            listView1.Columns.Add("Nome", 121);
            listView1.Columns.Add("Profissão", 121);
            List <string> Adicionado = new List <string>();

            for (int i = 1; i < CurrentGraph.Nodes.Count; i++)
            {
                var item1 = new ListViewItem(new[] { CurrentGraph.GetNodeById(i).Name, CurrentGraph.GetNodeById(i).profissao });
                //var item1 = new ListViewItem(new[] { CurrentGraph.GetNodeById(i).profissao });
                item1.Tag = CurrentGraph.GetNodeById(i);
                var node = (Node)item1.Tag;
                //if (!Adicionado.Contains(node.profissao)) {
                listView1.Items.Add(item1);
                //Adicionado.Add(node.profissao);
                //}
            }
            BaseGraph = CurrentGraph.Copy();
            RefreshGraphDraw();
        }
        private void InitToolBarCommands()
        {
            #region Первый этап
            #region Добавление рёбер
            var phase1AddEdgeCommand = new ToolBarToggleCommand(
                () =>
            {
                IsMouseVerticesMovingEnabled = false;
                IsEgesAddingEnabled          = true;
                _state = State.EdgesAdding;
            },
                () =>
            {
                IsMouseVerticesMovingEnabled = true;
                IsEgesAddingEnabled          = false;
                _state = State.Nothing;
            },
                () => _state == State.Nothing,
                () => true
                )
            {
                Image       = new BitmapImage(GetImageUri("Arrow.png")),
                Description = Strings.Strings_RU.buttonEdges
            };
            #endregion

            #region Завершить этап
            var allSubgraphs = new ObservableCollection <IGraph>();

            var phase1Command = new ToolBarInstantCommand(
                () =>
            {
                var solve = true;
                var gp    = new GraphPrinter();
                UserActionsManager.RegisterInfo(Strings.Strings_RU.stage1Check + gp.GraphToString(CurrentGraph));
                CurrentGraph.Vertices.ForEach(v1 =>
                                              CurrentGraph.Vertices.ForEach(v2 =>
                {
                    solve = solve && (v1.Equals(v2) || (CurrentGraph[v1, v2] == null ^
                                                        GivenGraph[
                                                            GivenGraph.Vertices.Single(v1.Equals),
                                                            GivenGraph.Vertices.Single(v2.Equals)] == null
                                                        ));
                }
                                                                            ));
                if (solve)
                {
                    UserActionsManager.RegisterInfo(Strings.Strings_RU.stage1Done);
                    GivenGraph   = CurrentGraph;
                    CurrentGraph = new UndirectedGraph();

                    Phase1ToolBarVisibility = Visibility.Collapsed;
                    Phase2ToolBarVisibility = Visibility.Visible;
                    L1 = Strings.Strings_RU.subgraph;

                    FindAllSubgraphs(GivenGraph, 0, GivenGraph.Vertices.ToList(), allSubgraphs);

                    new SimpleDialog("Справка", Strings.Strings_RU.stage2Help).Show();
                }
                else
                {
                    UserActionsManager.RegisterMistake(Strings.Strings_RU.stage1Mistake1, 10);
                }
            },
                () => _state == State.Nothing
                )
            {
                Image       = new BitmapImage(GetImageUri("Check.png")),
                Description = Strings.Strings_RU.stage1DoneButtonDisc
            };
            #endregion

            #region Справка
            var phase1HelpCommand = new ToolBarInstantCommand(
                () =>
            {
                new SimpleDialog("Справка", Strings.Strings_RU.stage1Help).Show();
            },
                () => _state == State.Nothing
                )
            {
                Description = Strings.Strings_RU.buttonHelp,
                Image       = new BitmapImage(GetImageUri("Info.png"))
            };
            #endregion

            #region Молния
            var thunderbolt1 = new ToolBarInstantCommand(
                () =>
            {
                UserActionsManager.RegisterInfo(Strings.Strings_RU.stage1ThunderCall);
                CurrentGraph.Vertices.ForEach(v1 =>
                                              CurrentGraph.Vertices.ForEach(v2 =>
                {
                    if (!v1.Equals(v2) && CurrentGraph[v1, v2] == null && GivenGraph[
                            GivenGraph.Vertices.Single(v1.Equals),
                            GivenGraph.Vertices.Single(v2.Equals)] == null)
                    {
                        CurrentGraph.AddEdge(new UndirectedEdge((Vertex)v1, (Vertex)v2));
                    }
                    if (!v1.Equals(v2) && CurrentGraph[v1, v2] != null && GivenGraph[
                            GivenGraph.Vertices.Single(v1.Equals),
                            GivenGraph.Vertices.Single(v2.Equals)] != null)
                    {
                        CurrentGraph.RemoveEdge(CurrentGraph[v1, v2]);
                    }
                }
                                                                            ));
            },
                () => _state == State.Nothing
                )
            {
                Description = "Молния",
                Image       = new BitmapImage(GetImageUri("thunder.png"))
            };
            #endregion
            #endregion

            #region Второй этап
            #region Добавление вершин

            var vertexDialogCommand = new ToolBarInstantCommand(
                () =>
            {
                var dialog = new VertexDialog((UndirectedGraph)CurrentGraph, GivenGraph.Vertices);
                dialog.Show();
                dialog.Closed += (sender, args) =>
                {
                    var buf      = CurrentGraph;
                    CurrentGraph = null;
                    CurrentGraph = buf;
                };
            },
                () => _state == State.Nothing)
            {
                Image       = new BitmapImage(GetImageUri("Vertexes.png")),
                Description = Strings.Strings_RU.buttonVertexDialog
            };
            #endregion

            #region Добавление рёбер
            var phase2AddEdgeCommand = new ToolBarToggleCommand(
                () =>
            {
                IsMouseVerticesMovingEnabled = false;
                IsEgesAddingEnabled          = true;
                _state = State.EdgesAdding;
            },
                () =>
            {
                IsMouseVerticesMovingEnabled = true;
                IsEgesAddingEnabled          = false;
                _state = State.Nothing;
            },
                () => _state == State.Nothing,
                () => true
                )
            {
                Image       = new BitmapImage(GetImageUri("Arrow.png")),
                Description = Strings.Strings_RU.buttonEdges
            };
            #endregion

            #region Добавление подграфов
            var subgraphCommand = new ToolBarInstantCommand(
                () =>
            {
                var subgraph = true;
                var unique   = Unique((UndirectedGraph)CurrentGraph, GraphLib.Lib);
                var gp       = new GraphPrinter();
                UserActionsManager.RegisterInfo(Strings.Strings_RU.stage2Check + gp.GraphToString(CurrentGraph));
                CurrentGraph.Vertices.ForEach(v1 =>
                {
                    CurrentGraph.Vertices.ForEach(v2 =>
                    {
                        subgraph &= v1.Equals(v2) || (CurrentGraph[v1, v2] == null ^ GivenGraph[
                                                          GivenGraph.Vertices.Single(v1.Equals),
                                                          GivenGraph.Vertices.Single(v2.Equals)] != null);
                    }
                                                  );
                }
                                              );
                if (CurrentGraph.VerticesCount == 0)
                {
                    return;
                }
                if (!subgraph)
                {
                    UserActionsManager.RegisterMistake(Strings.Strings_RU.stage2Mistake1, 10);
                    return;
                }

                if (!unique)
                {
                    UserActionsManager.RegisterMistake(Strings.Strings_RU.stage2Mistake2, 10);
                    return;
                }

                var newGraph = UndirectedGraph.CreateEmpty(CurrentGraph.VerticesCount);
                for (var i = 0; i < CurrentGraph.VerticesCount; i++)
                {
                    for (var j = i + 1; j < CurrentGraph.VerticesCount; j++)
                    {
                        if (CurrentGraph[CurrentGraph.Vertices[i], CurrentGraph.Vertices[j]] != null)
                        {
                            newGraph.AddEdge(new UndirectedEdge(newGraph.Vertices[i], newGraph.Vertices[j]));
                        }
                    }
                }
                UserActionsManager.RegisterInfo(Strings.Strings_RU.stage2Subgraph);

                GraphLib.Lib.Add(newGraph);
            },
                () => _state == State.Nothing
                )
            {
                Image       = new BitmapImage(GetImageUri("Collection.png")),
                Description = Strings.Strings_RU.buttonCheckSubgraph
            };
            #endregion

            #region Справка
            var phase2HelpCommand = new ToolBarInstantCommand(
                () =>
            {
                new SimpleDialog("Справка", Strings.Strings_RU.stage2Help).Show();
            },
                () => _state == State.Nothing
                )
            {
                Description = Strings.Strings_RU.buttonHelp,
                Image       = new BitmapImage(GetImageUri("Info.png"))
            };
            #endregion

            #region Молния
            var thunderbolt2 = new ToolBarInstantCommand(
                () =>
            {
                UserActionsManager.RegisterInfo(Strings.Strings_RU.stage2ThunderCall);
                allSubgraphs.ForEach(s =>
                {
                    if (Unique(s, GraphLib.Lib))
                    {
                        GraphLib.Lib.Add(s);
                    }
                });
                var g = UndirectedGraph.CreateEmpty(GivenGraph.VerticesCount);
                for (var i = 0; i < g.VerticesCount; i++)
                {
                    for (var j = i + 1; j < g.VerticesCount; j++)
                    {
                        if (GivenGraph[GivenGraph.Vertices[i], GivenGraph.Vertices[j]] != null)
                        {
                            g.AddEdge(new UndirectedEdge(g.Vertices[i], g.Vertices[j]));
                        }
                    }
                }
                GraphLib.Lib.Add(g);
            },
                () => _state == State.Nothing
                )
            {
                Description = "Молния",
                Image       = new BitmapImage(GetImageUri("thunder.png"))
            };
            #endregion

            #region Завершить этап
            var phase2Command = new ToolBarInstantCommand(
                () =>
            {
                if (GraphLib.Lib.Count > allSubgraphs.Count)
                {
                    UserActionsManager.RegisterInfo(Strings.Strings_RU.stage2Done);
                    UserActionsManager.ReportThatTaskFinished();
                }
                else
                {
                    UserActionsManager.RegisterMistake(Strings.Strings_RU.stage2Mistake3, 10);
                }
            },
                () => _state == State.Nothing
                )
            {
                Image       = new BitmapImage(GetImageUri("Check.png")),
                Description = Strings.Strings_RU.stage2DoneButtonDisc
            };
            #endregion
            #endregion

            Phase1ToolBarCommands = new ObservableCollection <ToolBarCommandBase>
            {
                phase1AddEdgeCommand,
                phase1Command,
                phase1HelpCommand
                #if DEBUG
                ,
                thunderbolt1
                #endif
            };
            Phase2ToolBarCommands = new ObservableCollection <ToolBarCommandBase>
            {
                vertexDialogCommand,
                phase2AddEdgeCommand,
                subgraphCommand,
                phase2Command,
                phase2HelpCommand
                #if DEBUG
                ,
                thunderbolt2
                #endif
            };
        }