public void TreePrint(TreeItem treeItem)
 {
     foreach (var item in treeItem.SubItems.OrderBy(x => x.Order))
     {
         ChildPrint(item, 0);
     }
 }
 public TreeItem GenerateTteeVm(int col, int depth, string version)
 {
     OrderInc = 0;
     var item = new TreeItem() { Name = "root " + version };
     item.SubItems = GenerateTteeItemList(col, depth,version);
     return item;
 }
Example #3
0
        private static void PopulateFolders(string dirName, TreeItem<string> parentFolder)
        {
            string[] folderItems = Directory.GetFileSystemEntries(dirName);

            foreach (var folderItem in folderItems)
            {
                TreeItem<string> folderSubItem = new TreeItem<string>(folderItem);
                parentFolder.AddChild(folderSubItem);

                // If the current node is a filename, don't call recursion and continue
                try
                {
                    Directory.GetDirectories(folderItem);
                }
                catch (IOException ex)
                {
                    continue;
                }
                catch (UnauthorizedAccessException)
                {
                    Console.WriteLine("LOG: No access to folder {0}", dirName);
                    continue;
                }

                PopulateFolders(folderItem, folderSubItem);
            }
        }
Example #4
0
 private void GenerateTree(TreeItem<FileSystemItem> node, int depth, int level = 0)
 {
     var itemCount = C.Random<int>(_fakingRules.GetItemCount(level));
     var nodes = node.AddRange(C.CollectionOfFake<FileSystemItem>(itemCount, new { Type = _fakingRules.GetItemTypes(level), Name = new Range(8,13) }));
     foreach (var n in nodes)
     {
         n.Content.FullPath = n.Content.Path = node.Content.Path + "/" + n.Content.Name;
         n.Content.Size = C.Random<int>(0xFF, 0xFFFF);
         if (level < depth) GenerateTree(n, depth, level+1);
     }
 }
Example #5
0
		public TreeItem (TreeStore store, TreeItem parent, CoverageItem model, string title) {
			this.store = store;
			this.parent = parent;
			this.model = model;

			if (parent == null)
				iter = store.AppendValues (title);
			else
				iter = store.AppendValues (parent.Iter, title);
			FillColumns ();
		}
 public void WriteTree(Guid versionId, TreeItem item)
 {
     OrderInc = 0;
     //            using (var context = _context)
     {
         //foreach (var element in item.SubItems.OrderBy(x => x.Order))
         {
             var root = Dive(item, null, versionId);
             HierarchyParentChildContext.Elements.Add(root);
             HierarchyParentChildContext.SaveChanges();
         }
     }
 }
Example #7
0
        public TreeEntryMenu(ITreeSource treeSource, TreeItem treeItem)
        {
            if(treeSource == null) throw new ArgumentNullException("treeSource");
            if(treeItem == null) throw new ArgumentNullException("treeItem");

            _treeSource = treeSource;
            _treeItem = treeItem;

            // save as
            // checkout

            Items.Add(GuiItemFactory.GetCheckoutPathItem<ToolStripMenuItem>(treeSource, treeItem.RelativePath));
        }
Example #8
0
 TreeItem CreateTreeItem(int level, string name, Image image)
 {
     var item = new TreeItem {
         Text = name,
         Expanded = expanded++ % 2 == 0,
         Image = image
     };
     if (level < 4) {
         for (int i = 0; i < 4; i++) {
             item.Children.Add (CreateTreeItem (level + 1, name + " " + i, image));
         }
     }
     return item;
 }
Example #9
0
        public UnstagedItemMenu(TreeItem item)
        {
            Verify.Argument.IsValidGitObject(item, "item");
            Verify.Argument.AreEqual(StagedStatus.Unstaged, item.StagedStatus & StagedStatus.Unstaged, "item",
                "This item is not unstaged.");

            _item = item;

            var dir = _item as TreeDirectory;
            if(_item.Status != FileStatus.Removed)
            {
                var fullPath = _item.FullPath;
                if(dir == null)
                {
                    Items.Add(GuiItemFactory.GetOpenUrlItem<ToolStripMenuItem>(Resources.StrOpen, null, fullPath));
                    Items.Add(GuiItemFactory.GetOpenUrlWithItem<ToolStripMenuItem>(Resources.StrOpenWith.AddEllipsis(), null, fullPath));
                    Items.Add(GuiItemFactory.GetOpenUrlItem<ToolStripMenuItem>(Resources.StrOpenContainingFolder, null, Path.GetDirectoryName(fullPath)));
                }
                else
                {
                    Items.Add(GuiItemFactory.GetOpenUrlItem<ToolStripMenuItem>(Resources.StrOpenInWindowsExplorer, null, fullPath));
                }
                Items.Add(new ToolStripSeparator());
            }
            Items.Add(GuiItemFactory.GetStageItem<ToolStripMenuItem>(_item));
            if(dir != null)
            {
                if(HasRevertableItems(dir))
                {
                    Items.Add(GuiItemFactory.GetRevertPathItem<ToolStripMenuItem>(_item));
                }
            }
            else
            {
                if(_item.Status == FileStatus.Removed || _item.Status == FileStatus.Modified)
                {
                    Items.Add(GuiItemFactory.GetRevertPathItem<ToolStripMenuItem>(_item));
                }
                if(_item.Status == FileStatus.Modified || _item.Status == FileStatus.Added)
                {
                    Items.Add(GuiItemFactory.GetRemovePathItem<ToolStripMenuItem>(_item));
                }
            }
        }
Example #10
0
        public void Index_GET()
        {
            IList<SiteDto> sites=SiteCacheManager.GetAllSites();
            TreeItem[] items=new TreeItem[sites.Count];
            for (int i = 0; i < sites.Count; i++)
            {
                items[i] = new TreeItem
                {
                    ID=sites[i].SiteId,
                    Name=sites[i].Name + (sites[i].Note.Trim()!=""?"["+sites[i].Note+"]":"")
                };
            }


            base.RenderTemplate(ResourceMap.GetPageContent(ManagementPage.Site_Index), new
            {
                siteTree=Helper.SingleTree("所有站点",items)
            });
        }
Example #11
0
        private static void FindExeFile(List<string> foundExeFiles, TreeItem<string> treeItem)
        {
            string pattern = "exe";

            if (!treeItem.IsFolder)
            {
                string[] fileParts = treeItem.Value.Split('.');

                if (fileParts[fileParts.Length - 1] == pattern)
                {
                    foundExeFiles.Add(treeItem.Value);
                }
            }

            for (int i = 0; i < treeItem.ChildItemsCount; i++)
            {
                FindExeFile(foundExeFiles, treeItem.GetChild(i));
            }
        }
Example #12
0
		public UserList (Channel channel)
		{
			this.Channel = channel;
			tree = new TreeView ();
			tree.Style = "userList";
			tree.Activated += HandleActivated;
			
			items = new TreeItemCollection ();
			items.Add (owners = new TreeItem { Text = "Room Owners", Expanded = true });
			items.Add (online = new TreeItem { Text = "Online", Expanded = true });
			items.Add (away = new TreeItem { Text = "Away", Expanded = true });
			if (Generator.ID == Generators.Mac) {
				foreach (var item in items.OfType<TreeItem>()) {
					item.Text = item.Text.ToUpperInvariant();
				}
			}
			tree.DataStore = items;
			
			this.AddDockedControl (tree);
		}
Example #13
0
        static void Main(string[] args)
        {
            string rootDirectory = @"C:\Windows";

            TreeItem<string> rootFolder = new TreeItem<string>(rootDirectory);

            Console.WriteLine("Getting items in {0}, this can take a while", rootDirectory);
            Console.WriteLine();

            PopulateFolders(rootDirectory, rootFolder);

            Tree<string> foldersTree = new Tree<string>(rootFolder);

            List<string> exeFiles = new List<string>();

            FindExeFile(exeFiles, foldersTree.Root);

            Console.WriteLine();
            Console.WriteLine("Found {0} .exe files", exeFiles.Count);
        }
Example #14
0
 private static Result CompareTrees(TreeItem tree1, TreeItem tree2)
 {
     if (tree1.Name != tree2.Name) return new Result(false, tree1, tree2);
     if (tree1.Order != tree2.Order) return new Result(false, tree1, tree2);
     if (tree1.SubItems == null)
     {
         if (tree2.SubItems != null) return new Result(false, tree1, tree2);
         if (tree1.Placeholder != tree2.Placeholder) return new Result(false, tree1, tree2);
     }
     else
     {
         if (tree2.SubItems == null) return new Result(false, tree1, tree2);
         if (tree1.SubItems.Count != tree2.SubItems.Count) return new Result(false, tree1, tree2);
         for (int i = 0; i < tree1.SubItems.Count; i++)
         {
             var r = CompareTrees(tree1.SubItems[i], tree2.SubItems[i]);
             if (!r.Equals) return r;
         }
     }
     return new Result(true, null, null);
 }
Example #15
0
      /// <summary>
      /// Expands the root tree item to the currently selected item.
      /// </summary>
      /// <param name="iRoot">Root tree item.</param>
      private void ExpandToSelection(ref TreeItem iRoot)
      {
         if (iRoot == null || SelectedId == 0 || SelectedId == iRoot.Id)
            return;

         var treeItem = LoadTreeItem(SelectedId);

         var records = EmployeeModel.AllRecords;
         var record = records.FirstOrDefault(i => i.Id == SelectedId);
         var reportToId = record.ReportTo;

         // Start from the selected item and work our way up until the root is reached.
         while (reportToId != iRoot.Id && (record = records.FirstOrDefault(i => i.Id == reportToId)) != null)
         {
            var parentItem = LoadTreeItem(record.Id);
            parentItem.Children[parentItem.Children.FindIndex(i => i.Id == treeItem.Id)] = treeItem;
            reportToId = record.ReportTo;
            treeItem = parentItem;
         }
         iRoot.Children[iRoot.Children.FindIndex(i => i.Id == treeItem.Id)] = treeItem;
      }
        public void GenerateCustomDataTree(out TreeItem input, out TreeItem output)
        {
            input = new TreeItem() { Name = "InputData", IsChoice = false, SubItems = new List<TreeItem>() };
            output = new TreeItem() { Name = "OutputData", IsChoice = false, SubItems = new List<TreeItem>() };

            input.SubItems.Add(new TreeItem() { Name = "Корневой", Placeholder = "я корневой", Order = 0 });
            TreeItem inputRoot = new TreeItem()
            {
                Name = "Справка",
                SubItems = new List<TreeItem>()
                {
                    new TreeItem()
                    {
                        Name = "Паспорт",
                        Order = 0,
                        SubItems =
                            new List<TreeItem>()
                            {
                                new TreeItem() {Name = "Серия", Placeholder = "8003", Order = 0},
                                new TreeItem() {Name = "номер", Placeholder = "600000", Order = 1}
                            }
                    },
                    new TreeItem()
                    {
                        Name = "ФИО",
                        Order = 1,
                        SubItems =
                            new List<TreeItem>()
                            {
                                new TreeItem() {Name = "Имя", Placeholder = "Петя", Order = 0},
                                new TreeItem() {Name = "Фамилия", Placeholder = "Кошечкин", Order = 1}
                            }
                    },
                    new TreeItem() {Name = "Номер справки", Placeholder = "СПР-1", Order = 2}
                },
                Order = 1
            };
            input.SubItems.Add(inputRoot);
            output.SubItems.Add(new TreeItem() { Name = "Корневой Вых", Placeholder = "я корневой вых", Order = 0 });
        }
Example #17
0
        private List<TreeItem<FileLayerSongDO>> BuildTree(IEnumerable<Tuple<int, List<string>>> data, int depth)
        {
            // wenn depth == items2.length
            // break;

            var grped = from r in
                            (from item in data
                             where item.Item2.Count > depth
                             select item)
                        group r by r.Item2[depth] into grp
                        select grp;

            List<TreeItem<FileLayerSongDO>> result = null;
            if (grped.Any())
            {
                result = new List<TreeItem<FileLayerSongDO>>();

                foreach (var item in grped)
                {
                    var child = new TreeItem<FileLayerSongDO>();
                    child.Level = depth;
                    var temp = new FileLayerSongDO();
                    temp.SetByDepth(depth, item.Key);
                    var current = item.First();

                    if (depth == current.Item2.Count - 1)
                        temp.ID = item.First().Item1;

                    child.Value = temp;

                    var childs = BuildTree(item, depth + 1);
                    if (childs != null)
                        child.SetChildren(childs);

                    result.Add(child);
                }
            }
            return result;
        }
Example #18
0
        public UserList(Channel channel)
        {
            Channel = channel;
            Size = new Size(150, 100);
            tree = new TreeView();
            tree.Style = "userList";
            tree.Activated += HandleActivated;

            items = new TreeItemCollection();
            items.Add(owners = new TreeItem { Text = "Room Owners", Expanded = true });
            items.Add(online = new TreeItem { Text = "Online", Expanded = true });
            items.Add(away = new TreeItem { Text = "Away", Expanded = true });
            if (Generator.IsMac)
            {
                foreach (var item in items.OfType<TreeItem>())
                {
                    item.Text = item.Text.ToUpperInvariant();
                }
            }
            tree.DataStore = items;
            
            Content = tree;
        }
        public bool Proccess(string atom, AbstractTreeItem seed, out AbstractTreeItem item)
        {
            MathExpr[] exprs = null;
            item= new TreeItem();
            item.Type=TreeItemType.Выражение;
            string polska = null;
            try
            {
                polska = GetPolskaFormat(atom, out exprs);
            }
            catch (MpException e)
            {
                item.Error = true;
                item.ErrorCode = e.Code;
            }
            catch (Exception e)
            {
                item.Error = true;
                item.ErrorCode = ErrorCodes.Unknown;
            }
            throw new NotImplementedException();

        }
        private void ChildPrint(TreeItem element, int i)
        {
            var ii = i;
            var tab = "";
            for (int j = 0; j < i; j++)
            {
                tab = tab + "_";
            }

            if (element.SubItems == null)
            {
                Console.WriteLine(tab + element.Name + " " + element.Placeholder);
            }
            else
            {
                Console.WriteLine(tab + element.Name);
                ++ii;
                foreach (var child in element.SubItems.OrderBy(x => x.Order))
                {
                    ChildPrint(child, ii);
                }
            }
        }
Example #21
0
        public void TestDataContractJsonSerializer()
        {
            var treeitem = new TreeItem<string>();
            treeitem.Id = "1";
            treeitem.Text = "Root";
            treeitem.Value = "3223";
            treeitem.Isexpand = true;
            treeitem.Showcheck = true;
            treeitem.Add(
                new TreeItem<string>
                    {
                       Id = "2", Text = "Node2", Value = "9982", Showcheck = true, Isexpand = true, Checkstate = 1 
                    });

            string mstr = treeitem.ToJsonString2();

            Console.WriteLine(mstr);

            string tstr = treeitem.ToJsonString();
            Console.WriteLine(tstr);

            Assert.Equal(tstr.Length, mstr.Length);
        }
Example #22
0
		TreeItem ToTree(Assembly assembly, ITest test, string filter)
		{
			// add a test
			var name = test.Name;
			if (test.IsSuite)
			{
				var an = new AssemblyName(test.Name);
				name = an.Name;
			}

			var item = new TreeItem { Text = name, Tag = new SingleTestFilter { Test = test, Assembly = assembly } };
			var nameMatches = filter == null || test.FullName.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0;
			if (test.HasChildren)
			{
				if (nameMatches)
					filter = null;
				item.Expanded = !(test is ParameterizedMethodSuite);
				foreach (var child in test.Tests)
				{
					var treeItem = ToTree(assembly, child, filter);
					if (treeItem != null)
						item.Children.Add(treeItem);
				}
				while (item.Children.Count == 1)
				{
					// collapse test nodes
					var child = item.Children[0] as TreeItem;
					if (child.Children.Count == 0)
						break;
					if (!child.Text.StartsWith(item.Text, StringComparison.Ordinal))
						item.Text += "." + child.Text;
					else
						item.Text = child.Text;
					item.Children.Clear();
					item.Children.AddRange(child.Children);
				}
				if (item.Children.Count == 0)
					return null;
			}
			else if (!nameMatches)
			{
				return null;
			}
			return item;
		}
