Package eas.startSetup

Source Code of eas.startSetup.Starter

/*
* Datei:            Starter.java
* Autor(en):        Lukas König
* Java-Version:     6.0
* Erstellt (vor):   19.12.2008
*
* (c) This file and the EAS (Easy Agent Simulation) framework containing it
* is protected by Creative Commons by-nc-sa license. Any altered or
* further developed versions of this file have to meet the agreements
* stated by the license conditions.
*
* In a nutshell
* -------------
* You are free:
* - to Share - to copy, distribute and transmit the work
* - to Remix - to adapt the work
*
* Under the following conditions:
* - Attribution - You must attribute the work in the manner specified by the
*   author or licensor (but not in any way that suggests that they endorse
*   you or your use of the work).
* - Noncommercial - You may not use this work for commercial purposes.
* - Share Alike - If you alter, transform, or build upon this work, you may
*   distribute the resulting work only under the same or a similar license to
*   this one.
*
* + Detailed license conditions (Germany):
*   http://creativecommons.org/licenses/by-nc-sa/3.0/de/
* + Detailed license conditions (unported):
*   http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en
*
* This header must be placed in the beginning of any version of this file.
*/

package eas.startSetup;

import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.jar.JarOutputStream;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

import eas.miscellaneous.StaticMethods;
import eas.miscellaneous.system.FileCopy;
import eas.miscellaneous.system.FileNamePostfixFilter;
import eas.miscellaneous.system.ZipIt;
import eas.miscellaneous.system.windowFrames.GeneralDialog;
import eas.plugins.Plugin;
import eas.plugins.PluginFactory;
import eas.plugins.standard.eaPlugin.DefaultMasterEA;
import eas.plugins.standard.eaPlugin.EAPlugin;
import eas.plugins.standard.other.NullPlugin;
import eas.plugins.standard.visualization.LiveWindow;
import eas.simulation.SimulationStarter;
import eas.startSetup.arrowGUI.PfeilController;
import eas.startSetup.marbBuilder.SteuerFenster;
import eas.startSetup.marbBuilder.traceBetrachter.TraceBetrachter;
import eas.statistics.ConstantsStatistics;
import eas.statistics.StatisticMethods;

