Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EasyBind revision part two #6505

Merged
merged 1 commit into from
May 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions src/main/java/org/jabref/gui/BasePanel.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import java.util.Optional;

import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.geometry.Orientation;
import javafx.scene.Node;
import javafx.scene.control.SplitPane;
Expand Down Expand Up @@ -372,7 +371,7 @@ public void setupMainPanel() {

// Saves the divider position as soon as it changes
// We need to keep a reference to the subscription, otherwise the binding gets garbage collected
dividerPositionSubscription = EasyBind.wrapNullable(Bindings.valueAt(splitPane.getDividers(), 0))
dividerPositionSubscription = EasyBind.valueAt(splitPane.getDividers(), 0)
.mapObservable(SplitPane.Divider::positionProperty)
.subscribeToValues(this::saveDividerLocation);

Expand Down
15 changes: 6 additions & 9 deletions src/main/java/org/jabref/gui/JabRefFrame.java
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ private void initLayout() {
setTop(head);

splitPane.getItems().addAll(sidePane, tabbedPane);
splitPane.setResizableWithParent(sidePane, false);
SplitPane.setResizableWithParent(sidePane, false);

// We need to wait with setting the divider since it gets reset a few times during the initial set-up
mainStage.showingProperty().addListener(new ChangeListener<>() {
Expand Down Expand Up @@ -954,14 +954,11 @@ private Group createTaskIndicator() {
Tooltip someTasksRunning = new Tooltip(Localization.lang("Background Tasks are running"));
Tooltip noTasksRunning = new Tooltip(Localization.lang("Background Tasks are done"));
indicator.setTooltip(noTasksRunning);
stateManager.getAnyTaskRunning().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (newValue.booleanValue()) {
indicator.setTooltip(someTasksRunning);
} else {
indicator.setTooltip(noTasksRunning);
}
stateManager.getAnyTaskRunning().addListener((observable, oldValue, newValue) -> {
if (newValue) {
indicator.setTooltip(someTasksRunning);
} else {
indicator.setTooltip(noTasksRunning);
}
});

Expand Down
21 changes: 9 additions & 12 deletions src/main/java/org/jabref/gui/StateManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@

import javafx.beans.Observable;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ReadOnlyListProperty;
import javafx.beans.property.ReadOnlyListWrapper;
Expand All @@ -27,6 +25,9 @@
import org.jabref.model.groups.GroupTreeNode;
import org.jabref.model.util.OptionalUtil;

import com.tobiasdiez.easybind.EasyBind;
import com.tobiasdiez.easybind.EasyBinding;

/**
* This class manages the GUI-state of JabRef, including:
*
Expand All @@ -48,17 +49,13 @@ public class StateManager {
private final OptionalObjectProperty<SearchQuery> activeSearchQuery = OptionalObjectProperty.empty();
private final ObservableMap<BibDatabaseContext, IntegerProperty> searchResultMap = FXCollections.observableHashMap();
private final OptionalObjectProperty<Node> focusOwner = OptionalObjectProperty.empty();
private final ObservableList<Task<?>> backgroundTasks = FXCollections.observableArrayList(taskProperty -> {
return new Observable[] {taskProperty.progressProperty(), taskProperty.runningProperty()};
private final ObservableList<Task<?>> backgroundTasks = FXCollections.observableArrayList(task -> {
return new Observable[]{task.progressProperty(), task.runningProperty()};
});

private BooleanBinding anyTaskRunning = Bindings.createBooleanBinding(
() -> backgroundTasks.stream().anyMatch(Task::isRunning), backgroundTasks
);
private final EasyBinding<Boolean> anyTaskRunning = EasyBind.reduce(backgroundTasks, tasks -> tasks.anyMatch(Task::isRunning));

private DoubleBinding tasksProgress = Bindings.createDoubleBinding(
() -> backgroundTasks.stream().filter(Task::isRunning).mapToDouble(Task::getProgress).average().orElse(1), backgroundTasks
);
private final EasyBinding<Double> tasksProgress = EasyBind.reduce(backgroundTasks, tasks -> tasks.filter(Task::isRunning).mapToDouble(Task::getProgress).average().orElse(1));

public StateManager() {
activeGroups.bind(Bindings.valueAt(selectedGroups, activeDatabase.orElse(null)));
Expand Down Expand Up @@ -143,11 +140,11 @@ public void addBackgroundTask(Task<?> backgroundTask) {
this.backgroundTasks.add(0, backgroundTask);
}

public BooleanBinding getAnyTaskRunning() {
public EasyBinding<Boolean> getAnyTaskRunning() {
return anyTaskRunning;
}

public DoubleBinding getTasksProgress() {
public EasyBinding<Double> getTasksProgress() {
return tasksProgress;
}
}
14 changes: 7 additions & 7 deletions src/main/java/org/jabref/gui/actions/ActionHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,25 +40,25 @@ public static BooleanExpression isFieldSetForSelectedEntry(Field field, StateMan

public static BooleanExpression isAnyFieldSetForSelectedEntry(List<Field> fields, StateManager stateManager) {
ObservableList<BibEntry> selectedEntries = stateManager.getSelectedEntries();
Binding<Boolean> fieldsAreSet = EasyBind.wrapNullable(Bindings.valueAt(selectedEntries, 0))
Binding<Boolean> fieldsAreSet = EasyBind.valueAt(selectedEntries, 0)
.mapObservable(entry -> Bindings.createBooleanBinding(() -> {
return entry.getFields().stream().anyMatch(fields::contains);
}, entry.getFieldsObservable()))
return entry.getFields().stream().anyMatch(fields::contains);
}, entry.getFieldsObservable()))
.orElse(false);
return BooleanExpression.booleanExpression(fieldsAreSet);
}

public static BooleanExpression isFilePresentForSelectedEntry(StateManager stateManager, PreferencesService preferencesService) {

ObservableList<BibEntry> selectedEntries = stateManager.getSelectedEntries();
Binding<Boolean> fileIsPresent = EasyBind.wrapNullable(Bindings.valueAt(selectedEntries, 0)).map(entry -> {
Binding<Boolean> fileIsPresent = EasyBind.valueAt(selectedEntries, 0).map(entry -> {
List<LinkedFile> files = entry.getFiles();

if ((entry.getFiles().size() > 0) && stateManager.getActiveDatabase().isPresent()) {
Optional<Path> filename = FileHelper.find(
stateManager.getActiveDatabase().get(),
files.get(0).getLink(),
preferencesService.getFilePreferences());
stateManager.getActiveDatabase().get(),
files.get(0).getLink(),
preferencesService.getFilePreferences());
return filename.isPresent();
} else {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public GenerateBibtexKeySingleAction(BibEntry entry, BibDatabaseContext database
this.undoManager = undoManager;

if (preferencesService.getBibtexKeyPatternPreferences().avoidOverwritingCiteKey()) {
this.executable.bind(entry.getCiteKeyBinding().isNull());
this.executable.bind(entry.getCiteKeyBinding().isEmpty());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import javax.swing.undo.UndoManager;

import javafx.beans.binding.ObjectBinding;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

Expand All @@ -18,6 +17,7 @@
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;

import com.tobiasdiez.easybind.EasyObservableValue;
import de.saxsys.mvvmfx.utils.validation.CompositeValidator;
import de.saxsys.mvvmfx.utils.validation.FunctionBasedValidator;
import de.saxsys.mvvmfx.utils.validation.ValidationMessage;
Expand All @@ -30,7 +30,7 @@ public class AbstractEditorViewModel extends AbstractViewModel {
protected BibEntry entry;
private final SuggestionProvider<?> suggestionProvider;
private final CompositeValidator fieldValidator;
private ObjectBinding<String> fieldBinding;
private EasyObservableValue<String> fieldBinding;

public AbstractEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers) {
this.field = field;
Expand All @@ -56,7 +56,7 @@ public void bindToEntry(BibEntry entry) {
this.entry = entry;

// We need to keep a reference to the binding since it otherwise gets discarded
fieldBinding = entry.getFieldBinding(field);
fieldBinding = entry.getFieldBinding(field).asOrdinary();

BindingsHelper.bindBidirectional(
this.textProperty(),
Expand Down
11 changes: 6 additions & 5 deletions src/main/java/org/jabref/gui/groups/GroupNodeViewModel.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
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;
Expand All @@ -39,6 +38,7 @@

import com.google.common.base.Enums;
import com.tobiasdiez.easybind.EasyBind;
import com.tobiasdiez.easybind.EasyObservableList;
import de.jensd.fx.glyphs.materialdesignicons.MaterialDesignIcon;

public class GroupNodeViewModel {
Expand Down Expand Up @@ -76,7 +76,7 @@ public GroupNodeViewModel(BibDatabaseContext databaseContext, StateManager state
.sorted((group1, group2) -> group1.getDisplayName().compareToIgnoreCase(group2.getDisplayName()))
.collect(Collectors.toCollection(FXCollections::observableArrayList));
} else {
children = BindingsHelper.mapBacked(groupNode.getChildren(), this::toViewModel);
children = EasyBind.mapBacked(groupNode.getChildren(), this::toViewModel);
}
hasChildren = new SimpleBooleanProperty();
hasChildren.bind(Bindings.isNotEmpty(children));
Expand All @@ -89,9 +89,10 @@ public GroupNodeViewModel(BibDatabaseContext databaseContext, StateManager state
entriesList = databaseContext.getDatabase().getEntries();
entriesList.addListener(this::onDatabaseChanged);

ObservableList<Boolean> selectedEntriesMatchStatus = EasyBind.map(stateManager.getSelectedEntries(), groupNode::matches);
anySelectedEntriesMatched = BindingsHelper.any(selectedEntriesMatchStatus, matched -> matched);
allSelectedEntriesMatched = BindingsHelper.all(selectedEntriesMatchStatus, matched -> matched);
EasyObservableList<Boolean> selectedEntriesMatchStatus = EasyBind.map(stateManager.getSelectedEntries(), groupNode::matches);
anySelectedEntriesMatched = selectedEntriesMatchStatus.anyMatch(matched -> matched);
// 'all' returns 'true' for empty streams, so this has to be checked explicitly
allSelectedEntriesMatched = selectedEntriesMatchStatus.isEmptyBinding().not().and(selectedEntriesMatchStatus.allMatch(matched -> matched));
}

public GroupNodeViewModel(BibDatabaseContext databaseContext, StateManager stateManager, TaskExecutor taskExecutor, AbstractGroup group, CustomLocalDragboard localDragboard) {
Expand Down
3 changes: 1 addition & 2 deletions src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import java.util.function.Predicate;
import java.util.stream.Collectors;

import javafx.beans.binding.Bindings;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleListProperty;
Expand Down Expand Up @@ -61,7 +60,7 @@ public GroupTreeViewModel(StateManager stateManager, DialogService dialogService
EasyBind.subscribe(selectedGroups, this::onSelectedGroupChanged);

// Set-up bindings
filterPredicate.bind(Bindings.createObjectBinding(() -> group -> group.isMatchedBy(filterText.get()), filterText));
filterPredicate.bind(EasyBind.map(filterText, text -> group -> group.isMatchedBy(text)));

// Init
refresh();
Expand Down
79 changes: 40 additions & 39 deletions src/main/java/org/jabref/gui/maintable/BibEntryTableViewModel.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import java.util.stream.Collectors;

import javafx.beans.binding.Bindings;
import javafx.beans.binding.ObjectBinding;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;

Expand All @@ -28,59 +27,65 @@

import com.tobiasdiez.easybind.EasyBind;
import com.tobiasdiez.easybind.EasyBinding;
import com.tobiasdiez.easybind.optional.OptionalBinding;

public class BibEntryTableViewModel {
private final BibEntry entry;
private final BibDatabase database;
private final MainTableNameFormatter nameFormatter;
private final Map<OrFields, ObservableValue<String>> fieldValues = new HashMap<>();
private final Map<SpecialField, ObservableValue<Optional<SpecialFieldValueViewModel>>> specialFieldValues = new HashMap<>();
private final Map<SpecialField, OptionalBinding<SpecialFieldValueViewModel>> specialFieldValues = new HashMap<>();
private final EasyBinding<List<LinkedFile>> linkedFiles;
private final ObjectBinding<Map<Field, String>> linkedIdentifiers;
private final EasyBinding<Map<Field, String>> linkedIdentifiers;
private final ObservableValue<List<AbstractGroup>> matchedGroups;

public BibEntryTableViewModel(BibEntry entry, BibDatabaseContext database, MainTableNameFormatter nameFormatter) {
this.entry = entry;
this.database = database.getDatabase();
this.nameFormatter = nameFormatter;

this.linkedFiles = EasyBind.map(getField(StandardField.FILE), FileFieldParser::parse);
this.linkedFiles = getField(StandardField.FILE).map(FileFieldParser::parse).orElse(Collections.emptyList());
this.linkedIdentifiers = createLinkedIdentifiersBinding(entry);
this.matchedGroups = createMatchedGroupsBinding(database);
this.matchedGroups = createMatchedGroupsBinding(database, entry);
}

private ObjectBinding<Map<Field, String>> createLinkedIdentifiersBinding(BibEntry entry) {
return Bindings.createObjectBinding(() -> {
private static EasyBinding<Map<Field, String>> createLinkedIdentifiersBinding(BibEntry entry) {
return EasyBind.combine(
entry.getFieldBinding(StandardField.URL),
entry.getFieldBinding(StandardField.DOI),
entry.getFieldBinding(StandardField.URI),
entry.getFieldBinding(StandardField.EPRINT),
(url, doi, uri, eprint) -> {
Map<Field, String> identifiers = new HashMap<>();
entry.getField(StandardField.URL).ifPresent(value -> identifiers.put(StandardField.URL, value));
entry.getField(StandardField.DOI).ifPresent(value -> identifiers.put(StandardField.DOI, value));
entry.getField(StandardField.URI).ifPresent(value -> identifiers.put(StandardField.URI, value));
entry.getField(StandardField.EPRINT).ifPresent(value -> identifiers.put(StandardField.EPRINT, value));
url.ifPresent(value -> identifiers.put(StandardField.URL, value));
doi.ifPresent(value -> identifiers.put(StandardField.DOI, value));
uri.ifPresent(value -> identifiers.put(StandardField.URI, value));
eprint.ifPresent(value -> identifiers.put(StandardField.EPRINT, value));
return identifiers;
},
getEntry().getFieldBinding(StandardField.URL),
getEntry().getFieldBinding(StandardField.DOI),
getEntry().getFieldBinding(StandardField.URI),
getEntry().getFieldBinding(StandardField.EPRINT));
});
}

public BibEntry getEntry() {
return entry;
}

public ObjectBinding<String> getField(Field field) {
return entry.getFieldBinding(field);
private static ObservableValue<List<AbstractGroup>> createMatchedGroupsBinding(BibDatabaseContext database, BibEntry entry) {
Optional<GroupTreeNode> root = database.getMetaData().getGroups();
if (root.isPresent()) {
return EasyBind.map(entry.getFieldBinding(StandardField.GROUPS), field -> {
List<AbstractGroup> groups = root.get().getMatchingGroups(entry)
.stream()
.map(GroupTreeNode::getGroup)
.collect(Collectors.toList());
groups.remove(root.get().getGroup());
return groups;
});
}
return new SimpleObjectProperty<>(Collections.emptyList());
}

public ObservableValue<Optional<SpecialFieldValueViewModel>> getSpecialField(SpecialField field) {
ObservableValue<Optional<SpecialFieldValueViewModel>> value = specialFieldValues.get(field);
if (value != null) {
return value;
} else {
value = EasyBind.map(getField(field), fieldValue -> field.parseValue(fieldValue).map(SpecialFieldValueViewModel::new));
specialFieldValues.put(field, value);
return value;
}
public OptionalBinding<String> getField(Field field) {
return entry.getFieldBinding(field);
}

public ObservableValue<List<LinkedFile>> getLinkedFiles() {
Expand All @@ -95,19 +100,15 @@ public ObservableValue<List<AbstractGroup>> getMatchedGroups() {
return matchedGroups;
}

private ObservableValue<List<AbstractGroup>> createMatchedGroupsBinding(BibDatabaseContext database) {
Optional<GroupTreeNode> root = database.getMetaData().getGroups();
if (root.isPresent()) {
return EasyBind.map(entry.getFieldBinding(StandardField.GROUPS), field -> {
List<AbstractGroup> groups = root.get().getMatchingGroups(entry)
.stream()
.map(GroupTreeNode::getGroup)
.collect(Collectors.toList());
groups.remove(root.get().getGroup());
return groups;
});
public ObservableValue<Optional<SpecialFieldValueViewModel>> getSpecialField(SpecialField field) {
OptionalBinding<SpecialFieldValueViewModel> value = specialFieldValues.get(field);
if (value != null) {
return value;
} else {
value = getField(field).flatMap(fieldValue -> field.parseValue(fieldValue).map(SpecialFieldValueViewModel::new));
specialFieldValues.put(field, value);
return value;
}
return new SimpleObjectProperty<>(Collections.emptyList());
}

public ObservableValue<String> getFields(OrFields fields) {
Expand Down
Loading