org.qcc.modules.learningpalette.OptionsPlugin.LearningPalettePanel.java Source code

Java tutorial

Introduction

Here is the source code for org.qcc.modules.learningpalette.OptionsPlugin.LearningPalettePanel.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.qcc.modules.learningpalette.OptionsPlugin;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.FileUtils;
import org.qcc.modules.learningpalette.Customizer.CustomizerControl;
import org.qcc.modules.learningpalette.Customizer.CustomizerExpressionField;
import org.qcc.modules.learningpalette.Customizer.CustomizerTextField;
import org.qcc.modules.learningpalette.Customizer.CustomizerVariableField;
import org.qcc.modules.learningpalette.PaletteItem;
import org.qcc.modules.learningpalette.PaletteManager;
import org.qcc.modules.learningpalette.SourceFilePaletteFactory;
import org.w3c.dom.Element;

final class LearningPalettePanel extends javax.swing.JPanel {

    private final LearningPaletteOptionsPanelController controller;

    private PaletteItem selectedPaletteItem;
    ArrayList<String> languageList = new ArrayList<>();
    Map<String, String> codeMapping;
    boolean loadingLanguage = false;
    String currentFileName;
    ArrayList<CustomizerControl> customizerControls = new ArrayList<>();
    ArrayList<PaletteItem> paletteItems = new ArrayList<>();

