Search in sources :

Example 16 with TypeInfo

use of org.terasology.reflection.TypeInfo in project Terasology by MovingBlocks.

the class SubtypeLayoutBuilder method populate.

@Override
protected void populate(Binding<T> binding, ColumnLayout layout, ColumnLayout mainLayout) {
    ColumnLayout widgetContainer = new ColumnLayout();
    Binding<TypeInfo<T>> editingType = new NotifyingBinding<TypeInfo<T>>(baseType) {

        @Override
        protected void onSet() {
            widgetContainer.removeAllWidgets();
            TypeWidgetBuilder<T> builder = SubtypeLayoutBuilder.this.library.getBuilder(get()).orElse(baseTypeWidgetBuilder);
            if (builder == null) {
                LOGGER.error("Could not find widget for type {}, editing as base type {}", get(), baseType);
                return;
            }
            widgetContainer.addWidget(builder.build(binding));
        }
    };
    if (binding.get() != null && !editingType.get().getRawType().equals(binding.get().getClass())) {
        Type actual = ReflectionUtil.parameterizeandResolveRawType(baseType.getType(), binding.get().getClass());
        TypeInfo<T> actualType = (TypeInfo<T>) TypeInfo.of(actual);
        if (!allowedSubtypes.contains(actualType)) {
            Optional<TypeInfo<T>> closestMatch = allowedSubtypes.stream().filter(subtype -> subtype.getRawType().isAssignableFrom(actualType.getRawType())).findFirst();
            // closestMatch is always present since editingType is guaranteed to be a subtype of T
            assert closestMatch.isPresent();
            editingType.set(closestMatch.get());
        } else {
            editingType.set(actualType);
        }
    }
    UIDropdownScrollable<TypeInfo<T>> typeSelection = new UIDropdownScrollable<>();
    typeSelection.setOptions(allowedSubtypes);
    typeSelection.bindSelection(editingType);
    typeSelection.setOptionRenderer(new StringTextRenderer<TypeInfo<T>>() {

        @Override
        public String getString(TypeInfo<T> value) {
            return getTypeName(value);
        }
    });
    // TODO: Translate
    typeSelection.setTooltip("Select the type for the new object");
    layout.addWidget(typeSelection);
    layout.addWidget(widgetContainer);
}
Also used : ModuleManager(org.terasology.engine.core.module.ModuleManager) LoggerFactory(org.slf4j.LoggerFactory) TypeWidgetLibrary(org.terasology.nui.widgets.types.TypeWidgetLibrary) TypeInfo(org.terasology.reflection.TypeInfo) TypeRegistry(org.terasology.reflection.TypeRegistry) ExpandableLayoutBuilder(org.terasology.nui.widgets.types.builtin.util.ExpandableLayoutBuilder) NotifyingBinding(org.terasology.nui.databinding.NotifyingBinding) ColumnLayout(org.terasology.nui.layouts.ColumnLayout) StringTextRenderer(org.terasology.nui.itemRendering.StringTextRenderer) Binding(org.terasology.nui.databinding.Binding) UIDropdownScrollable(org.terasology.nui.widgets.UIDropdownScrollable) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) PermissionProvider(org.terasology.gestalt.module.sandbox.PermissionProvider) Module(org.terasology.gestalt.module.Module) ModuleEnvironment(org.terasology.gestalt.module.ModuleEnvironment) ModuleContext(org.terasology.engine.core.module.ModuleContext) Set(java.util.Set) ReflectionUtil(org.terasology.engine.utilities.ReflectionUtil) Collectors(java.util.stream.Collectors) List(java.util.List) TypeWidgetBuilder(org.terasology.nui.widgets.types.TypeWidgetBuilder) Type(java.lang.reflect.Type) Modifier(java.lang.reflect.Modifier) Optional(java.util.Optional) Name(org.terasology.gestalt.naming.Name) UIDropdownScrollable(org.terasology.nui.widgets.UIDropdownScrollable) TypeInfo(org.terasology.reflection.TypeInfo) Type(java.lang.reflect.Type) ColumnLayout(org.terasology.nui.layouts.ColumnLayout) NotifyingBinding(org.terasology.nui.databinding.NotifyingBinding)

Example 17 with TypeInfo

use of org.terasology.reflection.TypeInfo in project Terasology by MovingBlocks.

the class ReflectionUtil method getComponentType.

/**
 * Returns the {@link TypeInfo} describing the component type of an array of the given type.
 *
 * @param type The {@link TypeInfo} describing the type of the array.
 * @param <C>  The component type of the array.
 */
