Search in sources :

Example 6 with BackgroundCommand

use of CCDD.CcddBackgroundCommand.BackgroundCommand in project CCDD by nasa.

the class CcddDbManagerDialog method initialize.

/**
 ********************************************************************************************
 * Create the project database manager dialog. This is executed in a separate thread since it
 * can take a noticeable amount time to complete, and by using a separate thread the GUI is
 * allowed to continue to update. The GUI menu commands, however, are disabled until the
 * telemetry scheduler initialization completes execution
 ********************************************************************************************
 */
private void initialize() {
    // Build the project database manager dialog in the background
    CcddBackgroundCommand.executeInBackground(ccddMain, new BackgroundCommand() {

        boolean errorFlag = false;

        // Create panels to hold the components of the dialog
        JPanel selectPnl = new JPanel(new GridBagLayout());

        // Set the initial layout manager characteristics
        GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing()), 0, 0);

        /**
         ************************************************************************************
         * Build the project database manager dialog
         ************************************************************************************
         */
        @Override
        protected void execute() {
            // Create a panel to hold the components of the dialog
            selectPnl.setBorder(BorderFactory.createEmptyBorder());
            // Create dialog based on supplied dialog type
            switch(dialogType) {
                case CREATE:
                    // Get the array containing the roles
                    String[] roles = dbControl.queryRoleList(CcddDbManagerDialog.this);
                    String[][] roleInfo = new String[roles.length][2];
                    // Step through each role
                    for (int index = 0; index < roles.length; index++) {
                        // Store the role name
                        roleInfo[index][0] = roles[index];
                    }
                    // from which to choose
                    if (!addRadioButtons(null, false, roleInfo, null, "Select project owner", selectPnl, gbc)) {
                        // Inform the user that no roles exist on the server
                        new CcddDialogHandler().showMessageDialog(ccddMain.getMainFrame(), "<html><b>No role exists", "Create Project", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                        errorFlag = true;
                    }
                    break;
                case OPEN:
                    // Get the project names and descriptions
                    getDatabaseInformation(true, false, null);
                    // projects from which to choose
                    if (!addRadioButtons((dbControl.getDatabaseName() == DEFAULT_DATABASE ? null : dbControl.getDatabaseName()), false, arrayItemData, disabledItems, "Select a project to open", selectPnl, gbc)) {
                        // Inform the user that no project exists on the server for which the
                        // current user has access
                        displayDatabaseError("Open");
                        errorFlag = true;
                    }
                    break;
                case RENAME:
                    // Get the project names and descriptions
                    getDatabaseInformation(true, false, dbControl.getDatabaseName());
                    // projects from which to choose
                    if (addRadioButtons(null, false, arrayItemData, disabledItems, "Select a project to rename", selectPnl, gbc)) {
                        // Create the rename project name and description labels and fields
                        addDatabaseInputFields("New project name", selectPnl, false, gbc);
                    } else // No project exists to choose
                    {
                        // Inform the user that no project exists on the server
                        displayDatabaseError("Rename");
                        errorFlag = true;
                    }
                    break;
                case COPY:
                    // Get the project names and descriptions
                    getDatabaseInformation(false, false, null);
                    // projects from which to choose
                    if (addRadioButtons(null, false, arrayItemData, disabledItems, "Select a project to copy", selectPnl, gbc)) {
                        // Create the copy project name and description labels and fields
                        addDatabaseInputFields("Project copy name", selectPnl, false, gbc);
                        // Create a date and time stamp check box
                        stampChkBx = new JCheckBox("Append date and time to project name");
                        stampChkBx.setBorder(BorderFactory.createEmptyBorder());
                        stampChkBx.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
                        stampChkBx.setSelected(false);
                        stampChkBx.setEnabled(false);
                        // Create a listener for check box selection actions
                        stampChkBx.addActionListener(new ActionListener() {

                            String timeStamp = "";

                            boolean isCopy = false;

                            /**
                             ****************************************************************
                             * Handle check box selection actions
                             ****************************************************************
                             */
                            @Override
                            public void actionPerformed(ActionEvent ae) {
                                // Check if the data and time stamp check box is selected
                                if (((JCheckBox) ae.getSource()).isSelected()) {
                                    // Get the current date and time stamp
                                    timeStamp = "_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
                                    isCopy = nameFld.getText().endsWith(COPY_APPEND);
                                    // Append the date and time stamp to the file name
                                    nameFld.setText(nameFld.getText().replaceFirst("(?:" + COPY_APPEND + "$|$)", timeStamp));
                                } else // The check box is not selected
                                {
                                    // Remove the date and time stamp
                                    nameFld.setText(nameFld.getText().replaceFirst(timeStamp, isCopy ? COPY_APPEND : ""));
                                }
                            }
                        });
                        gbc.insets.top = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() * 2;
                        gbc.gridy++;
                        selectPnl.add(stampChkBx, gbc);
                        gbc.insets.top = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing();
                    } else // No project exists to choose
                    {
                        // Inform the user that no project exists on the server
                        displayDatabaseError("Copy");
                        errorFlag = true;
                    }
                    break;
                case DELETE:
                    // Get the project names and descriptions
                    getDatabaseInformation(true, false, null);
                    // projects from which to choose
                    if (!addCheckBoxes(null, arrayItemData, disabledItems, "Select a project to delete", selectPnl)) {
                        // Inform the user that no project exists on the server
                        displayDatabaseError("Delete");
                        errorFlag = true;
                    }
                    break;
                case UNLOCK:
                    // Get the project names and descriptions
                    getDatabaseInformation(false, true, null);
                    // projects from which to choose
                    if (!addCheckBoxes(null, arrayItemData, disabledItems, "Select a project to unlock", selectPnl)) {
                        // Inform the user that no project exists on the server
                        displayDatabaseError("Unlock");
                        errorFlag = true;
                    }
                    break;
            }
        }

        /**
         ************************************************************************************
         * Project database manager dialog creation complete
         ************************************************************************************
         */
        @Override
        protected void complete() {
            // Check that no error occurred creating the dialog
            if (!errorFlag) {
                // Display the dialog based on supplied dialog type
                switch(dialogType) {
                    case CREATE:
                        // Create the project name and description labels and fields
                        addDatabaseInputFields("New project name", selectPnl, true, gbc);
                        // Display the project creation dialog
                        if (showOptionsDialog(ccddMain.getMainFrame(), selectPnl, "Create Project", DialogOption.CREATE_OPTION) == OK_BUTTON) {
                            // Create the project
                            dbControl.createDatabaseInBackground(nameFld.getText(), getRadioButtonSelected(), descriptionFld.getText());
                        }
                        break;
                    case OPEN:
                        // proceeding
                        if (showOptionsDialog(ccddMain.getMainFrame(), selectPnl, "Open Project", DialogOption.OPEN_OPTION, true) == OK_BUTTON && ccddMain.ignoreUncommittedChanges("Open Project", "Discard changes?", true, null, CcddDbManagerDialog.this)) {
                            // Open the selected project
                            dbControl.openDatabaseInBackground(getRadioButtonSelected());
                        }
                        break;
                    case RENAME:
                        // altered for the currently open project
                        if (showOptionsDialog(ccddMain.getMainFrame(), selectPnl, "Rename Project", DialogOption.RENAME_OPTION, true) == OK_BUTTON && (!getRadioButtonSelected().equals(dbControl.getDatabaseName()) || ccddMain.ignoreUncommittedChanges("Rename Project", "Discard changes?", true, null, CcddDbManagerDialog.this))) {
                            // Rename the project
                            dbControl.renameDatabaseInBackground(getRadioButtonSelected(), nameFld.getText(), descriptionFld.getText());
                        }
                        break;
                    case COPY:
                        // discarding the changes before proceeding
                        if (showOptionsDialog(ccddMain.getMainFrame(), selectPnl, "Copy Project", DialogOption.COPY_OPTION, true) == OK_BUTTON && (!getRadioButtonSelected().equals(dbControl.getDatabaseName()) || (getRadioButtonSelected().equals(dbControl.getDatabaseName()) && ccddMain.ignoreUncommittedChanges("Copy Project", "Discard changes?", true, null, CcddDbManagerDialog.this)))) {
                            // Copy the project
                            dbControl.copyDatabaseInBackground(getRadioButtonSelected(), nameFld.getText(), descriptionFld.getText());
                        }
                        break;
                    case DELETE:
                        // Display the project deletion dialog
                        if (showOptionsDialog(ccddMain.getMainFrame(), selectPnl, "Delete Project(s)", DialogOption.DELETE_OPTION, true) == OK_BUTTON) {
                            // Step through each selected project name
                            for (String name : getCheckBoxSelected()) {
                                // Delete the project
                                dbControl.deleteDatabaseInBackground(name);
                            }
                        }
                        break;
                    case UNLOCK:
                        // Display the project unlock dialog
                        if (showOptionsDialog(ccddMain.getMainFrame(), selectPnl, "Unlock Project(s)", DialogOption.UNLOCK_OPTION, true) == OK_BUTTON) {
                            // Step through each selected project name
                            for (String name : getCheckBoxSelected()) {
                                // Unlock the project
                                dbControl.setDatabaseLockStatus(name, false);
                            }
                        }
                        break;
                }
            }
        }
    });
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) GridBagLayout(java.awt.GridBagLayout) ActionEvent(java.awt.event.ActionEvent) JCheckBox(javax.swing.JCheckBox) ActionListener(java.awt.event.ActionListener) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand) SimpleDateFormat(java.text.SimpleDateFormat)

