| 1 |
|
| 2 |
local alloc = require ('minim-alloc') |
| 3 |
local cb = require('minim-callbacks') |
| 4 |
local pdfres = require('minim-pdfresources') |
| 5 |
alloc.remember ('minim-mp') |
| 6 |
|
| 7 |
local M = { } -- module contents |
| 8 |
local E = { } -- runscript environment |
| 9 |
local A = { } -- postprocessing functions |
| 10 |
|
| 11 |
--1 AUXILIARY FUNCTIONS |
| 12 |
|
| 13 |
local GLUE_NODE = node.id 'glue' |
| 14 |
local GLYPH_NODE = node.id 'glyph' |
| 15 |
local KERN_NODE = node.id 'kern' |
| 16 |
local WHATSIT_NODE = node.id 'whatsit' |
| 17 |
|
| 18 |
local function copy_table(from, to) |
| 19 |
for k,v in pairs(from) do to[k] = v end |
| 20 |
return to |
| 21 |
end |
| 22 |
|
| 23 |
-- 2 state metatable |
| 24 |
|
| 25 |
-- q Q store/restore graphics state |
| 26 |
|
| 27 |
-- In what follows, ‘append’ is a structure that contains a (tex) node list |
| 28 |
-- that will become the picture that is being constructed and an internal |
| 29 |
-- graphics state. |
| 30 |
-- |
| 31 |
-- We can call append:somefunction(...) to append a node or append:somevariable |
| 32 |
-- to query the graphics state. These go via its metatable: |
| 33 |
|
| 34 |
local append_meta = |
| 35 |
{ |
| 36 |
-- Either return an appending function or an entry in the graphics state. |
| 37 |
__index = function(table, key) |
| 38 |
return A[key] or table.state[#table.state][key] |
| 39 |
end, |
| 40 |
__newindex = function(table, key, value) |
| 41 |
table.state[#table.state][key] = value |
| 42 |
end |
| 43 |
} |
| 44 |
|
| 45 |
local function init_append() |
| 46 |
return setmetatable({ |
| 47 |
head = false, tail = false, -- node list |
| 48 |
baseline = false, -- internal state |
| 49 |
node_count = 0, -- node count |
| 50 |
state = { }, -- graphics state variables |
| 51 |
user = { }, -- user data for extensions |
| 52 |
object_info = { }, -- data for current object |
| 53 |
}, append_meta) |
| 54 |
end |
| 55 |
|
| 56 |
function A.node(append, nd) |
| 57 |
append.node_count = append.node_count + 1 |
| 58 |
append.head, append.tail = node.insert_after(append.head or nil, append.tail or nil, nd) |
| 59 |
end |
| 60 |
|
| 61 |
function A.save(append) |
| 62 |
local st = append.state[#append.state] or { } |
| 63 |
append.state[#append.state+1] = |
| 64 |
{ |
| 65 |
linewidth = st.linewidth, |
| 66 |
miterlimit = st.miterlimit, |
| 67 |
linejoin = st.linejoin, |
| 68 |
linecap = st.linecap, |
| 69 |
dashed = st.dashed, |
| 70 |
stroke = st.stroke, |
| 71 |
fill = st.fill |
| 72 |
} |
| 73 |
append:node(node.new('whatsit', 'pdf_save')) -- q |
| 74 |
end |
| 75 |
|
| 76 |
function A.restore(append) |
| 77 |
append.state[#append.state] = nil |
| 78 |
append:node(node.new('whatsit', 'pdf_restore')) -- Q |
| 79 |
end |
| 80 |
|
| 81 |
-- The following callback is executed just before the final step of surrounding |
| 82 |
-- the image in properly-dimensioned boxes. It receives the processed image |
| 83 |
-- object as argument. That object may have the following fields (which can be |
| 84 |
-- changed): |
| 85 |
-- head the head of the node list |
| 86 |
-- name the image name |
| 87 |
-- user the image user table |
| 88 |
-- wd, ht, dp tex dimensions |
| 89 |
-- x0, y0 position of (0,0) w.r.t. tex dimension |
| 90 |
-- bbox original metapost bounding box |
| 91 |
-- discard whether not to save this image |
| 92 |
cb.new_callback('finish_mpfigure', 'simple') |
| 93 |
|
| 94 |
--2 debugging |
| 95 |
|
| 96 |
local debugging = false |
| 97 |
|
| 98 |
function M.enable_debugging() |
| 99 |
debugging = true |
| 100 |
pdf.setcompresslevel(0) |
| 101 |
pdf.setobjcompresslevel(0) |
| 102 |
end |
| 103 |
E.enable_debugging = M.enable_debugging |
| 104 |
|
| 105 |
alloc.luadef('debugmetapost', M.enable_debugging) |
| 106 |
|
| 107 |
local function debug(...) |
| 108 |
if debugging then |
| 109 |
alloc.log(...) |
| 110 |
end |
| 111 |
end |
| 112 |
|
| 113 |
local function print_prop(append, obj, prop) |
| 114 |
if obj[prop] then |
| 115 |
local val = string.gsub(tostring(obj[prop]), '\r', '<CR>') |
| 116 |
append:literal('%% %s: %s', prop, val) |
| 117 |
end |
| 118 |
end |
| 119 |
|
| 120 |
local function print_multi(append, obj, prop) |
| 121 |
if obj[prop] then |
| 122 |
local x = '' |
| 123 |
for i = 1,#obj[prop] do |
| 124 |
x = x .. tostring(obj[prop][i])..' ' |
| 125 |
end |
| 126 |
append:literal('%% %s: %s', prop, x) |
| 127 |
end |
| 128 |
end |
| 129 |
|
| 130 |
local function print_knots(append, obj, ptype) |
| 131 |
if obj[ptype] then |
| 132 |
append:literal('%% %s: see below', ptype) |
| 133 |
for i = 1, #obj[ptype] do |
| 134 |
local a,b = obj[ptype][i].left_type or 'joined', obj[ptype][i].right_type or 'joined' |
| 135 |
append:literal('%% -+- knot: %s-%s', a, b) |
| 136 |
append:literal('%% | x_coord: %s', tostring(obj[ptype][i].x_coord)) |
| 137 |
append:literal('%% | y_coord: %s', tostring(obj[ptype][i].y_coord)) |
| 138 |
append:literal('%% | right_x: %s', tostring(obj[ptype][i].right_x)) |
| 139 |
append:literal('%% | right_y: %s', tostring(obj[ptype][i].right_y)) |
| 140 |
append:literal('%% | left_x: %s', tostring(obj[ptype][i].left_x)) |
| 141 |
append:literal('%% | left_y: %s', tostring(obj[ptype][i].left_y)) |
| 142 |
end |
| 143 |
end |
| 144 |
end |
| 145 |
|
| 146 |
function A.printobj(append, obj) |
| 147 |
local nc = append.node_count |
| 148 |
append:literal('%% Object Type: %s', obj.type) |
| 149 |
print_prop(append, obj, 'text') |
| 150 |
print_prop(append, obj, 'font') |
| 151 |
print_prop(append, obj, 'dsize') |
| 152 |
print_prop(append, obj, 'width') |
| 153 |
print_prop(append, obj, 'height') |
| 154 |
print_prop(append, obj, 'depth') |
| 155 |
print_multi(append, obj, 'transform') |
| 156 |
print_multi(append, obj, 'color') |
| 157 |
print_knots(append, obj, 'path') |
| 158 |
print_knots(append, obj, 'htap') |
| 159 |
if obj.pen then |
| 160 |
local x = obj.pen.type or 'not elliptical' |
| 161 |
append:literal('%% pen is %s', x) |
| 162 |
x = mplib.pen_info(obj) |
| 163 |
append:literal('%% width: %s', tostring(x.width)) |
| 164 |
append:literal('%% sx: %s', tostring(x.sx)) |
| 165 |
append:literal('%% sy: %s', tostring(x.sy)) |
| 166 |
append:literal('%% rx: %s', tostring(x.rx)) |
| 167 |
append:literal('%% ry: %s', tostring(x.ry)) |
| 168 |
append:literal('%% tx: %s', tostring(x.tx)) |
| 169 |
append:literal('%% ty: %s', tostring(x.ty)) |
| 170 |
print_knots(append, obj, 'pen path') |
| 171 |
end |
| 172 |
if obj.dash then |
| 173 |
local d = '' |
| 174 |
for i = 1,#obj.dash.dashes do |
| 175 |
d = d ..tonumber(obj.dash.dashes[i]).. ' ' |
| 176 |
end |
| 177 |
append:literal('%% dashes: %s', d) |
| 178 |
append:literal('%%dash offset: %s', tostring(obj.dash.offset)) |
| 179 |
end |
| 180 |
print_prop(append, obj, 'prescript') |
| 181 |
print_prop(append, obj, 'postscript') |
| 182 |
print_prop(append, obj, 'miterlimit') |
| 183 |
print_prop(append, obj, 'linejoin') |
| 184 |
print_prop(append, obj, 'linecap') |
| 185 |
append.node_count = nc |
| 186 |
end |
| 187 |
|
| 188 |
--2 pdf literal helpers |
| 189 |
|
| 190 |
local function format_numbers(...) |
| 191 |
return (string.format(...) |
| 192 |
:gsub('[.]0+ ', ' ') |
| 193 |
:gsub('([.][1-9]+)0+ ', '%1 ') |
| 194 |
:gsub(' +$', '')) |
| 195 |
end |
| 196 |
|
| 197 |
-- Only to be used for coordinates: ‘cm’ parameters should not be rounded. |
| 198 |
local function pdfnum(operator, ...) |
| 199 |
local fmt = string.format('%%.%sf %s', pdf.getdecimaldigits(), operator) |
| 200 |
return format_numbers(fmt, ...) |
| 201 |
end |
| 202 |
|
| 203 |
local function make_pdf_dashpattern(dl) |
| 204 |
return string.format('[%s] %s', |
| 205 |
table.concat(dl.dashes or {},' '), |
| 206 |
pdfnum('d', dl.offset)) |
| 207 |
end |
| 208 |
|
| 209 |
local function point_fmt(operator, ...) |
| 210 |
local dd = pdf.getdecimaldigits() |
| 211 |
local fmt = string.format('%%.%sf %%.%sf %s', dd, dd, operator) |
| 212 |
return format_numbers(fmt, ...) |
| 213 |
end |
| 214 |
|
| 215 |
local function bbox_fmt(...) |
| 216 |
local dd = pdf.getdecimaldigits() |
| 217 |
local fmt = string.format('/BBox [ %%.%sf %%.%sf %%.%sf %%.%sf ]', dd, dd, dd, dd) |
| 218 |
return format_numbers(fmt, ...) |
| 219 |
end |
| 220 |
|
| 221 |
local function curve_fmt(...) |
| 222 |
local dd = pdf.getdecimaldigits() |
| 223 |
local fmt = string.format('%%.%sf %%.%sf %%.%sf %%.%sf %%.%sf %%.%sf c', dd, dd, dd, dd, dd, dd) |
| 224 |
return format_numbers(fmt, ...) |
| 225 |
end |
| 226 |
|
| 227 |
function A.literal(append, fmt, ...) |
| 228 |
local lit = node.new('whatsit', 'pdf_literal') |
| 229 |
lit.data = fmt:format(...) |
| 230 |
append:node(lit) |
| 231 |
end |
| 232 |
|
| 233 |
--2 parsing helpers |
| 234 |
|
| 235 |
local function parse_lua_table(name, str) |
| 236 |
local f, msg = load('return '..str, name, 't') |
| 237 |
if msg then return alloc.err(msg) end |
| 238 |
local t = f() |
| 239 |
if not t or type(t) ~= 'table' then |
| 240 |
return alloc.err('%s attributes must be given as lua table', name) |
| 241 |
end |
| 242 |
-- format all numbers with pdfnum |
| 243 |
for k, v in pairs(t) do |
| 244 |
if type(v) == 'number' then |
| 245 |
t[k] = pdfnum('', v) |
| 246 |
end |
| 247 |
end |
| 248 |
return t |
| 249 |
end |
| 250 |
|
| 251 |
--2 boxing helpers |
| 252 |
|
| 253 |
local function make_surrounding_box(nd_id, head) |
| 254 |
local nd = node.new(nd_id) |
| 255 |
nd.dir, nd.head = 'TLT', head |
| 256 |
return nd |
| 257 |
end |
| 258 |
|
| 259 |
local function wrap_picture(head, x0, y0) |
| 260 |
-- Note: this does not set the image dimensions |
| 261 |
local horizontal = make_surrounding_box('hlist', head) |
| 262 |
local vertical = make_surrounding_box('vlist', horizontal) |
| 263 |
local outer = make_surrounding_box('hlist', vertical) |
| 264 |
vertical.shift = -y0 |
| 265 |
horizontal.shift = x0 |
| 266 |
return outer |
| 267 |
end |
| 268 |
M.wrap_picture = wrap_picture |
| 269 |
|
| 270 |
--2 colour conversion |
| 271 |
|
| 272 |
local function rgb_to_gray (r,g,b) |
| 273 |
return ( tex.count['RtoG'] * r / 10000 |
| 274 |
+ tex.count['GtoG'] * g / 10000 |
| 275 |
+ tex.count['BtoG'] * b / 10000 ) |
| 276 |
end |
| 277 |
E.rgb_to_gray = rgb_to_gray |
| 278 |
|
| 279 |
local function cmyk_to_rgb (c,m,y,k) |
| 280 |
return (1-k)*(1-c), (1-k)*(1-m), (1-k)*(1-y) |
| 281 |
end |
| 282 |
|
| 283 |
local function rgb_to_cmyk (r, g, b) |
| 284 |
local k = 1 - math.max(r, g, b) |
| 285 |
if k == 1 then |
| 286 |
return 0, 0, 0, k |
| 287 |
else |
| 288 |
return (1-r-k)/(1-k), (1-g-k)/(1-k), (1-b-k)/(1-k), k |
| 289 |
end |
| 290 |
end |
| 291 |
|
| 292 |
local function convert_colour(cr) |
| 293 |
-- always write rgb or cmyk black as grayscale |
| 294 |
if cr[1] == 0 and cr[2] == 0 and cr[3] == 0 |
| 295 |
and (cr[4] == 1 or not cr[4]) then |
| 296 |
return { 0 } |
| 297 |
end |
| 298 |
-- see if we must convert to another colour space |
| 299 |
local n = #cr |
| 300 |
local convert = tex.count['convertmpcolours'] |
| 301 |
if convert == 1 then |
| 302 |
if n == 3 then |
| 303 |
return { rgb_to_gray(table.unpack(cr)) } |
| 304 |
elseif n == 4 then |
| 305 |
return { rgb_to_gray(cmyk_to_rgb(table.unpack(cr))) } |
| 306 |
end |
| 307 |
elseif convert == 3 and n == 4 then |
| 308 |
return { cmyk_to_rgb(table.unpack(cr)) } |
| 309 |
elseif convert == 4 and n == 3 then |
| 310 |
return { rgb_to_cmyk(table.unpack(cr)) } |
| 311 |
end |
| 312 |
-- otherwise return the colour unchanged |
| 313 |
return cr |
| 314 |
end |
| 315 |
|
| 316 |
--2 colour literals |
| 317 |
|
| 318 |
-- MetaPost supports colour models with 1, 3 or 4 parameters. The corresponding |
| 319 |
-- pdf operators are |
| 320 |
|
| 321 |
-- RG rg RGB colour model for stroke/filling |
| 322 |
-- K k CMYK colour model for stroke/filling |
| 323 |
-- G g Grayscale colour model for stroke/filling |
| 324 |
|
| 325 |
-- ... CS cs select colourspace for stroke/filling |
| 326 |
-- ... SCN scn select colour in colourspace for stroke/filling |
| 327 |
|
| 328 |
-- In order to prevent duplicate colour settings, ‘append’ contains the state |
| 329 |
-- variables ‘stroke’ and ‘fill’ that record the last-used colour settings. |
| 330 |
|
| 331 |
-- preload device colour pattern colour spaces |
| 332 |
pdfres.add_resource('ColorSpace', 'PsG', { value = '[ /Pattern /DeviceGray ]' }) |
| 333 |
pdfres.add_resource('ColorSpace', 'PsRG', { value = '[ /Pattern /DeviceRGB ]' }) |
| 334 |
pdfres.add_resource('ColorSpace', 'PsK', { value = '[ /Pattern /DeviceCMYK ]' }) |
| 335 |
|
| 336 |
local colour_template = { '%.3f ', '%.3f %.3f ', '%.3f %.3f %.3f ', '%.3f %.3f %.3f %.3f ' } |
| 337 |
local colour_stroke_operators = { 'G', nil, 'RG', 'K' } |
| 338 |
local colour_fill_operators = { 'g', nil, 'rg', 'k' } |
| 339 |
local colour_pattern_spaces = { 'PsG', nil, 'PsRG', 'PsK' } |
| 340 |
|
| 341 |
local function get_colour_params(cr) |
| 342 |
return format_numbers(colour_template[#cr], table.unpack(cr)) .. ' ' |
| 343 |
end |
| 344 |
|
| 345 |
local function get_stroke_colour(cr) |
| 346 |
return get_colour_params(cr)..colour_stroke_operators[#cr] |
| 347 |
end |
| 348 |
|
| 349 |
local function get_fill_colour(append, cr) |
| 350 |
local params = get_colour_params(cr) |
| 351 |
if append.pattern then |
| 352 |
local ptype, pname = table.unpack(append.pattern) |
| 353 |
if ptype == 2 then -- coloured pattern |
| 354 |
local space = colour_pattern_spaces[#cr] |
| 355 |
append:node(pdfres.use_resource_node('ColorSpace', space)) |
| 356 |
return string.format('/%s cs %s%s scn', space, params, alloc.pdf_name(pname)) |
| 357 |
elseif ptype == 1 then -- uncoloured pattern |
| 358 |
return string.format('/Pattern cs %s scn', alloc.pdf_name(pname)) |
| 359 |
else -- should be unreachable |
| 360 |
alloc.err('Unknown pattern paint type %s', ptype) |
| 361 |
end |
| 362 |
end |
| 363 |
return params..colour_fill_operators[#cr] |
| 364 |
end |
| 365 |
|
| 366 |
-- TODO We should allow the user access to the internals here, so that support |
| 367 |
-- for other colour spaces may be added. Then, pattern support could also be |
| 368 |
-- moved into a plugin. |
| 369 |
function A.colour(append, cr, otype) |
| 370 |
if cr and #cr > 0 then |
| 371 |
cr = convert_colour(cr) |
| 372 |
-- stroke colour |
| 373 |
if otype ~= 'fill' then |
| 374 |
local stroke = get_stroke_colour(cr) |
| 375 |
if stroke ~= append.stroke then |
| 376 |
append.stroke = stroke |
| 377 |
append:literal(stroke) |
| 378 |
end |
| 379 |
end |
| 380 |
-- fill colour (possibly a pattern) |
| 381 |
if otype ~= 'outline' then |
| 382 |
local fill = get_fill_colour(append, cr) |
| 383 |
append.pattern = nil -- patterns only apply to one object |
| 384 |
if fill ~= append.fill then |
| 385 |
append.fill = fill |
| 386 |
append:literal(fill) |
| 387 |
end |
| 388 |
end |
| 389 |
end |
| 390 |
end |
| 391 |
|
| 392 |
--2 stroke setting literals |
| 393 |
|
| 394 |
-- M miterlimit |
| 395 |
-- j linejoin |
| 396 |
-- J linecap |
| 397 |
-- d dash |
| 398 |
|
| 399 |
-- As with colour, we record the last-used settings in ‘append’. This function |
| 400 |
-- is only called for fill/outline objects. |
| 401 |
|
| 402 |
function A.linestate (append, object) |
| 403 |
local ml = object.miterlimit |
| 404 |
local res = { } |
| 405 |
if ml and ml ~= append.miterlimit then |
| 406 |
append.miterlimit = ml |
| 407 |
table.insert(res, pdfnum('M', ml)) |
| 408 |
end |
| 409 |
local lj = object.linejoin |
| 410 |
if lj and lj ~= append.linejoin then |
| 411 |
append.linejoin = lj |
| 412 |
table.insert(res, string.format('%i j', lj)) |
| 413 |
end |
| 414 |
local lc = object.linecap |
| 415 |
if lc and lc ~= append.linecap then |
| 416 |
append.linecap = lc |
| 417 |
table.insert(res, string.format('%i J', lc)) |
| 418 |
end |
| 419 |
local dl = object.dash |
| 420 |
if dl then |
| 421 |
local d = make_pdf_dashpattern(dl) |
| 422 |
if d ~= append.dashed then |
| 423 |
append.dashed = d |
| 424 |
table.insert(res, d) |
| 425 |
end |
| 426 |
elseif append.dashed then |
| 427 |
append.dashed = false |
| 428 |
table.insert(res, '[] 0 d') |
| 429 |
end |
| 430 |
if #res > 0 then |
| 431 |
append:literal(table.concat(res, ' ')) |
| 432 |
end |
| 433 |
end |
| 434 |
|
| 435 |
--2 path literals |
| 436 |
|
| 437 |
-- MetaPost only gives us curved lines; if some of the segments are straight, |
| 438 |
-- we have to find out ourselves: |
| 439 |
|
| 440 |
local bend_tolerance = 131/65536 -- context uses this value, presumably with good reasons |
| 441 |
|
| 442 |
local function curved (a,b) |
| 443 |
local d = b.left_x - a.right_x |
| 444 |
if math.abs(a.right_x - a.x_coord - d) <= bend_tolerance |
| 445 |
and math.abs(b.x_coord - b.left_x - d) <= bend_tolerance then |
| 446 |
d = b.left_y - a.right_y |
| 447 |
if math.abs(a.right_y - a.y_coord - d) <= bend_tolerance |
| 448 |
and math.abs(b.y_coord - b.left_y - d) <= bend_tolerance then |
| 449 |
return false |
| 450 |
end |
| 451 |
end |
| 452 |
return true |
| 453 |
end |
| 454 |
|
| 455 |
-- Write the path as list of points. |
| 456 |
|
| 457 |
-- m move to this point without drawing anything |
| 458 |
-- c make a curved line (two control points) |
| 459 |
-- l make a straight line |
| 460 |
|
| 461 |
function A.curve(append, path, open, concat) |
| 462 |
-- The ‘concat’ function transforms the given coordinate pairs |
| 463 |
-- according to the current transformation. |
| 464 |
concat = concat or function(px, py) return px, py end |
| 465 |
local res = { } |
| 466 |
local append_line = function(to, op) |
| 467 |
table.insert(res, point_fmt(op, concat(to.x_coord, to.y_coord))) |
| 468 |
end |
| 469 |
local append_curve = function(from, to) |
| 470 |
local a, b = concat(from.right_x, from.right_y) |
| 471 |
local c, d = concat(to.left_x, to.left_y) |
| 472 |
table.insert(res, curve_fmt(a,b,c,d,concat(to.x_coord, to.y_coord))) |
| 473 |
end |
| 474 |
local append_knot = function(from, to) |
| 475 |
if not from then |
| 476 |
append_line(to, 'm') |
| 477 |
elseif curved(from, to) then |
| 478 |
append_curve(from, to) |
| 479 |
else |
| 480 |
append_line(to, 'l') |
| 481 |
end |
| 482 |
end |
| 483 |
local knot, prev_knot |
| 484 |
for i=1, #path do |
| 485 |
knot = path[i] |
| 486 |
append_knot(prev_knot, knot) |
| 487 |
prev_knot = knot |
| 488 |
end |
| 489 |
if not open then |
| 490 |
append_knot(knot, path[1]) |
| 491 |
elseif #path == 1 then |
| 492 |
append_line(path[1], 'l') -- special case: draw a point |
| 493 |
end |
| 494 |
append:literal(table.concat(res, '\n')) |
| 495 |
end |
| 496 |
|
| 497 |
-- And actually draw the path. |
| 498 |
|
| 499 |
-- S draw the path |
| 500 |
-- h close the path |
| 501 |
-- s close and draw the path (equivalent to h S) |
| 502 |
-- f fill the path (implies h) |
| 503 |
-- f* fill the path, use even/odd rule |
| 504 |
-- b close, fill and draw the path (equivalent to h B) |
| 505 |
-- b* close, fill and draw, use even/odd rule |
| 506 |
-- n do nothing (used for clipping paths) |
| 507 |
|
| 508 |
local function get_path_operator(otype, open) |
| 509 |
if otype == 'fill' then |
| 510 |
return 'f' |
| 511 |
elseif otype == 'outline' then |
| 512 |
return (open and 'S') or 's' |
| 513 |
elseif otype == 'both' then |
| 514 |
return 'b' |
| 515 |
elseif otype == 'nofill' then |
| 516 |
return '' |
| 517 |
elseif otype == 'eofill' then |
| 518 |
return 'f*' |
| 519 |
elseif otype == 'eofilldraw' then |
| 520 |
return 'b*' |
| 521 |
else |
| 522 |
alloc.err('Unknown path type ‘%s’', otype) |
| 523 |
return 'f' |
| 524 |
end |
| 525 |
end |
| 526 |
|
| 527 |
-- |
| 528 |
|
| 529 |
--1 PROCESSING OBJECTS |
| 530 |
|
| 531 |
-- Our processors are located in two tables: one that contains a processor for |
| 532 |
-- each object and one that contains processors for certain ‘special’ statements. Every |
| 533 |
-- table contains functions that take the ‘append’ structure and the current |
| 534 |
-- object as arguments. The tables are indexed by object/special name. |
| 535 |
|
| 536 |
-- The treatment of pre- and postscripts is like this: |
| 537 |
-- * Pre- and postscripts should be of the form ‘type: instruction’. |
| 538 |
-- * If the type of a prescript is present in the ‘specials’ table, the |
| 539 |
-- corresponding function will be used in place of the default handling. |
| 540 |
-- * Execution of other prescripts and of all postscripts will be given by the |
| 541 |
-- entries in the ‘prescripts’ and ‘postscripts’ table corresponding to the |
| 542 |
-- type. |
| 543 |
|
| 544 |
local process = {} |
| 545 |
local specials = {} |
| 546 |
M.specials = specials |
| 547 |
|
| 548 |
local prescripts = {} |
| 549 |
local postscripts = {} |
| 550 |
M.prescripts = prescripts |
| 551 |
M.postscripts = postscripts |
| 552 |
|
| 553 |
--2 choosing a parser |
| 554 |
|
| 555 |
local function split_specials(thespecials) |
| 556 |
if not thespecials then return function() return end end |
| 557 |
local l = thespecials:explode('\r') |
| 558 |
local i, n = 0, #l |
| 559 |
return function() |
| 560 |
if i < n then i = i + 1 else return end |
| 561 |
local sp, instr = l[i]:match('^([a-zA-Z_]+): *(.*)') |
| 562 |
return sp, instr or l[i] |
| 563 |
end |
| 564 |
end |
| 565 |
|
| 566 |
local function parse_object(append, object) |
| 567 |
append.object_info = { } |
| 568 |
if debugging then |
| 569 |
append:printobj(object) |
| 570 |
end |
| 571 |
local processor = nil |
| 572 |
for sp, instr in split_specials(object.prescript) do |
| 573 |
if not sp then |
| 574 |
alloc.err('Unrecognised prescript: %s', instr) |
| 575 |
append:literal('%% unsupported special excluded (see log file)') |
| 576 |
elseif specials[sp] then |
| 577 |
processor = function() specials[sp](append, instr, object) end |
| 578 |
elseif prescripts[sp] then |
| 579 |
prescripts[sp](append, instr, object) |
| 580 |
else |
| 581 |
alloc.err('Unrecognised prescript ‘%s’ with instruction: %s', sp, instr) |
| 582 |
append:literal('%% unsupported special excluded (see log file)') |
| 583 |
end |
| 584 |
end |
| 585 |
if processor then |
| 586 |
processor() |
| 587 |
else |
| 588 |
process[object.type](append, object) |
| 589 |
end |
| 590 |
for sp, instr in split_specials(object.postscript) do |
| 591 |
if not sp then |
| 592 |
alloc.err('Unrecognised postscript: %s', instr) |
| 593 |
append:literal('%% unsupported special excluded (see log file)') |
| 594 |
elseif postscripts[sp] then |
| 595 |
postscripts[sp](append, instr, object) |
| 596 |
else |
| 597 |
alloc.err('Unrecognised postscript ‘%s’ with instruction: %s', sp, instr) |
| 598 |
append:literal('%% unsupported special excluded (see log file)') |
| 599 |
end |
| 600 |
end |
| 601 |
end |
| 602 |
|
| 603 |
--2 start/stop bounds |
| 604 |
|
| 605 |
-- These can be ignored, because they are taken into account by MetaPost when |
| 606 |
-- it reports the bounding box of the picture. |
| 607 |
|
| 608 |
process.start_bounds = function(append, object) end |
| 609 |
process.stop_bounds = function(append, object) end |
| 610 |
|
| 611 |
--2 clipping |
| 612 |
|
| 613 |
-- W clipping operator |
| 614 |
-- n path no-op |
| 615 |
|
| 616 |
process.start_clip = function(append, object) |
| 617 |
append:save() |
| 618 |
append:curve(object.path, false) |
| 619 |
append:literal('W n') |
| 620 |
end |
| 621 |
|
| 622 |
process.stop_clip = function(append, object) |
| 623 |
append:restore() |
| 624 |
end |
| 625 |
|
| 626 |
--2 fill and outline |
| 627 |
|
| 628 |
process.fill_or_outline = function(append, object, otype) |
| 629 |
append:linestate(object) |
| 630 |
local t, appendpath |
| 631 |
if object.pen and object.pen.type == 'elliptical' then |
| 632 |
-- metapost includes nonelliptical pens in the outline |
| 633 |
t = mplib.pen_info(object) |
| 634 |
if t.width ~= append.linewidth then |
| 635 |
append:literal(pdfnum('w', t.width)) |
| 636 |
append.linewidth = t.width |
| 637 |
end |
| 638 |
if otype == 'fill' then otype = 'both' end -- for in append:colour |
| 639 |
local transformed = not ( t.sx == 1 and t.rx == 0 |
| 640 |
and t.ry == 0 and t.sy == 1 |
| 641 |
and t.tx == 0 and t.ty == 0 ) |
| 642 |
t = transformed and t |
| 643 |
end |
| 644 |
append:colour(object.color, otype) -- otype is 'fill' 'outline' or 'both' |
| 645 |
otype = append.object_info.otype or otype -- 'eofill' etc. |
| 646 |
local open = object.path |
| 647 |
and object.path[1].left_type |
| 648 |
and object.path[#object.path].right_type |
| 649 |
local operator = get_path_operator(otype, open) |
| 650 |
if t then |
| 651 |
local d = t.sx * t.sy - t.rx - t.ry |
| 652 |
local concat = function(px, py) |
| 653 |
return (t.sy*px - t.ry*py)/d, (t.sx*py - t.rx*px)/d |
| 654 |
end |
| 655 |
appendpath = function(path) |
| 656 |
append:save() |
| 657 |
append:literal('%f %f %f %f %f %f cm', t.sx, t.rx, t.ry, t.sy, t.tx, t.ty) |
| 658 |
append:curve(path, open, concat) |
| 659 |
append:literal(operator) |
| 660 |
append:restore() |
| 661 |
end |
| 662 |
else |
| 663 |
appendpath = function(path) |
| 664 |
append:curve(path, open) |
| 665 |
append:literal(operator) |
| 666 |
end |
| 667 |
end |
| 668 |
if object.path then appendpath(object.path) end |
| 669 |
if object.htap then appendpath(object.htap) end -- reversed trajectory |
| 670 |
end |
| 671 |
|
| 672 |
process.fill = function(append, object) |
| 673 |
process.fill_or_outline(append, object, 'fill') |
| 674 |
end |
| 675 |
|
| 676 |
process.outline = function(append, object) |
| 677 |
process.fill_or_outline(append, object, 'outline') |
| 678 |
end |
| 679 |
|
| 680 |
--2 specials |
| 681 |
|
| 682 |
-- this will be pointed to the right table at the start of each run |
| 683 |
local current_instance = false |
| 684 |
|
| 685 |
-- pure specials are already taken care of in parse_object (they only have |
| 686 |
-- a ‘prescript’ field). |
| 687 |
process.special = function(append, object) end |
| 688 |
|
| 689 |
prescripts.pdf = function(append, special, object) |
| 690 |
append:literal(special) |
| 691 |
end |
| 692 |
postscripts.pdf = prescripts.pdf |
| 693 |
|
| 694 |
prescripts.pdfcomment = function(append, str, object) |
| 695 |
append:literal('%% %s', str) |
| 696 |
end |
| 697 |
postscripts.pdfcomment = prescripts.pdfcomment |
| 698 |
|
| 699 |
prescripts.latelua = function(append, str, object) |
| 700 |
local n = node.new('whatsit', 'late_lua') |
| 701 |
n.data = str |
| 702 |
append:node(n) |
| 703 |
end |
| 704 |
postscripts.latelua = prescripts.latelua |
| 705 |
|
| 706 |
prescripts.OTYPE = function(append, str, object) |
| 707 |
append.object_info.otype = append.object_info.otype or str |
| 708 |
end |
| 709 |
|
| 710 |
specials.BASELINE = function(append, _, object) |
| 711 |
-- object is a ‘fill’ statement with only a single point in its path (and |
| 712 |
-- will thus not have to be transformed). |
| 713 |
append.baseline = object.path[1].y_coord |
| 714 |
end |
| 715 |
|
| 716 |
-- 2 box resources (xforms) |
| 717 |
|
| 718 |
-- The first problem that we run into is that we want to refer to xforms (from |
| 719 |
-- the metapost side) whose numerical id* we do know know yet (because the |
| 720 |
-- xform will only be made at the end of the run, during the lua-side |
| 721 |
-- processing of mplib output). |
| 722 |
-- |
| 723 |
-- Our solution is using negative ids for metapost-defined xforms, which will |
| 724 |
-- be converted to actual boxresource ids by means of a conversion table. |
| 725 |
-- |
| 726 |
-- The second problem is the need to position metapost-defined xforms by their |
| 727 |
-- original (metapost) origin. This necessitates storing extra information |
| 728 |
-- lua-side. |
| 729 |
-- |
| 730 |
-- * Not to be confused with the object number which we, due to pdftex’s |
| 731 |
-- special handling of xforms, will never come to know. |
| 732 |
|
| 733 |
local xform_nr_shim = { } |
| 734 |
|
| 735 |
local function resolve_xform_id(nr) |
| 736 |
nr = tonumber(nr) |
| 737 |
if nr < 0 then |
| 738 |
return xform_nr_shim[-nr] |
| 739 |
else |
| 740 |
return nr |
| 741 |
end |
| 742 |
end |
| 743 |
|
| 744 |
local function reserve_xform_id() |
| 745 |
xform_nr_shim[1+#xform_nr_shim] = false |
| 746 |
return -#xform_nr_shim |
| 747 |
end |
| 748 |
|
| 749 |
M.resolve_xform_id = resolve_xform_id |
| 750 |
E.resolve_xform_id = resolve_xform_id |
| 751 |
E.reserve_xform_id = reserve_xform_id |
| 752 |
|
| 753 |
-- When using xforms in metapost, the positive numbers refer to tex-defined and |
| 754 |
-- the negative to metapost-defined box resources. |
| 755 |
|
| 756 |
specials.BOXRESOURCE = function(append, id, object) |
| 757 |
local realid = resolve_xform_id(id) |
| 758 |
local rule = tex.useboxresource(realid) |
| 759 |
append:box(object, node.hpack(rule)) |
| 760 |
end |
| 761 |
|
| 762 |
local xform_sizes = { } |
| 763 |
local xform_center = { } |
| 764 |
|
| 765 |
local function set_boxresource_dimensions (id, transf, center) |
| 766 |
xform_sizes[id] = transf |
| 767 |
xform_center[id] = center |
| 768 |
end |
| 769 |
|
| 770 |
local function get_boxresource_dimensions (id) |
| 771 |
if xform_sizes[id] then |
| 772 |
return xform_sizes[id] |
| 773 |
else |
| 774 |
return { 'box_size', tex.getboxresourcedimensions(id) } |
| 775 |
end |
| 776 |
end |
| 777 |
|
| 778 |
local function get_boxresource_center (id) |
| 779 |
if xform_center[id] then |
| 780 |
return xform_center[id] |
| 781 |
else |
| 782 |
return "(0,0)" |
| 783 |
end |
| 784 |
end |
| 785 |
|
| 786 |
E.set_boxresource_dimensions = set_boxresource_dimensions |
| 787 |
E.get_boxresource_dimensions = get_boxresource_dimensions |
| 788 |
E.get_boxresource_center = get_boxresource_center |
| 789 |
|
| 790 |
local function save_as_boxresource(pic) |
| 791 |
-- attributes |
| 792 |
local attrs = { '/Subtype/Form', bbox_fmt(0, -pic.dp, pic.wd, pic.ht) } |
| 793 |
for k, v in pairs(pic.user.xform_attrs or { }) do |
| 794 |
table.insert(attrs, string.format('%s %s', alloc.pdf_name(k), v)) |
| 795 |
end |
| 796 |
-- box to-be-saved |
| 797 |
local box = wrap_picture(node.copy_list(pic.head), pic.x0, pic.y0) |
| 798 |
box.width, box.height, box.depth = pic.wd, pic.ht, pic.dp |
| 799 |
-- save the box |
| 800 |
local xform = tex.saveboxresource(box, |
| 801 |
table.concat(attrs, ' '), nil, false, 4) -- 4: no /Type, /BBox or /Matrix |
| 802 |
xform_nr_shim[-pic.user.xform_id] = xform |
| 803 |
end |
| 804 |
|
| 805 |
specials.XFORMINDEX = function(append, id, object) |
| 806 |
append.user.xform_id = tonumber(id) |
| 807 |
append.user.save_fn = save_as_boxresource |
| 808 |
end |
| 809 |
|
| 810 |
specials.XFORMATTRS = function(append, attrs, object) |
| 811 |
local t = parse_lua_table('XForm attributes', attrs) |
| 812 |
append.user.xform_attrs = t or { } |
| 813 |
end |
| 814 |
|
| 815 |
--2 patterns |
| 816 |
|
| 817 |
-- Saved patterns have the following fields: |
| 818 |
-- attr the pattern attributes |
| 819 |
-- stream the pattern drawing statements |
| 820 |
-- painttype the paint type of the pattern (1 or 2) |
| 821 |
|
| 822 |
local function write_pattern_object(pat) |
| 823 |
local objnum = pat.objnum or pdf.reserveobj() |
| 824 |
pdf.obj(objnum, 'stream', pat.stream, pat.attr) |
| 825 |
pdf.refobj(objnum) |
| 826 |
return string.format('%d 0 R', objnum) |
| 827 |
end |
| 828 |
|
| 829 |
prescripts.fillpattern = function(append, str, object) |
| 830 |
local name = 'MnmP'..tonumber(str) |
| 831 |
local pat = pdfres.get_resource('Pattern', name) |
| 832 |
if not pat then |
| 833 |
alloc.err('Unknown pattern %s', name) |
| 834 |
else |
| 835 |
append.pattern = { pat.painttype, name } |
| 836 |
append:node(pdfres.use_resource_node('Pattern', name)) |
| 837 |
end |
| 838 |
end |
| 839 |
|
| 840 |
local function make_pattern_xform(head, bb) |
| 841 |
-- regrettably, pdf.refobj does not work with xforms, so we must |
| 842 |
-- write it to the pdf immediately, whether the pattern will be |
| 843 |
-- used or not. |
| 844 |
local xform = tex.saveboxresource((node.hpack(node.copy_list(head))), |
| 845 |
'/Subtype/Form '..bb, nil, true, 4) -- 4: no /Type, /BBox or /Matrix |
| 846 |
return string.format(' /Resources << /XObject << /PTempl %d 0 R >> >>', xform), '/PTempl Do' |
| 847 |
end |
| 848 |
|
| 849 |
local function definepattern(pic) |
| 850 |
local bb = bbox_fmt(table.unpack(pic.bbox)) |
| 851 |
local pat, literals, resources = { write = write_pattern_object }, { } |
| 852 |
-- pattern content |
| 853 |
for n in node.traverse(pic.head) do |
| 854 |
-- try if we can construct the content stream ourselves; otherwise, |
| 855 |
-- stuff the pattern template into an xform. |
| 856 |
if n.id == WHATSIT_NODE then |
| 857 |
-- try if we can simply concatenate pdf statements |
| 858 |
if n.subtype == node.subtype 'literal' then |
| 859 |
table.insert(literals, n.data) |
| 860 |
elseif n.subtype == node.subtype 'save' then |
| 861 |
table.insert(literals, 'q') |
| 862 |
elseif n.subtype == node.subtype 'restore' then |
| 863 |
table.insert(literals, 'Q') |
| 864 |
else |
| 865 |
resources, pat.stream = make_pattern_xform(pic.head, bb) |
| 866 |
goto continue |
| 867 |
end |
| 868 |
else |
| 869 |
resources, pat.stream = make_pattern_xform(pic.head, bb) |
| 870 |
goto continue |
| 871 |
end |
| 872 |
pat.stream = table.concat(literals, '\n') |
| 873 |
end |
| 874 |
::continue:: |
| 875 |
-- construct the pattern object |
| 876 |
local i = pic.user.pattern_info |
| 877 |
local m = i.matrix |
| 878 |
pat.painttype = tonumber(i.painttype) |
| 879 |
pat.attr = table.concat({ |
| 880 |
string.format('/PatternType 1 /PaintType %d /TilingType %s /XStep %f /YStep %f\n', |
| 881 |
i.painttype, i.tilingtype, i.xstep, i.ystep), |
| 882 |
string.format('%s\n/Matrix [ %s %s %s %s %s %s ]', bb, m.xx, m.xy, m.yx, m.yy, m.x, m.y), |
| 883 |
resources }, '') |
| 884 |
-- remember the pattern |
| 885 |
pdfres.add_resource('Pattern', 'MnmP'..i.nr, pat) |
| 886 |
end |
| 887 |
|
| 888 |
specials.definepattern = function(append, str, object) |
| 889 |
local nr, tiling, paint, xs, ys, xx, xy, yx, yy = table.unpack(str:explode()) |
| 890 |
append.user.pattern_info = { nr = nr, xstep = xs, ystep = ys, |
| 891 |
tilingtype = tiling, painttype = paint, |
| 892 |
matrix = { xx = xx, xy = xy, yx = yx, yy = yy, x = 0, y = 0 } } |
| 893 |
append.user.save_fn = definepattern |
| 894 |
end |
| 895 |
|
| 896 |
-- 2 extgstates |
| 897 |
|
| 898 |
-- Specials for the graphics state: |
| 899 |
-- |
| 900 |
-- gstate:save q |
| 901 |
-- gstate:restore Q |
| 902 |
-- |
| 903 |
-- extgstate:label /label gs |
| 904 |
-- extgstate:{...} /newlabel gs |
| 905 |
-- |
| 906 |
-- If a lua table is passed to the extgstate, minim will try and find an |
| 907 |
-- earlier-defined matching ExtGState object. If it cannot be found, a new one |
| 908 |
-- will be created and used. The values of the table will be written to the pdf |
| 909 |
-- as-they-are (this means booleans and numbers are alright), but the keys will |
| 910 |
-- be converted to pdf name objects. |
| 911 |
|
| 912 |
prescripts.gstate = function(append, str, object) |
| 913 |
if str == 'save' or str == 'store' then |
| 914 |
append:save() |
| 915 |
elseif str == 'restore' then |
| 916 |
append:restore() |
| 917 |
else |
| 918 |
alloc.err('Unknown gstate operator: »%s«', str) |
| 919 |
end |
| 920 |
end |
| 921 |
postscripts.gstate = prescripts.gstate |
| 922 |
|
| 923 |
local gs_next, gs_index = 1, { } |
| 924 |
|
| 925 |
function M.get_gstate_name(t) |
| 926 |
-- format the pdf dict |
| 927 |
local d = { } |
| 928 |
for k,v in pairs(t) do |
| 929 |
if type(v) == 'table' and t.dashes then |
| 930 |
v = '[ '..make_pdf_dashpattern(v)..' ]' |
| 931 |
end |
| 932 |
table.insert(d, string.format('%s %s', alloc.pdf_name(k), v)) |
| 933 |
end |
| 934 |
table.sort(d) |
| 935 |
d[0] = '<<'; table.insert(d, '>>') |
| 936 |
t.value = table.concat(d, ' ', 0) |
| 937 |
-- check the index |
| 938 |
if not gs_index[t.value] then |
| 939 |
local name = string.format('MnmGs%d', gs_next) |
| 940 |
gs_index[t.value] = name |
| 941 |
gs_next = gs_next + 1 |
| 942 |
pdfres.add_resource('ExtGState', name, t) |
| 943 |
end |
| 944 |
-- return the resource name |
| 945 |
return gs_index[t.value] |
| 946 |
end |
| 947 |
|
| 948 |
prescripts.extgstate = function(append, str, object) |
| 949 |
-- determine resource name |
| 950 |
local name, t = str |
| 951 |
if string.find(str, '^[A-Za-z0-9_]+$') then |
| 952 |
t = pdfres.get_resource('ExtGState', name) |
| 953 |
if not t then return alloc.err('Unknown named ExtGState: %s', name) end |
| 954 |
else |
| 955 |
t = parse_lua_table('ExtGState', str) |
| 956 |
if not t then return end |
| 957 |
name = M.get_gstate_name(t) |
| 958 |
end |
| 959 |
-- -- update state parameters (disabled for now; may be enabled if it has practical use) |
| 960 |
-- if t.LW then append.linewidth = t.LW end |
| 961 |
-- if t.ML then append.miterlimit = t.LW end |
| 962 |
-- if t.LJ then append.linejoin = t.LW end |
| 963 |
-- if t.LC then append.linecap = t.LW end |
| 964 |
-- if t.D and type(t.D) == 'table' then append.dashed = make_pdf_dashpattern(t.D) end |
| 965 |
-- apply the state change |
| 966 |
append:literal('%s gs', alloc.pdf_name(name)) |
| 967 |
append:node(pdfres.use_resource_node('ExtGState', name)) |
| 968 |
end |
| 969 |
postscripts.extgstate = prescripts.extgstate |
| 970 |
|
| 971 |
-- 2 text |
| 972 |
|
| 973 |
process.text = function(append, object) |
| 974 |
alloc.err('Text figure primitives are not supported (this message should not occur)') |
| 975 |
end |
| 976 |
|
| 977 |
local function get_transform(rect) |
| 978 |
-- reconstruct the applied transformation by examining a unit square, i.e. |
| 979 |
-- ‘rect’ was originally the path (0,0) -- (0,1) -- (1,1) -- (1,0) |
| 980 |
local ll, lr, ul = rect[1], rect[2], rect[4] |
| 981 |
-- determine translation from (0,0) |
| 982 |
local tx, ty = ll.x_coord, ll.y_coord |
| 983 |
-- determine rotation and scaling from the diagonals |
| 984 |
local sx, rx = lr.x_coord - tx, lr.y_coord - ty |
| 985 |
local ry, sy = ul.x_coord - tx, ul.y_coord - ty |
| 986 |
return sx, rx, ry, sy, tx, ty |
| 987 |
end |
| 988 |
|
| 989 |
local function apply_transform(rect, box) |
| 990 |
local sx, rx, ry, sy, tx, ty = get_transform(rect) |
| 991 |
local transform = node.new('whatsit', 'pdf_setmatrix') |
| 992 |
transform.next, box.prev = box, transform |
| 993 |
transform.data = string.format('%f %f %f %f', sx, rx, ry, sy) |
| 994 |
tx = tex.sp(''..tx..'bp') |
| 995 |
ty = tex.sp(''..ty..'bp') |
| 996 |
return wrap_picture(transform, tx, ty) |
| 997 |
end |
| 998 |
|
| 999 |
function A.box(append, object, box) |
| 1000 |
box.width = 0 ; box.height = 0 ; box.depth = 0; |
| 1001 |
local outer = apply_transform(object.path, box) |
| 1002 |
append:colour(object.color, 'fill') |
| 1003 |
append:save() |
| 1004 |
append:node(outer) |
| 1005 |
append:restore() |
| 1006 |
end |
| 1007 |
|
| 1008 |
specials.TEXBOX = function(append, boxnr, object) |
| 1009 |
local box = tex.getbox(tonumber(boxnr)) |
| 1010 |
append:box(object, node.copy_list(box)) |
| 1011 |
end |
| 1012 |
|
| 1013 |
specials.CHAR = function(append, data, object) |
| 1014 |
local char, font, xo, yo = table.unpack(data:explode(' ')) |
| 1015 |
local n = node.new('glyph') |
| 1016 |
n.char, n.font, n.xoffset, n.yoffset = |
| 1017 |
tonumber(char), tonumber(font), tonumber(xo), tonumber(yo) |
| 1018 |
append:box(object, node.hpack(n)) |
| 1019 |
end |
| 1020 |
|
| 1021 |
-- |
| 1022 |
|
| 1023 |
--1 METAPOST INSTANCES |
| 1024 |
|
| 1025 |
local instances = { } |
| 1026 |
M.instances = instances |
| 1027 |
|
| 1028 |
--2 small instance helper functions |
| 1029 |
|
| 1030 |
-- parameters: wd, ht+dp, dp |
| 1031 |
local function make_transform(w, h, d) |
| 1032 |
return string.format('identity xscaled %fpt yscaled %fpt shifted (0,%fpt)', |
| 1033 |
w/65536, (h+d)/65536, -d/65536) |
| 1034 |
end |
| 1035 |
|
| 1036 |
local status_names = { [0] = 'good', 'warning', 'error', 'fatal' } |
| 1037 |
local function print_status(st) |
| 1038 |
return string.format('status %d (%s)', st, status_names[st]) |
| 1039 |
end |
| 1040 |
|
| 1041 |
M.on_line = false |
| 1042 |
M.max_errprint = 1 |
| 1043 |
local function print_log (nr, res, why) |
| 1044 |
local i = instances[nr] |
| 1045 |
-- only write to term if on_line or if exit status increases |
| 1046 |
local log, alog --luacheck:ignore 231 |
| 1047 |
if M.on_line or res.status > i.status then |
| 1048 |
alog = alloc.amsg |
| 1049 |
local nr_errs = 0 |
| 1050 |
log = function(...) |
| 1051 |
if string.sub(table.pack(...)[2],1,2) == "! " then |
| 1052 |
nr_errs = nr_errs + 1 |
| 1053 |
end |
| 1054 |
if M.max_errprint < 1 or M.max_errprint >= nr_errs then |
| 1055 |
alloc.msg(...) |
| 1056 |
else |
| 1057 |
alloc.log(...) |
| 1058 |
alloc.term('╧ [... see log file for full report ...]') |
| 1059 |
log, alog = alloc.log, alloc.alog |
| 1060 |
end |
| 1061 |
end |
| 1062 |
else |
| 1063 |
log, alog = alloc.log, alloc.alog |
| 1064 |
end |
| 1065 |
-- split log into lines; discard empty lines at the end |
| 1066 |
local report = res.log and res.log:explode('\n') or { } |
| 1067 |
-- write out the log |
| 1068 |
log('┌ %smetapost instance {%s} (%d)', why or '', i.jobname, i.nr) |
| 1069 |
for _,line in ipairs(report) do |
| 1070 |
if line ~= '' and line ~= "(Please type a command or say `end')" then |
| 1071 |
log('│ %s', line) |
| 1072 |
end |
| 1073 |
end |
| 1074 |
log('└ %s', print_status(res.status)) |
| 1075 |
-- generate error or warning if needed |
| 1076 |
if res.status > i.status then |
| 1077 |
local ecl = tex.errorcontextlines -- TODO: why does TeX fill the error context |
| 1078 |
tex.errorcontextlines = 0 -- with repeated <inserted text> BAD ??? |
| 1079 |
if res.status == 3 then |
| 1080 |
alloc.err('Metapost instance now defunct') |
| 1081 |
elseif res.status == 2 then |
| 1082 |
alloc.err('Error in metapost code. Further errors will be ignored') |
| 1083 |
elseif res.status == 1 then |
| 1084 |
alloc.msg('Metapost code caused warning') |
| 1085 |
end |
| 1086 |
tex.errorcontextlines = ecl |
| 1087 |
end |
| 1088 |
-- save the exit status for later comparison |
| 1089 |
i.status = res.status |
| 1090 |
end |
| 1091 |
|
| 1092 |
local function new_file_finder() |
| 1093 |
-- HACK: The file finder is called twice for every file input by metapost. |
| 1094 |
-- Thus, in order for the file recorder to work properly, we only record |
| 1095 |
-- repeated files and hope for the best. |
| 1096 |
local last_found = false |
| 1097 |
local function record(name, record_fn) |
| 1098 |
if last_found and name == last_found then |
| 1099 |
record_fn(name) |
| 1100 |
last_found = false |
| 1101 |
else |
| 1102 |
last_found = name |
| 1103 |
end |
| 1104 |
end |
| 1105 |
return function(name, mode, ftype) |
| 1106 |
if mode == 'w' then |
| 1107 |
record(name, kpse.record_output_file) |
| 1108 |
else |
| 1109 |
name = kpse.find_file(name, ftype) |
| 1110 |
record(name, kpse.record_input_file) |
| 1111 |
end |
| 1112 |
return name |
| 1113 |
end |
| 1114 |
end |
| 1115 |
|
| 1116 |
--2 processing results |
| 1117 |
|
| 1118 |
local function process_results(nr, res) |
| 1119 |
local pictures = {} |
| 1120 |
if res.fig then |
| 1121 |
alloc.alog (' (%d figures)', #res.fig) |
| 1122 |
for i=1, #res.fig do |
| 1123 |
local fig = res.fig[i] |
| 1124 |
local name = fig:filename() |
| 1125 |
local append = init_append() |
| 1126 |
if debugging then |
| 1127 |
append:literal('%% START OF MP FIGURE %s (instance %d)', name, nr) |
| 1128 |
end |
| 1129 |
-- parse and append all objects |
| 1130 |
append:save() |
| 1131 |
local objects = fig:objects() |
| 1132 |
for j=1, #objects do |
| 1133 |
parse_object (append, objects[j]) |
| 1134 |
end |
| 1135 |
append:restore() |
| 1136 |
if debugging then |
| 1137 |
append:literal('%% END OF MP FIGURE %s (instance %d)', name, nr) |
| 1138 |
end |
| 1139 |
-- bounding box and baseline information |
| 1140 |
local bb = fig:boundingbox() |
| 1141 |
local llx, lly, urx, ury = table.unpack(bb) |
| 1142 |
local bas = append.baseline or lly |
| 1143 |
local pic = |
| 1144 |
{ head = append.head |
| 1145 |
, user = append.user |
| 1146 |
, name = name |
| 1147 |
, bbox = bb } |
| 1148 |
if llx > urx and lly > ury then |
| 1149 |
pic.discard = true -- picture is empty |
| 1150 |
pic.wd, pic.ht, pic.dp, pic.x0, pic.y0 = 0,0,0,0,0 |
| 1151 |
else |
| 1152 |
pic.wd = tex.sp(string.format('%s bp', urx - llx)) |
| 1153 |
pic.ht = tex.sp(string.format('%s bp', ury - bas)) |
| 1154 |
pic.dp = tex.sp(string.format('%s bp', bas - lly)) |
| 1155 |
pic.x0 = tex.sp(string.format('%s bp', -llx )) |
| 1156 |
pic.y0 = tex.sp(string.format('%s bp', -bas )) |
| 1157 |
end |
| 1158 |
cb.call_callback('finish_mpfigure', pic) |
| 1159 |
if pic.user.save_fn then |
| 1160 |
pic.discard = true |
| 1161 |
pic.user.save_fn(pic) |
| 1162 |
end |
| 1163 |
if not pic.discard then |
| 1164 |
pic.head = wrap_picture(pic.head, pic.x0, pic.y0) |
| 1165 |
end |
| 1166 |
if debugging then |
| 1167 |
alloc.msg('┌ image %s, with %s objects, %s nodes', |
| 1168 |
name, #objects, append.node_count) |
| 1169 |
alloc.msg('│ dimensions (%fpt+%fpt)x%fpt', |
| 1170 |
pic.ht/65536, pic.dp/65536, pic.wd/65536) |
| 1171 |
alloc.msg('└ origin (%fpt,%fpt)', |
| 1172 |
pic.x0/65536, pic.y0/65536) |
| 1173 |
if pic.discard then alloc.amsg(' [discarded]') end |
| 1174 |
end |
| 1175 |
table.insert(pictures, pic) |
| 1176 |
end |
| 1177 |
else |
| 1178 |
alloc.alog (' (no figures)') |
| 1179 |
end |
| 1180 |
return pictures |
| 1181 |
end |
| 1182 |
|
| 1183 |
-- 2 running lua scripts |
| 1184 |
|
| 1185 |
-- There are two ways of running lua code with the runscript primitive. In the |
| 1186 |
-- normal case, the argument to runscript is executed as lua code. You can |
| 1187 |
-- bypass this mechanism by prepending the runscript argument with the name of |
| 1188 |
-- a lua function between double square brackets. Then, the remainder of the |
| 1189 |
-- string will be passed as an argument to that function.Q |
| 1190 |
-- |
| 1191 |
-- Code run with runscript may return a value; we will try and convert it to |
| 1192 |
-- a string that metapost can understand. |
| 1193 |
-- |
| 1194 |
-- Tables of the form { 'box_size', width, height, depth, margin } are |
| 1195 |
-- converted to a transform. (The margin will be ignored for now, this may |
| 1196 |
-- change in the future.) |
| 1197 |
|
| 1198 |
local function mkluastring(s) |
| 1199 |
return "'"..(s |
| 1200 |
:gsub('\\', '\\\\') |
| 1201 |
:gsub("'", "\\'") |
| 1202 |
:gsub('\n', '\\n') |
| 1203 |
:gsub('\013', '\\r') |
| 1204 |
:gsub('\000', '\\000') |
| 1205 |
).."'" |
| 1206 |
end |
| 1207 |
|
| 1208 |
local function runscript(code) |
| 1209 |
debug('┌ runscript: %s', code) |
| 1210 |
-- (possibly) pass directly to function |
| 1211 |
local fn, arg = code:match('^%[%[(.-)%]%](.*)') |
| 1212 |
if fn then code = 'return '..fn .. mkluastring(arg) end |
| 1213 |
-- execute the script |
| 1214 |
local f, msg = load(code, current_instance.jobname, 't', current_instance.env) |
| 1215 |
-- interpret results |
| 1216 |
if f then |
| 1217 |
local result = f() |
| 1218 |
if result == nil then |
| 1219 |
debug('└ (no return value)') |
| 1220 |
return |
| 1221 |
else |
| 1222 |
local t = type(result) |
| 1223 |
if t == 'number' then |
| 1224 |
result = string.format('%.16f', result) |
| 1225 |
elseif t == 'string' then |
| 1226 |
result = result |
| 1227 |
elseif t == 'table' and result[1] == 'box_size' then |
| 1228 |
result = make_transform(result[2], result[3], result[4]) |
| 1229 |
elseif t == 'table' and #result < 5 then |
| 1230 |
local fmt = #result == 1 and '%.16f' |
| 1231 |
or #result == 2 and '(%.16f, %.16f)' |
| 1232 |
or #result == 3 and '(%.16f, %.16f, %.16f)' |
| 1233 |
or #result == 4 and '(%.16f, %.16f, %.16f, %.16f)' |
| 1234 |
result = fmt:format(table.unpack(result)) |
| 1235 |
elseif t == 'table' and #result == 6 then |
| 1236 |
result = table.concat({ |
| 1237 |
'begingroup save t; transform t', |
| 1238 |
'xxpart t = %.16f', 'xypart t = %.16f', |
| 1239 |
'yxpart t = %.16f', 'yypart t = %.16f', |
| 1240 |
'xpart t = %.16f', 'ypart t = %.16f', |
| 1241 |
't endgroup' }, |
| 1242 |
';'):format(table.unpack(result)) |
| 1243 |
else |
| 1244 |
result = tostring(result) |
| 1245 |
end |
| 1246 |
if #result > 120 then |
| 1247 |
debug('└ %s etc. etc.', result:sub(1,110)) |
| 1248 |
else |
| 1249 |
debug('└ %s', result) |
| 1250 |
end |
| 1251 |
return result |
| 1252 |
end |
| 1253 |
else |
| 1254 |
local mp_msg = string.gsub(msg, '"', '"&ditto&"') |
| 1255 |
-- TODO: provide errhelp once the echo is gone |
| 1256 |
return string.format('hide(errmessage "Lua error: %s")', mp_msg) |
| 1257 |
end |
| 1258 |
end |
| 1259 |
|
| 1260 |
-- The environment the scripts will be run in can be specified at instance |
| 1261 |
-- creation; its default value is a copy (at that time) of the global |
| 1262 |
-- environment. The runscript environment will then be extended with all |
| 1263 |
-- elements of the M.mp_functions table. |
| 1264 |
|
| 1265 |
M.mp_functions = E |
| 1266 |
E.texmessage = alloc.msg |
| 1267 |
|
| 1268 |
local function prepare_env(e) -- in M.open() |
| 1269 |
local env = e or copy_table(_G, { }) |
| 1270 |
return setmetatable(env, { __index = E }) |
| 1271 |
end |
| 1272 |
|
| 1273 |
function E.quote(val) |
| 1274 |
if type(val) ~= 'string' then return val end |
| 1275 |
local escaped = string.format('%s', val):gsub('"', '"&ditto&"') |
| 1276 |
return string.format('("%s")', escaped) |
| 1277 |
end |
| 1278 |
|
| 1279 |
function E.sp_to_pt(val) |
| 1280 |
return string.format('%.16fpt', val/65536) |
| 1281 |
end |
| 1282 |
|
| 1283 |
function E.quote_for_lua(s) |
| 1284 |
return E.quote(mkluastring(s)) |
| 1285 |
end |
| 1286 |
|
| 1287 |
-- These are here so that luametafun does not bug out immediately. Please note |
| 1288 |
-- that using metafun is not otherwise supported or recommended. |
| 1289 |
local cct_maketext = alloc.registernumber('minim:mp:catcodes:maketext') |
| 1290 |
E.catcodes = { numbers = |
| 1291 |
{ inicatcodes = cct_maketext , texcatcodes = cct_maketext |
| 1292 |
, luacatcodes = cct_maketext , notcatcodes = cct_maketext |
| 1293 |
, vrbcatcodes = cct_maketext , prtcatcodes = cct_maketext |
| 1294 |
, ctxcatcodes = cct_maketext , txtcatcodes = cct_maketext |
| 1295 |
} } |
| 1296 |
E.mp = mp or { } --luacheck: ignore 113 |
| 1297 |
-- all functions below seem nonessential |
| 1298 |
E.mp.mf_path_reset = E.mp.mf_path_reset or function() end |
| 1299 |
E.mp.mf_finish_saving_data = E.mp.mf_finish_saving_data or function() end |
| 1300 |
E.mp.report = E.mp.report or function() end |
| 1301 |
|
| 1302 |
|
| 1303 |
--2 typesetting with tex |
| 1304 |
|
| 1305 |
-- The result of the maketext function is fed back into metapost; on that side, |
| 1306 |
-- the representation of a <picture primary> will be expected for btex...etex |
| 1307 |
-- and an empty string for verbatimtex...etex. maketext is indistinguishable |
| 1308 |
-- from btex...etex. |
| 1309 |
-- |
| 1310 |
-- We return here an image() containing a single path; it is that path that |
| 1311 |
-- will be replaced with a stored node list later on. |
| 1312 |
-- |
| 1313 |
-- The path itself is a unit rectangle: from the rectangle we will be able to |
| 1314 |
-- reconstruct how the tex box will have been transformed. We indicate with |
| 1315 |
-- a prescript that the rectangle should be replaced. |
| 1316 |
-- |
| 1317 |
-- The size of the picture is communicated to MetaPost by a ‘setbounds’ |
| 1318 |
-- instruction. |
| 1319 |
|
| 1320 |
local function maketext(text, mode) |
| 1321 |
if mode == 0 then -- btex or maketext |
| 1322 |
local nr = alloc.new_box() |
| 1323 |
debug('┌ btex: %s', text) |
| 1324 |
table.insert(current_instance.boxes, nr) |
| 1325 |
local assignment = string.format('\\global\\setbox%s=\\hbox{\\the\\everymaketext %s}', nr, text) |
| 1326 |
tex.runtoks(function() tex.print(current_instance.catcodes, assignment:explode('\n')) end) |
| 1327 |
local box = tex.box[nr] |
| 1328 |
debug('└ etex: box %d', nr) |
| 1329 |
return string.format('_set_maketext_result_(%d, %s)', nr, |
| 1330 |
make_transform(box.width, box.height, box.depth)) |
| 1331 |
elseif mode == 1 then -- verbatimtex |
| 1332 |
debug('┌ verbatimtex: %s', text) |
| 1333 |
text = '\\the\\everyverbatimtex\n'..text |
| 1334 |
tex.runtoks(function() tex.print(current_instance.catcodes, text:explode('\n')) end) |
| 1335 |
debug('└ etex') |
| 1336 |
end |
| 1337 |
end |
| 1338 |
|
| 1339 |
-- a font cache for infont and glyph of |
| 1340 |
local infont_fonts = { } |
| 1341 |
local function get_infont_font(fnt) |
| 1342 |
local csname = 'minim-mp infont '..fnt |
| 1343 |
local res = infont_fonts[csname] |
| 1344 |
if res then |
| 1345 |
debug('├ resolved font "%s" (%d)', fnt, res) |
| 1346 |
else |
| 1347 |
tex.runtoks(function() |
| 1348 |
tex.print(current_instance.catcodes, string.format( |
| 1349 |
'\\expandafter\\font\\csname %s\\endcsname={%s}\\relax', csname, fnt)) |
| 1350 |
end) |
| 1351 |
res = font.id(csname) |
| 1352 |
infont_fonts[csname] = res |
| 1353 |
debug('├ loaded font "%s" (%d)', fnt, res) |
| 1354 |
end |
| 1355 |
return res |
| 1356 |
end |
| 1357 |
|
| 1358 |
local function fontid_from_csname(fnt) |
| 1359 |
local id = font.id(fnt) |
| 1360 |
if id < 0 then return end |
| 1361 |
debug('├ resolved font \\%s (%d)', fnt, id) |
| 1362 |
return id |
| 1363 |
end |
| 1364 |
|
| 1365 |
local function getfontid(fnt) |
| 1366 |
return tonumber(fnt) |
| 1367 |
or fontid_from_csname(fnt) |
| 1368 |
or get_infont_font(fnt) |
| 1369 |
end |
| 1370 |
|
| 1371 |
local typeset_box = alloc.new_box('infont box') |
| 1372 |
|
| 1373 |
local function process_typeset(text, fnt, sep, fn) |
| 1374 |
tex.runtoks(function() |
| 1375 |
tex.sprint(current_instance.catcodes, string.format( |
| 1376 |
'\\setbox%d=\\hbox{\\setfontid%d\\relax', typeset_box, getfontid(fnt))) |
| 1377 |
tex.sprint(-2, text); tex.sprint(current_instance.catcodes, '}') |
| 1378 |
end) |
| 1379 |
local res, x = { }, 0 |
| 1380 |
for n in node.traverse(tex.box[typeset_box].list) do |
| 1381 |
if n.id == GLYPH_NODE then |
| 1382 |
fn(res, n, x) |
| 1383 |
x = x + n.width |
| 1384 |
elseif n.id == GLUE_NODE then |
| 1385 |
x = x + n.width |
| 1386 |
elseif n.id == KERN_NODE then |
| 1387 |
x = x + n.kern |
| 1388 |
end |
| 1389 |
end |
| 1390 |
return table.concat(res, sep) |
| 1391 |
end |
| 1392 |
|
| 1393 |
function E.minim_infont(text, fnt) |
| 1394 |
return process_typeset(text, fnt, '', function(res, n, x) |
| 1395 |
table.insert(res, string.format( |
| 1396 |
'draw image ( fill unitsquare shifted (%fpt,0) withprescript "CHAR:%d %d %d %d";' |
| 1397 |
..'setbounds currentpicture to unitsquare transformed %s shifted (%fpt,0););', |
| 1398 |
x/65536, n.char, n.font, n.xoffset, n.yoffset, |
| 1399 |
make_transform(n.width, n.height, n.depth), x/65536)) |
| 1400 |
end) |
| 1401 |
end |
| 1402 |
|
| 1403 |
|
| 1404 |
--2 glyph contours |
| 1405 |
|
| 1406 |
function M.make_glyph(glyphname, fnt) |
| 1407 |
-- gather information |
| 1408 |
if not luaotfload then |
| 1409 |
alloc.err('Luaotfload required for glyph of operator') |
| 1410 |
return { }, 10 |
| 1411 |
end |
| 1412 |
local fontid = getfontid(fnt) |
| 1413 |
local thefont = font.getfont(fontid) |
| 1414 |
if not thefont then |
| 1415 |
alloc.err('Font not found: %s (id %s)', fnt, fontid) |
| 1416 |
return { }, 10 |
| 1417 |
end |
| 1418 |
local gid = luaotfload.aux.gid_of_name(fontid, glyphname) |
| 1419 |
if not gid then |
| 1420 |
alloc.err('Font %s has no glyph named %s', thefont.psname, glyphname) |
| 1421 |
return { }, 10 |
| 1422 |
end |
| 1423 |
local segments = fonts.hashes.shapes[fontid].glyphs[gid].segments |
| 1424 |
if #segments == 0 then return { }, 10 end |
| 1425 |
local q = 1000 / (thefont.units_per_em or 1000) |
| 1426 |
-- retrieve the contours |
| 1427 |
local path, paths = { '(' }, { } |
| 1428 |
for _, s in ipairs(segments) do |
| 1429 |
local op = s[#s] |
| 1430 |
if op == 'm' then |
| 1431 |
if #path > 1 then |
| 1432 |
table.insert(path, '--cycle)') |
| 1433 |
table.insert(paths, table.concat(path, '')) |
| 1434 |
path = { '(' } |
| 1435 |
end |
| 1436 |
table.insert(path, string.format('(%f, %f)', q*s[1], q*s[2])) |
| 1437 |
elseif op == 'l' then |
| 1438 |
table.insert(path, string.format('--(%f, %f)', q*s[1], q*s[2])) |
| 1439 |
elseif op == 'c' then |
| 1440 |
table.insert(path, string.format('..controls (%f, %f) and (%f, %f) .. (%f, %f)', |
| 1441 |
q*s[1], q*s[2], q*s[3], q*s[4], q*s[5], q*s[6])) |
| 1442 |
end |
| 1443 |
end |
| 1444 |
table.insert(path, '--cycle)') |
| 1445 |
table.insert(paths, table.concat(path, '')) |
| 1446 |
return paths, thefont.size |
| 1447 |
end |
| 1448 |
|
| 1449 |
local function get_glyphname(c_id) |
| 1450 |
if type(c_id) == 'string' then return c_id end |
| 1451 |
local res = luaotfload.aux.name_of_slot(c_id) |
| 1452 |
debug('├ name of glyph %d is %s', c_id, res) |
| 1453 |
return res |
| 1454 |
end |
| 1455 |
|
| 1456 |
function E.get_glyph(c_id, fnt) |
| 1457 |
debug('┌ glyph %s of %s', c_id, fnt) |
| 1458 |
local name = get_glyphname(c_id) |
| 1459 |
local contours, size = M.make_glyph(name, fnt) |
| 1460 |
local res = { } |
| 1461 |
for _, c in ipairs(contours) do |
| 1462 |
local scaled = string.format('%s scaled %f', c, size/65536/1000) |
| 1463 |
debug('│ %s', scaled) |
| 1464 |
table.insert(res, scaled) |
| 1465 |
end |
| 1466 |
debug('└ %d contours returned', #res) |
| 1467 |
return table.concat(res, ', ') |
| 1468 |
end |
| 1469 |
|
| 1470 |
function E.get_contours(text, fnt) |
| 1471 |
return process_typeset(text, fnt, ', ', function(res, n, x) |
| 1472 |
local contours, size = M.make_glyph(get_glyphname(n.char), n.font) |
| 1473 |
for _, c in ipairs(contours) do |
| 1474 |
table.insert(res, string.format( |
| 1475 |
'%s scaled %f shifted (%fpt, %fpt)', c, |
| 1476 |
size/65536/1024, (x + n.xoffset)/65536, n.yoffset/65536)) |
| 1477 |
end |
| 1478 |
end) |
| 1479 |
end |
| 1480 |
|
| 1481 |
M.get_contours = E.get_contours |
| 1482 |
|
| 1483 |
|
| 1484 |
--2 opening, running and and closing instances |
| 1485 |
|
| 1486 |
M.default_format = 'plain.mp' |
| 1487 |
M.default_mathmode = 'scaled' |
| 1488 |
|
| 1489 |
local function apply_default_instance_opts(t) |
| 1490 |
return |
| 1491 |
{ ini_version = true |
| 1492 |
, error_line = (texconfig.error_line or 79) - 5 |
| 1493 |
, extensions = 1 |
| 1494 |
, find_file = new_file_finder() |
| 1495 |
--, script_error = ... |
| 1496 |
, job_name = t.jobname |
| 1497 |
, math_mode = t.mathmode or t.math or M.default_mathmode |
| 1498 |
, random_seed = t.randomseed or t.seed or nil |
| 1499 |
-- , file_line_error_style |
| 1500 |
, make_text = maketext |
| 1501 |
, run_script = runscript |
| 1502 |
} |
| 1503 |
end |
| 1504 |
|
| 1505 |
local function save_image_list(self, res) |
| 1506 |
for _, img in ipairs(res) do |
| 1507 |
if img.discard then |
| 1508 |
node.flush_list(img.head) |
| 1509 |
else |
| 1510 |
self.results.count = self.results.count + 1 |
| 1511 |
img.prev, img.next = self.results.last, nil |
| 1512 |
self.results.by_name[img.name] = img |
| 1513 |
if nil == self.results.first then |
| 1514 |
self.results.first = img |
| 1515 |
else |
| 1516 |
self.results.last.next = img |
| 1517 |
end |
| 1518 |
self.results.last = img |
| 1519 |
end |
| 1520 |
end |
| 1521 |
end |
| 1522 |
|
| 1523 |
function M.run (nr, code) |
| 1524 |
local self = instances[nr] |
| 1525 |
if self.status == 3 then |
| 1526 |
alloc.msg('metapost instance %s (%s) is defunct and will not run', self.jobname, nr) |
| 1527 |
return |
| 1528 |
end |
| 1529 |
current_instance = self |
| 1530 |
if debugging then |
| 1531 |
alloc.log('┌ metapost chunk for {%s} (%d)', self.jobname, nr) |
| 1532 |
for _, line in ipairs(code:explode('\013')) do |
| 1533 |
alloc.log('│ %s', line) |
| 1534 |
end |
| 1535 |
alloc.log('└') |
| 1536 |
end |
| 1537 |
local cct = tex.catcodetable |
| 1538 |
tex.catcodetable = self.catcodes |
| 1539 |
local res = self.instance:execute(code) |
| 1540 |
tex.catcodetable = cct |
| 1541 |
print_log(nr, res) |
| 1542 |
local picts = process_results(nr, res) |
| 1543 |
save_image_list(self, picts) |
| 1544 |
end |
| 1545 |
|
| 1546 |
M.init_code = { 'let dump=endinput;' |
| 1547 |
, 'boolean mplib; mplib:=true;' |
| 1548 |
, 'input INIT;' |
| 1549 |
, 'input minim.mp;' |
| 1550 |
, 'input minim-mp.mp;' } |
| 1551 |
local maketext_catcodes = alloc.registernumber('minim:mp:catcodes:maketext') |
| 1552 |
|
| 1553 |
function M.open (t) |
| 1554 |
local nr = #instances + 1 |
| 1555 |
tex.count['mp:cur:inst'] = nr |
| 1556 |
-- creating instance options |
| 1557 |
t.jobname = t.jobname or ':metapost:' |
| 1558 |
local init = string.gsub(table.concat(M.init_code, ''), 'INIT', t.format or M.default_format) |
| 1559 |
local opts = apply_default_instance_opts(t) |
| 1560 |
local instance = mplib.new(opts) |
| 1561 |
tex.runtoks 'mp:init:env' |
| 1562 |
-- adding the instance |
| 1563 |
instances[nr] = |
| 1564 |
{ nr = nr |
| 1565 |
, instance = instance |
| 1566 |
, jobname = t.jobname |
| 1567 |
, results = { first = nil, last = nil, by_name = {}, count = 0 } |
| 1568 |
, status = 0 |
| 1569 |
, catcodes = t.catcodes or maketext_catcodes |
| 1570 |
, boxes = { } -- allocated by maketext |
| 1571 |
, env = prepare_env(t.env) |
| 1572 |
} |
| 1573 |
current_instance = instances[nr] |
| 1574 |
print_log(nr, instance:execute(init), 'opening ') |
| 1575 |
tex.count['mp:cur:inst'] = -1 |
| 1576 |
return nr |
| 1577 |
end |
| 1578 |
|
| 1579 |
function M.close (nr) |
| 1580 |
local i = instances[nr] |
| 1581 |
tex.count['mp:cur:inst'] = nr |
| 1582 |
if i.instance then |
| 1583 |
local res = i.instance:finish() |
| 1584 |
print_log(nr, res, 'closing ') |
| 1585 |
end |
| 1586 |
for _, b in ipairs(i.boxes) do |
| 1587 |
-- remove allocated boxes |
| 1588 |
tex.box[b] = nil |
| 1589 |
end |
| 1590 |
instances[nr] = false |
| 1591 |
tex.count['mp:cur:inst'] = -1 |
| 1592 |
end |
| 1593 |
|
| 1594 |
--2 retrieving and using results |
| 1595 |
|
| 1596 |
local function retrieve(nr, name) |
| 1597 |
local results = instances[nr].results |
| 1598 |
local image |
| 1599 |
if name then |
| 1600 |
image = results.by_name[name] |
| 1601 |
results.by_name [name] = nil |
| 1602 |
else |
| 1603 |
image = results.first |
| 1604 |
end |
| 1605 |
if not image then return end |
| 1606 |
results.count = results.count - 1 |
| 1607 |
if image.prev then |
| 1608 |
if image.next then |
| 1609 |
image.prev.next = image.next |
| 1610 |
image.next.prev = image.prev |
| 1611 |
else |
| 1612 |
image.prev.next = nil |
| 1613 |
results.last = image.prev |
| 1614 |
end |
| 1615 |
elseif image.next then |
| 1616 |
results.first = image.next |
| 1617 |
image.next.prev = nil |
| 1618 |
else |
| 1619 |
results.first = nil |
| 1620 |
results.last = nil |
| 1621 |
end |
| 1622 |
return image |
| 1623 |
end |
| 1624 |
|
| 1625 |
function M.left (nr) |
| 1626 |
return instances[nr].results.count |
| 1627 |
end |
| 1628 |
|
| 1629 |
function M.get_image(nr, name) |
| 1630 |
local image = retrieve(nr, name) |
| 1631 |
if image then |
| 1632 |
local box = image.head |
| 1633 |
box.width = image.wd |
| 1634 |
box.height = image.ht |
| 1635 |
box.depth = image.dp |
| 1636 |
return box |
| 1637 |
end |
| 1638 |
end |
| 1639 |
|
| 1640 |
function M.shipout(nr) |
| 1641 |
local ox, oy = pdf.getorigin() |
| 1642 |
local ho, vo = tex.hoffset, tex.voffset |
| 1643 |
pdf.setorigin() |
| 1644 |
tex.hoffset = 0 |
| 1645 |
while M.left(nr) > 0 do |
| 1646 |
local image = retrieve(nr) |
| 1647 |
tex.pageheight = (image.ht + image.dp) |
| 1648 |
tex.pagewidth = image.wd |
| 1649 |
tex.voffset = image.ht |
| 1650 |
tex.box[255] = image.head |
| 1651 |
tex.shipout(255) |
| 1652 |
tex.count[0] = tex.count[0] + 1 |
| 1653 |
end |
| 1654 |
pdf.setorigin(ox, oy) |
| 1655 |
tex.hoffset, tex.voffset = ho, vo |
| 1656 |
end |
| 1657 |
|
| 1658 |
--2 tex interface |
| 1659 |
|
| 1660 |
local scan_int = token.scan_int |
| 1661 |
local scan_string = token.scan_string |
| 1662 |
|
| 1663 |
alloc.luadef('closemetapostinstance', function() M.close(scan_int()) end) |
| 1664 |
|
| 1665 |
local code_catcodes = alloc.registernumber('minim:mp:catcodes:mpcode') |
| 1666 |
|
| 1667 |
alloc.luadef('runmetapost', function() |
| 1668 |
local id = scan_int() |
| 1669 |
tex.count['mp:cur:inst'] = id |
| 1670 |
-- run tex code before |
| 1671 |
tex.runtoks 'mp:inst:pre:tex' |
| 1672 |
-- scan the argument with inert catcodes |
| 1673 |
local cct = tex.catcodetable |
| 1674 |
tex.catcodetable = code_catcodes |
| 1675 |
token.scan_keyword '\013' -- ^^M has catcode 12 now |
| 1676 |
local code = token.scan_string() |
| 1677 |
tex.catcodetable = cct |
| 1678 |
-- prepare the argument further |
| 1679 |
tex.toks['mp:mpcode'] = code |
| 1680 |
tex.runtoks 'mp:makempcode' |
| 1681 |
code = tex.toks['mp:mpcode'] |
| 1682 |
-- run the code |
| 1683 |
M.run(id, code) |
| 1684 |
-- run tech code after |
| 1685 |
tex.runtoks 'mp:inst:post:tex' |
| 1686 |
tex.count['mp:cur:inst'] = -1 |
| 1687 |
end, 'protected') |
| 1688 |
|
| 1689 |
alloc.luadef('getnextmpimage', function() |
| 1690 |
node.write(M.get_image(scan_int())) |
| 1691 |
end) |
| 1692 |
alloc.luadef('getnamedmpimage', function() |
| 1693 |
node.write(M.get_image(scan_int(), scan_string())) |
| 1694 |
end) |
| 1695 |
|
| 1696 |
alloc.luadef('boxnextmpimage', function() |
| 1697 |
local i = scan_int() |
| 1698 |
local b = scan_int() |
| 1699 |
tex.box[b] = M.get_image(i) |
| 1700 |
end) |
| 1701 |
|
| 1702 |
alloc.luadef('boxnamedmpimage', function() |
| 1703 |
local i = scan_int() |
| 1704 |
local b = scan_int() |
| 1705 |
local n = scan_string() |
| 1706 |
tex.box[b] = M.get_image(i, n) |
| 1707 |
end) |
| 1708 |
|
| 1709 |
alloc.luadef('remainingmpimages', function() |
| 1710 |
tex.sprint(M.left(scan_int())) |
| 1711 |
end) |
| 1712 |
|
| 1713 |
-- |
| 1714 |
|
| 1715 |
-- |
| 1716 |
|
| 1717 |
return M |
| 1718 |
|