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 1a8d67bb5e..5d23ecc068 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 @@ -36,6 +36,7 @@ public class Messages public static String displays; public static String enableAlarmFailed; public static String enableAlarms; + public static String enterNameForDuplicate; public static String guidance; public static String headerAlreadyDisabled; public static String headerAlreadyEnabled; @@ -43,9 +44,16 @@ public class Messages public static String headerConfirmDisableWithEnableDate; public static String headerConfirmEnable; public static String indefinitely; + public static String itemAlreadyExists; public static String MenuPath; public static String moveItemFailed; + public static String nameCannotBeEmpty; + public static String pasteItem; + public static String pasteItemFailed; public static String promptTitle; + public static String renameItem; + public static String renameDialogLabel; + public static String renameDialogTitle; public static String removeComponentFailed; public static String renameItemFailed; public static String totalPVs; diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/area/AlarmAreaView.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/area/AlarmAreaView.java index 63f5762453..809ad3d2e1 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/area/AlarmAreaView.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/area/AlarmAreaView.java @@ -75,8 +75,11 @@ public class AlarmAreaView extends StackPane implements AlarmClientListener */ private final AtomicReference> item_changes = new AtomicReference<>(); - /** Set of items that have updated, with iteration order based on when they updated */ - private final Set items_to_update = new LinkedHashSet<>(); + /** Set of items that have updated, with iteration order based on when they updated + * + * SYNC on access + */ + private final Set item_paths_to_update = new LinkedHashSet<>(); /** Throttle [5Hz] used for updates of existing items */ private final UpdateThrottle update_throttle = new UpdateThrottle(200, TimeUnit.MILLISECONDS, this::updateItems); @@ -165,9 +168,9 @@ public void itemUpdated(final AlarmTreeItem item) if (null == item_name) return; - synchronized (items_to_update) + synchronized (item_paths_to_update) { - items_to_update.add(item_name); + item_paths_to_update.add(item_name); } update_throttle.trigger(); } @@ -178,10 +181,10 @@ private void updateItems() final List changed_items = item_changes.getAndSet(null); final String[] update_array; - synchronized (items_to_update) + synchronized (item_paths_to_update) { - update_array = items_to_update.toArray(new String[items_to_update.size()]); - items_to_update.clear(); + update_array = item_paths_to_update.toArray(new String[item_paths_to_update.size()]); + item_paths_to_update.clear(); } Platform.runLater(() -> { 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..1d3c2865a9 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 @@ -15,13 +15,11 @@ import org.phoebus.applications.alarm.client.AlarmClient; import org.phoebus.applications.alarm.client.AlarmClientLeaf; +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.ui.dialog.DialogHelper; -import javafx.scene.control.TextInputDialog; -import javafx.scene.control.TreeView; import org.phoebus.util.time.TimestampFormats; /** @author Evan Smith @@ -56,27 +54,26 @@ 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. + /** Moves the provided item and all its children to a new path. + * + * @param model AlarmClient used to communicate to the AlarmServer + * @param item AlarmTreeItem to move + * @param path Path that the parents' children will now be located at. + * @param removeOldItem Whether the old item should be removed once it is moved */ - 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; - } + public static void moveItem(AlarmClient model, AlarmTreeItem item, String newPath, boolean removeOldItem) throws Exception + { + // Add the new item + model.sendItemConfigurationUpdate(newPath, item); + // ...and rebuild all its children + if (item instanceof AlarmClientNode) { + rebuildTree(model, item, newPath); + } + // Remove the item and all its children + if (removeOldItem) { + model.removeComponent(item); + } + } /** Validate the passed path string by checking if the path name is valid. * 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 f3d65c9801..5324c49ad6 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 @@ -12,10 +12,11 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -23,6 +24,8 @@ 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 org.phoebus.applications.alarm.AlarmSystem; import org.phoebus.applications.alarm.client.AlarmClient; @@ -80,6 +83,14 @@ * as generic JavaFX Node, only calling public methods * defined on this class. * + *

The model (AlarmClient) and the AlarmTreeView are kept in + * sync by a lockstep between model and view updates. When the + * model is changed, it calls item[removed|added]. The AlarmClient + * then blocks until the method returns (i.e. until the UI has + * been updated) and then can move on to the next update. The + * exception to this is itemUpdated, which adds to a queue of + * items to be updated which is then regularly processed. + * * @author Kay Kasemir */ @SuppressWarnings("nls") @@ -112,13 +123,13 @@ public class AlarmTreeView extends BorderPane implements AlarmClientListener private final CountDownLatch block_item_changes = new CountDownLatch(1); /** Map from alarm tree path to view's TreeItem */ - private final ConcurrentHashMap>> path2view = new ConcurrentHashMap<>(); + private final Map>> path2view = new HashMap<>(); /** Items to update, ordered by time of original update request * - * SYNC on access + * SYNC on access */ - private final Set>> items_to_update = new LinkedHashSet<>(); + private final Set item_paths_to_update = new LinkedHashSet<>(); /** Throttle [5Hz] used for updates of existing items */ private final UpdateThrottle throttle = new UpdateThrottle(200, TimeUnit.MILLISECONDS, this::performUpdates); @@ -140,6 +151,9 @@ public class AlarmTreeView extends BorderPane implements AlarmClientListener items.remove(changing); }); + private final SimpleObjectProperty> clipboard = new SimpleObjectProperty<>(null); + private final SimpleBooleanProperty isClipboardCut = new SimpleBooleanProperty(false); + // Javadoc for TreeItem shows example for overriding isLeaf() and getChildren() // to dynamically create TreeItem as TreeView requests information. // @@ -161,7 +175,7 @@ public AlarmTreeView(final AlarmClient model) { * @param model Model to represent. Must not be running, yet * @param itemName item name that may be expanded or given focus */ - public AlarmTreeView(final AlarmClient model, String itemName) + public AlarmTreeView(final AlarmClient model, final String itemName) { if (model.isRunning()) throw new IllegalStateException(); @@ -387,37 +401,34 @@ private void blockItemChanges() public void itemAdded(final AlarmTreeItem item) { blockItemChanges(); - // System.out.println(Thread.currentThread() + " Add " + item.getPathName()); - - // Parent must already exist - final AlarmTreeItem model_parent = item.getParent(); - final TreeItem> view_parent = path2view.get(model_parent.getPathName()); - - if (view_parent == null) - { - dumpTree(tree_view.getRoot()); - throw new IllegalStateException("Missing parent view item for " + item.getPathName()); - } - // Create view item ASAP so that following updates will find it.. - final TreeItem> view_item = createViewItem(item); - // .. but defer showing it on screen to UI thread final CountDownLatch done = new CountDownLatch(1); + Platform.runLater(() -> { indicateChange(); + + // Parent must already exist + final AlarmTreeItem model_parent = item.getParent(); + final TreeItem> view_parent = path2view.get(model_parent.getPathName()); + + if (view_parent == null) { + dumpTree(tree_view.getRoot()); + throw new IllegalStateException("Missing parent view item for " + item.getPathName()); + } + final TreeItem> view_item = createViewItem(item); + // Keep sorted by inserting at appropriate index final List>> items = view_parent.getChildren(); final int index = Collections.binarySearch(items, view_item, - (a, b) -> CompareNatural.compareTo(a.getValue().getName(), - b.getValue().getName())); + (a, b) -> CompareNatural.compareTo(a.getValue().getName(), + b.getValue().getName())); if (index < 0) - items.add(-index-1, view_item); + items.add(-index - 1, view_item); else items.add(index, view_item); done.countDown(); }); - updateStats(); // Waiting on the UI thread throttles the model's updates // to a rate that the UI can handle. @@ -438,18 +449,24 @@ public void itemAdded(final AlarmTreeItem item) public void itemRemoved(final AlarmTreeItem item) { blockItemChanges(); - // System.out.println(Thread.currentThread() + " Removed " + item.getPathName()); - - // Remove item and all sub-items from model2ui - final TreeItem> view_item = removeViewItems(item); - if (view_item == null) - throw new IllegalStateException("No view item for " + item.getPathName()); - // Remove the corresponding view final CountDownLatch done = new CountDownLatch(1); Platform.runLater(() -> { 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) + throw new IllegalStateException("No view item for " + item.getPathName()); + + // Remove the corresponding view + // // Can only locate the parent view item on UI thread, // because item might just have been created by itemAdded() event // and won't be on the screen until UI thread runs. @@ -459,7 +476,6 @@ public void itemRemoved(final AlarmTreeItem item) view_parent.getChildren().remove(view_item); done.countDown(); }); - updateStats(); // Waiting on the UI thread throttles the model's updates // to a rate that the UI can handle. @@ -493,87 +509,85 @@ private TreeItem> removeViewItems(final AlarmTreeItem item) public void itemUpdated(final AlarmTreeItem item) { blockItemChanges(); - // System.out.println(Thread.currentThread() + " Updated " + item.getPathName()); - final TreeItem> view_item = path2view.get(item.getPathName()); - if (view_item == null) - { - System.out.println("Unknown view for " + item.getPathName()); - path2view.keySet().stream().forEach(System.out::println); - throw new IllegalStateException("No view item for " + item.getPathName()); - } // UI update of existing item, i.e. // Platform.runLater(() -> TreeHelper.triggerTreeItemRefresh(view_item)); // is throttled. // If several items update, they're all redrawn in one Platform call, // and rapid updates of the same item are merged into just one final update - synchronized (items_to_update) + // We push the path instead of the view item in case the view item is removed + // between now and the update being handled. + synchronized (item_paths_to_update) { - items_to_update.add(view_item); + item_paths_to_update.add(item.getPathName()); } throttle.trigger(); - updateStats(); } /** Called by throttle to perform accumulated updates */ - @SuppressWarnings("unchecked") private void performUpdates() { - final TreeItem>[] view_items; - synchronized (items_to_update) + + // Drain items to update in one go; we will process it later on the main thread + final String[] view_item_paths; + synchronized (item_paths_to_update) { - // Creating a direct copy, i.e. another new LinkedHashSet<>(items_to_update), - // would be expensive, since we only need a _list_ of what's to update. - // Could use type-safe - // new ArrayList>>(items_to_update) - // but that calls toArray() internally, so doing that directly - view_items = items_to_update.toArray(new TreeItem[items_to_update.size()]); - items_to_update.clear(); + view_item_paths = item_paths_to_update.toArray(new String[item_paths_to_update.size()]); + item_paths_to_update.clear(); } - // Remember selection - final ObservableList>> updatedSelectedItems = - FXCollections.observableArrayList(tree_view.getSelectionModel().getSelectedItems()); - - // How to update alarm tree cells when data changed? - // `setValue()` with a truly new value (not 'equal') should suffice, - // but there are two problems: - // Since we're currently using the alarm tree model item as a value, - // the value as seen by the TreeView remains the same. - // We could use a model item wrapper class as the cell value - // and replace it (while still holding the same model item!) - // for the TreeView to see a different wrapper value, but - // as shown in org.phoebus.applications.alarm.TreeItemUpdateDemo, - // replacing a tree cell value fails to trigger refreshes - // for certain hidden items. - // Only replacing the TreeItem gives reliable refreshes. - for (final TreeItem> view_item : view_items) - // Top-level item has no parent, and is not visible, so we keep it - if (view_item.getParent() != null) - { - // Locate item in tree parent - final TreeItem> parent = view_item.getParent(); - final int index = parent.getChildren().indexOf(view_item); - - // Create new TreeItem for that value - final AlarmTreeItem value = view_item.getValue(); - final TreeItem> update = new TreeItem<>(value); - if (updatedSelectedItems.contains(view_item)) { - updatedSelectedItems.remove(view_item); - updatedSelectedItems.add(update); + Platform.runLater(() -> { + // Remember selection + final ObservableList>> updatedSelectedItems = + FXCollections.observableArrayList(tree_view.getSelectionModel().getSelectedItems()); + + // How to update alarm tree cells when data changed? + // `setValue()` with a truly new value (not 'equal') should suffice, + // but there are two problems: + // Since we're currently using the alarm tree model item as a value, + // the value as seen by the TreeView remains the same. + // We could use a model item wrapper class as the cell value + // and replace it (while still holding the same model item!) + // for the TreeView to see a different wrapper value, but + // as shown in org.phoebus.applications.alarm.TreeItemUpdateDemo, + // replacing a tree cell value fails to trigger refreshes + // for certain hidden items. + // Only replacing the TreeItem gives reliable refreshes. + for (final String view_item_path : view_item_paths) { + final TreeItem> view_item = path2view.get(view_item_path); + if (view_item == null) { + // Possible if the item has been removed since it was added to the update queue + continue; + } + + // Top-level item has no parent, and is not visible, so we keep it + if (view_item.getParent() != null) { + // Locate item in tree parent + final TreeItem> parent = view_item.getParent(); + final int index = parent.getChildren().indexOf(view_item); + + // Create new TreeItem for that value + final AlarmTreeItem value = view_item.getValue(); + final TreeItem> update = new TreeItem<>(value); + if (updatedSelectedItems.contains(view_item)) { + updatedSelectedItems.remove(view_item); + updatedSelectedItems.add(update); + } + // Move child links to new item + final ArrayList>> children = new ArrayList<>(view_item.getChildren()); + view_item.getChildren().clear(); + update.getChildren().addAll(children); + update.setExpanded(view_item.isExpanded()); + + path2view.put(value.getPathName(), update); + parent.getChildren().set(index, update); } - // Move child links to new item - final ArrayList>> children = new ArrayList<>(view_item.getChildren()); - view_item.getChildren().clear(); - update.getChildren().addAll(children); - update.setExpanded(view_item.isExpanded()); - - path2view.put(value.getPathName(), update); - parent.getChildren().set(index, update); } - // Restore selection - tree_view.getSelectionModel().clearSelection(); - updatedSelectedItems.forEach(item -> tree_view.getSelectionModel().select(item)); + + // Restore selection + tree_view.getSelectionModel().clearSelection(); + updatedSelectedItems.forEach(item -> tree_view.getSelectionModel().select(item)); + }); } /** Context menu, details depend on selected items */ @@ -604,6 +618,13 @@ else if (selection.size() == 1) menu_items.add(new ConfigureComponentAction(tree_view, model, item)); menu_items.add(new SeparatorMenuItem()); + menu_items.add(new CopyItemAction(tree_view, clipboard, isClipboardCut, item)); + menu_items.add(new CutItemAction(tree_view, clipboard, isClipboardCut, item)); + + menu_items.add(new PasteItemAction( + tree_view, model, item instanceof AlarmClientNode ? item : item.getParent(), clipboard, isClipboardCut.get() + )); + if (item instanceof AlarmClientNode) menu_items.add(new AddComponentAction(tree_view, model, item)); @@ -614,6 +635,7 @@ else if (selection.size() == 1) menu_items.add(new MoveTreeItemAction(tree_view, model, item)); } + if (selection.size() >= 1) { menu_items.add(new EnableComponentAction(tree_view, model, selection)); @@ -689,25 +711,7 @@ private void addDragSupport() }); } -// private long next_stats = 0; -// private final AtomicInteger update_count = new AtomicInteger(); -// private volatile double updates_per_sec = 0.0; - - private void updateStats() - { -// final long time = System.currentTimeMillis(); -// if (time > next_stats) -// { -// final int updates = update_count.getAndSet(0); -// updates_per_sec = updates_per_sec * 0.9 + updates * 0.1; -// next_stats = time + 1000; -// System.out.format("%.2f updates/sec\n", updates_per_sec); -// } -// else -// update_count.incrementAndGet(); - } - - private void dumpTree(TreeItem> item) + private static void dumpTree(final TreeItem> item) { final ObservableList>> children = item.getChildren(); System.out.printf("item: %s , has %d children.\n", item.getValue().getName(), children.size()); 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/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..302aeb37a3 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 @@ -40,27 +40,15 @@ public DuplicatePVAction(final Node node, final AlarmClient model, final AlarmCl 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 RenameDialog dialog = new RenameDialog(original.getParent(), original.getName()); + dialog.setHeaderText("Enter name for duplicate"); 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); // Request adding new PV JobManager.schedule(getText(), monitor -> { 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..725d1bbf1d 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 @@ -70,21 +70,12 @@ 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(); - 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. - 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. - model.removeComponent(item); + AlarmTreeHelper.moveItem(model, item, new_path, true); } catch (Exception e) { ExceptionDetailsErrorDialog.openError(Messages.error, Messages.moveItemFailed, 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..624ad9abbe --- /dev/null +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/PasteItemAction.java @@ -0,0 +1,94 @@ +package org.phoebus.applications.alarm.ui.tree; + +import javafx.beans.property.SimpleObjectProperty; +import javafx.scene.Node; +import javafx.scene.control.ButtonType; +import javafx.scene.control.Dialog; +import javafx.scene.control.MenuItem; +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; + + +@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 AlarmTreeItem parent, + final SimpleObjectProperty> clipboard, + final boolean isCut) + { + super(Messages.pasteItem, ImageCache.getImageView(AlarmSystem.class, "/icons/paste.png")); + + setDisable(clipboard.get() == null); + + setOnAction(event -> { + AlarmTreeItem item = clipboard.get(); + final String itemName = item.getName(); + + // Get new name, prompting user if any child of the new parent already has the same name + String newName = item.getName(); + if (parent.getChildren().stream().anyMatch(child -> child.getName().equals(itemName))) { + // Item already exists in the parent node we're copying to; prompt for rename + final RenameDialog dialog = new RenameDialog(parent, item.getName()); + dialog.setHeaderText(MessageFormat.format(Messages.itemAlreadyExists, parent.getName(), item.getName())); + DialogHelper.positionDialog(dialog, node, -100, -50); + final Optional name = dialog.showAndWait(); + if (name.isPresent()) { + newName = name.get(); + } else { + return; + } + } + + // Prompt user whether they want to paste the children too + if (item instanceof final AlarmClientNode alarmNode && !alarmNode.getChildren().isEmpty()) { + final Dialog dialog = new Dialog<>(); + DialogHelper.positionDialog(dialog, node, -100, -50); + dialog.getDialogPane().getButtonTypes().addAll(ButtonType.CANCEL, ButtonType.NO, ButtonType.YES); + dialog.setTitle("Copy children?"); + dialog.setHeaderText("Copy the children of this node too?"); + + final ButtonType result = dialog.showAndWait().orElse(null); + if (result == null || result == ButtonType.CANCEL) { + return; + } + if (result == ButtonType.NO) { + item = alarmNode.createDetachedCopy(); + } + } + + // Finally paste the item (on a separate thread of course) + // lambda variables must be final + final AlarmTreeItem finalItem = item; + final String finalNewName = newName; + JobManager.schedule("Paste alarm tree item", _ -> { + try { + final String newPath = AlarmTreePath.makePath(parent.getPathName(), finalNewName); + AlarmTreeHelper.moveItem(model, finalItem, newPath, isCut); + } 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/RenameDialog.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/RenameDialog.java new file mode 100644 index 0000000000..dbb1b5e65b --- /dev/null +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/RenameDialog.java @@ -0,0 +1,76 @@ +package org.phoebus.applications.alarm.ui.tree; + +import javafx.geometry.Pos; +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.model.AlarmTreeItem; +import org.phoebus.applications.alarm.ui.Messages; + +import java.util.function.Consumer; + + +public class RenameDialog extends Dialog { + + /** + * + * @param parent The parent of the item being renamed - use to check for name clashes + * @param oldName The old name of the item being renamed + * @param allowOldName Whether the new name can be the same as the old name + */ + public RenameDialog(final AlarmTreeItem parent, final String oldName) { + super(); + + setTitle(Messages.renameDialogTitle); + + final Label renameLabel = new Label(Messages.renameDialogLabel); + + final TextField input = new TextField(); + input.setText(oldName); + input.setPrefWidth(600.0); + HBox.setHgrow(input, Priority.ALWAYS); + + final HBox inputBox = new HBox(renameLabel, input); + inputBox.setAlignment(Pos.CENTER_LEFT); + + final Label errorLabel = new Label(Messages.itemAlreadyExists); + errorLabel.setTextFill(Color.RED); + errorLabel.setMaxWidth(Double.MAX_VALUE); + + final Consumer updateError = newError -> { + errorLabel.setText(newError); + getDialogPane().lookupButton(ButtonType.OK).setDisable(newError != null); + }; + + input.textProperty().addListener(_ -> { + // Disable OK if name has not changed + if (input.getText().equals(oldName)) { + updateError.accept(""); // disable OK but don't show an error + return; + } + + // Show error and disable OK if text is empty + if (input.getText().isEmpty()) { + updateError.accept(Messages.nameCannotBeEmpty); + return; + } + + // Show error and disable OK if the label matches any child + final boolean childExists = parent.getChildren().stream().anyMatch(child -> input.getText().equals(child.getName())); + updateError.accept(childExists ? Messages.itemAlreadyExists : null); + }); + + getDialogPane().setContent(new VBox(inputBox, errorLabel)); + getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL); + + // Default to error hidden and OK disabled + updateError.accept(""); + + setResultConverter(buttonType -> buttonType == ButtonType.OK ? input.getText() : null); + } +} 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..1df7d11859 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 @@ -15,6 +15,7 @@ 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; @@ -36,68 +37,31 @@ public RenameTreeItemAction(final TreeView> node, final AlarmClient model, final AlarmTreeItem item) { - 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 RenameDialog dialog = new RenameDialog(item.getParent(), item.getName()); + dialog.setHeaderText(Messages.enterNameForDuplicate); + 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(); - - // 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); - } - }); - }); - } + // Delete old, rebuild child links, and 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); + AlarmTreeHelper.moveItem(model, item, new_path, true); + } 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 2d6d863eff..57a9140133 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 @@ -26,6 +26,7 @@ Annunciator=Annunciator alarmCount=Alarm Count [within delay]: alarmCountTooltip=Alarms are indicated when they occur this often within the delay alarmDelay=Alarm Delay [seconds]: +alreadyHasItem='{0}' already has an item '{1}' annunciate=Annunciate annunciateTooltip=Request audible alarm annunciation (using the description)? automatedActions=Automated Actions: @@ -54,6 +55,7 @@ displays=Displays: enabled=Enabled enablingFilter=Enabling Filter: enablingFilterTooltip=Optional expression for enabling the alarm +enterNameForDuplicate=Enter name for duplicate error=Error enableAlarmFailed=Failed to enable alarm enableAlarms=Enable Alarms @@ -66,17 +68,24 @@ headerConfirmEnable=Enable all PVs in the selected section of the alarm hierarch indefinitely=Indefinitely info=Info invalidDate=You have selected a date that is either invalid or in the past +itemAlreadyExists=Item already exists latch=Latch latchTooltip=Latch alarm until acknowledged? MenuPath=Alarm moveItemFailed=Failed to move item +nameCannotBeEmpty=Name cannot be empty option=Option partlyDisabled2=(Partly disabled) +pasteItem=Paste Item +pasteItemFailed=Failed to paste component path=Path: promptTitle=Absolute Date is set to a point in time in the past 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 timer=Timer title=Title