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

convert search worker to javafx #4897

Merged
merged 35 commits into from
Jun 6, 2019
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
b2971ed
convert search worker to javafx
Siedlerchr Apr 18, 2019
6342c8f
Merge remote-tracking branch 'upstream/master' into convertSearchWorker
Siedlerchr Apr 20, 2019
2bb96e2
remove obsolete search worker
Siedlerchr Apr 20, 2019
82a746a
Merge remote-tracking branch 'upstream/master' into convertSearchWorker
Siedlerchr Apr 24, 2019
b374c0e
Add search query update result count
Siedlerchr Apr 24, 2019
669dc1a
Merge remote-tracking branch 'upstream/master' into convertSearchWorker
Siedlerchr May 1, 2019
907670e
First attempt at creating search highlighter for source tab
Siedlerchr May 1, 2019
45020d2
Add custom css for codeArea highlighting on Search
Siedlerchr May 1, 2019
7b01b92
fix exception loop
Siedlerchr May 1, 2019
a4465c2
inline search listener
Siedlerchr May 2, 2019
79e77c5
refactor searchQueryHighlightobservable
Siedlerchr May 3, 2019
11ac5ab
fix checkstyle
Siedlerchr May 3, 2019
2614523
fireSearchQueryHighlitghter on focus change
Siedlerchr May 3, 2019
572b8a1
Merge remote-tracking branch 'upstream/master' into convertSearchWorker
Siedlerchr May 4, 2019
75b089c
Add sample js for highlighting
Siedlerchr May 4, 2019
2b20ecd
add search query highlither to handle the highlighting
Siedlerchr May 4, 2019
6255111
add new regex js
Siedlerchr May 4, 2019
d99edc7
remove highlith listener before adding new one
Siedlerchr May 4, 2019
84758a7
Merge remote-tracking branch 'upstream/master' into convertSearchWorker
Siedlerchr May 6, 2019
75d3ca3
fix merge, move code to new PreviewViewer
Siedlerchr May 6, 2019
2db6403
fix checkstyle
Siedlerchr May 6, 2019
29155ef
Merge remote-tracking branch 'upstream/master' into convertSearchWorker
Siedlerchr May 12, 2019
cd6d181
fix search highlighting in source editor
Siedlerchr May 12, 2019
e419b2d
Merge remote-tracking branch 'upstream/master' into convertSearchWorker
Siedlerchr May 18, 2019
1210a2a
refactor state manager as parameter
Siedlerchr May 18, 2019
d0c5f2e
Get rid of SearchQueryHighlightObservable
Siedlerchr May 19, 2019
32925d8
Merge remote-tracking branch 'upstream/master' into convertSearchWorker
Siedlerchr May 19, 2019
858ffd8
Merge remote-tracking branch 'upstream/master' into convertSearchWorker
Siedlerchr May 25, 2019
6db6073
update on search
Siedlerchr May 25, 2019
ef6b159
Merge remote-tracking branch 'upstream/master' into convertSearchWorker
Siedlerchr May 25, 2019
da17d06
fix checkstyle
Siedlerchr May 25, 2019
63678c2
try again with checkstyle declaration order
Siedlerchr May 25, 2019
1c675db
Merge remote-tracking branch 'upstream/master' into convertSearchWorker
Siedlerchr May 27, 2019
6a220bd
Finally fix the number of search results on multiple libs
Siedlerchr May 27, 2019
752e433
fix checkstyle
Siedlerchr May 27, 2019
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
1 change: 0 additions & 1 deletion src/main/java/org/jabref/gui/BasePanel.java
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,6 @@ public BasePanel(JabRefFrame frame, BasePanelPreferences preferences, BibDatabas
this.entryEditor = new EntryEditor(this, preferences.getEntryEditorPreferences(), Globals.getFileUpdateMonitor(), dialogService, externalFileTypes, Globals.TASK_EXECUTOR);

this.preview = new PreviewPanel(getBibDatabaseContext(), this, dialogService, externalFileTypes, Globals.getKeyPrefs(), preferences.getPreviewPreferences());
frame().getGlobalSearchBar().getSearchQueryHighlightObservable().addSearchListener(preview);
}

@Subscribe
Expand Down
36 changes: 35 additions & 1 deletion src/main/java/org/jabref/gui/StateManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@
import java.util.stream.Collectors;

import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ReadOnlyListProperty;
import javafx.beans.property.ReadOnlyListWrapper;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;

