// fit2box.js - module for filling a tune in a box
//
// Copyright (C) 2025 Jean-François Moine
//
// This file is part of abc2svg.
//
// abc2svg is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// abc2svg is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with abc2svg. If not, see .
//
// This module is loaded when "%%fit2box" appears in a ABC source.
//
// Parameters
// %%fit2box width height
// width is the width of the box.
// The value '*' (star) is the value of %%pagewidth
// height is the height of the box.
// The value '*' (star) is the value od %%pageheight
if (typeof abc2svg == "undefined")
var abc2svg = {}
abc2svg.fit2box = {
// generation function with %%fit2box
do_fit: function(mus) {
var r, sv, v, w, h, hh, sc, marg, tit, cl,
parse = mus.get_parse(),
f = parse.file,
fn = parse.fname,
cfmt = mus.cfmt(),
wb = cfmt.fit2box[0],
hb = cfmt.fit2box[1],
user = mus.get_user(),
io = user.img_out, // save the original img_out
ob = "" // output buffer
user.img_out = function(p) { // function to get the output file
ob += p
}
// get a parameter
function getparm(parm) {
var j, v,
i = f.indexOf("%%" + parm)
if (i >= 0 && (!i || f[i - 1] == '\n')) {
j = f.indexOf('\n', i)
v = f.slice(i, j).split(/\s+/)
v = mus.get_unit(v[1])
} else {
v = cfmt[parm]
}
return v
} // getparm()
// set an old or new parameter
function setparm(parm, v) {
var i, j,
p = "%%" + parm
i = f.indexOf(p)
if (i >= 0 && (!i || f[i - 1] == '\n')) {
j = f.indexOf('\n', i)
f = f.replace(f.slice(i, j), p + ' ' + v)
} else {
f = p + ' ' + v + '\n' + f
}
} // setparm()
// get/set the box dimensions
if (wb == "*")
wb = getparm("pagewidth")
if (hb == "*")
hb = getparm("pageheight")
if (!hb)
hb = 1123 // (1123 = 29.7cm)
// set some parameters
setparm("stretchlast", "0")
setparm("stretchstaff", "0")
// get the original margins and remove them for the first generation
// (assume left margin == right margin)
marg = getparm("leftmargin")
setparm("leftmargin", "0")
setparm("rightmargin", "0")
// set the box width twice as before to avoid line breaks
setparm("pagewidth", (wb * 2).toFixed(2))
// force the scale
if (f.indexOf("\n%%pagescale ") >= 0)
f = f.replace(/(\n%%pagescale).*/, "$1 1")
else
f = f.replace(/(\nK:.*)/, "$1\n%%pagescale 1")
cfmt.trimsvg = 1
cfmt.fullsvg = "a"
// do a first generation
if (abc2svg.fit2box.otosvg)
abc2svg.fit2box.otosvg(fn, f)
else
mus.tosvg(fn, f)
// analyse the result of the generation
cfmt = mus.cfmt()
w = h = hh = 0
r = ob.match(/