Search in sources :

Example 1 with BackgroundCommand

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

the class CcddDbTableCommandHandler method modifyDataFields.

/**
 ********************************************************************************************
 * Modify table data field values in the data fields table. This command 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 database command completes execution
 *
 * @param modifications
 *            list of data field value modifications
 *
 * @param deletions
 *            list of data field value deletions
 *
 * @param editorWindow
 *            reference to the data field editor
 ********************************************************************************************
 */
protected void modifyDataFields(final List<String[]> modifications, final List<String[]> deletions, final CcddFieldTableEditorDialog editorWindow) {
    // Execute the command in the background
    CcddBackgroundCommand.executeInBackground(ccddMain, editorWindow, new BackgroundCommand() {

        boolean errorFlag = false;

        /**
         ************************************************************************************
         * Modify table types command
         ************************************************************************************
         */
        @Override
        protected void execute() {
            try {
                StringBuilder command = new StringBuilder("");
                // Step through each modification
                for (String[] mod : modifications) {
                    // Build the command to update the data field value in the data fields
                    // table
                    command.append("UPDATE " + InternalTable.FIELDS.getTableName() + " SET " + FieldsColumn.FIELD_VALUE.getColumnName() + " = " + delimitText(mod[2]) + " WHERE " + FieldsColumn.OWNER_NAME.getColumnName() + " = '" + mod[0] + "' AND " + FieldsColumn.FIELD_NAME.getColumnName() + " = '" + mod[1] + "'; ");
                }
                // Step through each deletion
                for (String[] del : deletions) {
                    // Build the command to delete the data field from the data fields table
                    command.append("DELETE FROM " + InternalTable.FIELDS.getTableName() + " WHERE " + FieldsColumn.OWNER_NAME.getColumnName() + " = '" + del[0] + "' AND " + FieldsColumn.FIELD_NAME.getColumnName() + " = '" + del[1] + "'; ");
                }
                // Execute the command to change the data fields
                dbCommand.executeDbCommand(command.toString(), editorWindow);
                // Log that updating the data fields succeeded
                eventLog.logEvent(SUCCESS_MSG, "Table data fields updated");
            } catch (SQLException se) {
                // Inform the user that updating the data fields failed
                eventLog.logFailEvent(editorWindow, "Cannot update data fields; cause '" + se.getMessage() + "'", "<html><b>Cannot update data fields");
                errorFlag = true;
            }
        }

        /**
         ************************************************************************************
         * Modify data fields command complete
         ************************************************************************************
         */
        @Override
        protected void complete() {
            editorWindow.doDataFieldUpdatesComplete(errorFlag);
        }
    });
}
Also used : SQLException(java.sql.SQLException) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand)

Example 2 with BackgroundCommand

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

the class CcddDbTableCommandHandler method copyTableType.

/**
 ********************************************************************************************
 * Create a copy of an existing table type. This command 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
 * database command completes execution
 *
 * @param typeName
 *            name of the table type to copy
 *
 * @param copyName
 *            name for the copy of this table type
 *
 * @param typeDialog
 *            reference to the type manager dialog
 ********************************************************************************************
 */
protected void copyTableType(final String typeName, final String copyName, final CcddTableTypeManagerDialog typeDialog) {
    // Execute the command in the background
    CcddBackgroundCommand.executeInBackground(ccddMain, new BackgroundCommand() {

        boolean errorFlag = false;

        // List of field definitions
        List<String[]> fieldDefinitions = null;

        /**
         ************************************************************************************
         * Copy table type command
         ************************************************************************************
         */
        @Override
        protected void execute() {
            try {
                // Create a data field handler and use it to extract the fields for the table
                // type to be copied
                CcddFieldHandler fieldHandler = new CcddFieldHandler(ccddMain, CcddFieldHandler.getFieldTypeName(typeName), typeDialog);
                // Get the data field definitions that were loaded from the database
                fieldDefinitions = fieldHandler.getFieldDefinitions();
                // Add the fields under the new type name to the list of existing field
                // definitions
                fieldDefinitions.addAll(fieldHandler.renameFieldTable(CcddFieldHandler.getFieldTypeName(copyName)));
                // Create the command to rebuild the table types and fields tables
                String command = storeTableTypesInfoTableCommand() + storeNonTableTypesInfoTableCommand(InternalTable.FIELDS, fieldDefinitions, null, typeDialog);
                // Execute the command to change the table's type name
                dbCommand.executeDbCommand(command, typeDialog);
                // Log that renaming the table succeeded
                eventLog.logEvent(SUCCESS_MSG, "Table type '" + typeName + "' copied to '" + copyName + "'");
            } catch (SQLException se) {
                // Inform the user that copying the table type failed
                eventLog.logFailEvent(typeDialog, "Cannot copy table type '" + typeName + "'; cause '" + se.getMessage() + "'", "<html><b>Cannot copy table type '</b>" + typeName + "<b>'");
                errorFlag = true;
            }
        }

        /**
         ************************************************************************************
         * Copy table type command complete
         ************************************************************************************
         */
        @Override
        protected void complete() {
            // represents a structure
            if (!errorFlag && tableTypeHandler.getTypeDefinition(typeName).isStructure()) {
                // Update the rate information, if applicable
                rateHandler.setRateInformation();
            }
            typeDialog.doTypeOperationComplete(errorFlag, fieldDefinitions, null);
        }
    });
}
Also used : SQLException(java.sql.SQLException) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand)