/**
* Starter class that provides a basic GUI for adjusting global program
* parameters, starting different program components and creating jobs out of
* multiple parameter combinations (e.g., for usage with JoSchKa).
*
* @author Lukas König
*/
public class Starter extends JFrame implements
                                ListSelectionListener,
                                MouseListener,
                                ActionListener,
                                KeyListener,
                                FocusListener,
                                ComponentListener,
                                MouseMotionListener {
   
    public static final String IMPORT_PLUGINS_STRING = "Import plugins...";
    public static final String EXPORT_PLUGINS_STRING = "Export plugins...";
    public static final String EXIT_STRING = "Exit";
   
    public static final String SET_PARAMETER_COLLECTION_STRING = "Set parameter collection...";
    public static final String START_ARROW_MASTER_STRING = "Start Arrow Master";
    public static final String COMBINE_STATISTICS_XML_STRING = "Combine statistics (XML)...";
    public static final String FITNESS_STATISTICS_XML_STRING = "Fitness statistics (XML)...";
    public static final String START_XML_TRACE_VIEWER_STRING = "Start XML trace viewer";
    public static final String START_MARB_BUILDER_STRING = "Start MARB Builder";
    public static final String START_SIMULATION_STRING = "Start simulation";
    public static final String FIND_NEW_PLUGINS_STRING = "Find new plugins";
    public static final String GENERATE_PARS_STRING = "Generate pars...";
    public static final String GENERATE_AND_STORE_PARS_STRING = "Generate and STORE pars.";
    public static final String GENERATE_PARS_JOSCHKA_STRING = "Generate pars. JoSchKa...";
    public static final String RESET_PARAMETERS_STRING = "Reset parameters...";
    public static final String DELETE_UNSELECTED_PLUGINS_STRING = "Delete all plugins except the selected...";
    public static final String LOAD_STORED_SIMULATION = "Load SimState...";
   
    public static final int SINGLE_PAR_COLUMN = 1;
    public static final int DESCRIPTION_COLUMN = 5;
    public static final int ICON_COLUMN = 0;
    public static final int CATEGORY_COLUMN = 4;
    public static final int VALUE_COLUMN = 2;
    public static final int TYPE_COLUMN = 3;

    /**
     * Die Versions-ID.
     */
    private static final long serialVersionUID = 1L;
    private static final String STORE_PDF_OF_STARTER = "Create PDF file of Starter...";

    /**
     * Die Parameterliste.
     */
//    @SuppressWarnings("rawtypes")
    private JTable paramListe;

    /**
     * Parameter.
     */
    private ParCollection pars;

    /**
     * Felder.
     */
    private JTextArea[] parFelder;

    /**
     * Ob die Felder fest sein sollen oder nicht.
     */
    private JCheckBox[] isFixedCheckBoxen;

    /**
     * Die ScrollPane des Parameter-Text-Objekts.
     */
    private JScrollPane scroll;

    /**
     * Textfelderpanel.
     */
    private JPanel textFelder;

    /**
     * Sie Ausgabe.
     */
    private JTextArea ausgabe;

    /**
     * Der im Fenster anzuzeigende Titel.
     */
    private final String joschkaStarterTitel;

    /**
     * Der Konstruktor.
     *
     * @param parameter  Der Parametersatz für den Lauf.
     */
    public Starter(final ParCollection parameter) {
        super("EAS Simulation Starter");
        joschkaStarterTitel = getTitle();
        pars = parameter;
        reset();
        if (pars.getMultiplyDefinedParNames() != null && pars.getMultiplyDefinedParNames().size() > 0) {
            final GeneralDialog dia = new GeneralDialog(
                    this,
                    "The following active parameter names are used in several plugins "
                            + "(only one value can be assigned to each of them (providing that all have the same datatype); "
                            + "\nthat value is the last value in the list assigned to the according parameter):"
                            + "\n \n"
                            + pars.getMultiplyDefinedParNames().toString().replace(",", "\n").replace(" ", "").replace("]", "").replace("[", ""),
                    "Achtung! Doppelte Parameternamen",
                    GeneralDialog.OK_BUTT,
                    null);
            dia.setVisible(true);
        }
    }

    /**
     * Setzt das Steuerfenster zurück.
     */
    public void reset() {
        this.setLocation(0, 0);

        try {
            String[] dim = StaticMethods.liesTextArray(new File("./starterconf.dat"), this.pars).get(0).split("/");
            String[] loc = StaticMethods.liesTextArray(new File("./starterconf.dat"), this.pars).get(1).split("/");
//            boolean full = Boolean.parseBoolean(StaticMethods.liesTextArray(new File("./starterconf.dat"), this.pars).get(1));
            int width = Integer.parseInt(dim[0]);
            int height = Integer.parseInt(dim[1]);
            int x = Integer.parseInt(loc[0]);
            int y = Integer.parseInt(loc[1]);
            this.setSize(width, height);
            this.setLocation(x, y);
//            if (full) {
//                setExtendedState(getExtendedState() | Frame.MAXIMIZED_BOTH);
//            }
        } catch (Exception e) {
            // this.setSize(this.getMaximumSize());
            setExtendedState(getExtendedState() | Frame.MAXIMIZED_BOTH);
            this.setSize(1024, 768);
        }
       
        setzeSteuerelemente();
        setVisible(true);
        getContentPane().setVisible(true);
    }

    /**
     * Setzt die Parameter in die Parameterliste.
     *
     * @return Die Anzahl der gesetzten Parameter.
     */
//    @SuppressWarnings("unchecked")
    private int setzeParameterListe() {
        final ArrayList<SingleParameter> liste = pars.getAllPars();
        // Collections.sort(liste, new AlphaSort());
        final SingleParameter[] s = new SingleParameter[liste.size()];

        for (int i = 0; i < liste.size(); i++) {
            s[i] = liste.get(i);
            paramListe.setValueAt(s[i], i, Starter.SINGLE_PAR_COLUMN);
            paramListe.setValueAt(liste.get(i).getParValue(), i, Starter.VALUE_COLUMN);
            paramListe.setValueAt(liste.get(i).getParameterCategory(), i, Starter.CATEGORY_COLUMN);
            paramListe.setValueAt(liste.get(i).getDescription(), i, Starter.DESCRIPTION_COLUMN);
            paramListe.setValueAt(liste.get(i).getParameterType(), i, Starter.TYPE_COLUMN);
        }

        return s.length;
    }

    private final JPanel buttons = new JPanel();
    private Color hintergrund;

    /**
     * Setzt alle Steuerelemente und Fenstereigenschaften.
     */
//    @SuppressWarnings({ "unchecked", "rawtypes" })
    private void setzeSteuerelemente() {
        this.addMenu();
        hintergrund = buttons.getBackground();
        final ArrayList<SingleParameter> liste = pars.getAllPars();
        getContentPane().setBackground(Color.white);
        getContentPane().setLayout(new GridLayout(2, 1));
        final JPanel p = new JPanel();
        p.setLayout(new GridLayout(1, 1));

        DefaultTableModel tableModel = new DefaultTableModel(this.pars.getAllPars().size(), 6) {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
       
        paramListe = new JTable(tableModel) {
            private static final long serialVersionUID = 1L;

            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
               
                if (this.getSelectedRow() == row) {
                    return c;
                }

                if (!this.isEnabled()) {
                    c.setBackground(Color.LIGHT_GRAY);
                    return c;
                }
               
                try {
                    SingleParameter par = (SingleParameter) this.getValueAt(row, Starter.SINGLE_PAR_COLUMN);
                   
                    if (par.getParameterCategory().equalsIgnoreCase("Plugins")) {
                        c.setBackground(Color.yellow);
                    } else if (par.getIntelligentInput(null, null) != null) {
                        c.setBackground(new Color(255, 255, 200));
                    } else {
                        c.setBackground(Color.white);
                    }
                   
                    if (column == Starter.SINGLE_PAR_COLUMN && !c.getBackground().equals(Color.white)) {
                        java.util.Map<TextAttribute, Integer> fontAttributes = new HashMap<TextAttribute, Integer>();
                        fontAttributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
                        Font foldUnderline = new Font("",Font.PLAIN, 12).deriveFont(fontAttributes);
                        c.setFont(foldUnderline);
                    }
                   
                } catch (Exception e) {}

                return c;
            }
        };
       
        paramListe.addMouseMotionListener(this);

// Sortierung der Tabelle - geht nicht, da gelbe Felder nicht mitsortiert werden.
//        TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>();
//        // Der Sorter muss dem JTable bekannt sein
//        paramListe.setRowSorter( sorter );
//        // ... und der Sorter muss wissen, welche Daten er sortieren muss
//        sorter.setModel(tableModel);
       
        paramListe.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        paramListe.getColumnModel().getColumn(Starter.SINGLE_PAR_COLUMN).setHeaderValue("Parameter");
        paramListe.getColumnModel().getColumn(Starter.SINGLE_PAR_COLUMN).setPreferredWidth(200);
        paramListe.getColumnModel().getColumn(Starter.CATEGORY_COLUMN).setHeaderValue("Category");
        paramListe.getColumnModel().getColumn(Starter.CATEGORY_COLUMN).setPreferredWidth(80);
        paramListe.getColumnModel().getColumn(Starter.DESCRIPTION_COLUMN).setHeaderValue("Description");
        paramListe.getColumnModel().getColumn(Starter.DESCRIPTION_COLUMN).setPreferredWidth(600);
        paramListe.getColumnModel().getColumn(Starter.ICON_COLUMN).setHeaderValue("Generic?");
        paramListe.getColumnModel().getColumn(Starter.ICON_COLUMN).setPreferredWidth(110);
        paramListe.getColumnModel().getColumn(Starter.TYPE_COLUMN).setHeaderValue("Datatype");
        paramListe.getColumnModel().getColumn(Starter.TYPE_COLUMN).setPreferredWidth(80);
        paramListe.getColumnModel().getColumn(Starter.VALUE_COLUMN).setHeaderValue("Value");
        paramListe.getColumnModel().getColumn(Starter.VALUE_COLUMN).setPreferredWidth(180);
        paramListe.setRowHeight(25);
        paramListe.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
       
        paramListe.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
       
        paramListe.getColumnModel().getColumn(Starter.ICON_COLUMN).setCellRenderer(new ImageRenderer());

        final JScrollPane scrollPane = new JScrollPane(paramListe);
        final int size = setzeParameterListe();
        paramListe.getSelectionModel().addListSelectionListener(this);

        p.add(scrollPane);
        ausgabe = new JTextArea();
        ausgabe.setEditable(true);
        final JScrollPane scrollPane2 = new JScrollPane(ausgabe);
        getContentPane().add(p);
        final JButton generiere = new JButton(GENERATE_PARS_JOSCHKA_STRING);
        final JButton generiereQuick = new JButton("Generate pars. *Quick*");
        final JButton generiereNstore = new JButton(GENERATE_AND_STORE_PARS_STRING);
        generiereNstore.setToolTipText("Generates parameters and stores them to 'parameters.txt'. On program start these parameters are loaded (however, they can be overwritten by command line parameters!)");
        // generiere.setFont(new Font("Palatine lino type", Font.ITALIC, 15));
        generiereNstore.setFont(new Font("Palatine lino type", Font.ITALIC, 15));
        final JButton simStart = new JButton(START_SIMULATION_STRING);
        simStart.setFont(new Font("Palatine lino type", Font.BOLD, 15));
        simStart.setForeground(new Color(0, 0, 150));
        final JButton simStartMARB = new JButton(START_MARB_BUILDER_STRING);
        simStartMARB.setFont(new Font("", Font.PLAIN, 10));
        final JButton traceStart = new JButton(START_XML_TRACE_VIEWER_STRING);
        traceStart.setFont(new Font("", Font.PLAIN, 10));
        final JButton alleFit = new JButton(FITNESS_STATISTICS_XML_STRING);
        alleFit.setFont(new Font("", Font.PLAIN, 10));
        final JButton zusammen = new JButton(COMBINE_STATISTICS_XML_STRING);
        zusammen.setFont(new Font("", Font.PLAIN, 10));
        final JButton pfeilStart = new JButton(START_ARROW_MASTER_STRING);
        pfeilStart.setFont(new Font("", Font.PLAIN, 10));
        final JButton parReset = new JButton(RESET_PARAMETERS_STRING);
        final JButton parSet = new JButton(SET_PARAMETER_COLLECTION_STRING);
        final JButton pluginsButton = new JButton(FIND_NEW_PLUGINS_STRING);
        pluginsButton.setBackground(Color.orange);
        pluginsButton.setToolTipText("Refreshes the list of plugins by scanning the local class tree.");
        final JPanel pButtons = new JPanel(new GridLayout(2, 1));
        pButtons.add(scrollPane2);
        textFelder = new JPanel(new GridLayout(1, 2));
        buttons.add(generiereNstore);
        buttons.add(simStart);
        buttons.add(generiereQuick);
        buttons.add(generiere);
//        buttons.add(simStartMARB);
//        buttons.add(traceStart);
//        buttons.add(alleFit);
//        buttons.add(zusammen);
//        buttons.add(pfeilStart);
        buttons.add(parReset);
        buttons.add(parSet);
        buttons.add(pluginsButton);
        pButtons.add(buttons);
        textFelder.add(pButtons);
        parFelder = new JTextArea[size];
        isFixedCheckBoxen = new JCheckBox[size];
        for (int i = 0; i < size; i++) {
            parFelder[i] = new JTextArea("" + liste.get(i).getParValue());
            parFelder[i].setVisible(true);
            isFixedCheckBoxen[i] = new JCheckBox("Fixed");
            isFixedCheckBoxen[i].setVisible(true);
            parFelder[i].setBackground(new Color(255, 200, 0));
            parFelder[i].setCaretColor(Color.red);
            parFelder[i].setForeground(Color.black);
            parFelder[i].addMouseListener(this);
            parFelder[i].addKeyListener(this);
            parFelder[i].addFocusListener(this);
        }
        getContentPane().add(textFelder);

        paramListe.addMouseListener(this);
        generiere.addActionListener(this);
        generiereQuick.addActionListener(this);
        generiereNstore.addActionListener(this);
        simStart.addActionListener(this);
        traceStart.addActionListener(this);
        alleFit.addActionListener(this);
        pfeilStart.addActionListener(this);
        zusammen.addActionListener(this);
        simStartMARB.addActionListener(this);
        parReset.addActionListener(this);
        parSet.addActionListener(this);
        pluginsButton.addActionListener(this);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private LiveWindow window;
   
    @Override
    public void valueChanged(final ListSelectionEvent e) {
        if (paramListe.getSelectedRow() < 0) {
            return;
        }
       
        final SingleParameter currentPar = (SingleParameter) paramListe.getValueAt(
                paramListe.getSelectedRow(),
                SINGLE_PAR_COLUMN);
       
        final BufferedImage img = currentPar.getImage(pars);

        if (img != null) {
            if (window != null) {
                window.dispose();
            }
            window = new LiveWindow(
                    "Parameter View [" + currentPar.getParameterName() + "]",
                    null,
                    pars,
                    img.getWidth(),
                    img.getHeight(),
                    true);
            window.setBounds(
                    700,
                    0,
                    window.getWidth()
                            + window.getInsets().left
                            + window.getInsets().right,
                    window.getHeight()
                            + window.getInsets().top
                            + window.getInsets().bottom);
            window.metaInfVis.img = img;
            window.setVisible(true);
        } else {
            if (window != null) {
                window.dispose();
            }
        }

        setTitle(joschkaStarterTitel
                + " ["
                + currentPar.getParameterName()
                + ": \""
                + currentPar.getParValue()
                + "\"]");

        for (int i = 0; i < parFelder.length; i++) {
            textFelder.remove(parFelder[i]);
            textFelder.remove(isFixedCheckBoxen[i]);
            parFelder[i].setVisible(false);
            isFixedCheckBoxen[i].setVisible(false);
        }
        if (scroll != null) {
            textFelder.remove(scroll);
        }
        scroll = new JScrollPane(
                parFelder[paramListe.getSelectedRow()]);

        // this.textFelder.add(
        // this.parFelder[this.paramListe.getSelectedIndex()]);
        textFelder.add(scroll);
        textFelder.add(
                isFixedCheckBoxen[paramListe.getSelectedRow()]);
        parFelder[paramListe.getSelectedRow()].setVisible(true);
//        parFelder[paramListe.getSelectedRow()].requestFocus();
//        parFelder[paramListe.getSelectedRow()].selectAll();
        isFixedCheckBoxen[paramListe.getSelectedRow()].setVisible(true);
       
        boolean cancelled = false;
       
        // Intelligent Input.
        IntelligentInput inputWindow = currentPar.getIntelligentInput(this, this.pars);
        if (inputWindow != null) {
            if (currentPar.getParameterName().equals(eas.statistics.ConstantsStatistics.MASTER_SCHEDULER_PAR_NAME)) {
                this.focusGained(new FocusEvent(this.parFelder[paramListe.getSelectedRow()], FocusEvent.FOCUS_GAINED));
            }
            inputWindow.setVisible(true);

            // If the user did not cancel the input.
            if (inputWindow.getResult() != null) {
                if (currentPar.getParameterName().equals(eas.statistics.ConstantsStatistics.MASTER_SCHEDULER_PAR_NAME)) {
                    // Füge Plugins hinzu (immer auf Feld 3). TODO: Flexibel machen!
                    HashSet<String> plugs = new HashSet<String>();
                    for (String s : this.parFelder[3].getText().split(",")) {
                        if (!s.equals("")) {
                            plugs.add(s);
                        }
                    }
                    for (String s : inputWindow.getPluginsToAdd().split(",")) {
                        if (!s.equals("")) {
                            plugs.add(s);
                        }
                    }
                   
                    this.parFelder[3].setText(plugs.toString().replace("]", "").replace("[", "").replace(" ", ""));
                }
                this.parFelder[paramListe.getSelectedRow()].setText(inputWindow.getResult().toString());
                this.setzeChanged(paramListe.getSelectedRow());
            } else {
              cancelled = true;
            }
           
            if (currentPar.getParameterName().equals(eas.statistics.ConstantsStatistics.MASTER_SCHEDULER_PAR_NAME)
                    || currentPar.getParameterName().equals(eas.statistics.ConstantsStatistics.PLUGINS_PAR_NAME)) {
                this.keyReleased(new KeyEvent(
                        this.parFelder[paramListe.getSelectedRow()],
                        KeyEvent.KEY_RELEASED,
                        System.currentTimeMillis(),
                        0,
                        1,
                        KeyEvent.CHAR_UNDEFINED));
               
                if (cancelled) {
                  cancelledFromIntelligentInput = true;
                }
               
                this.focusLost(new FocusEvent(this.parFelder[paramListe.getSelectedRow()], FocusEvent.FOCUS_LOST));
                cancelledFromIntelligentInput = false;
            }
        }
    }
   
    private boolean cancelledFromIntelligentInput = false;

    /**
     * Erzeugt den Parameterarray als Textparameter (keine JoSchKa-Zusätze).
     *
     * @return Der Parameterarray.
     */
    private ArrayList<String> erzeugeParArray() {
        final ArrayList<SingleParameter> liste = pars.getAllPars();
        final JoSchKa joschka = new JoSchKa();
        final ArrayList<String> stzP = new ArrayList<String>(parFelder.length);
        final ArrayList<String[]> werte = new ArrayList<String[]>(parFelder.length);
        String[] zwischWert;
        final ArrayList<String> festePar = new ArrayList<String>();
        final ArrayList<String[]> festeWerte = new ArrayList<String[]>();

        // Erzeuge Listen mit festen Werten und zu kombinierenden Werten.
        for (int i = 0; i < parFelder.length; i++) {
            final String[] zwisch = parFelder[i].getText().split("\n");
            zwischWert = new String[zwisch.length];
            for (int j = 0; j < zwisch.length; j++) {
                zwischWert[j] = zwisch[j];
            }

            if (isFixedCheckBoxen[i].isSelected()) {
                festePar.add(liste.get(i).getParameterName());
                festeWerte.add(zwischWert);
            } else {
                stzP.add(liste.get(i).getParameterName());
                werte.add(zwischWert);
            }
        }

        // Parametersätze erzeugen.
        try {
            final ArrayList<String> ausgaben = joschka.erzeuge(
                    pars,
                    stzP,
                    werte,
                    festePar,
                    festeWerte,
                    this.parsCount());

            paramListe.setBackground(Color.white);

            return ausgaben;
        } catch (final Exception e) {
            paramListe.setBackground(Color.red);
            ausgabe.setText(e.getMessage());
            e.printStackTrace();

            return new ArrayList<String>();
        }
    }

    /**
     * Generiert die Parameter.
     */
    private void generiere(final boolean generateDirectory) {
        ArrayList<String> ausgaben;
        JoSchKa joschka;

        // Array erzeugen:
        ausgaben = erzeugeParArray();
        joschka = new JoSchKa();

        // Darstellung der Parametersätze in GUI:
        ausgabe.setText("");
        if (ausgaben.size() <= 100) {
            for (final String s : ausgaben) {
                ausgabe.setText(ausgabe.getText() + s + "\n");
            }
        } else {
            if (!generateDirectory) {
                ausgabe.setText(
                        "Too many parameter lines for this text field.\n\n"
                                + "Please generate complete JoSchKa parameter package"
                                + "\nand examine JoSchKa.txt.");
            }
        }

        // JoSchKa-Ausgaben erzeugen:
        ausgaben = joschka.erzeugeJoSchKaStd(
                pars.getJoschkaUser() + "_" + pars.getJoschkaVerz(),
                "java " + pars.getJoschkaVMpar()
                        + " -cp \"" + pars.getjoschkaCP()
                        + ";./" + pars.getJoschkaJAR() + "\""
                        + " eas.simulation.SimulationStarter",
                // + " -jar " + this.pars.getJoschkaJAR(),
                ausgaben,
                pars);

        if (generateDirectory) {
            // JoSchKa-Verzeichnis erzeugen:
            final String ergebnis = generateJoSchKaFolder(ausgaben, pars);
            if (ergebnis == null) {
                // JoSchKa-Ausgaben speichern:
                StaticMethods.speichereTextAusArray(
                        pars.getstarterSourceDirectory()
                                + File.separatorChar
                                + pars.getJoschkaVerz(),
                        "JoSchKa.txt",
                        ausgaben,
                        pars);

                ausgabe.setText(
                        ausgabe.getText()
                                + "\nJoSchKa package stored in "
                                + new File(pars.getstarterSourceDirectory()).getAbsolutePath()
                                + File.separatorChar
                                + pars.getJoschkaVerz());
                StaticMethods.logInfo("JoSchKa package generated: "
                        + new File(pars.getstarterSourceDirectory()).getAbsolutePath()
                        + File.separatorChar
                        + pars.getJoschkaVerz(), pars);

                try {
                    Desktop.getDesktop().open(
                            new File(pars.getstarterSourceDirectory()
                                    + File.separatorChar
                                    + pars.getJoschkaVerz()));
                } catch (final IOException e) {
                }
            } else {
                ausgabe.setText(
                        ausgabe.getText()
                                + "\n\nJoSchKa-Ausgaben nicht erzeugt."
                                + "\nFehler: " + ergebnis);
                StaticMethods.logWarning(
                        "JoSchKa package NOT generated.", pars);
            }
        }
    }

    /**
     * Erzeugt das JoSchKa-Verzeichnis und kopiert die notwendigen Dateien
     * hinein.
     *
     * @param ausgaben  Die Ausgabesätze.
     * @param params    Der Parametersatz.
     *
     * @return Ob die Aktion durchgeführt werden konnte. <code>null</code> bedeutet
     *         fehlerfrei - sonst wird ein String mit der Beschreibung des
     *         Fehlers zurückgegeben.
     */
    public String generateJoSchKaFolder(
            final ArrayList<String> ausgaben,
            final ParCollection params) {
        final File quellVerz = new File(
                params.getstarterSourceDirectory() + File.separatorChar);
        final File zielVerz = new File(
                params.getstarterSourceDirectory()
                        + File.separatorChar
                        + params.getJoschkaVerz());
        final FileCopy kopieren = new FileCopy();
        File[] zwisch;

        // Alte Dateien löschen.
        deleteVerz(zielVerz);
        zielVerz.mkdir();

        // Automaten kopieren.
        zwisch = quellVerz.listFiles(new AutomatenFilter());

        if (zwisch == null) {
            throw new RuntimeException("Verzeichnis existiert nicht: " + quellVerz);
        }

        for (final File f : zwisch) {
            final File f2 = new File(
                    zielVerz.getAbsolutePath()
                            + File.separatorChar
                            + f.getName());
            kopieren.copy(f, f2);
        }

        // // Falls sich keine Automaten im Verzeichnis befinden.
        // if (!enthaelt) {
        // this.paramListe.setBackground(Color.red);
        // this.deleteVerz(zielVerz);
        // return "Keine Roboter in " + quellVerz.getAbsolutePath() + ".";
        // }

        // Umgebungsdateien kopieren.
        if (params.existsPlugin(new EAPlugin().id())) {
            for (final String ausg : ausgaben) {
                // Achtung: In 0, ..., 4, letzt von ausg stehen JoSchKa-Zusätze.
                final String[] ausg1 = StaticMethods.processStringAsCommandLineParameters(ausg);
                String[] ausg2; // Ohne JoSchKa-Zusätze.
                ausg2 = new String[ausg1.length - 6];
                for (int i = 0; i < ausg2.length; i++) {
                    ausg2[i] = ausg1[i + 5];
                }

                final ParCollection paramsZwisch = new ParCollection(ausg2);
                paramsZwisch.complete();
                final File umgebungQuell = new File(
                        quellVerz.getAbsolutePath()
                                + File.separatorChar
                                + paramsZwisch.getParValueString(
                                        EAPlugin.UMGEBUNG_ATTR));
                final File umgebungZiel = new File(
                        zielVerz.getAbsolutePath()
                                + File.separatorChar
                                + paramsZwisch.getParValueString(
                                        EAPlugin.UMGEBUNG_ATTR));
                if (umgebungQuell.exists()) {
                    kopieren.copy(umgebungQuell, umgebungZiel);
                } else {
                    paramListe.setBackground(Color.red);
                    deleteVerz(zielVerz);
                    return "Umgebungsdatei nicht gefunden: "
                            + umgebungQuell.getAbsolutePath() + ".";
                }
            }
        }

        // JAR-Dateien kopieren.
        final File rootPfad = new File(".");
        zwisch = rootPfad.listFiles(new FileNamePostfixFilter("jar"));
        for (final File f : zwisch) {
            final File f2 = new File(
                    zielVerz.getAbsolutePath()
                            + File.separatorChar
                            + f.getName());
            kopieren.copy(f, f2);
        }

        // EAS-JAR-Datei erzeugen.
        try {
            createJAR();
        } catch (final IOException e) {
            return "Creation of EAS JAR file failed: " + jarFileName() + ". "
                    + "Please create manually.";
        }

        return null;
    }

    private String jarFileName() {
        final String fileName = pars.getstarterSourceDirectory()
                + File.separator
                + pars.getJoschkaVerz()
                + File.separator
                + pars.getJoschkaJAR();
        return fileName;
    }

    public void createJAR() throws IOException {
      File jarFile = null;
     
      jarFile = new File(jarFileName());
     
        // JAR file name + (relative) path.
        final JarOutputStream jos = ZipIt.getJARstream(
                jarFile,
                Starter.class.getName());
        ZipIt.addToJARDirectoryRecursively(
                jos,
                Starter.class.getPackage().getName().split("[.]")[0], // "eas"
                jarFile);
        jos.close();
    }

    /**
     * Löscht ein flaches Verzeichnis mit allen Dateien.
     *
     * @param verz
     *            Das Verzeichnis.
     */
    private void deleteVerz(final File verz) {
        if (verz == null) { return; }

        final File[] zwisch = verz.listFiles();

        if (zwisch != null) {
            for (final File f : zwisch) {
                f.delete();
            }
        }

        verz.delete();
    }

    @SuppressWarnings("unused")
    private boolean contains(final String[] array, final String s) {
        for (final String s2 : array) {
            if (s.equals(s2)) { return true; }
        }

        return false;
    }

    /**
     * Der Listener.
     *
     * @param arg0
     *            Das Event.
     */
    @Override
    public void actionPerformed(final ActionEvent arg0) {
        this.setCursor(new Cursor(3));

        if (window != null) {
            window.dispose();
        }

        for (final JTextArea t : parFelder) {
            t.setVisible(false);
        }

        if (arg0.getActionCommand().equals(RESET_PARAMETERS_STRING)) {
            resetParameters();
            return;
        }

        final LinkedList<Integer> markierte = new LinkedList<Integer>();
        String hervorString = "explen";
        int hervorNum = -1;

        for (int i = 0; i < paramListe.getRowCount(); i++) {
            if (((SingleParameter) paramListe.getModel().getValueAt(i, Starter.SINGLE_PAR_COLUMN))
                    .isChanged()) {
                markierte.add(i);
            }
        }

        if (hervorNum >= 0) {
            parFelder[hervorNum].setText(hervorString);
        } else {
            StaticMethods.log(
                    StaticMethods.LOG_STAGE1,
                    "Hervorgehobene Parameter nicht gesetzt: " + hervorString,
                    pars);
        }

        try {
            pars = new ParCollection(StaticMethods.processStringAsCommandLineParameters(
                    erzeugeParArray().get(0)));
            pars.complete();

            setzeParameterListe();

            for (int i = 0; i < markierte.size(); i++) {
                setzeChanged(markierte.get(i));
            }
        } catch (final Exception e2) {
            this.setCursor(new Cursor(0));
            return;
        }

        if (arg0.getActionCommand().equals(GENERATE_PARS_JOSCHKA_STRING)) {
            final long startTime = System.currentTimeMillis();
            generiere(true);
            StaticMethods.logInfo(
                    "Generation time (ms): "
                            + (System.currentTimeMillis() - startTime),
                    pars);
        } else {
            generiere(false);
        }

        String[] params = StaticMethods.processStringAsCommandLineParameters(ausgabe.getText().split("\n")[0]);
        String[] paramsTrace;
        String filename;

        // Parameter speichern:
        if (arg0.getActionCommand().equals(GENERATE_AND_STORE_PARS_STRING)) {
            generateNstoreParams(params);
        }
       
        if (arg0.getActionCommand().equals(GENERATE_PARS_STRING)) {
            params = null;
        } else if (arg0.getActionCommand().equals(FIND_NEW_PLUGINS_STRING)) {
          findNewPlugins(params);
        } else if (arg0.getActionCommand().equals(START_SIMULATION_STRING)) {
            final ParCollection parsNeu = new ParCollection(params);
            parsNeu.complete();
            dispose();
            SimulationStarter.main(parsNeu.getAllParsArrayView());
        } else if (arg0.getActionCommand().equals(START_MARB_BUILDER_STRING)) {
            final ParCollection parsNeu = new ParCollection(params);
            parsNeu.setMaster(new DefaultMasterEA().id());
            parsNeu.setPlugins(new String[] {new EAPlugin().id()});
            parsNeu.complete();
            dispose();
            SteuerFenster.main(StaticMethods.processStringAsCommandLineParameters(
                    parsNeu.parStrPlain().replace('\n', ' ')));
        } else if (arg0.getActionCommand().equals(START_XML_TRACE_VIEWER_STRING)) {
            final FileDialog dia = new FileDialog(
                    this,
                    "Tracedatei zum Betrachten auswählen",
                    FileDialog.LOAD);
            dia.setFile("*.xml*");
            dia.setDirectory(pars.getStdDirectory());
            dia.setVisible(true);
            if (dia.getFile() == null) {
                this.setCursor(new Cursor(0));
                return;
            }
            filename = dia.getDirectory() + dia.getFile();
            // filename = filename.substring(0, filename.length() - 3);
            paramsTrace = new String[params.length + 2];
            paramsTrace[0] = filename;
            paramsTrace[1] = "dummy";
            for (int i = 0; i < params.length; i++) {
                paramsTrace[i + 2] = params[i];
            }

            dispose();
            TraceBetrachter.main(paramsTrace);
        } else if (arg0.getActionCommand().equals(FITNESS_STATISTICS_XML_STRING)) {
            final JFileChooser dia = new JFileChooser();
            dia.setDialogTitle(
                    "Verzeichnis zum Extrahieren der Statistiken auswählen");
            dia.setCurrentDirectory(new File(pars.getStdDirectory()));
            dia.setVisible(true);
            dia.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            final int returnVal = dia.showOpenDialog(this);
            File f = null;
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                f = dia.getSelectedFile();
                filename = f.getAbsolutePath();
                paramsTrace = new String[params.length + 2];
                paramsTrace[0] = filename;
                paramsTrace[1] = "allefitnesswerte";
                for (int i = 0; i < params.length; i++) {
                    paramsTrace[i + 2] = params[i];
                }

                TraceBetrachter.main(paramsTrace);
            }
        } else if (arg0.getActionCommand().equals(COMBINE_STATISTICS_XML_STRING)) {
            final JFileChooser dia = new JFileChooser();
            final FileNamePostfixFilter filter = new FileNamePostfixFilter("txt");
            filter.setVerzZulassen(true);
            dia.setDialogTitle(
                    "Dateien zum Zusammenfassen auswählen");
            dia.setCurrentDirectory(new File(pars.getStdDirectory()));
            dia.setBounds(0, 0, 800, 600);
            dia.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            dia.setMultiSelectionEnabled(true);
            dia.setFileFilter(filter);

            final int returnVal = dia.showOpenDialog(this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                final File[] fs = dia.getSelectedFiles();
                String verzeichnis = null;
                String zieldatei;
                final String[] quelldateien = new String[fs.length];
                final String trennzeichen = ";";
                int i = 0;

                for (final File f : fs) {
                    verzeichnis = f.getParentFile().getAbsolutePath();
                    quelldateien[i] = f.getName();
                    i++;
                }

                // Zieldateiname generieren:
                zieldatei = "durchschnitt";
                for (final String s : quelldateien) {
                    final String zwisch = StaticMethods.datNamOhneErw(s);
                    zieldatei += "_" + zwisch.substring(zwisch.length() - 4);
                }
                if (zieldatei.length() > 100) {
                    zieldatei = zieldatei.substring(0, 100);
                }
                zieldatei += ".txt";

                StatisticMethods.erzeugeDurchDatei(
                        verzeichnis,
                        quelldateien,
                        zieldatei,
                        trennzeichen,
                        pars);
            }
        } else if (arg0.getActionCommand().equals(START_ARROW_MASTER_STRING)) {
            dispose();
            PfeilController.main(params);
        } else if (arg0.getActionCommand().equals(SET_PARAMETER_COLLECTION_STRING)) {
            final GeneralDialog dia = new GeneralDialog(
                    this,
                    null,
                    "Set new parameters as collection "
                            + "(caution: program restart after click on OK button!)",
                    GeneralDialog.OK_CANCEL_BUTT,
                    "Fill in parameters alternating as name / value pairs separated by space "
                            + "(caution: program restart after click on OK button).");
            dia.setVisible(true);

            if (dia.getResult().equals(GeneralDialog.OK)) {
                final String[] args = StaticMethods.processStringAsCommandLineParameters(dia.getText());
                final ParCollection paramsNeu = new ParCollection(pars);
                paramsNeu.complete();
                paramsNeu.overwriteParameterList(args);
                dispose();
                Starter.main(StaticMethods.processStringAsCommandLineParameters(
                        paramsNeu.parStrPlain().replace('\n', ' ')));
            }
        } else if (arg0.getActionCommand().equals(Starter.STORE_PDF_OF_STARTER)) {
            String pdfFileName = GeneralDialog.getStringFromUser("File name", "./Starter.pdf", "STARTER_PDF_FILE-NAME");
            this.storePDF(new File(pdfFileName), true, 1000, 1000);
        }

        this.setCursor(new Cursor(0));
    }

    /**
     * Finds new plugins in the class hierarchy
     *
     * @param params
     */
    public void findNewPlugins(String[] params) {
        String msg = "The plugin finder will now search for plugins in the class "
            + "hierarchy of EAS to refresh the list of plugins.\n"
            + "New plugins will be added, missing plugins will be removed.\n \nThis procedure has to be performed "
            + "only if plugin classes have been added or removed.";
       
        if (new File(".").getAbsolutePath().contains(" ")) {
          msg += "\n \nWARNING: The EAS path contains white spaces:\n"
              + " \n" + new File(".").getAbsolutePath() + "\n \n"
              + "The plugin finder will "
              + "probably be able to extract the plugins anyway, however, it will take longer;\n"
              + "to avoid the delay, or if problems are encountered, try removing white spaces from the path.\n"
              + "(See log for details.)";
        }
       
        String search = "Search";
        String searchHidden = "Search including hidden plugins (not recommended)";
       
        GeneralDialog dia = new GeneralDialog(
            this,
            msg,
            "Search for new plugins...",
            new String[] {search, searchHidden, GeneralDialog.CANCEL},
            null);
       
        dia.setVisible(true);
       
        if (!dia.getResult().equals(GeneralDialog.CANCEL)) {
          // Make temp copy of plugin file.
          new FileCopy().copy(
              new File("./" + PluginFactory.PLUGIN_STORAGE_FILE_NAME),
              new File("./" + PluginFactory.PLUGIN_STORAGE_FILE_NAME + "--.tmp"));
         
          boolean includeHidden = dia.getResult().equals(searchHidden);
         
          dispose();
         
            final ParCollection parsNeu = new ParCollection(params);
            List<Class<Plugin<?>>> oldList = new ArrayList<Class<Plugin<?>>>(PluginFactory.STORED_PLUGINS);
           
            if (!StaticMethods.deleteDAT("./" + PluginFactory.PLUGIN_STORAGE_FILE_NAME)) {
                StaticMethods.speichereTextDatei(".", PluginFactory.PLUGIN_STORAGE_FILE_NAME, "MURKS", this.pars);
            }
           
            PluginFactory.STORED_PLUGINS = PluginFactory.loadPluginsFromFile(includeHidden);
           
            Starter.main(parsNeu.getAllParsArrayView());
            List<Class<Plugin<?>>> newList = new ArrayList<Class<Plugin<?>>>(PluginFactory.STORED_PLUGINS);
           
            newList.removeAll(oldList);
            oldList.removeAll(PluginFactory.STORED_PLUGINS);
           
            LinkedList<String> newListStr = new LinkedList<String>();
            LinkedList<String> oldListStr = new LinkedList<String>();
           
            for (Class<Plugin<?>> c : newList) {
                String name;
                try {
                    name = c.newInstance().id().toString();
                } catch (Exception e) {
                    name = "<ID not readable>";
                }
               
                newListStr.add(c.toString() + " (ID: " + name + ")");
            }
           
            for (Class<Plugin<?>> c : oldList) {
                String name;
                try {
                    name = c.newInstance().id().toString();
                } catch (Exception e) {
                    name = "<ID not readable>";
                }
               
                oldListStr.add(c.toString() + " (ID: " + name + ")");
            }
           
            String pluginsFound = " Plugins found (including master schedulers).\n \n"; // Alright.
           
            // Check if plugins have been found and restore old list if not.
            if (PluginFactory.STORED_PLUGINS == null || PluginFactory.STORED_PLUGINS.size() == 0) {
              pluginsFound = " Plugins reloaded. WARNING: The search for plugins was NOT successful (see log for details). \n \n"; // Not alright.
            new FileCopy().copy(
                new File("./" + PluginFactory.PLUGIN_STORAGE_FILE_NAME + ".tmp"),
                new File("./" + PluginFactory.PLUGIN_STORAGE_FILE_NAME));
              PluginFactory.STORED_PLUGINS = PluginFactory.loadPluginsFromFile(includeHidden);
            }
           
            GeneralDialog window = new GeneralDialog(
                    this,
                    null,
                    "Newly found plugins",
                    GeneralDialog.OK_BUTT,
                    PluginFactory.STORED_PLUGINS.size() + pluginsFound
                    + "New plugins: \n" + newListStr.toString().replace("[]","NONE.").replace("[", "").replace("]", "").replace(", ", "\n") + "\n \n \n"
                    + "Removed plugins: \n" + oldListStr.toString().replace("[]","NONE.").replace("[", "").replace("]", "").replace(", ", "\n")
                    );
            window.setVisible(true);
        }
    }

    /**
     * Generates and stores the current parameter collection to a file.
     *
     * @param params
     */
    private void generateNstoreParams(String[] params) {
        ParCollection paramsStore = new ParCollection(params);
        paramsStore.complete();
        ArrayList<String> list = new ArrayList<String>(2);
        list.add(paramsStore.parStrPlain().replace('\n', ' '));
        list.add(new Date(System.currentTimeMillis()).toString());
       
        try {
            StaticMethods.speichereTextAusArray(
                    ".",
                    "parameters.txt",
                    list,
                    paramsStore);
            this.setTitle("Parameters stored.");
        } catch (Exception e1) {
            StaticMethods.logWarning(
                    "Parameters not stored to 'parameters.txt': "
                            + e1.toString(), this.pars);
            this.setTitle("Parameters COULD NOT be stored (see log for error description).");
        }
    }

    /**
     * Shows a dialog that allows to change all parameters to there standard
     * values.
     */
    private void resetParameters() {
        final String[] parString = new String[] {
                ConstantsStatistics.MASTER_SCHEDULER_PAR_NAME, this.pars.getMasterSchedulerID(),
                ConstantsStatistics.PLUGINS_PAR_NAME, this.pars.getParValueArrayListString(ConstantsStatistics.PLUGINS_PAR_NAME).toString()};
//        System.out.println(Arrays.deepToString(parString));
//        System.exit(0);
       
        final ParCollection params = new ParCollection(parString);
        params.complete();
        String unterschiede = "\n";
        for (final SingleParameter p : params.getAllPars()) {
//            if (!"Plugins".equalsIgnoreCase(p.getParameterCategory())) {
                if (params.getParValue(p.getParameterName()) == null) {
                    if (pars.getParValue(p.getParameterName()) != null) {
                        unterschiede += p.getParameterName() + ": "
                                + pars.getParValue(p.getParameterName())
                                + " => "
                                + params.getParValue(p.getParameterName())
                                + ";\n";
                    }
                } else if (!params.getParValue(p.getParameterName()).equals(
                        pars.getParValue(p.getParameterName()))) {
                    unterschiede += p.getParameterName() + ": "
                            + pars.getParValue(p.getParameterName())
                            + " => " + params.getParValue(p.getParameterName())
                            + ";\n";
                }
//            }
        }

        GeneralDialog dia;
        dia = new GeneralDialog(
                this,
                null,
                RESET_PARAMETERS_STRING,
                GeneralDialog.YES_NO,
                "Do you really want to reset all parameters to their standard values (except parameters in the 'Plugins' category)? "
                        + " This concerns the following parameters:\n"
                        + unterschiede);
        dia.setVisible(true);

        if (dia.getResult().equals(GeneralDialog.YES)) {
            dispose();
            Starter.main(params.getAllParsArrayView());
        }
       
        return;
    }

    public void listAllPlugins() {
        final ArrayList<String> pluginIds = new ArrayList<String>(PluginFactory.STORED_PLUGINS.size());
        Plugin<?> testObject;
        for (final Class<Plugin<?>> c : PluginFactory.STORED_PLUGINS) {
            try {
                testObject = c.newInstance();

                // Print out Plugins + Generalizations
                pluginIds.add(
                        testObject.id() + "\t\t\t(" + c.getPackage() + ")");
//                                    + "\n     Generalizations: "
//                                    + Reflections.getClassesWithParameters(
//                                            Reflections.getGeneralizations(c))
//                                            .toString().replace(",", ";"));
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }
        Collections.sort(pluginIds);
        final GeneralDialog dia = new GeneralDialog(
                this,
                "",
                "Available plugins and master schedulers",
                GeneralDialog.OK_BUTT,
                pluginIds.toString().replace("[", "").replace("]", "").replace(", ", "\n"),
                20,
                100,
                false);
        dia.resetTextBoxCaret();
        dia.setVisible(true);
    }

    private int parsCount() {
        int gesNum = 1;
       
        for (int i = 0; i < parFelder.length; i++) {
            if (!parFelder[i].isVisible()
                    && !isFixedCheckBoxen[i].isSelected()) {
                gesNum *= parFelder[i].getText().split("\n").length;
            }
        }
       
        return gesNum;
    }
   
    /**
     * Listener.
     *
     * @param arg0
     *            Event.
     */
    @Override
    public void mouseClicked(final MouseEvent arg0) {
        if (arg0.getSource().equals(tipp)) {
            tipp.setVisible(false);
            return;
        }
       
        JTextArea aktText = null;
        String rnd = "";
        int gesNum = 1;
        String textV, textN, neuText = "";
        int carPos;

        if (arg0.getSource().getClass().equals(JList.class)) {
            if (arg0.getButton() == 3) {
                invertiereAlleKat();
            }

            return;
        }

        if ((arg0.getButton() == 3) && (arg0.getClickCount() >= 2)) {
            for (int i = 0; i < parFelder.length; i++) {
                if (!parFelder[i].isVisible()
                        && !isFixedCheckBoxen[i].isSelected()) {
                    gesNum *= parFelder[i].getText().split("\n").length;
                }
                if (parFelder[i].isVisible()) {
                    setzeAktChanged();
                    isFixedCheckBoxen[i].setSelected(true);
                    aktText = parFelder[i];
                }
            }

            if (arg0.getClickCount() == 2) {
                try {
                    carPos = aktText.getCaretPosition();
                    textV = aktText.getText().substring(0, carPos);
                    textN = aktText.getText().split("\n")[0].substring(carPos);

                    if (textV.split("\n").length == 1) {
                        for (int i = 0; i < gesNum; i++) {
                            neuText +=
                                    textV
                                            + normZahl(i, gesNum - 1)
                                            + textN
                                            + "\n";
                        }

                        aktText.setText(neuText);
                    }
                } catch (final Exception e) {
                    StaticMethods.log(
                            StaticMethods.LOG_OUTPUT,
                            "Nummerierung nicht erfolgreich.",
                            pars);
                }
            }

            if (arg0.getClickCount() >= 3) {
                for (int i = 0; i < gesNum; i++) {
                    rnd += "" + (new Random()).nextLong() + "\n";
                }

                aktText.setText(rnd);
            }
        }
       
      if (arg0.getClickCount() > 1) {
        this.parFelder[paramListe.getSelectedRow()].requestFocus();
        this.parFelder[paramListe.getSelectedRow()].selectAll();
      }
   }

    /**
     * @param i    Der aktuelle Wert.
     * @param max  Der maximale Wert.
     *
     * @return normZahl(3, 100) ==> 003
     */
    private String normZahl(final int i, final int max) {
        final String strI = "" + i, strMax = "" + max;
        String nullen = "";

        for (int j = 0; j < strMax.length() - strI.length(); j++) {
            nullen += "0";
        }

        return nullen + i;
    }

    @Override public void mouseEntered(final MouseEvent arg0) {}
    @Override public void mouseExited(final MouseEvent arg0) {}
    @Override public void mousePressed(final MouseEvent arg0) {}
    @Override public void mouseReleased(final MouseEvent arg0) {}
    @Override public void keyPressed(final KeyEvent e) {}

    @Override
    public void keyReleased(final KeyEvent e) {
        pluginsAkt = ((JTextArea) e.getSource()).getText().replace('\n',
                ',').split(",");
    }

    /**
     * Setzte den num-ten Listeneintrag auf "checked".
     *
     * @param num  Der zu markierende Eintrag.
     */
    private void setzeChanged(final int num) {
        if (num < 0) { return; }

        final SingleParameter p = (SingleParameter) paramListe.getModel().getValueAt(num, Starter.SINGLE_PAR_COLUMN);

        p.setChanged();
        paramListe.repaint();
    }

    /**
     * Setzt, dass das aktuelle Element verändert wurde.
     */
    private void setzeAktChanged() {
        setzeChanged(paramListe.getSelectedRow());
    }

    /**
     * Setzt, dass alle Elemente die Kategorieanzeige umschalten.
     */
    private void invertiereAlleKat() {
        SingleParameter p;

        for (int i = 0; i < paramListe.getRowCount(); i++) {
            p = (SingleParameter) paramListe.getModel().getValueAt(i, Starter.SINGLE_PAR_COLUMN);
            p.setShowCategory((p.isShowCategory() + 1) % 4);
        }

        paramListe.repaint();
    }

    @Override
    public void keyTyped(final KeyEvent e) {
        setzeAktChanged();
    }

    /**
     * Aktuelle Plugins.
     */
    private String[] pluginsOld;

    /**
     * Aktuelle Plugins.
     */
    private String[] pluginsAkt;

    /**
     * Plugins old als String.
     */
    private String pluginsOldStr;

    /**
     * @param eins  Erste String-Liste.
     * @param zwei  Zweite String-Liste.
     *
     * @return Ob die Anzahl der generischen Parameter der symmetrischen
     *         Differenz der Listen leer ist. Es wird NICHT case-sensitive
     *         geprüft.
     */
    private boolean aequiStrLists(
            final String[] eins,
            final String[] zwei) {
        boolean gefunden;

        if (eins == zwei) { return true; }
        if ((eins == null) || (zwei == null)) { return false; }

        for (final String s1 : eins) {
            if (PluginFactory.existsPlugin(s1)) {
                final Plugin<?> p1 = PluginFactory.getKonstPlug(s1, null);
                gefunden = false;

                if ((p1.getParameters() != null)
                        && (p1.getParameters().size() > 0)) {
                    for (final String s2 : zwei) {
                        if (s1.equalsIgnoreCase(s2)) {
                            gefunden = true;
                            break;
                        }
                    }

                    if (!gefunden) { return false; }
                }
            }
        }

        for (final String s2 : zwei) {
            if (PluginFactory.existsPlugin(s2)) {
                final Plugin<?> p2 = PluginFactory.getKonstPlug(s2, null);
                gefunden = false;

                if ((p2.getParameters() != null)
                        && (p2.getParameters().size() > 0)) {
                    for (final String s1 : eins) {
                        if (s2.equalsIgnoreCase(s1)) {
                            gefunden = true;
                            break;
                        }
                    }

                    if (!gefunden) { return false; }
                }
            }
        }

        return true;
    }

    @Override
    public void focusGained(final FocusEvent arg0) {
        if (arg0.getSource().equals(tipp)) {
            return;
        }

        if ((paramListe.getValueAt(paramListe.getSelectedRow(), SINGLE_PAR_COLUMN) != null)
                && (((SingleParameter) paramListe.getValueAt(paramListe.getSelectedRow(), SINGLE_PAR_COLUMN)).getParameterName()
                        .equalsIgnoreCase(eas.statistics.ConstantsStatistics.PLUGINS_PAR_NAME)
                || ((SingleParameter) paramListe.getValueAt(paramListe.getSelectedRow(), SINGLE_PAR_COLUMN)).getParameterName()
                        .equalsIgnoreCase(eas.statistics.ConstantsStatistics.MASTER_SCHEDULER_PAR_NAME))) {
            buttons.setEnabled(false);
            for (final JCheckBox c : isFixedCheckBoxen) {
                c.setEnabled(false);
            }
            buttons.setBackground(Color.gray);
            pluginsOld = parFelder[paramListe.getSelectedRow()].getText().replace('\n', ',').split(",");
            pluginsAkt = pluginsOld;
            pluginsOldStr = parFelder[paramListe.getSelectedRow()].getText();
        }
        paramListe.setEnabled(false);
    }

    @Override
    public void focusLost(final FocusEvent arg0) {
        if (arg0.getSource().equals(tipp)) {
            tipp.setVisible(false);
            return;
        }

        // Wenn Parameter leere Strings als Wert erhalten.
        final String[] werte = ((JTextArea) arg0.getSource()).getText().split("\n");
        for (final String s : werte) {
            if ((s == null) || s.equals("")) {
                final GeneralDialog dia = new GeneralDialog(
                        this,
                        "ACHTUNG: Im Parameterwert-Feld ist ein Parameter "
                                + "mit einem leeren String assoziiert, was nicht "
                                + "erlaubt ist.",
                        "ACHTUNG: Leerer Parameterwert!",
                        GeneralDialog.OK_BUTT,
                        null);
                dia.setVisible(true);
            }
        }

        // Wenn ein Leerzeichen im Text auftaucht.
        String text = ((JTextArea) arg0.getSource()).getText();
        if (text.indexOf(' ') >= 0) {
            if (text.charAt(0) != '"' || text.charAt(text.length() - 1) != '"') {
                final GeneralDialog dia = new GeneralDialog(
                        this,
                        "CAUTION: A parameter value contains a white space. "
                                + "Parameter values must not contain white spaces except "
                                + "if they are enclosed in quotation marks ' \" '.",
                        "CAUTION: White spaces in parameter value!",
                        GeneralDialog.OK_BUTT,
                        null);
                dia.setVisible(true);
            }
        }

        // Wenn Plugins verändert wurden.
        if ((paramListe.getValueAt(paramListe.getSelectedRow(), SINGLE_PAR_COLUMN) != null)
                && (((SingleParameter) paramListe.getValueAt(paramListe.getSelectedRow(), SINGLE_PAR_COLUMN)).getParameterName()
                        .equalsIgnoreCase(eas.statistics.ConstantsStatistics.PLUGINS_PAR_NAME)
                || ((SingleParameter) paramListe.getValueAt(paramListe.getSelectedRow(), SINGLE_PAR_COLUMN)).getParameterName()
                        .equalsIgnoreCase(eas.statistics.ConstantsStatistics.MASTER_SCHEDULER_PAR_NAME))) {

            // Wenn Plugins benötigt werden und fehlen.
            final LinkedList<String> plugListe = new LinkedList<String>();
            for (final String s : pluginsAkt) {
                plugListe.add(s);
            }
            for (final String s : plugListe) {
                if (PluginFactory.getKonstPlug(s, null) != null) {
                    final List<String> reqListe = PluginFactory.getKonstPlug(s, null).getRequiredPlugins();
                    if (reqListe != null) {
                        if (!plugListe.containsAll(reqListe)) {
//                            final AllgemeinerDialog dia = new AllgemeinerDialog(
//                                    this,
//                                    null,
//                                    "Mindestens eines der folgenden benötigten"
//                                            + " Plugins werden nicht generiert.",
//                                    AllgemeinerDialog.OK_BUTT, reqListe
//                                            .toString());

//                            dia.setVisible(true);
                            break;
                        }
                    }
                }
            }

            // Wenn generische Parameter sich verändert haben (und falls NICHT aus der GUI heraus die Eingabe abgebrochen wurde!).
            if (!cancelledFromIntelligentInput && !aequiStrLists(pluginsOld, pluginsAkt)) {
                final GeneralDialog dia = new GeneralDialog(
                        this,
                        "Achtung! Die Plugins wurden so verändert, dass "
                                + "die Parameterliste geändert werden muss. Wenn die "
                                + "Änderungen beibehalten werden sollen,\n"
                                + "muss das Programm neu gestartet werden. "
                                + "Dabei werden alle generierten JoSchKa-Ausgaben "
                                + "zurückgesetzt.\n \n"
                                + "Sollen die Änderungen wirklich beibehalten "
                                + "und das Programm neu gestartet werden?\n \n \n"
                                + "(Hinweis: Bereits generierte Ausgaben können "
                                + "verwendet werden, indem die Plugins manuell in "
                                + "der Textdatei verändert werden. \nIn dem Fall muss "
                                + "jetzt 'Nein' angegeben werden!)",
                        "Plugins wurden verändert",
                        GeneralDialog.YES_NO,
                        null);
//                dia.setVisible(true);
                dia.setResult(GeneralDialog.YES);
               
                if (dia.getResult().equals(GeneralDialog.NO)) {
                    ((JTextArea) arg0.getSource()).setText(pluginsOldStr);
                } else if (dia.getResult().equals(GeneralDialog.YES)) {
                    final String[] params = generiereErstenSatz();
                    ParCollection paramsComplete = new ParCollection(params);
                    paramsComplete.complete();
                    dispose();
                    Starter.main(paramsComplete.getAllParsArrayView());
                }
            }
        }

        buttons.setBackground(hintergrund);
        buttons.setEnabled(true);
        paramListe.setEnabled(true);
        for (final JCheckBox c : isFixedCheckBoxen) {
            c.setEnabled(true);
        }
    }

    @Override public void componentHidden(ComponentEvent arg0) {}
    @Override public void componentMoved(ComponentEvent arg0) {componentResized(arg0);}
    @Override public void componentShown(ComponentEvent arg0) {}

    @Override
    public void componentResized(ComponentEvent arg0) {
        StaticMethods.speichereTextDatei(
                ".",
                "starterconf.dat",
                "" + this.getWidth() + "/" + this.getHeight() + "\n" + this.getLocation().x + "/" + this.getLocation().y,
                this.pars);
    }

  @Override public void mouseDragged(MouseEvent e) {}

  @Override
  public void mouseMoved(MouseEvent e) {
      /*
       * The following functionality just sets the mouse pointer to hand
       * mode if an intelligent input is available. However, the given
       * implementation is so crappy that its not worth the little gain.
       * Maybe I will be willing TODO it some time in future...
       */
     
//    SingleParameter par = (SingleParameter) paramListe.getValueAt(paramListe.rowAtPoint(e.getPoint()), Starter.SINGLE_PAR_COLUMN);
//    if (paramListe.isEnabled() && (par.getIntelligentInput(null, null) != null)) {
//      this.setCursor(new Cursor(Cursor.HAND_CURSOR));
//    } else {
//      this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
//    }
  }

    /**
     * Generiert nur den ersten Parametersatz, also ohne Kombinationen von
     * Parametern.
     *
     * @return Der erste Parametersatz.
     */
    private String[] generiereErstenSatz() {
        final String[] liste = new String[paramListe.getRowCount() * 2];

        for (int i = 0; i < paramListe.getRowCount(); i++) {
            liste[2 * i] = ((SingleParameter) paramListe.getValueAt(i, SINGLE_PAR_COLUMN)).getParameterName();
            liste[2 * i + 1] = parFelder[i].getText();
        }

        return liste;
    }

    private static JDialog tipp;
    private static JLabel tippLabel;

    /**
     * Starter GUI.
     *
     * @param args  Command line parameters for creating the parameter collection.
     */
    public static void main(final String[] args) {
        // First set of parameters read from command line (ignoring plugins).
        String[] args2 = new String[args.length];
        for (int i = 0; i < args.length; i++) {
            args2[i] = args[i];
           
            if (args[i].equalsIgnoreCase(ConstantsStatistics.MASTER_SCHEDULER_PAR_NAME)
                    || args[i].equalsIgnoreCase(ConstantsStatistics.PLUGINS_PAR_NAME)) {
                if (args2.length > i + 1) {
                    args2[i + 1] = new NullPlugin().id();
                    i++;
                }
            }
        }
        ParCollection prematureParams = new ParCollection(args2);
        prematureParams.complete();
        GlobalVariables.setPrematureParameters(prematureParams);
       
        ParCollection params = new ParCollection(new String[] {});
        String storeTime = null;
       
        // Take parameters from file.
        try {
            List<String> argsFileRaw = StaticMethods.liesTextArray(".", "parameters.txt", null);
            String[] argsFile = StaticMethods.processStringAsCommandLineParameters(argsFileRaw.get(0));
            params.overwriteParameterList(argsFile);
            storeTime = argsFileRaw.get(1);
        } catch (Exception e) {
            StaticMethods.logInfo(
                    "Parameters could not be read from file 'parameters.txt': "
                        + e.toString(), params);
        }
       
        // Take parameters from command line.
        int commandLine = params.overwriteParameterList(args);
       
        params.regGenParams();
//        params = new ParCollection(params);

        // Take standard values for still not initialized parameters.
        params.complete();

        // Set premature parameters to final state.
        GlobalVariables.setPrematureParameters(params);
       
        if (!params.getStartImmediately()) {
            final Starter starter = new Starter(params);
           
            starter.addComponentListener(starter);
            starter.invertiereAlleKat();
            starter.invertiereAlleKat();
           
            if (storeTime != null) {
                starter.setTitle(
                        "Parameters loaded from file 'parameters.txt' (stored on "
                        + storeTime + ");"
                        + " #CommandLinePars = " + commandLine + ".");
            }
           
            // Tipp.
            if (tipp == null) {
                tipp = new JDialog(starter);
                tippLabel = new JLabel();
                tippLabel.setFont(new Font("", Font.BOLD, 20));
                tippLabel.setText("  Select a master scheduler and plugins to get started...  ");
//                label.setBorder(BorderFactory.createLineBorder(Color.blue, 10));
                tippLabel.setBorder(BorderFactory.createLineBorder(Color.blue, 10, true));
                tippLabel.setBackground(Color.orange);
                tippLabel.setForeground(Color.blue);
                tipp.setBackground(Color.orange);
                tipp.setLocation(100, 120);
                tipp.setSize(570, 50);
                tipp.getContentPane().add(tippLabel);
                tipp.setUndecorated(true);
                tipp.setVisible(true);
                tipp.setAlwaysOnTop(true);
                tipp.addFocusListener(starter);
                tipp.addMouseListener(starter);
            }
        } else {
//            params.setMaster(params.getStartImmediately());
            SimulationStarter.main(params.getAllParsArrayView());
        }
       
    }
   
    private void storePDF(File target, boolean shapes, int xWidth, int yWidth) {
        this.setBackground(Color.white);
       
        Document document = new Document();
        try {
           PdfWriter writer;
           if (shapes)
              writer = PdfWriter.getInstance(document,
                 new FileOutputStream(target));
           else
              writer = PdfWriter.getInstance(document,
                 new FileOutputStream(target));
           document.open();
           PdfContentByte cb = writer.getDirectContent();
           PdfTemplate tp = cb.createTemplate(xWidth, yWidth);
           Graphics2D g2;
           if (shapes) {
              g2 = tp.createGraphicsShapes(xWidth, yWidth);
           } else {
              g2 = tp.createGraphics(xWidth, yWidth);
           }
           this.print(g2);
           g2.dispose();
           cb.addTemplate(tp, 0, -200);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        document.close();
    }
   
    private void addMenu() {
        JMenuItem fileItem1 = new JMenuItem(EXIT_STRING); // File
        JMenuItem fileItem2 = new JMenuItem(LOAD_STORED_SIMULATION);
        JMenuItem fileItem3 = new JMenuItem(STORE_PDF_OF_STARTER);

        JMenuItem pluginsFind = new JMenuItem(FIND_NEW_PLUGINS_STRING); // Plugin
        JMenuItem pluginsExport = new JMenuItem(EXPORT_PLUGINS_STRING);
        JMenuItem pluginsImport = new JMenuItem(IMPORT_PLUGINS_STRING);
        JMenuItem pluginsDelete = new JMenuItem(DELETE_UNSELECTED_PLUGINS_STRING);
       
        JMenuItem runSimulation = new JMenuItem(START_SIMULATION_STRING); // Run
       
        JMenuItem marbItem1 = new JMenuItem(START_MARB_BUILDER_STRING);
        JMenuItem marbItem2 = new JMenuItem(START_XML_TRACE_VIEWER_STRING);
        JMenuItem marbItem3 = new JMenuItem(FITNESS_STATISTICS_XML_STRING);
        JMenuItem marbItem4 = new JMenuItem(COMBINE_STATISTICS_XML_STRING);
        JMenuItem arrowmasterItem5 = new JMenuItem(START_ARROW_MASTER_STRING);

        if (starterMenuListener == null) {
            starterMenuListener = new StarterMenuListener(this, pars);
        }
        fileItem1.addActionListener(starterMenuListener);
        fileItem2.addActionListener(starterMenuListener);
        fileItem3.addActionListener(starterMenuListener);
        pluginsFind.addActionListener(starterMenuListener);
        pluginsExport.addActionListener(starterMenuListener);
        pluginsImport.addActionListener(starterMenuListener);
        runSimulation.addActionListener(starterMenuListener);
        marbItem1.addActionListener(starterMenuListener);
        marbItem2.addActionListener(starterMenuListener);
        marbItem3.addActionListener(starterMenuListener);
        marbItem4.addActionListener(starterMenuListener);
        arrowmasterItem5.addActionListener(starterMenuListener);
        pluginsDelete.addActionListener(starterMenuListener);
       
        // File menu.
        JMenuBar menubar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
       
        fileMenu.add(fileItem2);
        fileMenu.add(fileItem3);
        fileMenu.add(fileItem1);
        menubar.add(fileMenu);
       
        // Plugin menu.
        JMenu pluginMenu = new JMenu("Plugins");
        pluginMenu.add(pluginsFind);
        pluginMenu.addSeparator();
        pluginMenu.add(pluginsImport);
        pluginMenu.add(pluginsExport);
        pluginMenu.add(pluginsDelete);
        menubar.add(pluginMenu);
       
        // Run menu.
        JMenu runMenu = new JMenu("Run");
        JMenu subMenuEA = new JMenu("MARB");

        menubar.add(runMenu);
       
        subMenuEA.add(marbItem1);
        subMenuEA.addSeparator();
        subMenuEA.add(marbItem2);
        subMenuEA.add(marbItem3);
        subMenuEA.add(marbItem4);
       
        runMenu.add(runSimulation);
        runMenu.addSeparator();
        runMenu.add(subMenuEA);
        runMenu.add(arrowmasterItem5);

        this.setJMenuBar(menubar);
    }
   
    private StarterMenuListener starterMenuListener;
}
// Ende gut, alles gut.
TOP

Related Classes of eas.startSetup.Starter

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.