org.reactfx.value.Var Java Examples

The following examples show how to use org.reactfx.value.Var. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SourceEditorController.java    From pmd-designer with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void initializeLanguageSelector() {

        languageVersionChoicebox.setConverter(DesignerUtil.stringConverter(LanguageVersion::getName, AuxLanguageRegistry::getLanguageVersionByName));

        getService(DesignerRoot.APP_GLOBAL_LANGUAGE)
            .values()
            .filter(Objects::nonNull)
            .subscribe(lang -> {
                languageVersionChoicebox.setItems(lang.getVersions().stream().sorted().collect(Collectors.toCollection(LiveArrayList::new)));
                languageVersionChoicebox.getSelectionModel().select(lang.getDefaultVersion());
                boolean disable = lang.getVersions().size() == 1;

                languageVersionChoicebox.setVisible(!disable);
                languageVersionChoicebox.setManaged(!disable);
            });


        languageVersionUIProperty = Var.suspendable(languageVersionChoicebox.valueProperty());
        // this will be overwritten by property restore if needed
        languageVersionUIProperty.setValue(defaultLanguageVersion());
    }
 
Example #2
Source File: SuspenderStreamTest.java    From ReactFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void test() {
    SuspendableVar<String> a = Var.newSimpleVar("foo").suspendable();
    Counter counter = new Counter();
    a.addListener((obs, oldVal, newVal) -> counter.inc());

    EventSource<Void> src = new EventSource<>();
    EventStream<Void> suspender = src.suspenderOf(a);

    suspender.hook(x -> a.setValue("bar")).subscribe(x -> {
        assertEquals(0, counter.get());
    });

    src.push(null);
    assertEquals(1, counter.get());
}
 
Example #3
Source File: ListRangeReductionTest.java    From ReactFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void test() {
    LiveList<Integer> list = new LiveArrayList<>(1, 2, 4);
    Var<IndexRange> range = Var.newSimpleVar(new IndexRange(0, 0));
    Val<Integer> rangeSum = list.reduceRange(range, (a, b) -> a + b);

    assertNull(rangeSum.getValue());

    List<Integer> observed = new ArrayList<>();
    rangeSum.values().subscribe(sum -> {
        observed.add(sum);
        if(sum == null) {
            range.setValue(new IndexRange(0, 2));
        } else if(sum == 3) {
            list.addAll(1, Arrays.asList(8, 16));
        } else if(sum == 9) {
            range.setValue(new IndexRange(2, 4));
        }
    });

    assertEquals(Arrays.asList(null, 3, 9, 18), observed);
}
 
Example #4
Source File: ValAsListTest.java    From ReactFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testNullToValChange() {
    Var<String> src = Var.newSimpleVar(null);
    LiveList<String> list = src.asList();
    assertEquals(0, list.size());

    List<ListModification<? extends String>> mods = new ArrayList<>();
    list.observeModifications(mods::add);

    src.setValue("foo");
    assertEquals(1, mods.size());
    ListModification<? extends String> mod = mods.get(0);
    assertEquals(0, mod.getRemovedSize());
    assertEquals(Collections.singletonList("foo"), mod.getAddedSubList());
    assertEquals(1, list.size());
}
 
Example #5
Source File: ListMapTest.java    From ReactFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testDynamicMap() {
    LiveList<String> strings = new LiveArrayList<>("1", "22", "333");
    Var<Function<String, Integer>> fn = Var.newSimpleVar(String::length);
    SuspendableList<Integer> ints = strings.mapDynamic(fn).suspendable();

    assertEquals(2, ints.get(1).intValue());

    ints.observeChanges(ch -> {
        for(ListModification<?> mod: ch) {
            assertEquals(Arrays.asList(1, 2, 3), mod.getRemoved());
            assertEquals(Arrays.asList(1, 16, 9), mod.getAddedSubList());
        }
    });

    ints.suspendWhile(() -> {
        strings.set(1, "4444");
        fn.setValue(s -> s.length() * s.length());
    });
}
 
Example #6
Source File: ValAsListTest.java    From ReactFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testValToNullChange() {
    Var<String> src = Var.newSimpleVar("foo");
    LiveList<String> list = src.asList();
    assertEquals(1, list.size());

    List<ListModification<? extends String>> mods = new ArrayList<>();
    list.observeModifications(mods::add);

    src.setValue(null);
    assertEquals(1, mods.size());
    ListModification<? extends String> mod = mods.get(0);
    assertEquals(Collections.singletonList("foo"), mod.getRemoved());
    assertEquals(0, mod.getAddedSize());
    assertEquals(0, list.size());
}
 