Example #23
0
        void ShowEventFolder(TreeItem item, Predicate<TreeItem> filter)
        {
            eventStyle.padding.left += 17;

            if (item.EventRef != null || item.BankRef != null)
            {
                // Highlight first found item
                if (!String.IsNullOrEmpty(searchString) &&
                    itemCount == 0 &&
                    selectedItem == null)
                {
                    SetSelectedItem(item);
                }

                item.Next = null;
                item.Prev = lastDrawnItem;
                if (lastDrawnItem != null)
                {
                    lastDrawnItem.Next = item;
                }
                lastDrawnItem = item;
                itemCount++;
            }

            if (item.EventRef != null)
            {
                // Rendering and GUI event handling to show an event
                GUIContent content = new GUIContent(item.Name, item.EventRef.Path.StartsWith("snapshot") ? snapshotIcon : eventIcon);

                eventStyle.normal.background = selectedItem == item ? EditorGUIUtility.Load("FMOD/Selected.png") as Texture2D : null;
                GUILayout.Label(content, eventStyle, GUILayout.ExpandWidth(true));

                Event e = Event.current;

                Rect rect = GUILayoutUtility.GetLastRect();
                if (e.type == EventType.MouseDown &&
                    e.button == 0 &&
                    rect.Contains(e.mousePosition))
                {
                    e.Use();

                    if (fromInspector && e.clickCount >= 2)
                    {
                        outputProperty.stringValue = item.EventRef.Path;
                        EditorUtils.UpdateParamsOnEmmitter(outputProperty.serializedObject);
                        outputProperty.serializedObject.ApplyModifiedProperties();

                        Close();
                    }

                    SetSelectedItem(item);
                }
                if (e.type == EventType.mouseDrag && rect.Contains(e.mousePosition) && !fromInspector)
                {
                    DragAndDrop.PrepareStartDrag();
                    DragAndDrop.objectReferences = new UnityEngine.Object[] { ScriptableObject.Instantiate(item.EventRef) };
                    DragAndDrop.StartDrag("New FMOD Studio Emitter");
                    e.Use();
                }
                if (Event.current.type == EventType.Repaint)
                {
                    item.Rect = rect;
                }
            }
            else if (item.BankRef != null)
            {
                // Rendering and event handling for a bank
                GUIContent content = new GUIContent(item.Name, bankIcon);

                eventStyle.normal.background = selectedItem == item ? EditorGUIUtility.Load("FMOD/Selected.png") as Texture2D : null;
                GUILayout.Label(content, eventStyle, GUILayout.ExpandWidth(true));

                Event e = Event.current;

                Rect rect = GUILayoutUtility.GetLastRect();
                if (e.type == EventType.MouseDown &&
                    e.button == 0 &&
                    rect.Contains(e.mousePosition))
                {
                    e.Use();

                    if (fromInspector && e.clickCount >= 2)
                    {
                        outputProperty.stringValue = item.BankRef.Name;
                        outputProperty.serializedObject.ApplyModifiedProperties();
                        Close();
                    }

                    SetSelectedItem(item);
                }
                if (e.type == EventType.mouseDrag && rect.Contains(e.mousePosition) && !fromInspector)
                {
                    DragAndDrop.PrepareStartDrag();
                    DragAndDrop.objectReferences = new UnityEngine.Object[] { ScriptableObject.Instantiate(item.BankRef) };
                    DragAndDrop.StartDrag("New FMOD Studio Bank Loader");
                    e.Use();
                }
                if (Event.current.type == EventType.Repaint)
                {
                    item.Rect = rect;
                }
            }
            else
            {
                eventStyle.normal.background = null;
                bool expanded = item.Expanded || !string.IsNullOrEmpty(searchString);
                GUIContent content = new GUIContent(item.Name, expanded ? folderOpenIcon : folderClosedIcon);
                GUILayout.Label(content, eventStyle);

                Rect rect = GUILayoutUtility.GetLastRect();
                if (Event.current.type == EventType.MouseDown &&
                    Event.current.button == 0 &&
                    rect.Contains(Event.current.mousePosition))
                {
                    Event.current.Use();
                    item.Expanded = !item.Expanded;
                }

                if (item.Expanded || !string.IsNullOrEmpty(searchString))
                {
                    if (item.Name.ToLower().Contains(searchString.ToLower()))
                    {
                        foreach(var childFolder in item.Children)
                        {
                            ShowEventFolder(childFolder, (x) => true);
                        }
                    }
                    else
                    {
                        foreach (var childFolder in item.Children.FindAll(filter))
                        {
                            ShowEventFolder(childFolder, filter);
                        }
                    }
                }
            }
            eventStyle.padding.left -= 17;
        }
Example #24
0
        private void RebuildDisplayFromCache()
        {
            Action<TreeItem> nullEvents = null;
            nullEvents = (x) => { x.Exists = false; x.Children.ForEach(nullEvents); };
            Predicate<TreeItem> isStale = (x) => !x.Exists;
            Action<TreeItem> removeStaleChildren = null;
            removeStaleChildren = (x) => { x.Children.RemoveAll(isStale); x.Children.ForEach(removeStaleChildren); };

            if (showEvents)
            {
                var editorEvents = EventManager.Events;

                treeItems[0].Children.ForEach(nullEvents);
                treeItems[1].Children.ForEach(nullEvents);

                foreach (var editorEvent in editorEvents)
                {
                    string[] split = editorEvent.Path.Split('/');
                    var level = split[0] == "snapshot:" ? treeItems[1].Children : treeItems[0].Children;
                    for (int i = 1; i < split.Length; i++)
                    {
                        TreeItem item = level.Find((x) => x.Name == split[i]);
                        if (item != null)
                        {
                            if (i == (split.Length - 1))
                            {
                                item.EventRef = editorEvent;
                            }
                            else
                            {
                                level = item.Children;
                            }
                        }
                        else
                        {
                            item = new TreeItem();
                            if (i == (split.Length - 1))
                            {
                                item.EventRef = editorEvent;
                            }
                            item.Name = split[i];
                            level.Add(item);
                            level.Sort((a, b) => a.EventRef != b.EventRef ? (a.EventRef != null ? 1 : -1) : a.Name.CompareTo(b.Name));
                            level = item.Children;
                        }
                        item.Exists = true;
                    }
                }

                removeStaleChildren(treeItems[0]);
                removeStaleChildren(treeItems[1]);
            }

            if (showBanks)
            {
                var editorBanks = EventManager.Banks;
                var children = treeItems[2].Children;

                children.ForEach(nullEvents);

                foreach (var editorBank in editorBanks)
                {
                    var name = Path.GetFileNameWithoutExtension(editorBank.Path);
                    TreeItem item = children.Find((x) => x.Name == name);
                    if (item == null)
                    {
                        item = new TreeItem();
                        item.Name = name;
                        item.BankRef = editorBank;
                        children.Add(item);
                    }
                    item.Exists = true;
                }
                children.Sort((a, b) => a.Name.CompareTo(b.Name));

                removeStaleChildren(treeItems[2]);
            }

            if (expandedState != null && EventManager.IsLoaded)
            {
                int i = 0;
                Action<TreeItem> setExpanded = null;
                setExpanded = (x) => { selectedItem = (i == selectedIndex) ? x : selectedItem; x.Expanded = expandedState[i++]; x.Children.ForEach(setExpanded); };
                try
                {
                    treeItems.ForEach(setExpanded);
                }
                catch
                {
                }

                expandedState = null;

                if (selectedItem != null)
                {
                    SetPreviewEvent(selectedItem.EventRef);
                }
                else
                {
                    SetPreviewEvent(null);
                }
            }
        }
        void OnGUI()
        {
            if (EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying)
            {
                // Brute force hack to stop us calling DLL functions while Unity is starting up
                // playing in editor mode and will cause us to leak system objects
                this.ShowNotification(new GUIContent("Playing In Editor Starting"));
                return;
            }

            if (!EventManager.IsLoaded)
            {
                this.ShowNotification(new GUIContent("No FMOD Studio banks loaded. Please check your settings."));
                return;
            }

            if (Event.current.type == EventType.Layout)
            {
                RebuildDisplayFromCache();
            }

            //if (eventStyle == null)
            {
                eventStyle = new GUIStyle(GUI.skin.button);
                eventStyle.normal.background = null;
                eventStyle.focused.background = null;
                eventStyle.active.background = null;
                eventStyle.onFocused.background = null;
                eventStyle.onNormal.background = null;
                eventStyle.onHover.background = null;
                eventStyle.onActive.background = null;
                eventStyle.stretchWidth = false;
                eventStyle.padding.left = 0;
                eventStyle.stretchHeight = false;
                eventStyle.fixedHeight = eventStyle.lineHeight + eventStyle.margin.top + eventStyle.margin.bottom;
                eventStyle.alignment = TextAnchor.MiddleLeft;

                eventIcon = EditorGUIUtility.Load("FMOD/EventIcon.png") as Texture;
                folderOpenIcon = EditorGUIUtility.Load("FMOD/FolderIconOpen.png") as Texture;
                folderClosedIcon = EditorGUIUtility.Load("FMOD/FolderIconClosed.png") as Texture;
                searchIcon = EditorGUIUtility.Load("FMOD/SearchIcon.png") as Texture;
                bankIcon = EditorGUIUtility.Load("FMOD/BankIcon.png") as Texture;
                snapshotIcon = EditorGUIUtility.Load("FMOD/SnapshotIcon.png") as Texture;
                borderIcon = EditorGUIUtility.Load("FMOD/Border.png") as Texture2D;
            }

            if (fromInspector)
            {
                var border = new GUIStyle(GUI.skin.box);
                border.normal.background = borderIcon;
                GUI.Box(new Rect(1, 1, position.width - 1, position.height - 1), GUIContent.none, border);
            }

            // Split the window int search box, tree view, preview pane (only if full browser)
            Rect searchRect = new Rect(4, 4, position.width-8, 16);
            float previewBoxHeight = fromInspector ? 0 : 300;
            Rect listRect = new Rect(0, searchRect.height + 6, position.width, position.height - previewBoxHeight - searchRect.height - 15);
            Rect previewRect = new Rect(0, position.height - previewBoxHeight, position.width, previewBoxHeight);

            // Scroll the selected item in the tree view - put above the search box otherwise it will take
            // our key presses
            if (selectedItem != null && Event.current.type == EventType.keyDown)
            {
                if (Event.current.keyCode == KeyCode.UpArrow)
                {
                    if (selectedItem.Prev != null)
                    {
                        SetSelectedItem(selectedItem.Prev);

                        // make sure it's visible
                        if (selectedItem.Rect.y < treeScroll.y)
                        {
                            treeScroll.y = selectedItem.Rect.y;
                        }
                    }
                    Event.current.Use();
                }
                if (Event.current.keyCode == KeyCode.DownArrow)
                {
                    if (selectedItem.Next != null)
                    {
                        SetSelectedItem(selectedItem.Next);
                        // make sure it's visible
                        if (selectedItem.Rect.y + selectedItem.Rect.height > treeScroll.y + listRect.height)
                        {
                            treeScroll.y += (selectedItem.Rect.y + selectedItem.Rect.height) - listRect.height;
                        }
                    }
                    Event.current.Use();
                }
            }

            // Show the search box at the top
            GUILayout.BeginArea(searchRect);
            GUILayout.BeginHorizontal();
            GUILayout.Label(new GUIContent(searchIcon), GUILayout.ExpandWidth(false));
            GUI.SetNextControlName("SearchBox");
            searchString = EditorGUILayout.TextField(searchString);
            GUILayout.EndHorizontal();
            GUILayout.EndArea();

            if (fromInspector)
            {
                GUI.FocusControl("SearchBox");

                if (selectedItem != null && Event.current.isKey && Event.current.keyCode == KeyCode.Return)
                {
                    Event.current.Use();

                    if (selectedItem.EventRef != null)
                    {
                        outputProperty.stringValue = "";
                        outputProperty.stringValue = selectedItem.EventRef.Path;
                        EditorUtils.UpdateParamsOnEmitter(outputProperty.serializedObject, selectedItem.EventRef.Path);
                    }
                    else
                    {
                        outputProperty.stringValue = selectedItem.BankRef.Name;
                    }
                    outputProperty.serializedObject.ApplyModifiedProperties();
                    Close();
                }
            }

            // Show the tree view

            Predicate<TreeItem> searchFilter = null;
            searchFilter = (x) => (x.Name.ToLower().Contains(searchString.ToLower()) || x.Children.Exists(searchFilter));

            // Check if our selected item still matches the search string
            if (selectedItem != null && !String.IsNullOrEmpty(searchString))
            {
                Predicate<TreeItem> containsSelected = null;
                containsSelected = (x) => (x == selectedItem || x.Children.Exists(containsSelected));
                Predicate<TreeItem> matchForSelected = null;
                matchForSelected = (x) => (x.Name.ToLower().Contains(searchString.ToLower()) && (x == selectedItem || x.Children.Exists(containsSelected))) || x.Children.Exists(matchForSelected);
                if (!treeItems.Exists(matchForSelected))
                {
                    SetSelectedItem(null);
                }
            }

            GUILayout.BeginArea(listRect);
            treeScroll = GUILayout.BeginScrollView(treeScroll, GUILayout.ExpandHeight(true));

            lastDrawnItem = null;
            itemCount = 0;

            if (showEvents)
            {
                treeItems[0].Expanded = fromInspector ? true : treeItems[0].Expanded;
                ShowEventFolder(treeItems[0], searchFilter);
                ShowEventFolder(treeItems[1], searchFilter);
            }
            if (showBanks)
            {
                treeItems[2].Expanded = fromInspector ? true : treeItems[2].Expanded;
                ShowEventFolder(treeItems[2], searchFilter);
            }

            GUILayout.EndScrollView();
            GUILayout.EndArea();

            // If the standalone event browser show a preview of the selected item
            if (!fromInspector)
            {

                GUI.Box(previewRect, GUIContent.none);

                if (selectedItem != null && selectedItem.EventRef != null && selectedItem.EventRef.Path.StartsWith("event:"))
                {
                    PreviewEvent(previewRect, selectedItem.EventRef);
                }

                if (selectedItem != null && selectedItem.EventRef != null && selectedItem.EventRef.Path.StartsWith("snapshot:"))
                {
                    PreviewSnapshot(previewRect, selectedItem.EventRef);
                }

                if (selectedItem != null && selectedItem.BankRef != null)
                {
                    PreviewBank(previewRect, selectedItem.BankRef);
                }
            }
        }
Example #26
0
 protected virtual IList <Issue> AnalyzeInternal(TreeItem treeItem)
 {
     return(new List <Issue>());
 }
Example #27
0
        public IActionResult AddRoot()
        {
            TreeItem treeItem = NewItem("<new root>", null);

            return(Redirect("/TreeItems/GetRoots/"));
        }
