Package ui

Source Code of ui.Main

/*
* This file is part of TextScout.
*
* TextScout is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* TextScout is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with TextScout. If not, see <http://www.gnu.org/licenses/>.
*/
package ui;


import data.Line;
import data.LineMatch;
import data.SearchResult;
import data.properties.AppProperties;
import data.properties.AppPropertiesImpl;
import gfx.FileStorage;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.MouseAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableRowSorter;
import javax.swing.text.Document;
import logic.InputValidator;
import logic.SearchEngine;
import logic.SearchListener;
import logic.comparators.FileSizeComparator;
import logic.comparators.StringComparator;
import logic.logger.Logger;
import static logic.logger.Logger.*;
import logic.logger.Logger.LogLevel;
import static logic.logger.Logger.LogLevel.*;
import org.fife.ui.rsyntaxtextarea.*;
import ui.models.ResultTableModel;
import ui.utils.DirectorySelector;
import ui.utils.DirectorySelectorImpl;

public class Main extends javax.swing.JFrame implements SearchListener, ListSelectionListener {

    public static final String APPLICATION_VERSION = "TextScout v0.1a";

    private ResultTableModel resultModel = null;
    private SearchEngine engine = null;
    private DefaultComboBoxModel<String> maskCbModel = null;
    private DefaultComboBoxModel<String> fileCbModel = null;
    private DefaultComboBoxModel<String> dirCbModel = null;
    private final AppProperties props = AppPropertiesImpl.getInstance();
    private TableRowSorter<ResultTableModel> rowSorter = null;

    /**
     * Creates new form Main
     */
    public Main() {
        setMacSpecificProperties();

        initComponents();
        pack();
        initMain();
    }

    private void initMain() {

        try {
            this.setTitle(APPLICATION_VERSION);
            this.setIconImage(new javax.swing.ImageIcon(getClass().getResource("/gfx/icon.png")).getImage());
            setMacSpecificProperties();

            btMask.setVisible(false);
            btFile.setVisible(false);

            //Maximize window
            this.setExtendedState(JFrame.MAXIMIZED_BOTH);

            //Create and set Table-Model for Result-Table
            resultModel = new ResultTableModel();
            taResults.setModel(resultModel);

            //Create and set model for the input comboboxes
            maskCbModel = new DefaultComboBoxModel<>();
            cbMask.setModel(maskCbModel);
            fileCbModel = new DefaultComboBoxModel<>();
            cbFiles.setModel(fileCbModel);
            dirCbModel = new DefaultComboBoxModel<>();
            cbPaths.setModel(dirCbModel);

            //Create isntance for the search engine
            engine = new SearchEngine(props);
            engine.addSearchListener(this);

            //Set selection model
            taResults.getSelectionModel().addListSelectionListener(this);

            initCodeDisplay();

            //Setup row sorter
            initRowSorter();

            //Set splitter proportion
            sppOutputs.setDividerLocation((int) (this.getWidth() * 1.5));

            //Load the configuration and input last inputs
            loadConfig();

        } catch (Exception ex) {
            log(FATAL_ERROR, ex);
            MsgBoxes.showError(ex);

        }
       
        setSize(800, 600);
    }

    private void initCodeDisplay() {
        staCode.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
        staCode.setEditable(false);
    }

