Example #1
0
        internal static void RegisterUserFactories()
        {
#if !UNITY_EDITOR
            HashSet <string> userAssemblies = new HashSet <string>(ScriptingRuntime.GetAllUserAssemblies());
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly assembly in assemblies)
            {
                if (!(userAssemblies.Contains(assembly.GetName().Name + ".dll")) ||
                    assembly.GetName().Name == "UnityEngine.UIElementsModule")
                {
                    continue;
                }

                var types = assembly.GetTypes();
                foreach (Type type in types)
                {
                    if (!typeof(IUxmlFactory).IsAssignableFrom(type) ||
                        type.IsInterface ||
                        type.IsAbstract ||
                        type.IsGenericType)
                    {
                        continue;
                    }

                    var factory = (IUxmlFactory)Activator.CreateInstance(type);
                    RegisterFactory(factory);
                }
            }
#endif
        }
        internal static void DiscoverFactories()
        {
            if (factories != null)
            {
                return;
            }

            factories = new Dictionary <string, List <IUxmlFactory> >();
            RegisterEngineFactories();

            AppDomain        currentDomain  = AppDomain.CurrentDomain;
            HashSet <string> userAssemblies = new HashSet <string>(ScriptingRuntime.GetAllUserAssemblies());

            foreach (Assembly assembly in currentDomain.GetAssemblies())
            {
                if (!userAssemblies.Contains(assembly.GetName().Name + ".dll"))
                {
                    continue;
                }

                Type[] types;
                try
                {
                    types = assembly.GetTypes();
                }
                catch (ReflectionTypeLoadException ex)
                {
                    var    exceptionMessages      = ex.LoaderExceptions.OfType <TypeLoadException>().Select(x => $"{x.TypeName} : {x.Message}").ToArray();
                    string loaderExceptionMessage = string.Empty;
                    if (exceptionMessages.Any())
                    {
                        loaderExceptionMessage = "\n\n" + string.Join("\n", exceptionMessages) + "\n";
                    }

                    Debug.LogWarning($"Error while loading types from assembly {assembly.FullName}: {ex}{loaderExceptionMessage}");
                    types = ex.Types.Where(t => t != null).ToArray();
                }

                foreach (var type in types)
                {
                    if (typeof(IUxmlFactory).IsAssignableFrom(type))
                    {
                        var factory = (IUxmlFactory)Activator.CreateInstance(type);
                        RegisterFactory(factory);
                    }
                }
            }
        }
            static string GetPrefixForNamespace(string ns)
            {
                if (s_NamespacePrefix == null)
                {
                    s_NamespacePrefix = new Dictionary <string, string>();

                    s_NamespacePrefix.Add(String.Empty, "global");
                    s_NamespacePrefix.Add(typeof(VisualElement).Namespace, "engine");
                    s_NamespacePrefix.Add(typeof(UxmlSchemaGenerator).Namespace, "editor");

                    AppDomain        currentDomain  = AppDomain.CurrentDomain;
                    HashSet <string> userAssemblies = new HashSet <string>(ScriptingRuntime.GetAllUserAssemblies());
                    foreach (Assembly assembly in currentDomain.GetAssemblies())
                    {
                        if (!userAssemblies.Contains(assembly.GetName().Name + ".dll"))
                        {
                            continue;
                        }

                        try
                        {
                            foreach (object nsPrefixAttributeObject in assembly.GetCustomAttributes(typeof(UxmlNamespacePrefixAttribute), false))
                            {
                                UxmlNamespacePrefixAttribute nsPrefixAttribute = (UxmlNamespacePrefixAttribute)nsPrefixAttributeObject;
                                s_NamespacePrefix[nsPrefixAttribute.ns] = nsPrefixAttribute.prefix;
                            }
                        }
                        catch (TypeLoadException e)
                        {
                            Debug.LogWarningFormat("Error while loading types from assembly {0}: {1}", assembly.FullName, e);
                        }
                    }
                }

                string prefix;

                if (s_NamespacePrefix.TryGetValue(ns ?? String.Empty, out prefix))
                {
                    return(prefix);
                }

                s_NamespacePrefix[ns] = String.Empty;
                return(String.Empty);
            }