Example 7 with BackgroundCommand

use of CCDD.CcddBackgroundCommand.BackgroundCommand in project CCDD by nasa.

the class CcddDbVerificationHandler method verifyDatabase.

/**
 ********************************************************************************************
 * Perform a consistency check of the project database. Query the user for permission to make
 * corrections, then apply the corrections at completion of the check. This method is executed
 * in a separate thread since it can take a noticeable amount time to complete, and by using a
 * separate thread the GUI is allowed to continue to update. The GUI menu commands, however,
 * are disabled until the table data consistency check completes execution
 ********************************************************************************************
 */
private void verifyDatabase() {
    CcddBackgroundCommand.executeInBackground(ccddMain, new BackgroundCommand() {

        /**
         ************************************************************************************
         * Verification cancellation dialog class
         ************************************************************************************
         */
        @SuppressWarnings("serial")
        class HaltDialog extends CcddDialogHandler {

            /**
             ********************************************************************************
             * Handle the close dialog button action
             ********************************************************************************
             */
            @Override
            protected void closeDialog(int button) {
                // Set the flag to cancel verification
                canceled = true;
                super.closeDialog(button);
            }
        }

        HaltDialog cancelDialog = new HaltDialog();

        /**
         ************************************************************************************
         * Perform project database verification
         ************************************************************************************
         */
        @Override
        protected void execute() {
            // Set the initial layout manager characteristics
            GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2, ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing(), 0, ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing()), 0, 0);
            // Create the cancellation dialog
            JPanel dialogPnl = new JPanel(new GridBagLayout());
            dialogPnl.setBorder(BorderFactory.createEmptyBorder());
            JLabel textLbl = new JLabel("<html><b>Verification in progress...<br><br>", SwingConstants.LEFT);
            textLbl.setFont(ModifiableFontInfo.LABEL_PLAIN.getFont());
            gbc.gridy++;
            dialogPnl.add(textLbl, gbc);
            JLabel textLbl2 = new JLabel("<html><b>" + CcddUtilities.colorHTMLText("*** Press </i>Halt<i> " + "to terminate verification ***", Color.RED) + "</b><br><br>", SwingConstants.CENTER);
            textLbl2.setFont(ModifiableFontInfo.LABEL_PLAIN.getFont());
            gbc.gridy++;
            dialogPnl.add(textLbl2, gbc);
            // Set the total number of verification steps (this is the number of methods called
            // to verify each portion of the database) and use it to calculate the number of
            // divisions within each step
            int numVerificationSteps = 6;
            numDivisionPerStep = 100 / numVerificationSteps;
            // Add a progress bar to the dialog
            progBar = new JProgressBar(0, numVerificationSteps * numDivisionPerStep);
            progBar.setValue(0);
            progBar.setString("Verify owners");
            progBar.setStringPainted(true);
            progBar.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
            gbc.insets.left = ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() * 2;
            gbc.insets.right = ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() * 2;
            gbc.insets.bottom = 0;
            gbc.gridy++;
            dialogPnl.add(progBar, gbc);
            // Display the verification cancellation dialog
            cancelDialog.showOptionsDialog(ccddMain.getMainFrame(), dialogPnl, "Verifying Project", DialogOption.HALT_OPTION, false, false);
            // Set flags indicating no changes are pending, no inconsistencies exist, and the
            // user hasn't canceled the check
            isChanges = false;
            try {
                // Get the comments for all data tables
                comments = dbTable.queryDataTableComments(ccddMain.getMainFrame());
                // Get metadata for all tables
                ResultSet tableResult = dbCommand.getConnection().getMetaData().getTables(null, null, null, new String[] { "TABLE" });
                // Check if verification isn't canceled
                if (!canceled) {
                    // Check for inconsistencies in the owner role of the project database and
                    // its tables, sequences, indices, and functions
                    verifyOwners();
                    // Check if verification isn't canceled
                    if (!canceled) {
                        // Update the progress bar
                        progBar.setValue(numDivisionPerStep);
                        progBar.setString("Verify internal tables");
                        // Check for inconsistencies in the internal tables
                        verifyInternalTables(tableResult);
                        // Check if verification isn't canceled
                        if (!canceled) {
                            // Update the progress bar
                            progBar.setValue(numDivisionPerStep * 2);
                            progBar.setString("Verify path references");
                            // Verify the table and variable path references in the internal
                            // tables
                            verifyPathReferences(tableResult);
                            // Check if verification isn't canceled
                            if (!canceled) {
                                // Update the progress bar
                                progBar.setValue(numDivisionPerStep * 3);
                                progBar.setString("Verify input data types");
                                // verify the input data types in the table types and data
                                // fields internal tables
                                verifyInputTypes(tableResult);
                                // Check if verification isn't canceled
                                if (!canceled) {
                                    // Update the progress bar
                                    progBar.setValue(numDivisionPerStep * 4);
                                    progBar.setString("Verify table types");
                                    // Check for inconsistencies between the table type
                                    // definitions and the tables of that type
                                    verifyTableTypes(tableResult);
                                    // Check if verification isn't canceled
                                    if (!canceled) {
                                        // Update the progress bar
                                        progBar.setValue(numDivisionPerStep * 5);
                                        progBar.setString("Verify data tables");
                                        // Check for inconsistencies within the data tables
                                        verifyDataTables();
                                        // Update the progress bar
                                        progBar.setValue(numDivisionPerStep * numVerificationSteps);
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (SQLException se) {
                // Inform the user that obtaining the project database metadata failed
                eventLog.logFailEvent(ccddMain.getMainFrame(), "Error obtaining project database '" + dbControl.getDatabaseName() + "' metadata; cause '" + se.getMessage() + "'", "<html><b>Error obtaining project database '" + dbControl.getDatabaseName() + "'metadata");
            } catch (Exception e) {
                // Display a dialog providing details on the unanticipated error
                CcddUtilities.displayException(e, ccddMain.getMainFrame());
            }
        }

        /**
         ************************************************************************************
         * Project database verification command complete
         ************************************************************************************
         */
        @Override
        protected void complete() {
            // Check if the user didn't cancel verification
            if (!canceled) {
                // Close the cancellation dialog
                cancelDialog.closeDialog();
                // Perform any corrections to the database authorized by the user
                updateDatabase();
            } else // Verification was canceled
            {
                // Note that verification was canceled in the event log
                eventLog.logEvent(STATUS_MSG, "Verification terminated by user");
            }
        }
    });
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) GridBagLayout(java.awt.GridBagLayout) SQLException(java.sql.SQLException) JProgressBar(javax.swing.JProgressBar) JLabel(javax.swing.JLabel) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand)

Example 8 with BackgroundCommand

use of CCDD.CcddBackgroundCommand.BackgroundCommand in project CCDD by nasa.

the class CcddScriptManagerDialog method initialize.

/**
 ********************************************************************************************
 * Create the script association manager dialog. This is executed in a separate thread since it
 * can take a noticeable amount time to complete, and by using a separate thread the GUI is
 * allowed to continue to update. The GUI menu commands, however, are disabled until the
 * telemetry scheduler initialization completes execution
 ********************************************************************************************
 */
private void initialize() {
    // user confirms ignoring the changes
    if (ccddMain.ignoreUncommittedChanges("Script Manager", "Ignore changes?", false, null, CcddScriptManagerDialog.this)) {
        // Build the script association manager dialog in the background
        CcddBackgroundCommand.executeInBackground(ccddMain, new BackgroundCommand() {

            // Create panels to hold the components of the dialog
            JPanel dialogPnl = new JPanel(new GridBagLayout());

            JPanel buttonPnl = new JPanel();

            /**
             ********************************************************************************
             * Build the script association manager dialog
             ********************************************************************************
             */
            @Override
            protected void execute() {
                isNodeSelectionChanging = false;
                // Create borders for the input fields
                border = BorderFactory.createCompoundBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.GRAY), BorderFactory.createEmptyBorder(ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing()));
                Border emptyBorder = BorderFactory.createEmptyBorder();
                // Set the initial layout manager characteristics
                GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(0, 0, ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing()), 0, 0);
                dialogPnl.setBorder(emptyBorder);
                // Create a panel to contain the script file name, association name, and
                // association description labels and fields
                JPanel inputPnl = new JPanel(new GridBagLayout());
                // Add the script file selection components to the input panel
                inputPnl.add(createScriptSelectionPanel(), gbc);
                // Create the name label and field, and add these to the input panel
                JLabel nameLbl = new JLabel("Script association name");
                nameLbl.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
                gbc.insets.top = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2;
                gbc.gridy++;
                inputPnl.add(nameLbl, gbc);
                nameFld = new JTextField("", 1);
                nameFld.setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
                nameFld.setEditable(true);
                nameFld.setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
                nameFld.setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
                nameFld.setBorder(border);
                gbc.insets.top = 0;
                gbc.insets.left = ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing();
                gbc.weightx = 1.0;
                gbc.gridy++;
                inputPnl.add(nameFld, gbc);
                // Create the description label and field, and add these to the input panel
                JLabel descriptionLbl = new JLabel("Script association description");
                descriptionLbl.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
                gbc.insets.top = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2;
                gbc.insets.left = 0;
                gbc.weightx = 0.0;
                gbc.gridy++;
                inputPnl.add(descriptionLbl, gbc);
                descriptionFld = new JTextArea("", 3, 1);
                descriptionFld.setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
                descriptionFld.setEditable(true);
                descriptionFld.setWrapStyleWord(true);
                descriptionFld.setLineWrap(true);
                descriptionFld.setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
                descriptionFld.setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
                descriptionFld.setBorder(emptyBorder);
                JScrollPane scrollPane = new JScrollPane(descriptionFld);
                scrollPane.setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
                scrollPane.setBorder(emptyBorder);
                scrollPane.setViewportBorder(border);
                scrollPane.setMinimumSize(scrollPane.getPreferredSize());
                gbc.insets.top = 0;
                gbc.insets.left = ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing();
                gbc.insets.bottom = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() * 2;
                gbc.gridwidth = GridBagConstraints.REMAINDER;
                gbc.weightx = 1.0;
                gbc.weighty = 1.0;
                gbc.gridy++;
                inputPnl.add(scrollPane, gbc);
                // Add the input panel and the table selection components to the inputs pane
                // within a horizontally split pane. Use a separator to denote the split pane's
                // drag component
                JSeparator inputSep = new JSeparator(SwingConstants.VERTICAL);
                inputSep.setForeground(dialogPnl.getBackground().darker());
                CustomSplitPane inputsPane = new CustomSplitPane(inputPnl, createSelectionPanel("Select associated tables", TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION), inputSep, JSplitPane.HORIZONTAL_SPLIT);
                // Add the inputs pane and the script association table components to the
                // dialog within a vertically split pane. Use a separator to denote the split
                // pane's drag component
                JSeparator assnSep = new JSeparator();
                assnSep.setForeground(dialogPnl.getBackground().darker());
                gbc.weighty = 1.0;
                gbc.insets.top = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing();
                gbc.insets.bottom = 0;
                gbc.gridy = 0;
                dialogPnl.add(new CustomSplitPane(inputsPane, scriptHandler.getAssociationsPanel("Script Associations", true, CcddScriptManagerDialog.this), assnSep, JSplitPane.VERTICAL_SPLIT), gbc);
                // Get a reference to the script associations table to shorten subsequent calls
                assnsTable = scriptHandler.getAssociationsTable();
                // Store the initial table data
                doAssnUpdatesComplete(false);
                // Add a listener for script association table row selection changes
                assnsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

                    /**
                     ************************************************************************
                     * Handle a table row selection change. Populate the script description
                     * field, file field, and table tree based on the first selected
                     * associations table row
                     ************************************************************************
                     */
                    @Override
                    public void valueChanged(ListSelectionEvent lse) {
                        // for a keyboard input this returns false)
                        if (!lse.getValueIsAdjusting()) {
                            // Get the first selected table row
                            int row = assnsTable.getSelectedRow();
                            // Check if a table row item is selected
                            if (row != -1) {
                                // Store the association name in the the name field
                                nameFld.setText(assnsTable.getValueAt(row, assnsTable.convertColumnIndexToView(AssociationsTableColumnInfo.NAME.ordinal())).toString());
                                // Store the association description in the the description
                                // field
                                descriptionFld.setText(assnsTable.getValueAt(row, assnsTable.convertColumnIndexToView(AssociationsTableColumnInfo.DESCRIPTION.ordinal())).toString());
                                // Store the script file name with path in the the script file
                                // field
                                scriptFld.setText(assnsTable.getValueAt(row, assnsTable.convertColumnIndexToView(AssociationsTableColumnInfo.SCRIPT_FILE.ordinal())).toString());
                                // Separate the table member portion into the individual table
                                // names. The line breaks used for HTML formatting must be
                                // replaced by line feed characters so that the split is made
                                // correctly
                                String[] tableNames = CcddUtilities.removeHTMLTags(assnsTable.getValueAt(row, assnsTable.convertColumnIndexToView(AssociationsTableColumnInfo.MEMBERS.ordinal())).toString().replaceAll("<br>", "\n")).split(Pattern.quote(ASSN_TABLE_SEPARATOR));
                                List<TreePath> paths = new ArrayList<>();
                                // Step through each table name
                                for (String tableName : tableNames) {
                                    ToolTipTreeNode node;
                                    // Check if the name refers to a group
                                    if (tableName.startsWith(GROUP_DATA_FIELD_IDENT)) {
                                        // Get the node in the table tree for this group
                                        node = tableTree.getNodeByNodeName(tableName.substring(GROUP_DATA_FIELD_IDENT.length()));
                                    } else // The name refers to a table
                                    {
                                        // Get the node in the table tree for this table name
                                        node = tableTree.getNodeByNodePath(tableName);
                                    }
                                    // Check if the table name is in the tree
                                    if (node != null) {
                                        // Add the path to the list
                                        paths.add(CcddCommonTreeHandler.getPathFromNode(node));
                                    }
                                }
                                // Select the associated tables in the table tree
                                tableTree.setSelectionPaths(paths.toArray(new TreePath[0]));
                            }
                        }
                    }
                });
                // Define the buttons for the lower panel: Add association button
                JButton btnAddAssn = CcddButtonPanelHandler.createButton("Add", INSERT_ICON, KeyEvent.VK_A, "Add the currently defined script association");
                // Add a listener for the Add button
                btnAddAssn.addActionListener(new ActionListener() {

                    /**
                     ************************************************************************
                     * Add a new script association
                     ************************************************************************
                     */
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        // Check that a script is specified
                        if (!scriptFld.getText().trim().isEmpty()) {
                            addAssociation(TableInsertionPoint.START);
                        } else // The script file field is blank
                        {
                            // Inform the user that a script must be selected
                            new CcddDialogHandler().showMessageDialog(ccddMain.getMainFrame(), "<html><b>Must enter or select a script", "Script Missing", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                        }
                    }
                });
                // Remove script association(s) button
                JButton btnRemoveAssn = CcddButtonPanelHandler.createButton("Remove", DELETE_ICON, KeyEvent.VK_R, "Remove the selected script association(s)");
                // Add a listener for the Remove button
                btnRemoveAssn.addActionListener(new ActionListener() {

                    /**
                     ************************************************************************
                     * Remove the selected script association(s)
                     ************************************************************************
                     */
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        removeAssociations();
                    }
                });
                // Replace script association(s) button
                JButton btnReplaceAssn = CcddButtonPanelHandler.createButton("Replace", REPLACE_ICON, KeyEvent.VK_P, "Replace the selected script association");
                // Add a listener for the Replace button
                btnReplaceAssn.addActionListener(new ActionListener() {

                    /**
                     ************************************************************************
                     * Replace the selected script association
                     ************************************************************************
                     */
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        replaceAssociation();
                    }
                });
                // Move Up button
                JButton btnMoveUp = CcddButtonPanelHandler.createButton("Up", UP_ICON, KeyEvent.VK_U, "Move the selected row(s) up");
                // Create a listener for the Move Up command
                btnMoveUp.addActionListener(new ValidateCellActionListener() {

                    /**
                     ************************************************************************
                     * Move the selected row(s) up in the table
                     ************************************************************************
                     */
                    @Override
                    protected void performAction(ActionEvent ae) {
                        assnsTable.moveRowUp();
                    }

                    /**
                     ************************************************************************
                     * Get the reference to the currently displayed table
                     ************************************************************************
                     */
                    @Override
                    protected CcddJTableHandler getTable() {
                        return assnsTable;
                    }
                });
                // Move Down button
                JButton btnMoveDown = CcddButtonPanelHandler.createButton("Down", DOWN_ICON, KeyEvent.VK_W, "Move the selected row(s) down");
                // Create a listener for the Move Down command
                btnMoveDown.addActionListener(new ValidateCellActionListener() {

                    /**
                     ************************************************************************
                     * Move the selected row(s) down in the table
                     ************************************************************************
                     */
                    @Override
                    protected void performAction(ActionEvent ae) {
                        assnsTable.moveRowDown();
                    }

                    /**
                     ************************************************************************
                     * Get the reference to the currently displayed table
                     ************************************************************************
                     */
                    @Override
                    protected CcddJTableHandler getTable() {
                        return assnsTable;
                    }
                });
                // Undo button
                JButton btnUndo = CcddButtonPanelHandler.createButton("Undo", UNDO_ICON, KeyEvent.VK_Z, "Undo the last edit action");
                // Create a listener for the Undo command
                btnUndo.addActionListener(new ValidateCellActionListener() {

                    /**
                     ************************************************************************
                     * Undo the last addition to the script association table
                     ************************************************************************
                     */
                    @Override
                    protected void performAction(ActionEvent ae) {
                        assnsTable.getUndoManager().undo();
                    }

                    /**
                     ************************************************************************
                     * Get the reference to the currently displayed table
                     ************************************************************************
                     */
                    @Override
                    protected CcddJTableHandler getTable() {
                        return assnsTable;
                    }
                });
                // Redo button
                JButton btnRedo = CcddButtonPanelHandler.createButton("Redo", REDO_ICON, KeyEvent.VK_Y, "Redo the last undone edit action");
                // Create a listener for the Redo command
                btnRedo.addActionListener(new ValidateCellActionListener() {

                    /**
                     ************************************************************************
                     * Redo the last addition to the script association table that was undone
                     ************************************************************************
                     */
                    @Override
                    protected void performAction(ActionEvent ae) {
                        assnsTable.getUndoManager().redo();
                    }

                    /**
                     ************************************************************************************
                     * Get the reference to the currently displayed table
                     ************************************************************************************
                     */
                    @Override
                    protected CcddJTableHandler getTable() {
                        return assnsTable;
                    }
                });
                // Script execution button
                btnExecute = CcddButtonPanelHandler.createButton("Execute", EXECUTE_ICON, KeyEvent.VK_E, "Execute the selected script association(s)");
                // Add a listener for the Execute button
                btnExecute.addActionListener(new ActionListener() {

                    /**
                     ************************************************************************
                     * Execute the selected script association(s)
                     ************************************************************************
                     */
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        // Execute the selected associations
                        scriptHandler.executeScriptAssociations(tableTree, CcddScriptManagerDialog.this);
                    }
                });
                // Store script associations button
                JButton btnStoreAssns = CcddButtonPanelHandler.createButton("Store", STORE_ICON, KeyEvent.VK_S, "Store the updated script associations to the database");
                // Add a listener for the Store button
                btnStoreAssns.addActionListener(new ActionListener() {

                    /**
                     ************************************************************************
                     * Store the script associations in the database
                     ************************************************************************
                     */
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        // associations
                        if (assnsTable.isTableChanged(committedAssnsData, Arrays.asList(new Integer[] { AssociationsTableColumnInfo.AVAILABLE.ordinal() })) && new CcddDialogHandler().showMessageDialog(CcddScriptManagerDialog.this, "<html><b>Store script associations?", "Store Associations", JOptionPane.QUESTION_MESSAGE, DialogOption.OK_CANCEL_OPTION) == OK_BUTTON) {
                            // Disable the dialog buttons until the updates complete
                            setControlsEnabled(false);
                            // Store the script associations list into the database
                            dbTable.storeInformationTableInBackground(InternalTable.ASSOCIATIONS, createAssociationsFromTable(), null, CcddScriptManagerDialog.this);
                        }
                    }
                });
                // Close button
                JButton btnClose = CcddButtonPanelHandler.createButton("Close", CLOSE_ICON, KeyEvent.VK_C, "Close the script association manager");
                // Add a listener for the Close button
                btnClose.addActionListener(new ActionListener() {

                    /**
                     ************************************************************************
                     * Close the script association dialog
                     ************************************************************************
                     */
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        // user elects to discard the changes
                        if (!isAssociationsChanged() || new CcddDialogHandler().showMessageDialog(CcddScriptManagerDialog.this, "<html><b>Discard changes?", "Discard Changes", JOptionPane.QUESTION_MESSAGE, DialogOption.OK_CANCEL_OPTION) == OK_BUTTON) {
                            // Reset the reference to the script associations manager in the
                            // script handler since the handler remains active)
                            scriptHandler.setScriptDialog(null);
                            // Close the dialog
                            closeFrame();
                        }
                    }
                });
                // Add buttons in the order in which they'll appear (left to right, top to
                // bottom)
                buttonPnl.add(btnAddAssn);
                buttonPnl.add(btnReplaceAssn);
                buttonPnl.add(btnMoveUp);
                buttonPnl.add(btnUndo);
                buttonPnl.add(btnStoreAssns);
                buttonPnl.add(btnRemoveAssn);
                buttonPnl.add(btnExecute);
                buttonPnl.add(btnMoveDown);
                buttonPnl.add(btnRedo);
                buttonPnl.add(btnClose);
                // Distribute the buttons across two rows
                setButtonRows(2);
            }

            /**
             ********************************************************************************
             * Script association manager dialog creation complete
             ********************************************************************************
             */
            @Override
            protected void complete() {
                // Display the script association management dialog
                createFrame(ccddMain.getMainFrame(), dialogPnl, buttonPnl, btnExecute, DIALOG_TITLE, null);
            }
        });
    }
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) JTextArea(javax.swing.JTextArea) GridBagLayout(java.awt.GridBagLayout) ActionEvent(java.awt.event.ActionEvent) ListSelectionEvent(javax.swing.event.ListSelectionEvent) ArrayList(java.util.ArrayList) JButton(javax.swing.JButton) JTextField(javax.swing.JTextField) CustomSplitPane(CCDD.CcddClassesComponent.CustomSplitPane) JSeparator(javax.swing.JSeparator) ValidateCellActionListener(CCDD.CcddClassesComponent.ValidateCellActionListener) ToolTipTreeNode(CCDD.CcddClassesComponent.ToolTipTreeNode) JScrollPane(javax.swing.JScrollPane) JLabel(javax.swing.JLabel) TableInsertionPoint(CCDD.CcddConstants.TableInsertionPoint) ListSelectionListener(javax.swing.event.ListSelectionListener) TreePath(javax.swing.tree.TreePath) ActionListener(java.awt.event.ActionListener) ValidateCellActionListener(CCDD.CcddClassesComponent.ValidateCellActionListener) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand) Border(javax.swing.border.Border) BevelBorder(javax.swing.border.BevelBorder)

