Package thegame

Source Code of thegame.GamePropertiesDialog

package thegame;

// Importation des libraires dont on a l'utilisation
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import net.java.games.input.Component.Identifier;
import net.sf.jiga.xtended.impl.game.InteractiveModel;
import net.sf.jiga.xtended.impl.game.Model;
import net.sf.jiga.xtended.impl.game.XtendedModel;
import net.sf.jiga.xtended.impl.game.physics.Player;
import net.sf.jiga.xtended.kernel.ThreadWorks;
import net.sf.jiga.xtended.ui.*;
import thegame.comp.Fighter;
import thegame.layers.Options;

public class GamePropertiesDialog extends JPanel {

    Container contenu;
    JTabbedPane jtp;
    JPanel panelResources;
    Border border;
    /**
     * resources directory (beginning with '/' sets to jar-archive external
     * resource else to in-jar-archive resource)
     */
    InstructionsPane sw_resourcesLoaderIPane;
    JScrollPane sw_backgroundTableModelSPane;
    Dimension panelSize;
    private JPanel panelJInput;
    javax.swing.Timer[] jinputTimer;
    private KeyEventDispatcher ked;
    FieldGui gui;

    public GamePropertiesDialog(FieldGui gui, boolean fullscreen) {
        super(true);
        this.gui = gui;

        /*
         * Le container de la frame
         */
        contenu = this;
        contenu.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        /*
         * OPTIONS TABS
         */
        jtp = new JTabbedPane(JTabbedPane.LEFT, JTabbedPane.WRAP_TAB_LAYOUT);

        panelSize = new Dimension(300, 300);
        border = BorderFactory.createEtchedBorder(Color.white, new Color(150, 145, 140));

        /**
         * JInput
         */
        panelJInput = new JPanel(new GridBagLayout(), true);
        loadJinput();

        /**
         * PATHS
         */
        panelResources = new JPanel(new BorderLayout(), true);
        panelResources.setBorder(new TitledBorder(border, "Resources folders :"));

        InstructionsPane ipane = sw_resourcesLoaderIPane = new InstructionsPane(jtp, 0, 3);
        /*
         * ipane.setPreferredSize(panelSize);
         */
        final JLabel playerModelsFolder = fullscreen ? switchToWMLabel : new JLabel("<html><b>Locate CHARACTERS (Xtended)MODELS !</b> *." + XtendedModel._MIME_EXT[0] + "</html>");
        final FileChooserPane fcp = new FileChooserPane(this, "");
        fcp.setModeOpen(true);
        fcp.setMultiSelectionEnabled(true);
        fcp.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int step = fullscreen ? ipane.addStep() : ipane.addInstructionSet(fcp);
        ipane.addStepComponent(step, playerModelsFolder, 1, 2);
        if (!fullscreen) {
            ipane.addStepComponent(step, new JButton(new AbstractAction("Load Characters", UIMessage._getIcon(UIMessage.TEMPLATE_TYPE, false)) {

                public void actionPerformed(ActionEvent e) {
                    Runnable r = new Runnable() {

                        public void run() {
                            Vector<File> vf = new Vector<File>();
                            if (fcp.getSelectedFiles() == null) {
                                FieldGui.clearPlayerModelsStack();
                            } else {
                                for (File directory : fcp.getSelectedFiles()) {
                                    vf.addAll(findModelsInPath(directory, XtendedModel._MIME_EXT));
                                }
                                playerModelsFolder.setText("Found " + vf.size() + " models.");
                                FieldGui.clearPlayerModelsStack();
                                for (File path : vf) {
                                    XtendedModel model = (XtendedModel) InteractiveModel._importModel(path.getPath());
                                    String map = null;
                                    while (new String("").equals(map) || map == null) {
                                        map = (String) UIMessage.showSelectDialog(GamePropertiesDialog.this, "What Moves Map will this character use ? ", "Choose a map !", new String[]{Fighter.SUPERMOVEST1, Fighter.SUPERMOVEST2}, map);
                                    }
                                    model.setAttribute("eventMapTYPE", map);
                                    FieldGui.addPlayerModel(model);
                                }
                            }
                        }
                    };
                    propsDialog.doLater(r);
                }
            }), 1, 2);
        }
        final JLabel backgroundModelsFolder = fullscreen ? switchToWMLabel : new JLabel("<html><b>Locate BACKGROUND (Xtended)MODELS ! </b>*." + XtendedModel._MIME_EXT[0] + "</html>");
        final FileChooserPane fcp2 = new FileChooserPane(this, "");
        fcp2.setModeOpen(true);
        fcp2.setMultiSelectionEnabled(true);
        fcp2.getFiles().addChoosableFileFilter(new ExampleFileFilter(XtendedModel._MIME_EXT, XtendedModel._dataFlavor.getHumanPresentableName()));
        if (!fullscreen) {
            step = ipane.addInstructionSet(fcp2);
        }
        ipane.addStepComponent(step, backgroundModelsFolder, 1, 2);
        if (!fullscreen) {
            ipane.addStepComponent(step, new JButton(new AbstractAction("Load Backgrounds", UIMessage._getIcon(UIMessage.TEMPLATE_TYPE, false)) {

                public void actionPerformed(ActionEvent e) {
                    Runnable r = new Runnable() {

                        public void run() {
                            Vector<File> vf = new Vector<File>();
                            if (fcp2.getSelectedFiles() == null) {
                                FieldGui.clearBackgroundModelsStack();
                            } else {
                                for (File directory : fcp2.getSelectedFiles()) {
                                    vf.addAll(findModelsInPath(directory, XtendedModel._MIME_EXT));
                                }
                                backgroundModelsFolder.setText("Found " + vf.size() + " models for backgrounds.");
                                FieldGui.clearBackgroundModelsStack();
                                for (int i = 0; i < vf.size(); i++) {
                                    FieldGui.addBackgroundModel(FieldGui.SCREEN_DEFAULT, (XtendedModel) Model._importModel(vf.get(i).getPath()));
                                }
                            }
                            loadTableOfBackgroundModel();
                        }
                    };
                    propsDialog.doLater(r);
                }
            }), 1, 2);
        }
        panelResources.add(sw_resourcesLoaderIPane, BorderLayout.CENTER);
        panelResources.add(sw_backgroundTableModelSPane = new JScrollPane(new JTable()), BorderLayout.NORTH);

        panelResources.add(status = new StatusPane(ipane, new AbstractAction("Apply to this Game", UIMessage._getIcon(UIMessage.REFRESH_TYPE, true)) {

            public void actionPerformed(ActionEvent e) {
                propsDialog.doLater(new Runnable() {

                    public void run() {
                        saveOptions();
                        dispose();
                    }
                });
            }
        }, new AbstractAction("Reload from " + Options.settingsFilename) {

            public void actionPerformed(ActionEvent e) {
                propsDialog.doLater(new Runnable() {

                    public void run() {
                        new Options(GamePropertiesDialog.this.gui, "Load File").loadSettings();
                        loadOptions();
                    }
                });
            }
        }), BorderLayout.SOUTH);

        /*
         * Creation des onglets JTabbedPane
         */
        JScrollPane sc = new JScrollPane(panelJInput);
        sc.getHorizontalScrollBar().setUnitIncrement(30);
        sc.getVerticalScrollBar().setUnitIncrement(30);
        sc.setPreferredSize(new Dimension(500, 300));
        jtp.addTab("Keyboard & Pads", UIMessage._getIcon(UIMessage.LWJGL_TYPE, true), sc, "Configure keyboard and pads !");
        jtp.addTab("Paths", UIMessage._getIcon(UIMessage.SEARCH_TYPE, true), panelResources, "Add more characters and stages to the game !");
        jtp.setSelectedIndex(0);
        if (fullscreen) {
            panelResources.setEnabled(false);
        }
        c = new GridBagConstraints();
        c.gridwidth = c.REMAINDER;
        c.fill = c.BOTH;
        c.weightx = c.weighty = 1;
        contenu.add(jtp, c);
        validate();
        loadOptions();

    }
    StatusPane status = null;
    private JLabel switchToWMLabel = new JLabel("Please, switch back (F4) to windowed mode to have access to this panel !");
    ThreadWorks propsDialog = new ThreadWorks("propDialog");