Example 3 with BackgroundCommand

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

the class CcddProjectFieldDialog method initialize.

/**
 ********************************************************************************************
 * Create the project data field 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 data field 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();

        JButton btnClose;

        /**
         ************************************************************************************
         * Build the project data field manager dialog
         ************************************************************************************
         */
        @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() / 2, 0, 0), 0, 0);
            Border emptyBorder = BorderFactory.createEmptyBorder();
            // Set the flag to indicate the project data field manager dialog is being
            // initialized
            isInitializing = true;
            // Add an undo edit manager
            undoManager = new CcddUndoManager() {

                /**
                 ****************************************************************************
                 * Update the change indicator if the editor panel has changed
                 ****************************************************************************
                 */
                @Override
                protected void ownerHasChanged() {
                    // - changes during initialization are ignored
                    if (!isInitializing) {
                        updateChangeIndicator();
                    }
                }
            };
            // Create the undo handler for the components with undoable actions. Disable
            // storage of edit actions during dialog creation
            undoHandler = new CcddUndoHandler(undoManager);
            undoHandler.setAllowUndo(false);
            // Create the field panel for the project description and data fields
            fieldPnlHndlr = new CcddInputFieldPanelHandler() {

                /**
                 ****************************************************************************
                 * Update the project data field manager change indicator
                 ****************************************************************************
                 */
                @Override
                protected void updateOwnerChangeIndicator() {
                    updateChangeIndicator();
                }
            };
            // Get the project description
            committedDescription = dbControl.getDatabaseDescription(dbControl.getDatabaseName());
            // Set the undo/redo manager and handler for the description and data field values
            fieldPnlHndlr.setEditPanelUndo(undoManager, undoHandler);
            // Create a field handler containing all data fields
            fieldHandler = new CcddFieldHandler(ccddMain, CcddFieldHandler.getFieldProjectName(), CcddProjectFieldDialog.this);
            // Set the data field handler reference in the undo handler so that data field
            // edits can be undone/redone
            undoHandler.setFieldHandler(fieldHandler);
            // Build the field information for the project data fields
            committedFieldInformation = fieldHandler.getFieldInformationCopy();
            // Create the input field panel
            fieldPnlHndlr.createDescAndDataFieldPanel(CcddProjectFieldDialog.this, null, null, committedDescription, fieldHandler);
            // Set the modal undo manager in the keyboard handler while the project data
            // field manager is active
            ccddMain.getKeyboardHandler().setModalDialogReference(undoManager, null);
            dialogPnl.setBorder(emptyBorder);
            // Create the project data field manager dialog labels and fields
            JLabel dlgLabel = new JLabel("Project: " + dbControl.getProjectName());
            dlgLabel.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
            dialogPnl.add(dlgLabel, gbc);
            // Add the field panel to the dialog
            gbc.insets.top = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2;
            gbc.insets.left = 0;
            gbc.insets.bottom = 0;
            gbc.insets.right = 0;
            gbc.weighty = 1.0;
            gbc.gridy++;
            dialogPnl.add(fieldPnlHndlr.getFieldPanel(), gbc);
            // Re-enable storage of edit actions
            undoHandler.setAllowUndo(true);
            // Manage fields button
            btnManageFields = CcddButtonPanelHandler.createButton("Fields", FIELD_ICON, KeyEvent.VK_F, "Manage the data fields");
            // Add a listener for the Manage Fields command
            btnManageFields.addActionListener(new ActionListener() {

                /**
                 ****************************************************************************
                 * Manage the data fields
                 ****************************************************************************
                 */
                @Override
                public void actionPerformed(ActionEvent ae) {
                    // Create the field editor dialog showing the fields for this project
                    new CcddFieldEditorDialog(ccddMain, fieldPnlHndlr, CcddFieldHandler.getFieldProjectName(), false, ModifiableSizeInfo.MIN_DIALOG_WIDTH.getSize());
                    // Set the undo manager in the keyboard handler back to the project data
                    // field manager
                    ccddMain.getKeyboardHandler().setModalDialogReference(undoManager, null);
                    // Enable/disable the Clear values button depending on if any data fields
                    // remain
                    btnClearValues.setEnabled(!fieldHandler.getFieldInformation().isEmpty());
                }
            });
            // Clear fields button
            btnClearValues = CcddButtonPanelHandler.createButton("Clear", CLEAR_ICON, KeyEvent.VK_C, "Clear the data fields");
            // Enable/disable the Clear values button depending on if any data fields
            // remain
            btnClearValues.setEnabled(!fieldHandler.getFieldInformation().isEmpty());
            // Add a listener for the Clear values command
            btnClearValues.addActionListener(new ActionListener() {

                /**
                 ****************************************************************************
                 * Clear the table data field values
                 ****************************************************************************
                 */
                @Override
                public void actionPerformed(ActionEvent ae) {
                    // Clear all of the data field values for the project
                    fieldPnlHndlr.clearFieldValues();
                }
            });
            // Undo button
            JButton btnUndo = CcddButtonPanelHandler.createButton("Undo", UNDO_ICON, KeyEvent.VK_Z, "Undo the last edit action");
            // Create a listener for the Undo command
            ActionListener undoAction = new ActionListener() {

                /**
                 ****************************************************************************
                 * Undo the last edit
                 ****************************************************************************
                 */
                @Override
                public void actionPerformed(ActionEvent ae) {
                    undoManager.undo();
                    // Update the data field background colors
                    fieldPnlHndlr.setFieldBackgound();
                }
            };
            // Add the undo listener to the Undo button and menu command
            btnUndo.addActionListener(undoAction);
            // 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
            ActionListener redoAction = new ActionListener() {

                /**
                 ****************************************************************************
                 * Redo the last cell that was undone
                 ****************************************************************************
                 */
                @Override
                public void actionPerformed(ActionEvent ae) {
                    undoManager.redo();
                    // Update the data field background colors
                    fieldPnlHndlr.setFieldBackgound();
                }
            };
            // Add the redo listener to the Redo button and menu command
            btnRedo.addActionListener(redoAction);
            // Store project data fields button
            JButton btnStoreFields = CcddButtonPanelHandler.createButton("Store", STORE_ICON, KeyEvent.VK_S, "Store project data field updates in the database");
            // Add a listener for the Store button
            btnStoreFields.addActionListener(new ActionListener() {

                /**
                 ****************************************************************************
                 * Store the project description and data fields in the database
                 ****************************************************************************
                 */
                @Override
                public void actionPerformed(ActionEvent ae) {
                    // the user confirms discarding them
                    if (isFieldsChanged() && new CcddDialogHandler().showMessageDialog(CcddProjectFieldDialog.this, "<html><b>Store project data fields?", "Store Project Fields", JOptionPane.QUESTION_MESSAGE, DialogOption.OK_CANCEL_OPTION) == OK_BUTTON) {
                        // Store the project description and data fields in the database
                        ccddMain.getDbTableCommandHandler().modifyProjectFields(fieldPnlHndlr.getDescription(), fieldHandler.getFieldInformation(), CcddProjectFieldDialog.this);
                        // Store the updated description and fields for comparison with a
                        // subsequent store operation
                        committedDescription = fieldPnlHndlr.getDescription();
                        committedFieldInformation = fieldHandler.getFieldInformationCopy();
                        // Update the project field dialog's change indicator
                        updateChangeIndicator();
                    }
                }
            });
            // Close button
            btnClose = CcddButtonPanelHandler.createButton("Close", CLOSE_ICON, KeyEvent.VK_C, "Close the group manager");
            // Add a listener for the Close button
            btnClose.addActionListener(new ActionListener() {

                /**
                 ****************************************************************************
                 * Close the group selection dialog
                 ****************************************************************************
                 */
                @Override
                public void actionPerformed(ActionEvent ae) {
                    // elects to discard the changes
                    if (!isFieldsChanged() || new CcddDialogHandler().showMessageDialog(CcddProjectFieldDialog.this, "<html><b>Discard changes?", "Discard Changes", JOptionPane.QUESTION_MESSAGE, DialogOption.OK_CANCEL_OPTION) == OK_BUTTON) {
                        // Close the dialog
                        closeDialog();
                        // Clear the modal dialog references in the keyboard handler
                        ccddMain.getKeyboardHandler().setModalDialogReference(null, null);
                    }
                }
            });
            // Add buttons in the order in which they'll appear (left to right, top to bottom)
            buttonPnl.add(btnManageFields);
            buttonPnl.add(btnUndo);
            buttonPnl.add(btnStoreFields);
            buttonPnl.add(btnClearValues);
            buttonPnl.add(btnRedo);
            buttonPnl.add(btnClose);
            // Distribute the buttons across two rows
            setButtonRows(2);
            // Store the current data field information in the event an undo/redo operation
            // occurs
            fieldPnlHndlr.storeCurrentFieldInformation();
            undoManager.endEditSequence();
            // Add a listener for changes in the panel's size
            CcddProjectFieldDialog.this.addComponentListener(new ComponentAdapter() {

                /**
                 ****************************************************************************
                 * Handle resizing of the panel
                 ****************************************************************************
                 */
                @Override
                public void componentResized(ComponentEvent ce) {
                    // Create a runnable object to be executed
                    SwingUtilities.invokeLater(new Runnable() {

                        /**
                         ********************************************************************
                         * Since the size returned by get___Size() can lag the actual size, use
                         * invokeLater to let the sizes "catch up"
                         ********************************************************************
                         */
                        @Override
                        public void run() {
                            // Update the minimum size of the owner so that all of the fields
                            // remain visible
                            CcddProjectFieldDialog.this.setPreferredSize(null);
                            CcddProjectFieldDialog.this.setMinimumSize(new Dimension(Math.max(ModifiableSizeInfo.MIN_DIALOG_WIDTH.getSize(), fieldPnlHndlr.getMaxFieldWidth()), CcddProjectFieldDialog.this.getPreferredSize().height));
                        }
                    });
                }
            });
            // Reset the flag now that initialization is complete
            isInitializing = false;
        }

        /**
         ************************************************************************************
         * Project data field manager dialog creation complete
         ************************************************************************************
         */
        @Override
        protected void complete() {
            // Display the project data field manager dialog
            showOptionsDialog(ccddMain.getMainFrame(), dialogPnl, buttonPnl, btnClose, DIALOG_TITLE, true);
        }
    });
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) GridBagLayout(java.awt.GridBagLayout) ActionEvent(java.awt.event.ActionEvent) JButton(javax.swing.JButton) JLabel(javax.swing.JLabel) Dimension(java.awt.Dimension) ActionListener(java.awt.event.ActionListener) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand) ComponentEvent(java.awt.event.ComponentEvent) Border(javax.swing.border.Border) ComponentAdapter(java.awt.event.ComponentAdapter)

