//05Sept2019 exact copy from OutputWindow.xaml. Not Sure if in future they will differ
        private void tvi_Selected(object sender, RoutedEventArgs e)
        {
            FrameworkElement fe  = sender as FrameworkElement;
            TreeViewItem     tvi = fe as TreeViewItem;

            ((tvi.Header as StackPanel).Children[0] as CheckBox).IsChecked = true;
            FrameworkElement tag = fe.Tag as FrameworkElement;
            //scrollviewer.BringIntoView(tag.GetVisualBounds(this));
            IAUControl control = tag as IAUControl;
            ////05Jun2013 control.outerborderthickness = new Thickness(1);
            string navtreeselcom = confService.GetConfigValueForKey("navtreeselectedcol");//23nov2012
            byte   red           = byte.Parse(navtreeselcom.Substring(3, 2), NumberStyles.HexNumber);
            byte   green         = byte.Parse(navtreeselcom.Substring(5, 2), NumberStyles.HexNumber);
            byte   blue          = byte.Parse(navtreeselcom.Substring(7, 2), NumberStyles.HexNumber);
            Color  c             = Color.FromArgb(255, red, green, blue);

            control.bordercolor          = new SolidColorBrush(c);// (Colors.Gold);//05Jun2013
            control.outerborderthickness = new Thickness(2);
            //Rect rct = new Rect(1, 1, tag.ActualWidth,tag.ActualHeight);
            tag.BringIntoView(); //treeview leaf node will appear selected as oppose to Focus()
            e.Handled = true;
            //tag.Focus();
            //(fe as TreeViewItem).Foreground = Brushes.LightBlue; //17Jan2013

            //ScrollViewer sv = this.scrollviewer;
            //sv.ScrollToVerticalOffset(NavTree.Items.IndexOf(tag));

            //ScrollViewer myScrollViewer = (ScrollViewer)NavTree.Template.FindName("_tv_scrollviewer_", NavTree);
            //myScrollViewer.ScrollToHome();
        }
        void tvi_Unselected(object sender, RoutedEventArgs e)
        {
            FrameworkElement fe      = sender as FrameworkElement;
            FrameworkElement tag     = fe.Tag as FrameworkElement;
            IAUControl       control = tag as IAUControl;

            control.bordercolor = new SolidColorBrush(Colors.Transparent);//05Jun2013
        }
        // Logic should'nt be same as in OutputWindow.xaml.cs because this is only meant for displaying output///
        void tvi_Selected(object sender, RoutedEventArgs e)
        {
            FrameworkElement fe  = sender as FrameworkElement;
            FrameworkElement tag = fe.Tag as FrameworkElement;

            IAUControl control = tag as IAUControl;

            control.bordercolor = new SolidColorBrush(Colors.Gold); //05Jun2013

            tag.BringIntoView();                                    //treeview leaf node will appear selected as oppose to Focus()
        }
        //05Sept2019 exact copy from OutputWindow.xaml. Not Sure if in future they will differ
        private void tvi_Unselected(object sender, RoutedEventArgs e)
        {
            FrameworkElement fe  = sender as FrameworkElement;
            FrameworkElement tag = fe.Tag as FrameworkElement;
            //scrollviewer.BringIntoView(tag.GetVisualBounds(this));
            IAUControl control = tag as IAUControl;

            ////05Jun2013 control.outerborderthickness = new Thickness(0);
            control.bordercolor = new SolidColorBrush(Colors.Transparent);//05Jun2013
            e.Handled           = true;
            //(fe as TreeViewItem).Foreground = Brushes.Black;
            //tag.Focus();
        }
        private void MainItem_Selected(object sender, RoutedEventArgs e)
        {
            FrameworkElement fe            = sender as FrameworkElement;
            FrameworkElement tag           = fe.Tag as FrameworkElement;
            IAUControl       control       = tag as IAUControl;
            string           navtreeselcom = confService.GetConfigValueForKey("navtreeselectedcol");//23nov2012
            byte             red           = byte.Parse(navtreeselcom.Substring(3, 2), NumberStyles.HexNumber);
            byte             green         = byte.Parse(navtreeselcom.Substring(5, 2), NumberStyles.HexNumber);
            byte             blue          = byte.Parse(navtreeselcom.Substring(7, 2), NumberStyles.HexNumber);
            Color            c             = Color.FromArgb(255, red, green, blue);

            control.bordercolor          = new SolidColorBrush(c); // (Colors.Gold);//05Jun2013
            control.outerborderthickness = new Thickness(2);
            tag.BringIntoView();                                   //treeview leaf node will appear selected as oppose to Focus()
        }
        private void PopulateTreeOld(CommandOutput output)
        {
            TreeViewItem MainItem = new TreeViewItem();

            MainItem.Header     = (output.NameOfAnalysis == null || output.NameOfAnalysis.Trim().Length < 1) ? "Out-put" : output.NameOfAnalysis;// "Output"; /// Parent node text
            MainItem.IsExpanded = true;
            List <string> Headers = new List <string>();

            if (MainItem.Header.ToString().Contains("Execution Started"))
            {
                MainItem.Background = Brushes.LawnGreen;
            }
            if (MainItem.Header.ToString().Contains("Execution Ended"))
            {
                MainItem.Background = Brushes.SkyBlue;
            }
            foreach (DependencyObject obj in output)
            {
                IAUControl control = obj as IAUControl;
                if (control == null)
                {
                    continue;                 //for non IAUControl
                }
                Headers.Add(control.ControlType);
                TreeViewItem tvi = new TreeViewItem();
                tvi.Header = control.ControlType;/// Leaf Node Text
                tvi.Tag    = control;

                tvi.Selected   += new RoutedEventHandler(tvi_Selected);
                tvi.Unselected += new RoutedEventHandler(tvi_Unselected);//29Jan2013
                MainItem.Items.Add(tvi);
            }

            NavTree.Items.Add(MainItem);

            if (MainItem.Items.Count > 0)                                                                //if analysis has something //17Jan2013
            {
                ((MainItem.Items.GetItemAt(0) as TreeViewItem).Tag as FrameworkElement).BringIntoView(); //bring to focus, the latest output.
            }
        }
        //25Feb2015 exact copy of PopulateTree from OutputWindow.xaml. Not Sure if in future they will differ
        private void PopulateTree(CommandOutput output, bool synedtsession = false)
        {
            string treenocharscount = confService.GetConfigValueForKey("nooftreechars");//16Dec2013
            int    openbracketindex, max;
            string analysisName = string.Empty;

            if (output.NameOfAnalysis != null && output.NameOfAnalysis.Trim().Length > 0) // For shortening left tree parent node name.
            {
                openbracketindex = output.NameOfAnalysis.Contains("(") ? output.NameOfAnalysis.IndexOf('(') : output.NameOfAnalysis.Length;

                analysisName = output.NameOfAnalysis.Substring(0, openbracketindex); //18Nov2013 (0, max);
                if (output.NameOfAnalysis.Contains("BSkyFormat("))                   //it is output
                {
                    analysisName = "BSkyFormat-Output";
                }
            }
            else
            {
                analysisName = "Output";
            }


            //// Main logic to populate tree ////
            TreeViewItem MainItem = new TreeViewItem();

            MainItem.Header     = analysisName;
            MainItem.IsExpanded = true;
            List <string> Headers = new List <string>();

            if (MainItem.Header.ToString().Contains("Execution Started"))
            {
                MainItem.Background = Brushes.LawnGreen;
            }
            if (MainItem.Header.ToString().Contains("Execution Ended"))
            {
                MainItem.Background = Brushes.SkyBlue;
            }
            //bool setFocus = true;

            foreach (DependencyObject obj in output)
            {
                IAUControl control = obj as IAUControl;
                if (control == null)
                {
                    continue;                 //for non IAUControl
                }
                Headers.Add(control.ControlType);
                TreeViewItem tvi = new TreeViewItem();

                ////Setting common Excel sheet/////
                AUParagraph _aup = obj as AUParagraph;
                if (_aup != null)
                {
                    _aup.MSExcelObj = _MSExcelObj;
                }
                BSkyNotes _note = obj as BSkyNotes;
                if (_note != null)
                {
                    _note.MSExcelObj = _MSExcelObj;
                }
                AUXGrid _aux = obj as AUXGrid;
                if (_aux != null)
                {
                    _aux.MSExcelObj = _MSExcelObj;
                }


                ////23Oct2013. for show hide leaf nodes based on checkbox //
                StackPanel treenodesp = new StackPanel();
                treenodesp.Orientation = Orientation.Horizontal;

                int  treenodecharlen;
                bool result = Int32.TryParse(treenocharscount, out treenodecharlen);
                if (!result)
                {
                    treenodecharlen = 15;
                }

                TextBlock nodetb = new TextBlock();
                nodetb.Tag = control;
                int    maxlen = control.ControlType.Length < treenodecharlen ? control.ControlType.Length : (treenodecharlen);
                string dots   = maxlen <= treenodecharlen ? "..." : "...";
                nodetb.Text       = control.ControlType.Substring(0, maxlen) + dots;
                nodetb.Margin     = new Thickness(1);
                nodetb.GotFocus  += new RoutedEventHandler(nodetb_GotFocus);
                nodetb.LostFocus += new RoutedEventHandler(nodetb_LostFocus);
                nodetb.ToolTip    = "Click to bring the item in the view";

                CheckBox cbleaf = new CheckBox();
                cbleaf.Content = "";// control.ControlType;
                cbleaf.Tag     = control;

                cbleaf.Checked   += new RoutedEventHandler(cbleaf_Checked);
                cbleaf.Unchecked += new RoutedEventHandler(cbleaf_Checked);

                cbleaf.Visibility = System.Windows.Visibility.Visible;///unhide to see it on output window.
                cbleaf.ToolTip    = "Select/Unselect this node to show/hide in right pane";
                if (!(control is BSkyNotes))
                {
                    cbleaf.IsChecked = true;
                }

                treenodesp.Children.Add(cbleaf);
                treenodesp.Children.Add(nodetb);

                tvi.Header = treenodesp;// cbleaf;//.Substring(0,openbracketindex);/// Leaf Node Text
                tvi.Tag    = control;

                tvi.Selected   += new RoutedEventHandler(tvi_Selected);
                tvi.Unselected += new RoutedEventHandler(tvi_Unselected);//29Jan2013
                MainItem.Items.Add(tvi);
            }
            if (synedtsession)
            {
                SessionItem.Items.Add(MainItem);
            }
            else
            {
                NavTree.Items.Add(MainItem);
            }
        }
        private void PopulateTreeOld2(CommandOutput output, bool synedtsession = false)
        {
            int    openbracketindex;
            string analysisName = string.Empty;

            if (output.NameOfAnalysis != null && output.NameOfAnalysis.Trim().Length > 0) // For shortening left tree parent node name.
            {
                openbracketindex = output.NameOfAnalysis.Contains("(") ? output.NameOfAnalysis.IndexOf('(') : output.NameOfAnalysis.Length;
                analysisName     = output.NameOfAnalysis.Substring(0, openbracketindex); //18Nov2013 (0, max);
                if (output.NameOfAnalysis.Contains("BSkyFormat("))                       //it is output
                {
                    analysisName = "BSkyFormat-Output";
                }
            }
            else
            {
                analysisName = "Output";
            }

            //// Main logic to populate tree ////
            TreeViewItem MainItem = new TreeViewItem();

            MainItem.Header     = analysisName;
            MainItem.IsExpanded = true;
            List <string> Headers = new List <string>();

            if (MainItem.Header.ToString().Contains("Execution Started"))
            {
                MainItem.Background = Brushes.LawnGreen;
            }
            if (MainItem.Header.ToString().Contains("Execution Ended"))
            {
                MainItem.Background = Brushes.SkyBlue;
            }
            //bool setFocus = true;

            foreach (DependencyObject obj in output)
            {
                IAUControl control = obj as IAUControl;
                if (control == null)
                {
                    continue;                 //for non IAUControl
                }
                Headers.Add(control.ControlType);
                TreeViewItem tvi = new TreeViewItem();


                ////23Oct2013. for show hide leaf nodes based on checkbox //
                StackPanel treenodesp = new StackPanel();
                treenodesp.Orientation = Orientation.Horizontal;

                TextBlock nodetb = new TextBlock();
                nodetb.Tag = control;
                int    maxlen = control.ControlType.Length <= 15 ? control.ControlType.Length : 16;
                string dots   = maxlen <= 15 ? "..." : "...";
                nodetb.Text       = control.ControlType.Substring(0, maxlen) + dots;
                nodetb.Margin     = new Thickness(1);
                nodetb.GotFocus  += new RoutedEventHandler(nodetb_GotFocus);
                nodetb.LostFocus += new RoutedEventHandler(nodetb_LostFocus);
                nodetb.ToolTip    = "Click to bring the item in the view";

                CheckBox cbleaf = new CheckBox();
                cbleaf.Content = "";
                cbleaf.Tag     = control;

                cbleaf.Checked   += new RoutedEventHandler(cbleaf_Checked);
                cbleaf.Unchecked += new RoutedEventHandler(cbleaf_Checked);

                cbleaf.Visibility = System.Windows.Visibility.Visible;///unhide to see it on output window.
                cbleaf.ToolTip    = "Select/Unselect this node to show/hide in right pane";
                if (!(control is BSkyNotes))
                {
                    cbleaf.IsChecked = true;
                }

                treenodesp.Children.Add(cbleaf);
                treenodesp.Children.Add(nodetb);

                tvi.Header = treenodesp;
                tvi.Tag    = control;

                tvi.Selected   += new RoutedEventHandler(tvi_Selected);
                tvi.Unselected += new RoutedEventHandler(tvi_Unselected);//29Jan2013
                MainItem.Items.Add(tvi);
            }
            if (synedtsession)
            {
                SessionItem.Items.Add(MainItem);
            }
            else
            {
                NavTree.Items.Add(MainItem);
            }

            if (MainItem.Items.Count > 0)
            {
                ((MainItem.Items.GetItemAt(0) as TreeViewItem).Tag as FrameworkElement).BringIntoView(); //bring to focus, the latest output.
            }
        }
        //05Sept2019 exact copy from OutputWindow.xaml. Not Sure if in future they will differ
        private Image GetImage(IAUControl ctrl)
        {
            Uri     imgUri      = null;
            string  controlType = ctrl.ControlType;
            string  tooltip     = string.Empty;
            AUXGrid _aux        = ctrl as AUXGrid;

            if (_aux != null)
            {
                controlType = "Table";
            }
            switch (controlType)
            {
            case "Title":
                imgUri  = new Uri("/Images/tree-title.png", UriKind.Relative);
                tooltip = "Title";
                break;

            case "Notes":
                imgUri  = new Uri("/Images/tree-notes.png", UriKind.Relative);
                tooltip = "Notes";
                break;

            case "Dataset Name":
                imgUri  = new Uri("/Images/tree-dataset.png", UriKind.Relative);
                tooltip = "Dataset Name";
                break;

            case "Graphic":
                imgUri  = new Uri("/Images/tree-graphs.png", UriKind.Relative);
                tooltip = "Plot";
                break;

            case "Error/Warnings":
                imgUri  = new Uri("/Images/tree-errorwarnings.png", UriKind.Relative);
                tooltip = "Error/Warnings";
                break;

            case "Command":
                imgUri  = new Uri("/Images/tree-syntax.png", UriKind.Relative);
                tooltip = "R Syntax";
                break;

            case "Table":
                imgUri  = new Uri("/Images/tree-tables.png", UriKind.Relative);
                tooltip = "Output Table";
                break;

            case "Toolbar":
                imgUri  = new Uri("/Images/tree-toolbar.png", UriKind.Relative);
                tooltip = "Analysis toolbar";
                break;

            default:
                imgUri  = new Uri("/Images/tree-info.png", UriKind.Relative);
                tooltip = "Info";
                break;
            }
            //Uri imgUri = new Uri("/Images/input.png", UriKind.Relative);
            Image img = new Image(); img.Source = new BitmapImage(imgUri);

            img.ToolTip = tooltip;
            return(img);
        }
        //05Sept2019 exact copy from OutputWindow.xaml. Not Sure if in future they will differ
        private void PopulateTree(CommandOutput output, bool synedtsession = false)
        {
            string treenocharscount = confService.GetConfigValueForKey("nooftreechars");//16Dec2013
            int    openbracketindex, max;
            string analysisName = string.Empty;


            if (output.NameOfAnalysis != null && output.NameOfAnalysis.Trim().Length > 0) // For shortening left tree parent node name.
            {
                openbracketindex = output.NameOfAnalysis.Contains("(") ? output.NameOfAnalysis.IndexOf('(') : output.NameOfAnalysis.Length;
                //if (output.NameOfAnalysis.Trim().Length > 15)
                //    max = 15;
                //else
                //    max = output.NameOfAnalysis.Trim().Length;
                analysisName = output.NameOfAnalysis.Substring(0, openbracketindex); //18Nov2013 (0, max);
                if (output.NameOfAnalysis.Contains("BSkyFormat("))                   //it is output
                {
                    analysisName = "BSkyFormat-Output";
                }
            }
            else
            {
                analysisName = "Output";
            }

            List <string> Headers  = new List <string>();
            TreeViewItem  MainItem = new TreeViewItem();

            if (!synedtsession)         ///\if (MainItem.Header.ToString().Contains("Execution Started"))
            {
                ///\MainItem.Background = Brushes.LawnGreen;
                MainItem.Header     = analysisName;
                MainItem.IsExpanded = true;

                if (MainItem.Header.ToString().Contains("Execution Started"))
                {
                    MainItem.Background = Brushes.LawnGreen;
                }
                if (MainItem.Header.ToString().Contains("Execution Ended"))
                {
                    MainItem.Background = Brushes.SkyBlue;
                }
                //bool setFocus = true;
            }
            ///\if (MainItem.Header.ToString().Contains("Execution Ended"))
            ///\MainItem.Background = Brushes.SkyBlue;
            //bool setFocus = true;

            foreach (DependencyObject obj in output)
            {
                IAUControl control = obj as IAUControl;
                if (control == null)
                {
                    continue;                 //for non IAUControl
                }
                Headers.Add(control.ControlType);
                TreeViewItem tvi = new TreeViewItem();

                ////Setting common Excel sheet/////
                AUParagraph _aup = obj as AUParagraph;
                if (_aup != null)
                {
                    _aup.MSExcelObj = _MSExcelObj;
                }
                BSkyNotes _note = obj as BSkyNotes;
                if (_note != null)
                {
                    _note.MSExcelObj = _MSExcelObj;
                }
                AUXGrid _aux = obj as AUXGrid;
                if (_aux != null)
                {
                    _aux.MSExcelObj = _MSExcelObj;
                }

                ///Toolbar delete icon saves reference of the analysis output controls ///
                BSkyOutputOptionsToolbar toolbar = obj as BSkyOutputOptionsToolbar;
                if (toolbar != null)
                {
                    toolbar.AnalysisOutput = output;
                }
                ////23Oct2013. for show hide leaf nodes based on checkbox //
                StackPanel treenodesp = new StackPanel();
                treenodesp.Orientation = Orientation.Horizontal;

                int  treenodecharlen;//for config char count
                bool result = Int32.TryParse(treenocharscount, out treenodecharlen);
                if (!result)
                {
                    treenodecharlen = 20;
                }

                TextBlock nodetb = new TextBlock();
                nodetb.Tag = control;

                string nodetext = control.ControlType;; // string.Empty;
                if (_aup != null && _aup.ControlType.Equals("Command"))
                {
                    nodetext = _aup.Text;
                }
                else
                {
                    nodetext = control.ControlType;
                }

                //maxlen is need to avoid indexoutofbounds when finding Substring()
                int maxlen = nodetext.Length < treenodecharlen ? nodetext.Length : (treenodecharlen);
                //if (maxlen > 20) maxlen = 20; //this could be used for putting restriction for max. length

                string dots = maxlen < nodetext.Length ? " ..." : "";//add dots only if text are getting trimmed.

                //Show node text with or without dots based on condition.
                if (maxlen >= nodetext.Length) //show full length
                {
                    nodetb.Text = nodetext.Replace("\n", " ").Replace("\r", " ");
                }
                else
                {
                    nodetb.Text = nodetext.Substring(0, maxlen).Replace("\n", " ").Replace("\r", " ") + dots;
                }

                nodetb.Margin     = new Thickness(1, 0, 0, 2);
                nodetb.GotFocus  += new RoutedEventHandler(nodetb_GotFocus);
                nodetb.LostFocus += new RoutedEventHandler(nodetb_LostFocus);
                nodetb.ToolTip    = BSky.GlobalResources.Properties.UICtrlResources.NavTreeNodeTBTooltip;

                CheckBox cbleaf = new CheckBox();
                cbleaf.Content = "";// control.ControlType;
                cbleaf.Tag     = control;
                //cbleaf.Click += new RoutedEventHandler(cbleaf_Checked);
                cbleaf.Checked   += new RoutedEventHandler(cbleaf_Checked);
                cbleaf.Unchecked += new RoutedEventHandler(cbleaf_Checked);
                //cbleaf.LostFocus +=new RoutedEventHandler(cbleaf_LostFocus);
                //cbleaf.GotFocus +=new RoutedEventHandler(cbleaf_GotFocus);
                cbleaf.Visibility = System.Windows.Visibility.Visible;///unhide to see it on output window.
                cbleaf.ToolTip    = BSky.GlobalResources.Properties.UICtrlResources.NavTreeCheckboxTooltip;

                ///if (!(control is BSkyNotes) && !((control is AUParagraph) && (control.ControlType.Equals("Header"))))
                if (isRunFromSyntaxEditor)
                {
                    //show/hide BSkyNote in the output if templated dialog syntax is run from the command editor
                    if (_note != null)
                    {
                        control.BSkyControlVisibility = Visibility.Collapsed;
                    }
                    else
                    {
                        control.BSkyControlVisibility = Visibility.Visible;
                    }
                }
                cbleaf.IsChecked = (control.BSkyControlVisibility == Visibility.Visible) ? true : false;

                #region putting icon in the tree
                Image img = GetImage(control);
                img.Margin = new Thickness(0, 0, 2, 2);
                #endregion

                treenodesp.Children.Add(cbleaf);
                treenodesp.Children.Add(img);
                treenodesp.Children.Add(nodetb);

                tvi.Header = treenodesp;// cbleaf;//.Substring(0,openbracketindex);/// Leaf Node Text
                tvi.Tag    = control;
                (control as FrameworkElement).Tag = tvi;

                ////following lines does not show any effect ///
                //FrameworkElement fe = obj as FrameworkElement;
                //fe.GotFocus += new RoutedEventHandler(delegate(object sender, RoutedEventArgs e) { tvi.IsSelected = true; /*Bold or background */ });

                tvi.Selected   += new RoutedEventHandler(tvi_Selected);
                tvi.Unselected += new RoutedEventHandler(tvi_Unselected);//29Jan2013

                ///\MainItem.Items.Add(tvi);
                if (synedtsession)                                                                   //analysis run
                {
                    if (control.ControlType.Equals("Title") || control.ControlType.Equals("Header")) // 'Header' for backward compatibilty
                    {
                        SessionItem.Tag = control;                                                   //SessionItem.Header= R-Session and SessionItem.Count==0
                        AddEventsAndContextMenu(SessionItem);
                    }
                    SessionItem.Items.Add(tvi);
                }
                else //dataset opened
                {
                    if (control.ControlType.Equals("Title") || control.ControlType.Equals("Header"))// 'Header' for backward compatibilty
                    {
                        MainItem.Tag = control;
                        AddEventsAndContextMenu(MainItem);
                    }
                    MainItem.Items.Add(tvi);
                }

                //if (setFocus) { fe.Focus();tvi.IsSelected = true; setFocus = false; }//setting focus to start time for each RUN
            }

            /*
             * if (synedtsession)
             *  SessionItem.Items.Add(MainItem);
             * else
             *  NavTree.Items.Add(MainItem);
             */
            if (!synedtsession)
            {
                NavTree.Items.Add(MainItem);
            }

            //follwing 'if' block could be commented because BringLastLeaf is doing its job. Test, if not scrolling to latest output then uncomment.
            //if (MainItem.Items.Count > 0)//if analysis has something //17Jan2013
            //{
            //    ((MainItem.Items.GetItemAt(0) as TreeViewItem).Tag as FrameworkElement).BringIntoView(); //bring to focus, the latest output.
            //}

            //if (NavTree!=null && NavTree.Items.Count > 0)//11Dec2014 scroll to bottom if there are items present
            //{
            //    int itcount = NavTree.Items.Count;
            //    (NavTree.Items.GetItemAt(itcount - 1) as TreeViewItem).BringIntoView();
            //}
        }