Search in sources :

Example 6 with UIWidget

use of org.terasology.nui.UIWidget in project Terasology by MovingBlocks.

the class WidgetSelectionScreen method initialise.

@Override
public void initialise() {
    availableWidgets = find("availableWidgets", UIDropdownScrollable.class);
    // Populate the widget list.
    ClassLibrary<UIWidget> metadataLibrary = getManager().getWidgetMetadataLibrary();
    for (ClassMetadata metadata : metadataLibrary) {
        if (!CoreScreenLayer.class.isAssignableFrom(metadata.getType())) {
            widgets.put(metadata.toString(), metadata);
        }
    }
    List<String> options = Lists.newArrayList(widgets.keySet());
    Collections.sort(options);
    availableWidgets.setOptions(options);
    // Add the widget as a child of the node.
    WidgetUtil.trySubscribe(this, "ok", button -> {
        String selection = availableWidgets.getSelection();
        JsonTree childNode;
        if (node.getValue().getType() == JsonTreeValue.Type.ARRAY) {
            ClassMetadata metadata = widgets.get(selection);
            // Get the widget tree from a utility method.
            childNode = NUIEditorNodeUtils.createNewWidget(selection, "newWidget", false);
            // If the widget is an UILayout override, also add a "contents" array node to the tree.
            if (UILayout.class.isAssignableFrom(metadata.getType())) {
                childNode.addChild(new JsonTreeValue("contents", null, JsonTreeValue.Type.ARRAY));
            }
        } else {
            childNode = new JsonTree(new JsonTreeValue(selection, null, JsonTreeValue.Type.OBJECT));
            childNode.setExpanded(true);
        }
        node.addChild(childNode);
        closeListeners.forEach(UpdateListener::onAction);
        getManager().closeScreen(ASSET_URI);
    });
    find("ok", UIButton.class).bindEnabled(new ReadOnlyBinding<Boolean>() {

        @Override
        public Boolean get() {
            return availableWidgets.getSelection() != null;
        }
    });
    WidgetUtil.trySubscribe(this, "cancel", button -> getManager().closeScreen(ASSET_URI));
}
Also used : ClassMetadata(org.terasology.reflection.metadata.ClassMetadata) JsonTree(org.terasology.nui.widgets.treeView.JsonTree) UIDropdownScrollable(org.terasology.nui.widgets.UIDropdownScrollable) CoreScreenLayer(org.terasology.engine.rendering.nui.CoreScreenLayer) UIWidget(org.terasology.nui.UIWidget) JsonTreeValue(org.terasology.nui.widgets.treeView.JsonTreeValue) UIButton(org.terasology.nui.widgets.UIButton) UpdateListener(org.terasology.nui.widgets.UpdateListener)

Example 7 with UIWidget

use of org.terasology.nui.UIWidget in project Terasology by MovingBlocks.

the class BehaviorEditor method onDraw.

@Override
public void onDraw(final Canvas canvas) {
    super.onDraw(canvas);
    canvas.addInteractionRegion(mouseInteractionListener);
    try (SubRegion subRegion = canvas.subRegion(canvas.getRegion(), false)) {
        canvas.setDrawOnTop(true);
        for (UIWidget widget : getWidgets()) {
            if (!widget.isVisible()) {
                continue;
            }
            if (widget instanceof RenderableNode) {
                RenderableNode renderableNode = (RenderableNode) widget;
                for (Port port : renderableNode.getPorts()) {
                    Port targetPort = port.getTargetPort();
                    if (port.isInput() || targetPort == null || !targetPort.node.isVisible()) {
                        continue;
                    }
                    drawConnection(canvas, port, targetPort, port == activeConnectionStart ? Color.BLACK : Color.GREY);
                }
            }
        }
        if (activeConnectionStart != null) {
            drawConnection(canvas, activeConnectionStart, mouseWorldPosition, Color.WHITE);
        }
        if (selectedNode != null) {
            Vector2f size = new Vector2f(selectedNode.getSize());
            Vector2f topLeft = new Vector2f(selectedNode.getPosition());
            Vector2f topRight = new Vector2f(topLeft);
            topRight.add(new Vector2f(size.x + .1f, 0));
            Vector2f bottomLeft = new Vector2f(topLeft);
            bottomLeft.add(new Vector2f(0, size.y + .1f));
            Vector2f bottomRight = new Vector2f(topLeft);
            bottomRight.add(new Vector2f(size.x + 0.1f, size.y + 0.1f));
            drawConnection(canvas, topLeft, topRight, Color.GREEN);
            drawConnection(canvas, topRight, bottomRight, Color.GREEN);
            drawConnection(canvas, bottomRight, bottomLeft, Color.GREEN);
            drawConnection(canvas, bottomLeft, topLeft, Color.GREEN);
        }
        if (newNode != null) {
            newNode.visit(node -> drawWidget(canvas, node));
        }
        canvas.setDrawOnTop(false);
    }
}
Also used : Vector2f(org.joml.Vector2f) SubRegion(org.terasology.nui.SubRegion) UIWidget(org.terasology.nui.UIWidget)