Example #4
0
 private static void DiscoverFactories()
 {
     if (Factories.s_Factories == null)
     {
         Factories.s_Factories = new Dictionary <string, Func <IUxmlAttributes, CreationContext, VisualElement> >();
         CoreFactories.RegisterAll();
         AppDomain        currentDomain = AppDomain.CurrentDomain;
         HashSet <string> hashSet       = new HashSet <string>(ScriptingRuntime.GetAllUserAssemblies());
         Assembly[]       assemblies    = currentDomain.GetAssemblies();
         for (int i = 0; i < assemblies.Length; i++)
         {
             Assembly assembly = assemblies[i];
             if (hashSet.Contains(assembly.GetName().Name + ".dll"))
             {
                 try
                 {
                     Type[] types = assembly.GetTypes();
                     for (int j = 0; j < types.Length; j++)
                     {
                         Type type = types[j];
                         if (typeof(IUxmlFactory).IsAssignableFrom(type))
                         {
                             IUxmlFactory uxmlFactory = (IUxmlFactory)Activator.CreateInstance(type);
                             Factories.RegisterFactory(uxmlFactory.CreatesType.FullName, new Func <IUxmlAttributes, CreationContext, VisualElement>(uxmlFactory.Create));
                         }
                     }
                 }
                 catch (TypeLoadException ex)
                 {
                     Debug.LogWarningFormat("Error while loading types from assembly {0}: {1}", new object[]
                     {
                         assembly.FullName,
                         ex
                     });
                 }
             }
         }
     }
 }
Example #5
0
        internal static void DiscoverFactories()
        {
            if (factories != null)
            {
                return;
            }

            factories = new Dictionary <string, List <IUxmlFactory> >();
            RegisterEngineFactories();

            AppDomain        currentDomain  = AppDomain.CurrentDomain;
            HashSet <string> userAssemblies = new HashSet <string>(ScriptingRuntime.GetAllUserAssemblies());

            foreach (Assembly assembly in currentDomain.GetAssemblies())
            {
                if (!userAssemblies.Contains(assembly.GetName().Name + ".dll"))
                {
                    continue;
                }

                try
                {
                    foreach (var type in assembly.GetTypes())
                    {
                        if (typeof(IUxmlFactory).IsAssignableFrom(type))
                        {
                            var factory = (IUxmlFactory)Activator.CreateInstance(type);
                            RegisterFactory(factory);
                        }
                    }
                }
                catch (TypeLoadException e)
                {
                    Debug.LogWarningFormat("Error while loading types from assembly {0}: {1}", assembly.FullName, e);
                }
            }
        }