Example #7
Source File: SmartTextFieldListCell.java    From pmd-designer with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private TextField getEditingGraphic(T t) {
    Var<String> stringVar = extractEditable(t);
    final TextField textField = new TextField(stringVar.getValue());

    textField.setPromptText(getPrompt());
    ControlUtil.makeTextFieldShowPromptEvenIfFocused(textField);

    // Use onAction here rather than onKeyReleased (with check for Enter),
    // as otherwise we encounter RT-34685
    textField.setOnAction(event -> {
        stringVar.setValue(textField.getText());
        commitEdit(t);
        event.consume();
    });
    textField.setOnKeyReleased(ke -> {
        if (ke.getCode() == KeyCode.ESCAPE) {
            cancelEdit();
            ke.consume();
        }
    });
    return textField;
}
 
Example #8
Source File: ListReductionTest.java    From ReactFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testWhenBound() {
    ObservableList<Integer> list = FXCollections.observableArrayList(1, 1, 1, 1, 1);
    Val<Integer> sum = LiveList.reduce(list, (a, b) -> a + b);
    Var<Integer> lastObserved = Var.newSimpleVar(sum.getValue());

    assertEquals(5, lastObserved.getValue().intValue());

    sum.addListener((obs, oldVal, newVal) -> {
        assertEquals(lastObserved.getValue(), oldVal);
        lastObserved.setValue(newVal);
    });

    list.addAll(2, Arrays.asList(2, 2));
    assertEquals(9, lastObserved.getValue().intValue());

    list.subList(3, 6).clear();
    assertEquals(5, lastObserved.getValue().intValue());
}
 
Example #9
Source File: ScaledVirtualized.java    From Flowless with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ScaledVirtualized(V content) {
    super();
    this.content = content;
    getChildren().add(content);
    getTransforms().add(zoom);

    estHeight = Val.combine(
            content.totalHeightEstimateProperty(),
            zoom.yProperty(),
            (estHeight, scaleFactor) -> estHeight * scaleFactor.doubleValue()
    );
    estWidth = Val.combine(
            content.totalWidthEstimateProperty(),
            zoom.xProperty(),
            (estWidth, scaleFactor) -> estWidth * scaleFactor.doubleValue()
    );
    estScrollX = Var.mapBidirectional(
            content.estimatedScrollXProperty(),
            scrollX -> scrollX * zoom.getX(),
            scrollX -> scrollX / zoom.getX()
    );
    estScrollY = Var.mapBidirectional(
            content.estimatedScrollYProperty(),
            scrollY -> scrollY * zoom.getY(),
            scrollY -> scrollY / zoom.getY()
    );

    zoom.xProperty()     .addListener((obs, ov, nv) -> requestLayout());
    zoom.yProperty()     .addListener((obs, ov, nv) -> requestLayout());
    zoom.zProperty()     .addListener((obs, ov, nv) -> requestLayout());
    zoom.pivotXProperty().addListener((obs, ov, nv) -> requestLayout());
    zoom.pivotYProperty().addListener((obs, ov, nv) -> requestLayout());
    zoom.pivotZProperty().addListener((obs, ov, nv) -> requestLayout());
}
 
Example #10
Source File: LanguageVersionRangeSlider.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Var<LanguageVersion> minVersionProperty() {
    return Var.mapBidirectional(
        lowValueProperty(),
        num -> fromIndex(num.intValue()),
        ver -> ver == null ? -1 : curVersions.indexOf(ver)
    );
}
 
Example #11
Source File: PropertyMapModel.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static Pair<ObservableMap<PropertyDescriptorSpec, Var<String>>, RebindSubscription<ObservableList<PropertyDescriptorSpec>>> localMapper(ObservableList<PropertyDescriptorSpec> props) {

        ObservableMap<PropertyDescriptorSpec, Var<String>> mapping = observableHashMap();

        RebindSubscription<ObservableList<PropertyDescriptorSpec>> lstSub = ReactfxExtensions.dynamicRecombine(props, (addedP, i) -> {
            mapping.put(addedP, defaultedVar(addedP.valueProperty()));
            return makeDefault(addedP, mapping);
        });

        return new Pair<>(mapping, lstSub);
    }
 
Example #12
Source File: PropertyMapModel.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static RebindSubscription<PropertyDescriptorSpec> makeDefault(PropertyDescriptorSpec p, ObservableMap<PropertyDescriptorSpec, Var<String>> mapping) {
    return RebindSubscription.make(
        () -> mapping.remove(p),
        addedP -> {
            if (addedP == p) {
                return makeDefault(p, mapping);
            } else {
                mapping.remove(p);
                mapping.put(addedP, defaultedVar(addedP.valueProperty()));
                return makeDefault(addedP, mapping);
            }
        }
    );
}
 
