internal void BeginEditTextOnSelected()
        {
            ItemLostFocus();

            selectedForEditing = (SelectedItem as ExplorerTreeViewItem);

            if (selectedForEditing == null) return;

            TextBox tb = new TextBox();
            tb.Text = selectedForEditing.Text;
            tb.LostFocus += tb_LostFocus;
            tb.KeyDown += tb_KeyDown;
            tb.Focusable = true;

            beforeEditingPath = selectedForEditing.FullPath;
            (selectedForEditing.Header as StackPanel).Children.RemoveAt(1);
            (selectedForEditing.Header as StackPanel).Children.Add(tb);
            selectedForEditing.CanDrag = false;

            tb.Select(0, tb.Text.Length - (System.IO.Path.GetExtension(tb.Text).Length));
            tb.Focus();
        }
 void SortNode(ExplorerTreeViewItem node)
 {
     node.Items.SortDescriptions.Clear();
     node.Items.SortDescriptions.Add(new SortDescription("PriorityIndex", ListSortDirection.Ascending));
     node.Items.SortDescriptions.Add(new SortDescription("Text", ListSortDirection.Ascending));
     node.Items.Refresh();
     node.IsExpanded = true;
 }
        // TODO behaviour opening .cs files and .sln
        private void HandleOpenFile(ExplorerTreeViewItem explorerTreeViewItem)
        {
            if (explorerTreeViewItem.CanDrag == false)
                return;

            // Optional: implement open file behaviour
            string extension = System.IO.Path.GetExtension(explorerTreeViewItem.Text).ToLower().Trim();

            // is directory?
            if (extension.Equals(string.Empty)) return;

            if (!AcceptedExtensions.Contains(extension)) return;

            switch (extension)
            {
                case ".gibbo":
                    //EditorHandler.ChangeSelectedObject(SceneManager.GameProject);
                    break;
                case ".scene":
                    //System.Threading.ThreadPool.QueueUserWorkItem(o => Gibbo.Library.SceneManager.LoadScene(node.FullPath));
                    if (SceneManager.ActiveScene != null && MessageBox.Show("Do you want to save the current scene?", "Warning", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        SceneManager.SaveActiveScene();
                    }

                    Gibbo.Library.SceneManager.LoadScene(explorerTreeViewItem.FullPath, true);
                    EditorHandler.ChangeSelectedObject(Gibbo.Library.SceneManager.ActiveScene);
                    EditorHandler.SelectedGameObjects = new List<GameObject>();
                    EditorHandler.SceneTreeView.CreateView();
                    //EditorHandler.EditorSplitterContainer.Panel2Collapsed = true;
                    EditorHandler.ChangeSelectedObjects();
                    break;
                case ".cs":
                    // TODO: add behaviour for opening .cs files
                    string projectPath = SceneManager.GameProject.ProjectPath;

                    #region SharpDevelop and Xamarin tries

                    // MessageBox.Show(@"C:\Program Files (x86)\SharpDevelop\4.3\bin\SharpDevelop.exe :" + SceneManager.GameProject.ProjectPath + "\\Scripts.sln" + " : " + explorerTreeViewItem.FullPath);
                    //C:\Program Files (x86)\SharpDevelop\4.3\bin\SharpDevelop.exe    
                    // C:\Program Files (x86)\Xamarin Studio\bin\XamarinStudio.exe
                    // if (sharpDevelop == null || sharpDevelop.HasExited)
                    // {
                    //     ProcessStartInfo pinfo = new ProcessStartInfo();
                    //     pinfo.FileName = @"C:\Program Files (x86)\Xamarin Studio\bin\XamarinStudio.exe";
                    //     pinfo.Arguments = "-nologo " + "Scripts.sln " + GibboHelper.MakeExclusiveRelativePath(SceneManager.GameProject.ProjectPath, explorerTreeViewItem.FullPath);
                    //     pinfo.WorkingDirectory = SceneManager.GameProject.ProjectPath;
                    //     //pinfo.RedirectStandardInput = true;
                    //     //pinfo.UseShellExecute = false;
                    //     sharpDevelop = Process.Start(pinfo);
                    // }
                    // else
                    // {
                    //     SetForegroundWindow(sharpDevelop.MainWindowHandle);
                    //     //sharpDevelop.

                    //     //sharpDevelop.StandardInput.WriteLine(GibboHelper.MakeExclusiveRelativePath(SceneManager.GameProject.ProjectPath, explorerTreeViewItem.FullPath));

                    //     //ProcessStartInfo pinfo = new ProcessStartInfo();
                    //     //pinfo.FileName = @"C:\Program Files (x86)\SharpDevelop\4.3\bin\SharpDevelop.exe";
                    //     //pinfo.Arguments = GibboHelper.MakeExclusiveRelativePath(SceneManager.GameProject.ProjectPath, explorerTreeViewItem.FullPath);
                    //     //sharpDevelop.StartInfo = pinfo;
                    //     //sharpDevelop.Start();
                    //     //using (StreamWriter sw = new StreamWriter(sharpDevelop.StandardInput))
                    //     //{
                    //     //    if (sw.BaseStream.CanWrite)
                    //     //    {
                    //     //        sw.WriteLine(GibboHelper.MakeExclusiveRelativePath(SceneManager.GameProject.ProjectPath, explorerTreeViewItem.FullPath));
                    //     //    }
                    //     //}
                    //}
                    //break;

                    // Process.Start(@"C:\Program Files (x86)\SharpDevelop\4.3\bin\SharpDevelop.exe " + SceneManager.GameProject.ProjectPath + "\\Scripts.sln");

                    #endregion

                    // check if default editor is lime
                    if (Properties.Settings.Default.DefaultScriptEditor.ToLower().Equals("lime"))
                    {
                        LimeScriptEditor.OpenScript(explorerTreeViewItem.FullPath);
                    }
                    // else, try visual studio
                    else if (EditorUtils.CheckVisualStudioExistance(Properties.Settings.Default.DefaultScriptEditor))
                    {
                        try
                        {
                            string rf = string.Empty;
                            string editor = Properties.Settings.Default.DefaultScriptEditor;
                            switch (editor)
                            {
                                case "VisualStudio2015":
                                    rf = "VisualStudio.DTE.14.0";
                                    break;
                                case "VisualStudio2013":
                                    rf = "VisualStudio.DTE.12.0";
                                    break;
                                case "VisualStudio2012":
                                    rf = "VisualStudio.DTE.11.0";
                                    break;
                                case "VisualStudio2010":
                                    rf = "VisualStudio.DTE.10.0";
                                    break;
                                //case "CSExpress2010":
                                //    rf = "VCSExpress.DTE.10.0";
                                //    break;
                            }

                            // attempts to find a solution
                            EnvDTE.DTE tmp2DTE;
                            if (EditorCommands.TryToRestoreSolution(out tmp2DTE))
                            {
                                // assign dte if a solution was found
                                dte = tmp2DTE as EnvDTE80.DTE2;
                            }

                            /*
                            // if instance exists, try to make it visible
                            if (dte != null)
                            {
                                try
                                {
                                    // attempts to access main window and make it visible
                                    dte.MainWindow.Visible = true;
                                }
                                catch (Exception)
                                {
                                    // if unable, set instance to null in order to create one.
                                    dte = null;
                                }
                            }*/

                            // if there's no instance, create one
                            if (dte == null)
                            {
                                // store the specified type visual studio instance (2015, 2013, 2012, 2010...)
                                Type type = Type.GetTypeFromProgID(rf);
                                // create that type of instance
                                dte = (EnvDTE80.DTE2)Activator.CreateInstance(type);

                                // create an unique guid and set it to dte main window caption, so we can search for it later on
                                string uniqueGuid = Guid.NewGuid().ToString();

                                // change main window title using user32.dll SetWindowText. Unable to change it directly using 'set' » dte.MainWindow.Caption = "x"
                                SetWindowText(new System.IntPtr(dte.MainWindow.HWnd), uniqueGuid);

                                // make the window visible
                                dte.MainWindow.Visible = true;

                                // get every visual studio process (devenv.exe)
                                Process[] pVSList = Process.GetProcessesByName("DEVENV");
                                // reset visual studio instance PID
                                EditorCommands.VisualStudioInstancePID = 0;
                                // iterate through every process and check its title
                                foreach (Process pVS in pVSList)
                                {
                                    // if the title is the Guid we stored previously, then store it
                                    if (uniqueGuid != string.Empty && pVS.MainWindowTitle.Equals(uniqueGuid))
                                    {
                                        // store the visual studio instance PID
                                        EditorCommands.VisualStudioInstancePID = pVS.Id;
                                        break;
                                    }
                                }

                                // open solution
                                dte.Solution.Open(UserPreferences.Instance.ProjectSlnFilePath);
                            }

                            // open document, which changes the title (which we had set to a Guid) to its name
                            dte.Documents.Open(explorerTreeViewItem.FullPath);
                        }
                        catch (Exception e)
                        {
                            Properties.Settings.Default.DefaultScriptEditor = "None";
                            Properties.Settings.Default.Save();

                            MessageBox.Show("You don't have selected a default scripting editor!\nEither select one on the Settings Window or open the scripts solution (.sln file) with other IDE to manage the scripts", "Error!");
                        }

                    }
                    else
                    {
                        MessageBox.Show("You don't have selected a default scripting editor.\nEither select one on the Settings Window or open the scripts solution (.sln file) with other IDE to manage the scripts", "Error!");
                    }
                    break;
                case ".sln":
                    // checks if the file is a valid solution file (e.g. one could place a dummy file with .sln extension and try to open it. In that case, there's
                    // no need to continue)
                    bool validSolution = UserPreferences.Instance.ProjectSlnFilePath.Equals(explorerTreeViewItem.FullPath);

                    // if it's a valid solution file, check if solution is already opened in order to avoid duplicate instances
                    EnvDTE.DTE tmpDTE;
                    if (validSolution && !EditorCommands.TryToRestoreSolution(out tmpDTE))
                    {
                        // dte is null, since no visual studion solution instance was found
                        // start solution process
                        Process vsProcess = Process.Start(UserPreferences.Instance.ProjectSlnFilePath);
                        // store its Id
                        EditorCommands.VisualStudioInstancePID = vsProcess.Id;

                    }
                    // if it's not a valid solution, pop a message warning the user
                    else if (!validSolution)
                    {
                        MessageBox.Show("Invalid solution file.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    break;
                default:
                    // Default behaviour, tries to use the default user opening for this type of file:
                    try
                    {
                        Process.Start(explorerTreeViewItem.FullPath);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    break;
            }
        }
        private ExplorerTreeViewItem AddNode(ExplorerTreeViewItem root, string text, int priorityIndex, ImageSource imageSource = null)
        {
            ExplorerTreeViewItem _node = new ExplorerTreeViewItem();
            _node.Style = (Style)FindResource("IgniteTreeViewItem");
            _node.PriorityIndex = priorityIndex;
            _node.Text = text;
            _node.MouseDoubleClick += newNode_MouseDoubleClick;
            
            StackPanel sp = new StackPanel();
            sp.Orientation = Orientation.Horizontal;
            sp.Children.Add(new Image() { Source = imageSource });
            sp.Children.Add(new TextBlock() { Text = System.IO.Path.GetFileName(text), Margin = new Thickness(MARGIN, 0, 0, 0) });

            _node.Header = sp;

            if (root != null)
            {
                root.Items.Add(_node);
                root.Items.Refresh();
            }

            return _node;
        }
        private void FillChildNodes(ExplorerTreeViewItem node)
        {
            try
            {
                DirectoryInfo[] dirs = new DirectoryInfo(node.FullPath).GetDirectories();

                // Add current directory Files:
                string[] files = Directory.GetFiles(node.FullPath);
                foreach (string file in files)
                {
                    if (AcceptedExtensions.Contains(System.IO.Path.GetExtension(file.ToLower())))
                    {
                        ExplorerTreeViewItem newNode = AddNode(node, System.IO.Path.GetFileName(file), 10, GetImageSource(System.IO.Path.GetExtension(file)));

                        newNode.Tag = "file";
                        newNode.ContextMenu = this.fileContextMenu;
                    }
                }

                node.Items.Refresh();

                // Add Sub Directories:
                foreach (DirectoryInfo dir in dirs)
                {
                    ExplorerTreeViewItem _node = AddNode(node, System.IO.Path.GetFileName(dir.Name), 5, (ImageSource)FindResource("FolderIcon"));
                    _node.ContextMenu = this.directoryContextMenu;
                    _node.Tag = "directory";

                    // Does the cur directory contain any files or sub directories?
                    if (Directory.GetFiles(dir.FullName).Count() > 0 ||
                        Directory.GetDirectories(dir.FullName).Count() > 0)
                    {
                        AddNode(_node, "*", 0);
                        _node.Expanded += Node_Expanded;

                    }

                    _node.Items.SortDescriptions.Clear();
                    _node.Items.SortDescriptions.Add(new SortDescription("PriorityIndex", ListSortDirection.Ascending));
                    _node.Items.SortDescriptions.Add(new SortDescription("Text", ListSortDirection.Ascending));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
        private void RealtimeFolderUpdater(ExplorerTreeViewItem folder)
        {
            // search for deleted files & directories on explorer
            foreach (ExplorerTreeViewItem node in folder.Items)
            {
                if (node.Tag.ToString().ToLower().Equals("directory"))
                {
                    if (!Directory.Exists(node.FullPath))
                        (node.Parent as ExplorerTreeViewItem).Items.Remove(node);
                }
                else
                {
                    if (!File.Exists(node.FullPath))
                    {
                        if (!(System.IO.Path.GetExtension(node.FullPath).ToLower().Equals(".cs") && !node.CanDrag))
                            (node.Parent as ExplorerTreeViewItem).Items.Remove(node);
                    }
                }
            }

            // search for new files on explorer:
            foreach (string filename in Directory.GetFiles(folder.FullPath))
            {
                if (!this.AcceptedExtensions.Contains(System.IO.Path.GetExtension(filename))) continue;

                bool found = false;
                foreach (ExplorerTreeViewItem node in folder.Items)
                {
                    //Console.WriteLine(filename + "::::" + node.FullPath.ToLower());
                    if (node.FullPath.ToLower().Equals(filename.ToLower()) && node.Tag.ToString().Equals("file"))
                    {
                        found = true;
                        break;
                    }
                }

                // file exists but it is not on the treeview?
                if (!found)
                {
                    // add item
                    ExplorerTreeViewItem newNode = AddNode(folder, System.IO.Path.GetFileName(filename), 10, GetImageSource(System.IO.Path.GetExtension(filename)));

                    newNode.Tag = "file";
                    newNode.ContextMenu = this.fileContextMenu;
                }
            }

            // search for new directories on explorer:
            foreach (string folderPath in Directory.GetDirectories(folder.FullPath))
            {
                bool found = false;
                foreach (ExplorerTreeViewItem node in folder.Items)
                {
                    if (node.FullPath.ToLower().Equals(folderPath.ToLower()) && node.Tag.ToString().Equals("directory"))
                    {
                        found = true;
                        break;
                    }
                }

                // directory exists but it is not on the treeview?
                if (!found)
                {
                    // add item
                    ExplorerTreeViewItem _node = AddNode(folder, System.IO.Path.GetFileName(folderPath), 5, (ImageSource)FindResource("FolderIcon"));
                    _node.ContextMenu = this.directoryContextMenu;
                    _node.Tag = "directory";

                    // Does the cur directory contain any files or sub directories?
                    if (Directory.GetFiles(folderPath).Count() > 0 ||
                        Directory.GetDirectories(folderPath).Count() > 0)
                    {
                        AddNode(_node, "*", 0);
                        _node.Expanded += Node_Expanded;

                    }

                    _node.Items.SortDescriptions.Clear();
                    _node.Items.SortDescriptions.Add(new SortDescription("PriorityIndex", ListSortDirection.Ascending));
                    _node.Items.SortDescriptions.Add(new SortDescription("Text", ListSortDirection.Ascending));
                }
            }

            foreach (ExplorerTreeViewItem item in folder.Items)
            {
                if (item.PriorityIndex == 5)
                {
                    if ((item.Items.Count > 0 && (item.Items[0] as ExplorerTreeViewItem).Text != "*") || item.Items.Count == 0)
                        RealtimeFolderUpdater(item);
                }
            }
        }
        // TODO behaviour opening .cs files and .sln
        private void HandleOpenFile(ExplorerTreeViewItem explorerTreeViewItem)
        {
            if (explorerTreeViewItem.CanDrag == false)
                return;

            // Optional: implement open file behaviour
            string extension = System.IO.Path.GetExtension(explorerTreeViewItem.Text).ToLower().Trim();

            // is directory?
            if (extension.Equals(string.Empty)) return;

            if (!AcceptedExtensions.Contains(extension)) return;

            switch (extension)
            {
                case ".gibbo":
                    //EditorHandler.ChangeSelectedObject(SceneManager.GameProject);
                    break;
                case ".scene":
                    //System.Threading.ThreadPool.QueueUserWorkItem(o => Gibbo.Library.SceneManager.LoadScene(node.FullPath));
                    if (SceneManager.ActiveScene != null && MessageBox.Show("Do you want to save the current scene?", "Warning", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        SceneManager.SaveActiveScene();
                    }

                    Gibbo.Library.SceneManager.LoadScene(explorerTreeViewItem.FullPath, true);
                    EditorHandler.ChangeSelectedObject(Gibbo.Library.SceneManager.ActiveScene);
                    EditorHandler.SelectedGameObjects = new List<GameObject>();
                    EditorHandler.SceneTreeView.CreateView();
                    //EditorHandler.EditorSplitterContainer.Panel2Collapsed = true;
                    EditorHandler.ChangeSelectedObjects();
                    break;
                case ".cs":
                    // TODO: add behaviour for opening .cs files
                    string projectPath = SceneManager.GameProject.ProjectPath;

                    // se o programa que, por defeito abre os ficheiros .cs n for o ddeexec abre com notepad ou algo do género : má solução
                    //var si = new System.Diagnostics.ProcessStartInfo { UseShellExecute = true, FileName = projectPath + @"\samples\SampleController.cs", Verb = "Open" };
                    //System.Diagnostics.Process.Start(si);

                    // funciona bastante bem da 1ª vez; pode ser complicado encontrar o caminho do startinfo.filename

                    //if (p == null || p.HasExited)
                    //    p = new Process();
                    //p.StartInfo.FileName = @"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.com";
                    //p.StartInfo.Arguments = projectPath + @"\Scripts.sln /command ""of " + explorerTreeViewItem.FullPath;
                    //p.Start();

                    //dte = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.11.0");

                   // MessageBox.Show(@"C:\Program Files (x86)\SharpDevelop\4.3\bin\SharpDevelop.exe :" + SceneManager.GameProject.ProjectPath + "\\Scripts.sln" + " : " + explorerTreeViewItem.FullPath);
                    //C:\Program Files (x86)\SharpDevelop\4.3\bin\SharpDevelop.exe    
                    // C:\Program Files (x86)\Xamarin Studio\bin\XamarinStudio.exe
                   // if (sharpDevelop == null || sharpDevelop.HasExited)
                   // {
                   //     ProcessStartInfo pinfo = new ProcessStartInfo();
                   //     pinfo.FileName = @"C:\Program Files (x86)\Xamarin Studio\bin\XamarinStudio.exe";
                   //     pinfo.Arguments = "-nologo " + "Scripts.sln " + GibboHelper.MakeExclusiveRelativePath(SceneManager.GameProject.ProjectPath, explorerTreeViewItem.FullPath);
                   //     pinfo.WorkingDirectory = SceneManager.GameProject.ProjectPath;
                   //     //pinfo.RedirectStandardInput = true;
                   //     //pinfo.UseShellExecute = false;
                   //     sharpDevelop = Process.Start(pinfo);
                   // }
                   // else
                   // {
                   //     SetForegroundWindow(sharpDevelop.MainWindowHandle);
                   //     //sharpDevelop.

                   //     //sharpDevelop.StandardInput.WriteLine(GibboHelper.MakeExclusiveRelativePath(SceneManager.GameProject.ProjectPath, explorerTreeViewItem.FullPath));

                   //     //ProcessStartInfo pinfo = new ProcessStartInfo();
                   //     //pinfo.FileName = @"C:\Program Files (x86)\SharpDevelop\4.3\bin\SharpDevelop.exe";
                   //     //pinfo.Arguments = GibboHelper.MakeExclusiveRelativePath(SceneManager.GameProject.ProjectPath, explorerTreeViewItem.FullPath);
                   //     //sharpDevelop.StartInfo = pinfo;
                   //     //sharpDevelop.Start();
                   //     //using (StreamWriter sw = new StreamWriter(sharpDevelop.StandardInput))
                   //     //{
                   //     //    if (sw.BaseStream.CanWrite)
                   //     //    {
                   //     //        sw.WriteLine(GibboHelper.MakeExclusiveRelativePath(SceneManager.GameProject.ProjectPath, explorerTreeViewItem.FullPath));
                   //     //    }
                   //     //}
                   //}
                    //break;

                   // Process.Start(@"C:\Program Files (x86)\SharpDevelop\4.3\bin\SharpDevelop.exe " + SceneManager.GameProject.ProjectPath + "\\Scripts.sln");

                    if (Properties.Settings.Default.DefaultScriptEditor.ToLower().Equals("lime"))
                    {
                        LimeScriptEditor.OpenScript(explorerTreeViewItem.FullPath);
                    }
                    else if (EditorUtils.CheckVisualStudioExistance(Properties.Settings.Default.DefaultScriptEditor))
                    {
                        try
                        {
                            string rf = string.Empty;
                            string editor = Properties.Settings.Default.DefaultScriptEditor;
                            switch (editor)
                            {
                                case "VisualStudio2013":
                                    rf = "VisualStudio.DTE.12.0";
                                    break;
                                case "VisualStudio2012":
                                    rf = "VisualStudio.DTE.11.0";
                                    break;
                                case "VisualStudio2010":
                                    rf = "VisualStudio.DTE.10.0";
                                    break;
                                //case "CSExpress2010":
                                //    rf = "VCSExpress.DTE.10.0";
                                //    break;
                            }

                            if (dte == null || !dte.MainWindow.Visible)
                            {
                                Type type = Type.GetTypeFromProgID(rf);
                                dte = (EnvDTE80.DTE2)Activator.CreateInstance(type);
                                dte.MainWindow.Visible = true;
                                dte.Solution.Open(UserPreferences.Instance.ProjectSlnFilePath);
                            }

                            dte.Documents.Open(explorerTreeViewItem.FullPath);
                        }
                        catch (Exception)
                        {
                            Properties.Settings.Default.DefaultScriptEditor = "None";
                            Properties.Settings.Default.Save();

                            MessageBox.Show("You don't have selected a default scripting editor!\nEither select one on the Settings Window or open the scripts solution (.sln file) with other IDE to manage the scripts", "Error!");
                        }

                    }
                    else
                    {
                        MessageBox.Show("You don't have selected a default scripting editor.\nEither select one on the Settings Window or open the scripts solution (.sln file) with other IDE to manage the scripts", "Error!");
                    }
                    break;
                default:
                    // Default behaviour, tries to use the default user opening for this type of file:
                    try
                    {
                        Process.Start(explorerTreeViewItem.FullPath);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    break;
            }
        }