se.trixon.toolbox.alphatrans.AlphatransTopComponent.java Source code

Java tutorial

Introduction

Here is the source code for se.trixon.toolbox.alphatrans.AlphatransTopComponent.java

Source

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

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import javax.swing.JList;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.apache.commons.io.FileUtils;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import se.trixon.almond.dialogs.Message;
import se.trixon.almond.dialogs.SimpleDialog;
import se.trixon.almond.dictionary.Dict;
import se.trixon.almond.icon.Pict;
import se.trixon.toolbox.alphatrans.cmd.CmdFile;
import se.trixon.toolbox.alphatrans.cmd.CmdIconv;
import se.trixon.toolbox.core.Toolbox;
import se.trixon.toolbox.core.base.ToolTopComponent;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//se.trixon.toolbox.alphatrans//Alphatrans//EN", autostore = false)
@TopComponent.Description(preferredID = "AlphatransTopComponent",
        //        iconBase = "se/trixon/toolbox/alphatrans/logo.png",
        persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
public final class AlphatransTopComponent extends ToolTopComponent {

    private final AlphatransController mController;
    private final CmdIconv mCmdIconv = new CmdIconv();
    private final CmdFile mCmdFile = new CmdFile();
    private String[] mCharSets;
    private File mFile;
    private String mFileEncoding = "";
    private String mFileType = "";
    private File mTempSourcePreviewFile;
    private File mTempDestFile;
    private File mTempDestPreviewFile;

    public AlphatransTopComponent() {
        mBundle = NbBundle.getBundle(AlphatransTopComponent.class);
        mToolName = mBundle.getString("Tool-Name");
        initComponents();
        setName(mToolName);
        mController = new AlphatransController(this);
        init();

        //openFile(new File(System.getProperty("user.home"), "rksmrgs.txt"));
    }

    /**
     * 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() {
        java.awt.GridBagConstraints gridBagConstraints;

        modeButtonGroup = new javax.swing.ButtonGroup();
        toolBar = new javax.swing.JToolBar();
        openButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        separator1 = new javax.swing.JToolBar.Separator();
        optionsPanel = new javax.swing.JPanel();
        modeLabel = new javax.swing.JLabel();
        normalRadioButton = new javax.swing.JRadioButton();
        translitRadioButton = new javax.swing.JRadioButton();
        ignoreRadioButton = new javax.swing.JRadioButton();
        omitCheckBox = new javax.swing.JCheckBox();
        filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0),
                new java.awt.Dimension(32767, 0));
        mainPanel = new javax.swing.JPanel();
        fromLabel = new javax.swing.JLabel();
        fromTextField = new javax.swing.JTextField();
        fromListScrollPane = new javax.swing.JScrollPane();
        fromList = new javax.swing.JList();
        fromPreviewLabel = new javax.swing.JLabel();
        fromTextScrollPane = new javax.swing.JScrollPane();
        fromTextArea = new javax.swing.JTextArea();
        toLabel = new javax.swing.JLabel();
        toTextField = new javax.swing.JTextField();
        toListScrollPane = new javax.swing.JScrollPane();
        toList = new javax.swing.JList();
        toPreviewLabel = new javax.swing.JLabel();
        toTextScrollPane = new javax.swing.JScrollPane();
        toTextArea = new javax.swing.JTextArea();

        toolBar.setFloatable(false);
        toolBar.setRollover(true);

        openButton.setToolTipText(Dict.OPEN.getString());
        openButton.setFocusable(false);
        openButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openButtonActionPerformed(evt);
            }
        });
        toolBar.add(openButton);

        saveButton.setToolTipText(Dict.SAVE_AS.getString());
        saveButton.setEnabled(false);
        saveButton.setFocusable(false);
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });
        toolBar.add(saveButton);
        toolBar.add(separator1);

        optionsPanel.setLayout(new java.awt.GridBagLayout());

        org.openide.awt.Mnemonics.setLocalizedText(modeLabel, org.openide.util.NbBundle
                .getMessage(AlphatransTopComponent.class, "AlphatransTopComponent.modeLabel.text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0);
        optionsPanel.add(modeLabel, gridBagConstraints);

        modeButtonGroup.add(normalRadioButton);
        normalRadioButton.setSelected(true);
        org.openide.awt.Mnemonics.setLocalizedText(normalRadioButton, org.openide.util.NbBundle
                .getMessage(AlphatransTopComponent.class, "AlphatransTopComponent.normalRadioButton.text")); // NOI18N
        normalRadioButton.setFocusable(false);
        normalRadioButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        normalRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modeActionPerformed(evt);
            }
        });
        optionsPanel.add(normalRadioButton, new java.awt.GridBagConstraints());

        modeButtonGroup.add(translitRadioButton);
        org.openide.awt.Mnemonics.setLocalizedText(translitRadioButton, org.openide.util.NbBundle
                .getMessage(AlphatransTopComponent.class, "AlphatransTopComponent.translitRadioButton.text")); // NOI18N
        translitRadioButton.setFocusable(false);
        translitRadioButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        translitRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modeActionPerformed(evt);
            }
        });
        optionsPanel.add(translitRadioButton, new java.awt.GridBagConstraints());

        modeButtonGroup.add(ignoreRadioButton);
        org.openide.awt.Mnemonics.setLocalizedText(ignoreRadioButton, org.openide.util.NbBundle
                .getMessage(AlphatransTopComponent.class, "AlphatransTopComponent.ignoreRadioButton.text")); // NOI18N
        ignoreRadioButton.setFocusable(false);
        ignoreRadioButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        ignoreRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modeActionPerformed(evt);
            }
        });
        optionsPanel.add(ignoreRadioButton, new java.awt.GridBagConstraints());

        org.openide.awt.Mnemonics.setLocalizedText(omitCheckBox, org.openide.util.NbBundle
                .getMessage(AlphatransTopComponent.class, "AlphatransTopComponent.omitCheckBox.text")); // NOI18N
        omitCheckBox.setFocusable(false);
        omitCheckBox.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        omitCheckBox.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                omitCheckBoxStateChanged(evt);
            }
        });
        optionsPanel.add(omitCheckBox, new java.awt.GridBagConstraints());
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        optionsPanel.add(filler1, gridBagConstraints);

        toolBar.add(optionsPanel);

        mainPanel.setLayout(new java.awt.GridBagLayout());

        org.openide.awt.Mnemonics.setLocalizedText(fromLabel, org.openide.util.NbBundle
                .getMessage(AlphatransTopComponent.class, "AlphatransTopComponent.fromLabel.text")); // NOI18N
        fromLabel.setMinimumSize(new java.awt.Dimension(200, 18));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2);
        mainPanel.add(fromLabel, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        mainPanel.add(fromTextField, gridBagConstraints);

        fromListScrollPane.setPreferredSize(new java.awt.Dimension(250, 130));

        fromList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        fromList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                fromListValueChanged(evt);
            }
        });
        fromListScrollPane.setViewportView(fromList);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        mainPanel.add(fromListScrollPane, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2);
        mainPanel.add(fromPreviewLabel, gridBagConstraints);

        fromTextArea.setEditable(false);
        fromTextArea.setColumns(20);
        fromTextArea.setFont(new java.awt.Font("Monospaced", 0, 15)); // NOI18N
        fromTextArea.setRows(5);
        fromTextScrollPane.setViewportView(fromTextArea);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        mainPanel.add(fromTextScrollPane, gridBagConstraints);

        org.openide.awt.Mnemonics.setLocalizedText(toLabel, org.openide.util.NbBundle
                .getMessage(AlphatransTopComponent.class, "AlphatransTopComponent.toLabel.text")); // NOI18N
        toLabel.setMinimumSize(new java.awt.Dimension(200, 18));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2);
        mainPanel.add(toLabel, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        mainPanel.add(toTextField, gridBagConstraints);

        toListScrollPane.setPreferredSize(new java.awt.Dimension(250, 130));

        toList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        toList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                toListValueChanged(evt);
            }
        });
        toListScrollPane.setViewportView(toList);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        mainPanel.add(toListScrollPane, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2);
        mainPanel.add(toPreviewLabel, gridBagConstraints);

        toTextArea.setEditable(false);
        toTextArea.setColumns(20);
        toTextArea.setFont(new java.awt.Font("Monospaced", 0, 15)); // NOI18N
        toTextArea.setRows(5);
        toTextScrollPane.setViewportView(toTextArea);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        mainPanel.add(toTextScrollPane, gridBagConstraints);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(toolBar, javax.swing.GroupLayout.DEFAULT_SIZE, 531, Short.MAX_VALUE)
                .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addComponent(toolBar, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)));
    }// </editor-fold>//GEN-END:initComponents

    private void openButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openButtonActionPerformed
        SimpleDialog.setParent(openButton.getTopLevelAncestor());
        if (SimpleDialog.openFile()) {
            openFile(SimpleDialog.getPath());
        }
    }//GEN-LAST:event_openButtonActionPerformed

    private void fromListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_fromListValueChanged
        preview();
    }//GEN-LAST:event_fromListValueChanged

    private void toListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_toListValueChanged
        preview();
    }//GEN-LAST:event_toListValueChanged

    private void omitCheckBoxStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_omitCheckBoxStateChanged
        preview();
    }//GEN-LAST:event_omitCheckBoxStateChanged

    private void modeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modeActionPerformed
        preview();
    }//GEN-LAST:event_modeActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        SimpleDialog.setParent(this);
        if (SimpleDialog.saveFile()) {
            saveFile(SimpleDialog.getPath());
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.Box.Filler filler1;
    private javax.swing.JLabel fromLabel;
    private javax.swing.JList fromList;
    private javax.swing.JScrollPane fromListScrollPane;
    private javax.swing.JLabel fromPreviewLabel;
    private javax.swing.JTextArea fromTextArea;
    private javax.swing.JTextField fromTextField;
    private javax.swing.JScrollPane fromTextScrollPane;
    private javax.swing.JRadioButton ignoreRadioButton;
    private javax.swing.JPanel mainPanel;
    private javax.swing.ButtonGroup modeButtonGroup;
    private javax.swing.JLabel modeLabel;
    private javax.swing.JRadioButton normalRadioButton;
    private javax.swing.JCheckBox omitCheckBox;
    private javax.swing.JButton openButton;
    private javax.swing.JPanel optionsPanel;
    private javax.swing.JButton saveButton;
    private javax.swing.JToolBar.Separator separator1;
    private javax.swing.JLabel toLabel;
    private javax.swing.JList toList;
    private javax.swing.JScrollPane toListScrollPane;
    private javax.swing.JLabel toPreviewLabel;
    private javax.swing.JTextArea toTextArea;
    private javax.swing.JTextField toTextField;
    private javax.swing.JScrollPane toTextScrollPane;
    private javax.swing.JToolBar toolBar;
    private javax.swing.JRadioButton translitRadioButton;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened() {
    }

    @Override
    public void componentClosed() {
    }

    @Override
    protected void componentActivated() {
        super.componentActivated();
        updateStatusText();
    }

    void writeProperties(java.util.Properties p) {
        p.setProperty("version", "1.0");
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
    }

    private void init() {
        initFilterBoxes();
        initTempFiles();
        mCharSets = mCmdIconv.list();
        fromList.setListData(mCharSets);
        toList.setListData(mCharSets);

        openButton.setIcon(Pict.Actions.DOCUMENT_OPEN.get(TOOLBAR_ICON_SIZE));
        saveButton.setIcon(Pict.Actions.DOCUMENT_SAVE_AS.get(TOOLBAR_ICON_SIZE));
    }

    private void initTempFiles() {
        try {
            mTempSourcePreviewFile = File.createTempFile("alphatrans_preview_source", null);
            mTempDestFile = File.createTempFile("alphatrans_dest", null);
            mTempDestPreviewFile = File.createTempFile("alphatrans_preview_dest", null);
            mTempSourcePreviewFile.deleteOnExit();
            mTempDestFile.deleteOnExit();
            mTempDestPreviewFile.deleteOnExit();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }

    private void initFilterBoxes() {
        fromTextField.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                doFilter();
            }

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

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

            private void doFilter() {
                filter(fromTextField.getText(), fromList);
            }

        });

        toTextField.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                doFilter();
            }

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

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

            private void doFilter() {
                filter(toTextField.getText(), toList);
            }

        });
    }

    private void filter(String filter, JList list) {
        ArrayList<String> filtered = new ArrayList<>();

        for (String charSet : mCharSets) {
            if (charSet.toLowerCase().contains(filter.toLowerCase())) {
                filtered.add(charSet);
            }
        }

        list.setListData(filtered.toArray());
    }

    private void openFile(File file) {
        mFile = file;
        mFileEncoding = mCmdFile.getMimeEncoding(file);
        mFileType = mCmdFile.getMimeType(file);
        fromTextField.setText("");
        toTextField.setText("");
        updateStatusText();
        fromList.setSelectedValue(mFileEncoding, true);
        toList.setSelectedValue(mFileEncoding, true);
        preview();
        saveButton.setEnabled(true);
    }

    private void updateStatusText() {
        String status = "";

        if (mFile != null) {
            status = NbBundle.getMessage(AlphatransTopComponent.class, "AlphatransTopComponent.StatusText",
                    mFileEncoding, mFileType, mFile.getAbsolutePath());
        }

        Toolbox.setStatusText(status);
    }

    private void previewSourceFile(String encoding) {
        if (mFileEncoding.equalsIgnoreCase("binary")) {
            String message = NbBundle.getMessage(AlphatransTopComponent.class, "messageBinaryFile",
                    mFile.getAbsolutePath());
            se.trixon.almond.dialogs.Message.warning(Dict.WARNING.getString(), message);
        }

        mCmdIconv.convert(mFile, mTempSourcePreviewFile, encoding, "UTF-8", false);
        try {
            fromTextArea.setText(FileUtils.readFileToString(mTempSourcePreviewFile, Charset.forName("UTF-8")));
            fromTextArea.setCaretPosition(0);
        } catch (IOException ex) {
            String message = NbBundle.getMessage(AlphatransTopComponent.class, "messagePreviewError", encoding);
            fromTextArea.setText(message);
            Exceptions.printStackTrace(ex);
        }
    }

    private void previewDestFile() {
        String mode = "";
        if (translitRadioButton.isSelected()) {
            mode = "//TRANSLIT";
        } else if (ignoreRadioButton.isSelected()) {
            mode = "//IGNORE";
        }

        String fromCharset = fromList.getSelectedValue().toString();
        String toCharset = toList.getSelectedValue().toString() + mode;

        String convertError = mCmdIconv.convert(mFile, mTempDestFile, fromCharset, toCharset,
                omitCheckBox.isSelected());
        mCmdIconv.convert(mTempDestFile, mTempDestPreviewFile, toCharset, "UTF-8", false);

        try {
            if (convertError == null) {
                toTextArea.setText(FileUtils.readFileToString(mTempDestPreviewFile, Charset.forName("UTF-8")));
            } else {
                toTextArea.setText(convertError);
            }
            toTextArea.setCaretPosition(0);
        } catch (IOException ex) {
            String message = NbBundle.getMessage(AlphatransTopComponent.class, "messagePreviewError", toCharset);
            toTextArea.setText(message);
            Exceptions.printStackTrace(ex);
        }
    }

    private void preview() {
        if (isDestValid() && isSourceValid()) {
            previewSourceFile(fromList.getSelectedValue().toString());
            previewDestFile();
            String preview;
            preview = NbBundle.getMessage(AlphatransTopComponent.class, "preview",
                    fromList.getSelectedValue().toString());
            fromPreviewLabel.setText(preview);
            preview = NbBundle.getMessage(AlphatransTopComponent.class, "preview",
                    toList.getSelectedValue().toString());
            toPreviewLabel.setText(preview);
        }
    }

    private boolean isDestValid() {
        return toList.getSelectedIndex() > -1;
    }

    private boolean isSourceValid() {
        return mFile != null && fromList.getSelectedIndex() > -1 && mFile.exists();
    }

    private void saveFile(File file) {
        try {
            FileUtils.copyFile(mTempDestFile, file, false);
        } catch (IOException ex) {
            Message.error(Dict.IO_ERROR_TITLE.getString(), ex.getLocalizedMessage());
        }
    }
}