Example 8 with UIWidget

use of org.terasology.nui.UIWidget in project Terasology by MovingBlocks.

the class AutoConfigWidgetFactory method buildWidgetFor.

/**
 * Creates {@link UIWidget} for {@link AutoConfig}
 *
 * @param config for creating widget
 * @return UIWidget created for config
 */
public UIWidget buildWidgetFor(AutoConfig config) {
    PropertyLayout container = new PropertyLayout();
    container.setRowConstraints("[min]");
    Collection<Property<?, ?>> widgetProperties = new ArrayList<>();
    for (Setting<?> setting : config.getSettings()) {
        Optional<UIWidget> settingWidget = settingWidgetFactory.createWidgetFor(setting);
        if (!settingWidget.isPresent()) {
            logger.error("Couldn't find a widget for the Setting [{}]", setting.getHumanReadableName());
            continue;
        }
        widgetProperties.add(new Property<>(translationSystem.translate(setting.getHumanReadableName()), null, settingWidget.get(), translationSystem.translate(setting.getDescription())));
    }
    container.addProperties(translationSystem.translate(config.getName()), widgetProperties);
    return container;
}
Also used : PropertyLayout(org.terasology.nui.layouts.PropertyLayout) ArrayList(java.util.ArrayList) Property(org.terasology.nui.properties.Property) UIWidget(org.terasology.nui.UIWidget)

Example 9 with UIWidget

use of org.terasology.nui.UIWidget in project Terasology by MovingBlocks.

the class NUISkinEditorScreen method resetPreviewWidget.

/**
 * {@inheritDoc}
 */
@Override
public void resetPreviewWidget() {
    if (selectedScreen != null) {
        try {
            // Construct a UISkinData instance.
            JsonElement skinElement = JsonTreeConverter.deserialize(getEditor().getRoot());
            UISkinData data = new UISkinFormat().load(skinElement);
            // Get the selected screen asset.
            Optional<UIElement> sourceAsset = assetManager.getAsset(selectedScreen, UIElement.class);
            if (!sourceAsset.isPresent()) {
                throw new FileNotFoundException(String.format("Asset %s not found", selectedScreen));
            }
            AssetDataFile source = sourceAsset.get().getSource();
            String content;
            try (JsonReader reader = new JsonReader(new InputStreamReader(source.openStream(), Charsets.UTF_8))) {
                reader.setLenient(true);
                content = new JsonParser().parse(reader).toString();
            }
            if (content != null) {
                JsonTree node = JsonTreeConverter.serialize(new JsonParser().parse(content));
                JsonElement screenElement = JsonTreeConverter.deserialize(node);
                UIWidget widget = new UIFormat().load(screenElement, alternativeLocale).getRootWidget();
                // Set the screen's skin using the previously generated UISkinData.
                widget.setSkin(Assets.generateAsset(data, UISkinAsset.class).getSkin());
                selectedScreenBox.setContent(widget);
            }
        } catch (Throwable t) {
            String truncatedStackTrace = Joiner.on(System.lineSeparator()).join(Arrays.copyOfRange(ExceptionUtils.getStackFrames(t), 0, 10));
            selectedScreenBox.setContent(new UILabel(truncatedStackTrace));
        }
    }
}
Also used : UILabel(org.terasology.nui.widgets.UILabel) UISkinFormat(org.terasology.engine.rendering.nui.skin.UISkinFormat) UIElement(org.terasology.nui.asset.UIElement) InputStreamReader(java.io.InputStreamReader) UIFormat(org.terasology.engine.rendering.nui.asset.UIFormat) JsonTree(org.terasology.nui.widgets.treeView.JsonTree) UISkinData(org.terasology.nui.skin.UISkinData) FileNotFoundException(java.io.FileNotFoundException) UIWidget(org.terasology.nui.UIWidget) JsonElement(com.google.gson.JsonElement) AssetDataFile(org.terasology.gestalt.assets.format.AssetDataFile) JsonReader(com.google.gson.stream.JsonReader) JsonParser(com.google.gson.JsonParser)

Example 10 with UIWidget

use of org.terasology.nui.UIWidget in project Terasology by MovingBlocks.

the class NUIEditorNodeUtils method getNodeInfo.

/**
 * @param node A node in an asset tree.
 * @param nuiManager The {@link NUIManager} to be used for widget type resolution.
 * @return The info about this node's type.
 */