@SuppressWarnings("unchecked")
public static <C> TypeInfo<C> getComponentType(TypeInfo<C[]> type) {
    if (type.getType() instanceof GenericArrayType) {
        GenericArrayType arrayType = (GenericArrayType) type.getType();
        Type componentType = arrayType.getGenericComponentType();
        Type resolvedComponentType = resolveType(arrayType, componentType);
        return (TypeInfo<C>) TypeInfo.of(resolvedComponentType);
    }
    return TypeInfo.of((Class<C>) type.getRawType().getComponentType());
}
Also used : GenericArrayType(java.lang.reflect.GenericArrayType) WildcardType(java.lang.reflect.WildcardType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) GenericArrayType(java.lang.reflect.GenericArrayType) TypeInfo(org.terasology.reflection.TypeInfo)

Example 18 with TypeInfo

use of org.terasology.reflection.TypeInfo in project Terasology by MovingBlocks.

the class TypeHandlerLibrary method getTypeHandler.

/**
 * Retrieves the {@link TypeHandler} for the specified type, if available.
 * <p>
 * Each {@link TypeHandlerFactory} added to this {@link TypeHandlerLibrary} is requested to generate a {@link
 * TypeHandler} for the given type. Most recently added factories are requested first, hence a {@link
 * TypeHandlerFactory} can override one that was added before it.
 *
 * @param type The {@link TypeInfo} describing the type for which to retrieve the {@link TypeHandler}.
 * @param <T> The type for which to retrieve the {@link TypeHandler}.
 * @return The {@link TypeHandler} for the specified type, if available.
 */
@SuppressWarnings("unchecked")
public <T> Optional<TypeHandler<T>> getTypeHandler(TypeInfo<T> type) {
    TypeHandlerContext context = new TypeHandlerContext(this, sandbox);
    if (typeHandlerCache.containsKey(type)) {
        return Optional.of((TypeHandler<T>) typeHandlerCache.get(type));
    }
    Map<TypeInfo<?>, FutureTypeHandler<?>> futures = futureTypeHandlers.get();
    boolean cleanupFutureTypeHandlers = false;
    if (futures == null) {
        cleanupFutureTypeHandlers = true;
        futures = new HashMap<>();
        futureTypeHandlers.set(futures);
    }
    FutureTypeHandler<T> future = (FutureTypeHandler<T>) futures.get(type);
    if (future != null) {
        return Optional.of(future);
    }
    try {
        future = new FutureTypeHandler<>();
        futures.put(type, future);
        // TODO: Explore reversing typeHandlerFactories itself before building object
        for (int i = typeHandlerFactories.size() - 1; i >= 0; i--) {
            TypeHandlerFactory typeHandlerFactory = typeHandlerFactories.get(i);
            Optional<TypeHandler<T>> typeHandler = typeHandlerFactory.create(type, context);
            if (typeHandler.isPresent()) {
                TypeHandler<T> handler = typeHandler.get();
                if (!sandbox.isValidTypeHandlerDeclaration(type, handler)) {
                    continue;
                }
                typeHandlerCache.put(type, handler);
                future.typeHandler = handler;
                return Optional.of(handler);
            }
        }
        return Optional.empty();
    } finally {
        futures.remove(type);
        if (cleanupFutureTypeHandlers) {
            futureTypeHandlers.remove();
        }
    }
}
Also used : TypeInfo(org.terasology.reflection.TypeInfo) CollectionTypeHandlerFactory(org.terasology.persistence.typeHandling.coreTypes.factories.CollectionTypeHandlerFactory) ArrayTypeHandlerFactory(org.terasology.persistence.typeHandling.coreTypes.factories.ArrayTypeHandlerFactory) ObjectFieldMapTypeHandlerFactory(org.terasology.persistence.typeHandling.coreTypes.factories.ObjectFieldMapTypeHandlerFactory) MapTypeHandlerFactory(org.terasology.persistence.typeHandling.coreTypes.factories.MapTypeHandlerFactory) EnumTypeHandlerFactory(org.terasology.persistence.typeHandling.coreTypes.factories.EnumTypeHandlerFactory) FloatTypeHandler(org.terasology.persistence.typeHandling.coreTypes.FloatTypeHandler) StringTypeHandler(org.terasology.persistence.typeHandling.coreTypes.StringTypeHandler) BooleanTypeHandler(org.terasology.persistence.typeHandling.coreTypes.BooleanTypeHandler) LocaleTypeHandler(org.terasology.persistence.typeHandling.coreTypes.LocaleTypeHandler) CharacterTypeHandler(org.terasology.persistence.typeHandling.coreTypes.CharacterTypeHandler) ByteArrayTypeHandler(org.terasology.persistence.typeHandling.coreTypes.ByteArrayTypeHandler) NumberTypeHandler(org.terasology.persistence.typeHandling.coreTypes.NumberTypeHandler) ByteTypeHandler(org.terasology.persistence.typeHandling.coreTypes.ByteTypeHandler) RuntimeDelegatingTypeHandler(org.terasology.persistence.typeHandling.coreTypes.RuntimeDelegatingTypeHandler) IntTypeHandler(org.terasology.persistence.typeHandling.coreTypes.IntTypeHandler) LongTypeHandler(org.terasology.persistence.typeHandling.coreTypes.LongTypeHandler) DoubleTypeHandler(org.terasology.persistence.typeHandling.coreTypes.DoubleTypeHandler)

