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