Example #28
0
        void OnGUI()
        {
            if (EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying)
            {
                // Brute force hack to stop us calling DLL functions while Unity is starting up
                // playing in editor mode and will cause us to leak system objects
                ShowNotification(new GUIContent("Playing In Editor Starting"));
                return;
            }

            if (!EventManager.IsValid)
            {
                ShowNotification(new GUIContent("No FMOD Studio banks loaded. Please check your settings."));
                return;
            }

            if (Event.current.type == EventType.Layout)
            {
                RebuildDisplayFromCache();
            }

            //if (eventStyle == null)
            {
                eventStyle = new GUIStyle(GUI.skin.button);
                eventStyle.normal.background    = null;
                eventStyle.focused.background   = null;
                eventStyle.active.background    = null;
                eventStyle.onFocused.background = null;
                eventStyle.onNormal.background  = null;
                eventStyle.onHover.background   = null;
                eventStyle.onActive.background  = null;
                eventStyle.stretchWidth         = false;
                eventStyle.padding.left         = 0;
                eventStyle.stretchHeight        = false;
                eventStyle.fixedHeight          = eventStyle.lineHeight + eventStyle.margin.top + eventStyle.margin.bottom;
                eventStyle.alignment            = TextAnchor.MiddleLeft;

                eventIcon        = EditorGUIUtility.Load("FMOD/EventIcon.png") as Texture;
                folderOpenIcon   = EditorGUIUtility.Load("FMOD/FolderIconOpen.png") as Texture;
                folderClosedIcon = EditorGUIUtility.Load("FMOD/FolderIconClosed.png") as Texture;
                searchIcon       = EditorGUIUtility.Load("FMOD/SearchIcon.png") as Texture;
                bankIcon         = EditorGUIUtility.Load("FMOD/BankIcon.png") as Texture;
                snapshotIcon     = EditorGUIUtility.Load("FMOD/SnapshotIcon.png") as Texture;
                borderIcon       = EditorGUIUtility.Load("FMOD/Border.png") as Texture2D;
            }

            if (fromInspector)
            {
                var border = new GUIStyle(GUI.skin.box);
                border.normal.background = borderIcon;
                GUI.Box(new Rect(1, 1, position.width - 1, position.height - 1), GUIContent.none, border);
            }

            // Split the window int search box, tree view, preview pane (only if full browser)
            Rect searchRect, listRect, previewRect;

            SplitWindow(out searchRect, out listRect, out previewRect);

            // Scroll the selected item in the tree view - put above the search box otherwise it will take
            // our key presses
            if (selectedItem != null && Event.current.type == EventType.KeyDown)
            {
                if (Event.current.keyCode == KeyCode.UpArrow)
                {
                    if (selectedItem.Prev != null)
                    {
                        SetSelectedItem(selectedItem.Prev);

                        // make sure it's visible
                        if (selectedItem.Rect.y < treeScroll.y)
                        {
                            treeScroll.y = selectedItem.Rect.y;
                        }
                    }
                    Event.current.Use();
                }
                if (Event.current.keyCode == KeyCode.DownArrow)
                {
                    if (selectedItem.Next != null)
                    {
                        SetSelectedItem(selectedItem.Next);
                        // make sure it's visible
                        if (selectedItem.Rect.y + selectedItem.Rect.height > treeScroll.y + listRect.height)
                        {
                            treeScroll.y += (selectedItem.Rect.y + selectedItem.Rect.height) - listRect.height;
                        }
                    }
                    Event.current.Use();
                }
                if (Event.current.keyCode == KeyCode.RightArrow)
                {
                    selectedItem.Expanded = true;
                    Event.current.Use();
                }
                if (Event.current.keyCode == KeyCode.LeftArrow)
                {
                    selectedItem.Expanded = false;
                    Event.current.Use();
                }
            }

            // Show the search box at the top
            GUILayout.BeginArea(searchRect);
            GUILayout.BeginHorizontal();
            GUILayout.Label(new GUIContent(searchIcon), GUILayout.ExpandWidth(false));
            GUI.SetNextControlName("SearchBox");
            searchString = EditorGUILayout.TextField(searchString);
            GUILayout.EndHorizontal();
            GUILayout.EndArea();

            if (fromInspector)
            {
                EditorGUI.FocusTextInControl("SearchBox");

                if (selectedItem != null && Event.current.isKey && Event.current.keyCode == KeyCode.Return &&
                    !(selectedItem.EventRef == null && selectedItem.BankRef == null))
                {
                    Event.current.Use();

                    if (selectedItem.EventRef != null)
                    {
                        outputProperty.stringValue = "";
                        outputProperty.stringValue = selectedItem.EventRef.Path;
                        EditorUtils.UpdateParamsOnEmitter(outputProperty.serializedObject, selectedItem.EventRef.Path);
                    }
                    else
                    {
                        outputProperty.stringValue = selectedItem.BankRef.Name;
                    }
                    outputProperty.serializedObject.ApplyModifiedProperties();
                    Close();
                }
                if (Event.current.isKey && Event.current.keyCode == KeyCode.Escape)
                {
                    Close();
                }
            }

            // Show the tree view
            Predicate <TreeItem> searchFilter = null;

            searchFilter = (x) => (x.Name.ToLower().Contains(searchString.ToLower()) || x.Children.Exists(searchFilter));

            // Check if our selected item still matches the search string
            if (selectedItem != null && !String.IsNullOrEmpty(searchString) && selectedItem.Children.Count == 0)
            {
                Predicate <TreeItem> containsSelected = null;
                containsSelected = (x) => (x == selectedItem || x.Children.Exists(containsSelected));
                Predicate <TreeItem> matchForSelected = null;
                matchForSelected = (x) => (x.Name.ToLower().Contains(searchString.ToLower()) && (x == selectedItem || x.Children.Exists(containsSelected))) || x.Children.Exists(matchForSelected);
                if (!treeItems.Exists(matchForSelected))
                {
                    SetSelectedItem(null);
                }
            }

            GUILayout.BeginArea(listRect);
            treeScroll = GUILayout.BeginScrollView(treeScroll, GUILayout.ExpandHeight(true));

            lastDrawnItem = null;
            itemCount     = 0;

            if (showEvents)
            {
                treeItems[(int)TreeType.Events].Expanded = fromInspector ? true : treeItems[(int)TreeType.Events].Expanded;
                ShowEventFolder(treeItems[(int)TreeType.Events], searchFilter);
                ShowEventFolder(treeItems[(int)TreeType.Snapshots], searchFilter);
            }
            if (showBanks)
            {
                treeItems[(int)TreeType.Banks].Expanded = fromInspector ? true : treeItems[(int)TreeType.Banks].Expanded;
                ShowEventFolder(treeItems[(int)TreeType.Banks], searchFilter);
            }
            if (showParameters)
            {
                treeItems[(int)TreeType.GlobalParameters].Expanded = fromInspector ? true : treeItems[(int)TreeType.GlobalParameters].Expanded;
                ShowEventFolder(treeItems[(int)TreeType.GlobalParameters], searchFilter);
            }

            GUILayout.EndScrollView();
            GUILayout.EndArea();

            // If the standalone event browser show a preview of the selected item
            if (!fromInspector)
            {
                GUI.Box(previewRect, GUIContent.none);

                if (selectedItem != null && selectedItem.EventRef != null && selectedItem.EventRef.Path.StartsWith("event:"))
                {
                    PreviewEvent(previewRect, selectedItem.EventRef);
                }

                if (selectedItem != null && selectedItem.EventRef != null && selectedItem.EventRef.Path.StartsWith("snapshot:"))
                {
                    PreviewSnapshot(previewRect, selectedItem.EventRef);
                }

                if (selectedItem != null && selectedItem.BankRef != null)
                {
                    PreviewBank(previewRect, selectedItem.BankRef);
                }

                if (selectedItem != null && selectedItem.ParamRef != null)
                {
                    PreviewParameter(previewRect, selectedItem.ParamRef);
                }
            }
        }
        public void DoConfigTokenEditorConnections(Node editor, TreeItem entry)
        {
            activeConfig = configs[entry];

            DoEditorConnections(editor, activeConfig);
        }
Example #30
0
 public LeafNode(TreeItem item)
 {
     _listItem = item;
 }
        void ShowEventFolder(TreeItem item, Predicate <TreeItem> filter)
        {
            eventStyle.padding.left += 17;

            if (item.EventRef != null || item.BankRef != null)
            {
                // Highlight first found item
                if (!String.IsNullOrEmpty(searchString) &&
                    itemCount == 0 &&
                    selectedItem == null)
                {
                    SetSelectedItem(item);
                }

                item.Next = null;
                item.Prev = lastDrawnItem;
                if (lastDrawnItem != null)
                {
                    lastDrawnItem.Next = item;
                }
                lastDrawnItem = item;
                itemCount++;
            }

            if (item.EventRef != null)
            {
                // Rendering and GUI event handling to show an event
                GUIContent content = new GUIContent(item.Name, item.EventRef.Path.StartsWith("snapshot") ? snapshotIcon : eventIcon);

                eventStyle.normal.background = selectedItem == item?EditorGUIUtility.Load("FMOD/Selected.png") as Texture2D : null;

                GUILayout.Label(content, eventStyle, GUILayout.ExpandWidth(true));

                Event e = Event.current;

                Rect rect = GUILayoutUtility.GetLastRect();
                if (e.type == EventType.MouseDown &&
                    e.button == 0 &&
                    rect.Contains(e.mousePosition))
                {
                    e.Use();

                    if (fromInspector && e.clickCount >= 2)
                    {
                        outputProperty.FindPropertyRelative("Path").stringValue = item.EventRef.Path;
                        outputProperty.serializedObject.ApplyModifiedProperties();
                        Close();
                    }

                    SetSelectedItem(item);
                }
                if (e.type == EventType.mouseDrag && rect.Contains(e.mousePosition) && !fromInspector)
                {
                    DragAndDrop.PrepareStartDrag();
                    DragAndDrop.objectReferences = new UnityEngine.Object[] { item.EventRef };
                    DragAndDrop.StartDrag("New FMOD Studio Emitter");
                    e.Use();
                }
                if (Event.current.type == EventType.Repaint)
                {
                    item.Rect = rect;
                }
            }
            else if (item.BankRef != null)
            {
                // Rendering and event handling for a bank
                GUIContent content = new GUIContent(item.Name, bankIcon);

                eventStyle.normal.background = selectedItem == item?EditorGUIUtility.Load("FMOD/Selected.png") as Texture2D : null;

                GUILayout.Label(content, eventStyle, GUILayout.ExpandWidth(true));

                Event e = Event.current;

                Rect rect = GUILayoutUtility.GetLastRect();
                if (e.type == EventType.MouseDown &&
                    e.button == 0 &&
                    rect.Contains(e.mousePosition))
                {
                    e.Use();

                    if (fromInspector && e.clickCount >= 2)
                    {
                        outputProperty.FindPropertyRelative("Name").stringValue = item.BankRef.Name;
                        outputProperty.serializedObject.ApplyModifiedProperties();
                        Close();
                    }

                    SetSelectedItem(item);
                }
                if (e.type == EventType.mouseDrag && rect.Contains(e.mousePosition) && !fromInspector)
                {
                    DragAndDrop.PrepareStartDrag();
                    DragAndDrop.objectReferences = new UnityEngine.Object[] { item.BankRef };
                    DragAndDrop.StartDrag("New FMOD Studio Bank Loader");
                    e.Use();
                }
                if (Event.current.type == EventType.Repaint)
                {
                    item.Rect = rect;
                }
            }
            else
            {
                eventStyle.normal.background = null;
                bool       expanded = item.Expanded || !string.IsNullOrEmpty(searchString);
                GUIContent content  = new GUIContent(item.Name, expanded ? folderOpenIcon : folderClosedIcon);
                GUILayout.Label(content, eventStyle);

                Rect rect = GUILayoutUtility.GetLastRect();
                if (Event.current.type == EventType.MouseDown &&
                    Event.current.button == 0 &&
                    rect.Contains(Event.current.mousePosition))
                {
                    Event.current.Use();
                    item.Expanded = !item.Expanded;
                }

                if (item.Expanded || !string.IsNullOrEmpty(searchString))
                {
                    if (item.Name.ToLower().Contains(searchString.ToLower()))
                    {
                        foreach (var childFolder in item.Children)
                        {
                            ShowEventFolder(childFolder, (x) => true);
                        }
                    }
                    else
                    {
                        foreach (var childFolder in item.Children.FindAll(filter))
                        {
                            ShowEventFolder(childFolder, filter);
                        }
                    }
                }
            }
            eventStyle.padding.left -= 17;
        }
 private static string GetName(TreeItem item)
 {
     return(item.Target.GetType().Name);
 }
Example #33
0
 private Task OnTreeItemClick(TreeItem item)
 {
     Trace?.Log($"TreeItem: {item.Text} clicked");
     return(Task.CompletedTask);
 }
 public BinarySearchTree_GenKey()
 {
     this.root = null;
 }
Example #35
0
 public Leaf(TreeItem item)
 {
     ListItem = item;
 }
Example #36
0
 public TreeViewItemWrapper(TreeItem item, int depth)
 {
     this.item  = item;
     this.depth = depth;
 }
        public void ProcessRequest(System.Web.HttpContext context)
        {
            string strJSON = null;

            try
            {
                string strId = context.Request.Params["id"];
                System.Diagnostics.Debug.WriteLine(strId);

                List <TreeItem> ls = new List <TreeItem>();

                TreeItem root = new TreeItem();

                if (string.IsNullOrEmpty(strId))
                {
                    root.id   = "1";
                    root.text = "RootNode ";
                }
                else
                {
                    root.id   = strId + ".1";
                    root.text = "Node " + strId;
                }
                // root.state = "closed";
                //root.id = System.Guid.NewGuid().ToString();
                root.children = true;

                //root.state = new KeyValuePair<string, jsbool>("closed", jsbool.@true);
                //root.state = oldNodeState.Disabled;

                // root.newstate.Add(NodeState.leaf, jsbool.@true);
                // root.newstate.Add(NodeState.disabled, jsbool.@true);

                // root.newstate.Add(NodeState.opened | NodeState.closed, jsbool.@true);


                // root.state = NodeState.closed | NodeState.selected | NodeState.disabled;
                //root.state = NodeState.closed;


                bool bRandomChildren = true;
                if (bRandomChildren)
                {
                    for (int i = 0; i < 10; ++i)
                    {
                        TreeItem ChildNode = new TreeItem();
                        ChildNode.id   = i.ToString();
                        ChildNode.text = "ChildNode " + i.ToString();
                        //ChildNode.state="closed";

                        if (i == 1)
                        {
                            TreeItem ChildChild = new TreeItem();
                            ChildChild.id   = "lol";
                            ChildChild.text = "hello";

                            //ChildNode.children.Add(ChildChild);
                        }                         // End if (i == 1)

                        //root.children.Add(ChildNode);
                    }             // Next i
                }                 // End if(bRandomChildren)

                ls.Add(root);
                TreeItem root2 = new TreeItem();

                if (string.IsNullOrEmpty(strId))
                {
                    root2.id   = "bla";
                    root2.text = "Ho;ha";
                }
                else
                {
                    root2.id   = strId + ".1";
                    root2.text = "More blabla";
                }

                ls.Add(root2);

                strJSON = Tools.Serialization.JSON.Serialize(ls);
            }             // End Try
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                Tools.AJAX.cAjaxResult AjaxResult = new Tools.AJAX.cAjaxResult();
                AjaxResult.error = new Tools.AJAX.AJAXException(ex);
                strJSON          = Tools.Serialization.JSON.Serialize(AjaxResult);
            }             // End Catch

            System.Diagnostics.Debug.WriteLine(strJSON);
            context.Response.ContentType = "application/json";
            context.Response.Write(strJSON);
        } // End Sub ProcessRequest
Example #38
0
 private void SetParent(TreeItem parent)
 {
     Parent = parent;
 }
