01 /*
02 * Copyright 2008-2017 the original author or authors.
03 *
04 * Licensed under the Apache License, Version 2.0 (the "License");
05 * you may not use this file except in compliance with the License.
06 * You may obtain a copy of the License at
07 *
08 * http://www.apache.org/licenses/LICENSE-2.0
09 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package griffon.javafx.collections.transformation;
17
18 import griffon.javafx.collections.ObservableMapBase;
19 import javafx.collections.MapChangeListener;
20 import javafx.collections.ObservableMap;
21 import javafx.collections.WeakMapChangeListener;
22
23 import javax.annotation.Nonnull;
24 import javax.annotation.Nullable;
25 import java.util.Map;
26
27 import static java.util.Objects.requireNonNull;
28
29 /**
30 * @author Andres Almiray
31 * @since 2.11.0
32 */
33 public abstract class TransformationMap<K, V, F> extends ObservableMapBase<K, V> implements ObservableMap<K, V> {
34 private final ObservableMap<K, ? extends F> source;
35 private MapChangeListener<K, F> sourceListener;
36
37 protected TransformationMap(@Nonnull ObservableMap<K, ? extends F> source) {
38 this.source = requireNonNull(source, "Argument 'source' must not be null");
39 source.addListener(new WeakMapChangeListener<>(getListener()));
40 }
41
42 @Nonnull
43 public final ObservableMap<K, ? extends F> getSource() {
44 return source;
45 }
46
47 public MapChangeListener<K, F> getListener() {
48 if (sourceListener == null) {
49 sourceListener = TransformationMap.this::sourceChanged;
50 }
51 return sourceListener;
52 }
53
54 public final boolean isInTransformationChain(@Nullable ObservableMap<?, ?> map) {
55 if (source == map) {
56 return true;
57 }
58 Map<?, ?> currentSource = source;
59 while (currentSource instanceof TransformationMap) {
60 currentSource = ((TransformationMap) currentSource).source;
61 if (currentSource == map) {
62 return true;
63 }
64 }
65 return false;
66 }
67
68 protected abstract void sourceChanged(MapChangeListener.Change<? extends K, ? extends F> c);
69 }
|