Example 4 with BackgroundCommand

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

the class CcddSchedulerHandler method autoFill.

/**
 ********************************************************************************************
 * Automatically fill the variables/applications in messages/time slots corresponding to their
 * rate
 ********************************************************************************************
 */
protected void autoFill() {
    canceled = false;
    cancelDialog = new HaltDialog();
    progBar = new JProgressBar();
    progress = 0;
    // Create the panel to contain the progress/cancellation dialog components
    final JPanel dialogPnl = new JPanel(new GridBagLayout());
    // Get the scheduler dialog type
    final SchedulerType schedulerType = getSchedulerOption();
    // Get the text that describes the type of object being assigned
    final String variableType = schedulerType == SchedulerType.TELEMETRY_SCHEDULER ? "variables" : (schedulerType == SchedulerType.APPLICATION_SCHEDULER ? "applications" : "unknown");
    // Create a thread to perform the auto-fill operation in the background
    final Thread progressThread = new Thread(new Runnable() {

        /**
         ************************************************************************************
         * Auto-fill the telemetry messages (if this is the telemetry scheduler) or application
         * time slots (if this is the application scheduler). Note that in the comments below
         * 'variable' is used to describe the object being assigned, which is accurate for the
         * telemetry scheduler. For the application scheduler substitute 'application' for
         * 'variable'
         ************************************************************************************
         */
        @Override
        public void run() {
            int numVariables = 0;
            int unassigned = 0;
            // Get an array of the available rates
            String[] availableRates = schedulerInput.getAvailableRates();
            // variables at each rate until no more rates are available
            for (String rate : availableRates) {
                // out using HTML tags
                if (!rate.startsWith("<html>")) {
                    // Check if this is a telemetry scheduler
                    if (schedulerType == SchedulerType.TELEMETRY_SCHEDULER) {
                        // Get the reference to the variable tree in order to shorten the
                        // subsequent call
                        CcddTableTreeHandler variableTree = ((CcddTelemetrySchedulerInput) schedulerInput).getVariableTree();
                        // Add the number of unassigned variables at the given rate.
                        // getVariablesAtRate() could be used, but it performs other operations
                        // associated with links and is slower
                        numVariables += variableTree.getPrimitiveVariablePaths(variableTree.getRootNode(), true).size();
                    } else // Check if this is an application scheduler
                    if (schedulerType == SchedulerType.APPLICATION_SCHEDULER) {
                        // Add the number of unassigned applications at the given rate
                        numVariables += schedulerInput.getVariablesAtRate(rate).size();
                    }
                }
            }
            // Check if there are any variables to assign
            if (numVariables != 0) {
                // Update the progress bar now that the number of variables is known
                progBar.setMaximum(numVariables);
                progBar.setIndeterminate(false);
                // Total size of the variable or link
                int totalSize;
                // Message option to which the variable or link will be added
                String option;
                // Variable that will be added
                Variable variable;
                // Variables that will be removed from the remaining list
                List<Variable> removedVars = new ArrayList<Variable>();
                // List of variables at a given rate
                List<Variable> varList;
                // List of the variables to exclude from the Variables tree. This should be all
                // of the variables unless there are any that can't be assigned
                List<String> excludedVars = new ArrayList<String>();
                // variables at each rate until no more rates are available
                for (String rate : availableRates) {
                    // Check if the user canceled auto-fill
                    if (canceled) {
                        break;
                    }
                    // grayed out using HTML tags
                    if (!rate.startsWith("<html>")) {
                        // Show the current rate being processed in the progress bar
                        progBar.setString("Assigning " + rate + " Hz " + variableType);
                        // Get the rate as a floating point value
                        float rateVal = CcddUtilities.convertStringToFloat(rate);
                        // Get a list of all variables at the given rate (ones already assigned
                        // are not included)
                        varList = schedulerInput.getVariablesAtRate(rate);
                        // Sort the list from largest to smallest
                        Collections.sort(varList);
                        // Loop through the list of variables until all are removed
                        while (!varList.isEmpty()) {
                            // Check if the user canceled padding adjustment
                            if (canceled) {
                                break;
                            }
                            // Total size of the variable or link
                            totalSize = 0;
                            // Set to the first variable in the list
                            variable = varList.get(0);
                            // Check if the variable is linked
                            if (variable.getLink() != null) {
                                // Step through each variable in the variable list
                                for (Variable linkVar : varList) {
                                    // variable
                                    if (linkVar.getLink() != null && linkVar.getLink().equals(variable.getLink())) {
                                        // Add the variable's size to the total size
                                        totalSize += variable.getSize();
                                        // Add the variable to the list of removed variables
                                        removedVars.add(linkVar);
                                    }
                                }
                            } else // The variable is unlinked
                            {
                                // Check if this is a telemetry scheduler
                                if (schedulerType == SchedulerType.TELEMETRY_SCHEDULER) {
                                    // Set total size to the given variable's size
                                    totalSize = variable.getSize();
                                    // Get the total size (in bytes) and the list of the
                                    // variable, or variables if this variable is associated
                                    // with others due to bit-packing or string membership and
                                    // therefore must be placed together in a message
                                    AssociatedVariable associates = ((CcddTelemetrySchedulerInput) schedulerInput).getAssociatedVariables(varList);
                                    // Set the total size to that of the associated variable(s)
                                    // and add the variable(s) to the list of those to be
                                    // removed
                                    totalSize = associates.getTotalSize();
                                    removedVars.addAll(associates.getAssociates());
                                } else // This is an application (or unknown type of) scheduler
                                {
                                    // Set total size to the given variable's size
                                    totalSize = variable.getSize();
                                    // Add the variable to the list of removed variables
                                    removedVars.add(variable);
                                }
                            }
                            // Find the option with the most room
                            option = getMessageWithRoom(rateVal, totalSize);
                            // Check to make sure there is an option
                            if (option != null) {
                                // Parse the option string to extract the sub-index (if this is
                                // a sub-option) and the message indices
                                Object[] parsedIndices = parseOption(option);
                                // Add the variable to the given message. If a sub-index is not
                                // given it will be set to -1. Add the list of added variables
                                // to the list of those to exclude in the Variables tree
                                excludedVars.addAll(addVariableToMessage(removedVars, (Integer[]) parsedIndices[1], (int) parsedIndices[0]));
                            } else // No option is available
                            {
                                // Increment the unplaced variable counter
                                unassigned++;
                            }
                            // Remove all the variables in removed variables list. This
                            // includes variables that did not fit into the telemetry table
                            varList.removeAll(removedVars);
                            // Clear the removed variables list
                            removedVars.clear();
                            // Update the auto-fill progress
                            progBar.setValue(progress);
                            progress++;
                        }
                    }
                }
                // Check if the auto-fill operation wasn't canceled by the user
                if (!canceled) {
                    // Close the auto-fill progress/cancellation dialog
                    cancelDialog.closeDialog(CANCEL_BUTTON);
                }
                // Perform any updates needed following adding variables to messages
                updateAfterVariableAdded();
                // Set the variable tree to exclude the variable(s)
                setVariableUnavailable(excludedVars);
                // Display the originally selected rate's variable tree
                schedulerInput.updateVariableTree(rateFilter.getSelectedItem().toString());
                // Update the remaining bytes column values
                schedulerEditor.updateRemainingBytesColumn();
                // Update the unused bytes/time field
                setUnusedField();
                // Update the assigned variables/applications list panel
                schedulerEditor.updateAssignmentList();
                // Update the scheduler dialog's change indicator
                getSchedulerDialog().updateChangeIndicator();
                // Check if there are items that are not assigned
                if (unassigned != 0) {
                    // Inform the user if there are items that are not assigned
                    new CcddDialogHandler().showMessageDialog(schedulerDlg.getDialog(), "<html><b> Auto-fill unable to assign " + unassigned + " " + variableType, "Auto-fill", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                }
            } else // There are no unassigned variables
            {
                // user
                if (!canceled) {
                    // Close the auto-fill progress/cancellation dialog
                    cancelDialog.closeDialog(CANCEL_BUTTON);
                }
                new CcddDialogHandler().showMessageDialog(schedulerDlg.getDialog(), "<html><b>All " + variableType + " with a rate are already assigned", "Auto-fill", JOptionPane.INFORMATION_MESSAGE, DialogOption.OK_OPTION);
            }
        }
    });
    // Execute the command in the background
    CcddBackgroundCommand.executeInBackground(ccddMain, schedulerDlg.getDialog(), new BackgroundCommand() {

        /**
         ************************************************************************************
         * Build and display the auto-fill progress/cancellation dialog. This is done as a
         * background operation so that the
         ************************************************************************************
         */
        @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);
            // Build the progress/cancellation dialog
            dialogPnl.setBorder(BorderFactory.createEmptyBorder());
            JLabel textLbl = new JLabel("<html><b>Assigning " + variableType + "...</b><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 auto-fill ***", Color.RED) + "</b><br><br>", SwingConstants.CENTER);
            textLbl2.setFont(ModifiableFontInfo.LABEL_PLAIN.getFont());
            gbc.gridy++;
            dialogPnl.add(textLbl2, gbc);
            // Add a progress bar to the dialog
            progBar.setIndeterminate(true);
            progBar.setMinimum(0);
            progBar.setValue(0);
            progBar.setString("Calculating number of variables");
            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);
            // the dialog if there are no variables to assign
            if (!canceled) {
                // Display the auto-fill progress/cancellation dialog
                cancelDialog.showOptionsDialog(schedulerDlg.getDialog(), dialogPnl, "Auto-fill " + (schedulerType == SchedulerType.TELEMETRY_SCHEDULER ? "Telemetry Messages" : (schedulerType == SchedulerType.APPLICATION_SCHEDULER ? "Time Slots" : "")), DialogOption.HALT_OPTION, false, true);
            }
        }
    });
    // Perform the auto-fill operation in a background thread
    progressThread.start();
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) AssociatedVariable(CCDD.CcddClassesDataTable.AssociatedVariable) Variable(CCDD.CcddClassesDataTable.Variable) Insets(java.awt.Insets) GridBagLayout(java.awt.GridBagLayout) JProgressBar(javax.swing.JProgressBar) AssociatedVariable(CCDD.CcddClassesDataTable.AssociatedVariable) JLabel(javax.swing.JLabel) SchedulerType(CCDD.CcddConstants.SchedulerType) ArrayList(java.util.ArrayList) JList(javax.swing.JList) List(java.util.List) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand)