import org.jabref.gui.util.OptionalObjectProperty;
import org.jabref.logic.search.SearchQuery;
import org.jabref.logic.search.SearchQueryHighlightListener;
import org.jabref.logic.search.SearchQueryHighlightObservable;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.groups.GroupTreeNode;
Expand All @@ -34,6 +38,8 @@ public class StateManager {
private final ObservableList<BibEntry> selectedEntries = FXCollections.observableArrayList();
private final ObservableMap<BibDatabaseContext, ObservableList<GroupTreeNode>> selectedGroups = FXCollections.observableHashMap();
private final OptionalObjectProperty<SearchQuery> activeSearchQuery = OptionalObjectProperty.empty();
private final IntegerProperty searchResultSize = new SimpleIntegerProperty();
private final SearchQueryHighlightObservable searchQueryHighlightObservable = new SearchQueryHighlightObservable();
Siedlerchr marked this conversation as resolved.
Show resolved Hide resolved

public StateManager() {
activeGroups.bind(Bindings.valueAt(selectedGroups, activeDatabase.orElse(null)));
Expand Down Expand Up @@ -79,7 +85,7 @@ public Optional<BibDatabaseContext> getActiveDatabase() {

public List<BibEntry> getEntriesInCurrentDatabase() {
return OptionalUtil.flatMap(activeDatabase.get(), BibDatabaseContext::getEntries)
.collect(Collectors.toList());
.collect(Collectors.toList());
}

public void clearSearchQuery() {
Expand All @@ -89,4 +95,32 @@ public void clearSearchQuery() {
public void setSearchQuery(SearchQuery searchQuery) {
activeSearchQuery.setValue(Optional.of(searchQuery));
}

public IntegerProperty searchResultSizeProperty() {
Siedlerchr marked this conversation as resolved.
Show resolved Hide resolved
return searchResultSize;
}

public void setSearchResultSize(int size) {
searchResultSize.setValue(size);
}

public SearchQueryHighlightObservable getSearchQueryHighlightObservable() {
return searchQueryHighlightObservable;
}

public void fireSearchQueryHighlightEvent() {
if (activeSearchQuery.get().isPresent()) {
searchQueryHighlightObservable.fireSearchlistenerEvent(activeSearchQuery.getValue().get());
}
}

public void resetSearchQueryHighlightObservable()
{
searchQueryHighlightObservable.reset();
}

public void addSearchQueryHighlightListener(SearchQueryHighlightListener listener) {
searchQueryHighlightObservable.removeSearchListener(listener);
searchQueryHighlightObservable.addSearchListener(listener);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#bibtexSourceCodeArea .search {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to move this code to the entry editor css?

-fx-fill: red;
}

.bibtexSourceCodeArea .text {
-fx-fill: -fx-text-background-color;
}
2 changes: 0 additions & 2 deletions src/main/java/org/jabref/gui/entryeditor/EntryEditor.css
Original file line number Diff line number Diff line change
Expand Up @@ -87,5 +87,3 @@
.related-articles-tab {
-fx-padding: 20 20 20 20;
}


2 changes: 1 addition & 1 deletion src/main/java/org/jabref/gui/entryeditor/EntryEditor.java
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ private void fetchAndMerge(EntryBasedFetcher fetcher) {
void addSearchListener(SearchQueryHighlightListener listener) {
// TODO: Highlight search text in entry editors
searchListeners.add(listener);
panel.frame().getGlobalSearchBar().getSearchQueryHighlightObservable().addSearchListener(listener);

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove empty line

}

public void setFocusToField(String fieldName) {
Expand Down
32 changes: 25 additions & 7 deletions src/main/java/org/jabref/gui/entryeditor/SourceTab.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.io.StringWriter;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;

import javax.swing.undo.UndoManager;

Expand All @@ -15,6 +16,7 @@
import javafx.scene.control.Tooltip;
import javafx.scene.input.InputMethodRequests;

import org.jabref.Globals;
import org.jabref.gui.DialogService;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.undo.CountingUndoManager;
Expand Down Expand Up @@ -53,10 +55,11 @@ public class SourceTab extends EntryEditorTab {
private final BibDatabaseMode mode;
private final UndoManager undoManager;
private final ObjectProperty<ValidationMessage> sourceIsValid = new SimpleObjectProperty<>();
private final ObservableRuleBasedValidator sourceValidator = new ObservableRuleBasedValidator(sourceIsValid);
@SuppressWarnings("unchecked") private final ObservableRuleBasedValidator sourceValidator = new ObservableRuleBasedValidator(sourceIsValid);
private final ImportFormatPreferences importFormatPreferences;
private final FileUpdateMonitor fileMonitor;
private final DialogService dialogService;
private CodeArea codeArea;

public SourceTab(BibDatabaseContext bibDatabaseContext, CountingUndoManager undoManager, LatexFieldFormatterPreferences fieldFormatterPreferences, ImportFormatPreferences importFormatPreferences, FileUpdateMonitor fileMonitor, DialogService dialogService) {
this.mode = bibDatabaseContext.getMode();
Expand All @@ -69,6 +72,17 @@ public SourceTab(BibDatabaseContext bibDatabaseContext, CountingUndoManager undo
this.fileMonitor = fileMonitor;
this.dialogService = dialogService;

Globals.stateManager.addSearchQueryHighlightListener(highlightPattern -> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please pass stateManager as external dependency.

if (highlightPattern.isPresent() && codeArea != null) {
codeArea.setStyleClass(0, codeArea.getLength(), "text");
Matcher matcher = highlightPattern.get().matcher(codeArea.getText());
while (matcher.find()) {
for (int i = 0; i <= matcher.groupCount(); i++) {
codeArea.setStyleClass(matcher.start(), matcher.end(), "search");
}
}
}
});
}

private static String getSourceString(BibEntry entry, BibDatabaseMode type, LatexFieldFormatterPreferences fieldFormatterPreferences) throws IOException {
Expand Down Expand Up @@ -115,6 +129,9 @@ private CodeArea createSourceEditor() {
codeArea.insertText(codeArea.getCaretPosition(), committed);
}
});
codeArea.setId("bibtexSourceCodeArea");
codeArea.getStylesheets().add(SourceTab.class.getResource("BibtexSourceCodeArea.css").toExternalForm());

return codeArea;
}

Expand All @@ -140,7 +157,7 @@ protected void bindToEntry(BibEntry entry) {
}
});
this.setContent(codeArea);

this.codeArea = codeArea;
// Store source for on focus out event in the source code (within its text area)
// and update source code for every change of entry field values
BindingsHelper.bindContentBidirectional(entry.getFieldsObservable(), codeArea.focusedProperty(), onFocus -> {
Expand All @@ -152,10 +169,12 @@ protected void bindToEntry(BibEntry entry) {
codeArea.clear();
try {
codeArea.appendText(getSourceString(entry, mode, fieldFormatterPreferences));
Globals.stateManager.fireSearchQueryHighlightEvent();

} catch (IOException ex) {
codeArea.setEditable(false);
codeArea.appendText(ex.getMessage() + "\n\n" +
Localization.lang("Correct the entry, and reopen editor to display/edit source."));
Localization.lang("Correct the entry, and reopen editor to display/edit source."));
LOGGER.debug("Incorrect entry", ex);
}
});
Expand Down Expand Up @@ -208,8 +227,7 @@ private void storeSource(BibEntry outOfFocusEntry, String text) {
String fieldValue = field.getValue();

if (InternalBibtexFields.isDisplayableField(fieldName) && !newEntry.hasField(fieldName)) {
compound.addEdit(
new UndoableFieldChange(outOfFocusEntry, fieldName, fieldValue, null));
compound.addEdit(new UndoableFieldChange(outOfFocusEntry, fieldName, fieldValue, null));
outOfFocusEntry.clearField(fieldName);
}
}
Expand All @@ -221,8 +239,7 @@ private void storeSource(BibEntry outOfFocusEntry, String text) {
String newValue = field.getValue();
if (!Objects.equals(oldValue, newValue)) {
// Test if the field is legally set.
new LatexFieldFormatter(fieldFormatterPreferences)
.format(newValue, fieldName);
new LatexFieldFormatter(fieldFormatterPreferences).format(newValue, fieldName);

compound.addEdit(new UndoableFieldChange(outOfFocusEntry, fieldName, oldValue, newValue));
outOfFocusEntry.setField(fieldName, newValue);
Expand All @@ -243,4 +260,5 @@ private void storeSource(BibEntry outOfFocusEntry, String text) {
LOGGER.debug("Incorrect source", ex);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.util.Optional;

import javafx.beans.binding.Bindings;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
Expand All @@ -30,7 +31,11 @@ public MainTableDataModel(BibDatabaseContext context) {
entriesFiltered.predicateProperty().bind(
Bindings.createObjectBinding(() -> this::isMatched,
Globals.stateManager.activeGroupProperty(), Globals.stateManager.activeSearchQueryProperty())

);
entriesFiltered.addListener((ListChangeListener<BibEntryTableViewModel>) c -> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use bindings: Bindings.size(entriesFiltered) ?

Globals.stateManager.setSearchResultSize(entriesFiltered.size());
});

// We need to wrap the list since otherwise sorting in the table does not work
entriesSorted = new SortedList<>(entriesFiltered);
Expand Down
63 changes: 47 additions & 16 deletions src/main/java/org/jabref/gui/preview/PreviewViewer.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.print.PrinterJob;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.ClipboardContent;
Expand Down Expand Up @@ -34,12 +36,21 @@ public class PreviewViewer extends ScrollPane implements InvalidationListener {

private static final Logger LOGGER = LoggerFactory.getLogger(PreviewViewer.class);

private static final String JS_HIGHLIGHT_FUNCTION = " <script type=\"text/javascript\">\r\n" +
" function highlight(text) {\r\n" +
" var innertxt = document.body.innerText;\r\n" +
" var response = innertxt.replace(new RegExp(text, 'gi'), str => `<span style='background-color:red'>${str}</span>`);\r\n" +
" document.body.innerHTML = response;\r\n" +
" }\r\n" +
" </script>";

private final ClipBoardManager clipBoardManager;
private final DialogService dialogService;

private final TaskExecutor taskExecutor = Globals.TASK_EXECUTOR;
private final WebView previewView;
private PreviewLayout layout;

/**
* The entry currently shown
*/
Expand All @@ -59,6 +70,23 @@ public PreviewViewer(BibDatabaseContext database, DialogService dialogService) {
previewView = new WebView();
setContent(previewView);
previewView.setContextMenuEnabled(false);

previewView.getEngine().getLoadWorker().stateProperty().addListener((ObservableValue<? extends Worker.State> observable,
Worker.State oldValue,
Worker.State newValue) -> {
if (newValue != Worker.State.SUCCEEDED) {
return;
}
Globals.stateManager.addSearchQueryHighlightListener(highlightPattern -> {
if (highlightPattern.isPresent()) {
String pattern = highlightPattern.get().pattern().replace("\\Q", "").replace("\\E", "");

previewView.getEngine().executeScript("highlight('" + pattern + "');");

}
});
});

}

public void setLayout(PreviewLayout newLayout) {
Expand Down Expand Up @@ -93,18 +121,21 @@ private void update() {
ExporterFactory.entryNumber = 1; // Set entry number in case that is included in the preview layout.

BackgroundTask
.wrap(() -> layout.generatePreview(entry.get(), database.getDatabase()))
.onRunning(() -> setPreviewText("<i>" + Localization.lang("Processing %0", Localization.lang("Citation Style")) + ": " + layout.getName() + " ..." + "</i>"))
.onSuccess(this::setPreviewText)
.onFailure(exception -> {
LOGGER.error("Error while generating citation style", exception);
setPreviewText(Localization.lang("Error while generating citation style"));
})
.executeWith(taskExecutor);
.wrap(() -> layout.generatePreview(entry.get(), database.getDatabase()))
.onRunning(() -> setPreviewText("<i>" + Localization.lang("Processing %0", Localization.lang("Citation Style")) + ": " + layout.getName() + " ..." + "</i>"))
.onSuccess(this::setPreviewText)
.onFailure(exception -> {
LOGGER.error("Error while generating citation style", exception);
setPreviewText(Localization.lang("Error while generating citation style"));
})
.executeWith(taskExecutor);
}

private void setPreviewText(String text) {
previewView.getEngine().loadContent(text);
String myText = JS_HIGHLIGHT_FUNCTION + "<div id=\"content\"" + text + "</div>";
Siedlerchr marked this conversation as resolved.
Show resolved Hide resolved
previewView.getEngine().setJavaScriptEnabled(true);
previewView.getEngine().loadContent(myText);

this.setHvalue(0);
}

Expand All @@ -116,13 +147,13 @@ public void print() {
}

BackgroundTask
.wrap(() -> {
job.getJobSettings().setJobName(entry.flatMap(BibEntry::getCiteKeyOptional).orElse("NO ENTRY"));
previewView.getEngine().print(job);
job.endJob();
})
.onFailure(exception -> dialogService.showErrorDialogAndWait(Localization.lang("Could not print preview"), exception))
.executeWith(taskExecutor);
.wrap(() -> {
job.getJobSettings().setJobName(entry.flatMap(BibEntry::getCiteKeyOptional).orElse("NO ENTRY"));
previewView.getEngine().print(job);
job.endJob();
})
.onFailure(exception -> dialogService.showErrorDialogAndWait(Localization.lang("Could not print preview"), exception))
.executeWith(taskExecutor);
}

public void copyPreviewToClipBoard() {
Expand Down
Loading