Example #39
0
        public IActionResult Move(int id, [Bind("ID,Value,Parent")] TreeItem treeItem, int rootId)
        {
            if (id != treeItem.ID)
            {
                TempData["msg"] = "Unknown error, sorry";
                return(NotFound());
            }
            TreeItem treeItemOld = _context.TreeItem.Find(id);

            if (treeItemOld.Parent == null)
            {
                if (treeItem.Parent != treeItemOld.Parent)
                {
                    TempData["msg"] = "Can't move roots";
                    return(Redirect("/TreeItems/GetTree/" + rootId.ToString()));
                }
                else
                {
                    _context.Entry(treeItemOld).State = EntityState.Detached;
                    _context.Update(treeItem);
                    _context.SaveChanges();
                    TempData["msg"] = "Edited";
                    return(Redirect("/TreeItems/GetTree/" + rootId.ToString()));
                }
            }
            else
            {
                _context.Entry(treeItemOld).State = EntityState.Detached;
            }

            bool isMovementCorret;

            if (treeItem.Parent == null)
            {
                isMovementCorret = true;
            }
            else if (treeItem.Parent == treeItem.ID)
            {
                isMovementCorret = false;
            }
            else
            {
                List <String> stats = new List <String>();
                stats = IsNotIDInChildren(treeItem.ID, treeItem.Parent, stats);
                if (stats.Contains("error"))
                {
                    isMovementCorret = false;
                }
                else
                {
                    isMovementCorret = true;
                }
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (isMovementCorret)
                    {
                        TempData["msg"] = "Edited";
                        _context.Update(treeItem);
                        _context.SaveChanges();
                    }
                    else
                    {
                        TempData["msg"] = "Can't move branch into itself";
                    }
                }
                catch (DbUpdateConcurrencyException)
                {
                    TempData["msg"] = "Unknown error, sorry";
                    return(NotFound());
                }
                return(Redirect("/TreeItems/GetTree/" + rootId.ToString()));
            }
            return(View(treeItem));
        }
        private void RebuildDisplayFromCache()
        {
            Action <TreeItem> nullEvents = null;

            nullEvents = (x) => { x.Exists = false; x.Children.ForEach(nullEvents); };
            Predicate <TreeItem> isStale             = (x) => !x.Exists;
            Action <TreeItem>    removeStaleChildren = null;

            removeStaleChildren = (x) => { x.Children.RemoveAll(isStale); x.Children.ForEach(removeStaleChildren); };

            if (showEvents)
            {
                var editorEvents = EventManager.Events;

                treeItems[0].Children.ForEach(nullEvents);
                treeItems[1].Children.ForEach(nullEvents);

                foreach (var editorEvent in editorEvents)
                {
                    string[] split = editorEvent.Path.Split('/');
                    var      level = split[0] == "snapshot:" ? treeItems[1].Children : treeItems[0].Children;
                    for (int i = 1; i < split.Length; i++)
                    {
                        TreeItem item = level.Find((x) => x.Name == split[i]);
                        if (item != null)
                        {
                            if (i == (split.Length - 1))
                            {
                                item.EventRef = editorEvent;
                            }
                            else
                            {
                                level = item.Children;
                            }
                        }
                        else
                        {
                            item = new TreeItem();
                            if (i == (split.Length - 1))
                            {
                                item.EventRef = editorEvent;
                            }
                            item.Name = split[i];
                            level.Add(item);
                            level.Sort((a, b) => a.EventRef != b.EventRef ? (a.EventRef != null ? 1 : -1) : a.Name.CompareTo(b.Name));
                            level = item.Children;
                        }
                        item.Exists = true;
                    }
                }

                removeStaleChildren(treeItems[0]);
                removeStaleChildren(treeItems[1]);
            }

            if (showBanks)
            {
                var editorBanks = EventManager.Banks;
                var children    = treeItems[2].Children;

                children.ForEach(nullEvents);

                foreach (var editorBank in editorBanks)
                {
                    var      name = Path.GetFileNameWithoutExtension(editorBank.Path);
                    TreeItem item = children.Find((x) => x.Name == name);
                    if (item == null)
                    {
                        item         = new TreeItem();
                        item.Name    = name;
                        item.BankRef = editorBank;
                        children.Add(item);
                    }
                    item.Exists = true;
                }
                children.Sort((a, b) => a.Name.CompareTo(b.Name));

                removeStaleChildren(treeItems[2]);
            }

            if (expandedState != null && EventManager.IsLoaded)
            {
                int i = 0;
                Action <TreeItem> setExpanded = null;
                setExpanded = (x) => { selectedItem = (i == selectedIndex) ? x : selectedItem; x.Expanded = expandedState[i++]; x.Children.ForEach(setExpanded); };
                try
                {
                    treeItems.ForEach(setExpanded);
                }
                catch
                {
                }

                expandedState = null;

                if (selectedItem != null)
                {
                    SetPreviewEvent(selectedItem.EventRef);
                }
                else
                {
                    SetPreviewEvent(null);
                }
            }
        }