    private void initRowSorter() {
        rowSorter = new TableRowSorter<>(resultModel);

        rowSorter.setComparator(ResultTableModel.COL_FILENAME, new StringComparator());
        rowSorter.setComparator(ResultTableModel.COL_FILEPATH, new StringComparator());
        rowSorter.setComparator(ResultTableModel.COL_FILESIZE, new FileSizeComparator());
        rowSorter.setComparator(ResultTableModel.COL_FILETYPE, new StringComparator());
        rowSorter.setComparator(ResultTableModel.COL_LASTCHANGE, new StringComparator());

        taResults.setRowSorter(rowSorter);
    }

    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pmResultPopUp = new javax.swing.JPopupMenu();
        miOpenFile = new javax.swing.JMenuItem();
        miOpenInFolder = new javax.swing.JMenuItem();
        miCopyFileName = new javax.swing.JMenuItem();
        pMain = new javax.swing.JPanel();
        pInput = new javax.swing.JPanel();
        pSearchInputs = new javax.swing.JPanel();
        pSearchInputLabels = new javax.swing.JPanel();
        lbMask = new javax.swing.JLabel();
        lbFiles = new javax.swing.JLabel();
        lbPaths = new javax.swing.JLabel();
        pSearchInputFields = new javax.swing.JPanel();
        pMask = new javax.swing.JPanel();
        cbMask = new javax.swing.JComboBox();
        btMask = new javax.swing.JButton();
        pFiles = new javax.swing.JPanel();
        cbFiles = new javax.swing.JComboBox();
        btFile = new javax.swing.JButton();
        pPaths = new javax.swing.JPanel();
        cbPaths = new javax.swing.JComboBox();
        btPath = new javax.swing.JButton();
        pSearchControl = new javax.swing.JPanel();
        pSearchControlDetail = new javax.swing.JPanel();
        btStart = new javax.swing.JButton();
        pOutput = new javax.swing.JPanel();
        sppOutputs = new javax.swing.JSplitPane();
        pResultTable = new javax.swing.JPanel();
        spResultTable = new javax.swing.JScrollPane();
        taResults = new javax.swing.JTable();
        pResultDetail = new javax.swing.JPanel();
        spResultDetail = new javax.swing.JScrollPane();
        staCode = new org.fife.ui.rsyntaxtextarea.RSyntaxTextArea();
        pInfos = new javax.swing.JPanel();
        pInfoProgress = new javax.swing.JPanel();
        lbProgress = new javax.swing.JLabel();
        pInfoResults = new javax.swing.JPanel();
        lbInfoResults = new javax.swing.JLabel();
        mbMenus = new javax.swing.JMenuBar();
        mFile = new javax.swing.JMenu();
        miSettings = new javax.swing.JMenuItem();
        msClose = new javax.swing.JPopupMenu.Separator();
        miClose = new javax.swing.JMenuItem();

