forked from Jonathan-LeRoux/IguanaTex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LatexForm.frm
1885 lines (1677 loc) · 79 KB
/
LatexForm.frm
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
VERSION 5.00
Begin {C62A69F0-16DC-11CE-9E98-00AA00574A4F} LatexForm
Caption = "IguanaTex"
ClientHeight = 4062
ClientLeft = -258
ClientTop = -948
ClientWidth = 5058
OleObjectBlob = "LatexForm.frx":0000
StartUpPosition = 1 'CenterOwner
End
Attribute VB_Name = "LatexForm"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Private LaTexEngineList As Variant
Private LatexmkOptionsList As Variant
Private UsePDFList As Variant
'Dim NumberOfTemplates As Long
Private TemplateSortedListString As String
Private TemplateSortedList() As String
Private TemplateNameSortedListString As String
Private FormHeightWidthSet As Boolean
Private DoneWithActivation As Boolean
Private theAppEventHandler As New AppEventHandler
#If Mac Then
Public TextWindow1 As New TextWindow
Public TextWindowTemplateCode As New TextWindow
#Else
Public TextWindow1 As MSForms.TextBox
Public TextWindowTemplateCode As MSForms.TextBox
#End If
Sub InitializeApp()
Set theAppEventHandler.App = Application
AddMenuItem "New Latex display...", "NewLatexEquation", 18 '226
AddMenuItem "Edit Latex display...", "EditLatexEquation", 37
AddMenuItem "Regenerate selection...", "RegenerateSelection", 19
AddMenuItem "Vectorize selection...", "ConvertToVector", 153
AddMenuItem "Rasterize selection...", "ConvertToBitmap", 931
AddMenuItem "Settings...", "LoadSettingsForm", 548
AddMenuItem "Insert vector file...", "InsertVectorGraphicsFile", 23
End Sub
Sub AddMenuItem(ByVal itemText As String, ByVal itemCommand As String, ByVal itemFaceId As Long)
' Check if we have already added the menu item
Dim initialized As Boolean
Dim bef As Integer
initialized = False
bef = 1
Dim Menu As CommandBars
Set Menu = Application.CommandBars
Dim i As Long
For i = 1 To Menu("Insert").Controls.count
With Menu("Insert").Controls(i)
If .Caption = itemText Then
initialized = True
Exit For
ElseIf InStr(.Caption, "Dia&gram") Then
bef = i
End If
End With
Next
' Create the menu choice.
If Not initialized Then
Dim NewControl As CommandBarControl
Set NewControl = Menu("Insert").Controls.Add _
(Type:=msoControlButton, _
before:=bef, _
Id:=itemFaceId)
NewControl.Caption = itemText
NewControl.OnAction = itemCommand
NewControl.Style = msoButtonIconAndCaption
End If
End Sub
Sub UnInitializeApp()
RemoveMenuItem "New Latex display..."
RemoveMenuItem "Edit Latex display..."
RemoveMenuItem "Regenerate selection..."
RemoveMenuItem "Vectorize selection..."
RemoveMenuItem "Rasterize selection..."
RemoveMenuItem "Settings..."
RemoveMenuItem "Insert vector file..."
' Clean up older versions
RemoveMenuItem "Regenerate selected displays..."
RemoveMenuItem "Convert to EMF..."
RemoveMenuItem "Convert to PNG..."
End Sub
Sub RemoveMenuItem(ByVal itemText As String)
Dim Menu As CommandBars
Set Menu = Application.CommandBars
Dim i As Variant
For i = 1 To Menu("Insert").Controls.count
If Menu("Insert").Controls(i).Caption = itemText Then
Menu("Insert").Controls(i).Delete
Exit For
End If
Next
End Sub
Private Sub ButtonCancel_Click()
Unload LatexForm
End Sub
Sub ButtonRun_Click()
Dim TempPath As String
TempPath = CleanPath(TextBoxTempFolder.Text)
If Not IsPathWritable(TempPath) Then Exit Sub
Dim FilePrefix As String
FilePrefix = DefaultFilePrefix
Dim debugMode As Boolean
debugMode = checkboxDebug.value
' Check if an external editor is being used as default, if so, do not delete temp files to avoid issues with external editor
Dim UseExternalEditor As Boolean
UseExternalEditor = GetITSetting("UseExternalEditor", False)
' Read settings
Dim LATEXENGINEID As Integer
LATEXENGINEID = ComboBoxLaTexEngine.ListIndex
Dim tex2pdf_command As String
tex2pdf_command = LaTexEngineList(LATEXENGINEID)
Dim gs_command As String
gs_command = GetITSetting("GS Command", DEFAULT_GS_COMMAND)
Dim IMconv As String
IMconv = GetITSetting("IMconv", DEFAULT_IM_CONV)
Dim tex2img_command As String
tex2img_command = GetITSetting("TeX2img Command", DEFAULT_TEX2IMG_COMMAND)
Dim pdfiumdraw_command As String
pdfiumdraw_command = GetFolderFromPath(tex2img_command) & "pdfiumdraw.exe"
Dim UseLatexmk As Boolean
UseLatexmk = GetITSetting("UseLatexmk", False)
Dim latexmk_command As String
latexmk_command = "latexmk"
Dim latexmk_options As String
latexmk_options = LatexmkOptionsList(LATEXENGINEID)
Dim TeXExePath As String, TeXExeExt As String
TeXExePath = GetITSetting("TeXExePath", DEFAULT_TEX_EXE_PATH)
TeXExeExt = vbNullString
#If Mac Then
' no need to do anything for TeXExeExt on Mac
#Else
If TeXExePath <> vbNullString Then TeXExeExt = ".exe"
#End If
Dim libgsPath As String
libgsPath = GetITSetting("Libgs", DEFAULT_LIBGS)
Dim libgsString As String
If libgsPath <> vbNullString Then
libgsString = " --libgs=" & ShellEscape(libgsPath)
Else
libgsString = vbNullString
End If
Dim UsePDF As Boolean
UsePDF = UsePDFList(LATEXENGINEID)
Dim UseVector As Boolean
Dim BitmapVector As Integer
BitmapVector = ComboBoxBitmapVector.ListIndex
UseVector = Not (BitmapVector = 0)
Dim VectorOutputType As String
VectorOutputType = GetITSetting("VectorOutputType", DEFAULT_VECTOR_OUTPUT_TYPE)
Dim OutputType As String
#If Mac Then
If Not UseVector Then
' Force PDF output for Mac in all cases except Vector (where dvi2svgm is a valid route),
' as it likely more desirable than PNG
UsePDF = True
End If
#End If
Dim TimeOutTimeString As String
Dim TimeOutTime As Long
TimeOutTimeString = GetITSetting("TimeOutTime", "20") ' Wait N seconds for the processes to complete
TimeOutTime = val(TimeOutTimeString) * 1000
Dim OutputDpiString As String
OutputDpiString = TextBoxLocalDPI.Text
Dim OutputDpi As Long
OutputDpi = val(OutputDpiString)
' Read current dpi in: this will be used when rescaling
Dim dpi As Double, default_screen_dpi As Double
dpi = 96 'lDotsPerInch ' I'm not convinced that this is the right thing to do, so for now I stop trying to take dpi into account
default_screen_dpi = 96
Dim VectorScalingX As Single, VectorScalingY As Single, BitmapScalingX As Single, BitmapScalingY As Single
VectorScalingX = dpi / default_screen_dpi * val(GetITSetting("VectorScalingX", "1"))
VectorScalingY = dpi / default_screen_dpi * val(GetITSetting("VectorScalingY", "1"))
BitmapScalingX = val(GetITSetting("BitmapScalingX", "1"))
BitmapScalingY = val(GetITSetting("BitmapScalingY", "1"))
' Write latex to a temp file
WriteToFile TempPath, FilePrefix, TextWindow1.Text
' Run latex
#If Mac Then
Dim fs As New MacFileSystemObject
#Else
Dim fs As New FileSystemObject
#End If
FrameProcess.Visible = True
Dim RetVal As Long, RetValConv As Long
Dim FinalFilename As String
Dim ErrorMessage As String
Dim RunCommand As String
If UseVector = True And VectorOutputType = "tex2img" Then
' Use TeX2img to generate an EMF file from LaTeX
LabelProcess.Caption = "LaTeX to EMF..."
FrameProcess.Repaint
RunCommand = ShellEscape(tex2img_command) & " --latex " + tex2pdf_command _
& " --preview- " + FilePrefix + ".tex" & " " + FilePrefix + ".emf"
RetVal& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
If (RetVal& <> 0 Or Not fs.FileExists(TempPath & FilePrefix & ".emf")) Then
ErrorMessage = "TeX2img did not return in " & TimeOutTimeString & " seconds and may have hung." _
& vbNewLine & "You should have run TeX2img once outside IguanaTex to make sure its path are set correctly." _
& vbNewLine & "Please make sure your code compiles outside IguanaTex."
ShowError ErrorMessage, RunCommand
FrameProcess.Visible = False
Exit Sub
End If
FinalFilename = FilePrefix & ".emf"
OutputType = "EMF"
Else
' Either a Bitmap display, a Vector display generated as SVG, or a Vector displays generated as EMF with pdfiumdraw
If UsePDF = True Then
' PDF to PNG/SVG/EMF route
Dim OutputExt As String
If UseLatexmk = True Then
OutputExt = ".pdf"
LabelProcess.Caption = "LaTeX to PDF..."
FrameProcess.Repaint
RunCommand = ShellEscape(TeXExePath & latexmk_command & TeXExeExt) & " " & latexmk_options _
& " -shell-escape -interaction=batchmode " & FilePrefix + ".tex"
RetVal& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
Else
If tex2pdf_command = "platex" Then
OutputExt = ".dvi"
LabelProcess.Caption = "LaTeX to DVI..."
Else
OutputExt = ".pdf"
LabelProcess.Caption = "LaTeX to PDF..."
End If
FrameProcess.Repaint
RunCommand = ShellEscape(TeXExePath & tex2pdf_command & TeXExeExt) & " -shell-escape -interaction=batchmode " _
& FilePrefix + ".tex"
RetVal& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
End If
If (RetVal& <> 0 Or Not fs.FileExists(TempPath & FilePrefix & OutputExt)) Then
' Error in Latex code
' Read log file and show it to the user
If fs.FileExists(TempPath & FilePrefix & ".log") Then
ShowLogFile (TempPath & FilePrefix & ".log")
Else
ErrorMessage = tex2pdf_command & " did not return in " & TimeOutTimeString & " seconds and may have hung." _
& vbNewLine & "Please make sure your code compiles outside IguanaTex." _
& vbNewLine & "You may also try generating in Debug mode, as it will let you know if any font/package is missing"
ShowError ErrorMessage, RunCommand
End If
FrameProcess.Visible = False
Exit Sub
End If
If UseLatexmk = False And tex2pdf_command = "platex" Then
LabelProcess.Caption = "DVI to PDF..."
FrameProcess.Repaint
' platex actually outputs a DVI file, which we need to convert to PDF (we could go the EPS route, but this blends easier with IguanaTex's existing code)
RunCommand = ShellEscape(TeXExePath & "dvipdfmx" & TeXExeExt) & " -o " + FilePrefix + ".pdf" _
& " " & FilePrefix & ".dvi"
RetValConv& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
If (RetValConv& <> 0 Or Not fs.FileExists(TempPath & FilePrefix & ".pdf")) Then
' Error in DVI to PDF conversion
ErrorMessage = "Error while using dvipdfmx to convert from DVI to PDF."
ShowError ErrorMessage, RunCommand
FrameProcess.Visible = False
Exit Sub
End If
End If
If UseVector = True Then ' SVG or EMF
If VectorOutputType = "dvisvgm" Then ' Convert to SVG
' Use dvisvgm to generate SVG file
LabelProcess.Caption = "PDF to SVG..."
FrameProcess.Repaint
RunCommand = ShellEscape(TeXExePath & "dvisvgm" & TeXExeExt) & " --pdf -o " _
& FilePrefix & ".svg" & libgsString & " " _
& FilePrefix & ".pdf"
RetValConv& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
If (RetValConv& <> 0 Or Not fs.FileExists(TempPath & FilePrefix & ".svg")) Then
' Error in PDF to SVG conversion
ErrorMessage = "Error while using dvisvgm to convert from PDF to SVG."
ShowError ErrorMessage, RunCommand
FrameProcess.Visible = False
Exit Sub
End If
FinalFilename = FilePrefix & ".svg"
OutputType = "SVG"
Else ' VectorOutputType = "pdfiumdraw"
' Use pdfiumdraw to generate an EMF file from the previously generated PDF
LabelProcess.Caption = "PDF to EMF..."
FrameProcess.Repaint
RunCommand = ShellEscape(pdfiumdraw_command) & " --extent=50 --emf --transparent --pages=1 " _
& FilePrefix & ".pdf"
RetVal& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
If (RetVal& <> 0 Or Not fs.FileExists(TempPath & FilePrefix & ".emf")) Then
ErrorMessage = "TeX2img's pdfiumdraw did not return in " & TimeOutTimeString & " seconds and may have hung." _
& vbNewLine & "You should have run TeX2img once outside IguanaTex to make sure its path are set correctly." _
& vbNewLine & "Please make sure your code compiles outside IguanaTex."
ShowError ErrorMessage, RunCommand
FrameProcess.Visible = False
Exit Sub
End If
FinalFilename = FilePrefix & ".emf"
OutputType = "EMF"
End If
Else ' "Bitmap" Display, i.e., PDF on Mac, PNG on Windows
#If Mac Then
LabelProcess.Caption = "Cropping PDF..."
FrameProcess.Repaint
#Else
LabelProcess.Caption = "PDF to PNG..."
FrameProcess.Repaint
#End If
' Output Bounding Box to file and read back in the appropriate information
#If Mac Then
RunCommand = ShellEscape(gs_command) & " -q -dBATCH -dNOPAUSE -sDEVICE=bbox " _
& FilePrefix & ".pdf" & " 2> " & FilePrefix & ".bbx"
#Else
RunCommand = "cmd /C " & ShellEscape(gs_command) & " -q -dBATCH -dNOPAUSE -sDEVICE=bbox " _
& FilePrefix & ".pdf" & " 2> " & FilePrefix & ".bbx"
#End If
RetValConv& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
If (RetValConv& <> 0 Or Not fs.FileExists(TempPath & FilePrefix & ".bbx")) Then
' Error in bounding box computation
ErrorMessage = "Error while using Ghostscript to compute the bounding box. Is your path correct?"
ShowError ErrorMessage, RunCommand
FrameProcess.Visible = False
Exit Sub
End If
Dim BBString As String
BBString = BoundingBoxString(TempPath + FilePrefix + ".bbx")
#If Mac Then
' PDF insert supported on Mac, only need to crop
RunCommand = ShellEscape(gs_command) & " -q -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=" _
& FilePrefix & "_tmp.pdf" & BBString _
& " -f " & ShellEscape(TempPath & FilePrefix & ".pdf")
RetValConv& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
If (RetValConv& <> 0 Or Not fs.FileExists(TempPath & FilePrefix & "_tmp.pdf")) Then
' Error in PDF crop
ErrorMessage = "Error while using Ghostscript to crop the PDF. Is your path correct?"
ShowError ErrorMessage, RunCommand
FrameProcess.Visible = False
Exit Sub
End If
OutputType = "PDF"
FinalFilename = FilePrefix & "_tmp.pdf"
#Else
' Convert PDF to PNG
RunCommand = ShellEscape(gs_command) & " -q -dBATCH -dNOPAUSE -sDEVICE=pngalpha -r" & OutputDpiString _
& " -sOutputFile=" & FilePrefix & "_tmp.png" & BBString _
& " -f " & ShellEscape(TempPath & FilePrefix & ".pdf")
RetValConv& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
If (RetValConv& <> 0 Or Not fs.FileExists(TempPath & FilePrefix & "_tmp.png")) Then
' Error in PDF to PNG conversion
ErrorMessage = "Error while using Ghostscript to convert from PDF to PNG. Is your path correct?"
ShowError ErrorMessage, RunCommand
FrameProcess.Visible = False
Exit Sub
End If
' Unfortunately, the resulting file has a metadata DPI of OutputDpi (=1200), not the default screen one (usually 96),
' so there is a discrepancy with the dvipng output, which is always 96 (independent of the screen, actually).
' The only workaround I have found so far is to use Imagemagick's convert to change the DPI (but not the pixel size!)
' Execute ShellEscape(IMconv) & " -units PixelsPerInch " & FilePrefix & "_tmp.png" & _
' " -density " & CStr(dpi) & " " & FilePrefix & ".png", TempPath, debugMode
RunCommand = ShellEscape(IMconv) & " -units PixelsPerInch " & FilePrefix & "_tmp.png" _
& " -density " & CStr(default_screen_dpi) & " " & FilePrefix & ".png"
RetValConv& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
If (RetValConv& <> 0 Or Not fs.FileExists(TempPath & FilePrefix & ".png")) Then
' Error in PDF to PNG conversion
ErrorMessage = "Error while using ImageMagick to change the PNG DPI. Is your path correct?" _
& vbNewLine & "The full path is needed to avoid conflict with Windows's built-in convert.exe."
ShowError ErrorMessage, RunCommand
FrameProcess.Visible = False
Exit Sub
End If
' 'I considered using ImageMagick's convert, but it's extremely slow, and uses ghostscript in the backend anyway
'PdfPngSwitches = "-density 1200 -trim -transparent white -antialias +repage"
'Execute IMconv & " " & PdfPngSwitches & " """ & FilePrefix & ".pdf"" """ & FilePrefix & ".png""", TempPath, debugMode
OutputType = "PNG"
FinalFilename = FilePrefix & ".png"
#End If
End If
Else
' DVI to PNG/SVG/EMF routes
LabelProcess.Caption = "LaTeX to DVI..."
FrameProcess.Repaint
If UseLatexmk = True Then
RunCommand = ShellEscape(TeXExePath & latexmk_command & TeXExeExt) & " " & latexmk_options _
& " -shell-escape -interaction=batchmode " + FilePrefix + ".tex"
Else
RunCommand = ShellEscape(TeXExePath & "pdflatex" & TeXExeExt) & " -shell-escape -output-format dvi -interaction=batchmode " _
& FilePrefix & ".tex"
End If
RetVal& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
If (RetVal& <> 0 Or Not fs.FileExists(TempPath & FilePrefix & ".dvi")) Then
' Error in Latex code
' Read log file and show it to the user
If fs.FileExists(TempPath & FilePrefix & ".log") Then
ShowLogFile (TempPath + FilePrefix + ".log")
Else
ErrorMessage = "latex did not return in " & TimeOutTimeString & " seconds and may have hung." _
& vbNewLine & "Please make sure your code compiles outside IguanaTex." _
& vbNewLine & "You may also try generating in Debug mode, as it will let you know if any font/package is missing."
ShowError ErrorMessage, RunCommand
End If
FrameProcess.Visible = False
Exit Sub
End If
If UseVector = True Then
If VectorOutputType = "dvisvgm" Then
' Use dvi2svg to generate SVG file
LabelProcess.Caption = "DVI to SVG..."
FrameProcess.Repaint
RunCommand = ShellEscape(TeXExePath & "dvisvgm" & TeXExeExt) & " --no-font -o " & FilePrefix & ".svg" _
& " " & FilePrefix & ".dvi"
RetValConv& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
If (RetValConv& <> 0 Or Not fs.FileExists(TempPath & FilePrefix & ".svg")) Then
' Error in DVI to SVG conversion
ErrorMessage = "Error while using dvisvgm to convert from DVI to SVG."
ShowError ErrorMessage, RunCommand
FrameProcess.Visible = False
Exit Sub
End If
FinalFilename = FilePrefix & ".svg"
OutputType = "SVG"
Else ' VectorOutputType = "pdfiumdraw"
' Use TeX2img's pdfiumdraw to generate an EMF file
LabelProcess.Caption = "DVI to PDF..."
FrameProcess.Repaint
RunCommand = ShellEscape(TeXExePath & "dvipdfmx" & TeXExeExt) & " -o " & FilePrefix + ".pdf" _
& " " & FilePrefix & ".dvi"
RetValConv& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
If (RetValConv& <> 0 Or Not fs.FileExists(TempPath & FilePrefix & ".pdf")) Then
' Error in DVI to PDF conversion
ErrorMessage = "Error while using dvipdfmx to convert from DVI to PDF."
ShowError ErrorMessage, RunCommand
FrameProcess.Visible = False
Exit Sub
End If
LabelProcess.Caption = "PDF to EMF..."
FrameProcess.Repaint
RunCommand = ShellEscape(pdfiumdraw_command) & " --extent=50 --emf --transparent --pages=1 " _
& FilePrefix & ".pdf"
RetVal& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
If (RetVal& <> 0 Or Not fs.FileExists(TempPath & FilePrefix & ".emf")) Then
ErrorMessage = "pdfiumdraw did not return in " & TimeOutTimeString & " seconds and may have hung." _
& vbNewLine & "You should have run TeX2img once outside IguanaTex to make sure its path are set correctly." _
& vbNewLine & "Please make sure your code compiles outside IguanaTex."
ShowError ErrorMessage, RunCommand
FrameProcess.Visible = False
Exit Sub
End If
FinalFilename = FilePrefix & ".emf"
OutputType = "EMF"
End If
Else
LabelProcess.Caption = "DVI to PNG..."
FrameProcess.Repaint
Dim DviPngSwitches As String
' monitor is 96 dpi or higher; we use OutputDpi (=1200 by default) dpi to get a crisper display,
' and rescale later on for new displays to match the point size
DviPngSwitches = "-q -D " & OutputDpiString & " -T tight -bg Transparent"
' If the user created a .png by using the standalone class with convert, we use that, else we use dvipng
If Not fs.FileExists(TempPath & FilePrefix & ".png") Then
RunCommand = ShellEscape(TeXExePath & "dvipng" & TeXExeExt) & " " & DviPngSwitches _
& " -o " & FilePrefix & ".png" & " " & FilePrefix & ".dvi"
RetValConv& = Execute(RunCommand, TempPath, debugMode, TimeOutTime)
If (RetValConv& <> 0 Or Not fs.FileExists(TempPath & FilePrefix & ".png")) Then
ErrorMessage = "dvipng failed, or did not return in " & TimeOutTimeString & " seconds and may have hung." _
& vbNewLine & "You may want to try compiling using the PDF->PNG option." _
& vbNewLine & "You may also try generating in Debug mode, as it will let you know if any font is missing."
ShowError ErrorMessage, RunCommand
FrameProcess.Visible = False
Exit Sub
End If
End If
OutputType = "PNG"
FinalFilename = FilePrefix & ".png"
End If
End If
End If
' Latex run successful.
' Now we prepare the insertion of the image
LabelProcess.Caption = "Insert image..."
FrameProcess.Repaint
' If we are in Edit mode, store parameters of old image
Dim posX As Single
Dim posY As Single
Dim oldHeight As Single
Dim oldWidth As Single
Dim Sel As Selection
Set Sel = Application.ActiveWindow.Selection
Dim oldshape As Shape
Dim oldshapeIsVector As Boolean
Dim s As Shape
Dim j As Long
Dim IsInGroup As Boolean
IsInGroup = False
If ButtonRun.Caption = "ReGenerate" Then
If Sel.ShapeRange.Type = msoGroup And Sel.HasChildShapeRange Then
' Old image is part of a group
Set oldshape = Sel.ChildShapeRange(1)
IsInGroup = True
Dim arr() As Variant ' gather all shapes to be regrouped later on
j = 0
For Each s In Sel.ShapeRange.GroupItems
If s.Name <> oldshape.Name Then
j = j + 1
ReDim Preserve arr(1 To j)
arr(j) = s.Name
End If
Next
' Store the group's animation and Zorder info in a dummy object tmpGroup
Dim oldGroup As Shape
Set oldGroup = Sel.ShapeRange(1)
Dim tmpGroup As Shape
Set tmpGroup = ActiveWindow.Selection.SlideRange.Shapes.AddShape(msoShapeDiamond, 1, 1, 1, 1)
MoveAnimation oldGroup, tmpGroup
MatchZOrder oldGroup, tmpGroup
' Tag all elements in the group with their hierarchy level and their name or group name
Dim MaxGroupLevel As Long
MaxGroupLevel = TagGroupHierarchy(arr, oldshape.Name)
Else
Set oldshape = Sel.ShapeRange(1)
End If
posX = oldshape.Left
posY = oldshape.Top
oldHeight = oldshape.Height
oldWidth = oldshape.Width
oldshapeIsVector = False
If oldshape.Tags.Item("BitmapVector") <> vbNullString Then
If oldshape.Tags.Item("BitmapVector") = 1 Then
oldshapeIsVector = True
End If
End If
Else
posX = 200
posY = 200
If Sel.Type = ppSelectionShapes Then ' if something is selected on a slide, use its position for the new display
'If Sel.ShapeRange.Type = msoGroup And Sel.HasChildShapeRange Then
' Set oldshape = Sel.ChildShapeRange(1)
'Else
' Set oldshape = Sel.ShapeRange(1)
'End If
posX = Sel.ShapeRange(1).Left
posY = Sel.ShapeRange(1).Top
End If
End If
' Get scaling factors
Dim isTexpoint As Boolean
Dim tScaleWidth As Single, tScaleHeight As Single
Dim MagicScalingFactorEMF As Single, MagicScalingFactorPNG As Single
Dim MagicScalingFactorSVG As Single, MagicScalingFactorPDF As Single
Dim MagicScalingFactor As Single
MagicScalingFactorEMF = 1 ' 1 / 100 ' Magical scaling factor for EMF.
MagicScalingFactorPNG = default_screen_dpi / OutputDpi
MagicScalingFactorPDF = 1
MagicScalingFactorSVG = 1
Select Case OutputType
Case "EMF": MagicScalingFactor = MagicScalingFactorEMF
Case "PNG": MagicScalingFactor = MagicScalingFactorPNG
Case "PDF": MagicScalingFactor = MagicScalingFactorPDF
Case "SVG": MagicScalingFactor = MagicScalingFactorSVG
Case Else: MagicScalingFactor = 1
End Select
Dim PointSize As Single
If ButtonRun.Caption <> "ReGenerate" Or CheckBoxReset.value Then
PointSize = val(textboxSize.Text)
tScaleWidth = PointSize / 10 * MagicScalingFactor ' 1/10 is for the default LaTeX point size (10 pt)
tScaleHeight = tScaleWidth
Else
' Handle the case of Texpoint displays
isTexpoint = False
Dim OldDpi As Long
OldDpi = OutputDpi
With oldshape.Tags
If .Item("TEXPOINTSCALING") <> vbNullString Then
isTexpoint = True
tScaleWidth = val(.Item("TEXPOINTSCALING")) * MagicScalingFactor
tScaleHeight = tScaleWidth
End If
If .Item("OUTPUTDPI") <> vbNullString Then
OldDpi = val(.Item("OUTPUTDPI"))
End If
End With
If Not isTexpoint Then ' modifying a normal display, either PNG or EMF
Dim HeightOld As Single, WidthOld As Single
HeightOld = oldshape.Height
WidthOld = oldshape.Width
tScaleHeight = 1
tScaleWidth = 1
If oldshapeIsVector = False Then ' this deals with displays from very old versions of IguanaTex that lack proper size tags
oldshape.ScaleHeight 1#, msoTrue
oldshape.ScaleWidth 1#, msoTrue
tScaleHeight = HeightOld / oldshape.Height * 960 / OutputDpi ' 0.8=960/1200 is there to preserve scaling of displays created with old versions of IguanaTex
tScaleWidth = WidthOld / oldshape.Width * 960 / OutputDpi
End If
With oldshape.Tags
If .Item("ORIGINALHEIGHT") <> vbNullString Then
Dim tmpHeight As Single
tmpHeight = val(.Item("ORIGINALHEIGHT"))
tScaleHeight = HeightOld / tmpHeight * OldDpi / OutputDpi
End If
If .Item("ORIGINALWIDTH") <> vbNullString Then
Dim tmpWidth As Single
tmpWidth = val(.Item("ORIGINALWIDTH"))
tScaleWidth = WidthOld / tmpWidth * OldDpi / OutputDpi
End If
End With
Dim OldMagicScalingFactor As Single
OldMagicScalingFactor = 1
With oldshape.Tags
If .Item("OUTPUTTYPE") <> vbNullString Then
Select Case OutputType
Case "EMF": OldMagicScalingFactor = MagicScalingFactorEMF
Case "PNG": OldMagicScalingFactor = MagicScalingFactorPNG
Case "PDF": OldMagicScalingFactor = MagicScalingFactorPDF
Case "SVG": OldMagicScalingFactor = MagicScalingFactorSVG
Case Else: MagicScalingFactor = 1
End Select
Else ' from an older version where we do not record OutputType
If oldshapeIsVector = False Then ' PNG
OldMagicScalingFactor = MagicScalingFactorPNG
Else ' EMF
OldMagicScalingFactor = MagicScalingFactorEMF
End If
End If
End With
' Compensate for any change between formats
tScaleHeight = tScaleHeight * MagicScalingFactor / OldMagicScalingFactor
tScaleWidth = tScaleWidth * MagicScalingFactor / OldMagicScalingFactor
' If UseVector = True And oldshapeIsVector = False Then
' tScaleHeight = tScaleHeight * MagicScalingFactorEMF / MagicScalingFactorPNG
' tScaleWidth = tScaleWidth * MagicScalingFactorEMF / MagicScalingFactorPNG
' ElseIf UseVector = False And oldshapeIsVector = True Then
' tScaleHeight = tScaleHeight / MagicScalingFactorEMF * MagicScalingFactorPNG
' tScaleWidth = tScaleWidth / MagicScalingFactorEMF * MagicScalingFactorPNG
' End If
End If
End If
' Insert image and rescale it
Dim NewShape As Shape
Set NewShape = AddDisplayShape(TempPath + FinalFilename, posX, posY)
If UseVector Then
If OutputType = "EMF" Then
' Clean up, optionally rescale the EMF picture, and convert it into PPT object
Set NewShape = ConvertEMF(NewShape, VectorScalingX * tScaleWidth, VectorScalingY * tScaleHeight, posX, posY, "emf", True, True)
Else 'SVG case
' Clean up and convert SVG into PPT object
Set NewShape = convertSVG(NewShape, tScaleWidth, tScaleHeight, posX, posY)
End If
' Tag shape and its components with their "original" sizes,
' which we get by dividing their current height/width by the scaling factors applied above
NewShape.Tags.Add "ORIGINALHEIGHT", NewShape.Height / tScaleHeight
NewShape.Tags.Add "ORIGINALWIDTH", NewShape.Width / tScaleWidth
If NewShape.Type = msoGroup Then
For Each s In NewShape.GroupItems
s.Tags.Add "ORIGINALHEIGHT", s.Height / tScaleHeight
s.Tags.Add "ORIGINALWIDTH", s.Width / tScaleWidth
Next
End If
Else
' Resize to the true size of the png file and adjust using the manual scaling factors set in Main Settings
With NewShape
.ScaleHeight 1#, msoTrue
.ScaleWidth 1#, msoTrue
.LockAspectRatio = msoFalse
.ScaleHeight BitmapScalingY, msoFalse
.ScaleWidth BitmapScalingX, msoFalse
.Tags.Add "OUTPUTDPI", OutputDpi ' Stores this display's resolution
' Add tags storing the original height and width, used next time to keep resizing ratio.
.Tags.Add "ORIGINALHEIGHT", NewShape.Height
.Tags.Add "ORIGINALWIDTH", NewShape.Width
' Apply scaling factors
.ScaleHeight tScaleHeight, msoFalse
.ScaleWidth tScaleWidth, msoFalse
.LockAspectRatio = msoTrue
End With
End If
' in v1.59, we start tagging the type of output the shape was obtained from, and the IguanaTex version number
NewShape.Tags.Add "OUTPUTTYPE", OutputType
NewShape.Tags.Add "IGUANATEXVERSION", IGUANATEX_VERSION
If CheckBoxForcePreserveSize.value Then
' We are forcing the new shape to have the same size as the old shape
' This is useful when converting between Bitmap and Vector
With NewShape
.LockAspectRatio = msoFalse
.Height = oldHeight
.Width = oldWidth
.LockAspectRatio = msoTrue
End With
End If
If ButtonRun.Caption = "ReGenerate" Then ' We are editing+resetting size of an old display, we keep rotation
NewShape.Rotation = oldshape.Rotation
If Not CheckBoxReset.value Then
NewShape.LockAspectRatio = oldshape.LockAspectRatio ' Unlock aspect ratio if old display had it unlocked
End If
End If
' Add tags
AddTagsToShape NewShape
If UseVector = True And NewShape.Type = msoGroup Then
Set s = NewShape.GroupItems(1)
AddTagsToShape s 'only left most for now, to make things simple
For Each s In NewShape.GroupItems
' Call AddTagsToShape(s)
s.Tags.Add "EMFchild", True
Next
End If
' Copy animation settings and formatting from old image, then delete it
If ButtonRun.Caption = "ReGenerate" Then
Dim TransferDesign As Boolean
TransferDesign = True
If UseVector <> oldshapeIsVector Or CheckBoxResetFormat.value Then
TransferDesign = False
End If
Dim j_remain As Long, j_current As Long
Dim n As Variant
Dim ThisShapeLevel As Long, i_tag As Long, Level As Long
If IsInGroup Then
' Transfer format to new shape
MatchZOrder oldshape, NewShape
If TransferDesign Then
oldshape.PickUp
NewShape.Apply
End If
' Handle the case of shape within EMF group.
Dim DeleteLowestLayer As Boolean
DeleteLowestLayer = False
If oldshape.Tags.Item("EMFchild") <> vbNullString Then
DeleteLowestLayer = True
End If
oldshape.Delete
Dim newGroup As Shape
' Get current slide, it will be used to group ranges
Dim sld As Slide
Dim SlideIndex As Long
SlideIndex = ActiveWindow.View.Slide.SlideIndex
Set sld = ActivePresentation.Slides(SlideIndex)
' Group all non-modified elements from old group, plus modified element
j = j + 1
ReDim Preserve arr(1 To j)
arr(j) = NewShape.Name
If DeleteLowestLayer Then
Dim arr_remain() As Variant
j_remain = 0
For Each n In arr
Set s = ActiveWindow.Selection.SlideRange.Shapes(n)
ThisShapeLevel = 0
For i_tag = 1 To s.Tags.count
If (s.Tags.Name(i_tag) = "LAYER") Then
ThisShapeLevel = val(s.Tags.value(i_tag))
End If
Next
If ThisShapeLevel = 1 Then
s.Delete
Else
j_remain = j_remain + 1
ReDim Preserve arr_remain(1 To j_remain)
arr_remain(j_remain) = s.Name
End If
Next
NewShape.Tags.Add "LAYER", 2
arr = arr_remain
Else
NewShape.Tags.Add "LAYER", 1
End If
NewShape.Tags.Add "SELECTIONNAME", NewShape.Name
' Hierarchically re-group elements
For Level = 1 To MaxGroupLevel
Dim CurrentLevelArr() As Variant
j_current = 0
For Each n In arr
ThisShapeLevel = 0
Dim ThisShapeSelectionName As String
ThisShapeSelectionName = vbNullString
On Error Resume Next
With ActiveWindow.Selection.SlideRange.Shapes(n).Tags
For i_tag = 1 To .count
If (.Name(i_tag) = "LAYER") Then
ThisShapeLevel = val(.value(i_tag))
End If
If (.Name(i_tag) = "SELECTIONNAME") Then
ThisShapeSelectionName = .value(i_tag)
End If
Next
End With
If ThisShapeLevel = Level Then
If j_current > 0 Then
If Not IsInArray(CurrentLevelArr, ThisShapeSelectionName) Then
j_current = j_current + 1
ReDim Preserve CurrentLevelArr(1 To j_current)
CurrentLevelArr(j_current) = ThisShapeSelectionName
End If
Else
j_current = j_current + 1
ReDim Preserve CurrentLevelArr(1 To j_current)
CurrentLevelArr(j_current) = ThisShapeSelectionName
End If
End If
Next
If j_current > 1 Then
Set newGroup = sld.Shapes.Range(CurrentLevelArr).Group
j = j + 1
ReDim Preserve arr(1 To j)
arr(j) = newGroup.Name
newGroup.Tags.Add "SELECTIONNAME", newGroup.Name
newGroup.Tags.Add "LAYER", Level + 1
End If
Next
' Delete the tags to avoid conflict with future runs
For Each n In arr
On Error Resume Next
ActiveWindow.Selection.SlideRange.Shapes(n).Tags.Delete ("SELECTIONNAME")
ActiveWindow.Selection.SlideRange.Shapes(n).Tags.Delete ("LAYER")
Next
' Use temporary group to retrieve the group's original animation and Zorder
MoveAnimation tmpGroup, newGroup
MatchZOrder tmpGroup, newGroup
tmpGroup.Delete
Else
MoveAnimation oldshape, NewShape
MatchZOrder oldshape, NewShape
If TransferDesign Then
If oldshapeIsVector And oldshape.Type = msoGroup Then
' First transfer group format to temporary shape
' (we use a duplicate of the old EMF shape)
Dim tmpGroupEMF As Shape
Set tmpGroupEMF = oldshape.Duplicate(1)
'TransferGroupFormat oldshape, tmpGroupEMF
' Transfer shape formatting
' First need to delete all but one shape in the group to unlock the format pickup
Dim tmpshp As Shape
Set tmpshp = oldshape.GroupItems(1)
For j = oldshape.GroupItems.count To 2 Step -1
' Delete backwards because Powerpoint renumbers
' We could also always delete .GroupItems(2) ...
oldshape.GroupItems(j).Delete
Next
tmpshp.PickUp
' Transfer shape formatting to each shape within the group
For Each s In NewShape.GroupItems
s.Apply
Next
tmpshp.Delete
' Now we can transfer the group formatting from the temporary shape
TransferGroupFormat tmpGroupEMF, NewShape
tmpGroupEMF.Delete
Else
oldshape.PickUp
NewShape.Apply
oldshape.Delete
End If
Else
oldshape.Delete
End If
End If
End If
' Handle non-transparent case if selected by user in form; this used to be handled by making the PNG itself non-transparent
If Not checkboxTransp.value Then
NewShape.Fill.ForeColor.RGB = vbWhite
NewShape.Fill.Visible = True
End If
' Add Alternative Text
NewShape.AlternativeText = TextWindow1.Text
If UseVector = True Then
NewShape.Title = "IguanaTex Vector Display"
Else
NewShape.Title = "IguanaTex Bitmap Display"
End If
' Select the new shape
NewShape.Select
' Delete temp files if not in debug mode, external editor not used, and chose not to keep them in Main Settings
Dim KeepTempFiles As Boolean
KeepTempFiles = GetITSetting("KeepTempFiles", True)
If (Not debugMode) And (Not UseExternalEditor) And (Not KeepTempFiles) Then
#If Mac Then
fs.FindDelete TempPath, FilePrefix + "*.*"
#Else
fs.DeleteFile TempPath + FilePrefix + "*.*"
#End If
End If
FrameProcess.Visible = False
Unload LatexForm
Exit Sub
End Sub
Private Sub AddTagsToShape(ByVal vSh As Shape)
With vSh.Tags
.Add "LATEXADDIN", TextWindow1.Text
.Add "IguanaTexSize", val(textboxSize.Text)
.Add "IGUANATEXCURSOR", TextWindow1.SelStart
.Add "TRANSPARENCY", checkboxTransp.value
.Add "FILENAME", TextBoxFile.Text
.Add "LATEXENGINEID", ComboBoxLaTexEngine.ListIndex
.Add "TEMPFOLDER", TextBoxTempFolder.Text
.Add "LATEXFORMHEIGHT", LatexForm.Height
.Add "LATEXFORMWIDTH", LatexForm.Width
.Add "LATEXFORMWRAP", TextWindow1.WordWrap
.Add "BitmapVector", ComboBoxBitmapVector.ListIndex
End With
End Sub
Private Sub ShowLogFile(LogFileName As String)
LogFileViewer.TextBox1.Text = ReadAll(LogFileName)
LogFileViewer.TextBox1.ScrollBars = fmScrollBarsBoth
LogFileViewer.Show 1
End Sub
Private Function IsInArray(ByVal arr As Variant, ByVal valueToCheck As String) As Boolean
IsInArray = False
Dim n As Variant
For Each n In arr
If n = valueToCheck Then
IsInArray = True
Exit For
End If
Next
End Function