Skip to content

Commit

Permalink
Merge pull request #285 from wimdeblauwe/feature/issue-283
Browse files Browse the repository at this point in the history
Drive the right-click action from JavaFX. Fixes #283
  • Loading branch information
ahus1 authored Jun 27, 2019
2 parents adc0cbb + d99990c commit f0c8bf7
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 95 deletions.
146 changes: 81 additions & 65 deletions src/main/java/org/asciidoc/intellij/editor/javafx/JavaFxHtmlPanel.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
import org.asciidoc.intellij.settings.AsciiDocApplicationSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.w3c.dom.html.HTMLImageElement;

import javax.swing.*;
import java.awt.*;
Expand Down Expand Up @@ -85,7 +86,6 @@ protected String compute() {
return new StringBuilder()
.append("<script src=\"").append(PreviewStaticServer.getScriptUrl("scrollToElement.js")).append("\"></script>\n")
.append("<script src=\"").append(PreviewStaticServer.getScriptUrl("processLinks.js")).append("\"></script>\n")
.append("<script src=\"").append(PreviewStaticServer.getScriptUrl("processImages.js")).append("\"></script>\n")
.append("<script src=\"").append(PreviewStaticServer.getScriptUrl("pickSourceLine.js")).append("\"></script>\n")
.append("<script type=\"text/x-mathjax-config\">\n" +
"MathJax.Hub.Config({\n" +
Expand Down Expand Up @@ -137,6 +137,7 @@ protected String compute() {
private final Path imagesPath;

private VirtualFile parentDirectory;
private VirtualFile saveImageLastDir = null;

JavaFxHtmlPanel(Document document, Path imagesPath) {

Expand Down Expand Up @@ -201,9 +202,8 @@ public void run() {
myWebView = new WebView();

updateFontSmoothingType(myWebView, false);
// will be disabled via JavaScript inside processImages.js as it is not generally helpful here,
// but processImages.js will use right-click to export the images.
myWebView.setContextMenuEnabled(true);
registerContextMenu(JavaFxHtmlPanel.this.myWebView);
myWebView.setContextMenuEnabled(false);
myWebView.setZoom(JBUI.scale(1.f));
myWebView.getEngine().loadContent(prepareHtml("<html><head></head><body>Initializing...</body>"));

Expand Down Expand Up @@ -246,6 +246,83 @@ public void run() {

}

private void registerContextMenu(WebView webView) {
webView.setOnMousePressed(e -> {
if (e.getButton() == MouseButton.SECONDARY) {
JSObject object = getJavaScriptObjectAtLocation(webView, e);
if (object instanceof HTMLImageElement) {
String src = ((HTMLImageElement) object).getAttribute("src");
ApplicationManager.getApplication().invokeLater(() -> saveImage(src));
}
}
});
}

private JSObject getJavaScriptObjectAtLocation(WebView webView, MouseEvent e) {
String script = String.format("document.elementFromPoint(%s,%s);", e.getX(), e.getY());
return (JSObject) webView.getEngine().executeScript(script);
}

private void saveImage(@NotNull String path) {
String parent = imagesPath.getFileName().toString();
String subPath = path.substring(path.indexOf(parent) + parent.length() + 1);
Path imagePath = imagesPath.resolve(subPath);
if (imagePath.toFile().exists()) {
File file = imagePath.toFile();
String fileName = imagePath.getFileName().toString();
ArrayList<String> extensions = new ArrayList<>();
int lastDotIndex = fileName.lastIndexOf('.');
if (lastDotIndex > 0 && !fileName.endsWith(".")) {
extensions.add(fileName.substring(lastDotIndex + 1));
}
// set static file name if image name has been generated dynamically
final String fileNameNoExt;
if (fileName.matches("diag-[0-9a-f]{32}\\.[a-z]+")) {
fileNameNoExt = "image";
} else {
fileNameNoExt = lastDotIndex > 0 ? fileName.substring(0, lastDotIndex) : fileName;
}
// check if also a SVG exists for the provided PNG
if (extensions.contains("png") &&
new File(file.getParent(), fileNameNoExt + ".svg").exists()) {
extensions.add("svg");
}
final FileSaverDescriptor descriptor = new FileSaverDescriptor("Export Image to", "Choose the destination file",
extensions.toArray(new String[]{}));
FileSaverDialog saveFileDialog = FileChooserFactory.getInstance().createSaveFileDialog(descriptor, (Project) null);

VirtualFile baseDir = saveImageLastDir;

if (baseDir == null) {
baseDir = parentDirectory;
}

VirtualFile finalBaseDir = baseDir;

SwingUtilities.invokeLater(() -> {
VirtualFileWrapper destination = saveFileDialog.save(finalBaseDir, fileNameNoExt);
if (destination != null) {
try {
saveImageLastDir = LocalFileSystem.getInstance().findFileByIoFile(destination.getFile().getParentFile());
Path src = imagePath;
// if the destination ends with .svg, but the source doesn't, patch the source file name as the user chose a different file type
if (destination.getFile().getAbsolutePath().endsWith(".svg") && !src.endsWith(".svg")) {
src = new File(src.toFile().getAbsolutePath().replaceAll("\\.png$", ".svg")).toPath();
}
Files.copy(src, destination.getFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
String message = "Can't save file: " + ex.getMessage();
Notification notification = AsciiDocPreviewEditor.NOTIFICATION_GROUP
.createNotification("Error in plugin", message, NotificationType.ERROR, null);
// increase event log counter
notification.setImportant(true);
Notifications.Bus.notify(notification);
}
}
});
}
}

private static void runFX(@NotNull Runnable r) {
IdeEventQueue.unsafeNonblockingExecute(r);
}
Expand Down Expand Up @@ -429,8 +506,6 @@ private static String getScriptingLines() {
@SuppressWarnings("unused")
public class JavaPanelBridge {

private VirtualFile lastDir = null;

public void openLink(@NotNull String link) {
final URI uri;
try {
Expand Down Expand Up @@ -514,65 +589,6 @@ public void scrollEditorToLine(int sourceLine) {
);
}

public void saveImage(@NotNull String path) {
String parent = imagesPath.getFileName().toString();
String subPath = path.substring(path.indexOf(parent) + parent.length() + 1);
Path imagePath = imagesPath.resolve(subPath);
if (imagePath.toFile().exists()) {
File file = imagePath.toFile();
String fileName = imagePath.getFileName().toString();
ArrayList<String> extensions = new ArrayList<>();
int lastDotIndex = fileName.lastIndexOf('.');
if (lastDotIndex > 0 && !fileName.endsWith(".")) {
extensions.add(fileName.substring(lastDotIndex + 1));
}
// set static file name if image name has been generated dynamically
final String fileNameNoExt;
if (fileName.matches("diag-[0-9a-f]{32}\\.[a-z]+")) {
fileNameNoExt = "image";
} else {
fileNameNoExt = lastDotIndex > 0 ? fileName.substring(0, lastDotIndex) : fileName;
}
// check if also a SVG exists for the provided PNG
if (extensions.contains("png") &&
new File(file.getParent(), fileNameNoExt + ".svg").exists()) {
extensions.add("svg");
}
final FileSaverDescriptor descriptor = new FileSaverDescriptor("Export Image to", "Choose the destination file",
extensions.toArray(new String[]{}));
FileSaverDialog saveFileDialog = FileChooserFactory.getInstance().createSaveFileDialog(descriptor, (Project) null);

VirtualFile baseDir = lastDir;

if (baseDir == null) {
baseDir = parentDirectory;
}

VirtualFile finalBaseDir = baseDir;

SwingUtilities.invokeLater(() -> {
VirtualFileWrapper destination = saveFileDialog.save(finalBaseDir, fileNameNoExt);
if (destination != null) {
try {
lastDir = LocalFileSystem.getInstance().findFileByIoFile(destination.getFile().getParentFile());
Path src = imagePath;
if (destination.getFile().getAbsolutePath().endsWith(".svg") && !src.endsWith(".svg")) {
src = new File(src.toFile().getAbsolutePath().replaceAll("\\.png$", ".svg")).toPath();
}
Files.copy(src, destination.getFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
String message = "Can't save file: " + ex.getMessage();
Notification notification = AsciiDocPreviewEditor.NOTIFICATION_GROUP
.createNotification("Error in plugin", message, NotificationType.ERROR, null);
// increase event log counter
notification.setImportant(true);
Notifications.Bus.notify(notification);
}
}
});
}
}

public void log(@Nullable String text) {
Logger.getInstance(JavaPanelBridge.class).warn(text);
}
Expand Down

This file was deleted.

0 comments on commit f0c8bf7

Please sign in to comment.