Example 9 with BackgroundCommand

use of CCDD.CcddBackgroundCommand.BackgroundCommand in project CCDD by nasa.

the class CcddTelemetrySchedulerDialog method initialize.

/**
 ********************************************************************************************
 * Create the telemetry scheduler dialog. This is executed in a separate thread since it can
 * take a noticeable amount time to complete, and by using a separate thread the GUI is allowed
 * to continue to update. The GUI menu commands, however, are disabled until the telemetry
 * scheduler initialization completes execution
 ********************************************************************************************
 */
private void initialize() {
    // Build the telemetry scheduler dialog in the background
    CcddBackgroundCommand.executeInBackground(ccddMain, new BackgroundCommand() {

        // Create a button panel
        JPanel buttonPnl = new JPanel();

        /**
         ************************************************************************************
         * Build the telemetry scheduler dialog
         ************************************************************************************
         */
        @Override
        protected void execute() {
            // Create a tree containing all of the variables. This is used for determining
            // bit-packing and variable relative position
            allVariableTree = new CcddTableTreeHandler(ccddMain, TableTreeType.INSTANCE_STRUCTURES_WITH_PRIMITIVES_AND_RATES, ccddMain.getMainFrame());
            // Expand the tree so that all nodes are 'visible'
            allVariableTree.setTreeExpansion(true);
            allVariableTreePaths = new ArrayList<String>();
            // Step through all of the nodes in the variable tree
            for (Enumeration<?> element = allVariableTree.getRootNode().preorderEnumeration(); element.hasMoreElements(); ) {
                // Convert the variable path to a string and add it to the list
                allVariableTreePaths.add(allVariableTree.getFullVariablePath(((ToolTipTreeNode) element.nextElement()).getPath()));
            }
            // Load the stored telemetry scheduler data from the project database
            schedulerDb.loadStoredData();
            // Auto-fill button
            btnAutoFill = CcddButtonPanelHandler.createButton("Auto-fill", AUTO_CREATE_ICON, KeyEvent.VK_F, "Auto-fill the message table with the variables");
            // Create a listener for the Auto-fill button
            btnAutoFill.addActionListener(new ValidateCellActionListener() {

                /**
                 ****************************************************************************
                 * Auto-fill the variables into the telemetry scheduler for the currently
                 * selected data stream
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    // Run auto-fill
                    activeSchHandler.autoFill();
                }

                /**
                 ****************************************************************************
                 * Get the reference to the currently displayed table
                 ****************************************************************************
                 */
                @Override
                protected CcddJTableHandler getTable() {
                    return activeSchHandler.getSchedulerEditor().getTable();
                }
            });
            // Clear Rate button
            btnClearRate = CcddButtonPanelHandler.createButton("Clear Rate", UNDO_ICON, KeyEvent.VK_R, "Remove the variables of the currently selected rate from all messages");
            // Add a listener for the Clear Rate button
            btnClearRate.addActionListener(new ValidateCellActionListener() {

                /**
                 ****************************************************************************
                 * Remove the variables of the currently selected rate from all messages in the
                 * currently selected data stream
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    activeSchHandler.getSchedulerEditor().clearVariablesFromMessages(activeSchHandler.getSchedulerInput().getSelectedRate());
                }

                /**
                 ****************************************************************************
                 * Get the reference to the currently displayed table
                 ****************************************************************************
                 */
                @Override
                protected CcddJTableHandler getTable() {
                    return activeSchHandler.getSchedulerEditor().getTable();
                }
            });
            // Clear Msgs button
            btnClear = CcddButtonPanelHandler.createButton("Clear Msgs", UNDO_ICON, KeyEvent.VK_R, "Remove the variables from all messages");
            // Add a listener for the Clear Msgs button
            btnClear.addActionListener(new ValidateCellActionListener() {

                /**
                 ****************************************************************************
                 * Remove the variables from all messages in the currently selected data stream
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    activeSchHandler.getSchedulerEditor().clearVariablesFromMessages(null);
                }

                /**
                 ****************************************************************************
                 * Get the reference to the currently displayed table
                 ****************************************************************************
                 */
                @Override
                protected CcddJTableHandler getTable() {
                    return activeSchHandler.getSchedulerEditor().getTable();
                }
            });
            // Add Sub-msg button
            btnAddSubMessage = CcddButtonPanelHandler.createButton("Add Sub-msg", INSERT_ICON, KeyEvent.VK_A, "Add a sub-message to the currently selected message");
            // Create a listener for the Add Sub-msg button
            btnAddSubMessage.addActionListener(new ValidateCellActionListener() {

                /**
                 ****************************************************************************
                 * Add a sub-message to the current message
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    activeSchHandler.getSchedulerEditor().addSubMessage();
                }

                /**
                 ****************************************************************************
                 * Get the reference to the currently displayed table
                 ****************************************************************************
                 */
                @Override
                protected CcddJTableHandler getTable() {
                    return activeSchHandler.getSchedulerEditor().getTable();
                }
            });
            // Del Sub-msg button
            btnDeleteSubMessage = CcddButtonPanelHandler.createButton("Del Sub-msg", DELETE_ICON, KeyEvent.VK_D, "Delete the currently selected sub-message");
            // Create a listener for the Del Sub-msg button
            btnDeleteSubMessage.addActionListener(new ValidateCellActionListener() {

                /**
                 ****************************************************************************
                 * Delete the current sub-message
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    activeSchHandler.getSchedulerEditor().deleteSubMessage();
                }

                /**
                 ****************************************************************************
                 * Get the reference to the currently displayed table
                 ****************************************************************************
                 */
                @Override
                protected CcddJTableHandler getTable() {
                    return activeSchHandler.getSchedulerEditor().getTable();
                }
            });
            // Assign message names and IDs button
            btnAssign = CcddButtonPanelHandler.createButton("Assign Msgs", AUTO_CREATE_ICON, KeyEvent.VK_M, "Automatically assign message names and/or IDs to the messages and sub-messages");
            // Add a listener for the Assign Msgs button
            btnAssign.addActionListener(new ValidateCellActionListener() {

                /**
                 ****************************************************************************
                 * Automatically assign names and/or IDs to the telemetry messages and
                 * sub-messages
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    new CcddAssignMessageIDDialog(ccddMain, activeSchHandler.getCurrentMessages(), CcddTelemetrySchedulerDialog.this);
                }

                /**
                 ****************************************************************************
                 * Get the reference to the currently displayed table
                 ****************************************************************************
                 */
                @Override
                protected CcddJTableHandler getTable() {
                    return activeSchHandler.getSchedulerEditor().getTable();
                }
            });
            // Store button
            btnStore = CcddButtonPanelHandler.createButton("Store", STORE_ICON, KeyEvent.VK_S, "Store the message updates in the project database");
            // Add a listener for the Store button
            btnStore.addActionListener(new ValidateCellActionListener() {

                /**
                 ****************************************************************************
                 * Store the data from the various data streams into the database
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    // storing the changes
                    if (isChanges() && new CcddDialogHandler().showMessageDialog(CcddTelemetrySchedulerDialog.this, "<html><b>Store changes?", "Store Changes", JOptionPane.QUESTION_MESSAGE, DialogOption.OK_CANCEL_OPTION) == OK_BUTTON) {
                        // Store the messages in the project database
                        storeData();
                    }
                }

                /**
                 ****************************************************************************
                 * Get the reference to the currently displayed table
                 ****************************************************************************
                 */
                @Override
                protected CcddJTableHandler getTable() {
                    return activeSchHandler.getSchedulerEditor().getTable();
                }
            });
            // Create a button to close the dialog
            btnClose = CcddButtonPanelHandler.createButton("Close", CLOSE_ICON, KeyEvent.VK_C, "Close the telemetry scheduler");
            // Add a listener for the Close button
            btnClose.addActionListener(new ValidateCellActionListener() {

                /**
                 ****************************************************************************
                 * Close the telemetry scheduler dialog
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    windowCloseButtonAction();
                }

                /**
                 ****************************************************************************
                 * Get the reference to the currently displayed table
                 ****************************************************************************
                 */
                @Override
                protected CcddJTableHandler getTable() {
                    return activeSchHandler.getSchedulerEditor().getTable();
                }
            });
            // Add buttons in the order in which they'll appear (left to right, top to bottom)
            buttonPnl.add(btnAutoFill);
            buttonPnl.add(btnClearRate);
            buttonPnl.add(btnAddSubMessage);
            buttonPnl.add(btnStore);
            buttonPnl.add(btnAssign);
            buttonPnl.add(btnClear);
            buttonPnl.add(btnDeleteSubMessage);
            buttonPnl.add(btnClose);
            // Create two rows of buttons
            setButtonRows(2);
            // Create a tabbed pane in which to place the scheduler handlers
            tabbedPane = new DnDTabbedPane(SwingConstants.TOP) {

                /**
                 ****************************************************************************
                 * Update the scheduler list order following a tab move
                 ****************************************************************************
                 */
                @Override
                protected Object tabMoveCleanup(int oldTabIndex, int newTabIndex, Object tabContents) {
                    // Adjust the new tab index if moving the tab to a higher index
                    newTabIndex -= newTabIndex > oldTabIndex ? 1 : 0;
                    // Re-order the rate information based on the new tab order
                    // Re-order the rate information based on the new tab order
                    RateInformation[] rateInfoArray = rateHandler.getRateInformation().toArray(new RateInformation[0]);
                    rateInfoArray = (RateInformation[]) CcddUtilities.moveArrayMember(rateInfoArray, oldTabIndex, newTabIndex);
                    List<RateInformation> rateInfoList = new ArrayList<RateInformation>(rateInfoArray.length);
                    rateInfoList.addAll(Arrays.asList(rateInfoArray));
                    rateHandler.setRateInformation(rateInfoList);
                    // Get the reference to the moved tab's original location in the list
                    CcddSchedulerHandler editor = schHandlers.get(oldTabIndex);
                    // Remove the tab
                    schHandlers.remove(oldTabIndex);
                    // Add the tab at its new location
                    schHandlers.add(newTabIndex, editor);
                    // Update the active tab pointer to the moved tab
                    activeSchHandler = schHandlers.get(tabbedPane.getSelectedIndex());
                    return editor;
                }
            };
            tabbedPane.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
            // Listen for tab selection changes
            tabbedPane.addChangeListener(new ChangeListener() {

                /**
                 ****************************************************************************
                 * Update the editor to the one associated with the selected tab
                 ****************************************************************************
                 */
                @Override
                public void stateChanged(ChangeEvent ce) {
                    // Set the active editor to the one indicated by the currently selected tab
                    activeSchHandler = schHandlers.get(tabbedPane.getSelectedIndex());
                }
            });
            // Add the scheduler handlers to the tabbed pane
            addDataStreams();
            // Set the first tab as the active editor
            activeSchHandler = schHandlers.get(0);
        }

        /**
         ************************************************************************************
         * Telemetry scheduler dialog creation complete
         ************************************************************************************
         */
        @Override
        protected void complete() {
            // Display the telemetry scheduler dialog
            showOptionsDialog(ccddMain.getMainFrame(), tabbedPane, buttonPnl, btnClose, "Telemetry Scheduler", true);
        }
    });
}
Also used : JPanel(javax.swing.JPanel) Enumeration(java.util.Enumeration) ActionEvent(java.awt.event.ActionEvent) ArrayList(java.util.ArrayList) RateInformation(CCDD.CcddClassesDataTable.RateInformation) DnDTabbedPane(CCDD.CcddClassesComponent.DnDTabbedPane) ChangeEvent(javax.swing.event.ChangeEvent) ValidateCellActionListener(CCDD.CcddClassesComponent.ValidateCellActionListener) ChangeListener(javax.swing.event.ChangeListener) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand)

