net.rptools.gui.listeners.fxml.AbstractURLController.java Source code

Java tutorial

Introduction

Here is the source code for net.rptools.gui.listeners.fxml.AbstractURLController.java

Source

/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
 * applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
 * OF ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */
package net.rptools.gui.listeners.fxml;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.List;

import javafx.application.Platform;
import javafx.beans.binding.BooleanBinding;
import javafx.collections.FXCollections;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableView;
import javafx.scene.control.TextInputControl;
import net.rptools.framework.RptoolsFileTypeDetector;

import org.apache.commons.lang3.StringUtils;
import org.rptools.framework.Framework;
import org.rptools.framework.ThreadPolicy;
import org.rptools.framework.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Controller base for URL lists. Currently only maps and campaigns.
 * @author username
 */
public abstract class AbstractURLController extends Controller {
    // Utility
    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractURLController.class);

    // Id box prefix
    private static final String BOX = "#box";

    // History state infix
    private static final String HISTORY_LOCATION_INFIX = ".history.location.";

    // History state infix
    private static final String HISTORY_NAME_INFIX = ".history.name.";

    @Override
    protected void init() {
        getURLList().getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        final List<AssetTableRow> urlRows = stateToGui();
        getURLList().setItems(FXCollections.observableList(urlRows));
        final String prefix = BOX + StringUtils.capitalize(getPrefix());
        LOGGER.debug("prefix={}", prefix);
        final TextInputControl name = ((TextInputControl) lookup(prefix + "Name"));
        final TextInputControl location = ((TextInputControl) lookup(prefix + "Location"));
        final BooleanBinding empty = name.textProperty().isEmpty().or(location.textProperty().isEmpty());
        lookup(prefix + "New").disableProperty().bind(empty);
    }

    /**
     * Utility to parse the state to GUI usable list.
     * @return list of state entries
     */
    @ThreadPolicy(ThreadPolicy.ThreadId.JFX)
    private List<AssetTableRow> stateToGui() {
        final Framework framework = getParent().getComponent().getFramework();
        final String prefix = getPrefix();
        final int historySize = getFileHistorySize();
        final List<AssetTableRow> rows = new ArrayList<AssetTableRow>();
        for (int i = 0; i < historySize; i++) {
            final String name = framework.getState(prefix + HISTORY_NAME_INFIX + i);
            final String location = framework.getState(prefix + HISTORY_LOCATION_INFIX + i);
            if (name != null) {
                rows.add(new AssetTableRow(name, location));
            } else {
                break;
            }
        }
        return rows;
    }

    /**
     * Utility to convert the GUI list to state.
     */
    @ThreadPolicy(ThreadPolicy.ThreadId.JFX)
    private void guiToState() {
        final Framework framework = getParent().getComponent().getFramework();
        final String prefix = getPrefix();
        final int historySize = getFileHistorySize();
        final List<AssetTableRow> rows = getURLList().getItems();
        final String[] attributes = new String[2 * Math.min(historySize, rows.size())];
        final String[] values = new String[2 * Math.min(historySize, rows.size())];
        for (int i = 0; i < attributes.length / 2; i++) {
            final AssetTableRow row = rows.get(i);
            attributes[2 * i] = prefix + HISTORY_NAME_INFIX + i;
            values[2 * i] = row.getProp1();
            attributes[2 * i + 1] = prefix + HISTORY_LOCATION_INFIX + i;
            values[2 * i + 1] = row.getProp2();
        }
        framework.setState(attributes, values);
    }

    /**
     * Getter.
     * @return prefix in the state-file's history
     */
    @ThreadPolicy(ThreadPolicy.ThreadId.ANY)
    protected abstract String getPrefix();

    /**
     * Add a file to the GUI history section.
     * @param location file name to add
     * @throws IOException I/O error
     */
    @ThreadPolicy(ThreadPolicy.ThreadId.ANY)
    public void updateFile(final String location) throws IOException {
        final int historySize = getFileHistorySize();
        final String expandedFileName = Utility.expandEnvironment(location);
        final String probeName = expandedFileName.replaceFirst("file://", "");
        final String name = RptoolsFileTypeDetector.probeContentName(FileSystems.getDefault().getPath(probeName));
        LOGGER.debug("probeName={}; name={}; location={}", probeName, name, location);
        if (name == null || location == null) { // safeguard
            return;
        }
        final AssetTableRow newRow = new AssetTableRow(name, location);
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                if (getURLList().getItems().size() == historySize) {
                    getURLList().getItems().remove(historySize - 1);
                }
                // This moves existing rows to the front
                if (getURLList().getItems().contains(newRow)) {
                    getURLList().getItems().remove(newRow);
                }
                getURLList().getItems().add(0, newRow);
                guiToState();
            }
        });
    }

    /**
     * Getter.
     * @return URL list
     */
    @ThreadPolicy(ThreadPolicy.ThreadId.JFX)
    protected abstract TableView<AssetTableRow> getURLList();

    /**
     * Getter.
     * @return file history size
     */
    @ThreadPolicy(ThreadPolicy.ThreadId.ANY)
    private int getFileHistorySize() {
        return Integer.parseInt(getParent().getComponent().getFramework().getProperty("framework.filehistory"));
    }
}