    private Vector<File> findModelsInPath(File path, String[] modelext) {
        Vector<File> files = new Vector<File>();
        Stack<File> dirs = new Stack<File>();
        dirs.push(path);
        while (dirs.empty() ? false : dirs.peek().isDirectory()) {
            for (File file : dirs.pop().listFiles()) {
                if (file.isDirectory()) {
                    dirs.push(file);
                } else {
                    for (String ext : modelext) {
                        if (file.getName().endsWith(ext)) {
                            files.add(file);
                            break;
                        }
                    }
                }
            }
        }
        return files;

    }

    /**
     * gamepad, joystick handlers
     */
    private void loadJinput() {
        panelJInput.removeAll();
        panelJInput.validate();
        synchronized (Sf3Player._availableGamepads) {
            if (jinputTimer != null) {
                for (javax.swing.Timer t : jinputTimer) {
                    t.stop();
                }
            }
            jinputTimer = new javax.swing.Timer[Sf3Player._availableGamepads.size()];
            net.java.games.input.Controller pads[] = Sf3Player._availableGamepads.values().toArray(new net.java.games.input.Controller[]{});
            for (int padNum = 0; padNum < Sf3Player._availableGamepads.size(); padNum++) {
                final net.java.games.input.Controller pad = pads[padNum];
                Vector<Vector> tableRows = new Vector<Vector>();
                final SortedMap<Player.key, Identifier> codeMap = gui.props.gamepadCodeMap;
                synchronized (codeMap) {
                    for (final Player.key action : codeMap.keySet()) {
                        Vector tableCols = new Vector();
                        tableCols.add(action);
                        tableCols.add(codeMap.get(action));
                        tableRows.add(tableCols);
                    }
                }
                Vector<String> cols = new Vector();
                cols.add("action");
                cols.add("button");
                GridBagConstraints cs = new GridBagConstraints();
                cs.gridwidth = cs.REMAINDER;
                cs.fill = cs.BOTH;
                cs.weightx = 1;
                cs.weighty = .1;
                panelJInput.add(new JLabel("[ " + padNum + " ] " + pad.getName()), cs);
                cs.weighty = 1;
                final JTable table = new JTable(tableRows, cols);
                panelJInput.add(table, cs);
                String[] buttons = new String[pads[padNum].getComponents().length];
                for (int i = 0; i < pad.getComponents().length; i++) {
                    buttons[i] = pad.getComponents()[i].getIdentifier().getName();
                }
                final JComboBox mapping = new JComboBox(buttons);
                final ActionListener mappingAct;
                mapping.addActionListener(mappingAct = new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                        String action = table.getValueAt(table.getSelectedRow(), 0).toString();
                        String id = table.getValueAt(table.getSelectedRow(), 1).toString();
                        for (Identifier i : Player._gamepadCodeMap.values()) {
                            if (i.getName().equals(id)) {
                                gui.props.gamepadCodeMap.put(Player.key.valueOf(action), i);
                                break;
                            }
                        }
                        System.out.println("mapped " + action + " to " + id + " of controller " + pad.getName());
                    }
                });
                table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(mapping));
                /**
                 * listen to gamepad, joystick event
                 */
                jinputTimer[padNum] = new javax.swing.Timer(10, new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                        pad.poll();
                        net.java.games.input.EventQueue eq = pad.getEventQueue();
                        net.java.games.input.Event ev = new net.java.games.input.Event();
                        while (eq.getNextEvent(ev)) {
                            if (table.getSelectedRow() != -1) {
                                String id = ev.getComponent().getIdentifier().getName();
                                table.setValueAt(id, table.getSelectedRow(), 1);
                                mappingAct.actionPerformed(e);
                            }
                        }
                    }
                });
                jinputTimer[padNum].start();
            }
        }
        /**
         * keyboard
         */
        Vector<Vector> jinput = new Vector<Vector>();
        final SortedMap<Player.key, Integer> codeMap = new TreeMap<Player.key, Integer>(gui.props.keyboardCodeMap);
        synchronized (codeMap) {
            for (final Player.key action : codeMap.keySet()) {
                Vector buttonCfg = new Vector();
                buttonCfg.add(action);
                buttonCfg.add(codeMap.get(action));
                jinput.add(buttonCfg);
            }
        }
        Vector<String> cols = new Vector();
        cols.add("action");
        cols.add("keystroke");
        GridBagConstraints cs = new GridBagConstraints();
        cs.gridwidth = cs.REMAINDER;
        cs.fill = cs.BOTH;
        cs.weightx = 1;
        cs.weighty = .1;
        panelJInput.add(new JLabel("keyboard"), cs);
        cs.weighty = 1;
        final JTable table = new JTable(jinput, cols);
        panelJInput.add(table, cs);
        final JTextField mapping = new JTextField("key stroke");
        final ActionListener mappingAct;
        mapping.addActionListener(mappingAct = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                String action = table.getValueAt(table.getSelectedRow(), 0).toString();
                int id = Integer.parseInt(table.getValueAt(table.getSelectedRow(), 1).toString());
                gui.props.keyboardCodeMap.put(Player.key.valueOf(action), id);
                System.out.println("mapped " + action + " to " + KeyEvent.getKeyText(id));
            }
        });
        table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(mapping));
        KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(ked);
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(ked = new KeyEventDispatcher() {

            long hash = System.nanoTime();

            @Override
            public boolean equals(Object obj) {
                return obj == null ? false : hash == obj.hashCode();
            }

            public boolean dispatchKeyEvent(KeyEvent e) {
                if (e.getID() == KeyEvent.KEY_PRESSED) {
                    if (table.getSelectedRow() != -1) {
                        int id = e.getKeyCode();
                        table.setValueAt(id, table.getSelectedRow(), 1);
                        mappingAct.actionPerformed(new ActionEvent(this, e.getID(), e.getKeyText(e.getKeyCode())));
                        return true;
                    }
                }
                return false;
            }
        });
        table.getColumnModel().getColumn(1).setCellRenderer(new TableCellRenderer() {

            JLabel label = new JLabel();

            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                label.setText(KeyEvent.getKeyText(Integer.parseInt(value.toString())));
                return label;
            }
        });
        panelJInput.validate();
    }

    /**
     * @return the new {@link FieldGui#getBackgroundModelsStack() FieldGui background stack}
     */
    private Vector<XtendedModel> updateTableModelBackgroundsModels(JTable table) {
        Vector<XtendedModel> returnModels = new Vector<XtendedModel>();
        Vector<Vector> rows = new Vector<Vector>();
        synchronized (FieldGui.getBackgroundModelsStack()) {
            for (Iterator<Map.Entry<String, XtendedModel[]>> it = FieldGui.getBackgroundModelsStack().entrySet().iterator(); it.hasNext();) {
                final Map.Entry<String, XtendedModel[]> s = it.next();
                int i = 0;
                for (XtendedModel m : s.getValue()) {
                    if (m instanceof XtendedModel) {
                        Vector v = new Vector();
                        v.add(new File(m.id + File.separator + m.prefix + "xx" + m.suffix).getName());
                        if (FieldGui.screenState.containsValue(s.getKey())) {
                            v.add(s.getKey());
                        } else {
                            v.add(FieldGui.SCREEN_DEFAULT);
                        }
                        v.add(FieldGui.findLayerName(i));
                        returnModels.add(m);
                        rows.add(v);
                    }
                    i++;
                }
            }
        }
        Vector v = new Vector();
        v.add("model");
        v.add("screen name");
        v.add("layer");
        table.setModel(new DefaultTableModel(rows, v));

        tableOfBackgroundModelslastValue = new Object[table.getRowCount()][table.getColumnCount()];
        for (int i = 0;
                i < table.getRowCount(); i++) {
            for (int j = 0; j < table.getColumnCount(); j++) {
                tableOfBackgroundModelslastValue[i][j] = table.getValueAt(i, j);
            }
        }

        Vector<String> backgrounds = new Vector<String>();
        for (String screen : FieldGui.screenState.values()) {
            if (!backgrounds.contains(screen)) {
                backgrounds.add(screen);
            }
        }
        sw_screenNameComboBox.setModel(new DefaultComboBoxModel(backgrounds));
        sw_screenNameComboBox.addActionListener(getTableOfBackgroundModelsRefreshListener(table));
        table.getColumnModel().getColumn(tableOfBackgroundModelsSCREENNAMEcolumn).setCellEditor(new DefaultCellEditor(sw_screenNameComboBox));

        JComboBox layersComboBox = new JComboBox(FieldGui.layersNames.keySet().toArray(new String[]{}));
        layersComboBox.addActionListener(getTableOfBackgroundModelsRefreshListener(table));
        table.getColumnModel().getColumn(tableOfBackgroundModelsLAYERcolumn).setCellEditor(new DefaultCellEditor(layersComboBox));
        TableCellRenderer XtendedModelCellRenderer = new TableCellRenderer() {

            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                return new JLabel(value.toString());
            }
        };
        table.getColumnModel().getColumn(tableOfBackgroundModelsVPATHcolumn).setCellRenderer(XtendedModelCellRenderer);

        return returnModels;
    }

    private ActionListener getTableOfBackgroundModelsRefreshListener(final JTable table) {
        return new ActionListener() {

            private void refreshTable() {
                for (int i = 0; i < table.getRowCount(); i++) {
                    for (int j = 0; j < table.getColumnCount(); j++) {
                        table.setValueAt(tableOfBackgroundModelslastValue[i][j], i, j);
                    }
                }
            }

            public void actionPerformed(ActionEvent e) {
                if (table.getSelectedRow() == -1) {
                    refreshTable();
                    return;
                }
                XtendedModel selectedModel = tableOfBackgroundModelsMODELSTACK.get(table.getSelectedRow());
                if (selectedModel instanceof XtendedModel) {
                    /**
                     * previous screen background layer selection
                     */
                    FieldGui.removeBackgroundModel((String) table.getValueAt(table.getSelectedRow(), tableOfBackgroundModelsSCREENNAMEcolumn), selectedModel);
                    /**
                     * new screen background layer selection
                     */
                    /**
                     *
                     */
                    XtendedModel replace = selectedModel;
                    int replaceIndex = FieldGui.layersNames.get((String) table.getValueAt(table.getSelectedRow(), tableOfBackgroundModelsLAYERcolumn));
                    while (replace instanceof XtendedModel) {
                        replace = FieldGui.addBackgroundModel((String) table.getValueAt(table.getSelectedRow(), tableOfBackgroundModelsSCREENNAMEcolumn), replace, replaceIndex++);
                    }
                    /**
                     * later or infinite loop ?
                     */
                    ThreadWorks.Swing.invokeLater(new Runnable() {

                        public void run() {
                            tableOfBackgroundModelsMODELSTACK = updateTableModelBackgroundsModels(table);
                            panelResources.validate();
                            panelResources.repaint();
                        }
                    });
                }
            }
        };
    }
    int tableOfBackgroundModelsVPATHcolumn = 0;
    int tableOfBackgroundModelsSCREENNAMEcolumn = 1;
    int tableOfBackgroundModelsLAYERcolumn = 2;
    Object[][] tableOfBackgroundModelslastValue = new Object[][]{};
    Vector<XtendedModel> tableOfBackgroundModelsMODELSTACK = new Vector<XtendedModel>();
    JComboBox sw_screenNameComboBox;

    private void loadTableOfBackgroundModel() {
        sw_backgroundTableModelSPane.getHorizontalScrollBar().setUnitIncrement(30);
        sw_backgroundTableModelSPane.getVerticalScrollBar().setUnitIncrement(30);
        sw_backgroundTableModelSPane.setPreferredSize(panelSize);
        final JTable table = new JTable();
        sw_screenNameComboBox = new JComboBox();
        tableOfBackgroundModelsMODELSTACK = updateTableModelBackgroundsModels(table);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        /*
         * table.setPreferredSize(panelSize);
         */
        sw_backgroundTableModelSPane.setViewportView(table);
        sw_resourcesLoaderIPane.validate();
        sw_resourcesLoaderIPane.repaint();
    }

    public int getButtonGroupCheck(ButtonGroup bgrp, AbstractButton[] bm) {
        int i = 0;
        while (i < bgrp.getButtonCount()) {
            if (bgrp.isSelected(bm[i].getModel())) {
                break;
            } else {
                i++;
            }
        }
        return i >= bgrp.getButtonCount() ? 0 : i;
    }

    private void setButtonGroupCheck(ButtonGroup bgrp, AbstractButton[] bm, String check) {
        for (int i = 0;
                i < bm.length; i++) {
            if (check.equals(bm[i].getText())) {
                bgrp.setSelected((ButtonModel) bm[i].getModel(), true);
            }
        }
    }

    public void loadOptions() {
        synchronized (gui.props.bgModels) {
            FieldGui.clearBackgroundModelsStack();
            for (Iterator<Map.Entry<String, XtendedModel[]>> it = gui.props.bgModels.entrySet().iterator(); it.hasNext();) {
                final Map.Entry<String, XtendedModel[]> s = it.next();
                FieldGui.setBackgroundModels(s.getKey(), s.getValue());
            }
        }
        synchronized (gui.props.characters) {
            FieldGui.clearPlayerModelsStack();
            for (XtendedModel model : gui.props.characters) {
                FieldGui.addPlayerModel(model);
            }
        }
        ThreadWorks.Swing.invokeLater(new Runnable() {

            public void run() {
                loadTableOfBackgroundModel();
                loadJinput();
            }
        });
    }
    long prg = UIMessage.newProgress(0, 100, contenu);

    private void deployCaches() {
        gui.props.deployContentsCaches(new CacheLoadListener() {

            @Override
            public void loadBegin() {
                super.loadBegin();
                gui.log("Cache Load starting... [");
            }

            @Override
            public void readCompleted() {
                super.readCompleted();
                gui.log(":");
            }

            @Override
            public void loadIsComplete() {
                super.loadIsComplete();
                gui.logLn("] Done.");
            }

            @Override
            public void readError(Exception trace) {
                super.readError(trace);
                gui.log(" Error " + trace.getMessage());
            }

            @Override
            public void readAborted() {
                super.readAborted();
                gui.logLn(" Aborted.");
            }
        }, prg);
    }

    public void saveOptions() {
        gui.props.bgModels = Collections.synchronizedMap(new HashMap<String, XtendedModel[]>());
        gui.props.characters = Collections.synchronizedList(new Vector<XtendedModel>());
        gui.props.bgModels.putAll(FieldGui.getBackgroundModelsStack());
        gui.props.characters.addAll(FieldGui.getPlayerModelsStack());
        ThreadWorks.Swing.invokeLater(new Runnable() {

            public void run() {
                loadTableOfBackgroundModel();
            }
        });
        deployCaches();
    }


    /**
     * releases all resources
     */
    public void dispose() {
        for (javax.swing.Timer t : jinputTimer) {
            t.stop();
        }
        KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(ked);
    }
}
TOP

Related Classes of thegame.GamePropertiesDialog

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.