-
-
Notifications
You must be signed in to change notification settings - Fork 144
/
AsciiDocJCEFHtmlPanel.java
1147 lines (1058 loc) · 46.2 KB
/
AsciiDocJCEFHtmlPanel.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.asciidoc.intellij.editor.jcef;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.actions.OpenFileAction;
import com.intellij.ide.lightEdit.LightEdit;
import com.intellij.ide.util.PsiNavigationSupport;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.CaretState;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.fileChooser.FileChooserFactory;
import com.intellij.openapi.fileChooser.FileSaverDescriptor;
import com.intellij.openapi.fileChooser.FileSaverDialog;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.util.SystemInfoRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.VirtualFileWrapper;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.ui.JreHiDpiUtil;
import com.intellij.ui.jcef.JBCefBrowser;
import com.intellij.ui.jcef.JBCefJSQuery;
import com.intellij.ui.jcef.JBCefPsiNavigationUtils;
import com.intellij.ui.jcef.JCEFHtmlPanel;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.util.PsiNavigateUtil;
import com.intellij.util.ui.UIUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.asciidoc.intellij.AsciiDoc;
import org.asciidoc.intellij.editor.AsciiDocHtmlPanel;
import org.asciidoc.intellij.editor.AsciiDocPreviewEditor;
import org.asciidoc.intellij.editor.javafx.JavaFxHtmlPanel;
import org.asciidoc.intellij.editor.javafx.PreviewStaticServer;
import org.asciidoc.intellij.file.AsciiDocFileType;
import org.asciidoc.intellij.psi.AsciiDocUtil;
import org.asciidoc.intellij.settings.AsciiDocApplicationSettings;
import org.cef.browser.CefBrowser;
import org.cef.handler.CefFocusHandlerAdapter;
import org.cef.handler.CefLoadHandler;
import org.cef.handler.CefLoadHandlerAdapter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AsciiDocJCEFHtmlPanel extends JCEFHtmlPanel implements AsciiDocHtmlPanel {
private static final Logger LOG = Logger.getInstance(AsciiDocJCEFHtmlPanel.class);
private final Path imagesPath;
private JBCefJSQuery myJSQuerySetScrollY;
private JBCefJSQuery myRenderedIteration;
private JBCefJSQuery myRenderedResult;
private JBCefJSQuery myScrollEditorToLine;
@Override
public void printToPdf(String target, Consumer<Boolean> success) {
getCefBrowser().printToPDF(target, null, (s, b) -> success.accept(b));
}
@Override
public boolean isPrintingSupported() {
return true;
}
@Override
public JComponent getPreferredFocusedComponent() {
if (getComponent().getComponents().length == 0) {
return getComponent();
}
return (JComponent) getComponent().getComponents()[0];
}
private JBCefJSQuery myZoomDelta;
private JBCefJSQuery myZoomReset;
private JBCefJSQuery mySaveImage;
private JBCefJSQuery myBrowserLog;
private JBCefJSQuery myOpenLink;
private volatile CountDownLatch rendered = new CountDownLatch(1);
private volatile CountDownLatch replaceResultLatch = new CountDownLatch(1);
private final CefLoadHandler myCefLoadHandler;
@NotNull
private final ScrollPreservingListener myScrollPreservingListener = new ScrollPreservingListener();
@NotNull
private final BridgeSettingListener myBridgeSettingListener = new BridgeSettingListener();
@NotNull
private final String base;
private VirtualFile parentDirectory;
private volatile int lineCount;
private volatile int line;
private volatile boolean forceRefresh = true;
private volatile long stamp = 0;
private volatile boolean replaceResult = false;
private volatile String frameHtml = null;
@NotNull
private static final String OUR_CLASS_URL;
private double uiZoom;
private static final NotNullLazyValue<String> MY_SCRIPTING_LINES = new NotNullLazyValue<>() {
@NotNull
@Override
protected String compute() {
//noinspection StringBufferReplaceableByString
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 src=\"").append(PreviewStaticServer.getScriptUrl("mouseEvents.js")).append("\"></script>\n")
.append("<script type=\"text/x-mathjax-config\">\n" +
"MathJax.Hub.Config({\n" +
" messageStyle: \"none\",\n" +
" EqnChunkDelay: 1," +
" imageFont: null," +
" tex2jax: {\n" +
" inlineMath: [[\"\\\\(\", \"\\\\)\"]],\n" +
" displayMath: [[\"\\\\[\", \"\\\\]\"]],\n" +
" ignoreClass: \"nostem|nolatexmath\"\n" +
" },\n" +
" asciimath2jax: {\n" +
" delimiters: [[\"\\\\$\", \"\\\\$\"]],\n" +
" ignoreClass: \"nostem|noasciimath\"\n" +
" },\n" +
" TeX: { equationNumbers: { autoNumber: \"none\" } }\n" +
"});\n" +
"MathJax.Hub.Register.MessageHook(\"Math Processing Error\",function (message) {\n" +
" window.JavaPanelBridge && window.JavaPanelBridge.log(JSON.stringify(message)); \n" +
"});" +
"MathJax.Hub.Register.MessageHook(\"TeX Jax - parse error\",function (message) {\n" +
" var errortext = document.getElementById('mathjaxerrortext'); " +
" var errorformula = document.getElementById('mathjaxerrorformula'); " +
" if (errorformula && errortext) { " +
" errortext.textContent = 'Math Formula problem: ' + message[1]; " +
" errorformula.textContent = '\\n' + message[2]; " +
" } " +
" window.JavaPanelBridge && window.JavaPanelBridge.log(JSON.stringify(message)); \n" +
"});" +
"</script>\n")
.append("<script src=\"").append(PreviewStaticServer.getScriptUrl("MathJax/MathJax.js")).append("&config=TeX-MML-AM_HTMLorMML\"></script>\n")
.toString();
}
};
static {
String url = "about:blank";
try {
// JCEF will complain with a "Not allowed to load local resource" error when non-ascii characters are included in this random URL
// therefore using toASCIIString()
url = AsciiDocJCEFHtmlPanel.class.getResource(AsciiDocJCEFHtmlPanel.class.getSimpleName() + ".class").toURI().toASCIIString();
} catch (Exception ex) {
LOG.warn("unable to initialize url", ex);
}
OUR_CLASS_URL = url;
}
@Nullable
private Editor editor;
public AsciiDocJCEFHtmlPanel(Document document, Path imagesPath) {
super(OUR_CLASS_URL + "@" + new Random().nextInt(Integer.MAX_VALUE));
this.imagesPath = imagesPath;
VirtualFile file = FileDocumentManager.getInstance().getFile(document);
if (file != null) {
parentDirectory = file.getParent();
}
if (parentDirectory != null) {
// parent will be null if we use Language Injection and Fragment Editor
base = parentDirectory.getUrl().replaceAll("^file://", "")
.replaceAll(":", "%3A");
} else {
base = "";
}
reregisterHandlers();
myCefLoadHandler = new CefLoadHandlerAdapter() {
@Override
public void onLoadingStateChange(CefBrowser browser, boolean isLoading, boolean canGoBack, boolean canGoForward) {
myScrollPreservingListener.onLoadingStateChange(browser, isLoading, canGoBack, canGoForward);
myBridgeSettingListener.onLoadingStateChange(browser, isLoading, canGoBack, canGoForward);
}
};
getJBCefClient().addLoadHandler(myCefLoadHandler, getCefBrowser());
// in Intellij 2020.3.x the load handler is broken as it will trigger ERR_ABORTED if loading in an iframe is aborted,
// maybe even trigger an error when the preview is force-refreshed and a currently loading page is aborted
// therefore: remove JetBrains load handler
try {
Field privateLoadHandler;
try {
// this is 2020.3
privateLoadHandler = JBCefBrowser.class.getDeclaredField("myLoadHandler");
} catch (NoSuchFieldException ex) {
// this is 2021.1
privateLoadHandler = this.getClass().getClassLoader().loadClass("com.intellij.ui.jcef.JBCefBrowserBase").getDeclaredField("myLoadHandler");
}
privateLoadHandler.setAccessible(true);
CefLoadHandler loadHandler = (CefLoadHandler) privateLoadHandler.get(this);
getJBCefClient().removeLoadHandler(loadHandler, getCefBrowser());
} catch (NoSuchFieldException | IllegalAccessException | ClassNotFoundException e) {
LOG.info("unable to clean up JCEF load handler", e);
}
try {
java.util.Properties p = new java.util.Properties();
try (InputStream stream = JavaFxHtmlPanel.class.getResourceAsStream("/META-INF/asciidoctorj-version.properties")) {
p.load(stream);
}
String asciidoctorVersion = p.getProperty("version.asciidoctor");
myInlineCss = extractAndPatchAsciidoctorCss(asciidoctorVersion);
try (InputStream stream = JavaFxHtmlPanel.class.getResourceAsStream("/gems/asciidoctor-"
+ asciidoctorVersion
+ "/data/stylesheets/coderay-asciidoctor.css")) {
myInlineCss += IOUtils.toString(stream, StandardCharsets.UTF_8);
}
try (InputStream is = JavaFxHtmlPanel.class.getResourceAsStream("rouge-github.css")) {
myInlineCss += IOUtils.toString(is, StandardCharsets.UTF_8);
}
try (InputStream stream = JavaFxHtmlPanel.class.getResourceAsStream("darcula.css")) {
myInlineCssDarcula = myInlineCss + IOUtils.toString(stream, StandardCharsets.UTF_8);
}
myFontAwesomeCssLink = "<link rel=\"stylesheet\" href=\"" + PreviewStaticServer.getStyleUrl("font-awesome/css/font-awesome.min.css") + "\">";
myDejavuCssLink = "<link rel=\"stylesheet\" href=\"" + PreviewStaticServer.getStyleUrl("dejavu/dejavu.css") + "\">";
myGoogleFontsCssLink = "<link rel=\"stylesheet\" href=\"" + PreviewStaticServer.getStyleUrl("googlefonts/googlefonts.css") + "\">";
} catch (IOException e) {
String message = "Unable to combine CSS resources: " + e.getMessage();
LOG.error(message, e);
Notification notification = AsciiDoc.getNotificationGroup()
.createNotification("Error rendering asciidoctor", message, NotificationType.ERROR, null);
// increase event log counter
notification.setImportant(true);
Notifications.Bus.notify(notification);
}
uiZoom = AsciiDocApplicationSettings.getInstance().getAsciiDocPreviewSettings().getZoom() / 100.0;
ApplicationManager.getApplication().executeOnPooledThread(() -> setHtml(prepareHtml(wrapHtmlForPage("<div id=\"content\">Initializing...</div>"), Collections.emptyMap())));
}
private void reregisterHandlers() {
if (myJSQuerySetScrollY != null) {
Disposer.dispose(myJSQuerySetScrollY);
}
if (myRenderedIteration != null) {
Disposer.dispose(myRenderedIteration);
}
if (myRenderedResult != null) {
Disposer.dispose(myRenderedResult);
}
if (myBrowserLog != null) {
Disposer.dispose(myBrowserLog);
}
if (myScrollEditorToLine != null) {
Disposer.dispose(myScrollEditorToLine);
}
if (myZoomDelta != null) {
Disposer.dispose(myZoomDelta);
}
if (myZoomReset != null) {
Disposer.dispose(myZoomReset);
}
if (mySaveImage != null) {
Disposer.dispose(mySaveImage);
}
if (myOpenLink != null) {
Disposer.dispose(myOpenLink);
}
myJSQuerySetScrollY = JBCefJSQuery.create(this);
myRenderedIteration = JBCefJSQuery.create(this);
myRenderedResult = JBCefJSQuery.create(this);
myBrowserLog = JBCefJSQuery.create(this);
myScrollEditorToLine = JBCefJSQuery.create(this);
myZoomDelta = JBCefJSQuery.create(this);
myZoomReset = JBCefJSQuery.create(this);
mySaveImage = JBCefJSQuery.create(this);
myOpenLink = JBCefJSQuery.create(this);
myJSQuerySetScrollY.addHandler((scrollY) -> {
try {
if (scrollY != null && scrollY.length() > 0) {
myScrollPreservingListener.myScrollY = (int) Double.parseDouble(scrollY);
}
} catch (NumberFormatException e) {
LOG.warn("unable to parse scroll Y", e);
}
return null;
});
myRenderedIteration.addHandler((r) -> {
try {
if (r != null && r.length() > 0 && !r.equals("undefined")) {
long iterationStamp = Integer.parseInt(r);
if (stamp == iterationStamp) {
rendered.countDown();
}
} else if (r != null && r.equals("undefined")) {
// TODO: find out why the first result is undefined
if (stamp == 1) {
rendered.countDown();
}
}
} catch (NumberFormatException e) {
LOG.warn("unable set iteration stamp", e);
}
return null;
});
myRenderedResult.addHandler((r) -> {
if (r != null && r.length() > 0) {
replaceResult = Boolean.parseBoolean(r);
replaceResultLatch.countDown();
}
return null;
});
myBrowserLog.addHandler((r) -> {
Logger.getInstance(AsciiDocJCEFHtmlPanel.class).warn("log from browser:" + r);
return null;
});
myScrollEditorToLine.addHandler(this::handleScrollEditorLine);
myZoomDelta.addHandler((r) -> {
try {
double deltaY = Double.parseDouble(r);
if (Double.compare(deltaY, 0.0) != 0) {
uiZoom = getCefBrowser().getZoomLevel() + 1;
double factor = (deltaY > 0.0 ? -0.2 : +0.2);
uiZoom = uiZoom + factor;
// define minimum/maximum zoom
if (uiZoom < JBUIScale.scale(0.1f)) {
uiZoom = 0.1;
} else if (uiZoom > JBUIScale.scale(10.f)) {
uiZoom = 10;
}
getCefBrowser().setZoomLevel(uiZoom - 1);
}
} catch (NumberFormatException e) {
LOG.warn("unable parse line number: " + r, e);
}
return null;
});
myZoomReset.addHandler((r) -> {
uiZoom = 1.0;
getCefBrowser().setZoomLevel(uiZoom - 1);
return null;
});
mySaveImage.addHandler(r -> {
ApplicationManager.getApplication().invokeLater(() ->
saveImage(r),
ModalityState.stateForComponent(getComponent()));
return null;
});
myOpenLink.addHandler((r) -> {
if (JBCefPsiNavigationUtils.INSTANCE.navigateTo(r)) {
return null;
}
openLink(r);
return null;
});
fixFocusHandlerOnWindowsFromInterferingWithEventDispatchThread();
}
private void fixFocusHandlerOnWindowsFromInterferingWithEventDispatchThread() {
if (SystemInfoRt.isWindows) {
/* this replaces the standard focus handler on Windows that
would otherwise call setFocus(false) on the EDT that would take about 500ms and would make the UI slow.
See: https://youtrack.jetbrains.com/issue/IDEA-260841
*/
getCefBrowser().getClient().removeFocusHandler();
getCefBrowser().getClient().addFocusHandler(new CefFocusHandlerAdapter() {
@Override
public boolean onSetFocus(CefBrowser browser, FocusSource source) {
if (source == FocusSource.FOCUS_SOURCE_NAVIGATION) {
if (SystemInfoRt.isWindows) {
/*
* Will set the focus on the CEF browser if the component has the focus.
* Putting the focus on the CEF browser allows users to use PgUp/PgDown and cursor up/down to navigate the document.
* Un-setting the focus for the CEF component is important to have the focus on the editor on Windows.
*/
ApplicationManager.getApplication().executeOnPooledThread(() -> getCefBrowser().setFocus(getPreferredFocusedComponent().hasFocus()));
}
return true; // suppress focusing the browser on navigation events
}
if (SystemInfoRt.isLinux) {
browser.getUIComponent().requestFocus();
} else {
browser.getUIComponent().requestFocusInWindow();
}
return false;
}
});
}
}
@Nullable
private JBCefJSQuery.Response handleScrollEditorLine(String r) {
try {
if (r.length() != 0) {
int split = r.indexOf(':');
int line = (int) Math.round(Double.parseDouble(r.substring(0, split)));
String file = r.substring(split + 1);
if (file.equals("stdin")) {
scrollEditorToLine(line);
} else {
ApplicationManager.getApplication().invokeLater(() -> {
VirtualFile targetFile = VirtualFileManager.getInstance().findFileByUrl("file://" + file);
if (targetFile != null) {
Project project = ProjectUtil.guessProjectForContentFile(targetFile);
if (project != null) {
if (LightEdit.owns(project)) {
OpenFileAction.openFile(targetFile, project);
} else {
int offset = -1;
PsiFile psiFile = PsiManager.getInstance(project).findFile(targetFile);
if (psiFile != null && line > 0) {
offset = StringUtil.lineColToOffset(psiFile.getText(), line - 1, 0);
}
PsiNavigationSupport.getInstance().createNavigatable(project, targetFile, offset).navigate(true);
}
} else {
LOG.warn("unable to identify project: " + targetFile);
}
}
});
}
}
} catch (NumberFormatException e) {
LOG.warn("unable parse line number: " + r, e);
}
return null;
}
private VirtualFile saveImageLastDir = null;
private void saveImage(@NotNull String path) {
String parent = imagesPath.getFileName().toString();
try {
path = URLDecoder.decode(path, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
LOG.warn("unable to decode URL " + path, e);
return;
}
int indexOfParent = path.indexOf(parent);
if (indexOfParent == -1) {
// parent string not found for image, image not generated by preview?
LOG.warn("found path " + path + " without " + parent);
return;
}
String subPath = path.substring(indexOfParent + parent.length() + 1);
if (subPath.contains("?")) {
subPath = subPath.substring(0, subPath.indexOf("?"));
}
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(), fileName.substring(0, lastDotIndex) + ".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;
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);
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(destination.getFile());
} catch (IOException ex) {
String message = "Can't save file: " + ex.getMessage();
Notification notification = AsciiDoc.getNotificationGroup()
.createNotification("Error in plugin", message, NotificationType.ERROR, null);
// increase event log counter
notification.setImportant(true);
Notifications.Bus.notify(notification);
}
}
} else {
LOG.warn("file not found to save: " + path);
}
}
private String extractAndPatchAsciidoctorCss(String asciidoctorVersion) throws IOException {
String css;
try (InputStream steam = JavaFxHtmlPanel.class.getResourceAsStream("/gems/asciidoctor-"
+ asciidoctorVersion
+ "/data/stylesheets/asciidoctor-default.css")) {
css = IOUtils.toString(steam, StandardCharsets.UTF_8);
}
// the following lines have been added for JavaFX
// TODO: revisit the following to find out if this is still true for JCEF
// JavaFX doesn't support synthetic bold/italic, and Droid Sans Mono doesn't have bold/italic styles delivered
// https://github.com/asciidoctor/asciidoctor-intellij-plugin/issues/193
// https://bugs.openjdk.java.net/browse/JDK-8089405
css = css.replaceAll("(\"Droid Sans Mono\"),", "");
// otherwise embedded SVG images will be skewed to full height of one browser window
css = css.replaceAll(Pattern.quote("object,embed{height:100%}"), "");
return css;
}
@Nullable
private String myInlineCss;
@Nullable
private String myInlineCssDarcula;
@Nullable
private String myFontAwesomeCssLink;
@Nullable
private String myDejavuCssLink;
@Nullable
private String myGoogleFontsCssLink;
private boolean tobeDisposed = false;
private volatile boolean hasLoadedOnce = false;
@Override
public synchronized void setHtml(@NotNull String htmlParam, @NotNull Map<String, String> attributes) {
if (tobeDisposed || isDisposed()) {
return;
}
if (getCefBrowser().getFocusedFrame() == null && hasLoadedOnce) {
// the CEF browser might have terminated after an initial rendering (seen with 202.6109.22)
// dispose this component so that it will be reloaded.
disposeMyself();
return;
}
rendered = new CountDownLatch(1);
replaceResultLatch = new CountDownLatch(1);
stamp += 1;
if (stamp > 10000) {
// force a refresh to avoid memory leaks
forceRefresh = true;
stamp = 0;
}
long iterationStamp = stamp;
String emptyFrame = prepareHtml(wrapHtmlForPage(""), attributes);
if (!emptyFrame.equals(frameHtml)) {
forceRefresh = true;
frameHtml = emptyFrame;
}
String html = htmlParam;
boolean result = false;
final AsciiDocApplicationSettings settings = AsciiDocApplicationSettings.getInstance();
if (hasLoadedOnce && !forceRefresh && settings.getAsciiDocPreviewSettings().isInplacePreviewRefresh() && html.contains("id=\"content\"")) {
final String htmlToReplace = StringEscapeUtils.escapeEcmaScript(prepareHtml(html, attributes));
// try to replace the HTML contents using JavaScript to avoid flickering MathML
try {
replaceResult = false;
getCefBrowser().executeJavaScript(
"function finish() {" +
"if ('__IntelliJTools' in window) {" +
"__IntelliJTools.processLinks && __IntelliJTools.processLinks();" +
"__IntelliJTools.processImages && __IntelliJTools.processImages();" +
"__IntelliJTools.pickSourceLine && __IntelliJTools.pickSourceLine(" + lineCount + ");" +
"}" +
"window.JavaPanelBridge && window.JavaPanelBridge.rendered(" + iterationStamp + ");" +
"}" +
"function updateContent() { " +
"var elem = document.getElementById('content'); if (elem && elem.parentNode) { " +
"var div = document.createElement('div');" +
"div.innerHTML = '" + htmlToReplace + "'; " +
"var errortext = document.getElementById('mathjaxerrortext'); " +
"var errorformula = document.getElementById('mathjaxerrorformula'); " +
"if (errorformula && errortext) { " +
" errortext.textContent = ''; " +
" errorformula.textContent = ''; " +
"} " +
"div.style.cssText = 'display: none'; " +
// need to add the element to the DOM as MathJAX will use document.getElementById in some places
"elem.appendChild(div); " +
"if(typeof hljs !== 'undefined') { [].slice.call(div.querySelectorAll('pre.highlight > code')).forEach(function (el) { hljs.highlightElement(el) }) } " +
// use MathJax to set the formulas in advance if formulas are present - this takes ~100ms
// re-evaluate the content element as it might have been replaced by a concurrent rendering
"if ('MathJax' in window && MathJax.Hub.getAllJax().length > 0) { " +
"MathJax.Hub.Typeset(div.firstChild, function() { " +
"var elem2 = document.getElementById('content'); " +
"__IntelliJTools.clearLinks && __IntelliJTools.clearLinks();" +
"__IntelliJTools.clearSourceLine && __IntelliJTools.clearSourceLine();" +
"elem2.parentNode.replaceChild(div.firstChild, elem2); " +
"finish(); }); } " +
// if no math was present before, replace contents, and do the MathJax typesetting afterwards in case Math has been added
"else { " +
"__IntelliJTools.clearLinks && __IntelliJTools.clearLinks();" +
"__IntelliJTools.clearSourceLine && __IntelliJTools.clearSourceLine();" +
"elem.parentNode.replaceChild(div.firstChild, elem); " +
"MathJax.Hub.Typeset(div.firstChild); " +
"finish(); " +
"} " +
"return true; } else { return false; }}; " + myRenderedResult.inject("updateContent()"),
getCefBrowser().getURL(), 0);
if (replaceResultLatch.await(2, TimeUnit.SECONDS)) {
result = replaceResult;
}
} catch (RuntimeException | InterruptedException e) {
// might happen when rendered output is not valid HTML due to passtrough content
LOG.warn("unable to use JavaScript for update", e);
}
}
// if not successful using JavaScript (like on first rendering attempt), set full content
if (!result) {
forceRefresh = false;
html = html + "<script>window.iterationStamp=" + iterationStamp + ";</script>";
html = wrapHtmlForPage(html);
final String htmlToRender = prepareHtml(html, attributes);
super.setHtml(htmlToRender);
getCefBrowser().setZoomLevel(uiZoom - 1);
}
try {
// slow down the rendering of the next version of the preview until the rendering if the current version is complete
// this prevents us building up a queue that would lead to a lagging preview
if (htmlParam.length() > 0 && !rendered.await(3, TimeUnit.SECONDS)) {
// error handling only if:
// the preview has rendered once -- as we don't want to close a window that is opening
// this preview hasn't been disposed -- as this wouldn't make much sense
if (!this.isDisposed() && hasLoadedOnce) {
LOG.warn("rendering didn't complete in time, might be slow or broken");
if (getCefBrowser().getFocusedFrame() == null) {
disposeMyself();
} else {
forceRefresh = true;
reregisterHandlers();
}
}
}
} catch (InterruptedException e) {
LOG.warn("interrupted while waiting for refresh to complete");
}
}
private void disposeMyself() {
if (!tobeDisposed) {
LOG.warn("triggering disposal of preview");
ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().getMessageBus()
.syncPublisher(AsciiDocPreviewEditor.RefreshPreviewListener.TOPIC)
.refreshPreview(this));
tobeDisposed = true;
}
}
@NotNull
private static String getScriptingLines() {
return MY_SCRIPTING_LINES.getValue();
}
private String prepareHtml(@NotNull String html, @NotNull Map<String, String> attributes) {
// Antora plugin might resolve some absolute URLs, convert them to localfile so they get their MD5 that prevents caching
Pattern pattern = Pattern.compile("<img src=\"file:///([^\"?]*)\"");
Matcher matcher = pattern.matcher(html);
while (matcher.find()) {
final MatchResult matchResult = matcher.toMatchResult();
String file = matchResult.group(1);
try {
file = URLDecoder.decode(file, StandardCharsets.UTF_8.name()); // restore "%20" as " "
} catch (IllegalArgumentException e) {
// ignored, this must be a manually entered URL with a percentage sign
continue;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
String tmpFile = findTempImageFile(file, null);
String md5;
String replacement;
if (tmpFile != null) {
md5 = calculateMd5(tmpFile, null);
tmpFile = tmpFile.replaceAll("\\\\", "/");
replacement = "<img src=\"file://" + tmpFile + "?" + md5 + "\"";
} else {
md5 = calculateMd5(file, base);
replacement = "<img src=\"file://" + base.replaceAll("%3A", ":") + "/" + file + "?" + md5 + "\"";
}
html = html.substring(0, matchResult.start()) +
replacement + html.substring(matchResult.end());
matcher.reset(html);
}
/* for each image we'll calculate a MD5 sum of its content. Once the content changes, MD5 and therefore the URL
* will change. The changed URL is necessary for the JavaFX web view to display the new content, as each URL
* will be loaded only once by the JavaFX web view. */
pattern = Pattern.compile("<img src=\"([^:\"]*)\"");
matcher = pattern.matcher(html);
while (matcher.find()) {
final MatchResult matchResult = matcher.toMatchResult();
String file = matchResult.group(1);
try {
file = URLDecoder.decode(file, StandardCharsets.UTF_8.name()); // restore "%20" as " "
} catch (IllegalArgumentException e) {
// ignored, this must be a manually entered URL with a percentage sign
continue;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
String tmpFile = findTempImageFile(file, attributes.get("imagesdir"));
String md5;
String replacement;
if (tmpFile != null) {
md5 = calculateMd5(tmpFile, null);
tmpFile = tmpFile.replaceAll("\\\\", "/");
replacement = "<img src=\"file://" + tmpFile + "?" + md5 + "\"";
} else {
md5 = calculateMd5(file, base);
replacement = "<img src=\"file://" + base.replaceAll("%3A", ":") + "/" + file + "?" + md5 + "\"";
}
html = html.substring(0, matchResult.start()) +
replacement + html.substring(matchResult.end());
matcher.reset(html);
}
/* the same as above for interactive SVGs */
pattern = Pattern.compile("<object ([^>])*data=\"([^:\"]*)\"");
matcher = pattern.matcher(html);
while (matcher.find()) {
final MatchResult matchResult = matcher.toMatchResult();
String other = matchResult.group(1);
if (other == null) {
other = "";
}
String file = matchResult.group(2);
try {
file = URLDecoder.decode(file, StandardCharsets.UTF_8.name()); // restore "%20" as " "
} catch (IllegalArgumentException e) {
// ignored, this must be a manually entered URL with a percentage sign
continue;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
String tmpFile = findTempImageFile(file, attributes.get("imagesdir"));
String md5;
String replacement;
if (tmpFile != null) {
md5 = calculateMd5(tmpFile, null);
replacement = "<object " + other + "data=\"file://" + tmpFile + "?" + md5 + "\"";
} else {
md5 = calculateMd5(file, base);
replacement = "<object " + other + "data=\"file://" + base.replaceAll("%3A", ":") + "/" + file + "?" + md5 + "\"";
}
html = html.substring(0, matchResult.start()) +
replacement + html.substring(matchResult.end());
matcher.reset(html);
}
html = AsciiDoc.enrichPage(html, AsciiDocHtmlPanel.getCssLines(isDarcula() ? myInlineCssDarcula : myInlineCss) + myFontAwesomeCssLink + myGoogleFontsCssLink + myDejavuCssLink, attributes, editor != null ? editor.getProject() : null);
html = html.replaceAll("<head>", "<head>\n" +
"<meta http-equiv=\"Content-Security-Policy\" content=\"" + PreviewStaticServer.createCSP(attributes) + "\">");
/* Add JavaScript for auto-scolling and clickable links */
return html
.replace("</body>", getScriptingLines() + "</body>");
}
@Override
public void dispose() {
getJBCefClient().removeLoadHandler(myCefLoadHandler, getCefBrowser());
Disposer.dispose(myJSQuerySetScrollY);
Disposer.dispose(myRenderedResult);
Disposer.dispose(myRenderedIteration);
Disposer.dispose(myBrowserLog);
Disposer.dispose(myScrollEditorToLine);
Disposer.dispose(myZoomDelta);
Disposer.dispose(myZoomReset);
Disposer.dispose(mySaveImage);
Disposer.dispose(myOpenLink);
super.dispose();
}
private String findTempImageFile(String filename, String imagesdir) {
try {
Path file = imagesPath.resolve(filename);
if (Files.exists(file)) {
return file.toFile().toString();
}
} catch (InvalidPathException e) {
LOG.info("problem decoding decode filename " + filename, e);
}
// when {imagesoutdir} is set, files created by asciidoctor-diagram end up in the root path of that dir, but HTML will still prepend {imagesdir}
// try again with removed {imagesdir}
// https://github.com/asciidoctor/asciidoctor-diagram/issues/110
if (imagesdir != null) {
String prefix = imagesdir + "/";
if (filename.startsWith(prefix)) {
filename = filename.substring(prefix.length());
try {
Path file = imagesPath.resolve(filename);
if (Files.exists(file)) {
return file.toFile().toString();
}
} catch (InvalidPathException e) {
LOG.info("problem decoding decode filename " + filename, e);
}
}
}
// a user might have specified multiple different imagesdir within the document, strip prefixes one-by-one and see if we find the image
String shortenedFilename = filename;
while (shortenedFilename.indexOf('/') != -1) {
shortenedFilename = shortenedFilename.substring(shortenedFilename.indexOf('/') + 1);
try {
Path file = imagesPath.resolve(shortenedFilename);
if (Files.exists(file)) {
return file.toFile().toString();
}
} catch (InvalidPathException e) {
LOG.info("problem decoding decode filename " + filename, e);
}
}
return null;
}
private String calculateMd5(String file, String base) {
String md5;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
try (FileInputStream fis = new FileInputStream((base != null ? base.replaceAll("%3A", ":") + "/" : "") + file)) {
int nread;
byte[] dataBytes = new byte[1024];
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
}
byte[] mdbytes = md.digest();
StringBuilder sb = new StringBuilder();
for (byte mdbyte : mdbytes) {
sb.append(Integer.toString((mdbyte & 0xff) + 0x100, 16).substring(1));
}
md5 = sb.toString();
} catch (NoSuchAlgorithmException | IOException e) {
md5 = "none";
}
return md5;
}
@NotNull
private String wrapHtmlForPage(String html) {
return "<html><head></head><body><div id=\"header\"></div><div style='position:fixed;top:0;left:0;background-color:#eeeeee;color:red;z-index:99;'><div id='mathjaxerrortext'></div><pre style='color:red' id='mathjaxerrorformula'></pre></div>"
+ html
+ "</body></html>";
}
@Override
public void render() {
}
private boolean isDarcula() {
final AsciiDocApplicationSettings settings = AsciiDocApplicationSettings.getInstance();
switch (settings.getAsciiDocPreviewSettings().getPreviewTheme()) {
case INTELLIJ:
return UIUtil.isUnderDarcula();
case ASCIIDOC:
return false;
case DARCULA:
return true;
default:
return false;
}
}
@Override
public void scrollToLine(int line, int lineCount) {
this.lineCount = lineCount;
this.line = line;
getCefBrowser().executeJavaScript(
"if ('__IntelliJTools' in window) " +
"__IntelliJTools.scrollToLine(" + line + ", " + lineCount + ");",
getCefBrowser().getURL(), 0);
getCefBrowser().executeJavaScript(
"var value = document.documentElement.scrollTop || document.body.scrollTop;" +
myJSQuerySetScrollY.inject("value"),
getCefBrowser().getURL(), 0);
}
@Override
public @Nullable Editor getEditor() {
return editor;
}
@Override
public void setEditor(@NotNull Editor editor) {
this.editor = editor;
}
private class ScrollPreservingListener extends CefLoadHandlerAdapter {
@SuppressWarnings("checkstyle:VisibilityModifier")
volatile int myScrollY = 0;
@Override
public void onLoadingStateChange(CefBrowser browser, boolean isLoading, boolean canGoBack, boolean canGoForward) {
if (isLoading) {
if (JreHiDpiUtil.isJreHiDPIEnabled() && !hasLoadedOnce) {
ApplicationManager.getApplication().invokeLater(() -> {
// change the height back and forth for one pixel to force re-sizing of the JCEF in the preview
// to fix situations where two screens are of different HiDPI mode - once per new JCEF preview
// workaround for: https://youtrack.jetbrains.com/issue/IDEA-246551
// in 2020.3.2 this uses the Swing API. From 2021.1 the CefBrowser can be triggered for a resize outside the EDT
// using getCefBrowser().wasResized().
// Starting from IC-211.6222.4 (EAP) this might no longer be necessary?
if (getComponent().getComponents().length > 0) {
Component c = getComponent().getComponents()[0];
int width = c.getWidth();
int height = c.getHeight();
c.setSize(width, height - 1);
c.setSize(width, height);
}
});
}
getCefBrowser().executeJavaScript(
"var value = document.documentElement.scrollTop || document.body.scrollTop;" +