-
Notifications
You must be signed in to change notification settings - Fork 0
/
luapstricks.lua
4314 lines (4176 loc) · 131 KB
/
luapstricks.lua
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
---- luapstricks.lua
-- Copyright 2021--2023 Marcel Krüger <[email protected]>
--
-- This work may be distributed and/or modified under the
-- conditions of the LaTeX Project Public License, either version 1.3
-- of this license or (at your option) any later version.
-- The latest version of this license is in
-- http://www.latex-project.org/lppl.txt
-- and version 1.3 or later is part of all distributions of LaTeX
-- version 2005/12/01 or later.
--
-- This work has the LPPL maintenance status `maintained'.
--
-- The Current Maintainer of this work is M. Krüger
--
-- This work consists of the files luapstricks.lua and luapstricks-plugin-pstmarble.lua
if luatexbase then
luatexbase.provides_module {
name = 'luapstricks',
version = 'v0.10',
date = '2023-05-23',
description = 'PSTricks backend for LuaLaTeX',
}
end
local setwhatsitfield = node.setwhatsitfield or node.setfield
local late_lua_sub = node.subtype'late_lua'
local pdfprint = vf.pdf -- Set later to have the right mode
local function gobble() end
local function no_pdfprint_allowed()
pdfprint = gobble -- Don't warn more than once for each code block
tex.error("luapstricks: Graphics in immediate code segment", {
"There was an attempt to trigger drawing commands in an immediate code block. \z
This isn't allowed and will therefore be ignored."
})
end
local pi = math.pi
local two_pi = 2*pi
local pi2_inv = 2/pi
local pi3_inv = 3/pi
local sin_table = {0, 1, 0, -1}
local l = lpeg
local whitespace = (l.S'\0\t\n\r\f ' + '%' * (1-l.P'\n')^0 * (l.P'\n' + -1))^1
local regular = 1 - l.S'\0\t\n\r\f %()<>[]{}/'
local exitmarker = {}
local lookup
local issued_document_metadata_warning
local function warn_document_metadata()
if issued_document_metadata_warning then return end
issued_document_metadata_warning = true
texio.write_nl"Extended graphic state modifications dropped since LaTeX support is not loaded."
texio.write_nl"Insert \\DocumentMetadata{} as first line of your document to solve this issue."
end
-- local integer = l.S'+-'^-1 * l.R'09'^1 / tonumber
local real = l.S'+-'^-1 * (l.R'09'^1 * ('.' * l.R'09'^0)^-1 + '.' * l.R'09'^1) * (l.S'Ee' * l.S'+-'^-1 * l.R'09'^1)^-1 / tonumber
local radix_scanner = setmetatable({}, {__index = function(t, b)
local digit
if b < 10 then
digit = l.R('0' .. string.char(string.byte'0' + b - 1))
else
digit = l.R'09'
if b > 10 then
digit = digit + l.R('A' .. string.char(string.byte'A' + b - 11))
digit = digit + l.R('a' .. string.char(string.byte'a' + b - 11))
end
end
digit = l.C(digit^1) * l.Cp()
t[b] = digit
return digit
end})
local radix = l.Cmt(l.R'09' * l.R'09'^-1 / tonumber * '#', function(subj, pos, radix)
if radix < 2 or radix > 36 then return end
local digits, pos = radix_scanner[radix]:match(subj, pos)
if not digits then return end
digits = tonumber(digits, radix)
return pos, digits
end)
local number = radix + real -- + integer -- Every integer is also a real
local str_view do
local meta = {
__index = function(s, k)
if k == 'value' then
return string.sub(s.base.value, s.offset, s.last)
end
end,
__newindex = function(s, k, v)
if k == 'value' then
s.base.value = string.sub(s.base.value, 1, s.offset-1) .. v .. string.sub(s.base.value, s.last+1)
return
end
-- We could do rawset here, but there is no reason for setting keys anyway
assert(false)
end,
}
function str_view(base, offset, length)
if getmetatable(base) == meta then
offset = offset + base.offset - 1
base = base.base
end
return setmetatable({
kind = 'string',
base = base,
offset = offset,
last = offset + length - 1,
}, meta)
end
end
local string_patt do
local literal = '(' * l.Cs(l.P{(
l.Cg('\\' * (
'n' * l.Cc'\n'
+ 'r' * l.Cc'\r'
+ 't' * l.Cc'\t'
+ 'b' * l.Cc'\b'
+ 'f' * l.Cc'\f'
+ '\\' * l.Cc'\\'
+ '(' * l.Cc'('
+ ')' * l.Cc')'
+ l.R'07' * l.R'07'^-2 / function(s) return string.char(tonumber(s, 8) % 0x100) end
+ ('\r' * l.P'\n'^-1 + '\n')^-1 * l.Cc''
))
+ l.Cg('\r' * l.P'\n'^-1 * l.Cc'\n')
+ (1-l.S'()')
+ '(' * l.V(1) * ')'
)^0}) * ')'
local hexchar = l.R('09', 'af', 'AF')
local hexbyte = hexchar * hexchar^-1 / function(s)
local b = tonumber(s, 16)
return #s == 1 and 16*b or b
end
local hex = '<' * (hexbyte^0 / string.char) * '>'
string_patt = literal + hex -- TODO: Base85 is not implemented
end
local name = l.C(regular^1 + l.S'[]' + '<<' + '>>')
local literal_name = '/' * l.C(regular^0)
local imm_name = '//' * l.C(regular^0)
-- All objects are literal by default, except names represented as direct strings and operators
local any_object = l.P{whitespace^-1 * (
number * -regular
+ l.Ct(l.Cg(string_patt, 'value') * l.Cg(l.Cc'string', 'kind'))
+ imm_name / function(name) return lookup(name) end
+ l.Ct(l.Cg(literal_name, 'value') * l.Cg(l.Cc'name', 'kind'))
+ name
+ l.Ct(l.Cg(l.Ct(l.Cg('{' * l.Ct(l.V(1)^0) * whitespace^-1 * '}', 'value') * l.Cg(l.Cc'array', 'kind')), 'value') * l.Cg(l.Cc'executable', 'kind'))
)}
local object_list = l.Ct(any_object^0) * whitespace^-1 * (-1 + l.Cp())
local function parse_ps(s)
local tokens, fail_offset = object_list:match(s)
if fail_offset then
error(string.format('Failed to parse PS tokens at `%s\'', s:sub(fail_offset)))
end
return tokens
end
local serialize_pdf do
function serialize_pdf(obj)
local t = type(obj)
if t == 'number' then
return string.format(math.type(obj) == 'float' and '%.5f' or '%i', obj)
elseif t == 'boolean' then
return obj and 'true' or 'false'
elseif t == 'string' then
return '/' .. obj
elseif t == 'table' then
t = obj.kind
if t == 'name' then
return '/' .. obj.value
elseif t == 'string' then
return '(' .. obj.value .. ')' -- TODO: Escaping
elseif t == 'dict' then
local helper = {}
for k, v in next, obj.value do
helper[#helper+1] = serialize_pdf(k)
helper[#helper+1] = serialize_pdf(v)
end
return '<<' .. table.concat(helper, ' ') .. '>>'
elseif t == 'array' then
local helper = {}
for i, v in ipairs(obj.value) do
helper[i] = serialize_pdf(v)
end
return '[' .. table.concat(helper, ' ') .. ']'
else
error'Unable to serialize object'
end
end
error'Unable to serialize object'
end
end
local srand, rrand, rand do
local state
function srand(s)
state = s//1
if state < 1 then
state = -(state % 0x7ffffffe) + 1
elseif state > 0x7ffffffe then
state = 0x7ffffffe
end
end
function rrand()
return state
end
function rand()
state = (16807 * state) % 0x7fffffff
-- if state <= 0 then
-- state = state + 0x7fffffff
-- end
return state
end
srand(math.random(1, 0x7ffffffe))
end
local maybe_decompress do
local compressed_pattern = '%!PS\n\z
currentfile<</Predictor 1' * l.R'05' * '/Columns ' * (l.R'09'^1/tonumber) * '>>/FlateDecode filter cvx exec\n'
* l.C(l.P(1)^1)
local stacklimit = 999000
function maybe_decompress(data)
local columns, compressed = compressed_pattern:match(data)
if not columns then return data end
data = zlib.decompress(compressed)
local bytes do
local size = #data
if size < stacklimit then
bytes = {data:byte(1, -1)}
else
bytes = {}
local off = 1
for i = 1, size, stacklimit do
table.move({data:byte(i, i+stacklimit-1)}, 1, stacklimit, i, bytes)
end
end
end
local new_data = {}
local start_row = 1
local out_row = 1
while true do
local control = bytes[start_row]
if not control then break end
if control == 0 or (control == 2 and start_row == 1) then
table.move(bytes, start_row + 1, start_row + columns, out_row, new_data)
elseif control == 1 then
local last = bytes[start_row + 1]
new_data[out_row] = last
for i = 2, columns do
last = (bytes[start_row + i] + last) & 0xFF
new_data[out_row + i - 1] = last
end
elseif control == 2 then
for i = 1, columns do
new_data[out_row + i - 1] = (bytes[start_row + i] + new_data[out_row - columns - 1 + i]) & 0xFF
end
else
error'Unimplemented'
end
start_row = start_row + columns + 1
out_row = out_row + columns
end
local result = ''
local size = #new_data
for i = 1, size, stacklimit do
result = result .. string.char(table.unpack(new_data, i, i + stacklimit > size and size or i + stacklimit - 1))
end
return result
end
end
local font_aliases = {
-- First add some help to find the TeX Gyre names under the corresponding URW font names
['NimbusRoman-Regular'] = 'kpse:texgyretermes-regular.otf',
['NimbusRoman-Italic'] = 'kpse:texgyretermes-italic.otf',
['NimbusRoman-Bold'] = 'kpse:texgyretermes-bold.otf',
['NimbusRoman-BoldItalic'] = 'kpse:texgyretermes-bolditalic.otf',
['NimbusSans-Regular'] = 'kpse:texgyreheros-regular.otf',
['NimbusSans-Italic'] = 'kpse:texgyreheros-italic.otf',
['NimbusSans-Bold'] = 'kpse:texgyreheros-bold.otf',
['NimbusSans-BoldItalic'] = 'kpse:texgyreheros-bolditalic.otf',
['NimbusSansNarrow-Regular'] = 'kpse:texgyreheroscn-regular.otf',
['NimbusSansNarrow-Oblique'] = 'kpse:texgyreheroscn-italic.otf',
['NimbusSansNarrow-Bold'] = 'kpse:texgyreheroscn-bold.otf',
['NimbusSansNarrow-BoldOblique'] = 'kpse:texgyreheroscn-bolditalic.otf',
['NimbusMonoPS-Regular'] = 'kpse:texgyrecursor-regular.otf',
['NimbusMonoPS-Italic'] = 'kpse:texgyrecursor-italic.otf',
['NimbusMonoPS-Bold'] = 'kpse:texgyrecursor-bold.otf',
['NimbusMonoPS-BoldItalic'] = 'kpse:texgyrecursor-bolditalic.otf',
['URWBookman-Light'] = 'kpse:texgyrebonum-regular.otf',
['URWBookman-LightItalic'] = 'kpse:texgyrebonum-italic.otf',
['URWBookman-Demi'] = 'kpse:texgyrebonum-bold.otf',
['URWBookman-DemiItalic'] = 'kpse:texgyrebonum-bolditalic.otf',
['URWGothic-Book'] = 'kpse:texgyreadventor-regular.otf',
['URWGothic-BookOblique'] = 'kpse:texgyreadventor-italic.otf',
['URWGothic-Demi'] = 'kpse:texgyreadventor-bold.otf',
['URWGothic-DemiOblique'] = 'kpse:texgyreadventor-bolditalic.otf',
-- These fonts have weird names in their URW variant, so we use the standard font names directly instead.
['NewCenturySchlbk-Roman'] = 'kpse:texgyreschola-regular.otf',
['NewCenturySchlbk-Italic'] = 'kpse:texgyreschola-italic.otf',
['NewCenturySchlbk-Bold'] = 'kpse:texgyreschola-bold.otf',
['NewCenturySchlbk-BoldItalic'] = 'kpse:texgyreschola-bolditalic.otf',
['Palatino-Roman'] = 'kpse:texgyrepagella-regular.otf',
['Palatino-Italic'] = 'kpse:texgyrepagella-italic.otf',
['Palatino-Bold'] = 'kpse:texgyrepagella-bold.otf',
['Palatino-BoldItalic'] = 'kpse:texgyrepagella-bolditalic.otf',
['ZapfChancery-MediumItalic'] = 'kpse:texgyrechorus-mediumitalic.otf',
-- The two symbol fonts don't have OpenType equivalents in TeX Live
-- so we use TFM based fonts instead
['StandardSymbolsPS'] = 'usyr',
['Dingbats'] = 'uzdr',
}
-- Then map the standard 35 font names to the URW names as done by GhostScript
-- (Except for New Century Schoolbook which got mapped directly before.
for psname, remapped in next, {
['Times-Roman'] = 'NimbusRoman-Regular',
['Times-Italic'] = 'NimbusRoman-Italic',
['Times-Bold'] = 'NimbusRoman-Bold',
['Times-BoldItalic'] = 'NimbusRoman-BoldItalic',
['Helvetica'] = 'NimbusSans-Regular',
['Helvetica-Oblique'] = 'NimbusSans-Italic',
['Helvetica-Bold'] = 'NimbusSans-Bold',
['Helvetica-BoldOblique'] = 'NimbusSans-BoldItalic',
['Helvetica-Narrow'] = 'NimbusSansNarrow-Regular',
['Helvetica-Narrow-Oblique'] = 'NimbusSansNarrow-Oblique',
['Helvetica-Narrow-Bold'] = 'NimbusSansNarrow-Bold',
['Helvetica-Narrow-BoldOblique'] = 'NimbusSansNarrow-BoldOblique',
['Courier'] = 'NimbusMonoPS-Regular',
['Courier-Oblique'] = 'NimbusMonoPS-Italic',
['Courier-Bold'] = 'NimbusMonoPS-Bold',
['Courier-BoldOblique'] = 'NimbusMonoPS-BoldItalic',
['Bookman-Light'] = 'URWBookman-Light',
['Bookman-LightItalic'] = 'URWBookman-LightItalic',
['Bookman-Demi'] = 'URWBookman-Demi',
['Bookman-DemiItalic'] = 'URWBookman-DemiItalic',
['AvantGarde-Book'] = 'URWGothic-Book',
['AvantGarde-BookOblique'] = 'URWGothic-BookOblique',
['AvantGarde-Demi'] = 'URWGothic-Demi',
['AvantGarde-DemiOblique'] = 'URWGothic-DemiOblique',
['Symbol'] = 'StandardSymbolsPS',
['StandardSymL'] = 'StandardSymbolsPS',
['ZapfDingbats'] = 'Dingbats',
-- Some additional names needed for PSTricks
['NimbusRomNo9L-Regu'] = 'NimbusRoman-Regular',
['NimbusRomNo9L-ReguItal'] = 'NimbusRoman-Italic',
['NimbusRomNo9L-Medi'] = 'NimbusRoman-Bold',
['NimbusRomNo9L-MediItal'] = 'NimbusRoman-BoldItalic',
['NimbusRomNo9L-Bold'] = 'NimbusRoman-Bold',
['NimbusSanL-Regu'] = 'NimbusSans-Regular',
['NimbusSanL-ReguItal'] = 'NimbusSans-Italic',
['NimbusSanL-Bold'] = 'NimbusSans-Bold',
['NimbusSanL-BoldItal'] = 'NimbusSans-BoldItalic',
['NimbusSanL-BoldCond'] = 'NimbusSansNarrow-Bold',
['NimbusSanL-BoldCondItal'] = 'NimbusSansNarrow-BoldOblique',
['NimbusSanL-ReguCond'] = 'NimbusSansNarrow-Regular',
['NimbusSanL-ReguCondItal'] = 'NimbusSansNarrow-Oblique',
['NimbusMonL-Regu'] = 'NimbusMonoPS-Regular',
['NimbusMonL-ReguObli'] = 'NimbusMonoPS-Italic',
['NimbusMonL-Bold'] = 'NimbusMonoPS-Bold',
['NimbusMonL-BoldObli'] = 'NimbusMonoPS-BoldItalic',
['URWBookmanL-DemiBoldItal'] = 'URWBookman-DemiItalic',
['URWBookmanL-DemiBold'] = 'URWBookman-Demi',
['URWBookmanL-LighItal'] = 'URWBookman-LightItalic',
['URWBookmanL-Ligh'] = 'URWBookman-Light',
['URWGothicL-BookObli'] = 'URWGothic-BookOblique',
['URWGothicL-Book'] = 'URWGothic-Book',
['URWGothicL-DemiObli'] = 'URWGothic-DemiOblique',
['URWGothicL-Demi'] = 'URWGothic-Demi',
['CenturySchL-Roma'] = 'NewCenturySchlbk-Roman',
['CenturySchL-Ital'] = 'NewCenturySchlbk-Italic',
['CenturySchL-Bold'] = 'NewCenturySchlbk-Bold',
['CenturySchL-BoldItal'] = 'NewCenturySchlbk-BoldItalic',
['URWPalladioL-Roma'] = 'Palatino-Roman',
['URWPalladioL-Ital'] = 'Palatino-Italic',
['URWPalladioL-Bold'] = 'Palatino-Bold',
['URWPalladioL-BoldItal'] = 'Palatino-BoldItalic',
['URWChanceryL-MediItal'] = 'ZapfChancery-MediumItalic',
} do
font_aliases[psname] = font_aliases[remapped] or remapped
end
local operand_stack = {}
local pushs do
local function helper(height, args, arg, ...)
if args == 0 then return end
height = height + 1
operand_stack[height] = arg
return helper(height, args - 1, ...)
end
function pushs(...)
return helper(#operand_stack, select('#', ...), ...)
end
end
local function push(value)
operand_stack[#operand_stack+1] = value
end
local function ps_error(kind, ...)
pushs(...)
return error{pserror = kind, trace = debug.traceback()}
end
local function pop(...)
local height = #operand_stack
if height == 0 then
return ps_error('stackunderflow', ...)
end
local v = operand_stack[height]
operand_stack[height] = nil
return v, v
end
local function pop_num(...)
local raw = pop(...)
local n = raw
local tn = type(n)
if tn == 'table' and n.kind == 'executable' then
n = n.value
tn = type(n)
end
if tn ~= 'number' then
ps_error('typecheck', raw, ...)
end
return n, raw
end
local pop_int = pop_num
local function pop_proc(...)
local v = pop()
if type(v) ~= 'table' or v.kind ~= 'executable' or type(v.value) ~= 'table' or v.value.kind ~= 'array' then
ps_error('typecheck', v, ...)
end
return v.value.value, v
end
local pop_bool = pop
local function pop_dict()
local orig = pop()
local dict = orig
if type(dict) ~= 'table' then
ps_error('typecheck', orig)
end
if dict.kind == 'executable' then
dict = dict.value
if type(dict) ~= 'table' then
ps_error('typecheck', orig)
end
end
if dict.kind ~= 'dict' then
ps_error('typecheck', orig)
end
return dict.value, orig, dict
end
local function pop_array()
local orig = pop()
local arr = orig
if type(arr) == 'table' and arr.kind == 'executable' then
arr = arr.value
end
if type(arr) ~= 'table' or arr.kind ~= 'array' then
ps_error('typecheck', orig)
end
return arr
end
local pop_string = pop
local function pop_key()
local key = pop()
if type(key) == 'table' then
local kind = key.kind
if kind == 'executable' then
key = key.value
if type(key) ~= 'table' then return key end
kind = key.kind
end
if kind == 'string' or kind == 'name' or kind == 'operator' then
key = key.value
end
end
return key
end
local execute_ps, execute_tok
local dictionary_stack
-- About the bbox entry:
-- - If the bounding box is not currently tracked, it is set to nil
-- - Otherwise it's a linked list linked with the .next field. Every entry is a "matrix level"
-- - if .bbox[1] is nil, the current matrix level does not have a set bounding box yet
-- - Otherside it's {min_x, min_y, max_x, max_y}
-- - If a .bbox.matrix entry is present then it describes the matrix which should be applied before the bbox gets added to the next "matrix level"
local graphics_stack = {{
matrix = {10, 0, 0, 10, 0, 0}, -- Chosen for consistency with GhostScript's pdfwrite. Must be the same as defaultmatrix
bbox = nil,
linewidth = nil,
current_path = nil,
current_point = nil,
color = {},
fillconstantalpha = 1,
strokeconstantalpha = 1,
alphaisshape = nil,
blendmode = nil,
linejoin = nil,
linecap = nil,
strokeadjust = nil,
font = nil,
dash = nil,
saved_delayed = nil, -- nil if the `gsave` of this graphic state is not delayed
flatness = 1,
miterlimit = nil,
}}
local lua_node_lookup = setmetatable({}, {__mode = 'k'})
local char_width_storage -- Non nil only at the beginning of a Type 3 glyph. Used to export the width.
local ExtGStateCount = 0
local pdfdict_gput = token.create'pdfdict_gput:nnn'
if pdfdict_gput.cmdname == 'undefined_cs' then
pdfdict_gput = nil
end
local lbrace = token.create(string.byte'{')
local rbrace = token.create(string.byte'}')
local ExtGState = setmetatable({}, {__index = pdfdict_gput and function(t, k)
ExtGStateCount = ExtGStateCount + 1
local name = 'PSExtG' .. ExtGStateCount
tex.runtoks(function()
tex.write(pdfdict_gput, lbrace, 'g__pdf_Core/Page/Resources/ExtGState', rbrace, lbrace, name, rbrace, lbrace, k, rbrace)
end)
ltx.__pdf.Page.Resources.ExtGState = true
ltx.pdf.Page_Resources_gpush(tex.count.g_shipout_readonly_int)
name = '/' .. name .. ' gs'
t[k] = name
return name
end or function()
warn_document_metadata()
return ''
end})
local write_shading do
local ShadingCount = 0
if pdfdict_gput then
function write_shading(attr, data)
local obj = pdf.obj{
type = 'stream',
immediate = false,
attr = attr,
string = data,
}
pdf.refobj(obj)
ShadingCount = ShadingCount + 1
local name = 'PSShad' .. ShadingCount
local k = obj .. ' 0 R'
tex.runtoks(function()
tex.write(pdfdict_gput, lbrace, 'g__pdf_Core/Page/Resources/Shading', rbrace, lbrace, name, rbrace, lbrace, k, rbrace)
end)
ltx.__pdf.Page.Resources.Shading = true
ltx.pdf.Page_Resources_gpush(tex.count.g_shipout_readonly_int)
name = '/' .. name
return name
end
else
function write_shading()
warn_document_metadata()
return ''
end
end
end
local function matrix_transform(x, y, xx, xy, yx, yy, dx, dy)
return x * xx + y * yx + dx, x * xy + y * yy + dy
end
local function matrix_invert(xx, xy, yx, yy, dx, dy)
local determinante = xx*yy - xy*yx
xx, xy, yx, yy = yy/determinante, -xy/determinante, -yx/determinante, xx/determinante
dx, dy = - dx * xx - dy * yx, - dx * xy - dy * yy
return xx, xy, yx, yy, dx, dy
end
local delayed = {
text = {},
matrix = {1, 0, 0, 1, 0, 0},
}
local function update_matrix(xx, xy, yx, yy, dx, dy)
local matrix = graphics_stack[#graphics_stack].matrix
matrix[1], matrix[2],
matrix[3], matrix[4],
matrix[5], matrix[6]
= xx * matrix[1] + xy * matrix[3], xx * matrix[2] + xy * matrix[4],
yx * matrix[1] + yy * matrix[3], yx * matrix[2] + yy * matrix[4],
dx * matrix[1] + dy * matrix[3] + matrix[5], dx * matrix[2] + dy * matrix[4] + matrix[6]
local delayed_matrix = delayed.matrix
delayed_matrix[1], delayed_matrix[2],
delayed_matrix[3], delayed_matrix[4],
delayed_matrix[5], delayed_matrix[6]
= xx * delayed_matrix[1] + xy * delayed_matrix[3], xx * delayed_matrix[2] + xy * delayed_matrix[4],
yx * delayed_matrix[1] + yy * delayed_matrix[3], yx * delayed_matrix[2] + yy * delayed_matrix[4],
dx * delayed_matrix[1] + dy * delayed_matrix[3] + delayed_matrix[5], dx * delayed_matrix[2] + dy * delayed_matrix[4] + delayed_matrix[6]
local current_path = graphics_stack[#graphics_stack].current_path
if not current_path then return end
local determinante = xx*yy - xy*yx
xx, xy, yx, yy, dx, dy = matrix_invert(xx, xy, yx, yy, dx, dy)
local i=1
while current_path[i] do
local entry = current_path[i]
if type(entry) == 'number' then
local after = current_path[i+1]
assert(type(after) == 'number')
current_path[i], current_path[i+1] = xx * entry + yx * after + dx, xy * entry + yy * after + dy
i = i+2
else
i = i+1
end
end
local current_point = graphics_stack[#graphics_stack].current_point
local x, y = current_point[1], current_point[2]
current_point[1], current_point[2] = xx * x + yx * y + dx, xy * x + yy * y + dy
end
local function delayed_print(str)
local delayed_text = delayed.text
delayed_text[#delayed_text + 1] = str
end
local function reset_delayed(delayed)
local delayed_matrix = delayed.matrix
local delayed_text = delayed.text
for i=1, #delayed_text do
delayed_text[i] = nil
end
delayed_matrix[1], delayed_matrix[2],
delayed_matrix[3], delayed_matrix[4],
delayed_matrix[5], delayed_matrix[6] = 1, 0, 0, 1, 0, 0
end
local function flush_delayed_table(delayed, state, force_start)
local delayed_matrix = delayed.matrix
local delayed_text = delayed.text
local cm_string = string.format('%.5f %.5f %.5f %.5f %.5f %.5f cm', delayed_matrix[1], delayed_matrix[2],
delayed_matrix[3], delayed_matrix[4],
delayed_matrix[5], delayed_matrix[6])
if cm_string == "1.00000 0.00000 0.00000 1.00000 0.00000 0.00000 cm" then
cm_string = nil
else
local bbox = state.bbox
if bbox then
state.bbox = { matrix = delayed_matrix, next = bbox }
delayed.matrix = {} -- Will be initialized in reset_delayed
end
end
-- Before flushing, make sure that the current graphics state has started.
graphics_stack_height = graphics_stack_height or #graphics_stack
local saved_delayed = state.saved_delayed
if saved_delayed and(cm_string or delayed_text[1] or force_start) then
state.saved_delayed = nil
pdfprint'q'
end
for i=1, #delayed_text do
pdfprint(delayed_text[i])
end
if cm_string then
pdfprint((cm_string:gsub('%.?0+ ', ' ')))
end
return reset_delayed(delayed)
end
local function flush_delayed(force_start)
local pre_first_delayed_group
for i = #graphics_stack, 1, -1 do
if not graphics_stack[i].saved_delayed then
pre_first_delayed_group = i
break
end
end
for i = pre_first_delayed_group, #graphics_stack-1 do
flush_delayed_table(graphics_stack[i+1].saved_delayed, graphics_stack[i]) -- No need for force_start here
end
return flush_delayed_table(delayed, graphics_stack[#graphics_stack], force_start)
end
local function register_point_bbox(bbox, x, y)
local min_x, min_y, max_x, max_y = bbox[1], bbox[2], bbox[3], bbox[4]
if min_x then
if x < min_x then
bbox[1] = x
elseif x > max_x then
bbox[3] = x
end
if y < min_y then
bbox[2] = y
elseif y > max_y then
bbox[4] = y
end
else
bbox[1], bbox[2], bbox[3], bbox[4] = x, y, x, y
end
end
-- Only call after flush_delayed
local function register_point(state, x, y)
local bbox = state.bbox
if not bbox then return end
return register_point_bbox(bbox, x, y)
end
local function merge_bbox(bbox, after)
if bbox[1] then
local matrix = bbox.matrix
if matrix then
register_point_bbox(after, matrix_transform(bbox[1], bbox[2], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6]))
register_point_bbox(after, matrix_transform(bbox[1], bbox[4], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6]))
register_point_bbox(after, matrix_transform(bbox[3], bbox[2], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6]))
register_point_bbox(after, matrix_transform(bbox[3], bbox[4], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6]))
else
register_point_bbox(after, bbox[1], bbox[2])
register_point_bbox(after, bbox[3], bbox[4])
end
end
return after
end
function drawarc(xc, yc, r, a1, a2)
a1, a2 = math.rad(a1), math.rad(a2)
local dx, dy = r*math.cos(a1), r*math.sin(a1)
local x, y = xc + dx, yc + dy
local segments = math.ceil(math.abs(a2-a1)*pi2_inv)
local da = (a2-a1)/segments
local state = graphics_stack[#graphics_stack]
local current_path = state.current_path
local i
if current_path then
i = #current_path + 1
current_path[i], current_path[i+1], current_path[i+2] = x, y, 'l'
i = i + 3
else
current_path = {x, y, 'm'}
i = 4
state.current_path = current_path
state.current_point = {}
end
local factor = 4*math.tan(da/4)/3
dx, dy = factor*dy, -factor*dx
for _=1, segments do
current_path[i], current_path[i+1] = x - dx, y - dy
a1 = a1 + da
dx, dy = r*math.cos(a1), r*math.sin(a1)
x, y = xc + dx, yc + dy
dx, dy = factor*dy, -factor*dx
current_path[i+2], current_path[i+3] = x + dx, y + dy
current_path[i+4], current_path[i+5] = x, y
current_path[i+6] = 'c'
i = i + 7
end
state.current_point[1], state.current_point[2] = x, y
end
local function try_lookup(name)
for i = #dictionary_stack, 1, -1 do
local dict = dictionary_stack[i]
local value = dict.value[name]
if value ~= nil then
return value
end
end
end
function lookup(name)
local result = try_lookup(name)
if result == nil then
return error(string.format('Unknown name %q', name))
end
return result
end
local function bind(proc)
for i=1, #proc do
local entry = proc[i]
local tentry = type(entry)
if tentry == 'table' and entry.kind == 'executable' and type(entry.value) == 'table' and entry.value.kind == 'array' then
bind(entry.value.value)
elseif tentry == 'string' then
local res = try_lookup(entry)
if type(res) == 'function' then
proc[i] = res
end
end
end
end
local subdivide, flatten do
function subdivide(t, x0, y0, x1, y1, x2, y2, x3, y3)
local mt = 1-t
local x01, y01 = mt * x0 + t * x1, mt * y0 + t * y1
local x12, y12 = mt * x1 + t * x2, mt * y1 + t * y2
local x23, y23 = mt * x2 + t * x3, mt * y2 + t * y3
local x012, y012 = mt * x01 + t * x12, mt * y01 + t * y12
local x123, y123 = mt * x12 + t * x23, mt * y12 + t * y23
local x0123, y0123 = mt * x012 + t * x123, mt * y012 + t * y123
return x01, y01, x012, y012, x0123, y0123, x123, y123, x23, y23, x3, y3
end
local function flatness(x0, y0, x1, y1, x2, y2, x3, y3)
local dx, dy = x3-x0, y3-y0
local dist = math.sqrt(dx*dx + dy*dy)
local d1 = math.abs(dx * (x0-x1) - dy * (y0-y1)) / dist
local d2 = math.abs(dx * (x0-x2) - dy * (y0-y2)) / dist
return d1 > d2 and d1 or d2
end
function flatten(out, target, x0, y0, x1, y1, x2, y2, x3, y3)
local current = flatness(x0, y0, x1, y1, x2, y2, x3, y3)
if current <= target then
local i = #out
-- out[i+1], out[i+2],
-- out[i+3], out[i+4],
-- out[i+5], out[i+6], out[i+7]
-- = x1, y1, x2, y2, x3, y3, 'c'
out[i+1], out[i+2], out[i+3]
= x3, y3, 'l'
return
end
local a, b, c, d, e, f, g, h, i, j, k, l = subdivide(.5, x0, y0, x1, y1, x2, y2, x3, y3)
flatten(out, target, x0, y0, a, b, c, d, e, f)
return flatten(out, target, e, f, g, h, i, j, k, l)
end
end
local function ps_to_string(a)
local ta = type(a)
if ta == 'table' and a.kind == 'executable' then
a = a.value
ta = type(a)
end
if ta == 'string' then
elseif ta == 'boolean' then
a = a and 'true' or 'false'
elseif ta == 'number' then
a = string.format(math.type(a) == 'float' and '%.6g' or '%i', a)
-- a = tostring(a)
elseif ta == 'function' then
texio.write_nl'Warning: cvs on operators is unsupported. Replaced by dummy.'
a = '--nostringval--'
elseif ta == 'table' then
local kind = a.kind
if kind == 'string' or kind == 'name' then
a = a.value
elseif kind == 'operator' then
texio.write_nl'Warning: cvs on operators is unsupported. Replaced by dummy.'
a = '--nostringval--'
else
a = '--nostringval--'
end
elseif ta == 'userdata' and a.read then
a = 'file'
else
assert(false)
end
return a
end
local mark = {kind = 'mark'}
local null = {kind = 'null'}
local statusdict = {kind = 'dict', value = {}}
local globaldict = {kind = 'dict', value = {}}
local userdict = {kind = 'dict', value = {
SDict = {kind = 'dict', value = {
normalscale = {kind = 'executable', value = {kind = 'array', value = {}}},
}},
TeXDict = {kind = 'dict', value = {
Resolution = function() push((pdf.getpkresolution())) end,
}},
['@beginspecial'] = {kind = 'executable', value = {kind = 'array', value = {}}},
['@setspecial'] = {kind = 'executable', value = {kind = 'array', value = {}}},
['@endspecial'] = {kind = 'executable', value = {kind = 'array', value = {}}},
}}
userdict.value.TeXDict.value.VResolution = userdict.value.TeXDict.value.Resolution
local FontDirectory = {kind = 'dict', value = {}}
local ResourceCategories = {kind = 'dict', value = {}}
local function num_to_base(num, base, ...)
if num == 0 then return string.char(...) end
local remaining = num // base
local digit = num - base * remaining
if digit < 10 then
digit = digit + 0x30
else
digit = digit + 0x37
end
return num_to_base(remaining, base, digit, ...)
end
local plugin_interface = {
push = push,
pop = pop,
pop_num = pop_num,
pop_dict = pop_dict,
pop_array = pop_array,
pop_key = pop_key,
pop_proc = pop_proc,
exec = nil, -- execute_tok, -- filled in later
}
local systemdict
local function generic_show(str, ax, ay)
local state = graphics_stack[#graphics_stack]
local current_point = state.current_point
if not current_point then return nil, 'nocurrentpoint' end
local rawpsfont = state.font
if not rawpsfont then return nil, 'invalidfont' end
local str = str.value
local psfont = rawpsfont.value
local fid = psfont.FID
local matrix = psfont.FontMatrix.value
local fonttype = psfont.FontType
if fonttype ~= 0x1CA and fonttype ~= 3 then
texio.write_nl'luapstricks: Attempt to use unsupported font type.'
return nil, 'invalidfont'
end
local x0, y0 = current_point[1], current_point[2]
update_matrix(
matrix[1], matrix[2],
matrix[3], matrix[4],
matrix[5] + x0, matrix[6] + y0)
local w = 0
if fonttype == 0x1CA then
local characters = assert(font.getfont(fid)).characters
local max_d, max_h = 0, 0
flush_delayed()
if pdfprint ~= gobble then
vf.push()
vf.fontid(fid)
end
for b in string.bytes(str) do
if pdfprint ~= gobble then
vf.char(b)
if ax then
vf.right(ax)
vf.down(-ay)
end
end
local char = characters[b]
if char then
w = w + (char.width or 0)
if char.depth and char.depth > max_d then
max_d = char.depth
end
if char.height and char.height > max_h then
max_h = char.height
end
end
end
w = w/65781.76
if pdfprint ~= gobble then
max_d = max_d/65781.76
max_h = max_h/65781.76
register_point(state, 0, -max_d)
if ax then
local count = #str
register_point(state, w + count * ax, max_h + count * ay)
else
register_point(state, w, max_h)
end
vf.pop()