Example #41
0
        internal SoundViewModel(Sound sound)
        {
            CompositeDisposable treeItemDisposable = new CompositeDisposable();
            CompositeDisposable listItemDisposable = new CompositeDisposable();

            Simulation.TrainManager.TrainManager.RunSounds   = sound.SoundElements.OfType <RunElement>().ToList();
            Simulation.TrainManager.TrainManager.MotorSounds = sound.SoundElements.OfType <MotorElement>().ToList();

            sound.SoundElements
            .ObserveAddChanged()
            .Subscribe(x =>
            {
                RunElement run     = x as RunElement;
                MotorElement motor = x as MotorElement;

                if (run != null)
                {
                    Simulation.TrainManager.TrainManager.RunSounds.Add(run);
                }

                if (motor != null)
                {
                    Simulation.TrainManager.TrainManager.MotorSounds.Add(motor);
                }
            })
            .AddTo(disposable);

            sound.SoundElements
            .ObserveRemoveChanged()
            .Subscribe(x =>
            {
                RunElement run     = x as RunElement;
                MotorElement motor = x as MotorElement;

                if (run != null)
                {
                    Simulation.TrainManager.TrainManager.RunSounds.Remove(run);
                }

                if (motor != null)
                {
                    Simulation.TrainManager.TrainManager.MotorSounds.Remove(motor);
                }
            })
            .AddTo(disposable);

            TreeItem = sound
                       .ObserveProperty(x => x.TreeItem)
                       .Do(_ => TreeItem?.Value.Dispose())
                       .Select(x => new TreeViewItemViewModel(x))
                       .ToReactiveProperty()
                       .AddTo(disposable);

            TreeItem.Subscribe(x =>
            {
                treeItemDisposable.Dispose();
                treeItemDisposable = new CompositeDisposable();

                x.PropertyChangedAsObservable()
                .ToReadOnlyReactivePropertySlim(mode: ReactivePropertyMode.None)
                .Subscribe(_ => TreeItem.ForceNotify())
                .AddTo(treeItemDisposable);
            })
            .AddTo(disposable);

            SelectedTreeItem = sound
                               .ToReactivePropertyAsSynchronized(
                x => x.SelectedTreeItem,
                x => TreeItem.Value.SearchViewModel(x),
                x => x?.Model
                )
                               .AddTo(disposable);

            ListColumns = sound.ListColumns
                          .ToReadOnlyReactiveCollection(x => new ListViewColumnHeaderViewModel(x))
                          .AddTo(disposable);

            ListItems = sound.ListItems
                        .ToReadOnlyReactiveCollection(x => new ListViewItemViewModel(x))
                        .AddTo(disposable);

            SelectedListItem = sound
                               .ToReactivePropertyAsSynchronized(
                x => x.SelectedListItem,
                x => ListItems.FirstOrDefault(y => y.Model == x),
                x => x?.Model
                )
                               .AddTo(disposable);

            SelectedTreeItem
            .Subscribe(_ =>
            {
                SelectedListItem.Value = null;
                sound.CreateListColumns();
                sound.CreateListItems();
            })
            .AddTo(disposable);

            SelectedListItem
            .Where(x => x != null)
            .Subscribe(x =>
            {
                listItemDisposable.Dispose();
                listItemDisposable = new CompositeDisposable();

                CompositeDisposable tagDisposable = new CompositeDisposable();

                x.Tag
                .OfType <INotifyPropertyChanged>()
                .Subscribe(y =>
                {
                    tagDisposable.Dispose();
                    tagDisposable = new CompositeDisposable();

                    y.PropertyChangedAsObservable()
                    .Subscribe(_ => sound.UpdateListItem(x.Model))
                    .AddTo(tagDisposable);
                })
                .AddTo(listItemDisposable);

                tagDisposable.AddTo(listItemDisposable);
            })
            .AddTo(disposable);

            SelectedRun = SelectedListItem
                          .Select(x => x?.Tag.Value as RunElement)
                          .Do(_ => SelectedRun?.Value?.Dispose())
                          .Select(x => x != null ? new RunElementViewModel(x, sound.SoundElements.OfType <RunElement>().Where(y => y != x)) : null)
                          .ToReadOnlyReactivePropertySlim()
                          .AddTo(disposable);

            SelectedFlange = SelectedListItem
                             .Select(x => x?.Tag.Value as FlangeElement)
                             .Do(_ => SelectedFlange?.Value?.Dispose())
                             .Select(x => x != null ? new FlangeElementViewModel(x, sound.SoundElements.OfType <FlangeElement>().Where(y => y != x)) : null)
                             .ToReadOnlyReactivePropertySlim()
                             .AddTo(disposable);

            SelectedMotor = SelectedListItem
                            .Select(x => x?.Tag.Value as MotorElement)
                            .Do(_ => SelectedMotor?.Value?.Dispose())
                            .Select(x => x != null ? new MotorElementViewModel(x, sound.SoundElements.OfType <MotorElement>().Where(y => y != x)) : null)
                            .ToReadOnlyReactivePropertySlim()
                            .AddTo(disposable);

            SelectedFrontSwitch = SelectedListItem
                                  .Select(x => x?.Tag.Value as FrontSwitchElement)
                                  .Do(_ => SelectedFrontSwitch?.Value?.Dispose())
                                  .Select(x => x != null ? new FrontSwitchElementViewModel(x, sound.SoundElements.OfType <FrontSwitchElement>().Where(y => y != x)) : null)
                                  .ToReadOnlyReactivePropertySlim()
                                  .AddTo(disposable);

            SelectedRearSwitch = SelectedListItem
                                 .Select(x => x?.Tag.Value as RearSwitchElement)
                                 .Do(_ => SelectedRearSwitch?.Value?.Dispose())
                                 .Select(x => x != null ? new RearSwitchElementViewModel(x, sound.SoundElements.OfType <RearSwitchElement>().Where(y => y != x)) : null)
                                 .ToReadOnlyReactivePropertySlim()
                                 .AddTo(disposable);

            SelectedBrake = SelectedListItem
                            .Select(x => x?.Tag.Value as BrakeElement)
                            .Do(_ => SelectedBrake?.Value?.Dispose())
                            .Select(x => x != null ? new BrakeElementViewModel(x, sound.SoundElements.OfType <BrakeElement>().Where(y => y != x)) : null)
                            .ToReadOnlyReactivePropertySlim()
                            .AddTo(disposable);

            SelectedCompressor = SelectedListItem
                                 .Select(x => x?.Tag.Value as CompressorElement)
                                 .Do(_ => SelectedCompressor?.Value?.Dispose())
                                 .Select(x => x != null ? new CompressorElementViewModel(x, sound.SoundElements.OfType <CompressorElement>().Where(y => y != x)) : null)
                                 .ToReadOnlyReactivePropertySlim()
                                 .AddTo(disposable);

            SelectedSuspension = SelectedListItem
                                 .Select(x => x?.Tag.Value as SuspensionElement)
                                 .Do(_ => SelectedSuspension?.Value?.Dispose())
                                 .Select(x => x != null ? new SuspensionElementViewModel(x, sound.SoundElements.OfType <SuspensionElement>().Where(y => y != x)) : null)
                                 .ToReadOnlyReactivePropertySlim()
                                 .AddTo(disposable);

            SelectedPrimaryHorn = SelectedListItem
                                  .Select(x => x?.Tag.Value as PrimaryHornElement)
                                  .Do(_ => SelectedPrimaryHorn?.Value?.Dispose())
                                  .Select(x => x != null ? new PrimaryHornElementViewModel(x, sound.SoundElements.OfType <PrimaryHornElement>().Where(y => y != x)) : null)
                                  .ToReadOnlyReactivePropertySlim()
                                  .AddTo(disposable);

            SelectedSecondaryHorn = SelectedListItem
                                    .Select(x => x?.Tag.Value as SecondaryHornElement)
                                    .Do(_ => SelectedSecondaryHorn?.Value?.Dispose())
                                    .Select(x => x != null ? new SecondaryHornElementViewModel(x, sound.SoundElements.OfType <SecondaryHornElement>().Where(y => y != x)) : null)
                                    .ToReadOnlyReactivePropertySlim()
                                    .AddTo(disposable);

            SelectedMusicHorn = SelectedListItem
                                .Select(x => x?.Tag.Value as MusicHornElement)
                                .Do(_ => SelectedMusicHorn?.Value?.Dispose())
                                .Select(x => x != null ? new MusicHornElementViewModel(x, sound.SoundElements.OfType <MusicHornElement>().Where(y => y != x)) : null)
                                .ToReadOnlyReactivePropertySlim()
                                .AddTo(disposable);

            SelectedDoor = SelectedListItem
                           .Select(x => x?.Tag.Value as DoorElement)
                           .Do(_ => SelectedDoor?.Value?.Dispose())
                           .Select(x => x != null ? new DoorElementViewModel(x, sound.SoundElements.OfType <DoorElement>().Where(y => y != x)) : null)
                           .ToReadOnlyReactivePropertySlim()
                           .AddTo(disposable);

            SelectedAts = SelectedListItem
                          .Select(x => x?.Tag.Value as AtsElement)
                          .Do(_ => SelectedAts?.Value?.Dispose())
                          .Select(x => x != null ? new AtsElementViewModel(x, sound.SoundElements.OfType <AtsElement>().Where(y => y != x)) : null)
                          .ToReadOnlyReactivePropertySlim()
                          .AddTo(disposable);

            SelectedBuzzer = SelectedListItem
                             .Select(x => x?.Tag.Value as BuzzerElement)
                             .Do(_ => SelectedBuzzer?.Value?.Dispose())
                             .Select(x => x != null ? new BuzzerElementViewModel(x, sound.SoundElements.OfType <BuzzerElement>().Where(y => y != x)) : null)
                             .ToReadOnlyReactivePropertySlim()
                             .AddTo(disposable);

            SelectedPilotLamp = SelectedListItem
                                .Select(x => x?.Tag.Value as PilotLampElement)
                                .Do(_ => SelectedPilotLamp?.Value?.Dispose())
                                .Select(x => x != null ? new PilotLampElementViewModel(x, sound.SoundElements.OfType <PilotLampElement>().Where(y => y != x)) : null)
                                .ToReadOnlyReactivePropertySlim()
                                .AddTo(disposable);

            SelectedBrakeHandle = SelectedListItem
                                  .Select(x => x?.Tag.Value as BrakeHandleElement)
                                  .Do(_ => SelectedBrakeHandle?.Value?.Dispose())
                                  .Select(x => x != null ? new BrakeHandleElementViewModel(x, sound.SoundElements.OfType <BrakeHandleElement>().Where(y => y != x)) : null)
                                  .ToReadOnlyReactivePropertySlim()
                                  .AddTo(disposable);

            SelectedMasterController = SelectedListItem
                                       .Select(x => x?.Tag.Value as MasterControllerElement)
                                       .Do(_ => SelectedMasterController?.Value?.Dispose())
                                       .Select(x => x != null ? new MasterControllerElementViewModel(x, sound.SoundElements.OfType <MasterControllerElement>().Where(y => y != x)) : null)
                                       .ToReadOnlyReactivePropertySlim()
                                       .AddTo(disposable);

            SelectedReverser = SelectedListItem
                               .Select(x => x?.Tag.Value as ReverserElement)
                               .Do(_ => SelectedReverser?.Value?.Dispose())
                               .Select(x => x != null ? new ReverserElementViewModel(x, sound.SoundElements.OfType <ReverserElement>().Where(y => y != x)) : null)
                               .ToReadOnlyReactivePropertySlim()
                               .AddTo(disposable);

            SelectedBreaker = SelectedListItem
                              .Select(x => x?.Tag.Value as BreakerElement)
                              .Do(_ => SelectedBreaker?.Value?.Dispose())
                              .Select(x => x != null ? new BreakerElementViewModel(x, sound.SoundElements.OfType <BreakerElement>().Where(y => y != x)) : null)
                              .ToReadOnlyReactivePropertySlim()
                              .AddTo(disposable);

            SelectedRequestStop = SelectedListItem
                                  .Select(x => x?.Tag.Value as RequestStopElement)
                                  .Do(_ => SelectedAts?.Value?.Dispose())
                                  .Select(x => x != null ? new RequestStopElementViewModel(x, sound.SoundElements.OfType <RequestStopElement>().Where(y => y != x)) : null)
                                  .ToReadOnlyReactivePropertySlim()
                                  .AddTo(disposable);

            SelectedTouch = SelectedListItem
                            .Select(x => x?.Tag.Value as TouchElement)
                            .Do(_ => SelectedTouch?.Value?.Dispose())
                            .Select(x => x != null ? new TouchElementViewModel(x, sound.SoundElements.OfType <TouchElement>().Where(y => y != x)) : null)
                            .ToReadOnlyReactivePropertySlim()
                            .AddTo(disposable);

            SelectedOthers = SelectedListItem
                             .Select(x => x?.Tag.Value as OthersElement)
                             .Do(_ => SelectedOthers?.Value?.Dispose())
                             .Select(x => x != null ? new OthersElementViewModel(x, sound.SoundElements.OfType <OthersElement>().Where(y => y != x)) : null)
                             .ToReadOnlyReactivePropertySlim()
                             .AddTo(disposable);

            AddRun = SelectedTreeItem
                     .Select(x => x == TreeItem.Value.Children[0])
                     .ToReactiveCommand()
                     .WithSubscribe(sound.AddElement <RunElement>)
                     .AddTo(disposable);

            AddFlange = SelectedTreeItem
                        .Select(x => x == TreeItem.Value.Children[1])
                        .ToReactiveCommand()
                        .WithSubscribe(sound.AddElement <FlangeElement>)
                        .AddTo(disposable);

            AddMotor = SelectedTreeItem
                       .Select(x => x == TreeItem.Value.Children[2])
                       .ToReactiveCommand()
                       .WithSubscribe(sound.AddElement <MotorElement>)
                       .AddTo(disposable);

            AddFrontSwitch = SelectedTreeItem
                             .Select(x => x == TreeItem.Value.Children[3])
                             .ToReactiveCommand()
                             .WithSubscribe(sound.AddElement <FrontSwitchElement>)
                             .AddTo(disposable);

            AddRearSwitch = SelectedTreeItem
                            .Select(x => x == TreeItem.Value.Children[4])
                            .ToReactiveCommand()
                            .WithSubscribe(sound.AddElement <RearSwitchElement>)
                            .AddTo(disposable);

            AddBrake = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[5]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(BrakeKey))
                        .OfType <BrakeKey>()
                        .Except(sound.SoundElements.OfType <BrakeElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <BrakeElement, BrakeKey>)
            .AddTo(disposable);

            AddCompressor = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[6]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(CompressorKey))
                        .OfType <CompressorKey>()
                        .Except(sound.SoundElements.OfType <CompressorElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <CompressorElement, CompressorKey>)
            .AddTo(disposable);

            AddSuspension = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[7]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(SuspensionKey))
                        .OfType <SuspensionKey>()
                        .Except(sound.SoundElements.OfType <SuspensionElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <SuspensionElement, SuspensionKey>)
            .AddTo(disposable);

            AddPrimaryHorn = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[8]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(HornKey))
                        .OfType <HornKey>()
                        .Except(sound.SoundElements.OfType <PrimaryHornElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <PrimaryHornElement, HornKey>)
            .AddTo(disposable);

            AddSecondaryHorn = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[9]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(HornKey))
                        .OfType <HornKey>()
                        .Except(sound.SoundElements.OfType <SecondaryHornElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <SecondaryHornElement, HornKey>)
            .AddTo(disposable);

            AddMusicHorn = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[10]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(HornKey))
                        .OfType <HornKey>()
                        .Except(sound.SoundElements.OfType <MusicHornElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <MusicHornElement, HornKey>)
            .AddTo(disposable);

            AddDoor = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[11]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(DoorKey))
                        .OfType <DoorKey>()
                        .Except(sound.SoundElements.OfType <DoorElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <DoorElement, DoorKey>)
            .AddTo(disposable);

            AddAts = SelectedTreeItem
                     .Select(x => x == TreeItem.Value.Children[12])
                     .ToReactiveCommand()
                     .WithSubscribe(sound.AddElement <AtsElement>)
                     .AddTo(disposable);

            AddBuzzer = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[13]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(BuzzerKey))
                        .OfType <BuzzerKey>()
                        .Except(sound.SoundElements.OfType <BuzzerElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <BuzzerElement, BuzzerKey>)
            .AddTo(disposable);

            AddPilotLamp = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[14]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(PilotLampKey))
                        .OfType <PilotLampKey>()
                        .Except(sound.SoundElements.OfType <PilotLampElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <PilotLampElement, PilotLampKey>)
            .AddTo(disposable);

            AddBrakeHandle = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[15]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(BrakeHandleKey))
                        .OfType <BrakeHandleKey>()
                        .Except(sound.SoundElements.OfType <BrakeHandleElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <BrakeHandleElement, BrakeHandleKey>)
            .AddTo(disposable);

            AddMasterController = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[16]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(MasterControllerKey))
                        .OfType <MasterControllerKey>()
                        .Except(sound.SoundElements.OfType <MasterControllerElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <MasterControllerElement, MasterControllerKey>)
            .AddTo(disposable);

            AddReverser = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[17]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(ReverserKey))
                        .OfType <ReverserKey>()
                        .Except(sound.SoundElements.OfType <ReverserElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <ReverserElement, ReverserKey>)
            .AddTo(disposable);

            AddBreaker = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[18]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(BreakerKey))
                        .OfType <BreakerKey>()
                        .Except(sound.SoundElements.OfType <BreakerElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <BreakerElement, BreakerKey>)
            .AddTo(disposable);

            AddRequestStop = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[19]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(RequestStopKey))
                        .OfType <RequestStopKey>()
                        .Except(sound.SoundElements.OfType <RequestStopElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <RequestStopElement, RequestStopKey>)
            .AddTo(disposable);

            AddTouch = SelectedTreeItem
                       .Select(x => x == TreeItem.Value.Children[20])
                       .ToReactiveCommand()
                       .WithSubscribe(sound.AddElement <TouchElement>)
                       .AddTo(disposable);

            AddOthers = new[]
            {
                SelectedTreeItem.Select(x => x == TreeItem.Value.Children[21]),
                sound.SoundElements
                .CollectionChangedAsObservable()
                .ToReadOnlyReactivePropertySlim()
                .Select(_ => Enum.GetValues(typeof(OthersKey))
                        .OfType <OthersKey>()
                        .Except(sound.SoundElements.OfType <OthersElement>().Select(y => y.Key))
                        .Any()
                        )
            }
            .CombineLatestValuesAreAllTrue()
            .ToReactiveCommand()
            .WithSubscribe(sound.AddElement <OthersElement, OthersKey>)
            .AddTo(disposable);

            RemoveRun = SelectedRun
                        .Select(x => x != null)
                        .ToReactiveCommand()
                        .WithSubscribe(sound.RemoveElement <RunElement>)
                        .AddTo(disposable);

            RemoveFlange = SelectedFlange
                           .Select(x => x != null)
                           .ToReactiveCommand()
                           .WithSubscribe(sound.RemoveElement <FlangeElement>)
                           .AddTo(disposable);

            RemoveMotor = SelectedMotor
                          .Select(x => x != null)
                          .ToReactiveCommand()
                          .WithSubscribe(sound.RemoveElement <MotorElement>)
                          .AddTo(disposable);

            RemoveFrontSwitch = SelectedFrontSwitch
                                .Select(x => x != null)
                                .ToReactiveCommand()
                                .WithSubscribe(sound.RemoveElement <FrontSwitchElement>)
                                .AddTo(disposable);

            RemoveRearSwitch = SelectedRearSwitch
                               .Select(x => x != null)
                               .ToReactiveCommand()
                               .WithSubscribe(sound.RemoveElement <RearSwitchElement>)
                               .AddTo(disposable);

            RemoveBrake = SelectedBrake
                          .Select(x => x != null)
                          .ToReactiveCommand()
                          .WithSubscribe(sound.RemoveElement <BrakeElement>)
                          .AddTo(disposable);

            RemoveCompressor = SelectedCompressor
                               .Select(x => x != null)
                               .ToReactiveCommand()
                               .WithSubscribe(sound.RemoveElement <CompressorElement>)
                               .AddTo(disposable);

            RemoveSuspension = SelectedSuspension
                               .Select(x => x != null)
                               .ToReactiveCommand()
                               .WithSubscribe(sound.RemoveElement <SuspensionElement>)
                               .AddTo(disposable);

            RemovePrimaryHorn = SelectedPrimaryHorn
                                .Select(x => x != null)
                                .ToReactiveCommand()
                                .WithSubscribe(sound.RemoveElement <PrimaryHornElement>)
                                .AddTo(disposable);

            RemoveSecondaryHorn = SelectedSecondaryHorn
                                  .Select(x => x != null)
                                  .ToReactiveCommand()
                                  .WithSubscribe(sound.RemoveElement <SecondaryHornElement>)
                                  .AddTo(disposable);

            RemoveMusicHorn = SelectedMusicHorn
                              .Select(x => x != null)
                              .ToReactiveCommand()
                              .WithSubscribe(sound.RemoveElement <MusicHornElement>)
                              .AddTo(disposable);

            RemoveDoor = SelectedDoor
                         .Select(x => x != null)
                         .ToReactiveCommand()
                         .WithSubscribe(sound.RemoveElement <DoorElement>)
                         .AddTo(disposable);

            RemoveAts = SelectedAts
                        .Select(x => x != null)
                        .ToReactiveCommand()
                        .WithSubscribe(sound.RemoveElement <AtsElement>)
                        .AddTo(disposable);

            RemoveBuzzer = SelectedBuzzer
                           .Select(x => x != null)
                           .ToReactiveCommand()
                           .WithSubscribe(sound.RemoveElement <BuzzerElement>)
                           .AddTo(disposable);

            RemovePilotLamp = SelectedPilotLamp
                              .Select(x => x != null)
                              .ToReactiveCommand()
                              .WithSubscribe(sound.RemoveElement <PilotLampElement>)
                              .AddTo(disposable);

            RemoveBrakeHandle = SelectedBrakeHandle
                                .Select(x => x != null)
                                .ToReactiveCommand()
                                .WithSubscribe(sound.RemoveElement <BrakeHandleElement>)
                                .AddTo(disposable);

            RemoveMasterController = SelectedMasterController
                                     .Select(x => x != null)
                                     .ToReactiveCommand()
                                     .WithSubscribe(sound.RemoveElement <MasterControllerElement>)
                                     .AddTo(disposable);

            RemoveReverser = SelectedReverser
                             .Select(x => x != null)
                             .ToReactiveCommand()
                             .WithSubscribe(sound.RemoveElement <ReverserElement>)
                             .AddTo(disposable);

            RemoveBreaker = SelectedBreaker
                            .Select(x => x != null)
                            .ToReactiveCommand()
                            .WithSubscribe(sound.RemoveElement <BreakerElement>)
                            .AddTo(disposable);

            RemoveRequestStop = SelectedRequestStop
                                .Select(x => x != null)
                                .ToReactiveCommand()
                                .WithSubscribe(sound.RemoveElement <RequestStopElement>)
                                .AddTo(disposable);

            RemoveTouch = SelectedTouch
                          .Select(x => x != null)
                          .ToReactiveCommand()
                          .WithSubscribe(sound.RemoveElement <TouchElement>)
                          .AddTo(disposable);

            RemoveOthers = SelectedOthers
                           .Select(x => x != null)
                           .ToReactiveCommand()
                           .WithSubscribe(sound.RemoveElement <OthersElement>)
                           .AddTo(disposable);

            treeItemDisposable.AddTo(disposable);
            listItemDisposable.AddTo(disposable);
        }
Example #42
0
 /// <summary>
 /// Analyzes the specified element for issues.
 /// </summary>
 public virtual void Analyze(TreeItem treeItem, AnalyzerContext analyzerContext)
 {
     analyzerContext.UpdateIssues(this, treeItem, AnalyzeInternal(treeItem));
 }
