|   1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
 | using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Collections;
using System;
namespace MMO.Modifier
{
    ///Proviving a UnityEditor.GenericMenu, shows a complete popup browser.
    public class GenericMenuBrowser : PopupWindowContent
    {        
        //class node used in browser
        public class MenuNode
        {
            public MenuItemInfo item = null;
            public MenuNode parent = null;
            public Dictionary<string, MenuNode> children = new Dictionary<string, MenuNode>(System.StringComparer.OrdinalIgnoreCase);
            public string name = null;
            public bool unfolded = true;
            public string fullPath = null;
            //Leafs have menu items
            public bool isLeaf
            {
                get { return item != null; }
            }
        }
        ///MenuItemInfo exposition
        public class MenuItemInfo
        {
            public GUIContent content;
            public bool separator;
            public bool selected;
            public GenericMenu.MenuFunction func;
            public GenericMenu.MenuFunction2 func2;
            public object userData;
            public MenuItemInfo(GUIContent c, bool sep, bool slc, GenericMenu.MenuFunction f1, GenericMenu.MenuFunction2 f2, object o)
            {
                content = c;
                separator = sep;
                selected = slc;
                func = f1;
                func2 = f2;
                userData = o;
            }
        }
        private static GenericMenuBrowser current;
        private static GenericMenu boundMenu;
        private static MenuItemInfo[] items;
        private static MenuNode rootNode = new MenuNode();
        private static List<MenuNode> leafNodes;
        private static MenuNode currentNode = null;
        private const float HELP_RECT_HEIGHT = 30;
        private string title;
        private Color hoverColor = new Color(0.5f, 0.5f, 1, 0.3f);
        private Vector2 scrollPos;
        private string lastSearch;
        private string search;
        private GUIStyle headerStyle;
        private int hoveringIndex;
        private bool init;
        private float helpRectRequiredHeight = 0;
        private static Texture2D _tex;
        private static Texture2D tex
        {
            get
            {
                if (_tex == null)
                {
                    _tex = new Texture2D(1, 1);
                    _tex.hideFlags = HideFlags.HideAndDontSave;
                }
                return _tex;
            }
        }
        readonly public static Texture2D folderIcon = EditorGUIUtility.FindTexture("Folder Icon");
        private GUIStyle _helpStyle;
        private GUIStyle helpStyle
        {
            get
            {
                if (_helpStyle == null)
                {
                    _helpStyle = new GUIStyle("label");
                    _helpStyle.wordWrap = true;
                    _helpStyle.richText = true;
                    _helpStyle.alignment = TextAnchor.UpperLeft;
                }
                return _helpStyle;
            }
        }
        public override Vector2 GetWindowSize() { return new Vector2(250, Mathf.Max(350 + helpRectRequiredHeight, 350)); }
        ///Shows the popup menu at position and with title
        public static void Show(GenericMenu newMenu, Vector2 pos, string title)
        {
            PopupWindow.Show(new Rect(pos.x, pos.y, 0, 0), new GenericMenuBrowser(newMenu, title));
        }
        [UnityEditor.InitializeOnLoadMethod]
        static void Initialize()
        {
            UnityEditor.EditorApplication.update += OnEditorUpdate;
        }
        //So that threads work in Editor too
        static void OnEditorUpdate()
        {
        }
        public static GUIStyle toolbarSearchTextField;
        public static GUIStyle toolbarSearchCancelButton;
        public static GUIStyle shadowedBackground;
        public static GUIStyle leftLabel;
        //init
        public GenericMenuBrowser(GenericMenu newMenu, string title)
        {
            current = this;
            this.title = title;
            rootNode = new MenuNode();
            currentNode = rootNode;
            headerStyle = new GUIStyle("label");
            headerStyle.alignment = TextAnchor.UpperCenter;
            headerStyle.fontSize = 16;
            headerStyle.fontStyle = FontStyle.Bold;
            toolbarSearchTextField = new GUIStyle("ToolbarSeachTextField");
            toolbarSearchTextField.fontSize = 11;
            toolbarSearchTextField.fixedHeight = 16;
            toolbarSearchCancelButton = new GUIStyle("ToolbarSeachCancelButton");
            toolbarSearchCancelButton.fixedHeight = 16;
            shadowedBackground = "CurveEditorBackground";
            leftLabel = new GUIStyle("label");
            hoveringIndex = -1;
            search = null;
            lastSearch = null;
            SetMenu(newMenu);
        }
        //Set the menu.
        public static void SetMenu(GenericMenu newMenu)
        {
            if (newMenu == null)
            {
                return;
            }
            boundMenu = newMenu;
            GenerateTree();
        }
        public override void OnOpen() {  }
        public override void OnClose() { }
        ///Gets an array of MenuItemInfo out of the GenericMenu provided
        public static MenuItemInfo[] GetMenuItems(GenericMenu menu)
        {
            var result = new List<MenuItemInfo>();
            var field = typeof(GenericMenu).GetField("menuItems", BindingFlags.Instance | BindingFlags.NonPublic);
            var items = field.GetValue(menu) as ArrayList;
            foreach (var item in items)
            {
                var type = item.GetType();
                var content = type.GetField("content").GetValue(item) as GUIContent;
                var separator = (bool)type.GetField("separator").GetValue(item);
                var selected = (bool)type.GetField("on").GetValue(item);
                var func1 = type.GetField("func").GetValue(item) as GenericMenu.MenuFunction;
                var func2 = type.GetField("func2").GetValue(item) as GenericMenu.MenuFunction2;
                var userData = type.GetField("userData").GetValue(item);
                result.Add(new MenuItemInfo(content, separator, selected, func1, func2, userData));
            }
            return result.ToArray();
        }
        ///A Search Field
        public static string SearchField(string search)
        {
            GUILayout.BeginHorizontal();
            search = EditorGUILayout.TextField(search, toolbarSearchTextField);
            if (GUILayout.Button(string.Empty, toolbarSearchCancelButton))
            {
                search = string.Empty;
                GUIUtility.keyboardControl = 0;
            }
            GUILayout.EndHorizontal();
            return search;
        }
        ///A thin separator
        public static void Separator()
        {
            var lastRect = GUILayoutUtility.GetLastRect();
            GUILayout.Space(7);
            GUI.color = new Color(0, 0, 0, 0.3f);
            GUI.DrawTexture(Rect.MinMaxRect(lastRect.xMin, lastRect.yMax + 4, lastRect.xMax, lastRect.yMax + 6), tex);
            GUI.color = Color.white;
        }
        ///A thick separator similar to ngui. Thanks
        public static void BoldSeparator()
        {
            var lastRect = GUILayoutUtility.GetLastRect();
            GUILayout.Space(1);
            GUI.color = new Color(0, 0, 0, 0.3f);
            GUI.DrawTexture(new Rect(0, lastRect.yMax + 1, Screen.width, 2), tex);
            GUI.DrawTexture(new Rect(0, lastRect.yMax + 3, Screen.width, 1), tex);
            GUI.color = Color.white;
        }
        //Generate the tree node structure out of the items
        static void GenerateTree()
        {
            items = GetMenuItems(boundMenu);
            leafNodes = new List<MenuNode>();
            for (var i = 0; i < items.Length; i++)
            {
                var item = items[i];
                var itemPath = item.content.text;
                var parts = itemPath.Split('/');
                MenuNode current = rootNode;
                var path = string.Empty;
                for (var j = 0; j < parts.Length; j++)
                {
                    var part = parts[j];
                    path += "/" + part;
                    MenuNode child = null;
                    if (!current.children.TryGetValue(part, out child))
                    {
                        child = new MenuNode { name = part, parent = current };
                        child.fullPath = path;
                        current.children[part] = child;
                        if (part == parts.Last())
                        {
                            child.item = item;
                            leafNodes.Add(child);
                        }
                    }
                    current = child;
                }
            }
        }
        //Show stuff
        public override void OnGUI(Rect rect)
        {
            var e = Event.current;
            EditorGUIUtility.SetIconSize(Vector2.zero);
            hoveringIndex = Mathf.Clamp(hoveringIndex, -1, currentNode.children.Count - 1);
            if (EditorGUIUtility.isProSkin)
            {
                GUI.Box(rect, string.Empty, shadowedBackground);
            }
            var headerHeight = currentNode.parent != null ? 72 : 45;
            var headerRect = new Rect(0, 0, rect.width, headerHeight);
            DoHeader(headerRect, e);
            var treeRect = Rect.MinMaxRect(0, headerHeight, rect.width, rect.height - HELP_RECT_HEIGHT);
            DoTree(treeRect, e);
            var helpRect = Rect.MinMaxRect(2, rect.height - HELP_RECT_HEIGHT + 2, rect.width - 2, rect.height - 2);
            DoFooter(helpRect, e);
            //handle the events
            HandeEvents(e);
            if (!init)
            {
                init = true;
                EditorGUI.FocusTextInControl("SearchToolbar");
            }
            EditorGUIUtility.SetIconSize(Vector2.zero);
        }
        void DoHeader(Rect headerRect, Event e)
        {
            //HEADER
            GUILayout.Label(title, headerStyle);
            ///SEARCH
            if (e.keyCode == KeyCode.DownArrow) { GUIUtility.keyboardControl = 0; }
            if (e.keyCode == KeyCode.UpArrow) { GUIUtility.keyboardControl = 0; }
            GUILayout.BeginHorizontal();
            GUI.SetNextControlName("SearchToolbar");
            search = SearchField(search);
            GUILayout.EndHorizontal();
            BoldSeparator();
            ///BACK
            if (currentNode.parent != null && string.IsNullOrEmpty(search))
            {
                GUILayout.Space(2);
                GUILayout.BeginHorizontal("box");
                GUILayout.Label("◄", GUILayout.Width(16));
                string nodeName = string.Empty;
                if (string.IsNullOrEmpty(currentNode.parent.name))
                {
                    nodeName = string.Format("{0}", currentNode.name);
                }
                else
                {
                    nodeName = string.Format("{0}/{1}", currentNode.parent.name, currentNode.name);
                }
                GUILayout.Box(nodeName, "label", GUILayout.Width(0), GUILayout.ExpandWidth(true));
                GUILayout.EndHorizontal();
                var lastRect = GUILayoutUtility.GetLastRect();
                if (e.type == EventType.MouseDown && e.button == 0 && lastRect.Contains(e.mousePosition))
                {
                    e.Use();
                    currentNode = currentNode.parent;
                }
                if (lastRect.Contains(e.mousePosition))
                {
                    GUI.color = hoverColor;
                    GUI.DrawTexture(lastRect, EditorGUIUtility.whiteTexture);
                    GUI.color = Color.white;
                    base.editorWindow.Repaint();
                    hoveringIndex = -1;
                }
            }
        }
        ///Returns whether or not the input is valid for a search match vs the target.
        ///Done by splitting input to words and checking sequential occurency within target string.
        public static bool SearchMatch(string input, string target)
        {
            //ignore case
            input = input.ToUpper();
            target = target.ToUpper();
            //treat dot as spaces and split to words
            var words = input.Replace('.', ' ').Split(' ');
            //at least one word should also be contained in target leaf name in case we have path
            var leafName = target.Contains('/') ? target.Substring(target.LastIndexOf('/') + 1) : target;
            //if fewer than 3 chars, do a direct match check with leaf name
            if (input.Length <= 2)
            {
                return input == leafName;
            }
            var match = false;
            var lastIndex = -1;
            foreach (var word in words)
            {
                if (!target.Contains(word))
                {
                    return false;
                }
                var index = target.IndexOf(word);
                if (lastIndex > index)
                {
                    return false;
                }
                if (leafName.Contains(word))
                {
                    match = true;
                }
                lastIndex = index;
            }
            return match;
        }
        //THE TREE
        void DoTree(Rect treeRect, Event e)
        {
            GUILayout.BeginArea(treeRect);
            scrollPos = EditorGUILayout.BeginScrollView(scrollPos, false, false);
            GUILayout.BeginVertical();
            if (search != lastSearch)
            {
                hoveringIndex = 0;
                if (!string.IsNullOrEmpty(search))
                {
                    var searchRootNode = new MenuNode() { name = "Search Root" };
                    foreach (var node in leafNodes)
                    {
                        if (SearchMatch(search, node.fullPath))
                        {
                            searchRootNode.children[node.fullPath] = node;
                        }
                    }
                    currentNode = searchRootNode;
                }
                else
                {
                    currentNode = rootNode;
                }
                lastSearch = search;
            }
            var i = 0;
            var itemAdded = false;
            MenuNode lastParent = null;
            foreach (var childPair in currentNode.children)
            {
                var node = childPair.Value;
                var leafItem = node.item;
                var icon = leafItem != null ? leafItem.content.image : folderIcon;
                var isDisabled = leafItem != null && leafItem.func == null && leafItem.func2 == null;
                //when with search, show category on top
                if (!string.IsNullOrEmpty(search))
                {
                    var currentParent = node.parent;
                    if (currentParent != lastParent)
                    {
                        lastParent = currentParent;
                        GUI.color = EditorGUIUtility.isProSkin ? Color.black : Color.white;
                        GUILayout.BeginHorizontal("box");
                        GUI.color = Color.white;
                        string path = currentParent.fullPath;
                        if (path != null && path.StartsWith("/"))
                        {
                            path = path.Substring(1);
                        }
                        var headerLabel = string.Format("{0}{1}", currentParent.unfolded ? "▼" : "▶", path);
                        if (GUILayout.Button(headerLabel, leftLabel, GUILayout.Height(16)))
                        {
                            currentParent.unfolded = !currentParent.unfolded;
                        }
                        GUILayout.EndHorizontal();
                    }
                    if (!node.parent.unfolded)
                    {
                        continue;
                    }
                }
                if (leafItem != null && leafItem.separator)
                {
                    Separator();
                    continue;
                }
                itemAdded = true;
                GUI.color = EditorGUIUtility.isProSkin ? Color.white : new Color(0.8f, 0.8f, 0.8f, 1);
                GUILayout.BeginHorizontal("box");
                GUI.color = Color.white;
                //Prefix icon
                //GUILayout.Label(icon, GUILayout.Width(32), GUILayout.Height(16));
                GUI.color = Color.white;
                GUI.enabled = !isDisabled;
                //Content
                var label = node.name;
                var text = label;
                GUILayout.Box(text, "label", GUILayout.Width(0), GUILayout.ExpandWidth(true), GUILayout.Height(16));
                //string dot = "●";
                GUILayout.Label(leafItem != null ? "": "►", GUILayout.Width(20), GUILayout.Height(16));
                GUILayout.EndHorizontal();
                var elementRect = GUILayoutUtility.GetLastRect();
                if (e.type == EventType.MouseDown && e.button == 0 && elementRect.Contains(e.mousePosition))
                {
                    e.Use();
                    if (leafItem != null)
                    {
                        ExecuteItemFunc(leafItem);
                        break;
                    }
                    else
                    {
                        currentNode = node;
                        hoveringIndex = 0;
                        break;
                    }
                }
                if (e.type == EventType.MouseMove && elementRect.Contains(e.mousePosition))
                {
                    hoveringIndex = i;
                }
                if (hoveringIndex == i)
                {
                    GUI.color = hoverColor;
                    GUI.DrawTexture(elementRect, EditorGUIUtility.whiteTexture);
                    GUI.color = Color.white;
                    base.editorWindow.Repaint();
                }
                i++;
                GUI.enabled = true;
            }
            if (!itemAdded)
            {
                GUILayout.Label("No results to display");
            }
            GUILayout.EndVertical();
            EditorGUILayout.EndScrollView();
            GUILayout.EndArea();
        }
        ///HELP AREA
        void DoFooter(Rect helpRect, Event e)
        {
            helpRectRequiredHeight = 0;
            var hoveringNode = hoveringIndex >= 0 && currentNode.children.Count > 0 ? currentNode.children.Values.ToList()[hoveringIndex] : null;
            GUI.color = new Color(0, 0, 0, 0.3f);
            GUI.Box(helpRect, string.Empty, "TextField");
            GUI.color = Color.white;
            GUILayout.BeginArea(helpRect);
            GUILayout.BeginVertical();
            var doc = string.Empty;
            if (hoveringNode != null && hoveringNode.item != null)
            {
                doc = hoveringNode.item.content.tooltip;
            }
            GUILayout.Label(doc, helpStyle);
            GUILayout.EndVertical();
            GUILayout.EndArea();
        }
        //Executes the item's registered delegate
        void ExecuteItemFunc(MenuItemInfo item)
        {
            if (item.func != null)
            {
                item.func();
            }
            else
            {
                item.func2(item.userData);
            }
            base.editorWindow.Close();
        }
        //Handle events
        void HandeEvents(Event e)
        {
            //Go back with right click as well...
            if (e.type == EventType.MouseDown && e.button == 1)
            {
                if (currentNode.parent != null)
                {
                    currentNode = currentNode.parent;
                }
                e.Use();
            }
            if (e.type == EventType.KeyDown)
            {
                if (e.keyCode == KeyCode.RightArrow || e.keyCode == KeyCode.Return)
                {
                    var next = currentNode.children.Values.ToList()[hoveringIndex];
                    if (e.keyCode == KeyCode.Return && next.item != null)
                    {
                        ExecuteItemFunc(next.item);
                    }
                    else if (next.item == null)
                    {
                        currentNode = next;
                        hoveringIndex = 0;
                    }
                    return;
                }
                if (e.keyCode == KeyCode.LeftArrow)
                {
                    var previous = currentNode.parent;
                    if (previous != null)
                    {
                        hoveringIndex = currentNode.parent.children.Values.ToList().IndexOf(currentNode);
                        currentNode = previous;
                    }
                    return;
                }
                if (e.keyCode == KeyCode.DownArrow)
                {
                    hoveringIndex++;
                    return;
                }
                if (e.keyCode == KeyCode.UpArrow)
                {
                    hoveringIndex--;
                    return;
                }
                if (e.keyCode == KeyCode.Escape)
                {
                    base.editorWindow.Close();
                    return;
                }
                EditorGUI.FocusTextInControl("SearchToolbar");
            }
        }
    }
}
 |