Unnamed: 0
int64
0
2.05k
func
stringlengths
27
124k
target
bool
2 classes
project
stringlengths
39
117
200
alignTableCenterVerticleButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); CanvasFormattingController.notifyAlignVCenterSelected(selectedPanels); managedCanvas.fireFocusPersist(); } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
201
positionYSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); if (selectedPanels != null && selectedPanels.size() == 1) { Panel selectedPanel = selectedPanels.get(0); int newYLocation = ((Integer) positionYSpinner.getValue()).intValue() - CORRECTION_OFFSET; if (selectedPanel.getLocation().y != newYLocation) { CanvasFormattingController.notifyYPropertyChange(newYLocation, selectedPanel); managedCanvas.fireFocusPersist(); } } } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
202
panelTitleFont.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (listenersEnabled) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); CanvasFormattingController.notifyTitleBarFontSelected( ((JVMFontFamily) panelTitleFont.getSelectedItem()).toString(), selectedPanels); managedCanvas.fireFocusPersist(); } } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
203
miscPanelTitleBarCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (listenersEnabled) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); CanvasFormattingController.notifyTitleBarStatus(miscPanelTitleBarCheckBox.isSelected(), selectedPanels); managedCanvas.fireFocusPersist(); } miscPanelTitleField.setEditable(miscPanelTitleBarCheckBox.isSelected()); } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
204
miscPanelTitleField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (listenersEnabled) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); CanvasFormattingController.notifyNewTitle(miscPanelTitleField.getText(), selectedPanels); managedCanvas.fireFocusPersist(); } } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
205
miscPanelTitleField.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { if (listenersEnabled) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); boolean changed = false; for (Panel p : selectedPanels) { if (!p.getTitle().equals(miscPanelTitleField.getText())) { changed = true; } } if (changed) { CanvasFormattingController.notifyNewTitle(miscPanelTitleField.getText(), selectedPanels); managedCanvas.fireFocusPersist(); } } } @Override public void focusGained(FocusEvent e) { } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
206
panelTitleFontSize.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (listenersEnabled) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); CanvasFormattingController.notifyTitleBarFontSizeSelected( Integer.class.cast(panelTitleFontSize.getValue()), selectedPanels); managedCanvas.fireFocusPersist(); } } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
207
ActionListener panelTitleFontStyleListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (listenersEnabled) { int fontStyle = Font.PLAIN; if (panelTitleFontStyleBold.getModel().isSelected()) { fontStyle = Font.BOLD; if (panelTitleFontStyleItalic.getModel().isSelected()) { fontStyle += Font.ITALIC; } } else if (panelTitleFontStyleItalic.getModel().isSelected()) { fontStyle = Font.ITALIC; } List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); CanvasFormattingController.notifyTitleBarFontStyleSelected( Integer.valueOf(fontStyle), selectedPanels); managedCanvas.fireFocusPersist(); } } };
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
208
ActionListener panelTitleFontTextAttributeListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (listenersEnabled) { int attribute = ControlAreaFormattingConstants.UNDERLINE_OFF; if (panelTitleFontUnderline.getModel().isSelected()) { attribute = TextAttribute.UNDERLINE_ON; } List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); CanvasFormattingController.notifyTitleBarFontUnderlineSelected( Integer.valueOf(attribute), selectedPanels); managedCanvas.fireFocusPersist(); } } };
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
209
panelTitleFontColorComboBox.setRenderer(new ListCellRenderer() { private ColorPanel myColorPanel = new ColorPanel(new Color(0)); @Override public Component getListCellRendererComponent(JList list, Object obj, int arg2, boolean arg3, boolean arg4) { if (obj instanceof Color) { myColorPanel.setColor((Color) obj); return myColorPanel; } return new JPanel(); } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
210
panelTitleFontColorComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (listenersEnabled) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); CanvasFormattingController.notifyTitleBarFontForegroundColorSelected( Integer.valueOf((Color.class.cast(panelTitleFontColorComboBox.getSelectedItem())).getRGB()), selectedPanels); managedCanvas.fireFocusPersist(); } } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
211
panelTitleBackgroundColorComboBox.setRenderer(new ListCellRenderer() { private ColorPanel myColorPanel = new ColorPanel(new Color(0)); @Override public Component getListCellRendererComponent(JList list, Object obj, int arg2, boolean arg3, boolean arg4) { if (obj instanceof Color) { myColorPanel.setColor((Color) obj); return myColorPanel; } return new JPanel(); } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
212
dimensionHorizontalSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (listenersEnabled) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); int newWidth = ((Integer) dimensionHorizontalSpinner.getValue()).intValue(); CanvasFormattingController.notifyWidthPropertyChange(newWidth, selectedPanels); managedCanvas.fireFocusPersist(); } } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
213
panelTitleBackgroundColorComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (listenersEnabled) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); CanvasFormattingController.notifyTitleBarFontBackgroundColorSelected( Integer.valueOf((Color.class.cast(panelTitleBackgroundColorComboBox.getSelectedItem())).getRGB()), selectedPanels); managedCanvas.fireFocusPersist(); } } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
214
dimensionVerticalSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (listenersEnabled) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); int newHeight = ((Integer) dimensionVerticalSpinner.getValue()).intValue(); CanvasFormattingController.notifyHeightPropertyChange(newHeight, selectedPanels); managedCanvas.fireFocusPersist(); } } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
215
leftBorderButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); if (listenersEnabled) { CanvasFormattingController .notifyWestBorderStatus(leftBorderButton.isSelected(), selectedPanels); setAllAndNoBorderButtonState(selectedPanels); managedCanvas.fireFocusPersist(); } } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
216
rightBorderButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); if (listenersEnabled) { CanvasFormattingController.notifyEastBorderStatus(rightBorderButton.isSelected(), selectedPanels); setAllAndNoBorderButtonState(selectedPanels); managedCanvas.fireFocusPersist(); } } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
217
topBorderButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); if (listenersEnabled) { CanvasFormattingController .notifyNorthBorderStatus(topBorderButton.isSelected(), selectedPanels); setAllAndNoBorderButtonState(selectedPanels); managedCanvas.fireFocusPersist(); } } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
218
bottomBorderButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); if (listenersEnabled) { CanvasFormattingController.notifySouthBorderStatus(bottomBorderButton.isSelected(), selectedPanels); setAllAndNoBorderButtonState(selectedPanels); managedCanvas.fireFocusPersist(); } } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
219
fullBorderButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean enabled = listenersEnabled; if (fullBorderButton.isSelected()) { listenersEnabled = false; leftBorderButton.setSelected(true); rightBorderButton.setSelected(true); topBorderButton.setSelected(true); bottomBorderButton.setSelected(true); noBorderButton.setSelected(false); listenersEnabled = enabled; if (listenersEnabled) { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); CanvasFormattingController.notifyAllBorderStatus(true, selectedPanels); managedCanvas.fireFocusPersist(); } } else { List<Panel> selectedPanels = managedCanvas.getSelectedPanels(); for (Panel p : selectedPanels) { if (p.getBorderState() != PanelBorder.ALL_BORDERS) { fullBorderButton.setSelected(true); return; } } } } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
220
private static class ColorComboBoxRenderer extends DefaultListCellRenderer implements ListCellRenderer { private static final long serialVersionUID = 4172995566305076422L; private Map<Object, Color> remapper; public ColorComboBoxRenderer() { setPreferredSize(new Dimension(70, 20)); remapper = new HashMap<Object, Color>(); } public void remap(Object object, Color color) { remapper.put(object, color); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel component = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); /* remap certain colors to different ones, in case our presentation differs from * the way colors are stored internally */ Color c = remapper.get(value); if (c == null) { c = (Color) value; } if (c != null) { setBorder(BorderFactory.createLineBorder(c, 4)); component.setText(""); } return component; } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
221
private static class ColorPanel extends JPanel { /** * */ private static final long serialVersionUID = 5931786628055358422L; private static final Dimension COMBO_BOX_DIMENSION = new Dimension(50, 20); Color color; public ColorPanel(Color c) { color = c; setBackground(c); this.setPreferredSize(COMBO_BOX_DIMENSION); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(color); g.fillRect(0, 0, getWidth(), getHeight()); } protected void setColor(Color aColor) { this.color = aColor; } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
222
private static class LineComboBoxRenderer extends JLabel implements ListCellRenderer { private static final long serialVersionUID = 2325113335574780392L; private final PanelBorder border = new PanelBorder(PanelBorder.NORTH_BORDER); public LineComboBoxRenderer() { setOpaque(true); setHorizontalAlignment(CENTER); setVerticalAlignment(CENTER); border.setBorderStyle(BorderStyle.SINGLE); setBorder(new CompoundBorder(new EmptyBorder(4, 4, 4, 4), border)); } /* * This method finds the image and text corresponding to the selected * value and returns the label, set up to display the text and image. */ public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { // Get the selected index. (The index param isn't // always valid, so just use the value.) int selectedIndex = ((Integer) value).intValue(); if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } border.setBorderStyle(selectedIndex); setText(""); return this; } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasFormattingControlsPanel.java
223
public class CanvasIcons { private static ImageIcon jlsAlignTableLeftImage = null; private static ImageIcon jlsAlignTableHCenterImage = null; private static ImageIcon jlsAlignTableRightImage = null; private static ImageIcon jlsAlignTableBottomImage = null; private static ImageIcon jlsAlignTableVCenterImage = null; private static ImageIcon jlsAlignTableTopImage = null; private static ImageIcon jlsLeftBorderSelectedImage = null; private static ImageIcon jlsRightBorderSelectedImage = null; private static ImageIcon jlsTopBorderSelectedImage = null; private static ImageIcon jlsBottomBorderSelectedImage = null; private static ImageIcon jlsAllBorderSelectedImage = null; private static ImageIcon jlsNoBorderSelectedImage = null; private static ImageIcon jlsLeftBorderImage = null; private static ImageIcon jlsRightBorderImage = null; private static ImageIcon jlsTopBorderImage = null; private static ImageIcon jlsBottomBorderImage = null; private static ImageIcon jlsAllBorderImage = null; private static ImageIcon jlsNoBorderImage = null; private static ImageIcon panelWidthImage = null; private static ImageIcon panelHeightImage = null; public static enum Icons { JLS_LEFT_BORDER_SELECTED_ICON, JLS_RIGHT_BORDER_SELECTED_ICON, JLS_TOP_BORDER_SELECTED_ICON, JLS_BOTTOM_BORDER_SELECTED_ICON, JLS_ALL_BORDER_SELECTED_ICON, JLS_NO_BORDER_SELECTED_ICON, JLS_LEFT_BORDER_ICON, JLS_RIGHT_BORDER_ICON, JLS_TOP_BORDER_ICON, JLS_BOTTOM_BORDER_ICON, JLS_ALL_BORDER_ICON, JLS_NO_BORDER_ICON, JLS_ALIGN_TABLE_LEFT_ICON, JLS_ALIGN_TABLE_HCENTER_ICON, JLS_ALIGN_TABLE_RIGHT_ICON, JLS_ALIGN_TABLE_BOTTOM_ICON, JLS_ALIGN_TABLE_VCENTER_ICON, JLS_ALIGN_TABLE_TOP_ICON, PANEL_WIDTH_ICON, PANEL_HEIGHT_ICON, }; public static ImageIcon getIcon(Icons anIconEnum) { switch(anIconEnum) { case JLS_LEFT_BORDER_SELECTED_ICON: if (jlsLeftBorderSelectedImage == null) jlsLeftBorderSelectedImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/LeftBorder_on.png")); return jlsLeftBorderSelectedImage; case JLS_RIGHT_BORDER_SELECTED_ICON: if (jlsRightBorderSelectedImage == null) jlsRightBorderSelectedImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/RightBorder_on.png")); return jlsRightBorderSelectedImage; case JLS_TOP_BORDER_SELECTED_ICON: if (jlsTopBorderSelectedImage == null) jlsTopBorderSelectedImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/TopBorder_on.png")); return jlsTopBorderSelectedImage; case JLS_BOTTOM_BORDER_SELECTED_ICON: if (jlsBottomBorderSelectedImage == null) jlsBottomBorderSelectedImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/BottomBorder_on.png")); return jlsBottomBorderSelectedImage; case JLS_ALL_BORDER_SELECTED_ICON: if (jlsAllBorderSelectedImage == null) jlsAllBorderSelectedImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/AllBorder_on.png")); return jlsAllBorderSelectedImage; case JLS_NO_BORDER_SELECTED_ICON: if (jlsNoBorderSelectedImage == null) jlsNoBorderSelectedImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/NoBorder_on.png")); return jlsNoBorderSelectedImage; case JLS_LEFT_BORDER_ICON: if (jlsLeftBorderImage == null) jlsLeftBorderImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/LeftBorder_off.png")); return jlsLeftBorderImage; case JLS_RIGHT_BORDER_ICON: if (jlsRightBorderImage == null) jlsRightBorderImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/RightBorder_off.png")); return jlsRightBorderImage; case JLS_TOP_BORDER_ICON: if (jlsTopBorderImage == null) jlsTopBorderImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/TopBorder_off.png")); return jlsTopBorderImage; case JLS_BOTTOM_BORDER_ICON: if (jlsBottomBorderImage == null) jlsBottomBorderImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/BottomBorder_off.png")); return jlsBottomBorderImage; case JLS_ALL_BORDER_ICON: if (jlsAllBorderImage == null) jlsAllBorderImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/AllBorder_off.png")); return jlsAllBorderImage; case JLS_NO_BORDER_ICON: if (jlsNoBorderImage == null) jlsNoBorderImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/NoBorder_off.png")); return jlsNoBorderImage; case JLS_ALIGN_TABLE_LEFT_ICON: if (jlsAlignTableLeftImage == null) jlsAlignTableLeftImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/TableAlignLeft_off.png")); return jlsAlignTableLeftImage; case JLS_ALIGN_TABLE_HCENTER_ICON: if (jlsAlignTableHCenterImage == null) jlsAlignTableHCenterImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/TableAlignCenter_off.png")); return jlsAlignTableHCenterImage; case JLS_ALIGN_TABLE_RIGHT_ICON: if (jlsAlignTableRightImage == null) jlsAlignTableRightImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/TableAlignRight_off.png")); return jlsAlignTableRightImage; case JLS_ALIGN_TABLE_BOTTOM_ICON: if (jlsAlignTableBottomImage == null) jlsAlignTableBottomImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/TableAlignBottom_off.png")); return jlsAlignTableBottomImage; case JLS_ALIGN_TABLE_VCENTER_ICON: if (jlsAlignTableVCenterImage == null) jlsAlignTableVCenterImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/TableAlignVerticalCenter_off.png")); return jlsAlignTableVCenterImage; case JLS_ALIGN_TABLE_TOP_ICON: if (jlsAlignTableTopImage == null) jlsAlignTableTopImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/TableAlignTop_off.png")); return jlsAlignTableTopImage; case PANEL_WIDTH_ICON: if (panelWidthImage == null) panelWidthImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/button_panelWidth_on.gif")); return panelWidthImage; case PANEL_HEIGHT_ICON: if (panelHeightImage == null) panelHeightImage = new ImageIcon(CanvasIcons.class.getClassLoader().getResource("images/button_panelHeight_on.gif")); return panelHeightImage; default: return null; } } private CanvasIcons() { // no instantiation } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasIcons.java
224
public static enum Icons { JLS_LEFT_BORDER_SELECTED_ICON, JLS_RIGHT_BORDER_SELECTED_ICON, JLS_TOP_BORDER_SELECTED_ICON, JLS_BOTTOM_BORDER_SELECTED_ICON, JLS_ALL_BORDER_SELECTED_ICON, JLS_NO_BORDER_SELECTED_ICON, JLS_LEFT_BORDER_ICON, JLS_RIGHT_BORDER_ICON, JLS_TOP_BORDER_ICON, JLS_BOTTOM_BORDER_ICON, JLS_ALL_BORDER_ICON, JLS_NO_BORDER_ICON, JLS_ALIGN_TABLE_LEFT_ICON, JLS_ALIGN_TABLE_HCENTER_ICON, JLS_ALIGN_TABLE_RIGHT_ICON, JLS_ALIGN_TABLE_BOTTOM_ICON, JLS_ALIGN_TABLE_VCENTER_ICON, JLS_ALIGN_TABLE_TOP_ICON, PANEL_WIDTH_ICON, PANEL_HEIGHT_ICON, };
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasIcons.java
225
public class CanvasManifestation extends View implements PanelFocusSelectionProvider, SelectionProvider { private static final long serialVersionUID = 984902490997930475L; private static final Logger LOGGER = LoggerFactory.getLogger(CanvasManifestation.class); final Map<Integer, Panel> renderedPanels; private final Set<Panel> selectedPanels; private CanvasFormattingControlsPanel controlPanel; Augmentation augmentation; CanvasPanel canvasPanel; int panelId = 0; private Color scrollColor = null; private Color defaultBorderColor = null; private Color titleLabelColor = null; private Color titleBarColor = null; private boolean canvasEnabled = true; private boolean updating = false; /* Canvas enable/disable added to facilitate fix of MCT-2832 */ private static Set<String> manifestingComponents = new HashSet<String>(); private final PropertyChangeListener selectionListener = new PropertyChangeListener() { @Override public void propertyChange(java.beans.PropertyChangeEvent evt) { Panel selectedPanel = (Panel) evt.getSource(); for (Panel p : renderedPanels.values()) { if (p == selectedPanel) { augmentation.removeHighlights(Collections.singleton(p)); selectedPanels.remove(p); augmentation.repaint(); } else p.clearCurrentSelections(); } firePropertyChange(evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); } }; /** * The client property used for storing manifest info in the swing client properties. */ public static final String MANIFEST_INFO = "gov.nasa.arc.canvas.ManifestInfo"; public static final String CANVAS_CONTENT_PROPERTY = "CANVAS CONTENT PROPERTY"; private String getRealComponentId(AbstractComponent component) { return component.getComponentId(); } public CanvasManifestation(AbstractComponent component, ViewInfo info) { super(component,info); setAutoscrolls(true); this.renderedPanels = new HashMap<Integer, Panel>(); this.selectedPanels = new LinkedHashSet<Panel>(); canvasPanel = new CanvasPanel(); canvasPanel.getAccessibleContext().setAccessibleName("Canvas"); canvasPanel.setLayout(new CanvasLayoutManager(CanvasLayoutManager.MIX)); /* * Check to ensure that there are no other canvas manifestations being manifested above this * element, to avoid infinite recursion (tunnel of mirrors) */ if (manifestingComponents.add(getRealComponentId(getManifestedComponent()))) { try { augmentation = new Augmentation(canvasPanel, this); setDropTarget(new CanvasDropTarget(this, selectionListener)); setBackground(getColor("background")); canvasPanel.setBackground(getColor("background")); scrollColor = getColor("scroll"); titleBarColor = getColor("titlebar"); defaultBorderColor = getColor("defaultBorderColor"); titleLabelColor = getColor("titlebar.foreground"); if (titleLabelColor == null) titleLabelColor = getColor("Label.foreground"); Color gridColor = getColor("grid"); Color gridMinorColor = getColor("grid.minor"); if (gridMinorColor == null) gridMinorColor = gridColor; if (gridColor != null) { canvasPanel.setGridColors(gridColor, gridMinorColor); } getManifestedComponent().getComponents(); load(); canvasPanel.setAutoscrolls(true); OverlayLayout overlayLayout = new OverlayLayout(this); setLayout(overlayLayout); add(augmentation); add(canvasPanel); setRepaintComponentPair(canvasPanel, augmentation); computePreferredSize(); } finally { manifestingComponents.remove(getRealComponentId(getManifestedComponent())); } } else { canvasEnabled = false; // Disable this manifestation. setBackground(Color.GRAY); //TODO: Move colors & error message to external locations JLabel errorLabel = new JLabel("Cannot display canvas view: Nested canvas creates an endless cycle."); errorLabel.setForeground(Color.YELLOW); errorLabel.setAlignmentY(TOP_ALIGNMENT); setLayout(new FlowLayout()); add(errorLabel); } } private Color getColor(String name) { return UIManager.getColor(name); } @Override public void enterLockedState() { super.enterLockedState(); // ensure that all the references to manifestation info are reloaded so that the properties are associated with // the cloned manifestation info load(); } private void load() { if (!canvasEnabled) return; // Disabled panels should load nothing ExtendedProperties viewProperties = getViewProperties(); Set<Object> canvasContents = viewProperties.getProperty(CanvasManifestation.CANVAS_CONTENT_PROPERTY); if (canvasContents != null) { // Remove stale manifestation info in the canvas view property // Note that changes will not be persisted until the next commit. AbstractComponent component = getManifestedComponent(); Iterator<Object> iterator = canvasContents.iterator(); while(iterator.hasNext()) { MCTViewManifestationInfo info = (MCTViewManifestationInfo) iterator.next(); if (!containsChildComponent(component, info.getComponentId())) { iterator.remove(); } } int zorder = 0; for (Object canvasContent : canvasContents) { buildGUI((MCTViewManifestationInfo) canvasContent, zorder); zorder++; } removeStalePanels(canvasContents); panelId++; canvasPanel.revalidate(); } else { removeStalePanels(Collections.<Object> emptySet()); canvasPanel.revalidate(); canvasPanel.repaint(); } } private boolean containsChildComponent(AbstractComponent parentComponent, String childComponentId) { for (AbstractComponent childComponent : parentComponent.getComponents()) { if (childComponentId.equals(childComponent.getComponentId())) return true; } return false; } private void removeStalePanels(Set<Object> canvasCotents) { Iterator<Panel> it = renderedPanels.values().iterator(); while (it.hasNext()) { Panel p = it.next(); MCTViewManifestationInfo paneInfo = CanvasManifestation.getManifestationInfo(p.getWrappedManifestation()); if (!canvasCotents.contains(paneInfo)) { this.canvasPanel.remove(p); it.remove(); selectedPanels.remove(p); augmentation.removeHighlights(Collections.singleton(p)); } } } boolean contains(Panel panel) { return renderedPanels.get(panel.getId()) == panel; } /** * Returns true if the given point is not within a panel, is in the blank area of the canvas. * @param p point to check whether it is directly contained in the canvas or a panel * @return true if the point is in nested manifestation */ boolean isPointinaPanel(Point p) { for (Entry<Integer, Panel> entry : renderedPanels.entrySet()) { Panel panel = entry.getValue(); if (panel.containsPoint(p)) { return true; } } return false; } /** * This method recursively finds the panel by this location on screen. * @param p location on screen * @return the <code>Panel</code> that contains point p */ Panel findImmediatePanel(Point p) { if (!canvasEnabled) return null; // Disabled panels have no sub panels ExtendedProperties viewProperties = getViewProperties(); gov.nasa.arc.mct.util.LinkedHashSet<Object> canvasContents = (gov.nasa.arc.mct.util.LinkedHashSet<Object>)viewProperties.getProperty(CanvasManifestation.CANVAS_CONTENT_PROPERTY); if (canvasContents != null) { for (Object object : canvasContents) { MCTViewManifestationInfo info = (MCTViewManifestationInfo) object; String panelOrder = info .getInfoProperty(ControlAreaFormattingConstants.PANEL_ORDER); Panel panel = renderedPanels.get(Integer.valueOf(panelOrder)); if (panel != null) { if (panel.containsPoint(p)) { View wrappedManifestation = panel.getWrappedManifestation(); if (wrappedManifestation instanceof CanvasManifestation) { CanvasManifestation innerCanvasManifestation = (CanvasManifestation) wrappedManifestation; Panel innerPanel = innerCanvasManifestation.findImmediatePanel(p); if (innerPanel != null) return innerPanel; } return panel; } } else { LOGGER.error("Panel with ID: " + panelOrder + " does not exist. It will be removed."); renderedPanels.remove(panelOrder); } } } return null; } private View getManifestationFromViewInfo(AbstractComponent comp, String viewType, MCTViewManifestationInfo canvasContent) { Collection<ViewInfo> embeddedInfos = comp.getViewInfos(ViewType.EMBEDDED); if (embeddedInfos.isEmpty()) return null; ViewInfo matchedVi = null; for (ViewInfo vi:embeddedInfos) { if (vi.getType().equals(viewType)) { matchedVi = vi; break; } } if (matchedVi == null) { matchedVi = embeddedInfos.iterator().next(); } return CanvasViewStrategy.CANVAS_OWNED.createViewFromManifestInfo(matchedVi, comp, getManifestedComponent(), canvasContent); } private View getManifestation(AbstractComponent comp, String viewType, MCTViewManifestationInfo canvasContent) { View viewManifestation = getManifestationFromViewInfo(comp, viewType, canvasContent); if (viewManifestation == null) { LOGGER.error("Cannot find view type {}.", viewType); return null; } viewManifestation.putClientProperty(CanvasManifestation.MANIFEST_INFO, canvasContent); viewManifestation.setNamingContext(canvasContent); assert viewManifestation.getNamingContext() == canvasContent; return viewManifestation; } private void buildGUI(MCTViewManifestationInfo canvasContent, int zorder) { if (!canvasEnabled) return; // Nothing to build on a disabled canvas String componentId = canvasContent.getComponentId(); String indexStr = canvasContent.getInfoProperty(ControlAreaFormattingConstants.PANEL_ORDER); int index = Integer.parseInt(indexStr); if (panelId < index) { panelId = index; } Panel existingPanel = renderedPanels.get(index); if (existingPanel != null) { if (!updating || selectedPanels.contains(existingPanel)) { // update existing panel existingPanel.update(canvasContent); changeOrder(existingPanel, zorder); } } else { String viewType = canvasContent.getManifestedViewType(); ComponentRegistry cr = ComponentRegistryAccess.getComponentRegistry(); AbstractComponent comp = cr.getComponent(componentId); View viewManifestation = getManifestation(comp, viewType, canvasContent); if (viewManifestation == null) { return; } Panel panel = createPanel(viewManifestation, index, this); viewManifestation.setNamingContext(panel); Dimension dimension = canvasContent.getDimension(); Point location = canvasContent.getStartPoint(); Rectangle bound = new Rectangle(location, dimension); panel.setBounds(bound); placeWidget(panel, zorder); renderedPanels.put(index, panel); } } private void placeWidget(Panel widget, int zorder) { canvasPanel.add(widget, null); changeOrder(widget, zorder); } public Panel createPanel(View manifestation, int panelId, PanelFocusSelectionProvider focusProvider) { Panel p = new Panel(manifestation, panelId, focusProvider); if (scrollColor != null) { p.setScrollColor(scrollColor, getBackground()); } if (titleBarColor != null) { p.setTitleBarColor(titleBarColor, titleLabelColor); } if (defaultBorderColor != null) { p.setDefaultBorderColor(defaultBorderColor); } p.setBackground( getBackground() ); p.getSelectionProvider().addSelectionChangeListener(selectionListener); return p; } @Override protected JComponent initializeControlManifestation() { // Set canvas control this.controlPanel = new CanvasFormattingControlsPanel(this); Dimension d = controlPanel.getMinimumSize(); d.setSize(0, 0); controlPanel.setMinimumSize(d); Dimension preferredSize = controlPanel.getPreferredSize(); JScrollPane jp = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); preferredSize.height += jp.getHorizontalScrollBar().getPreferredSize().height; controlPanel.setPreferredSize(preferredSize); JScrollPane controlScrollPane = new JScrollPane(controlPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); return controlScrollPane; } List<Panel> getSelectedPanels() { return Collections.unmodifiableList(new LinkedList<Panel>(selectedPanels)); } @Override public void updateMonitoredGUI() { if (updating) return; load(); } @Override public void updateMonitoredGUI(ReloadEvent event) { updateMonitoredGUI(); } @Override public void updateMonitoredGUI(AddChildEvent event) { updateMonitoredGUI(); } @Override public void updateMonitoredGUI(RemoveChildEvent event) { updateMonitoredGUI(); } @Override public boolean isContentOwner() { return true; } public Color getDefaultBorderColor() { return defaultBorderColor != null ? defaultBorderColor : Color.BLACK; } @Override public void fireFocusSelection(Panel panel) { if (panel != null) { clearSelections(); select(panel); if (controlPanel != null) { controlPanel.informOnePanelSelected(getSelectedPanels()); } firePropertyChange(SelectionProvider.SELECTION_CHANGED_PROP, null, getSelectedManifestations()); augmentation.repaint(); } } @Override public void fireSelectionRemoved(Panel panel) { assert selectedPanels.contains(panel) : "Panel must be selected in the canvas."; // Remove selection and highlight. augmentation.removeHighlights(Collections.singleton(panel)); selectedPanels.remove(panel); firePropertyChange(SelectionProvider.SELECTION_CHANGED_PROP, null, getSelectedManifestations()); if (controlPanel != null) { switch (selectedPanels.size()) { case 0: controlPanel.informZeroPanelsSelected(); break; case 1: controlPanel.informOnePanelSelected(getSelectedPanels()); break; default : controlPanel.informMultipleViewPanelsSelected(getSelectedPanels()); break; } } // Remove from canvas panel and persist. Integer key = null; for (Entry<Integer, Panel> entry : renderedPanels.entrySet()) { if (panel == entry.getValue()) { key = entry.getKey(); break; } } assert key != null : "Panel not found in canvas view."; renderedPanels.remove(key); canvasPanel.remove(panel); canvasPanel.repaint(); Set<Object> viewProperties = getViewProperties().getProperty(CanvasManifestation.CANVAS_CONTENT_PROPERTY); MCTViewManifestationInfo info = null; for (Object viewProperty : viewProperties) { assert viewProperty instanceof MCTViewManifestationInfo : "Canvas property must be MCTViewManifestationInfo"; info = (MCTViewManifestationInfo) viewProperty; if (info == CanvasManifestation.getManifestationInfo(panel.getWrappedManifestation())) { break; } } viewProperties.remove(info); fireFocusPersist(); firePropertyChange(PanelFocusTraversalPolicy.FOCUS_SELECTION_CHANGE_PROP, null, renderedPanels); } @Override public void fireSelectionCloned(Collection<Panel> panels) { for (Panel panel : panels) { int nextPanelId = panelId++; panel.setId(nextPanelId); View manifestation = panel.getWrappedManifestation(); MCTViewManifestationInfo viewManifestationInfo = CanvasManifestation.getManifestationInfo(manifestation); getViewProperties().addProperty(CANVAS_CONTENT_PROPERTY, viewManifestationInfo); viewManifestationInfo.addInfoProperty(ControlAreaFormattingConstants.PANEL_ORDER, Integer.toString(nextPanelId)); canvasPanel.add(panel, new Rectangle(viewManifestationInfo.getStartPoint(), viewManifestationInfo.getDimension())); renderedPanels.put(nextPanelId, panel); } canvasPanel.revalidate(); setSelection(panels); fireFocusPersist(); firePropertyChange(PanelFocusTraversalPolicy.FOCUS_SELECTION_CHANGE_PROP, null, renderedPanels); } @Override public void fireFocusPersist() { if (!isLocked()) { try { updating = true; getManifestedComponent().save(); } finally { updating = false; } } } @Override public void fireManifestationChanged() { firePropertyChange(SelectionProvider.SELECTION_CHANGED_PROP, null, getSelectedManifestations()); } public void firePanelsDropped() { firePropertyChange(PanelFocusTraversalPolicy.FOCUS_SELECTION_CHANGE_PROP, null, renderedPanels); canvasPanel.computePreferredSize(); } public void updateController(Collection<Panel> panels) { // This occurs when the canvas manifestation is in a panel. // We are NOT currently supporting canvas control in a panel. if (controlPanel == null) return; if (panels == null || panels.isEmpty()) controlPanel.informZeroPanelsSelected(); else if (panels.size() == 1) controlPanel.informOnePanelSelected(Collections.singletonList(panels.iterator().next())); else controlPanel.informMultipleViewPanelsSelected(panels); } private void changeOrder(Panel panel, int order) { canvasPanel.setComponentZOrder(panel, order); } void changeOrder(Panel panel, PANEL_ZORDER order) { ExtendedProperties viewProperties = getViewProperties(); gov.nasa.arc.mct.util.LinkedHashSet<Object> canvasContents = (gov.nasa.arc.mct.util.LinkedHashSet<Object>)viewProperties.getProperty(CanvasManifestation.CANVAS_CONTENT_PROPERTY); MCTViewManifestationInfo movedManifestInfo = CanvasManifestation.getManifestationInfo(panel.getWrappedManifestation()); canvasContents.remove(movedManifestInfo); switch(order) { case FRONT: changeOrder(panel, 0); canvasContents.add(movedManifestInfo); break; case BACK: changeOrder(panel, canvasPanel.getComponentCount()-1); canvasContents.offerLast(movedManifestInfo); break; } } @Override public void fireOrderChange(Panel panel, PANEL_ZORDER order) { changeOrder(panel, order); canvasPanel.repaint(); } public void enableGrid(int gridSize) { canvasPanel.paintGrid(gridSize); } /** * Sets a single selection based on the mouse location. * @param p <code>Point</code> */ Panel setSingleSelection(Point p) { clearSelections(); return addSingleSelection(p); } /** * Add a single selection based on mouse location. * @param p <code>Point</code> */ Panel addSingleSelection(Point p) { Panel panel = findImmediatePanel(p); if (panel != null) { Container container = SwingUtilities.getAncestorOfClass(CanvasManifestation.class, panel); assert container instanceof CanvasManifestation : "Panels must be contained in a CanvasManifestation"; CanvasManifestation nestedCanvasManifestation = (CanvasManifestation) container; nestedCanvasManifestation.select(panel); } return panel; } /** * Sets the selected panels to the given selection * @param newlySelectedPanels panels to select */ void setSelection(Collection<Panel> newlySelectedPanels) { clearSelections(); selectedPanels.addAll(newlySelectedPanels); for (Panel p:newlySelectedPanels) { changeOrder(p, PANEL_ZORDER.FRONT); } augmentation.addHighlights(newlySelectedPanels); if (controlPanel != null) { if (newlySelectedPanels.size() == 1) { controlPanel.informOnePanelSelected(Collections.singletonList(newlySelectedPanels.iterator().next())); } else { controlPanel.informMultipleViewPanelsSelected(newlySelectedPanels); } } firePropertyChange(SelectionProvider.SELECTION_CHANGED_PROP, null, getSelectedManifestations()); } /** * Adds the target panel to the set of selectedPanels in this <code>CanvasManifestation</code>. * In addition, it highlights the panel and brings it to front. * @param panel */ private void select(Panel panel) { if (selectedPanels.contains(panel)) return; selectedPanels.add(panel); if (controlPanel != null) { if (selectedPanels.size() == 1) { controlPanel.informOnePanelSelected(getSelectedPanels()); } else { controlPanel.informMultipleViewPanelsSelected(getSelectedPanels()); } } changeOrder(panel, PANEL_ZORDER.FRONT); augmentation.addHighlights(selectedPanels); panel.clearCurrentSelections(); firePropertyChange(SelectionProvider.SELECTION_CHANGED_PROP, null, getSelectedManifestations()); } /** * Clears all selections and all its nested <code>CanvasManifestation</code>s. * Also resets the formatting control settings. */ private void clearSelections() { clearSelectionInCanvas(); if (controlPanel != null) { controlPanel.informZeroPanelsSelected(); } } private void clearSelectionInCanvas() { if (!canvasEnabled) return; // Disabled panels contain nothing augmentation.removeHighlights(selectedPanels); selectedPanels.clear(); for (Entry<Integer, Panel> entry : renderedPanels.entrySet()) { Panel panel = entry.getValue(); panel.clearCurrentSelections(); } } @Override public SelectionProvider getSelectionProvider() { return this; } @Override public void addSelectionChangeListener(PropertyChangeListener listener) { addPropertyChangeListener(SelectionProvider.SELECTION_CHANGED_PROP, listener); } @Override public void clearCurrentSelections() { clearSelections(); // Clear selection in panels for (Panel p : renderedPanels.values()) p.clearCurrentSelections(); } public void selectAll() { setSelection(renderedPanels.values()); augmentation.repaint(); } @Override public Collection<View> getSelectedManifestations() { List<View> manifestations = new ArrayList<View>(); addToSelectionCollection(manifestations); return manifestations; } private void addToSelectionCollection(List<View> manifestations) { for (Panel panel : selectedPanels) manifestations.add(panel.getWrappedManifestation()); for (Entry<Integer, Panel> entry : renderedPanels.entrySet()) { Panel panel = entry.getValue(); View wrappedManifestation = panel.getWrappedManifestation(); if (wrappedManifestation instanceof CanvasManifestation) { ((CanvasManifestation) wrappedManifestation).addToSelectionCollection(manifestations); } } } @Override public void removeSelectionChangeListener(PropertyChangeListener listener) { removePropertyChangeListener(SelectionProvider.SELECTION_CHANGED_PROP, listener); } public int getGridSize() { return this.canvasPanel.getGridSize(); } public boolean isSnapEnable() { return this.canvasPanel.isSnapEnable(); } public void enableSnap(boolean snapToGrid) { if (getGridSize() != ControlAreaFormattingConstants.NO_GRID_SIZE) { this.canvasPanel.enableSnap(snapToGrid); } } public void retile() { this.canvasPanel.retile(); } Dimension getCanvasSize() { return this.canvasPanel.getPreferredSize(); } void computePreferredSize() { this.canvasPanel.computePreferredSize(); } public static MCTViewManifestationInfo getManifestationInfo(View v) { return MCTViewManifestationInfo.class.cast(v.getClientProperty(CanvasManifestation.MANIFEST_INFO)); } private final class CanvasPanel extends JPanel { private static final long serialVersionUID = 1066175421844534610L; private BufferedImage grid = null; private Color gridMajor = ControlAreaFormattingConstants.MAJOR_GRID_LINE_COLOR; private Color gridMinor = ControlAreaFormattingConstants.MINOR_GRID_LINE_COLOR; @Override public boolean isOptimizedDrawingEnabled() { return false; } public int getGridSize() { CanvasLayoutManager layoutManager = (CanvasLayoutManager)getLayout(); return layoutManager.getGridSize(); } public void computePreferredSize() { Component[] childComponents = getComponents(); if (childComponents.length == 0) { return; } Rectangle bound = childComponents[0].getBounds(); int largestWidth = bound.x + bound.width; int largestHeight = bound.y + bound.height; for (int i=1; i<childComponents.length; i++) { bound = childComponents[i].getBounds(); if (bound.x+bound.width > largestWidth) { largestWidth = bound.x + bound.width; } if (bound.y+bound.height > largestHeight) { largestHeight = bound.y+bound.height; } } Dimension currentDimension = getPreferredSize(); if (largestWidth != currentDimension.width || largestHeight != currentDimension.height) { if (((JComponent) CanvasManifestation.this.getParent()) != null) { Rectangle visibleRect = ((JComponent) CanvasManifestation.this.getParent()).getVisibleRect(); if (largestWidth < visibleRect.width) largestWidth = visibleRect.width; if (largestHeight < visibleRect.height) largestHeight = visibleRect.height; } setPreferredSize(new Dimension(largestWidth, largestHeight)); revalidate(); } } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (grid != null) { int x, y; int width, height; Rectangle clip = this.getBounds(); width = grid.getHeight(this); height = grid.getWidth(this); if(width > 0 && height > 0) { for(x = clip.x; x < (clip.x + clip.width) ; x += width) { for(y = clip.y; y < (clip.y + clip.height) ; y += height) { g.drawImage(grid,x,y,this); } } } } } public void paintGrid(int gridSize) { if (gridSize != getGridSize()) { CanvasLayoutManager layoutManager = (CanvasLayoutManager)getLayout(); layoutManager.setGridSize(gridSize); if (gridSize == ControlAreaFormattingConstants.NO_GRID_SIZE) { grid = null; } else { int w = ControlAreaFormattingConstants.MAJOR_GRID_LINE; int h = ControlAreaFormattingConstants.MAJOR_GRID_LINE; grid = (BufferedImage) (this.createImage(w, h)); if (grid == null) return; // unable to create a bufferedImage... Graphics2D gc = grid.createGraphics(); // now, draw the grid lines. Note that the second drawLine is for // drawing Major lines. // The first drawLine is for the minor lines. gc.setColor(this.getBackground()); gc.fillRect(0, 0, w, h); for (int x = 0; x < w; x += gridSize) { gc.setColor(gridMinor); gc.drawLine(x, 0, x, h); // minor line if (x % ControlAreaFormattingConstants.MAJOR_GRID_LINE == 0) { gc.setColor(gridMajor); gc.drawLine(x + 1, 0, x + 1, h); // major line } } for (int y = 0; y < h; y += gridSize) { gc.setColor(gridMinor); gc.drawLine(0, y, w, y); // minor line if (y % ControlAreaFormattingConstants.MAJOR_GRID_LINE == 0) { gc.setColor(gridMajor); gc.drawLine(0, y + 1, w, y + 1); // major line } } } repaint(); } } public void enableSnap(boolean snapToGrid) { CanvasLayoutManager layoutManager = (CanvasLayoutManager)getLayout(); layoutManager.enableSnap(snapToGrid); } public boolean isSnapEnable() { CanvasLayoutManager layoutManager = (CanvasLayoutManager)getLayout(); return layoutManager.isSnapEnable(); } public void retile() { CanvasLayoutManager layoutManager = (CanvasLayoutManager)getLayout(); layoutManager.switchLayout(CanvasLayoutManager.TILE); doLayout(); layoutManager.switchLayout(CanvasLayoutManager.MIX); } public void setGridColors(Color major, Color minor) { this.gridMajor = major; this.gridMinor = minor; } } private static final class CanvasDropTarget extends DropTarget { private static final long serialVersionUID = 7461617221853901503L; private CanvasManifestation canvasManifestation; private PropertyChangeListener selectionListener; CanvasDropTarget(CanvasManifestation canvasManifestation, PropertyChangeListener selectionListener) { this.canvasManifestation = canvasManifestation; this.selectionListener = selectionListener; } @Override public void drop(DropTargetDropEvent dtde) { AbstractComponent canvasComponent = canvasManifestation.getManifestedComponent(); Transferable data = dtde.getTransferable(); try { if (!data.isDataFlavorSupported(View.DATA_FLAVOR)) { dtde.rejectDrop(); return; } if (canvasComponent != null) { View[] viewRoles = (View[]) data.getTransferData(View.DATA_FLAVOR); dropAction(canvasComponent, Arrays.asList(viewRoles), dtde.getLocation()); } } catch (UnsupportedFlavorException e) { LOGGER.error("UnsupportedFlavorException", e); } catch (IOException e) { LOGGER.error("IOException", e); } } private void dropAction(AbstractComponent canvasComponent, Collection<View> droppedViews, Point location) { // Check if component is locked and not editable. if (canvasManifestation.isLocked()) { showCompositionErrorMessage("Object \"" + canvasComponent.getDisplayName() + "\" is currently locked."); return; } // Differentiate dropped components between new and existing children. List<AbstractComponent> toBeComposed = new LinkedList<AbstractComponent>(); List<AbstractComponent> referencedComponents = canvasComponent.getComponents(); Collection<AbstractComponent> dropComponents = getDroppedComponents(droppedViews.toArray(new View[droppedViews.size()])); for (AbstractComponent sourceComponent : dropComponents) { AbstractComponent actualComponent = sourceComponent; boolean found = false; for (AbstractComponent ac : referencedComponents) { if (ac.getComponentId().equals(actualComponent.getComponentId())) { found = true; } } if (!found) toBeComposed.add(actualComponent); } // Check if allows adding/removing children from current component. if (!toBeComposed.isEmpty()) { ExecutionResult result = checkPolicyForDrops(canvasComponent, toBeComposed, canvasManifestation); if (!result.getStatus()) { showCompositionErrorMessage(result.getMessage()); return; } } if (!toBeComposed.isEmpty()) { canvasComponent.addDelegateComponents(toBeComposed); } Collection<Panel> panels = new LinkedHashSet<Panel>(); // Update the drop point just in case there is something in // the toBeComposed collection panels.addAll(addToCanvas(droppedViews, canvasManifestation, location)); // Select the newly added panels. canvasManifestation.setSelection(panels); canvasManifestation.firePanelsDropped(); Window w = SwingUtilities.getWindowAncestor(canvasManifestation); if (w != null) { w.toFront(); } } private void showCompositionErrorMessage(final String message) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { OptionBox.showMessageDialog(canvasManifestation, message, "Composition Error - ", OptionBox.ERROR_MESSAGE); } }); } private boolean isViewEmbeddable(View v, AbstractComponent comp) { return comp.getViewInfos(ViewType.EMBEDDED).contains(v.getInfo()); } private ViewInfo getViewInfoForCanvas(View v, AbstractComponent comp) { if (isViewEmbeddable(v, comp)) { return v.getInfo(); } Set<ViewInfo> viewInfos = comp.getViewInfos(ViewType.EMBEDDED); return viewInfos.iterator().next(); } private Collection<Panel> addToCanvas(Collection<View> toBeAddedViews, CanvasManifestation containerManifestation, Point dropPoint) { Collection<Panel> panels = new LinkedHashSet<Panel>(); for (View v : toBeAddedViews) { AbstractComponent viewComp = v.getManifestedComponent(); ViewInfo newViewInfo = getViewInfoForCanvas(v, viewComp); AbstractComponent comp = viewComp; int nextPanelId = containerManifestation.panelId++; MCTViewManifestationInfo viewManifestationInfo = new MCTViewManifestationInfoImpl(); viewManifestationInfo.setComponentId(comp.getComponentId()); viewManifestationInfo.setStartPoint(dropPoint); viewManifestationInfo.setManifestedViewType(newViewInfo.getType()); if (v.getInfo().equals(newViewInfo)) { ExtendedProperties ep = v.getViewProperties().clone(); ep.addProperty(CanvasViewStrategy.OWNED_TYPE_PROPERTY_NAME, v.getInfo().getType()); viewManifestationInfo.getOwnedProperties().add(ep); } viewManifestationInfo.addInfoProperty(ControlAreaFormattingConstants.PANEL_ORDER, String.valueOf(nextPanelId)); // use the viewComp here instead of the master component to retrieve the actual properties for the view View addManifestation = CanvasViewStrategy.CANVAS_OWNED.createViewFromManifestInfo(newViewInfo, comp, canvasManifestation.getManifestedComponent(), viewManifestationInfo); addManifestation.putClientProperty(CanvasManifestation.MANIFEST_INFO, viewManifestationInfo); Panel panel = containerManifestation.createPanel(addManifestation, nextPanelId, containerManifestation); viewManifestationInfo.setDimension(panel.getPreferredSize()); addManifestation.setNamingContext(panel); assert addManifestation.getNamingContext() == panel; // Add new panel info to the canvas content property list ExtendedProperties viewTypeProperties = containerManifestation.getViewProperties(); viewTypeProperties.addProperty(CANVAS_CONTENT_PROPERTY, viewManifestationInfo); containerManifestation.renderedPanels.put( nextPanelId, panel); containerManifestation.canvasPanel.add(panel, new Rectangle(dropPoint, panel.getPreferredSize())); panels.add(panel); containerManifestation.changeOrder(panel, PANEL_ZORDER.FRONT); panel.getSelectionProvider().addSelectionChangeListener(selectionListener); } if (!panels.isEmpty()) { containerManifestation.canvasPanel.revalidate(); containerManifestation.fireFocusPersist(); } return panels; } protected ExecutionResult checkPolicyForDrops(AbstractComponent canvasComponent, Collection<AbstractComponent> dropComponents, View canvasManifestation) { PolicyContext context = new PolicyContext(); context.setProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), canvasComponent); context.setProperty(PolicyContext.PropertyName.SOURCE_COMPONENTS.getName(), dropComponents); context .setProperty(PolicyContext.PropertyName.ACTION.getName(), Character .valueOf('w')); context.setProperty(PolicyContext.PropertyName.VIEW_MANIFESTATION_PROVIDER.getName(), canvasManifestation); String policyCategoryKey = PolicyInfo.CategoryType.COMPOSITION_POLICY_CATEGORY.getKey(); ExecutionResult result = PolicyManagerAccess.getPolicyManager().execute( policyCategoryKey, context); return result; } private List<AbstractComponent> getDroppedComponents(View[] origViews) { List<AbstractComponent> marshalledComponents = new LinkedList<AbstractComponent>(); for (View v : origViews) { marshalledComponents.add(v.getManifestedComponent()); } return marshalledComponents; } } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasManifestation.java
226
private final PropertyChangeListener selectionListener = new PropertyChangeListener() { @Override public void propertyChange(java.beans.PropertyChangeEvent evt) { Panel selectedPanel = (Panel) evt.getSource(); for (Panel p : renderedPanels.values()) { if (p == selectedPanel) { augmentation.removeHighlights(Collections.singleton(p)); selectedPanels.remove(p); augmentation.repaint(); } else p.clearCurrentSelections(); } firePropertyChange(evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); } };
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasManifestation.java
227
private static final class CanvasDropTarget extends DropTarget { private static final long serialVersionUID = 7461617221853901503L; private CanvasManifestation canvasManifestation; private PropertyChangeListener selectionListener; CanvasDropTarget(CanvasManifestation canvasManifestation, PropertyChangeListener selectionListener) { this.canvasManifestation = canvasManifestation; this.selectionListener = selectionListener; } @Override public void drop(DropTargetDropEvent dtde) { AbstractComponent canvasComponent = canvasManifestation.getManifestedComponent(); Transferable data = dtde.getTransferable(); try { if (!data.isDataFlavorSupported(View.DATA_FLAVOR)) { dtde.rejectDrop(); return; } if (canvasComponent != null) { View[] viewRoles = (View[]) data.getTransferData(View.DATA_FLAVOR); dropAction(canvasComponent, Arrays.asList(viewRoles), dtde.getLocation()); } } catch (UnsupportedFlavorException e) { LOGGER.error("UnsupportedFlavorException", e); } catch (IOException e) { LOGGER.error("IOException", e); } } private void dropAction(AbstractComponent canvasComponent, Collection<View> droppedViews, Point location) { // Check if component is locked and not editable. if (canvasManifestation.isLocked()) { showCompositionErrorMessage("Object \"" + canvasComponent.getDisplayName() + "\" is currently locked."); return; } // Differentiate dropped components between new and existing children. List<AbstractComponent> toBeComposed = new LinkedList<AbstractComponent>(); List<AbstractComponent> referencedComponents = canvasComponent.getComponents(); Collection<AbstractComponent> dropComponents = getDroppedComponents(droppedViews.toArray(new View[droppedViews.size()])); for (AbstractComponent sourceComponent : dropComponents) { AbstractComponent actualComponent = sourceComponent; boolean found = false; for (AbstractComponent ac : referencedComponents) { if (ac.getComponentId().equals(actualComponent.getComponentId())) { found = true; } } if (!found) toBeComposed.add(actualComponent); } // Check if allows adding/removing children from current component. if (!toBeComposed.isEmpty()) { ExecutionResult result = checkPolicyForDrops(canvasComponent, toBeComposed, canvasManifestation); if (!result.getStatus()) { showCompositionErrorMessage(result.getMessage()); return; } } if (!toBeComposed.isEmpty()) { canvasComponent.addDelegateComponents(toBeComposed); } Collection<Panel> panels = new LinkedHashSet<Panel>(); // Update the drop point just in case there is something in // the toBeComposed collection panels.addAll(addToCanvas(droppedViews, canvasManifestation, location)); // Select the newly added panels. canvasManifestation.setSelection(panels); canvasManifestation.firePanelsDropped(); Window w = SwingUtilities.getWindowAncestor(canvasManifestation); if (w != null) { w.toFront(); } } private void showCompositionErrorMessage(final String message) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { OptionBox.showMessageDialog(canvasManifestation, message, "Composition Error - ", OptionBox.ERROR_MESSAGE); } }); } private boolean isViewEmbeddable(View v, AbstractComponent comp) { return comp.getViewInfos(ViewType.EMBEDDED).contains(v.getInfo()); } private ViewInfo getViewInfoForCanvas(View v, AbstractComponent comp) { if (isViewEmbeddable(v, comp)) { return v.getInfo(); } Set<ViewInfo> viewInfos = comp.getViewInfos(ViewType.EMBEDDED); return viewInfos.iterator().next(); } private Collection<Panel> addToCanvas(Collection<View> toBeAddedViews, CanvasManifestation containerManifestation, Point dropPoint) { Collection<Panel> panels = new LinkedHashSet<Panel>(); for (View v : toBeAddedViews) { AbstractComponent viewComp = v.getManifestedComponent(); ViewInfo newViewInfo = getViewInfoForCanvas(v, viewComp); AbstractComponent comp = viewComp; int nextPanelId = containerManifestation.panelId++; MCTViewManifestationInfo viewManifestationInfo = new MCTViewManifestationInfoImpl(); viewManifestationInfo.setComponentId(comp.getComponentId()); viewManifestationInfo.setStartPoint(dropPoint); viewManifestationInfo.setManifestedViewType(newViewInfo.getType()); if (v.getInfo().equals(newViewInfo)) { ExtendedProperties ep = v.getViewProperties().clone(); ep.addProperty(CanvasViewStrategy.OWNED_TYPE_PROPERTY_NAME, v.getInfo().getType()); viewManifestationInfo.getOwnedProperties().add(ep); } viewManifestationInfo.addInfoProperty(ControlAreaFormattingConstants.PANEL_ORDER, String.valueOf(nextPanelId)); // use the viewComp here instead of the master component to retrieve the actual properties for the view View addManifestation = CanvasViewStrategy.CANVAS_OWNED.createViewFromManifestInfo(newViewInfo, comp, canvasManifestation.getManifestedComponent(), viewManifestationInfo); addManifestation.putClientProperty(CanvasManifestation.MANIFEST_INFO, viewManifestationInfo); Panel panel = containerManifestation.createPanel(addManifestation, nextPanelId, containerManifestation); viewManifestationInfo.setDimension(panel.getPreferredSize()); addManifestation.setNamingContext(panel); assert addManifestation.getNamingContext() == panel; // Add new panel info to the canvas content property list ExtendedProperties viewTypeProperties = containerManifestation.getViewProperties(); viewTypeProperties.addProperty(CANVAS_CONTENT_PROPERTY, viewManifestationInfo); containerManifestation.renderedPanels.put( nextPanelId, panel); containerManifestation.canvasPanel.add(panel, new Rectangle(dropPoint, panel.getPreferredSize())); panels.add(panel); containerManifestation.changeOrder(panel, PANEL_ZORDER.FRONT); panel.getSelectionProvider().addSelectionChangeListener(selectionListener); } if (!panels.isEmpty()) { containerManifestation.canvasPanel.revalidate(); containerManifestation.fireFocusPersist(); } return panels; } protected ExecutionResult checkPolicyForDrops(AbstractComponent canvasComponent, Collection<AbstractComponent> dropComponents, View canvasManifestation) { PolicyContext context = new PolicyContext(); context.setProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), canvasComponent); context.setProperty(PolicyContext.PropertyName.SOURCE_COMPONENTS.getName(), dropComponents); context .setProperty(PolicyContext.PropertyName.ACTION.getName(), Character .valueOf('w')); context.setProperty(PolicyContext.PropertyName.VIEW_MANIFESTATION_PROVIDER.getName(), canvasManifestation); String policyCategoryKey = PolicyInfo.CategoryType.COMPOSITION_POLICY_CATEGORY.getKey(); ExecutionResult result = PolicyManagerAccess.getPolicyManager().execute( policyCategoryKey, context); return result; } private List<AbstractComponent> getDroppedComponents(View[] origViews) { List<AbstractComponent> marshalledComponents = new LinkedList<AbstractComponent>(); for (View v : origViews) { marshalledComponents.add(v.getManifestedComponent()); } return marshalledComponents; } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasManifestation.java
228
SwingUtilities.invokeLater(new Runnable() { @Override public void run() { OptionBox.showMessageDialog(canvasManifestation, message, "Composition Error - ", OptionBox.ERROR_MESSAGE); } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasManifestation.java
229
private final class CanvasPanel extends JPanel { private static final long serialVersionUID = 1066175421844534610L; private BufferedImage grid = null; private Color gridMajor = ControlAreaFormattingConstants.MAJOR_GRID_LINE_COLOR; private Color gridMinor = ControlAreaFormattingConstants.MINOR_GRID_LINE_COLOR; @Override public boolean isOptimizedDrawingEnabled() { return false; } public int getGridSize() { CanvasLayoutManager layoutManager = (CanvasLayoutManager)getLayout(); return layoutManager.getGridSize(); } public void computePreferredSize() { Component[] childComponents = getComponents(); if (childComponents.length == 0) { return; } Rectangle bound = childComponents[0].getBounds(); int largestWidth = bound.x + bound.width; int largestHeight = bound.y + bound.height; for (int i=1; i<childComponents.length; i++) { bound = childComponents[i].getBounds(); if (bound.x+bound.width > largestWidth) { largestWidth = bound.x + bound.width; } if (bound.y+bound.height > largestHeight) { largestHeight = bound.y+bound.height; } } Dimension currentDimension = getPreferredSize(); if (largestWidth != currentDimension.width || largestHeight != currentDimension.height) { if (((JComponent) CanvasManifestation.this.getParent()) != null) { Rectangle visibleRect = ((JComponent) CanvasManifestation.this.getParent()).getVisibleRect(); if (largestWidth < visibleRect.width) largestWidth = visibleRect.width; if (largestHeight < visibleRect.height) largestHeight = visibleRect.height; } setPreferredSize(new Dimension(largestWidth, largestHeight)); revalidate(); } } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (grid != null) { int x, y; int width, height; Rectangle clip = this.getBounds(); width = grid.getHeight(this); height = grid.getWidth(this); if(width > 0 && height > 0) { for(x = clip.x; x < (clip.x + clip.width) ; x += width) { for(y = clip.y; y < (clip.y + clip.height) ; y += height) { g.drawImage(grid,x,y,this); } } } } } public void paintGrid(int gridSize) { if (gridSize != getGridSize()) { CanvasLayoutManager layoutManager = (CanvasLayoutManager)getLayout(); layoutManager.setGridSize(gridSize); if (gridSize == ControlAreaFormattingConstants.NO_GRID_SIZE) { grid = null; } else { int w = ControlAreaFormattingConstants.MAJOR_GRID_LINE; int h = ControlAreaFormattingConstants.MAJOR_GRID_LINE; grid = (BufferedImage) (this.createImage(w, h)); if (grid == null) return; // unable to create a bufferedImage... Graphics2D gc = grid.createGraphics(); // now, draw the grid lines. Note that the second drawLine is for // drawing Major lines. // The first drawLine is for the minor lines. gc.setColor(this.getBackground()); gc.fillRect(0, 0, w, h); for (int x = 0; x < w; x += gridSize) { gc.setColor(gridMinor); gc.drawLine(x, 0, x, h); // minor line if (x % ControlAreaFormattingConstants.MAJOR_GRID_LINE == 0) { gc.setColor(gridMajor); gc.drawLine(x + 1, 0, x + 1, h); // major line } } for (int y = 0; y < h; y += gridSize) { gc.setColor(gridMinor); gc.drawLine(0, y, w, y); // minor line if (y % ControlAreaFormattingConstants.MAJOR_GRID_LINE == 0) { gc.setColor(gridMajor); gc.drawLine(0, y + 1, w, y + 1); // major line } } } repaint(); } } public void enableSnap(boolean snapToGrid) { CanvasLayoutManager layoutManager = (CanvasLayoutManager)getLayout(); layoutManager.enableSnap(snapToGrid); } public boolean isSnapEnable() { CanvasLayoutManager layoutManager = (CanvasLayoutManager)getLayout(); return layoutManager.isSnapEnable(); } public void retile() { CanvasLayoutManager layoutManager = (CanvasLayoutManager)getLayout(); layoutManager.switchLayout(CanvasLayoutManager.TILE); doLayout(); layoutManager.switchLayout(CanvasLayoutManager.MIX); } public void setGridColors(Color major, Color minor) { this.gridMajor = major; this.gridMinor = minor; } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_CanvasManifestation.java
230
public class CanvasRemoveComponentUpdateTest { @Mock private AbstractComponent mockParentComponent; @Mock private AbstractComponent mockChildComponent; @Mock private MCTViewManifestationInfo mockInfo; @Mock private ComponentRegistry mockComponentRegistry; private ExtendedProperties extProps; private ComponentRegistryAccess access; @BeforeMethod public void setup() { MockitoAnnotations.initMocks(this); extProps = new ExtendedProperties(); Mockito.when(mockParentComponent.getComponents()).thenReturn( Collections.<AbstractComponent> singletonList(mockChildComponent)); String childComponentId = "test1"; Mockito.when(mockChildComponent.getId()).thenReturn(childComponentId); Mockito.when(mockInfo.getComponentId()).thenReturn(childComponentId); Mockito.when(mockInfo.getInfoProperty("PANEL_ORDER")).thenReturn("0"); extProps.addProperty("CANVAS CONTENT PROPERTY", mockInfo); access = new ComponentRegistryAccess(); Mockito.when(mockComponentRegistry.getComponent(childComponentId)).thenReturn(mockChildComponent); access.setRegistry(mockComponentRegistry); } @AfterMethod public void tearDown() { access.releaseRegistry(mockComponentRegistry); } @SuppressWarnings("serial") @Test public void test() { View manif = new CanvasManifestation(mockParentComponent, new ViewInfo(CanvasManifestation.class,"",ViewType.OBJECT)) { @Override public ExtendedProperties getViewProperties() { return extProps; } }; Mockito.when(mockParentComponent.getComponents()).thenReturn( Collections.<AbstractComponent> emptyList()); RemoveChildEvent event = new RemoveChildEvent(new JPanel(), mockChildComponent); manif.updateMonitoredGUI(event); Set<Object> canvasContents = manif.getViewProperties().getProperty("CANVAS CONTENT PROPERTY"); Assert.assertFalse(canvasContents.iterator().hasNext()); } }
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_CanvasRemoveComponentUpdateTest.java
231
View manif = new CanvasManifestation(mockParentComponent, new ViewInfo(CanvasManifestation.class,"",ViewType.OBJECT)) { @Override public ExtendedProperties getViewProperties() { return extProps; } };
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_CanvasRemoveComponentUpdateTest.java
232
public class ChangeGridSizeAction extends GroupAction { private static final long serialVersionUID = -5917294719128741636L; private static ResourceBundle bundle = ResourceBundle.getBundle("CanvasResourceBundle"); public ChangeGridSizeAction() { super(bundle.getString("Change_Grid_Size")); } @Override public void actionPerformed(ActionEvent e) { } /** * Returns list of selected manifestations. The default behavior is to return {@link ActionContext#getSelectedManifestations()}. * @param context to use for deriving selected manifestations. * @return selected manifestations */ protected Collection<View> getSelectedManifestations(ActionContext context) { return context.getSelectedManifestations(); } @Override public boolean canHandle(ActionContext actionContext) { List<GroupAction.RadioAction> actions = new ArrayList<RadioAction>(); actions.add(new ChangeAction(actionContext, bundle.getString("Fine_Grid"), ControlAreaFormattingConstants.FINE_GRID_SIZE)); actions.add(new ChangeAction(actionContext, bundle.getString("Small_Grid"), ControlAreaFormattingConstants.SMALL_GRID_SIZE)); actions.add(new ChangeAction(actionContext, bundle.getString("Medium_Grid"), ControlAreaFormattingConstants.MED_GRID_SIZE)); actions.add(new ChangeAction(actionContext, bundle.getString("Large_Grid"), ControlAreaFormattingConstants.LARGE_GRID_SIZE)); actions.add(new ChangeAction(actionContext, bundle.getString("No_Grid"), ControlAreaFormattingConstants.NO_GRID_SIZE)); setActions(actions.toArray(new RadioAction[5])); return true; } @Override public boolean isEnabled() { return false; } private int getNumOfManifestationsOfTargetGridSize( Collection<CanvasManifestation> selectedManifestations, int targetGridSize) { int numOfCanvasManifestations = 0; int numOfTargetGridSize = 0; for (CanvasManifestation viewManifestation : selectedManifestations) { numOfCanvasManifestations++; int gridSize = viewManifestation.getGridSize(); if (gridSize == targetGridSize) { numOfTargetGridSize++; } } return numOfCanvasManifestations - numOfTargetGridSize; } private Collection<CanvasManifestation> getCanvasManifestations( Collection<View> selectedManifestations) { List<CanvasManifestation> selectedCanvasManifestations = new LinkedList<CanvasManifestation>(); for (View viewManifestation : selectedManifestations) { if (viewManifestation instanceof CanvasManifestation) { selectedCanvasManifestations.add((CanvasManifestation) viewManifestation); } } return selectedCanvasManifestations; } private class ChangeAction extends GroupAction.RadioAction { private static final long serialVersionUID = 1710587599649997202L; private Collection<CanvasManifestation> selectedManifestations; private int isFixedOrSelected; private int gridSize; public ChangeAction(ActionContext context, String gridText, int gridSize) { putValue(ChangeAction.NAME, gridText); this.gridSize = gridSize; selectedManifestations = getCanvasManifestations(getSelectedManifestations(context)); isFixedOrSelected = getNumOfManifestationsOfTargetGridSize(selectedManifestations, gridSize); } @Override public boolean isSelected() { return isFixedOrSelected == 0; } @Override public boolean isMixed() { return selectedManifestations.size() > 1 && isFixedOrSelected != 0 && isFixedOrSelected != selectedManifestations.size(); } @Override public void actionPerformed(ActionEvent e) { for (CanvasManifestation manifestation : selectedManifestations) { manifestation.enableGrid(gridSize); } } @Override public boolean isEnabled() { return true; } } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_ChangeGridSizeAction.java
233
private class ChangeAction extends GroupAction.RadioAction { private static final long serialVersionUID = 1710587599649997202L; private Collection<CanvasManifestation> selectedManifestations; private int isFixedOrSelected; private int gridSize; public ChangeAction(ActionContext context, String gridText, int gridSize) { putValue(ChangeAction.NAME, gridText); this.gridSize = gridSize; selectedManifestations = getCanvasManifestations(getSelectedManifestations(context)); isFixedOrSelected = getNumOfManifestationsOfTargetGridSize(selectedManifestations, gridSize); } @Override public boolean isSelected() { return isFixedOrSelected == 0; } @Override public boolean isMixed() { return selectedManifestations.size() > 1 && isFixedOrSelected != 0 && isFixedOrSelected != selectedManifestations.size(); } @Override public void actionPerformed(ActionEvent e) { for (CanvasManifestation manifestation : selectedManifestations) { manifestation.enableGrid(gridSize); } } @Override public boolean isEnabled() { return true; } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_ChangeGridSizeAction.java
234
public class ChangeSnapAction extends ContextAwareAction { private static final long serialVersionUID = -5917294719128741636L; private static ResourceBundle bundle = ResourceBundle.getBundle("CanvasResourceBundle"); private Collection<CanvasManifestation> selectedManifestations; public ChangeSnapAction() { super(bundle.getString("Snap_to_Grid")); } @Override public void actionPerformed(ActionEvent e) { Object selectedKey = getValue(Action.SELECTED_KEY); boolean state = selectedKey == null || ((Boolean)selectedKey).booleanValue(); for (CanvasManifestation manifestation : selectedManifestations) { manifestation.enableSnap(state); } } private Boolean getState() { Boolean state = selectedManifestations.iterator().next().isSnapEnable(); for (CanvasManifestation manifestation: selectedManifestations) { if (manifestation.isSnapEnable() != state.booleanValue()) { return null; } } return state; } @Override public boolean canHandle(ActionContext actionContext) { selectedManifestations = getCanvasManifestations(getSelectedManifestations(actionContext)); if (!selectedManifestations.isEmpty()) { Boolean state = getState(); putValue(Action.SELECTED_KEY, state); } return !selectedManifestations.isEmpty(); } protected Collection<View> getSelectedManifestations(ActionContext context) { return context.getSelectedManifestations(); } @Override public boolean isEnabled() { for (CanvasManifestation manifestation : selectedManifestations) { if (manifestation.getGridSize() != ControlAreaFormattingConstants.NO_GRID_SIZE) { return true; } } return false; } private Collection<CanvasManifestation> getCanvasManifestations( Collection<View> selectedManifestations) { List<CanvasManifestation> selectedCanvasManifestations = new LinkedList<CanvasManifestation>(); for (View viewManifestation : selectedManifestations) { if (viewManifestation instanceof CanvasManifestation) { selectedCanvasManifestations.add((CanvasManifestation) viewManifestation); } } return selectedCanvasManifestations; } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_ChangeSnapAction.java
235
public class MarqueSelectionListener extends MouseInputAdapter { private JPanel selection; private int clickX, clickY; private final JComponent rootPanel; private boolean dragStart=false; private final MultipleSelectionProvider selectionProvider; public MarqueSelectionListener(JComponent panel, MultipleSelectionProvider provider) { rootPanel = panel; selectionProvider = provider; } public interface MultipleSelectionProvider { /** * Select the set of panels * @param selection of panels */ public void selectPanels(Collection<Panel> selection); /** * Determines if the point is in the top selection scope. * @param point in screen coordinates */ public boolean pointInTopLevelPanel(Point p); } /** * Returns true if the drag action should not trigger marque selection. Move and resize are * currently delegated to the panel if they are active. * @param c container for the event */ private boolean isInOverridingAction(Container c) { int cursorType = c.getCursor().getType(); return cursorType == Cursor.MOVE_CURSOR || cursorType == Cursor.N_RESIZE_CURSOR || cursorType == Cursor.NE_RESIZE_CURSOR || cursorType == Cursor.NW_RESIZE_CURSOR || cursorType == Cursor.S_RESIZE_CURSOR || cursorType == Cursor.SE_RESIZE_CURSOR || cursorType == Cursor.SW_RESIZE_CURSOR || cursorType == Cursor.E_RESIZE_CURSOR || cursorType == Cursor.W_RESIZE_CURSOR; } @Override public void mouseDragged(MouseEvent e) { if (selection == null) { // this method is invoked during each drag event, so dragStart tracks the start of the drag event if (!dragStart) { // check the cursor to see if the user is currently in a move or resize mode // also verify whether the selected point is directly in the top level panel. This // should prevent nested selections from triggering selections at the top level. Container c = (Container) e.getSource(); if (!isInOverridingAction(c) && selectionProvider.pointInTopLevelPanel(e.getLocationOnScreen())) { selection = createSelection(); clickX = e.getX(); clickY = e.getY(); selection.setBounds(clickX, clickY, 1, 1); rootPanel.add(selection); rootPanel.setComponentZOrder(selection, 0); } } } else { int mouseX = e.getX(); int mouseY = e.getY(); if (mouseX >= clickX) { if (mouseY >= clickY) { // existing upper left point is unchanged, so just adjust // the height, width selection.setBounds(clickX, clickY, mouseX - clickX, mouseY - clickY); } else { // original click is now the lower left point int width = mouseX - clickX; selection.setBounds(mouseX - width, mouseY, width, clickY - mouseY); } } else { if (mouseY >= clickY) { // original click is now the upper right point selection.setBounds(mouseX, clickY, clickX - mouseX, mouseY - clickY); } else { // original click is now the lower right point selection.setBounds(mouseX, mouseY, clickX - mouseX, clickY - mouseY); } } } dragStart = true; } @Override public void mouseReleased(MouseEvent e) { dragStart = false; if (selection != null) { rootPanel.remove(selection); // figure out what components are selected if any List<Component> selectedComponents = new ArrayList<Component>(); Rectangle selectedRegion = selection.getBounds(); for (Component c : rootPanel.getComponents()) { if (selectedRegion.intersects(c.getBounds())) { selectedComponents.add(c); } } List<Panel> selectedPanels = new ArrayList<Panel>(selectedComponents.size()); for (Component selected : selectedComponents) { selectedPanels.add((Panel)selected); } selectionProvider.selectPanels(selectedPanels); } selection = null; } private JPanel createSelection() { JPanel p = new JPanel(); p.setBorder(BorderFactory.createLineBorder(Color.gray, 5)); p.setOpaque(false); p.setBackground(null); return p; } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_MarqueSelectionListener.java
236
public interface MultipleSelectionProvider { /** * Select the set of panels * @param selection of panels */ public void selectPanels(Collection<Panel> selection); /** * Determines if the point is in the top selection scope. * @param point in screen coordinates */ public boolean pointInTopLevelPanel(Point p); }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_MarqueSelectionListener.java
237
public class MarqueSelectionListenerTest { @Mock MultipleSelectionProvider mockSelectionProvider; private JPanel rootPanel; private MarqueSelectionListener listener; @BeforeMethod public void setup() { MockitoAnnotations.initMocks(this); rootPanel = new JPanel(); listener = new MarqueSelectionListener(rootPanel, mockSelectionProvider); } @DataProvider(name="mouseDataWithCursor") public Object[][] getData() { int[] cursors = new int[] { Cursor.MOVE_CURSOR, Cursor.N_RESIZE_CURSOR, Cursor.NE_RESIZE_CURSOR, Cursor.NW_RESIZE_CURSOR, Cursor.S_RESIZE_CURSOR , Cursor.SE_RESIZE_CURSOR, Cursor.SW_RESIZE_CURSOR, Cursor.E_RESIZE_CURSOR, Cursor.W_RESIZE_CURSOR }; Object[][] parameters = new Object[cursors.length][]; for (int i = 0; i < cursors.length; i++) { JPanel panel = new JPanel(); panel.setCursor(Cursor.getPredefinedCursor(cursors[i])); parameters[i] = new Object[] { new MouseEvent(panel,123,System.currentTimeMillis(),0,2,2,1,false) }; } return parameters; } @Test(dataProvider="mouseDataWithCursor") /** * ensure mouse dragged will not start a drag sequence if the state is not appropriate. This can be caused * because of the mouse cursor (another gesture is already active, resizing for example). */ public void testMouseDraggedStartCursorMove(MouseEvent e) { Mockito.when(mockSelectionProvider.pointInTopLevelPanel((Point)Mockito.anyObject())).thenReturn(true); listener.mouseDragged(e); Assert.assertEquals(rootPanel.getComponents().length, 0, "marquee selection should not be added because cursor indicates move or resize event" ); } @Test /** * ensure mouse dragging with a point inside the container does not start a selection. The mouse movement * in this case should be delegated back into the owning component and not start a marquee selection. */ public void testMouseDraggedInsideAComponent() { JPanel panel = new JPanel(); panel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); MouseEvent e = new MouseEvent(panel,123,System.currentTimeMillis(),0,2,2,1,false); Mockito.when(mockSelectionProvider.pointInTopLevelPanel((Point)Mockito.anyObject())).thenReturn(false); listener.mouseDragged(e); Assert.assertEquals(rootPanel.getComponents().length, 0, "marquee selection should not be added the starting mouse event is inside an enclosing panel" ); } @DataProvider(name="mouseDraggingDirections") public Object[][] getMouseData() { return new Object[][] { new Object[] {new Rectangle(2,2,1,1), new Point(3,3)}, new Object[] {new Rectangle(1,1,1,1), new Point(1,1)}, new Object[] {new Rectangle(2,1,1,1), new Point(3,1)}, new Object[] {new Rectangle(1,2,1,1), new Point(1,3)} }; } @Test(dataProvider="mouseDraggingDirections") public void testMouseDraggedStart(Rectangle expectedBounds, Point mouseClicked) { JPanel panel = new JPanel(); panel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); MouseEvent e = new MouseEvent(panel,123,System.currentTimeMillis(),0,2,2,1,false); Mockito.when(mockSelectionProvider.pointInTopLevelPanel((Point)Mockito.anyObject())).thenReturn(true); listener.mouseDragged(e); Assert.assertEquals(rootPanel.getComponents().length, 1, "marquee selection should have been started" ); // now drag the mouse and check the selection is adjusted correctly e = new MouseEvent(panel,1234,System.currentTimeMillis(),0,mouseClicked.x,mouseClicked.y,1,false); listener.mouseDragged(e); Assert.assertEquals(rootPanel.getComponents()[0].getBounds(),expectedBounds); } @SuppressWarnings("unchecked") @Test public void testMouseDragIncremental() { JPanel panel = new JPanel(); Panel child = Mockito.mock(Panel.class); Mockito.when(child.getBounds()).thenReturn(new Rectangle(2,2,1,1)); rootPanel.add(child); MouseEvent e = new MouseEvent(panel,123,System.currentTimeMillis(),0,2,2,1,false); Mockito.when(mockSelectionProvider.pointInTopLevelPanel((Point)Mockito.anyObject())).thenReturn(true); listener.mouseDragged(e); listener.mouseReleased(e); Mockito.verify(mockSelectionProvider).selectPanels((Collection<Panel>)Mockito.anyObject()); } }
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_MarqueSelectionListenerTest.java
238
public class PanelBorderSelectionTest { @Mock private AbstractComponent mockComponent; private Robot robot; private static final String TITLE = "Panel Border Selection Test"; private static final int PANEL_SIZE = 100; private JFrame frame; private Panel testPanel; private CanvasManifestation canvasManifestation = null; private View panelManifestation = null; private MCTViewManifestationInfo manifestationInfo; @Mock Platform mockPlatform; @Mock PolicyManager mockPolicyManager; ExecutionResult lockedResult = new ExecutionResult(null, true, null); ExecutionResult unlockedResult = new ExecutionResult(null, false, null); Platform oldPlatform; @BeforeClass public void setupClass() { oldPlatform = PlatformAccess.getPlatform(); } @AfterClass public void teardownClass() { new PlatformAccess().setPlatform(oldPlatform); } @BeforeMethod public void setup() { MockitoAnnotations.initMocks(this); new PlatformAccess().setPlatform(mockPlatform); robot = BasicRobot.robotWithCurrentAwtHierarchy(); manifestationInfo = new MCTViewManifestationInfoImpl(); manifestationInfo.addInfoProperty(ControlAreaFormattingConstants.PANEL_ORDER,"0"); Mockito.when(mockComponent.getViewInfos(ViewType.TITLE)).thenReturn(Collections.singleton(new ViewInfo(MockTitleManifestation.class,"", ViewType.TITLE))); Mockito.when(mockComponent.getDisplayName()).thenReturn("test comp"); Mockito.when(mockComponent.getComponents()).thenReturn( Collections.<AbstractComponent> emptyList()); Mockito.when(mockPlatform.getPolicyManager()) .thenReturn(mockPolicyManager); Mockito.when(mockPolicyManager.execute(Mockito.anyString(), Mockito.<PolicyContext> any())) .thenReturn(new ExecutionResult(null, false, null)); // Nothing is locked GuiActionRunner.execute(new GuiTask() { @SuppressWarnings("serial") @Override protected void executeInEDT() throws Throwable { frame = new JFrame(TITLE); frame.setName(TITLE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final ExtendedProperties viewProps = new ExtendedProperties(); canvasManifestation = new TestCanvasManifestation(mockComponent, new ViewInfo(CanvasManifestation.class, "", ViewType.CENTER)) { @Override public ExtendedProperties getViewProperties() { return viewProps; } }; canvasManifestation.setPreferredSize(new Dimension(PANEL_SIZE * 3, PANEL_SIZE * 3)); frame.getContentPane().add(canvasManifestation); frame.setLocation(PANEL_SIZE, PANEL_SIZE); frame.getContentPane().setSize(new Dimension(PANEL_SIZE * 3, PANEL_SIZE * 3)); frame.setSize(new Dimension(PANEL_SIZE * 3, PANEL_SIZE * 3)); panelManifestation = new MockManifestation(mockComponent, new ViewInfo(CanvasManifestation.class, "", ViewType.OBJECT)); MCTViewManifestationInfoImpl info = new MCTViewManifestationInfoImpl(); panelManifestation.putClientProperty(CanvasManifestation.MANIFEST_INFO, info); testPanel = canvasManifestation.createPanel(panelManifestation, 0, canvasManifestation); Assert.assertNotNull(CanvasManifestation.getManifestationInfo(testPanel.getWrappedManifestation())); canvasManifestation.getViewProperties().addProperty(CanvasManifestation.CANVAS_CONTENT_PROPERTY, info); canvasManifestation.fireSelectionCloned(Collections.singleton(testPanel)); testPanel.setSize(PANEL_SIZE, PANEL_SIZE); testPanel.setPreferredSize(new Dimension(PANEL_SIZE, PANEL_SIZE)); testPanel.setLocation(PANEL_SIZE, PANEL_SIZE); frame.pack(); frame.setVisible(true); } }); } @AfterMethod public void tearDown() { robot.cleanUp(); } @Test public void testFullSize() { testPanel.setPreferredSize(new Dimension(PANEL_SIZE, PANEL_SIZE)); testPanel.getWrappedManifestation().setPreferredSize(new Dimension(PANEL_SIZE / 2, PANEL_SIZE / 2)); canvasManifestation.revalidate(); clickBorders(); } @Test public void testWithScrolls() { testPanel.getWrappedManifestation().setPreferredSize(new Dimension(PANEL_SIZE * 2, PANEL_SIZE * 2)); canvasManifestation.revalidate(); clickBorders(); } @Test public void testDeselectClearsFocus() { JTextField focusField = new JTextField(); testPanel.getWrappedManifestation().add(focusField); testPanel.revalidate(); focusField.requestFocusInWindow(); robot.click(focusField); Assert.assertTrue(focusField.hasFocus()); Point p = testPanel.getLocationOnScreen(); robot.click(p, MouseButton.LEFT_BUTTON, 1); p.translate(-PANEL_SIZE / 2, -PANEL_SIZE / 2); robot.click(p, MouseButton.LEFT_BUTTON, 1); Assert.assertFalse(focusField.hasFocus()); } @Test public void testCornerDragging() { BreakableMouseDragListener listener = new BreakableMouseDragListener(); // This listener will throw runtime exceptions if drag events are received... // ...without preceding press events panelManifestation.addMouseListener(listener); panelManifestation.addMouseMotionListener(listener); Point p = testPanel.getLocationOnScreen(); p.translate(testPanel.getWidth() - 1, testPanel.getHeight() - 1); robot.click(p, MouseButton.LEFT_BUTTON, 1); // Should select robot.waitForIdle(); Assert.assertTrue(canvasManifestation.getSelectedManifestations().size() > 0); Assert.assertFalse(listener.expectsDragEvent); p.translate(-20, -20); robot.moveMouse(p); robot.pressMouse(MouseButton.LEFT_BUTTON); robot.releaseMouse(MouseButton.LEFT_BUTTON); p.translate(22, 22); // To bottom-right resizer robot.moveMouse(p); for (int i = 0; i < 10; i++) robot.moveMouse(p); robot.pressMouse(MouseButton.LEFT_BUTTON); for (int i = 0; i < 5; i++) { p.translate(-4, -4); robot.moveMouse(p); } robot.releaseMouseButtons(); robot.waitForIdle(); Assert.assertFalse(listener.receivedUnexpectedDragEvent); } public void clickBorders() { for (double x = 0; x <= 1.0; x += 0.5) { for (double y = 0; y <= 1.0; y += 0.5) { int dx = (int) (x * (double) (PANEL_SIZE - 1)); int dy = (int) (y * (double) (PANEL_SIZE - 1)); // Click on the canvas - clear selections Point p = canvasManifestation.getLocationOnScreen(); p.translate(PANEL_SIZE / 2, PANEL_SIZE / 2); robot.click(p, MouseButton.LEFT_BUTTON, 1); robot.waitForIdle(); Assert.assertTrue(canvasManifestation.getSelectedManifestations().size() == 0); // Click on the border (or center) p = testPanel.getLocationOnScreen(); p.translate(dx, dy); robot.click(p, MouseButton.LEFT_BUTTON, 1); robot.waitForIdle(); // We should only be selected if we're on the border if (x * y * (1.0 - x) * (1.0 - y) == 0.0) { Assert.assertTrue(canvasManifestation.getSelectedManifestations().size() > 0); } else { Assert.assertTrue(canvasManifestation.getSelectedManifestations().size() == 0); } } } } @SuppressWarnings("serial") private static class TestCanvasManifestation extends CanvasManifestation { @Override public void fireFocusPersist() { } public TestCanvasManifestation(AbstractComponent component, ViewInfo vi) { super(component, vi); } } @SuppressWarnings("serial") public static class MockTitleManifestation extends View { public MockTitleManifestation(AbstractComponent component, ViewInfo vi) { super(component,vi); this.setBackground(Color.RED); } } @SuppressWarnings("serial") public static class MockManifestation extends View { public MockManifestation(AbstractComponent component, ViewInfo vi) { super(component,vi); this.setBackground(Color.GREEN); } } private class BreakableMouseDragListener implements MouseMotionListener, MouseListener { private boolean expectsDragEvent = false; private boolean receivedUnexpectedDragEvent = false; @Override public void mouseDragged(MouseEvent arg0) { receivedUnexpectedDragEvent = true; } @Override public void mouseMoved(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { expectsDragEvent = true; } @Override public void mouseReleased(MouseEvent arg0) { expectsDragEvent = false; } } }
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_PanelBorderSelectionTest.java
239
GuiActionRunner.execute(new GuiTask() { @SuppressWarnings("serial") @Override protected void executeInEDT() throws Throwable { frame = new JFrame(TITLE); frame.setName(TITLE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final ExtendedProperties viewProps = new ExtendedProperties(); canvasManifestation = new TestCanvasManifestation(mockComponent, new ViewInfo(CanvasManifestation.class, "", ViewType.CENTER)) { @Override public ExtendedProperties getViewProperties() { return viewProps; } }; canvasManifestation.setPreferredSize(new Dimension(PANEL_SIZE * 3, PANEL_SIZE * 3)); frame.getContentPane().add(canvasManifestation); frame.setLocation(PANEL_SIZE, PANEL_SIZE); frame.getContentPane().setSize(new Dimension(PANEL_SIZE * 3, PANEL_SIZE * 3)); frame.setSize(new Dimension(PANEL_SIZE * 3, PANEL_SIZE * 3)); panelManifestation = new MockManifestation(mockComponent, new ViewInfo(CanvasManifestation.class, "", ViewType.OBJECT)); MCTViewManifestationInfoImpl info = new MCTViewManifestationInfoImpl(); panelManifestation.putClientProperty(CanvasManifestation.MANIFEST_INFO, info); testPanel = canvasManifestation.createPanel(panelManifestation, 0, canvasManifestation); Assert.assertNotNull(CanvasManifestation.getManifestationInfo(testPanel.getWrappedManifestation())); canvasManifestation.getViewProperties().addProperty(CanvasManifestation.CANVAS_CONTENT_PROPERTY, info); canvasManifestation.fireSelectionCloned(Collections.singleton(testPanel)); testPanel.setSize(PANEL_SIZE, PANEL_SIZE); testPanel.setPreferredSize(new Dimension(PANEL_SIZE, PANEL_SIZE)); testPanel.setLocation(PANEL_SIZE, PANEL_SIZE); frame.pack(); frame.setVisible(true); } });
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_PanelBorderSelectionTest.java
240
canvasManifestation = new TestCanvasManifestation(mockComponent, new ViewInfo(CanvasManifestation.class, "", ViewType.CENTER)) { @Override public ExtendedProperties getViewProperties() { return viewProps; } };
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_PanelBorderSelectionTest.java
241
private class BreakableMouseDragListener implements MouseMotionListener, MouseListener { private boolean expectsDragEvent = false; private boolean receivedUnexpectedDragEvent = false; @Override public void mouseDragged(MouseEvent arg0) { receivedUnexpectedDragEvent = true; } @Override public void mouseMoved(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { expectsDragEvent = true; } @Override public void mouseReleased(MouseEvent arg0) { expectsDragEvent = false; } }
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_PanelBorderSelectionTest.java
242
@SuppressWarnings("serial") public static class MockManifestation extends View { public MockManifestation(AbstractComponent component, ViewInfo vi) { super(component,vi); this.setBackground(Color.GREEN); } }
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_PanelBorderSelectionTest.java
243
@SuppressWarnings("serial") public static class MockTitleManifestation extends View { public MockTitleManifestation(AbstractComponent component, ViewInfo vi) { super(component,vi); this.setBackground(Color.RED); } }
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_PanelBorderSelectionTest.java
244
@SuppressWarnings("serial") private static class TestCanvasManifestation extends CanvasManifestation { @Override public void fireFocusPersist() { } public TestCanvasManifestation(AbstractComponent component, ViewInfo vi) { super(component, vi); } }
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_PanelBorderSelectionTest.java
245
public interface PanelFocusSelectionProvider { public void fireFocusSelection(Panel panel); public void fireManifestationChanged(); public void fireFocusPersist(); public void fireOrderChange(Panel panel, PANEL_ZORDER order); public void fireSelectionRemoved(Panel panel); public void fireSelectionCloned(Collection<Panel> panels); }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_PanelFocusSelectionProvider.java
246
class PanelFocusTraversalPolicy extends SortingFocusTraversalPolicy implements PropertyChangeListener { public static final String FOCUS_SELECTION_CHANGE_PROP = "FOCUS_SELECTION_CHANGE_PROP"; private Set<Panel> visitedPanels = new LinkedHashSet<Panel>(); private LinkedList<Panel> orderedListPanels = new LinkedList<Panel>(); public PanelFocusTraversalPolicy(Map<Integer, Panel> renderedPanels) { addToOrderedList(renderedPanels); } private void addToOrderedList(Map<Integer, Panel> panelMap) { LinkedList<Integer> keyList = new LinkedList<Integer>(panelMap.keySet()); Collections.sort(keyList); for (Integer key : keyList) { Panel panel = panelMap.get(key); orderedListPanels.add(panel); } } @Override public Component getLastComponent(Container aContainer) { Panel panel = orderedListPanels.getLast(); visitedPanels.add(panel); return panel; } @Override public Component getFirstComponent(Container aContainer) { Panel panel = orderedListPanels.getFirst(); visitedPanels.add(panel); return panel; } @Override public Component getDefaultComponent(Container aContainer) { if (visitedPanels.size() == orderedListPanels.size()) { if (aContainer instanceof SelectionProvider) { ((SelectionProvider) aContainer).clearCurrentSelections(); restartFocusTraversalCycle(); } KeyboardFocusManager.getCurrentKeyboardFocusManager().upFocusCycle(aContainer); return KeyboardFocusManager.getCurrentKeyboardFocusManager().getCurrentFocusCycleRoot(); } return getFirstComponent(aContainer); } @Override public Component getComponentBefore(Container aContainer, Component aComponent) { if (!orderedListPanels.contains(aComponent)) return getDefaultComponent(aContainer); int index = orderedListPanels.indexOf(aComponent); if (index == 0) { KeyboardFocusManager.getCurrentKeyboardFocusManager().upFocusCycle(aContainer); return KeyboardFocusManager.getCurrentKeyboardFocusManager().getCurrentFocusCycleRoot(); } else { Panel panel = orderedListPanels.get(index - 1); View wrappedManifestation = panel.getWrappedManifestation(); if (wrappedManifestation.isFocusTraversalPolicyProvider()) { FocusTraversalPolicy focusTraversalPolicy = wrappedManifestation.getFocusTraversalPolicy(); return focusTraversalPolicy.getLastComponent(wrappedManifestation); } visitedPanels.add(panel); return panel; } } @Override public Component getComponentAfter(Container aContainer, Component aComponent) { if (!orderedListPanels.contains(aComponent)) return getDefaultComponent(aContainer); if (aComponent instanceof Panel) { View wrappedManifestation = ((Panel) aComponent).getWrappedManifestation(); if (wrappedManifestation.isFocusTraversalPolicyProvider()) { FocusTraversalPolicy focusTraversalPolicy = wrappedManifestation.getFocusTraversalPolicy(); if (focusTraversalPolicy instanceof PanelFocusTraversalPolicy) { if (!((PanelFocusTraversalPolicy) focusTraversalPolicy).finishedTraversalCycle()) { return focusTraversalPolicy.getDefaultComponent(aContainer); } } } } int lastIndex = orderedListPanels.size() - 1; int index = orderedListPanels.indexOf(aComponent); if (index == lastIndex) { KeyboardFocusManager.getCurrentKeyboardFocusManager().upFocusCycle(aContainer); return KeyboardFocusManager.getCurrentKeyboardFocusManager().getCurrentFocusCycleRoot(); } else { Panel panel = orderedListPanels.get(index + 1); visitedPanels.add(panel); return panel; } } @SuppressWarnings("unchecked") @Override public void propertyChange(PropertyChangeEvent evt) { restartFocusTraversalCycle(); orderedListPanels.clear(); addToOrderedList((Map<Integer, Panel>) evt.getNewValue()); } private void restartFocusTraversalCycle() { for (Panel panel : orderedListPanels) { View wrappedManifestation = panel.getWrappedManifestation(); if (wrappedManifestation.isFocusTraversalPolicyProvider()) { FocusTraversalPolicy focusTraversalPolicy = wrappedManifestation.getFocusTraversalPolicy(); if (focusTraversalPolicy instanceof PanelFocusTraversalPolicy) ((PanelFocusTraversalPolicy) focusTraversalPolicy).restartFocusTraversalCycle(); } } visitedPanels.clear(); } private boolean finishedTraversalCycle() { return visitedPanels.size() == orderedListPanels.size(); } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_PanelFocusTraversalPolicy.java
247
public class PanelFocusTraversalPolicyTest { private PanelFocusTraversalPolicy policy; private Map<Integer, Panel> renderedPanels; @BeforeClass public void setup() { renderedPanels = new HashMap<Integer, Panel>(); } @Test public void testSinglePanel() { MockProvider provider = new MockProvider(); int panelId = 0; Panel panel = Mockito.mock(Panel.class); MockManifestation manifestation = new MockManifestation(); Mockito.when(panel.getPanelFocusSelectionProvider()).thenReturn(provider); Mockito.when(panel.getWrappedManifestation()).thenReturn(manifestation); renderedPanels.put(Integer.valueOf(panelId), panel); policy = new PanelFocusTraversalPolicy(renderedPanels); Assert.assertSame(policy.getDefaultComponent(provider), panel); Assert.assertSame(policy.getFirstComponent(provider), panel); Assert.assertSame(policy.getLastComponent(provider), panel); Assert.assertNotSame(policy.getComponentBefore(provider, panel), panel); Assert.assertNotSame(policy.getComponentAfter(provider, panel), panel); } @SuppressWarnings("serial") private static class MockProvider extends Container implements PanelFocusSelectionProvider { @Override public void fireFocusPersist() { } @Override public void fireFocusSelection(Panel panel) { } @Override public void fireManifestationChanged() { } @Override public void fireOrderChange(Panel panel, PANEL_ZORDER order) { } @Override public void fireSelectionCloned(Collection<Panel> panels) { } @Override public void fireSelectionRemoved(Panel panel) { } } @SuppressWarnings("serial") private static class MockManifestation extends View { } }
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_PanelFocusTraversalPolicyTest.java
248
@SuppressWarnings("serial") private static class MockManifestation extends View { }
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_PanelFocusTraversalPolicyTest.java
249
@SuppressWarnings("serial") private static class MockProvider extends Container implements PanelFocusSelectionProvider { @Override public void fireFocusPersist() { } @Override public void fireFocusSelection(Panel panel) { } @Override public void fireManifestationChanged() { } @Override public void fireOrderChange(Panel panel, PANEL_ZORDER order) { } @Override public void fireSelectionCloned(Collection<Panel> panels) { } @Override public void fireSelectionRemoved(Panel panel) { } }
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_PanelFocusTraversalPolicyTest.java
250
@SuppressWarnings("serial") public class PanelInspector extends View { private static final Color BACKGROUND_COLOR = LafColor.WINDOW_BORDER.darker(); private static final Color FOREGROUND_COLOR = LafColor.WINDOW.brighter(); private static final ImageIcon BUTTON_ICON = new ImageIcon(PanelInspector.class.getResource("/images/infoViewButton-OFF.png")); private static final ImageIcon BUTTON_PRESSED_ICON = new ImageIcon(PanelInspector.class.getResource("/images/infoViewButton-ON.png")); private static final String PANEL_SPECIFIC = " (Panel-Specific)"; private static final String DASH = " - "; private final PropertyChangeListener selectionChangeListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { @SuppressWarnings("unchecked") Collection<View> selectedViews = (Collection<View>) evt.getNewValue(); selectedManifestationChanged(selectedViews.isEmpty() || selectedViews.size() > 1 ? null : selectedViews.iterator().next()); } }; private JLabel viewTitle = new JLabel(); private JLabel space = new JLabel(" "); private JPanel emptyPanel = new JPanel(); private JComponent content; private View view; private JComponent viewControls; private JPanel titlebar = new JPanel(); private JPanel viewButtonBar = new JPanel(); private GridBagConstraints c = new GridBagConstraints(); private ControllerTwistie controllerTwistie; public PanelInspector(AbstractComponent ac, ViewInfo vi) { super(ac,vi); registerSelectionChange(); setLayout(new BorderLayout()); titlebar.setLayout(new GridBagLayout()); JLabel titleLabel = new JLabel("Panel Inspector: "); c.insets = new Insets(0, 0, 0, 0); c.fill = GridBagConstraints.NONE; c.anchor = GridBagConstraints.LINE_START; c.weightx = 0; c.gridwidth = 1; titlebar.add(titleLabel, c); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1; titlebar.add(viewTitle, c); c.fill = GridBagConstraints.NONE; c.weightx = 0; titlebar.add(space); titleLabel.setForeground(FOREGROUND_COLOR); viewTitle.setForeground(FOREGROUND_COLOR); viewTitle.addMouseMotionListener(new WidgetDragger()); titlebar.setBackground(BACKGROUND_COLOR); viewButtonBar.setLayout(new FlowLayout(FlowLayout.RIGHT, 0, 0)); viewButtonBar.setBackground(BACKGROUND_COLOR); add(titlebar, BorderLayout.NORTH); add(emptyPanel, BorderLayout.CENTER); content = emptyPanel; setMinimumSize(new Dimension(0, 0)); } private ButtonGroup createViewSelectionButtons(AbstractComponent ac, ViewInfo selectedViewInfo) { ButtonGroup buttonGroup = new ButtonGroup(); final Set<ViewInfo> viewInfos = ac.getViewInfos(ViewType.EMBEDDED); for (ViewInfo vi : viewInfos) { ViewChoiceButton button = new ViewChoiceButton(vi); buttonGroup.add(button); viewButtonBar.add(button); if (vi.equals(selectedViewInfo)) buttonGroup.setSelected(button.getModel(), true); } return buttonGroup; } private void selectedManifestationChanged(View view) { remove(content); if (view == null) { viewTitle.setIcon(null); viewTitle.setText(""); viewTitle.setTransferHandler(null); content = emptyPanel; } else { viewTitle.setIcon(view.getManifestedComponent().getIcon()); viewTitle.setText(view.getManifestedComponent().getDisplayName() + DASH + view.getInfo().getViewName() + PANEL_SPECIFIC); viewTitle.setTransferHandler(new WidgetTransferHandler()); content = this.view = view.getInfo().createView(view.getManifestedComponent()); JComponent viewControls = getViewControls(); if (viewControls != null) { c.weightx = 0; controllerTwistie = new ControllerTwistie(); titlebar.add(controllerTwistie, c); } createViewSelectionButtons(view.getManifestedComponent(), view.getInfo()); c.anchor = GridBagConstraints.LINE_END; c.gridwidth = GridBagConstraints.REMAINDER; c.weightx = 0; titlebar.add(viewButtonBar, c); } Dimension preferredSize = content.getPreferredSize(); JScrollPane jp = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); preferredSize.height += jp.getHorizontalScrollBar().getPreferredSize().height; JScrollPane inspectorScrollPane = new JScrollPane(content, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); content = inspectorScrollPane; add(inspectorScrollPane, BorderLayout.CENTER); revalidate(); } private void registerSelectionChange() { // Register when the panel inspector is added to the window. addAncestorListener(new AncestorListener() { SelectionProvider selectionProvider; @Override public void ancestorAdded(AncestorEvent event) { selectionProvider = (SelectionProvider) event.getAncestorParent(); selectionProvider.addSelectionChangeListener(selectionChangeListener); } @Override public void ancestorMoved(AncestorEvent event) { } @Override public void ancestorRemoved(AncestorEvent event) { if (selectionProvider != null) { selectionProvider.removeSelectionChangeListener(selectionChangeListener); } } }); } private void showOrHideController(boolean toShow) { remove(content); JScrollPane scrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); scrollPane.setViewportView(view); if (toShow) { JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, getViewControls(), scrollPane); splitPane.setResizeWeight(.66); splitPane.setOneTouchExpandable(true); splitPane.setContinuousLayout(true); splitPane.setBorder(null); content = splitPane; // Overwrite lock state for the panel-specific view if (isLocked) view.exitLockedState(); else view.enterLockedState(); } else { content = scrollPane; } add(content, BorderLayout.CENTER); revalidate(); } protected JComponent getViewControls() { assert view != null; if (viewControls == null) viewControls = view.getControlManifestation(); return viewControls; } @Override public SelectionProvider getSelectionProvider() { return super.getSelectionProvider(); } private boolean isLocked = false; @Override public void enterLockedState() { isLocked = false; super.enterLockedState(); view.enterLockedState(); } @Override public void exitLockedState() { isLocked = true; super.exitLockedState(); if (view != null) view.exitLockedState(); } private static final class WidgetDragger extends MouseMotionAdapter { @Override public void mouseDragged(MouseEvent e) { JComponent c = (JComponent) e.getSource(); TransferHandler th = c.getTransferHandler(); th.exportAsDrag(c, e, TransferHandler.COPY); } } private final class WidgetTransferHandler extends TransferHandler { @Override public int getSourceActions(JComponent c) { return COPY; } @Override protected Transferable createTransferable(JComponent c) { if (view != null) { return new ViewRoleSelection(new View[] { view}); } else { return null; } } } private final class ViewChoiceButton extends JToggleButton { private static final String SWITCH_TO = "Switch to "; public ViewChoiceButton(final ViewInfo viewInfo) { setBorder(BorderFactory.createEmptyBorder()); setAction(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { PanelInspector.this.remove(content); content = view = viewInfo.createView(view.getManifestedComponent()); Dimension preferredSize = content.getPreferredSize(); JScrollPane jp = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); preferredSize.height += jp.getHorizontalScrollBar().getPreferredSize().height; JScrollPane inspectorScrollPane = new JScrollPane(content, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); PanelInspector.this.add(inspectorScrollPane, BorderLayout.CENTER); PanelInspector.this.revalidate(); content = inspectorScrollPane; viewTitle.setText(view.getManifestedComponent().getDisplayName() + DASH + view.getInfo().getViewName() + PANEL_SPECIFIC); viewControls = null; if (controllerTwistie != null) controllerTwistie.changeState(false); } }); setIcon(viewInfo.getIcon() == null ? BUTTON_ICON : viewInfo.getIcon()); setPressedIcon(viewInfo.getIcon() == null ? BUTTON_ICON : viewInfo.getIcon()); setSelectedIcon(viewInfo.getSelectedIcon() == null ? BUTTON_PRESSED_ICON : viewInfo.getSelectedIcon()); setToolTipText(SWITCH_TO + viewInfo.getViewName() + PANEL_SPECIFIC); } } private final class ControllerTwistie extends Twistie { public ControllerTwistie() { super(); } @Override protected void changeStateAction(boolean state) { showOrHideController(state); } } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_PanelInspector.java
251
private final PropertyChangeListener selectionChangeListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { @SuppressWarnings("unchecked") Collection<View> selectedViews = (Collection<View>) evt.getNewValue(); selectedManifestationChanged(selectedViews.isEmpty() || selectedViews.size() > 1 ? null : selectedViews.iterator().next()); } };
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_PanelInspector.java
252
addAncestorListener(new AncestorListener() { SelectionProvider selectionProvider; @Override public void ancestorAdded(AncestorEvent event) { selectionProvider = (SelectionProvider) event.getAncestorParent(); selectionProvider.addSelectionChangeListener(selectionChangeListener); } @Override public void ancestorMoved(AncestorEvent event) { } @Override public void ancestorRemoved(AncestorEvent event) { if (selectionProvider != null) { selectionProvider.removeSelectionChangeListener(selectionChangeListener); } } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_PanelInspector.java
253
private final class ControllerTwistie extends Twistie { public ControllerTwistie() { super(); } @Override protected void changeStateAction(boolean state) { showOrHideController(state); } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_PanelInspector.java
254
private final class ViewChoiceButton extends JToggleButton { private static final String SWITCH_TO = "Switch to "; public ViewChoiceButton(final ViewInfo viewInfo) { setBorder(BorderFactory.createEmptyBorder()); setAction(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { PanelInspector.this.remove(content); content = view = viewInfo.createView(view.getManifestedComponent()); Dimension preferredSize = content.getPreferredSize(); JScrollPane jp = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); preferredSize.height += jp.getHorizontalScrollBar().getPreferredSize().height; JScrollPane inspectorScrollPane = new JScrollPane(content, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); PanelInspector.this.add(inspectorScrollPane, BorderLayout.CENTER); PanelInspector.this.revalidate(); content = inspectorScrollPane; viewTitle.setText(view.getManifestedComponent().getDisplayName() + DASH + view.getInfo().getViewName() + PANEL_SPECIFIC); viewControls = null; if (controllerTwistie != null) controllerTwistie.changeState(false); } }); setIcon(viewInfo.getIcon() == null ? BUTTON_ICON : viewInfo.getIcon()); setPressedIcon(viewInfo.getIcon() == null ? BUTTON_ICON : viewInfo.getIcon()); setSelectedIcon(viewInfo.getSelectedIcon() == null ? BUTTON_PRESSED_ICON : viewInfo.getSelectedIcon()); setToolTipText(SWITCH_TO + viewInfo.getViewName() + PANEL_SPECIFIC); } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_PanelInspector.java
255
setAction(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { PanelInspector.this.remove(content); content = view = viewInfo.createView(view.getManifestedComponent()); Dimension preferredSize = content.getPreferredSize(); JScrollPane jp = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); preferredSize.height += jp.getHorizontalScrollBar().getPreferredSize().height; JScrollPane inspectorScrollPane = new JScrollPane(content, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); PanelInspector.this.add(inspectorScrollPane, BorderLayout.CENTER); PanelInspector.this.revalidate(); content = inspectorScrollPane; viewTitle.setText(view.getManifestedComponent().getDisplayName() + DASH + view.getInfo().getViewName() + PANEL_SPECIFIC); viewControls = null; if (controllerTwistie != null) controllerTwistie.changeState(false); } });
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_PanelInspector.java
256
private static final class WidgetDragger extends MouseMotionAdapter { @Override public void mouseDragged(MouseEvent e) { JComponent c = (JComponent) e.getSource(); TransferHandler th = c.getTransferHandler(); th.exportAsDrag(c, e, TransferHandler.COPY); } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_PanelInspector.java
257
private final class WidgetTransferHandler extends TransferHandler { @Override public int getSourceActions(JComponent c) { return COPY; } @Override protected Transferable createTransferable(JComponent c) { if (view != null) { return new ViewRoleSelection(new View[] { view}); } else { return null; } } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_PanelInspector.java
258
public final class PanelInspectorTest { private PanelInspector panelInspector; @Mock private View view; Method showHideControllerMethod; @SuppressWarnings("serial") @BeforeClass public void setup() { MockitoAnnotations.initMocks(this); AbstractComponent ac = Mockito.mock(AbstractComponent.class); ViewInfo vi = Mockito.mock(ViewInfo.class); panelInspector = new PanelInspector(ac, vi) { @Override protected JComponent getViewControls() { return new JPanel(); } }; try { // set content field Field cf = PanelInspector.class.getDeclaredField("content"); cf.setAccessible(true); cf.set(panelInspector, new JPanel()); // set view field Field vf = PanelInspector.class.getDeclaredField("view"); vf.setAccessible(true); vf.set(panelInspector, view); showHideControllerMethod = PanelInspector.class.getDeclaredMethod("showOrHideController", boolean.class); showHideControllerMethod.setAccessible(true); } catch (SecurityException e) { Assert.fail(e.getMessage(), e); } catch (NoSuchFieldException e) { Assert.fail(e.getMessage(), e); } catch (IllegalArgumentException e) { Assert.fail(e.getMessage(), e); } catch (IllegalAccessException e) { Assert.fail(e.getMessage(), e); } catch (NoSuchMethodException e) { Assert.fail(e.getMessage(), e); } } @Test public void testEnterLockedState() { try { // set canvas locked state (isLocked) to true Field cf = PanelInspector.class.getDeclaredField("isLocked"); cf.setAccessible(true); cf.set(panelInspector, Boolean.TRUE); showHideControllerMethod.invoke(panelInspector, true); Mockito.verify(view, Mockito.times(1)).exitLockedState(); } catch (SecurityException e) { Assert.fail(e.getMessage(), e); } catch (NoSuchFieldException e) { Assert.fail(e.getMessage(), e); } catch (IllegalArgumentException e) { Assert.fail(e.getMessage(), e); } catch (IllegalAccessException e) { Assert.fail(e.getMessage(), e); } catch (InvocationTargetException e) { Assert.fail(e.getMessage(), e); } } }
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_PanelInspectorTest.java
259
panelInspector = new PanelInspector(ac, vi) { @Override protected JComponent getViewControls() { return new JPanel(); } };
false
canvas_src_test_java_gov_nasa_arc_mct_canvas_view_PanelInspectorTest.java
260
public class ReTileAction extends ContextAwareAction { private static final long serialVersionUID = 5487339986221192656L; private static ResourceBundle bundle = ResourceBundle.getBundle("CanvasResourceBundle"); private Collection<CanvasManifestation> selectedManifestations; public ReTileAction() { super(bundle.getString("ReTile")); } @Override public void actionPerformed(ActionEvent e) { for (CanvasManifestation manifestation : selectedManifestations) { manifestation.retile(); manifestation.computePreferredSize(); manifestation.fireFocusPersist(); } } @Override public boolean canHandle(ActionContext actionContext) { selectedManifestations = getCanvasManifestations(getSelectedManifestations(actionContext)); return !selectedManifestations.isEmpty(); } @Override public boolean isEnabled() { for (CanvasManifestation canvasManifestation: selectedManifestations) { if (canvasManifestation.isLocked()) return false; } return true; } protected Collection<View> getSelectedManifestations(ActionContext actionContext) { return actionContext.getSelectedManifestations(); } private Collection<CanvasManifestation> getCanvasManifestations( Collection<View> selectedManifestations) { List<CanvasManifestation> selectedCanvasManifestations = new LinkedList<CanvasManifestation>(); for (View viewManifestation : selectedManifestations) { if (viewManifestation instanceof CanvasManifestation) { selectedCanvasManifestations.add((CanvasManifestation) viewManifestation); } } return selectedCanvasManifestations; } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_ReTileAction.java
261
public class WindowChangeGridSizeAction extends ChangeGridSizeAction { private static final long serialVersionUID = -5917294719128741636L; @Override protected Collection<View> getSelectedManifestations(ActionContext context) { return context.getRootManifestations(); } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_WindowChangeGridSizeAction.java
262
public class WindowChangeSnapAction extends ChangeSnapAction { private static final long serialVersionUID = -2895979247608627747L; @Override protected Collection<View> getSelectedManifestations(ActionContext actionContext) { return actionContext.getRootManifestations(); } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_WindowChangeSnapAction.java
263
public class WindowReTileAction extends ReTileAction { private static final long serialVersionUID = -6345815090369154387L; public WindowReTileAction() { super(); } @Override protected Collection<View> getSelectedManifestations(ActionContext actionContext) { return actionContext.getRootManifestations(); } }
false
canvas_src_main_java_gov_nasa_arc_mct_canvas_view_WindowReTileAction.java
264
public class CollectionComponentProvider extends AbstractComponentProvider { private static ResourceBundle bundle = ResourceBundle.getBundle("CollectionComponent"); private final ComponentTypeInfo componentTypeInfo; /** * Default constructor for a collection component object. */ public CollectionComponentProvider() { componentTypeInfo = new ComponentTypeInfo( bundle.getString("display_name"), bundle.getString("description"), CollectionComponent.class, true, new ImageIcon(CollectionComponent.class.getResource("/icons/Collection.png"))); } @Override public Collection<ComponentTypeInfo> getComponentTypes() { return Collections.singleton(componentTypeInfo); } @Override public Collection<ViewInfo> getViews(String componentTypeId) { return Collections.<ViewInfo>emptyList(); } }
false
collectionComponent_src_main_java_gov_nasa_arc_mct_collection_CollectionComponentProvider.java
265
public class ComponentRegistryAccess { private static AtomicReference<ComponentRegistry> registry = new AtomicReference<ComponentRegistry>(); // this is not a traditional singleton as this class is created by the OSGi declarative services mechanism. /** * Returns the component registry instance. This will not return null as the cardinality of * the component specified through the OSGi components services is 1. * @return a component registry service instance */ public static ComponentRegistry getComponentRegistry() { return registry.get(); } /** * set the active instance of the <code>ComponentRegistry</code>. This method is invoked by * OSGi (see the OSGI-INF/component.xml file for additional details). * @param componentRegistry available in MCT */ public void setRegistry(ComponentRegistry componentRegistry) { registry.set(componentRegistry); } /** * release the active instance of the <code>ComponentRegistry</code>. This method is invoked by * OSGi (see the OSGI-INF/component.xml file for additional details). * @param componentRegistry to be released */ public void releaseRegistry(ComponentRegistry componentRegistry) { registry.set(null); } }
false
collectionComponent_src_main_java_gov_nasa_arc_mct_collection_access_ComponentRegistryAccess.java
266
public final class PolicyManagerAccess { private static AtomicReference<PolicyManager> manager = new AtomicReference<PolicyManager>(); /** * Sets the policy manager instance. * @param policyManager - The policy manager. */ public void setPolicyManager(PolicyManager policyManager) { manager.set(policyManager); } /** * Releases the policy manager and set as null. * @param policyManager - release this policy manager. */ public void releasePolicyManager(PolicyManager policyManager) { manager.set(null); } /** * Gets the policy manager. * @return PolicyManager. */ public static PolicyManager getPolicyManager() { return manager.get(); } }
false
collectionComponent_src_main_java_gov_nasa_arc_mct_collection_access_PolicyManagerAccess.java
267
public class MockComponent extends AbstractComponent { }
false
tests_src_main_java_gov_nasa_arc_mct_component_MockComponent.java
268
public class MockComponentProvider extends AbstractComponentProvider { private final Collection<PolicyInfo> policyInfos; private final Collection<MenuItemInfo> menuItemInfos; private final Collection<ComponentTypeInfo> componentTypeInfos; private final Collection<ViewInfo> viewInfos; public MockComponentProvider( Collection<PolicyInfo> policyInfos, Collection<MenuItemInfo> menuItemInfos, Collection<ComponentTypeInfo> componentTypeInfos, Collection<ViewInfo> viewInfos) { this.policyInfos = policyInfos; this.menuItemInfos = menuItemInfos; this.componentTypeInfos = componentTypeInfos; this.viewInfos = viewInfos; } @Override public Collection<ComponentTypeInfo> getComponentTypes() { return this.componentTypeInfos; } @Override public Collection<MenuItemInfo> getMenuItemInfos() { return this.menuItemInfos; } @Override public Collection<PolicyInfo> getPolicyInfos() { return this.policyInfos; } @Override public Collection<ViewInfo> getViews(String componentTypeId) { return viewInfos; } }
false
tests_src_main_java_gov_nasa_arc_mct_component_MockComponentProvider.java
269
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class MockModelRole { private Object mockData; public MockModelRole() { super(); } public Object getMockData() { return mockData; } public void setMockData(Object mockData) { this.mockData = mockData; } }
false
tests_src_main_java_gov_nasa_arc_mct_component_MockModelRole.java
270
public abstract class AbstractComponent implements Cloneable { /** A dummy component, used as a sentinel value. */ public final static AbstractComponent NULL_COMPONENT; static { AbstractComponent tmpComp = new AbstractComponent() { }; tmpComp.id = "0"; tmpComp.getCapability(ComponentInitializer.class).initialize(); NULL_COMPONENT = tmpComp; } /** The unique ID of the component, filled in by the framework. */ private String id; private String owner; private String originalOwner; private String creator; private Date creationDate; private AbstractComponent workUnitDelegate = null; private String displayName = null; // human readable name for the component. private String externalKey = null; // reference that can be used to contain external keys private Map<String, ExtendedProperties> viewRoleProperties; private ComponentInitializer initializer; private int version; private final AtomicBoolean isDirty = new AtomicBoolean(false); private boolean isStale = false; /** The existing manifestations of this component. */ private final WeakHashSet<View> viewManifestations = new WeakHashSet<View>(); private SoftReference<List<AbstractComponent>> cachedComponentReferences = new SoftReference<List<AbstractComponent>>(null); private List<AbstractComponent> mutatedComponentReferences; /** * Initialize the component by registering it with the component registry * and creating a new, empty set of view roles. */ protected void initialize() { performInitialization(); getCapability(Initializer.class).setInitialized(); } private void performInitialization() { if (this.id == null) { this.id = IdGenerator.nextComponentId(); } } /** * Verifies the class requirements are met for this component class. * * @param componentClass * class to verify, must not be null * @throws IllegalArgumentException * if the class does not meet the requirements */ public static void checkBaseComponentRequirements(Class<? extends AbstractComponent> componentClass) throws IllegalArgumentException { try { // ensure that a public no argument constructor exists. If this is // an inner non static class // there is an implicit argument of the enclosing class so this // scenario should be covered componentClass.getConstructor(new Class[0]); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(componentClass.getName() + " must provide a public no argument constructor"); } } /** * Returns the work unit delegate if any for this component. A work unit delegate will be persisted instead of this * component. This is generally only useful to views that are owning properties of other views or components. * @return work unit delegate or null if there is no delegate */ public AbstractComponent getWorkUnitDelegate() { return workUnitDelegate; } /** * Get the type ID string for the type of the component. Component type IDs * are unique for each registered component type. * * @return the component type ID */ public String getComponentTypeID() { return this.getClass().getName(); } /** * Returns the views for the desired view type. This method will apply the <code>PolicyInfo.CategoryType.FILTER_VIEW_ROLE</code> policy * and the <code>PolicyInfo.CategoryType.PREFERRED_VIEW</code> policy before returning the appropriate list of views. * @param type of view to discover. * @return views that are appropriate for this component. */ public Set<ViewInfo> getViewInfos(ViewType type) { Set<ViewInfo> possibleViewInfos = PlatformAccess.getPlatform().getComponentRegistry().getViewInfos(getComponentTypeID(), type); Set<ViewInfo> filteredViewInfos = new LinkedHashSet<ViewInfo>(); Platform platform = PlatformAccess.getPlatform(); PolicyManager policyManager = platform.getPolicyManager(); PolicyContext context = new PolicyContext(); context.setProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), this); context.setProperty(PolicyContext.PropertyName.VIEW_TYPE.getName(), type); for (ViewInfo viewInfo : possibleViewInfos) { context.setProperty(PolicyContext.PropertyName.TARGET_VIEW_INFO.getName(), viewInfo); if (policyManager.execute(PolicyInfo.CategoryType.FILTER_VIEW_ROLE.getKey(), context) .getStatus()) { filteredViewInfos.add(viewInfo); } } // if there is a preferredView then make sure this is added first in the // list for (ViewInfo viewRole : filteredViewInfos) { context.setProperty(PolicyContext.PropertyName.TARGET_VIEW_INFO.getName(), viewRole); if (!policyManager.execute(PolicyInfo.CategoryType.PREFERRED_VIEW.getKey(), context) .getStatus()) { Set<ViewInfo> setWithPreferredViewFirst = new LinkedHashSet<ViewInfo>(); setWithPreferredViewFirst.add(viewRole); setWithPreferredViewFirst.addAll(filteredViewInfos); filteredViewInfos = setWithPreferredViewFirst; break; } } return filteredViewInfos; } private synchronized void ensureViewPropertiesLoaded() { if (viewRoleProperties == null) { viewRoleProperties = PlatformAccess.getPlatform().getPersistenceProvider().getAllProperties(getComponentId()); } assert viewRoleProperties != null; } private synchronized void addViewProperty(String viewRoleType, ExtendedProperties properties) { ensureViewPropertiesLoaded(); if (!viewRoleProperties.containsKey(viewRoleType)) { this.viewRoleProperties.put(viewRoleType, properties); } } /** * Return the unique ID for this component. * * @return the ID for the component */ public String getId() { return this.id; } /** * Return the unique ID for this component. This is a synonym for * {@link #getId()}. * * @return the ID for the component */ public String getComponentId() { return this.id; } /** * Sets the ID of this component. The framework calls this method * automatically. It should never be called by plugin code. * * @param id * the new ID for the component */ public void setId(String id) { if (id != null && initializer != null && initializer.isInitialized()) { throw new IllegalStateException("id must be set before component is initialized"); } this.id = id; } /** * Tests whether the component is currently a leaf. * * <p> * A leaf component is defined as a component that will never have any * children. This is an <i>immutable</i> property of a component instance * and must not change during its lifetime. The default implementation * returns false (thus the default component will be a container), a * subclass that should identify itself as a leaf should override this * method and return true. * * @return true, if the component is currently a leaf. False otherwise. */ public boolean isLeaf() { return false; } /** * Sets the user ID of the owner of the component. * * @param owner * the user ID of the owner of the component */ public synchronized void setOwner(String owner) { if (originalOwner == null) { originalOwner = this.owner; } this.owner = owner; } /** * Gets the user ID of the owner of the component prior to the owner being modified. * @return the user Id of the owner */ public final synchronized String getOriginalOwner() { return originalOwner; } private synchronized void resetOriginalOwner() { originalOwner = null; } /** * Gets the user ID of the owner of the component. * * @return the component owner user ID */ public synchronized String getOwner() { return this.owner; } /** * Gets the creator of this component. * @return the creator of this component */ public synchronized String getCreator() { return creator; } /** * Gets the creation time of this component. * @return when this component was created */ public synchronized Date getCreationDate() { return creationDate; } /** * Adds a new delegate (child) component. The model of the new delegate * component will be added as a new delegate model, and all view role * instances will be updated. The new child will be added after all existing * children. If the child is already present, this will move the child to * the end. * * @param childComponent * the new child component */ public final void addDelegateComponent(AbstractComponent childComponent) { addDelegateComponents(Collections.singleton(childComponent)); } /** * This method is invoked by the persistence provider when the component is saved to the underlying persistence store. The * implementation delegates to the viewPersisted method. */ public final void componentSaved() { Set<View> guiComponents = getAllViewManifestations(); if (guiComponents != null) { for (View gui : guiComponents) { gui.viewPersisted(); } } } /** * Gets the components which are referencing this component. Currently, only delegate components are considered. * The result of this method is transient and thus requires overhead for each execution. * @return collection which can be empty but never null of components which reference this component. */ public Collection<AbstractComponent> getReferencingComponents() { PersistenceProvider persistenceService = PlatformAccess.getPlatform().getPersistenceProvider(); return persistenceService.getReferences(this); } /** * Adds a delegate (child) component to this component. The model of the * delegate component will be added as a delegate model, if not already * present, and all the view roles will be updated by sending an * {@link AddChildEvent} to the view role listeners. If the model is already * present, the child model will be moved to the given position. * * @param childIndex * the index within the children to add the new component, or -1 * to add at the end * @param childComponent * the new delegate component */ private void processAddDelegateComponent(int childIndex, AbstractComponent childComponent) { List<AbstractComponent> list = getComponents(); if (childIndex < 0) { childIndex = list.size(); } // If the child already exists, remove it, and adjust the insert index // if needed. int existingIndex = -1; for (int i = 0; i < list.size(); i++) { if (list.get(i).getComponentId().equals(childComponent.getComponentId())) { existingIndex = i; } } if (existingIndex >= 0) { removeComponent(list.get(existingIndex)); if (existingIndex < childIndex) { --childIndex; } } // Now add it again. addComponentAt(childIndex, childComponent); } /** * Determine by policy if this component can be deleted. * * @return true if this component can be deleted, false otherwise. */ public final boolean canBeDeleted() { Platform platform = PlatformAccess.getPlatform(); PolicyManager policyManager = platform.getPolicyManager(); PolicyContext context = new PolicyContext(); context.setProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), this); context.setProperty(PolicyContext.PropertyName.ACTION.getName(), 'w'); String compositionKey = PolicyInfo.CategoryType.CAN_DELETE_COMPONENT_POLICY_CATEGORY .getKey(); return policyManager.execute(compositionKey, context).getStatus(); } /** * Adds new delegate (child) components to this component. The model for * each component will be added as a delegate model, if not already present. * Then, all view roles will be updated by sending an {@link AddChildEvent} * for each new delegate added. The child will be added at the end of any * existing children. If the child was already present, this will move the * child to the end. * * <p> * This method is called when a drop of one or more components happens in * the directory tree. The canvas area of this component is unaffected. * * @param childComponents * the collection of delegate components to add * @return true if <code>childComponents</code> are added successfully; * otherwise false. */ public final boolean addDelegateComponents(Collection<AbstractComponent> childComponents) { return addDelegateComponents(-1, childComponents); } /** * Adds new delegate (child) components to this component. The model for * each component will be added as a delegate model, if not already present. * Then, all view roles will be updated by sending an {@link AddChildEvent} * for each new delegate added. The child will be added at a given index * among the existing children. If the child was already present, this will * move the child to the new position. * * <p> * This method is called when a drop of one or more components happens in * the directory tree. * * @param childIndex * the index with the children to add the new component, or -1 to * add at the end * @param childComponents * the collection of delegate components to add * @return true if <code>childComponents</code> are added successfully; * otherwise false. */ public final boolean addDelegateComponents(int childIndex, Collection<AbstractComponent> childComponents) { if (isLeaf()) { throw new UnsupportedOperationException("components declared as leaf cannot be mutated"); } Platform platform = PlatformAccess.getPlatform(); PolicyManager policyManager = platform.getPolicyManager(); PolicyContext context = new PolicyContext(); context.setProperty(PolicyContext.PropertyName.TARGET_COMPONENT.getName(), this); context.setProperty(PolicyContext.PropertyName.ACTION.getName(), 'w'); context .setProperty(PolicyContext.PropertyName.SOURCE_COMPONENTS.getName(), childComponents); if (policyManager.execute(PolicyInfo.CategoryType.ACCEPT_DELEGATE_MODEL_CATEGORY.getKey(), context).getStatus()) { if (!childComponents.isEmpty()) { for (AbstractComponent childComponent : childComponents) { processAddDelegateComponent(childIndex, childComponent); } } addDelegateComponentsCallback(childComponents); return true; } return false; } /** * Invoked after any of the <code>addDelegateComponents</code> methods are invoked. The default * implementation does nothing. * @param childComponents that were added. */ protected void addDelegateComponentsCallback(Collection<AbstractComponent> childComponents) { } /** * Removes a delegate (child) component from this component. The model of * the delegate component is removed as a delegate model. Then, all view * roles are updated by sending a {@link RemoveChildEvent}. * * @param childComponent * the delegate component to remove */ public final void removeDelegateComponent(AbstractComponent childComponent) { removeDelegateComponents(Collections.singleton(childComponent)); } /** * Removes delegate (child) components from this component. * * @param childComponents * the delegate components to remove */ public synchronized void removeDelegateComponents(Collection<AbstractComponent> childComponents) { if (isLeaf()) { throw new UnsupportedOperationException("components declared as leaf cannot be mutated"); } for (AbstractComponent comp : childComponents) { removeComponent(comp); } } /** * Get the human readable name for this component that is suitable for * displaying to the user in a GUI. * * If the display name has not been set, the component ID will be returned. * * Note: this method should <b>not</b> be relied on to retrieve component * IDs (or other component type specific identifiers such as PUI IDs). * * @return the display name of the component. */ public synchronized String getDisplayName() { if (displayName == null) { return getId(); } else { return displayName; } } /** * Get the human readable name for this component that is suitable for user display. This method differs from * {@link #getDisplayName()} as this method will be invoked when many components are being presented together and * having additional information may help the user distinguish components whose display name varies by only a small amount. * For example, this method may be used in presenting search results that may have the same display name so this method will be * invoked to help differentiate the results in the interface. The default implementation of this method will invoke {@link #getDisplayName()}. * @return a string representing the extended display name */ public String getExtendedDisplayName() { return getDisplayName(); } /** * Gets the external key for this component if it exists. * @return key used outside MCT if it exists, null otherwise */ public synchronized String getExternalKey() { return externalKey; } /** * Sets the external key that allow MCT components to generically reference external entities. How this is * used outside MCT is considered behavior of the component and will be described further by the component author. * @param key used outside MCT */ public synchronized void setExternalKey(String key) { externalKey = key; } /** * Sets the human readable display name for this component. * * @param name * the new display name */ public synchronized void setDisplayName(String name) { this.displayName = name; } /** * Sets the display name of the component and updates all view * manifestations to match, by sending a {@link PropertyChangeEvent} to each * view role listener. * * @param name * the new display name */ public void setAndUpdateDisplayName(String name) { this.setDisplayName(name); PropertyChangeEvent event = new PropertyChangeEvent(this); event.setProperty(PropertyChangeEvent.DISPLAY_NAME, this.displayName); firePropertyChangeEvent(event); } /** * Sets the coomponent's owner and updates all views. * * @param name the owner name */ public void setAndUpdateOwner(String name) { this.setOwner(name); PropertyChangeEvent event = new PropertyChangeEvent(this); event.setProperty(PropertyChangeEvent.OWNER, this.owner); firePropertyChangeEvent(event); } private void firePropertyChangeEvent(PropertyChangeEvent event) { Set<View> guiComponents = getAllViewManifestations(); if (guiComponents != null) { for (View gui : guiComponents) { gui.updateMonitoredGUI(event); } } } /** * Open this component in a new top level window. */ public final void open() { Platform platform = PlatformAccess.getPlatform(); assert platform != null; if (DetectGraphicsDevices.getInstance().getNumberGraphicsDevices() > DetectGraphicsDevices.MINIMUM_MONITOR_CHECK) { Frame frame = null; for (Frame f: Frame.getFrames()) { if (f.isActive() || f.isFocused()) { frame = f; break; } } if (frame != null) { GraphicsConfiguration graphicsConfig = frame.getGraphicsConfiguration(); open(graphicsConfig); } else { // Need this when MCT first startups and when there's no active window available. openInNewWindow(platform); } } else { openInNewWindow(platform); } } private void openInNewWindow(Platform platform) { assert platform != null : "Platform should not be null."; AbstractComponent ac = getComponentId() == null ? this : getNewComponentFromPersistence(); if (ac != null) { platform.getWindowManager().openInNewWindow(ac); } } private AbstractComponent getNewComponentFromPersistence() { return PlatformAccess.getPlatform().getPersistenceProvider().getComponent(getComponentId()); } /** * Detect multiple monitor displays and allow menu item to open this component in a new top level window. * @param graphicsConfig - Detect multiple display monitor devices */ public final void open(GraphicsConfiguration graphicsConfig) { Platform platform = PlatformAccess.getPlatform(); assert platform != null; WindowManager windowManager = platform.getWindowManager(); if (platform.getRootComponent() == this) windowManager.openInNewWindow(this, graphicsConfig); else windowManager.openInNewWindow(PlatformAccess.getPlatform().getPersistenceProvider().getComponent(getComponentId()), graphicsConfig); } /** * Gets an instance of the capability. A capability is functionality that * can be provided by a component dynamically. For example, functionality * that can be provided only before a component has been initialized, doing this * using inheritance would require introducing an exception into the method * signatures and additional semantic documentation. The * capabilities provided are specific to the component type and are not * constrained by the platform. * * @param <T> * Class of the capability * @param capability * requested from the component * @return an instance of the capability requested or null if not provided */ public final <T> T getCapability(Class<T> capability) { if (ComponentInitializer.class.isAssignableFrom(capability)) { if (initializer == null) { initializer = new Initializer(); } return capability.cast(initializer); } else if (Updatable.class.isAssignableFrom(capability)) { if (initializer == null) { initializer = new Initializer(); } return capability.cast(initializer); } return handleGetCapability(capability); } /** * Provides subclasses a chance to inject capabilities. The default * implementation does nothing by returning null. There are no requirements * on component providers to add capabilities. * * @param <T> * Class of the capability * @param capability * requested from the component * @see AbstractComponent#getCapability(Class) * @return an instance of the capability requested for null if not available */ protected <T> T handleGetCapability(Class<T> capability) { return null; } /** * Provide multiple capabilities for a capability class. * @param <T> Class of the capability * @param capability requested from the component * @return list of capabilities */ public final <T>List<T> getCapabilities(Class<T> capability) { return handleGetCapabilities(capability); } /** * Provides subclasses a chance to inject capabilities. * @param <T> the class of the capability * @param capability requested from the component * @return list of capabilities */ protected <T>List<T> handleGetCapabilities(Class<T> capability) { T t = getCapability(capability); return t == null ? Collections.<T>emptyList() : Collections.singletonList(t); } private AbstractComponent getWorkUnitComponent() { return workUnitDelegate != null ? workUnitDelegate : this; } private void addComponentToWorkUnit() { PlatformAccess.getPlatform().getPersistenceProvider().addComponentToWorkUnit(getWorkUnitComponent()); } /** * Determines if the underlying component has changes that only exist in memory. * @return true if the component needs to be saved false otherwise. */ public boolean isDirty() { return getWorkUnitComponent().isDirty.get(); } /** * Determines if the version of the underlying component is older than the component * persisted in the database. * @return true this version is older */ public synchronized boolean isStale() { return isStale; } /** * Mark the component as having outstanding changes in memory. */ public void save() { getWorkUnitComponent().isDirty.set(true); addComponentToWorkUnit(); if (getWorkUnitComponent() != this) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (View v : viewManifestations) v.updateMonitoredGUI(); } }); } } @Override public AbstractComponent clone() { try { Class<? extends AbstractComponent> componentClassType = this.getClass(); String newID = IdGenerator.nextComponentId(); AbstractComponent clonedComponent = componentClassType.newInstance(); clonedComponent.setId(newID); ModelStatePersistence persistence = getCapability(ModelStatePersistence.class); if (persistence != null) { String modelState = persistence.getModelState(); ModelStatePersistence clonedPersistence = clonedComponent.getCapability(ModelStatePersistence.class); assert clonedPersistence != null; clonedPersistence.setModelState(modelState); } for (AbstractComponent child : getComponents()) { clonedComponent.addComponent(child); } ensureViewPropertiesLoaded(); clonedComponent.ensureViewPropertiesLoaded(); for (Entry<String, ExtendedProperties> e : viewRoleProperties.entrySet()) { clonedComponent.viewRoleProperties.put(e.getKey(), e.getValue().clone()); } clonedComponent.owner = owner; clonedComponent.creator = creator; clonedComponent.displayName = displayName; clonedComponent.externalKey = externalKey; clonedComponent.version = version; ComponentInitializer clonedCapability = clonedComponent.getCapability(ComponentInitializer.class); clonedCapability.initialize(); return clonedComponent; } catch (SecurityException e) { throw new MCTRuntimeException(e); } catch (IllegalArgumentException e) { throw new MCTRuntimeException(e); } catch (InstantiationException e) { throw new MCTRuntimeException(e); } catch (IllegalAccessException e) { throw new MCTRuntimeException(e); } } private synchronized void setViewProperty(String viewType, ExtendedProperties properties) { ensureViewPropertiesLoaded(); this.viewRoleProperties.put(viewType, properties); } private synchronized Map<String,ExtendedProperties> getRawViewProperties() { return viewRoleProperties; } private synchronized Map<String,ExtendedProperties> getViewProperties() { ensureViewPropertiesLoaded(); return viewRoleProperties; } private synchronized ExtendedProperties getViewProperties(String viewType) { ensureViewPropertiesLoaded(); return this.viewRoleProperties.get(viewType); } /** * Returns the version of the component. * @return the version of the component */ public int getVersion() { return version; } /** * Returns the icon image for this component. * @return an icon image */ public final ImageIcon getIcon() { Collection<ExtendedComponentTypeInfo> infos = ExternalComponentRegistryImpl.getInstance().getComponentInfos(); for (ExtendedComponentTypeInfo info : infos) { if (getClass() == info.getComponentClass()) { return info.getIcon(); } } return MCTIcons.getComponent(); } /** * Returns the icon based on the component type. * @param className of the component type * @return an image icon */ public static ImageIcon getIconForComponentType(String className) { Collection<ExtendedComponentTypeInfo> infos = ExternalComponentRegistryImpl.getInstance().getComponentInfos(); for (ExtendedComponentTypeInfo info : infos) { if (className.equals(info.getComponentClass().getName())) { return info.getIcon(); } } return MCTIcons.getComponent(); } /** * Resets component properties. * @param txn the transaction to be performed atomically */ public synchronized void resetComponentProperties(ResetPropertiesTransaction txn) { txn.perform(); } /** * Adds a view manifestation that should be alerted to changes in this component. * @param viewManifestation to notify when changes occur. */ public void addViewManifestation(View viewManifestation) { viewManifestations.add(viewManifestation); } /** * Gets all the currently monitored manifestations. * @return all the current views of this manifestation */ public Set<View> getAllViewManifestations() { return new HashSet<View>(viewManifestations); } private final class Initializer implements ComponentInitializer, Updatable { private boolean initialized; @Override public void setId(String id) { AbstractComponent.this.id = id; } @Override public void setOwner(String owner) { AbstractComponent.this.owner = owner; } @Override public void setWorkUnitDelegate(AbstractComponent delegate) { AbstractComponent.this.workUnitDelegate = delegate; } @Override public void componentSaved() { AbstractComponent.this.isDirty.set(false); AbstractComponent.this.resetOriginalOwner(); AbstractComponent.this.releaseChildrenList(); } @Override public void setViewRoleProperty(String viewRoleType, ExtendedProperties properties) { setViewProperty(viewRoleType, properties); } @Override public ExtendedProperties getViewRoleProperties(String viewType) { return getViewProperties(viewType); } @Override public void setCreationDate(Date creationDate) { AbstractComponent.this.creationDate = creationDate; } @Override public void setCreator(String creator) { AbstractComponent.this.creator = creator; } @Override public void addViewRoleProperties(String viewRoleType, ExtendedProperties properties) { addViewProperty(viewRoleType, properties); } @Override public void initialize() { checkInitialized(); AbstractComponent.this.initialize(); } public void setInitialized() { checkInitialized(); initialized = true; } private void checkInitialized() { if (isInitialized()) { throw new IllegalStateException("component already initialized"); } } @Override public boolean isInitialized() { return initialized; } @Override public Map<String, ExtendedProperties> getMutatedViewRoleProperties() { return AbstractComponent.this.getRawViewProperties(); } @Override public Map<String, ExtendedProperties> getAllViewRoleProperties() { return Collections.unmodifiableMap(getViewProperties()); } @Override public synchronized void setVersion(int version) { AbstractComponent.this.version = version; } @Override public void setBaseDisplayedName(String baseDisaplyedName) { AbstractComponent.this.displayName = baseDisaplyedName; } @Override public void addReferences(List<AbstractComponent> references) { for (AbstractComponent c : references) { processAddDelegateComponent(-1, c); } } @Override public void removeReferences(List<AbstractComponent> references) { for (AbstractComponent c : references) { removeComponent(c); } } @Override public void notifyStale() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (View v : viewManifestations) { v.notifyStaleState(true); } } }); } @Override public synchronized void setStaleByVersion(int version) { if (getVersion() < version) { AbstractComponent.this.isStale = true ; } } } /** * Defines a transaction to reset component properties. */ public interface ResetPropertiesTransaction { /** * Defines the steps to reset certain component properties. */ public void perform(); } /** * Get a list of all components to which this component refers. * Generally, a referenced component may be thought of as a child * of the referencing component, but the precise interpretation of the * relationship may vary among component types and view types. * @return a list of all referenced components */ public synchronized List<AbstractComponent> getComponents() { return getOrLoadComponents(); } /** * Returns the component by the specified id. * @param id of the component to find * @return component with the given id or null if no component currently has the id. */ public static AbstractComponent getComponentById(String id) { Platform platform = PlatformAccess.getPlatform(); return platform.getPersistenceProvider().getComponent(id); } private void referencedComponentsMutated() { mutatedComponentReferences = cachedComponentReferences.get(); assert mutatedComponentReferences != null : "method must be invoked while holding a strong reference to the mutated list of children"; } private synchronized void releaseChildrenList() { mutatedComponentReferences = null; } private List<AbstractComponent> getOrLoadComponents() { if (isLeaf()) { return Collections.<AbstractComponent>emptyList(); } List<AbstractComponent> currentlyReferencedComponents = cachedComponentReferences.get(); if (currentlyReferencedComponents == null) { currentlyReferencedComponents = new ArrayList<AbstractComponent>(PlatformAccess.getPlatform().getPersistenceProvider().getReferencedComponents(this)); cachedComponentReferences = new SoftReference<List<AbstractComponent>>(currentlyReferencedComponents); } return currentlyReferencedComponents; } /** * Add a reference to the specified component. * Generally, a referenced component may be thought of as a child * of the referencing component, but the precise interpretation of the * relationship may vary among component types and view types. * @param component the component to which to refer */ private synchronized void addComponent(AbstractComponent component) { List<AbstractComponent> referencedComponents = getOrLoadComponents(); referencedComponents.add(component); referencedComponentsMutated(); } /** * Add a reference to the specified component, at the specified index. * Generally, a referenced component may be thought of as a child * of the referencing component, but the precise interpretation of the * relationship may vary among component types and view types. * @param index the index at which to reference * @param component the component to which to refer */ private synchronized void addComponentAt(int index, AbstractComponent component) { List<AbstractComponent> referencedComponents = getOrLoadComponents(); referencedComponents.add(index, component); referencedComponentsMutated(); } /** * Remove a reference to the specified component * Generally, a referenced component may be thought of as a child * of the referencing component, but the precise interpretation of the * relationship may vary among component types and view types. * @param component the component to dereference */ private synchronized void removeComponent(AbstractComponent component) { List<AbstractComponent> referencedComponents = getOrLoadComponents(); for (AbstractComponent ac : referencedComponents) { if (ac.getComponentId().equals(component.getComponentId())) { referencedComponents.remove(component); break; } } referencedComponentsMutated(); } /** * Returns a description of nuclear data that is inspectable. * This ordered list of fields is rendered in MCT Platform's InfoView. * * @return ordered list of property descriptors */ public List<PropertyDescriptor> getFieldDescriptors() { return null; } }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_AbstractComponent.java
271
SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (View v : viewManifestations) v.updateMonitoredGUI(); } });
false
mctcore_src_main_java_gov_nasa_arc_mct_components_AbstractComponent.java
272
private final class Initializer implements ComponentInitializer, Updatable { private boolean initialized; @Override public void setId(String id) { AbstractComponent.this.id = id; } @Override public void setOwner(String owner) { AbstractComponent.this.owner = owner; } @Override public void setWorkUnitDelegate(AbstractComponent delegate) { AbstractComponent.this.workUnitDelegate = delegate; } @Override public void componentSaved() { AbstractComponent.this.isDirty.set(false); AbstractComponent.this.resetOriginalOwner(); AbstractComponent.this.releaseChildrenList(); } @Override public void setViewRoleProperty(String viewRoleType, ExtendedProperties properties) { setViewProperty(viewRoleType, properties); } @Override public ExtendedProperties getViewRoleProperties(String viewType) { return getViewProperties(viewType); } @Override public void setCreationDate(Date creationDate) { AbstractComponent.this.creationDate = creationDate; } @Override public void setCreator(String creator) { AbstractComponent.this.creator = creator; } @Override public void addViewRoleProperties(String viewRoleType, ExtendedProperties properties) { addViewProperty(viewRoleType, properties); } @Override public void initialize() { checkInitialized(); AbstractComponent.this.initialize(); } public void setInitialized() { checkInitialized(); initialized = true; } private void checkInitialized() { if (isInitialized()) { throw new IllegalStateException("component already initialized"); } } @Override public boolean isInitialized() { return initialized; } @Override public Map<String, ExtendedProperties> getMutatedViewRoleProperties() { return AbstractComponent.this.getRawViewProperties(); } @Override public Map<String, ExtendedProperties> getAllViewRoleProperties() { return Collections.unmodifiableMap(getViewProperties()); } @Override public synchronized void setVersion(int version) { AbstractComponent.this.version = version; } @Override public void setBaseDisplayedName(String baseDisaplyedName) { AbstractComponent.this.displayName = baseDisaplyedName; } @Override public void addReferences(List<AbstractComponent> references) { for (AbstractComponent c : references) { processAddDelegateComponent(-1, c); } } @Override public void removeReferences(List<AbstractComponent> references) { for (AbstractComponent c : references) { removeComponent(c); } } @Override public void notifyStale() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (View v : viewManifestations) { v.notifyStaleState(true); } } }); } @Override public synchronized void setStaleByVersion(int version) { if (getVersion() < version) { AbstractComponent.this.isStale = true ; } } }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_AbstractComponent.java
273
SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (View v : viewManifestations) { v.notifyStaleState(true); } } });
false
mctcore_src_main_java_gov_nasa_arc_mct_components_AbstractComponent.java
274
public interface ResetPropertiesTransaction { /** * Defines the steps to reset certain component properties. */ public void perform(); }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_AbstractComponent.java
275
public class AbstractComponentTest { public static class BaseComponentSub1 extends AbstractComponent { public BaseComponentSub1(int a){ } } public static class BaseComponentSub3 extends AbstractComponent { BaseComponentSub3(){ } } public static class BaseComponentSub2 extends AbstractComponent { public BaseComponentSub2(){ } } public static class TestingView3 extends View { private static final long serialVersionUID = 1L; public TestingView3(AbstractComponent ac, ViewInfo vi) { super(ac,vi); } } @Mock private Platform mockPlatform; @Mock private WindowManager mockWindowManager; @Mock private PersistenceProvider mockPersistenceService; @BeforeMethod public void setup() { PolicyManager mockManager = new PolicyManager() { @Override public ExecutionResult execute(String categoryKey, PolicyContext context) { return new ExecutionResult(null, true, null); } }; MockitoAnnotations.initMocks(this); Mockito.when(mockPlatform.getPolicyManager()).thenReturn(mockManager); Mockito.when(mockPlatform.getWindowManager()).thenReturn(mockWindowManager); Mockito.when(mockPlatform.getPersistenceProvider()).thenReturn(mockPersistenceService); Mockito.when(mockPersistenceService.getReferencedComponents(Mockito.any(AbstractComponent.class))).thenReturn(Collections.<AbstractComponent>emptyList()); (new PlatformAccess()).setPlatform(mockPlatform); } @Test public void testCheckBaseComponentRequirements() { AbstractComponent.checkBaseComponentRequirements(BaseComponentSub2.class); checkConstructor(BaseComponentSub1.class); checkConstructor(BaseComponentSub3.class); } @SuppressWarnings({ "unchecked", "rawtypes" }) @DataProvider(name="viewInfoData") public Object[][] viewInfoData() { View v1 = Mockito.mock(View.class); View v2 = Mockito.mock(TestingView3.class); ViewInfo vi = new ViewInfo(v1.getClass(),"v1", ViewType.CENTER); //ViewInfo vi2 = new ViewInfo(v2.getClass(), "v2", ViewType.INSPECTION); ViewInfo vi3 = new ViewInfo(v2.getClass(), "v2", ViewType.CENTER); return new Object[][] { new Object[] { new LinkedHashSet(Arrays.asList(vi,vi3)), Collections.emptySet(), ViewType.CENTER, new LinkedHashSet(Arrays.asList(vi,vi3)) }, new Object[] { new LinkedHashSet(Arrays.asList(vi,vi3)), Collections.singleton(vi), ViewType.CENTER, Collections.singleton(vi3) }, new Object[] { Collections.emptySet(), Collections.emptySet(), ViewType.LAYOUT, Collections.emptySet() } }; } @SuppressWarnings("rawtypes") @Test(dataProvider="viewInfoData") public void testGetViewInfos(Set<ViewInfo> viewInfos, final Set<ViewInfo> filterOut, ViewType type, Set<ViewInfo> expected) { AbstractComponent ac = new BaseComponentSub2(); CoreComponentRegistry mockRegistry = Mockito.mock(CoreComponentRegistry.class); PolicyManager mockPolicyManager = Mockito.mock(PolicyManager.class); Mockito.when(mockPlatform.getComponentRegistry()).thenReturn(mockRegistry); Mockito.when(mockRegistry.getViewInfos(Mockito.anyString(), Mockito.same(type))).thenReturn(viewInfos); Mockito.when(mockPlatform.getPolicyManager()).thenReturn(mockPolicyManager); Mockito.when(mockPolicyManager.execute(Mockito.matches(PolicyInfo.CategoryType.FILTER_VIEW_ROLE.getKey()), Mockito.any(PolicyContext.class))).thenAnswer( new Answer() { public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); PolicyContext pc = (PolicyContext) args[1]; ViewInfo vi = pc.getProperty(PolicyContext.PropertyName.TARGET_VIEW_INFO.getName(), ViewInfo.class); return new ExecutionResult(pc, !filterOut.contains(vi), ""); } } ); Mockito.when(mockPolicyManager.execute(Mockito.matches(PolicyInfo.CategoryType.PREFERRED_VIEW.getKey()), Mockito.any(PolicyContext.class))).thenReturn(new ExecutionResult(new PolicyContext(),true, "")); Set<ViewInfo> infos = ac.getViewInfos(type); Assert.assertEquals(infos, expected); } @Test public void testInitialize() { AbstractComponent comp = new BaseComponentSub2(); Assert.assertNull(comp.getId()); comp.initialize(); Assert.assertTrue(comp.getCapability(ComponentInitializer.class).isInitialized()); Assert.assertNotNull(comp.getId()); } @Test public void testClone() { BaseComponentSub2 comp = new BaseComponentSub2(); ExtendedProperties props = new ExtendedProperties(); props.addProperty("value", "value"); Mockito.when(mockPersistenceService.getAllProperties(comp.getComponentId())).thenReturn(Collections.singletonMap("view1", props)); BaseComponentSub2 compClone = BaseComponentSub2.class.cast(comp.clone()); Map<String,ExtendedProperties> clonedProps = compClone.getCapability(ComponentInitializer.class).getAllViewRoleProperties(); Assert.assertTrue(clonedProps.size() == 1); ExtendedProperties clonedEp = clonedProps.get("view1"); Assert.assertTrue(clonedEp.getAllProperties().size() == 1); Assert.assertEquals(clonedEp.getProperty("value",String.class),"value"); } @Test public void addDelegateComponentsTest() { (new PlatformAccess()).setPlatform(mockPlatform); BaseComponentSub2 comp = new BaseComponentSub2(); BaseComponentSub2 comp2 = new BaseComponentSub2(); comp.addDelegateComponent(comp2); Assert.assertEquals(comp.getComponents().size(), 1); Assert.assertEquals(comp.getComponents().iterator().next(), comp2); } private void checkConstructor(Class<? extends AbstractComponent> clazz) { try { AbstractComponent.checkBaseComponentRequirements(clazz); Assert.fail("only public no argument constructors should be allowed " + clazz.getName()); } catch (IllegalArgumentException e) { // } } }
false
mctcore_src_test_java_gov_nasa_arc_mct_components_AbstractComponentTest.java
276
PolicyManager mockManager = new PolicyManager() { @Override public ExecutionResult execute(String categoryKey, PolicyContext context) { return new ExecutionResult(null, true, null); } };
false
mctcore_src_test_java_gov_nasa_arc_mct_components_AbstractComponentTest.java
277
new Answer() { public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); PolicyContext pc = (PolicyContext) args[1]; ViewInfo vi = pc.getProperty(PolicyContext.PropertyName.TARGET_VIEW_INFO.getName(), ViewInfo.class); return new ExecutionResult(pc, !filterOut.contains(vi), ""); } }
false
mctcore_src_test_java_gov_nasa_arc_mct_components_AbstractComponentTest.java
278
public static class BaseComponentSub1 extends AbstractComponent { public BaseComponentSub1(int a){ } }
false
mctcore_src_test_java_gov_nasa_arc_mct_components_AbstractComponentTest.java
279
public static class BaseComponentSub2 extends AbstractComponent { public BaseComponentSub2(){ } }
false
mctcore_src_test_java_gov_nasa_arc_mct_components_AbstractComponentTest.java
280
public static class BaseComponentSub3 extends AbstractComponent { BaseComponentSub3(){ } }
false
mctcore_src_test_java_gov_nasa_arc_mct_components_AbstractComponentTest.java
281
public static class TestingView3 extends View { private static final long serialVersionUID = 1L; public TestingView3(AbstractComponent ac, ViewInfo vi) { super(ac,vi); } }
false
mctcore_src_test_java_gov_nasa_arc_mct_components_AbstractComponentTest.java
282
public class DetectGraphicsDevices { private static final Logger logger = LoggerFactory.getLogger(DetectGraphicsDevices.class); private static final DetectGraphicsDevices detectGraphicsDevices = new DetectGraphicsDevices(); /** Minimum display monitor check. */ public static final int MINIMUM_MONITOR_CHECK = 1; /** Open multiple monitor Objects menu action. */ public static final String OPEN_MULTIPLE_MONITORS_OBJECTS_ACTION = "OPEN_MULTIPLE_MONITORS_OBJECTS_ACTION"; /** Open multiple monitor This menu action. */ public static final String OPEN_MULTIPLE_MONITORS_THIS_ACTION = "OPEN_MULTIPLE_MONITORS_THIS_ACTION"; /** Objects menu additions menu path. */ public static final String OBJECTS_ADDITIONS_MENU_PATH = "/objects/additions"; /** This menu additions menu path. */ public static final String THIS_ADDITIONS_MENU_PATH = "/this/additions"; /** Objects submenu path. */ public static final String OBJECTS_SUBMENU_PATH = "objects/submenu.ext"; /** Text menu for Objects menu action. */ public static final String SHOW_OBJECTS_ACTION_MULTIPLE_MONITORS_TEXT = "Open in Another Monitor"; /** Open multiple monitor Objects menu name. */ public static final String OBJECTS_OPEN_MULTIPLE_MONITORS_MENU = "OBJECTS_OPEN_MULTIPLE_MONITORS_MENU"; /** Open multiple monitor This menu name. */ public static final String THIS_OPEN_MULTIPLE_MONITORS_MENU = "THIS_OPEN_MULTIPLE_MONITORS_MENU"; /** Text menu for This menu action. */ public static final String SHOW_THIS_ACTION_MULTIPLE_MONITORS_TEXT = "Open This Object in Another Monitor"; /** Default text menu. */ public static final String DEFAULT_MULTIPLE_MONITOR_TEXT = "Default 'Display0' Monitor"; /** Prefix for menu name. */ public static final String PROPER_DEVICE_NAME_PREFIX = "Monitor"; private GraphicsEnvironment graphicsEnv = null; private GraphicsDevice[] graphicsDevices = null; private GraphicsDevice singleGraphicsDevice = null; /** * Singleton getInstance. * * @return detectGraphicsDevices */ public static DetectGraphicsDevices getInstance() { return detectGraphicsDevices; } /** * Private constructor for Singleton. */ private DetectGraphicsDevices() { graphicsEnv = GraphicsEnvironment.getLocalGraphicsEnvironment(); graphicsDevices = graphicsEnv.getScreenDevices(); } /** * Determines whether graphics device environment is headless or not. * * @return isHeadless - boolean (default is false) */ public boolean isGraphicsEnvHeadless() { // Tests whether the display (or keyboard, mouse) an be supported within this GraphicsEnvironment // If true, then HeadlessException is thrown and GraphicsEnv cannot support display; false otherwise boolean isHeadless = false; try { isHeadless = GraphicsEnvironment.isHeadless(); logger.debug("GraphicsEnvironment.isHeadless(): " + GraphicsEnvironment.isHeadless()); } catch(HeadlessException headlessEx) { logger.error("HeadlessException: {0}", headlessEx); } logger.debug("isHeadless: {0}", isHeadless); return isHeadless; } /** * Determines whether graphics device environment is headless or not. * * @return isHeadlessInstance - boolean (default is false) */ public boolean isGraphicsEnvHeadlessInstance() { // Tests whether the display (or keyboard, mouse) an be supported within this GraphicsEnvironment // If true, then HeadlessException is thrown and GraphicsEnv can support display; false otherwise boolean isHeadlessInstance = false; try { isHeadlessInstance = graphicsEnv.isHeadlessInstance(); logger.debug("graphicsEnv.isHeadlessInstance(): {0}", graphicsEnv.isHeadlessInstance()); } catch(HeadlessException headlessEx) { logger.error("HeadlessException: {0}", headlessEx); } logger.debug("isHeadlessInstance: {0}", isHeadlessInstance); return isHeadlessInstance; } /** * Gets the total number of graphics device available. * * @return graphicsDevices.length - Total number of graphics devices detected */ public int getNumberGraphicsDevices() { logger.debug("Total number of graphics device monitors (graphicsDevices.length): {0}", graphicsDevices.length); return (graphicsDevices != null ? graphicsDevices.length : 0); } /** * Gets the array of GraphicsDevices available. * * @return graphicsDevices - Array of graphics devices objects */ public GraphicsDevice[] getGraphicsDevice() { return graphicsDevices; } /** * Sets the array of GraphicsDevices. * * @param graphicsDevices - Array of graphics devices objects */ public void setGraphicsDevice(GraphicsDevice[] graphicsDevices) { this.graphicsDevices = graphicsDevices; } /** * Gets a single primary graphics device. * * @return singleGraphicsDevice */ public GraphicsDevice getSingleGraphicDevice() { return singleGraphicsDevice; } /** * Gets a single primary graphics device configuration based on graphics device name. * * @param graphicsDeviceName - The graphics device name. * @return graphicsDeviceConfig - The graphics device configuration object or null. */ public GraphicsConfiguration getSingleGraphicDeviceConfig(String graphicsDeviceName) { GraphicsConfiguration graphicsDeviceConfig = null; GraphicsDevice[] graphicsDevices = getGraphicsDevice(); for (int i=0; i < graphicsDevices.length; i++) { GraphicsConfiguration[] graphicsConfigs = graphicsDevices[i].getConfigurations(); logger.debug("[i={0}]: Total Graphics Configs: {1}", i, graphicsConfigs.length); String graphicsDeviceNameID = graphicsDevices[i].getIDstring(); graphicsDeviceNameID = graphicsDeviceNameID.replace("\\", ""); graphicsDeviceNameID = graphicsDeviceNameID.trim(); graphicsDeviceName = graphicsDeviceName.trim(); logger.debug("graphicsDeviceNameID: {0}", graphicsDeviceNameID + " ==? graphicsDeviceName: {1}", graphicsDeviceName + " check=" + (graphicsDeviceNameID.equals(graphicsDeviceName))); if (graphicsDeviceNameID.equals(graphicsDeviceName)) { graphicsDeviceConfig = graphicsDevices[i].getDefaultConfiguration(); singleGraphicsDevice = graphicsDevices[i]; if (graphicsDevices[i] == null) { logger.error("Multiple monitor graphics devices are NULL will open on default current monitor."); } logger.debug("singleGraphicsDevice: {0}", singleGraphicsDevice); return graphicsDeviceConfig; } } return graphicsDeviceConfig; } /** * Checks whether target is Windows OS platform. * * @return boolean - WindowsOS or not */ public static boolean isWindows() { String os = System.getProperty("os.name").toLowerCase(); return (os.indexOf("win") >= 0); } /** * Checks whether target is MacOS platform. * * @return boolean - MacOS or not */ public static boolean isMac() { String os = System.getProperty("os.name").toLowerCase(); return (os.indexOf("mac") >= 0); } /** * Checks whether target is UNIX/Linux platform. * * @return boolean - UNIX or Linux OS platform or not */ public static boolean isUnixLinux() { String os = System.getProperty("os.name").toLowerCase(); return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0); } /** * Gets an array list of graphics device names available. * * @return graphicsDeviceNames - ArrayList of strings for graphics device names */ public ArrayList<String> getGraphicDeviceNames() { ArrayList<String> graphicsDeviceNames = new ArrayList<String>(); for (int i=0; i < graphicsDevices.length; i++) { graphicsDeviceNames.add(graphicsDevices[i].getIDstring()); } return graphicsDeviceNames; } }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_DetectGraphicsDevices.java
283
@XmlRootElement(name="extendedInfo") @XmlAccessorType(XmlAccessType.FIELD) public class ExtendedProperties implements Cloneable { @XmlJavaTypeAdapter(ExtendedPropertiesXmlAdapter.class) private HashMap<String, Set<Object>> viewRoleProperties = new LinkedHashMap<String, Set<Object>>(); /** * Replace a property. * @param key the key of the property * @param value the value of the property */ public synchronized void setProperty(String key, String value) { LinkedHashSet<Object> valueList = new LinkedHashSet<Object>(); valueList.add(value); this.viewRoleProperties.put(key, valueList); } /** * Replace a property. * @param key the key of the property * @param value the value of the property */ public synchronized void setProperty(String key, Object value) { assert value instanceof String || value instanceof MCTViewManifestationInfo : value.getClass().getName(); LinkedHashSet<Object> valueList = new LinkedHashSet<Object>(); valueList.add(value); this.viewRoleProperties.put(key, valueList); } /** * Replace all existing properties with the supplied properties. * @param viewInfo the supplied properties */ public synchronized void setProperties(ExtendedProperties viewInfo) { this.viewRoleProperties.clear(); this.viewRoleProperties.putAll(viewInfo.viewRoleProperties); } /** * Returns all properties. * @return map from a key to a set of properties that <code>Object</code>s */ public Map<String, Set<Object>> getAllProperties() { return Collections.unmodifiableMap(viewRoleProperties); } /** * Add a property. * @param key the key of the property * @param value the value of the property */ public synchronized void addProperty(String key, Object value) { assert value instanceof String || value instanceof MCTViewManifestationInfo; Set<Object> valueList = viewRoleProperties.get(key); if (valueList == null) { valueList = new LinkedHashSet<Object>(); viewRoleProperties.put(key, valueList); } valueList.add(value); } /** * Get the value of a property. * @param <T> the type of the return type * @param key the key of the property * @param returnType the type of the returned property value * @return the value of the property */ public synchronized<T> T getProperty(String key, Class<T> returnType) { Set<Object> valueList = viewRoleProperties.get(key); if (valueList == null || valueList.isEmpty()) { return null; } return returnType.cast(valueList.iterator().next()); } /** * Gets the default extended property value. * @param <T> data type of the return for this method * @param returnType the data type of the return * @return the return value */ public synchronized<T> T getMostRecentProperty(Class<T> returnType) { Set<Object> valueList = null; Set<String> keySet = viewRoleProperties.keySet(); Iterator<String> it = keySet.iterator(); Object mostRecentKey = null; while (it.hasNext()) { mostRecentKey = it.next(); } valueList = viewRoleProperties.get(mostRecentKey); return returnType.cast(valueList.iterator().next()); } /** * Get the value of a property. * @param key the key of the property * @return the value of the property */ public synchronized Set<Object> getProperty(String key) { return viewRoleProperties.get(key); } /** * Find out if there is any property defined. * @return true if there is at least one property defined; false otherwise. */ public synchronized boolean hasProperty() { return !this.viewRoleProperties.isEmpty(); } /** * Clone the properties and return the clone. * @return the cloned ViewRoleProperties object. */ @Override public synchronized ExtendedProperties clone() { ExtendedProperties clonedProperties = new ExtendedProperties(); for (Entry<String, Set<Object>> entry: this.viewRoleProperties.entrySet()) { LinkedHashSet<Object> clonedSet = new LinkedHashSet<Object>(); for (Object o:entry.getValue()) { Object addedObject = o; if (o instanceof MCTViewManifestationInfoImpl) { addedObject = MCTViewManifestationInfoImpl.class.cast(o).clone(); } clonedSet.add(addedObject); } clonedProperties.viewRoleProperties.put(entry.getKey(), clonedSet); } return clonedProperties; } }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_ExtendedProperties.java
284
@XmlAccessorType(XmlAccessType.FIELD) final class ExtendedPropertiesHashMapType { ViewRolePropertiesEntryType[] entries; public ExtendedPropertiesHashMapType() { super(); } ExtendedPropertiesHashMapType(Map<String, Set<Object>> data) { this.entries = new ViewRolePropertiesEntryType[data.size()]; int i=0; for (Map.Entry<String, Set<Object>> entry: data.entrySet()) { this.entries[i] = new ViewRolePropertiesEntryType(); this.entries[i].key = entry.getKey(); Set<Object> values = entry.getValue(); this.entries[i].value = new Object[values.size()]; int j=0; for (Object val: values) { this.entries[i].value[j++] = val; } i++; } } HashMap<String, Set<Object>> unMarshal() { HashMap<String, Set<Object>> returnValue = new HashMap<String, Set<Object>>(); for (ViewRolePropertiesEntryType entry: entries) { LinkedHashSet<Object> valueList = new LinkedHashSet<Object>(); for (Object obj: entry.value) { valueList.offerLast(obj); } returnValue.put(entry.key, valueList); } return returnValue; } private static final class ViewRolePropertiesEntryType { @XmlAttribute public String key; @XmlElements({ @XmlElement(type=String.class), @XmlElement(name="ManifestInfo", type=MCTViewManifestationInfoImpl.class) }) public Object[] value; } }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_ExtendedPropertiesHashMapType.java
285
private static final class ViewRolePropertiesEntryType { @XmlAttribute public String key; @XmlElements({ @XmlElement(type=String.class), @XmlElement(name="ManifestInfo", type=MCTViewManifestationInfoImpl.class) }) public Object[] value; }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_ExtendedPropertiesHashMapType.java
286
public class ExtendedPropertiesXmlAdapter extends XmlAdapter<ExtendedPropertiesHashMapType, HashMap<String, Set<Object>>> { @Override public gov.nasa.arc.mct.components.ExtendedPropertiesHashMapType marshal( HashMap<String, Set<Object>> v) throws Exception { return new ExtendedPropertiesHashMapType(v); } @Override public HashMap<String, Set<Object>> unmarshal( gov.nasa.arc.mct.components.ExtendedPropertiesHashMapType v) throws Exception { return v.unMarshal(); } }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_ExtendedPropertiesXmlAdapter.java
287
public interface FeedProvider { /** * Required key for the map returned by {@link FeedAggregator#getData(java.util.Set, java.util.concurrent.TimeUnit, long, long)} to identify the normalized time data. * */ public static final String NORMALIZED_TIME_KEY = "time"; /** * Required key for the map returned by {@link FeedAggregator#getData(java.util.Set, java.util.concurrent.TimeUnit, long, long)} to identify the normalized data value. */ public static final String NORMALIZED_VALUE_KEY = "data"; /** * Optional key for the map returned by {@link FeedAggregator#getData(java.util.Set, java.util.concurrent.TimeUnit, long, long)} to identify the normalized data value. */ public static final String NORMALIZED_RENDERING_INFO = "ri"; /** * key for the map returned by {@link FeedAggregator#getData(java.util.Set, java.util.concurrent.TimeUnit, long, long)} to identify if the data value is valid. */ public static final String NORMALIZED_IS_VALID_KEY = "isValid"; /** * Optional key for the map returned by {@link FeedAggregator#getData(java.util.Set, java.util.concurrent.TimeUnit, long, long)} to identify the type of the status class using ISP data types. */ public static final String NORMALIZED_TELEMETRY_STATUS_CLASS_KEY = "status"; /** Rendering info. */ static class RenderingInfo { private String statusText; private Color statusColor; private String valueText; private Color valueColor; private boolean valid; private boolean plottable = true; static final String sep = "&"; public RenderingInfo( String valueText, Color valueColor, String statusText, Color statusColor, boolean valid) { super(); this.statusText = statusText; this.statusColor = statusColor; this.valueColor = valueColor; this.valueText = valueText; this.valid = valid; } /** * Returns rendering info, given its string representation * * @param riAsString string representation * @return rendering info instance */ public static FeedProvider.RenderingInfo valueOf(String riAsString) { int start = -1; int end = riAsString.indexOf(sep); String valueColor = riAsString.substring(start + 1, end); start = end; end = riAsString.indexOf(sep, end + 1); String statusText = riAsString.substring(start + 1, end); start = end; end = riAsString.indexOf(sep, end + 1); String statusColor = riAsString.substring(start + 1, end); start = end; end = riAsString.indexOf(sep, end + 1); String isValid = riAsString.substring(start + 1, end); start = end; end = riAsString.indexOf(sep, end + 1); String isPlottable = riAsString.substring(start + 1, end); start = end; String valueText = riAsString.substring(start + 1); FeedProvider.RenderingInfo ri = null; ri = new FeedProvider.RenderingInfo( valueText, new Color(Integer.parseInt(valueColor)), statusText, new Color(Integer.parseInt(statusColor)), Boolean.valueOf(isValid) ); ri.setPlottable(Boolean.valueOf(isPlottable)); return ri; } @Override public String toString() { return Integer.toString(valueColor.getRGB()) +sep+ statusText +sep+ Integer.toString(statusColor.getRGB()) +sep+ Boolean.toString(valid) +sep+ Boolean.toString(plottable) +sep+ valueText ; } /** * Gets the value. * @return the value as string */ public String getValueText() { return valueText; } /** * Sets the text representation of the value * @param v the value */ public void setValueText(String v) { this.valueText = v; } /** * Gets the value color. * @return the value color */ public Color getValueColor() { return valueColor; } /** * Gets the status. * @return the status as string */ public String getStatusText() { return statusText; } /** * Gets the status color. * @return the status color */ public Color getStatusColor() { return statusColor; } /** * Gets the validity. * @return true if the status is valid. */ public boolean isValid() { return valid; } /** gets plottable. */ public boolean isPlottable() { return plottable; } /** sets plottable. */ public void setPlottable(boolean plottable) { this.plottable = plottable; } } /** * Returns the subscription id for the platform to manage. The id will be used as input for the * subscription service. * * @return subscription id to manage, the id must be unique across all feed providers (so this should include information on * when the id is available flight number, segment, ...). This method must not return null, but should return * an empty list to signify that subscriptions should not be managed by the platform. */ public String getSubscriptionId(); /** * Provides a reference to the time service for this feed. * @return the time service used by this feed provider. */ public TimeService getTimeService(); /** * Returns a description of the feed component in a form suitable for displaying to the user in, for example, a plot legend. * The component author may include newline characters (\n) which the view may use to separate lines. * @return description of this feed component */ public String getLegendText(); /** * Returns the maximum number of samples that can be returned per second (the actual rate may fluctuate). * @return maximum number of samples */ public int getMaximumSampleRate(); /** * Represents the data type provided through this feed provider. */ public enum FeedType { /** * A value than can be cast to a {@link Double}. */ FLOATING_POINT() { @Override public Object convert(String value) { return Double.valueOf(value); } }, /** * A raw string value. */ STRING() { @Override public Object convert(String value) { return value; } }, /** * A value than can be cast to a {@link Long}. */ INTEGER() { @Override public Object convert(String value) { return Long.valueOf(value); } }; /** * Converts the given String value into the data type represented by this object. * @param value to convert * @return the deserialized representation of the object */ public abstract Object convert(String value); }; /** * Gets a representation of the type for this feed. <b>BETA</b> * @return a representation of the data type for this feed. */ public FeedType getFeedType(); /** * Returns the name of the feed. The name should have enough information to identify the component and * also include consideration for name collapsing (use consistent naming conventions to allow collapsing * information where no information loss will occur. For example, a tabular view may use row and column * headers to collect common information). * @return String representing human canonical display information */ public String getCanonicalName(); /** * Returns rendering info, given data status. * @param data the feed data * @return information on how this data should be rendered */ public RenderingInfo getRenderingInfo(Map<String,String> data); /** * Returns the maximum timestamp for valid data. This is used to support predictions that have values * beyond the current time. * @return the long representing epoch time. */ public long getValidDataExtent(); /** * Returns true if the feed represents predictive data. This can be used to determine how far into the * future to make data requests. * @return true if this feed represents a prediction, false otherwise. */ public boolean isPrediction(); /** * Returns true if the data buffer is non-Change of Data (COD); otherwise returns false if COD. * @return boolean whether the feed provider is a non-COD data buffer or not. */ public boolean isNonCODDataBuffer(); }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_FeedProvider.java
288
public enum FeedType { /** * A value than can be cast to a {@link Double}. */ FLOATING_POINT() { @Override public Object convert(String value) { return Double.valueOf(value); } }, /** * A raw string value. */ STRING() { @Override public Object convert(String value) { return value; } }, /** * A value than can be cast to a {@link Long}. */ INTEGER() { @Override public Object convert(String value) { return Long.valueOf(value); } }; /** * Converts the given String value into the data type represented by this object. * @param value to convert * @return the deserialized representation of the object */ public abstract Object convert(String value); };
false
mctcore_src_main_java_gov_nasa_arc_mct_components_FeedProvider.java
289
FLOATING_POINT() { @Override public Object convert(String value) { return Double.valueOf(value); } },
false
mctcore_src_main_java_gov_nasa_arc_mct_components_FeedProvider.java
290
STRING() { @Override public Object convert(String value) { return value; } },
false
mctcore_src_main_java_gov_nasa_arc_mct_components_FeedProvider.java
291
INTEGER() { @Override public Object convert(String value) { return Long.valueOf(value); } };
false
mctcore_src_main_java_gov_nasa_arc_mct_components_FeedProvider.java
292
static class RenderingInfo { private String statusText; private Color statusColor; private String valueText; private Color valueColor; private boolean valid; private boolean plottable = true; static final String sep = "&"; public RenderingInfo( String valueText, Color valueColor, String statusText, Color statusColor, boolean valid) { super(); this.statusText = statusText; this.statusColor = statusColor; this.valueColor = valueColor; this.valueText = valueText; this.valid = valid; } /** * Returns rendering info, given its string representation * * @param riAsString string representation * @return rendering info instance */ public static FeedProvider.RenderingInfo valueOf(String riAsString) { int start = -1; int end = riAsString.indexOf(sep); String valueColor = riAsString.substring(start + 1, end); start = end; end = riAsString.indexOf(sep, end + 1); String statusText = riAsString.substring(start + 1, end); start = end; end = riAsString.indexOf(sep, end + 1); String statusColor = riAsString.substring(start + 1, end); start = end; end = riAsString.indexOf(sep, end + 1); String isValid = riAsString.substring(start + 1, end); start = end; end = riAsString.indexOf(sep, end + 1); String isPlottable = riAsString.substring(start + 1, end); start = end; String valueText = riAsString.substring(start + 1); FeedProvider.RenderingInfo ri = null; ri = new FeedProvider.RenderingInfo( valueText, new Color(Integer.parseInt(valueColor)), statusText, new Color(Integer.parseInt(statusColor)), Boolean.valueOf(isValid) ); ri.setPlottable(Boolean.valueOf(isPlottable)); return ri; } @Override public String toString() { return Integer.toString(valueColor.getRGB()) +sep+ statusText +sep+ Integer.toString(statusColor.getRGB()) +sep+ Boolean.toString(valid) +sep+ Boolean.toString(plottable) +sep+ valueText ; } /** * Gets the value. * @return the value as string */ public String getValueText() { return valueText; } /** * Sets the text representation of the value * @param v the value */ public void setValueText(String v) { this.valueText = v; } /** * Gets the value color. * @return the value color */ public Color getValueColor() { return valueColor; } /** * Gets the status. * @return the status as string */ public String getStatusText() { return statusText; } /** * Gets the status color. * @return the status color */ public Color getStatusColor() { return statusColor; } /** * Gets the validity. * @return true if the status is valid. */ public boolean isValid() { return valid; } /** gets plottable. */ public boolean isPlottable() { return plottable; } /** sets plottable. */ public void setPlottable(boolean plottable) { this.plottable = plottable; } }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_FeedProvider.java
293
public abstract class JAXBModelStatePersistence<C> implements ModelStatePersistence { private static final Map<Class<?>, JAXBContext> marshalCache = new ConcurrentHashMap<Class<?>, JAXBContext>(); @Override public final String getModelState() { try { return marshal(getStateToPersist()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (JAXBException e) { // TODO Auto-generated catch block throw new RuntimeException(e); } } @Override public final void setModelState(String state) { try { setPersistentState(unmarshal(getJAXBClass(), state)); } catch (DataBindingException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (JAXBException e) { throw new RuntimeException(e); } } /** * Gets the current model state to persist. * @return the current model state */ protected abstract C getStateToPersist(); /** * Sets the current model state. * @param modelState to reference as the current model state. */ protected abstract void setPersistentState(C modelState); /** * Gets the class used for JAXB serialization. * @return class used as JAXBContext */ protected abstract Class<C> getJAXBClass(); private JAXBContext getFromCache(Class<?> unMarshalledClazz) throws JAXBException { JAXBContext jc = marshalCache.get(unMarshalledClazz); if (jc == null) { jc = JAXBContext.newInstance(unMarshalledClazz); marshalCache.put(unMarshalledClazz, jc); } return jc; } /** * Unmarshals the supplied bytes and return the unmarshalled object. * * @param unMarshalledClazz * the class of the object to be created from the unmarshalling * operation * @param state * the string that contains the marshalled data. * @return the object created from unmarshalling the model role data. */ private C unmarshal(Class<C> unMarshalledClazz, String state) throws DataBindingException, JAXBException, UnsupportedEncodingException { InputStream is = new ByteArrayInputStream(state.getBytes("ASCII")); JAXBContext jc = getFromCache(unMarshalledClazz); Unmarshaller u = jc.createUnmarshaller(); return unMarshalledClazz.cast(u.unmarshal(is)); } /** * Marshals the data and return the marshalled String. The object is * converted between byte and Unicode characters using the named encoding * "UTF-8". * * @param toBeMarshalled * the object whose data is to be marshalled. */ private String marshal(C toBeMarshalled) throws JAXBException, UnsupportedEncodingException { ByteArrayOutputStream out = new ByteArrayOutputStream(); Class<?> clazz = toBeMarshalled.getClass(); JAXBContext ctxt = getFromCache(clazz); Marshaller marshaller = ctxt.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_ENCODING, "ASCII"); marshaller.marshal(toBeMarshalled, out); return out.toString("ASCII"); } }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_JAXBModelStatePersistence.java
294
public class JAXBModelStatePersistenceTest { @Test public void testRoundTripSerialization() { final String expectedValue = "abc"; JAXBExample je = new JAXBExample(); je.setValue(expectedValue); ModelStatePersister msp = new ModelStatePersister(); msp.example = je; String state = msp.getModelState(); msp.setModelState(state); JAXBExample roundTripValue = msp.example; Assert.assertNotSame(roundTripValue, je); Assert.assertEquals(roundTripValue.getValue(), expectedValue); } @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public static class JAXBExample { private String value; /** * @return the value */ public String getValue() { return value; } /** * @param value the value to set */ public void setValue(String value) { this.value = value; } } public static class ModelStatePersister extends JAXBModelStatePersistence<JAXBExample> { public JAXBExample example; @Override protected JAXBExample getStateToPersist() { return example; } @Override protected void setPersistentState(JAXBExample modelState) { example = modelState; } @Override protected Class<JAXBExample> getJAXBClass() { return JAXBExample.class; } } }
false
mctcore_src_test_java_gov_nasa_arc_mct_components_JAXBModelStatePersistenceTest.java
295
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public static class JAXBExample { private String value; /** * @return the value */ public String getValue() { return value; } /** * @param value the value to set */ public void setValue(String value) { this.value = value; } }
false
mctcore_src_test_java_gov_nasa_arc_mct_components_JAXBModelStatePersistenceTest.java
296
public static class ModelStatePersister extends JAXBModelStatePersistence<JAXBExample> { public JAXBExample example; @Override protected JAXBExample getStateToPersist() { return example; } @Override protected void setPersistentState(JAXBExample modelState) { example = modelState; } @Override protected Class<JAXBExample> getJAXBClass() { return JAXBExample.class; } }
false
mctcore_src_test_java_gov_nasa_arc_mct_components_JAXBModelStatePersistenceTest.java
297
public interface ModelStatePersistence { /** * Gets the model state for the component. * @return model state of the component */ String getModelState(); /** * Sets the model state of the component. * @param state that was persisted */ void setModelState(String state); }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_ModelStatePersistence.java
298
public interface Placeholder { /** * In lieu of real value, a Placeholder can deliver some substitute value * as a string. * @return a string containing the substitute value */ public String getPlaceholderValue(); }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_Placeholder.java
299
public class PropertyDescriptor { /** * Defines the supported visual control types. */ public enum VisualControlDescriptor { /**A label visual component such as a JLabel. Its value is immutable. */ Label, /**A text field component such as a JTextField, modified using getValueAsText and setValueAsText. Initialized using getValueAsText. */ TextField, /**A check box component such as a JCheckBox. It is initialized and modified using getValue and setValue of type Boolean. */ CheckBox, /**A combo box component such as a JComboBox, initialized and modified using getValue and setValue. Its enumerated list is populated using getTags. */ ComboBox; }; private boolean isFieldMutable = false; private String shortDescription; private VisualControlDescriptor visualControlDescriptor; private PropertyEditor<?> propertyEditor; /** * Constructs a descriptor. This is typically used for an mutable field. * @param shortDescription the label text * @param propertyEditor the property editor * @param visualControlDescriptor specification of the visual component that will be used to render the value */ public PropertyDescriptor(String shortDescription, PropertyEditor<?> propertyEditor, VisualControlDescriptor visualControlDescriptor) { super(); this.shortDescription = shortDescription; this.propertyEditor = propertyEditor; this.visualControlDescriptor = visualControlDescriptor; } /** * Get the property editor. * @return the property editor */ public PropertyEditor<?> getPropertyEditor() { return propertyEditor; } /** * Determines mutability. * @return true if this field is editable */ public boolean isFieldMutable() { return isFieldMutable; } /** * Specify mutability. * @param isFieldMutable whether this field is editable */ public void setFieldMutable(boolean isFieldMutable) { this.isFieldMutable = isFieldMutable; } /** * Get a short description of the property. * @return description */ public String getShortDescription() { return shortDescription; } /** * Get a description of a visual control (such as a Swing component). * @return visual control description */ public VisualControlDescriptor getVisualControlDescriptor() { return visualControlDescriptor; } }
false
mctcore_src_main_java_gov_nasa_arc_mct_components_PropertyDescriptor.java