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

Shared database synchronized by FocusChangedEvent #6771

Merged
merged 8 commits into from
Sep 1, 2020
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package org.jabref.model.database.event;

import java.util.Optional;

import org.jabref.logic.util.DelayTaskThrottler;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.event.FieldChangedEvent;
import org.jabref.model.entry.field.Field;
Expand All @@ -12,30 +15,56 @@
*/
public class CoarseChangeFilter {

private final EventBus eventBus = new EventBus();
private Field lastFieldChanged;
private final BibDatabaseContext context;
private final EventBus eventBus = new EventBus();
private final DelayTaskThrottler delayPost;

private Optional<Field> lastFieldChanged;
private int totalDelta;

public CoarseChangeFilter(BibDatabaseContext bibDatabaseContext) {
// Listen for change events
bibDatabaseContext.getDatabase().registerListener(this);
bibDatabaseContext.getMetaData().registerListener(this);
this.context = bibDatabaseContext;
// Delay event post by 5 seconds
this.delayPost = new DelayTaskThrottler(5000);
this.lastFieldChanged = Optional.empty();
this.totalDelta = 0;
}

@Subscribe
public synchronized void listen(@SuppressWarnings("unused") BibDatabaseContextChangedEvent event) {
if (!(event instanceof FieldChangedEvent)) {
Runnable eventPost = () -> {
// Reset total change delta
totalDelta = 0;
// Post event
eventBus.post(event);
};

if (!(event instanceof FieldChangedEvent)) {
eventPost.run();
} else {
// Only relay event if the field changes are more than one character or a new field is edited
FieldChangedEvent fieldChange = (FieldChangedEvent) event;
boolean isEditOnNewField = lastFieldChanged == null || !lastFieldChanged.equals(fieldChange.getField());
// Sum up change delta
totalDelta += fieldChange.getDelta();

// If editing is started
boolean isNewEdit = lastFieldChanged.isEmpty();
// If other field is edited
boolean isEditOnOtherField = !lastFieldChanged.get().equals(fieldChange.getField());
// Only deltas of 1 registered by fieldChange, major change means editing much content
boolean isMajorChange = totalDelta >= 100;

if (fieldChange.getDelta() > 1 || isEditOnNewField) {
lastFieldChanged = fieldChange.getField();
eventBus.post(event);
if ((isEditOnOtherField && !isNewEdit) || isMajorChange) {
// Submit old changes immediately
eventPost.run();
} else {
delayPost.schedule(eventPost);
}
// Set new last field
lastFieldChanged = Optional.of(fieldChange.getField());
}
}

Expand Down