Example #43
0
        public static void AddSQLServerInstance(string serverName)
        {
            try
            {
                repo.Application.AllServersInfo.WaitForItemExists(120000);
                TreeItem serveritem = repo.Application.AllServers.GetChildItem(serverName);
                if (serveritem == null)
                {
                    repo.Application.AllServers.RightClick();
                    //serveritem.RightClick();

                    //Click On Manage Servers
                    repo.SQLdmDC.ManageServersInfo.WaitForExists(120000);
                    repo.SQLdmDC.ManageServers.ClickThis();

                    //Wait For Confirmation
                    repo.ManageServersDialog.SelfInfo.WaitForExists(new Duration(1000000));

                    //Click ON Add Button IN Manage Servers
                    repo.ManageServersDialog.btnMSAddInfo.WaitForExists(120000);
                    repo.ManageServersDialog.btnMSAdd.ClickThis();


                    //Click ON Next in Add Server Wizard
                    repo.AddServersWizardDialog.btnASWNextInfo.WaitForExists(120000);
                    repo.AddServersWizardDialog.btnASWNext.ClickThis();

                    //Click ON Next in Add Configure Authentication
                    repo.AddServersWizardDialog.btnASWNextInfo.WaitForExists(120000);
                    repo.AddServersWizardDialog.btnASWNext.ClickThis();

                    //Enter Server Name
                    repo.AddServersWizardDialog.txtAvailableServersInfo.WaitForExists(120000);
                    repo.AddServersWizardDialog.txtAvailableServers.TextValue = serverName.ToString();

                    //Click ON Add Button in Select Server To Monitor
                    repo.AddServersWizardDialog.btnSSTMAddInfo.WaitForExists(120000);
                    repo.AddServersWizardDialog.btnSSTMAdd.ClickThis();

                    //Click ON Next in Select Server To Monitor
                    repo.AddServersWizardDialog.btnASWNextInfo.WaitForExists(120000);
                    repo.AddServersWizardDialog.btnASWNext.ClickThis();

                    //Click ON Next in Add Servers
                    repo.AddServersWizardDialog.btnASWNextInfo.WaitForExists(120000);
                    repo.AddServersWizardDialog.btnASWNext.ClickThis();

                    //Click ON Next in Configure SQLdm
                    repo.AddServersWizardDialog.btnASWNextInfo.WaitForExists(120000);
                    repo.AddServersWizardDialog.btnASWNext.ClickThis();

                    //Click ON Next in Configure OS Collection
                    repo.AddServersWizardDialog.btnASWNextInfo.WaitForExists(120000);
                    repo.AddServersWizardDialog.btnASWNext.ClickThis();

                    //Click ON Finish in Configure OS Collection
                    repo.AddServersWizardDialog.btnASFinishInfo.WaitForExists(120000);
                    repo.AddServersWizardDialog.btnASFinish.ClickThis();

                    //Click ON Finish in Configure OS Collection
                    repo.ExceptionMessageBoxForm.btnMSYesInfo.WaitForExists(120000);
                    repo.ExceptionMessageBoxForm.btnMSYes.ClickThis();

                    //Click ON Apply Button IN Manage Servers
                    repo.ManageServersDialog.btnApplyInfo.WaitForExists(120000);
                    repo.ManageServersDialog.btnApply.ClickThis();

                    //Click ON Ok Button IN Manage Servers
                    repo.ManageServersDialog.btnMSOkInfo.WaitForExists(120000);
                    //repo.ManageServersDialog.btnMSOk.Enabled= true
                    repo.ManageServersDialog.btnMSOk.ClickThis();


                    Reports.ReportLog("Successfully Added Server Instance: " + serverName, Reports.SQLdmReportLevel.Success, null, Config.TestCaseName);
                }

                else
                {
                    Reports.ReportLog("Server Instance is Already Present: " + serverName, Reports.SQLdmReportLevel.Info, null, Config.TestCaseName);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Failed : OpenProperties : " + ex.Message);
            }
        }
        void OnGUI()
        {
            if (!EventManager.IsLoaded)
            {
                this.ShowNotification(new GUIContent("No FMOD Studio banks loaded. Please check your settings."));
                return;
            }

            // TODO: don't do this every redraw?
            RebuildDisplayFromCache();

            //if (eventStyle == null)
            {
                eventStyle = new GUIStyle(GUI.skin.button);
                eventStyle.normal.background    = null;
                eventStyle.focused.background   = null;
                eventStyle.active.background    = null;
                eventStyle.onFocused.background = null;
                eventStyle.onNormal.background  = null;
                eventStyle.onHover.background   = null;
                eventStyle.onActive.background  = null;
                eventStyle.stretchWidth         = false;
                eventStyle.padding.left         = 0;
                eventStyle.stretchHeight        = false;
                eventStyle.fixedHeight          = eventStyle.lineHeight + eventStyle.margin.top + eventStyle.margin.bottom;
                eventStyle.alignment            = TextAnchor.MiddleLeft;

                eventIcon        = EditorGUIUtility.Load("FMOD/EventIcon.png") as Texture;
                folderOpenIcon   = EditorGUIUtility.Load("FMOD/FolderIconOpen.png") as Texture;
                folderClosedIcon = EditorGUIUtility.Load("FMOD/FolderIconClosed.png") as Texture;
                searchIcon       = EditorGUIUtility.Load("FMOD/SearchIcon.png") as Texture;
                bankIcon         = EditorGUIUtility.Load("FMOD/BankIcon.png") as Texture;
                snapshotIcon     = EditorGUIUtility.Load("FMOD/SnapshotIcon.png") as Texture;
            }

            // Split the window int search box, tree view, preview pane (only if full browser)
            Rect  searchRect       = new Rect(0, 0, position.width, 16);
            float previewBoxHeight = fromInspector ? 0 : 400;
            Rect  listRect         = new Rect(0, searchRect.height + 2, position.width, position.height - previewBoxHeight - searchRect.height - 15);
            Rect  previewRect      = new Rect(0, position.height - previewBoxHeight, position.width, previewBoxHeight);

            // Scroll the selected item in the tree view - put above the search box otherwise it will take
            // our key presses
            if (selectedItem != null && Event.current.type == EventType.keyDown)
            {
                if (Event.current.keyCode == KeyCode.UpArrow)
                {
                    if (selectedItem.Prev != null)
                    {
                        SetSelectedItem(selectedItem.Prev);

                        // make sure it's visible
                        if (selectedItem.Rect.y < treeScroll.y)
                        {
                            treeScroll.y = selectedItem.Rect.y;
                        }
                    }
                    Event.current.Use();
                }
                if (Event.current.keyCode == KeyCode.DownArrow)
                {
                    if (selectedItem.Next != null)
                    {
                        SetSelectedItem(selectedItem.Next);
                        // make sure it's visible
                        if (selectedItem.Rect.y + selectedItem.Rect.height > treeScroll.y + listRect.height)
                        {
                            treeScroll.y += (selectedItem.Rect.y + selectedItem.Rect.height) - listRect.height;
                        }
                    }
                    Event.current.Use();
                }
            }

            // Show the search box at the top
            GUILayout.BeginArea(searchRect);
            GUILayout.BeginHorizontal();
            GUILayout.Label(new GUIContent(searchIcon), GUILayout.ExpandWidth(false));
            GUI.SetNextControlName("SearchBox");
            searchString = GUILayout.TextField(searchString);
            GUILayout.EndHorizontal();
            GUILayout.EndArea();

            if (fromInspector)
            {
                GUI.FocusControl("SearchBox");

                if (selectedItem != null && Event.current.isKey && Event.current.keyCode == KeyCode.Return)
                {
                    Event.current.Use();

                    if (selectedItem.EventRef != null)
                    {
                        outputProperty.FindPropertyRelative("Path").stringValue = selectedItem.EventRef.Path;
                    }
                    else
                    {
                        outputProperty.FindPropertyRelative("Name").stringValue = selectedItem.BankRef.Name;
                    }
                    outputProperty.serializedObject.ApplyModifiedProperties();
                    Close();
                }
            }

            // Show the tree view

            Predicate <TreeItem> searchFilter = null;

            searchFilter = (x) => (x.Name.ToLower().Contains(searchString.ToLower()) || x.Children.Exists(searchFilter));

            // Check if our selected item still matches the search string
            if (selectedItem != null && !String.IsNullOrEmpty(searchString))
            {
                Predicate <TreeItem> containsSelected = null;
                containsSelected = (x) => (x == selectedItem || x.Children.Exists(containsSelected));
                Predicate <TreeItem> matchForSelected = null;
                matchForSelected = (x) => (x.Name.ToLower().Contains(searchString.ToLower()) && (x == selectedItem || x.Children.Exists(containsSelected))) || x.Children.Exists(matchForSelected);
                if (!treeItems.Exists(matchForSelected))
                {
                    SetSelectedItem(null);
                }
            }

            GUILayout.BeginArea(listRect);
            treeScroll = GUILayout.BeginScrollView(treeScroll, GUILayout.ExpandHeight(true));

            lastDrawnItem = null;
            itemCount     = 0;

            if (showEvents)
            {
                treeItems[0].Expanded = fromInspector ? true : treeItems[0].Expanded;
                ShowEventFolder(treeItems[0], searchFilter);
                ShowEventFolder(treeItems[1], searchFilter);
            }
            if (showBanks)
            {
                treeItems[2].Expanded = fromInspector ? true : treeItems[2].Expanded;
                ShowEventFolder(treeItems[2], searchFilter);
            }

            GUILayout.EndScrollView();
            GUILayout.EndArea();

            // If the standalone event browser show a preview of the selected item
            if (!fromInspector)
            {
                Rect previewAutoRect = new Rect(previewRect);
                previewAutoRect.height -= 140;
                Rect previewCustomBox = new Rect(previewRect);
                previewCustomBox.y      = previewAutoRect.y + previewAutoRect.height + 10;
                previewCustomBox.height = 128;


                GUI.Box(previewRect, GUIContent.none);


                if (selectedItem != null && selectedItem.EventRef != null && selectedItem.EventRef.Path.StartsWith("event:"))
                {
                    GUILayout.BeginArea(previewAutoRect);

                    var style = new GUIStyle(GUI.skin.FindStyle("label"));
                    style.richText = true;

                    var selectedEvent = selectedItem.EventRef;

                    // path
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>Full Path</b>", style, style);
                    EditorGUILayout.LabelField(selectedEvent.Path);
                    EditorGUILayout.EndHorizontal();

                    // guid
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>GUID</b>", style, style);
                    EditorGUILayout.LabelField(selectedEvent.Guid.ToString("b"));
                    EditorGUILayout.EndHorizontal();

                    // Bank
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>Bank</b>", style, style);
                    StringBuilder builder = new StringBuilder();
                    selectedEvent.Banks.ForEach((x) => { builder.Append(Path.GetFileNameWithoutExtension(x.Path)); builder.Append(", "); });
                    EditorGUILayout.LabelField(builder.ToString(0, Math.Max(0, builder.Length - 2)));
                    EditorGUILayout.EndHorizontal();

                    // Panning
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>Panning</b>", style, style);
                    EditorGUILayout.LabelField(selectedEvent.Is3D ? "3D" : "2D");
                    EditorGUILayout.EndHorizontal();

                    // One shot
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>Oneshot</b>", style, style);
                    EditorGUILayout.LabelField(selectedEvent.IsOneShot.ToString());
                    EditorGUILayout.EndHorizontal();

                    // Streaming
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>Streaming</b>", style, style);
                    EditorGUILayout.LabelField(selectedEvent.IsStream.ToString());
                    EditorGUILayout.EndHorizontal();

                    EditorGUILayout.BeginHorizontal();
                    if (GUILayout.Button("Play"))
                    {
                        EditorUtils.PreviewEvent(selectedEvent);
                        forceRepaint = true;
                    }
                    if (GUILayout.Button("Pause"))
                    {
                        EditorUtils.PreviewPause();
                    }
                    if (GUILayout.Button("Stop"))
                    {
                        forceRepaint = false;
                        EditorUtils.PreviewStop();
                    }
                    if (GUILayout.Button("Show In Studio"))
                    {
                        string cmd = string.Format("studio.window.navigateTo(studio.project.lookup(\"{0}\"))", selectedEvent.Guid.ToString("b"));
                        EditorUtils.SendScriptCommand(cmd);
                    }
                    EditorGUILayout.EndHorizontal();

                    paramScroll = GUILayout.BeginScrollView(paramScroll, false, true);
                    foreach (var paramRef in selectedEvent.Parameters)
                    {
                        if (!previewParamValues.ContainsKey(paramRef.Name))
                        {
                            previewParamValues[paramRef.Name] = 0;
                        }
                        previewParamValues[paramRef.Name] = EditorGUILayout.Slider(paramRef.Name, previewParamValues[paramRef.Name], paramRef.Min, paramRef.Max);
                        EditorUtils.PreviewUpdateParameter(paramRef.Name, previewParamValues[paramRef.Name]);
                    }
                    GUILayout.EndScrollView();

                    GUILayout.EndArea();

                    GUILayout.BeginArea(previewCustomBox);



                    if (selectedEvent.Is3D)
                    {
                        Texture circle  = EditorGUIUtility.Load("FMOD/preview.png") as Texture;
                        Texture circle2 = EditorGUIUtility.Load("FMOD/previewemitter.png") as Texture;
                        Rect    rect    = new Rect(position.width / 2.0f - 150f, 0, 128, 128);
                        GUI.DrawTexture(rect, circle);

                        Vector2 centre = rect.center;

                        Rect rect2 = new Rect(rect.center + eventPosition - new Vector2(4, 4), new Vector2(8, 8));
                        GUI.DrawTexture(rect2, circle2);


                        if ((Event.current.type == EventType.mouseDown || Event.current.type == EventType.mouseDrag) && rect.Contains(Event.current.mousePosition))
                        {
                            var     newPosition = Event.current.mousePosition;
                            Vector2 delta       = (newPosition - centre);
                            float   distance    = delta.magnitude;
                            if (distance < 60)
                            {
                                newPosition.x  -= 4;
                                newPosition.y  -= 4;
                                eventPosition   = newPosition - rect.center;
                                previewDistance = distance / 60.0f * selectedEvent.MaxDistance;
                                delta.Normalize();
                                float angle = Mathf.Atan2(delta.y, delta.x);
                                previewOrientation = angle + Mathf.PI * 0.5f;
                            }
                            Event.current.Use();
                        }

                        EditorUtils.PreviewUpdatePosition(previewDistance, previewOrientation);
                    }


                    float   offset   = position.width / 2.0f;
                    Texture meterOn  = EditorGUIUtility.Load("FMOD/LevelMeter.png") as Texture;
                    Texture meterOff = EditorGUIUtility.Load("FMOD/LevelMeterOff.png") as Texture;
                    float[] metering = EditorUtils.GetMetering();
                    foreach (float rms in metering)
                    {
                        GUI.DrawTexture(new Rect(offset, 0, meterOff.width, 128), meterOff);

                        float db           = rms;
                        float visible      = 128 * db;
                        Rect  levelPosRect = new Rect(offset, 128 - visible, meterOn.width, visible);
                        Rect  levelUVRect  = new Rect(0, 0, 1.0f, db);
                        GUI.DrawTextureWithTexCoords(levelPosRect, meterOn, levelUVRect);
                        offset += meterOn.width + 5.0f;
                    }
                    GUILayout.EndArea();
                }


                if (selectedItem != null && selectedItem.EventRef != null && selectedItem.EventRef.Path.StartsWith("snapshot:"))
                {
                    GUILayout.BeginArea(previewAutoRect);

                    var style = new GUIStyle(GUI.skin.FindStyle("label"));
                    style.richText = true;

                    var selectedEvent = selectedItem.EventRef;

                    // path
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>Full Path</b>", style, style);
                    EditorGUILayout.LabelField(selectedEvent.Path);
                    EditorGUILayout.EndHorizontal();

                    // guid
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>GUID</b>", style, style);
                    EditorGUILayout.LabelField(selectedEvent.Guid.ToString("b"));
                    EditorGUILayout.EndHorizontal();

                    GUILayout.EndArea();
                }

                if (selectedItem != null && selectedItem.BankRef != null)
                {
                    GUILayout.BeginArea(previewRect);
                    string[] SizeSuffix   = { "B", "KB", "MB", "GB" };
                    var      selectedBank = selectedItem.BankRef;
                    var      style        = new GUIStyle(GUI.skin.FindStyle("label"));
                    style.richText = true;
                    GUILayout.Label("<b>Platform Bank Sizes</b>", style);
                    EditorGUI.indentLevel++;
                    foreach (var sizeInfo in selectedBank.FileSizes)
                    {
                        int  order = 0;
                        long len   = sizeInfo.Value;
                        while (len >= 1024 && order + 1 < SizeSuffix.Length)
                        {
                            order++;
                            len /= 1024;
                        }
                        EditorGUILayout.LabelField(sizeInfo.Name, String.Format("{0} {1}", len, SizeSuffix[order]));
                    }
                    EditorGUI.indentLevel--;

                    GUILayout.EndArea();
                }
            }
        }
        public static void ShowAsPopup(Rect buttonPosition, GUIContent[] labels, int selectedIndex, SelectedIndexEventHandler onSelection, string search = "", SearchChangedEventHandler onSearchChanged = null)
        {
            List <TreeItem> roots                 = new List <TreeItem>();
            TreeItem        selectedItem          = null;
            Dictionary <string, TreeItem> itemMap = new Dictionary <string, TreeItem>();
            List <TreeItem> items                 = new List <TreeItem>();

            //Create all the actual leaf items
            for (int i = 0; i < labels.Length; i++)
            {
                GUIContent label = labels[i];
                string     text  = label.text;

                if (!string.IsNullOrEmpty(text))
                {
                    string[] bits = text.Split(new char[] { '/' });

                    GUIContent leafContent = new GUIContent(bits[bits.Length - 1], label.image, label.tooltip);

                    // We store the index into the labels array in userData
                    TreeItem item = new TreeItem(leafContent, text, (int)i, userSelectedItem => {
                        if (onSelection != null)
                        {
                            onSelection((int)userSelectedItem.UserData);
                        }
                    });

                    if (!itemMap.ContainsKey(text))
                    {
                        items.Add(item);
                        if (!itemMap.ContainsKey(text))
                        {
                            itemMap.Add(text, item);
                        }
                        if (i == selectedIndex)
                        {
                            selectedItem = item;
                        }
                    }
                    else
                    {
                        Debug.LogErrorFormat("Duplicate Key \"{0}\" in label \"{1}\"", text, label);
                    }
                }
            }

            // Create any intermediate parent items
            foreach (TreeItem item in items)
            {
                int index = (int)item.UserData;

                string originalText = labels[index].text;
                if (!string.IsNullOrEmpty(originalText))
                {
                    string[] bits   = originalText.Split(new char[] { '/' });
                    TreeItem prev   = null;
                    TreeItem parent = null;
                    for (int i = 1; i < bits.Length; i++)
                    {
                        prev = parent;
                        string key = string.Join("/", bits.Take(i).ToArray());
                        if (!itemMap.TryGetValue(key, out parent))
                        {
                            parent = new TreeItem(new GUIContent(bits[i - 1]), null);
                            if (prev != null)
                            {
                                prev.AddChild(parent);
                            }
                            else
                            {
                                roots.Add(parent);
                            }
                            itemMap.Add(key, parent);
                        }
                    }
                    // Add the actual item to the parent (if we even found a parent)
                    if (parent != null)
                    {
                        parent.AddChild(item);
                    }
                    else
                    {
                        roots.Add(item);
                    }
                }
            }

            ShowAsPopup(buttonPosition, roots.ToArray(), selectedItem, search, onSearchChanged);
        }
Example #46
0
 public FileItem(TreeItem parent, string name) : base(parent, name)
 {
 }
Example #47
0
 public void AddChild(TreeItem item)
 {
     Children.Add(item);
     item.SetParent(this);
 }
        public static IEnumerable <string> GetLeafFolders(this TreeItem root)
        {
            var leafFullPaths = root.Leaves.Select(node => node.FullPath);

            return(leafFullPaths);
        }
Example #49
0
        public static void TreeTest()
        {
            int numTasks = 100000;
            int reportEvery = 1000;

            ShieldedTree<Guid, TreeItem> tree = new ShieldedTree<Guid, TreeItem>();
            int transactionCount = 0;
            Shielded<int> lastReport = new Shielded<int>(0);
            Shielded<int> countComplete = new Shielded<int>(0);
            //            Shielded<DateTime> lastTime = new Shielded<DateTime>(DateTime.UtcNow);
            //
            //            Shield.Conditional(() => countComplete >= lastReport + reportEvery, () =>
            //            {
            //                DateTime newNow = DateTime.UtcNow;
            //                int speed = (countComplete - lastReport) * 1000 / (int)newNow.Subtract(lastTime).TotalMilliseconds;
            //                lastTime.Assign(newNow);
            //                lastReport.Modify((ref int n) => n += reportEvery);
            //                int count = countComplete;
            //                Shield.SideEffect(() =>
            //                {
            //                    Console.Write("\n{0} at {1} item/s", count, speed);
            //                }
            //                );
            //                return true;
            //            }
            //            );

            if (true)
            {
                var treeTime = mtTest("tree", numTasks, i =>
                {
                    return Task.Factory.StartNew(() =>
                    {
                        var item1 = new TreeItem();
                        Shield.InTransaction(() =>
                        {
                            //Interlocked.Increment(ref transactionCount);
                            tree.Add(item1.Id, item1);
            //                            countComplete.Commute((ref int c) => c++);
                        }
                        );
                    }
                    );
                }
                );
                Guid? previous = null;
                bool correct = true;
                Shield.InTransaction(() =>
                {
                    int count = 0;
                    foreach (var item in tree)
                    {
                        count++;
                        if (previous != null && previous.Value.CompareTo(item.Key) > 0)
                        {
                            correct = false;
                            break;
                        }
                        previous = item.Key;
                    }
                    correct = correct && (count == numTasks);
                }
                );
                Console.WriteLine("\n -- {0} ms with {1} iterations and is {2}.",
                    treeTime, transactionCount, correct ? "correct" : "incorrect");
            }

            if (true)
            {
                ShieldedDict<Guid, TreeItem> dict = new ShieldedDict<Guid, TreeItem>();
                transactionCount = 0;
                Shield.InTransaction(() =>
                {
                    countComplete.Assign(0);
                    lastReport.Assign(0);
                }
                );

                var time = mtTest("dictionary", numTasks, i =>
                {
                    return Task.Factory.StartNew(() =>
                    {
                        var item1 = new TreeItem();
                        Shield.InTransaction(() =>
                        {
                            //Interlocked.Increment(ref transactionCount);
                            dict[item1.Id] = item1;
            //                            countComplete.Commute((ref int c) => c++);
                        }
                        );
                    }
                    );
                }
                );
                Console.WriteLine("\n -- {0} ms with {1} iterations. Not sorted.",
                time, transactionCount);
            }

            if (true)
            {
                ConcurrentDictionary<Guid, TreeItem> dict = new ConcurrentDictionary<Guid, TreeItem>();

                var time = mtTest("ConcurrentDictionary", numTasks, i =>
                {
                    return Task.Factory.StartNew(() =>
                    {
                        var item1 = new TreeItem();
                        dict[item1.Id] = item1;
                    }
                    );
                }
                );
                Console.WriteLine("\n -- {0} ms with {1} iterations. Not sorted.",
                time, numTasks);
            }
        }
Example #50
0
        public CoverageView(string fileName, ProgressBar status)
        {
            TreeStore store = new TreeStore(typeof(string), typeof(string), typeof(string), typeof(string), typeof(object));

            tree = new TreeView(store);

            CellRendererText renderer = new CellRendererText();

            // LAME: Why is this property a float instead of a double ?
            renderer.Xalign = 0.5f;

            tree.AppendColumn("Classes", new CellRendererText(), "text", 0);
            tree.AppendColumn("Lines Hit", renderer, "text", 1);
            tree.AppendColumn("Lines Missed", renderer, "text", 2);
            tree.AppendColumn("Coverage", renderer, "text", 3);

            tree.GetColumn(0).Resizable = true;
            tree.GetColumn(1).Alignment = 0.0f;
            tree.GetColumn(1).Resizable = true;
            tree.GetColumn(2).Alignment = 0.0f;
            tree.GetColumn(2).Resizable = true;
            tree.GetColumn(3).Alignment = 0.0f;
            tree.GetColumn(3).Resizable = true;

            tree.HeadersVisible = true;

            model = new CoverageModel();
            foreach (string filter in DEFAULT_FILTERS)
            {
                model.AddFilter(filter);
            }
            this.status     = status;
            model.Progress += Progress;
            model.ReadFromFile(fileName);

            TreeItem root = new TreeItem(store, null, model, "PROJECT");

            Hashtable classes2 = model.Classes;

            namespaces = new Hashtable();
            string[] sorted_names = new string [classes2.Count];
            classes2.Keys.CopyTo(sorted_names, 0);
            Array.Sort(sorted_names);
            Progress("Building tree", 0.95);
            foreach (string name in sorted_names)
            {
                ClassCoverageItem klass = (ClassCoverageItem)classes2 [name];

                if (klass.filtered)
                {
                    continue;
                }

                string   namespace2 = klass.name_space;
                TreeItem nsItem     = (TreeItem)namespaces [namespace2];
                if (nsItem == null)
                {
                    nsItem = new TreeItem(store, root, (CoverageItem)model.Namespaces [namespace2], namespace2);
                    //				nsItem.SetPixmap (0, namespaceOpenPixmap);
                    namespaces [namespace2] = nsItem;
                }

                if (nsItem.model.filtered)
                {
                    continue;
                }

                ClassItem classItem = new ClassItem(store, nsItem, klass, klass.name);

                // We should create the method nodes only when the class item
                // is opened

                foreach (MethodCoverageItem method in klass.Methods)
                {
                    if (method.filtered)
                    {
                        continue;
                    }

                    string title = method.Name;
                    if (title.Length > 64)
                    {
                        title = title.Substring(0, 63) + "...)";
                    }

                    new MethodItem(store, classItem, classItem, method, title);
                }
            }

            tree.ExpandRow(store.GetPath(root.Iter), false);

            // it becomes very hard to navigate if everything is expanded
            //foreach (string ns in namespaces.Keys)
            //	tree.ExpandRow (store.GetPath (((TreeItem)namespaces [ns]).Iter), false);

            tree.ButtonPressEvent += new ButtonPressEventHandler(OnButtonPress);
            tree.Selection.Mode    = SelectionMode.Single;

            source_views = new Hashtable();
            window_maps  = new Hashtable();
            Progress("Done", 1.0);
            // LAME: Why doesn't widgets visible by default ???
            tree.Show();
        }
Example #51
0
        void OnGUI()
        {
            if (!EventManager.IsLoaded)
            {
                this.ShowNotification(new GUIContent("No FMOD Studio banks loaded. Please check your settings."));
                return;
            }

            if (Event.current.type == EventType.Layout)
            {
                RebuildDisplayFromCache();
            }

            //if (eventStyle == null)
            {
                eventStyle = new GUIStyle(GUI.skin.button);
                eventStyle.normal.background = null;
                eventStyle.focused.background = null;
                eventStyle.active.background = null;
                eventStyle.onFocused.background = null;
                eventStyle.onNormal.background = null;
                eventStyle.onHover.background = null;
                eventStyle.onActive.background = null;
                eventStyle.stretchWidth = false;
                eventStyle.padding.left = 0;
                eventStyle.stretchHeight = false;
                eventStyle.fixedHeight = eventStyle.lineHeight + eventStyle.margin.top + eventStyle.margin.bottom;
                eventStyle.alignment = TextAnchor.MiddleLeft;

                eventIcon = EditorGUIUtility.Load("FMOD/EventIcon.png") as Texture;
                folderOpenIcon = EditorGUIUtility.Load("FMOD/FolderIconOpen.png") as Texture;
                folderClosedIcon = EditorGUIUtility.Load("FMOD/FolderIconClosed.png") as Texture;
                searchIcon = EditorGUIUtility.Load("FMOD/SearchIcon.png") as Texture;
                bankIcon = EditorGUIUtility.Load("FMOD/BankIcon.png") as Texture;
                snapshotIcon = EditorGUIUtility.Load("FMOD/SnapshotIcon.png") as Texture;
            }

            // Split the window int search box, tree view, preview pane (only if full browser)
            Rect searchRect = new Rect(0, 0, position.width, 16);
            float previewBoxHeight = fromInspector ? 0 : 400;
            Rect listRect = new Rect(0, searchRect.height + 2, position.width, position.height - previewBoxHeight - searchRect.height - 15);
            Rect previewRect = new Rect(0, position.height - previewBoxHeight, position.width, previewBoxHeight);

            // Scroll the selected item in the tree view - put above the search box otherwise it will take
            // our key presses
            if (selectedItem != null && Event.current.type == EventType.keyDown)
            {
                if (Event.current.keyCode == KeyCode.UpArrow)
                {
                    if (selectedItem.Prev != null)
                    {
                        SetSelectedItem(selectedItem.Prev);

                        // make sure it's visible
                        if (selectedItem.Rect.y < treeScroll.y)
                        {
                            treeScroll.y = selectedItem.Rect.y;
                        }
                    }
                    Event.current.Use();
                }
                if (Event.current.keyCode == KeyCode.DownArrow)
                {
                    if (selectedItem.Next != null)
                    {
                        SetSelectedItem(selectedItem.Next);
                        // make sure it's visible
                        if (selectedItem.Rect.y + selectedItem.Rect.height > treeScroll.y + listRect.height)
                        {
                            treeScroll.y += (selectedItem.Rect.y + selectedItem.Rect.height) - listRect.height;
                        }
                    }
                    Event.current.Use();
                }
            }

            // Show the search box at the top
            GUILayout.BeginArea(searchRect);
            GUILayout.BeginHorizontal();
            GUILayout.Label(new GUIContent(searchIcon), GUILayout.ExpandWidth(false));
            GUI.SetNextControlName("SearchBox");
            searchString = GUILayout.TextField(searchString);
            GUILayout.EndHorizontal();
            GUILayout.EndArea();

            if (fromInspector)
            {
                GUI.FocusControl("SearchBox");

                if (selectedItem != null && Event.current.isKey && Event.current.keyCode == KeyCode.Return)
                {
                    Event.current.Use();

                    if (selectedItem.EventRef != null)
                    {
                        outputProperty.stringValue = selectedItem.EventRef.Path;
                        EditorUtils.UpdateParamsOnEmmitter(outputProperty.serializedObject);
                    }
                    else
                    {
                        outputProperty.stringValue = selectedItem.BankRef.Name;
                    }
                    outputProperty.serializedObject.ApplyModifiedProperties();
                    Close();
                }
            }

            // Show the tree view

            Predicate<TreeItem> searchFilter = null;
            searchFilter = (x) => (x.Name.ToLower().Contains(searchString.ToLower()) || x.Children.Exists(searchFilter));

            // Check if our selected item still matches the search string
            if (selectedItem != null && !String.IsNullOrEmpty(searchString))
            {
                Predicate<TreeItem> containsSelected = null;
                containsSelected = (x) => (x == selectedItem || x.Children.Exists(containsSelected));
                Predicate<TreeItem> matchForSelected = null;
                matchForSelected = (x) => (x.Name.ToLower().Contains(searchString.ToLower()) && (x == selectedItem || x.Children.Exists(containsSelected))) || x.Children.Exists(matchForSelected);
                if (!treeItems.Exists(matchForSelected))
                {
                    SetSelectedItem(null);
                }
            }

            GUILayout.BeginArea(listRect);
            treeScroll = GUILayout.BeginScrollView(treeScroll, GUILayout.ExpandHeight(true));

            lastDrawnItem = null;
            itemCount = 0;

            if (showEvents)
            {
                treeItems[0].Expanded = fromInspector ? true : treeItems[0].Expanded;
                ShowEventFolder(treeItems[0], searchFilter);
                ShowEventFolder(treeItems[1], searchFilter);
            }
            if (showBanks)
            {
                treeItems[2].Expanded = fromInspector ? true : treeItems[2].Expanded;
                ShowEventFolder(treeItems[2], searchFilter);
            }

            GUILayout.EndScrollView();
            GUILayout.EndArea();

            // If the standalone event browser show a preview of the selected item
            if (!fromInspector)
            {
                Rect previewAutoRect = new Rect(previewRect);
                previewAutoRect.height -= 140;
                Rect previewCustomBox = new Rect(previewRect);
                previewCustomBox.y = previewAutoRect.y + previewAutoRect.height + 10;
                previewCustomBox.height = 128;

                GUI.Box(previewRect, GUIContent.none);

                if (selectedItem != null && selectedItem.EventRef != null && selectedItem.EventRef.Path.StartsWith("event:"))
                {
                    GUILayout.BeginArea(previewAutoRect);

                    var style = new GUIStyle(GUI.skin.FindStyle("label"));
                    style.richText = true;

                    var selectedEvent = selectedItem.EventRef;

                    // path
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>Full Path</b>", style, style);
                    EditorGUILayout.LabelField(selectedEvent.Path);
                    EditorGUILayout.EndHorizontal();

                    // guid
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>GUID</b>", style, style);
                    EditorGUILayout.LabelField(selectedEvent.Guid.ToString("b"));
                    EditorGUILayout.EndHorizontal();

                    // Bank
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>Bank</b>", style, style);
                    StringBuilder builder = new StringBuilder();
                    selectedEvent.Banks.ForEach((x) => { builder.Append(Path.GetFileNameWithoutExtension(x.Path)); builder.Append(", "); });
                    EditorGUILayout.LabelField(builder.ToString(0, Math.Max(0, builder.Length - 2)));
                    EditorGUILayout.EndHorizontal();

                    // Panning
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>Panning</b>", style, style);
                    EditorGUILayout.LabelField(selectedEvent.Is3D ? "3D" : "2D");
                    EditorGUILayout.EndHorizontal();

                    // One shot
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>Oneshot</b>", style, style);
                    EditorGUILayout.LabelField(selectedEvent.IsOneShot.ToString());
                    EditorGUILayout.EndHorizontal();

                    // Streaming
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>Streaming</b>", style, style);
                    EditorGUILayout.LabelField(selectedEvent.IsStream.ToString());
                    EditorGUILayout.EndHorizontal();

                    EditorGUILayout.BeginHorizontal();
                    if (GUILayout.Button("Play"))
                    {
                        EditorUtils.PreviewEvent(selectedEvent);
                        forceRepaint = true;
                    }
                    if (GUILayout.Button("Pause"))
                    {
                        EditorUtils.PreviewPause();
                    }
                    if (GUILayout.Button("Stop"))
                    {
                        forceRepaint = false;
                        EditorUtils.PreviewStop();
                    }
                    if (GUILayout.Button("Show In Studio"))
                    {
                        string cmd = string.Format("studio.window.navigateTo(studio.project.lookup(\"{0}\"))", selectedEvent.Guid.ToString("b"));
                        EditorUtils.SendScriptCommand(cmd);
                    }
                    EditorGUILayout.EndHorizontal();

                    paramScroll = GUILayout.BeginScrollView(paramScroll, false, true);
                    foreach (var paramRef in selectedEvent.Parameters)
                    {
                        if (!previewParamValues.ContainsKey(paramRef.Name))
                        {
                            previewParamValues[paramRef.Name] = 0;
                        }
                        previewParamValues[paramRef.Name] = EditorGUILayout.Slider(paramRef.Name, previewParamValues[paramRef.Name], paramRef.Min, paramRef.Max);
                        EditorUtils.PreviewUpdateParameter(paramRef.Name, previewParamValues[paramRef.Name]);
                    }
                    GUILayout.EndScrollView();

                    GUILayout.EndArea();

                    GUILayout.BeginArea(previewCustomBox);

                    if (selectedEvent.Is3D)
                    {

                        Texture circle = EditorGUIUtility.Load("FMOD/preview.png") as Texture;
                        Texture circle2 = EditorGUIUtility.Load("FMOD/previewemitter.png") as Texture;
                        Rect rect = new Rect(position.width / 2.0f - 150f, 0, 128, 128);
                        GUI.DrawTexture(rect, circle);

                        Vector2 centre = rect.center;

                        Rect rect2 = new Rect(rect.center + eventPosition - new Vector2(6, 6), new Vector2(12, 12));
                        GUI.DrawTexture(rect2, circle2);

                        if ((Event.current.type == EventType.mouseDown || Event.current.type == EventType.mouseDrag) && rect.Contains(Event.current.mousePosition))
                        {
                            var newPosition = Event.current.mousePosition;
                            Vector2 delta = (newPosition - centre);
                            float distance = delta.magnitude;
                            if (distance < 60)
                            {
                                eventPosition = newPosition - rect.center;
                                previewDistance = distance / 60.0f * selectedEvent.MaxDistance;
                                delta.Normalize();
                                float angle = Mathf.Atan2(delta.y, delta.x);
                                previewOrientation = angle + Mathf.PI * 0.5f;
                            }
                            Event.current.Use();
                        }

                        EditorUtils.PreviewUpdatePosition(previewDistance, previewOrientation);
                    }

                    float offset = position.width / 2.0f;
                    Texture meterOn = EditorGUIUtility.Load("FMOD/LevelMeter.png") as Texture;
                    Texture meterOff = EditorGUIUtility.Load("FMOD/LevelMeterOff.png") as Texture;
                    float[] metering = EditorUtils.GetMetering();
                    int meterHeight = 128;
                    int meterWidth = (int)((128 / (float)meterOff.height) * meterOff.width);
                    foreach (float rms in metering)
                    {
                        GUI.DrawTexture(new Rect(offset, 0, meterWidth, meterHeight), meterOff);

                        float db = rms > 0 ? 20.0f * Mathf.Log10(rms * Mathf.Sqrt(2.0f)) : -80.0f;
                        if (db > 10.0f) db = 10.0f;
                        float visible = 0;
                        int[] segmentPixels = new int[]{ 0, 18, 38, 60, 89, 130, 187, 244, 300 };
                        float[] segmentDB = new float[]{ -80.0f, -60.0f, -50.0f, -40.0f, -30.0f, -20.0f, -10.0f, 0, 10.0f };
                        int segment = 1;
                        while (segmentDB[segment] < db)
                        {
                            segment++;
                        }
                        visible = segmentPixels[segment - 1] + ((db - segmentDB[segment - 1])  / (segmentDB[segment] - segmentDB[segment - 1])) * (segmentPixels[segment] - segmentPixels[segment - 1]);
                        visible *= 128 / (float)meterOff.height;
                        Rect levelPosRect = new Rect(offset, 128 - visible, meterWidth, visible);
                        Rect levelUVRect = new Rect(0, 0, 1.0f, visible / meterHeight);
                        GUI.DrawTextureWithTexCoords(levelPosRect, meterOn, levelUVRect);
                        offset += meterWidth + 5.0f;
                    }
                    GUILayout.EndArea();
                }

                if (selectedItem != null && selectedItem.EventRef != null && selectedItem.EventRef.Path.StartsWith("snapshot:"))
                {
                    GUILayout.BeginArea(previewAutoRect);

                    var style = new GUIStyle(GUI.skin.FindStyle("label"));
                    style.richText = true;

                    var selectedEvent = selectedItem.EventRef;

                    // path
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>Full Path</b>", style, style);
                    EditorGUILayout.LabelField(selectedEvent.Path);
                    EditorGUILayout.EndHorizontal();

                    // guid
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.PrefixLabel("<b>GUID</b>", style, style);
                    EditorGUILayout.LabelField(selectedEvent.Guid.ToString("b"));
                    EditorGUILayout.EndHorizontal();

                    GUILayout.EndArea();
                }

                if (selectedItem != null && selectedItem.BankRef != null)
                {
                    GUILayout.BeginArea(previewRect);
                    string[] SizeSuffix = { "B", "KB", "MB", "GB" };
                    var selectedBank = selectedItem.BankRef;
                    var style = new GUIStyle(GUI.skin.FindStyle("label"));
                    style.richText = true;
                    GUILayout.Label("<b>Platform Bank Sizes</b>", style);
                    EditorGUI.indentLevel++;
                    foreach (var sizeInfo in selectedBank.FileSizes)
                    {
                        int order = 0;
                        long len = sizeInfo.Value;
                        while (len >= 1024 && order + 1 < SizeSuffix.Length)
                        {
                            order++;
                            len /= 1024;
                        }
                        EditorGUILayout.LabelField(sizeInfo.Name, String.Format("{0} {1}", len, SizeSuffix[order]));
                    }
                    EditorGUI.indentLevel--;

                    GUILayout.EndArea();
                }
            }
        }
Example #52
0
 public MethodItem(TreeStore store, TreeItem parent, ClassItem parent_class, CoverageItem model, string title)
     : base(store, parent, model, title)
 {
     ParentClass = parent_class;
 }
Example #53
0
        void SetSelectedItem(TreeItem item)
        {
            //if (item != selectedItem)
            {
                selectedItem = item;

                if (item != null)
                {
                    SetPreviewEvent(item.EventRef);
                }
                else
                {
                    SetPreviewEvent(null);
                }
            }
        }
Example #54
0
 public ClassItem(TreeStore store, TreeItem parent, CoverageItem model, string title)
     : base(store, parent, model, title)
 {
 }
Example #55
0
		void PopulateTree(string filter = null)
		{
			var testSuites = GetTestSuites().Select(suite => ToTree(suite.Assembly, suite, filter)).Where(r => r != null).ToList();
			var treeData = new TreeItem(testSuites);
			Application.Instance.AsyncInvoke(() => tree.DataStore = treeData);
		}
Example #56
0
 public void BeginUpdate()
 {
     Control.DataStore = null;
     fRootNode         = new TreeItem();
 }
        } // End Function GetSQL

        public void ProcessRequest(HttpContext context)
        {
            string strJSON = null;

            try
            {
                string strId   = context.Request.Params["id"];
                string strData = context.Request.Params["data"];
                string strPath = context.Request.Params["path"];
                string path_id = context.Request.Params["path_id"];

                type_t EntityType = (type_t)Enum.Parse(typeof(type_t), strData, true);

                System.Diagnostics.Debug.WriteLine(strId);
                System.Diagnostics.Debug.WriteLine(strData);
                System.Diagnostics.Debug.WriteLine(strPath);
                System.Diagnostics.Debug.WriteLine(path_id);
                System.Diagnostics.Debug.WriteLine(EntityType);


                string strSQL = GetSQL(strId, EntityType);

                long lng;
                long.TryParse(strId, out lng);

                strSQL = strSQL.Replace("@abc", lng.ToString());

                System.Data.DataTable dt = SQL.GetDataTable(strSQL);


                List <TreeItem> ls = new List <TreeItem>();

                foreach (System.Data.DataRow dr in dt.Rows)
                {
                    TreeItem root = new TreeItem();
                    //root.id = strPath + "/" + System.Convert.ToString(dr["Path_Id"]);

                    // Trouble - symlink unfortunately has same id
                    // but this id is only used by jsTree anyway
                    root.id      = System.Guid.NewGuid().ToString();
                    root.real_id = System.Convert.ToString(dr["real_path_id"]);
                    root.path_id = System.Convert.ToString(dr["Path_Id"]);


                    root.text     = System.Convert.ToString(dr["name"]);
                    root.children = System.Convert.ToBoolean(dr["HasChildren"]);
                    root.state    = NodeState.closed;
                    root.data     = System.Convert.ToString(dr["objtype"]);

                    // root.type = 123;
                    // root.type = type_t.SO;
                    // root.type = (type_t)Enum.Parse(typeof(type_t), System.Convert.ToString(dr["objtype"]));
                    root.type = System.Convert.ToString(dr["objtype"]);

                    // root.a_attr.target = "_blank";
                    // root.a_attr.href = "http://127.0.0.1";

                    ls.Add(root);
                } // Next dr

                strJSON = Tools.Serialization.JSON.Serialize(ls);
                // List<TreeItem > obj = Tools.Serialization.JSON.Deserialize<List<TreeItem >>(strJSON);
                // Console.WriteLine(obj);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                Tools.AJAX.cAjaxResult AjaxResult = new Tools.AJAX.cAjaxResult();
                AjaxResult.error = new Tools.AJAX.AJAXException(ex);
                strJSON          = Tools.Serialization.JSON.Serialize(AjaxResult);
            }

            System.Diagnostics.Debug.WriteLine(strJSON);
            context.Response.ContentType = "application/json";
            context.Response.Write(strJSON);
        } // End Sub ProcessRequest