        miOpenFile.setText("Open");
        miOpenFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onPopUpOpen(evt);
            }
        });
        pmResultPopUp.add(miOpenFile);

        miOpenInFolder.setText("Show in folder");
        miOpenInFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onPopUpOpenInFolder(evt);
            }
        });
        pmResultPopUp.add(miOpenInFolder);

        miCopyFileName.setText("Copy file name");
        miCopyFileName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onPopUpCopy(evt);
            }
        });
        pmResultPopUp.add(miCopyFileName);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        pMain.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
        pMain.setLayout(new java.awt.BorderLayout());

        pInput.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4), javax.swing.BorderFactory.createTitledBorder("Search")));
        pInput.setLayout(new java.awt.BorderLayout());

        pSearchInputs.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
        pSearchInputs.setLayout(new java.awt.BorderLayout());

        pSearchInputLabels.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
        pSearchInputLabels.setLayout(new java.awt.GridLayout(0, 1));

        lbMask.setText("Mask: ");
        pSearchInputLabels.add(lbMask);

        lbFiles.setText("File(s): ");
        pSearchInputLabels.add(lbFiles);

        lbPaths.setText("Path(s): ");
        pSearchInputLabels.add(lbPaths);

        pSearchInputs.add(pSearchInputLabels, java.awt.BorderLayout.WEST);

        pSearchInputFields.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
        pSearchInputFields.setLayout(new java.awt.GridLayout(0, 1));

        pMask.setLayout(new java.awt.BorderLayout());

        cbMask.setEditable(true);
        cbMask.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbMask.setSelectedIndex(-1);
        pMask.add(cbMask, java.awt.BorderLayout.CENTER);

        btMask.setText("...");
        btMask.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                onClickBtMask(evt);
            }
        });
        btMask.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onBtMask(evt);
            }
        });
        pMask.add(btMask, java.awt.BorderLayout.EAST);

        pSearchInputFields.add(pMask);

        pFiles.setLayout(new java.awt.BorderLayout());

        cbFiles.setEditable(true);
        cbFiles.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbFiles.setSelectedIndex(-1);
        pFiles.add(cbFiles, java.awt.BorderLayout.CENTER);

        btFile.setText("...");
        pFiles.add(btFile, java.awt.BorderLayout.EAST);

        pSearchInputFields.add(pFiles);

        pPaths.setLayout(new java.awt.BorderLayout());

        cbPaths.setEditable(true);
        cbPaths.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbPaths.setSelectedIndex(-1);
        pPaths.add(cbPaths, java.awt.BorderLayout.CENTER);

        btPath.setText("...");
        btPath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPathActionPerformed(evt);
            }
        });
        pPaths.add(btPath, java.awt.BorderLayout.EAST);

        pSearchInputFields.add(pPaths);

        pSearchInputs.add(pSearchInputFields, java.awt.BorderLayout.CENTER);

        pInput.add(pSearchInputs, java.awt.BorderLayout.CENTER);

        pSearchControl.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
        pSearchControl.setLayout(new java.awt.BorderLayout());

        pSearchControlDetail.setLayout(new java.awt.GridLayout(0, 1, 2, 2));

        btStart.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gfx/start.png"))); // NOI18N
        btStart.setText("Start");
        btStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onStartStop(evt);
            }
        });
        pSearchControlDetail.add(btStart);

        pSearchControl.add(pSearchControlDetail, java.awt.BorderLayout.CENTER);

        pInput.add(pSearchControl, java.awt.BorderLayout.EAST);

        pMain.add(pInput, java.awt.BorderLayout.PAGE_START);

        pOutput.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4), javax.swing.BorderFactory.createTitledBorder("Results")));
        pOutput.setLayout(new java.awt.BorderLayout());

        sppOutputs.setDividerLocation(500);
        sppOutputs.setDividerSize(3);
        sppOutputs.setResizeWeight(0.6);

        pResultTable.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
        pResultTable.setMinimumSize(new java.awt.Dimension(200, 200));
        pResultTable.setPreferredSize(new java.awt.Dimension(450, 400));
        pResultTable.setLayout(new java.awt.BorderLayout());

        taResults.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        taResults.setComponentPopupMenu(pmResultPopUp);
        taResults.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                onResultTableClick(evt);
            }
        });
        spResultTable.setViewportView(taResults);

        pResultTable.add(spResultTable, java.awt.BorderLayout.CENTER);

        sppOutputs.setLeftComponent(pResultTable);

        pResultDetail.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
        pResultDetail.setMinimumSize(new java.awt.Dimension(200, 200));
        pResultDetail.setPreferredSize(new java.awt.Dimension(350, 400));
        pResultDetail.setLayout(new java.awt.BorderLayout());

        spResultDetail.setPreferredSize(new java.awt.Dimension(100, 400));

        staCode.setEditable(false);
        staCode.setColumns(1);
        staCode.setRows(100);
        staCode.setPreferredSize(new java.awt.Dimension(100, 400));
        spResultDetail.setViewportView(staCode);

        pResultDetail.add(spResultDetail, java.awt.BorderLayout.CENTER);

        sppOutputs.setRightComponent(pResultDetail);

        pOutput.add(sppOutputs, java.awt.BorderLayout.CENTER);

        pMain.add(pOutput, java.awt.BorderLayout.CENTER);

        pInfos.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
        pInfos.setLayout(new java.awt.GridLayout(1, 0, 2, 2));

        pInfoProgress.setLayout(new java.awt.BorderLayout());
        pInfoProgress.add(lbProgress, java.awt.BorderLayout.CENTER);

        pInfos.add(pInfoProgress);

        pInfoResults.setLayout(new java.awt.BorderLayout());
        pInfoResults.add(lbInfoResults, java.awt.BorderLayout.CENTER);

        pInfos.add(pInfoResults);

        pMain.add(pInfos, java.awt.BorderLayout.PAGE_END);

        getContentPane().add(pMain, java.awt.BorderLayout.CENTER);

        mFile.setText("File");

        miSettings.setLabel("Settings...");
        miSettings.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miSettingsActionPerformed(evt);
            }
        });
        mFile.add(miSettings);
        mFile.add(msClose);

        miClose.setLabel("Exit");
        miClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miCloseActionPerformed(evt);
            }
        });
        mFile.add(miClose);

        mbMenus.add(mFile);

        setJMenuBar(mbMenus);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void onClickBtMask(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_onClickBtMask
        //Not in use!
    }//GEN-LAST:event_onClickBtMask

    private void onBtMask(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onBtMask
        System.out.println(cbMask.getSelectedIndex() + " -- " + cbMask.getSelectedItem());
    }//GEN-LAST:event_onBtMask

    private void onStartStop(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onStartStop
        final InputValidator validator = new InputValidator();

        if (engine.isRunning()) {
            engine.stop();
        } else {
            try {
                resultModel.clear();

                engine.setup(validator.prepareSearchMask(maskCbModel.getSelectedItem().toString()),
                        validator.prepareFileMask(fileCbModel.getSelectedItem().toString()),
                        validator.prepareDirectories(dirCbModel.getSelectedItem().toString()));
                engine.process();
                setStartStopButtonState(false);
                storeInput();
            } catch (Exception ex) {
                log(LogLevel.ERROR, ex);
                MsgBoxes.showError(ex);
            }

        }
    }//GEN-LAST:event_onStartStop

    private void btPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPathActionPerformed
        DirectorySelector selector = new DirectorySelectorImpl(this);
        if (selector.select()) {
            final int insertIndex = 0;
            dirCbModel.insertElementAt(selector.getDirectory(), insertIndex);
            cbPaths.setSelectedIndex(insertIndex);
        }
    }//GEN-LAST:event_btPathActionPerformed

    private void miSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miSettingsActionPerformed
        PropertiesDialog settingsDialog = new AppPropertiesDialog(this.props, this);
        settingsDialog.exec();
    }//GEN-LAST:event_miSettingsActionPerformed

    private void onResultTableClick(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_onResultTableClick

        //Set the selection for an right-click so that the popup menu  handles the correct line
        taResults.getSelectionModel().setSelectionInterval(taResults.rowAtPoint(evt.getPoint()), taResults.rowAtPoint(evt.getPoint()));
        taResults.changeSelection(taResults.rowAtPoint(evt.getPoint()), taResults.rowAtPoint(evt.getPoint()), true, true);

        if (evt.getClickCount() == 2) {
            onPopUpOpen(null);
        }

    }//GEN-LAST:event_onResultTableClick

    private void onPopUpCopy(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onPopUpCopy
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(resultModel.get(taResults.getSelectedRow()).getAbsoluteFilePath()), null);
    }//GEN-LAST:event_onPopUpCopy

    private void onPopUpOpenInFolder(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onPopUpOpenInFolder
        SearchResult result = resultModel.get(taResults.getSelectedRow());
        File fileToShow = new File(result.getPath());
        if (!fileToShow.exists()) {
            return;
        }

        try {
            Desktop.getDesktop().open(fileToShow);
        } catch (Exception ex) {
            log(LogLevel.ERROR, ex);
        }
    }//GEN-LAST:event_onPopUpOpenInFolder

    private void onPopUpOpen(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onPopUpOpen
        SearchResult result = resultModel.get(taResults.getSelectedRow());
        File fileToShow = new File(result.getAbsoluteFilePath());
        if (!fileToShow.exists()) {
            return;
        }

        try {
            Desktop.getDesktop().open(fileToShow);
        } catch (Exception ex) {
            log(LogLevel.ERROR, ex);
        }
    }//GEN-LAST:event_onPopUpOpen

    private void miCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miCloseActionPerformed
        dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    }//GEN-LAST:event_miCloseActionPerformed

    private boolean inputValidation(String mask, String files, String dirs) {
        if (mask.length() == 0) {
            MsgBoxes.showError("No mask entered!");
            return false;
        }

        if (dirs.length() == 0) {
            MsgBoxes.showError("No directory entered!");
            return false;
        }
        return true;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
       
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    //Set system UI-Manager
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                }
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btFile;
    private javax.swing.JButton btMask;
    private javax.swing.JButton btPath;
    private javax.swing.JButton btStart;
    private javax.swing.JComboBox cbFiles;
    private javax.swing.JComboBox cbMask;
    private javax.swing.JComboBox cbPaths;
    private javax.swing.JLabel lbFiles;
    private javax.swing.JLabel lbInfoResults;
    private javax.swing.JLabel lbMask;
    private javax.swing.JLabel lbPaths;
    private javax.swing.JLabel lbProgress;
    private javax.swing.JMenu mFile;
    private javax.swing.JMenuBar mbMenus;
    private javax.swing.JMenuItem miClose;
    private javax.swing.JMenuItem miCopyFileName;
    private javax.swing.JMenuItem miOpenFile;
    private javax.swing.JMenuItem miOpenInFolder;
    private javax.swing.JMenuItem miSettings;
    private javax.swing.JPopupMenu.Separator msClose;
    private javax.swing.JPanel pFiles;
    private javax.swing.JPanel pInfoProgress;
    private javax.swing.JPanel pInfoResults;
    private javax.swing.JPanel pInfos;
    private javax.swing.JPanel pInput;
    private javax.swing.JPanel pMain;
    private javax.swing.JPanel pMask;
    private javax.swing.JPanel pOutput;
    private javax.swing.JPanel pPaths;
    private javax.swing.JPanel pResultDetail;
    private javax.swing.JPanel pResultTable;
    private javax.swing.JPanel pSearchControl;
    private javax.swing.JPanel pSearchControlDetail;
    private javax.swing.JPanel pSearchInputFields;
    private javax.swing.JPanel pSearchInputLabels;
    private javax.swing.JPanel pSearchInputs;
    private javax.swing.JPopupMenu pmResultPopUp;
    private javax.swing.JScrollPane spResultDetail;
    private javax.swing.JScrollPane spResultTable;
    private javax.swing.JSplitPane sppOutputs;
    private org.fife.ui.rsyntaxtextarea.RSyntaxTextArea staCode;
    private javax.swing.JTable taResults;
    // End of variables declaration//GEN-END:variables

    @Override
    public void started() {
        lbInfoResults.setText("Searching...");
        try {
            resetSyntaxTable();
        } catch (Exception ex) {
            log(LogLevel.ERROR, ex);
        }
    }

    @Override
    public void enteredDirectory(String dir) {
        lbProgress.setText("Scanning: " + dir);
    }

    @Override
    public void foundMatch(SearchResult result, int matches, int files) {
        final DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);

        resultModel.add(result);
        lbInfoResults.setText(String.format("Found %s matche(s) in %s file(s)", formatter.format(matches), formatter.format(files)));
    }

    @Override
    public void finished() {
        if (resultModel.isEmpty()) {
            lbInfoResults.setText("");
        }
        lbProgress.setText("");
        setStartStopButtonState(true);
    }

    private void setStartStopButtonState(boolean start) {
        //ToDo: Load pictures
        if (start) {
            btStart.setText("Start");
            btStart.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gfx/start.png")));
        } else {
            btStart.setText("Stop");
            btStart.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gfx/stop.png")));
        }
    }

    private void loadConfig() {
        //ToDo
        //Handle the mask combo box
        maskCbModel.removeAllElements();
        for (String element : props.getHistoryProperties().getLastSearchMasks()) {
            maskCbModel.addElement(element);
        }
        if (maskCbModel.getSize() > 0) {
            cbMask.setSelectedIndex(0);
        }

        //Handle the file-extension combo box
        fileCbModel.removeAllElements();
        for (String element : props.getHistoryProperties().getLastFileMasks()) {
            fileCbModel.addElement(element);
        }
        if (fileCbModel.getSize() > 0) {
            cbFiles.setSelectedIndex(0);
        }

        //Handle directory combo box
        dirCbModel.removeAllElements();

        for (String element : props.getHistoryProperties().getLastDirectories()) {
            dirCbModel.addElement(element);
        }
        if (dirCbModel.getSize() > 0) {
            cbPaths.setSelectedIndex(0);
        }
    }

    private void storeInput() {

        props.getHistoryProperties().setLastSearchMasks(getItemsToStore(maskCbModel, cbMask));
        props.getHistoryProperties().setLastFileMasks(getItemsToStore(fileCbModel, cbFiles));
        props.getHistoryProperties().setLastDirectories(getItemsToStore(dirCbModel, cbPaths));
    }

    private List<String> getItemsToStore(DefaultComboBoxModel model, JComboBox comboBox) {
        List<String> items = new LinkedList<>();
        int index = comboBox.getSelectedIndex() == -1 ? 0 : comboBox.getSelectedIndex();
        int inputHistorySize = props.getHistoryProperties().getInputHistorySize();

        //if new item
        if (comboBox.getSelectedIndex() == -1) {
            addIfNotExists(items, model.getSelectedItem().toString());
        }

        for (int i = 0; i < model.getSize(); i++) {
            addIfNotExists(items, model.getElementAt(i).toString());
        }

        if (items.size() > inputHistorySize) {
            items.remove(items.size() - 1);
        }

        model.removeAllElements();
        for (String item : items) {
            model.addElement(item);
        }
        comboBox.setSelectedIndex(index);

        return items;
    }

    private void addIfNotExists(List<String> list, String item) {
        if (!list.contains(item)) {
            list.add(item);
        }
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        SearchResult result = null;
        Document doc = staCode.getDocument();
        boolean firstRun = true;
        int offset = 0;
        String linePrefix = "";

        if (taResults.getSelectedRow() >= resultModel.getRowCount() || taResults.getSelectedRow() < 0) {
            return;
        }

        result = resultModel.get(taResults.getSelectedRow());

        staCode.setSyntaxEditingStyle(result.getSyntaxStyle());

        try {
            resetSyntaxTable();

            for (LineMatch match : result.getMatches()) {
                for (Line line : match.getLines()) {
                    offset = firstRun ? doc.getStartPosition().getOffset() : doc.getEndPosition().getOffset();
                    linePrefix = firstRun ? "" : "\n";

                    doc.insertString(offset,
                            String.format("%-5d\t", line.getLineNumber()) + line.getLine() + linePrefix, null);
                    firstRun = false;
                }
                //Add Separator
                if (result.getMatchCount() > 1) //if more than one matches
                {
                    String matchSeparator = "";
                    offset = firstRun ? doc.getStartPosition().getOffset() : doc.getEndPosition().getOffset();
                    linePrefix = firstRun ? "" : "\n";

                    for (int i = 0; i < 256; i++) {
                        matchSeparator += '\u2500';
                    }

                    doc.insertString(offset, matchSeparator + linePrefix, null);
                }
            }
        } catch (Exception ex) {
            log(LogLevel.ERROR, ex);
        }

        staCode.setSelectionStart(0);
    }

    private void resetSyntaxTable() throws Exception {
        staCode.getDocument().remove(staCode.getDocument().getStartPosition().getOffset(), staCode.getDocument().getLength());
    }

    private void setMacSpecificProperties() {
        try {
            //ToDo: Activate it again - find solution
//            System.setProperty("apple.laf.useScreenMenuBar", "true");
//            System.setProperty("com.apple.mrj.application.apple.menu.about.name", "ImageRotator");
//            System.setProperty("com.apple.mrj.application.apple.menu.about.name=JUnit", APPLICATION_VERSION);
            //Setting name doesn't work
//            System.setProperty(
//            "com.apple.mrj.application.apple.menu.about.name", "Name");
//            Application.getApplication().setDockIconImage(new javax.swing.ImageIcon(FileStorage.getResourceUrl("icon.png")).getImage());
//           
        } catch (Exception ex) {
            log(Logger.LogLevel.ERROR, ex);
        }
    }
}
TOP

Related Classes of ui.Main

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.