Example #13
Source File: SourceEditorController.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Refreshes the AST and returns the new compilation unit if the parse didn't fail.
 */
private static void initTreeView(ASTManager manager,
                                 AstTreeView treeView,
                                 Var<String> errorMessageProperty) {

    manager.sourceCodeProperty()
           .values()
           .filter(StringUtils::isBlank)
           .subscribe(code -> treeView.setAstRoot(null));

    manager.currentExceptionProperty()
           .values()
           .subscribe(e -> {
               if (e == null) {
                   errorMessageProperty.setValue(null);
               } else {
                   errorMessageProperty.setValue(sanitizeExceptionMessage(e));
               }
           });

    manager.compilationUnitProperty()
           .values()
           .filter(Objects::nonNull)
           .subscribe(node -> {
               errorMessageProperty.setValue("");
               treeView.setAstRoot(node);
           });
}
 
Example #14
Source File: LanguageVersionRangeSlider.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Var<LanguageVersion> maxVersionProperty() {
    return Var.mapBidirectional(
        highValueProperty(),
        num -> fromIndex(num.intValue()),
        ver -> ver == null ? curVersions.size() : curVersions.indexOf(ver)
    );
}
 
Example #15
Source File: FibTest.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) {
    int n = 40;

    FibTest eagerTest = new FibTest(n);
    LongProperty eagerResult = new SimpleLongProperty();
    eagerTest.setupFor(eagerResult);

    FibTest lazyTest = new FibTest(n);
    SuspendableVar<Number> lazyResult = Var.suspendable(Var.newSimpleVar(0L));
    lazyTest.setupFor(lazyResult);

    long t1 = System.currentTimeMillis();
    eagerTest.run();
    long t2 = System.currentTimeMillis();
    double eagerTime = (t2-t1)/1000.0;

    t1 = System.currentTimeMillis();
    Guard g = lazyResult.suspend();
    lazyTest.run();
    g.close();
    t2 = System.currentTimeMillis();
    double lazyTime = (t2-t1)/1000.0;

    System.out.println("EAGER TEST:");
    System.out.println("    fib_" + n + " = " + eagerResult.get());
    System.out.println("    result invalidations: " + eagerTest.invalidationCount);
    System.out.println("    duration: " + eagerTime + " seconds");
    System.out.println();
    System.out.println("LAZY TEST:");
    System.out.println("    fib_" + n + " = " + lazyResult.getValue());
    System.out.println("    result invalidations: " + lazyTest.invalidationCount);
    System.out.println("    duration: " + lazyTime + " seconds");
}
 
Example #16
Source File: AnimatedValDemo.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void start(Stage primaryStage) {
    Circle circle = new Circle(30.0);
    Pane canvas = new Pane(circle);

    // animate circle position
    Var<Point2D> center = Var.newSimpleVar(new Point2D(W/2, H/2));
    Val<Point2D> animCenter = center.animate(
            (p1, p2) -> Duration.ofMillis((long) p1.distance(p2)),
            (p1, p2, frac) -> p1.multiply(1.0-frac).add(p2.multiply(frac)));

    circle.centerXProperty().bind(animCenter.map(Point2D::getX));
    circle.centerYProperty().bind(animCenter.map(Point2D::getY));

    // animate circle color
    Var<Color> color = Var.newSimpleVar(Color.BLUE);
    Val<Color> animColor = Val.animate(color, Duration.ofMillis(500));
    circle.fillProperty().bind(animColor);

    // on click, move to random position and transition to random color
    Random random = new Random();
    circle.setOnMouseClicked(click -> {
        center.setValue(new Point2D(
                random.nextInt(W),
                random.nextInt(H)));
        color.setValue(Color.rgb(
                random.nextInt(240),
                random.nextInt(240),
                random.nextInt(240)));
    });

    primaryStage.setScene(new Scene(canvas, W, H));
    primaryStage.show();
}
 
Example #17
Source File: ListReductionTest.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testMultipleModificationsWhenBound() {
    SuspendableList<Integer> list = new LiveArrayList<>(1, 1, 1, 1, 1).suspendable();
    Val<Integer> sum = list.reduce((a, b) -> a + b);
    Var<Integer> lastObserved = Var.newSimpleVar(null);
    sum.observeChanges((obs, oldVal, newVal) -> lastObserved.setValue(newVal));
    list.suspendWhile(() -> {
        list.addAll(0, Arrays.asList(3, 2));
        list.remove(4, 6);
        list.addAll(4, Arrays.asList(8, 15));
    });
    assertEquals(31, lastObserved.getValue().intValue());
}
 
