-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
GroupTreeView.java
627 lines (549 loc) · 27.4 KB
/
GroupTreeView.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
package org.jabref.gui.groups;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.ObjectProperty;
import javafx.css.PseudoClass;
import javafx.geometry.Orientation;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Control;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableRow;
import javafx.scene.control.TreeTableView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import org.jabref.gui.DialogService;
import org.jabref.gui.DragAndDropDataFormats;
import org.jabref.gui.Globals;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.gui.util.ControlHelper;
import org.jabref.gui.util.CustomLocalDragboard;
import org.jabref.gui.util.RecursiveTreeItem;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.gui.util.ViewModelTreeTableCellFactory;
import org.jabref.gui.util.ViewModelTreeTableRowFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.groups.AllEntriesGroup;
import org.jabref.preferences.PreferencesService;
import com.tobiasdiez.easybind.EasyBind;
import org.controlsfx.control.textfield.CustomTextField;
import org.controlsfx.control.textfield.TextFields;
import org.reactfx.util.FxTimer;
import org.reactfx.util.Timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GroupTreeView extends BorderPane {
private static final Logger LOGGER = LoggerFactory.getLogger(GroupTreeView.class);
private static final PseudoClass PSEUDOCLASS_ANYSELECTED = PseudoClass.getPseudoClass("any-selected");
private static final PseudoClass PSEUDOCLASS_ALLSELECTED = PseudoClass.getPseudoClass("all-selected");
private static final PseudoClass PSEUDOCLASS_ROOTELEMENT = PseudoClass.getPseudoClass("root");
private static final PseudoClass PSEUDOCLASS_SUBELEMENT = PseudoClass.getPseudoClass("sub"); // > 1 deep
private static final double SCROLL_SPEED = 50;
private TreeTableView<GroupNodeViewModel> groupTree;
private TreeTableColumn<GroupNodeViewModel, GroupNodeViewModel> mainColumn;
private TreeTableColumn<GroupNodeViewModel, GroupNodeViewModel> numberColumn;
private TreeTableColumn<GroupNodeViewModel, GroupNodeViewModel> expansionNodeColumn;
private CustomTextField searchField;
private final StateManager stateManager;
private final DialogService dialogService;
private final TaskExecutor taskExecutor;
private final PreferencesService preferencesService;
private GroupTreeViewModel viewModel;
private CustomLocalDragboard localDragboard;
private DragExpansionHandler dragExpansionHandler;
private Timer scrollTimer;
private double scrollVelocity = 0;
/**
* Note: This panel is deliberately not created in fxml, since parsing equivalent fxml takes about 500 msecs
*/
public GroupTreeView(TaskExecutor taskExecutor,
StateManager stateManager,
PreferencesService preferencesService,
DialogService dialogService) {
this.taskExecutor = taskExecutor;
this.stateManager = stateManager;
this.preferencesService = preferencesService;
this.dialogService = dialogService;
createNodes();
this.getStylesheets().add(Objects.requireNonNull(GroupTreeView.class.getResource("GroupTree.css")).toExternalForm());
initialize();
}
private void createNodes() {
searchField = new CustomTextField();
searchField.setPromptText(Localization.lang("Filter groups"));
searchField.setId("searchField");
HBox.setHgrow(searchField, Priority.ALWAYS);
HBox groupFilterBar = new HBox(searchField);
groupFilterBar.setId("groupFilterBar");
this.setTop(groupFilterBar);
mainColumn = new TreeTableColumn<>();
mainColumn.setId("mainColumn");
mainColumn.setResizable(true);
numberColumn = new TreeTableColumn<>();
numberColumn.getStyleClass().add("numberColumn");
numberColumn.setMinWidth(60d);
numberColumn.setMaxWidth(60d);
numberColumn.setPrefWidth(60d);
numberColumn.setResizable(false);
expansionNodeColumn = new TreeTableColumn<>();
expansionNodeColumn.getStyleClass().add("expansionNodeColumn");
expansionNodeColumn.setMaxWidth(20d);
expansionNodeColumn.setMinWidth(20d);
expansionNodeColumn.setPrefWidth(20d);
expansionNodeColumn.setResizable(false);
groupTree = new TreeTableView<>();
groupTree.setId("groupTree");
groupTree.setColumnResizePolicy(TreeTableView.CONSTRAINED_RESIZE_POLICY);
groupTree.getColumns().addAll(List.of(mainColumn, numberColumn, expansionNodeColumn));
this.setCenter(groupTree);
mainColumn.prefWidthProperty().bind(groupTree.widthProperty().subtract(80d).subtract(15d));
Button addNewGroup = new Button(Localization.lang("Add group"));
addNewGroup.setId("addNewGroup");
addNewGroup.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(addNewGroup, Priority.ALWAYS);
addNewGroup.setTooltip(new Tooltip(Localization.lang("New group")));
addNewGroup.setOnAction(event -> addNewGroup());
HBox groupBar = new HBox(addNewGroup);
groupBar.setId("groupBar");
this.setBottom(groupBar);
}
private void initialize() {
this.localDragboard = stateManager.getLocalDragboard();
viewModel = new GroupTreeViewModel(stateManager, dialogService, preferencesService, taskExecutor, localDragboard);
// Set-up groups tree
groupTree.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
dragExpansionHandler = new DragExpansionHandler();
// Set-up bindings
Platform.runLater(() ->
BindingsHelper.bindContentBidirectional(
groupTree.getSelectionModel().getSelectedItems(),
viewModel.selectedGroupsProperty(),
newSelectedGroups -> newSelectedGroups.forEach(this::selectNode),
this::updateSelection
));
// We try to prevent publishing changes in the search field directly to the search task that takes some time
// for larger group structures.
final Timer searchTask = FxTimer.create(Duration.ofMillis(400), () -> {
LOGGER.debug("Run group search " + searchField.getText());
viewModel.filterTextProperty().setValue(searchField.textProperty().getValue());
});
searchField.textProperty().addListener((observable, oldValue, newValue) -> searchTask.restart());
groupTree.rootProperty().bind(
EasyBind.map(viewModel.rootGroupProperty(),
group -> {
if (group == null) {
return null;
} else {
return new RecursiveTreeItem<>(
group,
GroupNodeViewModel::getChildren,
GroupNodeViewModel::expandedProperty,
viewModel.filterPredicateProperty());
}
}));
// Icon and group name
new ViewModelTreeTableCellFactory<GroupNodeViewModel>()
.withText(GroupNodeViewModel::getDisplayName)
.withIcon(GroupNodeViewModel::getIcon)
.withTooltip(GroupNodeViewModel::getDescription)
.install(mainColumn);
// Number of hits (only if user wants to see them)
new ViewModelTreeTableCellFactory<GroupNodeViewModel>()
.withGraphic(this::createNumberCell)
.install(numberColumn);
// Arrow indicating expanded status
new ViewModelTreeTableCellFactory<GroupNodeViewModel>()
.withGraphic(this::getArrowCell)
.withOnMouseClickedEvent(group -> event -> {
group.toggleExpansion();
event.consume();
})
.install(expansionNodeColumn);
new ViewModelTreeTableRowFactory<GroupNodeViewModel>()
.withContextMenu(this::createContextMenuForGroup)
.withEventFilter(MouseEvent.MOUSE_PRESSED, (row, event) -> {
if (event.getTarget() instanceof StackPane pane) {
if (pane.getStyleClass().contains("arrow") || pane.getStyleClass().contains("tree-disclosure-node")) {
event.consume();
}
}
})
.withCustomInitializer(row -> {
// Remove disclosure node since we display custom version in separate column
// Simply setting to null is not enough since it would be replaced by the default node on every change
row.setDisclosureNode(null);
row.disclosureNodeProperty().addListener((observable, oldValue, newValue) -> row.setDisclosureNode(null));
})
.setOnDragDetected(this::handleOnDragDetected)
.setOnDragDropped(this::handleOnDragDropped)
.setOnDragExited(this::handleOnDragExited)
.setOnDragOver(this::handleOnDragOver)
.withPseudoClass(PSEUDOCLASS_ROOTELEMENT, row -> Bindings.createBooleanBinding(
() -> (row != null) && (groupTree.getRoot() != null) && (row.getItem() == groupTree.getRoot().getValue()), row.treeItemProperty()))
.withPseudoClass(PSEUDOCLASS_SUBELEMENT, row -> Bindings.createBooleanBinding(
() -> (row != null) && (groupTree.getTreeItemLevel(row.getTreeItem()) > 1), row.treeItemProperty()))
.install(groupTree);
setupDragScrolling();
// Filter text field
setupClearButtonField(searchField);
}
private StackPane getArrowCell(GroupNodeViewModel viewModel) {
final StackPane disclosureNode = new StackPane();
disclosureNode.visibleProperty().bind(viewModel.hasChildrenProperty());
disclosureNode.getStyleClass().setAll("tree-disclosure-node");
final StackPane disclosureNodeArrow = new StackPane();
disclosureNodeArrow.getStyleClass().setAll("arrow");
disclosureNode.getChildren().add(disclosureNodeArrow);
return disclosureNode;
}
private StackPane createNumberCell(GroupNodeViewModel group) {
final StackPane node = new StackPane();
if (!group.isRoot()) {
BindingsHelper.includePseudoClassWhen(node, PSEUDOCLASS_ANYSELECTED,
group.anySelectedEntriesMatchedProperty());
BindingsHelper.includePseudoClassWhen(node, PSEUDOCLASS_ALLSELECTED,
group.allSelectedEntriesMatchedProperty());
}
Text text = new Text();
EasyBind.subscribe(preferencesService.getGroupsPreferences().displayGroupCountProperty(),
shouldDisplayGroupCount -> {
if (text.textProperty().isBound()) {
text.textProperty().unbind();
text.setText("");
}
node.getStyleClass().clear();
if (shouldDisplayGroupCount) {
node.getStyleClass().add("hits");
text.textProperty().bind(group.getHits().map(Number::intValue).map(this::getFormattedNumber));
}
});
text.getStyleClass().setAll("text");
text.styleProperty().bind(Bindings.createStringBinding(() -> {
double reducedFontSize;
double font_size = preferencesService.getWorkspacePreferences().getMainFontSize();
// For each breaking point, the font size is reduced 0.20 em to fix issue 8797
if (font_size > 26.0) {
reducedFontSize = 0.25;
} else if (font_size > 22.0) {
reducedFontSize = 0.35;
} else if (font_size > 18.0) {
reducedFontSize = 0.55;
} else {
reducedFontSize = 0.75;
}
return String.format("-fx-font-size: %fem;", reducedFontSize);
}, preferencesService.getWorkspacePreferences().mainFontSizeProperty()));
node.getChildren().add(text);
node.setMaxWidth(Control.USE_PREF_SIZE);
return node;
}
private void handleOnDragExited(TreeTableRow<GroupNodeViewModel> row, GroupNodeViewModel fieldViewModel, DragEvent dragEvent) {
ControlHelper.removeDroppingPseudoClasses(row);
}
private void handleOnDragDetected(TreeTableRow<GroupNodeViewModel> row, GroupNodeViewModel groupViewModel, MouseEvent event) {
List<String> groupsToMove = new ArrayList<>();
for (TreeItem<GroupNodeViewModel> selectedItem : row.getTreeTableView().getSelectionModel().getSelectedItems()) {
if ((selectedItem != null) && (selectedItem.getValue() != null)) {
groupsToMove.add(selectedItem.getValue().getPath());
}
}
if (groupsToMove.size() > 0) {
localDragboard.clearAll();
}
// Put the group nodes as content
Dragboard dragboard = row.startDragAndDrop(TransferMode.MOVE);
// Display the group when dragging
dragboard.setDragView(row.snapshot(null, null));
ClipboardContent content = new ClipboardContent();
content.put(DragAndDropDataFormats.GROUP, groupsToMove);
dragboard.setContent(content);
event.consume();
}
private void handleOnDragDropped(TreeTableRow<GroupNodeViewModel> row, GroupNodeViewModel originalItem, DragEvent event) {
Dragboard dragboard = event.getDragboard();
boolean success = false;
if (dragboard.hasContent(DragAndDropDataFormats.GROUP) && row.getItem().canAddGroupsIn()) {
List<String> pathToSources = (List<String>) dragboard.getContent(DragAndDropDataFormats.GROUP);
List<GroupNodeViewModel> changedGroups = new LinkedList<>();
for (String pathToSource : pathToSources) {
Optional<GroupNodeViewModel> source = viewModel
.rootGroupProperty().get()
.getChildByPath(pathToSource);
if (source.isPresent() && source.get().canBeDragged()) {
source.get().draggedOn(row.getItem(), ControlHelper.getDroppingMouseLocation(row, event));
changedGroups.add(source.get());
success = true;
}
}
groupTree.getSelectionModel().clearSelection();
changedGroups.forEach(value -> selectNode(value, true));
if (success) {
viewModel.writeGroupChangesToMetaData();
}
}
if (localDragboard.hasBibEntries()) {
List<BibEntry> entries = localDragboard.getBibEntries();
row.getItem().addEntriesToGroup(entries);
success = true;
}
event.setDropCompleted(success);
event.consume();
}
private void handleOnDragOver(TreeTableRow<GroupNodeViewModel> row, GroupNodeViewModel originalItem, DragEvent event) {
Dragboard dragboard = event.getDragboard();
if ((event.getGestureSource() != row) && (row.getItem() != null) && row.getItem().acceptableDrop(dragboard)) {
event.acceptTransferModes(TransferMode.MOVE, TransferMode.LINK);
// expand node and all children on drag over
dragExpansionHandler.expandGroup(row.getTreeItem());
if (localDragboard.hasBibEntries()) {
ControlHelper.setDroppingPseudoClasses(row);
} else {
ControlHelper.setDroppingPseudoClasses(row, event);
}
}
event.consume();
}
private void updateSelection(List<TreeItem<GroupNodeViewModel>> newSelectedGroups) {
if ((newSelectedGroups == null) || newSelectedGroups.isEmpty()) {
viewModel.selectedGroupsProperty().clear();
} else {
List<GroupNodeViewModel> list = newSelectedGroups.stream().filter(model -> (model != null) && !(model.getValue().getGroupNode().getGroup() instanceof AllEntriesGroup)).map(TreeItem::getValue).collect(Collectors.toList());
viewModel.selectedGroupsProperty().setAll(list);
}
}
private void selectNode(GroupNodeViewModel value) {
selectNode(value, false);
}
private void selectNode(GroupNodeViewModel value, boolean expandParents) {
getTreeItemByValue(value)
.ifPresent(treeItem -> {
if (expandParents) {
TreeItem<GroupNodeViewModel> parent = treeItem.getParent();
while (parent != null) {
parent.setExpanded(true);
parent = parent.getParent();
}
}
groupTree.getSelectionModel().select(treeItem);
});
}
private Optional<TreeItem<GroupNodeViewModel>> getTreeItemByValue(GroupNodeViewModel value) {
return getTreeItemByValue(groupTree.getRoot(), value);
}
private Optional<TreeItem<GroupNodeViewModel>> getTreeItemByValue(TreeItem<GroupNodeViewModel> root,
GroupNodeViewModel value) {
if (root == null) {
return Optional.empty();
}
if (root.getValue().equals(value)) {
return Optional.of(root);
}
Optional<TreeItem<GroupNodeViewModel>> node = Optional.empty();
for (TreeItem<GroupNodeViewModel> child : root.getChildren()) {
node = getTreeItemByValue(child, value);
if (node.isPresent()) {
break;
}
}
return node;
}
// see http://programmingtipsandtraps.blogspot.com/2015/10/drag-and-drop-in-treetableview-with.html
private void setupDragScrolling() {
scrollTimer = FxTimer.createPeriodic(Duration.ofMillis(20), () ->
getVerticalScrollbar().ifPresent(scrollBar -> {
double newValue = scrollBar.getValue() + scrollVelocity;
newValue = Math.min(newValue, 1d);
newValue = Math.max(newValue, 0d);
scrollBar.setValue(newValue);
}));
groupTree.setOnScroll(event -> scrollTimer.stop());
groupTree.setOnDragDone(event -> scrollTimer.stop());
groupTree.setOnDragEntered(event -> scrollTimer.stop());
groupTree.setOnDragDropped(event -> scrollTimer.stop());
groupTree.setOnDragExited(event -> {
if (event.getY() > 0) {
scrollVelocity = 1.0 / SCROLL_SPEED;
} else {
scrollVelocity = -1.0 / SCROLL_SPEED;
}
scrollTimer.restart();
});
}
private Optional<ScrollBar> getVerticalScrollbar() {
for (Node node : groupTree.lookupAll(".scroll-bar")) {
if (node instanceof ScrollBar scrollbar
&& scrollbar.getOrientation().equals(Orientation.VERTICAL)) {
return Optional.of(scrollbar);
}
}
return Optional.empty();
}
private ContextMenu createContextMenuForGroup(GroupNodeViewModel group) {
if (group == null) {
return null;
}
ContextMenu contextMenu = new ContextMenu();
ActionFactory factory = new ActionFactory(Globals.getKeyPrefs());
MenuItem removeGroup;
if (group.hasSubgroups() && group.canAddGroupsIn() && !group.isRoot()) {
removeGroup = new Menu(Localization.lang("Remove group"), null,
factory.createMenuItem(StandardActions.GROUP_REMOVE_KEEP_SUBGROUPS,
new GroupTreeView.ContextAction(StandardActions.GROUP_REMOVE_KEEP_SUBGROUPS, group)),
factory.createMenuItem(StandardActions.GROUP_REMOVE_WITH_SUBGROUPS,
new GroupTreeView.ContextAction(StandardActions.GROUP_REMOVE_WITH_SUBGROUPS, group))
);
} else {
removeGroup = factory.createMenuItem(StandardActions.GROUP_REMOVE, new GroupTreeView.ContextAction(StandardActions.GROUP_REMOVE, group));
}
contextMenu.getItems().addAll(
factory.createMenuItem(StandardActions.GROUP_EDIT, new ContextAction(StandardActions.GROUP_EDIT, group)),
removeGroup,
new SeparatorMenuItem(),
factory.createMenuItem(StandardActions.GROUP_SUBGROUP_ADD, new ContextAction(StandardActions.GROUP_SUBGROUP_ADD, group)),
factory.createMenuItem(StandardActions.GROUP_SUBGROUP_REMOVE, new ContextAction(StandardActions.GROUP_SUBGROUP_REMOVE, group)),
factory.createMenuItem(StandardActions.GROUP_SUBGROUP_SORT, new ContextAction(StandardActions.GROUP_SUBGROUP_SORT, group)),
new SeparatorMenuItem(),
factory.createMenuItem(StandardActions.GROUP_ENTRIES_ADD, new ContextAction(StandardActions.GROUP_ENTRIES_ADD, group)),
factory.createMenuItem(StandardActions.GROUP_ENTRIES_REMOVE, new ContextAction(StandardActions.GROUP_ENTRIES_REMOVE, group))
);
contextMenu.getItems().forEach(item -> item.setGraphic(null));
contextMenu.getStyleClass().add("context-menu");
return contextMenu;
}
private void addNewGroup() {
viewModel.addNewGroupToRoot();
}
private String getFormattedNumber(int hits) {
if (hits >= 1000000) {
double millions = hits / 1000000.0;
return new DecimalFormat("#,##0.#").format(millions) + "m";
} else if (hits >= 1000) {
double thousands = hits / 1000.0;
return new DecimalFormat("#,##0.#").format(thousands) + "k";
}
return Integer.toString(hits);
}
// ToDo: reflective access, should be removed
// Workaround taken from https://github.com/controlsfx/controlsfx/issues/330
private void setupClearButtonField(CustomTextField customTextField) {
try {
Method m = TextFields.class.getDeclaredMethod("setupClearButtonField", TextField.class, ObjectProperty.class);
m.setAccessible(true);
m.invoke(null, customTextField, customTextField.rightProperty());
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
LOGGER.error("Failed to decorate text field with clear button", ex);
}
}
private static class DragExpansionHandler {
private static final long DRAG_TIME_BEFORE_EXPANDING_MS = 1000;
private TreeItem<GroupNodeViewModel> draggedItem;
private long dragStarted;
public void expandGroup(TreeItem<GroupNodeViewModel> treeItem) {
if (!treeItem.equals(draggedItem)) {
this.draggedItem = treeItem;
this.dragStarted = System.currentTimeMillis();
this.draggedItem.setExpanded(this.draggedItem.isExpanded());
return;
}
if ((System.currentTimeMillis() - this.dragStarted) > DRAG_TIME_BEFORE_EXPANDING_MS) {
// expand or collapse the tree item and reset the time
this.dragStarted = System.currentTimeMillis();
this.draggedItem.setExpanded(!this.draggedItem.isExpanded());
} else {
// leave the expansion state of the tree item as it is
this.draggedItem.setExpanded(this.draggedItem.isExpanded());
}
}
}
private class ContextAction extends SimpleCommand {
private final StandardActions command;
private final GroupNodeViewModel group;
public ContextAction(StandardActions command, GroupNodeViewModel group) {
this.command = command;
this.group = group;
this.executable.bind(BindingsHelper.constantOf(
switch (command) {
case GROUP_EDIT ->
group.isEditable();
case GROUP_REMOVE, GROUP_REMOVE_WITH_SUBGROUPS, GROUP_REMOVE_KEEP_SUBGROUPS ->
group.isEditable() && group.canRemove();
case GROUP_SUBGROUP_ADD ->
group.isEditable() && group.canAddGroupsIn()
|| group.isRoot();
case GROUP_SUBGROUP_REMOVE ->
group.isEditable() && group.hasSubgroups() && group.canRemove()
|| group.isRoot();
case GROUP_SUBGROUP_SORT ->
group.isEditable() && group.hasSubgroups() && group.canAddEntriesIn()
|| group.isRoot();
case GROUP_ENTRIES_ADD, GROUP_ENTRIES_REMOVE ->
group.canAddEntriesIn();
default ->
true;
}));
}
@Override
public void execute() {
switch (command) {
case GROUP_REMOVE ->
viewModel.removeGroupNoSubgroups(group);
case GROUP_REMOVE_KEEP_SUBGROUPS ->
viewModel.removeGroupKeepSubgroups(group);
case GROUP_REMOVE_WITH_SUBGROUPS ->
viewModel.removeGroupAndSubgroups(group);
case GROUP_EDIT -> {
viewModel.editGroup(group);
groupTree.refresh();
}
case GROUP_SUBGROUP_ADD ->
viewModel.addNewSubgroup(group, GroupDialogHeader.SUBGROUP);
case GROUP_SUBGROUP_REMOVE ->
viewModel.removeSubgroups(group);
case GROUP_SUBGROUP_SORT ->
viewModel.sortAlphabeticallyRecursive(group.getGroupNode());
case GROUP_ENTRIES_ADD ->
viewModel.addSelectedEntries(group);
case GROUP_ENTRIES_REMOVE ->
viewModel.removeSelectedEntries(group);
}
}
}
/**
* Focus on GroupTree
*/
public void requestFocusGroupTree() {
groupTree.requestFocus();
}
}