    LearningPalettePanel(LearningPaletteOptionsPanelController controller) {
        this.controller = controller;
        initComponents();
        // TODO listen to changes in form fields and call controller.changed()
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pItemCombo = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        createNewButton = new javax.swing.JButton();
        itemNameText = new javax.swing.JTextField();
        paletteItemName = new javax.swing.JLabel();
        descriptionText = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        codeText = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        languageCombo = new javax.swing.JComboBox();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        customizerList = new javax.swing.JList();
        moveUpCustomizer = new javax.swing.JButton();
        moveDownCustomizer = new javax.swing.JButton();
        deleteSelectedCustomizer = new javax.swing.JButton();
        customizerType = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        customizerReplace = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        customizerLabel = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        addCustomizer = new javax.swing.JButton();
        deleteSelectedItem = new javax.swing.JButton();

        pItemCombo.setEnabled(false);
        pItemCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pItemComboActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(createNewButton, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.createNewButton.text")); // NOI18N
        createNewButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createNewButtonActionPerformed(evt);
            }
        });

        itemNameText.setEditable(false);
        itemNameText.setText(org.openide.util.NbBundle.getMessage(LearningPalettePanel.class,
                "LearningPalettePanel.itemNameText.text")); // NOI18N
        itemNameText.setEnabled(false);
        itemNameText.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemNameTextActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(paletteItemName, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.paletteItemName.text")); // NOI18N

        descriptionText.setEditable(false);
        descriptionText.setText(org.openide.util.NbBundle.getMessage(LearningPalettePanel.class,
                "LearningPalettePanel.descriptionText.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.jLabel2.text")); // NOI18N

        codeText.setEditable(false);
        codeText.setColumns(20);
        codeText.setRows(5);
        codeText.setEnabled(false);
        jScrollPane1.setViewportView(codeText);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.jLabel3.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.jLabel4.text")); // NOI18N

        languageCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "JAVA", "CPP" }));
        languageCombo.setEnabled(false);
        languageCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                languageComboActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(saveButton, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.saveButton.text")); // NOI18N
        saveButton.setEnabled(false);
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.cancelButton.text")); // NOI18N
        cancelButton.setToolTipText(org.openide.util.NbBundle.getMessage(LearningPalettePanel.class,
                "LearningPalettePanel.cancelButton.toolTipText")); // NOI18N
        cancelButton.setDefaultCapable(false);
        cancelButton.setEnabled(false);
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.jLabel5.text")); // NOI18N

        customizerList.setEnabled(false);
        jScrollPane2.setViewportView(customizerList);

        org.openide.awt.Mnemonics.setLocalizedText(moveUpCustomizer, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.moveUpCustomizer.text")); // NOI18N
        moveUpCustomizer.setEnabled(false);
        moveUpCustomizer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                moveUpCustomizerActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(moveDownCustomizer, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.moveDownCustomizer.text")); // NOI18N
        moveDownCustomizer.setToolTipText(org.openide.util.NbBundle.getMessage(LearningPalettePanel.class,
                "LearningPalettePanel.moveDownCustomizer.toolTipText")); // NOI18N
        moveDownCustomizer.setEnabled(false);
        moveDownCustomizer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                moveDownCustomizerActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(deleteSelectedCustomizer, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.deleteSelectedCustomizer.text")); // NOI18N
        deleteSelectedCustomizer.setEnabled(false);
        deleteSelectedCustomizer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteSelectedCustomizerActionPerformed(evt);
            }
        });

        customizerType
                .setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Text", "Expression", "Variable" }));
        customizerType.setEnabled(false);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel6, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.jLabel6.text")); // NOI18N

        customizerReplace.setEditable(false);
        customizerReplace.setText(org.openide.util.NbBundle.getMessage(LearningPalettePanel.class,
                "LearningPalettePanel.customizerReplace.text")); // NOI18N
        customizerReplace.setEnabled(false);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel7, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.jLabel7.text")); // NOI18N
        jLabel7.setToolTipText(org.openide.util.NbBundle.getMessage(LearningPalettePanel.class,
                "LearningPalettePanel.jLabel7.toolTipText")); // NOI18N

        customizerLabel.setEditable(false);
        customizerLabel.setText(org.openide.util.NbBundle.getMessage(LearningPalettePanel.class,
                "LearningPalettePanel.customizerLabel.text")); // NOI18N
        customizerLabel.setEnabled(false);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel8, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.jLabel8.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(addCustomizer, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.addCustomizer.text")); // NOI18N
        addCustomizer.setEnabled(false);
        addCustomizer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addCustomizerActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(deleteSelectedItem, org.openide.util.NbBundle
                .getMessage(LearningPalettePanel.class, "LearningPalettePanel.deleteSelectedItem.text")); // NOI18N
        deleteSelectedItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteSelectedItemActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 70,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel4).addComponent(jLabel3).addComponent(jLabel1)
                                .addComponent(paletteItemName).addComponent(jLabel5))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(languageCombo, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        132, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGroup(layout.createSequentialGroup().addGroup(layout
                                                        .createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.TRAILING, false)
                                                        .addComponent(descriptionText,
                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(pItemCombo,
                                                                javax.swing.GroupLayout.Alignment.LEADING, 0, 491,
                                                                Short.MAX_VALUE)
                                                        .addComponent(itemNameText,
                                                                javax.swing.GroupLayout.Alignment.LEADING,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE, 133,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                                        .addPreferredGap(
                                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addGroup(layout
                                                                .createParallelGroup(
                                                                        javax.swing.GroupLayout.Alignment.LEADING,
                                                                        false)
                                                                .addComponent(createNewButton,
                                                                        javax.swing.GroupLayout.DEFAULT_SIZE, 116,
                                                                        Short.MAX_VALUE)
                                                                .addComponent(deleteSelectedItem,
                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        Short.MAX_VALUE)))))
                                .addGroup(layout.createSequentialGroup().addGap(10, 10, 10).addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jScrollPane1)
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        168, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addGroup(layout
                                                        .createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addGroup(layout.createSequentialGroup().addGroup(layout
                                                                .createParallelGroup(
                                                                        javax.swing.GroupLayout.Alignment.TRAILING,
                                                                        false)
                                                                .addComponent(moveDownCustomizer,
                                                                        javax.swing.GroupLayout.Alignment.LEADING,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 107,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(deleteSelectedCustomizer,
                                                                        javax.swing.GroupLayout.Alignment.LEADING)
                                                                .addComponent(moveUpCustomizer,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 107,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        Short.MAX_VALUE)
                                                                .addGroup(layout.createParallelGroup(
                                                                        javax.swing.GroupLayout.Alignment.LEADING,
                                                                        false)
                                                                        .addGroup(layout.createSequentialGroup()
                                                                                .addComponent(cancelButton,
                                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                                        Short.MAX_VALUE)
                                                                                .addPreferredGap(
                                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                                .addComponent(saveButton,
                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                        99,
                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                                        .addComponent(addCustomizer,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                237,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                                                        .addGroup(layout.createSequentialGroup()
                                                                .addGap(158, 158, 158)
                                                                .addGroup(layout.createParallelGroup(
                                                                        javax.swing.GroupLayout.Alignment.TRAILING)
                                                                        .addComponent(jLabel8).addComponent(jLabel7)
                                                                        .addComponent(jLabel6))
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addGroup(layout.createParallelGroup(
                                                                        javax.swing.GroupLayout.Alignment.LEADING,
                                                                        false)
                                                                        .addComponent(customizerLabel,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                238,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                        .addComponent(customizerReplace,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                238,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                        .addComponent(customizerType,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                238,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE))))))))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(pItemCombo, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1).addComponent(createNewButton))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(itemNameText, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(paletteItemName).addComponent(deleteSelectedItem))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(descriptionText, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel4).addComponent(languageCombo,
                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(12, 12, 12)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel3).addComponent(jScrollPane1,
                                        javax.swing.GroupLayout.PREFERRED_SIZE, 117,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup().addGap(8, 8, 8).addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 102,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel5)))
                                .addGroup(layout.createSequentialGroup().addGap(6, 6, 6)
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(moveUpCustomizer).addComponent(jLabel6).addComponent(
                                                        customizerType, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(moveDownCustomizer)
                                                .addGroup(layout
                                                        .createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(customizerReplace,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addComponent(jLabel7)))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(customizerLabel,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(jLabel8))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(addCustomizer).addComponent(deleteSelectedCustomizer))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(saveButton).addComponent(cancelButton,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 23,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
    }// </editor-fold>//GEN-END:initComponents

    private void createNewButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createNewButtonActionPerformed

        if (selectedPaletteItem == null) {
            createNewPaletteItem();
        } else {
            //TODO: Detect if existing item needs to be saved.
            createNewPaletteItem();
        }
    }//GEN-LAST:event_createNewButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed

        //First validate the input:
        //Palette Item name does not already exist, for one
        for (int i = 0; i < pItemCombo.getItemCount(); i++) {
            PaletteItem compare = (PaletteItem) pItemCombo.getItemAt(i);
            if (compare != selectedPaletteItem
                    && compare.getItemName().trim().equals(this.itemNameText.getText().trim())) {
                JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this),
                        "A palette item already exists with that name, choose a new name.");
                return;
            }
        }
        //That user has not started to type a customizer in and failed ot add it.
        //Custom button text
        if (customizerLabel.getText().trim().length() > 0 || customizerReplace.getText().trim().length() > 0) {
            Object[] options = { "Yes", "No" };
            int n = JOptionPane.showOptionDialog(SwingUtilities.getWindowAncestor(this),
                    "You have started to add a customizer, but \n" + "have not clicked save, continue?",
                    "Are you sure?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
                    options[1]);

            if (n != 0) {
                return;
            }
        }

        try {
            //Generate XML Document
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // root elements
            org.w3c.dom.Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("PaletteItem");
            doc.appendChild(rootElement);

            Element category = doc.createElement("Category");
            category.setTextContent("User Defined");
            rootElement.appendChild(category);

            Element displayName = doc.createElement("DisplayName");
            displayName.setTextContent(this.itemNameText.getText().trim());
            rootElement.appendChild(displayName);

            Element toolTip = doc.createElement("Tooltip");
            toolTip.setTextContent(this.descriptionText.getText());
            rootElement.appendChild(toolTip);

            Element languagesParent = doc.createElement("Languages");

            for (String language : languageList) {
                String outputMapping;
                if (codeMapping.containsKey(language) == false) {
                    outputMapping = "";
                } else {
                    outputMapping = codeMapping.get(language);
                }

                Element languageParent = doc.createElement("Language");
                languageParent.setAttribute("id", language);
                Element codeTemplate = doc.createElement("codeTemplate");
                codeTemplate.setTextContent(outputMapping);
                languageParent.appendChild(codeTemplate);
                languagesParent.appendChild(languageParent);

            }
            rootElement.appendChild(languagesParent);

            //org.qcc.modules.learningpalette.LP_BasicInput.java
            Element paletteClass = doc.createElement("PaletteLogicClass");
            paletteClass.setTextContent("org.qcc.modules.learningpalette.LP_BasicInput");
            rootElement.appendChild(paletteClass);

            //Create Customizer (For later use)
            Element customizerParent = doc.createElement("Customizer");
            rootElement.appendChild(customizerParent);

            for (CustomizerControl control : customizerControls) {
                Element customizerItem = doc.createElement("Item");
                customizerItem.setAttribute("type", control.getType());
                customizerItem.setAttribute("name", control.getName());
                customizerItem.setAttribute("label", control.getLabel());
                customizerItem.setAttribute("value", "");
                customizerParent.appendChild(customizerItem);
            }

            //Create file name 
            if (currentFileName == null) {
                String fileName = "UserDefined_";

                //Random number
                int uniqueID = randInt(0, 9999999);
                //Random letter
                char c = (char) randInt(65, 90);

                currentFileName = fileName + uniqueID + c + ".xml";
            }

            //Get the directory to save to.
            String saveDirectory = System.getProperty("user.dir") + "\\LearningPaletteXML";

            //Make the directory if necessary
            File newDirectory = new File(saveDirectory);
            if (!newDirectory.exists()) {
                if (newDirectory.mkdir()) {
                    System.out.println("Directory is created!");
                } else {
                    System.out.println("Failed to create directory!");
                }
            }

            //Save the file
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            Result output = new StreamResult(new File(saveDirectory + "\\" + currentFileName));
            Source input = new DOMSource(doc);
            transformer.transform(input, output);

            loadPaletteItems((this.itemNameText.getText()));

            //Now reload the form with the saved list of palette items.
            //pItemCombo.revalidate();
            //pItemCombo.repaint();
        } catch (Exception ex) {
            //TODO: Exception handling.
            System.out.println(ex.getMessage());
        }

    }//GEN-LAST:event_saveButtonActionPerformed

    public static int randInt(int min, int max) {

        // NOTE: Usually this should be a field rather than a method
        // variable so that it is not re-seeded every call.
        Random rand = new Random();

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        int randomNum = rand.nextInt((max - min) + 1) + min;

        return randomNum;
    }

    private void languageComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_languageComboActionPerformed
        loadingLanguage = true;
        String selectedLanguage = languageCombo.getSelectedItem().toString();

        String newCode;
        if (codeMapping.containsKey(selectedLanguage)) {
            newCode = codeMapping.get(selectedLanguage);
        } else {
            newCode = "";
        }

        codeText.setText(newCode);

        loadingLanguage = false;
    }//GEN-LAST:event_languageComboActionPerformed

    private void addCustomizerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addCustomizerActionPerformed
        //TODO: Validation

        String customizerTypeField = this.customizerType.getSelectedItem().toString();

        String replacementText = this.customizerReplace.getText().trim();
        String customizerLabel = this.customizerLabel.getText().trim();
        String defaultValue = "";

        if (replacementText.equals("")) {
            JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this),
                    "Replacement text cannot be empty. This text will be replaced in your code.");
            return;
        }

        if (customizerLabel.equals("")) {
            JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this),
                    "Label text cannot be empty. This text will be displayed on your popup customizer.");
            return;
        }

        //Verify no duplicates exist and no substrings exist
        for (int i = 0; i < customizerControls.size(); i++) {
            CustomizerControl item = customizerControls.get(i);
            if (item.getName().equals(replacementText)) {
                JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this),
                        "This replacement customizer already exists, choose a new replacement text.");
                return;
            }

            if (replacementText.contains(item.getName()) || item.getName().contains(replacementText)) {
                JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this),
                        "The replacement text for this customizer contains a substring of an existing item, or vice versa.\nThis can cause conflicts when a replacement is performed. Use more specific, unique customizer replacement texts.\n\nFor example, '$ABC' could conflict with '$ABCD', as a replace performed on $ABC would also replace [$ABC]D.");
                return;
            }
        }

        if (customizerTypeField.equals("Text")) {
            CustomizerTextField newTextField = new CustomizerTextField(this.customizerReplace.getText(),
                    this.customizerLabel.getText(), "");
            customizerControls.add(newTextField);
        } else if (customizerTypeField.equals("Variable")) {
            CustomizerVariableField newVariableField = new CustomizerVariableField(this.customizerReplace.getText(),
                    this.customizerLabel.getText(), "");
            customizerControls.add(newVariableField);
        } else if (customizerTypeField.equals("Expression")) {
            CustomizerExpressionField newExpressionField = new CustomizerExpressionField(
                    this.customizerReplace.getText(), this.customizerLabel.getText(), "");
            customizerControls.add(newExpressionField);
        }

        this.customizerReplace.setText("");
        this.customizerLabel.setText("");

        updateCustomizers();

    }//GEN-LAST:event_addCustomizerActionPerformed

    private void moveUpCustomizerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveUpCustomizerActionPerformed
        //Move Up was clicked.

        int selectedIndex = customizerList.getSelectedIndex();
        if (selectedIndex == -1) {
            return;
        }

        if (selectedIndex > 0) {
            CustomizerControl toMove = customizerControls.get(selectedIndex);
            customizerControls.set(selectedIndex, customizerControls.get(selectedIndex - 1));
            customizerControls.set(selectedIndex - 1, toMove);

            //Redefine Customizers
            CustomizerControl[] customizers = new CustomizerControl[customizerControls.size()];
            customizers = customizerControls.toArray(new CustomizerControl[0]);
            customizerList.setListData(customizers);

            //Finally, reselect moved item.
            customizerList.setSelectedValue(toMove, true);
        }
    }//GEN-LAST:event_moveUpCustomizerActionPerformed

    private void moveDownCustomizerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveDownCustomizerActionPerformed
        //Move Down was clicked.
        int selectedIndex = customizerList.getSelectedIndex();
        if (selectedIndex == -1) {
            return;
        }

        if (selectedIndex < customizerControls.size() - 1) {
            CustomizerControl toMove = customizerControls.get(selectedIndex);
            customizerControls.set(selectedIndex, customizerControls.get(selectedIndex + 1));
            customizerControls.set(selectedIndex + 1, toMove);

            //Redefine Customizers
            CustomizerControl[] customizers = new CustomizerControl[customizerControls.size()];
            customizers = customizerControls.toArray(new CustomizerControl[0]);
            customizerList.setListData(customizers);

            //Finally, reselect moved item.
            customizerList.setSelectedValue(toMove, true);
        }
    }//GEN-LAST:event_moveDownCustomizerActionPerformed

    private void deleteSelectedCustomizerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteSelectedCustomizerActionPerformed
        //Delete was clicked.
        if (customizerList.getSelectedIndex() == -1) {
            return;
        }

        //Get object and remove it from ArrayList.
        Object toDelete = customizerList.getSelectedValue();
        customizerControls.remove(toDelete);

        //Redefine Customizers
        CustomizerControl[] customizers = new CustomizerControl[customizerControls.size()];
        customizers = customizerControls.toArray(new CustomizerControl[0]);
        customizerList.setListData(customizers);
    }//GEN-LAST:event_deleteSelectedCustomizerActionPerformed

    private void itemNameTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemNameTextActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_itemNameTextActionPerformed

    private void pItemComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pItemComboActionPerformed
        if (pItemCombo.getSelectedItem() == null) {
            return;
        }

        selectedPaletteItem = (PaletteItem) pItemCombo.getSelectedItem();

        loadingLanguage = true;
        loadPaletteItemToForm(selectedPaletteItem, selectedPaletteItem.getFileName());
        loadingLanguage = false;
    }//GEN-LAST:event_pItemComboActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        loadPaletteItems("");
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void deleteSelectedItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteSelectedItemActionPerformed
        if (selectedPaletteItem != null) {
            Object[] options = { "Yes", "No" };
            int n = JOptionPane.showOptionDialog(SwingUtilities.getWindowAncestor(this),
                    "This will delete the selected palette item permanently.\n"
                            + "Are you sure you wish to continue?",
                    "Are you sure?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
                    options[1]);

            if (n != 0) {
                return;
            }

            //Step 1: Remove palette item from the combo box
            String fileName = selectedPaletteItem.getFileName();
            pItemCombo.removeItem(selectedPaletteItem);

            //Step 2: Delete the file if necessary
            if (fileName != null && fileName.equals("") == false) {
                String saveDirectory = System.getProperty("user.dir") + "\\LearningPaletteXML";

                //Make the directory if necessary
                File folder = new File(saveDirectory);
                if (!folder.exists()) {
                    if (folder.mkdir()) {
                        System.out.println("Directory is created!");
                    } else {
                        System.out.println("Failed to create directory!");
                    }
                }

                File fileToDelete = null;
                File[] listOfFiles = folder.listFiles();
                for (File file : listOfFiles) {
                    if (file.isFile()) {
                        if (file.getName().equals(fileName)) {
                            fileToDelete = file;
                        }
                    }
                }

                if (fileToDelete != null) {
                    fileToDelete.delete();
                }
            }

            //Step 3: call loadPaletteItems("")
            //Cleanup the form
            itemNameText.setText("");
            descriptionText.setText("");
            customizerReplace.setText("");
            customizerLabel.setText("");
            customizerList.removeAll();

            loadPaletteItems("");
        }
    }//GEN-LAST:event_deleteSelectedItemActionPerformed

    private void updateCustomizers() {
        //Redefine Customizers
        CustomizerControl[] customizers = new CustomizerControl[customizerControls.size()];
        customizers = customizerControls.toArray(new CustomizerControl[0]);
        customizerList.setListData(customizers);
    }

    private void loadPaletteItemToForm(PaletteItem item, String fileName) {

        this.itemNameText.setEnabled(true);
        this.itemNameText.setEditable(true);
        this.itemNameText.setText(item.getItemName());

        this.descriptionText.setEnabled(true);
        this.descriptionText.setEditable(true);
        this.descriptionText.setText(item.getToolTip());

        this.codeText.setEnabled(true);
        this.codeText.setEditable(true);

        this.languageCombo.setEnabled(true);
        this.saveButton.setEnabled(true);
        this.cancelButton.setEnabled(true);

        //Now generate language definition for each palette item language.
        codeMapping = new HashMap<>();
        languageCombo.setSelectedIndex(0);
        loadingLanguage = true;

        String javaCode = "";
        for (int i = 0; i < languageCombo.getItemCount(); i++) {
            String defaultCode;
            String language = languageCombo.getItemAt(i).toString();
            try {
                Map<String, String> codeMap = item.getCodeMap(language);
                defaultCode = codeMap.get("codeTemplate");
            } catch (Exception ex) {
                //The K,V pair doesn't exist yet, not an issue.
                defaultCode = "";
            }

            if (i == 0) {
                javaCode = defaultCode;
            }

            codeMapping.put(language, defaultCode);
        }

        codeText.setText(javaCode);
        loadingLanguage = false;

        //Enable Customizer Options
        moveDownCustomizer.setEnabled(true);
        moveUpCustomizer.setEnabled(true);
        deleteSelectedCustomizer.setEnabled(true);
        customizerList.setEnabled(true);

        //Load a CustomizerControl[] array.
        CustomizerControl[] controls = new CustomizerControl[item.getCustomizerControls().size()];
        controls = item.getCustomizerControls().toArray(new CustomizerControl[0]);
        customizerList.setListData(controls);

        customizerType.setEnabled(true);
        customizerReplace.setEnabled(true);
        customizerReplace.setEditable(true);
        customizerReplace.setText("");

        customizerLabel.setEnabled(true);
        customizerLabel.setEditable(true);
        customizerLabel.setText("");

        addCustomizer.setEnabled(true);

        currentFileName = fileName;
    }

    private void createNewPaletteItem() {
        selectedPaletteItem = new PaletteItem();
        pItemCombo.addItem(selectedPaletteItem);
        pItemCombo.setSelectedItem(selectedPaletteItem);

        loadPaletteItemToForm(selectedPaletteItem, null);

    }

    private void loadPaletteItems(String selection) {

        PaletteItem select = null;

        //Reset Palette Items that may have been loaded earlier
        paletteItems.clear();
        pItemCombo.removeAllItems();

        //Now get a list of palette items saved on the disk
        //UserDefined_*.xml
        String saveDirectory = System.getProperty("user.dir") + "\\LearningPaletteXML";

        //Make the directory if necessary
        File folder = new File(saveDirectory);
        if (!folder.exists()) {
            if (folder.mkdir()) {
                System.out.println("Directory is created!");
            } else {
                System.out.println("Failed to create directory!");
            }
        }

        File[] listOfFiles = folder.listFiles();
        for (File file : listOfFiles) {
            if (file.isFile()) {
                String fileName = file.getName();
                if (fileName.matches("\\bUserDefined_.*\\.xml")) {
                    try {
                        //Read the file then parse it as an inputstream to the PaletteItem class.
                        String str = FileUtils.readFileToString(file);
                        InputStream stream = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
                        PaletteItem newItem = new PaletteItem(stream);
                        if (newItem.wasLoadSuccessful()) {
                            paletteItems.add(newItem);
                            if (newItem.getItemName().equals(selection)) {
                                select = newItem;
                            }
                            newItem.setFileName(fileName);
                        }
                    } catch (Exception ex) {
                        //Improperly defined palette item.
                    }
                }
            }
        }

        for (int i = 0; i < paletteItems.size(); i++) {
            pItemCombo.addItem(paletteItems.get(i));
        }

        //If we found our selection, select it.
        if (select != null) {
            pItemCombo.setSelectedItem(select);
        } else {
            if (pItemCombo.getItemCount() > 0) {
                pItemCombo.setSelectedIndex(0);
            } else {
                selectedPaletteItem = null;
            }

        }
        updateFormState();
    }

    void load() {

        //Populate language list.
        if (languageList.isEmpty()) {
            for (int i = 0; i < languageCombo.getItemCount(); i++) {
                languageList.add(languageCombo.getItemAt(i).toString());
            }
        }

        loadPaletteItems("");

        codeText.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                codeTextChanged();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                codeTextChanged();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                codeTextChanged();
            }
        });

    }

    private void codeTextChanged() {
        if (loadingLanguage) {
            return;
        }

        String currentCode = codeText.getText();
        String currentLanguage = languageCombo.getSelectedItem().toString();
        System.out.println(currentLanguage + ": " + currentCode);

        codeMapping.put(currentLanguage, currentCode);
    }

    private void updateFormState() {
        //If a palette item is selected, activate form
        boolean enabled;
        if (selectedPaletteItem != null) {
            enabled = true;
        } else {
            //Clean up form and lock it down.
            enabled = false;
        }

        pItemCombo.setEnabled(enabled);
        deleteSelectedItem.setEnabled(enabled);
        itemNameText.setEnabled(enabled);
        descriptionText.setEnabled(enabled);
        customizerReplace.setEnabled(enabled);
        customizerLabel.setEnabled(enabled);
        moveDownCustomizer.setEnabled(enabled);
        moveUpCustomizer.setEnabled(enabled);
        deleteSelectedCustomizer.setEnabled(enabled);
        customizerList.setEnabled(enabled);
        addCustomizer.setEnabled(enabled);
        saveButton.setEnabled(enabled);
        cancelButton.setEnabled(enabled);
        customizerType.setEnabled(enabled);
    }

    void store() {
        // TODO store modified settings
        // Example:
        // Preferences.userNodeForPackage(LearningPalettePanel.class).putBoolean("someFlag", someCheckBox.isSelected());
        // or for org.openide.util with API spec. version >= 7.4:
        // NbPreferences.forModule(LearningPalettePanel.class).putBoolean("someFlag", someCheckBox.isSelected());
        // or:
        // SomeSystemOption.getDefault().setSomeStringProperty(someTextField.getText());
        //PaletteManager.getInstance().reloadPaletteItems();
        //SourceFilePaletteFactory.createPalette();

        //Create the palette if necessary (has not been loaded yet)
        PaletteManager.getInstance().reloadPaletteItems();
        SourceFilePaletteFactory.catChildFactory.refreshNow();
        SourceFilePaletteFactory.paletteController.refresh();

    }

    boolean valid() {
        // TODO check whether form is consistent and complete
        return true;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addCustomizer;
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextArea codeText;
    private javax.swing.JButton createNewButton;
    private javax.swing.JTextField customizerLabel;
    private javax.swing.JList customizerList;
    private javax.swing.JTextField customizerReplace;
    private javax.swing.JComboBox customizerType;
    private javax.swing.JButton deleteSelectedCustomizer;
    private javax.swing.JButton deleteSelectedItem;
    private javax.swing.JTextField descriptionText;
    private javax.swing.JTextField itemNameText;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JComboBox languageCombo;
    private javax.swing.JButton moveDownCustomizer;
    private javax.swing.JButton moveUpCustomizer;
    private javax.swing.JComboBox pItemCombo;
    private javax.swing.JLabel paletteItemName;
    private javax.swing.JButton saveButton;
    // End of variables declaration//GEN-END:variables
}