Example #6
0
        internal static Type GetTargetClassFromName(string targetClassName, Type attributeInterface)
        {
            Type targetClass = null;

            foreach (var assemblyName in ScriptingRuntime.GetAllUserAssemblies())
            {
                // we need to pass the assembly name without the .dll extension, so removing that first
                var name = Path.GetFileNameWithoutExtension(assemblyName);
                targetClass = Type.GetType(targetClassName + "," + name);
                if (targetClass != null)
                {
                    break;
                }
            }

            if (targetClass == null)
            {
                Debug.LogWarningFormat("Class type not found: " + targetClassName);
                return(null);
            }

            ValidateTargetClass(targetClass, attributeInterface);
            return(targetClass);
        }
        public EventTypeSelectField()
        {
            m_Choices = new List <StringValuePairs <long> >();
            m_State   = new Dictionary <long, bool>();
            m_Color   = new Dictionary <string, Color>();

            AppDomain        currentDomain  = AppDomain.CurrentDomain;
            HashSet <string> userAssemblies = new HashSet <string>(ScriptingRuntime.GetAllUserAssemblies());

            foreach (Assembly assembly in currentDomain.GetAssemblies())
            {
                if (userAssemblies.Contains(assembly.GetName().Name + ".dll"))
                {
                    continue;
                }

                try
                {
                    foreach (var type in assembly.GetTypes())
                    {
                        if (typeof(EventBase).IsAssignableFrom(type) && !type.ContainsGenericParameters)
                        {
                            var methodInfo = type.GetMethod("TypeId", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
                            if (methodInfo != null)
                            {
                                if (m_State.Count == 64)
                                {
                                    Debug.LogError("Too many values");
                                    break;
                                }

                                var typeId = (long)methodInfo.Invoke(null, null);
                                m_Choices.Add(new StringValuePairs <long> {
                                    s = type.Name, v = typeId
                                });
                                m_State.Add(typeId, true);

                                m_Color.Add(type.Name, Color.white);
                            }
                        }
                    }

                    if (m_Color.Count > 0)
                    {
                        List <Color> listOfColors = GetListOfColors();
                        int          indexCounter = 0;
                        var          listOfKeys   = m_Color.Keys.ToList();
                        foreach (var key in listOfKeys)
                        {
                            Color newColor = listOfColors[indexCounter];
                            m_Color[key] = newColor;
                            indexCounter++;
                            if (indexCounter >= listOfColors.Count)
                            {
                                indexCounter = 0;
                            }
                        }
                    }
                }
                catch (TypeLoadException e)
                {
                    Debug.LogWarningFormat("Error while loading types from assembly {0}: {1}", assembly.FullName, e);
                }
                catch (ReflectionTypeLoadException e)
                {
                    for (var i = 0; i < e.LoaderExceptions.Length; i++)
                    {
                        if (e.LoaderExceptions[i] != null)
                        {
                            Debug.LogError(e.Types[i] + ": " + e.LoaderExceptions[i].Message);
                        }
                    }
                }
            }

            m_Choices.Sort();
            UpdateValue();
        }
Example #8
0
        static UXMLEditorFactories()
        {
            if (k_Registered)
            {
                return;
            }

            k_Registered = true;

            IUxmlFactory[] factories =
            {
                // Primitives
                new TextElement.UxmlFactory(),

                // Compounds
                new PropertyControl <int> .UxmlFactory(),
                new PropertyControl <long> .UxmlFactory(),
                new PropertyControl <float> .UxmlFactory(),
                new PropertyControl <double> .UxmlFactory(),
                new PropertyControl <string> .UxmlFactory(),

                new VisualSplitter.UxmlFactory(),

                // Toolbar
                new Toolbar.UxmlFactory(),
                new ToolbarButton.UxmlFactory(),
                new ToolbarToggle.UxmlFactory(),
                new ToolbarSpacer.UxmlFactory(),
                new ToolbarMenu.UxmlFactory(),
                new ToolbarSearchField.UxmlFactory(),
                new ToolbarPopupSearchField.UxmlFactory(),
                new ToolbarBreadcrumbs.UxmlFactory(),
                // Bound
                new PropertyField.UxmlFactory(),
                new InspectorElement.UxmlFactory(),

                // Fields
                new FloatField.UxmlFactory(),
                new DoubleField.UxmlFactory(),
                new IntegerField.UxmlFactory(),
                new LongField.UxmlFactory(),
                new CurveField.UxmlFactory(),
                new ObjectField.UxmlFactory(),
                new ColorField.UxmlFactory(),
                new EnumField.UxmlFactory(),
                new MaskField.UxmlFactory(),
                new LayerMaskField.UxmlFactory(),
                new LayerField.UxmlFactory(),
                new TagField.UxmlFactory(),
                new GradientField.UxmlFactory(),
                new EnumFlagsField.UxmlFactory(),
                new Hash128Field.UxmlFactory(),

#if !UNITY_2021_1_OR_NEWER
                new ProgressBar.UxmlFactory(),
#endif
                // Compounds
                new RectField.UxmlFactory(),
                new Vector2Field.UxmlFactory(),
                new Vector3Field.UxmlFactory(),
                new Vector4Field.UxmlFactory(),
                new BoundsField.UxmlFactory(),


                new RectIntField.UxmlFactory(),
                new Vector2IntField.UxmlFactory(),
                new Vector3IntField.UxmlFactory(),
                new BoundsIntField.UxmlFactory(),

                new EventTypeSelectField.UxmlFactory()
            };

            foreach (IUxmlFactory factory in factories)
            {
                VisualElementFactoryRegistry.RegisterFactory(factory);
            }

            // Discover packages and user factories.
            HashSet <string> userAssemblies = new HashSet <string>(ScriptingRuntime.GetAllUserAssemblies());
            var types = TypeCache.GetTypesDerivedFrom <IUxmlFactory>();

            foreach (var type in types)
            {
                if (type.IsAbstract ||
                    !userAssemblies.Contains(type.Assembly.GetName().Name + ".dll") ||
                    !typeof(IUxmlFactory).IsAssignableFrom(type) ||
                    type.IsInterface ||
                    type.IsGenericType ||
                    type.Assembly.GetName().Name == "UnityEngine.UIElementsModule" ||
                    type.Assembly.GetName().Name == "UnityEditor.UIElementsModule")
                {
                    continue;
                }

                var factory = (IUxmlFactory)Activator.CreateInstance(type);
                VisualElementFactoryRegistry.RegisterFactory(factory);
            }
        }
Example #9
0
 public string[] GetAllUserAssemblies()
 {
     return(ScriptingRuntime.GetAllUserAssemblies());
 }
Example #10
0
        public EventTypeSearchField()
        {
            m_Choices       = new List <EventTypeChoice>();
            m_State         = new Dictionary <long, bool>();
            m_GroupedEvents = new Dictionary <string, List <long> >();

            AppDomain        currentDomain  = AppDomain.CurrentDomain;
            HashSet <string> userAssemblies = new HashSet <string>(ScriptingRuntime.GetAllUserAssemblies());

            foreach (Assembly assembly in currentDomain.GetAssemblies())
            {
                if (userAssemblies.Contains(assembly.GetName().Name + ".dll"))
                {
                    continue;
                }

                try
                {
                    foreach (var type in assembly.GetTypes().Where(t => typeof(EventBase).IsAssignableFrom(t) && !t.ContainsGenericParameters))
                    {
                        // Only select Pointer events on startup
                        AddType(type, IsGenericTypeOf(type, typeof(PointerEventBase <>)));
                    }

                    // Special case for ChangeEvent<>.
                    var implementingTypes = GetAllTypesImplementingOpenGenericType(typeof(INotifyValueChanged <>), assembly).ToList();
                    foreach (var valueChangedType in implementingTypes)
                    {
                        var baseType = valueChangedType.BaseType;
                        if (baseType == null || baseType.GetGenericArguments().Length <= 0)
                        {
                            continue;
                        }

                        var argumentType = baseType.GetGenericArguments()[0];
                        if (!argumentType.IsGenericParameter)
                        {
                            AddType(typeof(ChangeEvent <>).MakeGenericType(argumentType), false);
                        }
                    }
                }
                catch (TypeLoadException e)
                {
                    Debug.LogWarningFormat("Error while loading types from assembly {0}: {1}", assembly.FullName, e);
                }
                catch (ReflectionTypeLoadException e)
                {
                    for (var i = 0; i < e.LoaderExceptions.Length; i++)
                    {
                        if (e.LoaderExceptions[i] != null)
                        {
                            Debug.LogError(e.Types[i] + ": " + e.LoaderExceptions[i].Message);
                        }
                    }
                }
            }

            m_State.Add(0, false);

            // Add groups, with negative ids.
            var keyIndex = -1;

            foreach (var key in m_GroupedEvents.Keys.OrderBy(k => k))
            {
                m_Choices.Add(new EventTypeChoice()
                {
                    Name = key, Group = key, TypeId = keyIndex
                });
                m_State.Add(keyIndex--, key.Contains("IPointerEvent"));
            }

            m_Choices.Sort();
            m_Choices.Insert(0, new EventTypeChoice()
            {
                Name = "IAll", Group = "IAll", TypeId = 0
            });
            m_FilteredChoices = m_Choices.ToList();

            m_MenuContainer = new VisualElement();
            m_MenuContainer.AddToClassList(ussClassName);

            m_OuterContainer = new VisualElement();
            m_OuterContainer.AddToClassList(ussContainerClassName);
            m_MenuContainer.Add(m_OuterContainer);

            m_ListView = new ListView();
            m_ListView.AddToClassList(ussListViewClassName);
            m_ListView.pickingMode                   = PickingMode.Position;
            m_ListView.showBoundCollectionSize       = false;
            m_ListView.fixedItemHeight               = 20;
            m_ListView.selectionType                 = SelectionType.None;
            m_ListView.showAlternatingRowBackgrounds = AlternatingRowBackground.All;

            m_ListView.makeItem = () =>
            {
                var container = new VisualElement();
                container.AddToClassList(ussItemContainerClassName);

                var toggle = new Toggle();
                toggle.labelElement.AddToClassList(ussItemLabelClassName);
                toggle.visualInput.AddToClassList(ussItemToggleClassName);
                toggle.RegisterValueChangedCallback(OnToggleValueChanged);
                container.Add(toggle);

                var label = new Label();
                label.AddToClassList(ussItemCountClassName);
                label.pickingMode = PickingMode.Ignore;
                container.Add(label);

                return(container);
            };

            m_ListView.bindItem = (element, i) =>
            {
                var toggle     = element[0] as Toggle;
                var countLabel = element[1] as Label;
                var choice     = m_FilteredChoices[i];
                toggle.SetValueWithoutNotify(m_State[choice.TypeId]);
                var isGroup = choice.Name == choice.Group;

                toggle.label = isGroup ? $"{choice.Group.Substring(1).Replace("Event", "")} Events" : choice.Name;
                toggle.labelElement.RemoveFromClassList(isGroup ? ussItemLabelClassName : ussGroupLabelClassName);
                toggle.labelElement.AddToClassList(isGroup ? ussGroupLabelClassName : ussItemLabelClassName);
                toggle.userData = i;

                if (m_EventCountLog != null && m_EventCountLog.ContainsKey(choice.TypeId))
                {
                    countLabel.style.display = DisplayStyle.Flex;
                    countLabel.text          = m_EventCountLog[choice.TypeId].ToString();
                }
                else
                {
                    countLabel.text          = "";
                    countLabel.style.display = DisplayStyle.None;
                }
            };

            m_ListView.itemsSource = m_FilteredChoices;
            m_OuterContainer.Add(m_ListView);

            UpdateTextHint();

            m_MenuContainer.RegisterCallback <AttachToPanelEvent>(OnAttachToPanel);
            m_MenuContainer.RegisterCallback <DetachFromPanelEvent>(OnDetachFromPanel);
            textInputField.RegisterValueChangedCallback(OnValueChanged);

            RegisterCallback <FocusInEvent>(OnFocusIn);
            RegisterCallback <FocusEvent>(OnFocus);
            RegisterCallback <FocusOutEvent>(OnFocusOut);
        }