-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathGroupNodeViewModel.java
330 lines (277 loc) · 13 KB
/
GroupNodeViewModel.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
package org.jabref.gui.groups;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.input.Dragboard;
import javafx.scene.paint.Color;
import org.jabref.gui.DragAndDropDataFormats;
import org.jabref.gui.StateManager;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.InternalMaterialDesignIcon;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.gui.util.CustomLocalDragboard;
import org.jabref.gui.util.DroppingMouseLocation;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.groups.DefaultGroupsFactory;
import org.jabref.logic.layout.format.LatexToUnicodeFormatter;
import org.jabref.logic.util.DelayTaskThrottler;
import org.jabref.model.FieldChange;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.groups.AbstractGroup;
import org.jabref.model.groups.AutomaticGroup;
import org.jabref.model.groups.GroupEntryChanger;
import org.jabref.model.groups.GroupTreeNode;
import org.jabref.model.strings.StringUtil;
import com.google.common.base.Enums;
import org.fxmisc.easybind.EasyBind;
public class GroupNodeViewModel {
private final String displayName;
private final boolean isRoot;
private final ObservableList<GroupNodeViewModel> children;
private final BibDatabaseContext databaseContext;
private final StateManager stateManager;
private final GroupTreeNode groupNode;
private final SimpleIntegerProperty hits;
private final SimpleBooleanProperty hasChildren;
private final SimpleBooleanProperty expandedProperty = new SimpleBooleanProperty();
private final BooleanBinding anySelectedEntriesMatched;
private final BooleanBinding allSelectedEntriesMatched;
private final TaskExecutor taskExecutor;
private final CustomLocalDragboard localDragBoard;
private final ObservableList<BibEntry> entriesList;
private final DelayTaskThrottler throttler;
public GroupNodeViewModel(BibDatabaseContext databaseContext, StateManager stateManager, TaskExecutor taskExecutor, GroupTreeNode groupNode, CustomLocalDragboard localDragBoard) {
this.databaseContext = Objects.requireNonNull(databaseContext);
this.taskExecutor = Objects.requireNonNull(taskExecutor);
this.stateManager = Objects.requireNonNull(stateManager);
this.groupNode = Objects.requireNonNull(groupNode);
this.localDragBoard = Objects.requireNonNull(localDragBoard);
displayName = new LatexToUnicodeFormatter().format(groupNode.getName());
isRoot = groupNode.isRoot();
if (groupNode.getGroup() instanceof AutomaticGroup) {
AutomaticGroup automaticGroup = (AutomaticGroup) groupNode.getGroup();
children = automaticGroup.createSubgroups(this.databaseContext.getDatabase().getEntries())
.stream()
.map(this::toViewModel)
.sorted((group1, group2) -> group1.getDisplayName().compareToIgnoreCase(group2.getDisplayName()))
.collect(Collectors.toCollection(FXCollections::observableArrayList));
} else {
children = BindingsHelper.mapBacked(groupNode.getChildren(), this::toViewModel);
}
hasChildren = new SimpleBooleanProperty();
hasChildren.bind(Bindings.isNotEmpty(children));
hits = new SimpleIntegerProperty(0);
calculateNumberOfMatches();
expandedProperty.set(groupNode.getGroup().isExpanded());
expandedProperty.addListener((observable, oldValue, newValue) -> groupNode.getGroup().setExpanded(newValue));
// Register listener
// The wrapper created by the FXCollections will set a weak listener on the wrapped list. This weak listener gets garbage collected. Hence, we need to maintain a reference to this list.
entriesList = databaseContext.getDatabase().getEntries();
entriesList.addListener(this::onDatabaseChanged);
throttler = new DelayTaskThrottler(1000);
ObservableList<Boolean> selectedEntriesMatchStatus = EasyBind.map(stateManager.getSelectedEntries(), groupNode::matches);
anySelectedEntriesMatched = BindingsHelper.any(selectedEntriesMatchStatus, matched -> matched);
allSelectedEntriesMatched = BindingsHelper.all(selectedEntriesMatchStatus, matched -> matched);
}
public GroupNodeViewModel(BibDatabaseContext databaseContext, StateManager stateManager, TaskExecutor taskExecutor, AbstractGroup group, CustomLocalDragboard localDragboard) {
this(databaseContext, stateManager, taskExecutor, new GroupTreeNode(group), localDragboard);
}
static GroupNodeViewModel getAllEntriesGroup(BibDatabaseContext newDatabase, StateManager stateManager, TaskExecutor taskExecutor, CustomLocalDragboard localDragBoard) {
return new GroupNodeViewModel(newDatabase, stateManager, taskExecutor, DefaultGroupsFactory.getAllEntriesGroup(), localDragBoard);
}
private GroupNodeViewModel toViewModel(GroupTreeNode child) {
return new GroupNodeViewModel(databaseContext, stateManager, taskExecutor, child, localDragBoard);
}
public List<FieldChange> addEntriesToGroup(List<BibEntry> entries) {
// TODO: warn if assignment has undesired side effects (modifies a field != keywords)
//if (!WarnAssignmentSideEffects.warnAssignmentSideEffects(group, groupSelector.frame))
//{
// return; // user aborted operation
//}
var changes = groupNode.addEntriesToGroup(entries);
// Update appearance of group
anySelectedEntriesMatched.invalidate();
allSelectedEntriesMatched.invalidate();
return changes;
// TODO: Store undo
// if (!undo.isEmpty()) {
// groupSelector.concludeAssignment(UndoableChangeEntriesOfGroup.getUndoableEdit(target, undo), target.getNode(), assignedEntries);
}
public SimpleBooleanProperty expandedProperty() {
return expandedProperty;
}
public BooleanBinding anySelectedEntriesMatchedProperty() {
return anySelectedEntriesMatched;
}
public BooleanBinding allSelectedEntriesMatchedProperty() {
return allSelectedEntriesMatched;
}
public SimpleBooleanProperty hasChildrenProperty() {
return hasChildren;
}
public String getDisplayName() {
return displayName;
}
public boolean isRoot() {
return isRoot;
}
public String getDescription() {
return groupNode.getGroup().getDescription().orElse("");
}
public SimpleIntegerProperty getHits() {
return hits;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if ((o == null) || (getClass() != o.getClass())) {
return false;
}
GroupNodeViewModel that = (GroupNodeViewModel) o;
return groupNode.equals(that.groupNode);
}
@Override
public String toString() {
return "GroupNodeViewModel{" +
"displayName='" + displayName + '\'' +
", isRoot=" + isRoot +
", icon='" + getIcon() + '\'' +
", children=" + children +
", databaseContext=" + databaseContext +
", groupNode=" + groupNode +
", hits=" + hits +
'}';
}
@Override
public int hashCode() {
return groupNode.hashCode();
}
public JabRefIcon getIcon() {
Optional<String> iconName = groupNode.getGroup().getIconName();
return iconName.flatMap(this::parseIcon)
.orElseGet(this::createDefaultIcon);
}
private JabRefIcon createDefaultIcon() {
Color color = groupNode.getGroup().getColor().orElse(IconTheme.getDefaultGroupColor());
return IconTheme.JabRefIcons.DEFAULT_GROUP_ICON_COLORED.withColor(color);
}
private Optional<JabRefIcon> parseIcon(String iconCode) {
return Enums.getIfPresent(IconTheme.JabRefIcons.class, iconCode.toUpperCase(Locale.ENGLISH))
.toJavaUtil()
.map(icon -> new InternalMaterialDesignIcon(getColor(), icon));
}
public ObservableList<GroupNodeViewModel> getChildren() {
return children;
}
public GroupTreeNode getGroupNode() {
return groupNode;
}
/**
* Gets invoked if an entry in the current database changes.
*/
private void onDatabaseChanged(ListChangeListener.Change<? extends BibEntry> change) {
throttler.schedule(this::calculateNumberOfMatches);
}
private void calculateNumberOfMatches() {
// We calculate the new hit value
// We could be more intelligent and try to figure out the new number of hits based on the entry change
// for example, a previously matched entry gets removed -> hits = hits - 1
BackgroundTask
.wrap(() -> groupNode.calculateNumberOfMatches(databaseContext.getDatabase()))
.onSuccess(hits::setValue)
.executeWith(taskExecutor);
}
public GroupTreeNode addSubgroup(AbstractGroup subgroup) {
return groupNode.addSubgroup(subgroup);
}
void toggleExpansion() {
expandedProperty().set(!expandedProperty().get());
}
boolean isMatchedBy(String searchString) {
return StringUtil.isBlank(searchString) || StringUtil.containsIgnoreCase(getDisplayName(), searchString);
}
public Color getColor() {
return groupNode.getGroup().getColor().orElse(IconTheme.getDefaultGroupColor());
}
public String getPath() {
return groupNode.getPath();
}
public Optional<GroupNodeViewModel> getChildByPath(String pathToSource) {
return groupNode.getChildByPath(pathToSource).map(this::toViewModel);
}
/**
* Decides if the content stored in the given {@link Dragboard} can be droped on the given target row.
* Currently, the following sources are allowed:
* - another group (will be added as subgroup on drop)
* - entries if the group implements {@link GroupEntryChanger} (will be assigned to group on drop)
*/
public boolean acceptableDrop(Dragboard dragboard) {
// TODO: we should also check isNodeDescendant
boolean canDropOtherGroup = dragboard.hasContent(DragAndDropDataFormats.GROUP);
boolean canDropEntries = localDragBoard.hasBibEntries() && (groupNode.getGroup() instanceof GroupEntryChanger);
return canDropOtherGroup || canDropEntries;
}
public void moveTo(GroupNodeViewModel target) {
// TODO: Add undo and display message
//MoveGroupChange undo = new MoveGroupChange(((GroupTreeNodeViewModel)source.getParent()).getNode(),
// source.getNode().getPositionInParent(), target.getNode(), target.getChildCount());
getGroupNode().moveTo(target.getGroupNode());
//panel.getUndoManager().addEdit(new UndoableMoveGroup(this.groupsRoot, moveChange));
//panel.markBaseChanged();
//frame.output(Localization.lang("Moved group \"%0\".", node.getNode().getGroup().getName()));
}
public void moveTo(GroupTreeNode target, int targetIndex) {
getGroupNode().moveTo(target, targetIndex);
}
public Optional<GroupTreeNode> getParent() {
return groupNode.getParent();
}
public void draggedOn(GroupNodeViewModel target, DroppingMouseLocation mouseLocation) {
Optional<GroupTreeNode> targetParent = target.getParent();
if (targetParent.isPresent()) {
int targetIndex = target.getPositionInParent();
// In case we want to move an item in the same parent
// and the item is moved down, we need to adjust the target index
if (targetParent.equals(getParent())) {
int sourceIndex = this.getPositionInParent();
if (sourceIndex < targetIndex) {
targetIndex--;
}
}
// Different actions depending on where the user releases the drop in the target row
// Bottom + top -> insert source row before / after this row
// Center -> add as child
switch (mouseLocation) {
case BOTTOM:
this.moveTo(targetParent.get(), targetIndex + 1);
break;
case CENTER:
this.moveTo(target);
break;
case TOP:
this.moveTo(targetParent.get(), targetIndex);
break;
}
} else {
// No parent = root -> just add
this.moveTo(target);
}
}
private int getPositionInParent() {
return groupNode.getPositionInParent();
}
}