diff --git a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientLeaf.java b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientLeaf.java index 2c0260bfe9..ed50d91567 100644 --- a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientLeaf.java +++ b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientLeaf.java @@ -52,9 +52,9 @@ public AlarmClientLeaf(final String parent_path, final String name) * a detached copy is used to send the request. * @return {@link AlarmClientLeaf} with same configuration, but no parent */ - public AlarmClientLeaf createDetachedCopy() + public AlarmClientLeaf createDetachedCopy(final String newName) { - final AlarmClientLeaf pv = new AlarmClientLeaf(null, getName()); + final AlarmClientLeaf pv = new AlarmClientLeaf(null, newName); pv.setDescription(getDescription()); pv.setEnabled(getEnabled()); pv.setLatching(isLatching()); @@ -69,6 +69,14 @@ public AlarmClientLeaf createDetachedCopy() return pv; } + /** When requesting a configuration update, + * a detached copy is used to send the request. + * @return {@link AlarmClientLeaf} with same configuration, but no parent + */ + public AlarmClientLeaf createDetachedCopy() { + return createDetachedCopy(getName()); + } + /** @return Return description */ @Override public String getDescription() diff --git a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientNode.java b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientNode.java index e5ec601250..315238ab63 100644 --- a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientNode.java +++ b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientNode.java @@ -7,6 +7,7 @@ *******************************************************************************/ package org.phoebus.applications.alarm.client; +import java.util.ArrayList; import java.util.concurrent.CopyOnWriteArrayList; import org.phoebus.applications.alarm.model.AlarmTreeItemWithState; @@ -27,4 +28,17 @@ public AlarmClientNode(final String parent_path, final String name) super(parent_path, name, new CopyOnWriteArrayList<>()); state = new BasicState(SeverityLevel.OK); } + + /** @return {@link AlarmClientNode} with same configuration, but no parent or children */ + public AlarmClientNode createDetachedCopy() + { + final AlarmClientNode node = new AlarmClientNode(null, getName()); + + node.setGuidance(new ArrayList<>(getGuidance())); + node.setDisplays(new ArrayList<>(getDisplays())); + node.setCommands(new ArrayList<>(getCommands())); + node.setActions(new ArrayList<>(getActions())); + + return node; + } } diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/Messages.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/Messages.java index fe94645f22..55ea1d10a0 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/Messages.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/Messages.java @@ -22,6 +22,15 @@ public class Messages public static String Annunciator; public static String commands; public static String configure; + public static String cutPasteAcrossConfigs; + public static String cutPasteIntoChild; + public static String createAlarmsDialogTitle; + public static String createAlarmsDialogHint; + public static String createAlarmFailed; + public static String creatingAlarms; + public static String createNodeDialogTitle; + public static String createNodeDialogHeader; + public static String createNodeFailed; public static String delayTooltip0; public static String delayTooltip1; public static String delayTooltip2; @@ -36,6 +45,8 @@ public class Messages public static String displays; public static String enableAlarmFailed; public static String enableAlarms; + public static String enterNameForDuplicate; + public static String enterNewName; public static String guidance; public static String headerAlreadyDisabled; public static String headerAlreadyEnabled; @@ -43,13 +54,25 @@ public class Messages public static String headerConfirmDisableWithEnableDate; public static String headerConfirmEnable; public static String indefinitely; + public static String manageItems; public static String MenuPath; public static String moveItemFailed; + public static String nameCannotBeEmpty; + public static String nodeAlreadyExists; + public static String nodePvsAlreadyExist; + public static String pasteItem; + public static String pasteItemFailed; public static String promptTitle; + public static String pvAlreadyExists; + public static String pvEnteredMoreThanOnce; + public static String renameItem; + public static String renameDialogLabel; + public static String renameDialogTitle; public static String removeComponentFailed; public static String renameItemFailed; public static String search; public static String searchByPv; + public static String specificPvAlreadyExists; public static String totalPVs; public static String unacknowledgeFailed; public static String withEnableDate; diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AddComponentAction.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AddComponentAction.java deleted file mode 100644 index 6493b9ab9b..0000000000 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AddComponentAction.java +++ /dev/null @@ -1,278 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2018-2022 Oak Ridge National Laboratory. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - *******************************************************************************/ -package org.phoebus.applications.alarm.ui.tree; - -import java.util.List; - -import org.phoebus.applications.alarm.client.AlarmClient; -import org.phoebus.applications.alarm.model.AlarmTreeItem; -import org.phoebus.applications.alarm.model.AlarmTreeLeaf; -import org.phoebus.applications.alarm.ui.Messages; -import org.phoebus.framework.jobs.JobManager; -import org.phoebus.ui.autocomplete.PVAutocompleteMenu; -import org.phoebus.ui.dialog.DialogHelper; -import org.phoebus.ui.dialog.ExceptionDetailsErrorDialog; -import org.phoebus.ui.javafx.ImageCache; - -import javafx.application.Platform; -import javafx.scene.Node; -import javafx.scene.control.Alert; -import javafx.scene.control.Alert.AlertType; -import javafx.scene.control.ButtonType; -import javafx.scene.control.Dialog; -import javafx.scene.control.Label; -import javafx.scene.control.MenuItem; -import javafx.scene.control.RadioButton; -import javafx.scene.control.TextArea; -import javafx.scene.control.ToggleGroup; -import javafx.scene.control.Tooltip; -import javafx.scene.layout.GridPane; -import javafx.scene.layout.HBox; -import javafx.scene.layout.Priority; - -/** Action that adds a new item to the alarm tree configuration - * @author Kay Kasemir - */ -@SuppressWarnings("nls") -class AddComponentAction extends MenuItem -{ - private static class AddComponentDialog extends Dialog - { - private final TextArea name = new TextArea(); - private final Label message = new Label(); - private final RadioButton type_node = new RadioButton("Node"), - type_pv = new RadioButton("PV/s"); - - public AddComponentDialog(final AlarmTreeItem parent) - { - final GridPane layout = new GridPane(); - // layout.setGridLinesVisible(true); - layout.setHgap(5); - layout.setVgap(5); - - layout.add(new Label("Type:"), 0, 0); - - final ToggleGroup types = new ToggleGroup(); - type_node.setToggleGroup(types); - type_node.setTooltip(new Tooltip("Create a new node in the alarm configuration hierachy")); - - type_pv.setToggleGroup(types); - type_pv.setTooltip(new Tooltip("Add a PV or a list of space-separated PVs to the alarm configuration")); - - layout.add(new HBox(5, type_node, type_pv), 1, 0); - - // For 'main' and the 'subsystem' level suggest adding another node. - // Further below, suggest PV - if (parent.getParent() == null || - parent.getParent().getParent() == null) - type_node.setSelected(true); - else - type_pv.setSelected(true); - - layout.add(new Label("Name:"), 0, 1); - name.setTooltip(new Tooltip("Name of new node or PV")); - GridPane.setHgrow(name, Priority.ALWAYS); - layout.add(name, 1, 1); - - layout.add(message, 1, 2); - - // Update hint as user types or selects type - types.selectedToggleProperty().addListener((prop, old, value) -> checkName(name.getText())); - name.textProperty().addListener( (prop, old, value) -> checkName(value)); - - setTitle("Add Component to " + parent.getPathName()); - getDialogPane().setContent(layout); - getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL); - setResizable(true); - - layout.setPrefWidth(600); - - setResultConverter(button -> - button == ButtonType.OK ? name.getText() : null); - - // Initial focus on name - Platform.runLater(() -> name.requestFocus()); - - type_pv.selectedProperty().addListener(p -> - { - updateAutocompletion(); - // Selecting a type then also focuses on the name - Platform.runLater(() -> name.requestFocus()); - }); - // Initial setting - updateAutocompletion(); - } - - /** Add or remove PV name completion support based on type_pv */ - private void updateAutocompletion() - { - // Always OK to detach - PVAutocompleteMenu.INSTANCE.detachField(name); - // If PV names are required, attach - if (type_pv.isSelected()) - PVAutocompleteMenu.INSTANCE.attachField(name); - } - - private void checkName(final String name) - { - if (isPV()) - { - final List names = splitNames(name); - if (names.size() <= 1) - message.setText("Enter one or more PV names, separated by spaces"); - else - message.setText("Adding " + names.size() + " PVs"); - } - else - message.setText("Add name of new Node"); - } - - public boolean isPV() - { - return type_pv.isSelected(); - } - - // Allowing not just space as mentioned in tooltip and message, but also comma or semicolon - public static List splitNames(final String names) - { - return List.of(names.split("[\\s;]+")); - } - } - - /** @param node Node to position dialog - * @param model Model where new component is added - * @param parent Parent item in alarm tree - */ - public AddComponentAction(final Node node, final AlarmClient model, final AlarmTreeItem parent) - { - super("Add Component", ImageCache.getImageView(ImageCache.class, "/icons/add.png")); - setOnAction(event -> - { - final AddComponentDialog dialog = new AddComponentDialog(parent); - DialogHelper.positionDialog(dialog, node, -100, -50); - final String new_name = dialog.showAndWait().orElse(null); - if (new_name == null || new_name.isBlank()) - return; - - // Add in background thread - JobManager.schedule(getText(), monitor -> - { - final AlarmTreeItem root = getRoot(parent); - if (dialog.isPV()) - { - final List new_names = AddComponentDialog.splitNames(new_name); - for (String pv : new_names) - { - // Check for item of same name at that level - if (haveExistingItem(node, parent, pv)) - break; - // Check for duplicate PV, anywhere in alarm tree - final String existing = findPV(root, pv); - if (existing == null) - try { - model.addPV(parent.getPathName(), pv); - } catch (Exception e) { - ExceptionDetailsErrorDialog.openError(Messages.error, - Messages.addComponentFailed, - e); - } - else - { - Platform.runLater(() -> - { - final Alert error = new Alert(AlertType.ERROR); - error.setTitle(getText()); - error.setHeaderText("Cannot add PV " + pv); - error.setContentText("Duplicate for " + existing); - error.setResizable(true); - DialogHelper.positionDialog(error, node, -100, -50); - error.showAndWait(); - }); - break; - } - } - } - else - { - // Dialog allows entering several space- or line-separated names - // to support a list of PVs. - // For components, squash that into one new, trimmed name - final String comp_name = new_name.replace('\r', ' ') - .replace('\n', ' ') - .replaceAll(" +", " ") - .trim(); - if (! haveExistingItem(node, parent, comp_name)) { - try { - model.addComponent(parent.getPathName(), comp_name); - } catch (Exception e) { - ExceptionDetailsErrorDialog.openError(Messages.error, - Messages.addComponentFailed, - e); - } - } - } - }); - }); - } - - /** @param node Node to position dialog - * @param parent Parent in alarm tree - * @param new_name New name to add to parent - * @return true if parent already has item of that name, - * and alert dialog has been scheduled. - */ - private boolean haveExistingItem(final Node node, final AlarmTreeItem parent, final String new_name) - { - // Check for name name on that level - if (parent.getChild(new_name) == null) - return false; - Platform.runLater(() -> - { - final Alert error = new Alert(AlertType.ERROR); - error.setTitle(getText()); - error.setHeaderText("Cannot add " + new_name); - error.setContentText("Duplicate for existing item of same name at " + parent.getPathName()); - error.setResizable(true); - DialogHelper.positionDialog(error, node, -100, -50); - error.showAndWait(); - }); - return true; - } - - /** @param item {@link AlarmTreeItem} - * @return Root element of alarm tree - */ - private AlarmTreeItem getRoot(AlarmTreeItem item) - { - AlarmTreeItem root = item; - while (root.getParent() != null) - root = root.getParent(); - return root; - } - - /** @param item Alarm tree item (initially root) where to search for PV - * @param pv Name of PV - * @return PV or null when not found - */ - private String findPV(final AlarmTreeItem item, final String pv) - { - if (item instanceof AlarmTreeLeaf) - { - if (item.getName().equals(pv)) - return item.getPathName(); - } - else - for (AlarmTreeItem sub : item.getChildren()) - { - final String found = findPV(sub, pv); - if (found != null) - return found; - } - return null; - } -} diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeHelper.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeHelper.java index 25e77114a6..858e50b399 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeHelper.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeHelper.java @@ -18,10 +18,7 @@ import org.phoebus.applications.alarm.model.AlarmTreeItem; import org.phoebus.applications.alarm.model.AlarmTreePath; import org.phoebus.applications.alarm.ui.Messages; -import org.phoebus.ui.dialog.DialogHelper; -import javafx.scene.control.TextInputDialog; -import javafx.scene.control.TreeView; import org.phoebus.util.time.TimestampFormats; /** @author Evan Smith @@ -56,28 +53,6 @@ public static void rebuildTree(AlarmClient model, AlarmTreeItem parent, Strin } } - /** Prompt the screen with a dialog box. - * @param title Title string of the dialog box. - * @param header Header string of the dialog box. - * @param default_text Default text contents of dialog box. - * @param node Node where the dialog box will be located. - * @return String The entered string or null if the entry was empty. - */ - public static String prompt(String title, String header, final String default_text, final TreeView> node) - { - // Prompt for new name - final TextInputDialog prompt = new TextInputDialog(default_text); - DialogHelper.positionDialog(prompt, node, -200, -100); - prompt.setTitle(title); - prompt.setHeaderText(header); - prompt.getDialogPane().setPrefWidth(500); - prompt.setResizable(true); - final String input = prompt.showAndWait().orElse(""); - if (input.isEmpty()) - return null; - return input; - } - /** Validate the passed path string by checking if the path name is valid. * *

A path name is considered valid if the path to the item's new location exists in the tree, @@ -153,6 +128,18 @@ private static Stream streamLeafItems(final AlarmTreeItem al } } + /** + * Collects the names of {@link AlarmClientLeaf}s items. + * @param root The start node from where to get {@link AlarmClientLeaf}s. If this is an {@link AlarmClientLeaf}, it + * will be returned as the sole item in the {@link Set} + * @return A {@link Set} of the names of all {@link AlarmClientLeaf}s. + */ + public static Set getLeafNames(final AlarmTreeItem root) { + return streamLeafItems(root) + .map(AlarmTreeItem::getName) + .collect(Collectors.toSet()); + } + /** * * @param items {@link List} of {@link AlarmTreeItem}s that may be a mix of leaves and non-leaves, e.g. a user diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeView.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeView.java index 0025cd5954..adc1b9b0e1 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeView.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeView.java @@ -24,7 +24,13 @@ import java.util.logging.Level; import java.util.stream.Collectors; +import javafx.beans.property.SimpleBooleanProperty; +import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; +import javafx.collections.ListChangeListener; +import javafx.event.ActionEvent; +import javafx.event.EventHandler; +import javafx.scene.control.Menu; import javafx.scene.control.TextField; import org.phoebus.applications.alarm.AlarmSystem; import org.phoebus.applications.alarm.client.AlarmClient; @@ -152,8 +158,24 @@ public class AlarmTreeView extends BorderPane implements AlarmClientListener items.remove(changing); }); + /** + * List of paths to select when the item comes in from Kafka. This allows + * us to automatically select items as the user adds them. + * + * The list is necessary because there is a delay between the user clicking + * the button to add a new item, and the message with the new item arriving + * at Kafka and then round-tripping back to the client and being displayed + * in the UI. + */ + private final ObservableList incoming_paths_to_select = FXCollections.observableList(new ArrayList<>()); + + private final List>> filterExemptions = new ArrayList<>(); + private final TextField searchBox; + private static final SimpleObjectProperty> clipboard = new SimpleObjectProperty<>(null); + private static final SimpleBooleanProperty isClipboardCut = new SimpleBooleanProperty(false); + // Javadoc for TreeItem shows example for overriding isLeaf() and getChildren() // to dynamically create TreeItem as TreeView requests information. // @@ -180,6 +202,14 @@ public AlarmTreeView(final AlarmClient model, final String itemName) if (model.isRunning()) throw new IllegalStateException(); + incoming_paths_to_select.addListener((ListChangeListener) change -> { + while (change.next()) { + if (change.wasAdded()) { + tree_view.getSelectionModel().clearSelection(); + } + } + }); + changing.setTextFill(Color.WHITE); changing.setBackground(new Background(new BackgroundFill(Color.BLUE, CornerRadii.EMPTY, Insets.EMPTY))); @@ -200,6 +230,7 @@ public AlarmTreeView(final AlarmClient model, final String itemName) createContextMenu(); addClickSupport(); addDragSupport(); + addKeyboardSupport(); if (AlarmSystem.alarm_tree_startup_ms <= 0) { @@ -275,14 +306,19 @@ private ToolBar createToolbar(TextField searchBox) final Button searchButton = new Button(Messages.search); - searchButton.setOnAction(event -> propagateVisibilityDownTree(tree_view.getRoot())); - searchBox.setOnAction(event -> propagateVisibilityDownTree(tree_view.getRoot())); // act as if button pressed when enter pressed + final Runnable onFilterUpdated = () -> { + filterExemptions.clear(); + propagateVisibilityDownTree(tree_view.getRoot()); + }; + + searchButton.setOnAction(_ -> onFilterUpdated.run()); + searchBox.setOnAction(_ -> onFilterUpdated.run()); // act as if button pressed when enter pressed searchBox.textProperty().addListener(_ -> { // act as if button pressed when text box cleared if (searchBox.getText().isEmpty()) { - propagateVisibilityDownTree(tree_view.getRoot()); + onFilterUpdated.run(); } }); @@ -361,7 +397,9 @@ else if (!shouldDisplay && currentParent != null) private boolean shouldDisplay(final TreeItem> item) { - return (searchBox.getText().isEmpty() || !item.getChildren().isEmpty()) + return filterExemptions.contains(item) + || searchBox.getText().isEmpty() + || !item.getChildren().isEmpty() || item.getValue() instanceof AlarmClientLeaf && item.getValue().getName().toLowerCase().contains(searchBox.getText().toLowerCase()); } @@ -519,13 +557,38 @@ public void itemAdded(final AlarmTreeItem item) final AlarmTreeItem model_parent = item.getParent(); final TreeItem> view_parent = path2view.get(model_parent.getPathName()); - if (view_parent == null) { + if (view_parent == null) + { dumpTree(tree_view.getRoot()); throw new IllegalStateException("Missing parent view item for " + item.getPathName()); } final TreeItem> view_item = createViewItem(item); + final boolean is_incoming_item = incoming_paths_to_select.remove(item.getPathName()); + propagateVisibilityUpTree(view_item); + + if (is_incoming_item) { + if (view_item.getParent() == null) { + // User has added an item, but it's hidden by the filter which + // can be extremely confusing, so we make an exception for the + // new item (which is cleared next time the filter is updated) + filterExemptions.add(view_item); + propagateVisibilityUpTree(view_item); + } + + view_item.getParent().setExpanded(true); + tree_view.getSelectionModel().select(view_item); + + // JavaFX's selection/focus model continue to cause issues... In this + // case, selecting the item above does not focus it and due to how + // focusing works off indices, the incorrect item is selected. We + // manually defocus by passing -1 to avoid this problem (no, trying + // to select the same index still as the selected item does not work + // as expected. I am not sure why) + tree_view.getFocusModel().focus(-1); + } + done.countDown(); }); @@ -554,6 +617,11 @@ public void itemRemoved(final AlarmTreeItem item) { indicateChange(); + // Clear clipboard if we are removing clipboard's item + if (clipboard.get() != null && clipboard.get().getPathName().equals(item.getPathName())) { + clipboard.set(null); + } + // Remove item and all sub-items from model2ui final TreeItem> view_item = removeViewItems(item); if (view_item == null) @@ -705,32 +773,47 @@ private void createContextMenu() if (AlarmUI.mayConfigure(model)) { - if (selection.size() <= 0) + final Menu manageMenu = new Menu(); + manageMenu.setText(Messages.manageItems); + manageMenu.setGraphic(ImageCache.getImageView(AlarmUI.class, "/icons/edit.png")); + final ObservableList manageMenuItems = manageMenu.getItems(); + + if (selection.size() <= 0) { // Add first item to empty config - menu_items.add(new AddComponentAction(tree_view, model, model.getRoot())); + manageMenuItems.add(new CreateNodeAction(tree_view, model, model.getRoot(), incoming_paths_to_select)); + manageMenuItems.add(new CreateAlarmsAction(tree_view, model, model.getRoot(), incoming_paths_to_select)); + } else if (selection.size() == 1) { final AlarmTreeItem item = selection.get(0); - menu_items.add(new ConfigureComponentAction(tree_view, model, item)); - menu_items.add(new SeparatorMenuItem()); + final AlarmTreeItem parent = item instanceof AlarmClientNode ? item : item.getParent(); + final TreeItem> viewParent = path2view.get(parent.getPathName()); - if (item instanceof AlarmClientNode) - menu_items.add(new AddComponentAction(tree_view, model, item)); + manageMenuItems.add(new CreateNodeAction(tree_view, model, parent, incoming_paths_to_select)); + manageMenuItems.add(new CreateAlarmsAction(tree_view, model, parent, incoming_paths_to_select)); + manageMenuItems.add(new ConfigureComponentAction(tree_view, model, item)); - menu_items.add(new RenameTreeItemAction(tree_view, model, item)); + manageMenuItems.add(new CopyItemAction(tree_view, clipboard, isClipboardCut, item)); + manageMenuItems.add(new CutItemAction(tree_view, clipboard, isClipboardCut, item)); + manageMenuItems.add(new PasteItemAction(tree_view, model, viewParent, clipboard, isClipboardCut.get(), incoming_paths_to_select)); + + manageMenuItems.add(new RenameTreeItemAction(tree_view, model, item, incoming_paths_to_select)); if (item instanceof AlarmClientLeaf) - menu_items.add(new DuplicatePVAction(tree_view, model, (AlarmClientLeaf) item)); + manageMenuItems.add(new DuplicatePVAction(tree_view, model, (AlarmClientLeaf) item, incoming_paths_to_select)); - menu_items.add(new MoveTreeItemAction(tree_view, model, item)); + manageMenuItems.add(new MoveTreeItemAction(tree_view, model, item, incoming_paths_to_select)); } + if (selection.size() >= 1) { - menu_items.add(new EnableComponentAction(tree_view, model, selection)); - menu_items.add(new DisableAction(tree_view, model, selection)); - menu_items.add(new RemoveComponentAction(tree_view, model, selection)); + manageMenuItems.add(new EnableComponentAction(tree_view, model, selection)); + manageMenuItems.add(new DisableAction(tree_view, model, selection)); + manageMenuItems.add(new RemoveComponentAction(tree_view, model, selection)); } + + menu_items.add(manageMenu); } menu_items.add(new SeparatorMenuItem()); @@ -799,6 +882,44 @@ private void addDragSupport() }); } + private void addKeyboardSupport() + { + tree_view.setOnKeyPressed(event -> { + final TreeItem> selectedViewItem = tree_view.getSelectionModel().getSelectedItem(); + final List> selection = tree_view.getSelectionModel() + .getSelectedItems() + .stream() + .map(TreeItem::getValue) + .collect(Collectors.toList()); + + switch (event.getCode()) { + case ESCAPE -> { + tree_view.getSelectionModel().clearSelection(); + } + case DELETE -> { + new RemoveComponentAction(tree_view, model, selection).fire(); + } + case C -> { + if (event.isControlDown() && selectedViewItem != null) { + new CopyItemAction(tree_view, clipboard, isClipboardCut, selectedViewItem.getValue()).fire(); + } + } + case X -> { + if (event.isControlDown() && selectedViewItem != null) { + new CutItemAction(tree_view, clipboard, isClipboardCut, selectedViewItem.getValue()).fire(); + } + } + case V -> { + if (event.isControlDown() && selectedViewItem != null) { + final TreeItem> parent = selectedViewItem.getValue() instanceof AlarmClientNode ? selectedViewItem : selectedViewItem.getParent(); + new PasteItemAction(tree_view, model, parent, clipboard, isClipboardCut.get(), incoming_paths_to_select).fire(); + } + } + case null, default -> {} + } + }); + } + private static void dumpTree(final TreeItem> item) { final ObservableList>> children = item.getChildren(); diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CopyItemAction.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CopyItemAction.java new file mode 100644 index 0000000000..7c8a9ff00e --- /dev/null +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CopyItemAction.java @@ -0,0 +1,28 @@ +package org.phoebus.applications.alarm.ui.tree; + +import javafx.beans.property.SimpleBooleanProperty; +import javafx.beans.property.SimpleObjectProperty; +import javafx.scene.Node; +import javafx.scene.control.MenuItem; +import org.phoebus.applications.alarm.AlarmSystem; +import org.phoebus.applications.alarm.model.AlarmTreeItem; +import org.phoebus.ui.javafx.ImageCache; + + +@SuppressWarnings("nls") +public class CopyItemAction extends MenuItem +{ + /** @param node Node to position dialog + * @param clipboard Property containing the clipboard + * @param isCut Property indicating whether the clipboard item should be removed when pasted + * @param item Parent item in alarm tree + */ + public CopyItemAction(final Node node, final SimpleObjectProperty> clipboard, final SimpleBooleanProperty isCut, final AlarmTreeItem item) + { + super("Copy Item", ImageCache.getImageView(AlarmSystem.class, "/icons/copy.png")); + setOnAction(event -> { + clipboard.set(item); + isCut.set(false); + }); + } +} diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CreateAlarmsAction.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CreateAlarmsAction.java new file mode 100644 index 0000000000..9a7d5cabe3 --- /dev/null +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CreateAlarmsAction.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2018-2022 Oak Ridge National Laboratory. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + *******************************************************************************/ +package org.phoebus.applications.alarm.ui.tree; + +import javafx.collections.ObservableList; +import javafx.scene.Node; +import javafx.scene.control.MenuItem; +import org.phoebus.applications.alarm.client.AlarmClient; +import org.phoebus.applications.alarm.model.AlarmTreeItem; +import org.phoebus.applications.alarm.model.AlarmTreePath; +import org.phoebus.applications.alarm.ui.Messages; +import org.phoebus.framework.jobs.JobManager; +import org.phoebus.ui.dialog.DialogHelper; +import org.phoebus.ui.dialog.ExceptionDetailsErrorDialog; +import org.phoebus.ui.javafx.ImageCache; + +import java.util.List; + + +@SuppressWarnings("nls") +class CreateAlarmsAction extends MenuItem +{ + + /** @param node Node to position dialog + * @param model Model where new PV is added + * @param parent Parent item in alarm tree + */ + public CreateAlarmsAction(final Node node, final AlarmClient model, final AlarmTreeItem parent, final ObservableList incoming_paths_to_select) + { + super("Create Alarm(s)", ImageCache.getImageView(ImageCache.class, "/icons/add.png")); + setOnAction(event -> + { + final CreateAlarmsDialog dialog = new CreateAlarmsDialog(model); + DialogHelper.positionDialog(dialog, node, -100, -50); + final List pvs = dialog.showAndWait().orElse(null); + if (pvs == null) { + return; + } + + for (final String name : pvs) { + incoming_paths_to_select.add(AlarmTreePath.makePath(parent.getPathName(), name)); + } + + JobManager.schedule(getText(), monitor -> { + for (final String name : pvs) { + try { + model.addPV(parent.getPathName(), name); + } catch (final Exception ex) { + ExceptionDetailsErrorDialog.openError(Messages.error, Messages.createAlarmFailed, ex); + } + } + }); + }); + } +} diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CreateAlarmsDialog.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CreateAlarmsDialog.java new file mode 100644 index 0000000000..d0f667888e --- /dev/null +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CreateAlarmsDialog.java @@ -0,0 +1,94 @@ +package org.phoebus.applications.alarm.ui.tree; + +import javafx.scene.control.ButtonType; +import javafx.scene.control.Dialog; +import javafx.scene.control.Label; +import javafx.scene.control.TextArea; +import javafx.scene.layout.VBox; +import javafx.scene.paint.Color; +import org.phoebus.applications.alarm.client.AlarmClient; +import org.phoebus.applications.alarm.ui.Messages; +import org.phoebus.ui.autocomplete.MultiplePVAutocompleteMenu; + +import java.text.MessageFormat; +import java.util.List; +import java.util.Set; +import java.util.function.Consumer; + + +public class CreateAlarmsDialog extends Dialog> { + + public CreateAlarmsDialog(final AlarmClient model) { + super(); + + setTitle(Messages.createAlarmsDialogTitle); + + getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL); + + final Label hintText = new Label(Messages.createAlarmsDialogHint); + + final TextArea textArea = new TextArea(); + textArea.setPrefWidth(800); + + final Label errorLabel = new Label(); + errorLabel.setTextFill(Color.RED); + final Consumer updateError = newError -> { + errorLabel.setText(newError); + getDialogPane().lookupButton(ButtonType.OK).setDisable(newError != null); + }; + + final Label pvCountLabel = new Label(); + pvCountLabel.setText(MessageFormat.format(Messages.creatingAlarms, 0)); + + final Set allPvs = AlarmTreeHelper.getLeafNames(model.getRoot()); + textArea.textProperty().addListener(_ -> { + final List pvs = splitNames(textArea.getText()); + + pvCountLabel.setText(MessageFormat.format(Messages.creatingAlarms, pvs.size())); + + // Disable OK if no alarms being added + if (pvs.isEmpty()) { + updateError.accept(""); + return; + } + + // Show error and disable OK if any PV already exists in the config + boolean ok = true; + for (final String pv : pvs) { + if (allPvs.contains(pv)) { + ok = false; + updateError.accept(MessageFormat.format(Messages.specificPvAlreadyExists, pv)); + break; + } + if (pvs.stream().filter(x -> x.equals(pv)).count() > 1) { + ok = false; + updateError.accept(MessageFormat.format(Messages.pvEnteredMoreThanOnce, pv)); + break; + } + } + if (ok) { + updateError.accept(null); + } + }); + + getDialogPane().setContent(new VBox(hintText, textArea, pvCountLabel, errorLabel)); + setResultConverter(button -> { + if (button == ButtonType.OK) { + return splitNames(textArea.getText()); + } + return null; + }); + + MultiplePVAutocompleteMenu.INSTANCE.attachField(textArea); + + updateError.accept(""); // disable OK by default as text field is empty + + textArea.requestFocus(); + } + + private static List splitNames(final String names) { + return names.isEmpty() + ? List.of() + : List.of(MultiplePVAutocompleteMenu.DELIMITER_PATTERN.split(names)); + } +} diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CreateNodeAction.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CreateNodeAction.java new file mode 100644 index 0000000000..7d8bd353d4 --- /dev/null +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CreateNodeAction.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (c) 2018-2022 Oak Ridge National Laboratory. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + *******************************************************************************/ +package org.phoebus.applications.alarm.ui.tree; + +import javafx.collections.ObservableList; +import javafx.scene.Node; +import javafx.scene.control.MenuItem; +import org.phoebus.applications.alarm.client.AlarmClient; +import org.phoebus.applications.alarm.model.AlarmTreeItem; +import org.phoebus.applications.alarm.model.AlarmTreePath; +import org.phoebus.applications.alarm.ui.Messages; +import org.phoebus.framework.jobs.JobManager; +import org.phoebus.ui.dialog.DialogHelper; +import org.phoebus.ui.dialog.ExceptionDetailsErrorDialog; +import org.phoebus.ui.javafx.ImageCache; + + +@SuppressWarnings("nls") +class CreateNodeAction extends MenuItem +{ + + /** @param node Node to position dialog + * @param model Model where new component is added + * @param parent Parent item in alarm tree + */ + public CreateNodeAction(final Node node, final AlarmClient model, final AlarmTreeItem parent, final ObservableList incoming_paths_to_select) + { + super("Create Node", ImageCache.getImageView(ImageCache.class, "/icons/add.png")); + setOnAction(event -> + { + final NameDialog dialog = new NameDialog(model, parent, "", true); + dialog.setTitle(Messages.createNodeDialogTitle); + dialog.setHeaderText(Messages.createNodeDialogHeader); + DialogHelper.positionDialog(dialog, node, -100, -50); + final String name = dialog.showAndWait().orElse(null); + if (name == null) { + return; + } + + String path = AlarmTreePath.makePath(parent.getPathName(), name); + + incoming_paths_to_select.add(path); + + JobManager.schedule(getText(), monitor -> { + try { + model.addComponent(parent.getPathName(), name); + } catch (final Exception ex) { + ExceptionDetailsErrorDialog.openError(Messages.error, Messages.createNodeFailed, ex); + } + }); + }); + } +} diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CutItemAction.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CutItemAction.java new file mode 100644 index 0000000000..4a7057f56a --- /dev/null +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/CutItemAction.java @@ -0,0 +1,28 @@ +package org.phoebus.applications.alarm.ui.tree; + +import javafx.beans.property.SimpleBooleanProperty; +import javafx.beans.property.SimpleObjectProperty; +import javafx.scene.Node; +import javafx.scene.control.MenuItem; +import org.phoebus.applications.alarm.AlarmSystem; +import org.phoebus.applications.alarm.model.AlarmTreeItem; +import org.phoebus.ui.javafx.ImageCache; + + +@SuppressWarnings("nls") +public class CutItemAction extends MenuItem +{ + /** @param node Node to position dialog + * @param clipboard Property containing the clipboard + * @param isCut Property indicating whether the clipboard item should be removed when pasted + * @param item Parent item in alarm tree + */ + public CutItemAction(final Node node, final SimpleObjectProperty> clipboard, final SimpleBooleanProperty isCut, final AlarmTreeItem item) + { + super("Cut Item", ImageCache.getImageView(AlarmSystem.class, "/icons/cut.png")); + setOnAction(event -> { + clipboard.set(item); + isCut.set(true); + }); + } +} diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/DuplicatePVAction.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/DuplicatePVAction.java index d93214df08..9a3d1883e5 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/DuplicatePVAction.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/DuplicatePVAction.java @@ -8,10 +8,12 @@ package org.phoebus.applications.alarm.ui.tree; import javafx.application.Platform; +import javafx.collections.ObservableList; import org.phoebus.applications.alarm.AlarmSystem; import org.phoebus.applications.alarm.client.AlarmClient; import org.phoebus.applications.alarm.client.AlarmClientLeaf; import org.phoebus.applications.alarm.model.AlarmTreePath; +import org.phoebus.applications.alarm.ui.Messages; import org.phoebus.framework.jobs.JobManager; import org.phoebus.ui.dialog.DialogHelper; import org.phoebus.ui.dialog.ExceptionDetailsErrorDialog; @@ -19,7 +21,6 @@ import javafx.scene.Node; import javafx.scene.control.MenuItem; -import javafx.scene.control.TextInputDialog; import java.util.logging.Level; import java.util.logging.Logger; @@ -34,38 +35,29 @@ class DuplicatePVAction extends MenuItem * @param model Model where new component is added * @param original Item subject to copy */ - public DuplicatePVAction(final Node node, final AlarmClient model, final AlarmClientLeaf original) + public DuplicatePVAction(final Node node, final AlarmClient model, final AlarmClientLeaf original, final ObservableList incoming_paths_to_select) { super("Duplicate PV", ImageCache.getImageView(AlarmSystem.class, "/icons/move.png")); setOnAction(event -> { // Prompt for new PV name - final TextInputDialog dialog = new TextInputDialog(); - dialog.setTitle(getText()); - dialog.setHeaderText("Enter name for duplicate of\n" + original.getPathName()); + final NameDialog dialog = new NameDialog(model, original.getParent(), original); + dialog.setHeaderText(Messages.enterNameForDuplicate); DialogHelper.positionDialog(dialog, node, -100, -50); final String new_name = dialog.showAndWait().orElse(null); - if (new_name == null || new_name.isEmpty()) + if (new_name == null) return; // Create near copy of original PV, but with new name - final AlarmClientLeaf template = new AlarmClientLeaf(null, new_name); - template.setDescription(original.getDescription()); - template.setEnabled(original.isEnabled()); - template.setLatching(original.isLatching()); - template.setAnnunciating(original.isAnnunciating()); - template.setDelay(original.getDelay()); - template.setCount(original.getCount()); - template.setFilter(original.getFilter()); - template.setGuidance(original.getGuidance()); - template.setDisplays(original.getDisplays()); - template.setCommands(original.getCommands()); - template.setActions(original.getActions()); + final AlarmClientLeaf template = original.createDetachedCopy(new_name); + + final String new_path = AlarmTreePath.makePath(original.getParent().getPathName(), new_name); + + incoming_paths_to_select.add(new_path); // Request adding new PV JobManager.schedule(getText(), monitor -> { try { - final String new_path = AlarmTreePath.makePath(original.getParent().getPathName(), new_name); model.sendItemConfigurationUpdate(new_path, template); } catch (Exception e) { Logger.getLogger(DuplicatePVAction.class.getName()).log(Level.WARNING, "Failed to send item configuration", e); diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/MoveTreeItemAction.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/MoveTreeItemAction.java index 93ac6d881b..08693b1e81 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/MoveTreeItemAction.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/MoveTreeItemAction.java @@ -7,8 +7,10 @@ *******************************************************************************/ package org.phoebus.applications.alarm.ui.tree; +import javafx.collections.ObservableList; import org.phoebus.applications.alarm.AlarmSystem; import org.phoebus.applications.alarm.client.AlarmClient; +import org.phoebus.applications.alarm.client.AlarmClientNode; import org.phoebus.applications.alarm.model.AlarmTreeItem; import org.phoebus.applications.alarm.model.AlarmTreePath; import org.phoebus.applications.alarm.ui.Messages; @@ -32,9 +34,10 @@ public class MoveTreeItemAction extends MenuItem * @param model The AlarmClient. * @param item The item within the TreeView to move. */ - public MoveTreeItemAction(TreeView> node, - AlarmClient model, - AlarmTreeItem item) + public MoveTreeItemAction(final TreeView> node, + final AlarmClient model, + final AlarmTreeItem item, + final ObservableList incoming_paths_to_select) { super("Move Item", ImageCache.getImageView(AlarmSystem.class, "/icons/move.png")); @@ -56,7 +59,7 @@ public MoveTreeItemAction(TreeView> node, path = result.get(); if (AlarmTreeHelper.validateNewPath(path, node.getRoot().getValue())) break; - + // Show error dialog and retry ExceptionDetailsErrorDialog.openError("Invalid Path", "Invalid path. Please try again.", @@ -70,20 +73,20 @@ public MoveTreeItemAction(TreeView> node, return; } - // Tree view keeps the selection indices, which will point to wrong content - // after those items have been removed. - node.getSelectionModel().clearSelection(); + incoming_paths_to_select.add(path); final String new_path = path; // On a background thread, send the item configuration updates for the item to be moved and all its children. JobManager.schedule(getText(), monitor -> { try { - // Move the item. + // Add the new item model.sendItemConfigurationUpdate(new_path, item); - // Move the item's children. - AlarmTreeHelper.rebuildTree(model, item, new_path); - // Delete the old item. This deletes the old item's children as well. + // ...and rebuild all its children + if (item instanceof AlarmClientNode) { + AlarmTreeHelper.rebuildTree(model, item, new_path); + } + // Remove the item and all its children model.removeComponent(item); } catch (Exception e) { ExceptionDetailsErrorDialog.openError(Messages.error, diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/NameDialog.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/NameDialog.java new file mode 100644 index 0000000000..b9fbb1c3d8 --- /dev/null +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/NameDialog.java @@ -0,0 +1,80 @@ +package org.phoebus.applications.alarm.ui.tree; + +import javafx.scene.control.ButtonType; +import javafx.scene.control.Dialog; +import javafx.scene.control.Label; +import javafx.scene.control.TextField; +import javafx.scene.layout.HBox; +import javafx.scene.layout.Priority; +import javafx.scene.layout.VBox; +import javafx.scene.paint.Color; +import org.phoebus.applications.alarm.client.AlarmClient; +import org.phoebus.applications.alarm.client.AlarmClientNode; +import org.phoebus.applications.alarm.model.AlarmTreeItem; +import org.phoebus.applications.alarm.ui.Messages; + +import java.util.Set; +import java.util.function.Consumer; + + +public class NameDialog extends Dialog { + + public NameDialog(final AlarmClient model, final AlarmTreeItem parent, final AlarmTreeItem item) { + this(model, parent, item.getName(), item instanceof AlarmClientNode); + } + + public NameDialog(final AlarmClient model, final AlarmTreeItem parent, final String initialName, final boolean isNode) { + super(); + + setTitle(Messages.renameDialogTitle); + + final TextField input = new TextField(); + input.setPrefWidth(600.0); + HBox.setHgrow(input, Priority.ALWAYS); + + final Label errorLabel = new Label(Messages.nodeAlreadyExists); + errorLabel.setTextFill(Color.RED); + errorLabel.setMaxWidth(Double.MAX_VALUE); + + final Consumer updateError = newError -> { + errorLabel.setText(newError); + getDialogPane().lookupButton(ButtonType.OK).setDisable(newError != null); + }; + + final Set allPvs = AlarmTreeHelper.getLeafNames(model.getRoot()); + input.textProperty().addListener(_ -> { + // Show error and disable OK if text is empty + if (input.getText().isEmpty()) { + updateError.accept(Messages.nameCannotBeEmpty); + return; + } + + if (isNode) { + // Show error and disable OK if the new name matches any child + final boolean childExists = parent.getChildren().stream().anyMatch(child -> input.getText().equals(child.getName())); + updateError.accept(childExists ? Messages.nodeAlreadyExists : null); + } else { + // Show error and disable OK if the PV already exists in the config + final boolean pvExists = allPvs.contains(input.getText()); + updateError.accept(pvExists ? Messages.pvAlreadyExists : null); + } + }); + + + getDialogPane().setContent(new VBox(input, errorLabel)); + getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL); + + setResultConverter(buttonType -> { + if (buttonType == ButtonType.OK) { + // " +" matches one or more spaces + return input.getText().replaceAll(" +", " ").trim(); + } + return null; + }); + + input.setText(initialName); + errorLabel.setText(""); // It can be confusing if an error is shown immediately when the UI loads + + input.requestFocus(); + } +} diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/PasteItemAction.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/PasteItemAction.java new file mode 100644 index 0000000000..fba127360d --- /dev/null +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/PasteItemAction.java @@ -0,0 +1,160 @@ +package org.phoebus.applications.alarm.ui.tree; + +import javafx.beans.property.SimpleObjectProperty; +import javafx.collections.ObservableList; +import javafx.scene.Node; +import javafx.scene.control.Alert; +import javafx.scene.control.Label; +import javafx.scene.control.MenuItem; +import javafx.scene.control.ScrollPane; +import javafx.scene.control.TreeItem; +import javafx.scene.layout.VBox; +import org.phoebus.applications.alarm.AlarmSystem; +import org.phoebus.applications.alarm.client.AlarmClient; +import org.phoebus.applications.alarm.client.AlarmClientNode; +import org.phoebus.applications.alarm.model.AlarmTreeItem; +import org.phoebus.applications.alarm.model.AlarmTreePath; +import org.phoebus.applications.alarm.ui.Messages; +import org.phoebus.framework.jobs.JobManager; +import org.phoebus.ui.dialog.DialogHelper; +import org.phoebus.ui.dialog.ExceptionDetailsErrorDialog; +import org.phoebus.ui.javafx.ImageCache; + +import java.text.MessageFormat; +import java.util.Optional; +import java.util.Set; + + +@SuppressWarnings("nls") +public class PasteItemAction extends MenuItem +{ + + /** @param node Node to position dialog + * @param model {@link AlarmClient} + * @param parent Parent to paste the item into + * @param clipboard Property containing the clipboard + * @param isCut Property indicating whether the clipboard item should be removed when pasted + */ + public PasteItemAction( + final Node node, + final AlarmClient model, + final TreeItem> viewParent, + final SimpleObjectProperty> clipboard, + final boolean isCut, + final ObservableList incoming_paths_to_select) + { + super(Messages.pasteItem, ImageCache.getImageView(AlarmSystem.class, "/icons/paste.png")); + + final AlarmTreeItem parent = viewParent.getValue(); + + setDisable(clipboard.get() == null || isCut && parent.getPathName().equals(clipboard.get().getParent().getPathName())); + + setOnAction(event -> { + final AlarmTreeItem item = clipboard.get(); + final String itemName = item.getName(); + + final String itemConfig = AlarmTreePath.splitPath(item.getPathName())[0]; + final String modelConfig = AlarmTreePath.splitPath(model.getRoot().getPathName())[0]; + final boolean isCrossConfig = !itemConfig.equals(modelConfig); + + // Cross-config cut/paste is forbidden. (Why? User cuts from config A -> switches to + // config B -> pastes to config B -> config A is no longer loaded so how can we remove + // the old item?) + if (isCut && isCrossConfig) { + final Alert alert = new Alert(Alert.AlertType.ERROR); + DialogHelper.positionDialog(alert, node, -100, -50); + alert.setTitle(Messages.pasteItemFailed); + alert.setHeaderText(Messages.cutPasteAcrossConfigs); + alert.show(); + return; + } + + // Cutting+pasting a node into one of its children is forbidden for obvious reasons + final boolean isPasteIntoSelf = parent.getPathName().equals(item.getPathName()); + final boolean isPasteIntoChild = parent.getPathName().startsWith(item.getPathName() + "/"); + if (isCut && (isPasteIntoSelf || isPasteIntoChild)) { + final Alert alert = new Alert(Alert.AlertType.ERROR); + DialogHelper.positionDialog(alert, node, -100, -50); + alert.setTitle(Messages.pasteItemFailed); + alert.setHeaderText(Messages.cutPasteIntoChild); + alert.show(); + return; + } + + // Figure out if this item needs renaming + final boolean needsRename; + final Set allPvsInNewConfig = AlarmTreeHelper.getLeafNames(model.getRoot()); + if (item instanceof AlarmClientNode) { + // Needs to be renamed if new name matches any child + needsRename = parent.getChildren().stream().anyMatch(child -> item.getName().equals(child.getName())); + } else { + // Needs to be renamed if pasting would result in a duplicate PV + needsRename = !isCut && allPvsInNewConfig.contains(item.getName()); + } + + // Get final name + final String finalName; + if (needsRename) { + final NameDialog nameDialog = new NameDialog(model, parent, item); + nameDialog.setHeaderText(MessageFormat.format(Messages.enterNewName, parent.getName(), item.getName())); + DialogHelper.positionDialog(nameDialog, node, -100, -50); + final Optional name = nameDialog.showAndWait(); + if (!name.isPresent()) { + return; + } + finalName = name.get(); + } else { + finalName = item.getName(); + } + + // Special case: if a node is pasted across configs, some of the PVs in that node + // may already exist. But the user still may have intended to copy across all the + // PVs and so we should not just fail silently. Best-effort copying is unlikely + // to be helpful here, and likely to cause unintended behaviour, so we do not offer + // that option and just display an error instead. + if (isCrossConfig && item instanceof AlarmClientNode) { + final Set duplicatePvs = AlarmTreeHelper.getLeafNames(item); + duplicatePvs.retainAll(allPvsInNewConfig); + + if (!duplicatePvs.isEmpty()) { + final Alert alert = new Alert(Alert.AlertType.ERROR); + DialogHelper.positionDialog(alert, node, -100, -50); + alert.setTitle(Messages.pasteItemFailed); + alert.setHeaderText(Messages.nodePvsAlreadyExist); + + final VBox pvPane = new VBox(); + for (final String pv : duplicatePvs) { + pvPane.getChildren().add(new Label(pv)); + } + final ScrollPane scrollPane = new ScrollPane(pvPane); + scrollPane.setMaxHeight(400.0); + + alert.getDialogPane().setContent(scrollPane); + alert.show(); + return; + } + } + + final String newPath = AlarmTreePath.makePath(parent.getPathName(), finalName); + + incoming_paths_to_select.add(newPath); + + // Finally paste the item (on a separate thread of course) + JobManager.schedule("Paste alarm tree item", _ -> { + try { + model.sendItemConfigurationUpdate(newPath, item); + if (isCut) { + // If we're cutting, there's never any risk of duplicate PVs so we can copy all the children too + AlarmTreeHelper.rebuildTree(model, item, newPath); + model.removeComponent(item); + } else if (isCrossConfig && item instanceof AlarmClientNode) { + // Cross-config pasting should copy all the children + AlarmTreeHelper.rebuildTree(model, item, newPath); + } + } catch (final Exception ex) { + ExceptionDetailsErrorDialog.openError(Messages.error, Messages.pasteItemFailed, ex); + } + }); + }); + } +} diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/RenameTreeItemAction.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/RenameTreeItemAction.java index 40e5f13191..b5a1270420 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/RenameTreeItemAction.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/RenameTreeItemAction.java @@ -7,14 +7,15 @@ *******************************************************************************/ package org.phoebus.applications.alarm.ui.tree; +import javafx.collections.ObservableList; import org.phoebus.applications.alarm.AlarmSystem; import org.phoebus.applications.alarm.client.AlarmClient; import org.phoebus.applications.alarm.client.AlarmClientNode; import org.phoebus.applications.alarm.model.AlarmTreeItem; import org.phoebus.applications.alarm.model.AlarmTreePath; -import org.phoebus.applications.alarm.model.BasicState; import org.phoebus.applications.alarm.ui.Messages; import org.phoebus.framework.jobs.JobManager; +import org.phoebus.ui.dialog.DialogHelper; import org.phoebus.ui.dialog.ExceptionDetailsErrorDialog; import org.phoebus.ui.javafx.ImageCache; @@ -33,71 +34,44 @@ class RenameTreeItemAction extends MenuItem * @param pv PV to rename */ public RenameTreeItemAction(final TreeView> node, - final AlarmClient model, - final AlarmTreeItem item) + final AlarmClient model, + final AlarmTreeItem item, + final ObservableList incoming_paths_to_select) { - super("Rename Item", ImageCache.getImageView(AlarmSystem.class, "/icons/rename.png")); + super(Messages.renameItem, ImageCache.getImageView(AlarmSystem.class, "/icons/rename.png")); - if (item instanceof AlarmClientNode) - { - setOnAction(event -> - { - //Prompt for new name - final String new_name = AlarmTreeHelper.prompt(getText(), "Enter new name for Node", item.getName(), node); - if (null == new_name) - return; - // Tree view keeps the selection indices, which will point to wrong content - // after those items have been removed - if (node instanceof TreeView) - ((TreeView) node).getSelectionModel().clearSelection(); + setOnAction(event -> + { + // Prompt for new name + final NameDialog dialog = new NameDialog(model, item.getParent(), item); + dialog.setHeaderText(Messages.enterNewName); + DialogHelper.positionDialog(dialog, node, -100, -50); + final String new_name = dialog.showAndWait().orElse(null); + if (new_name == null) + return; - // Delete old, rebuild child links, and add new name in background thread. - JobManager.schedule(getText(), monitor -> - { - final AlarmTreeItem parent = item.getParent(); - // Remove the item and all its children. - // Add the new item, and then rebuild all its children. - try { - final String new_path = AlarmTreePath.makePath(parent.getPathName(), new_name); - model.sendItemConfigurationUpdate(new_path, item); - AlarmTreeHelper.rebuildTree(model, item, new_path); - model.removeComponent(item); - } catch (Exception e) { - ExceptionDetailsErrorDialog.openError(Messages.error, - Messages.renameItemFailed, - e); - } - }); - }); - } - else - { - setOnAction(event -> - { - //Prompt for new name - final String new_name = AlarmTreeHelper.prompt(getText(), "Enter new name for PV", item.getName(), node); - if (null == new_name) - return; - // Tree view keeps the selection indices, which will point to wrong content - // after those items have been removed - if (node instanceof TreeView) - ((TreeView) node).getSelectionModel().clearSelection(); + final String new_path = AlarmTreePath.makePath(item.getParent().getPathName(), new_name); - // Delete old, add new name in background thread - JobManager.schedule(getText(), monitor -> - { - final AlarmTreeItem parent = item.getParent(); - try { - final String new_path = AlarmTreePath.makePath(parent.getPathName(), new_name); - model.sendItemConfigurationUpdate(new_path, item); - model.removeComponent(item); - } catch (Exception e) { - ExceptionDetailsErrorDialog.openError(Messages.error, - Messages.renameItemFailed, - e); + incoming_paths_to_select.add(new_path); + + // Delete old, rebuild child links, and add new name in background thread. + JobManager.schedule(getText(), monitor -> + { + try { + // Add the new item + model.sendItemConfigurationUpdate(new_path, item); + // ...and rebuild all its children + if (item instanceof AlarmClientNode) { + AlarmTreeHelper.rebuildTree(model, item, new_path); } - }); - }); - } + // Remove the item and all its children + model.removeComponent(item); + } catch (final Exception ex) { + ExceptionDetailsErrorDialog.openError(Messages.error, + Messages.renameItemFailed, + ex); + } + }); + }); } } diff --git a/app/alarm/ui/src/main/resources/icons/cut.png b/app/alarm/ui/src/main/resources/icons/cut.png new file mode 100644 index 0000000000..e2a59bc600 Binary files /dev/null and b/app/alarm/ui/src/main/resources/icons/cut.png differ diff --git a/app/alarm/ui/src/main/resources/org/phoebus/applications/alarm/ui/messages.properties b/app/alarm/ui/src/main/resources/org/phoebus/applications/alarm/ui/messages.properties index d3435a40d5..d33b41fe8d 100644 --- a/app/alarm/ui/src/main/resources/org/phoebus/applications/alarm/ui/messages.properties +++ b/app/alarm/ui/src/main/resources/org/phoebus/applications/alarm/ui/messages.properties @@ -33,6 +33,15 @@ behavior=Behavior: behaviorTooltip=Enable alarms? See also 'Enabling Filter' commands=Commands: configure=Configure +cutPasteAcrossConfigs=You cannot cut and paste a component across configs.\nInstead, copy the component across and then delete the original. +cutPasteIntoChild=You cannot cut and paste a component into itself or one of its children +createAlarmsDialogTitle=Create Alarm(s) +createAlarmsDialogHint=Enter alarm PV. To enter multiple PVs, separate them with spaces/commas/semicolons/newlines. +createAlarmFailed=Failed to create alarm +creatingAlarms=Creating {0} alarms +createNodeDialogTitle=Create Node +createNodeDialogHeader=Enter node name +createNodeFailed=Failed to create node dateTimePickerTooltip=Select a date until which the alarm should be disabled delay=Delay delayTooltip0=Alarms are indicated when they persist for at least this long.\n{0} @@ -57,6 +66,8 @@ enablingFilterTooltip=Optional expression for enabling the alarm error=Error enableAlarmFailed=Failed to enable alarm enableAlarms=Enable Alarms +enterNameForDuplicate=Enter name for duplicate +enterNewName=Enter new name guidance=Guidance: headerAlreadyDisabled=All PVs in the selected section are already disabled headerAlreadyEnabled=All PVs in the selected section are already enabled @@ -68,16 +79,28 @@ info=Info invalidDate=You have selected a date that is either invalid or in the past latch=Latch latchTooltip=Latch alarm until acknowledged? +manageItems=Manage item(s) MenuPath=Alarm moveItemFailed=Failed to move item +nameCannotBeEmpty=Name cannot be empty +nodePvsAlreadyExist=The node you're pasting has some PVs which already exist in the config: +nodeAlreadyExists=Node already exists option=Option partlyDisabled2=(Partly disabled) +pasteItem=Paste Item +pasteItemFailed=Failed to paste item path=Path: promptTitle=Absolute Date is set to a point in time in the past +pvAlreadyExists=PV already exists in this config +pvEnteredMoreThanOnce=PV entered more than once: {0} relativeDateLabel=Relative Date: relativeDateTooltip=Select a predefined duration for disabling the alarm removeComponentFailed=Failed to remove component +renameDialogTitle=Rename +renameDialogLabel=Rename: +renameItem=Rename item renameItemFailed=Failed to rename item +specificPvAlreadyExists=PV already exists in this config: {0} timer=Timer title=Title tooltipAddTableItem=Add a new table item diff --git a/core/ui/src/main/java/org/phoebus/ui/autocomplete/AutocompleteMenu.java b/core/ui/src/main/java/org/phoebus/ui/autocomplete/AutocompleteMenu.java index c17c21924e..0a4f22ba9a 100644 --- a/core/ui/src/main/java/org/phoebus/ui/autocomplete/AutocompleteMenu.java +++ b/core/ui/src/main/java/org/phoebus/ui/autocomplete/AutocompleteMenu.java @@ -222,7 +222,7 @@ private void updateHistory(final String text) private void lookup(final TextInputControl field) { - final String text = field.getText(); + final String text = getCompletionText(field); synchronized (results) { @@ -231,6 +231,10 @@ private void lookup(final TextInputControl field) proposal_service.lookup(text, (name, priority, proposals) -> handleLookupResult(field, text, name, priority, proposals)); } + protected String getCompletionText(final TextInputControl field) { + return field.getText(); + } + /** Latest list of menu items to show. * Used to schedule only one 'RunLater' */ @@ -296,19 +300,20 @@ private AutocompleteItem createItem(final TextInputControl field, markup.getChildren().add(match); } - return new AutocompleteItem(markup, () -> - { - final String value = proposal.apply(text); - field.setText(value); - field.positionCaret(value.length()); - invokeAction(field); - }); + return new AutocompleteItem(markup, () -> autocompleteAction(field, text, proposal)); + } + + protected void autocompleteAction(final TextInputControl field, final String text, final Proposal proposal) { + final String value = proposal.apply(text); + field.setText(value); + field.positionCaret(value.length()); + invokeAction(field); } /** Try to invoke 'onAction' handler * @param field Potential {@link TextField} */ - private void invokeAction(final TextInputControl field) + protected void invokeAction(final TextInputControl field) { if (field instanceof TextField) { diff --git a/core/ui/src/main/java/org/phoebus/ui/autocomplete/MultiplePVAutocompleteMenu.java b/core/ui/src/main/java/org/phoebus/ui/autocomplete/MultiplePVAutocompleteMenu.java new file mode 100644 index 0000000000..deb16bf799 --- /dev/null +++ b/core/ui/src/main/java/org/phoebus/ui/autocomplete/MultiplePVAutocompleteMenu.java @@ -0,0 +1,41 @@ +package org.phoebus.ui.autocomplete; + +import javafx.scene.control.TextInputControl; +import org.phoebus.framework.autocomplete.PVProposalService; +import org.phoebus.framework.autocomplete.Proposal; + +import java.util.regex.Pattern; + + +/** Auto-completion menu for multiple PV names + * + * Allows auto-completion of multiple PVs within a single text + * field, separated by delimiters specified by DELIMITER_PATTERN + * + * @author Percy Baker + */ +public class MultiplePVAutocompleteMenu extends AutocompleteMenu +{ + public static final MultiplePVAutocompleteMenu INSTANCE = new MultiplePVAutocompleteMenu(); + + public static final Pattern DELIMITER_PATTERN = Pattern.compile("[\\s;,]+"); + + private MultiplePVAutocompleteMenu() + { + super(PVProposalService.INSTANCE); + } + + @Override + protected String getCompletionText(final TextInputControl field) { + final String[] split = DELIMITER_PATTERN.split(field.getText()); + return split.length == 0 ? "" : split[split.length - 1]; + } + + @Override + protected void autocompleteAction(final TextInputControl field, final String text, final Proposal proposal) { + final String value = field.getText(0, field.getText().length() - text.length()) + proposal.apply(text); + field.setText(value); + field.positionCaret(value.length()); + invokeAction(field); + } +}