public static NodeInfo getNodeInfo(JsonTree node, NUIManager nuiManager) {
    Deque<JsonTree> pathToRoot = getPathToRoot(node);
    // Start iterating from top to bottom.
    Class<?> currentClass = null;
    Class<?> activeLayoutClass = null;
    Function<String, Class<? extends UIWidget>> resolve = (String type) -> verifyNotNull(nuiManager.getWidgetMetadataLibrary().resolve(type, ModuleContext.getContext()), "Failed to resolve widget %s in %s", type, ModuleContext.getContext()).getType();
    for (JsonTree n : pathToRoot) {
        if (n.isRoot()) {
            // currentClass is not set - set it to the screen type.
            String type = (String) n.getChildWithKey("type").getValue().getValue();
            currentClass = resolve.apply(type);
        } else {
            if (List.class.isAssignableFrom(currentClass) && n.getValue().getKey() == null && "contents".equals(n.getParent().getValue().getKey())) {
                // Transition from a "contents" list to a UIWidget.
                currentClass = UIWidget.class;
            } else {
                // Retrieve the type of an unspecified UIWidget.
                if (currentClass == UIWidget.class && n.hasSiblingWithKey("type")) {
                    String type = (String) n.getSiblingWithKey("type").getValue().getValue();
                    currentClass = resolve.apply(type);
                }
                // If the current class is a layout, remember its' value (but do not set until later on!)
                Class<?> layoutClass = null;
                if (UILayout.class.isAssignableFrom(currentClass)) {
                    layoutClass = currentClass;
                }
                if (UILayout.class.isAssignableFrom(currentClass) && "contents".equals(n.getValue().getKey())) {
                    // "contents" fields of a layout are always (widget) lists.
                    currentClass = List.class;
                } else if (UIWidget.class.isAssignableFrom(currentClass) && "layoutInfo".equals(n.getValue().getKey())) {
                    // Set currentClass to the layout hint type for the active layout.
                    currentClass = (Class<?>) ReflectionUtil.getTypeParameter(activeLayoutClass.getGenericSuperclass(), 0);
                } else {
                    String value = n.getValue().toString();
                    Set<Field> fields = ReflectionUtils.getAllFields(currentClass);
                    Optional<Field> newField = fields.stream().filter(f -> f.getName().equalsIgnoreCase(value)).findFirst();
                    if (newField.isPresent()) {
                        currentClass = newField.get().getType();
                    } else {
                        Optional<Field> serializedNameField = fields.stream().filter(f -> f.isAnnotationPresent(SerializedName.class) && f.getAnnotation(SerializedName.class).value().equals(value)).findFirst();
                        if (serializedNameField.isPresent()) {
                            currentClass = serializedNameField.get().getType();
                        } else {
                            return null;
                        }
                    }
                }
                // Set the layout class value.
                if (layoutClass != null) {
                    activeLayoutClass = layoutClass;
                }
            }
        }
    }
    // If the final result is a generic UIWidget, attempt to retrieve its type.
    if (currentClass == UIWidget.class && node.hasChildWithKey("type")) {
        String type = (String) node.getChildWithKey("type").getValue().getValue();
        currentClass = resolve.apply(type);
    }
    return new NodeInfo(currentClass, activeLayoutClass);
}
Also used : Set(java.util.Set) UILayout(org.terasology.nui.UILayout) Optional(java.util.Optional) JsonTree(org.terasology.nui.widgets.treeView.JsonTree) UIWidget(org.terasology.nui.UIWidget)

Aggregations

UIWidget (org.terasology.nui.UIWidget)14 UIElement (org.terasology.nui.asset.UIElement)4 UILabel (org.terasology.nui.widgets.UILabel)3 JsonTree (org.terasology.nui.widgets.treeView.JsonTree)3 JsonElement (com.google.gson.JsonElement)2 Optional (java.util.Optional)2 UIFormat (org.terasology.engine.rendering.nui.asset.UIFormat)2 DefaultBinding (org.terasology.nui.databinding.DefaultBinding)2 ColumnLayout (org.terasology.nui.layouts.ColumnLayout)2 UIButton (org.terasology.nui.widgets.UIButton)2 UIDropdownScrollable (org.terasology.nui.widgets.UIDropdownScrollable)2 Defaults (com.google.common.base.Defaults)1 JsonParser (com.google.gson.JsonParser)1 JsonReader (com.google.gson.stream.JsonReader)1 FileNotFoundException (java.io.FileNotFoundException)1 InputStreamReader (java.io.InputStreamReader)1 Constructor (java.lang.reflect.Constructor)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Parameter (java.lang.reflect.Parameter)1 ArrayList (java.util.ArrayList)1