/
ContentBehavior.java
506 lines (476 loc) · 19.5 KB
/
ContentBehavior.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
/*******************************************************************************
* Copyright (c) 2014, 2016 itemis AG and others.
* 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
*
* Contributors:
* Alexander Nyßen (itemis AG) - initial API and implementation
*
* Note: Parts of this class have been transferred from org.eclipse.gef.editparts.AbstractEditPart.
*
*******************************************************************************/
package org.eclipse.gef.mvc.fx.behaviors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.eclipse.gef.common.collections.SetMultimapChangeListener;
import org.eclipse.gef.common.dispose.IDisposable;
import org.eclipse.gef.mvc.fx.models.HoverModel;
import org.eclipse.gef.mvc.fx.models.SelectionModel;
import org.eclipse.gef.mvc.fx.parts.IContentPart;
import org.eclipse.gef.mvc.fx.parts.IContentPartFactory;
import org.eclipse.gef.mvc.fx.parts.IRootPart;
import org.eclipse.gef.mvc.fx.parts.IVisualPart;
import org.eclipse.gef.mvc.fx.parts.PartUtils;
import org.eclipse.gef.mvc.fx.viewer.IViewer;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
import javafx.beans.property.ReadOnlyProperty;
import javafx.collections.ListChangeListener;
import javafx.collections.MapChangeListener;
import javafx.scene.Node;
/**
* A behavior that can be adapted to an {@link IRootPart} or an
* {@link IContentPart} to synchronize the list of {@link IContentPart} children
* and (only in case of an {@link IContentPart}) anchorages with the list of
* content children and anchored.
*
* @author anyssen
*
*/
public class ContentBehavior extends AbstractBehavior implements IDisposable {
private ListChangeListener<Object> contentModelObserver = new ListChangeListener<Object>() {
@Override
public void onChanged(
ListChangeListener.Change<? extends Object> change) {
System.out.println("Content changed " + change);
// XXX: An atomic operation (including setAll()) on the
// ObservableList will lead to an atomic change here; we do not have
// to iterate through the individual changes but may simply
// synchronize with the list as it emerges after the changes have
// been applied.
// while (change.next()) {
// if (change.wasRemoved()) {
// removeContentPartChildren(getHost(),
// ImmutableList.copyOf(change.getRemoved()));
// } else if (change.wasAdded()) {
// addContentPartChildren(getHost(),
// ImmutableList.copyOf(change.getAddedSubList()),
// change.getFrom());
// } else if (change.wasPermutated()) {
// throw new UnsupportedOperationException(
// "Reorder not yet implemented");
// }
// }
synchronizeContentPartChildren(getHost(), change.getList());
// TODO: Check if the flushing of the viewer models can be done in a
// more appropriate place.
IViewer viewer = getHost().getRoot().getViewer();
SelectionModel selectionModel = viewer
.getAdapter(SelectionModel.class);
if (selectionModel != null) {
selectionModel.clearSelection();
}
HoverModel hoverModel = viewer.getAdapter(HoverModel.class);
if (hoverModel != null) {
hoverModel.clearHover();
}
}
};
private ListChangeListener<Object> contentChildrenObserver = new ListChangeListener<Object>() {
@SuppressWarnings("unchecked")
@Override
public void onChanged(
final ListChangeListener.Change<? extends Object> change) {
System.out.println("Content children changed " + change);
// XXX: An atomic operation (including setAll()) on the
// ObservableList will lead to an atomic change here; we do not have
// to iterate through the individual changes but may simply
// synchronize with the list as it emerges after the changes have
// been applied.
IContentPart<? extends Node> parent = (IContentPart<? extends Node>) ((ReadOnlyProperty<?>) change
.getList()).getBean();
// while (change.next()) {
// if (change.wasRemoved()) {
// removeContentPartChildren(parent,
// ImmutableList.copyOf(change.getRemoved()));
// } else if (change.wasAdded()) {
// addContentPartChildren(parent,
// ImmutableList.copyOf(change.getAddedSubList()),
// change.getFrom());
// } else if (change.wasPermutated()) {
// throw new UnsupportedOperationException(
// "Reorder not yet implemented");
// }
// }
synchronizeContentPartChildren(parent, change.getList());
}
};
private SetMultimapChangeListener<Object, String> contentAnchoragesObserver = new SetMultimapChangeListener<Object, String>() {
@SuppressWarnings("unchecked")
@Override
public void onChanged(
final SetMultimapChangeListener.Change<? extends Object, ? extends String> change) {
System.out.println("Content anchorages changed " + change);
// XXX: An atomic operation (including replaceAll()) on the
// ObservableSetMultimap will lead to an atomic change here; we do
// not have to iterate through the individual changes but may simply
// synchronize with the list as it emerges after the changes have
// been applied.
// TODO: detach or attach directly
IContentPart<? extends Node> anchored = (IContentPart<? extends Node>) ((ReadOnlyProperty<?>) change
.getSetMultimap()).getBean();
synchronizeContentPartAnchorages(anchored,
HashMultimap.create(change.getSetMultimap()));
}
};
private MapChangeListener<Object, IContentPart<? extends Node>> contentPartMapObserver = new MapChangeListener<Object, IContentPart<? extends Node>>() {
@Override
public void onChanged(
MapChangeListener.Change<? extends Object, ? extends IContentPart<? extends Node>> change) {
if (change.wasRemoved()) {
IContentPart<? extends Node> contentPart = change
.getValueRemoved();
contentPart.contentChildrenUnmodifiableProperty()
.removeListener(contentChildrenObserver);
contentPart.contentAnchoragesUnmodifiableProperty()
.removeListener(contentAnchoragesObserver);
}
if (change.wasAdded()) {
IContentPart<? extends Node> contentPart = change
.getValueAdded();
contentPart.contentChildrenUnmodifiableProperty()
.addListener(contentChildrenObserver);
contentPart.contentAnchoragesUnmodifiableProperty()
.addListener(contentAnchoragesObserver);
}
}
};
// private void addContentPartChildren(IVisualPart<? extends Node> parent,
// final List<? extends Object> contentChildren, int index) {
// // find all content parts for which no content element exists in
// // contentChildren, and therefore have to be removed
// for (Object contentChild : contentChildren) {
// IContentPart<? extends Node> contentPart = findOrCreatePartFor(
// contentChild);
// if (contentPart.getParent() != null) {
// // TODO: Up to now a model element may only be controlled by
// // a single content part; unless we differentiate content
// // elements by context (which is not covered by the current
// // content part map implementation) it is an illegal state
// // if we locate a content part, which is already bound to a
// // parent and whose content is equal to the one we are
// // processing here.
// throw new IllegalStateException(
// "Located a ContentPart which controls the same (or an equal) content
// element but is already bound to a parent. A content element may only be
// controlled by a single ContentPart.");
// }
// parent.addChild(contentPart,
// index + contentChildren.indexOf(contentChild));
// }
// }
@SuppressWarnings("unchecked")
private List<IContentPart<? extends Node>> addAll(
IVisualPart<? extends Node> parent,
List<? extends Object> contentChildren) {
List<IContentPart<? extends Node>> childContentParts = PartUtils
.filterParts(parent.getChildrenUnmodifiable(),
IContentPart.class);
List<IContentPart<? extends Node>> added = new ArrayList<>();
// store the existing content parts in a map using the contents as keys
Map<Object, IContentPart<? extends Node>> contentPartMap = new HashMap<>();
// find all content parts for which no content element exists in
// contentChildren, and therefore have to be removed
for (IContentPart<? extends Node> contentPart : childContentParts) {
// store content part in map
contentPartMap.put(contentPart.getContent(), contentPart);
}
int contentChildrenSize = contentChildren.size();
int childContentPartsSize = childContentParts.size();
for (int i = 0; i < contentChildrenSize; i++) {
Object content = contentChildren.get(i);
// Do a quick check to see if the existing content part is at
// the
// correct location in the children list.
if (i < childContentPartsSize
&& childContentParts.get(i).getContent() == content) {
continue;
}
// Look to see if the ContentPart is already around but in the
// wrong location.
IContentPart<? extends Node> contentPart = findOrCreatePartFor(
content);
if (contentPartMap.containsKey(content)) {
// Re-order the existing content part to its designated
// location in the children list.
// TODO: this is wrong, it has to take into consideration
// the
// visual parts in between
parent.reorderChild(contentPart, i);
} else {
// A ContentPart for this model does not exist yet. Create
// and
// insert one.
if (contentPart.getParent() != null) {
// TODO: Up to now a model element may only be
// controlled by a single content part; unless we
// differentiate content elements by context (which is not
// covered by the current content part map implementation)
// it is an illegal state if we locate a content part, which
// is already bound to a parent and whose content is equal
// to the one we are processing here.
throw new IllegalStateException(
"Located a ContentPart which controls the same (or an equal) content element but is already bound to a parent. A content element may only be controlled by a single ContentPart.");
}
parent.addChild(contentPart, i);
added.add(contentPart);
added.addAll(addAll(contentPart,
contentPart.getContentChildrenUnmodifiable()));
}
}
return added;
}
@SuppressWarnings("unchecked")
private List<IContentPart<? extends Node>> detachAll(
IVisualPart<? extends Node> parent,
final List<? extends Object> contentChildren) {
List<IContentPart<? extends Node>> toRemove = new ArrayList<>();
// only synchronize IContentPart children
// find all content parts for which no content element exists in
// contentChildren, and therefore have to be removed
for (IContentPart<? extends Node> contentPart : (List<IContentPart<? extends Node>>) PartUtils
.filterParts(parent.getChildrenUnmodifiable(),
IContentPart.class)) {
// mark for removal
if (!contentChildren.contains(contentPart.getContent())) {
toRemove.addAll(
detachAll(contentPart, Collections.emptyList()));
toRemove.add(contentPart);
synchronizeContentPartAnchorages(contentPart,
HashMultimap.create());
}
}
return toRemove;
}
@Override
public void dispose() {
// the content part pool is shared by all content behaviors of a viewer,
// so the viewer disposes it.
contentModelObserver = null;
contentChildrenObserver = null;
contentAnchoragesObserver = null;
}
/**
* If the given {@link IContentPart} does neither have a parent nor any
* anchoreds, then it's content is set to <code>null</code> and the part is
* added to the {@link ContentPartPool}.
*
* @param contentPart
* The {@link IContentPart} that is eventually disposed.
*/
protected void disposeIfObsolete(IContentPart<? extends Node> contentPart) {
if (contentPart.getParent() == null
&& contentPart.getAnchoredsUnmodifiable().isEmpty()) {
// System.out.println("DISPOSE " + contentPart.getContent());
getContentPartPool().add(contentPart);
contentPart.setContent(null);
} // else {
// System.out.println("CANNOT DISPOSE " + contentPart.getContent());
// }
}
@Override
protected void doActivate() {
IVisualPart<? extends Node> host = getHost();
if (host != host.getRoot()) {
throw new IllegalArgumentException();
}
IViewer viewer = host.getRoot().getViewer();
viewer.contentPartMapProperty().addListener(contentPartMapObserver);
synchronizeContentPartChildren(getHost(), viewer.getContents());
viewer.getContents().addListener(contentModelObserver);
}
@Override
protected void doDeactivate() {
IVisualPart<? extends Node> host = getHost();
IViewer viewer = host.getRoot().getViewer();
viewer.getContents().removeListener(contentModelObserver);
synchronizeContentPartChildren(getHost(), Collections.emptyList());
viewer.contentPartMapProperty().removeListener(contentPartMapObserver);
}
/**
* Finds/Revives/Creates an {@link IContentPart} for the given
* <i>content</i> {@link Object}. If an {@link IContentPart} for the given
* content {@link Object} can be found in the viewer's content-part-map,
* then this part is returned. If an {@link IContentPart} for the given
* content {@link Object} is stored in the {@link ContentPartPool}, then
* this part is returned. Otherwise, the injected
* {@link IContentPartFactory} is used to create a new {@link IContentPart}
* for the given content {@link Object}.
*
* @param content
* The content {@link Object} for which the corresponding
* {@link IContentPart} is to be returned.
* @return The {@link IContentPart} corresponding to the given
* <i>content</i> {@link Object}.
*/
protected IContentPart<? extends Node> findOrCreatePartFor(Object content) {
Map<Object, IContentPart<? extends Node>> contentPartMap = getHost()
.getRoot().getViewer().getContentPartMap();
if (contentPartMap.containsKey(content)) {
// System.out.println("FOUND " + content);
return contentPartMap.get(content);
} else {
// 'Revive' a content part, if it was removed before
IContentPart<? extends Node> contentPart = getContentPartPool()
.remove(content);
// If the part could not be revived, a new one is created
if (contentPart == null) {
// create part using the factory
// System.out.println("CREATE " + content);
IContentPartFactory contentPartFactory = getContentPartFactory();
contentPart = contentPartFactory.createContentPart(content,
Collections.emptyMap());
if (contentPart == null) {
throw new IllegalStateException("IContentPartFactory '"
+ contentPartFactory.getClass().getSimpleName()
+ "' did not create part for " + content + ".");
}
} // else {
// System.out.println("REVIVE " + content);
// }
// initialize part
contentPart.setContent(content);
return contentPart;
}
}
/**
* Returns the {@link IContentPartFactory} of the current viewer.
*
* @return the {@link IContentPartFactory} of the current viewer.
*/
protected IContentPartFactory getContentPartFactory() {
return getHost().getRoot().getViewer()
.getAdapter(IContentPartFactory.class);
}
/**
* Returns the {@link ContentPartPool} that is used to recycle content parts
* in the context of an {@link IViewer}.
*
* @return The {@link ContentPartPool} of the {@link IViewer}.
*/
protected ContentPartPool getContentPartPool() {
return getHost().getRoot().getViewer()
.getAdapter(ContentPartPool.class);
}
/**
* Updates the host {@link IVisualPart}'s {@link IContentPart} anchorages
* (see {@link IVisualPart#getAnchoragesUnmodifiable()}) so that it is in
* sync with the set of content anchorages that is passed in.
*
* @param anchored
* The anchored {@link IVisualPart} whose content part anchorages
* to synchronize with the given content anchorages.
*
* @param contentAnchorages
* * The map of content anchorages with roles to be synchronized
* with the list of {@link IContentPart} anchorages (
* {@link IContentPart#getAnchoragesUnmodifiable()}).
*
* @see IContentPart#getContentAnchoragesUnmodifiable()
* @see IContentPart#getAnchoragesUnmodifiable()
*/
public void synchronizeContentPartAnchorages(
IVisualPart<? extends Node> anchored,
SetMultimap<? extends Object, ? extends String> contentAnchorages) {
if (contentAnchorages == null) {
throw new IllegalArgumentException(
"contentAnchorages may not be null");
}
SetMultimap<IVisualPart<? extends Node>, String> anchorages = anchored
.getAnchoragesUnmodifiable();
// find anchorages whose content vanished
List<Entry<IVisualPart<? extends Node>, String>> toRemove = new ArrayList<>();
Set<Entry<IVisualPart<? extends Node>, String>> entries = anchorages
.entries();
for (Entry<IVisualPart<? extends Node>, String> e : entries) {
if (!(e.getKey() instanceof IContentPart)) {
continue;
}
Object content = ((IContentPart<? extends Node>) e.getKey())
.getContent();
if (!contentAnchorages.containsEntry(content, e.getValue())) {
toRemove.add(e);
}
}
// Correspondingly remove the anchorages. This is done in a separate
// step to prevent ConcurrentModificationException.
for (Entry<IVisualPart<? extends Node>, String> contentPart : toRemove) {
anchored.detachFromAnchorage(contentPart.getKey(),
contentPart.getValue());
disposeIfObsolete(
(IContentPart<? extends Node>) contentPart.getKey());
}
// find content for which no anchorages exist
List<Entry<IVisualPart<? extends Node>, String>> toAdd = new ArrayList<>();
for (Entry<? extends Object, ? extends String> e : contentAnchorages
.entries()) {
IContentPart<? extends Node> anchorage = findOrCreatePartFor(
e.getKey());
if (!anchorages.containsEntry(anchorage, e.getValue())) {
toAdd.add(
Maps.<IVisualPart<? extends Node>, String> immutableEntry(
anchorage, e.getValue()));
}
}
// Correspondingly add the anchorages. This is done in a separate
// step to prevent ConcurrentModificationException.
for (Entry<IVisualPart<? extends Node>, String> e : toAdd) {
anchored.attachToAnchorage(e.getKey(), e.getValue());
}
}
/**
* Updates the host {@link IVisualPart}'s {@link IContentPart} children (see
* {@link IVisualPart#getChildrenUnmodifiable()}) so that it is in sync with
* the set of content children that is passed in.
*
* @param parent
* The parent {@link IVisualPart} whose content part children to
* synchronize against the given content children.
*
* @param contentChildren
* The list of content part children to be synchronized with the
* list of {@link IContentPart} children (
* {@link IContentPart#getChildrenUnmodifiable()}).
*
* @see IContentPart#getContentChildrenUnmodifiable()
* @see IContentPart#getChildrenUnmodifiable()
*/
public void synchronizeContentPartChildren(
IVisualPart<? extends Node> parent,
final List<? extends Object> contentChildren) {
if (contentChildren == null) {
throw new IllegalArgumentException(
"contentChildren may not be null");
}
List<IContentPart<? extends Node>> toRemove = detachAll(parent,
contentChildren);
for (IContentPart<? extends Node> contentPart : toRemove) {
contentPart.getParent().removeChild(contentPart);
disposeIfObsolete(contentPart);
}
List<IContentPart<? extends Node>> added = addAll(parent,
contentChildren);
for (IContentPart<? extends Node> cp : added) {
synchronizeContentPartAnchorages(cp,
cp.getContentAnchoragesUnmodifiable());
}
}
}