Example 19 with TypeInfo

use of org.terasology.reflection.TypeInfo in project Terasology by MovingBlocks.

the class ConstructorLibrary method getCollectionCopyConstructor.

public static <E> CollectionCopyConstructor<? extends Collection<E>, E> getCollectionCopyConstructor(TypeInfo<? extends Collection<E>> typeInfo) {
    Class<? extends Collection<E>> rawType = typeInfo.getRawType();
    Type type = typeInfo.getType();
    if (Multiset.class.isAssignableFrom(rawType)) {
        if (ImmutableMultiset.class.isAssignableFrom(rawType)) {
            return ImmutableMultiset::copyOf;
        }
        return HashMultiset::create;
    }
    if (SortedSet.class.isAssignableFrom(rawType)) {
        if (ImmutableSortedSet.class.isAssignableFrom(rawType)) {
            return ImmutableSortedSet::copyOf;
        }
        return TreeSet::new;
    }
    if (EnumSet.class.isAssignableFrom(rawType)) {
        return (items) -> {
            if (!(type instanceof ParameterizedType)) {
                throw new IllegalArgumentException("Invalid EnumSet type: " + type.toString());
            }
            Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
            if (!(elementType instanceof Class)) {
                throw new IllegalArgumentException("Invalid EnumSet type: " + type.toString());
            }
            return EnumSet.copyOf((Collection) items);
        };
    }
    if (Set.class.isAssignableFrom(rawType)) {
        if (ImmutableSet.class.isAssignableFrom(rawType)) {
            return ImmutableSet::copyOf;
        }
        return LinkedHashSet::new;
    }
    if (Queue.class.isAssignableFrom(rawType)) {
        return ArrayDeque::new;
    }
    if (ImmutableList.class.isAssignableFrom(rawType)) {
        return ImmutableList::copyOf;
    }
    return ArrayList::new;
}
Also used : UnsafeAllocator(org.terasology.reflection.reflect.internal.UnsafeAllocator) Arrays(java.util.Arrays) Array(java.lang.reflect.Array) SortedSet(java.util.SortedSet) Multiset(com.google.common.collect.Multiset) TypeInfo(org.terasology.reflection.TypeInfo) HashMap(java.util.HashMap) Constructor(java.lang.reflect.Constructor) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) LinkedHashMap(java.util.LinkedHashMap) ImmutableList(com.google.common.collect.ImmutableList) HashMultiset(com.google.common.collect.HashMultiset) ImmutableMultiset(com.google.common.collect.ImmutableMultiset) Map(java.util.Map) InstanceCreator(org.terasology.persistence.typeHandling.InstanceCreator) EnumSet(java.util.EnumSet) LinkedHashSet(java.util.LinkedHashSet) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) ConcurrentNavigableMap(java.util.concurrent.ConcurrentNavigableMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) PrivilegedAction(java.security.PrivilegedAction) InvocationTargetException(java.lang.reflect.InvocationTargetException) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap) ParameterizedType(java.lang.reflect.ParameterizedType) TreeMap(java.util.TreeMap) Type(java.lang.reflect.Type) Queue(java.util.Queue) AccessController(java.security.AccessController) ArrayDeque(java.util.ArrayDeque) Comparator(java.util.Comparator) Collections(java.util.Collections) SortedMap(java.util.SortedMap) ParameterizedType(java.lang.reflect.ParameterizedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Collection(java.util.Collection)

Aggregations

TypeInfo (org.terasology.reflection.TypeInfo)19 Test (org.junit.jupiter.api.Test)11 Type (java.lang.reflect.Type)10 ParameterizedType (java.lang.reflect.ParameterizedType)9 GenericArrayType (java.lang.reflect.GenericArrayType)8 WildcardType (java.lang.reflect.WildcardType)8 Optional (java.util.Optional)4 Set (java.util.Set)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 Map (java.util.Map)3 Collectors (java.util.stream.Collectors)3 CopyStrategy (org.terasology.reflection.copy.CopyStrategy)3 ImmutableSet (com.google.common.collect.ImmutableSet)2 Constructor (java.lang.reflect.Constructor)2 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 HashMap (java.util.HashMap)2 List (java.util.List)2