Skip to content
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
14 changes: 7 additions & 7 deletions jabgui/src/main/java/org/jabref/gui/preview/PreviewPanel.java
Original file line number Diff line number Diff line change
Expand Up @@ -121,21 +121,21 @@ private void createKeyBindings() {
private ContextMenu createPopupMenu() {
MenuItem copyCitationHtml = new MenuItem(Localization.lang("Copy citation (html)"), IconTheme.JabRefIcons.COPY.getGraphicNode());
keyBindingRepository.getKeyCombination(KeyBinding.COPY_PREVIEW).ifPresent(copyCitationHtml::setAccelerator);
copyCitationHtml.setOnAction(event -> previewView.copyPreviewHtmlToClipBoard());
copyCitationHtml.setOnAction(_ -> previewView.copyPreviewHtmlToClipBoard());
MenuItem copyCitationText = new MenuItem(Localization.lang("Copy citation (text)"));
copyCitationText.setOnAction(event -> previewView.copyPreviewTextToClipBoard());
copyCitationText.setOnAction(_ -> previewView.copyPreviewPlainTextToClipBoard());
MenuItem exportToClipboard = new MenuItem(Localization.lang("Export to clipboard"));
exportToClipboard.setOnAction(event -> previewView.exportToClipBoard(stateManager));
exportToClipboard.setOnAction(_ -> previewView.exportToClipBoard(stateManager));
MenuItem copySelection = new MenuItem(Localization.lang("Copy selection"));
copySelection.setOnAction(event -> previewView.copySelectionToClipBoard());
copySelection.setOnAction(_ -> previewView.copySelectionToClipBoard());
MenuItem printEntryPreview = new MenuItem(Localization.lang("Print entry preview"), IconTheme.JabRefIcons.PRINTED.getGraphicNode());
printEntryPreview.setOnAction(event -> previewView.print());
printEntryPreview.setOnAction(_ -> previewView.print());
MenuItem previousPreviewLayout = new MenuItem(Localization.lang("Previous preview layout"));
keyBindingRepository.getKeyCombination(KeyBinding.PREVIOUS_PREVIEW_LAYOUT).ifPresent(previousPreviewLayout::setAccelerator);
previousPreviewLayout.setOnAction(event -> this.previousPreviewStyle());
previousPreviewLayout.setOnAction(_ -> this.previousPreviewStyle());
MenuItem nextPreviewLayout = new MenuItem(Localization.lang("Next preview layout"));
keyBindingRepository.getKeyCombination(KeyBinding.NEXT_PREVIEW_LAYOUT).ifPresent(nextPreviewLayout::setAccelerator);
nextPreviewLayout.setOnAction(event -> this.nextPreviewStyle());
nextPreviewLayout.setOnAction(_ -> this.nextPreviewStyle());

ContextMenu menu = new ContextMenu();
menu.getItems().add(copyCitationHtml);
Expand Down
183 changes: 98 additions & 85 deletions jabgui/src/main/java/org/jabref/gui/preview/PreviewViewer.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import java.util.List;
import java.util.Objects;

import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.property.SimpleStringProperty;
Expand All @@ -26,6 +25,7 @@
import org.jabref.gui.preferences.GuiPreferences;
import org.jabref.gui.search.Highlighter;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.UiTaskExecutor;
import org.jabref.gui.util.WebViewStore;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.layout.format.Number;
Expand All @@ -41,7 +41,6 @@
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.EventTarget;
Expand All @@ -56,40 +55,37 @@ public class PreviewViewer extends ScrollPane implements InvalidationListener {

// https://stackoverflow.com/questions/5669448/get-selected-texts-html-in-div/5670825#5670825
private static final String JS_GET_SELECTION_HTML_SCRIPT = """
function getSelectionHtml() {
let html = "";
if (typeof window.getSelection != "undefined") {
let sel = window.getSelection();
if (sel.rangeCount) {
let container = document.createElement("div");
for (let i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
getSelectionHtml();
""";
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
getSelectionHtml();
""";

private final ClipBoardManager clipBoardManager;
private final DialogService dialogService;
private final TaskExecutor taskExecutor;
private final WebView previewView;
private final StringProperty searchQueryProperty;
private final GuiPreferences preferences;

// Used for resolving strings and pdf directories for links.
private @Nullable BibDatabaseContext databaseContext;

private @Nullable BibEntry entry;

private PreviewLayout layout;

private String layoutText;

public PreviewViewer(DialogService dialogService,
Expand All @@ -115,8 +111,14 @@ public PreviewViewer(DialogService dialogService,
setFitToWidth(true);
previewView = WebViewStore.get();
setContent(previewView);

configurePreviewView(themeManager);
}

private void configurePreviewView(ThemeManager themeManager) {
previewView.setContextMenuEnabled(false);
previewView.getEngine().setJavaScriptEnabled(true);
themeManager.installCss(previewView.getEngine());

previewView.getEngine().getLoadWorker().stateProperty().addListener((_, _, newValue) -> {
if (newValue != Worker.State.SUCCEEDED) {
Expand All @@ -137,20 +139,18 @@ public PreviewViewer(DialogService dialogService,
NativeDesktop.openBrowser(href, preferences.getExternalApplicationsPreferences());
} catch (MalformedURLException exception) {
LOGGER.error("Invalid URL", exception);
} catch (IOException exception) {
LOGGER.error("Invalid URL Input", exception);
} catch (IOException e) {
LOGGER.error("Could not open URL: {}", href, e);
}
}
evt.preventDefault();
}, false);
}
});

themeManager.installCss(previewView.getEngine());
}

public void setLayout(PreviewLayout newLayout) {
// Change listeners might set the layout to null while the update method is executing, therefore we need to prevent this here
// Change listeners might set the layout to null while the update method is executing, therefore, we need to prevent this here
if ((newLayout == null) || newLayout.equals(layout)) {
return;
}
Expand All @@ -172,9 +172,9 @@ public void setEntry(@Nullable BibEntry newEntry) {

entry = newEntry;

// Register listeners for new entry
if (entry != null) {
// Register for changes
for (Observable observable : newEntry.getObservables()) {
for (Observable observable : entry.getObservables()) {
observable.addListener(this);
}
}
Expand All @@ -185,40 +185,38 @@ public void setDatabaseContext(BibDatabaseContext newDatabaseContext) {
if (Objects.equals(databaseContext, newDatabaseContext)) {
return;
}

setEntry(null);

databaseContext = newDatabaseContext;
this.databaseContext = newDatabaseContext;
update();
}

private void update() {
if ((databaseContext == null) || (entry == null) || (layout == null)) {
LOGGER.debug("databaseContext null {}, entry null {}, or layout null {}", databaseContext == null, entry == null, layout == null);
// Make sure that the preview panel is not completely white, especially with dark theme on
LOGGER.debug("Missing components - Database: {}, Entry: {}, Layout: {}",
databaseContext == null ? "null" : databaseContext,
entry == null ? "null" : entry,
layout == null ? "null" : layout);
setPreviewText("");
return;
}

Number.serialExportNumber = 1; // Set entry number in case that is included in the preview layout.

final BibEntry theEntry = entry;
BackgroundTask
.wrap(() -> layout.generatePreview(theEntry, databaseContext))
.onSuccess(this::setPreviewText)
.onFailure(exception -> {
LOGGER.error("Error while generating citation style", exception);

// Convert stack trace to a string
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
exception.printStackTrace(printWriter);
String stackTraceString = stringWriter.toString();

// Set the preview text with the localized error message and the stack trace
setPreviewText(Localization.lang("Error while generating citation style") + "\n\n" + exception.getLocalizedMessage() + "\n\nBibTeX (internal):\n" + theEntry + "\n\nStack Trace:\n" + stackTraceString);
})
.executeWith(taskExecutor);
Number.serialExportNumber = 1;
BibEntry currentEntry = entry;

BackgroundTask.wrap(() -> layout.generatePreview(currentEntry, databaseContext))
.onSuccess(this::setPreviewText)
.onFailure(e -> setPreviewText(formatError(currentEntry, e)))
.executeWith(taskExecutor);
}

private String formatError(BibEntry entry, Throwable exception) {
StringWriter sw = new StringWriter();
exception.printStackTrace(new PrintWriter(sw));
return "%s\n\n%s\n\nBibTeX (internal):\n%s\n\nStack Trace:\n%s".formatted(
Localization.lang("Error while generating citation style"),
exception.getLocalizedMessage(),
entry,
sw);
}

private void setPreviewText(String text) {
Expand All @@ -230,62 +228,81 @@ private void setPreviewText(String text) {
</html>
""".formatted(text);
highlightLayoutText();
this.setHvalue(0);
setHvalue(0);
}

private void highlightLayoutText() {
if (layoutText == null) {
return;
}

if (StringUtil.isNotBlank(searchQueryProperty.get())) {
SearchQuery searchQuery = new SearchQuery(searchQueryProperty.get());
String highlightedHtml = Highlighter.highlightHtml(layoutText, searchQuery);
Platform.runLater(() -> previewView.getEngine().loadContent(highlightedHtml));
String queryText = searchQueryProperty.get();
if (StringUtil.isNotBlank(queryText)) {
SearchQuery searchQuery = new SearchQuery(queryText);
String highlighted = Highlighter.highlightHtml(layoutText, searchQuery);
UiTaskExecutor.runInJavaFXThread(() -> previewView.getEngine().loadContent(highlighted));
} else {
Platform.runLater(() -> previewView.getEngine().loadContent(layoutText));
UiTaskExecutor.runInJavaFXThread(() -> previewView.getEngine().loadContent(layoutText));
}
}

public void print() {
PrinterJob job = PrinterJob.createPrinterJob();
boolean proceed = dialogService.showPrintDialog(job);
if (!proceed && (entry != null)) {
if ((entry == null) || !dialogService.showPrintDialog(job)) {
return;
}

BackgroundTask
.wrap(() -> {
job.getJobSettings().setJobName(entry.getCitationKey().orElse("NO CITATION KEY"));
previewView.getEngine().print(job);
job.endJob();
})
.onFailure(exception -> dialogService.showErrorDialogAndWait(Localization.lang("Could not print preview"), exception))
.executeWith(taskExecutor);
BackgroundTask.wrap(() -> {
job.getJobSettings().setJobName(entry.getCitationKey().orElse("NO CITATION KEY"));
previewView.getEngine().print(job);
job.endJob();
})
.onFailure(e -> dialogService.showErrorDialogAndWait(Localization.lang("Could not print preview"), e))
.executeWith(taskExecutor);
}

public void copyPreviewHtmlToClipBoard() {
Document document = previewView.getEngine().getDocument();
ClipboardContent content = ClipboardContentGenerator.processHtml(List.of(document.getElementById("content").getTextContent()));
if ((entry == null) || (layout == null) || (databaseContext == null)) {
LOGGER.warn("Cannot copy preview citation: Missing entry, layout, or database context.");
return;
}

String citationHtml = layout.generatePreview(entry, databaseContext);
ClipboardContent content = ClipboardContentGenerator.processHtml(List.of(citationHtml));
clipBoardManager.setContent(content);
}

public void copyPreviewTextToClipBoard() {
Document document = previewView.getEngine().getDocument();
ClipboardContent content = ClipboardContentGenerator.processText(List.of(document.getElementById("content").getTextContent()));
public void copyPreviewPlainTextToClipBoard() {
if ((entry == null) || (layout == null) || (databaseContext == null)) {
LOGGER.warn("Cannot copy preview citation: Missing entry, layout, or database context.");
return;
}

String plainText = (String) previewView.getEngine().executeScript("document.body.innerText");
ClipboardContent content = new ClipboardContent();
content.putString(plainText);
clipBoardManager.setContent(content);
}

public void copySelectionToClipBoard() {
if ((entry == null) || (layout == null) || (databaseContext == null)) {
LOGGER.warn("Cannot copy preview citation: Missing entry, layout, or database context.");
return;
}

ClipboardContent content = new ClipboardContent();
content.putString(getSelectionTextContent());
content.putString((String) previewView.getEngine().executeScript("window.getSelection().toString()"));
content.putHtml(getSelectionHtmlContent());

clipBoardManager.setContent(content);
}

public void exportToClipBoard(StateManager stateManager) {
ExportToClipboardAction exportToClipboardAction = new ExportToClipboardAction(dialogService, stateManager, clipBoardManager, taskExecutor, preferences);
ExportToClipboardAction exportToClipboardAction = new ExportToClipboardAction(
dialogService,
stateManager,
clipBoardManager,
taskExecutor,
preferences);
exportToClipboardAction.execute();
}

Expand All @@ -294,10 +311,6 @@ public void invalidated(Observable observable) {
update();
}

public String getSelectionTextContent() {
return (String) previewView.getEngine().executeScript("window.getSelection().toString()");
}

public String getSelectionHtmlContent() {
return (String) previewView.getEngine().executeScript(JS_GET_SELECTION_HTML_SCRIPT);
}
Expand Down