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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
|
if not modules then modules = { } end modules ['grph-inc'] = {
version = 1.001,
comment = "companion to grph-inc.mkiv",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
-- figures -> managers.figures
-- lowercase types
-- mps tex tmp svg
-- partly qualified
-- dimensions
-- consult rlx
-- figures.boxnumber can go as we now can use names
-- avoid push
--[[
The ConTeXt figure inclusion mechanisms are among the oldest code
in ConTeXt and evolve dinto a complex whole. One reason is that we
deal with backend in an abstract way. What complicates matters is
that we deal with internal graphics as well: TeX code, MetaPost code,
etc. Later on figure databases were introduced, which resulted in
a plug in model for locating images. On top of that runs a conversion
mechanism (with caching) and resource logging.
Porting that to Lua is not that trivial because quite some
status information is kept between al these stages. Of course, image
reuse also has some price, and so I decided to implement the graphics
inclusion in several layers: detection, loading, inclusion, etc.
Object sharing and scaling can happen at each stage, depending on the
way the resource is dealt with.
The TeX-Lua mix is suboptimal. This has to do with the fact that we cannot
run TeX code from within Lua. Some more functionality will move to Lua.
]]--
local format, lower, find, match, gsub, gmatch = string.format, string.lower, string.find, string.match, string.gsub, string.gmatch
local texbox = tex.box
local contains = table.contains
local concat, insert, remove = table.concat, table.insert, table.remove
local todimen = string.todimen
local settings_to_array = utilities.parsers.settings_to_array
local settings_to_hash = utilities.parsers.settings_to_hash
local allocate = utilities.storage.allocate
local setmetatableindex = table.setmetatableindex
local variables = interfaces.variables
local codeinjections = backends.codeinjections
local nodeinjections = backends.nodeinjections
local trace_figures = false trackers.register("graphics.locating", function(v) trace_figures = v end)
local trace_bases = false trackers.register("graphics.bases", function(v) trace_bases = v end)
local trace_programs = false trackers.register("graphics.programs", function(v) trace_programs = v end)
local trace_conversion = false trackers.register("graphics.conversion", function(v) trace_conversion = v end)
local trace_inclusion = false trackers.register("graphics.inclusion", function(v) trace_inclusion = v end)
local report_inclusion = logs.reporter("graphics","inclusion")
local context, img = context, img
--- some extra img functions ---
local imgkeys = img.keys()
function img.totable(imgtable)
local result = { }
for k=1,#imgkeys do
local key = imgkeys[k]
result[key] = imgtable[key]
end
return result
end
function img.serialize(i,...)
return table.serialize(img.totable(i),...)
end
function img.print(i,...)
return table.print(img.totable(i),...)
end
function img.clone(i,data)
i.width = data.width or i.width
i.height = data.height or i.height
-- attr etc
return i
end
local validsizes = table.tohash(img.boxes())
local validtypes = table.tohash(img.types())
function img.checksize(size)
if size then
size = gsub(size,"box","")
return (validsizes[size] and size) or "crop"
else
return "crop"
end
end
local indexed = { }
function img.ofindex(n)
return indexed[n]
end
--- we can consider an grph-ini file
figures = figures or { }
local figures = figures
figures.loaded = allocate()
figures.used = allocate()
figures.found = allocate()
figures.suffixes = allocate()
figures.patterns = allocate()
figures.boxnumber = figures.boxnumber or 0
figures.defaultsearch = true
figures.defaultwidth = 0
figures.defaultheight = 0
figures.defaultdepth = 0
figures.nofprocessed = 0
figures.preferquality = true -- quality over location
figures.existers = allocate() local existers = figures.existers
figures.checkers = allocate() local checkers = figures.checkers
figures.includers = allocate() local includers = figures.includers
figures.converters = allocate() local converters = figures.converters
figures.identifiers = allocate() local identifiers = figures.identifiers
figures.programs = allocate() local programs = figures.programs
figures.localpaths = allocate {
".", "..", "../.."
}
figures.cachepaths = allocate {
prefix = "",
path = ".",
subpath = ".",
}
figures.paths = allocate(table.copy(figures.localpaths))
figures.order = allocate{
"pdf", "mps", "jpg", "png", "jp2", "jbig", "svg", "eps", "gif", "mov", "buffer", "tex", "cld",
}
figures.formats = allocate{
["pdf"] = { list = { "pdf" } },
["mps"] = { patterns = { "mps", "%d+" } },
["jpg"] = { list = { "jpg", "jpeg" } },
["jp2"] = { list = { "jp2" } },
["png"] = { list = { "png" } },
["jbig"] = { list = { "jbig", "jbig2", "jb2" } },
["svg"] = { list = { "svg", "svgz" } },
["eps"] = { list = { "eps", "ai" } },
["gif"] = { list = { "gif" } },
["mov"] = { list = { "mov", "flv", "mp4" } }, -- "avi" is not supported
["buffer"] = { list = { "tmp", "buffer", "buf" } },
["tex"] = { list = { "tex" } },
["cld"] = { list = { "cld" } },
}
function figures.setlookups()
local fs, fp = allocate(), allocate()
figures.suffixes, figures.patterns = fs, fp
for _, format in next, figures.order do
local data = figures.formats[format]
local list = data.list
if list then
for i=1,#list do
fs[list[i]] = format -- hash
end
else
fs[format] = format
end
local patterns = data.patterns
if patterns then
for i=1,#patterns do
fp[#fp+1] = { patterns[i], format } -- array
end
end
end
end
figures.setlookups()
local function register(tag,target,what)
local data = figures.formats[target] -- resolver etc
if not data then
data = { }
figures.formats[target] = data
end
local d = data[tag] -- list or pattern
if d and not contains(d,what) then
d[#d+1] = what -- suffix or patternspec
else
data[tag] = { what }
end
if not contains(figures.order,target) then
figures.order[#figures.order+1] = target
end
figures.setlookups()
end
function figures.registersuffix (suffix, target) register('list', target,suffix ) end
function figures.registerpattern(pattern,target) register('pattern',target,pattern) end
local last_locationset, last_pathlist = last_locationset or nil, last_pathlist or nil
function figures.setpaths(locationset,pathlist)
if last_locationset == locationset and last_pathlist == pathlist then
-- this function can be called each graphic so we provide this optimization
return
end
local iv, t, h = interfaces.variables, figures.paths, settings_to_hash(locationset)
if last_locationset ~= locationset then
-- change == reset (actually, a 'reset' would indeed reset
if h[iv["local"]] then
t = table.fastcopy(figures.localpaths or { })
else
t = { }
end
figures.defaultsearch = h[iv["default"]]
last_locationset = locationset
end
if h[iv["global"]] then
local list = settings_to_array(pathlist)
for i=1,#list do
local s = list[i]
if not contains(t,s) then
t[#t+1] = s
end
end
end
figures.paths, last_pathlist = t, pathlist
if trace_figures then
report_inclusion("locations: %s",last_locationset)
report_inclusion("path list: %s",concat(figures.paths, " "))
end
end
-- check conversions and handle it here
function figures.hash(data)
return data.status.hash or tostring(data.status.private) -- the <img object>
-- return data.status.fullname .. "+".. (data.status.page or data.request.page or 1) -- img is still not perfect
end
-- interfacing to tex
local function new() -- we could use metatables status -> used -> request but it needs testing
local request = {
name = false,
label = false,
format = false,
page = false,
width = false,
height = false,
preview = false,
["repeat"] = false,
controls = false,
display = false,
mask = false,
conversion = false,
resolution = false,
cache = false,
prefix = false,
size = false,
}
local used = {
fullname = false,
format = false,
name = false,
path = false,
suffix = false,
width = false,
height = false,
}
local status = {
status = 0,
converted = false,
cached = false,
fullname = false,
format = false,
}
-- this needs checking because we might check for nil, the test case
-- is getfiguredimensions which then should return ~= 0
-- setmetatableindex(status, used)
-- setmetatableindex(used, request)
return {
request = request,
used = used,
status = status,
}
end
-- use table.insert|remove
local lastfiguredata = nil -- will be topofstack or last so no { } (else problems with getfiguredimensions)
local callstack = { }
function figures.initialize(request)
local figuredata = new()
if request then
-- request.width/height are strings and are only used when no natural dimensions
-- can be determined; at some point the handlers might set them to numbers instead
-- local w, h = tonumber(request.width), tonumber(request.height)
request.page = math.max(tonumber(request.page) or 1,1)
request.size = img.checksize(request.size)
request.object = request.object == variables.yes
request["repeat"] = request["repeat"] == variables.yes
request.preview = request.preview == variables.yes
request.cache = request.cache ~= "" and request.cache
request.prefix = request.prefix ~= "" and request.prefix
request.format = request.format ~= "" and request.format
-- request.width = (w and w > 0) or false
-- request.height = (h and h > 0) or false
table.merge(figuredata.request,request)
end
return figuredata
end
function figures.push(request)
statistics.starttiming(figures)
local figuredata = figures.initialize(request)
insert(callstack,figuredata)
lastfiguredata = figuredata
return figuredata
end
function figures.pop()
lastfiguredata = remove(callstack) or lastfiguredata
statistics.stoptiming(figures)
end
function figures.current()
return callstack[#callstack] or lastfiguredata
end
function figures.get(category,tag,default)
local value = lastfiguredata and lastfiguredata[category]
value = value and value[tag]
if not value or value == "" or value == true then
return default or ""
else
return value
end
end
--
function figures.tprint(category,tag,default)
context(figures.get(category,tag,default))
end
local defaultformat = "pdf"
local defaultprefix = "m_k_i_v_"
-- todo: local path or cache path
local function forbiddenname(filename)
if not filename or filename == "" then
return false
end
local expandedfullname = file.collapsepath(filename,true)
local expandedinputname = file.collapsepath(file.addsuffix(environment.jobfilename,environment.jobfilesuffix),true)
if expandedfullname == expandedinputname then
report_inclusion("skipping graphic with same name as input filename (%s), enforce suffix",expandedinputname)
return true
end
local expandedoutputname = file.collapsepath(codeinjections.getoutputfilename(),true)
if expandedfullname == expandedoutputname then
report_inclusion("skipping graphic with same name as output filename (%s), enforce suffix",expandedoutputname)
return true
end
end
local function register(askedname,specification)
if specification then
if forbiddenname(specification.fullname) then
specification = { }
else
local format = specification.format
if format then
local conversion = specification.conversion
local resolution = specification.resolution
if conversion == "" then
conversion = nil
end
if resolution == "" then
resolution = nil
end
local newformat = conversion
if not newformat or newformat == "" then
newformat = defaultformat
end
if trace_conversion then
report_inclusion("checking conversion of '%s': old format '%s', new format '%s', conversion '%s', resolution '%s'",
askedname,format,newformat,conversion or "default",resolution or "default")
end
local converter = (newformat ~= format) and converters[format]
if converter then
if converter[newformat] then
converter = converter[newformat]
else
newformat = defaultformat
if converter[newformat] then
converter = converter[newformat]
else
converter = nil
newformat = defaultformat
end
end
elseif trace_conversion then
report_inclusion("no converter for '%s' -> '%s'",format,newformat)
end
if converter then
-- local oldname = specification.fullname
local oldname = specification.foundname
local newpath = file.dirname(oldname)
local oldbase = file.basename(oldname)
local newbase = file.removesuffix(oldbase)
local fc = specification.cache or figures.cachepaths.path
if fc and fc ~= "" and fc ~= "." then
newpath = fc
else
newbase = defaultprefix .. newbase
end
if not file.is_writable(newpath) then
if trace_conversion then
report_inclusion("[ath '%s'is not writable, forcing conversion path '.' ",newpath)
end
newpath = "."
end
local subpath = specification.subpath or figures.cachepaths.subpath
if subpath and subpath ~= "" and subpath ~= "." then
newpath = newpath .. "/" .. subpath
end
local prefix = specification.prefix or figures.cachepaths.prefix
if prefix and prefix ~= "" then
newbase = prefix .. newbase
end
if resolution and resolution ~= "" then -- the order might change
newbase = newbase .. "_" .. resolution
end
local newbase = file.addsuffix(newbase,newformat)
local newname = file.join(newpath,newbase)
dir.makedirs(newpath)
oldname = file.collapsepath(oldname)
newname = file.collapsepath(newname)
local oldtime = lfs.attributes(oldname,'modification') or 0
local newtime = lfs.attributes(newname,'modification') or 0
if newtime == 0 or oldtime > newtime then
if trace_conversion then
report_inclusion("converting '%s' from '%s' to '%s'",askedname,format,newformat)
end
converter(oldname,newname,resolution or "")
else
if trace_conversion then
report_inclusion("no need to convert '%s' from '%s' to '%s'",askedname,format,newformat)
end
end
if io.exists(newname) then
specification.foundname = oldname
specification.fullname = newname
specification.prefix = prefix
specification.subpath = subpath
specification.converted = true
format = newformat
elseif io.exists(oldname) then
specification.fullname = newname
specification.converted = false
end
end
end
local found = figures.suffixes[format] -- validtypes[format]
if not found then
specification.found = false
if trace_figures then
report_inclusion("format not supported: %s",format)
end
else
specification.found = true
if trace_figures then
if validtypes[format] then
report_inclusion("format natively supported by backend: %s",format)
else
report_inclusion("format supported by output file format: %s",format)
end
end
end
end
else
specification = { }
end
specification.foundname = specification.foundname or specification.fullname
figures.found[askedname .. "->" .. (specification.conversion or "default") .. "->" .. (specification.resolution or "default")] = specification
return specification
end
local resolve_too = true -- urls
local function locate(request) -- name, format, cache
local askedname = resolvers.cleanpath(request.name)
local foundname = figures.found[askedname .. "->" .. (request.conversion or "default") .. "->" .. (request.resolution or "default")]
if foundname then
return foundname
end
-- protocol check
local hashed = url.hashed(askedname)
if hashed then
if hashed.scheme == "file" then
local path = hashed.path
if path and path ~= "" then
askedname = path
end
else
local foundname = resolvers.findbinfile(askedname)
if foundname then
askedname = foundname
end
end
end
-- we could use the hashed data instead
local askedpath= file.is_rootbased_path(askedname)
local askedbase = file.basename(askedname)
local askedformat = (request.format ~= "" and request.format ~= "unknown" and request.format) or file.extname(askedname) or ""
local askedcache = request.cache
local askedconversion = request.conversion
local askedresolution = request.resolution
if askedformat ~= "" then
askedformat = lower(askedformat)
if trace_figures then
report_inclusion("strategy: forced format %s",askedformat)
end
local format = figures.suffixes[askedformat]
if not format then
local figurepatterns = figures.patterns
for i=1,#figurepatterns do
local pattern = figurepatterns[i]
if find(askedformat,pattern[1]) then
format = pattern[2]
break
end
end
end
if format then
local foundname, quitscanning = figures.exists(askedname,format,resolve_too) -- not askedformat
if foundname then
return register(askedname, {
askedname = askedname,
fullname = askedname,
format = format,
cache = askedcache,
foundname = foundname,
conversion = askedconversion,
resolution = askedresolution,
})
elseif quitscanning then
return register(askedname)
end
elseif trace_figures then
report_inclusion("strategy: unknown format %s",askedformat)
end
if askedpath then
-- path and type given, todo: strip pieces of path
if figures.exists(askedname,askedformat,resolve_too) then
return register(askedname, {
askedname = askedname,
fullname = askedname,
format = askedformat,
cache = askedcache,
conversion = askedconversion,
resolution = askedresolution,
})
end
else
-- type given
local figurepaths = figures.paths
for i=1,#figurepaths do
local path = figurepaths[i]
local check = path .. "/" .. askedname
-- we pass 'true' as it can be an url as well, as the type
-- is given we don't waste much time
if figures.exists(check,askedformat,resolve_too) then
return register(check, {
askedname = askedname,
fullname = check,
format = askedformat,
cache = askedcache,
conversion = askedconversion,
resolution = askedresolution,
})
end
end
if figures.defaultsearch then
local check = resolvers.findfile(askedname)
if check and check ~= "" then
return register(askedname, {
askedname = askedname,
fullname = check,
format = askedformat,
cache = askedcache,
conversion = askedconversion,
resolution = askedresolution,
})
end
end
end
elseif askedpath then
if trace_figures then
report_inclusion("strategy: rootbased path")
end
local figureorder = figures.order
for i=1,#figureorder do
local format = figureorder[i]
local list = figures.formats[format].list or { format }
for j=1,#list do
local suffix = list[j]
local check = file.addsuffix(askedname,suffix)
if figures.exists(check,format,resolve_too) then
return register(askedname, {
askedname = askedname,
fullname = check,
format = format,
cache = askedcache,
conversion = askedconversion,
resolution = askedresolution,
})
end
end
end
else
if figures.preferquality then
if trace_figures then
report_inclusion("strategy: unknown format, prefer quality")
end
local figurepaths = figures.paths
local figureorder = figures.order
for j=1,#figureorder do
local format = figureorder[j]
local list = figures.formats[format].list or { format }
for k=1,#list do
local suffix = list[k]
-- local name = file.replacesuffix(askedbase,suffix)
local name = file.replacesuffix(askedname,suffix)
for i=1,#figurepaths do
local path = figurepaths[i]
local check = path .. "/" .. name
local isfile = url.hashed(check).scheme == "file"
if not isfile then
if trace_figures then
report_inclusion("warning: skipping path %s",path)
end
elseif figures.exists(check,format,true) then
return register(askedname, {
askedname = askedname,
fullname = check,
format = format,
cache = askedcache,
conversion = askedconversion,
resolution = askedresolution,
})
end
end
end
end
else -- 'location'
if trace_figures then
report_inclusion("strategy: unknown format, prefer path")
end
local figurepaths = figures.paths
local figureorder = figures.order
for i=1,#figurepaths do
local path = figurepaths[i]
for j=1,#figureorder do
local format = figureorder[j]
local list = figures.formats[format].list or { format }
for k=1,#list do
local suffix = list[k]
local check = path .. "/" .. file.replacesuffix(askedbase,suffix)
if figures.exists(check,format,resolve_too) then
return register(askedname, {
askedname = askedname,
fullname = check,
format = format,
cache = askedcache,
conversion = askedconversion,
resolution = askedresolution,
})
end
end
end
end
end
if figures.defaultsearch then
if trace_figures then
report_inclusion("strategy: default tex path")
end
local figureorder = figures.order
for j=1,#figureorder do
local format = figureorder[j]
local list = figures.formats[format].list or { format }
for k=1,#list do
local suffix = list[k]
local check = resolvers.findfile(file.replacesuffix(askedname,suffix))
if check and check ~= "" then
return register(askedname, {
askedname = askedname,
fullname = check,
format = format,
cache = askedcache,
conversion = askedconversion,
resolution = askedresolution,
})
end
end
end
end
end
return register(askedname)
end
-- -- -- plugins -- -- --
function identifiers.default(data)
local dr, du, ds = data.request, data.used, data.status
local l = locate(dr)
local foundname = l.foundname
local fullname = l.fullname or foundname
if fullname then
du.format = l.format or false
du.fullname = fullname -- can be cached
ds.fullname = foundname -- original
ds.format = l.format
ds.status = (l.found and 10) or 0
end
return data
end
function figures.identify(data)
data = data or figures.current()
local list = identifiers.list -- defined at the end
for i=1,#list do
local identifier = list[i]
data = identifier(data)
if data.status.status > 0 then
break
end
end
return data
end
function figures.exists(askedname,format,resolve)
return (existers[format] or existers.generic)(askedname,resolve)
end
function figures.check(data)
data = data or figures.current()
return (checkers[data.status.format] or checkers.generic)(data)
end
function figures.include(data)
data = data or figures.current()
return (includers[data.status.format] or includers.generic)(data)
end
function figures.scale(data) -- will become lua code
context.doscalefigure()
return data
end
function figures.done(data)
figures.nofprocessed = figures.nofprocessed + 1
data = data or figures.current()
--~ print(table.serialize(figures.current()))
local dr, du, ds, nr = data.request, data.used, data.status, figures.boxnumber
local box = texbox[nr]
ds.width = box.width
ds.height = box.height
ds.xscale = ds.width /(du.width or 1)
ds.yscale = ds.height/(du.height or 1)
ds.page = ds.page or du.page or dr.page -- sort of redundant but can be limited
--~ print(table.serialize(figures.current()))
return data
end
function figures.dummy(data)
data = data or figures.current()
local dr, du, nr = data.request, data.used, figures.boxnumber
local box = node.hpack(node.new("hlist")) -- we need to set the dir (luatex 0.60 buglet)
du.width = du.width or figures.defaultwidth
du.height = du.height or figures.defaultheight
du.depth = du.depth or figures.defaultdepth
-- box.dir = "TLT"
box.width = du.width
box.height = du.height
box.depth = du.depth
texbox[nr] = box -- hm, should be global (to be checked for consistency)
end
-- -- -- generic -- -- --
function existers.generic(askedname,resolve)
-- not findbinfile
local result
if lfs.isfile(askedname) then
result = askedname
elseif resolve then
result = resolvers.findbinfile(askedname) or ""
if result == "" then result = false end
end
if trace_figures then
if result then
report_inclusion("found: %s -> %s",askedname,result)
else
report_inclusion("not found: %s",askedname)
end
end
return result
end
function checkers.generic(data)
local dr, du, ds = data.request, data.used, data.status
local name, page, size, color = du.fullname or "unknown generic", du.page or dr.page, dr.size or "crop", dr.color or "natural"
local mask = dr.mask or "none"
local conversion = dr.conversion
local resolution = dr.resolution
if not conversion or conversion == "" then
conversion = "unknown"
end
if not resolution or resolution == "" then
resolution = "unknown"
end
local hash = name .. "->" .. page .. "->" .. size .. "->" .. color .. "->" .. conversion .. "->" .. resolution
.. "->" .. mask
local figure = figures.loaded[hash]
if figure == nil then
figure = img.new {
filename = name,
page = page,
pagebox = dr.size,
}
codeinjections.setfigurecolorspace(data,figure)
codeinjections.setfiguremask(data,figure)
figure = (figure and img.scan(figure)) or false
local f, d = codeinjections.setfigurealternative(data,figure)
figure, data = f or figure, d or data
figures.loaded[hash] = figure
if trace_conversion then
report_inclusion("new graphic, hash: %s",hash)
end
else
if trace_conversion then
report_inclusion("existing graphic, hash: %s",hash)
end
end
if figure then
du.width = figure.width
du.height = figure.height
du.pages = figure.pages
du.depth = figure.depth or 0
du.colordepth = figure.colordepth or 0
du.xresolution = figure.xres or 0
du.yresolution = figure.yres or 0
du.xsize = figure.xsize or 0
du.ysize = figure.ysize or 0
ds.private = figure
ds.hash = hash
end
return data
end
function includers.generic(data)
local dr, du, ds = data.request, data.used, data.status
-- here we set the 'natural dimensions'
dr.width = du.width
dr.height = du.height
local hash = figures.hash(data)
local figure = figures.used[hash]
if figure == nil then
figure = ds.private
if figure then
figure = img.copy(figure)
figure = (figure and img.clone(figure,data.request)) or false
end
figures.used[hash] = figure
end
if figure then
local nr = figures.boxnumber
-- it looks like we have a leak in attributes here .. todo
local box = node.hpack(img.node(figure)) -- img.node(figure) not longer valid
indexed[figure.index] = figure
box.width, box.height, box.depth = figure.width, figure.height, 0 -- new, hm, tricky, we need to do that in tex (yet)
texbox[nr] = box
ds.objectnumber = figure.objnum
context.relocateexternalfigure()
end
return data
end
-- -- -- nongeneric -- -- --
function checkers.nongeneric(data,command) -- todo: macros and context.*
local dr, du, ds = data.request, data.used, data.status
local name = du.fullname or "unknown nongeneric"
local hash = name
if dr.object then
-- hm, bugged ... waiting for an xform interface
if not job.objects.get("FIG::"..hash) then
if type(command) == "function" then
command()
end
context.dosetfigureobject(hash)
end
context.doboxfigureobject(hash)
elseif type(command) == "function" then
command()
end
return data
end
function includers.nongeneric(data)
return data
end
-- -- -- mov -- -- --
function checkers.mov(data)
local dr, du, ds = data.request, data.used, data.status
local width = todimen(dr.width or figures.defaultwidth)
local height = todimen(dr.height or figures.defaultheight)
local foundname = du.fullname
dr.width, dr.height = width, height
du.width, du.height, du.foundname = width, height, foundname
if trace_inclusion then
report_inclusion("including movie '%s': width %s, height %s",foundname,width,height)
end
-- we need to push the node.write in between ... we could make a shared helper for this
context.startfoundexternalfigure(width .. "sp",height .. "sp")
context(function()
nodeinjections.insertmovie {
width = width,
height = height,
factor = number.dimenfactors.bp,
["repeat"] = dr["repeat"],
controls = dr.controls,
preview = dr.preview,
label = dr.label,
foundname = foundname,
}
end)
context.stopfoundexternalfigure()
return data
end
includers.mov = includers.nongeneric
-- -- -- mps -- -- --
local function internal(askedname)
local spec, mprun, mpnum = match(lower(askedname),"mprun(:?)(.-)%.(%d+)")
if spec == ":" then
return mprun, mpnum
else
return "", mpnum
end
end
function existers.mps(askedname)
local mprun, mpnum = internal(askedname)
if mpnum then
return askedname
else
return existers.generic(askedname)
end
end
function checkers.mps(data)
local mprun, mpnum = internal(data.used.fullname)
if mpnum then
return checkers.nongeneric(data,function() context.docheckfiguremprun(mprun,mpnum) end)
else
return checkers.nongeneric(data,function() context.docheckfiguremps(data.used.fullname) end)
end
end
includers.mps = includers.nongeneric
-- -- -- tex -- -- --
function existers.tex(askedname)
askedname = resolvers.findfile(askedname)
return (askedname ~= "" and askedname) or false
end
function checkers.tex(data)
return checkers.nongeneric(data,function() context.docheckfiguretex(data.used.fullname) end)
end
includers.tex = includers.nongeneric
-- -- -- buffer -- -- --
function existers.buffer(askedname)
local name = file.nameonly(askedname)
local okay = buffers.exists(name)
return okay and name, true -- always quit scanning
end
function checkers.buffer(data)
return checkers.nongeneric(data,function() context.docheckfigurebuffer(file.nameonly(data.used.fullname)) end)
end
includers.buffers = includers.nongeneric
-- -- -- cld -- -- --
existers.cld = existers.tex
function checkers.cld(data)
return checkers.nongeneric(data,function() context.docheckfigurecld(data.used.fullname) end)
end
includers.cld = includers.nongeneric
-- -- -- converters -- -- --
local function makeoptions(options)
local to = type(options)
return (to == "table" and concat(options," ")) or (to == "string" and options) or ""
end
local function runprogram(...)
local command = format(...)
if trace_conversion or trace_programs then
report_inclusion("running %s",command)
end
os.spawn(command)
end
-- -- -- eps -- -- --
local epsconverter = { }
converters.eps = epsconverter
programs.gs = {
resolutions = {
[variables.low] = "screen",
[variables.medium] = "ebook",
[variables.high] = "prepress",
},
options = {
"-dAutoRotatePages=/None",
"-dPDFSETTINGS=/%s",
"-dEPSCrop",
},
command = (os.type == "windows" and "gswin32c") or "gs"
}
function epsconverter.pdf(oldname,newname,resolution) -- the resolution interface might change
local gs = programs.gs
runprogram (
'%s -q -sDEVICE=pdfwrite -dNOPAUSE -dNOCACHE -dBATCH %s -sOutputFile="%s" "%s" -c quit',
gs.command,
format(makeoptions(gs.options),gs.resolutions[resolution or ""] or "prepress"),
newname,
oldname
)
end
epsconverter.default = epsconverter.pdf
-- -- -- svg -- -- --
local svgconverter = { }
converters.svg = svgconverter
converters.svgz = svgconverter
-- inkscape on windows only works with complete paths
programs.inkscape = {
options = {
"--export-dpi=600"
},
command = "inkscape"
}
function svgconverter.pdf(oldname,newname)
local inkscape = programs.inkscape
local oldname = dir.expandname(oldname)
local newname = dir.expandname(newname)
runprogram (
'%s "%s" %s -A "%s"',
inkscape.command, oldname, makeoptions(inkscape.options), newname
)
end
function svgconverter.png(oldname,newname)
local inkscape = programs.inkscape
runprogram (
'%s "%s" --export-png="%s" %s',
inkscape.command, oldname, newname, makeoptions(inkscape.options)
)
end
svgconverter.default = svgconverter.pdf
-- -- -- gif -- -- --
local gifconverter = { }
converters.gif = gifconverter
programs.convert = {
command = "convert" -- imagemagick
-- command = "gm convert" -- graphicmagick
}
function gifconverter.pdf(oldname,newname)
local convert = programs.convert
runprogram (
"%s %s %s %s",
convert.command, makeoptions(convert.options), oldname, newname
)
end
gifconverter.default = gifconverter.pdf
-- todo: lowres
-- -- -- bases -- -- --
figures.bases = { }
figures.bases.list = { } -- index => { basename, fullname, xmlroot }
figures.bases.used = { } -- [basename] => { basename, fullname, xmlroot } -- pointer to list
figures.bases.found = { }
figures.bases.enabled = false
local bases = figures.bases
function bases.use(basename)
if basename == "reset" then
bases.list, bases.used, bases.found, bases.enabled = { }, { }, { }, false
else
basename = file.addsuffix(basename,"xml")
if not bases.used[basename] then
local t = { basename, nil, nil }
bases.used[basename] = t
bases.list[#bases.list+1] = t
if not bases.enabled then
bases.enabled = true
xml.registerns("rlx","http://www.pragma-ade.com/schemas/rlx") -- we should be able to do this per xml file
end
if trace_bases then
report_inclusion("registering base '%s'",basename)
end
end
end
end
function bases.find(basename,askedlabel)
if trace_bases then
report_inclusion("checking for '%s' in base '%s'",askedlabel,basename)
end
basename = file.addsuffix(basename,"xml")
local t = bases.found[askedlabel]
if t == nil then
local base = bases.used[basename]
local page = 0
if base[2] == nil then
-- no yet located
local figurepaths = figures.paths
for i=1,#figurepaths do
local path = figurepaths[i]
local xmlfile = path .. "/" .. basename
if io.exists(xmlfile) then
base[2] = xmlfile
base[3] = xml.load(xmlfile)
if trace_bases then
report_inclusion("base '%s' loaded",xmlfile)
end
break
end
end
end
t = false
if base[2] and base[3] then -- rlx:library
for e in xml.collected(base[3],"/(*:library|figurelibrary)/*:figure/*:label") do
page = page + 1
if xml.text(e) == askedlabel then
t = {
base = file.replacesuffix(base[2],"pdf"),
format = "pdf",
name = xml.text(e,"../*:file"), -- to be checked
page = page,
}
bases.found[askedlabel] = t
if trace_bases then
report_inclusion("figure '%s' found in base '%s'",askedlabel,base[2])
end
return t
end
end
if trace_bases and not t then
report_inclusion("figure '%s' not found in base '%s'",askedlabel,base[2])
end
end
end
return t
end
-- we can access sequential or by name
function bases.locate(askedlabel)
local list = bases.list
for i=1,#list do
local entry = list[i]
local t = bases.find(entry[1],askedlabel)
if t then
return t
end
end
return false
end
function identifiers.base(data)
if bases.enabled then
local dr, du, ds = data.request, data.used, data.status
local fbl = bases.locate(dr.name or dr.label)
if fbl then
du.page = fbl.page
du.format = fbl.format
du.fullname = fbl.base
ds.fullname = fbl.name
ds.format = fbl.format
ds.page = fbl.page
ds.status = 10
end
end
return data
end
identifiers.list = {
identifiers.base,
identifiers.default
}
-- tracing
statistics.register("graphics processing time", function()
local nofprocessed = figures.nofprocessed
if nofprocessed > 0 then
return format("%s seconds including tex, %s processed images", statistics.elapsedtime(figures),nofprocessed)
else
return nil
end
end)
-- helper
function figures.applyratio(width,height,w,h) -- width and height are strings and w and h are numbers
if not width or width == "" then
if not height or height == "" then
return figures.defaultwidth, figures.defaultheight
else
height = string.todimen(height)
if w and h then
return height * w/h, height
else
return figures.defaultwidth, height
end
end
else
width = string.todimen(width)
if not height or height == "" then
if w and h then
return width, width * h/w
else
return width, figures.defaultheight
end
else
return width, string.todimen(height)
end
end
end
|