Example 10 with BackgroundCommand

use of CCDD.CcddBackgroundCommand.BackgroundCommand in project CCDD by nasa.

the class CcddVariablesDialog method initialize.

/**
 ********************************************************************************************
 * Create the variable paths & names dialog. This is executed in a separate thread since it can
 * take a noticeable amount time to complete, and by using a separate thread the GUI is allowed
 * to continue to update. The GUI menu commands, however, are disabled until the telemetry
 * scheduler initialization completes execution
 ********************************************************************************************
 */
private void initialize() {
    // Build the variable paths & names dialog in the background
    CcddBackgroundCommand.executeInBackground(ccddMain, new BackgroundCommand() {

        // Create a panel to hold the components of the dialog
        JPanel dialogPnl = new JPanel(new GridBagLayout());

        JPanel buttonPnl = new JPanel();

        JButton btnShow;

        /**
         ************************************************************************************
         * Build the variable paths & names dialog
         ************************************************************************************
         */
        @Override
        protected void execute() {
            // Create borders for the dialog components
            Border border = BorderFactory.createCompoundBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.GRAY), BorderFactory.createEmptyBorder(ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing()));
            Border emptyBorder = BorderFactory.createEmptyBorder();
            // Set the initial layout manager characteristics
            GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE, new Insets(ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2, 0, ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2, 0), 0, 0);
            // Create panels to hold the components of the dialog
            JPanel upperPnl = new JPanel(new GridBagLayout());
            JPanel inputPnl = new JPanel(new GridBagLayout());
            dialogPnl.setBorder(emptyBorder);
            upperPnl.setBorder(emptyBorder);
            inputPnl.setBorder(emptyBorder);
            // Create the variable path separator label and input field, and add them to the
            // dialog panel
            JLabel varPathSepLbl = new JLabel("<html>Enter variable path<br>&#160separator character(s)");
            varPathSepLbl.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
            inputPnl.add(varPathSepLbl, gbc);
            varPathSepFld = new JTextField(ccddMain.getProgPrefs().get(VARIABLE_PATH_SEPARATOR, "_"), 5);
            varPathSepFld.setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
            varPathSepFld.setEditable(true);
            varPathSepFld.setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
            varPathSepFld.setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
            varPathSepFld.setBorder(border);
            gbc.insets.left = ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing();
            gbc.insets.bottom = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing();
            gbc.gridy++;
            inputPnl.add(varPathSepFld, gbc);
            // Create the data type/variable name separator label and input field, and add them
            // to the dialog panel
            final JLabel typeNameSepLbl = new JLabel("<html>Enter data type/variable name<br>&#160;separator character(s)");
            typeNameSepLbl.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
            gbc.insets.left = 0;
            gbc.insets.bottom = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2;
            gbc.gridy++;
            inputPnl.add(typeNameSepLbl, gbc);
            typeNameSepFld = new JTextField(ccddMain.getProgPrefs().get(TYPE_NAME_SEPARATOR, "_"), 5);
            typeNameSepFld.setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
            typeNameSepFld.setEditable(true);
            typeNameSepFld.setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
            typeNameSepFld.setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
            typeNameSepFld.setBorder(border);
            gbc.insets.left = ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing();
            gbc.insets.bottom = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing();
            gbc.gridy++;
            inputPnl.add(typeNameSepFld, gbc);
            // Create a check box for hiding data types
            hideDataTypeCb = new JCheckBox("Hide data types", Boolean.parseBoolean(ccddMain.getProgPrefs().get(HIDE_DATA_TYPE, "false")));
            hideDataTypeCb.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
            hideDataTypeCb.setBorder(emptyBorder);
            gbc.gridy++;
            inputPnl.add(hideDataTypeCb, gbc);
            // Add a listener for the hide data type check box
            hideDataTypeCb.addActionListener(new ActionListener() {

                /**
                 ****************************************************************************
                 * Handle a change in the hide data type check box status
                 ****************************************************************************
                 */
                @Override
                public void actionPerformed(ActionEvent ae) {
                    // Enable/disable the data type/variable name separator input label and
                    // field
                    typeNameSepLbl.setEnabled(!((JCheckBox) ae.getSource()).isSelected());
                    typeNameSepFld.setEnabled(!((JCheckBox) ae.getSource()).isSelected());
                }
            });
            // Add the inputs panel, containing the separator characters fields and check box,
            // to the upper panel
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.insets.right = ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing();
            gbc.gridy = 0;
            upperPnl.add(inputPnl, gbc);
            // Build the table tree showing both table prototypes and table instances; i.e.,
            // parent tables with their child tables (i.e., parents with children)
            tableTree = new CcddTableTreeHandler(ccddMain, new CcddGroupHandler(ccddMain, null, ccddMain.getMainFrame()), TableTreeType.TABLES, true, false, ccddMain.getMainFrame());
            // Add the tree to the upper panel
            gbc.insets.top = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2;
            gbc.insets.left = ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing();
            gbc.fill = GridBagConstraints.BOTH;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.weightx = 1.0;
            gbc.weighty = 1.0;
            gbc.gridx++;
            upperPnl.add(tableTree.createTreePanel("Tables", TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION, ccddMain.getMainFrame()), gbc);
            gbc.gridwidth = 1;
            gbc.insets.right = 0;
            gbc.gridx = 0;
            gbc.fill = GridBagConstraints.BOTH;
            dialogPnl.add(upperPnl, gbc);
            // Create the variables and number of variables total labels
            JLabel variablesLbl = new JLabel("Variables");
            variablesLbl.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
            variablesLbl.setForeground(ModifiableColorInfo.SPECIAL_LABEL_TEXT.getColor());
            numVariablesLbl = new JLabel();
            numVariablesLbl.setFont(ModifiableFontInfo.LABEL_PLAIN.getFont());
            gbc.fill = GridBagConstraints.REMAINDER;
            // Add the variables labels to the dialog
            JPanel variablesPnl = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
            variablesPnl.add(variablesLbl);
            variablesPnl.add(numVariablesLbl);
            gbc.weighty = 0.0;
            gbc.insets.top = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing();
            gbc.insets.bottom = 0;
            gbc.gridy++;
            dialogPnl.add(variablesPnl, gbc);
            // Define the variable paths & names JTable
            variableTable = new CcddJTableHandler(DefaultPrimitiveTypeInfo.values().length) {

                /**
                 ****************************************************************************
                 * Allow multiple line display in all columns
                 ****************************************************************************
                 */
                @Override
                protected boolean isColumnMultiLine(int column) {
                    return true;
                }

                /**
                 ************************************************************************************
                 * Allow HTML-formatted text in the specified column(s)
                 ************************************************************************************
                 */
                @Override
                protected boolean isColumnHTML(int column) {
                    return column == 0;
                }

                /**
                 ****************************************************************************
                 * Load the structure table variables paths & names into the table and format
                 * the table cells
                 ****************************************************************************
                 */
                @Override
                protected void loadAndFormatData() {
                    // Place the data into the table model along with the column names, set up
                    // the editors and renderers for the table cells, set up the table grid
                    // lines, and calculate the minimum width required to display the table
                    // information
                    setUpdatableCharacteristics(tableData, new String[] { "Application Format", "User Format" }, null, new String[] { "Variable name with structure path " + "as defined within the application", "Variable name with structure path " + "as specified by user input" }, false, true, true);
                }
            };
            // Get the project's variables
            tableData = getVariables();
            // Place the table into a scroll pane
            JScrollPane scrollPane = new JScrollPane(variableTable);
            // Set common table parameters and characteristics
            variableTable.setFixedCharacteristics(scrollPane, false, ListSelectionModel.MULTIPLE_INTERVAL_SELECTION, TableSelectionMode.SELECT_BY_CELL, true, ModifiableColorInfo.TABLE_BACK.getColor(), true, false, ModifiableFontInfo.DATA_TABLE_CELL.getFont(), true);
            // Define the panel to contain the table
            JPanel variablesTblPnl = new JPanel();
            variablesTblPnl.setLayout(new BoxLayout(variablesTblPnl, BoxLayout.X_AXIS));
            variablesTblPnl.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
            variablesTblPnl.add(scrollPane);
            // Add the table to the dialog
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.fill = GridBagConstraints.BOTH;
            gbc.weighty = 1.0;
            gbc.gridx = 0;
            gbc.gridy++;
            dialogPnl.add(variablesTblPnl, gbc);
            // Show variables button
            btnShow = CcddButtonPanelHandler.createButton("Show", RENAME_ICON, KeyEvent.VK_O, "Show the project variables");
            // Add a listener for the Show button
            btnShow.addActionListener(new ActionListener() {

                // Initialize the current values
                String varPathSep = ccddMain.getProgPrefs().get(VARIABLE_PATH_SEPARATOR, "_");

                String typeNameSep = ccddMain.getProgPrefs().get(TYPE_NAME_SEPARATOR, "_");

                String hideDataType = ccddMain.getProgPrefs().get(HIDE_DATA_TYPE, "_");

                /**
                 ****************************************************************************
                 * Convert the variables and display the results
                 ****************************************************************************
                 */
                @Override
                public void actionPerformed(ActionEvent ae) {
                    // Remove any excess white space
                    varPathSepFld.setText(varPathSepFld.getText().trim());
                    typeNameSepFld.setText(typeNameSepFld.getText().trim());
                    // Check if a separator field contains a character that cannot be used
                    if (varPathSepFld.getText().matches(".*[\\[\\]].*") || (!hideDataTypeCb.isSelected() && typeNameSepFld.getText().matches(".*[\\[\\]].*"))) {
                        // Inform the user that the input value is invalid
                        new CcddDialogHandler().showMessageDialog(CcddVariablesDialog.this, "<html><b>Invalid character(s) in separator field(s)", "Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                    } else // Check if the separator values changed
                    if (!varPathSep.equals(varPathSepFld.getText()) || !typeNameSep.equals(typeNameSepFld.getText()) || !hideDataType.equals(String.valueOf(hideDataTypeCb.isSelected()))) {
                        // Store the current values
                        varPathSep = varPathSepFld.getText();
                        typeNameSep = typeNameSepFld.getText();
                        hideDataType = String.valueOf(hideDataTypeCb.isSelected());
                        // Get the variables (matching the filtering tables, if applicable) and
                        // display them in the table
                        tableData = getVariables();
                        variableTable.loadAndFormatData();
                    }
                }
            });
            // Print variable paths button
            JButton btnPrint = CcddButtonPanelHandler.createButton("Print", PRINT_ICON, KeyEvent.VK_P, "Print the variable paths list");
            // Add a listener for the Print button
            btnPrint.addActionListener(new ActionListener() {

                /**
                 ****************************************************************************
                 * Print the variables list
                 ****************************************************************************
                 */
                @Override
                public void actionPerformed(ActionEvent ae) {
                    variableTable.printTable("Project '" + ccddMain.getDbControlHandler().getDatabaseName() + "' Variables", null, CcddVariablesDialog.this, PageFormat.LANDSCAPE);
                }
            });
            // Store separators button
            JButton btnStore = CcddButtonPanelHandler.createButton("Store", STORE_ICON, KeyEvent.VK_S, "Store the variable path separators and hide data types flag");
            // Add a listener for the Store button
            btnStore.addActionListener(new ActionListener() {

                /**
                 ****************************************************************************
                 * Store the variable separators and hide data types flag
                 ****************************************************************************
                 */
                @Override
                public void actionPerformed(ActionEvent ae) {
                    // Store the separator information in the program preferences
                    ccddMain.getProgPrefs().put(VARIABLE_PATH_SEPARATOR, varPathSepFld.getText());
                    ccddMain.getProgPrefs().put(TYPE_NAME_SEPARATOR, typeNameSepFld.getText());
                    ccddMain.getProgPrefs().put(HIDE_DATA_TYPE, String.valueOf(hideDataTypeCb.isSelected()));
                    // Step through the open editor dialogs
                    for (CcddTableEditorDialog editorDialog : ccddMain.getTableEditorDialogs()) {
                        // Step through each individual editor
                        for (CcddTableEditorHandler editor : editorDialog.getTableEditors()) {
                            // Update the variable path column, if present
                            editor.updateVariablePaths();
                        }
                    }
                }
            });
            // Close variables dialog button
            JButton btnCancel = CcddButtonPanelHandler.createButton("Close", CLOSE_ICON, KeyEvent.VK_C, "Close the variables dialog");
            // Add a listener for the Close button
            btnCancel.addActionListener(new ActionListener() {

                /**
                 ****************************************************************************
                 * Close the variables dialog
                 ****************************************************************************
                 */
                @Override
                public void actionPerformed(ActionEvent ae) {
                    // Remove the converted variable name list(s) other than the one created
                    // using the separators stored in the program preferences
                    variableHandler.removeUnusedLists();
                    // Close the dialog
                    closeDialog(CANCEL_BUTTON);
                }
            });
            // Add the buttons to the dialog's button panel
            buttonPnl.setBorder(emptyBorder);
            buttonPnl.add(btnShow);
            buttonPnl.add(btnPrint);
            buttonPnl.add(btnStore);
            buttonPnl.add(btnCancel);
        }

        /**
         ************************************************************************************
         * Variable paths & names dialog creation complete
         ************************************************************************************
         */
        @Override
        protected void complete() {
            // Display the variable name dialog
            showOptionsDialog(ccddMain.getMainFrame(), dialogPnl, buttonPnl, btnShow, "Variable Paths & Names", true);
        }
    });
}
Also used : JScrollPane(javax.swing.JScrollPane) JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) FlowLayout(java.awt.FlowLayout) GridBagLayout(java.awt.GridBagLayout) ActionEvent(java.awt.event.ActionEvent) BoxLayout(javax.swing.BoxLayout) JButton(javax.swing.JButton) JLabel(javax.swing.JLabel) JTextField(javax.swing.JTextField) JCheckBox(javax.swing.JCheckBox) ActionListener(java.awt.event.ActionListener) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand) Border(javax.swing.border.Border) BevelBorder(javax.swing.border.BevelBorder) EtchedBorder(javax.swing.border.EtchedBorder)

Aggregations

BackgroundCommand (CCDD.CcddBackgroundCommand.BackgroundCommand)26 JPanel (javax.swing.JPanel)16 GridBagConstraints (java.awt.GridBagConstraints)14 GridBagLayout (java.awt.GridBagLayout)14 Insets (java.awt.Insets)14 ActionEvent (java.awt.event.ActionEvent)13 ArrayList (java.util.ArrayList)11 ActionListener (java.awt.event.ActionListener)10 SQLException (java.sql.SQLException)10 JButton (javax.swing.JButton)9 JLabel (javax.swing.JLabel)8 ValidateCellActionListener (CCDD.CcddClassesComponent.ValidateCellActionListener)7 TypeDefinition (CCDD.CcddTableTypeHandler.TypeDefinition)4 List (java.util.List)4 BoxLayout (javax.swing.BoxLayout)4 JCheckBox (javax.swing.JCheckBox)4 DnDTabbedPane (CCDD.CcddClassesComponent.DnDTabbedPane)3 Border (javax.swing.border.Border)3 CustomSplitPane (CCDD.CcddClassesComponent.CustomSplitPane)2 CCDDException (CCDD.CcddClassesDataTable.CCDDException)2