Example #58
0
        /// <summary>
        ///     Reads the entire event list and creates a list with the events
        /// </summary>
        /// <returns>
        ///     <br>IList: if event list was created successfully</br>
        ///     <br>Null: if an error occurred</br>
        /// </returns>
        public IList <IEvent> ReadEvents()
        {
            try
            {
                IList <IEvent>   listEvent          = new List <IEvent>();
                IList <TreeItem> treeItemsEventList = new ResultElements().Entries();
                if (treeItemsEventList != null && treeItemsEventList.Count != 0)
                {
                    Button cachedLineDownButton;

                    /*check if scrollDown button is available
                     * exception thrown if it isn't, reading list without scrolling down
                     */
                    try
                    {
                        cachedLineDownButton = new ResultElements().ButtonLineDown;
                    }
                    catch (Exception)
                    {
                        Log.Info(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "Scroll down button not found, no problem if event list is not scrollable (only a few entries)");
                        cachedLineDownButton = null;
                    }

                    // make sure first event is visible
                    this.ScrollToTop();

                    int index;
                    for (index = 0; index < treeItemsEventList.Count; index++)
                    {
                        TreeItem        treeItemEvent = treeItemsEventList[index];
                        IList <Unknown> listCells     = treeItemEvent.Children;

                        /*Checks if first cell of actual tree item has no text
                         * This is the case if the description of an event needs more than one row
                         */
                        if (listCells[Id].As <Cell>().Text.Equals(string.Empty))
                        {
                            // check if list is empty if it is, cell of first row (event) is empty -> failure
                            if (listEvent.Count == 0)
                            {
                                Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "List empty ?,First cell of first row is empty");
                            }
                            else
                            {
                                // cell "row" is empty, list is not empty ->add description to previous event:
                                int lastEventIndex = listEvent.Count - 1;
                                this.CreateEventDescription(listCells, listEvent[lastEventIndex]);
                            }
                        }
                        else
                        {
                            // normal event, add to list :
                            listEvent.Add(this.CreateEvent(listCells));
                        }

                        // if null,  no scroll needed
                        if (cachedLineDownButton != null)
                        {
                            this.ScrollDown(cachedLineDownButton);
                        }
                    }

                    return(listEvent);
                }

                Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), "List is empty!");
                return(null);
            }
            catch (Exception exception)
            {
                Log.Error(LogInfo.Namespace(MethodBase.GetCurrentMethod()), exception.Message);
                return(null);
            }
        }