Example 5 with BackgroundCommand

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

the class CcddDataTypeEditorDialog method initialize.

/**
 ********************************************************************************************
 * Create the data type editor 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 data type editor dialog in the background
    CcddBackgroundCommand.executeInBackground(ccddMain, new BackgroundCommand() {

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

        JPanel buttonPnl = new JPanel();

        JButton btnClose;

        /**
         ************************************************************************************
         * Build the data type editor dialog
         ************************************************************************************
         */
        @Override
        protected void execute() {
            modifications = new ArrayList<TableModification>();
            loadedReferences = new ArrayList<DataTypeReference>();
            // Set the initial layout manager characteristics
            GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0);
            // Create a copy of the data type data so it can be used to determine if changes
            // are made
            committedData = dataTypeHandler.getDataTypeDataArray();
            // Define the panel to contain the table and place it in the editor
            JPanel tablePnl = new JPanel();
            tablePnl.setLayout(new BoxLayout(tablePnl, BoxLayout.X_AXIS));
            tablePnl.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
            tablePnl.add(createDataTypeTable());
            editorPnl.add(tablePnl, gbc);
            editorPnl.setBorder(BorderFactory.createEmptyBorder());
            // Create the cell editor for base data types
            createBasePrimitiveTypeCellEditor();
            // Set the modal undo manager and table references in the keyboard handler while
            // the data type editor is active
            ccddMain.getKeyboardHandler().setModalDialogReference(dataTypeTable.getUndoManager(), dataTypeTable);
            // New button
            JButton btnInsertRow = CcddButtonPanelHandler.createButton("Ins Row", INSERT_ICON, KeyEvent.VK_I, "Insert a new row into the table");
            // Create a listener for the Insert Row button
            btnInsertRow.addActionListener(new ValidateCellActionListener(dataTypeTable) {

                /**
                 ****************************************************************************
                 * Insert a new row into the table at the selected location
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    dataTypeTable.insertEmptyRow(true);
                }
            });
            // Delete button
            JButton btnDeleteRow = CcddButtonPanelHandler.createButton("Del Row", DELETE_ICON, KeyEvent.VK_D, "Delete the selected row(s) from the table");
            // Create a listener for the Delete row button
            btnDeleteRow.addActionListener(new ValidateCellActionListener(dataTypeTable) {

                /**
                 ****************************************************************************
                 * Delete the selected row(s) from the table
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    // Step through each row selected for deletion
                    for (int row : dataTypeTable.getSelectedRows()) {
                        // Get the data type name
                        String dataType = CcddDataTypeHandler.getDataTypeName(dataTypeTable.getValueAt(row, DataTypesColumn.USER_NAME.ordinal()).toString(), dataTypeTable.getValueAt(row, DataTypesColumn.C_NAME.ordinal()).toString());
                        // Check if the data type name is present
                        if (!dataType.isEmpty()) {
                            boolean isInUse = false;
                            // type, and not just text matching the data type's name
                            for (String dataTypeRef : getDataTypeReferences(dataType).getReferences()) {
                                // Split the reference into table name, column name, table
                                // type, and context
                                String[] tblColDescAndCntxt = dataTypeRef.split(TABLE_DESCRIPTION_SEPARATOR, 4);
                                String refComment = tblColDescAndCntxt[SearchResultsQueryColumn.COMMENT.ordinal()];
                                // Check if the match is within a sizeof() call
                                if (CcddVariableSizeAndConversionHandler.hasSizeof(tblColDescAndCntxt[SearchResultsQueryColumn.CONTEXT.ordinal()], dataType)) {
                                    // Set the flag to indicate the reference is to the data
                                    // type, and stop searching
                                    isInUse = true;
                                    break;
                                }
                                // Extract the viewable name and type of the table, and the
                                // name of the column containing the data type, Separate the
                                // column string into the individual column values
                                String[] refNameAndType = refComment.split(",");
                                String[] refColumns = CcddUtilities.splitAndRemoveQuotes(tblColDescAndCntxt[SearchResultsQueryColumn.CONTEXT.ordinal()]);
                                // Use the type and column to get the column's input data type
                                TypeDefinition typeDefn = ccddMain.getTableTypeHandler().getTypeDefinition(refNameAndType[1]);
                                // Get the indices for all columns that can reference a data
                                // type
                                List<Integer> primColumns = typeDefn.getColumnIndicesByInputType(InputDataType.PRIMITIVE);
                                primColumns.addAll(typeDefn.getColumnIndicesByInputType(InputDataType.PRIM_AND_STRUCT));
                                // Step through each of the data type columns
                                for (int column : primColumns) {
                                    // Check if the column contents matches the data type name
                                    if (refColumns[column].equals(dataType)) {
                                        // Set the flag to indicate the reference is to the
                                        // data type, and stop searching
                                        isInUse = true;
                                        break;
                                    }
                                }
                                // Check if the data type has a valid reference
                                if (isInUse) {
                                    // Stop searching
                                    break;
                                }
                            }
                            // Check if the data type is in use by a data table
                            if (isInUse) {
                                // Deselect the data type
                                dataTypeTable.removeRowSelectionInterval(row, row);
                                // Inform the user that the data type can't be deleted
                                new CcddDialogHandler().showMessageDialog(CcddDataTypeEditorDialog.this, "<html><b>Cannot delete data type '" + dataType + "'; data type is referenced by a data table", "Delete Data Type", JOptionPane.QUESTION_MESSAGE, DialogOption.OK_OPTION);
                            }
                        }
                    }
                    dataTypeTable.deleteRow(true);
                }
            });
            // 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 button
            btnMoveUp.addActionListener(new ValidateCellActionListener(dataTypeTable) {

                /**
                 ****************************************************************************
                 * Move the selected row(s) up in the table
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    dataTypeTable.moveRowUp();
                }
            });
            // 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 button
            btnMoveDown.addActionListener(new ValidateCellActionListener(dataTypeTable) {

                /**
                 ****************************************************************************
                 * Move the selected row(s) down in the table
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    dataTypeTable.moveRowDown();
                }
            });
            // Undo button
            JButton btnUndo = CcddButtonPanelHandler.createButton("Undo", UNDO_ICON, KeyEvent.VK_Z, "Undo the last edit");
            // Create a listener for the Undo button
            btnUndo.addActionListener(new ValidateCellActionListener(dataTypeTable) {

                /**
                 ****************************************************************************
                 * Undo the last cell edit
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    dataTypeTable.getUndoManager().undo();
                }
            });
            // Redo button
            JButton btnRedo = CcddButtonPanelHandler.createButton("Redo", REDO_ICON, KeyEvent.VK_Y, "Redo the last undone edit");
            // Create a listener for the Redo button
            btnRedo.addActionListener(new ValidateCellActionListener(dataTypeTable) {

                /**
                 ****************************************************************************
                 * Redo the last cell edit that was undone
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    dataTypeTable.getUndoManager().redo();
                }
            });
            // Store the data types button
            JButton btnStore = CcddButtonPanelHandler.createButton("Store", STORE_ICON, KeyEvent.VK_S, "Store the data type(s)");
            // Create a listener for the Store button
            btnStore.addActionListener(new ValidateCellActionListener(dataTypeTable) {

                /**
                 ****************************************************************************
                 * Store the data types
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    // the action
                    if (dataTypeTable.isTableChanged(committedData) && !checkForMissingColumns() && new CcddDialogHandler().showMessageDialog(CcddDataTypeEditorDialog.this, "<html><b>Store changes in project database?", "Store Changes", JOptionPane.QUESTION_MESSAGE, DialogOption.OK_CANCEL_OPTION) == OK_BUTTON) {
                        // Get a list of the data type modifications
                        buildUpdates();
                        // Update the tables affected by the changes to the data type(s)
                        dbTable.modifyTablePerDataTypeOrMacroChanges(modifications, getUpdatedData(), CcddDataTypeEditorDialog.this);
                    }
                }
            });
            // Close button
            btnClose = CcddButtonPanelHandler.createButton("Close", CLOSE_ICON, KeyEvent.VK_C, "Close the data type editor");
            // Create a listener for the Close button
            btnClose.addActionListener(new ValidateCellActionListener(dataTypeTable) {

                /**
                 ****************************************************************************
                 * Close the data type editor dialog
                 ****************************************************************************
                 */
                @Override
                protected void performAction(ActionEvent ae) {
                    windowCloseButtonAction();
                }
            });
            // Add buttons in the order in which they'll appear (left to right, top to bottom)
            buttonPnl.add(btnInsertRow);
            buttonPnl.add(btnMoveUp);
            buttonPnl.add(btnUndo);
            buttonPnl.add(btnStore);
            buttonPnl.add(btnDeleteRow);
            buttonPnl.add(btnMoveDown);
            buttonPnl.add(btnRedo);
            buttonPnl.add(btnClose);
            // Distribute the buttons across two rows
            setButtonRows(2);
        }

        /**
         ************************************************************************************
         * Data type editor dialog creation complete
         ************************************************************************************
         */
        @Override
        protected void complete() {
            // Display the data type editor dialog
            showOptionsDialog(ccddMain.getMainFrame(), editorPnl, buttonPnl, btnClose, DIALOG_TITLE, true);
        }
    });
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) GridBagLayout(java.awt.GridBagLayout) ActionEvent(java.awt.event.ActionEvent) BoxLayout(javax.swing.BoxLayout) JButton(javax.swing.JButton) ArrayList(java.util.ArrayList) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition) ValidateCellActionListener(CCDD.CcddClassesComponent.ValidateCellActionListener) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand)

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