Example #18
Source File: NodeEditionCodeArea.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public final Var<List<Node>> currentRuleResultsProperty() {
    return currentRuleResults;
}
 
Example #19
Source File: PropertyCollectionView.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected Var<String> extractEditable(PropertyDescriptorSpec propertyDescriptorSpec) {
    return propertyDescriptorSpec.nameProperty();
}
 
Example #20
Source File: ViolationCollectionView.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected Var<String> extractEditable(LiveViolationRecord liveViolationRecord) {
    return liveViolationRecord.messageProperty();
}
 
Example #21
Source File: PropertyMapModel.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public LiveList<Pair<PropertyDescriptorSpec, Var<String>>> asList() {
    return mapBothWays(knownProps, it -> new Pair<>(it, mapping.computeIfAbsent(it, k -> defaultedVar(k.valueProperty()))), Pair::getKey);
}
 
Example #22
Source File: ExportXPathWizardController.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private Var<String> nameProperty() {
    return Var.fromVal(nameField.textProperty(), nameField::setText);
}
 
Example #23
Source File: ReactfxUtil.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static Var<Boolean> booleanVar(BooleanProperty p) {
    return Var.mapBidirectional(p, Boolean::booleanValue, Function.identity());
}
 
Example #24
Source File: LogEntry.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Var<String> detailsProperty() {
    return detailsText;
}
 
Example #25
Source File: VirtualFlow.java    From Flowless with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public Var<Double> estimatedScrollYProperty() {
    return orientation.estimatedScrollYProperty(this);
}
 
Example #26
Source File: SearchableTreeView.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Update the cells to search for anything.
 */
private Subscription bindSearchQuery(ObservableValue<String> query, Var<Integer> numResults, javafx.scene.Node eventSource) {


    Val<List<SearchableTreeItem<T>>> allItems = Val.wrap(rootProperty())
                                                   .map(it1 -> getRealRoot())
                                                   .map(it1 -> {
                                                       List<SearchableTreeItem<T>> tmp = new ArrayList<>();
                                                       it1.foreach(tmp::add);
                                                       return tmp;
                                                   })
                                                   .orElseConst(Collections.emptyList());

    return ReactfxUtil.subscribeDisposable(
        query,
        q -> {

            Val<List<MatchResult<SearchableTreeItem<T>>>> selectedResults =
                allItems.map(it -> selectMatches(q, it));

            return ReactfxUtil.subscribeDisposable(
                selectedResults,
                newRes -> {
                    numResults.setValue(newRes.size());
                    // the values are never null, at most empty, because of orElseConst above
                    newRes.forEach(res -> res.getData().currentSearchResult.setValue(res));
                    Subscription sub = Subscription.EMPTY;
                    if (!newRes.isEmpty()) {

                        Var<Integer> curIdx = Var.newSimpleVar(0);
                        curIdx.values()
                              .subscribe(idx -> {
                                  SearchableTreeItem<T> item = newRes.get(idx).getData();
                                  int row = getRow(item);
                                  getSelectionModel().select(row);

                                  if (!myWrapper.isIndexVisible(row)) {
                                      int safe = row < 3 ? 0 : row - 3;
                                      scrollTo(safe);
                                  }
                              });

                        sub = sub.and(subscribeKeyNav(newRes.size(), curIdx, eventSource));
                    }
                    refresh();
                    return sub;
                }).and(() -> {
                    selectedResults.ifPresent(lst -> lst.forEach(it -> it.getData().currentSearchResult.setValue(null)));
                    refresh();
                });
        }
    );

}
 
Example #27
Source File: ASTManagerImpl.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public Var<ClassLoader> classLoaderProperty() {
    return auxclasspathClassLoader;
}
 
Example #28
Source File: NodeDetailPaneController.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Var<Boolean> hideCommonAttributesProperty() {
    return Var.fromVal(hideCommonAttributesToggle.selectedProperty(), hideCommonAttributesToggle::setSelected);
}
 
Example #29
Source File: PropertyMapModel.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public ObservableMap<PropertyDescriptorSpec, Var<String>> asMap() {
    return mapping;
}
 
Example #30
Source File: ToolbarTitledPane.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Var<String> errorTypeProperty() {
    return errorType;
}