Example #59
0
        public static void TreeTest()
        {
            int numTasks = 100000;

            var tree = new ShieldedTreeNc<Guid, TreeItem>();
            int transactionCount = 0;
            Shielded<int> lastReport = new Shielded<int>(0);
            Shielded<int> countComplete = new Shielded<int>(0);

            if (true)
            {
                var treeTime = mtTest("tree", numTasks, i =>
                {
                    return Task.Factory.StartNew(() =>
                    {
                        var item1 = new TreeItem();
                        Shield.InTransaction(() =>
                        {
                            //Interlocked.Increment(ref transactionCount);
                            tree.Add(item1.Id, item1);
            //                            countComplete.Commute((ref int c) => c++);
                        }
                        );
                    }
                    );
                }
                );
                Guid? previous = null;
                bool correct = true;
                Shield.InTransaction(() =>
                {
                    int count = 0;
                    foreach (var item in tree)
                    {
                        count++;
                        if (previous != null && previous.Value.CompareTo(item.Key) > 0)
                        {
                            correct = false;
                            break;
                        }
                        previous = item.Key;
                    }
                    correct = correct && (count == numTasks);
                }
                );
                Console.WriteLine("\n -- {0} ms with {1} iterations and is {2}.",
                    treeTime, transactionCount, correct ? "correct" : "incorrect");
            }

            if (true)
            {
                var dict = new ShieldedDictNc<Guid, TreeItem>();
                transactionCount = 0;
                Shield.InTransaction(() =>
                {
                    countComplete.Value = 0;
                    lastReport.Value = 0;
                }
                );

                var time = mtTest("dictionary", numTasks, i =>
                {
                    return Task.Factory.StartNew(() =>
                    {
                        var item1 = new TreeItem();
                        Shield.InTransaction(() =>
                        {
                            //Interlocked.Increment(ref transactionCount);
                            dict[item1.Id] = item1;
            //                            countComplete.Commute((ref int c) => c++);
                        }
                        );
                    }
                    );
                }
                );
                Console.WriteLine("\n -- {0} ms with {1} iterations. Not sorted.",
                time, transactionCount);
            }

            if (true)
            {
                ConcurrentDictionary<Guid, TreeItem> dict = new ConcurrentDictionary<Guid, TreeItem>();

                var time = mtTest("ConcurrentDictionary", numTasks, i =>
                {
                    return Task.Factory.StartNew(() =>
                    {
                        var item1 = new TreeItem();
                        dict[item1.Id] = item1;
                    }
                    );
                }
                );
                Console.WriteLine("\n -- {0} ms with {1} iterations. Not sorted.",
                time, numTasks);
            }
        }
Example #60
0
 public ComputerTreeItem(string name, TreeItem parent)
     : base(name, parent)
 {
 }